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

SelectionRestart.integration.test.ts

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