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

BackgroundWorkStop.integration.test.ts

931 lines34.7 KB

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