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