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(
227 "shadows instances whose driver is not registered in this build without failing boot",
228 () =>
229 Effect.gen(function* () {
230 const codexId = ProviderInstanceId.make("codex_main");
231 const ghostId = ProviderInstanceId.make("ghost_main");
232
233 const configMap: ProviderInstanceConfigMap = {
234 [codexId]: {
235 driver: ProviderDriverKind.make("codex"),
236 enabled: false,
237 config: makeCodexConfig({}),
238 },
239 [ghostId]: {
240 driver: ProviderDriverKind.make("ghostDriver"),
241 displayName: "A fork-only driver we don't ship",
242 enabled: false,
243 config: { arbitrary: "payload", preserved: true },
244 },
245 };
246
247 const { registry } = yield* makeProviderInstanceRegistry({
248 drivers: [CodexDriver],
249 configMap,
250 });
251
252 const instances = yield* registry.listInstances;
253 expect(instances).toHaveLength(1);
254 expect(instances[0]!.instanceId).toBe(codexId);
255
256 const unavailable = yield* registry.listUnavailable;
257 expect(unavailable).toHaveLength(1);
258 const ghost = unavailable[0]!;
259 expect(ghost.instanceId).toBe(ghostId);
260 expect(ghost.driver).toBe("ghostDriver");
261 expect(ghost.availability).toBe("unavailable");
262 expect(ghost.unavailableReason).toMatch(/ghostDriver/);
263 }).pipe(Effect.provide(testLayer)),
264 );
265});
266
267describe("ProviderInstanceRegistryLive — all drivers slice", () => {
268 // All drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
269 // Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`
270 // at construction time, so we wire `OpenCodeRuntimeLive` into the stack.
271 // `OpenCodeRuntimeLive` bundles its own `NetService.layer` via
272 // `Layer.provide`, so the only external requirement it still exposes is
273 // `ChildProcessSpawner` — resolved here by piping it through
274 // `provideMerge(NodeServices.layer)`.
275 //
276 // The nested `provideMerge`s read bottom-up: `NodeServices.layer`
277 // provides `OpenCodeRuntimeLive`'s deps while keeping its own outputs
278 // surfaced; that merged layer then provides `ServerConfig.layerTest`'s
279 // `FileSystem` dep while keeping everything else surfaced to the test.
280 const infraLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer));
281 const testLayer = ServerConfig.layerTest(process.cwd(), {
282 prefix: "provider-instance-registry-all-drivers-test",
283 }).pipe(
284 Layer.provideMerge(infraLayer),
285 Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
286 Layer.provideMerge(ServerSettingsService.layerTest()),
287 Layer.provideMerge(TestHttpClientLive),
288 Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
289 );
290
291 it.live("boots one instance of every shipped driver from a single config map", () =>
292 Effect.gen(function* () {
293 const codexId = ProviderInstanceId.make("codex_default");
294 const claudeId = ProviderInstanceId.make("claude_default");
295 const cursorId = ProviderInstanceId.make("cursor_default");
296 const grokId = ProviderInstanceId.make("grok_default");
297 const openCodeId = ProviderInstanceId.make("opencode_default");
298
299 const codexDriverKind = ProviderDriverKind.make("codex");
300 const claudeDriverKind = ProviderDriverKind.make("claudeAgent");
301 const cursorDriverKind = ProviderDriverKind.make("cursor");
302 const grokDriverKind = ProviderDriverKind.make("grok");
303 const openCodeDriverKind = ProviderDriverKind.make("opencode");
304
305 const configMap: ProviderInstanceConfigMap = {
306 [codexId]: {
307 driver: codexDriverKind,
308 displayName: "Codex",
309 enabled: false,
310 config: makeCodexConfig({ homePath: "/home/julius/.codex" }),
311 },
312 [claudeId]: {
313 driver: claudeDriverKind,
314 displayName: "Claude",
315 enabled: false,
316 config: makeClaudeConfig({
317 homePath: "/home/julius/.claude-work",
318 launchArgs: "--verbose",
319 }),
320 },
321 [cursorId]: {
322 driver: cursorDriverKind,
323 displayName: "Cursor",
324 enabled: false,
325 config: makeCursorConfig({}),
326 },
327 [grokId]: {
328 driver: grokDriverKind,
329 displayName: "Grok",
330 enabled: false,
331 config: makeGrokConfig({}),
332 },
333 [openCodeId]: {
334 driver: openCodeDriverKind,
335 displayName: "OpenCode",
336 enabled: false,
337 config: makeOpenCodeConfig({}),
338 },
339 };
340
341 const { registry } = yield* makeProviderInstanceRegistry({
342 drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
343 configMap,
344 });
345
346 // Every configured instance must materialize — none downgraded to a
347 // shadow snapshot, because every driver in the map is registered.
348 const unavailable = yield* registry.listUnavailable;
349 expect(unavailable).toEqual([]);
350
351 const instances = yield* registry.listInstances;
352 expect(instances).toHaveLength(5);
353 expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
354 [codexId, claudeId, cursorId, grokId, openCodeId].toSorted(),
355 );
356
357 // Instance lookup by id resolves each instance to its own bundle —
358 // this is how rest-of-server routes turn/session calls in the new
359 // model. Each driver's bundle carries its advertised `driverKind`.
360 const codex = yield* registry.getInstance(codexId);
361 const claude = yield* registry.getInstance(claudeId);
362 const cursor = yield* registry.getInstance(cursorId);
363 const grok = yield* registry.getInstance(grokId);
364 const openCode = yield* registry.getInstance(openCodeId);
365 expect(codex?.driverKind).toBe(codexDriverKind);
366 expect(claude?.driverKind).toBe(claudeDriverKind);
367 expect(cursor?.driverKind).toBe(cursorDriverKind);
368 expect(grok?.driverKind).toBe(grokDriverKind);
369 expect(openCode?.driverKind).toBe(openCodeDriverKind);
370 expect(codex?.displayName).toBe("Codex");
371 expect(claude?.displayName).toBe("Claude");
372 expect(cursor?.displayName).toBe("Cursor");
373 expect(grok?.displayName).toBe("Grok");
374 expect(openCode?.displayName).toBe("OpenCode");
375
376 // Every instance owns its own set of closures — no sharing across
377 // drivers. `adapter` / `textGeneration` / `snapshot` are all
378 // distinct references even when two instances happen to share a
379 // trait (e.g. Cursor + others all use a stub-or-real
380 // `textGeneration`; they must still be different object values).
381 const adapters = [
382 codex!.adapter,
383 claude!.adapter,
384 cursor!.adapter,
385 grok!.adapter,
386 openCode!.adapter,
387 ];
388 expect(new Set(adapters).size).toBe(adapters.length);
389 const textGenerations = [
390 codex!.textGeneration,
391 claude!.textGeneration,
392 cursor!.textGeneration,
393 grok!.textGeneration,
394 openCode!.textGeneration,
395 ];
396 expect(new Set(textGenerations).size).toBe(textGenerations.length);
397 const snapshots = [
398 codex!.snapshot,
399 claude!.snapshot,
400 cursor!.snapshot,
401 grok!.snapshot,
402 openCode!.snapshot,
403 ];
404 expect(new Set(snapshots).size).toBe(snapshots.length);
405
406 // Snapshots identify themselves by `instanceId` + `driver` so
407 // downstream aggregation in `ProviderRegistry` can tell instances
408 // apart even when two share a driver. With `enabled: false`, the
409 // check short-circuits and we get a disabled/pending snapshot back
410 // — that's enough signal to validate the stamping wrapper without
411 // spawning real binaries.
412 const codexSnapshot = yield* codex!.snapshot.getSnapshot;
413 expect(codexSnapshot.instanceId).toBe(codexId);
414 expect(codexSnapshot.driver).toBe(codexDriverKind);
415 expect(codexSnapshot.enabled).toBe(false);
416 expect(codexSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex");
417
418 const claudeSnapshot = yield* claude!.snapshot.getSnapshot;
419 expect(claudeSnapshot.instanceId).toBe(claudeId);
420 expect(claudeSnapshot.driver).toBe(claudeDriverKind);
421 expect(claudeSnapshot.enabled).toBe(false);
422 expect(claudeSnapshot.continuation?.groupKey).toBe("claude:home:/home/julius/.claude-work");
423
424 const cursorSnapshot = yield* cursor!.snapshot.getSnapshot;
425 expect(cursorSnapshot.instanceId).toBe(cursorId);
426 expect(cursorSnapshot.driver).toBe(cursorDriverKind);
427 expect(cursorSnapshot.enabled).toBe(false);
428 expect(cursorSnapshot.continuation?.groupKey).toBe(
429 `${cursorDriverKind}:instance:${cursorId}`,
430 );
431
432 const grokSnapshot = yield* grok!.snapshot.getSnapshot;
433 expect(grokSnapshot.instanceId).toBe(grokId);
434 expect(grokSnapshot.driver).toBe(grokDriverKind);
435 expect(grokSnapshot.enabled).toBe(false);
436 expect(grokSnapshot.continuation?.groupKey).toBe(`${grokDriverKind}:instance:${grokId}`);
437
438 const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot;
439 expect(openCodeSnapshot.instanceId).toBe(openCodeId);
440 expect(openCodeSnapshot.driver).toBe(openCodeDriverKind);
441 expect(openCodeSnapshot.enabled).toBe(false);
442 expect(openCodeSnapshot.continuation?.groupKey).toBe(
443 `${openCodeDriverKind}:instance:${openCodeId}`,
444 );
445 }).pipe(Effect.provide(testLayer)),
446 );
447});