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

ProviderInstanceRegistryLive.test.ts

482 lines19.1 KB

1/**
2 * Multi-instance validation slices for `ProviderInstanceRegistryLive`.
3 *
4 * Two axes of the driver/registry refactor are exercised here:
5 *
6 * 1. **Same driver, many instances** — the "multi-instance codex slice"
7 * describe block below configures two independent `codex` instances and
8 * asserts each gets its own closures and identity. This is the
9 * multi-codex capability the refactor exists to unlock.
10 *
11 * 2. **Many drivers, one registry** — the "all drivers slice" describe
12 * block below configures one instance of every shipped driver
13 * (`codex`, `claudeAgent`, `cursor`, `grok`, `opencode`) in a single
14 * `ProviderInstanceConfigMap` and asserts the registry boots them all
15 * without cross-contamination. This proves the driver SPI is uniform
16 * across every provider — any driver plugs into the registry through
17 * the same `ProviderDriver` value contract.
18 *
19 * Every instance in these tests is configured with `enabled: false` so the
20 * provider-status checks short-circuit to pending/disabled snapshots
21 * without trying to spawn real `codex` / `claude` / `agent` / `grok` / `opencode`
22 * binaries. That keeps the assertions focused on registry routing
23 * behaviour rather than the runtime details of each provider.
24 */
25import { describe, expect, it } from "@effect/vitest";
26import * as NodeServices from "@effect/platform-node/NodeServices";
27import {
28 type ClaudeSettings,
29 type CodexSettings,
30 type CursorSettings,
31 type GrokSettings,
32 type OpenCodeSettings,
33 ProviderDriverKind,
34 type ProviderInstanceConfigMap,
35 ProviderInstanceId,
36} from "@t3tools/contracts";
37import * as DateTime from "effect/DateTime";
38import * as Effect from "effect/Effect";
39import * as Layer from "effect/Layer";
40import * as Stream from "effect/Stream";
41import { HttpClient, HttpClientResponse } from "effect/unstable/http";
42​
43import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
44import type { BuiltInDriversEnv } from "../builtInDrivers.ts";
45import { AntigravityInstallation } from "../AntigravityInstallation.ts";
46import { ServerConfig } from "../../config.ts";
47import { ServerSettingsService } from "../../serverSettings.ts";
48import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
49import { CodexDriver } from "../Drivers/CodexDriver.ts";
50import { CursorDriver } from "../Drivers/CursorDriver.ts";
51import { GrokDriver } from "../Drivers/GrokDriver.ts";
52import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
53import * as ModelManifest from "../ModelManifest.ts";
54import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
55import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
56import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
57​
58const TestHttpClientLive = Layer.succeed(
59 HttpClient.HttpClient,
60 HttpClient.make((request) =>
61 Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
62 ),
63);
64​
65const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
66​
67const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
68 reportClientActivity: () => Effect.void,
69 removeRpcClient: () => Effect.void,
70 reportHostPowerState: () => Effect.void,
71 snapshot: Effect.succeed({
72 hostPower: {
73 source: "unknown",
74 idle: "unknown",
75 idleSeconds: null,
76 locked: "unknown",
77 suspended: false,
78 onBattery: "unknown",
79 lowPowerMode: "unknown",
80 thermalState: "unknown",
81 stale: true,
82 updatedAt: TEST_EPOCH,
83 },
84 leases: [],
85 activeForegroundLeaseCount: 0,
86 activeScopeKeys: [],
87 shouldRunOpportunisticWork: true,
88 updatedAt: TEST_EPOCH,
89 }),
90 streamChanges: Stream.empty,
91 hasDemand: () => Effect.succeed(true),
92 shouldRunScopeWork: () => Effect.succeed(true),
93 shouldRunOpportunisticWork: Effect.succeed(true),
94});
95​
96const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
97 enabled: false,
98 binaryPath: "codex",
99 homePath: "",
100 shadowHomePath: "",
101 launchArgs: "",
102 customModels: [],
103 ...overrides,
104});
105​
106const makeClaudeConfig = (overrides: Partial<ClaudeSettings>): ClaudeSettings => ({
107 enabled: false,
108 binaryPath: "claude",
109 homePath: "",
110 customModels: [],
111 launchArgs: "",
112 autoCompactWindow: "",
113 ...overrides,
114});
115​
116const makeCursorConfig = (overrides: Partial<CursorSettings>): CursorSettings => ({
117 enabled: false,
118 binaryPath: "cursor-agent",
119 apiEndpoint: "",
120 customModels: [],
121 ...overrides,
122});
123​
124const makeGrokConfig = (overrides: Partial<GrokSettings>): GrokSettings => ({
125 enabled: false,
126 binaryPath: "grok",
127 customModels: [],
128 ...overrides,
129});
130​
131const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSettings => ({
132 enabled: false,
133 binaryPath: "opencode",
134 serverUrl: "",
135 serverPassword: "",
136 customModels: [],
137 ...overrides,
138});
139​
140describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
141 // `ServerConfig.layerTest` needs `FileSystem` to materialize its scratch
142 // directory. `Layer.merge` just unions requirements, so we have to push
143 // `NodeServices.layer` through `Layer.provideMerge` to satisfy that
144 // dependency while still surfacing NodeServices to the test body (the
145 // codex driver's `create` yields `ChildProcessSpawner` directly).
146 const testLayer = ServerConfig.layerTest(process.cwd(), {
147 prefix: "provider-instance-registry-test",
148 }).pipe(
149 Layer.provideMerge(NodeServices.layer),
150 Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
151 Layer.provideMerge(ServerSettingsService.layerTest()),
152 Layer.provideMerge(TestHttpClientLive),
153 Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
154 Layer.provideMerge(ModelManifest.layerTest),
155 );
156​
157 it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () =>
158 Effect.gen(function* () {
159 const personalId = ProviderInstanceId.make("codex_personal");
160 const workId = ProviderInstanceId.make("codex_work");
161 const codexDriverKind = ProviderDriverKind.make("codex");
162​
163 const configMap: ProviderInstanceConfigMap = {
164 [personalId]: {
165 driver: codexDriverKind,
166 displayName: "Codex (personal)",
167 enabled: false,
168 config: makeCodexConfig({
169 binaryPath: "/opt/codex-personal/bin/codex",
170 homePath: "/home/julius/.codex_personal",
171 customModels: ["personal-preview"],
172 }),
173 },
174 [workId]: {
175 driver: codexDriverKind,
176 displayName: "Codex (work)",
177 enabled: false,
178 config: makeCodexConfig({
179 binaryPath: "/opt/codex-work/bin/codex",
180 homePath: "/home/julius/.codex",
181 customModels: ["work-preview"],
182 }),
183 },
184 };
185​
186 const { registry } = yield* makeProviderInstanceRegistry({
187 drivers: [CodexDriver],
188 configMap,
189 });
190​
191 const instances = yield* registry.listInstances;
192 expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
193 [personalId, workId].toSorted(),
194 );
195 expect(instances.every((instance) => instance.driverKind === codexDriverKind)).toBe(true);
196 expect(instances.map((instance) => instance.displayName).toSorted()).toEqual(
197 ["Codex (personal)", "Codex (work)"].toSorted(),
198 );
199​
200 // Each instance must be retrievable by id and carry its *own* closures.
201 const personal = yield* registry.getInstance(personalId);
202 const work = yield* registry.getInstance(workId);
203 expect(personal).toBeDefined();
204 expect(work).toBeDefined();
205 expect(personal!.adapter).not.toBe(work!.adapter);
206 expect(personal!.textGeneration).not.toBe(work!.textGeneration);
207 expect(personal!.snapshot).not.toBe(work!.snapshot);
208​
209 // Snapshots identify themselves by instanceId + driver — this is
210 // what makes per-instance routing distinguishable downstream.
211 const personalSnapshot = yield* personal!.snapshot.getSnapshot;
212 expect(personalSnapshot.instanceId).toBe(personalId);
213 expect(personalSnapshot.driver).toBe(codexDriverKind);
214 expect(personalSnapshot.enabled).toBe(false);
215 expect(personalSnapshot.continuation?.groupKey).toBe(
216 "codex:home:/home/julius/.codex_personal",
217 );
218​
219 const workSnapshot = yield* work!.snapshot.getSnapshot;
220 expect(workSnapshot.instanceId).toBe(workId);
221 expect(workSnapshot.driver).toBe(codexDriverKind);
222 expect(workSnapshot.enabled).toBe(false);
223 expect(workSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex");
224​
225 // Nothing goes to the unavailable bucket — both drivers are registered.
226 const unavailable = yield* registry.listUnavailable;
227 expect(unavailable).toEqual([]);
228 }).pipe(Effect.provide(testLayer)),
229 );
230​
231 it.live("treats an explicit in-config enabled:false as disabling despite the envelope", () =>
232 Effect.gen(function* () {
233 // Old settings files can carry both flags with conflicting values.
234 // The explicit false must win so a user's disable is never undone.
235 const staleId = ProviderInstanceId.make("codex_stale");
236 const configMap: ProviderInstanceConfigMap = {
237 [staleId]: {
238 driver: ProviderDriverKind.make("codex"),
239 enabled: true,
240 config: makeCodexConfig({ enabled: false }),
241 },
242 };
243​
244 const { registry } = yield* makeProviderInstanceRegistry({
245 drivers: [CodexDriver],
246 configMap,
247 });
248​
249 const instance = yield* registry.getInstance(staleId);
250 expect(instance).toBeDefined();
251 expect(instance!.enabled).toBe(false);
252 const snapshot = yield* instance!.snapshot.getSnapshot;
253 expect(snapshot.enabled).toBe(false);
254 }).pipe(Effect.provide(testLayer)),
255 );
256​
257 it.live(
258 "shadows instances whose driver is not registered in this build without failing boot",
259 () =>
260 Effect.gen(function* () {
261 const codexId = ProviderInstanceId.make("codex_main");
262 const ghostId = ProviderInstanceId.make("ghost_main");
263​
264 const configMap: ProviderInstanceConfigMap = {
265 [codexId]: {
266 driver: ProviderDriverKind.make("codex"),
267 enabled: false,
268 config: makeCodexConfig({}),
269 },
270 [ghostId]: {
271 driver: ProviderDriverKind.make("ghostDriver"),
272 displayName: "A fork-only driver we don't ship",
273 enabled: false,
274 config: { arbitrary: "payload", preserved: true },
275 },
276 };
277​
278 const { registry } = yield* makeProviderInstanceRegistry({
279 drivers: [CodexDriver],
280 configMap,
281 });
282​
283 const instances = yield* registry.listInstances;
284 expect(instances).toHaveLength(1);
285 expect(instances[0]!.instanceId).toBe(codexId);
286​
287 const unavailable = yield* registry.listUnavailable;
288 expect(unavailable).toHaveLength(1);
289 const ghost = unavailable[0]!;
290 expect(ghost.instanceId).toBe(ghostId);
291 expect(ghost.driver).toBe("ghostDriver");
292 expect(ghost.availability).toBe("unavailable");
293 expect(ghost.unavailableReason).toMatch(/ghostDriver/);
294 }).pipe(Effect.provide(testLayer)),
295 );
296});
297​
298describe("ProviderInstanceRegistryLive — all drivers slice", () => {
299 // All drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
300 // Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`
301 // at construction time, so we wire `OpenCodeRuntimeLive` into the stack.
302 // `OpenCodeRuntimeLive` bundles its own `NetService.layer` via
303 // `Layer.provide`, so the only external requirement it still exposes is
304 // `ChildProcessSpawner` — resolved here by piping it through
305 // `provideMerge(NodeServices.layer)`.
306 //
307 // The nested `provideMerge`s read bottom-up: `NodeServices.layer`
308 // provides `OpenCodeRuntimeLive`'s deps while keeping its own outputs
309 // surfaced; that merged layer then provides `ServerConfig.layerTest`'s
310 // `FileSystem` dep while keeping everything else surfaced to the test.
311 const infraLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer));
312 const testLayer = AntigravityInstallation.layer.pipe(
313 Layer.provideMerge(
314 ServerConfig.layerTest(process.cwd(), {
315 prefix: "provider-instance-registry-all-drivers-test",
316 }),
317 ),
318 Layer.provideMerge(infraLayer),
319 Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
320 Layer.provideMerge(ServerSettingsService.layerTest()),
321 Layer.provideMerge(TestHttpClientLive),
322 Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
323 Layer.provideMerge(ModelManifest.layerTest),
324 );
325​
326 it.live("boots one instance of every shipped driver from a single config map", () =>
327 Effect.gen(function* () {
328 const codexId = ProviderInstanceId.make("codex_default");
329 const claudeId = ProviderInstanceId.make("claude_default");
330 const cursorId = ProviderInstanceId.make("cursor_default");
331 const grokId = ProviderInstanceId.make("grok_default");
332 const openCodeId = ProviderInstanceId.make("opencode_default");
333​
334 const codexDriverKind = ProviderDriverKind.make("codex");
335 const claudeDriverKind = ProviderDriverKind.make("claudeAgent");
336 const cursorDriverKind = ProviderDriverKind.make("cursor");
337 const grokDriverKind = ProviderDriverKind.make("grok");
338 const openCodeDriverKind = ProviderDriverKind.make("opencode");
339​
340 const configMap: ProviderInstanceConfigMap = {
341 [codexId]: {
342 driver: codexDriverKind,
343 displayName: "Codex",
344 enabled: false,
345 config: makeCodexConfig({ homePath: "/home/julius/.codex" }),
346 },
347 [claudeId]: {
348 driver: claudeDriverKind,
349 displayName: "Claude",
350 enabled: false,
351 config: makeClaudeConfig({
352 homePath: "/home/julius/.claude-work",
353 launchArgs: "--verbose",
354 }),
355 },
356 [cursorId]: {
357 driver: cursorDriverKind,
358 displayName: "Cursor",
359 enabled: false,
360 config: makeCursorConfig({}),
361 },
362 [grokId]: {
363 driver: grokDriverKind,
364 displayName: "Grok",
365 enabled: false,
366 config: makeGrokConfig({}),
367 },
368 [openCodeId]: {
369 driver: openCodeDriverKind,
370 displayName: "OpenCode",
371 enabled: false,
372 config: makeOpenCodeConfig({}),
373 },
374 };
375​
376 const { registry } = yield* makeProviderInstanceRegistry<BuiltInDriversEnv>({
377 drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
378 configMap,
379 });
380​
381 // Every configured instance must materialize — none downgraded to a
382 // shadow snapshot, because every driver in the map is registered.
383 const unavailable = yield* registry.listUnavailable;
384 expect(unavailable).toEqual([]);
385​
386 const instances = yield* registry.listInstances;
387 expect(instances).toHaveLength(5);
388 expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
389 [codexId, claudeId, cursorId, grokId, openCodeId].toSorted(),
390 );
391​
392 // Instance lookup by id resolves each instance to its own bundle —
393 // this is how rest-of-server routes turn/session calls in the new
394 // model. Each driver's bundle carries its advertised `driverKind`.
395 const codex = yield* registry.getInstance(codexId);
396 const claude = yield* registry.getInstance(claudeId);
397 const cursor = yield* registry.getInstance(cursorId);
398 const grok = yield* registry.getInstance(grokId);
399 const openCode = yield* registry.getInstance(openCodeId);
400 expect(codex?.driverKind).toBe(codexDriverKind);
401 expect(claude?.driverKind).toBe(claudeDriverKind);
402 expect(cursor?.driverKind).toBe(cursorDriverKind);
403 expect(grok?.driverKind).toBe(grokDriverKind);
404 expect(openCode?.driverKind).toBe(openCodeDriverKind);
405 expect(codex?.displayName).toBe("Codex");
406 expect(claude?.displayName).toBe("Claude");
407 expect(cursor?.displayName).toBe("Cursor");
408 expect(grok?.displayName).toBe("Grok");
409 expect(openCode?.displayName).toBe("OpenCode");
410​
411 // Every instance owns its own set of closures — no sharing across
412 // drivers. `adapter` / `textGeneration` / `snapshot` are all
413 // distinct references even when two instances happen to share a
414 // trait (e.g. Cursor + others all use a stub-or-real
415 // `textGeneration`; they must still be different object values).
416 const adapters = [
417 codex!.adapter,
418 claude!.adapter,
419 cursor!.adapter,
420 grok!.adapter,
421 openCode!.adapter,
422 ];
423 expect(new Set(adapters).size).toBe(adapters.length);
424 const textGenerations = [
425 codex!.textGeneration,
426 claude!.textGeneration,
427 cursor!.textGeneration,
428 grok!.textGeneration,
429 openCode!.textGeneration,
430 ];
431 expect(new Set(textGenerations).size).toBe(textGenerations.length);
432 const snapshots = [
433 codex!.snapshot,
434 claude!.snapshot,
435 cursor!.snapshot,
436 grok!.snapshot,
437 openCode!.snapshot,
438 ];
439 expect(new Set(snapshots).size).toBe(snapshots.length);
440​
441 // Snapshots identify themselves by `instanceId` + `driver` so
442 // downstream aggregation in `ProviderRegistry` can tell instances
443 // apart even when two share a driver. With `enabled: false`, the
444 // check short-circuits and we get a disabled/pending snapshot back
445 // — that's enough signal to validate the stamping wrapper without
446 // spawning real binaries.
447 const codexSnapshot = yield* codex!.snapshot.getSnapshot;
448 expect(codexSnapshot.instanceId).toBe(codexId);
449 expect(codexSnapshot.driver).toBe(codexDriverKind);
450 expect(codexSnapshot.enabled).toBe(false);
451 expect(codexSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex");
452​
453 const claudeSnapshot = yield* claude!.snapshot.getSnapshot;
454 expect(claudeSnapshot.instanceId).toBe(claudeId);
455 expect(claudeSnapshot.driver).toBe(claudeDriverKind);
456 expect(claudeSnapshot.enabled).toBe(false);
457 expect(claudeSnapshot.continuation?.groupKey).toBe("claude:home:/home/julius/.claude-work");
458​
459 const cursorSnapshot = yield* cursor!.snapshot.getSnapshot;
460 expect(cursorSnapshot.instanceId).toBe(cursorId);
461 expect(cursorSnapshot.driver).toBe(cursorDriverKind);
462 expect(cursorSnapshot.enabled).toBe(false);
463 expect(cursorSnapshot.continuation?.groupKey).toBe(
464 `${cursorDriverKind}:instance:${cursorId}`,
465 );
466​
467 const grokSnapshot = yield* grok!.snapshot.getSnapshot;
468 expect(grokSnapshot.instanceId).toBe(grokId);
469 expect(grokSnapshot.driver).toBe(grokDriverKind);
470 expect(grokSnapshot.enabled).toBe(false);
471 expect(grokSnapshot.continuation?.groupKey).toBe(`${grokDriverKind}:instance:${grokId}`);
472​
473 const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot;
474 expect(openCodeSnapshot.instanceId).toBe(openCodeId);
475 expect(openCodeSnapshot.driver).toBe(openCodeDriverKind);
476 expect(openCodeSnapshot.enabled).toBe(false);
477 expect(openCodeSnapshot.continuation?.groupKey).toBe(
478 `${openCodeDriverKind}:instance:${openCodeId}`,
479 );
480 }).pipe(Effect.provide(testLayer)),
481 );
482});