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