Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProviderSwitch.integration.test.ts

973 lines38.5 KB

1import { assert, describe, it } from "@effect/vitest";
2import {
3 CommandId,
4 MessageId,
5 type ModelSelection,
6 type OrchestrationV2Command,
7 type OrchestrationV2ProviderCapabilities,
8 type OrchestrationV2ProviderSession,
9 type OrchestrationV2ProviderThread,
10 ProjectId,
11 ProviderInstanceId,
12 ProviderThreadId,
13 ProviderTurnId,
14 ThreadId,
15 TurnItemId,
16 ProviderDriverKind,
17} from "@t3tools/contracts";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as PubSub from "effect/PubSub";
21import * as Ref from "effect/Ref";
22import * as Stream from "effect/Stream";
23​
24import { ClaudeProviderCapabilitiesV2 } from "../Adapters/ClaudeAdapterV2.ts";
25import { CodexProviderCapabilitiesV2 } from "../Adapters/CodexAdapterV2.ts";
26import { CursorProviderCapabilitiesV2 } from "../Adapters/CursorAdapterV2.ts";
27import { OrchestratorV2 } from "../Orchestrator.ts";
28import {
29 type ProviderAdapterV2Event,
30 ProviderAdapterProtocolError,
31 type ProviderAdapterV2Shape,
32} from "../ProviderAdapter.ts";
33import { makeLayer as makeProviderAdapterRegistryLayer } from "../ProviderAdapterRegistry.ts";
34import {
35 CLAUDE_MODEL_SELECTION,
36 CODEX_MODEL_SELECTION,
37 CURSOR_MODEL_SELECTION,
38} from "./fixtures/shared.ts";
39import { makeOrchestratorV2ReplayLayerWithRegistry } from "./ProviderReplayHarness.ts";
40import { checkpointWorkspace } from "./ReplayFixtureWorkspace.ts";
41​
42const threadId = ThreadId.make("thread:provider-switch");
43const projectId = ProjectId.make("project:provider-switch");
44const firstPrompt = "Respond with exactly: codex before switch";
45const claudePrompt = "Respond with exactly: claude switched response";
46const returnPrompt = "Respond with exactly: codex after return";
47const CODEX_DRIVER = ProviderDriverKind.make("codex");
48const CLAUDE_DRIVER = ProviderDriverKind.make("claudeAgent");
49const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
50​
51interface CapturedTurn {
52 readonly driver: ProviderDriverKind;
53 readonly threadId: ThreadId;
54 readonly providerThreadId: ProviderThreadId;
55 readonly text: string;
57​
58function unimplemented(driver: ProviderDriverKind, detail: string) {
59 return Effect.fail(new ProviderAdapterProtocolError({ driver, detail }));
61​
62function makeTestAdapter(input: {
63 readonly instanceId: ProviderInstanceId;
64 readonly driver: ProviderDriverKind;
65 readonly capabilities: OrchestrationV2ProviderCapabilities;
66 readonly modelSelection: ModelSelection;
67 readonly responseByRunOrdinal: Readonly<Record<number, string>>;
68 readonly responseByThreadId?: Readonly<Record<string, Readonly<Record<number, string>>>>;
69 readonly capturedTurns: Ref.Ref<ReadonlyArray<CapturedTurn>>;
70 readonly failResume?: boolean;
71}): ProviderAdapterV2Shape {
72 return {
73 instanceId: input.instanceId,
74 driver: input.driver,
75 getCapabilities: () => Effect.succeed(input.capabilities),
76 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
77 openSession: (sessionInput) =>
78 Effect.gen(function* () {
79 const events = yield* PubSub.unbounded<ProviderAdapterV2Event>();
80 const now = yield* DateTime.now;
81 const providerSession: OrchestrationV2ProviderSession = {
82 id: sessionInput.providerSessionId,
83 driver: input.driver,
84 providerInstanceId: input.instanceId,
85 status: "ready",
86 cwd: sessionInput.runtimePolicy.cwd ?? process.cwd(),
87 model: input.modelSelection.model,
88 capabilities: input.capabilities,
89 createdAt: now,
90 updatedAt: now,
91 lastError: null,
92 };
93​
94 return {
95 instanceId: input.instanceId,
96 driver: input.driver,
97 providerSessionId: sessionInput.providerSessionId,
98 providerSession,
99 events: Stream.fromPubSub(events),
100 ensureThread: (threadInput) =>
101 Effect.gen(function* () {
102 const createdAt = yield* DateTime.now;
103 const nativeThreadId = `${input.driver}:${threadInput.threadId}`;
104 return {
105 id: ProviderThreadId.make(`provider-thread:${nativeThreadId}`),
106 driver: input.driver,
107 providerInstanceId: input.instanceId,
108 providerSessionId: sessionInput.providerSessionId,
109 appThreadId: threadInput.threadId,
110 ownerNodeId: null,
111 nativeThreadRef: {
112 driver: input.driver,
113 nativeId: nativeThreadId,
114 strength: "strong",
115 },
116 nativeConversationHeadRef: null,
117 status: "idle",
118 firstRunOrdinal: null,
119 lastRunOrdinal: null,
120 handoffIds: [],
121 forkedFrom: null,
122 createdAt,
123 updatedAt: createdAt,
124 } satisfies OrchestrationV2ProviderThread;
125 }),
126 resumeThread: ({ providerThread }) =>
127 input.failResume
128 ? unimplemented(input.driver, "simulated native resume failure")
129 : Effect.succeed(providerThread),
130 startTurn: (turnInput) =>
131 Effect.gen(function* () {
132 yield* Effect.yieldNow;
133 yield* Ref.update(input.capturedTurns, (turns) => [
134 ...turns,
135 {
136 driver: input.driver,
137 threadId: turnInput.threadId,
138 providerThreadId: turnInput.providerThread.id,
139 text: turnInput.message.text,
140 },
141 ]);
142 const eventTime = yield* DateTime.now;
143 const providerTurnId = ProviderTurnId.make(
144 `provider-turn:${input.driver}:${turnInput.threadId}:${turnInput.runOrdinal}`,
145 );
146 const response =
147 input.responseByThreadId?.[turnInput.threadId]?.[turnInput.runOrdinal] ??
148 input.responseByRunOrdinal[turnInput.runOrdinal] ??
149 `${input.driver} response for run ${turnInput.runOrdinal}`;
150 const providerEvents: ReadonlyArray<ProviderAdapterV2Event> = [
151 {
152 type: "provider_turn.updated",
153 driver: input.driver,
154 providerTurn: {
155 id: providerTurnId,
156 providerThreadId: turnInput.providerThread.id,
157 nodeId: turnInput.rootNodeId,
158 runAttemptId: turnInput.attemptId,
159 nativeTurnRef: {
160 driver: input.driver,
161 nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`,
162 strength: "strong",
163 },
164 ordinal: turnInput.runOrdinal,
165 status: "completed",
166 startedAt: eventTime,
167 completedAt: eventTime,
168 },
169 },
170 {
171 type: "turn_item.updated",
172 driver: input.driver,
173 turnItem: {
174 id: TurnItemId.make(
175 `turn-item:${input.driver}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`,
176 ),
177 threadId: turnInput.threadId,
178 runId: turnInput.runId,
179 nodeId: turnInput.rootNodeId,
180 providerThreadId: turnInput.providerThread.id,
181 providerTurnId,
182 nativeItemRef: null,
183 parentItemId: null,
184 ordinal: turnInput.runOrdinal * 100 + 1,
185 status: "completed",
186 title: null,
187 startedAt: eventTime,
188 completedAt: eventTime,
189 updatedAt: eventTime,
190 type: "assistant_message",
191 messageId: MessageId.make(
192 `message:${input.driver}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`,
193 ),
194 text: response,
195 streaming: false,
196 },
197 },
198 {
199 type: "turn.terminal",
200 driver: input.driver,
201 providerThreadId: turnInput.providerThread.id,
202 providerTurnId,
203 runOrdinal: turnInput.runOrdinal,
204 status: "completed",
205 failure: null,
206 threadDisposition: "reusable",
207 },
208 ];
209 for (const event of providerEvents) {
210 yield* PubSub.publish(events, event);
211 }
212 }),
213 steerTurn: () => Effect.void,
214 interruptTurn: () => Effect.void,
215 respondToRuntimeRequest: () => Effect.void,
216 readThreadSnapshot: () =>
217 unimplemented(input.driver, "readThreadSnapshot unused in provider switch test"),
218 rollbackThread: () =>
219 unimplemented(input.driver, "rollbackThread unused in provider switch test"),
220 forkThread: () =>
221 unimplemented(input.driver, "forkThread unused in provider switch test"),
222 };
223 }),
224 };
226​
227const waitForIdle = Effect.fn("ProviderSwitchTest.waitForIdle")(function* (
228 targetThreadId: ThreadId,
229) {
230 const orchestrator = yield* OrchestratorV2;
231 for (let attempt = 0; attempt < 1_000; attempt += 1) {
232 const projection = yield* orchestrator.getThreadProjection(targetThreadId);
233 if (
234 projection.runs.every(
235 (run) => !["queued", "starting", "running", "waiting"].includes(run.status),
236 )
237 ) {
238 return projection;
239 }
240 yield* Effect.sleep("5 millis");
241 }
242 return yield* Effect.die(new Error("Provider switch test timed out waiting for idle"));
243});
244​
245describe("orchestration v2 provider switching", () => {
246 it.live("uses portable fallback when native resume fails after a provider switch", () =>
247 Effect.scoped(
248 Effect.gen(function* () {
249 const cwd = yield* checkpointWorkspace("provider-switch");
250 const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
251 const registryLayer = makeProviderAdapterRegistryLayer([
252 makeTestAdapter({
253 instanceId: ProviderInstanceId.make("codex"),
254 driver: CODEX_DRIVER,
255 capabilities: CodexProviderCapabilitiesV2,
256 modelSelection: CODEX_MODEL_SELECTION,
257 responseByRunOrdinal: {
258 1: "codex before switch",
259 3: "codex after return",
260 },
261 capturedTurns,
262 failResume: true,
263 }),
264 makeTestAdapter({
265 instanceId: ProviderInstanceId.make("claudeAgent"),
266 driver: CLAUDE_DRIVER,
267 capabilities: ClaudeProviderCapabilitiesV2,
268 modelSelection: CLAUDE_MODEL_SELECTION,
269 responseByRunOrdinal: { 2: "claude switched response" },
270 capturedTurns,
271 }),
272 ]);
273 const commands = [
274 {
275 type: "thread.create",
276 createdBy: "user",
277 creationSource: "web",
278 commandId: CommandId.make("command:provider-switch:create"),
279 threadId,
280 projectId,
281 title: "Provider switch",
282 modelSelection: CODEX_MODEL_SELECTION,
283 runtimeMode: "full-access",
284 interactionMode: "default",
285 branch: null,
286 worktreePath: null,
287 },
288 {
289 type: "message.dispatch",
290 createdBy: "user",
291 creationSource: "web",
292 commandId: CommandId.make("command:provider-switch:codex"),
293 threadId,
294 messageId: MessageId.make("message:provider-switch:codex"),
295 text: firstPrompt,
296 attachments: [],
297 modelSelection: CODEX_MODEL_SELECTION,
298 dispatchMode: { type: "start_immediately" },
299 },
300 {
301 type: "message.dispatch",
302 createdBy: "user",
303 creationSource: "web",
304 commandId: CommandId.make("command:provider-switch:claude"),
305 threadId,
306 messageId: MessageId.make("message:provider-switch:claude"),
307 text: claudePrompt,
308 attachments: [],
309 modelSelection: CLAUDE_MODEL_SELECTION,
310 dispatchMode: { type: "start_immediately" },
311 },
312 {
313 type: "message.dispatch",
314 createdBy: "user",
315 creationSource: "web",
316 commandId: CommandId.make("command:provider-switch:return"),
317 threadId,
318 messageId: MessageId.make("message:provider-switch:return"),
319 text: returnPrompt,
320 attachments: [],
321 modelSelection: CODEX_MODEL_SELECTION,
322 dispatchMode: { type: "start_immediately" },
323 },
324 ] satisfies ReadonlyArray<OrchestrationV2Command>;
325​
326 const projection = yield* Effect.gen(function* () {
327 const orchestrator = yield* OrchestratorV2;
328 yield* orchestrator.dispatch(commands[0]!);
329 yield* orchestrator.dispatch(commands[1]!);
330 yield* waitForIdle(threadId);
331 yield* orchestrator.dispatch(commands[2]!);
332 yield* waitForIdle(threadId);
333 yield* orchestrator.dispatch(commands[3]!);
334 return yield* waitForIdle(threadId);
335 }).pipe(
336 Effect.provide(
337 makeOrchestratorV2ReplayLayerWithRegistry(
338 {
339 name: "provider-switch",
340 runtimePolicyOverride: {
341 cwd,
342 approvalPolicy: "never",
343 sandboxPolicy: {
344 type: "readOnly",
345 access: { type: "fullAccess" },
346 networkAccess: false,
347 },
348 },
349 },
350 registryLayer,
351 ),
352 ),
353 );
354 const turns = yield* Ref.get(capturedTurns);
355​
356 assert.deepEqual(
357 projection.runs.map((run) => [run.providerInstanceId, run.status]),
358 [
359 ["codex", "completed"],
360 ["claudeAgent", "completed"],
361 ["codex", "completed"],
362 ],
363 );
364 assert.lengthOf(projection.providerThreads, 2);
365 assert.equal(projection.runs[0]?.providerThreadId, projection.runs[2]?.providerThreadId);
366 assert.notEqual(projection.runs[0]?.providerThreadId, projection.runs[1]?.providerThreadId);
367 assert.deepEqual(
368 projection.contextHandoffs.map((handoff) => handoff.strategy),
369 ["full_thread_summary", "delta_since_target_last_seen"],
370 );
371 assert.deepEqual(
372 projection.contextTransfers.map((transfer) => [
373 transfer.type,
374 transfer.status,
375 transfer.resolution?.strategy,
376 ]),
377 [
378 ["provider_handoff", "consumed", "portable_context"],
379 ["provider_handoff", "consumed", "delta_context"],
380 ],
381 );
382 assert.deepEqual(
383 projection.turnItems
384 .filter((item) => item.type === "user_message")
385 .map((item) => item.text),
386 [firstPrompt, claudePrompt, returnPrompt],
387 );
388 assert.deepEqual(
389 projection.providerThreads.map((providerThread) => [
390 providerThread.driver,
391 providerThread.status,
392 providerThread.handoffIds.length,
393 ]),
394 [
395 ["codex", "idle", 1],
396 ["claudeAgent", "idle", 1],
397 ],
398 );
399 assert.equal(turns[0]?.text, firstPrompt);
400 assert.include(turns[1]?.text ?? "", "Context handoff (full_thread_summary):");
401 assert.include(turns[1]?.text ?? "", "codex before switch");
402 assert.include(turns[1]?.text ?? "", claudePrompt);
403 assert.include(turns[2]?.text ?? "", "Context handoff (delta_since_target_last_seen):");
404 assert.include(turns[2]?.text ?? "", "claude switched response");
405 assert.include(turns[2]?.text ?? "", returnPrompt);
406 assert.notInclude(turns[2]?.text ?? "", "codex before switch");
407 assert.equal(turns[0]?.providerThreadId, turns[2]?.providerThreadId);
408 }),
409 ),
410 );
411​
412 it.live("resolves a Claude fork into portable Codex context on first dispatch", () =>
413 Effect.scoped(
414 Effect.gen(function* () {
415 const sourceThreadId = ThreadId.make("thread:cross-provider-fork:source");
416 const targetThreadId = ThreadId.make("thread:cross-provider-fork:target");
417 const sourcePrompt = "Remember that the release color is violet.";
418 const targetPrompt = "What release color did we choose?";
419 const cwd = yield* checkpointWorkspace("cross-provider-fork");
420 const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
421 const registryLayer = makeProviderAdapterRegistryLayer([
422 makeTestAdapter({
423 instanceId: ProviderInstanceId.make("codex"),
424 driver: CODEX_DRIVER,
425 capabilities: CodexProviderCapabilitiesV2,
426 modelSelection: CODEX_MODEL_SELECTION,
427 responseByRunOrdinal: { 1: "The release color is violet." },
428 capturedTurns,
429 }),
430 makeTestAdapter({
431 instanceId: ProviderInstanceId.make("claudeAgent"),
432 driver: CLAUDE_DRIVER,
433 capabilities: ClaudeProviderCapabilitiesV2,
434 modelSelection: CLAUDE_MODEL_SELECTION,
435 responseByRunOrdinal: { 1: "I will remember violet." },
436 capturedTurns,
437 }),
438 ]);
439 const commands = [
440 {
441 type: "thread.create",
442 createdBy: "user",
443 creationSource: "web",
444 commandId: CommandId.make("command:cross-provider-fork:create"),
445 threadId: sourceThreadId,
446 projectId,
447 title: "Cross-provider fork source",
448 modelSelection: CLAUDE_MODEL_SELECTION,
449 runtimeMode: "full-access",
450 interactionMode: "default",
451 branch: null,
452 worktreePath: null,
453 },
454 {
455 type: "message.dispatch",
456 createdBy: "user",
457 creationSource: "web",
458 commandId: CommandId.make("command:cross-provider-fork:source"),
459 threadId: sourceThreadId,
460 messageId: MessageId.make("message:cross-provider-fork:source"),
461 text: sourcePrompt,
462 attachments: [],
463 modelSelection: CLAUDE_MODEL_SELECTION,
464 dispatchMode: { type: "start_immediately" },
465 },
466 {
467 type: "thread.fork",
468 createdBy: "user",
469 creationSource: "web",
470 commandId: CommandId.make("command:cross-provider-fork:fork"),
471 sourceThreadId,
472 targetThreadId,
473 sourcePoint: { type: "latest_stable" },
474 title: "Cross-provider fork target",
475 },
476 {
477 type: "message.dispatch",
478 createdBy: "user",
479 creationSource: "web",
480 commandId: CommandId.make("command:cross-provider-fork:target"),
481 threadId: targetThreadId,
482 messageId: MessageId.make("message:cross-provider-fork:target"),
483 text: targetPrompt,
484 attachments: [],
485 modelSelection: CODEX_MODEL_SELECTION,
486 dispatchMode: { type: "start_immediately" },
487 },
488 ] satisfies ReadonlyArray<OrchestrationV2Command>;
489​
490 const targetProjection = yield* Effect.gen(function* () {
491 const orchestrator = yield* OrchestratorV2;
492 yield* orchestrator.dispatch(commands[0]!);
493 yield* orchestrator.dispatch(commands[1]!);
494 yield* waitForIdle(sourceThreadId);
495 yield* orchestrator.dispatch(commands[2]!);
496 yield* orchestrator.dispatch(commands[3]!);
497 return yield* waitForIdle(targetThreadId);
498 }).pipe(
499 Effect.provide(
500 makeOrchestratorV2ReplayLayerWithRegistry(
501 {
502 name: "cross-provider-fork",
503 runtimePolicyOverride: {
504 cwd,
505 approvalPolicy: "never",
506 sandboxPolicy: {
507 type: "readOnly",
508 access: { type: "fullAccess" },
509 networkAccess: false,
510 },
511 },
512 },
513 registryLayer,
514 ),
515 ),
516 );
517 const turns = yield* Ref.get(capturedTurns);
518 const targetTurn = turns.find((turn) => turn.threadId === targetThreadId);
519​
520 assert.deepEqual(
521 targetProjection.runs.map((run) => [run.providerInstanceId, run.status]),
522 [["codex", "completed"]],
523 );
524 assert.lengthOf(targetProjection.providerThreads, 1);
525 assert.equal(targetProjection.providerThreads[0]?.driver, "codex");
526 assert.isNull(targetProjection.providerThreads[0]?.forkedFrom);
527 assert.deepEqual(
528 targetProjection.contextTransfers.map((transfer) => [
529 transfer.type,
530 transfer.status,
531 transfer.resolution?.strategy,
532 ]),
533 [["fork", "consumed", "portable_context"]],
534 );
535 assert.deepEqual(
536 targetProjection.contextHandoffs.map((handoff) => handoff.strategy),
537 ["full_thread_summary"],
538 );
539 assert.equal(
540 targetProjection.runs[0]?.contextHandoffId,
541 targetProjection.contextHandoffs[0]?.id,
542 );
543 assert.include(targetTurn?.text ?? "", "Context handoff (full_thread_summary):");
544 assert.include(targetTurn?.text ?? "", sourcePrompt);
545 assert.include(targetTurn?.text ?? "", "I will remember violet.");
546 assert.include(targetTurn?.text ?? "", targetPrompt);
547 }),
548 ),
549 );
550​
551 it.live("resolves a same-provider Cursor fork with portable context", () =>
552 Effect.scoped(
553 Effect.gen(function* () {
554 const sourceThreadId = ThreadId.make("thread:cursor-portable-fork:source");
555 const targetThreadId = ThreadId.make("thread:cursor-portable-fork:target");
556 const sourcePrompt = "Remember that the deployment marker is indigo.";
557 const sourceResponse = "I will remember indigo.";
558 const targetPrompt = "What deployment marker did we choose?";
559 const cwd = yield* checkpointWorkspace("cursor-portable-fork");
560 const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
561 const registryLayer = makeProviderAdapterRegistryLayer([
562 makeTestAdapter({
563 instanceId: ProviderInstanceId.make("cursor"),
564 driver: CURSOR_DRIVER,
565 capabilities: CursorProviderCapabilitiesV2,
566 modelSelection: CURSOR_MODEL_SELECTION,
567 responseByRunOrdinal: {},
568 responseByThreadId: {
569 [sourceThreadId]: { 1: sourceResponse },
570 [targetThreadId]: { 1: "The deployment marker is indigo." },
571 },
572 capturedTurns,
573 }),
574 ]);
575 const commands = [
576 {
577 type: "thread.create",
578 createdBy: "user",
579 creationSource: "web",
580 commandId: CommandId.make("command:cursor-portable-fork:create"),
581 threadId: sourceThreadId,
582 projectId,
583 title: "Cursor portable fork source",
584 modelSelection: CURSOR_MODEL_SELECTION,
585 runtimeMode: "full-access",
586 interactionMode: "default",
587 branch: null,
588 worktreePath: null,
589 },
590 {
591 type: "message.dispatch",
592 createdBy: "user",
593 creationSource: "web",
594 commandId: CommandId.make("command:cursor-portable-fork:source"),
595 threadId: sourceThreadId,
596 messageId: MessageId.make("message:cursor-portable-fork:source"),
597 text: sourcePrompt,
598 attachments: [],
599 modelSelection: CURSOR_MODEL_SELECTION,
600 dispatchMode: { type: "start_immediately" },
601 },
602 {
603 type: "thread.fork",
604 createdBy: "user",
605 creationSource: "web",
606 commandId: CommandId.make("command:cursor-portable-fork:fork"),
607 sourceThreadId,
608 targetThreadId,
609 sourcePoint: { type: "latest_stable" },
610 title: "Cursor portable fork target",
611 },
612 {
613 type: "message.dispatch",
614 createdBy: "user",
615 creationSource: "web",
616 commandId: CommandId.make("command:cursor-portable-fork:target"),
617 threadId: targetThreadId,
618 messageId: MessageId.make("message:cursor-portable-fork:target"),
619 text: targetPrompt,
620 attachments: [],
621 modelSelection: CURSOR_MODEL_SELECTION,
622 dispatchMode: { type: "start_immediately" },
623 },
624 ] satisfies ReadonlyArray<OrchestrationV2Command>;
625​
626 const targetProjection = yield* Effect.gen(function* () {
627 const orchestrator = yield* OrchestratorV2;
628 yield* orchestrator.dispatch(commands[0]!);
629 yield* orchestrator.dispatch(commands[1]!);
630 yield* waitForIdle(sourceThreadId);
631 yield* orchestrator.dispatch(commands[2]!);
632 yield* orchestrator.dispatch(commands[3]!);
633 return yield* waitForIdle(targetThreadId);
634 }).pipe(
635 Effect.provide(
636 makeOrchestratorV2ReplayLayerWithRegistry(
637 {
638 name: "cursor-portable-fork",
639 runtimePolicyOverride: {
640 cwd,
641 approvalPolicy: "never",
642 sandboxPolicy: {
643 type: "readOnly",
644 access: { type: "fullAccess" },
645 networkAccess: false,
646 },
647 },
648 },
649 registryLayer,
650 ),
651 ),
652 );
653 const turns = yield* Ref.get(capturedTurns);
654 const targetTurn = turns.find((turn) => turn.threadId === targetThreadId);
655​
656 assert.deepEqual(
657 targetProjection.runs.map((run) => [run.providerInstanceId, run.status]),
658 [["cursor", "completed"]],
659 );
660 assert.lengthOf(targetProjection.providerThreads, 1);
661 assert.equal(targetProjection.providerThreads[0]?.driver, "cursor");
662 assert.isNull(targetProjection.providerThreads[0]?.forkedFrom);
663 assert.deepEqual(
664 targetProjection.contextTransfers.map((transfer) => [
665 transfer.type,
666 transfer.status,
667 transfer.resolution?.strategy,
668 ]),
669 [["fork", "consumed", "portable_context"]],
670 );
671 assert.deepEqual(
672 targetProjection.contextHandoffs.map((handoff) => handoff.strategy),
673 ["full_thread_summary"],
674 );
675 assert.include(targetTurn?.text ?? "", "Context handoff (full_thread_summary):");
676 assert.include(targetTurn?.text ?? "", sourcePrompt);
677 assert.include(targetTurn?.text ?? "", sourceResponse);
678 assert.include(targetTurn?.text ?? "", targetPrompt);
679 }),
680 ),
681 );
682​
683 it.live("switches providers while consuming a pending cross-provider merge-back", () =>
684 Effect.scoped(
685 Effect.gen(function* () {
686 const sourceThreadId = ThreadId.make("thread:cross-provider-merge:source");
687 const forkThreadId = ThreadId.make("thread:cross-provider-merge:fork");
688 const firstSourcePrompt = "Remember that the first source marker is amber.";
689 const secondSourcePrompt = "Remember that the second source marker is violet.";
690 const forkPrompt = "Remember that the fork marker is cobalt.";
691 const mergePrompt = "Report all three remembered markers.";
692 const cwd = yield* checkpointWorkspace("cross-provider-merge");
693 const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
694 const registryLayer = makeProviderAdapterRegistryLayer([
695 makeTestAdapter({
696 instanceId: ProviderInstanceId.make("codex"),
697 driver: CODEX_DRIVER,
698 capabilities: CodexProviderCapabilitiesV2,
699 modelSelection: CODEX_MODEL_SELECTION,
700 responseByRunOrdinal: {},
701 responseByThreadId: {
702 [sourceThreadId]: {
703 1: "I will remember amber.",
704 3: "The markers are amber, violet, and cobalt.",
705 },
706 [forkThreadId]: {
707 1: "I will remember cobalt.",
708 },
709 },
710 capturedTurns,
711 }),
712 makeTestAdapter({
713 instanceId: ProviderInstanceId.make("claudeAgent"),
714 driver: CLAUDE_DRIVER,
715 capabilities: ClaudeProviderCapabilitiesV2,
716 modelSelection: CLAUDE_MODEL_SELECTION,
717 responseByRunOrdinal: { 2: "I will remember violet." },
718 capturedTurns,
719 }),
720 ]);
721 const commands = [
722 {
723 type: "thread.create",
724 createdBy: "user",
725 creationSource: "web",
726 commandId: CommandId.make("command:cross-provider-merge:create"),
727 threadId: sourceThreadId,
728 projectId,
729 title: "Cross-provider merge source",
730 modelSelection: CODEX_MODEL_SELECTION,
731 runtimeMode: "full-access",
732 interactionMode: "default",
733 branch: null,
734 worktreePath: null,
735 },
736 {
737 type: "message.dispatch",
738 createdBy: "user",
739 creationSource: "web",
740 commandId: CommandId.make("command:cross-provider-merge:first-source"),
741 threadId: sourceThreadId,
742 messageId: MessageId.make("message:cross-provider-merge:first-source"),
743 text: firstSourcePrompt,
744 attachments: [],
745 modelSelection: CODEX_MODEL_SELECTION,
746 dispatchMode: { type: "start_immediately" },
747 },
748 {
749 type: "message.dispatch",
750 createdBy: "user",
751 creationSource: "web",
752 commandId: CommandId.make("command:cross-provider-merge:second-source"),
753 threadId: sourceThreadId,
754 messageId: MessageId.make("message:cross-provider-merge:second-source"),
755 text: secondSourcePrompt,
756 attachments: [],
757 modelSelection: CLAUDE_MODEL_SELECTION,
758 dispatchMode: { type: "start_immediately" },
759 },
760 {
761 type: "thread.fork",
762 createdBy: "user",
763 creationSource: "web",
764 commandId: CommandId.make("command:cross-provider-merge:fork"),
765 sourceThreadId,
766 targetThreadId: forkThreadId,
767 sourcePoint: { type: "latest_stable" },
768 title: "Cross-provider merge fork",
769 },
770 {
771 type: "message.dispatch",
772 createdBy: "user",
773 creationSource: "web",
774 commandId: CommandId.make("command:cross-provider-merge:fork-turn"),
775 threadId: forkThreadId,
776 messageId: MessageId.make("message:cross-provider-merge:fork-turn"),
777 text: forkPrompt,
778 attachments: [],
779 modelSelection: CODEX_MODEL_SELECTION,
780 dispatchMode: { type: "start_immediately" },
781 },
782 {
783 type: "thread.merge_back",
784 createdBy: "user",
785 creationSource: "web",
786 commandId: CommandId.make("command:cross-provider-merge:merge"),
787 sourceThreadId: forkThreadId,
788 targetThreadId: sourceThreadId,
789 sourcePoint: { type: "latest_stable" },
790 },
791 {
792 type: "message.dispatch",
793 createdBy: "user",
794 creationSource: "web",
795 commandId: CommandId.make("command:cross-provider-merge:consume"),
796 threadId: sourceThreadId,
797 messageId: MessageId.make("message:cross-provider-merge:consume"),
798 text: mergePrompt,
799 attachments: [],
800 modelSelection: CODEX_MODEL_SELECTION,
801 dispatchMode: { type: "start_immediately" },
802 },
803 ] satisfies ReadonlyArray<OrchestrationV2Command>;
804​
805 const projection = yield* Effect.gen(function* () {
806 const orchestrator = yield* OrchestratorV2;
807 yield* orchestrator.dispatch(commands[0]!);
808 yield* orchestrator.dispatch(commands[1]!);
809 yield* waitForIdle(sourceThreadId);
810 yield* orchestrator.dispatch(commands[2]!);
811 yield* waitForIdle(sourceThreadId);
812 yield* orchestrator.dispatch(commands[3]!);
813 yield* orchestrator.dispatch(commands[4]!);
814 yield* waitForIdle(forkThreadId);
815 yield* orchestrator.dispatch(commands[5]!);
816 yield* orchestrator.dispatch(commands[6]!);
817 return yield* waitForIdle(sourceThreadId);
818 }).pipe(
819 Effect.provide(
820 makeOrchestratorV2ReplayLayerWithRegistry(
821 {
822 name: "cross-provider-merge",
823 runtimePolicyOverride: {
824 cwd,
825 approvalPolicy: "never",
826 sandboxPolicy: {
827 type: "readOnly",
828 access: { type: "fullAccess" },
829 networkAccess: false,
830 },
831 },
832 },
833 registryLayer,
834 ),
835 ),
836 );
837 const turns = yield* Ref.get(capturedTurns);
838 const mergedTurn = turns.findLast(
839 (turn) => turn.threadId === sourceThreadId && turn.driver === "codex",
840 );
841 const mergeTransfer = projection.contextTransfers.find(
842 (transfer) => transfer.type === "merge_back",
843 );
844​
845 assert.isDefined(mergedTurn);
846 assert.include(mergedTurn.text, "Context handoff (full_thread_summary):");
847 assert.include(mergedTurn.text, firstSourcePrompt);
848 assert.include(mergedTurn.text, "I will remember amber.");
849 assert.include(mergedTurn.text, secondSourcePrompt);
850 assert.include(mergedTurn.text, "I will remember violet.");
851 assert.include(mergedTurn.text, "Context handoff (merge_back / fork_delta_summary):");
852 assert.include(mergedTurn.text, forkPrompt);
853 assert.include(mergedTurn.text, "I will remember cobalt.");
854 assert.include(mergedTurn.text, mergePrompt);
855 assert.isDefined(mergeTransfer);
856 assert.equal(mergeTransfer.status, "consumed");
857 assert.equal(mergeTransfer.targetProviderInstanceId, "codex");
858 assert.equal(mergeTransfer.resolution?.strategy, "fork_delta_context");
859 }),
860 ),
861 );
862​
863 it.live("routes two custom instances of the same driver independently", () =>
864 Effect.scoped(
865 Effect.gen(function* () {
866 const personalThreadId = ThreadId.make("thread:custom-codex-personal");
867 const workThreadId = ThreadId.make("thread:custom-codex-work");
868 const personalSelection = {
869 instanceId: ProviderInstanceId.make("codex_personal"),
870 model: "gpt-5.4",
871 } satisfies ModelSelection;
872 const workSelection = {
873 instanceId: ProviderInstanceId.make("codex_work"),
874 model: "gpt-5.4",
875 } satisfies ModelSelection;
876 const cwd = yield* checkpointWorkspace("custom-codex-instances");
877 const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
878 const registryLayer = makeProviderAdapterRegistryLayer([
879 makeTestAdapter({
880 instanceId: personalSelection.instanceId,
881 driver: CODEX_DRIVER,
882 capabilities: CodexProviderCapabilitiesV2,
883 modelSelection: personalSelection,
884 responseByRunOrdinal: { 1: "personal response" },
885 capturedTurns,
886 }),
887 makeTestAdapter({
888 instanceId: workSelection.instanceId,
889 driver: CODEX_DRIVER,
890 capabilities: CodexProviderCapabilitiesV2,
891 modelSelection: workSelection,
892 responseByRunOrdinal: { 1: "work response" },
893 capturedTurns,
894 }),
895 ]);
896​
897 const [personal, work] = yield* Effect.gen(function* () {
898 const orchestrator = yield* OrchestratorV2;
899 for (const [targetThreadId, selection, suffix] of [
900 [personalThreadId, personalSelection, "personal"],
901 [workThreadId, workSelection, "work"],
902 ] as const) {
903 yield* orchestrator.dispatch({
904 type: "thread.create",
905 createdBy: "user",
906 creationSource: "web",
907 commandId: CommandId.make(`command:custom-codex:${suffix}:create`),
908 threadId: targetThreadId,
909 projectId,
910 title: `Custom Codex ${suffix}`,
911 modelSelection: selection,
912 runtimeMode: "full-access",
913 interactionMode: "default",
914 branch: null,
915 worktreePath: null,
916 });
917 yield* orchestrator.dispatch({
918 type: "message.dispatch",
919 createdBy: "user",
920 creationSource: "web",
921 commandId: CommandId.make(`command:custom-codex:${suffix}:message`),
922 threadId: targetThreadId,
923 messageId: MessageId.make(`message:custom-codex:${suffix}`),
924 text: `${suffix} prompt`,
925 attachments: [],
926 modelSelection: selection,
927 dispatchMode: { type: "start_immediately" },
928 });
929 yield* waitForIdle(targetThreadId);
930 }
931 return yield* Effect.all([
932 orchestrator.getThreadProjection(personalThreadId),
933 orchestrator.getThreadProjection(workThreadId),
934 ]);
935 }).pipe(
936 Effect.provide(
937 makeOrchestratorV2ReplayLayerWithRegistry(
938 {
939 name: "custom-codex-instances",
940 runtimePolicyOverride: {
941 cwd,
942 approvalPolicy: "never",
943 sandboxPolicy: {
944 type: "readOnly",
945 access: { type: "fullAccess" },
946 networkAccess: false,
947 },
948 },
949 },
950 registryLayer,
951 ),
952 ),
953 );
954​
955 assert.equal(personal.runs[0]?.providerInstanceId, personalSelection.instanceId);
956 assert.equal(
957 personal.providerSessions[0]?.providerInstanceId,
958 personalSelection.instanceId,
959 );
960 assert.equal(work.runs[0]?.providerInstanceId, workSelection.instanceId);
961 assert.equal(work.providerSessions[0]?.providerInstanceId, workSelection.instanceId);
962 assert.notEqual(personal.providerSessions[0]?.id, work.providerSessions[0]?.id);
963 assert.deepEqual(
964 (yield* Ref.get(capturedTurns)).map((turn) => [turn.threadId, turn.text]),
965 [
966 [personalThreadId, "personal prompt"],
967 [workThreadId, "work prompt"],
968 ],
969 );
970 }),
971 ),
972 );
973});