Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { ProviderDriverKind, type ServerProviderModel } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Path from "effect/Path";
8import * as TestClock from "effect/testing/TestClock";
9import { HttpClient, HttpClientResponse } from "effect/unstable/http";
10
11import * as ServerConfig from "../config.ts";
12import * as ServerSettings from "../serverSettings.ts";
13import {
14 applyManifestDefault,
15 BUNDLED_MODEL_MANIFEST,
16 classifyModels,
17 make,
18 resolveProviderCatalog,
19 type ModelManifestData,
20 manifestUpdatedAtMs,
21 encodeManifestCache,
22} from "./ModelManifest.ts";
23
24/**
25 * Test policy: this file covers manifest machinery, not manifest contents.
26 * Do not add assertions for real model slugs, names, status, aliases, or
27 * profiles when editing model-manifest.json. Add tests only when fetch/cache
28 * behavior or the provider-neutral resolver semantics change, and use
29 * synthetic models for resolver coverage.
30 */
31
32const CODEX = ProviderDriverKind.make("codex");
33const model = (overrides: Partial<ServerProviderModel>): ServerProviderModel => ({
34 slug: "gpt-test",
35 name: "GPT Test",
36 isCustom: false,
37 capabilities: null,
38 ...overrides,
39});
40
41describe("classifyModels", () => {
42 it("flags non-current models, clears stale flags, and skips custom models", () => {
43 const manifest: ModelManifestData = {
44 version: 1,
45 currentModels: { codex: ["current-a", "current-b"] },
46 };
47 const models = [
48 model({ slug: "current-a" }),
49 // Stale flag from a previous classification pass must be cleared.
50 model({ slug: "current-b", isLegacy: true }),
51 model({ slug: "old-model" }),
52 // Custom models are user-defined and never reclassified.
53 model({ slug: "my-own-model", isCustom: true }),
54 ];
55 assert.deepStrictEqual(
56 classifyModels(models, manifest, CODEX).map((entry) => [entry.slug, entry.isLegacy ?? false]),
57 [
58 ["current-a", false],
59 ["current-b", false],
60 ["old-model", true],
61 ["my-own-model", false],
62 ],
63 );
64 });
65});
66
67describe("applyManifestDefault", () => {
68 it("moves the default flag and its aliases to the manifest's chat default", () => {
69 const driver = ProviderDriverKind.make("antigravity");
70 const manifest: ModelManifestData = {
71 version: 1,
72 currentModels: {},
73 providers: {
74 antigravity: {
75 defaults: { chat: "gemini-new" },
76 profiles: {},
77 models: [{ slug: "gemini-new", name: "New", status: "current" }],
78 },
79 },
80 };
81 const models = [
82 model({ slug: "gemini-old", isDefault: true, aliases: ["antigravity-default"] }),
83 model({ slug: "gemini-new" }),
84 ];
85 assert.deepStrictEqual(applyManifestDefault(models, manifest, driver), [
86 model({ slug: "gemini-old" }),
87 model({ slug: "gemini-new", isDefault: true, aliases: ["antigravity-default"] }),
88 ]);
89 // The account does not offer the manifest default: keep the runtime's choice.
90 assert.deepStrictEqual(
91 applyManifestDefault(models.slice(0, 1), manifest, driver),
92 models.slice(0, 1),
93 );
94 });
95});
96
97describe("resolveProviderCatalog", () => {
98 it("resolves generic model presentation through a reusable profile", () => {
99 const manifest: ModelManifestData = {
100 version: 1,
101 currentModels: {},
102 providers: {
103 synthetic: {
104 defaults: { chat: "model-next" },
105 profiles: {
106 standard: {
107 capabilities: {
108 optionDescriptors: [
109 {
110 id: "mode",
111 label: "Mode",
112 type: "select",
113 options: [{ id: "fast", label: "Fast", isDefault: true }],
114 },
115 ],
116 },
117 adapter: { opaque: true },
118 },
119 },
120 models: [
121 {
122 slug: "model-next",
123 name: "Model Next",
124 aliases: ["next"],
125 status: "current",
126 badge: "new",
127 profile: "standard",
128 },
129 ],
130 },
131 },
132 };
133
134 const catalog = resolveProviderCatalog(manifest, ProviderDriverKind.make("synthetic"));
135 assert.deepStrictEqual(catalog?.models[0], {
136 model: {
137 slug: "model-next",
138 name: "Model Next",
139 aliases: ["next"],
140 badge: "new",
141 isCustom: false,
142 isDefault: true,
143 capabilities: manifest.providers!.synthetic!.profiles.standard!.capabilities!,
144 },
145 adapter: undefined,
146 profileAdapter: { opaque: true },
147 });
148 });
149
150 it("rejects invalid catalog references", () => {
151 const invalidCatalog = (input: {
152 readonly models: NonNullable<ModelManifestData["providers"]>[string]["models"];
153 readonly defaultChat?: string;
154 }): ModelManifestData => ({
155 version: 1,
156 currentModels: {},
157 providers: {
158 synthetic: {
159 ...(input.defaultChat ? { defaults: { chat: input.defaultChat } } : {}),
160 profiles: {},
161 models: input.models,
162 },
163 },
164 });
165
166 for (const invalid of [
167 invalidCatalog({
168 models: [
169 { slug: "duplicate", name: "First", status: "current" },
170 { slug: "duplicate", name: "Second", status: "current" },
171 ],
172 }),
173 invalidCatalog({
174 models: [
175 {
176 slug: "missing-profile",
177 name: "Missing Profile",
178 status: "current",
179 profile: "missing",
180 },
181 ],
182 }),
183 invalidCatalog({
184 models: [{ slug: "present", name: "Present", status: "current" }],
185 defaultChat: "absent",
186 }),
187 ]) {
188 assert.isNull(resolveProviderCatalog(invalid, ProviderDriverKind.make("synthetic")));
189 }
190 });
191});
192
193// Remote fixtures date after the bundle so a fetch still outranks it.
194const REMOTE_UPDATED_AT = "2099-01-01T00:00:00Z";
195
196const REMOTE_MANIFEST: ModelManifestData = {
197 version: 1,
198 updatedAt: REMOTE_UPDATED_AT,
199 currentModels: {
200 codex: ["remote-model"],
201 claudeAgent: ["remote-agent-model"],
202 },
203};
204
205const REMOTE_CLAUDE_MANIFEST: ModelManifestData = {
206 version: 1,
207 updatedAt: REMOTE_UPDATED_AT,
208 currentModels: {},
209 providers: {
210 claudeAgent: {
211 profiles: {
212 synthetic: {
213 adapter: { claudeCode: { effortMap: { extreme: "high" } } },
214 },
215 },
216 models: [
217 {
218 slug: "remote-only-model",
219 name: "Remote Only Model",
220 status: "current",
221 profile: "synthetic",
222 },
223 ],
224 },
225 },
226};
227
228const remoteClaudeManifestWithCompatibility = (compatibility: unknown): ModelManifestData => ({
229 ...REMOTE_CLAUDE_MANIFEST,
230 providers: {
231 claudeAgent: {
232 profiles: REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.profiles,
233 models: REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.models.map((model) => ({
234 ...model,
235 adapter: { claudeCode: compatibility },
236 })),
237 },
238 },
239});
240
241const INVALID_REMOTE_MANIFESTS: ReadonlyArray<ModelManifestData> = [
242 {
243 ...REMOTE_CLAUDE_MANIFEST,
244 providers: {
245 claudeAgent: {
246 profiles: {
247 synthetic: {
248 adapter: { claudeCode: { effortMap: { extreme: 123 } } },
249 },
250 },
251 models: REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.models,
252 },
253 },
254 },
255 {
256 ...REMOTE_CLAUDE_MANIFEST,
257 providers: {
258 claudeAgent: {
259 profiles: {},
260 models: REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.models,
261 },
262 },
263 },
264 {
265 ...REMOTE_CLAUDE_MANIFEST,
266 providers: {
267 claudeAgent: {
268 profiles: REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.profiles,
269 models: [
270 ...REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.models,
271 {
272 slug: "remote-only-model",
273 name: "Duplicate Remote Model",
274 status: "current",
275 profile: "synthetic",
276 },
277 ],
278 },
279 },
280 },
281 {
282 ...REMOTE_CLAUDE_MANIFEST,
283 providers: {
284 claudeAgent: {
285 defaults: { chat: "absent-model" },
286 profiles: REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.profiles,
287 models: REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.models,
288 },
289 },
290 },
291 remoteClaudeManifestWithCompatibility({ minVersion: "2.x" }),
292 remoteClaudeManifestWithCompatibility({ maxVersionExclusive: "2.x" }),
293 remoteClaudeManifestWithCompatibility({
294 minVersion: "2.2",
295 maxVersionExclusive: "2.1",
296 }),
297];
298
299const httpClientLayer = (handler: () => Response) =>
300 Layer.succeed(
301 HttpClient.HttpClient,
302 HttpClient.make((request) => Effect.succeed(HttpClientResponse.fromWeb(request, handler()))),
303 );
304
305const serviceLayers = (input: {
306 readonly prefix: string;
307 readonly response: () => Response;
308 readonly settings?: Parameters<typeof ServerSettings.layerTest>[0];
309}) =>
310 ServerConfig.layerTest(process.cwd(), { prefix: input.prefix }).pipe(
311 Layer.provideMerge(NodeServices.layer),
312 Layer.provideMerge(ServerSettings.layerTest(input.settings ?? {})),
313 Layer.provideMerge(httpClientLayer(input.response)),
314 );
315
316describe("ModelManifest service", () => {
317 it.live("prefers a fetched manifest over the bundle and caches it to disk", () =>
318 Effect.gen(function* () {
319 const service = yield* make;
320 const refreshed = yield* service.refresh;
321 assert.deepStrictEqual(refreshed, REMOTE_MANIFEST);
322
323 // A fresh service instance sees the disk cache without another fetch:
324 // its HTTP layer is still stubbed, but `current` never fetches at all.
325 const rebooted = yield* make;
326 assert.deepStrictEqual(yield* rebooted.current, REMOTE_MANIFEST);
327 }).pipe(
328 Effect.scoped,
329 Effect.provide(
330 serviceLayers({
331 prefix: "model-manifest-fetch-test",
332 response: () => Response.json(REMOTE_MANIFEST),
333 }),
334 ),
335 ),
336 );
337
338 it.live("keeps the bundled manifest when the remote payload is malformed", () =>
339 Effect.gen(function* () {
340 const service = yield* make;
341 assert.deepStrictEqual(yield* service.refresh, BUNDLED_MODEL_MANIFEST);
342 }).pipe(
343 Effect.scoped,
344 Effect.provide(
345 serviceLayers({
346 prefix: "model-manifest-malformed-test",
347 response: () => Response.json({ version: 999, nonsense: true }),
348 }),
349 ),
350 ),
351 );
352
353 it.effect("preserves the last-good remote cache when later payloads are invalid", () => {
354 let responseIndex = 0;
355 const responses = [REMOTE_CLAUDE_MANIFEST, ...INVALID_REMOTE_MANIFESTS];
356
357 return Effect.gen(function* () {
358 const service = yield* make;
359 assert.deepStrictEqual(yield* service.refresh, REMOTE_CLAUDE_MANIFEST);
360
361 for (const _invalid of INVALID_REMOTE_MANIFESTS) {
362 yield* TestClock.adjust("1 hour");
363 responseIndex += 1;
364 assert.deepStrictEqual(yield* service.refresh, REMOTE_CLAUDE_MANIFEST);
365 }
366
367 const rebooted = yield* make;
368 assert.deepStrictEqual(yield* rebooted.current, REMOTE_CLAUDE_MANIFEST);
369 }).pipe(
370 Effect.scoped,
371 Effect.provide(
372 serviceLayers({
373 prefix: "model-manifest-last-good-test",
374 response: () => Response.json(responses[responseIndex]),
375 }),
376 ),
377 );
378 });
379
380 it.live("drops a disk cache of a manifest older than the bundled one", () =>
381 Effect.gen(function* () {
382 const fs = yield* FileSystem.FileSystem;
383 const path = yield* Path.Path;
384 const config = yield* ServerConfig.ServerConfig;
385 assert.isAbove(manifestUpdatedAtMs(BUNDLED_MODEL_MANIFEST), 0);
386 const cachePath = path.join(config.stateDir, "model-manifest.json");
387 // A cache of the manifest as it was before the release edited it. The
388 // fetch time is irrelevant: the remote may be unreachable now, so
389 // `current` must already prefer the bundle.
390 const { updatedAt: _undated, ...undatedManifest } = REMOTE_MANIFEST;
391 for (const stale of [
392 undatedManifest,
393 { ...REMOTE_MANIFEST, updatedAt: "2000-01-01T00:00:00Z" },
394 ]) {
395 yield* fs.writeFileString(
396 cachePath,
397 yield* encodeManifestCache({ fetchedAtMs: 0, manifest: stale }),
398 );
399 const service = yield* make;
400 assert.deepStrictEqual(yield* service.current, BUNDLED_MODEL_MANIFEST);
401 }
402
403 // A cache of a newer edit still outranks the bundle.
404 yield* fs.writeFileString(
405 cachePath,
406 yield* encodeManifestCache({ fetchedAtMs: 0, manifest: REMOTE_MANIFEST }),
407 );
408 const later = yield* make;
409 assert.deepStrictEqual(yield* later.current, REMOTE_MANIFEST);
410 }).pipe(
411 Effect.scoped,
412 Effect.provide(
413 serviceLayers({
414 prefix: "model-manifest-newer-bundle-test",
415 response: () => Response.json(REMOTE_MANIFEST),
416 }),
417 ),
418 ),
419 );
420
421 it.live("does not fetch when provider update checks are disabled", () =>
422 Effect.gen(function* () {
423 let fetchCount = 0;
424 const service = yield* make.pipe(
425 Effect.provide(
426 httpClientLayer(() => {
427 fetchCount += 1;
428 return Response.json(REMOTE_MANIFEST);
429 }),
430 ),
431 );
432 assert.deepStrictEqual(yield* service.refresh, BUNDLED_MODEL_MANIFEST);
433 assert.strictEqual(fetchCount, 0);
434 }).pipe(
435 Effect.scoped,
436 Effect.provide(
437 serviceLayers({
438 prefix: "model-manifest-optout-test",
439 response: () => Response.json(REMOTE_MANIFEST),
440 settings: { enableProviderUpdateChecks: false },
441 }),
442 ),
443 ),
444 );
445});