Open History to see the last commit
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 * as DateTime from "effect/DateTime";
38import * as Effect from "effect/Effect";
39import * as Layer from "effect/Layer";
40import * as Stream from "effect/Stream";
41import { HttpClient, HttpClientResponse } from "effect/unstable/http";
42
43import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
44import type { BuiltInDriversEnv } from "../builtInDrivers.ts";
45import { AntigravityInstallation } from "../AntigravityInstallation.ts";
46import { ServerConfig } from "../../config.ts";
47import { ServerSettingsService } from "../../serverSettings.ts";
48import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
49import { CodexDriver } from "../Drivers/CodexDriver.ts";
50import { CursorDriver } from "../Drivers/CursorDriver.ts";
51import { GrokDriver } from "../Drivers/GrokDriver.ts";
52import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
53import * as ModelManifest from "../ModelManifest.ts";
54import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
55import * as CodexResetCredit from "./codexResetCredit.ts";
56import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
57import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
58
59const TestHttpClientLive = Layer.succeed(
60 HttpClient.HttpClient,
61 HttpClient.make((request) =>
62 Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
63 ),
64);
65
66const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
67
68const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
69 reportClientActivity: () => Effect.void,
70 removeRpcClient: () => Effect.void,
71 reportHostPowerState: () => Effect.void,
72 snapshot: Effect.succeed({
73 hostPower: {
74 source: "unknown",
75 idle: "unknown",
76 idleSeconds: null,
77 locked: "unknown",
78 suspended: false,
79 onBattery: "unknown",
80 lowPowerMode: "unknown",
81 thermalState: "unknown",
82 stale: true,
83 updatedAt: TEST_EPOCH,
84 },
85 leases: [],
86 activeForegroundLeaseCount: 0,
87 activeScopeKeys: [],
88 shouldRunOpportunisticWork: true,
89 updatedAt: TEST_EPOCH,
90 }),
91 streamChanges: Stream.empty,
92 hasDemand: () => Effect.succeed(true),
93 shouldRunScopeWork: () => Effect.succeed(true),
94 shouldRunOpportunisticWork: Effect.succeed(true),
95});
96
97const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
98 enabled: false,
99 binaryPath: "codex",
100 homePath: "",
101 shadowHomePath: "",
102 launchArgs: "",
103 customModels: [],
104 ...overrides,
105});
106
107const makeClaudeConfig = (overrides: Partial<ClaudeSettings>): ClaudeSettings => ({
108 enabled: false,
109 binaryPath: "claude",
110 homePath: "",
111 customModels: [],
112 launchArgs: "",
113 autoCompactWindow: "",
114 ...overrides,
115});
116
117const makeCursorConfig = (overrides: Partial<CursorSettings>): CursorSettings => ({
118 enabled: false,
119 binaryPath: "cursor-agent",
120 apiEndpoint: "",
121 customModels: [],
122 ...overrides,
123});
124
125const makeGrokConfig = (overrides: Partial<GrokSettings>): GrokSettings => ({
126 enabled: false,
127 binaryPath: "grok",
128 customModels: [],
129 ...overrides,
130});
131
132const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSettings => ({
133 enabled: false,
134 binaryPath: "opencode",
135 serverUrl: "",
136 serverPassword: "",
137 customModels: [],
138 ...overrides,
139});
140
141describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
142 // `ServerConfig.layerTest` needs `FileSystem` to materialize its scratch
143 // directory. `Layer.merge` just unions requirements, so we have to push
144 // `NodeServices.layer` through `Layer.provideMerge` to satisfy that
145 // dependency while still surfacing NodeServices to the test body (the
146 // codex driver's `create` yields `ChildProcessSpawner` directly).
147 const testLayer = ServerConfig.layerTest(process.cwd(), {
148 prefix: "provider-instance-registry-test",
149 }).pipe(
150 Layer.provideMerge(NodeServices.layer),
151 Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
152 Layer.provideMerge(ServerSettingsService.layerTest()),
153 Layer.provideMerge(TestHttpClientLive),
154 Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
155 Layer.provideMerge(ModelManifest.layerTest),
156 Layer.provideMerge(CodexResetCredit.layerTest),
157 );
158
159 it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () =>
160 Effect.gen(function* () {
161 const personalId = ProviderInstanceId.make("codex_personal");
162 const workId = ProviderInstanceId.make("codex_work");
163 const codexDriverKind = ProviderDriverKind.make("codex");
164
165 const configMap: ProviderInstanceConfigMap = {
166 [personalId]: {
167 driver: codexDriverKind,
168 displayName: "Codex (personal)",
169 enabled: false,
170 config: makeCodexConfig({
171 binaryPath: "/opt/codex-personal/bin/codex",
172 homePath: "/home/julius/.codex_personal",
173 customModels: ["personal-preview"],
174 }),
175 },
176 [workId]: {
177 driver: codexDriverKind,
178 displayName: "Codex (work)",
179 enabled: false,
180 config: makeCodexConfig({
181 binaryPath: "/opt/codex-work/bin/codex",
182 homePath: "/home/julius/.codex",
183 customModels: ["work-preview"],
184 }),
185 },
186 };
187
188 const { registry } = yield* makeProviderInstanceRegistry({
189 drivers: [CodexDriver],
190 configMap,
191 });
192
193 const instances = yield* registry.listInstances;
194 expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
195 [personalId, workId].toSorted(),
196 );
197 expect(instances.every((instance) => instance.driverKind === codexDriverKind)).toBe(true);
198 expect(instances.map((instance) => instance.displayName).toSorted()).toEqual(
199 ["Codex (personal)", "Codex (work)"].toSorted(),
200 );
201
202 // Each instance must be retrievable by id and carry its *own* closures.
203 const personal = yield* registry.getInstance(personalId);
204 const work = yield* registry.getInstance(workId);
205 expect(personal).toBeDefined();
206 expect(work).toBeDefined();
207 expect(personal!.adapter).not.toBe(work!.adapter);
208 expect(personal!.textGeneration).not.toBe(work!.textGeneration);
209 expect(personal!.snapshot).not.toBe(work!.snapshot);
210
211 // Snapshots identify themselves by instanceId + driver — this is
212 // what makes per-instance routing distinguishable downstream.
213 const personalSnapshot = yield* personal!.snapshot.getSnapshot;
214 expect(personalSnapshot.instanceId).toBe(personalId);
215 expect(personalSnapshot.driver).toBe(codexDriverKind);
216 expect(personalSnapshot.enabled).toBe(false);
217 expect(personalSnapshot.continuation?.groupKey).toBe(
218 "codex:home:/home/julius/.codex_personal",
219 );
220
221 const workSnapshot = yield* work!.snapshot.getSnapshot;
222 expect(workSnapshot.instanceId).toBe(workId);
223 expect(workSnapshot.driver).toBe(codexDriverKind);
224 expect(workSnapshot.enabled).toBe(false);
225 expect(workSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex");
226
227 // Nothing goes to the unavailable bucket — both drivers are registered.
228 const unavailable = yield* registry.listUnavailable;
229 expect(unavailable).toEqual([]);
230 }).pipe(Effect.provide(testLayer)),
231 );
232
233 it.live("treats an explicit in-config enabled:false as disabling despite the envelope", () =>
234 Effect.gen(function* () {
235 // Old settings files can carry both flags with conflicting values.
236 // The explicit false must win so a user's disable is never undone.
237 const staleId = ProviderInstanceId.make("codex_stale");
238 const configMap: ProviderInstanceConfigMap = {
239 [staleId]: {
240 driver: ProviderDriverKind.make("codex"),
241 enabled: true,
242 config: makeCodexConfig({ enabled: false }),
243 },
244 };
245
246 const { registry } = yield* makeProviderInstanceRegistry({
247 drivers: [CodexDriver],
248 configMap,
249 });
250
251 const instance = yield* registry.getInstance(staleId);
252 expect(instance).toBeDefined();
253 expect(instance!.enabled).toBe(false);
254 const snapshot = yield* instance!.snapshot.getSnapshot;
255 expect(snapshot.enabled).toBe(false);
256 }).pipe(Effect.provide(testLayer)),
257 );
258
259 it.live(
260 "shadows instances whose driver is not registered in this build without failing boot",
261 () =>
262 Effect.gen(function* () {
263 const codexId = ProviderInstanceId.make("codex_main");
264 const ghostId = ProviderInstanceId.make("ghost_main");
265
266 const configMap: ProviderInstanceConfigMap = {
267 [codexId]: {
268 driver: ProviderDriverKind.make("codex"),
269 enabled: false,
270 config: makeCodexConfig({}),
271 },
272 [ghostId]: {
273 driver: ProviderDriverKind.make("ghostDriver"),
274 displayName: "A fork-only driver we don't ship",
275 enabled: false,
276 config: { arbitrary: "payload", preserved: true },
277 },
278 };
279
280 const { registry } = yield* makeProviderInstanceRegistry({
281 drivers: [CodexDriver],
282 configMap,
283 });
284
285 const instances = yield* registry.listInstances;
286 expect(instances).toHaveLength(1);
287 expect(instances[0]!.instanceId).toBe(codexId);
288
289 const unavailable = yield* registry.listUnavailable;
290 expect(unavailable).toHaveLength(1);
291 const ghost = unavailable[0]!;
292 expect(ghost.instanceId).toBe(ghostId);
293 expect(ghost.driver).toBe("ghostDriver");
294 expect(ghost.availability).toBe("unavailable");
295 expect(ghost.unavailableReason).toMatch(/ghostDriver/);
296 }).pipe(Effect.provide(testLayer)),
297 );
298});
299
300describe("ProviderInstanceRegistryLive — all drivers slice", () => {
301 // All drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
302 // Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`
303 // at construction time, so we wire `OpenCodeRuntimeLive` into the stack.
304 // `OpenCodeRuntimeLive` bundles its own `NetService.layer` via
305 // `Layer.provide`, so the only external requirement it still exposes is
306 // `ChildProcessSpawner` — resolved here by piping it through
307 // `provideMerge(NodeServices.layer)`.
308 //
309 // The nested `provideMerge`s read bottom-up: `NodeServices.layer`
310 // provides `OpenCodeRuntimeLive`'s deps while keeping its own outputs
311 // surfaced; that merged layer then provides `ServerConfig.layerTest`'s
312 // `FileSystem` dep while keeping everything else surfaced to the test.
313 const infraLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer));
314 const testLayer = AntigravityInstallation.layer.pipe(
315 Layer.provideMerge(
316 ServerConfig.layerTest(process.cwd(), {
317 prefix: "provider-instance-registry-all-drivers-test",
318 }),
319 ),
320 Layer.provideMerge(infraLayer),
321 Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
322 Layer.provideMerge(ServerSettingsService.layerTest()),
323 Layer.provideMerge(TestHttpClientLive),
324 Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
325 Layer.provideMerge(ModelManifest.layerTest),
326 Layer.provideMerge(CodexResetCredit.layerTest),
327 );
328
329 it.live("boots one instance of every shipped driver from a single config map", () =>
330 Effect.gen(function* () {
331 const codexId = ProviderInstanceId.make("codex_default");
332 const claudeId = ProviderInstanceId.make("claude_default");
333 const cursorId = ProviderInstanceId.make("cursor_default");
334 const grokId = ProviderInstanceId.make("grok_default");
335 const openCodeId = ProviderInstanceId.make("opencode_default");
336
337 const codexDriverKind = ProviderDriverKind.make("codex");
338 const claudeDriverKind = ProviderDriverKind.make("claudeAgent");
339 const cursorDriverKind = ProviderDriverKind.make("cursor");
340 const grokDriverKind = ProviderDriverKind.make("grok");
341 const openCodeDriverKind = ProviderDriverKind.make("opencode");
342
343 const configMap: ProviderInstanceConfigMap = {
344 [codexId]: {
345 driver: codexDriverKind,
346 displayName: "Codex",
347 enabled: false,
348 config: makeCodexConfig({ homePath: "/home/julius/.codex" }),
349 },
350 [claudeId]: {
351 driver: claudeDriverKind,
352 displayName: "Claude",
353 enabled: false,
354 config: makeClaudeConfig({
355 homePath: "/home/julius/.claude-work",
356 launchArgs: "--verbose",
357 }),
358 },
359 [cursorId]: {
360 driver: cursorDriverKind,
361 displayName: "Cursor",
362 enabled: false,
363 config: makeCursorConfig({}),
364 },
365 [grokId]: {
366 driver: grokDriverKind,
367 displayName: "Grok",
368 enabled: false,
369 config: makeGrokConfig({}),
370 },
371 [openCodeId]: {
372 driver: openCodeDriverKind,
373 displayName: "OpenCode",
374 enabled: false,
375 config: makeOpenCodeConfig({}),
376 },
377 };
378
379 const { registry } = yield* makeProviderInstanceRegistry<BuiltInDriversEnv>({
380 drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
381 configMap,
382 });
383
384 // Every configured instance must materialize — none downgraded to a
385 // shadow snapshot, because every driver in the map is registered.
386 const unavailable = yield* registry.listUnavailable;
387 expect(unavailable).toEqual([]);
388
389 const instances = yield* registry.listInstances;
390 expect(instances).toHaveLength(5);
391 expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
392 [codexId, claudeId, cursorId, grokId, openCodeId].toSorted(),
393 );
394
395 // Instance lookup by id resolves each instance to its own bundle —
396 // this is how rest-of-server routes turn/session calls in the new
397 // model. Each driver's bundle carries its advertised `driverKind`.
398 const codex = yield* registry.getInstance(codexId);
399 const claude = yield* registry.getInstance(claudeId);
400 const cursor = yield* registry.getInstance(cursorId);
401 const grok = yield* registry.getInstance(grokId);
402 const openCode = yield* registry.getInstance(openCodeId);
403 expect(codex?.driverKind).toBe(codexDriverKind);
404 expect(claude?.driverKind).toBe(claudeDriverKind);
405 expect(cursor?.driverKind).toBe(cursorDriverKind);
406 expect(grok?.driverKind).toBe(grokDriverKind);
407 expect(openCode?.driverKind).toBe(openCodeDriverKind);
408 expect(codex?.displayName).toBe("Codex");
409 expect(claude?.displayName).toBe("Claude");
410 expect(cursor?.displayName).toBe("Cursor");
411 expect(grok?.displayName).toBe("Grok");
412 expect(openCode?.displayName).toBe("OpenCode");
413
414 // Every instance owns its own set of closures — no sharing across
415 // drivers. `adapter` / `textGeneration` / `snapshot` are all
416 // distinct references even when two instances happen to share a
417 // trait (e.g. Cursor + others all use a stub-or-real
418 // `textGeneration`; they must still be different object values).
419 const adapters = [
420 codex!.adapter,
421 claude!.adapter,
422 cursor!.adapter,
423 grok!.adapter,
424 openCode!.adapter,
425 ];
426 expect(new Set(adapters).size).toBe(adapters.length);
427 const textGenerations = [
428 codex!.textGeneration,
429 claude!.textGeneration,
430 cursor!.textGeneration,
431 grok!.textGeneration,
432 openCode!.textGeneration,
433 ];
434 expect(new Set(textGenerations).size).toBe(textGenerations.length);
435 const snapshots = [
436 codex!.snapshot,
437 claude!.snapshot,
438 cursor!.snapshot,
439 grok!.snapshot,
440 openCode!.snapshot,
441 ];
442 expect(new Set(snapshots).size).toBe(snapshots.length);
443
444 // Snapshots identify themselves by `instanceId` + `driver` so
445 // downstream aggregation in `ProviderRegistry` can tell instances
446 // apart even when two share a driver. With `enabled: false`, the
447 // check short-circuits and we get a disabled/pending snapshot back
448 // — that's enough signal to validate the stamping wrapper without
449 // spawning real binaries.
450 const codexSnapshot = yield* codex!.snapshot.getSnapshot;
451 expect(codexSnapshot.instanceId).toBe(codexId);
452 expect(codexSnapshot.driver).toBe(codexDriverKind);
453 expect(codexSnapshot.enabled).toBe(false);
454 expect(codexSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex");
455
456 const claudeSnapshot = yield* claude!.snapshot.getSnapshot;
457 expect(claudeSnapshot.instanceId).toBe(claudeId);
458 expect(claudeSnapshot.driver).toBe(claudeDriverKind);
459 expect(claudeSnapshot.enabled).toBe(false);
460 expect(claudeSnapshot.continuation?.groupKey).toBe("claude:home:/home/julius/.claude-work");
461
462 const cursorSnapshot = yield* cursor!.snapshot.getSnapshot;
463 expect(cursorSnapshot.instanceId).toBe(cursorId);
464 expect(cursorSnapshot.driver).toBe(cursorDriverKind);
465 expect(cursorSnapshot.enabled).toBe(false);
466 expect(cursorSnapshot.continuation?.groupKey).toBe(
467 `${cursorDriverKind}:instance:${cursorId}`,
468 );
469
470 const grokSnapshot = yield* grok!.snapshot.getSnapshot;
471 expect(grokSnapshot.instanceId).toBe(grokId);
472 expect(grokSnapshot.driver).toBe(grokDriverKind);
473 expect(grokSnapshot.enabled).toBe(false);
474 expect(grokSnapshot.continuation?.groupKey).toBe(`${grokDriverKind}:instance:${grokId}`);
475
476 const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot;
477 expect(openCodeSnapshot.instanceId).toBe(openCodeId);
478 expect(openCodeSnapshot.driver).toBe(openCodeDriverKind);
479 expect(openCodeSnapshot.enabled).toBe(false);
480 expect(openCodeSnapshot.continuation?.groupKey).toBe(
481 `${openCodeDriverKind}:instance:${openCodeId}`,
482 );
483 }).pipe(Effect.provide(testLayer)),
484 );
485});