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 * as ProviderReplayHarness 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 layerRegistry = ProviderAdapterRegistry.layerSingle(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 ProviderReplayHarness.layerWithRegistry(
484 { name: "selection-restart-lifecycle" },
485 layerRegistry,
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
540it.live.each(["stopped", "error"] as const)(
541 "restarts the live session on a model change when a newer %s session record exists",
542 (deadStatus) =>
543 Effect.scoped(
544 Effect.gen(function* () {
545 const name = `selection-restart-dead-${deadStatus}`;
546 const cwd = yield* checkpointWorkspace(name);
547 const threadId = ThreadId.make(`thread:${name}`);
548 const state = yield* Ref.make<RestartAdapterState>({
549 activeTurn: null,
550 opened: [],
551 started: [],
552 closedSessionCount: 0,
553 // The dead record is seeded directly, so the adapter's one-shot
554 // simulated replacement-open failure is skipped.
555 failedReplacementOpen: true,
556 });
557 const layerRegistry = ProviderAdapterRegistry.layerSingle(
558 makeRestartAdapter(state, exclusiveCapabilities),
559 );
560
561 const result = yield* Effect.gen(function* () {
562 const orchestrator = yield* Orchestrator.OrchestratorV2;
563 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
564 const eventSink = yield* EventSink.EventSinkV2;
565 const dispatch = (step: string, modelSelection: ModelSelection) =>
566 Effect.gen(function* () {
567 const terminal = yield* orchestrator.streamDomainEvents.pipe(
568 Stream.filter(
569 (event) => event.type === "run.updated" && event.payload.status === "completed",
570 ),
571 Stream.take(1),
572 Stream.runDrain,
573 Effect.forkScoped,
574 );
575 yield* orchestrator.dispatch({
576 type: "message.dispatch",
577 createdBy: "user",
578 creationSource: "web",
579 commandId: CommandId.make(`${name}:${step}`),
580 threadId,
581 messageId: MessageId.make(`${name}:${step}`),
582 text: step,
583 attachments: [],
584 modelSelection,
585 dispatchMode: { type: "start_immediately" },
586 });
587 yield* worker.drain();
588 yield* Fiber.join(terminal);
589 yield* worker.drain();
590 return yield* orchestrator.getThreadProjection(threadId);
591 });
592 yield* orchestrator.dispatch({
593 type: "thread.create",
594 createdBy: "user",
595 creationSource: "web",
596 commandId: CommandId.make(`${name}:create`),
597 threadId,
598 projectId: ProjectId.make(`project:${name}`),
599 title: name,
600 modelSelection: seedSelection,
601 runtimeMode: "full-access",
602 interactionMode: "default",
603 branch: null,
604 worktreePath: cwd,
605 });
606 const first = yield* dispatch("first", seedSelection);
607 const liveSession = first.providerSessions.find(
608 (session) => session.status !== "stopped" && session.status !== "error",
609 );
610 assert.isDefined(liveSession);
611
612 // Dead session records stay bound in the projection until
613 // detachment. A stale stopped/error record written after the
614 // live session attached must not hide it.
615 const deadAt = yield* DateTime.now;
616 const deadSession: OrchestrationV2ProviderSession = {
617 id: ProviderSessionId.make(`session:${name}:dead`),
618 driver,
619 providerInstanceId,
620 status: "ready",
621 cwd,
622 model: seedSelection.model,
623 capabilities: exclusiveCapabilities,
624 createdAt: deadAt,
625 updatedAt: deadAt,
626 lastError: null,
627 };
628 yield* eventSink.write({
629 events: [
630 {
631 id: EventId.make(`event:${name}:dead-attached`),
632 type: "provider-session.attached",
633 threadId,
634 driver,
635 providerInstanceId,
636 occurredAt: deadAt,
637 payload: deadSession,
638 },
639 {
640 id: EventId.make(`event:${name}:dead-updated`),
641 type: "provider-session.updated",
642 threadId,
643 driver,
644 providerInstanceId,
645 occurredAt: deadAt,
646 payload: {
647 ...deadSession,
648 status: deadStatus,
649 updatedAt: deadAt,
650 lastError: deadStatus === "error" ? "Simulated session failure." : null,
651 },
652 },
653 ],
654 });
655
656 const switchCommandId = CommandId.make(`${name}:switch`);
657 yield* orchestrator.dispatch({
658 type: "thread.model-selection.set",
659 commandId: switchCommandId,
660 threadId,
661 modelSelection: replacementSelection,
662 });
663 yield* worker.drain();
664 const storedSwitchEvents = yield* eventSink
665 .readByCommandId({ commandId: switchCommandId })
666 .pipe(Stream.runCollect);
667 const detachedSessionIds = [...storedSwitchEvents].flatMap((stored) =>
668 stored.event.type === "provider-session.detached"
669 ? [stored.event.payload.providerSessionId]
670 : [],
671 );
672
673 const second = yield* dispatch("second", replacementSelection);
674 return {
675 projection: second,
676 captured: yield* Ref.get(state),
677 liveSessionId: liveSession.id,
678 detachedSessionIds,
679 };
680 }).pipe(Effect.provide(ProviderReplayHarness.layerWithRegistry({ name }, layerRegistry)));
681
682 const { projection, captured } = result;
683 assert.lengthOf(projection.runs, 2);
684 assert.equal(projection.runs[1]?.modelSelection.model, replacementSelection.model);
685 // The exact released session is the older live one, never the newer
686 // dead record.
687 assert.deepEqual(result.detachedSessionIds, [result.liveSessionId]);
688 assert.equal(captured.closedSessionCount, 1);
689 assert.deepEqual(
690 captured.opened.map((open) => open.model),
691 [seedSelection.model, replacementSelection.model],
692 );
693 assert.deepEqual(
694 captured.started.map((turn) => turn.model),
695 [seedSelection.model, replacementSelection.model],
696 );
697 const servingSession = projection.providerSessions.find(
698 (session) =>
699 session.id ===
700 projection.providerThreads.find(
701 (providerThread) => providerThread.id === projection.thread.activeProviderThreadId,
702 )?.providerSessionId,
703 );
704 assert.equal(servingSession?.model, replacementSelection.model);
705 }),
706 ),
707);
708
709it.live("detaches the old provider session after an active provider handoff", () =>
710 Effect.scoped(
711 Effect.gen(function* () {
712 const cwd = yield* checkpointWorkspace("selection-provider-handoff-lifecycle");
713 const threadId = ThreadId.make("thread:selection-provider-handoff-lifecycle");
714 const state = yield* Ref.make<RestartAdapterState>({
715 activeTurn: null,
716 opened: [],
717 started: [],
718 closedSessionCount: 0,
719 failedReplacementOpen: false,
720 });
721 const targetStartCount = yield* Ref.make(0);
722 const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
723 makeRestartAdapter(state, exclusiveCapabilities),
724 makeCompletingHandoffAdapter(targetStartCount),
725 ]);
726
727 const result = yield* Effect.gen(function* () {
728 const orchestrator = yield* Orchestrator.OrchestratorV2;
729 yield* orchestrator.dispatch({
730 type: "thread.create",
731 createdBy: "user",
732 creationSource: "web",
733 commandId: CommandId.make("command:selection-handoff:create"),
734 threadId,
735 projectId: ProjectId.make("project:selection-handoff"),
736 title: "Selection provider handoff",
737 modelSelection: initialSelection,
738 runtimeMode: "full-access",
739 interactionMode: "default",
740 branch: null,
741 worktreePath: cwd,
742 });
743 yield* orchestrator.dispatch({
744 type: "message.dispatch",
745 createdBy: "user",
746 creationSource: "web",
747 commandId: CommandId.make("command:selection-handoff:first"),
748 threadId,
749 messageId: MessageId.make("message:selection-handoff:first"),
750 text: "first",
751 attachments: [],
752 modelSelection: initialSelection,
753 dispatchMode: { type: "start_immediately" },
754 });
755 let activeRunId: RunId | null = null;
756 for (let index = 0; index < 1_000; index += 1) {
757 const current = yield* orchestrator.getThreadProjection(threadId);
758 if (current.providerTurns.some((turn) => turn.status === "running")) {
759 activeRunId = current.runs[0]?.id ?? null;
760 break;
761 }
762 yield* Effect.sleep("5 millis");
763 }
764 if (activeRunId === null) {
765 return yield* Effect.die("active provider-handoff run is missing");
766 }
767
768 yield* orchestrator.dispatch({
769 type: "message.dispatch",
770 createdBy: "user",
771 creationSource: "web",
772 commandId: CommandId.make("command:selection-handoff:second"),
773 threadId,
774 messageId: MessageId.make("message:selection-handoff:second"),
775 text: "second",
776 attachments: [],
777 modelSelection: handoffSelection,
778 dispatchMode: { type: "restart_active", targetRunId: activeRunId },
779 });
780 for (let index = 0; index < 1_000; index += 1) {
781 const current = yield* orchestrator.getThreadProjection(threadId);
782 if (current.attempts.length === 2 && current.attempts[1]?.status === "completed") {
783 const captured = yield* Ref.get(state);
784 return { projection: current, captured };
785 }
786 yield* Effect.sleep("5 millis");
787 }
788 const current = yield* orchestrator.getThreadProjection(threadId);
789 const adapterState = yield* Ref.get(state);
790 const capturedTargetStartCount = yield* Ref.get(targetStartCount);
791 yield* Effect.logError("active provider handoff did not complete", {
792 runs: current.runs.map((run) => [run.status, run.activeAttemptId]),
793 attempts: current.attempts.map((attempt) => [attempt.id, attempt.status]),
794 providerTurns: current.providerTurns.map((turn) => [turn.id, turn.status]),
795 providerThreads: current.providerThreads.map((thread) => [
796 thread.providerInstanceId,
797 thread.providerSessionId,
798 thread.status,
799 ]),
800 targetStartCount: capturedTargetStartCount,
801 adapterState,
802 });
803 return yield* Effect.die("active provider handoff did not complete");
804 }).pipe(
805 Effect.provide(
806 ProviderReplayHarness.layerWithRegistry(
807 { name: "selection-provider-handoff-lifecycle" },
808 layerRegistry,
809 ),
810 ),
811 );
812
813 assert.lengthOf(result.projection.runs, 1);
814 assert.lengthOf(result.projection.attempts, 2);
815 assert.equal(result.projection.runs[0]?.providerInstanceId, handoffProviderInstanceId);
816 assert.equal(result.projection.contextHandoffs.length, 1);
817 assert.equal(result.captured.closedSessionCount, 1);
818 assert.equal(yield* Ref.get(targetStartCount), 1);
819 }),
820 ),
821);
822
823it.live.each(["active", "idle", "selection-command", "pooled", "separate-home"] as const)(
824 "preserves native history only for compatible account switches (%s)",
825 (mode) =>
826 Effect.scoped(
827 Effect.gen(function* () {
828 const name = `shared-home-${mode}`;
829 const cwd = yield* checkpointWorkspace(name);
830 const threadId = ThreadId.make(`thread:${name}`);
831 const targetId = ProviderInstanceId.make("codex-shadow-account");
832 const state = yield* Ref.make<RestartAdapterState>({
833 activeTurn: null,
834 opened: [],
835 started: [],
836 closedSessionCount: 0,
837 failedReplacementOpen: true,
838 });
839 const resumes: Array<{
840 instanceId: ProviderInstanceId;
841 nativeId: string | null | undefined;
842 }> = [];
843 const messages: string[] = [];
844 const capabilities = mode === "pooled" ? pooledCapabilities : exclusiveCapabilities;
845 const adapters = [providerInstanceId, targetId].map((instanceId) => {
846 const base = makeRestartAdapter(state, capabilities, instanceId);
847 return {
848 ...base,
849 openSession: (input) =>
850 base.openSession(input).pipe(
851 Effect.map((session) => ({
852 ...session,
853 resumeThread: (input) =>
854 Effect.gen(function* () {
855 resumes.push({
856 instanceId,
857 nativeId: input.providerThread.nativeThreadRef?.nativeId,
858 });
859 return yield* session.resumeThread(input);
860 }),
861 startTurn: (input) =>
862 Effect.gen(function* () {
863 messages.push(input.message.text);
864 yield* session.startTurn(input);
865 }),
866 })),
867 ),
868 } satisfies ProviderAdapterV2Shape;
869 });
870 const layerRegistry = Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistryV2, {
871 get: (instanceId) =>
872 Effect.succeed(adapters.find((adapter) => adapter.instanceId === instanceId)!),
873 list: () => Effect.succeed([providerInstanceId, targetId]),
874 getMetadata: (instanceId) =>
875 Effect.succeed({
876 driver,
877 continuationKey:
878 mode === "separate-home" ? `codex:home:/${instanceId}` : "codex:home:/shared",
879 enabled: true,
880 capabilities,
881 }),
882 });
883 yield* Effect.gen(function* () {
884 const orchestrator = yield* Orchestrator.OrchestratorV2;
885 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
886 const selection = {
887 ...initialSelection,
888 model: mode === "active" ? initialSelection.model : "complete",
889 };
890 yield* orchestrator.dispatch({
891 type: "thread.create",
892 commandId: CommandId.make(`${name}:create`),
893 threadId,
894 projectId: ProjectId.make(`project:${name}`),
895 title: name,
896 modelSelection: selection,
897 runtimeMode: "full-access",
898 interactionMode: "default",
899 branch: null,
900 worktreePath: cwd,
901 createdBy: "user",
902 creationSource: "web",
903 });
904 const dispatch = (step: string, modelSelection: ModelSelection, targetRunId?: RunId) =>
905 Effect.gen(function* () {
906 const terminal = yield* orchestrator.streamDomainEvents.pipe(
907 Stream.filter((event) =>
908 mode === "active" && step === "first"
909 ? event.type === "provider-turn.updated" && event.payload.status === "running"
910 : event.type === "run.updated" && event.payload.status === "completed",
911 ),
912 Stream.take(1),
913 Stream.runDrain,
914 Effect.forkScoped,
915 );
916 yield* orchestrator.dispatch({
917 type: "message.dispatch",
918 commandId: CommandId.make(`${name}:${step}`),
919 threadId,
920 messageId: MessageId.make(`${name}:${step}`),
921 text: step,
922 attachments: [],
923 modelSelection,
924 dispatchMode:
925 targetRunId === undefined
926 ? { type: "start_immediately" }
927 : { type: "restart_active", targetRunId },
928 createdBy: "user",
929 creationSource: "web",
930 });
931 yield* worker.drain();
932 yield* Fiber.join(terminal);
933 yield* worker.drain();
934 return yield* orchestrator.getThreadProjection(threadId);
935 });
936 const first = yield* dispatch("first", selection);
937 const originalThread = first.providerThreads.find(
938 (thread) => thread.id === first.thread.activeProviderThreadId,
939 )!;
940 const targetSelection = { instanceId: targetId, model: "complete" };
941 if (mode === "selection-command") {
942 yield* orchestrator.dispatch({
943 type: "provider.switch",
944 commandId: CommandId.make(`${name}:switch`),
945 threadId,
946 modelSelection: targetSelection,
947 });
948 yield* worker.drain();
949 }
950 const second = yield* dispatch(
951 "second",
952 targetSelection,
953 mode === "active" ? first.runs[0]!.id : undefined,
954 );
955 const targetThread = second.providerThreads.find(
956 (thread) => thread.id === second.thread.activeProviderThreadId,
957 )!;
958 if (mode === "separate-home") {
959 assert.notEqual(targetThread.id, originalThread.id);
960 assert.lengthOf(second.contextHandoffs, 1);
961 assert.lengthOf(second.contextTransfers, 1);
962 assert.isEmpty(resumes);
963 assert.notEqual(messages[1], "second");
964 return;
965 }
966 assert.equal(targetThread.id, originalThread.id);
967 assert.deepEqual(targetThread.nativeThreadRef, originalThread.nativeThreadRef);
968 assert.equal(targetThread.providerInstanceId, targetId);
969 assert.notEqual(targetThread.providerSessionId, originalThread.providerSessionId);
970 assert.isEmpty(second.contextHandoffs);
971 assert.isEmpty(second.contextTransfers);
972 assert.deepEqual(resumes, [
973 { instanceId: targetId, nativeId: originalThread.nativeThreadRef?.nativeId },
974 ]);
975 assert.deepEqual(messages, ["first", "second"]);
976 assert.equal((yield* Ref.get(state)).closedSessionCount, mode === "pooled" ? 0 : 1);
977 if (mode === "pooled") {
978 assert.isFalse(
979 second.providerSessions.some(
980 (session) => session.id === originalThread.providerSessionId,
981 ),
982 );
983 }
984 const third = yield* dispatch("third", { ...selection, model: "complete" });
985 const returnedThread = third.providerThreads.find(
986 (thread) => thread.id === third.thread.activeProviderThreadId,
987 )!;
988 assert.equal(returnedThread.id, originalThread.id);
989 assert.deepEqual(returnedThread.nativeThreadRef, originalThread.nativeThreadRef);
990 assert.equal(returnedThread.providerInstanceId, providerInstanceId);
991 assert.isEmpty(third.contextHandoffs);
992 assert.deepEqual(messages, ["first", "second", "third"]);
993 }).pipe(Effect.provide(ProviderReplayHarness.layerWithRegistry({ name }, layerRegistry)));
994 }),
995 ),
996);