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