Open History to see the last commit
1import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
2import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, it } from "@effect/vitest";
5import {
6 CommandId,
7 EventId,
8 MessageId,
9 type ModelSelection,
10 NodeId,
11 type OrchestrationV2Run,
12 ProjectId,
13 ProviderDriverKind,
14 ProviderInstanceId,
15 ProviderThreadId,
16 RunId,
17 ThreadId,
18 TurnItemId,
19} from "@t3tools/contracts";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as Layer from "effect/Layer";
23import * as Stream from "effect/Stream";
24
25import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
26import * as ServerConfig from "../config.ts";
27import * as McpSessionRegistryTestkit from "../mcp/McpSessionRegistry.testkit.ts";
28import * as SqlitePersistence from "../persistence/Sqlite.ts";
29import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
30import * as ProjectService from "../project/ProjectService.ts";
31import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
32import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";
33import * as ServerSettings from "../serverSettings.ts";
34import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
35import * as VcsProcess from "../vcs/VcsProcess.ts";
36import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
37import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
38import * as EventSink from "./EventSink.ts";
39import * as Orchestrator from "./Orchestrator.ts";
40import { continueRestartedRun } from "./RestartContinuation.ts";
41import * as RuntimeLayer from "./runtimeLayer.ts";
42import * as ProviderTurnStartServiceTestkit from "./ProviderTurnStartService.testkit.ts";
43import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
44
45const layerPlatformTest = Layer.merge(
46 NodeServices.layer,
47 Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
48 resolveLink: () => Effect.die("unused title link"),
49 }),
50);
51
52const layerServerConfig = ServerConfig.layerTest(process.cwd(), {
53 prefix: "t3-orchestration-v2-delegated-completion-",
54});
55
56const modelSelection = {
57 instanceId: ProviderInstanceId.make("codex"),
58 model: "gpt-5.4",
59} satisfies ModelSelection;
60
61const layerVcsDriverRegistryTest = VcsDriverRegistry.layer.pipe(
62 Layer.provide(VcsProcess.layer),
63 Layer.provide(layerServerConfig),
64 Layer.provide(layerPlatformTest),
65);
66
67const layerCheckpointStoreTest = CheckpointStore.layer.pipe(
68 Layer.provide(layerVcsDriverRegistryTest),
69);
70
71const driver = ProviderDriverKind.make("codex");
72const orchestrationAdapter = {
73 instanceId: modelSelection.instanceId,
74 driver,
75 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
76 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
77 openSession: () => Effect.die("sessions are not used by delegated completion tests"),
78} as ProviderAdapter.ProviderAdapterV2["Service"];
79const providerInstance = {
80 instanceId: modelSelection.instanceId,
81 driverKind: driver,
82 continuationIdentity: {
83 driverKind: driver,
84 continuationKey: "codex:test",
85 },
86 displayName: "Codex test",
87 enabled: true,
88 // No supportedRuntimeModes: every runtime mode runs as stored.
89 snapshot: { getSnapshot: Effect.succeed({}) } as unknown as ProviderInstance["snapshot"],
90 orchestrationAdapter,
91 textGeneration: {} as ProviderInstance["textGeneration"],
92} satisfies ProviderInstance;
93
94const layerTestProviderInstanceRegistry = Layer.succeed(
95 ProviderInstanceRegistry.ProviderInstanceRegistry,
96 {
97 getInstance: (instanceId) =>
98 Effect.succeed(instanceId === providerInstance.instanceId ? providerInstance : undefined),
99 listInstances: Effect.succeed([providerInstance]),
100 listUnavailable: Effect.succeed([]),
101 streamChanges: Stream.empty,
102 subscribeChanges: Effect.never,
103 },
104);
105
106const layerTest = Layer.mergeAll(RuntimeLayer.layer, RuntimeLayer.layerEventSink).pipe(
107 Layer.provideMerge(RuntimeLayer.layerProjectService),
108 Layer.provide(
109 Layer.mock(WorkspacePaths.WorkspacePaths)({
110 normalizeWorkspaceRoot: (workspaceRoot) => Effect.succeed(workspaceRoot),
111 }),
112 ),
113 Layer.provide(ProviderTurnStartServiceTestkit.layer),
114 Layer.provide(
115 Layer.succeed(ProjectEnrichmentService.ProjectEnrichmentService, {
116 peek: () =>
117 Effect.succeed({
118 repositoryIdentity: null,
119 faviconPath: null,
120 repositoryIdentityResolved: false,
121 }),
122 request: () => Effect.void,
123 getAvailable: () =>
124 Effect.succeed({
125 repositoryIdentity: null,
126 faviconPath: null,
127 repositoryIdentityResolved: false,
128 }),
129 invalidate: () => Effect.void,
130 subscribeChanges: Effect.never,
131 }),
132 ),
133 Layer.provide(McpSessionRegistryTestkit.layer),
134 Layer.provide(McpProviderSessions.layer),
135 Layer.provide(SqlitePersistence.layerMemory),
136 Layer.provide(layerCheckpointStoreTest),
137 Layer.provide(layerServerConfig),
138 Layer.provide(ServerSettings.layerTest()),
139 Layer.provide(layerTestProviderInstanceRegistry),
140 Layer.provide(layerPlatformTest),
141);
142
143const seedParentWithTerminalTask = (input: {
144 readonly threadId: ThreadId;
145 readonly projectId: ProjectId;
146 readonly runId: RunId;
147 readonly rootNodeId: NodeId;
148 readonly taskId: NodeId;
149 readonly deliveryState: "delivered" | "claimed" | "acknowledged" | "disposed";
150 readonly completionWake?: "always" | "settled_only";
151 readonly deliveryTaskIds?: ReadonlyArray<NodeId>;
152 readonly now: DateTime.Utc;
153}) =>
154 Effect.gen(function* () {
155 const projects = yield* ProjectService.ProjectService;
156 const orchestrator = yield* Orchestrator.OrchestratorV2;
157 const eventSink = yield* EventSink.EventSinkV2;
158 const providerThreadId = ProviderThreadId.make(
159 `provider-thread:${String(input.threadId).replace("thread:", "")}`,
160 );
161
162 yield* projects.create({
163 commandId: CommandId.make(`command:seed-project:${input.threadId}`),
164 projectId: input.projectId,
165 title: "Delegated completion delivery",
166 workspaceRoot: `/workspace/${input.projectId}`,
167 });
168
169 yield* orchestrator.dispatch({
170 type: "thread.create",
171 createdBy: "user",
172 creationSource: "web",
173 commandId: CommandId.make(`command:seed-create:${input.threadId}`),
174 threadId: input.threadId,
175 projectId: input.projectId,
176 title: "Delegated completion delivery",
177 modelSelection,
178 runtimeMode: "full-access",
179 interactionMode: "default",
180 branch: null,
181 worktreePath: null,
182 });
183
184 yield* eventSink.write({
185 commandId: CommandId.make(`command:seed-projection:${input.threadId}`),
186 events: [
187 {
188 id: EventId.make(`event:seed-provider-thread:${input.threadId}`),
189 type: "provider-thread.updated",
190 threadId: input.threadId,
191 driver,
192 providerInstanceId: modelSelection.instanceId,
193 occurredAt: input.now,
194 payload: {
195 id: providerThreadId,
196 driver,
197 providerInstanceId: modelSelection.instanceId,
198 providerSessionId: null,
199 appThreadId: input.threadId,
200 ownerNodeId: input.rootNodeId,
201 nativeThreadRef: {
202 driver,
203 nativeId: `native:${input.threadId}`,
204 strength: "strong",
205 },
206 nativeConversationHeadRef: null,
207 status: "active",
208 firstRunOrdinal: 1,
209 lastRunOrdinal: 1,
210 handoffIds: [],
211 forkedFrom: null,
212 createdAt: input.now,
213 updatedAt: input.now,
214 },
215 },
216 {
217 id: EventId.make(`event:seed-run:${input.threadId}`),
218 type: "run.updated",
219 threadId: input.threadId,
220 runId: input.runId,
221 nodeId: input.rootNodeId,
222 providerInstanceId: modelSelection.instanceId,
223 occurredAt: input.now,
224 payload: {
225 id: input.runId,
226 threadId: input.threadId,
227 ordinal: 1,
228 providerInstanceId: modelSelection.instanceId,
229 modelSelection,
230 providerThreadId,
231 userMessageId: MessageId.make(`message:seed-user:${input.threadId}`),
232 rootNodeId: input.rootNodeId,
233 activeAttemptId: null,
234 status: "running",
235 requestedAt: input.now,
236 startedAt: input.now,
237 completedAt: null,
238 checkpointId: null,
239 contextHandoffId: null,
240 delegatedCompletion: {
241 disposition: "open",
242 nextGeneration: 2,
243 delivery:
244 input.deliveryTaskIds === undefined
245 ? null
246 : {
247 generation: 1,
248 messageId: MessageId.make(`message:delegated-delivery:${input.threadId}`),
249 taskIds: input.deliveryTaskIds,
250 },
251 },
252 },
253 },
254 {
255 id: EventId.make(`event:seed-task:${input.threadId}`),
256 type: "subagent.updated",
257 threadId: input.threadId,
258 runId: input.runId,
259 nodeId: input.taskId,
260 driver,
261 providerInstanceId: modelSelection.instanceId,
262 occurredAt: input.now,
263 payload: {
264 id: input.taskId,
265 threadId: input.threadId,
266 runId: input.runId,
267 parentNodeId: input.rootNodeId,
268 origin: "app_owned",
269 createdBy: "agent",
270 driver,
271 providerInstanceId: modelSelection.instanceId,
272 providerThreadId: null,
273 childThreadId: null,
274 nativeTaskRef: null,
275 prompt: "Inspect the delivered ownership edge.",
276 title: null,
277 model: null,
278 completionWake: input.completionWake ?? "settled_only",
279 completionDelivery: {
280 state: input.deliveryState,
281 observedByRunId: input.deliveryState === "acknowledged" ? input.runId : null,
282 },
283 status: "completed",
284 result: "child finished",
285 startedAt: input.now,
286 completedAt: input.now,
287 updatedAt: input.now,
288 },
289 },
290 ],
291 });
292 });
293
294it.layer(layerTest)("delegated completion delivery repairs", (it) => {
295 it.effect("acceptance batches pending siblings without acknowledging their results", () =>
296 Effect.gen(function* () {
297 const orchestrator = yield* Orchestrator.OrchestratorV2;
298 const sink = yield* EventSink.EventSinkV2;
299 const now = yield* DateTime.now;
300 const threadId = ThreadId.make("mailbox-batch");
301 const runId = RunId.make("mailbox-parent");
302 const taskId = NodeId.make("mailbox-first");
303 const messageId = MessageId.make(`message:delegated-delivery:${threadId}`);
304 yield* seedParentWithTerminalTask({
305 threadId,
306 runId,
307 projectId: ProjectId.make("mailbox-project"),
308 rootNodeId: NodeId.make("mailbox-root"),
309 taskId,
310 deliveryState: "claimed",
311 completionWake: "always",
312 deliveryTaskIds: [taskId],
313 now,
314 });
315 const projection = yield* orchestrator.getThreadProjection(threadId);
316 const task = projection.subagents[0]!;
317 const pendingIds = [NodeId.make("mailbox-second"), NodeId.make("mailbox-third")];
318 yield* sink.write({
319 events: [
320 {
321 id: EventId.make("mailbox-message"),
322 type: "message.updated",
323 threadId,
324 runId,
325 occurredAt: now,
326 payload: {
327 id: messageId,
328 threadId,
329 runId,
330 nodeId: task.parentNodeId,
331 role: "user",
332 text: "Background task finished",
333 attachments: [],
334 streaming: false,
335 createdBy: "agent",
336 creationSource: "server",
337 createdAt: now,
338 updatedAt: now,
339 delegatedCompletion: { parentRunId: runId, generation: 1, taskIds: [taskId] },
340 },
341 },
342 ...pendingIds.map((id) => ({
343 id: EventId.make(`event:${id}`),
344 type: "subagent.updated" as const,
345 threadId,
346 runId,
347 nodeId: id,
348 occurredAt: now,
349 payload: {
350 ...task,
351 id,
352 completionDelivery: { state: "pending" as const, observedByRunId: null },
353 },
354 })),
355 ],
356 });
357 yield* orchestrator.dispatch({
358 type: "notification.delivery.accept",
359 commandId: CommandId.make("accept-first"),
360 threadId,
361 messageId,
362 });
363 const accepted = yield* orchestrator.getThreadProjection(threadId);
364 assert.equal(
365 accepted.subagents.find((row) => row.id === taskId)?.completionDelivery?.state,
366 "delivered",
367 );
368 const cohort = accepted.runs.find((row) => row.id === runId)?.delegatedCompletion;
369 assert.deepEqual(cohort?.delivery?.taskIds, pendingIds);
370 assert.equal(cohort?.delivery?.generation, 2);
371 for (const id of pendingIds) {
372 assert.deepEqual(accepted.subagents.find((row) => row.id === id)?.completionDelivery, {
373 state: "claimed",
374 observedByRunId: null,
375 });
376 }
377 yield* orchestrator.dispatch({
378 type: "notification.delivery.accept",
379 commandId: CommandId.make("repeat-old-acceptance"),
380 threadId,
381 messageId,
382 });
383 const duplicate = yield* orchestrator.getThreadProjection(threadId);
384 assert.deepEqual(duplicate.runs.find((row) => row.id === runId)?.delegatedCompletion, cohort);
385 }),
386 );
387
388 it.effect("acceptance batches a settled_only sibling once its spawning run ended", () =>
389 Effect.gen(function* () {
390 const orchestrator = yield* Orchestrator.OrchestratorV2;
391 const sink = yield* EventSink.EventSinkV2;
392 const now = yield* DateTime.now;
393 const threadId = ThreadId.make("mailbox-mixed");
394 const runId = RunId.make("mailbox-mixed-parent");
395 const taskId = NodeId.make("mailbox-mixed-always");
396 const siblingId = NodeId.make("mailbox-mixed-settled-only");
397 const messageId = MessageId.make(`message:delegated-delivery:${threadId}`);
398 yield* seedParentWithTerminalTask({
399 threadId,
400 runId,
401 projectId: ProjectId.make("mailbox-mixed-project"),
402 rootNodeId: NodeId.make("mailbox-mixed-root"),
403 taskId,
404 deliveryState: "claimed",
405 completionWake: "always",
406 deliveryTaskIds: [taskId],
407 now,
408 });
409 const projection = yield* orchestrator.getThreadProjection(threadId);
410 const task = projection.subagents[0]!;
411 const spawningRun = projection.runs.find((row) => row.id === runId)!;
412 // A restart cut the spawning run; its continuation is the live run now.
413 yield* sink.write({
414 events: [
415 {
416 ...runEvent({ threadId, runId, ordinal: 1, status: "cancelled", now }),
417 payload: { ...spawningRun, status: "cancelled" as const, completedAt: now },
418 },
419 runEvent({
420 threadId,
421 runId: RunId.make("mailbox-mixed-continuation"),
422 ordinal: 2,
423 status: "running",
424 now,
425 }),
426 {
427 id: EventId.make("mailbox-mixed-message"),
428 type: "message.updated",
429 threadId,
430 runId,
431 occurredAt: now,
432 payload: {
433 id: messageId,
434 threadId,
435 runId,
436 nodeId: task.parentNodeId,
437 role: "user",
438 text: "Background task finished",
439 attachments: [],
440 streaming: false,
441 createdBy: "agent",
442 creationSource: "server",
443 createdAt: now,
444 updatedAt: now,
445 delegatedCompletion: { parentRunId: runId, generation: 1, taskIds: [taskId] },
446 },
447 },
448 {
449 id: EventId.make(`event:${siblingId}`),
450 type: "subagent.updated" as const,
451 threadId,
452 runId,
453 nodeId: siblingId,
454 occurredAt: now,
455 payload: {
456 ...task,
457 id: siblingId,
458 completionWake: "settled_only" as const,
459 completionDelivery: { state: "pending" as const, observedByRunId: null },
460 },
461 },
462 ],
463 });
464 yield* orchestrator.dispatch({
465 type: "notification.delivery.accept",
466 commandId: CommandId.make("accept-mixed"),
467 threadId,
468 messageId,
469 });
470 const accepted = yield* orchestrator.getThreadProjection(threadId);
471 const cohort = accepted.runs.find((row) => row.id === runId)?.delegatedCompletion;
472 assert.deepEqual(cohort?.delivery?.taskIds, [siblingId]);
473 assert.equal(
474 accepted.subagents.find((row) => row.id === siblingId)?.completionDelivery?.state,
475 "claimed",
476 );
477 }),
478 );
479
480 it.effect("builds completion text and metadata from the same live cohort", () =>
481 Effect.gen(function* () {
482 const orchestrator = yield* Orchestrator.OrchestratorV2;
483 const now = yield* DateTime.now;
484 const threadId = ThreadId.make("thread:delegated-delivery-live-cohort");
485 const projectId = ProjectId.make("project:delegated-delivery-live-cohort");
486 const runId = RunId.make("run:delegated-delivery-live-cohort");
487 const rootNodeId = NodeId.make("node:delegated-delivery-live-cohort-root");
488 const firstTaskId = NodeId.make("node:delegated-delivery-live-cohort-first");
489 const secondTaskId = NodeId.make("node:delegated-delivery-live-cohort-second");
490 const messageId = MessageId.make(`message:delegated-delivery:${threadId}`);
491
492 yield* seedParentWithTerminalTask({
493 threadId,
494 projectId,
495 runId,
496 rootNodeId,
497 taskId: firstTaskId,
498 deliveryState: "claimed",
499 completionWake: "always",
500 deliveryTaskIds: [firstTaskId, secondTaskId],
501 now,
502 });
503
504 yield* orchestrator.dispatch({
505 type: "message.dispatch",
506 commandId: CommandId.make("command:delegated-delivery-live-cohort"),
507 threadId,
508 messageId,
509 text: `Delegated task ${firstTaskId} reached a terminal state.`,
510 attachments: [],
511 dispatchMode: { type: "queue_after_active" },
512 createdBy: "agent",
513 creationSource: "server",
514 delegatedCompletion: {
515 parentRunId: runId,
516 generation: 1,
517 taskIds: [firstTaskId],
518 },
519 });
520
521 const projection = yield* orchestrator.getThreadProjection(threadId);
522 const message = projection.messages.find((candidate) => candidate.id === messageId);
523 assert.deepEqual(message?.delegatedCompletion?.taskIds, [firstTaskId, secondTaskId]);
524 assert.include(message?.text ?? "", String(firstTaskId));
525 assert.include(message?.text ?? "", String(secondTaskId));
526 assert.include(message?.text ?? "", "task_status");
527 }),
528 );
529
530 it.effect("does not re-offer when wake-policy upgrades after delivered ownership settled", () =>
531 Effect.gen(function* () {
532 const orchestrator = yield* Orchestrator.OrchestratorV2;
533 const now = yield* DateTime.now;
534 const threadId = ThreadId.make("thread:delegated-delivery-a1");
535 const projectId = ProjectId.make("project:delegated-delivery-a1");
536 const runId = RunId.make("run:delegated-delivery-a1");
537 const rootNodeId = NodeId.make("node:delegated-delivery-a1-root");
538 const taskId = NodeId.make("node:delegated-delivery-a1-task");
539
540 yield* seedParentWithTerminalTask({
541 threadId,
542 projectId,
543 runId,
544 rootNodeId,
545 taskId,
546 deliveryState: "delivered",
547 completionWake: "settled_only",
548 now,
549 });
550
551 const upgrade = yield* orchestrator.dispatch({
552 type: "delegated_task.wake-policy",
553 commandId: CommandId.make("command:delegated-delivery-a1:wake-policy"),
554 parentThreadId: threadId,
555 taskId,
556 completionWake: "always",
557 });
558
559 const projection = yield* orchestrator.getThreadProjection(threadId);
560 const task = projection.subagents.find((candidate) => candidate.id === taskId);
561 const parentRun = projection.runs.find((candidate) => candidate.id === runId);
562
563 assert.equal(task?.completionWake, "always");
564 assert.deepEqual(task?.completionDelivery, {
565 state: "delivered",
566 observedByRunId: null,
567 });
568 assert.deepEqual(parentRun?.delegatedCompletion, {
569 disposition: "open",
570 nextGeneration: 2,
571 delivery: null,
572 });
573 assert.isFalse(
574 upgrade.storedEvents.some(
575 (stored) =>
576 stored.event.type === "subagent.updated" &&
577 stored.event.payload.id === taskId &&
578 stored.event.payload.completionDelivery?.state === "claimed",
579 ),
580 );
581 assert.isFalse(
582 upgrade.storedEvents.some(
583 (stored) =>
584 stored.event.type === "run.updated" &&
585 stored.event.payload.id === runId &&
586 stored.event.payload.delegatedCompletion?.delivery !== null &&
587 stored.event.payload.delegatedCompletion?.delivery !== undefined,
588 ),
589 );
590 }),
591 );
592
593 it.effect(
594 "treats repeated acknowledge and dispose with distinct command IDs as successful no-ops",
595 () =>
596 Effect.gen(function* () {
597 const orchestrator = yield* Orchestrator.OrchestratorV2;
598 const now = yield* DateTime.now;
599 const threadId = ThreadId.make("thread:delegated-delivery-a2");
600 const projectId = ProjectId.make("project:delegated-delivery-a2");
601 const runId = RunId.make("run:delegated-delivery-a2");
602 const rootNodeId = NodeId.make("node:delegated-delivery-a2-root");
603 const taskId = NodeId.make("node:delegated-delivery-a2-task");
604
605 yield* seedParentWithTerminalTask({
606 threadId,
607 projectId,
608 runId,
609 rootNodeId,
610 taskId,
611 deliveryState: "delivered",
612 completionWake: "always",
613 now,
614 });
615
616 // Distinct command IDs mirror task_status vs t3_thread_read racing after
617 // their shared read preflight saw delivered ownership.
618 const firstAck = yield* orchestrator.dispatch({
619 type: "delegated_task.completion-delivery.acknowledge",
620 commandId: CommandId.make("command:delegated-delivery-a2:ack-task-status"),
621 parentThreadId: threadId,
622 taskId,
623 observedByRunId: runId,
624 });
625 const secondAck = yield* orchestrator.dispatch({
626 type: "delegated_task.completion-delivery.acknowledge",
627 commandId: CommandId.make("command:delegated-delivery-a2:ack-thread-read"),
628 parentThreadId: threadId,
629 taskId,
630 observedByRunId: runId,
631 });
632
633 const firstAckTask = firstAck.storedEvents.find(
634 (stored) =>
635 stored.event.type === "subagent.updated" && stored.event.payload.id === taskId,
636 );
637 const secondAckTask = secondAck.storedEvents.find(
638 (stored) =>
639 stored.event.type === "subagent.updated" && stored.event.payload.id === taskId,
640 );
641 assert.isDefined(firstAckTask);
642 assert.isDefined(secondAckTask);
643 if (
644 firstAckTask?.event.type !== "subagent.updated" ||
645 secondAckTask?.event.type !== "subagent.updated"
646 ) {
647 return yield* Effect.die(new Error("Acknowledge events missing."));
648 }
649 assert.equal(firstAckTask.event.payload.completionDelivery?.state, "acknowledged");
650 assert.equal(secondAckTask.event.payload.completionDelivery?.state, "acknowledged");
651 // Idempotent replay keeps the first observation's ownership and timestamp.
652 assert.deepEqual(
653 secondAckTask.event.payload.completionDelivery,
654 firstAckTask.event.payload.completionDelivery,
655 );
656 assert.deepEqual(
657 secondAckTask.event.payload.updatedAt,
658 firstAckTask.event.payload.updatedAt,
659 );
660 assert.equal(secondAck.storedEvents.length, 1);
661
662 const afterAck = yield* orchestrator.getThreadProjection(threadId);
663 assert.deepEqual(
664 afterAck.subagents.find((candidate) => candidate.id === taskId)?.completionDelivery,
665 {
666 state: "acknowledged",
667 observedByRunId: runId,
668 },
669 );
670
671 const firstDispose = yield* orchestrator.dispatch({
672 type: "delegated_task.completion-delivery.dispose",
673 commandId: CommandId.make("command:delegated-delivery-a2:dispose-task-status"),
674 parentThreadId: threadId,
675 taskId,
676 });
677 const secondDispose = yield* orchestrator.dispatch({
678 type: "delegated_task.completion-delivery.dispose",
679 commandId: CommandId.make("command:delegated-delivery-a2:dispose-thread-read"),
680 parentThreadId: threadId,
681 taskId,
682 });
683
684 const firstDisposeTask = firstDispose.storedEvents.find(
685 (stored) =>
686 stored.event.type === "subagent.updated" && stored.event.payload.id === taskId,
687 );
688 const secondDisposeTask = secondDispose.storedEvents.find(
689 (stored) =>
690 stored.event.type === "subagent.updated" && stored.event.payload.id === taskId,
691 );
692 assert.isDefined(firstDisposeTask);
693 assert.isDefined(secondDisposeTask);
694 if (
695 firstDisposeTask?.event.type !== "subagent.updated" ||
696 secondDisposeTask?.event.type !== "subagent.updated"
697 ) {
698 return yield* Effect.die(new Error("Dispose events missing."));
699 }
700 assert.equal(firstDisposeTask.event.payload.completionDelivery?.state, "disposed");
701 assert.equal(secondDisposeTask.event.payload.completionDelivery?.state, "disposed");
702 assert.deepEqual(
703 secondDisposeTask.event.payload.completionDelivery,
704 firstDisposeTask.event.payload.completionDelivery,
705 );
706 assert.equal(secondDispose.storedEvents.length, 1);
707
708 const afterDispose = yield* orchestrator.getThreadProjection(threadId);
709 assert.deepEqual(
710 afterDispose.subagents.find((candidate) => candidate.id === taskId)?.completionDelivery,
711 {
712 state: "disposed",
713 observedByRunId: null,
714 },
715 );
716
717 const acknowledgeAfterDispose = yield* orchestrator.dispatch({
718 type: "delegated_task.completion-delivery.acknowledge",
719 commandId: CommandId.make("command:delegated-delivery-a2:ack-after-dispose"),
720 parentThreadId: threadId,
721 taskId,
722 observedByRunId: runId,
723 });
724 const acknowledgedTask = acknowledgeAfterDispose.storedEvents.find(
725 (stored) => stored.event.type === "subagent.updated",
726 );
727 if (acknowledgedTask?.event.type !== "subagent.updated") {
728 return yield* Effect.die(new Error("Acknowledge-after-dispose event missing."));
729 }
730 assert.deepEqual(acknowledgedTask.event.payload.completionDelivery, {
731 state: "disposed",
732 observedByRunId: null,
733 });
734 assert.equal(acknowledgeAfterDispose.storedEvents.length, 1);
735
736 const afterStaleAcknowledge = yield* orchestrator.getThreadProjection(threadId);
737 assert.deepEqual(
738 afterStaleAcknowledge.subagents.find((candidate) => candidate.id === taskId)
739 ?.completionDelivery,
740 {
741 state: "disposed",
742 observedByRunId: null,
743 },
744 );
745 }),
746 );
747});
748
749// Runtime reconciliation writes restart cancellations under this command
750// prefix, which the live terminal-run listener skips.
751const reconcileCommandId = (name: string) => CommandId.make(`command:runtime-reconcile:${name}`);
752
753const parentProviderThreadId = (threadId: ThreadId) =>
754 ProviderThreadId.make(`provider-thread:${String(threadId).replace("thread:", "")}`);
755
756const runEvent = (input: {
757 readonly threadId: ThreadId;
758 readonly runId: RunId;
759 readonly ordinal: number;
760 readonly status: OrchestrationV2Run["status"];
761 readonly now: DateTime.Utc;
762 readonly providerThreadId?: ProviderThreadId;
763 readonly userMessageId?: MessageId;
764 readonly delegatedCompletion?: OrchestrationV2Run["delegatedCompletion"];
765}) => ({
766 id: EventId.make(`event:${input.runId}:${input.status}`),
767 type: "run.updated" as const,
768 threadId: input.threadId,
769 runId: input.runId,
770 providerInstanceId: modelSelection.instanceId,
771 occurredAt: input.now,
772 payload: {
773 id: input.runId,
774 threadId: input.threadId,
775 ordinal: input.ordinal,
776 providerInstanceId: modelSelection.instanceId,
777 modelSelection,
778 providerThreadId: input.providerThreadId ?? null,
779 userMessageId: input.userMessageId ?? MessageId.make(`message:${input.runId}`),
780 rootNodeId: null,
781 activeAttemptId: null,
782 status: input.status,
783 requestedAt: input.now,
784 startedAt: input.now,
785 completedAt: input.status === "running" ? null : input.now,
786 checkpointId: null,
787 contextHandoffId: null,
788 ...(input.delegatedCompletion === undefined
789 ? {}
790 : { delegatedCompletion: input.delegatedCompletion }),
791 },
792});
793
794/** A running app-owned task whose child thread's first run the restart cancelled. */
795const seedRestartCancelledChild = (input: {
796 readonly parentThreadId: ThreadId;
797 readonly projectId: ProjectId;
798 readonly parentRunId: RunId;
799 readonly rootNodeId: NodeId;
800 readonly name: string;
801 readonly completionWake: "always" | "settled_only";
802 readonly continuationPending: boolean;
803 /** "completed" seeds a settled turn whose background work the restart cancelled. */
804 readonly runStatus?: "cancelled" | "completed";
805 readonly now: DateTime.Utc;
806}) =>
807 Effect.gen(function* () {
808 const eventSink = yield* EventSink.EventSinkV2;
809 const taskId = NodeId.make(`node:${input.name}`);
810 const childThreadId = ThreadId.make(`thread:${input.name}`);
811 const childRunId = RunId.make(`run:${input.name}:1`);
812 yield* eventSink.write({
813 commandId: CommandId.make(`command:seed-child:${input.name}`),
814 events: [
815 {
816 id: EventId.make(`event:${input.name}:thread`),
817 type: "thread.created",
818 threadId: childThreadId,
819 occurredAt: input.now,
820 payload: {
821 createdBy: "agent",
822 creationSource: "server",
823 id: childThreadId,
824 projectId: input.projectId,
825 title: input.name,
826 providerInstanceId: modelSelection.instanceId,
827 modelSelection,
828 runtimeMode: "full-access",
829 interactionMode: "default",
830 branch: null,
831 worktreePath: null,
832 activeProviderThreadId: null,
833 lineage: {
834 parentThreadId: input.parentThreadId,
835 relationshipToParent: "subagent",
836 rootThreadId: input.parentThreadId,
837 },
838 forkedFrom: { type: "node", nodeId: taskId },
839 createdAt: input.now,
840 updatedAt: input.now,
841 archivedAt: null,
842 settledOverride: null,
843 settledAt: null,
844 lastVisitedAt: null,
845 deletedAt: null,
846 },
847 },
848 {
849 id: EventId.make(`event:${input.name}:task`),
850 type: "subagent.updated",
851 threadId: input.parentThreadId,
852 runId: input.parentRunId,
853 nodeId: taskId,
854 driver,
855 providerInstanceId: modelSelection.instanceId,
856 occurredAt: input.now,
857 payload: {
858 id: taskId,
859 threadId: input.parentThreadId,
860 runId: input.parentRunId,
861 parentNodeId: input.rootNodeId,
862 origin: "app_owned",
863 createdBy: "agent",
864 driver,
865 providerInstanceId: modelSelection.instanceId,
866 providerThreadId: null,
867 childThreadId,
868 nativeTaskRef: null,
869 prompt: `Run ${input.name}.`,
870 title: null,
871 model: null,
872 completionWake: input.completionWake,
873 status: "running",
874 result: null,
875 startedAt: input.now,
876 completedAt: null,
877 updatedAt: input.now,
878 },
879 },
880 ],
881 });
882 yield* eventSink.writeWithEffects({
883 commandId: reconcileCommandId(input.name),
884 events: [
885 runEvent({
886 threadId: childThreadId,
887 runId: childRunId,
888 ordinal: 1,
889 status: input.runStatus ?? "cancelled",
890 now: input.now,
891 }),
892 ],
893 effects: input.continuationPending
894 ? [
895 {
896 id: `effect:restart-continuation:${childRunId}`,
897 commandId: reconcileCommandId(input.name),
898 threadId: childThreadId,
899 request: { type: "provider-runtime.continue", sourceRunId: childRunId },
900 },
901 ]
902 : [],
903 });
904 return { taskId, childThreadId, childRunId };
905 });
906
907it.layer(layerTest)("delegated tasks across a server restart", (it) => {
908 it.effect("holds a restart-cancelled child for its continuation's result", () =>
909 Effect.gen(function* () {
910 const orchestrator = yield* Orchestrator.OrchestratorV2;
911 const eventSink = yield* EventSink.EventSinkV2;
912 const now = yield* DateTime.now;
913 const threadId = ThreadId.make("thread:restart-parent");
914 const projectId = ProjectId.make("project:restart-parent");
915 const runId = RunId.make("run:restart-parent");
916 const rootNodeId = NodeId.make("node:restart-parent-root");
917 yield* seedParentWithTerminalTask({
918 threadId,
919 projectId,
920 runId,
921 rootNodeId,
922 taskId: NodeId.make("node:restart-parent-settled"),
923 deliveryState: "delivered",
924 now,
925 });
926 const child = (
927 name: string,
928 continuationPending: boolean,
929 runStatus?: "cancelled" | "completed",
930 ) =>
931 seedRestartCancelledChild({
932 parentThreadId: threadId,
933 projectId,
934 parentRunId: runId,
935 rootNodeId,
936 name,
937 completionWake: "always",
938 continuationPending,
939 ...(runStatus === undefined ? {} : { runStatus }),
940 now,
941 });
942 const resumed = yield* child("restart-resumed-child", true);
943 const stopped = yield* child("restart-stopped-child", false);
944 // Settled with only background work left: its interim reply is not the result.
945 const backgrounded = yield* child("restart-backgrounded-child", true, "completed");
946 // A second restart cut the first continuation before it started.
947 const recut = yield* child("restart-recut-child", false);
948 const recutContinuationId = RunId.make("run:restart-recut-child:2");
949 const recutCommandId = CommandId.make("command:restart-recut-child:reconcile");
950 const recutRun = runEvent({
951 threadId: recut.childThreadId,
952 runId: recutContinuationId,
953 ordinal: 2,
954 status: "cancelled",
955 now,
956 });
957 yield* eventSink.writeWithEffects({
958 commandId: recutCommandId,
959 events: [
960 {
961 ...recutRun,
962 payload: {
963 ...recutRun.payload,
964 startedAt: null,
965 restartContinuationOfRunId: recut.childRunId,
966 },
967 },
968 ],
969 effects: [
970 {
971 id: `effect:restart-continuation:${recutContinuationId}`,
972 commandId: recutCommandId,
973 threadId: recut.childThreadId,
974 request: { type: "provider-runtime.continue", sourceRunId: recutContinuationId },
975 },
976 ],
977 });
978
979 yield* orchestrator.recoverDelegatedTasks;
980
981 const recovered = yield* orchestrator.getThreadProjection(threadId);
982 const task = (id: NodeId) => recovered.subagents.find((row) => row.id === id);
983 assert.equal(task(stopped.taskId)?.status, "cancelled");
984 assert.equal(task(stopped.taskId)?.completionDelivery?.state, "claimed");
985 assert.equal(task(resumed.taskId)?.status, "running");
986 assert.isNull(task(resumed.taskId)?.result ?? null);
987 assert.equal(task(backgrounded.taskId)?.status, "running");
988 assert.isNull(task(backgrounded.taskId)?.result ?? null);
989 assert.equal(task(recut.taskId)?.status, "running");
990 assert.isTrue(yield* orchestrator.delegatedTaskResultPending(recut.childThreadId));
991 assert.isTrue(yield* orchestrator.delegatedTaskResultPending(resumed.childThreadId));
992 assert.isFalse(yield* orchestrator.delegatedTaskResultPending(stopped.childThreadId));
993 // A replayed first continuation settling must not release the second one's hold.
994 yield* orchestrator.recoverDelegatedTask(recut.childThreadId, recut.childRunId);
995 const replayed = yield* orchestrator.getThreadProjection(threadId);
996 assert.equal(replayed.subagents.find((row) => row.id === recut.taskId)?.status, "running");
997 // A caller that read the cancelled run before the child resumed sees it as pending.
998 yield* eventSink.write({
999 commandId: CommandId.make("command:restart-stopped-child:resumed"),
1000 events: [
1001 runEvent({
1002 threadId: stopped.childThreadId,
1003 runId: RunId.make("run:restart-stopped-child:2"),
1004 ordinal: 2,
1005 status: "running",
1006 now,
1007 }),
1008 ],
1009 });
1010 assert.isTrue(yield* orchestrator.delegatedTaskResultPending(stopped.childThreadId));
1011 assert.isFalse(
1012 recovered.contextTransfers.some(
1013 (transfer) => transfer.sourceThreadId === resumed.childThreadId,
1014 ),
1015 );
1016
1017 // The continuation's own run finishing settles the task with its result.
1018 const afterSequence = yield* eventSink.latestSequence();
1019 const continuationRunId = RunId.make("run:restart-resumed-child:2");
1020 yield* eventSink.write({
1021 commandId: CommandId.make("command:restart-resumed-child:completed"),
1022 events: [
1023 {
1024 id: EventId.make("event:restart-resumed-child:result"),
1025 type: "message.updated",
1026 threadId: resumed.childThreadId,
1027 runId: continuationRunId,
1028 occurredAt: now,
1029 payload: {
1030 id: MessageId.make("message:restart-resumed-child:result"),
1031 threadId: resumed.childThreadId,
1032 runId: continuationRunId,
1033 nodeId: null,
1034 role: "assistant",
1035 text: "Finished after the restart.",
1036 attachments: [],
1037 streaming: false,
1038 createdBy: "agent",
1039 creationSource: "server",
1040 createdAt: now,
1041 updatedAt: now,
1042 },
1043 },
1044 runEvent({
1045 threadId: resumed.childThreadId,
1046 runId: continuationRunId,
1047 ordinal: 2,
1048 status: "completed",
1049 now,
1050 }),
1051 ],
1052 });
1053 const settled = yield* eventSink
1054 .stream({ afterSequence, eventType: "subagent.updated" })
1055 .pipe(
1056 Stream.filter(
1057 (stored) =>
1058 stored.event.type === "subagent.updated" &&
1059 stored.event.payload.id === resumed.taskId,
1060 ),
1061 Stream.take(1),
1062 Stream.runHead,
1063 );
1064 assert.isTrue(settled._tag === "Some");
1065 const finished = yield* orchestrator.getThreadProjection(threadId);
1066 const finishedTask = finished.subagents.find((row) => row.id === resumed.taskId);
1067 assert.equal(finishedTask?.status, "completed");
1068 assert.equal(finishedTask?.result, "Finished after the restart.");
1069 }),
1070 );
1071
1072 it.effect("settles a restart-cancelled child whose continuation declines to start", () =>
1073 Effect.gen(function* () {
1074 const orchestrator = yield* Orchestrator.OrchestratorV2;
1075 const now = yield* DateTime.now;
1076 const threadId = ThreadId.make("thread:restart-declined-parent");
1077 const projectId = ProjectId.make("project:restart-declined-parent");
1078 const runId = RunId.make("run:restart-declined-parent");
1079 const rootNodeId = NodeId.make("node:restart-declined-parent-root");
1080 yield* seedParentWithTerminalTask({
1081 threadId,
1082 projectId,
1083 runId,
1084 rootNodeId,
1085 taskId: NodeId.make("node:restart-declined-parent-settled"),
1086 deliveryState: "delivered",
1087 now,
1088 });
1089 const child = yield* seedRestartCancelledChild({
1090 parentThreadId: threadId,
1091 projectId,
1092 parentRunId: runId,
1093 rootNodeId,
1094 name: "restart-declined-child",
1095 completionWake: "always",
1096 continuationPending: true,
1097 now,
1098 });
1099 yield* orchestrator.recoverDelegatedTasks;
1100 const held = yield* orchestrator.getThreadProjection(threadId);
1101 assert.equal(held.subagents.find((row) => row.id === child.taskId)?.status, "running");
1102
1103 yield* continueRestartedRun({
1104 threadId: child.childThreadId,
1105 sourceRunId: child.childRunId,
1106 }).pipe(
1107 Effect.provide(ServerSettings.layerTest({ continueThreadsAfterServerUpdate: false })),
1108 );
1109
1110 const settled = yield* orchestrator.getThreadProjection(threadId);
1111 const task = settled.subagents.find((row) => row.id === child.taskId);
1112 assert.equal(task?.status, "cancelled");
1113 assert.equal(task?.completionDelivery?.state, "claimed");
1114 }),
1115 );
1116
1117 // A running provider turn does not prove the provider consumed the delivery
1118 // (Claude marks the turn running before it reads the prompt), so a cut
1119 // delivery is offered again even when a continuation resumes that turn.
1120 it.effect("re-offers a cut delivery even when a continuation resumes its turn", () =>
1121 Effect.gen(function* () {
1122 const orchestrator = yield* Orchestrator.OrchestratorV2;
1123 const eventSink = yield* EventSink.EventSinkV2;
1124 const now = yield* DateTime.now;
1125 const seed = (name: string, continuationPending: boolean) =>
1126 Effect.gen(function* () {
1127 const threadId = ThreadId.make(`thread:${name}`);
1128 const runId = RunId.make(`run:${name}`);
1129 const taskId = NodeId.make(`node:${name}-task`);
1130 const messageId = MessageId.make(`message:delegated-delivery:${threadId}`);
1131 const deliveryRunId = RunId.make(`run:${name}:delivery`);
1132 yield* seedParentWithTerminalTask({
1133 threadId,
1134 projectId: ProjectId.make(`project:${name}`),
1135 runId,
1136 rootNodeId: NodeId.make(`node:${name}-root`),
1137 taskId,
1138 deliveryState: "claimed",
1139 completionWake: "always",
1140 deliveryTaskIds: [taskId],
1141 now,
1142 });
1143 yield* eventSink.writeWithEffects({
1144 commandId: reconcileCommandId(name),
1145 events: [
1146 {
1147 id: EventId.make(`event:${name}:delivery-message`),
1148 type: "message.updated",
1149 threadId,
1150 runId: deliveryRunId,
1151 occurredAt: now,
1152 payload: {
1153 id: messageId,
1154 threadId,
1155 runId: deliveryRunId,
1156 nodeId: null,
1157 role: "user",
1158 text: `Delegated task ${taskId} reached a terminal state.`,
1159 attachments: [],
1160 streaming: false,
1161 createdBy: "agent",
1162 creationSource: "server",
1163 createdAt: now,
1164 updatedAt: now,
1165 delegatedCompletion: { parentRunId: runId, generation: 1, taskIds: [taskId] },
1166 },
1167 },
1168 runEvent({
1169 threadId,
1170 runId: deliveryRunId,
1171 ordinal: 2,
1172 status: "cancelled",
1173 now,
1174 providerThreadId: parentProviderThreadId(threadId),
1175 userMessageId: messageId,
1176 }),
1177 ],
1178 effects: continuationPending
1179 ? [
1180 {
1181 id: `effect:restart-continuation:${deliveryRunId}`,
1182 commandId: reconcileCommandId(name),
1183 threadId,
1184 request: { type: "provider-runtime.continue", sourceRunId: deliveryRunId },
1185 },
1186 ]
1187 : [],
1188 });
1189 return { threadId, runId, taskId };
1190 });
1191 const cut = yield* seed("delivery-cut", false);
1192 const resumed = yield* seed("delivery-resumed", true);
1193
1194 yield* orchestrator.recoverDelegatedTasks;
1195
1196 for (const seeded of [cut, resumed]) {
1197 const projection = yield* orchestrator.getThreadProjection(seeded.threadId);
1198 assert.deepEqual(
1199 projection.subagents.find((row) => row.id === seeded.taskId)?.completionDelivery?.state,
1200 "claimed",
1201 );
1202 const delivery = projection.runs.find((row) => row.id === seeded.runId)?.delegatedCompletion
1203 ?.delivery;
1204 assert.equal(delivery?.generation, 2);
1205 assert.deepEqual(delivery?.taskIds, [seeded.taskId]);
1206 }
1207 }),
1208 );
1209
1210 it.effect("settles a cancelled child whose held wakes wait behind it", () =>
1211 Effect.gen(function* () {
1212 const orchestrator = yield* Orchestrator.OrchestratorV2;
1213 const eventSink = yield* EventSink.EventSinkV2;
1214 const now = yield* DateTime.now;
1215 const threadId = ThreadId.make("thread:held-wake-parent");
1216 const projectId = ProjectId.make("project:held-wake-parent");
1217 const runId = RunId.make("run:held-wake-parent");
1218 const rootNodeId = NodeId.make("node:held-wake-parent-root");
1219 yield* seedParentWithTerminalTask({
1220 threadId,
1221 projectId,
1222 runId,
1223 rootNodeId,
1224 taskId: NodeId.make("node:held-wake-parent-settled"),
1225 deliveryState: "delivered",
1226 now,
1227 });
1228 const child = yield* seedRestartCancelledChild({
1229 parentThreadId: threadId,
1230 projectId,
1231 parentRunId: runId,
1232 rootNodeId,
1233 name: "held-wake-child",
1234 completionWake: "always",
1235 continuationPending: false,
1236 now,
1237 });
1238 // Pull request watch wakes queued while the child ran; the restart held them.
1239 const held = runEvent({
1240 threadId: child.childThreadId,
1241 runId: RunId.make("run:held-wake-child:2"),
1242 ordinal: 2,
1243 status: "queued",
1244 now,
1245 });
1246 yield* eventSink.write({
1247 commandId: CommandId.make("command:held-wake-child:held"),
1248 events: [
1249 {
1250 ...held,
1251 payload: { ...held.payload, startedAt: null, completedAt: null, queueHeld: true },
1252 },
1253 ],
1254 });
1255
1256 yield* orchestrator.recoverDelegatedTasks;
1257
1258 const recovered = yield* orchestrator.getThreadProjection(threadId);
1259 const task = recovered.subagents.find((row) => row.id === child.taskId);
1260 assert.equal(task?.status, "cancelled");
1261 assert.isNotNull(task?.result ?? null);
1262 assert.isTrue(
1263 recovered.contextTransfers.some(
1264 (transfer) =>
1265 transfer.type === "subagent_result" && transfer.sourceThreadId === child.childThreadId,
1266 ),
1267 );
1268 assert.isFalse(yield* orchestrator.delegatedTaskResultPending(child.childThreadId));
1269 // The held wake stays held for the user to resume or discard.
1270 const childProjection = yield* orchestrator.getThreadProjection(child.childThreadId);
1271 assert.deepEqual(
1272 childProjection.runs.map((run) => [run.status, run.queueHeld ?? false]),
1273 [
1274 ["cancelled", false],
1275 ["queued", true],
1276 ],
1277 );
1278 }),
1279 );
1280
1281 it.effect("settles a child whose provider failure holds its queued wakes", () =>
1282 Effect.gen(function* () {
1283 const orchestrator = yield* Orchestrator.OrchestratorV2;
1284 const eventSink = yield* EventSink.EventSinkV2;
1285 const now = yield* DateTime.now;
1286 const threadId = ThreadId.make("thread:failed-hold-parent");
1287 const projectId = ProjectId.make("project:failed-hold-parent");
1288 const runId = RunId.make("run:failed-hold-parent");
1289 const rootNodeId = NodeId.make("node:failed-hold-parent-root");
1290 yield* seedParentWithTerminalTask({
1291 threadId,
1292 projectId,
1293 runId,
1294 rootNodeId,
1295 taskId: NodeId.make("node:failed-hold-parent-settled"),
1296 deliveryState: "delivered",
1297 now,
1298 });
1299 const child = yield* seedRestartCancelledChild({
1300 parentThreadId: threadId,
1301 projectId,
1302 parentRunId: runId,
1303 rootNodeId,
1304 name: "failed-hold-child",
1305 completionWake: "always",
1306 continuationPending: false,
1307 now,
1308 });
1309 // The child is resumed, and a wake queues behind its running turn.
1310 const activeRun = runEvent({
1311 threadId: child.childThreadId,
1312 runId: RunId.make("run:failed-hold-child:2"),
1313 ordinal: 2,
1314 status: "running",
1315 now,
1316 });
1317 const queued = runEvent({
1318 threadId: child.childThreadId,
1319 runId: RunId.make("run:failed-hold-child:3"),
1320 ordinal: 3,
1321 status: "queued",
1322 now,
1323 });
1324 yield* eventSink.write({
1325 commandId: CommandId.make("command:failed-hold-child:resumed"),
1326 events: [
1327 activeRun,
1328 { ...queued, payload: { ...queued.payload, startedAt: null, completedAt: null } },
1329 ],
1330 });
1331 const afterSequence = yield* eventSink.latestSequence();
1332 const errorItemId = TurnItemId.make("turn-item:failed-hold-child:error");
1333 yield* eventSink.write({
1334 commandId: CommandId.make("command:failed-hold-child:failed"),
1335 events: [
1336 {
1337 id: EventId.make("event:failed-hold-child:error"),
1338 type: "turn-item.updated",
1339 threadId: child.childThreadId,
1340 runId: activeRun.runId,
1341 providerInstanceId: modelSelection.instanceId,
1342 occurredAt: now,
1343 payload: {
1344 id: errorItemId,
1345 type: "error",
1346 threadId: child.childThreadId,
1347 runId: activeRun.runId,
1348 nodeId: null,
1349 providerThreadId: null,
1350 providerTurnId: null,
1351 nativeItemRef: null,
1352 parentItemId: null,
1353 ordinal: 1,
1354 status: "failed",
1355 title: "Provider failure",
1356 startedAt: now,
1357 completedAt: now,
1358 updatedAt: now,
1359 failure: {
1360 class: "provider_error",
1361 message: "Provider failed.",
1362 code: "provider_failed",
1363 retryable: null,
1364 },
1365 },
1366 },
1367 {
1368 ...activeRun,
1369 id: EventId.make("event:failed-hold-child:failed"),
1370 payload: { ...activeRun.payload, status: "failed", completedAt: now },
1371 },
1372 ],
1373 });
1374
1375 // The failure holds the queue, which leaves the failure as the task's result.
1376 const settled = yield* eventSink
1377 .stream({ afterSequence, eventType: "subagent.updated" })
1378 .pipe(
1379 Stream.filter(
1380 (stored) =>
1381 stored.event.type === "subagent.updated" && stored.event.payload.id === child.taskId,
1382 ),
1383 Stream.take(1),
1384 Stream.runHead,
1385 );
1386 assert.isTrue(settled._tag === "Some");
1387 const recovered = yield* orchestrator.getThreadProjection(threadId);
1388 assert.equal(recovered.subagents.find((row) => row.id === child.taskId)?.status, "failed");
1389 const childProjection = yield* orchestrator.getThreadProjection(child.childThreadId);
1390 assert.deepEqual(
1391 childProjection.runs.map((run) => [run.status, run.queueHeld ?? false]),
1392 [
1393 ["cancelled", false],
1394 ["failed", false],
1395 ["queued", true],
1396 ],
1397 );
1398 }),
1399 );
1400
1401 it.effect("wakes the parent for a settled_only task once its spawning turn ended", () =>
1402 Effect.gen(function* () {
1403 const orchestrator = yield* Orchestrator.OrchestratorV2;
1404 const eventSink = yield* EventSink.EventSinkV2;
1405 const now = yield* DateTime.now;
1406 const threadId = ThreadId.make("thread:settled-only-restart");
1407 const projectId = ProjectId.make("project:settled-only-restart");
1408 const runId = RunId.make("run:settled-only-restart");
1409 const rootNodeId = NodeId.make("node:settled-only-restart-root");
1410 yield* seedParentWithTerminalTask({
1411 threadId,
1412 projectId,
1413 runId,
1414 rootNodeId,
1415 taskId: NodeId.make("node:settled-only-restart-settled"),
1416 deliveryState: "delivered",
1417 now,
1418 });
1419 // The restart cut the turn blocked in delegate_task(wait); its
1420 // continuation is a new, live run.
1421 yield* eventSink.write({
1422 commandId: reconcileCommandId("settled-only-restart"),
1423 events: [
1424 runEvent({
1425 threadId,
1426 runId,
1427 ordinal: 1,
1428 status: "cancelled",
1429 now,
1430 providerThreadId: parentProviderThreadId(threadId),
1431 userMessageId: MessageId.make(`message:seed-user:${threadId}`),
1432 delegatedCompletion: { disposition: "open", nextGeneration: 2, delivery: null },
1433 }),
1434 runEvent({
1435 threadId,
1436 runId: RunId.make("run:settled-only-restart:continuation"),
1437 ordinal: 2,
1438 status: "running",
1439 now,
1440 providerThreadId: parentProviderThreadId(threadId),
1441 }),
1442 ],
1443 });
1444 const child = yield* seedRestartCancelledChild({
1445 parentThreadId: threadId,
1446 projectId,
1447 parentRunId: runId,
1448 rootNodeId,
1449 name: "settled-only-restart-child",
1450 completionWake: "settled_only",
1451 continuationPending: false,
1452 now,
1453 });
1454
1455 yield* orchestrator.recoverDelegatedTasks;
1456
1457 const projection = yield* orchestrator.getThreadProjection(threadId);
1458 assert.equal(
1459 projection.subagents.find((row) => row.id === child.taskId)?.completionDelivery?.state,
1460 "claimed",
1461 );
1462 assert.deepEqual(
1463 projection.runs.find((row) => row.id === runId)?.delegatedCompletion?.delivery?.taskIds,
1464 [child.taskId],
1465 );
1466 }),
1467 );
1468});