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