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

ProviderRuntimeRecoveryService.test.ts

1,453 lines50.9 KB

1import { assert, it, vi } from "@effect/vitest";
2import {
3 MessageId,
4 NodeId,
5 ProviderDriverKind,
6 ProviderInstanceId,
7 ProviderSessionId,
8 ProviderThreadId,
9 ProviderTurnId,
10 RunAttemptId,
11 RunId,
12 RuntimeRequestId,
13 ThreadId,
14 TurnItemId,
15 type OrchestrationV2ThreadProjection,
16} from "@t3tools/contracts";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19​
20import * as EffectWorker from "./EffectWorker.ts";
21import * as EffectOutbox from "./EffectOutbox.ts";
22import * as EventSink from "./EventSink.ts";
23import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
24import * as ProjectionStore from "./ProjectionStore.ts";
25import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
26import * as ServerSettings from "../serverSettings.ts";
27​
28it.effect("expires orphaned runtime requests before command readiness", () => {
29 const threadId = ThreadId.make("thread_recovery_requests");
30 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
31 null;
32 const committed = vi.fn(
33 (input: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0]) => {
34 committedInput = input;
35 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
36 },
37 );
38 const projection = {
39 thread: { id: threadId },
40 runtimeRequests: [
41 {
42 id: RuntimeRequestId.make("request_orphaned"),
43 nodeId: NodeId.make("node_orphaned"),
44 status: "pending",
45 responseCapability: { type: "not_resumable", reason: "old process" },
46 },
47 ],
48 providerSessions: [],
49 providerThreads: [],
50 runs: [],
51 nodes: [],
52 } as unknown as OrchestrationV2ThreadProjection;
53 const layer = ProviderRuntimeRecovery.layer.pipe(
54 Layer.provide(ServerSettings.layerTest()),
55 Layer.provide(
56 Layer.mergeAll(
57 Layer.mock(ProjectionStore.ProjectionStoreV2)({
58 getRecoveryThreadIds: () => Effect.succeed([threadId]),
59 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
60 }),
61 Layer.mock(EventSink.EventSinkV2)({ commitCommand: committed }),
62 IdAllocator.layer,
63 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
64 runRecoveryOnce: Effect.succeed(false),
65 }),
66 Layer.mock(EffectOutbox.EffectOutboxV2)({
67 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
68 }),
69 ),
70 ),
71 );
72 return Effect.gen(function* () {
73 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).recover;
74 const command = committedInput;
75 assert.isNotNull(command);
76 if (command === null) return;
77 assert.equal(command?.events[0]?.type, "runtime-request.updated");
78 if (command?.events[0]?.type === "runtime-request.updated") {
79 assert.equal(command.events[0].payload.status, "expired");
80 assert.equal(command.events[0].payload.responseCapability.type, "not_resumable");
81 }
82 }).pipe(Effect.provide(layer));
83});
84​
85it.effect("preserves async questions across startup and shutdown", () => {
86 const threadId = ThreadId.make("async-recovery-thread");
87 const nodeId = NodeId.make("async-recovery-node");
88 const projection = {
89 thread: { id: threadId },
90 runtimeRequests: [
91 {
92 id: RuntimeRequestId.make("async-recovery-request"),
93 nodeId,
94 status: "pending",
95 responseCapability: { type: "message" },
96 },
97 ],
98 providerSessions: [],
99 providerThreads: [],
100 runs: [],
101 nodes: [],
102 turnItems: [],
103 } as unknown as OrchestrationV2ThreadProjection;
104 const commitCommand = vi.fn(() => Effect.die("an async question needs no process-loss write"));
105 const layer = ProviderRuntimeRecovery.layer.pipe(
106 Layer.provide(ServerSettings.layerTest()),
107 Layer.provide(
108 Layer.mergeAll(
109 Layer.mock(ProjectionStore.ProjectionStoreV2)({
110 getRecoveryThreadIds: () => Effect.succeed([threadId]),
111 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
112 }),
113 Layer.mock(EventSink.EventSinkV2)({ commitCommand }),
114 IdAllocator.layer,
115 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
116 runRecoveryOnce: Effect.succeed(false),
117 }),
118 Layer.mock(EffectOutbox.EffectOutboxV2)({
119 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
120 cancelUnsettled: () => Effect.succeed([]),
121 signalCancellations: () => Effect.void,
122 }),
123 ),
124 ),
125 );
126 return Effect.gen(function* () {
127 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
128 assert.equal((yield* recovery.reconcile("startup")).closedRequests, 0);
129 assert.equal((yield* recovery.reconcile("startup")).closedRequests, 0);
130 assert.isFalse(commitCommand.mock.calls.length > 0);
131 }).pipe(Effect.provide(layer));
132});
133​
134it.effect(
135 "preserves a replayable waiting run while cancelling its process-bound background work",
136 () => {
137 const threadId = ThreadId.make("thread_waiting_checkpoint");
138 const runId = RunId.make("run_waiting_checkpoint");
139 const providerThreadId = ProviderThreadId.make("provider_thread_waiting_checkpoint");
140 const providerInstanceId = ProviderInstanceId.make("claude");
141 const backgroundItemId = TurnItemId.make("turn_item_waiting_checkpoint");
142 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
143 null;
144 const projection = {
145 thread: { id: threadId },
146 runtimeRequests: [],
147 providerSessions: [],
148 providerThreads: [
149 {
150 id: providerThreadId,
151 driver: ProviderDriverKind.make("claude"),
152 providerInstanceId,
153 status: "idle",
154 pendingBackgroundTasks: [
155 { taskId: String(backgroundItemId), description: "Finish background task" },
156 ],
157 },
158 ],
159 runs: [{ id: runId, status: "waiting", providerInstanceId, providerThreadId }],
160 attempts: [],
161 nodes: [],
162 subagents: [],
163 messages: [],
164 turnItems: [
165 {
166 id: backgroundItemId,
167 runId,
168 nodeId: null,
169 providerThreadId,
170 type: "command_execution",
171 status: "running",
172 },
173 ],
174 } as unknown as OrchestrationV2ThreadProjection;
175 const layer = ProviderRuntimeRecovery.layer.pipe(
176 Layer.provide(ServerSettings.layerTest()),
177 Layer.provide(
178 Layer.mergeAll(
179 Layer.mock(ProjectionStore.ProjectionStoreV2)({
180 getRecoveryThreadIds: () => Effect.succeed([threadId]),
181 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
182 }),
183 Layer.mock(EventSink.EventSinkV2)({
184 commitCommand: (input) => {
185 committedInput = input;
186 return Effect.succeed({
187 committed: true,
188 cancelledEffectCount: 0,
189 } as never);
190 },
191 }),
192 IdAllocator.layer,
193 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
194 runRecoveryOnce: Effect.succeed(false),
195 }),
196 Layer.mock(EffectOutbox.EffectOutboxV2)({
197 listByCommandId: () =>
198 Effect.succeed([
199 {
200 request: { type: "checkpoint.capture", runId },
201 status: "running",
202 },
203 ] as never),
204 reconcileAfterProcessLoss: Effect.succeed({ requeued: 1, cancelled: 0 }),
205 }),
206 ),
207 ),
208 );
209​
210 return Effect.gen(function* () {
211 const summary =
212 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
213 assert.equal(summary.terminalizedRuns, 0);
214 assert.equal(summary.requeuedEffects, 1);
215​
216 const command = committedInput;
217 assert.isNotNull(command);
218 if (command === null) return;
219​
220 assert.isFalse(command.events.some((event) => event.type === "run.updated"));
221 const recorded = command.events.flatMap((event) =>
222 event.type === "run.background-work-cancelled" ? [event.payload] : [],
223 );
224​
225 assert.deepEqual(
226 recorded.map((entry) => ({
227 runId: entry.runId,
228 kinds: entry.restartCancelledBackgroundWork.map((work) => work.kind),
229 })),
230 [{ runId, kinds: ["shell"] }],
231 );
232 assert.isTrue(
233 command.events.some(
234 (event) =>
235 event.type === "turn-item.updated" &&
236 event.payload.id === backgroundItemId &&
237 event.payload.status === "cancelled",
238 ),
239 );
240 assert.isTrue(
241 command.events.some(
242 (event) =>
243 event.type === "provider-thread.updated" &&
244 event.payload.id === providerThreadId &&
245 event.payload.pendingBackgroundTasks?.length === 0,
246 ),
247 );
248 }).pipe(Effect.provide(layer));
249 },
250);
251​
252it.effect(
253 "records cancelled work on the provider thread that lost it after a provider switch",
254 () => {
255 const threadId = ThreadId.make("thread_switch_note");
256 const claudeRunId = RunId.make("run_switch_note_claude");
257 const codexRunId = RunId.make("run_switch_note_codex");
258 const claudeThreadId = ProviderThreadId.make("provider_thread_switch_note_claude");
259 const codexThreadId = ProviderThreadId.make("provider_thread_switch_note_codex");
260 const claude = ProviderInstanceId.make("claude");
261 const codex = ProviderInstanceId.make("codex");
262 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
263 null;
264​
265 const projection = {
266 thread: { id: threadId },
267 runtimeRequests: [],
268 providerSessions: [],
269 providerThreads: [
270 {
271 id: claudeThreadId,
272 ownerNodeId: null,
273 driver: ProviderDriverKind.make("claudeAgent"),
274 providerInstanceId: claude,
275 status: "idle",
276 pendingBackgroundTasks: [{ taskId: "task-claude", description: "Watch the build" }],
277 },
278 {
279 id: codexThreadId,
280 ownerNodeId: null,
281 driver: ProviderDriverKind.make("codex"),
282 providerInstanceId: codex,
283 status: "idle",
284 },
285 ],
286 providerTurns: [],
287 runs: [
288 {
289 id: claudeRunId,
290 ordinal: 1,
291 status: "completed",
292 providerInstanceId: claude,
293 providerThreadId: claudeThreadId,
294 },
295 {
296 id: codexRunId,
297 ordinal: 2,
298 status: "completed",
299 providerInstanceId: codex,
300 providerThreadId: codexThreadId,
301 },
302 ],
303 attempts: [],
304 nodes: [],
305 subagents: [],
306 messages: [],
307 turnItems: [
308 {
309 id: TurnItemId.make("turn_item_switch_note_subagent"),
310 runId: claudeRunId,
311 nodeId: null,
312 providerThreadId: claudeThreadId,
313 nativeItemRef: null,
314 type: "subagent",
315 title: "Background subagent",
316 status: "running",
317 },
318 ],
319 } as unknown as OrchestrationV2ThreadProjection;
320 const layer = ProviderRuntimeRecovery.layer.pipe(
321 Layer.provide(ServerSettings.layerTest()),
322 Layer.provide(
323 Layer.mergeAll(
324 Layer.mock(ProjectionStore.ProjectionStoreV2)({
325 getRecoveryThreadIds: () => Effect.succeed([threadId]),
326 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
327 }),
328 Layer.mock(EventSink.EventSinkV2)({
329 commitCommand: (input) => {
330 committedInput = input;
331 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
332 },
333 }),
334 IdAllocator.layer,
335 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
336 runRecoveryOnce: Effect.succeed(false),
337 }),
338 Layer.mock(EffectOutbox.EffectOutboxV2)({
339 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
340 }),
341 ),
342 ),
343 );
344​
345 return Effect.gen(function* () {
346 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
347 const recorded = (committedInput?.events ?? []).flatMap((event) =>
348 event.type === "run.background-work-cancelled" ? [event.payload] : [],
349 );
350​
351 assert.deepEqual(
352 recorded.map((entry) => ({
353 runId: entry.runId,
354 kinds: entry.restartCancelledBackgroundWork.map((work) => work.kind),
355 })),
356 [{ runId: claudeRunId, kinds: ["subagent", "task"] }],
357 );
358 }).pipe(Effect.provide(layer));
359 },
360);
361​
362it.effect("cancels a stale waiting run when no checkpoint capture can finish it", () => {
363 const threadId = ThreadId.make("thread_stale_waiting");
364 const runId = RunId.make("run_stale_waiting");
365 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
366 null;
367 const projection = {
368 thread: { id: threadId },
369 runtimeRequests: [],
370 providerSessions: [],
371 providerThreads: [],
372 providerTurns: [],
373 runs: [
374 {
375 id: runId,
376 status: "waiting",
377 providerInstanceId: ProviderInstanceId.make("codex"),
378 },
379 ],
380 attempts: [],
381 nodes: [],
382 subagents: [],
383 messages: [],
384 turnItems: [],
385 } as unknown as OrchestrationV2ThreadProjection;
386 const layer = ProviderRuntimeRecovery.layer.pipe(
387 Layer.provide(ServerSettings.layerTest()),
388 Layer.provide(
389 Layer.mergeAll(
390 Layer.mock(ProjectionStore.ProjectionStoreV2)({
391 getRecoveryThreadIds: () => Effect.succeed([threadId]),
392 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
393 }),
394 Layer.mock(EventSink.EventSinkV2)({
395 commitCommand: (input) => {
396 committedInput = input;
397 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
398 },
399 }),
400 IdAllocator.layer,
401 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
402 runRecoveryOnce: Effect.succeed(false),
403 }),
404 Layer.mock(EffectOutbox.EffectOutboxV2)({
405 listByCommandId: () => Effect.succeed([]),
406 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
407 }),
408 ),
409 ),
410 );
411​
412 return Effect.gen(function* () {
413 const summary =
414 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
415 assert.equal(summary.terminalizedRuns, 1);
416 const runEvent = committedInput?.events.find((event) => event.type === "run.updated");
417 assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.status : null, "cancelled");
418 }).pipe(Effect.provide(layer));
419});
420​
421it.effect("recovery closes a secret card's form but leaves a link card open", () => {
422 const threadId = ThreadId.make("thread_secret_recovery");
423 const runId = RunId.make("run_secret_recovery");
424 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
425 null;
426 const projection = {
427 thread: { id: threadId },
428 runtimeRequests: [],
429 providerSessions: [],
430 providerThreads: [],
431 providerTurns: [],
432 runs: [{ id: runId, status: "running", providerInstanceId: ProviderInstanceId.make("codex") }],
433 attempts: [],
434 nodes: [],
435 subagents: [],
436 messages: [],
437 turnItems: [
438 {
439 id: "turn-item:secret-request:recovery",
440 threadId,
441 runId,
442 nodeId: null,
443 type: "secret_request",
444 status: "waiting",
445 secretStatus: "pending",
446 label: "GitHub token",
447 reason: "Used as GH_TOKEN.",
448 },
449 {
450 id: "turn-item:link-request:recovery",
451 threadId,
452 runId,
453 nodeId: null,
454 type: "link_request",
455 status: "waiting",
456 linkStatus: "pending",
457 url: "https://box.example.ts.net",
458 reason: "Run the suite there.",
459 },
460 ],
461 } as unknown as OrchestrationV2ThreadProjection;
462 const layer = ProviderRuntimeRecovery.layer.pipe(
463 Layer.provide(ServerSettings.layerTest()),
464 Layer.provide(
465 Layer.mergeAll(
466 Layer.mock(ProjectionStore.ProjectionStoreV2)({
467 getRecoveryThreadIds: () => Effect.succeed([threadId]),
468 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
469 }),
470 Layer.mock(EventSink.EventSinkV2)({
471 commitCommand: (input) => {
472 committedInput = input;
473 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
474 },
475 }),
476 IdAllocator.layer,
477 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
478 runRecoveryOnce: Effect.succeed(false),
479 }),
480 Layer.mock(EffectOutbox.EffectOutboxV2)({
481 listByCommandId: () => Effect.succeed([]),
482 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
483 }),
484 ),
485 ),
486 );
487​
488 return Effect.gen(function* () {
489 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
490 const cards = (committedInput?.events ?? []).flatMap((event) =>
491 event.type === "turn-item.updated" ? [event.payload] : [],
492 );
493 const secret = cards.find((card) => card.type === "secret_request");
494 assert.equal(secret?.status, "cancelled");
495 assert.equal(secret?.type === "secret_request" ? secret.secretStatus : null, "cancelled");
496 // Nothing in memory waits on a link card; the user can still answer it.
497 assert.equal(
498 cards.some((card) => card.type === "link_request"),
499 false,
500 );
501 }).pipe(Effect.provide(layer));
502});
503​
504it.effect.each(["queued", "preparing"] as const)("recovers $0 work after restart", (status) => {
505 const threadId = ThreadId.make("thread_queued_restart");
506 const runId = RunId.make("run_queued_restart");
507 const attemptId = RunAttemptId.make("attempt_queued_restart");
508 const rootNodeId = NodeId.make("node_queued_restart");
509 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
510 null;
511 const projection = {
512 thread: { id: threadId },
513 runtimeRequests: [],
514 providerSessions: [],
515 providerThreads: [],
516 providerTurns: [],
517 runs: [
518 {
519 id: runId,
520 status,
521 queuePosition: 1,
522 providerInstanceId: ProviderInstanceId.make("codex"),
523 ...(status === "preparing"
524 ? {
525 workspacePreparation: {
526 type: "worktree",
527 baseRef: "parent-local-commit",
528 startFromOrigin: false,
529 },
530 }
531 : {}),
532 },
533 ],
534 attempts: [
535 {
536 id: attemptId,
537 runId,
538 rootNodeId,
539 status: "pending",
540 },
541 ],
542 nodes: [
543 {
544 id: rootNodeId,
545 runId,
546 status: "pending",
547 },
548 ],
549 subagents: [],
550 messages: [],
551 turnItems: [],
552 } as unknown as OrchestrationV2ThreadProjection;
553 const layer = ProviderRuntimeRecovery.layer.pipe(
554 Layer.provide(ServerSettings.layerTest()),
555 Layer.provide(
556 Layer.mergeAll(
557 Layer.mock(ProjectionStore.ProjectionStoreV2)({
558 getRecoveryThreadIds: () => Effect.succeed([threadId]),
559 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
560 getThreadRecords: () => Effect.succeed(projection),
561 }),
562 Layer.mock(EventSink.EventSinkV2)({
563 commitCommand: (input) => {
564 committedInput = input;
565 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
566 },
567 }),
568 IdAllocator.layer,
569 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
570 runRecoveryOnce: Effect.succeed(false),
571 }),
572 Layer.mock(EffectOutbox.EffectOutboxV2)({
573 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
574 }),
575 ),
576 ),
577 );
578​
579 return Effect.gen(function* () {
580 const summary =
581 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
582 assert.equal(summary.terminalizedRuns, status === "preparing" ? 1 : 0);
583 const command = committedInput;
584 assert.isNotNull(command);
585 if (command === null) return;
586 const runEvent = command.events.find((event) => event.type === "run.updated");
587 const attemptEvent = command.events.find((event) => event.type === "run-attempt.updated");
588 const nodeEvent = command.events.find((event) => event.type === "node.updated");
589 assert.equal(
590 runEvent?.type === "run.updated" ? runEvent.payload.status : null,
591 status === "preparing" ? "cancelled" : "queued",
592 );
593 assert.isEmpty(command.effects);
594 if (status === "preparing") {
595 assert.equal(
596 attemptEvent?.type === "run-attempt.updated" ? attemptEvent.payload.status : null,
597 "cancelled",
598 );
599 assert.equal(
600 nodeEvent?.type === "node.updated" ? nodeEvent.payload.status : null,
601 "cancelled",
602 );
603 } else {
604 assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.queuePosition : null, 1);
605 assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.queueHeld : false, true);
606 assert.isUndefined(attemptEvent);
607 assert.isUndefined(nodeEvent);
608 }
609 }).pipe(Effect.provide(layer));
610});
611​
612it.effect(
613 "cancels the complete in-flight subtree and stops its persisted session without reopening it",
614 () => {
615 const threadId = ThreadId.make("thread_recovery_cancel");
616 const runId = RunId.make("run_recovery_cancel");
617 const attemptId = RunAttemptId.make("attempt_recovery_cancel");
618 const rootNodeId = NodeId.make("node_recovery_cancel");
619 const providerThreadId = ProviderThreadId.make("provider_thread_recovery_cancel");
620 const providerTurnId = ProviderTurnId.make("provider_turn_recovery_cancel");
621 const providerSessionId = ProviderSessionId.make("provider_session_recovery_cancel");
622 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
623 null;
624 const projection = {
625 thread: { id: threadId },
626 runtimeRequests: [],
627 providerSessions: [
628 {
629 id: providerSessionId,
630 driver: ProviderDriverKind.make("codex"),
631 providerInstanceId: ProviderInstanceId.make("codex"),
632 status: "ready",
633 },
634 ],
635 providerThreads: [
636 {
637 id: providerThreadId,
638 driver: ProviderDriverKind.make("codex"),
639 providerInstanceId: ProviderInstanceId.make("codex"),
640 status: "active",
641 },
642 ],
643 providerTurns: [
644 {
645 id: providerTurnId,
646 runAttemptId: attemptId,
647 nodeId: rootNodeId,
648 status: "running",
649 },
650 ],
651 runs: [
652 {
653 id: runId,
654 status: "starting",
655 providerThreadId,
656 providerInstanceId: ProviderInstanceId.make("codex"),
657 },
658 ],
659 attempts: [
660 {
661 id: attemptId,
662 runId,
663 rootNodeId,
664 status: "running",
665 },
666 ],
667 nodes: [{ id: rootNodeId, runId, status: "running" }],
668 subagents: [],
669 messages: [{ id: MessageId.make("message_recovery_cancel"), runId, streaming: true }],
670 turnItems: [
671 {
672 id: TurnItemId.make("turn_item_recovery_cancel"),
673 runId,
674 nodeId: rootNodeId,
675 status: "running",
676 },
677 ],
678 } as unknown as OrchestrationV2ThreadProjection;
679 const layer = ProviderRuntimeRecovery.layer.pipe(
680 Layer.provide(ServerSettings.layerTest()),
681 Layer.provide(
682 Layer.mergeAll(
683 Layer.mock(ProjectionStore.ProjectionStoreV2)({
684 getRecoveryThreadIds: () => Effect.succeed([threadId]),
685 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
686 }),
687 Layer.mock(EventSink.EventSinkV2)({
688 commitCommand: (input) => {
689 committedInput = input;
690 return Effect.succeed({ committed: true, cancelledEffectCount: 2 } as never);
691 },
692 }),
693 IdAllocator.layer,
694 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
695 runRecoveryOnce: Effect.succeed(false),
696 }),
697 Layer.mock(EffectOutbox.EffectOutboxV2)({
698 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
699 }),
700 ),
701 ),
702 );
703​
704 return Effect.gen(function* () {
705 const summary = yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)
706 .recover;
707 assert.equal(summary.terminalizedRuns, 1);
708 assert.equal(summary.stoppedSessions, 1);
709 assert.equal(summary.retiredEffects, 2);
710 assert.deepEqual(committedInput?.cancelUnsettledEffects?.effectTypes, [
711 "provider-turn.start",
712 "provider-turn.interrupt",
713 "provider-turn.steer",
714 "provider-turn.restart",
715 "runtime-request.respond",
716 ]);
717 const events = committedInput?.events ?? [];
718 assert.deepEqual(
719 events.map((event) => [
720 event.type,
721 "status" in event.payload ? event.payload.status : null,
722 ]),
723 [
724 ["run.updated", "cancelled"],
725 ["run-attempt.updated", "cancelled"],
726 ["node.updated", "cancelled"],
727 ["provider-turn.updated", "cancelled"],
728 ["message.updated", null],
729 ["turn-item.updated", "cancelled"],
730 ["provider-thread.updated", "idle"],
731 ["provider-session.updated", "stopped"],
732 ],
733 );
734 const messageEvent = events.find((event) => event.type === "message.updated");
735 assert.isFalse(messageEvent?.type === "message.updated" && messageEvent.payload.streaming);
736 }).pipe(Effect.provide(layer));
737 },
738);
739​
740it.effect("cancels workflow members and child roots without run ids after restart", () => {
741 const parentThreadId = ThreadId.make("thread_recovery_workflow_members");
742 const childThreadId = ThreadId.make("thread_recovery_workflow_member_child");
743 const memberId = NodeId.make("node_recovery_workflow_member");
744 const childRootId = NodeId.make("node_recovery_workflow_member_root");
745 const providerInstanceId = ProviderInstanceId.make("claudeAgent");
746 const driver = ProviderDriverKind.make("claudeAgent");
747 const member = {
748 id: memberId,
749 threadId: parentThreadId,
750 runId: null,
751 origin: "provider_native",
752 status: "running",
753 driver,
754 providerInstanceId,
755 };
756 const parentProjection = {
757 thread: { id: parentThreadId, providerInstanceId },
758 runs: [],
759 attempts: [],
760 nodes: [
761 { id: memberId, threadId: parentThreadId, runId: null, kind: "subagent", status: "running" },
762 ],
763 subagents: [member],
764 runtimeRequests: [],
765 providerSessions: [],
766 providerThreads: [],
767 providerTurns: [],
768 messages: [],
769 turnItems: [],
770 } as unknown as OrchestrationV2ThreadProjection;
771 const childProjection = {
772 ...parentProjection,
773 thread: { id: childThreadId, providerInstanceId },
774 nodes: [
775 {
776 id: childRootId,
777 threadId: childThreadId,
778 runId: null,
779 kind: "root_turn",
780 status: "running",
781 },
782 ],
783 subagents: [],
784 } as unknown as OrchestrationV2ThreadProjection;
785 const committed: Array<Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0]> = [];
786 const layer = ProviderRuntimeRecovery.layer.pipe(
787 Layer.provide(ServerSettings.layerTest()),
788 Layer.provide(
789 Layer.mergeAll(
790 Layer.mock(ProjectionStore.ProjectionStoreV2)({
791 getRecoveryThreadIds: () => Effect.succeed([parentThreadId, childThreadId]),
792 getRuntimeRecoveryProjection: (threadId) =>
793 Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection),
794 }),
795 Layer.mock(EventSink.EventSinkV2)({
796 commitCommand: (input) => {
797 committed.push(input);
798 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
799 },
800 }),
801 IdAllocator.layer,
802 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
803 runRecoveryOnce: Effect.succeed(false),
804 }),
805 Layer.mock(EffectOutbox.EffectOutboxV2)({
806 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
807 }),
808 ),
809 ),
810 );
811​
812 return Effect.gen(function* () {
813 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
814 assert.deepEqual(
815 committed.flatMap((command) =>
816 command.events.map((event) => [
817 command.threadId,
818 event.type,
819 "status" in event.payload ? event.payload.status : null,
820 ]),
821 ),
822 [
823 [parentThreadId, "subagent.updated", "cancelled"],
824 [parentThreadId, "node.updated", "cancelled"],
825 [childThreadId, "node.updated", "cancelled"],
826 ],
827 );
828 }).pipe(Effect.provide(layer));
829});
830​
831it.effect(
832 "clears persisted pendingBackgroundTasks and terminalizes stale background items on settled runs",
833 () => {
834 const threadId = ThreadId.make("thread_recovery_background");
835 const settledRunId = RunId.make("run_recovery_background_settled");
836 const activeRunId = RunId.make("run_recovery_background_active");
837 const activeAttemptId = RunAttemptId.make("attempt_recovery_background_active");
838 const activeRootNodeId = NodeId.make("node_recovery_background_active");
839 const idleProviderThreadId = ProviderThreadId.make("provider_thread_recovery_background_idle");
840 const activeProviderThreadId = ProviderThreadId.make(
841 "provider_thread_recovery_background_active",
842 );
843 const secondaryProviderThreadId = ProviderThreadId.make(
844 "provider_thread_recovery_background_secondary",
845 );
846 const providerSessionId = ProviderSessionId.make("provider_session_recovery_background");
847 const settledStaleItemId = TurnItemId.make("turn_item_recovery_background_stale");
848 const activeRunItemId = TurnItemId.make("turn_item_recovery_background_active");
849 const nullRunCommandItemId = TurnItemId.make("turn_item_recovery_background_null_run");
850 const nullRunSubagentItemId = TurnItemId.make("turn_item_recovery_background_null_subagent");
851 const claudeInstanceId = ProviderInstanceId.make("claude");
852 const secondaryInstanceId = ProviderInstanceId.make("claude-secondary");
853 const subagentInstanceId = ProviderInstanceId.make("claude-subagent");
854 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
855 null;
856 const projection = {
857 thread: { id: threadId },
858 runtimeRequests: [],
859 providerSessions: [
860 {
861 id: providerSessionId,
862 driver: ProviderDriverKind.make("claude"),
863 providerInstanceId: claudeInstanceId,
864 status: "ready",
865 },
866 ],
867 providerThreads: [
868 {
869 id: idleProviderThreadId,
870 driver: ProviderDriverKind.make("claude"),
871​
872 providerInstanceId: claudeInstanceId,
873 status: "idle",
874 pendingBackgroundTasks: [{ taskId: "bg-settled", description: "sleep 30" }],
875 },
876 {
877 id: activeProviderThreadId,
878 driver: ProviderDriverKind.make("claude"),
879 providerInstanceId: claudeInstanceId,
880 status: "active",
881 pendingBackgroundTasks: [{ taskId: "bg-active", description: "npm test" }],
882 },
883 {
884 id: secondaryProviderThreadId,
885 driver: ProviderDriverKind.make("claude"),
886 providerInstanceId: secondaryInstanceId,
887 status: "idle",
888 pendingBackgroundTasks: [],
889 },
890 ],
891 providerTurns: [],
892 runs: [
893 {
894 id: settledRunId,
895 status: "completed",
896 providerInstanceId: claudeInstanceId,
897 },
898 {
899 id: activeRunId,
900 status: "running",
901 providerInstanceId: claudeInstanceId,
902 },
903 ],
904 attempts: [
905 {
906 id: activeAttemptId,
907 runId: activeRunId,
908 rootNodeId: activeRootNodeId,
909 status: "running",
910 },
911 ],
912 nodes: [{ id: activeRootNodeId, runId: activeRunId, status: "running" }],
913 subagents: [],
914 messages: [],
915 turnItems: [
916 {
917 id: settledStaleItemId,
918 runId: settledRunId,
919 nodeId: null,
920 providerThreadId: idleProviderThreadId,
921 type: "command_execution",
922 status: "running",
923 },
924 {
925 id: activeRunItemId,
926 runId: activeRunId,
927 nodeId: activeRootNodeId,
928 providerThreadId: activeProviderThreadId,
929 type: "dynamic_tool",
930 status: "running",
931 },
932 {
933 id: nullRunCommandItemId,
934 runId: null,
935 nodeId: null,
936 providerThreadId: secondaryProviderThreadId,
937 type: "command_execution",
938 status: "running",
939 },
940 {
941 id: nullRunSubagentItemId,
942 runId: null,
943 nodeId: null,
944 providerThreadId: secondaryProviderThreadId,
945 type: "subagent",
946 status: "running",
947 providerInstanceId: subagentInstanceId,
948 },
949 ],
950 } as unknown as OrchestrationV2ThreadProjection;
951 const layer = ProviderRuntimeRecovery.layer.pipe(
952 Layer.provide(ServerSettings.layerTest()),
953 Layer.provide(
954 Layer.mergeAll(
955 Layer.mock(ProjectionStore.ProjectionStoreV2)({
956 getRecoveryThreadIds: () => Effect.succeed([threadId]),
957 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
958 }),
959 Layer.mock(EventSink.EventSinkV2)({
960 commitCommand: (input) => {
961 committedInput = input;
962 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
963 },
964 }),
965 IdAllocator.layer,
966 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
967 runRecoveryOnce: Effect.succeed(false),
968 }),
969 Layer.mock(EffectOutbox.EffectOutboxV2)({
970 listByCommandId: () => Effect.succeed([]),
971 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
972 }),
973 ),
974 ),
975 );
976​
977 return Effect.gen(function* () {
978 const summary =
979 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
980 assert.equal(summary.terminalizedRuns, 1);
981 const events = committedInput?.events ?? [];
982​
983 const turnItemCancels = events.filter(
984 (event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
985 );
986​
987 assert.equal(turnItemCancels.length, 4);
988 assert.deepEqual(
989 turnItemCancels
990 .map((event) => event.type === "turn-item.updated" && event.payload.id)
991 .sort(),
992 [activeRunItemId, nullRunCommandItemId, nullRunSubagentItemId, settledStaleItemId].sort(),
993 );
994​
995 const cancelById = (id: TurnItemId) =>
996 turnItemCancels.find(
997 (event) => event.type === "turn-item.updated" && event.payload.id === id,
998 );
999 assert.equal(cancelById(nullRunCommandItemId)?.providerInstanceId, secondaryInstanceId);
1000​
1001 assert.notEqual(subagentInstanceId, secondaryInstanceId);
1002 assert.equal(cancelById(nullRunSubagentItemId)?.providerInstanceId, subagentInstanceId);
1003​
1004 assert.equal(cancelById(settledStaleItemId)?.providerInstanceId, claudeInstanceId);
1005​
1006 const providerThreadEvents = events.filter(
1007 (event) => event.type === "provider-thread.updated",
1008 );
1009​
1010 assert.equal(providerThreadEvents.length, 2);
1011 for (const event of providerThreadEvents) {
1012 if (event.type !== "provider-thread.updated") continue;
1013 assert.deepEqual(event.payload.pendingBackgroundTasks ?? [], []);
1015 const idleThreadEvent = providerThreadEvents.find(
1016 (event) =>
1017 event.type === "provider-thread.updated" && event.payload.id === idleProviderThreadId,
1018 );
1019 assert.equal(
1020 idleThreadEvent?.type === "provider-thread.updated" ? idleThreadEvent.payload.status : null,
1021 "idle",
1022 );
1023 const activeThreadEvent = providerThreadEvents.find(
1024 (event) =>
1025 event.type === "provider-thread.updated" && event.payload.id === activeProviderThreadId,
1026 );
1027 assert.equal(
1028 activeThreadEvent?.type === "provider-thread.updated"
1029 ? activeThreadEvent.payload.status
1030 : null,
1031 "idle",
1032 );
1033 }).pipe(Effect.provide(layer));
1034 },
1036​
1037it.effect(
1038 "terminalizes a leftover nonpersistent dynamic_tool on a settled run after process loss",
1039 () => {
1040 const threadId = ThreadId.make("thread_recovery_orphan_wait");
1041 const settledRunId = RunId.make("run_recovery_orphan_wait_settled");
1042 const providerThreadId = ProviderThreadId.make("provider_thread_recovery_orphan_wait");
1043 const orphanWaitItemId = TurnItemId.make(
1044 "turn-item:provider:codex:native-item:exec-4669f3bb-78c9-4af1-b44e-daa340d2c538",
1045 );
1046 const persistentMonitorItemId = TurnItemId.make(
1047 "turn-item:provider:codex:native-item:exec-persistent-monitor",
1048 );
1049 const orphanWaitNodeId = NodeId.make("node_recovery_orphan_wait");
1050 const persistentMonitorNodeId = NodeId.make("node_recovery_persistent_monitor");
1051 const codexInstanceId = ProviderInstanceId.make("codex");
1052 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
1053 null;
1054 const projection = {
1055 thread: { id: threadId, providerInstanceId: codexInstanceId },
1056 runtimeRequests: [],
1057 providerSessions: [],
1058 providerThreads: [
1060 id: providerThreadId,
1061 driver: ProviderDriverKind.make("codex"),
1062 providerInstanceId: codexInstanceId,
1063 status: "idle",
1064 pendingBackgroundTasks: [],
1065 },
1066 ],
1067 providerTurns: [],
1068 runs: [{ id: settledRunId, status: "completed", providerInstanceId: codexInstanceId }],
1069 attempts: [],
1070 nodes: [
1071 { id: orphanWaitNodeId, runId: settledRunId, status: "running", kind: "tool_call" },
1073 id: persistentMonitorNodeId,
1074 runId: settledRunId,
1075 status: "running",
1076 kind: "tool_call",
1077 },
1078 ],
1079 subagents: [],
1080 messages: [],
1081 turnItems: [
1083 id: orphanWaitItemId,
1084 runId: settledRunId,
1085 nodeId: orphanWaitNodeId,
1086 providerThreadId,
1087 type: "dynamic_tool",
1088 status: "running",
1089 toolName: "t3-code.t3_thread_wait",
1090 input: {
1091 threadId:
1092 "thread:delegated-task:command%3Amcp%3Aaafffab1-e811-458a-ae83-558e542c61ff%3Adelegate-task%3Areview-mobile-reconnect-opus-20260815",
1093 timeoutMs: 30000,
1094 },
1095 },
1097 id: persistentMonitorItemId,
1098 runId: settledRunId,
1099 nodeId: persistentMonitorNodeId,
1100 providerThreadId,
1101 type: "dynamic_tool",
1102 status: "running",
1103 toolName: "grok.monitor",
1104 input: { persistent: true, command: "tail -f" },
1105 },
1106 ],
1107 } as unknown as OrchestrationV2ThreadProjection;
1108 const layer = ProviderRuntimeRecovery.layer.pipe(
1109 Layer.provide(ServerSettings.layerTest()),
1110 Layer.provide(
1111 Layer.mergeAll(
1112 Layer.mock(ProjectionStore.ProjectionStoreV2)({
1113 getRecoveryThreadIds: () => Effect.succeed([threadId]),
1114 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
1115 }),
1116 Layer.mock(EventSink.EventSinkV2)({
1117 commitCommand: (input) => {
1118 committedInput = input;
1119 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
1120 },
1121 }),
1122 IdAllocator.layer,
1123 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
1124 runRecoveryOnce: Effect.succeed(false),
1125 }),
1126 Layer.mock(EffectOutbox.EffectOutboxV2)({
1127 listByCommandId: () => Effect.succeed([]),
1128 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
1129 }),
1130 ),
1131 ),
1132 );
1133​
1134 return Effect.gen(function* () {
1135 const summary =
1136 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
1137 assert.equal(summary.terminalizedRuns, 0);
1138 const turnItemCancels = (committedInput?.events ?? []).filter(
1139 (event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
1140 );
1141​
1142 assert.equal(turnItemCancels.length, 2);
1143 assert.deepEqual(
1144 turnItemCancels
1145 .map((event) => event.type === "turn-item.updated" && event.payload.id)
1146 .sort(),
1147 [orphanWaitItemId, persistentMonitorItemId].sort(),
1148 );
1149 const nodeCancels = (committedInput?.events ?? []).filter(
1150 (event) => event.type === "node.updated" && event.payload.status === "cancelled",
1151 );
1152 assert.equal(nodeCancels.length, 2);
1153 assert.deepEqual(
1154 nodeCancels.map((event) => event.type === "node.updated" && event.payload.id).sort(),
1155 [orphanWaitNodeId, persistentMonitorNodeId].sort(),
1156 );
1157 }).pipe(Effect.provide(layer));
1158 },
1160​
1161it.effect(
1162 "terminalizes the linked subagent and node for a stale subagent item on a settled run",
1163 () => {
1164 const threadId = ThreadId.make("thread_recovery_subagent");
1165 const settledRunId = RunId.make("run_recovery_subagent_settled");
1166 const providerThreadId = ProviderThreadId.make("provider_thread_recovery_subagent");
1167 const staleSubagentNodeId = NodeId.make("node_recovery_subagent_stale");
1168 const doneSubagentNodeId = NodeId.make("node_recovery_subagent_done");
1169 const staleItemId = TurnItemId.make("turn_item_recovery_subagent_stale");
1170 const doneItemId = TurnItemId.make("turn_item_recovery_subagent_done");
1171 const claudeInstanceId = ProviderInstanceId.make("claude");
1172 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
1173 null;
1174 const projection = {
1175 thread: { id: threadId },
1176 runtimeRequests: [],
1177 providerSessions: [],
1178 providerThreads: [
1180 id: providerThreadId,
1181 driver: ProviderDriverKind.make("claude"),
1182 providerInstanceId: claudeInstanceId,
1183 status: "idle",
1184 pendingBackgroundTasks: [],
1185 },
1186 ],
1187 providerTurns: [],
1188​
1189 runs: [{ id: settledRunId, status: "completed", providerInstanceId: claudeInstanceId }],
1190 attempts: [],
1191 nodes: [
1192 { id: staleSubagentNodeId, runId: settledRunId, status: "running" },
1193 { id: doneSubagentNodeId, runId: settledRunId, status: "completed" },
1194 ],
1195 subagents: [
1197 id: staleSubagentNodeId,
1198 runId: settledRunId,
1199 origin: "provider_native",
1200 driver: ProviderDriverKind.make("claude"),
1201 providerInstanceId: claudeInstanceId,
1202 status: "running",
1203 },
1205 id: doneSubagentNodeId,
1206 runId: settledRunId,
1207 origin: "provider_native",
1208 driver: ProviderDriverKind.make("claude"),
1209 providerInstanceId: claudeInstanceId,
1210 status: "completed",
1211 result: "done",
1212 },
1213 ],
1214 messages: [],
1215 turnItems: [
1217 id: staleItemId,
1218 runId: settledRunId,
1219 nodeId: staleSubagentNodeId,
1220 providerThreadId,
1221 type: "subagent",
1222 status: "running",
1223 subagentId: staleSubagentNodeId,
1224 providerInstanceId: claudeInstanceId,
1225 },
1227 id: doneItemId,
1228 runId: settledRunId,
1229 nodeId: doneSubagentNodeId,
1230 providerThreadId,
1231 type: "subagent",
1232 status: "completed",
1233 subagentId: doneSubagentNodeId,
1234 providerInstanceId: claudeInstanceId,
1235 },
1236 ],
1237 } as unknown as OrchestrationV2ThreadProjection;
1238 const layer = ProviderRuntimeRecovery.layer.pipe(
1239 Layer.provide(ServerSettings.layerTest()),
1240 Layer.provide(
1241 Layer.mergeAll(
1242 Layer.mock(ProjectionStore.ProjectionStoreV2)({
1243 getRecoveryThreadIds: () => Effect.succeed([threadId]),
1244 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
1245 }),
1246 Layer.mock(EventSink.EventSinkV2)({
1247 commitCommand: (input) => {
1248 committedInput = input;
1249 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
1250 },
1251 }),
1252 IdAllocator.layer,
1253 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
1254 runRecoveryOnce: Effect.succeed(false),
1255 }),
1256 Layer.mock(EffectOutbox.EffectOutboxV2)({
1257 listByCommandId: () => Effect.succeed([]),
1258 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
1259 }),
1260 ),
1261 ),
1262 );
1263​
1264 return Effect.gen(function* () {
1265 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
1266 const events = committedInput?.events ?? [];
1267​
1268 const turnItemCancels = events.filter(
1269 (event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
1270 );
1271 assert.equal(turnItemCancels.length, 1);
1272​
1273 const subagentCancels = events.filter((event) => event.type === "subagent.updated");
1274 assert.equal(subagentCancels.length, 1);
1275 const subagentCancel = subagentCancels[0];
1276 assert.equal(
1277 subagentCancel?.type === "subagent.updated" ? subagentCancel.payload.id : null,
1278 staleSubagentNodeId,
1279 );
1280 assert.equal(
1281 subagentCancel?.type === "subagent.updated" ? subagentCancel.payload.status : null,
1282 "cancelled",
1283 );
1284​
1285 const nodeCancels = events.filter((event) => event.type === "node.updated");
1286 assert.equal(nodeCancels.length, 1);
1287 const nodeCancel = nodeCancels[0];
1288 assert.equal(
1289 nodeCancel?.type === "node.updated" ? nodeCancel.payload.id : null,
1290 staleSubagentNodeId,
1291 );
1292​
1293 assert.isFalse(
1294 events.some(
1295 (event) => event.type === "subagent.updated" && event.payload.id === doneSubagentNodeId,
1296 ),
1297 );
1298 assert.isFalse(
1299 events.some(
1300 (event) => event.type === "node.updated" && event.payload.id === doneSubagentNodeId,
1301 ),
1302 );
1303 }).pipe(Effect.provide(layer));
1304 },
1306​
1307it.effect("leaves delegated tasks to their own child threads after process loss", () => {
1308 const threadId = ThreadId.make("thread_recovery_delegation");
1309 const settledRunId = RunId.make("run_recovery_delegation_settled");
1310 const runningRunId = RunId.make("run_recovery_delegation_running");
1311 const providerThreadId = ProviderThreadId.make("provider_thread_recovery_delegation");
1312 const claudeInstanceId = ProviderInstanceId.make("claude");
1313 const driver = ProviderDriverKind.make("claude");
1314 const settledTaskId = NodeId.make("node_recovery_delegation_settled");
1315 const runningTaskId = NodeId.make("node_recovery_delegation_running");
1316 const nativeSubagentId = NodeId.make("node_recovery_native_subagent");
1317 const delegatedTask = (id: NodeId, runId: RunId) => ({
1318 id,
1319 runId,
1320 origin: "app_owned",
1321 childThreadId: ThreadId.make(`thread:delegated-task:${id}`),
1322 driver,
1323 providerInstanceId: claudeInstanceId,
1324 status: "running",
1325 });
1326 const subagentItem = (subagentId: NodeId, runId: RunId, origin: string) => ({
1327 id: TurnItemId.make(`turn_item:${subagentId}`),
1328 runId,
1329 nodeId: subagentId,
1330 providerThreadId,
1331 type: "subagent",
1332 status: "running",
1333 subagentId,
1334 origin,
1335 childThreadId:
1336 origin === "app_owned" ? ThreadId.make(`thread:delegated-task:${subagentId}`) : null,
1337 providerInstanceId: claudeInstanceId,
1338 title: `subagent ${subagentId}`,
1339 });
1340 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
1341 null;
1342 const projection = {
1343 thread: { id: threadId, providerInstanceId: claudeInstanceId },
1344 runtimeRequests: [],
1345 providerSessions: [],
1346 providerThreads: [
1348 id: providerThreadId,
1349 driver,
1350 providerInstanceId: claudeInstanceId,
1351 ownerNodeId: null,
1352 status: "idle",
1353 pendingBackgroundTasks: [],
1354 },
1355 ],
1356 providerTurns: [],
1357 runs: [
1359 id: settledRunId,
1360 ordinal: 1,
1361 status: "completed",
1362 providerThreadId,
1363 providerInstanceId: claudeInstanceId,
1364 },
1366 id: runningRunId,
1367 ordinal: 2,
1368 status: "running",
1369 providerThreadId,
1370 providerInstanceId: claudeInstanceId,
1371 },
1372 ],
1373 attempts: [],
1374 nodes: [
1375 { id: settledTaskId, runId: settledRunId, status: "running", kind: "subagent" },
1376 { id: runningTaskId, runId: runningRunId, status: "running", kind: "subagent" },
1377 { id: nativeSubagentId, runId: settledRunId, status: "running", kind: "subagent" },
1378 ],
1379 subagents: [
1380 delegatedTask(settledTaskId, settledRunId),
1381 delegatedTask(runningTaskId, runningRunId),
1383 ...delegatedTask(nativeSubagentId, settledRunId),
1384 origin: "provider_native",
1385 childThreadId: null,
1386 },
1387 ],
1388 messages: [],
1389 turnItems: [
1390 subagentItem(settledTaskId, settledRunId, "app_owned"),
1391 subagentItem(runningTaskId, runningRunId, "app_owned"),
1392 subagentItem(nativeSubagentId, settledRunId, "provider_native"),
1393 ],
1394 } as unknown as OrchestrationV2ThreadProjection;
1395 const layer = ProviderRuntimeRecovery.layer.pipe(
1396 Layer.provide(ServerSettings.layerTest()),
1397 Layer.provide(
1398 Layer.mergeAll(
1399 Layer.mock(ProjectionStore.ProjectionStoreV2)({
1400 getRecoveryThreadIds: () => Effect.succeed([threadId]),
1401 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
1402 }),
1403 Layer.mock(EventSink.EventSinkV2)({
1404 commitCommand: (input) => {
1405 committedInput = input;
1406 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
1407 },
1408 }),
1409 IdAllocator.layer,
1410 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
1411 runRecoveryOnce: Effect.succeed(false),
1412 }),
1413 Layer.mock(EffectOutbox.EffectOutboxV2)({
1414 listByCommandId: () => Effect.succeed([]),
1415 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
1416 }),
1417 ),
1418 ),
1419 );
1420​
1421 return Effect.gen(function* () {
1422 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
1423 const events = committedInput?.events ?? [];
1424 const touched = events.flatMap((event) =>
1425 event.type === "turn-item.updated"
1426 ? event.payload.type === "subagent"
1427 ? [event.payload.subagentId]
1428 : []
1429 : event.type === "subagent.updated" || event.type === "node.updated"
1430 ? [event.payload.id]
1431 : [],
1432 );
1433​
1434 assert.isTrue(
1435 events.some(
1436 (event) =>
1437 event.type === "run.updated" &&
1438 event.payload.id === runningRunId &&
1439 event.payload.status === "cancelled",
1440 ),
1441 );
1442 assert.notInclude(touched, settledTaskId);
1443 assert.notInclude(touched, runningTaskId);
1444 assert.include(touched, nativeSubagentId);
1445​
1446 const noted = events.flatMap((event) =>
1447 event.type === "run.background-work-cancelled"
1448 ? event.payload.restartCancelledBackgroundWork.map((work) => work.label)
1449 : [],
1450 );
1451 assert.deepEqual(noted, [`subagent ${nativeSubagentId}`]);
1452 }).pipe(Effect.provide(layer));
1453});