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