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