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

SelectionRestart.integration.test.ts

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