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