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

SelectionRestart.integration.test.ts

1,002 lines39.5 KB

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