Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 EventId,
5 MessageId,
6 NodeId,
7 ProjectId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 ProviderThreadId,
11 ProviderTurnId,
12 RunAttemptId,
13 RunId,
14 ThreadId,
15 TurnItemId,
16 type OrchestrationV2DomainEvent,
17} from "@t3tools/contracts";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as Fiber from "effect/Fiber";
21import * as Queue from "effect/Queue";
22import * as Stream from "effect/Stream";
23import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
24import * as EffectWorker from "./EffectWorker.ts";
25import * as EventSink from "./EventSink.ts";
26import * as Orchestrator from "./Orchestrator.ts";
27import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
28import * as ProviderSessionManager from "./ProviderSessionManager.ts";
29import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
30import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
31import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
32
33const driver = ProviderDriverKind.make("codex");
34const instanceId = ProviderInstanceId.make("codex");
35const modelSelection = { instanceId, model: "test-model" };
36
37const stopEarlierBackgroundWork = ({
38 failedStart = false,
39 stopWithQueue,
40 olderStart = false,
41 stalledRun,
42 workflowMember = false,
43}: {
44 readonly failedStart?: boolean;
45 readonly stopWithQueue?: "thread.stop" | "run.interrupt";
46 readonly olderStart?: boolean;
47 readonly workflowMember?: boolean;
48 readonly stalledRun?:
49 | "missing-session"
50 | "missing-session-terminal"
51 | "returned-interrupt"
52 | "returned-interrupt-terminal"
53 | "superseded-attempt";
54}) =>
55 Effect.scoped(
56 Effect.gen(function* () {
57 const cwd = yield* checkpointWorkspace("background-work-stop");
58 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
59 const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
60 const interrupts: ProviderAdapter.ProviderAdapterV2InterruptInput[] = [];
61 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
62 instanceId,
63 driver,
64 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
65 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
66 openSession: (input) =>
67 Effect.gen(function* () {
68 const now = yield* DateTime.now;
69 return {
70 instanceId,
71 driver,
72 providerSessionId: input.providerSessionId,
73 providerSession: {
74 id: input.providerSessionId,
75 driver,
76 providerInstanceId: instanceId,
77 status: "ready",
78 cwd,
79 model: modelSelection.model,
80 capabilities: CodexProviderCapabilitiesV2,
81 createdAt: now,
82 updatedAt: now,
83 lastError: null,
84 },
85 events: Stream.fromQueue(events),
86 ensureThread: ({ threadId }) =>
87 Effect.succeed({
88 id: ProviderThreadId.make(`provider-thread:codex:${threadId}`),
89 driver,
90 providerInstanceId: instanceId,
91 providerSessionId: input.providerSessionId,
92 appThreadId: threadId,
93 ownerNodeId: null,
94 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
95 nativeConversationHeadRef: null,
96 status: "idle",
97 firstRunOrdinal: null,
98 lastRunOrdinal: null,
99 handoffIds: [],
100 forkedFrom: null,
101 createdAt: now,
102 updatedAt: now,
103 }),
104 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
105 startTurn: (turn) =>
106 Effect.gen(function* () {
107 started.push(turn);
108 yield* Queue.offer(events, {
109 type: "provider_turn.updated",
110 driver,
111 providerTurn: {
112 id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
113 providerThreadId: turn.providerThread.id,
114 nodeId: turn.rootNodeId,
115 runAttemptId: turn.attemptId,
116 nativeTurnRef: {
117 driver,
118 nativeId: `native:${turn.attemptId}`,
119 strength: "strong",
120 },
121 ordinal: turn.providerTurnOrdinal,
122 status: "running",
123 startedAt: now,
124 completedAt: null,
125 },
126 });
127 }),
128 steerTurn: () => Effect.die("unused"),
129 interruptTurn: (interrupt) =>
130 Effect.sync(() => {
131 interrupts.push(interrupt);
132 }),
133 respondToRuntimeRequest: () => Effect.die("unused"),
134 readThreadSnapshot: () => Effect.die("unused"),
135 rollbackThread: () => Effect.die("unused"),
136 forkThread: () => Effect.die("unused"),
137 };
138 }),
139 };
140 yield* Effect.gen(function* () {
141 const orchestrator = yield* Orchestrator.OrchestratorV2;
142 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
143 const sink = yield* EventSink.EventSinkV2;
144 const threadId = ThreadId.make("thread:background-work-stop");
145 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
146 orchestrator.streamDomainEvents.pipe(
147 Stream.filter(predicate),
148 Stream.take(1),
149 Stream.runDrain,
150 Effect.forkScoped,
151 );
152 yield* orchestrator.dispatch({
153 type: "thread.create",
154 commandId: CommandId.make("create"),
155 threadId,
156 projectId: ProjectId.make("project:background-work-stop"),
157 title: "Background work stop",
158 modelSelection,
159 runtimeMode: "full-access",
160 interactionMode: "default",
161 branch: null,
162 worktreePath: cwd,
163 createdBy: "user",
164 creationSource: "web",
165 });
166 const running = yield* watch(
167 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
168 );
169 yield* orchestrator.dispatch({
170 type: "message.dispatch",
171 commandId: CommandId.make("start-dev-server"),
172 threadId,
173 messageId: MessageId.make("message:start-dev-server"),
174 text: "Start the dev server",
175 attachments: [],
176 dispatchMode: { type: "start_immediately" },
177 createdBy: "user",
178 creationSource: "web",
179 });
180 yield* worker.drain();
181 yield* Fiber.join(running);
182 const first = started[0]!;
183 const codexTurn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
184 const devServerId = TurnItemId.make("turn-item:dev-server");
185 const now = yield* DateTime.now;
186 yield* sink.write({
187 events: [
188 {
189 id: EventId.make("dev-server"),
190 type: "turn-item.updated",
191 threadId,
192 runId: first.runId,
193 occurredAt: now,
194 payload: {
195 id: devServerId,
196 threadId,
197 runId: first.runId,
198 nodeId: first.rootNodeId,
199 providerThreadId: codexTurn.providerThreadId,
200 providerTurnId: codexTurn.id,
201 nativeItemRef: null,
202 parentItemId: null,
203 ordinal: 100,
204 status: "running",
205 title: null,
206 startedAt: now,
207 completedAt: null,
208 updatedAt: now,
209 type: "command_execution",
210 input: "vp run dev --share",
211 },
212 },
213 ],
214 });
215 if (stalledRun !== undefined) {
216 const before = yield* orchestrator.getThreadProjection(threadId);
217 const run = before.runs[0]!;
218 const node = before.nodes.find((candidate) => candidate.id === run.rootNodeId)!;
219 const attempt = before.attempts[0]!;
220 if (stalledRun === "missing-session" || stalledRun === "missing-session-terminal") {
221 const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
222 const failed = yield* watch(
223 (event) => event.type === "run.updated" && event.payload.status === "failed",
224 );
225 yield* sessions.release({
226 providerSessionId: first.providerThread.providerSessionId!,
227 reason: "runtime_error",
228 });
229 yield* Fiber.join(failed);
230 yield* sink.write({
231 events: [
232 {
233 id: EventId.make("stale-run"),
234 type: "run.updated",
235 threadId,
236 occurredAt: now,
237 payload: run,
238 },
239 {
240 id: EventId.make("stale-node"),
241 type: "node.updated",
242 threadId,
243 occurredAt: now,
244 payload: node,
245 },
246 {
247 id: EventId.make("stale-attempt"),
248 type: "run-attempt.updated",
249 threadId,
250 occurredAt: now,
251 payload: attempt,
252 },
253 ],
254 });
255 }
256 const messageId = MessageId.make("partial-output");
257 const item = before.turnItems.find((candidate) => candidate.id === devServerId)!;
258 assert.ok(item.type === "command_execution");
259 const terminalProviderTurn = stalledRun.endsWith("-terminal");
260 if (terminalProviderTurn) {
261 yield* sink.write({
262 events: [
263 {
264 id: EventId.make("terminal-provider-turn"),
265 type: "provider-turn.updated",
266 threadId,
267 occurredAt: now,
268 payload: { ...codexTurn, status: "completed", completedAt: now },
269 },
270 ...(stalledRun === "missing-session-terminal"
271 ? [
272 {
273 id: EventId.make("completed-dev-server"),
274 type: "turn-item.updated" as const,
275 threadId,
276 occurredAt: now,
277 payload: { ...item, status: "completed" as const, completedAt: now },
278 },
279 ]
280 : []),
281 ],
282 });
283 }
284 yield* sink.write({
285 events: [
286 {
287 id: EventId.make("partial-message"),
288 type: "message.updated",
289 threadId,
290 runId: run.id,
291 occurredAt: now,
292 payload: {
293 id: messageId,
294 threadId,
295 runId: run.id,
296 nodeId: node.id,
297 role: "assistant",
298 text: "Partial output",
299 attachments: [],
300 streaming: true,
301 createdBy: "agent",
302 creationSource: "provider",
303 createdAt: now,
304 updatedAt: now,
305 },
306 },
307 {
308 id: EventId.make("partial-item"),
309 type: "turn-item.updated",
310 threadId,
311 runId: run.id,
312 occurredAt: now,
313 payload: {
314 ...item,
315 providerThreadId: codexTurn.providerThreadId,
316 providerTurnId: codexTurn.id,
317 id: TurnItemId.make("partial-output"),
318 type: "assistant_message",
319 messageId,
320 text: "Partial output",
321 streaming: true,
322 },
323 },
324 ],
325 });
326 if (stalledRun === "superseded-attempt") {
327 yield* sink.write({
328 events: [
329 {
330 id: EventId.make("new-attempt"),
331 type: "run.updated",
332 threadId,
333 occurredAt: now,
334 payload: { ...run, activeAttemptId: RunAttemptId.make("new-attempt") },
335 },
336 ],
337 });
338 }
339 yield* orchestrator.dispatch(
340 stalledRun === "superseded-attempt"
341 ? {
342 type: "thread.background-work.settle",
343 commandId: CommandId.make("late-settle"),
344 threadId,
345 providerThreadId: codexTurn.providerThreadId,
346 providerTurnId: codexTurn.id,
347 }
348 : {
349 type: "thread.stop",
350 commandId: CommandId.make("stop-stalled-run"),
351 threadId,
352 },
353 );
354 yield* worker.drain();
355 const after = yield* orchestrator.getThreadProjection(threadId);
356 const interrupted = stalledRun !== "superseded-attempt";
357 assert.equal(after.runs[0]?.status, interrupted ? "interrupted" : "running");
358 assert.equal(after.attempts[0]?.status, interrupted ? "interrupted" : "running");
359 assert.equal(
360 after.providerTurns[0]?.status,
361 terminalProviderTurn ? "completed" : interrupted ? "interrupted" : "running",
362 );
363 assert.equal(
364 after.nodes.find((candidate) => candidate.id === node.id)?.status,
365 interrupted ? "interrupted" : "running",
366 );
367 const output = after.messages.find((message) => message.id === messageId)!;
368 assert.equal(output.streaming, !interrupted);
369 assert.equal(output.text, "Partial output");
370 assert.equal(
371 after.turnItems.find((candidate) => candidate.id === devServerId)?.status,
372 stalledRun === "missing-session-terminal"
373 ? "completed"
374 : interrupted
375 ? "interrupted"
376 : "running",
377 );
378 assert.equal(
379 after.turnItems.find((candidate) => candidate.type === "assistant_message")?.status,
380 interrupted ? "interrupted" : "running",
381 );
382 assert.equal(
383 after.turnItems.filter((candidate) => candidate.type === "run_interrupt_result").length,
384 interrupted ? 1 : 0,
385 );
386 assert.isEmpty(after.runs.filter((candidate) => candidate.status === "waiting"));
387 return;
388 }
389 const settled = yield* watch(
390 (event) =>
391 event.type === "run.updated" &&
392 event.payload.id === first.runId &&
393 event.payload.status === "waiting",
394 );
395 yield* Queue.offer(events, {
396 type: "provider_turn.updated",
397 driver,
398 providerTurn: { ...codexTurn, status: "completed", completedAt: now },
399 });
400 yield* Queue.offer(events, {
401 type: "turn.terminal",
402 driver,
403 providerThreadId: codexTurn.providerThreadId,
404 providerTurnId: codexTurn.id,
405 runOrdinal: first.runOrdinal,
406 status: "completed",
407 failure: null,
408 threadDisposition: "reusable",
409 });
410 yield* Fiber.join(settled);
411 yield* worker.drain();
412
413 const codexProviderThread = (yield* orchestrator.getThreadProjection(threadId))
414 .providerThreads[0]!;
415 const subagentThread = (name: string) =>
416 Effect.gen(function* () {
417 const subagentThreadId = ThreadId.make(`thread:${name}`);
418 const rootId = NodeId.make(`node:${name}-root`);
419 yield* orchestrator.dispatch({
420 type: "thread.create",
421 commandId: CommandId.make(`create-${name}`),
422 threadId: subagentThreadId,
423 projectId: ProjectId.make("project:background-work-stop"),
424 title: name,
425 modelSelection,
426 runtimeMode: "full-access",
427 interactionMode: "default",
428 branch: null,
429 worktreePath: cwd,
430 createdBy: "agent",
431 creationSource: "provider",
432 });
433 yield* sink.write({
434 events: [
435 {
436 id: EventId.make(`${name}-root`),
437 type: "node.updated",
438 threadId: subagentThreadId,
439 occurredAt: now,
440 payload: {
441 id: rootId,
442 threadId: subagentThreadId,
443 runId: null,
444 parentNodeId: null,
445 rootNodeId: rootId,
446 kind: "root_turn",
447 status: "running",
448 countsForRun: false,
449 providerThreadId: null,
450 providerTurnId: null,
451 nativeItemRef: null,
452 runtimeRequestId: null,
453 checkpointScopeId: null,
454 startedAt: now,
455 completedAt: null,
456 },
457 },
458 ],
459 });
460 return { threadId: subagentThreadId, rootId };
461 });
462 const { threadId: reviewerThreadId, rootId: reviewerRootId } =
463 yield* subagentThread("reviewer");
464 const tester = yield* subagentThread("tester");
465 const nestedSubagentId = NodeId.make("subagent:nested");
466 const nestedItemId = TurnItemId.make("turn-item:nested-subagent");
467 const nested = {
468 threadId: reviewerThreadId,
469 runId: null,
470 origin: "provider_native",
471 driver,
472 providerInstanceId: instanceId,
473 providerThreadId: null,
474 childThreadId: tester.threadId,
475 prompt: "Check the tests",
476 title: null,
477 status: "running",
478 result: null,
479 startedAt: now,
480 completedAt: null,
481 updatedAt: now,
482 } as const;
483 yield* sink.write({
484 events: [
485 ...(workflowMember
486 ? []
487 : [
488 {
489 id: EventId.make("nested-subagent-item"),
490 type: "turn-item.updated",
491 threadId: reviewerThreadId,
492 occurredAt: now,
493 payload: {
494 ...nested,
495 id: nestedItemId,
496 nodeId: nestedSubagentId,
497 providerTurnId: null,
498 nativeItemRef: null,
499 parentItemId: null,
500 ordinal: 1,
501 type: "subagent",
502 subagentId: nestedSubagentId,
503 },
504 } as const,
505 ]),
506 {
507 id: EventId.make("nested-subagent"),
508 type: "subagent.updated",
509 threadId: reviewerThreadId,
510 occurredAt: now,
511 payload: {
512 ...nested,
513 id: nestedSubagentId,
514 parentNodeId: reviewerRootId,
515 createdBy: "agent",
516 nativeTaskRef: workflowMember
517 ? { driver, nativeId: "workflow:member", strength: "strong" }
518 : null,
519 model: null,
520 },
521 },
522 ],
523 });
524 if (workflowMember) {
525 const memberRoot = (yield* orchestrator.getThreadProjection(tester.threadId)).nodes[0]!;
526 yield* sink.write({
527 events: [
528 {
529 id: EventId.make("workflow-member-node"),
530 type: "node.updated",
531 threadId: reviewerThreadId,
532 occurredAt: now,
533 payload: {
534 ...memberRoot,
535 id: nestedSubagentId,
536 threadId: reviewerThreadId,
537 parentNodeId: reviewerRootId,
538 rootNodeId: reviewerRootId,
539 kind: "subagent",
540 },
541 },
542 ],
543 });
544 }
545 const settledRun = (input: {
546 readonly ordinal: number;
547 readonly providerThreadId: ProviderThreadId;
548 readonly runningItem?: {
549 readonly id: TurnItemId;
550 readonly kind: "command" | "subagent";
551 };
552 }) => {
553 const runId = RunId.make(`run:${input.ordinal}`);
554 const attemptId = RunAttemptId.make(`attempt:${input.ordinal}`);
555 const nodeId = NodeId.make(`node:${input.ordinal}`);
556 const providerTurnId = ProviderTurnId.make(`provider-turn:${input.ordinal}`);
557 const events: Array<OrchestrationV2DomainEvent> = [
558 {
559 id: EventId.make(`run:${input.ordinal}`),
560 type: "run.created",
561 threadId,
562 occurredAt: now,
563 payload: {
564 id: runId,
565 threadId,
566 ordinal: input.ordinal,
567 providerInstanceId: instanceId,
568 modelSelection,
569 providerThreadId: input.providerThreadId,
570 userMessageId: MessageId.make(`message:${input.ordinal}`),
571 rootNodeId: nodeId,
572 activeAttemptId: attemptId,
573 status: "completed",
574 requestedAt: now,
575 startedAt: now,
576 completedAt: now,
577 checkpointId: null,
578 contextHandoffId: null,
579 },
580 },
581 {
582 id: EventId.make(`node:${input.ordinal}`),
583 type: "node.updated",
584 threadId,
585 runId,
586 occurredAt: now,
587 payload: {
588 id: nodeId,
589 threadId,
590 runId,
591 parentNodeId: null,
592 rootNodeId: nodeId,
593 kind: "root_turn",
594 status: "completed",
595 countsForRun: true,
596 providerThreadId: input.providerThreadId,
597 providerTurnId,
598 nativeItemRef: null,
599 runtimeRequestId: null,
600 checkpointScopeId: null,
601 startedAt: now,
602 completedAt: now,
603 },
604 },
605 {
606 id: EventId.make(`attempt:${input.ordinal}`),
607 type: "run-attempt.created",
608 threadId,
609 occurredAt: now,
610 payload: {
611 id: attemptId,
612 runId,
613 attemptOrdinal: 1,
614 rootNodeId: nodeId,
615 providerInstanceId: instanceId,
616 providerThreadId: input.providerThreadId,
617 providerTurnId,
618 reason: "initial",
619 status: "completed",
620 startedAt: now,
621 completedAt: now,
622 },
623 },
624 {
625 id: EventId.make(`provider-turn:${input.ordinal}`),
626 type: "provider-turn.updated",
627 threadId,
628 occurredAt: now,
629 payload: {
630 id: providerTurnId,
631 providerThreadId: input.providerThreadId,
632 nodeId,
633 runAttemptId: attemptId,
634 nativeTurnRef: null,
635 ordinal: input.ordinal,
636 status: "completed",
637 startedAt: now,
638 completedAt: now,
639 },
640 },
641 ];
642 const item = input.runningItem;
643 if (item !== undefined) {
644 const base = {
645 id: item.id,
646 threadId,
647 runId,
648 nodeId,
649 providerThreadId: input.providerThreadId,
650 providerTurnId,
651 nativeItemRef: null,
652 parentItemId: null,
653 ordinal: input.ordinal * 100,
654 status: "running",
655 title: null,
656 startedAt: now,
657 completedAt: null,
658 updatedAt: now,
659 } as const;
660 events.push({
661 id: EventId.make(`item:${input.ordinal}`),
662 type: "turn-item.updated",
663 threadId,
664 runId,
665 occurredAt: now,
666 payload:
667 item.kind === "command"
668 ? { ...base, type: "command_execution", input: "vp run test --watch" }
669 : {
670 ...base,
671 providerThreadId: ProviderThreadId.make("provider-thread:codex-subagent"),
672 type: "subagent",
673 subagentId: NodeId.make(`subagent:${input.ordinal}`),
674 origin: "provider_native",
675 driver,
676 providerInstanceId: instanceId,
677 childThreadId: reviewerThreadId,
678 prompt: "Review the change",
679 result: null,
680 },
681 });
682 if (item.kind === "subagent") {
683 events.push({
684 id: EventId.make(`subagent:${input.ordinal}`),
685 type: "subagent.updated",
686 threadId,
687 runId,
688 occurredAt: now,
689 payload: {
690 ...base,
691 id: NodeId.make(`subagent:${input.ordinal}`),
692 parentNodeId: nodeId,
693 origin: "provider_native",
694 createdBy: "agent",
695 driver,
696 providerInstanceId: instanceId,
697 providerThreadId: null,
698 childThreadId: reviewerThreadId,
699 nativeTaskRef: null,
700 prompt: "Review the change",
701 model: null,
702 result: null,
703 },
704 });
705 }
706 }
707 return { runId, providerTurnId, events };
708 };
709
710 const watcherId = TurnItemId.make("turn-item:watcher");
711 const otherProviderThreadId = ProviderThreadId.make("provider-thread:other");
712 const watcherRun = settledRun({
713 ordinal: 2,
714 providerThreadId: olderStart ? otherProviderThreadId : codexProviderThread.id,
715 ...(olderStart ? {} : { runningItem: { id: watcherId, kind: "command" as const } }),
716 });
717 const reviewerId = TurnItemId.make("turn-item:reviewer");
718 const reviewerRun = settledRun({
719 ordinal: 3,
720 providerThreadId: codexProviderThread.id,
721 runningItem: { id: reviewerId, kind: "subagent" },
722 });
723 const latestRun = settledRun({ ordinal: 4, providerThreadId: otherProviderThreadId });
724 yield* sink.write({
725 events: [
726 ...watcherRun.events,
727 ...reviewerRun.events,
728 {
729 id: EventId.make("provider-thread:other"),
730 type: "provider-thread.updated",
731 threadId,
732 occurredAt: now,
733 payload: {
734 ...codexProviderThread,
735 id: otherProviderThreadId,
736 firstRunOrdinal: 4,
737 lastRunOrdinal: 4,
738 },
739 },
740 ...latestRun.events,
741 ],
742 });
743
744 const failedRun = settledRun({ ordinal: 5, providerThreadId: otherProviderThreadId });
745 if (failedStart) {
746 yield* sink.write({
747 events: failedRun.events.flatMap((event): Array<OrchestrationV2DomainEvent> => {
748 switch (event.type) {
749 case "provider-turn.updated":
750 return [];
751 case "run.created":
752 return [{ ...event, payload: { ...event.payload, status: "failed" } }];
753 case "node.updated":
754 return [
755 {
756 ...event,
757 payload: { ...event.payload, status: "failed", providerTurnId: null },
758 },
759 ];
760 case "run-attempt.created":
761 return [
762 {
763 ...event,
764 payload: { ...event.payload, status: "failed", providerTurnId: null },
765 },
766 ];
767 default:
768 return [event];
769 }
770 }),
771 });
772 }
773
774 if (stopWithQueue !== undefined) {
775 const owner = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
776 (run) => run.id === latestRun.runId,
777 )!;
778 yield* sink.write({
779 events: [
780 {
781 id: EventId.make("latest-run-waiting"),
782 type: "run.updated",
783 threadId,
784 runId: owner.id,
785 occurredAt: now,
786 payload: { ...owner, status: "waiting", completedAt: null },
787 },
788 ],
789 });
790 yield* orchestrator.dispatch({
791 type: "message.dispatch",
792 commandId: CommandId.make("queue-follow-up"),
793 threadId,
794 messageId: MessageId.make("message:queue-follow-up"),
795 text: "Follow up after the background work",
796 attachments: [],
797 dispatchMode: { type: "queue_after_active" },
798 createdBy: "user",
799 creationSource: "web",
800 });
801 const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
802 assert.equal(queued.status, "queued");
803 yield* sink.write({
804 events: [
805 {
806 id: EventId.make("queue-held"),
807 type: "run.updated",
808 threadId,
809 runId: queued.id,
810 occurredAt: now,
811 payload: { ...queued, queueHeld: true },
812 },
813 {
814 id: EventId.make("latest-run-settled"),
815 type: "run.updated",
816 threadId,
817 runId: owner.id,
818 occurredAt: now,
819 payload: owner,
820 },
821 ],
822 });
823 }
824
825 if (olderStart) {
826 const older = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
827 (run) => run.id === watcherRun.runId,
828 )!;
829 yield* sink.write({
830 events: [
831 {
832 id: EventId.make("older-run-starting"),
833 type: "run.updated",
834 threadId,
835 runId: older.id,
836 occurredAt: now,
837 payload: { ...older, status: "starting", startedAt: null, completedAt: null },
838 },
839 ],
840 });
841 }
842
843 yield* orchestrator.dispatch(
844 stopWithQueue === "thread.stop"
845 ? {
846 type: "thread.stop",
847 commandId: CommandId.make("stop-background-work"),
848 threadId,
849 }
850 : {
851 type: "run.interrupt",
852 commandId: CommandId.make("stop-background-work"),
853 threadId,
854 runId: olderStart
855 ? watcherRun.runId
856 : failedStart
857 ? failedRun.runId
858 : latestRun.runId,
859 ...(stopWithQueue === undefined ? {} : { holdQueue: true }),
860 },
861 );
862 yield* worker.drain();
863
864 assert.sameDeepMembers(
865 interrupts.map((interrupt) => [interrupt.providerThread.id, interrupt.providerTurnId]),
866 [
867 ...(olderStart ? [] : [[otherProviderThreadId, latestRun.providerTurnId]]),
868 [codexProviderThread.id, reviewerRun.providerTurnId],
869 ],
870 );
871 const after = yield* orchestrator.getThreadProjection(threadId);
872 if (olderStart) {
873 assert.equal(
874 after.runs.find((run) => run.id === watcherRun.runId)?.status,
875 "interrupted",
876 );
877 }
878 if (stopWithQueue !== undefined) {
879 assert.equal(after.runs.at(-1)?.status, "queued");
880 assert.equal(after.runs.at(-1)?.queueHeld, true);
881 assert.lengthOf(started, 1);
882 }
883 assert.deepEqual(
884 [devServerId, ...(olderStart ? [] : [watcherId]), reviewerId].map(
885 (id) => after.turnItems.find((item) => item.id === id)?.status,
886 ),
887 olderStart
888 ? ["interrupted", "interrupted"]
889 : ["interrupted", "interrupted", "interrupted"],
890 );
891 assert.equal(after.subagents[0]?.status, "interrupted");
892 const reviewerThread = yield* orchestrator.getThreadProjection(reviewerThreadId);
893 assert.equal(reviewerThread.nodes[0]?.status, "interrupted");
894 assert.equal(reviewerThread.subagents[0]?.status, "interrupted");
895 if (workflowMember) {
896 assert.isUndefined(reviewerThread.turnItems.find((item) => item.id === nestedItemId));
897 assert.equal(
898 reviewerThread.nodes.find((node) => node.id === nestedSubagentId)?.status,
899 "interrupted",
900 );
901 } else {
902 assert.equal(
903 reviewerThread.turnItems.find((item) => item.id === nestedItemId)?.status,
904 "interrupted",
905 );
906 }
907 const testerThread = yield* orchestrator.getThreadProjection(tester.threadId);
908 assert.equal(testerThread.nodes[0]?.status, "interrupted");
909 }).pipe(
910 Effect.provide(
911 ProviderReplayHarness.layerWithRegistry(
912 { name: "background-work-stop" },
913 ProviderAdapterRegistry.layerSingle(adapter),
914 { runEffectWorker: false },
915 ),
916 ),
917 );
918 }),
919 );
920
921it.effect("Stop reaches background work an earlier provider thread still runs", () =>
922 stopEarlierBackgroundWork({}),
923);
924
925it.effect("Stop settles workflow members without subagent turn items", () =>
926 stopEarlierBackgroundWork({ workflowMember: true }),
927);
928
929it.effect(
930 "Stop reaches earlier background work after the newest run fails before provider start",
931 () => stopEarlierBackgroundWork({ failedStart: true }),
932);
933
934it.effect.each(["thread.stop", "run.interrupt"] as const)(
935 "%s stops background work when a later message is queued",
936 (stopType) => stopEarlierBackgroundWork({ stopWithQueue: stopType }),
937);
938
939it.effect.each(["thread.stop", "run.interrupt"] as const)(
940 "%s reaches later background work when an older run is starting",
941 (stopType) => stopEarlierBackgroundWork({ stopWithQueue: stopType, olderStart: true }),
942);
943
944it.effect.each([
945 "missing-session",
946 "missing-session-terminal",
947 "returned-interrupt",
948 "returned-interrupt-terminal",
949 "superseded-attempt",
950] as const)("Stop recovers a stalled run after %s without changing a newer attempt", (stalledRun) =>
951 stopEarlierBackgroundWork({ stalledRun }),
952);