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