Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ModelManifest.test.ts

591 lines18.7 KB

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("classifies qualified Codex families without changing their wire ids", () => {
42 const manifest: ModelManifestData = { version: 1, currentModels: { codex: ["gpt-test"] } };
43 const models = [
44 model({ slug: "openai.gpt-test", isLegacy: true }),
45 model({ slug: "openai.gpt-old" }),
46 ];
47 assert.deepStrictEqual(
48 classifyModels(models, manifest, CODEX).map((entry) => [entry.slug, entry.isLegacy ?? false]),
49 [
50 ["openai.gpt-test", false],
51 ["openai.gpt-old", true],
52 ],
53 );
54 });
55 it("flags non-current models, clears stale flags, and skips custom models", () => {
56 const manifest: ModelManifestData = {
57 version: 1,
58 currentModels: { codex: ["current-a", "current-b"] },
59 };
60 const models = [
61 model({ slug: "current-a" }),
62 // Stale flag from a previous classification pass must be cleared.
63 model({ slug: "current-b", isLegacy: true }),
64 model({ slug: "old-model" }),
65 // Custom models are user-defined and never reclassified.
66 model({ slug: "my-own-model", isCustom: true }),
67 ];
68 assert.deepStrictEqual(
69 classifyModels(models, manifest, CODEX).map((entry) => [entry.slug, entry.isLegacy ?? false]),
70 [
71 ["current-a", false],
72 ["current-b", false],
73 ["old-model", true],
74 ["my-own-model", false],
75 ],
76 );
77 });
78});
79​
80describe("applyManifestDefault", () => {
81 it("resolves the manifest default to the qualified live model", () => {
82 const manifest: ModelManifestData = {
83 version: 1,
84 currentModels: {},
85 providers: { codex: { models: [], profiles: {}, defaults: { chat: "gpt-test" } } },
86 };
87 const models = [
88 model({ slug: "openai.gpt-old", isDefault: true }),
89 model({ slug: "openai.gpt-test" }),
90 ];
91 assert.strictEqual(
92 applyManifestDefault(models, manifest, CODEX).find((entry) => entry.isDefault)?.slug,
93 "openai.gpt-test",
94 );
95 });
96 it("moves the default flag and its aliases to the manifest's chat default", () => {
97 const driver = ProviderDriverKind.make("antigravity");
98 const manifest: ModelManifestData = {
99 version: 1,
100 currentModels: {},
101 providers: {
102 antigravity: {
103 defaults: { chat: "gemini-new" },
104 profiles: {},
105 models: [{ slug: "gemini-new", name: "New", status: "current" }],
106 },
107 },
108 };
109 const models = [
110 model({ slug: "gemini-old", isDefault: true, aliases: ["antigravity-default"] }),
111 model({ slug: "gemini-new" }),
112 ];
113 assert.deepStrictEqual(applyManifestDefault(models, manifest, driver), [
114 model({ slug: "gemini-old" }),
115 model({ slug: "gemini-new", isDefault: true, aliases: ["antigravity-default"] }),
116 ]);
117 // The account does not offer the manifest default: keep the runtime's choice.
118 assert.deepStrictEqual(
119 applyManifestDefault(models.slice(0, 1), manifest, driver),
120 models.slice(0, 1),
121 );
122 });
123});
124​
125describe("resolveProviderCatalog", () => {
126 it("resolves generic model presentation through a reusable profile", () => {
127 const manifest: ModelManifestData = {
128 version: 1,
129 currentModels: {},
130 providers: {
131 synthetic: {
132 defaults: { chat: "model-next" },
133 profiles: {
134 standard: {
135 capabilities: {
136 optionDescriptors: [
137 {
138 id: "mode",
139 label: "Mode",
140 type: "select",
141 options: [{ id: "fast", label: "Fast", isDefault: true }],
142 },
143 ],
144 },
145 adapter: { opaque: true },
146 },
147 },
148 models: [
149 {
150 slug: "model-next",
151 name: "Model Next",
152 aliases: ["next"],
153 status: "current",
154 badge: "new",
155 profile: "standard",
156 },
157 ],
158 },
159 },
160 };
161​
162 const catalog = resolveProviderCatalog(manifest, ProviderDriverKind.make("synthetic"));
163 assert.deepStrictEqual(catalog?.models[0], {
164 model: {
165 slug: "model-next",
166 name: "Model Next",
167 aliases: ["next"],
168 badge: "new",
169 isCustom: false,
170 isDefault: true,
171 capabilities: manifest.providers!.synthetic!.profiles.standard!.capabilities!,
172 },
173 adapter: undefined,
174 profileAdapter: { opaque: true },
175 });
176 });
177​
178 it("rejects invalid catalog references", () => {
179 const invalidCatalog = (input: {
180 readonly models: NonNullable<ModelManifestData["providers"]>[string]["models"];
181 readonly defaultChat?: string;
182 }): ModelManifestData => ({
183 version: 1,
184 currentModels: {},
185 providers: {
186 synthetic: {
187 ...(input.defaultChat ? { defaults: { chat: input.defaultChat } } : {}),
188 profiles: {},
189 models: input.models,
190 },
191 },
192 });
193​
194 for (const invalid of [
195 invalidCatalog({
196 models: [
197 { slug: "duplicate", name: "First", status: "current" },
198 { slug: "duplicate", name: "Second", status: "current" },
199 ],
200 }),
201 invalidCatalog({
202 models: [
203 {
204 slug: "missing-profile",
205 name: "Missing Profile",
206 status: "current",
207 profile: "missing",
208 },
209 ],
210 }),
211 invalidCatalog({
212 models: [{ slug: "present", name: "Present", status: "current" }],
213 defaultChat: "absent",
214 }),
215 ]) {
216 assert.isNull(resolveProviderCatalog(invalid, ProviderDriverKind.make("synthetic")));
217 }
218 });
219});
220​
221// Remote fixtures date after the bundle so a fetch still outranks it.
222const REMOTE_UPDATED_AT = "2099-01-01T00:00:00Z";
223​
224const REMOTE_MANIFEST: ModelManifestData = {
225 version: 1,
226 updatedAt: REMOTE_UPDATED_AT,
227 currentModels: {
228 codex: ["remote-model"],
229 claudeAgent: ["remote-agent-model"],
230 },
231};
232​
233const REMOTE_CLAUDE_MANIFEST: ModelManifestData = {
234 version: 1,
235 updatedAt: REMOTE_UPDATED_AT,
236 currentModels: {},
237 providers: {
238 claudeAgent: {
239 profiles: {
240 synthetic: {
241 adapter: { claudeCode: { effortMap: { extreme: "high" } } },
242 },
243 },
244 models: [
245 {
246 slug: "remote-only-model",
247 name: "Remote Only Model",
248 status: "current",
249 profile: "synthetic",
250 },
251 ],
252 },
253 },
254};
255​
256const remoteClaudeManifestWithCompatibility = (compatibility: unknown): ModelManifestData => ({
257 ...REMOTE_CLAUDE_MANIFEST,
258 providers: {
259 claudeAgent: {
260 profiles: REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.profiles,
261 models: REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.models.map((model) => ({
262 ...model,
263 adapter: { claudeCode: compatibility },
264 })),
265 },
266 },
267});
268​
269const INVALID_REMOTE_MANIFESTS: ReadonlyArray<ModelManifestData> = [
270 {
271 ...REMOTE_CLAUDE_MANIFEST,
272 providers: {
273 claudeAgent: {
274 profiles: {
275 synthetic: {
276 adapter: { claudeCode: { effortMap: { extreme: 123 } } },
277 },
278 },
279 models: REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.models,
280 },
281 },
282 },
283 {
284 ...REMOTE_CLAUDE_MANIFEST,
285 providers: {
286 claudeAgent: {
287 profiles: {},
288 models: REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.models,
289 },
290 },
291 },
292 {
293 ...REMOTE_CLAUDE_MANIFEST,
294 providers: {
295 claudeAgent: {
296 profiles: REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.profiles,
297 models: [
298 ...REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.models,
299 {
300 slug: "remote-only-model",
301 name: "Duplicate Remote Model",
302 status: "current",
303 profile: "synthetic",
304 },
305 ],
306 },
307 },
308 },
309 {
310 ...REMOTE_CLAUDE_MANIFEST,
311 providers: {
312 claudeAgent: {
313 defaults: { chat: "absent-model" },
314 profiles: REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.profiles,
315 models: REMOTE_CLAUDE_MANIFEST.providers!.claudeAgent!.models,
316 },
317 },
318 },
319 remoteClaudeManifestWithCompatibility({ minVersion: "2.x" }),
320 remoteClaudeManifestWithCompatibility({ maxVersionExclusive: "2.x" }),
321 remoteClaudeManifestWithCompatibility({
322 minVersion: "2.2",
323 maxVersionExclusive: "2.1",
324 }),
325];
326​
327const httpClientLayer = (handler: () => Response) =>
328 Layer.succeed(
329 HttpClient.HttpClient,
330 HttpClient.make((request) => Effect.succeed(HttpClientResponse.fromWeb(request, handler()))),
331 );
332​
333const serviceLayers = (input: {
334 readonly prefix: string;
335 readonly response: () => Response;
336 readonly settings?: Parameters<typeof ServerSettings.layerTest>[0];
337}) =>
338 ServerConfig.layerTest(process.cwd(), { prefix: input.prefix }).pipe(
339 Layer.provideMerge(NodeServices.layer),
340 Layer.provideMerge(ServerSettings.layerTest(input.settings ?? {})),
341 Layer.provideMerge(httpClientLayer(input.response)),
342 );
343​
344describe("ModelManifest service", () => {
345 it.live("explicit refresh bypasses fresh memory and disk caches", () => {
346 let fetchCount = 0;
347 const updated: ModelManifestData = {
348 ...REMOTE_MANIFEST,
349 currentModels: { codex: ["gpt-reloaded"] },
350 };
351 return Effect.gen(function* () {
352 const service = yield* make;
353 assert.deepStrictEqual(yield* service.refresh, REMOTE_MANIFEST);
354 assert.deepStrictEqual(yield* service.refresh, REMOTE_MANIFEST);
355 assert.strictEqual(fetchCount, 1);
356​
357 const rebooted = yield* make;
358 assert.deepStrictEqual(yield* rebooted.refresh, REMOTE_MANIFEST);
359 assert.strictEqual(fetchCount, 1);
360 assert.deepStrictEqual(yield* rebooted.forceRefresh, updated);
361 assert.strictEqual(fetchCount, 2);
362 assert.deepStrictEqual(yield* rebooted.current, updated);
363 assert.deepStrictEqual(yield* (yield* make).current, updated);
364 }).pipe(
365 Effect.scoped,
366 Effect.provide(
367 serviceLayers({
368 prefix: "model-manifest-force-refresh-test",
369 response: () => Response.json(fetchCount++ === 0 ? REMOTE_MANIFEST : updated),
370 }),
371 ),
372 );
373 });
374​
375 it.live("explicit refresh retries immediately after failure and preserves last-good data", () => {
376 let fetchCount = 0;
377 return Effect.gen(function* () {
378 const service = yield* make;
379 assert.deepStrictEqual(yield* service.refresh, REMOTE_MANIFEST);
380 assert.deepStrictEqual(yield* service.forceRefresh, REMOTE_MANIFEST);
381 assert.deepStrictEqual(yield* service.current, REMOTE_MANIFEST);
382 assert.deepStrictEqual(yield* (yield* make).current, REMOTE_MANIFEST);
383 assert.strictEqual(fetchCount, 2);
384 assert.deepStrictEqual(yield* service.forceRefresh, REMOTE_MANIFEST);
385 assert.strictEqual(fetchCount, 3);
386 }).pipe(
387 Effect.scoped,
388 Effect.provide(
389 serviceLayers({
390 prefix: "model-manifest-force-retry-test",
391 response: () =>
392 fetchCount++ === 1
393 ? new Response(null, { status: 503 })
394 : Response.json(REMOTE_MANIFEST),
395 }),
396 ),
397 );
398 });
399​
400 it.live("explicit refresh bypasses the retry delay after an initial failure", () => {
401 let fetchCount = 0;
402 return Effect.gen(function* () {
403 const service = yield* make;
404 assert.deepStrictEqual(yield* service.refresh, BUNDLED_MODEL_MANIFEST);
405 assert.deepStrictEqual(yield* service.refresh, BUNDLED_MODEL_MANIFEST);
406 assert.strictEqual(fetchCount, 1);
407 assert.deepStrictEqual(yield* service.forceRefresh, REMOTE_MANIFEST);
408 assert.strictEqual(fetchCount, 2);
409 }).pipe(
410 Effect.scoped,
411 Effect.provide(
412 serviceLayers({
413 prefix: "model-manifest-force-initial-retry-test",
414 response: () =>
415 fetchCount++ === 0
416 ? new Response(null, { status: 503 })
417 : Response.json(REMOTE_MANIFEST),
418 }),
419 ),
420 );
421 });
422​
423 it.live("prefers a fetched manifest over the bundle and caches it to disk", () =>
424 Effect.gen(function* () {
425 const service = yield* make;
426 const refreshed = yield* service.refresh;
427 assert.deepStrictEqual(refreshed, REMOTE_MANIFEST);
428​
429 // A fresh service instance sees the disk cache without another fetch:
430 // its HTTP layer is still stubbed, but `current` never fetches at all.
431 const rebooted = yield* make;
432 assert.deepStrictEqual(yield* rebooted.current, REMOTE_MANIFEST);
433 }).pipe(
434 Effect.scoped,
435 Effect.provide(
436 serviceLayers({
437 prefix: "model-manifest-fetch-test",
438 response: () => Response.json(REMOTE_MANIFEST),
439 }),
440 ),
441 ),
442 );
443​
444 it.live("keeps the bundled manifest when the remote payload is malformed", () =>
445 Effect.gen(function* () {
446 const service = yield* make;
447 assert.deepStrictEqual(yield* service.refresh, BUNDLED_MODEL_MANIFEST);
448 }).pipe(
449 Effect.scoped,
450 Effect.provide(
451 serviceLayers({
452 prefix: "model-manifest-malformed-test",
453 response: () => Response.json({ version: 999, nonsense: true }),
454 }),
455 ),
456 ),
457 );
458​
459 it.effect("preserves the last-good remote cache when later payloads are invalid", () => {
460 let responseIndex = 0;
461 const responses = [REMOTE_CLAUDE_MANIFEST, ...INVALID_REMOTE_MANIFESTS];
462​
463 return Effect.gen(function* () {
464 const service = yield* make;
465 assert.deepStrictEqual(yield* service.refresh, REMOTE_CLAUDE_MANIFEST);
466​
467 for (const _invalid of INVALID_REMOTE_MANIFESTS) {
468 yield* TestClock.adjust("1 hour");
469 responseIndex += 1;
470 assert.deepStrictEqual(yield* service.refresh, REMOTE_CLAUDE_MANIFEST);
471 }
472​
473 const rebooted = yield* make;
474 assert.deepStrictEqual(yield* rebooted.current, REMOTE_CLAUDE_MANIFEST);
475 }).pipe(
476 Effect.scoped,
477 Effect.provide(
478 serviceLayers({
479 prefix: "model-manifest-last-good-test",
480 response: () => Response.json(responses[responseIndex]),
481 }),
482 ),
483 );
484 });
485​
486 it.live("drops a disk cache of a manifest older than the bundled one", () =>
487 Effect.gen(function* () {
488 const fs = yield* FileSystem.FileSystem;
489 const path = yield* Path.Path;
490 const config = yield* ServerConfig.ServerConfig;
491 const cachePath = path.join(config.stateDir, "model-manifest.json");
492 // A cache of the manifest as it was before the release edited it. The
493 // fetch time is irrelevant: the remote may be unreachable now, so
494 // `current` must already prefer the bundle.
495 const { updatedAt: _undated, ...undatedManifest } = REMOTE_MANIFEST;
496 for (const stale of [
497 undatedManifest,
498 { ...REMOTE_MANIFEST, updatedAt: "2000-01-01T00:00:00Z" },
499 ]) {
500 yield* fs.writeFileString(
501 cachePath,
502 yield* encodeManifestCache({ fetchedAtMs: 0, manifest: stale }),
503 );
504 const service = yield* make;
505 assert.deepStrictEqual(yield* service.current, BUNDLED_MODEL_MANIFEST);
506 }
507​
508 // A cache of a newer edit still outranks the bundle.
509 yield* fs.writeFileString(
510 cachePath,
511 yield* encodeManifestCache({ fetchedAtMs: 0, manifest: REMOTE_MANIFEST }),
512 );
513 const later = yield* make;
514 assert.deepStrictEqual(yield* later.current, REMOTE_MANIFEST);
515 }).pipe(
516 Effect.scoped,
517 Effect.provide(
518 serviceLayers({
519 prefix: "model-manifest-newer-bundle-test",
520 response: () => Response.json(REMOTE_MANIFEST),
521 }),
522 ),
523 ),
524 );
525​
526 it.live("does not fetch when provider update checks are disabled", () =>
527 Effect.gen(function* () {
528 let fetchCount = 0;
529 const service = yield* make.pipe(
530 Effect.provide(
531 httpClientLayer(() => {
532 fetchCount += 1;
533 return Response.json(REMOTE_MANIFEST);
534 }),
535 ),
536 );
537 assert.deepStrictEqual(yield* service.refresh, BUNDLED_MODEL_MANIFEST);
538 assert.deepStrictEqual(yield* service.forceRefresh, BUNDLED_MODEL_MANIFEST);
539 assert.strictEqual(fetchCount, 0);
540 }).pipe(
541 Effect.scoped,
542 Effect.provide(
543 serviceLayers({
544 prefix: "model-manifest-optout-test",
545 response: () => Response.json(REMOTE_MANIFEST),
546 settings: { enableProviderUpdateChecks: false },
547 }),
548 ),
549 ),
550 );
551});
552​
553it.effect("caches valid compatibility policies and keeps them after a malformed refresh", () => {
554 const remote: ModelManifestData = {
555 ...REMOTE_MANIFEST,
556 compatibility: [
557 {
558 driver: "codex",
559 t3CodeRange: ">=0.0.42",
560 recommendedVersion: "2.0.0",
561 ranges: [{ range: "=2.0.0", status: "supported" }],
562 },
563 ],
564 };
565 let invalid = false;
566 return Effect.gen(function* () {
567 const service = yield* make;
568 assert.deepStrictEqual((yield* service.refresh).compatibility, remote.compatibility);
569 invalid = true;
570 yield* TestClock.adjust("1 hour");
571 assert.deepStrictEqual((yield* service.refresh).compatibility, remote.compatibility);
572 const rebooted = yield* make;
573 assert.deepStrictEqual((yield* rebooted.current).compatibility, remote.compatibility);
574 }).pipe(
575 Effect.scoped,
576 Effect.provide(
577 serviceLayers({
578 prefix: "model-manifest-compatibility-test",
579 response: () =>
580 Response.json(
581 invalid
582 ? {
583 ...remote,
584 compatibility: [{ ...remote.compatibility![0], recommendedVersion: "3.0.0" }],
585 }
586 : remote,
587 ),
588 }),
589 ),
590 );
591});