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

ProviderInstanceRegistryLive.test.ts

783 lines31.5 KB

1import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
2/**
3 * Multi-instance validation slices for `ProviderInstanceRegistryLive`.
4 *
5 * Two axes of the driver/registry refactor are exercised here:
6 *
7 * 1. **Same driver, many instances** — the "multi-instance codex slice"
8 * describe block below configures two independent `codex` instances and
9 * asserts each gets its own closures and identity. This is the
10 * multi-codex capability the refactor exists to unlock.
11 *
12 * 2. **Many drivers, one registry** — the "all drivers slice" describe
13 * block below configures one instance of every shipped driver
14 * (`codex`, `claudeAgent`, `cursor`, `grok`, `opencode`) in a single
15 * `ProviderInstanceConfigMap` and asserts the registry boots them all
16 * without cross-contamination. This proves the driver SPI is uniform
17 * across every provider — any driver plugs into the registry through
18 * the same `ProviderDriver` value contract.
19 *
20 * Every instance in these tests is configured with `enabled: false` so the
21 * provider-status checks short-circuit to pending/disabled snapshots
22 * without trying to spawn real `codex` / `claude` / `agent` / `grok` / `opencode`
23 * binaries. That keeps the assertions focused on registry routing
24 * behaviour rather than the runtime details of each provider.
25 */
26import { describe, expect, it } from "@effect/vitest";
27import * as NodeServices from "@effect/platform-node/NodeServices";
28import {
29 type ClaudeSettings,
30 type CodexSettings,
31 type CursorSettings,
32 type GrokSettings,
33 type OpenCodeSettings,
34 ProviderDriverKind,
35 type ProviderInstanceConfigMap,
36 ProviderInstanceId,
37} from "@t3tools/contracts";
38import { HostProcessPlatform, isHostWindows } from "@t3tools/shared/hostProcess";
39import * as DateTime from "effect/DateTime";
40import * as Effect from "effect/Effect";
41import * as FileSystem from "effect/FileSystem";
42import * as Layer from "effect/Layer";
43import * as Path from "effect/Path";
44import * as Stream from "effect/Stream";
45import { HttpClient, HttpClientResponse } from "effect/unstable/http";
46​
47import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
48import { AntigravityInstallation } from "../AntigravityInstallation.ts";
49import { ServerConfig } from "../../config.ts";
50import { expandHomePath } from "../../pathExpansion.ts";
51import { ServerSettingsService } from "../../serverSettings.ts";
52import { ClaudeDriver, type ClaudeDriverEnv } from "../Drivers/ClaudeDriver.ts";
53import { CodexDriver, type CodexDriverEnv } from "../Drivers/CodexDriver.ts";
54import { CursorDriver, type CursorDriverEnv } from "../Drivers/CursorDriver.ts";
55import { GrokDriver, type GrokDriverEnv } from "../Drivers/GrokDriver.ts";
56import { OpenCodeDriver, type OpenCodeDriverEnv } from "../Drivers/OpenCodeDriver.ts";
57import * as ModelManifest from "../ModelManifest.ts";
58import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
59import * as ResetCreditCoordinator from "./resetCreditCoordinator.ts";
60import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
61import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
62import { ProviderOrchestrationAdapterInfrastructureLive } from "./ProviderOrchestrationAdapterInfrastructure.ts";
63​
64const TestHttpClientLive = Layer.succeed(
65 HttpClient.HttpClient,
66 HttpClient.make((request) =>
67 Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
68 ),
69);
70​
71const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
72​
73const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
74 reportClientActivity: () => Effect.void,
75 removeRpcClient: () => Effect.void,
76 reportHostPowerState: () => Effect.void,
77 snapshot: Effect.succeed({
78 hostPower: {
79 source: "unknown",
80 idle: "unknown",
81 idleSeconds: null,
82 locked: "unknown",
83 suspended: false,
84 onBattery: "unknown",
85 lowPowerMode: "unknown",
86 thermalState: "unknown",
87 stale: true,
88 updatedAt: TEST_EPOCH,
89 },
90 leases: [],
91 activeForegroundLeaseCount: 0,
92 activeScopeKeys: [],
93 shouldRunOpportunisticWork: true,
94 updatedAt: TEST_EPOCH,
95 }),
96 streamChanges: Stream.empty,
97 hasDemand: () => Effect.succeed(true),
98 shouldRunScopeWork: () => Effect.succeed(true),
99 shouldRunOpportunisticWork: Effect.succeed(true),
100});
101​
102const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
103 enabled: false,
104 binaryPath: "codex",
105 homePath: "",
106 shadowHomePath: "",
107 launchArgs: "",
108 customModels: [],
109 ...overrides,
110});
111​
112const makeClaudeConfig = (overrides: Partial<ClaudeSettings>): ClaudeSettings => ({
113 enabled: false,
114 binaryPath: "claude",
115 homePath: "",
116 customModels: [],
117 launchArgs: "",
118 autoCompactWindow: "",
119 ...overrides,
120});
121​
122const makeCursorConfig = (overrides: Partial<CursorSettings>): CursorSettings => ({
123 enabled: false,
124 customModels: [],
125 ...overrides,
126});
127​
128const makeGrokConfig = (overrides: Partial<GrokSettings>): GrokSettings => ({
129 enabled: false,
130 binaryPath: "grok",
131 customModels: [],
132 ...overrides,
133});
134​
135const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSettings => ({
136 enabled: false,
137 binaryPath: "opencode",
138 serverUrl: "",
139 serverPassword: "",
140 customModels: [],
141 ...overrides,
142});
143​
144const makeTildeProviderFixtures = Effect.fn(
145 "ProviderInstanceRegistryLive.test.makeTildeProviderFixtures",
146)(function* () {
147 const fileSystem = yield* FileSystem.FileSystem;
148 const path = yield* Path.Path;
149 const homePath = expandHomePath("~");
150 const fixtureDir = yield* fileSystem.makeTempDirectoryScoped({
151 directory: homePath,
152 prefix: ".t3-provider-path-test-",
153 });
154 const codexPath = path.join(fixtureDir, "codex");
155 const claudePath = path.join(fixtureDir, "claude");
156 const claudeHomePath = path.join(fixtureDir, "claude-home");
157 const codexScriptPath = path.join(fixtureDir, "codex-script.json");
158 const codexFixtureDir = path.join(import.meta.dirname, "../testFixtures");
159​
160 yield* fileSystem.copyFile(path.join(codexFixtureDir, "codexCollabMockPeer.sh"), codexPath);
161 yield* fileSystem.copyFile(
162 path.join(codexFixtureDir, "codexCollabMockPeer.mjs"),
163 path.join(fixtureDir, "codexCollabMockPeer.mjs"),
164 );
165 yield* fileSystem.copyFile(
166 path.join(codexFixtureDir, "codexMultiAgentWire.json"),
167 path.join(fixtureDir, "codexMultiAgentWire.json"),
168 );
169 yield* fileSystem.writeFileString(
170 codexScriptPath,
171 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed script document read by the external Codex mock peer.
172 JSON.stringify({ rootThreadId: "probe-thread", notifications: [] }),
173 );
174 yield* fileSystem.chmod(codexPath, 0o755);
175​
176 yield* fileSystem.writeFileString(
177 claudePath,
178 [
179 "#!/usr/bin/env node",
180 'import { existsSync } from "node:fs";',
181 'import * as NodeReadline from "node:readline";',
182 'if (process.argv.includes("--version")) {',
183 ' process.stdout.write("claude 2.1.219\\n");',
184 " process.exit(0);",
185 "}",
186 "const lines = NodeReadline.createInterface({ input: process.stdin });",
187 'lines.on("line", (line) => {',
188 " const message = JSON.parse(line);",
189 ' if (message.type !== "control_request") return;',
190 ' if (message.request?.subtype === "get_usage") {',
191 " const marker = process.env.T3_CLAUDE_RESET_MARKER;",
192 " if (process.env.T3_CLAUDE_USAGE_FAILS_AFTER_CLAIM && marker && existsSync(marker)) {",
193 " process.stdout.write(JSON.stringify({",
194 ' type: "control_response",',
195 ' response: { subtype: "error", request_id: message.request_id, error: "usage failed" },',
196 ' }) + "\\n");',
197 " return;",
198 " }",
199 " process.stdout.write(JSON.stringify({",
200 ' type: "control_response",',
201 ' response: { subtype: "success", request_id: message.request_id, response: {',
202 ' session: {}, subscription_type: "pro", rate_limits_available: true,',
203 " rate_limits: { five_hour: { utilization: marker && existsSync(marker) ? 0 : 100, resets_at: null } },",
204 " } },",
205 ' }) + "\\n");',
206 " return;",
207 " }",
208 ' if (message.request?.subtype !== "initialize") return;',
209 " process.stdout.write(JSON.stringify({",
210 ' type: "control_response",',
211 " response: {",
212 ' subtype: "success",',
213 " request_id: message.request_id,",
214 " response: {",
215 " commands: [], agents: [], models: [],",
216 ' output_style: "default", available_output_styles: ["default"],',
217 ' account: { email: "test@example.com", subscriptionType: "pro", tokenSource: "oauth" },',
218 " },",
219 " },",
220 ' }) + "\\n");',
221 "});",
222 "setInterval(() => {}, 1_000);",
223 "",
224 ].join("\n"),
225 );
226 yield* fileSystem.chmod(claudePath, 0o755);
227 yield* fileSystem.makeDirectory(claudeHomePath);
228​
229 const asTildePath = (filePath: string) => `~/${path.relative(homePath, filePath)}`;
230 return {
231 codexBinaryPath: asTildePath(codexPath),
232 claudeBinaryPath: asTildePath(claudePath),
233 claudeHomePath,
234 codexScriptPath,
235 };
236});
237​
238describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
239 // `ServerConfig.layerTest` needs `FileSystem` to materialize its scratch
240 // directory. `Layer.merge` just unions requirements, so we have to push
241 // `NodeServices.layer` through `Layer.provideMerge` to satisfy that
242 // dependency while still surfacing NodeServices to the test body (the
243 // codex driver's `create` yields `ChildProcessSpawner` directly).
244 const baseLayer = ServerConfig.layerTest(process.cwd(), {
245 prefix: "provider-instance-registry-test",
246 }).pipe(
247 Layer.provideMerge(NodeServices.layer),
248 Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
249 Layer.provideMerge(ServerSettingsService.layerTest()),
250 Layer.provideMerge(TestHttpClientLive),
251 Layer.provideMerge(ServerSettingsService.layerTest()),
252 Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
253 Layer.provideMerge(ModelManifest.layerTest),
254 Layer.provideMerge(ResetCreditCoordinator.layerTest),
255 );
256 const testLayer = ProviderOrchestrationAdapterInfrastructureLive.pipe(
257 Layer.provideMerge(baseLayer),
258 );
259​
260 it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () =>
261 Effect.gen(function* () {
262 const personalId = ProviderInstanceId.make("codex_personal");
263 const workId = ProviderInstanceId.make("codex_work");
264 const codexDriverKind = ProviderDriverKind.make("codex");
265​
266 const configMap: ProviderInstanceConfigMap = {
267 [personalId]: {
268 driver: codexDriverKind,
269 displayName: "Codex (personal)",
270 enabled: false,
271 config: makeCodexConfig({
272 binaryPath: "/opt/codex-personal/bin/codex",
273 homePath: "/home/julius/.codex_personal",
274 customModels: ["personal-preview"],
275 }),
276 },
277 [workId]: {
278 driver: codexDriverKind,
279 displayName: "Codex (work)",
280 enabled: false,
281 config: makeCodexConfig({
282 binaryPath: "/opt/codex-work/bin/codex",
283 homePath: "/home/julius/.codex",
284 customModels: ["work-preview"],
285 }),
286 },
287 };
288​
289 const { registry } = yield* makeProviderInstanceRegistry<CodexDriverEnv>({
290 drivers: [CodexDriver],
291 configMap,
292 });
293​
294 const instances = yield* registry.listInstances;
295 expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
296 [personalId, workId].toSorted(),
297 );
298 expect(instances.every((instance) => instance.driverKind === codexDriverKind)).toBe(true);
299 expect(instances.map((instance) => instance.displayName).toSorted()).toEqual(
300 ["Codex (personal)", "Codex (work)"].toSorted(),
301 );
302​
303 // Each instance must be retrievable by id and carry its *own* closures.
304 const personal = yield* registry.getInstance(personalId);
305 const work = yield* registry.getInstance(workId);
306 expect(personal).toBeDefined();
307 expect(work).toBeDefined();
308 expect(personal!.orchestrationAdapter).not.toBe(work!.orchestrationAdapter);
309 expect(personal!.textGeneration).not.toBe(work!.textGeneration);
310 expect(personal!.snapshot).not.toBe(work!.snapshot);
311​
312 // Snapshots identify themselves by instanceId + driver — this is
313 // what makes per-instance routing distinguishable downstream.
314 const personalSnapshot = yield* personal!.snapshot.getSnapshot;
315 expect(personalSnapshot.instanceId).toBe(personalId);
316 expect(personalSnapshot.driver).toBe(codexDriverKind);
317 expect(personalSnapshot.enabled).toBe(false);
318 // The layout resolves the configured home through the host Path.
319 const path = yield* Path.Path;
320 expect(personalSnapshot.continuation?.groupKey).toBe(
321 `codex:home:${path.resolve("/home/julius/.codex_personal")}`,
322 );
323​
324 const workSnapshot = yield* work!.snapshot.getSnapshot;
325 expect(workSnapshot.instanceId).toBe(workId);
326 expect(workSnapshot.driver).toBe(codexDriverKind);
327 expect(workSnapshot.enabled).toBe(false);
328 expect(workSnapshot.continuation?.groupKey).toBe(
329 `codex:home:${path.resolve("/home/julius/.codex")}`,
330 );
331​
332 // Nothing goes to the unavailable bucket — both drivers are registered.
333 const unavailable = yield* registry.listUnavailable;
334 expect(unavailable).toEqual([]);
335 }).pipe(Effect.provide(testLayer)),
336 );
337​
338 it.live("treats an explicit in-config enabled:false as disabling despite the envelope", () =>
339 Effect.gen(function* () {
340 // Old settings files can carry both flags with conflicting values.
341 // The explicit false must win so a user's disable is never undone.
342 const staleId = ProviderInstanceId.make("codex_stale");
343 const configMap: ProviderInstanceConfigMap = {
344 [staleId]: {
345 driver: ProviderDriverKind.make("codex"),
346 enabled: true,
347 config: makeCodexConfig({ enabled: false }),
348 },
349 };
350​
351 const { registry } = yield* makeProviderInstanceRegistry({
352 drivers: [CodexDriver],
353 configMap,
354 });
355​
356 const instance = yield* registry.getInstance(staleId);
357 expect(instance).toBeDefined();
358 expect(instance!.enabled).toBe(false);
359 const snapshot = yield* instance!.snapshot.getSnapshot;
360 expect(snapshot.enabled).toBe(false);
361 }).pipe(Effect.provide(testLayer)),
362 );
363​
364 it.live("reports Codex's answer when a redemption changed nothing", () =>
365 Effect.gen(function* () {
366 if (yield* isHostWindows) return;
367 const fileSystem = yield* FileSystem.FileSystem;
368 const fixtures = yield* makeTildeProviderFixtures();
369 yield* fileSystem.writeFileString(
370 fixtures.codexScriptPath,
371 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed script document read by the external Codex mock peer.
372 JSON.stringify({
373 rootThreadId: "probe-thread",
374 notifications: [],
375 account: { type: "chatgpt", email: "test@example.com", planType: "plus" },
376 failRateLimitsRead: true,
377 resetCreditOutcome: "alreadyRedeemed",
378 }),
379 );
380 const codexId = ProviderInstanceId.make("codex_reset");
381 const { registry } = yield* makeProviderInstanceRegistry({
382 drivers: [CodexDriver],
383 configMap: {
384 [codexId]: {
385 driver: ProviderDriverKind.make("codex"),
386 enabled: true,
387 environment: [
388 { name: "T3_CODEX_COLLAB_SCRIPT", value: fixtures.codexScriptPath, sensitive: false },
389 ],
390 config: makeCodexConfig({ enabled: true, binaryPath: fixtures.codexBinaryPath }),
391 },
392 },
393 });
394 const codex = yield* registry.getInstance(codexId);
395 expect(codex).toBeDefined();
396 // The usage read fails, so the re-probe cannot confirm new limits.
397 yield* codex!.snapshot.refresh;
398 expect(yield* codex!.consumeResetCredit!()).toBe("alreadyRedeemed");
399 }).pipe(Effect.provide(testLayer)),
400 );
401​
402 it.live("runs Codex and Claude readiness probes from configured tilde paths", () =>
403 Effect.gen(function* () {
404 if (yield* isHostWindows) return;
405​
406 const fixtures = yield* makeTildeProviderFixtures();
407​
408 const codexId = ProviderInstanceId.make("codex_tilde");
409 const claudeId = ProviderInstanceId.make("claude_tilde");
410 const configMap: ProviderInstanceConfigMap = {
411 [codexId]: {
412 driver: ProviderDriverKind.make("codex"),
413 enabled: true,
414 environment: [
415 {
416 name: "T3_CODEX_COLLAB_SCRIPT",
417 value: fixtures.codexScriptPath,
418 sensitive: false,
419 },
420 ],
421 config: makeCodexConfig({ enabled: true, binaryPath: fixtures.codexBinaryPath }),
422 },
423 [claudeId]: {
424 driver: ProviderDriverKind.make("claudeAgent"),
425 enabled: true,
426 config: makeClaudeConfig({
427 enabled: true,
428 binaryPath: fixtures.claudeBinaryPath,
429 homePath: fixtures.claudeHomePath,
430 }),
431 },
432 };
433​
434 const { registry } = yield* makeProviderInstanceRegistry<CodexDriverEnv | ClaudeDriverEnv>({
435 drivers: [CodexDriver, ClaudeDriver],
436 configMap,
437 });
438 const codex = yield* registry.getInstance(codexId);
439 const claude = yield* registry.getInstance(claudeId);
440 expect(codex).toBeDefined();
441 expect(claude).toBeDefined();
442​
443 const [codexSnapshot, claudeSnapshot] = yield* Effect.all(
444 [codex!.snapshot.refresh, claude!.snapshot.refresh],
445 { concurrency: "unbounded" },
446 );
447 expect(codexSnapshot).toMatchObject({ status: "ready", installed: true, version: "0.0.0" });
448 expect(claudeSnapshot).toMatchObject({
449 status: "ready",
450 installed: true,
451 version: "2.1.219",
452 });
453 }).pipe(Effect.provide(testLayer)),
454 );
455​
456 const redeemClaudeReset = (claim: { result: string; usageFailsAfterClaim: boolean }) =>
457 Effect.gen(function* () {
458 const fs = yield* FileSystem.FileSystem;
459 const path = yield* Path.Path;
460 const fixtures = yield* makeTildeProviderFixtures();
461 const marker = path.join(fixtures.claudeHomePath, "redeemed");
462 yield* fs.writeFileString(
463 path.join(fixtures.claudeHomePath, ".credentials.json"),
464 '{"claudeAiOauth":{"accessToken":"fake-token"}}',
465 );
466 yield* fs.writeFileString(
467 path.join(fixtures.claudeHomePath, ".claude.json"),
468 '{"oauthAccount":{"organizationUuid":"fake-org"}}',
469 );
470 const client = HttpClient.make((request) =>
471 Effect.gen(function* () {
472 if (request.url.endsWith("/api/oauth/usage")) {
473 return HttpClientResponse.fromWeb(
474 request,
475 Response.json({
476 cedar_ember: {
477 eligible: true,
478 next_grant_id: "grant_a",
479 grants: [{ id: "grant_a", resets_left: 1, usable_now: true }],
480 },
481 }),
482 );
483 }
484 if (request.url.endsWith("/reset_rate_limits")) {
485 yield* fs.writeFileString(marker, "redeemed").pipe(Effect.orDie);
486 return HttpClientResponse.fromWeb(request, Response.json({ result: claim.result }));
487 }
488 return HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }));
489 }),
490 );
491 const instanceId = ProviderInstanceId.make("claude_reset");
492 const { registry } = yield* makeProviderInstanceRegistry({
493 drivers: [ClaudeDriver],
494 configMap: {
495 [instanceId]: {
496 driver: ProviderDriverKind.make("claudeAgent"),
497 enabled: true,
498 environment: [
499 { name: "T3_CLAUDE_RESET_MARKER", value: marker, sensitive: false },
500 ...(claim.usageFailsAfterClaim
501 ? [{ name: "T3_CLAUDE_USAGE_FAILS_AFTER_CLAIM", value: "1", sensitive: false }]
502 : []),
503 ],
504 config: makeClaudeConfig({
505 enabled: true,
506 binaryPath: fixtures.claudeBinaryPath,
507 homePath: fixtures.claudeHomePath,
508 }),
509 },
510 },
511 }).pipe(Effect.provideService(HttpClient.HttpClient, client));
512 const instance = yield* registry.getInstance(instanceId);
513 expect(instance).toBeDefined();
514 const before = yield* instance!.snapshot.refresh;
515 expect(before.usageLimits?.windows[0]?.usedPercent).toBe(100);
516 expect(before.usageLimits?.resetCredits?.nextCreditId).toBe("grant_a");
517 const outcome = yield* instance!.consumeResetCredit!().pipe(Effect.result);
518 return { outcome, after: yield* instance!.snapshot.getSnapshot };
519 }).pipe(
520 // macOS logins live in the Keychain, where resets are never read.
521 Effect.provideService(HostProcessPlatform, "linux"),
522 Effect.provide(testLayer),
523 );
524​
525 it.live("refreshes Claude usage after redeeming a reset", () =>
526 Effect.gen(function* () {
527 const { outcome, after } = yield* redeemClaudeReset({
528 result: "reset",
529 usageFailsAfterClaim: false,
530 });
531 expect(outcome).toMatchObject({ _tag: "Success", success: "reset" });
532 expect(after.usageLimits?.windows[0]?.usedPercent).toBe(0);
533 }),
534 );
535​
536 it.live("reports Claude's answer when a claim changed nothing and the re-probe fails", () =>
537 Effect.gen(function* () {
538 const { outcome } = yield* redeemClaudeReset({
539 result: "already_used",
540 usageFailsAfterClaim: true,
541 });
542 expect(outcome).toMatchObject({ _tag: "Success", success: "alreadyRedeemed" });
543 }),
544 );
545​
546 it.live(
547 "shadows instances whose driver is not registered in this build without failing boot",
548 () =>
549 Effect.gen(function* () {
550 const codexId = ProviderInstanceId.make("codex_main");
551 const ghostId = ProviderInstanceId.make("ghost_main");
552​
553 const configMap: ProviderInstanceConfigMap = {
554 [codexId]: {
555 driver: ProviderDriverKind.make("codex"),
556 enabled: false,
557 config: makeCodexConfig({}),
558 },
559 [ghostId]: {
560 driver: ProviderDriverKind.make("ghostDriver"),
561 displayName: "A fork-only driver we don't ship",
562 enabled: false,
563 config: { arbitrary: "payload", preserved: true },
564 },
565 };
566​
567 const { registry } = yield* makeProviderInstanceRegistry<CodexDriverEnv>({
568 drivers: [CodexDriver],
569 configMap,
570 });
571​
572 const instances = yield* registry.listInstances;
573 expect(instances).toHaveLength(1);
574 expect(instances[0]!.instanceId).toBe(codexId);
575​
576 const unavailable = yield* registry.listUnavailable;
577 expect(unavailable).toHaveLength(1);
578 const ghost = unavailable[0]!;
579 expect(ghost.instanceId).toBe(ghostId);
580 expect(ghost.driver).toBe("ghostDriver");
581 expect(ghost.availability).toBe("unavailable");
582 expect(ghost.unavailableReason).toMatch(/ghostDriver/);
583 }).pipe(Effect.provide(testLayer)),
584 );
585});
586​
587describe("ProviderInstanceRegistryLive — all drivers slice", () => {
588 // All drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
589 // Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`
590 // at construction time, so we wire `OpenCodeRuntimeLive` into the stack.
591 // `OpenCodeRuntimeLive` bundles its own `NetService.layer` via
592 // `Layer.provide`, so the only external requirement it still exposes is
593 // `ChildProcessSpawner` — resolved here by piping it through
594 // `provideMerge(NodeServices.layer)`.
595 //
596 // The nested `provideMerge`s read bottom-up: `NodeServices.layer`
597 // provides `OpenCodeRuntimeLive`'s deps while keeping its own outputs
598 // surfaced; that merged layer then provides `ServerConfig.layerTest`'s
599 // `FileSystem` dep while keeping everything else surfaced to the test.
600 const infraLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer));
601 const baseLayer = AntigravityInstallation.layer.pipe(
602 Layer.provideMerge(ServerSecretStore.layer),
603 Layer.provideMerge(
604 ServerConfig.layerTest(process.cwd(), {
605 prefix: "provider-instance-registry-all-drivers-test",
606 }),
607 ),
608 Layer.provideMerge(infraLayer),
609 Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
610 Layer.provideMerge(ServerSettingsService.layerTest()),
611 Layer.provideMerge(TestHttpClientLive),
612 Layer.provideMerge(ServerSettingsService.layerTest()),
613 Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
614 Layer.provideMerge(ModelManifest.layerTest),
615 Layer.provideMerge(ResetCreditCoordinator.layerTest),
616 );
617 const testLayer = ProviderOrchestrationAdapterInfrastructureLive.pipe(
618 Layer.provideMerge(baseLayer),
619 );
620​
621 it.live("boots one instance of every shipped driver from a single config map", () =>
622 Effect.gen(function* () {
623 const codexId = ProviderInstanceId.make("codex_default");
624 const claudeId = ProviderInstanceId.make("claude_default");
625 const cursorId = ProviderInstanceId.make("cursor_default");
626 const grokId = ProviderInstanceId.make("grok_default");
627 const openCodeId = ProviderInstanceId.make("opencode_default");
628​
629 const codexDriverKind = ProviderDriverKind.make("codex");
630 const claudeDriverKind = ProviderDriverKind.make("claudeAgent");
631 const cursorDriverKind = ProviderDriverKind.make("cursor");
632 const grokDriverKind = ProviderDriverKind.make("grok");
633 const openCodeDriverKind = ProviderDriverKind.make("opencode");
634​
635 const configMap: ProviderInstanceConfigMap = {
636 [codexId]: {
637 driver: codexDriverKind,
638 displayName: "Codex",
639 enabled: false,
640 config: makeCodexConfig({ homePath: "/home/julius/.codex" }),
641 },
642 [claudeId]: {
643 driver: claudeDriverKind,
644 displayName: "Claude",
645 enabled: false,
646 config: makeClaudeConfig({
647 homePath: "/home/julius/.claude-work",
648 launchArgs: "--verbose",
649 }),
650 },
651 [cursorId]: {
652 driver: cursorDriverKind,
653 displayName: "Cursor",
654 enabled: false,
655 config: makeCursorConfig({}),
656 },
657 [grokId]: {
658 driver: grokDriverKind,
659 displayName: "Grok",
660 enabled: false,
661 config: makeGrokConfig({}),
662 },
663 [openCodeId]: {
664 driver: openCodeDriverKind,
665 displayName: "OpenCode",
666 enabled: false,
667 config: makeOpenCodeConfig({}),
668 },
669 };
670​
671 const { registry } = yield* makeProviderInstanceRegistry<
672 CodexDriverEnv | ClaudeDriverEnv | CursorDriverEnv | GrokDriverEnv | OpenCodeDriverEnv
673 >({
674 drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
675 configMap,
676 });
677​
678 // Every configured instance must materialize — none downgraded to a
679 // shadow snapshot, because every driver in the map is registered.
680 const unavailable = yield* registry.listUnavailable;
681 expect(unavailable).toEqual([]);
682​
683 const instances = yield* registry.listInstances;
684 expect(instances).toHaveLength(5);
685 expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
686 [codexId, claudeId, cursorId, grokId, openCodeId].toSorted(),
687 );
688​
689 // Instance lookup by id resolves each instance to its own bundle —
690 // this is how rest-of-server routes turn/session calls in the new
691 // model. Each driver's bundle carries its advertised `driverKind`.
692 const codex = yield* registry.getInstance(codexId);
693 const claude = yield* registry.getInstance(claudeId);
694 const cursor = yield* registry.getInstance(cursorId);
695 const grok = yield* registry.getInstance(grokId);
696 const openCode = yield* registry.getInstance(openCodeId);
697 expect(codex?.driverKind).toBe(codexDriverKind);
698 expect(claude?.driverKind).toBe(claudeDriverKind);
699 expect(cursor?.driverKind).toBe(cursorDriverKind);
700 expect(grok?.driverKind).toBe(grokDriverKind);
701 expect(openCode?.driverKind).toBe(openCodeDriverKind);
702 expect(codex?.displayName).toBe("Codex");
703 expect(claude?.displayName).toBe("Claude");
704 expect(cursor?.displayName).toBe("Cursor");
705 expect(grok?.displayName).toBe("Grok");
706 expect(openCode?.displayName).toBe("OpenCode");
707​
708 // Every instance owns its own set of closures — no sharing across
709 // drivers. `orchestrationAdapter` / `textGeneration` / `snapshot` are all
710 // distinct references even when two instances happen to share a
711 // trait (e.g. Cursor + others all use a stub-or-real
712 // `textGeneration`; they must still be different object values).
713 const adapters = [
714 codex!.orchestrationAdapter,
715 claude!.orchestrationAdapter,
716 cursor!.orchestrationAdapter,
717 grok!.orchestrationAdapter,
718 openCode!.orchestrationAdapter,
719 ];
720 expect(new Set(adapters).size).toBe(adapters.length);
721 const textGenerations = [
722 codex!.textGeneration,
723 claude!.textGeneration,
724 cursor!.textGeneration,
725 grok!.textGeneration,
726 openCode!.textGeneration,
727 ];
728 expect(new Set(textGenerations).size).toBe(textGenerations.length);
729 const snapshots = [
730 codex!.snapshot,
731 claude!.snapshot,
732 cursor!.snapshot,
733 grok!.snapshot,
734 openCode!.snapshot,
735 ];
736 expect(new Set(snapshots).size).toBe(snapshots.length);
737​
738 // Snapshots identify themselves by `instanceId` + `driver` so
739 // downstream aggregation in `ProviderRegistry` can tell instances
740 // apart even when two share a driver. With `enabled: false`, the
741 // check short-circuits and we get a disabled/pending snapshot back
742 // — that's enough signal to validate the stamping wrapper without
743 // spawning real binaries.
744 const codexSnapshot = yield* codex!.snapshot.getSnapshot;
745 expect(codexSnapshot.instanceId).toBe(codexId);
746 expect(codexSnapshot.driver).toBe(codexDriverKind);
747 expect(codexSnapshot.enabled).toBe(false);
748 expect(codexSnapshot.continuation?.groupKey).toBe(
749 `codex:home:${(yield* Path.Path).resolve("/home/julius/.codex")}`,
750 );
751​
752 const claudeSnapshot = yield* claude!.snapshot.getSnapshot;
753 expect(claudeSnapshot.instanceId).toBe(claudeId);
754 expect(claudeSnapshot.driver).toBe(claudeDriverKind);
755 expect(claudeSnapshot.enabled).toBe(false);
756 expect(claudeSnapshot.continuation?.groupKey).toBe(
757 `claude:home:${(yield* Path.Path).resolve("/home/julius/.claude-work")}`,
758 );
759​
760 const cursorSnapshot = yield* cursor!.snapshot.getSnapshot;
761 expect(cursorSnapshot.instanceId).toBe(cursorId);
762 expect(cursorSnapshot.driver).toBe(cursorDriverKind);
763 expect(cursorSnapshot.enabled).toBe(false);
764 expect(cursorSnapshot.continuation?.groupKey).toBe(
765 `${cursorDriverKind}:instance:${cursorId}`,
766 );
767​
768 const grokSnapshot = yield* grok!.snapshot.getSnapshot;
769 expect(grokSnapshot.instanceId).toBe(grokId);
770 expect(grokSnapshot.driver).toBe(grokDriverKind);
771 expect(grokSnapshot.enabled).toBe(false);
772 expect(grokSnapshot.continuation?.groupKey).toBe(`${grokDriverKind}:instance:${grokId}`);
773​
774 const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot;
775 expect(openCodeSnapshot.instanceId).toBe(openCodeId);
776 expect(openCodeSnapshot.driver).toBe(openCodeDriverKind);
777 expect(openCodeSnapshot.enabled).toBe(false);
778 expect(openCodeSnapshot.continuation?.groupKey).toBe(
779 `${openCodeDriverKind}:instance:${openCodeId}`,
780 );
781 }).pipe(Effect.provide(testLayer)),
782 );
783});