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

SelectionRestart.integration.test.ts

899 lines34.1 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("Stop during a restart interrupts the turn the restart could not stop", () =>
450 Effect.scoped(
451 Effect.gen(function* () {
452 const cwd = yield* checkpointWorkspace("selection-restart-stop");
453 const threadId = ThreadId.make("thread:selection-restart-stop");
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(state);
462 // A wedged provider ignores the restart's soft cancel; only Stop ends its turn.
463 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
464 ...base,
465 openSession: (input) =>
466 base.openSession(input).pipe(
467 Effect.map((session) => ({
468 ...session,
469 interruptTurn: (interrupt: ProviderAdapter.ProviderAdapterV2InterruptInput) =>
470 interrupt.requestRuntimeRestart === true
471 ? session.interruptTurn(interrupt)
472 : Effect.never,
473 })),
474 ),
475 };
476​
477 const result = yield* Effect.gen(function* () {
478 const orchestrator = yield* Orchestrator.OrchestratorV2;
479 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
480 const running = yield* orchestrator.streamDomainEvents.pipe(
481 Stream.filter(
482 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
483 ),
484 Stream.take(1),
485 Stream.runDrain,
486 Effect.forkScoped({ startImmediately: true }),
487 );
488 yield* orchestrator.dispatch({
489 type: "thread.create",
490 createdBy: "user",
491 creationSource: "web",
492 commandId: CommandId.make("command:selection-restart-stop:create"),
493 threadId,
494 projectId: ProjectId.make("project:selection-restart-stop"),
495 title: "Stop during restart",
496 modelSelection: initialSelection,
497 runtimeMode: "full-access",
498 interactionMode: "default",
499 branch: null,
500 worktreePath: cwd,
501 });
502 yield* orchestrator.dispatch({
503 type: "message.dispatch",
504 createdBy: "user",
505 creationSource: "web",
506 commandId: CommandId.make("command:selection-restart-stop:first"),
507 threadId,
508 messageId: MessageId.make("message:selection-restart-stop:first"),
509 text: "first",
510 attachments: [],
511 modelSelection: initialSelection,
512 dispatchMode: { type: "start_immediately" },
513 });
514 yield* worker.drain();
515 yield* Fiber.join(running);
516 const runId = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!.id;
517​
518 yield* orchestrator.dispatch({
519 type: "message.dispatch",
520 createdBy: "user",
521 creationSource: "web",
522 commandId: CommandId.make("command:selection-restart-stop:steer"),
523 threadId,
524 messageId: MessageId.make("message:selection-restart-stop:steer"),
525 text: "Are you still going?",
526 attachments: [],
527 modelSelection: initialSelection,
528 dispatchMode: { type: "restart_active", targetRunId: runId },
529 });
530 yield* orchestrator.dispatch({
531 type: "run.interrupt",
532 commandId: CommandId.make("command:selection-restart-stop:stop"),
533 threadId,
534 runId,
535 });
536 yield* worker.drain();
537 return {
538 projection: yield* orchestrator.getThreadProjection(threadId),
539 captured: yield* Ref.get(state),
540 };
541 }).pipe(
542 Effect.provide(
543 ProviderReplayHarness.layerWithRegistry(
544 { name: "selection-restart-stop" },
545 ProviderAdapterRegistry.layerSingle(adapter),
546 ),
547 ),
548 );
549​
550 assert.isNull(result.captured.activeTurn);
551 assert.lengthOf(result.captured.started, 1);
552 assert.equal(result.projection.runs[0]?.status, "interrupted");
553 assert.deepEqual(
554 result.projection.providerTurns.map((turn) => turn.status),
555 ["interrupted"],
556 );
557 }),
558 ),
559);
560​
561it.live(
562 "restarts the live session on a model change when a newer stopped session record exists",
563 () =>
564 Effect.scoped(
565 Effect.gen(function* () {
566 const name = "selection-restart-dead-stopped";
567 const cwd = yield* checkpointWorkspace(name);
568 const threadId = ThreadId.make(`thread:${name}`);
569 const state = yield* Ref.make<RestartAdapterState>({
570 activeTurn: null,
571 opened: [],
572 started: [],
573 closedSessionCount: 0,
574 failedReplacementOpen: true,
575 });
576 const layerRegistry = ProviderAdapterRegistry.layerSingle(
577 makeRestartAdapter(state, exclusiveCapabilities),
578 );
579​
580 const result = yield* Effect.gen(function* () {
581 const orchestrator = yield* Orchestrator.OrchestratorV2;
582 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
583 const eventSink = yield* EventSink.EventSinkV2;
584 const dispatch = (step: string, modelSelection: ModelSelection) =>
585 Effect.gen(function* () {
586 const terminal = yield* orchestrator.streamDomainEvents.pipe(
587 Stream.filter(
588 (event) => event.type === "run.updated" && event.payload.status === "completed",
589 ),
590 Stream.take(1),
591 Stream.runDrain,
592 Effect.forkScoped,
593 );
594 yield* orchestrator.dispatch({
595 type: "message.dispatch",
596 createdBy: "user",
597 creationSource: "web",
598 commandId: CommandId.make(`${name}:${step}`),
599 threadId,
600 messageId: MessageId.make(`${name}:${step}`),
601 text: step,
602 attachments: [],
603 modelSelection,
604 dispatchMode: { type: "start_immediately" },
605 });
606 yield* worker.drain();
607 yield* Fiber.join(terminal);
608 yield* worker.drain();
609 return yield* orchestrator.getThreadProjection(threadId);
610 });
611 yield* orchestrator.dispatch({
612 type: "thread.create",
613 createdBy: "user",
614 creationSource: "web",
615 commandId: CommandId.make(`${name}:create`),
616 threadId,
617 projectId: ProjectId.make(`project:${name}`),
618 title: name,
619 modelSelection: seedSelection,
620 runtimeMode: "full-access",
621 interactionMode: "default",
622 branch: null,
623 worktreePath: cwd,
624 });
625 const first = yield* dispatch("first", seedSelection);
626 const liveSession = first.providerSessions.find(
627 (session) => session.status !== "stopped" && session.status !== "error",
628 );
629 assert.isDefined(liveSession);
630​
631 const deadAt = yield* DateTime.now;
632 const deadSession: OrchestrationV2ProviderSession = {
633 id: ProviderSessionId.make(`session:${name}:dead`),
634 driver,
635 providerInstanceId,
636 status: "ready",
637 cwd,
638 model: seedSelection.model,
639 capabilities: exclusiveCapabilities,
640 createdAt: deadAt,
641 updatedAt: deadAt,
642 lastError: null,
643 };
644 yield* eventSink.write({
645 events: [
646 {
647 id: EventId.make(`event:${name}:dead-attached`),
648 type: "provider-session.attached",
649 threadId,
650 driver,
651 providerInstanceId,
652 occurredAt: deadAt,
653 payload: deadSession,
654 },
655 {
656 id: EventId.make(`event:${name}:dead-updated`),
657 type: "provider-session.updated",
658 threadId,
659 driver,
660 providerInstanceId,
661 occurredAt: deadAt,
662 payload: {
663 ...deadSession,
664 status: "stopped",
665 updatedAt: deadAt,
666 lastError: null,
667 },
668 },
669 ],
670 });
671​
672 const switchCommandId = CommandId.make(`${name}:switch`);
673 yield* orchestrator.dispatch({
674 type: "thread.model-selection.set",
675 commandId: switchCommandId,
676 threadId,
677 modelSelection: replacementSelection,
678 });
679 yield* worker.drain();
680 const storedSwitchEvents = yield* eventSink
681 .readByCommandId({ commandId: switchCommandId })
682 .pipe(Stream.runCollect);
683 const detachedSessionIds = [...storedSwitchEvents].flatMap((stored) =>
684 stored.event.type === "provider-session.detached"
685 ? [stored.event.payload.providerSessionId]
686 : [],
687 );
688​
689 const second = yield* dispatch("second", replacementSelection);
690 return {
691 projection: second,
692 captured: yield* Ref.get(state),
693 liveSessionId: liveSession.id,
694 detachedSessionIds,
695 };
696 }).pipe(Effect.provide(ProviderReplayHarness.layerWithRegistry({ name }, layerRegistry)));
697​
698 const { projection, captured } = result;
699 assert.lengthOf(projection.runs, 2);
700 assert.equal(projection.runs[1]?.modelSelection.model, replacementSelection.model);
701 assert.deepEqual(modelSwitches(projection), [
702 { from: seedSelection, to: replacementSelection },
703 ]);
704 assert.deepEqual(result.detachedSessionIds, [result.liveSessionId]);
705 assert.equal(captured.closedSessionCount, 1);
706 assert.deepEqual(
707 captured.opened.map((open) => open.model),
708 [seedSelection.model, replacementSelection.model],
709 );
710 assert.deepEqual(
711 captured.started.map((turn) => turn.model),
712 [seedSelection.model, replacementSelection.model],
713 );
714 const servingSession = projection.providerSessions.find(
715 (session) =>
716 session.id ===
717 projection.providerThreads.find(
718 (providerThread) => providerThread.id === projection.thread.activeProviderThreadId,
719 )?.providerSessionId,
720 );
721 assert.equal(servingSession?.model, replacementSelection.model);
722 }),
723 ),
724);
725​
726it.live.each(["active", "idle", "selection-command", "pooled", "separate-home"] as const)(
727 "preserves native history only for compatible account switches (%s)",
728 (mode) =>
729 Effect.scoped(
730 Effect.gen(function* () {
731 const name = `shared-home-${mode}`;
732 const cwd = yield* checkpointWorkspace(name);
733 const threadId = ThreadId.make(`thread:${name}`);
734 const targetId = ProviderInstanceId.make("codex-shadow-account");
735 const state = yield* Ref.make<RestartAdapterState>({
736 activeTurn: null,
737 opened: [],
738 started: [],
739 closedSessionCount: 0,
740 failedReplacementOpen: true,
741 });
742 const resumes: Array<{
743 instanceId: ProviderInstanceId;
744 nativeId: string | null | undefined;
745 }> = [];
746 const messages: string[] = [];
747 const capabilities = mode === "pooled" ? pooledCapabilities : exclusiveCapabilities;
748 const adapters = [providerInstanceId, targetId].map((instanceId) => {
749 const base = makeRestartAdapter(state, capabilities, instanceId);
750 return {
751 ...base,
752 openSession: (input) =>
753 base.openSession(input).pipe(
754 Effect.map((session) => ({
755 ...session,
756 resumeThread: (input) =>
757 Effect.gen(function* () {
758 resumes.push({
759 instanceId,
760 nativeId: input.providerThread.nativeThreadRef?.nativeId,
761 });
762 return yield* session.resumeThread(input);
763 }),
764 startTurn: (input) =>
765 Effect.gen(function* () {
766 messages.push(input.message.text);
767 yield* session.startTurn(input);
768 }),
769 })),
770 ),
771 } satisfies ProviderAdapter.ProviderAdapterV2["Service"];
772 });
773 const layerRegistry = Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistryV2, {
774 get: (instanceId) =>
775 Effect.succeed(adapters.find((adapter) => adapter.instanceId === instanceId)!),
776 list: () => Effect.succeed([providerInstanceId, targetId]),
777 getMetadata: (instanceId) =>
778 Effect.succeed({
779 driver,
780 continuationKey:
781 mode === "separate-home" ? `codex:home:/${instanceId}` : "codex:home:/shared",
782 enabled: true,
783 capabilities,
784 }),
785 });
786 yield* Effect.gen(function* () {
787 const orchestrator = yield* Orchestrator.OrchestratorV2;
788 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
789 const selection = {
790 ...initialSelection,
791 model: mode === "active" ? initialSelection.model : "complete",
792 };
793 yield* orchestrator.dispatch({
794 type: "thread.create",
795 commandId: CommandId.make(`${name}:create`),
796 threadId,
797 projectId: ProjectId.make(`project:${name}`),
798 title: name,
799 modelSelection: selection,
800 runtimeMode: "full-access",
801 interactionMode: "default",
802 branch: null,
803 worktreePath: cwd,
804 createdBy: "user",
805 creationSource: "web",
806 });
807 const dispatch = (step: string, modelSelection: ModelSelection, targetRunId?: RunId) =>
808 Effect.gen(function* () {
809 const terminal = yield* orchestrator.streamDomainEvents.pipe(
810 Stream.filter((event) =>
811 mode === "active" && step === "first"
812 ? event.type === "provider-turn.updated" && event.payload.status === "running"
813 : event.type === "run.updated" && event.payload.status === "completed",
814 ),
815 Stream.take(1),
816 Stream.runDrain,
817 Effect.forkScoped,
818 );
819 yield* orchestrator.dispatch({
820 type: "message.dispatch",
821 commandId: CommandId.make(`${name}:${step}`),
822 threadId,
823 messageId: MessageId.make(`${name}:${step}`),
824 text: step,
825 attachments: [],
826 modelSelection,
827 dispatchMode:
828 targetRunId === undefined
829 ? { type: "start_immediately" }
830 : { type: "restart_active", targetRunId },
831 createdBy: "user",
832 creationSource: "web",
833 });
834 yield* worker.drain();
835 yield* Fiber.join(terminal);
836 yield* worker.drain();
837 return yield* orchestrator.getThreadProjection(threadId);
838 });
839 const first = yield* dispatch("first", selection);
840 const originalThread = first.providerThreads.find(
841 (thread) => thread.id === first.thread.activeProviderThreadId,
842 )!;
843 const targetSelection = { instanceId: targetId, model: "complete" };
844 if (mode === "selection-command") {
845 yield* orchestrator.dispatch({
846 type: "provider.switch",
847 commandId: CommandId.make(`${name}:switch`),
848 threadId,
849 modelSelection: targetSelection,
850 });
851 yield* worker.drain();
852 }
853 const second = yield* dispatch(
854 "second",
855 targetSelection,
856 mode === "active" ? first.runs[0]!.id : undefined,
857 );
858 const targetThread = second.providerThreads.find(
859 (thread) => thread.id === second.thread.activeProviderThreadId,
860 )!;
861 if (mode === "separate-home") {
862 assert.notEqual(targetThread.id, originalThread.id);
863 assert.lengthOf(second.contextHandoffs, 1);
864 assert.lengthOf(second.contextTransfers, 1);
865 assert.isEmpty(resumes);
866 assert.notEqual(messages[1], "second");
867 return;
868 }
869 assert.equal(targetThread.id, originalThread.id);
870 assert.deepEqual(targetThread.nativeThreadRef, originalThread.nativeThreadRef);
871 assert.equal(targetThread.providerInstanceId, targetId);
872 assert.notEqual(targetThread.providerSessionId, originalThread.providerSessionId);
873 assert.isEmpty(second.contextHandoffs);
874 assert.isEmpty(second.contextTransfers);
875 assert.deepEqual(resumes, [
876 { instanceId: targetId, nativeId: originalThread.nativeThreadRef?.nativeId },
877 ]);
878 assert.deepEqual(messages, ["first", "second"]);
879 assert.equal((yield* Ref.get(state)).closedSessionCount, mode === "pooled" ? 0 : 1);
880 if (mode === "pooled") {
881 assert.isFalse(
882 second.providerSessions.some(
883 (session) => session.id === originalThread.providerSessionId,
884 ),
885 );
886 }
887 const third = yield* dispatch("third", { ...selection, model: "complete" });
888 const returnedThread = third.providerThreads.find(
889 (thread) => thread.id === third.thread.activeProviderThreadId,
890 )!;
891 assert.equal(returnedThread.id, originalThread.id);
892 assert.deepEqual(returnedThread.nativeThreadRef, originalThread.nativeThreadRef);
893 assert.equal(returnedThread.providerInstanceId, providerInstanceId);
894 assert.isEmpty(third.contextHandoffs);
895 assert.deepEqual(messages, ["first", "second", "third"]);
896 }).pipe(Effect.provide(ProviderReplayHarness.layerWithRegistry({ name }, layerRegistry)));
897 }),
898 ),
899);