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

ProviderInstanceRegistry.test.ts

779 lines30.5 KB

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