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

SelectionRestart.integration.test.ts

776 lines29.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 * 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;
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;
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 };
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(
442 "restarts the live session on a model change when a newer stopped session record exists",
443 () =>
444 Effect.scoped(
445 Effect.gen(function* () {
446 const name = "selection-restart-dead-stopped";
447 const cwd = yield* checkpointWorkspace(name);
448 const threadId = ThreadId.make(`thread:${name}`);
449 const state = yield* Ref.make<RestartAdapterState>({
450 activeTurn: null,
451 opened: [],
452 started: [],
453 closedSessionCount: 0,
454 failedReplacementOpen: true,
455 });
456 const layerRegistry = ProviderAdapterRegistry.layerSingle(
457 makeRestartAdapter(state, exclusiveCapabilities),
458 );
459​
460 const result = yield* Effect.gen(function* () {
461 const orchestrator = yield* Orchestrator.OrchestratorV2;
462 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
463 const eventSink = yield* EventSink.EventSinkV2;
464 const dispatch = (step: string, modelSelection: ModelSelection) =>
465 Effect.gen(function* () {
466 const terminal = yield* orchestrator.streamDomainEvents.pipe(
467 Stream.filter(
468 (event) => event.type === "run.updated" && event.payload.status === "completed",
469 ),
470 Stream.take(1),
471 Stream.runDrain,
472 Effect.forkScoped,
473 );
474 yield* orchestrator.dispatch({
475 type: "message.dispatch",
476 createdBy: "user",
477 creationSource: "web",
478 commandId: CommandId.make(`${name}:${step}`),
479 threadId,
480 messageId: MessageId.make(`${name}:${step}`),
481 text: step,
482 attachments: [],
483 modelSelection,
484 dispatchMode: { type: "start_immediately" },
485 });
486 yield* worker.drain();
487 yield* Fiber.join(terminal);
488 yield* worker.drain();
489 return yield* orchestrator.getThreadProjection(threadId);
490 });
491 yield* orchestrator.dispatch({
492 type: "thread.create",
493 createdBy: "user",
494 creationSource: "web",
495 commandId: CommandId.make(`${name}:create`),
496 threadId,
497 projectId: ProjectId.make(`project:${name}`),
498 title: name,
499 modelSelection: seedSelection,
500 runtimeMode: "full-access",
501 interactionMode: "default",
502 branch: null,
503 worktreePath: cwd,
504 });
505 const first = yield* dispatch("first", seedSelection);
506 const liveSession = first.providerSessions.find(
507 (session) => session.status !== "stopped" && session.status !== "error",
508 );
509 assert.isDefined(liveSession);
510​
511 const deadAt = yield* DateTime.now;
512 const deadSession: OrchestrationV2ProviderSession = {
513 id: ProviderSessionId.make(`session:${name}:dead`),
514 driver,
515 providerInstanceId,
516 status: "ready",
517 cwd,
518 model: seedSelection.model,
519 capabilities: exclusiveCapabilities,
520 createdAt: deadAt,
521 updatedAt: deadAt,
522 lastError: null,
523 };
524 yield* eventSink.write({
525 events: [
526 {
527 id: EventId.make(`event:${name}:dead-attached`),
528 type: "provider-session.attached",
529 threadId,
530 driver,
531 providerInstanceId,
532 occurredAt: deadAt,
533 payload: deadSession,
534 },
535 {
536 id: EventId.make(`event:${name}:dead-updated`),
537 type: "provider-session.updated",
538 threadId,
539 driver,
540 providerInstanceId,
541 occurredAt: deadAt,
542 payload: {
543 ...deadSession,
544 status: "stopped",
545 updatedAt: deadAt,
546 lastError: null,
547 },
548 },
549 ],
550 });
551​
552 const switchCommandId = CommandId.make(`${name}:switch`);
553 yield* orchestrator.dispatch({
554 type: "thread.model-selection.set",
555 commandId: switchCommandId,
556 threadId,
557 modelSelection: replacementSelection,
558 });
559 yield* worker.drain();
560 const storedSwitchEvents = yield* eventSink
561 .readByCommandId({ commandId: switchCommandId })
562 .pipe(Stream.runCollect);
563 const detachedSessionIds = [...storedSwitchEvents].flatMap((stored) =>
564 stored.event.type === "provider-session.detached"
565 ? [stored.event.payload.providerSessionId]
566 : [],
567 );
568​
569 const second = yield* dispatch("second", replacementSelection);
570 return {
571 projection: second,
572 captured: yield* Ref.get(state),
573 liveSessionId: liveSession.id,
574 detachedSessionIds,
575 };
576 }).pipe(Effect.provide(ProviderReplayHarness.layerWithRegistry({ name }, layerRegistry)));
577​
578 const { projection, captured } = result;
579 assert.lengthOf(projection.runs, 2);
580 assert.equal(projection.runs[1]?.modelSelection.model, replacementSelection.model);
581 assert.deepEqual(result.detachedSessionIds, [result.liveSessionId]);
582 assert.equal(captured.closedSessionCount, 1);
583 assert.deepEqual(
584 captured.opened.map((open) => open.model),
585 [seedSelection.model, replacementSelection.model],
586 );
587 assert.deepEqual(
588 captured.started.map((turn) => turn.model),
589 [seedSelection.model, replacementSelection.model],
590 );
591 const servingSession = projection.providerSessions.find(
592 (session) =>
593 session.id ===
594 projection.providerThreads.find(
595 (providerThread) => providerThread.id === projection.thread.activeProviderThreadId,
596 )?.providerSessionId,
597 );
598 assert.equal(servingSession?.model, replacementSelection.model);
599 }),
600 ),
601);
602​
603it.live.each(["active", "idle", "selection-command", "pooled", "separate-home"] as const)(
604 "preserves native history only for compatible account switches (%s)",
605 (mode) =>
606 Effect.scoped(
607 Effect.gen(function* () {
608 const name = `shared-home-${mode}`;
609 const cwd = yield* checkpointWorkspace(name);
610 const threadId = ThreadId.make(`thread:${name}`);
611 const targetId = ProviderInstanceId.make("codex-shadow-account");
612 const state = yield* Ref.make<RestartAdapterState>({
613 activeTurn: null,
614 opened: [],
615 started: [],
616 closedSessionCount: 0,
617 failedReplacementOpen: true,
618 });
619 const resumes: Array<{
620 instanceId: ProviderInstanceId;
621 nativeId: string | null | undefined;
622 }> = [];
623 const messages: string[] = [];
624 const capabilities = mode === "pooled" ? pooledCapabilities : exclusiveCapabilities;
625 const adapters = [providerInstanceId, targetId].map((instanceId) => {
626 const base = makeRestartAdapter(state, capabilities, instanceId);
627 return {
628 ...base,
629 openSession: (input) =>
630 base.openSession(input).pipe(
631 Effect.map((session) => ({
632 ...session,
633 resumeThread: (input) =>
634 Effect.gen(function* () {
635 resumes.push({
636 instanceId,
637 nativeId: input.providerThread.nativeThreadRef?.nativeId,
638 });
639 return yield* session.resumeThread(input);
640 }),
641 startTurn: (input) =>
642 Effect.gen(function* () {
643 messages.push(input.message.text);
644 yield* session.startTurn(input);
645 }),
646 })),
647 ),
648 } satisfies ProviderAdapter.ProviderAdapterV2["Service"];
649 });
650 const layerRegistry = Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistryV2, {
651 get: (instanceId) =>
652 Effect.succeed(adapters.find((adapter) => adapter.instanceId === instanceId)!),
653 list: () => Effect.succeed([providerInstanceId, targetId]),
654 getMetadata: (instanceId) =>
655 Effect.succeed({
656 driver,
657 continuationKey:
658 mode === "separate-home" ? `codex:home:/${instanceId}` : "codex:home:/shared",
659 enabled: true,
660 capabilities,
661 }),
662 });
663 yield* Effect.gen(function* () {
664 const orchestrator = yield* Orchestrator.OrchestratorV2;
665 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
666 const selection = {
667 ...initialSelection,
668 model: mode === "active" ? initialSelection.model : "complete",
669 };
670 yield* orchestrator.dispatch({
671 type: "thread.create",
672 commandId: CommandId.make(`${name}:create`),
673 threadId,
674 projectId: ProjectId.make(`project:${name}`),
675 title: name,
676 modelSelection: selection,
677 runtimeMode: "full-access",
678 interactionMode: "default",
679 branch: null,
680 worktreePath: cwd,
681 createdBy: "user",
682 creationSource: "web",
683 });
684 const dispatch = (step: string, modelSelection: ModelSelection, targetRunId?: RunId) =>
685 Effect.gen(function* () {
686 const terminal = yield* orchestrator.streamDomainEvents.pipe(
687 Stream.filter((event) =>
688 mode === "active" && step === "first"
689 ? event.type === "provider-turn.updated" && event.payload.status === "running"
690 : event.type === "run.updated" && event.payload.status === "completed",
691 ),
692 Stream.take(1),
693 Stream.runDrain,
694 Effect.forkScoped,
695 );
696 yield* orchestrator.dispatch({
697 type: "message.dispatch",
698 commandId: CommandId.make(`${name}:${step}`),
699 threadId,
700 messageId: MessageId.make(`${name}:${step}`),
701 text: step,
702 attachments: [],
703 modelSelection,
704 dispatchMode:
705 targetRunId === undefined
706 ? { type: "start_immediately" }
707 : { type: "restart_active", targetRunId },
708 createdBy: "user",
709 creationSource: "web",
710 });
711 yield* worker.drain();
712 yield* Fiber.join(terminal);
713 yield* worker.drain();
714 return yield* orchestrator.getThreadProjection(threadId);
715 });
716 const first = yield* dispatch("first", selection);
717 const originalThread = first.providerThreads.find(
718 (thread) => thread.id === first.thread.activeProviderThreadId,
719 )!;
720 const targetSelection = { instanceId: targetId, model: "complete" };
721 if (mode === "selection-command") {
722 yield* orchestrator.dispatch({
723 type: "provider.switch",
724 commandId: CommandId.make(`${name}:switch`),
725 threadId,
726 modelSelection: targetSelection,
727 });
728 yield* worker.drain();
729 }
730 const second = yield* dispatch(
731 "second",
732 targetSelection,
733 mode === "active" ? first.runs[0]!.id : undefined,
734 );
735 const targetThread = second.providerThreads.find(
736 (thread) => thread.id === second.thread.activeProviderThreadId,
737 )!;
738 if (mode === "separate-home") {
739 assert.notEqual(targetThread.id, originalThread.id);
740 assert.lengthOf(second.contextHandoffs, 1);
741 assert.lengthOf(second.contextTransfers, 1);
742 assert.isEmpty(resumes);
743 assert.notEqual(messages[1], "second");
744 return;
745 }
746 assert.equal(targetThread.id, originalThread.id);
747 assert.deepEqual(targetThread.nativeThreadRef, originalThread.nativeThreadRef);
748 assert.equal(targetThread.providerInstanceId, targetId);
749 assert.notEqual(targetThread.providerSessionId, originalThread.providerSessionId);
750 assert.isEmpty(second.contextHandoffs);
751 assert.isEmpty(second.contextTransfers);
752 assert.deepEqual(resumes, [
753 { instanceId: targetId, nativeId: originalThread.nativeThreadRef?.nativeId },
754 ]);
755 assert.deepEqual(messages, ["first", "second"]);
756 assert.equal((yield* Ref.get(state)).closedSessionCount, mode === "pooled" ? 0 : 1);
757 if (mode === "pooled") {
758 assert.isFalse(
759 second.providerSessions.some(
760 (session) => session.id === originalThread.providerSessionId,
761 ),
762 );
763 }
764 const third = yield* dispatch("third", { ...selection, model: "complete" });
765 const returnedThread = third.providerThreads.find(
766 (thread) => thread.id === third.thread.activeProviderThreadId,
767 )!;
768 assert.equal(returnedThread.id, originalThread.id);
769 assert.deepEqual(returnedThread.nativeThreadRef, originalThread.nativeThreadRef);
770 assert.equal(returnedThread.providerInstanceId, providerInstanceId);
771 assert.isEmpty(third.contextHandoffs);
772 assert.deepEqual(messages, ["first", "second", "third"]);
773 }).pipe(Effect.provide(ProviderReplayHarness.layerWithRegistry({ name }, layerRegistry)));
774 }),
775 ),
776);