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

ProviderInstanceRegistryLive.test.ts

801 lines31.7 KB

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