Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 EventId,
5 MessageId,
6 type ModelSelection,
7 type OrchestrationV2ProviderCapabilities,
8 type OrchestrationV2ProviderSession,
9 type OrchestrationV2ProviderThread,
10 ProjectId,
11 ProviderDriverKind,
12 ProviderInstanceId,
13 ProviderSessionId,
14 ProviderThreadId,
15 ProviderTurnId,
16 type RunId,
17 ThreadId,
18} from "@t3tools/contracts";
19import * as DateTime from "effect/DateTime";
20import * as Effect from "effect/Effect";
21import * as Fiber from "effect/Fiber";
22import * as Layer from "effect/Layer";
23import * as Queue from "effect/Queue";
24import * as Ref from "effect/Ref";
25import * as Stream from "effect/Stream";
26
27import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
28import * as EffectWorker from "./EffectWorker.ts";
29import * as EventSink from "./EventSink.ts";
30import * as Orchestrator from "./Orchestrator.ts";
31import {
32 ProviderAdapterOpenSessionError,
33 type ProviderAdapterV2Event,
34 type ProviderAdapterV2Shape,
35 type ProviderAdapterV2TurnInput,
36} from "./ProviderAdapter.ts";
37import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
38import { makeOrchestratorV2ReplayLayerWithRegistry } from "./testkit/ProviderReplayHarness.ts";
39import { checkpointWorkspace } from "./testkit/ReplayFixtureWorkspace.ts";
40
41const driver = ProviderDriverKind.make("codex");
42const providerInstanceId = ProviderInstanceId.make("codex-restart-test");
43const initialSelection = {
44 instanceId: providerInstanceId,
45 model: "restart-model-a",
46} satisfies ModelSelection;
47const replacementSelection = {
48 instanceId: providerInstanceId,
49 model: "restart-model-b",
50} satisfies ModelSelection;
51const seedSelection = {
52 instanceId: providerInstanceId,
53 model: "seed-model",
54} satisfies ModelSelection;
55const handoffDriver = ProviderDriverKind.make("claudeAgent");
56const handoffProviderInstanceId = ProviderInstanceId.make("claude-handoff-test");
57const handoffSelection = {
58 instanceId: handoffProviderInstanceId,
59 model: "handoff-model",
60} satisfies ModelSelection;
61const pooledCapabilities: OrchestrationV2ProviderCapabilities = CodexProviderCapabilitiesV2;
62const exclusiveCapabilities: OrchestrationV2ProviderCapabilities = {
63 ...CodexProviderCapabilitiesV2,
64 sessions: {
65 ...CodexProviderCapabilitiesV2.sessions,
66 supportsMultipleProviderThreadsPerSession: false,
67 supportsModelSwitchInSession: false,
68 },
69};
70
71interface ActiveTurn {
72 readonly input: ProviderAdapterV2TurnInput;
73 readonly providerTurnId: ProviderTurnId;
74}
75
76interface RestartAdapterState {
77 readonly activeTurn: ActiveTurn | null;
78 readonly opened: ReadonlyArray<{
79 readonly model: string | null;
80 readonly cwd: string | null;
81 }>;
82 readonly started: ReadonlyArray<{
83 readonly model: string;
84 readonly cwd: string | null;
85 readonly attemptId: string;
86 }>;
87 readonly closedSessionCount: number;
88 readonly failedReplacementOpen: boolean;
89}
90
91function makeRestartAdapter(
92 state: Ref.Ref<RestartAdapterState>,
93 sessionCapabilities: OrchestrationV2ProviderCapabilities = pooledCapabilities,
94 providerInstanceId = initialSelection.instanceId,
95): ProviderAdapterV2Shape {
96 return {
97 instanceId: providerInstanceId,
98 driver,
99 getCapabilities: () => Effect.succeed(sessionCapabilities),
100 planSelectionTransition: ({ current, target }) =>
101 Effect.succeed(
102 current.model === target.model
103 ? ({ type: "apply_on_next_turn" } as const)
104 : ({ type: "restart_session" } as const),
105 ),
106 openSession: (sessionInput) =>
107 Effect.gen(function* () {
108 const failThisOpen = yield* Ref.modify(state, (current) => {
109 const shouldFail =
110 sessionInput.modelSelection.model === replacementSelection.model &&
111 !current.failedReplacementOpen;
112 return [
113 shouldFail,
114 {
115 ...current,
116 failedReplacementOpen: current.failedReplacementOpen || shouldFail,
117 opened: [
118 ...current.opened,
119 {
120 model: sessionInput.modelSelection.model,
121 cwd: sessionInput.runtimePolicy.cwd,
122 },
123 ],
124 },
125 ] as const;
126 });
127 if (failThisOpen) {
128 return yield* new ProviderAdapterOpenSessionError({
129 driver,
130 providerSessionId: sessionInput.providerSessionId,
131 cause: "simulated replacement open failure",
132 });
133 }
134
135 const events = yield* Queue.unbounded<ProviderAdapterV2Event>();
136 const now = yield* DateTime.now;
137 const providerSession: OrchestrationV2ProviderSession = {
138 id: sessionInput.providerSessionId,
139 driver,
140 providerInstanceId,
141 status: "ready",
142 cwd: sessionInput.runtimePolicy.cwd ?? "/fallback",
143 model: sessionInput.modelSelection.model,
144 capabilities: sessionCapabilities,
145 createdAt: now,
146 updatedAt: now,
147 lastError: null,
148 };
149 yield* Effect.addFinalizer(() =>
150 Ref.update(state, (current) => ({
151 ...current,
152 closedSessionCount: current.closedSessionCount + 1,
153 })),
154 );
155
156 const publishTerminal = (active: ActiveTurn, status: "completed" | "interrupted") =>
157 Effect.gen(function* () {
158 const occurredAt = yield* DateTime.now;
159 yield* Queue.offer(events, {
160 type: "provider_turn.updated",
161 driver,
162 providerTurn: {
163 id: active.providerTurnId,
164 providerThreadId: active.input.providerThread.id,
165 nodeId: active.input.rootNodeId,
166 runAttemptId: active.input.attemptId,
167 nativeTurnRef: {
168 driver,
169 nativeId: `native:${active.providerTurnId}`,
170 strength: "strong",
171 },
172 ordinal: active.input.providerTurnOrdinal,
173 status,
174 startedAt: occurredAt,
175 completedAt: occurredAt,
176 },
177 });
178 yield* Queue.offer(events, {
179 type: "turn.terminal",
180 driver,
181 providerThreadId: active.input.providerThread.id,
182 providerTurnId: active.providerTurnId,
183 runOrdinal: active.input.runOrdinal,
184 status,
185 failure: null,
186 threadDisposition: "reusable",
187 });
188 });
189
190 return {
191 instanceId: providerInstanceId,
192 driver,
193 providerSessionId: sessionInput.providerSessionId,
194 providerSession,
195 events: Stream.fromQueue(events),
196 ensureThread: (threadInput) =>
197 Effect.gen(function* () {
198 const createdAt = yield* DateTime.now;
199 return {
200 id: ProviderThreadId.make(`provider-thread:${threadInput.threadId}`),
201 driver,
202 providerInstanceId,
203 providerSessionId: sessionInput.providerSessionId,
204 appThreadId: threadInput.threadId,
205 ownerNodeId: null,
206 nativeThreadRef: {
207 driver,
208 nativeId: `native-thread:${threadInput.threadId}`,
209 strength: "strong",
210 },
211 nativeConversationHeadRef: null,
212 status: "idle",
213 firstRunOrdinal: null,
214 lastRunOrdinal: null,
215 handoffIds: [],
216 forkedFrom: null,
217 createdAt,
218 updatedAt: createdAt,
219 } satisfies OrchestrationV2ProviderThread;
220 }),
221 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
222 startTurn: (input) =>
223 Effect.gen(function* () {
224 yield* Ref.update(state, (current) => ({
225 ...current,
226 started: [
227 ...current.started,
228 {
229 model: input.modelSelection.model,
230 cwd: input.runtimePolicy.cwd,
231 attemptId: input.attemptId,
232 },
233 ],
234 }));
235 const active = {
236 input,
237 providerTurnId: ProviderTurnId.make(`provider-turn:${input.attemptId}`),
238 } satisfies ActiveTurn;
239 if (input.modelSelection.model === initialSelection.model) {
240 const occurredAt = yield* DateTime.now;
241 yield* Ref.update(state, (current) => ({ ...current, activeTurn: active }));
242 yield* Queue.offer(events, {
243 type: "provider_turn.updated",
244 driver,
245 providerTurn: {
246 id: active.providerTurnId,
247 providerThreadId: input.providerThread.id,
248 nodeId: input.rootNodeId,
249 runAttemptId: input.attemptId,
250 nativeTurnRef: {
251 driver,
252 nativeId: `native:${active.providerTurnId}`,
253 strength: "strong",
254 },
255 ordinal: input.providerTurnOrdinal,
256 status: "running",
257 startedAt: occurredAt,
258 completedAt: null,
259 },
260 });
261 return;
262 }
263 yield* publishTerminal(active, "completed");
264 }),
265 steerTurn: () => Effect.void,
266 interruptTurn: () =>
267 Effect.gen(function* () {
268 const active = (yield* Ref.get(state)).activeTurn;
269 if (active !== null) {
270 const updatedAt = yield* DateTime.now;
271 yield* Queue.offer(events, {
272 type: "provider_thread.updated",
273 driver,
274 providerThread: {
275 ...active.input.providerThread,
276 status: "idle",
277 updatedAt,
278 },
279 });
280 yield* publishTerminal(active, "interrupted");
281 yield* Ref.update(state, (current) => ({ ...current, activeTurn: null }));
282 }
283 }),
284 respondToRuntimeRequest: () => Effect.void,
285 readThreadSnapshot: () => Effect.die("unused readThreadSnapshot"),
286 rollbackThread: () => Effect.die("unused rollbackThread"),
287 forkThread: () => Effect.die("unused forkThread"),
288 };
289 }),
290 };
291}
292
293function makeCompletingHandoffAdapter(startCount: Ref.Ref<number>): ProviderAdapterV2Shape {
294 return {
295 instanceId: handoffProviderInstanceId,
296 driver: handoffDriver,
297 getCapabilities: () => Effect.succeed(exclusiveCapabilities),
298 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
299 openSession: (sessionInput) =>
300 Effect.gen(function* () {
301 const events = yield* Queue.unbounded<ProviderAdapterV2Event>();
302 const now = yield* DateTime.now;
303 return {
304 instanceId: handoffProviderInstanceId,
305 driver: handoffDriver,
306 providerSessionId: sessionInput.providerSessionId,
307 providerSession: {
308 id: sessionInput.providerSessionId,
309 driver: handoffDriver,
310 providerInstanceId: handoffProviderInstanceId,
311 status: "ready",
312 cwd: sessionInput.runtimePolicy.cwd ?? "/fallback",
313 model: sessionInput.modelSelection.model,
314 capabilities: exclusiveCapabilities,
315 createdAt: now,
316 updatedAt: now,
317 lastError: null,
318 },
319 events: Stream.fromQueue(events),
320 ensureThread: (threadInput) =>
321 Effect.gen(function* () {
322 const createdAt = yield* DateTime.now;
323 return {
324 id: ProviderThreadId.make(`provider-thread:handoff:${threadInput.threadId}`),
325 driver: handoffDriver,
326 providerInstanceId: handoffProviderInstanceId,
327 providerSessionId: sessionInput.providerSessionId,
328 appThreadId: threadInput.threadId,
329 ownerNodeId: null,
330 nativeThreadRef: {
331 driver: handoffDriver,
332 nativeId: `native-thread:handoff:${threadInput.threadId}`,
333 strength: "strong",
334 },
335 nativeConversationHeadRef: null,
336 status: "idle",
337 firstRunOrdinal: null,
338 lastRunOrdinal: null,
339 handoffIds: [],
340 forkedFrom: null,
341 createdAt,
342 updatedAt: createdAt,
343 } satisfies OrchestrationV2ProviderThread;
344 }),
345 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
346 startTurn: (input) =>
347 Effect.gen(function* () {
348 yield* Ref.update(startCount, (count) => count + 1);
349 const occurredAt = yield* DateTime.now;
350 const providerTurnId = ProviderTurnId.make(
351 `provider-turn:handoff:${input.attemptId}`,
352 );
353 yield* Queue.offer(events, {
354 type: "provider_turn.updated",
355 driver: handoffDriver,
356 providerTurn: {
357 id: providerTurnId,
358 providerThreadId: input.providerThread.id,
359 nodeId: input.rootNodeId,
360 runAttemptId: input.attemptId,
361 nativeTurnRef: {
362 driver: handoffDriver,
363 nativeId: `native:${providerTurnId}`,
364 strength: "strong",
365 },
366 ordinal: input.providerTurnOrdinal,
367 status: "completed",
368 startedAt: occurredAt,
369 completedAt: occurredAt,
370 },
371 });
372 yield* Queue.offer(events, {
373 type: "turn.terminal",
374 driver: handoffDriver,
375 providerThreadId: input.providerThread.id,
376 providerTurnId,
377 runOrdinal: input.runOrdinal,
378 status: "completed",
379 failure: null,
380 threadDisposition: "reusable",
381 });
382 }),
383 steerTurn: () => Effect.void,
384 interruptTurn: () => Effect.void,
385 respondToRuntimeRequest: () => Effect.void,
386 readThreadSnapshot: () => Effect.die("unused readThreadSnapshot"),
387 rollbackThread: () => Effect.die("unused rollbackThread"),
388 forkThread: () => Effect.die("unused forkThread"),
389 };
390 }),
391 };
392}
393
394it.live("restarts selection as a new attempt and retries after old-session cleanup", () =>
395 Effect.scoped(
396 Effect.gen(function* () {
397 const cwd = yield* checkpointWorkspace("selection-restart-lifecycle");
398 const threadId = ThreadId.make("thread:selection-restart-lifecycle");
399 const state = yield* Ref.make<RestartAdapterState>({
400 activeTurn: null,
401 opened: [],
402 started: [],
403 closedSessionCount: 0,
404 failedReplacementOpen: false,
405 });
406 const registry = ProviderAdapterRegistry.makeSingleLayer(makeRestartAdapter(state));
407
408 const result = yield* Effect.gen(function* () {
409 const orchestrator = yield* Orchestrator.OrchestratorV2;
410 yield* orchestrator.dispatch({
411 type: "thread.create",
412 createdBy: "user",
413 creationSource: "web",
414 commandId: CommandId.make("command:selection-restart:create"),
415 threadId,
416 projectId: ProjectId.make("project:selection-restart"),
417 title: "Selection restart",
418 modelSelection: initialSelection,
419 runtimeMode: "full-access",
420 interactionMode: "default",
421 branch: null,
422 worktreePath: cwd,
423 });
424 yield* orchestrator.dispatch({
425 type: "message.dispatch",
426 createdBy: "user",
427 creationSource: "web",
428 commandId: CommandId.make("command:selection-restart:first"),
429 threadId,
430 messageId: MessageId.make("message:selection-restart:first"),
431 text: "first",
432 attachments: [],
433 modelSelection: initialSelection,
434 dispatchMode: { type: "start_immediately" },
435 });
436 for (let index = 0; index < 1_000; index += 1) {
437 const current = yield* orchestrator.getThreadProjection(threadId);
438 if (current.providerTurns.some((turn) => turn.status === "running")) break;
439 yield* Effect.sleep("5 millis");
440 }
441 const activeProjection = yield* orchestrator.getThreadProjection(threadId);
442 assert.isTrue(activeProjection.providerTurns.some((turn) => turn.status === "running"));
443 const activeRunId = activeProjection.runs[0]?.id;
444 if (activeRunId === undefined) {
445 return yield* Effect.die("active restart test run is missing");
446 }
447
448 yield* orchestrator.dispatch({
449 type: "message.dispatch",
450 createdBy: "user",
451 creationSource: "web",
452 commandId: CommandId.make("command:selection-restart:second"),
453 threadId,
454 messageId: MessageId.make("message:selection-restart:second"),
455 text: "second",
456 attachments: [],
457 modelSelection: replacementSelection,
458 dispatchMode: { type: "restart_active", targetRunId: activeRunId },
459 });
460 for (let index = 0; index < 1_000; index += 1) {
461 const current = yield* orchestrator.getThreadProjection(threadId);
462 if (current.attempts.length === 2 && current.attempts[1]?.status === "completed") {
463 const captured = yield* Ref.get(state);
464 return { projection: current, captured };
465 }
466 yield* Effect.sleep("5 millis");
467 }
468 const current = yield* orchestrator.getThreadProjection(threadId);
469 const adapterState = yield* Ref.get(state);
470 yield* Effect.logError("selection restart did not complete", {
471 runs: current.runs.map((run) => [run.status, run.activeAttemptId]),
472 attempts: current.attempts.map((attempt) => [attempt.id, attempt.status]),
473 providerTurns: current.providerTurns.map((turn) => [turn.id, turn.status]),
474 providerThreads: current.providerThreads.map((thread) => [
475 thread.providerSessionId,
476 thread.status,
477 ]),
478 adapterState,
479 });
480 return yield* Effect.die("selection restart did not complete");
481 }).pipe(
482 Effect.provide(
483 makeOrchestratorV2ReplayLayerWithRegistry(
484 { name: "selection-restart-lifecycle" },
485 registry,
486 ),
487 ),
488 );
489 const { projection, captured } = result;
490
491 assert.lengthOf(projection.runs, 1);
492 assert.lengthOf(projection.attempts, 2);
493 assert.deepEqual(
494 projection.attempts.map((attempt) => attempt.status),
495 ["superseded", "completed"],
496 );
497 assert.deepEqual(
498 projection.providerTurns.map((turn) => turn.status),
499 ["interrupted", "completed"],
500 );
501 assert.isFalse(
502 projection.turnItems.some(
503 (item) => item.type === "run_interrupt_request" || item.type === "run_interrupt_result",
504 ),
505 "selection restart supersede must not project hard-Stop interrupt items",
506 );
507 assert.equal(projection.runs[0]?.modelSelection.model, replacementSelection.model);
508 assert.isTrue(captured.failedReplacementOpen);
509 // The old pooled process remains available to its other threads; this
510 // thread moved to a freshly allocated replacement session.
511 assert.equal(captured.closedSessionCount, 0);
512 assert.deepEqual(
513 captured.opened.map((open) => [open.model, open.cwd]),
514 [
515 [initialSelection.model, cwd],
516 [replacementSelection.model, cwd],
517 [replacementSelection.model, cwd],
518 ],
519 );
520 assert.deepEqual(
521 captured.started.map((turn) => [turn.model, turn.cwd]),
522 [
523 [initialSelection.model, cwd],
524 [replacementSelection.model, cwd],
525 ],
526 );
527 assert.notEqual(
528 projection.providerSessions[0]?.id,
529 projection.providerThreads[0]?.providerSessionId,
530 );
531 assert.equal(
532 projection.providerThreads[0]?.providerSessionId,
533 projection.providerSessions.find((session) => session.model === replacementSelection.model)
534 ?.id,
535 );
536 }),
537 ),
538);
539
540for (const deadStatus of ["stopped", "error"] as const) {
541 it.live(
542 `restarts the live session on a model change when a newer ${deadStatus} session record exists`,
543 () =>
544 Effect.scoped(
545 Effect.gen(function* () {
546 const name = `selection-restart-dead-${deadStatus}`;
547 const cwd = yield* checkpointWorkspace(name);
548 const threadId = ThreadId.make(`thread:${name}`);
549 const state = yield* Ref.make<RestartAdapterState>({
550 activeTurn: null,
551 opened: [],
552 started: [],
553 closedSessionCount: 0,
554 // The dead record is seeded directly, so the adapter's one-shot
555 // simulated replacement-open failure is skipped.
556 failedReplacementOpen: true,
557 });
558 const registry = ProviderAdapterRegistry.makeSingleLayer(
559 makeRestartAdapter(state, exclusiveCapabilities),
560 );
561
562 const result = yield* Effect.gen(function* () {
563 const orchestrator = yield* Orchestrator.OrchestratorV2;
564 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
565 const eventSink = yield* EventSink.EventSinkV2;
566 const dispatch = (step: string, modelSelection: ModelSelection) =>
567 Effect.gen(function* () {
568 const terminal = yield* orchestrator.streamDomainEvents.pipe(
569 Stream.filter(
570 (event) => event.type === "run.updated" && event.payload.status === "completed",
571 ),
572 Stream.take(1),
573 Stream.runDrain,
574 Effect.forkScoped,
575 );
576 yield* orchestrator.dispatch({
577 type: "message.dispatch",
578 createdBy: "user",
579 creationSource: "web",
580 commandId: CommandId.make(`${name}:${step}`),
581 threadId,
582 messageId: MessageId.make(`${name}:${step}`),
583 text: step,
584 attachments: [],
585 modelSelection,
586 dispatchMode: { type: "start_immediately" },
587 });
588 yield* worker.drain();
589 yield* Fiber.join(terminal);
590 yield* worker.drain();
591 return yield* orchestrator.getThreadProjection(threadId);
592 });
593 yield* orchestrator.dispatch({
594 type: "thread.create",
595 createdBy: "user",
596 creationSource: "web",
597 commandId: CommandId.make(`${name}:create`),
598 threadId,
599 projectId: ProjectId.make(`project:${name}`),
600 title: name,
601 modelSelection: seedSelection,
602 runtimeMode: "full-access",
603 interactionMode: "default",
604 branch: null,
605 worktreePath: cwd,
606 });
607 const first = yield* dispatch("first", seedSelection);
608 const liveSession = first.providerSessions.find(
609 (session) => session.status !== "stopped" && session.status !== "error",
610 );
611 assert.isDefined(liveSession);
612
613 // Dead session records stay bound in the projection until
614 // detachment. A stale stopped/error record written after the
615 // live session attached must not hide it.
616 const deadAt = yield* DateTime.now;
617 const deadSession: OrchestrationV2ProviderSession = {
618 id: ProviderSessionId.make(`session:${name}:dead`),
619 driver,
620 providerInstanceId,
621 status: "ready",
622 cwd,
623 model: seedSelection.model,
624 capabilities: exclusiveCapabilities,
625 createdAt: deadAt,
626 updatedAt: deadAt,
627 lastError: null,
628 };
629 yield* eventSink.write({
630 events: [
631 {
632 id: EventId.make(`event:${name}:dead-attached`),
633 type: "provider-session.attached",
634 threadId,
635 driver,
636 providerInstanceId,
637 occurredAt: deadAt,
638 payload: deadSession,
639 },
640 {
641 id: EventId.make(`event:${name}:dead-updated`),
642 type: "provider-session.updated",
643 threadId,
644 driver,
645 providerInstanceId,
646 occurredAt: deadAt,
647 payload: {
648 ...deadSession,
649 status: deadStatus,
650 updatedAt: deadAt,
651 lastError: deadStatus === "error" ? "Simulated session failure." : null,
652 },
653 },
654 ],
655 });
656
657 const switchCommandId = CommandId.make(`${name}:switch`);
658 yield* orchestrator.dispatch({
659 type: "thread.model-selection.set",
660 commandId: switchCommandId,
661 threadId,
662 modelSelection: replacementSelection,
663 });
664 yield* worker.drain();
665 const storedSwitchEvents = yield* eventSink
666 .readByCommandId({ commandId: switchCommandId })
667 .pipe(Stream.runCollect);
668 const detachedSessionIds = [...storedSwitchEvents].flatMap((stored) =>
669 stored.event.type === "provider-session.detached"
670 ? [stored.event.payload.providerSessionId]
671 : [],
672 );
673
674 const second = yield* dispatch("second", replacementSelection);
675 return {
676 projection: second,
677 captured: yield* Ref.get(state),
678 liveSessionId: liveSession.id,
679 detachedSessionIds,
680 };
681 }).pipe(Effect.provide(makeOrchestratorV2ReplayLayerWithRegistry({ name }, registry)));
682
683 const { projection, captured } = result;
684 assert.lengthOf(projection.runs, 2);
685 assert.equal(projection.runs[1]?.modelSelection.model, replacementSelection.model);
686 // The exact released session is the older live one, never the newer
687 // dead record.
688 assert.deepEqual(result.detachedSessionIds, [result.liveSessionId]);
689 assert.equal(captured.closedSessionCount, 1);
690 assert.deepEqual(
691 captured.opened.map((open) => open.model),
692 [seedSelection.model, replacementSelection.model],
693 );
694 assert.deepEqual(
695 captured.started.map((turn) => turn.model),
696 [seedSelection.model, replacementSelection.model],
697 );
698 const servingSession = projection.providerSessions.find(
699 (session) =>
700 session.id ===
701 projection.providerThreads.find(
702 (providerThread) => providerThread.id === projection.thread.activeProviderThreadId,
703 )?.providerSessionId,
704 );
705 assert.equal(servingSession?.model, replacementSelection.model);
706 }),
707 ),
708 );
709}
710
711it.live("detaches the old provider session after an active provider handoff", () =>
712 Effect.scoped(
713 Effect.gen(function* () {
714 const cwd = yield* checkpointWorkspace("selection-provider-handoff-lifecycle");
715 const threadId = ThreadId.make("thread:selection-provider-handoff-lifecycle");
716 const state = yield* Ref.make<RestartAdapterState>({
717 activeTurn: null,
718 opened: [],
719 started: [],
720 closedSessionCount: 0,
721 failedReplacementOpen: false,
722 });
723 const targetStartCount = yield* Ref.make(0);
724 const registry = ProviderAdapterRegistry.makeLayer([
725 makeRestartAdapter(state, exclusiveCapabilities),
726 makeCompletingHandoffAdapter(targetStartCount),
727 ]);
728
729 const result = yield* Effect.gen(function* () {
730 const orchestrator = yield* Orchestrator.OrchestratorV2;
731 yield* orchestrator.dispatch({
732 type: "thread.create",
733 createdBy: "user",
734 creationSource: "web",
735 commandId: CommandId.make("command:selection-handoff:create"),
736 threadId,
737 projectId: ProjectId.make("project:selection-handoff"),
738 title: "Selection provider handoff",
739 modelSelection: initialSelection,
740 runtimeMode: "full-access",
741 interactionMode: "default",
742 branch: null,
743 worktreePath: cwd,
744 });
745 yield* orchestrator.dispatch({
746 type: "message.dispatch",
747 createdBy: "user",
748 creationSource: "web",
749 commandId: CommandId.make("command:selection-handoff:first"),
750 threadId,
751 messageId: MessageId.make("message:selection-handoff:first"),
752 text: "first",
753 attachments: [],
754 modelSelection: initialSelection,
755 dispatchMode: { type: "start_immediately" },
756 });
757 let activeRunId: RunId | null = null;
758 for (let index = 0; index < 1_000; index += 1) {
759 const current = yield* orchestrator.getThreadProjection(threadId);
760 if (current.providerTurns.some((turn) => turn.status === "running")) {
761 activeRunId = current.runs[0]?.id ?? null;
762 break;
763 }
764 yield* Effect.sleep("5 millis");
765 }
766 if (activeRunId === null) {
767 return yield* Effect.die("active provider-handoff run is missing");
768 }
769
770 yield* orchestrator.dispatch({
771 type: "message.dispatch",
772 createdBy: "user",
773 creationSource: "web",
774 commandId: CommandId.make("command:selection-handoff:second"),
775 threadId,
776 messageId: MessageId.make("message:selection-handoff:second"),
777 text: "second",
778 attachments: [],
779 modelSelection: handoffSelection,
780 dispatchMode: { type: "restart_active", targetRunId: activeRunId },
781 });
782 for (let index = 0; index < 1_000; index += 1) {
783 const current = yield* orchestrator.getThreadProjection(threadId);
784 if (current.attempts.length === 2 && current.attempts[1]?.status === "completed") {
785 const captured = yield* Ref.get(state);
786 return { projection: current, captured };
787 }
788 yield* Effect.sleep("5 millis");
789 }
790 const current = yield* orchestrator.getThreadProjection(threadId);
791 const adapterState = yield* Ref.get(state);
792 const capturedTargetStartCount = yield* Ref.get(targetStartCount);
793 yield* Effect.logError("active provider handoff did not complete", {
794 runs: current.runs.map((run) => [run.status, run.activeAttemptId]),
795 attempts: current.attempts.map((attempt) => [attempt.id, attempt.status]),
796 providerTurns: current.providerTurns.map((turn) => [turn.id, turn.status]),
797 providerThreads: current.providerThreads.map((thread) => [
798 thread.providerInstanceId,
799 thread.providerSessionId,
800 thread.status,
801 ]),
802 targetStartCount: capturedTargetStartCount,
803 adapterState,
804 });
805 return yield* Effect.die("active provider handoff did not complete");
806 }).pipe(
807 Effect.provide(
808 makeOrchestratorV2ReplayLayerWithRegistry(
809 { name: "selection-provider-handoff-lifecycle" },
810 registry,
811 ),
812 ),
813 );
814
815 assert.lengthOf(result.projection.runs, 1);
816 assert.lengthOf(result.projection.attempts, 2);
817 assert.equal(result.projection.runs[0]?.providerInstanceId, handoffProviderInstanceId);
818 assert.equal(result.projection.contextHandoffs.length, 1);
819 assert.equal(result.captured.closedSessionCount, 1);
820 assert.equal(yield* Ref.get(targetStartCount), 1);
821 }),
822 ),
823);
824
825for (const mode of ["active", "idle", "selection-command", "pooled", "separate-home"] as const) {
826 it.live(`preserves native history only for compatible account switches (${mode})`, () =>
827 Effect.scoped(
828 Effect.gen(function* () {
829 const name = `shared-home-${mode}`;
830 const cwd = yield* checkpointWorkspace(name);
831 const threadId = ThreadId.make(`thread:${name}`);
832 const targetId = ProviderInstanceId.make("codex-shadow-account");
833 const state = yield* Ref.make<RestartAdapterState>({
834 activeTurn: null,
835 opened: [],
836 started: [],
837 closedSessionCount: 0,
838 failedReplacementOpen: true,
839 });
840 const resumes: Array<{
841 instanceId: ProviderInstanceId;
842 nativeId: string | null | undefined;
843 }> = [];
844 const messages: string[] = [];
845 const capabilities = mode === "pooled" ? pooledCapabilities : exclusiveCapabilities;
846 const adapters = [providerInstanceId, targetId].map((instanceId) => {
847 const base = makeRestartAdapter(state, capabilities, instanceId);
848 return {
849 ...base,
850 openSession: (input) =>
851 base.openSession(input).pipe(
852 Effect.map((session) => ({
853 ...session,
854 resumeThread: (input) =>
855 Effect.gen(function* () {
856 resumes.push({
857 instanceId,
858 nativeId: input.providerThread.nativeThreadRef?.nativeId,
859 });
860 return yield* session.resumeThread(input);
861 }),
862 startTurn: (input) =>
863 Effect.gen(function* () {
864 messages.push(input.message.text);
865 yield* session.startTurn(input);
866 }),
867 })),
868 ),
869 } satisfies ProviderAdapterV2Shape;
870 });
871 const registry = Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistryV2, {
872 get: (instanceId) =>
873 Effect.succeed(adapters.find((adapter) => adapter.instanceId === instanceId)!),
874 list: () => Effect.succeed([providerInstanceId, targetId]),
875 getMetadata: (instanceId) =>
876 Effect.succeed({
877 driver,
878 continuationKey:
879 mode === "separate-home" ? `codex:home:/${instanceId}` : "codex:home:/shared",
880 enabled: true,
881 capabilities,
882 }),
883 });
884 yield* Effect.gen(function* () {
885 const orchestrator = yield* Orchestrator.OrchestratorV2;
886 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
887 const selection = {
888 ...initialSelection,
889 model: mode === "active" ? initialSelection.model : "complete",
890 };
891 yield* orchestrator.dispatch({
892 type: "thread.create",
893 commandId: CommandId.make(`${name}:create`),
894 threadId,
895 projectId: ProjectId.make(`project:${name}`),
896 title: name,
897 modelSelection: selection,
898 runtimeMode: "full-access",
899 interactionMode: "default",
900 branch: null,
901 worktreePath: cwd,
902 createdBy: "user",
903 creationSource: "web",
904 });
905 const dispatch = (step: string, modelSelection: ModelSelection, targetRunId?: RunId) =>
906 Effect.gen(function* () {
907 const terminal = yield* orchestrator.streamDomainEvents.pipe(
908 Stream.filter((event) =>
909 mode === "active" && step === "first"
910 ? event.type === "provider-turn.updated" && event.payload.status === "running"
911 : event.type === "run.updated" && event.payload.status === "completed",
912 ),
913 Stream.take(1),
914 Stream.runDrain,
915 Effect.forkScoped,
916 );
917 yield* orchestrator.dispatch({
918 type: "message.dispatch",
919 commandId: CommandId.make(`${name}:${step}`),
920 threadId,
921 messageId: MessageId.make(`${name}:${step}`),
922 text: step,
923 attachments: [],
924 modelSelection,
925 dispatchMode:
926 targetRunId === undefined
927 ? { type: "start_immediately" }
928 : { type: "restart_active", targetRunId },
929 createdBy: "user",
930 creationSource: "web",
931 });
932 yield* worker.drain();
933 yield* Fiber.join(terminal);
934 yield* worker.drain();
935 return yield* orchestrator.getThreadProjection(threadId);
936 });
937 const first = yield* dispatch("first", selection);
938 const originalThread = first.providerThreads.find(
939 (thread) => thread.id === first.thread.activeProviderThreadId,
940 )!;
941 const targetSelection = { instanceId: targetId, model: "complete" };
942 if (mode === "selection-command") {
943 yield* orchestrator.dispatch({
944 type: "provider.switch",
945 commandId: CommandId.make(`${name}:switch`),
946 threadId,
947 modelSelection: targetSelection,
948 });
949 yield* worker.drain();
950 }
951 const second = yield* dispatch(
952 "second",
953 targetSelection,
954 mode === "active" ? first.runs[0]!.id : undefined,
955 );
956 const targetThread = second.providerThreads.find(
957 (thread) => thread.id === second.thread.activeProviderThreadId,
958 )!;
959 if (mode === "separate-home") {
960 assert.notEqual(targetThread.id, originalThread.id);
961 assert.lengthOf(second.contextHandoffs, 1);
962 assert.lengthOf(second.contextTransfers, 1);
963 assert.isEmpty(resumes);
964 assert.notEqual(messages[1], "second");
965 return;
966 }
967 assert.equal(targetThread.id, originalThread.id);
968 assert.deepEqual(targetThread.nativeThreadRef, originalThread.nativeThreadRef);
969 assert.equal(targetThread.providerInstanceId, targetId);
970 assert.notEqual(targetThread.providerSessionId, originalThread.providerSessionId);
971 assert.isEmpty(second.contextHandoffs);
972 assert.isEmpty(second.contextTransfers);
973 assert.deepEqual(resumes, [
974 { instanceId: targetId, nativeId: originalThread.nativeThreadRef?.nativeId },
975 ]);
976 assert.deepEqual(messages, ["first", "second"]);
977 assert.equal((yield* Ref.get(state)).closedSessionCount, mode === "pooled" ? 0 : 1);
978 if (mode === "pooled") {
979 assert.isFalse(
980 second.providerSessions.some(
981 (session) => session.id === originalThread.providerSessionId,
982 ),
983 );
984 }
985 const third = yield* dispatch("third", { ...selection, model: "complete" });
986 const returnedThread = third.providerThreads.find(
987 (thread) => thread.id === third.thread.activeProviderThreadId,
988 )!;
989 assert.equal(returnedThread.id, originalThread.id);
990 assert.deepEqual(returnedThread.nativeThreadRef, originalThread.nativeThreadRef);
991 assert.equal(returnedThread.providerInstanceId, providerInstanceId);
992 assert.isEmpty(third.contextHandoffs);
993 assert.deepEqual(messages, ["first", "second", "third"]);
994 }).pipe(Effect.provide(makeOrchestratorV2ReplayLayerWithRegistry({ name }, registry)));
995 }),
996 ),
997 );
998}