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

SelectionRestart.integration.test.ts

1,115 lines41.5 KB

1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 EventId,
5 MessageId,
6 type ModelSelection,
7 type OrchestrationV2ProviderCapabilities,
8 type OrchestrationV2ThreadProjection,
9 type OrchestrationV2ProviderSession,
10 type OrchestrationV2ProviderThread,
11 ProjectId,
12 ProviderDriverKind,
13 ProviderInstanceId,
14 ProviderSessionId,
15 ProviderThreadId,
16 ProviderTurnId,
17 type RunId,
18 ThreadId,
19 TurnItemId,
20} from "@t3tools/contracts";
21import * as DateTime from "effect/DateTime";
22import * as Effect from "effect/Effect";
23import * as Fiber from "effect/Fiber";
24import * as Layer from "effect/Layer";
25import * as Queue from "effect/Queue";
26import * as Ref from "effect/Ref";
27import * as Stream from "effect/Stream";
28​
29import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
30import * as EffectWorker from "./EffectWorker.ts";
31import * as EventSink from "./EventSink.ts";
32import * as Orchestrator from "./Orchestrator.ts";
33import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
34import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
35import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
36import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
37​
38const driver = ProviderDriverKind.make("codex");
39const providerInstanceId = ProviderInstanceId.make("codex-restart-test");
40const initialSelection = {
41 instanceId: providerInstanceId,
42 model: "restart-model-a",
43} satisfies ModelSelection;
44const replacementSelection = {
45 instanceId: providerInstanceId,
46 model: "restart-model-b",
47} satisfies ModelSelection;
48const seedSelection = {
49 instanceId: providerInstanceId,
50 model: "seed-model",
51} satisfies ModelSelection;
52const modelSwitches = (projection: OrchestrationV2ThreadProjection) =>
53 projection.turnItems.flatMap((item) =>
54 item.type === "user_message" && item.modelSwitch !== undefined ? [item.modelSwitch] : [],
55 );
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​
288it.live("retries a failed selection restart session open before completing", () =>
289 Effect.gen(function* () {
290 const cwd = yield* checkpointWorkspace("selection-restart-lifecycle");
291 const threadId = ThreadId.make("thread:selection-restart-lifecycle");
292 const state = yield* Ref.make<RestartAdapterState>({
293 activeTurn: null,
294 opened: [],
295 started: [],
296 closedSessionCount: 0,
297 failedReplacementOpen: false,
298 });
299 const layerRegistry = ProviderAdapterRegistry.layerSingle(makeRestartAdapter(state));
300​
301 const result = yield* Effect.gen(function* () {
302 const orchestrator = yield* Orchestrator.OrchestratorV2;
303 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
304 const eventSink = yield* EventSink.EventSinkV2;
305​
306 yield* orchestrator.dispatch({
307 type: "thread.create",
308 createdBy: "user",
309 creationSource: "web",
310 commandId: CommandId.make("command:selection-restart:create"),
311 threadId,
312 projectId: ProjectId.make("project:selection-restart"),
313 title: "Selection restart",
314 modelSelection: initialSelection,
315 runtimeMode: "full-access",
316 interactionMode: "default",
317 branch: null,
318 worktreePath: cwd,
319 });
320 const running = yield* eventSink
321 .stream({
322 threadId,
323 afterSequence: yield* eventSink.latestSequence({ threadId }),
324 })
325 .pipe(
326 Stream.map((stored) => stored.event),
327 Stream.filter(
328 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
329 ),
330 Stream.take(1),
331 Stream.runDrain,
332 Effect.forkScoped,
333 );
334 yield* orchestrator.dispatch({
335 type: "message.dispatch",
336 createdBy: "user",
337 creationSource: "web",
338 commandId: CommandId.make("command:selection-restart:first"),
339 threadId,
340 messageId: MessageId.make("message:selection-restart:first"),
341 text: "first",
342 attachments: [],
343 modelSelection: initialSelection,
344 dispatchMode: { type: "start_immediately" },
345 });
346 yield* Fiber.join(running);
347 yield* worker.drain();
348 const activeProjection = yield* orchestrator.getThreadProjection(threadId);
349 assert.isTrue(activeProjection.providerTurns.some((turn) => turn.status === "running"));
350 const activeRunId = activeProjection.runs[0]?.id;
351 if (activeRunId === undefined) {
352 return yield* Effect.die("active restart test run is missing");
353 }
354​
355 const completed = yield* eventSink
356 .stream({
357 threadId,
358 afterSequence: yield* eventSink.latestSequence({ threadId }),
359 })
360 .pipe(
361 Stream.map((stored) => stored.event),
362 Stream.filter(
363 (event) => event.type === "run.updated" && event.payload.status === "completed",
364 ),
365 Stream.take(1),
366 Stream.runDrain,
367 Effect.forkScoped,
368 );
369 yield* orchestrator.dispatch({
370 type: "message.dispatch",
371 createdBy: "user",
372 creationSource: "web",
373 commandId: CommandId.make("command:selection-restart:second"),
374 threadId,
375 messageId: MessageId.make("message:selection-restart:second"),
376 text: "second",
377 attachments: [],
378 modelSelection: replacementSelection,
379 dispatchMode: { type: "restart_active", targetRunId: activeRunId },
380 });
381 yield* Fiber.join(completed);
382 yield* worker.drain();
383 return {
384 projection: yield* orchestrator.getThreadProjection(threadId),
385 captured: yield* Ref.get(state),
386 };
387 }).pipe(
388 Effect.provide(
389 ProviderReplayHarness.layerWithRegistry(
390 { name: "selection-restart-lifecycle" },
391 layerRegistry,
392 ),
393 ),
394 );
395 const { projection, captured } = result;
396​
397 assert.lengthOf(projection.runs, 1);
398 assert.lengthOf(projection.attempts, 2);
399 assert.deepEqual(
400 projection.attempts.map((attempt) => attempt.status),
401 ["superseded", "completed"],
402 );
403 assert.deepEqual(
404 projection.providerTurns.map((turn) => turn.status),
405 ["interrupted", "completed"],
406 );
407 assert.isFalse(
408 projection.turnItems.some(
409 (item) => item.type === "run_interrupt_request" || item.type === "run_interrupt_result",
410 ),
411 "selection restart supersede must not project hard-Stop interrupt items",
412 );
413 assert.equal(projection.runs.at(-1)?.modelSelection.model, replacementSelection.model);
414 assert.deepEqual(modelSwitches(projection), [
415 { from: initialSelection, to: replacementSelection },
416 ]);
417 assert.equal(projection.runs.at(-1)?.status, "completed");
418 assert.isTrue(captured.failedReplacementOpen);
419 assert.equal(captured.closedSessionCount, 0);
420 assert.deepEqual(
421 captured.opened.map((open) => [open.model, open.cwd]),
422 [
423 [initialSelection.model, cwd],
424 [replacementSelection.model, cwd],
425 [replacementSelection.model, cwd],
426 ],
427 );
428 assert.deepEqual(
429 captured.started.map((turn) => [turn.model, turn.cwd]),
430 [
431 [initialSelection.model, cwd],
432 [replacementSelection.model, cwd],
433 ],
434 );
435 assert.notEqual(
436 projection.providerSessions[0]?.id,
437 projection.providerThreads[0]?.providerSessionId,
438 );
439 assert.equal(
440 projection.providerThreads[0]?.providerSessionId,
441 projection.providerSessions.find((session) => session.model === replacementSelection.model)
442 ?.id,
443 );
444 }),
445);
446​
447// regression: #22971 an exclusive session closes on detach; that failed the run and held the queue
448it.live.each(["pooled", "exclusive"] as const)(
449 "a workspace handoff on a %s session completes its run and starts the queued continuation",
450 (mode) =>
451 Effect.gen(function* () {
452 const cwd = yield* checkpointWorkspace(`workspace-handoff-${mode}`);
453 const handoffCwd = yield* checkpointWorkspace(`workspace-handoff-${mode}-target`);
454 const threadId = ThreadId.make(`thread:workspace-handoff:${mode}`);
455 const state = yield* Ref.make<RestartAdapterState>({
456 activeTurn: null,
457 opened: [],
458 started: [],
459 closedSessionCount: 0,
460 failedReplacementOpen: false,
461 });
462 const base = makeRestartAdapter(
463 state,
464 mode === "pooled" ? pooledCapabilities : exclusiveCapabilities,
465 );
466 const handoffToolId = TurnItemId.make(`turn-item:workspace-handoff:${mode}:tool`);
467 // A session that closes on detach is never asked to interrupt: Claude's cannot answer.
468 // Its turn is inside the handoff's own tool call, which the closed session never ends.
469 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] =
470 mode === "pooled"
471 ? base
472 : {
473 ...base,
474 openSession: (input) =>
475 Effect.gen(function* () {
476 const session = yield* base.openSession(input);
477 const toolEvents =
478 yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
479 return {
480 ...session,
481 events: Stream.merge(session.events, Stream.fromQueue(toolEvents)),
482 startTurn: (turn) =>
483 Effect.gen(function* () {
484 yield* session.startTurn(turn);
485 const now = yield* DateTime.now;
486 yield* Queue.offer(toolEvents, {
487 type: "turn_item.updated",
488 driver,
489 turnItem: {
490 id: handoffToolId,
491 type: "dynamic_tool",
492 threadId: turn.threadId,
493 runId: turn.runId,
494 nodeId: turn.rootNodeId,
495 providerThreadId: turn.providerThread.id,
496 providerTurnId: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
497 nativeItemRef: null,
498 parentItemId: null,
499 ordinal: 1,
500 status: "running",
501 title: "t3_worktree_handoff",
502 toolName: "t3-code.t3_worktree_handoff",
503 input: {},
504 output: null,
505 startedAt: now,
506 completedAt: null,
507 updatedAt: now,
508 },
509 });
510 }),
511 interruptTurn: () => Effect.die("an exclusive handoff must not interrupt"),
512 };
513 }),
514 };
515 const layerRegistry = ProviderAdapterRegistry.layerSingle(adapter);
516​
517 const projection = yield* Effect.gen(function* () {
518 const orchestrator = yield* Orchestrator.OrchestratorV2;
519 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
520 const eventSink = yield* EventSink.EventSinkV2;
521​
522 yield* orchestrator.dispatch({
523 type: "thread.create",
524 createdBy: "user",
525 creationSource: "web",
526 commandId: CommandId.make("command:workspace-handoff:create"),
527 threadId,
528 projectId: ProjectId.make("project:workspace-handoff"),
529 title: "Workspace handoff",
530 modelSelection: initialSelection,
531 runtimeMode: "full-access",
532 interactionMode: "default",
533 branch: null,
534 worktreePath: cwd,
535 });
536 const running = yield* eventSink
537 .stream({
538 threadId,
539 afterSequence: yield* eventSink.latestSequence({ threadId }),
540 })
541 .pipe(
542 Stream.map((stored) => stored.event),
543 Stream.filter(
544 (event) =>
545 event.type === "provider-turn.updated" && event.payload.status === "running",
546 ),
547 Stream.take(1),
548 Stream.runDrain,
549 Effect.forkScoped,
550 );
551 yield* orchestrator.dispatch({
552 type: "message.dispatch",
553 createdBy: "user",
554 creationSource: "web",
555 commandId: CommandId.make("command:workspace-handoff:first"),
556 threadId,
557 messageId: MessageId.make("message:workspace-handoff:first"),
558 text: "move to a worktree",
559 attachments: [],
560 modelSelection: initialSelection,
561 dispatchMode: { type: "start_immediately" },
562 });
563 yield* Fiber.join(running);
564 yield* worker.drain();
565​
566 const settled = yield* eventSink
567 .stream({
568 threadId,
569 afterSequence: yield* eventSink.latestSequence({ threadId }),
570 })
571 .pipe(
572 Stream.map((stored) => stored.event),
573 Stream.filter(
574 (event) =>
575 event.type === "run.updated" &&
576 event.payload.status !== "running" &&
577 event.payload.status !== "queued" &&
578 event.payload.status !== "starting",
579 ),
580 Stream.take(1),
581 Stream.runDrain,
582 Effect.forkScoped,
583 );
584 // The continuation starts from an async run.updated reaction, which drain alone does not await.
585 const continuationRunning = yield* eventSink
586 .stream({
587 threadId,
588 afterSequence: yield* eventSink.latestSequence({ threadId }),
589 })
590 .pipe(
591 Stream.map((stored) => stored.event),
592 Stream.filter(
593 (event) =>
594 event.type === "provider-turn.updated" && event.payload.status === "running",
595 ),
596 Stream.take(1),
597 Stream.runDrain,
598 Effect.forkScoped,
599 );
600 // What t3_worktree_handoff dispatches while the calling turn is still running.
601 const bound = yield* orchestrator.dispatch({
602 type: "thread.metadata.update",
603 commandId: CommandId.make("command:workspace-handoff:rebind"),
604 threadId,
605 branch: "repro-handoff",
606 worktreePath: handoffCwd,
607 continuation: {
608 messageId: MessageId.make("message:workspace-handoff:continuation"),
609 text: "continue in the worktree",
610 },
611 });
612 // The detach can settle the run at once, so its follow-up must exist in the same commit.
613 assert.deepEqual(
614 bound.storedEvents.flatMap(({ event }) =>
615 event.type === "run.created" ? [event.payload.status] : [],
616 ),
617 ["queued"],
618 );
619 yield* Fiber.join(settled);
620 yield* Fiber.join(continuationRunning);
621 yield* worker.drain();
622 return yield* orchestrator.getThreadProjection(threadId);
623 }).pipe(
624 Effect.provide(
625 ProviderReplayHarness.layerWithRegistry(
626 { name: `workspace-handoff-${mode}` },
627 layerRegistry,
628 ),
629 ),
630 );
631​
632 assert.equal(projection.thread.worktreePath, handoffCwd);
633 assert.equal(projection.runs[0]?.status, "completed");
634 assert.isNotNull(projection.runs[0]?.checkpointId ?? null);
635 assert.isFalse(
636 projection.turnItems.some(
637 (item) => item.type === "run_interrupt_result" || item.type === "error",
638 ),
639 "an intentional workspace handoff must not project an interrupt result or a failure",
640 );
641 if (mode === "exclusive") {
642 // regression: #39410 the handoff's tool call stayed running after its session closed.
643 assert.equal(
644 projection.turnItems.find((item) => item.id === handoffToolId)?.status,
645 "interrupted",
646 );
647 }
648 assert.deepEqual(
649 (yield* Ref.get(state)).started.map((turn) => turn.cwd),
650 [cwd, handoffCwd],
651 );
652 }),
653);
654​
655it.live("Stop during a restart interrupts the turn the restart could not stop", () =>
656 Effect.gen(function* () {
657 const cwd = yield* checkpointWorkspace("selection-restart-stop");
658 const threadId = ThreadId.make("thread:selection-restart-stop");
659 const state = yield* Ref.make<RestartAdapterState>({
660 activeTurn: null,
661 opened: [],
662 started: [],
663 closedSessionCount: 0,
664 failedReplacementOpen: false,
665 });
666 const base = makeRestartAdapter(state);
667 // A wedged provider ignores the restart's soft cancel; only Stop ends its turn.
668 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
669 ...base,
670 openSession: (input) =>
671 base.openSession(input).pipe(
672 Effect.map((session) => ({
673 ...session,
674 interruptTurn: (interrupt: ProviderAdapter.ProviderAdapterV2InterruptInput) =>
675 interrupt.requestRuntimeRestart === true
676 ? session.interruptTurn(interrupt)
677 : Effect.never,
678 })),
679 ),
680 };
681​
682 const result = yield* Effect.gen(function* () {
683 const orchestrator = yield* Orchestrator.OrchestratorV2;
684 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
685 const running = yield* orchestrator.streamDomainEvents.pipe(
686 Stream.filter(
687 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
688 ),
689 Stream.take(1),
690 Stream.runDrain,
691 Effect.forkScoped({ startImmediately: true }),
692 );
693 yield* orchestrator.dispatch({
694 type: "thread.create",
695 createdBy: "user",
696 creationSource: "web",
697 commandId: CommandId.make("command:selection-restart-stop:create"),
698 threadId,
699 projectId: ProjectId.make("project:selection-restart-stop"),
700 title: "Stop during restart",
701 modelSelection: initialSelection,
702 runtimeMode: "full-access",
703 interactionMode: "default",
704 branch: null,
705 worktreePath: cwd,
706 });
707 yield* orchestrator.dispatch({
708 type: "message.dispatch",
709 createdBy: "user",
710 creationSource: "web",
711 commandId: CommandId.make("command:selection-restart-stop:first"),
712 threadId,
713 messageId: MessageId.make("message:selection-restart-stop:first"),
714 text: "first",
715 attachments: [],
716 modelSelection: initialSelection,
717 dispatchMode: { type: "start_immediately" },
718 });
719 yield* worker.drain();
720 yield* Fiber.join(running);
721 const runId = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!.id;
722​
723 yield* orchestrator.dispatch({
724 type: "message.dispatch",
725 createdBy: "user",
726 creationSource: "web",
727 commandId: CommandId.make("command:selection-restart-stop:steer"),
728 threadId,
729 messageId: MessageId.make("message:selection-restart-stop:steer"),
730 text: "Are you still going?",
731 attachments: [],
732 modelSelection: initialSelection,
733 dispatchMode: { type: "restart_active", targetRunId: runId },
734 });
735 yield* orchestrator.dispatch({
736 type: "run.interrupt",
737 commandId: CommandId.make("command:selection-restart-stop:stop"),
738 threadId,
739 runId,
740 });
741 yield* worker.drain();
742 return {
743 projection: yield* orchestrator.getThreadProjection(threadId),
744 captured: yield* Ref.get(state),
745 };
746 }).pipe(
747 Effect.provide(
748 ProviderReplayHarness.layerWithRegistry(
749 { name: "selection-restart-stop" },
750 ProviderAdapterRegistry.layerSingle(adapter),
751 ),
752 ),
753 );
754​
755 assert.isNull(result.captured.activeTurn);
756 assert.lengthOf(result.captured.started, 1);
757 assert.equal(result.projection.runs[0]?.status, "interrupted");
758 assert.deepEqual(
759 result.projection.providerTurns.map((turn) => turn.status),
760 ["interrupted"],
761 );
762 }),
763);
764​
765it.live(
766 "restarts the live session on a model change when a newer stopped session record exists",
767 () =>
768 Effect.gen(function* () {
769 const name = "selection-restart-dead-stopped";
770 const cwd = yield* checkpointWorkspace(name);
771 const threadId = ThreadId.make(`thread:${name}`);
772 const state = yield* Ref.make<RestartAdapterState>({
773 activeTurn: null,
774 opened: [],
775 started: [],
776 closedSessionCount: 0,
777 failedReplacementOpen: true,
778 });
779 const layerRegistry = ProviderAdapterRegistry.layerSingle(
780 makeRestartAdapter(state, exclusiveCapabilities),
781 );
782​
783 const result = yield* Effect.gen(function* () {
784 const orchestrator = yield* Orchestrator.OrchestratorV2;
785 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
786 const eventSink = yield* EventSink.EventSinkV2;
787 const dispatch = (step: string, modelSelection: ModelSelection) =>
788 Effect.gen(function* () {
789 const terminal = yield* orchestrator.streamDomainEvents.pipe(
790 Stream.filter(
791 (event) => event.type === "run.updated" && event.payload.status === "completed",
792 ),
793 Stream.take(1),
794 Stream.runDrain,
795 Effect.forkScoped,
796 );
797 yield* orchestrator.dispatch({
798 type: "message.dispatch",
799 createdBy: "user",
800 creationSource: "web",
801 commandId: CommandId.make(`${name}:${step}`),
802 threadId,
803 messageId: MessageId.make(`${name}:${step}`),
804 text: step,
805 attachments: [],
806 modelSelection,
807 dispatchMode: { type: "start_immediately" },
808 });
809 yield* worker.drain();
810 yield* Fiber.join(terminal);
811 yield* worker.drain();
812 return yield* orchestrator.getThreadProjection(threadId);
813 });
814 yield* orchestrator.dispatch({
815 type: "thread.create",
816 createdBy: "user",
817 creationSource: "web",
818 commandId: CommandId.make(`${name}:create`),
819 threadId,
820 projectId: ProjectId.make(`project:${name}`),
821 title: name,
822 modelSelection: seedSelection,
823 runtimeMode: "full-access",
824 interactionMode: "default",
825 branch: null,
826 worktreePath: cwd,
827 });
828 const first = yield* dispatch("first", seedSelection);
829 const liveSession = first.providerSessions.find(
830 (session) => session.status !== "stopped" && session.status !== "error",
831 );
832 assert.isDefined(liveSession);
833​
834 const deadAt = yield* DateTime.now;
835 const deadSession: OrchestrationV2ProviderSession = {
836 id: ProviderSessionId.make(`session:${name}:dead`),
837 driver,
838 providerInstanceId,
839 status: "ready",
840 cwd,
841 model: seedSelection.model,
842 capabilities: exclusiveCapabilities,
843 createdAt: deadAt,
844 updatedAt: deadAt,
845 lastError: null,
846 };
847 yield* eventSink.write({
848 events: [
849 {
850 id: EventId.make(`event:${name}:dead-attached`),
851 type: "provider-session.attached",
852 threadId,
853 driver,
854 providerInstanceId,
855 occurredAt: deadAt,
856 payload: deadSession,
857 },
858 {
859 id: EventId.make(`event:${name}:dead-updated`),
860 type: "provider-session.updated",
861 threadId,
862 driver,
863 providerInstanceId,
864 occurredAt: deadAt,
865 payload: {
866 ...deadSession,
867 status: "stopped",
868 updatedAt: deadAt,
869 lastError: null,
870 },
871 },
872 ],
873 });
874​
875 const switchCommandId = CommandId.make(`${name}:switch`);
876 yield* orchestrator.dispatch({
877 type: "thread.model-selection.set",
878 commandId: switchCommandId,
879 threadId,
880 modelSelection: replacementSelection,
881 });
882 yield* worker.drain();
883 const storedSwitchEvents = yield* eventSink
884 .readByCommandId({ commandId: switchCommandId })
885 .pipe(Stream.runCollect);
886 const detachedSessionIds = [...storedSwitchEvents].flatMap((stored) =>
887 stored.event.type === "provider-session.detached"
888 ? [stored.event.payload.providerSessionId]
889 : [],
890 );
891​
892 const second = yield* dispatch("second", replacementSelection);
893 return {
894 projection: second,
895 captured: yield* Ref.get(state),
896 liveSessionId: liveSession.id,
897 detachedSessionIds,
898 };
899 }).pipe(Effect.provide(ProviderReplayHarness.layerWithRegistry({ name }, layerRegistry)));
900​
901 const { projection, captured } = result;
902 assert.lengthOf(projection.runs, 2);
903 assert.equal(projection.runs[1]?.modelSelection.model, replacementSelection.model);
904 assert.deepEqual(modelSwitches(projection), [
905 { from: seedSelection, to: replacementSelection },
906 ]);
907 assert.deepEqual(result.detachedSessionIds, [result.liveSessionId]);
908 assert.equal(captured.closedSessionCount, 1);
909 assert.deepEqual(
910 captured.opened.map((open) => open.model),
911 [seedSelection.model, replacementSelection.model],
912 );
913 assert.deepEqual(
914 captured.started.map((turn) => turn.model),
915 [seedSelection.model, replacementSelection.model],
916 );
917 const servingSession = projection.providerSessions.find(
918 (session) =>
919 session.id ===
920 projection.providerThreads.find(
921 (providerThread) => providerThread.id === projection.thread.activeProviderThreadId,
922 )?.providerSessionId,
923 );
924 assert.equal(servingSession?.model, replacementSelection.model);
925 }),
926);
927​
928const accountSwitchModes = [
929 "active",
930 "idle",
931 "selection-command",
932 "pooled",
933 "separate-home",
934 "active-separate-home",
935] as const;
936​
937it.live.each(accountSwitchModes)(
938 "preserves native history only for compatible account switches (%s)",
939 (mode) =>
940 Effect.gen(function* () {
941 const name = `shared-home-${mode}`;
942 const active = mode === "active" || mode === "active-separate-home";
943 const separateHome = mode === "separate-home" || mode === "active-separate-home";
944 const cwd = yield* checkpointWorkspace(name);
945 const threadId = ThreadId.make(`thread:${name}`);
946 const targetId = ProviderInstanceId.make("codex-shadow-account");
947 const state = yield* Ref.make<RestartAdapterState>({
948 activeTurn: null,
949 opened: [],
950 started: [],
951 closedSessionCount: 0,
952 failedReplacementOpen: true,
953 });
954 const resumes: Array<{
955 instanceId: ProviderInstanceId;
956 nativeId: string | null | undefined;
957 }> = [];
958 const messages: string[] = [];
959 const capabilities = mode === "pooled" ? pooledCapabilities : exclusiveCapabilities;
960 const adapters = [providerInstanceId, targetId].map((instanceId) => {
961 const base = makeRestartAdapter(state, capabilities, instanceId);
962 return {
963 ...base,
964 openSession: (input) =>
965 base.openSession(input).pipe(
966 Effect.map((session) => ({
967 ...session,
968 resumeThread: (input) =>
969 Effect.gen(function* () {
970 resumes.push({
971 instanceId,
972 nativeId: input.providerThread.nativeThreadRef?.nativeId,
973 });
974 return yield* session.resumeThread(input);
975 }),
976 startTurn: (input) =>
977 Effect.gen(function* () {
978 messages.push(input.message.text);
979 yield* session.startTurn(input);
980 }),
981 })),
982 ),
983 } satisfies ProviderAdapter.ProviderAdapterV2["Service"];
984 });
985 const layerRegistry = Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistryV2, {
986 get: (instanceId) =>
987 Effect.succeed(adapters.find((adapter) => adapter.instanceId === instanceId)!),
988 list: () => Effect.succeed([providerInstanceId, targetId]),
989 getMetadata: (instanceId) =>
990 Effect.succeed({
991 driver,
992 continuationKey: separateHome ? `codex:home:/${instanceId}` : "codex:home:/shared",
993 enabled: true,
994 capabilities,
995 }),
996 });
997 yield* Effect.gen(function* () {
998 const orchestrator = yield* Orchestrator.OrchestratorV2;
999 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1000 const selection = {
1001 ...initialSelection,
1002 model: active ? initialSelection.model : "complete",
1003 };
1004 yield* orchestrator.dispatch({
1005 type: "thread.create",
1006 commandId: CommandId.make(`${name}:create`),
1007 threadId,
1008 projectId: ProjectId.make(`project:${name}`),
1009 title: name,
1010 modelSelection: selection,
1011 runtimeMode: "full-access",
1012 interactionMode: "default",
1013 branch: null,
1014 worktreePath: cwd,
1015 createdBy: "user",
1016 creationSource: "web",
1017 });
1018 const dispatch = (step: string, modelSelection: ModelSelection, targetRunId?: RunId) =>
1019 Effect.gen(function* () {
1020 const terminal = yield* orchestrator.streamDomainEvents.pipe(
1021 Stream.filter((event) =>
1022 active && step === "first"
1023 ? event.type === "provider-turn.updated" && event.payload.status === "running"
1024 : event.type === "run.updated" && event.payload.status === "completed",
1025 ),
1026 Stream.take(1),
1027 Stream.runDrain,
1028 Effect.forkScoped,
1029 );
1030 yield* orchestrator.dispatch({
1031 type: "message.dispatch",
1032 commandId: CommandId.make(`${name}:${step}`),
1033 threadId,
1034 messageId: MessageId.make(`${name}:${step}`),
1035 text: step,
1036 attachments: [],
1037 modelSelection,
1038 dispatchMode:
1039 targetRunId === undefined
1040 ? { type: "start_immediately" }
1041 : { type: "restart_active", targetRunId },
1042 createdBy: "user",
1043 creationSource: "web",
1044 });
1045 yield* worker.drain();
1046 yield* Fiber.join(terminal);
1047 yield* worker.drain();
1048 return yield* orchestrator.getThreadProjection(threadId);
1049 });
1050 const first = yield* dispatch("first", selection);
1051 const originalThread = first.providerThreads.find(
1052 (thread) => thread.id === first.thread.activeProviderThreadId,
1053 )!;
1054 const targetSelection = { instanceId: targetId, model: "complete" };
1055 if (mode === "selection-command") {
1056 yield* orchestrator.dispatch({
1057 type: "provider.switch",
1058 commandId: CommandId.make(`${name}:switch`),
1059 threadId,
1060 modelSelection: targetSelection,
1061 });
1062 yield* worker.drain();
1064 const second = yield* dispatch(
1065 "second",
1066 targetSelection,
1067 active ? first.runs[0]!.id : undefined,
1068 );
1069 const targetThread = second.providerThreads.find(
1070 (thread) => thread.id === second.thread.activeProviderThreadId,
1071 )!;
1072 if (separateHome) {
1073 assert.notEqual(targetThread.id, originalThread.id);
1074 assert.lengthOf(second.contextHandoffs, 1);
1075 assert.deepEqual(
1076 second.turnItems.flatMap((item) =>
1077 item.type === "handoff" ? [item.contextHandoffId] : [],
1078 ),
1079 [second.contextHandoffs[0]!.id],
1080 );
1081 assert.lengthOf(second.contextTransfers, 1);
1082 assert.isEmpty(resumes);
1083 assert.notEqual(messages[1], "second");
1084 return;
1086 assert.equal(targetThread.id, originalThread.id);
1087 assert.deepEqual(targetThread.nativeThreadRef, originalThread.nativeThreadRef);
1088 assert.equal(targetThread.providerInstanceId, targetId);
1089 assert.notEqual(targetThread.providerSessionId, originalThread.providerSessionId);
1090 assert.isEmpty(second.contextHandoffs);
1091 assert.isEmpty(second.contextTransfers);
1092 assert.deepEqual(resumes, [
1093 { instanceId: targetId, nativeId: originalThread.nativeThreadRef?.nativeId },
1094 ]);
1095 assert.deepEqual(messages, ["first", "second"]);
1096 assert.equal((yield* Ref.get(state)).closedSessionCount, mode === "pooled" ? 0 : 1);
1097 if (mode === "pooled") {
1098 assert.isFalse(
1099 second.providerSessions.some(
1100 (session) => session.id === originalThread.providerSessionId,
1101 ),
1102 );
1104 const third = yield* dispatch("third", { ...selection, model: "complete" });
1105 const returnedThread = third.providerThreads.find(
1106 (thread) => thread.id === third.thread.activeProviderThreadId,
1107 )!;
1108 assert.equal(returnedThread.id, originalThread.id);
1109 assert.deepEqual(returnedThread.nativeThreadRef, originalThread.nativeThreadRef);
1110 assert.equal(returnedThread.providerInstanceId, providerInstanceId);
1111 assert.isEmpty(third.contextHandoffs);
1112 assert.deepEqual(messages, ["first", "second", "third"]);
1113 }).pipe(Effect.provide(ProviderReplayHarness.layerWithRegistry({ name }, layerRegistry)));
1114 }),