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

ProviderInstanceRegistryLive.test.ts

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