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