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

SelectionRestart.integration.test.ts

999 lines38.7 KB

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