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

ClaudeAutomaticDelivery.integration.test.ts

886 lines34.0 KB

1import type { SDKMessage, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, it } from "@effect/vitest";
5import {
6 ClaudeSettings,
7 CommandId,
8 EventId,
9 MessageId,
10 NodeId,
11 ProjectId,
12 ProviderInstanceId,
13 ScheduledTaskUpsertInput,
14 ThreadId,
15 type OrchestrationV2DomainEvent,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Deferred from "effect/Deferred";
19import * as SecureRandom from "effect/crypto/SecureRandom";
20import * as Effect from "effect/Effect";
21import * as FileSystem from "effect/FileSystem";
22import * as Fiber from "effect/Fiber";
23import * as Layer from "effect/Layer";
24import * as Path from "effect/Path";
25import * as Queue from "effect/Queue";
26import * as Schema from "effect/Schema";
27import * as Stream from "effect/Stream";
28import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
29import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
30import * as SecretRequests from "../secrets/SecretRequests.ts";
31import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
32import * as Scheduler from "../scheduling/Scheduler.ts";
33import * as SqlitePersistence from "../persistence/Sqlite.ts";
34import * as ClaudeAdapterV2 from "./Adapters/ClaudeAdapterV2.ts";
35import * as CommandReceiptStore from "./CommandReceiptStore.ts";
36import * as EffectWorker from "./EffectWorker.ts";
37import * as EventSink from "./EventSink.ts";
38import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
39import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
40import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
41import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
42import * as Orchestrator from "./Orchestrator.ts";
43import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
44import * as ThreadLaunchService from "./ThreadLaunchService.ts";
45import * as ThreadManagementService from "./ThreadManagementService.ts";
46import * as ServerSettings from "../serverSettings.ts";
47import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
48import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
49​
50const sessionId = "automatic-delivery-session";
51const settings = Schema.decodeSync(ClaudeSettings)({});
52const decodeScheduledTask = Schema.decodeEffect(ScheduledTaskUpsertInput);
53const refusal =
54 "The user doesn't want to take this action right now. STOP what you are doing and wait for the user to tell you how to proceed.";
55const statusIds = ["status-1", "status-2", "status-3", "status-4"];
56const modelSelection = {
57 instanceId: ProviderInstanceId.make("claudeAgent"),
58 model: "claude-sonnet-4-6",
59};
60​
61function frame(value: unknown): SDKMessage {
62 return value as SDKMessage;
64​
65const batch = frame({
66 type: "assistant",
67 uuid: "batch",
68 session_id: sessionId,
69 parent_tool_use_id: null,
70 message: {
71 id: "tool-batch",
72 role: "assistant",
73 type: "message",
74 model: modelSelection.model,
75 content: [
76 { type: "tool_use", id: "build", name: "Bash", input: { command: "make" } },
77 ...statusIds.map((id) => ({
78 type: "tool_use",
79 id,
80 name: "mcp__t3-code__task_status",
81 input: { taskId: id },
82 })),
83 ],
84 stop_reason: "tool_use",
85 stop_sequence: null,
86 usage: { input_tokens: 1, output_tokens: 1 },
87 },
88});
89​
90const toolResult = (id: string, cancelled: boolean) =>
91 frame({
92 type: "user",
93 uuid: `result-${id}`,
94 session_id: sessionId,
95 parent_tool_use_id: null,
96 message: {
97 role: "user",
98 content: [
99 {
100 type: "tool_result",
101 tool_use_id: id,
102 is_error: cancelled,
103 content: cancelled ? refusal : id === "build" ? "build OK" : "Task completed normally",
104 },
105 ],
106 },
107 ...(cancelled ? { tool_result_meta: [{ id, non_execution_kind: "cancelled" }] } : {}),
108 });
109​
110const result = (uuid: string, aborted: boolean) =>
111 frame({
112 type: "result",
113 subtype: "success",
114 uuid,
115 session_id: sessionId,
116 is_error: false,
117 num_turns: 1,
118 result: "",
119 stop_reason: "end_turn",
120 terminal_reason: aborted ? "aborted_tools" : "completed",
121 permission_denials: [],
122 duration_ms: 1,
123 duration_api_ms: 1,
124 total_cost_usd: 0,
125 usage: { input_tokens: 1, output_tokens: 1 },
126 modelUsage: {},
127 });
128​
129const deliveries = [
130 "child completion",
131 "scheduled message",
132 "user steering",
133 "promoted queued message",
134] as const;
135​
136it.effect.each(deliveries)(
137 "delivers %s with Claude's native pending-tool cancellation behavior",
138 (delivery) =>
139 Effect.gen(function* () {
140 const cwd = yield* checkpointWorkspace("claude-automatic-delivery");
141 const sdkMessages = yield* Queue.unbounded<SDKMessage>();
142 const offers: SDKUserMessage[] = [];
143 const nativeQueue: SDKUserMessage[] = [];
144 // @effect-diagnostics-next-line abortControllerInEffect:off - The fake SDK interrupts its batch independently of the test fiber.
145 const batchAbort = new AbortController();
146 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
147 instanceId: modelSelection.instanceId,
148 settings,
149 environment: {},
150 attachmentsDir: cwd,
151 fileSystem: yield* FileSystem.FileSystem,
152 path: yield* Path.Path,
153 random: yield* SecureRandom.SecureRandom,
154 idAllocator: yield* IdAllocator.IdAllocatorV2,
155 queryRunner: {
156 allocateSessionId: Effect.succeed(sessionId),
157 open: () =>
158 Effect.succeed({
159 messages: Stream.fromQueue(sdkMessages),
160 offer: (message) =>
161 Effect.sync(() => {
162 offers.push(message);
163 nativeQueue.push(message);
164 // Claude Code 2.1.289 aborts on now-priority commands even while Bash blocks reads.
165 if (nativeQueue.some((command) => command.priority === "now")) {
166 batchAbort.abort({ kind: "interrupt" });
167 }
168 }),
169 setModel: () => Effect.void,
170 applyFlagSettings: () => Effect.void,
171 setPermissionMode: () => Effect.void,
172 backgroundTasks: () => Effect.succeed(false),
173 mcpServerStatus: Effect.succeed([]),
174 readMcpResource: () => Effect.die("unexpected MCP resource read"),
175 callMcpTool: () => Effect.die("unexpected MCP tool call"),
176 listPermissionRules: Effect.die("unexpected permission rules read"),
177 stopTask: () => Effect.void,
178 interrupt: Effect.die("automatic delivery must never interrupt"),
179 close: Effect.void,
180 }),
181 forkSession: () => Effect.die("unused"),
182 subagentLaunchToolUseId: () => Effect.succeed(null),
183 subagentModel: () => Effect.succeed(null),
184 assertComplete: Effect.void,
185 },
186 });
187 yield* Effect.gen(function* () {
188 const orchestrator = yield* Orchestrator.OrchestratorV2;
189 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
190 const threadId = ThreadId.make("thread:automatic-delivery");
191 const projectId = ProjectId.make("project:automatic-delivery");
192 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
193 orchestrator.streamDomainEvents.pipe(
194 Stream.filter(predicate),
195 Stream.take(1),
196 Stream.runDrain,
197 Effect.forkScoped,
198 );
199 yield* orchestrator.dispatch({
200 type: "thread.create",
201 commandId: CommandId.make("create"),
202 threadId,
203 projectId,
204 title: "Automatic delivery",
205 modelSelection,
206 runtimeMode: "full-access",
207 interactionMode: "default",
208 branch: null,
209 worktreePath: cwd,
210 createdBy: "user",
211 creationSource: "web",
212 });
213 const running = yield* watch(
214 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
215 );
216 yield* orchestrator.dispatch({
217 type: "message.dispatch",
218 commandId: CommandId.make("first"),
219 threadId,
220 messageId: MessageId.make("first"),
221 text: "Build and check all four tasks.",
222 attachments: [],
223 dispatchMode: { type: "start_immediately" },
224 createdBy: "user",
225 creationSource: "web",
226 });
227 yield* worker.drain();
228 yield* Fiber.join(running);
229 const pending = yield* watch(
230 (event) =>
231 event.type === "turn-item.updated" &&
232 event.payload.nativeItemRef?.nativeId === "status-4",
233 );
234 yield* Queue.offer(sdkMessages, batch);
235 yield* Fiber.join(pending);
236 const before = yield* orchestrator.getThreadProjection(threadId);
237 assert.equal(before.turnItems.filter((item) => item.status === "running").length, 5);
238 const parent = before.runs[0]!;
239 if (parent.rootNodeId === null) return yield* Effect.die("parent has no root node");
240 const messageId = MessageId.make("automatic-notice");
241 if (delivery === "child completion") {
242 const taskId = NodeId.make("completed-child");
243 const now = yield* DateTime.now;
244 const sink = yield* EventSink.EventSinkV2;
245 yield* sink.write({
246 events: [
247 {
248 id: EventId.make("cohort"),
249 type: "run.updated",
250 threadId,
251 runId: parent.id,
252 occurredAt: now,
253 payload: {
254 ...parent,
255 delegatedCompletion: {
256 disposition: "open",
257 nextGeneration: 2,
258 delivery: { generation: 1, messageId, taskIds: [taskId] },
259 },
260 },
261 },
262 {
263 id: EventId.make("child"),
264 type: "subagent.updated",
265 threadId,
266 runId: parent.id,
267 nodeId: taskId,
268 occurredAt: now,
269 payload: {
270 id: taskId,
271 threadId,
272 runId: parent.id,
273 parentNodeId: parent.rootNodeId,
274 origin: "app_owned",
275 createdBy: "agent",
276 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
277 providerInstanceId: modelSelection.instanceId,
278 providerThreadId: null,
279 childThreadId: null,
280 nativeTaskRef: null,
281 prompt: "Background work",
282 title: "Child",
283 model: null,
284 completionWake: "always",
285 completionDelivery: { state: "claimed", observedByRunId: null },
286 status: "completed",
287 result: "done",
288 startedAt: now,
289 completedAt: now,
290 updatedAt: now,
291 },
292 },
293 ],
294 });
295 const command = {
296 type: "message.dispatch" as const,
297 commandId: CommandId.make("completion"),
298 threadId,
299 messageId,
300 text: "Child completed",
301 attachments: [],
302 dispatchMode: { type: "queue_after_active" as const },
303 createdBy: "agent" as const,
304 creationSource: "server" as const,
305 delegatedCompletion: { parentRunId: parent.id, generation: 1, taskIds: [taskId] },
306 };
307 yield* orchestrator.dispatch(command);
308 yield* orchestrator.dispatch(command);
309 yield* orchestrator.recoverDelegatedTasks;
310 } else if (delivery === "scheduled message") {
311 yield* Effect.gen(function* () {
312 const service = yield* ScheduledTaskService.ScheduledTaskService;
313 const { task } = yield* service.upsert(
314 yield* decodeScheduledTask({
315 title: "Status check",
316 prompt: "Check the four tasks.",
317 enabled: true,
318 schedule: { type: "interval", everyMs: 60_000 },
319 projectId,
320 threadId,
321 workspaceStrategy: { type: "root" },
322 modelSelection,
323 runtimeMode: "full-access",
324 interactionMode: "default",
325 }),
326 );
327 const ran = yield* service.runNow({ id: task.id });
328 assert.equal(ran.task.lastRunStatus, "succeeded");
329 }).pipe(
330 Effect.provide(
331 ScheduledTaskService.layer.pipe(
332 Layer.provide(ThreadManagementService.layer),
333 Layer.provide(ServerSettings.layerTest()),
334 Layer.provide(
335 Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
336 ensureTranscript: () =>
337 Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
338 }),
339 ),
340 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
341 Layer.provide(ManagedPolicy.layerTest()),
342 Layer.provide(
343 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
344 namedProjectsRoot: "/projects",
345 isScratchProject: () => Effect.succeed(false),
346 }),
347 ),
348 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
349 Layer.provide(
350 CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
351 ),
352 Layer.provide(
353 Layer.mergeAll(NodeCrypto.layer, Scheduler.layer, SqlitePersistence.layerMemory),
354 ),
355 ),
356 ),
357 );
358 } else if (delivery === "user steering") {
359 yield* orchestrator.dispatch({
360 type: "message.dispatch",
361 commandId: CommandId.make("steer"),
362 threadId,
363 messageId,
364 text: "Change direction now.",
365 attachments: [],
366 dispatchMode: { type: "steer_active", targetRunId: parent.id },
367 createdBy: "user",
368 creationSource: "web",
369 });
370 } else {
371 yield* orchestrator.dispatch({
372 type: "message.dispatch",
373 commandId: CommandId.make("queue"),
374 threadId,
375 messageId,
376 text: "Change direction now.",
377 attachments: [],
378 dispatchMode: { type: "queue_after_active" },
379 createdBy: "user",
380 creationSource: "web",
381 });
382 const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!;
383 yield* orchestrator.dispatch({
384 type: "queued-message.promote-to-steer",
385 commandId: CommandId.make("promote"),
386 threadId,
387 queuedRunId: queuedRun.id,
388 targetRunId: parent.id,
389 });
390 const promoted = yield* orchestrator.getThreadProjection(threadId);
391 assert.equal(promoted.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled");
392 assert.equal(
393 promoted.messages.find((message) => message.id === messageId)?.runId,
394 parent.id,
395 );
396 const steer = promoted.turnItems.find(
397 (item) => item.type === "user_message" && item.messageId === messageId,
398 );
399 assert.ok(steer?.type === "user_message");
400 assert.equal(steer.inputIntent, "promoted_queued_to_steer");
401 }
402 yield* worker.drain();
403 const explicitSteer =
404 delivery === "user steering" || delivery === "promoted queued message";
405 assert.equal(batchAbort.signal.aborted, explicitSteer);
406 assert.equal(offers.length, explicitSteer ? 2 : 1);
407 const finished = yield* watch(
408 (event) =>
409 event.type === "run.updated" &&
410 event.payload.id === parent.id &&
411 event.payload.status === "waiting",
412 );
413 yield* Queue.offer(sdkMessages, toolResult("build", false));
414 for (const id of statusIds)
415 yield* Queue.offer(sdkMessages, toolResult(id, batchAbort.signal.aborted));
416 if (explicitSteer) yield* Queue.offer(sdkMessages, result("aborted", true));
417 yield* Queue.offer(sdkMessages, result("completed", false));
418 yield* Fiber.join(finished);
419 yield* worker.drain();
420 yield* orchestrator.resumeQueuedRuns;
421 yield* worker.drain();
422 if (!explicitSteer) {
423 const queued = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!;
424 const noticeFinished = yield* watch(
425 (event) =>
426 event.type === "run.updated" &&
427 event.payload.id === queued.id &&
428 event.payload.status === "waiting",
429 );
430 const delivered =
431 delivery === "child completion"
432 ? yield* watch(
433 (event) =>
434 event.type === "subagent.updated" &&
435 event.payload.completionDelivery?.state === "delivered",
436 )
437 : null;
438 yield* Queue.offer(sdkMessages, result("notice-completed", false));
439 yield* Fiber.join(noticeFinished);
440 yield* worker.drain();
441 if (delivered !== null) yield* Fiber.join(delivered);
442 }
443 const after = yield* orchestrator.getThreadProjection(threadId);
444 const reads = after.turnItems.filter((item) =>
445 statusIds.includes(item.nativeItemRef?.nativeId ?? ""),
446 );
447 assert.equal(reads.length, 4);
448 for (const read of reads) {
449 assert.equal(read.status, explicitSteer ? "cancelled" : "completed");
450 assert.equal(read.toolNonExecutionKind, explicitSteer ? "cancelled" : undefined);
451 assert.equal(read.type === "dynamic_tool" && read.output === refusal, explicitSteer);
452 }
453 assert.equal(offers.length, 2);
454 assert.equal(
455 offers.filter((offer) => offer.priority === "now").length,
456 explicitSteer ? 1 : 0,
457 );
458 if (!explicitSteer) {
459 assert.equal(after.runs.length, 2);
460 if (delivery === "child completion") {
461 assert.equal(after.messages.filter((message) => message.id === messageId).length, 1);
462 assert.equal(after.subagents[0]?.completionDelivery?.state, "delivered");
463 } else {
464 assert.equal(
465 after.messages.filter((message) => message.scheduledTaskId !== undefined).length,
466 1,
467 );
468 }
469 }
470 yield* orchestrator.recoverDelegatedTasks;
471 yield* orchestrator.resumeQueuedRuns;
472 yield* worker.drain();
473 assert.equal(offers.length, 2);
474 }).pipe(
475 Effect.provide(
476 ProviderReplayHarness.layerWithRegistry(
477 { name: "claude-automatic-delivery" },
478 ProviderAdapterRegistry.layerSingle(adapter),
479 { runEffectWorker: false },
480 ),
481 ),
482 );
483 }).pipe(
484 Effect.provide(
485 Layer.mergeAll(
486 IdAllocator.layer,
487 McpProviderSessions.layer,
488 NodeServices.layer,
489 NodeCrypto.layer,
490 ),
491 ),
492 ),
493);
494​
495it.effect("applies an effort change to the running Claude query without waiting for a turn", () =>
496 Effect.gen(function* () {
497 const cwd = yield* checkpointWorkspace("claude-live-effort");
498 const sdkMessages = yield* Queue.unbounded<SDKMessage>();
499 const flagSettings: unknown[] = [];
500 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
501 instanceId: modelSelection.instanceId,
502 settings,
503 environment: {},
504 attachmentsDir: cwd,
505 fileSystem: yield* FileSystem.FileSystem,
506 path: yield* Path.Path,
507 random: yield* SecureRandom.SecureRandom,
508 idAllocator: yield* IdAllocator.IdAllocatorV2,
509 queryRunner: {
510 allocateSessionId: Effect.succeed(sessionId),
511 open: () =>
512 Effect.succeed({
513 messages: Stream.fromQueue(sdkMessages),
514 offer: () => Effect.void,
515 setModel: () => Effect.void,
516 applyFlagSettings: (flags) =>
517 Effect.sync(() => {
518 flagSettings.push(flags);
519 }),
520 setPermissionMode: () => Effect.void,
521 backgroundTasks: () => Effect.succeed(false),
522 mcpServerStatus: Effect.succeed([]),
523 readMcpResource: () => Effect.die("unexpected MCP resource read"),
524 callMcpTool: () => Effect.die("unexpected MCP tool call"),
525 listPermissionRules: Effect.die("unexpected permission rules read"),
526 stopTask: () => Effect.void,
527 interrupt: Effect.die("an effort change must not interrupt the turn"),
528 close: Effect.void,
529 }),
530 forkSession: () => Effect.die("unused"),
531 subagentLaunchToolUseId: () => Effect.succeed(null),
532 subagentModel: () => Effect.succeed(null),
533 assertComplete: Effect.void,
534 },
535 });
536 yield* Effect.gen(function* () {
537 const orchestrator = yield* Orchestrator.OrchestratorV2;
538 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
539 const threadId = ThreadId.make("thread:live-effort");
540 const high = { ...modelSelection, options: [{ id: "effort", value: "high" }] };
541 const running = yield* orchestrator.streamDomainEvents.pipe(
542 Stream.filter(
543 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
544 ),
545 Stream.take(1),
546 Stream.runDrain,
547 Effect.forkScoped,
548 );
549 yield* orchestrator.dispatch({
550 type: "thread.create",
551 commandId: CommandId.make("create"),
552 threadId,
553 projectId: ProjectId.make("project:live-effort"),
554 title: "Live effort",
555 modelSelection: high,
556 runtimeMode: "full-access",
557 interactionMode: "default",
558 branch: null,
559 worktreePath: cwd,
560 createdBy: "user",
561 creationSource: "web",
562 });
563 yield* orchestrator.dispatch({
564 type: "message.dispatch",
565 commandId: CommandId.make("first"),
566 threadId,
567 messageId: MessageId.make("first"),
568 text: "Keep working.",
569 attachments: [],
570 dispatchMode: { type: "start_immediately" },
571 createdBy: "user",
572 creationSource: "web",
573 });
574 yield* worker.drain();
575 yield* Fiber.join(running);
576 assert.deepEqual(flagSettings, []);
577​
578 yield* orchestrator.dispatch({
579 type: "thread.model-selection.set",
580 commandId: CommandId.make("medium"),
581 threadId,
582 modelSelection: { ...modelSelection, options: [{ id: "effort", value: "medium" }] },
583 });
584 yield* worker.drain();
585​
586 assert.deepEqual(flagSettings, [{ effortLevel: "medium", fastMode: null, ultracode: null }]);
587 }).pipe(
588 Effect.provide(
589 ProviderReplayHarness.layerWithRegistry(
590 { name: "claude-live-effort" },
591 ProviderAdapterRegistry.layerSingle(adapter),
592 { runEffectWorker: false },
593 ),
594 ),
595 );
596 }).pipe(
597 Effect.provide(
598 Layer.mergeAll(
599 IdAllocator.layer,
600 McpProviderSessions.layer,
601 NodeServices.layer,
602 NodeCrypto.layer,
603 ),
604 ),
605 ),
606);
607​
608const backgroundTaskStarted = (taskId: string) =>
609 frame({
610 type: "system",
611 subtype: "task_started",
612 task_id: taskId,
613 tool_use_id: `tool-${taskId}`,
614 description: "Background build",
615 is_backgrounded: true,
616 task_type: "local_bash",
617 uuid: `started-${taskId}`,
618 session_id: sessionId,
619 });
620​
621const backgroundTaskNotification = (taskId: string) =>
622 frame({
623 type: "system",
624 subtype: "task_notification",
625 task_id: taskId,
626 tool_use_id: `tool-${taskId}`,
627 status: "completed",
628 output_file: `/tmp/claude-replay/tasks/${taskId}.output`,
629 summary: `Background build ${taskId} completed`,
630 uuid: `notification-${taskId}`,
631 session_id: sessionId,
632 });
633​
634const wakeAssistant = (uuid: string) =>
635 frame({
636 type: "assistant",
637 uuid,
638 session_id: sessionId,
639 parent_tool_use_id: null,
640 message: {
641 id: `msg-${uuid}`,
642 role: "assistant",
643 type: "message",
644 model: modelSelection.model,
645 content: [{ type: "text", text: `Background build finished (${uuid}).` }],
646 stop_reason: null,
647 stop_sequence: null,
648 usage: { input_tokens: 1, output_tokens: 1 },
649 },
650 });
651​
652it.effect("offers a continuation for a later wake after a queued continuation is cancelled", () =>
653 Effect.gen(function* () {
654 const cwd = yield* checkpointWorkspace("claude-cancelled-continuation");
655 const sdkMessages = yield* Queue.unbounded<SDKMessage>();
656 const processed = new WeakMap<SDKMessage, Deferred.Deferred<void>>();
657 const offerAndWait = Effect.fnUntraced(function* (message: SDKMessage) {
658 const done = yield* Deferred.make<void>();
659 processed.set(message, done);
660 yield* Queue.offer(sdkMessages, message);
661 yield* Deferred.await(done);
662 });
663 const fileSystem = yield* FileSystem.FileSystem;
664 const path = yield* Path.Path;
665 const random = yield* SecureRandom.SecureRandom;
666 const idAllocator = yield* IdAllocator.IdAllocatorV2;
667 const continuations: ProviderContinuationRequests.ProviderContinuationRequest[] = [];
668 const services =
669 yield* Effect.context<
670 Effect.Services<ReturnType<typeof ClaudeAdapterV2.makeClaudeAdapterV2>>
671 >();
672 const registry = ProviderAdapterRegistry.layerFromAdaptersEffect(
673 Effect.gen(function* () {
674 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
675 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
676 instanceId: modelSelection.instanceId,
677 settings,
678 environment: {},
679 attachmentsDir: cwd,
680 fileSystem,
681 path,
682 random,
683 idAllocator,
684 continuationRequests: {
685 offer: (request) =>
686 Effect.sync(() => continuations.push(request)).pipe(
687 Effect.andThen(requests.offer(request)),
688 ),
689 },
690 queryRunner: {
691 allocateSessionId: Effect.succeed(sessionId),
692 open: () =>
693 Effect.succeed({
694 // Resolve each frame's Deferred once the adapter pulls the next one.
695 messages: Stream.fromQueue(sdkMessages).pipe(
696 Stream.flatMap((message) =>
697 Stream.make(message).pipe(
698 Stream.concat(
699 Stream.fromEffect(
700 Effect.suspend(() => {
701 const done = processed.get(message);
702 return done === undefined
703 ? Effect.void
704 : Deferred.succeed(done, undefined);
705 }),
706 ).pipe(Stream.drain),
707 ),
708 ),
709 ),
710 ),
711 offer: () => Effect.void,
712 setModel: () => Effect.void,
713 applyFlagSettings: () => Effect.void,
714 setPermissionMode: () => Effect.void,
715 backgroundTasks: () => Effect.succeed(false),
716 mcpServerStatus: Effect.succeed([]),
717 readMcpResource: () => Effect.die("unexpected MCP resource read"),
718 callMcpTool: () => Effect.die("unexpected MCP tool call"),
719 listPermissionRules: Effect.die("unexpected permission rules read"),
720 stopTask: () => Effect.void,
721 interrupt: Effect.void,
722 close: Effect.void,
723 }),
724 forkSession: () => Effect.die("unused"),
725 subagentLaunchToolUseId: () => Effect.succeed(null),
726 subagentModel: () => Effect.succeed(null),
727 assertComplete: Effect.void,
728 },
729 }).pipe(Effect.provideContext(services));
730 return [adapter];
731 }),
732 );
733 yield* Effect.gen(function* () {
734 const orchestrator = yield* Orchestrator.OrchestratorV2;
735 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
736 const threadId = ThreadId.make("thread:cancelled-continuation");
737 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
738 orchestrator.streamDomainEvents.pipe(
739 Stream.filter(predicate),
740 Stream.take(1),
741 Stream.runDrain,
742 Effect.forkScoped,
743 );
744 const runUpdated = (messageId: string, status: string) =>
745 watch(
746 (event) =>
747 event.type === "run.updated" &&
748 event.payload.userMessageId === messageId &&
749 event.payload.status === status,
750 );
751 // A user turn that leaves a background task running when it ends.
752 const userTurnWithBackgroundTask = Effect.fnUntraced(function* (id: string, taskId: string) {
753 const running = yield* runUpdated(id, "running");
754 yield* orchestrator.dispatch({
755 type: "message.dispatch",
756 commandId: CommandId.make(id),
757 threadId,
758 messageId: MessageId.make(id),
759 text: "Run the build in the background.",
760 attachments: [],
761 dispatchMode: { type: "start_immediately" },
762 createdBy: "user",
763 creationSource: "web",
764 });
765 yield* worker.drain();
766 yield* Fiber.join(running);
767 const waiting = yield* runUpdated(id, "waiting");
768 yield* Queue.offer(sdkMessages, backgroundTaskStarted(taskId));
769 yield* Queue.offer(sdkMessages, result(`result-${id}`, false));
770 yield* Fiber.join(waiting);
771 });
772 yield* orchestrator.dispatch({
773 type: "thread.create",
774 commandId: CommandId.make("create"),
775 threadId,
776 projectId: ProjectId.make("project:cancelled-continuation"),
777 title: "Cancelled continuation",
778 modelSelection,
779 runtimeMode: "full-access",
780 interactionMode: "default",
781 branch: null,
782 worktreePath: cwd,
783 createdBy: "user",
784 creationSource: "web",
785 });
786​
787 // The first run is still finalizing when its background task wakes Claude.
788 yield* userTurnWithBackgroundTask("first", "build-1");
789 const queued = yield* watch(
790 (event) => event.type === "run.created" && event.payload.status === "queued",
791 );
792 yield* offerAndWait(backgroundTaskNotification("build-1"));
793 yield* offerAndWait(wakeAssistant("wake-1"));
794 yield* Fiber.join(queued);
795 assert.lengthOf(continuations, 1);
796 const continuationRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
797 (run) => run.status === "queued",
798 );
799 assert.ok(continuationRun !== undefined);
800 yield* orchestrator.dispatch({
801 type: "queued-run.cancel",
802 commandId: CommandId.make("cancel"),
803 threadId,
804 runId: continuationRun.id,
805 });
806 yield* offerAndWait(result("wake-1-result", false));
807 yield* worker.drain();
808 yield* orchestrator.resumeQueuedRuns;
809 yield* worker.drain();
810 const idle = yield* orchestrator.getThreadProjection(threadId);
811 assert.equal(idle.runs.find((run) => run.id === continuationRun.id)?.status, "cancelled");
812 assert.isFalse(idle.runs.some((run) => run.status === "queued"));
813​
814 yield* userTurnWithBackgroundTask("second", "build-2");
815 yield* worker.drain();
816 // The second user run has completed, so this continuation starts without queueing.
817 const isContinuationRun = (event: OrchestrationV2DomainEvent, type: string, status: string) =>
818 (event.type === "run.created" || event.type === "run.updated") &&
819 event.type === type &&
820 event.payload.status === status &&
821 event.payload.userMessageId !== MessageId.make("first") &&
822 event.payload.userMessageId !== MessageId.make("second");
823 const secondCreated = yield* watch((event) =>
824 isContinuationRun(event, "run.created", "starting"),
825 );
826 const secondRunning = yield* watch((event) =>
827 isContinuationRun(event, "run.updated", "running"),
828 );
829 yield* offerAndWait(backgroundTaskNotification("build-2"));
830 yield* offerAndWait(wakeAssistant("wake-2"));
831 assert.lengthOf(
832 continuations,
833 2,
834 "the wake after a cancelled queued continuation must offer a new continuation",
835 );
836 yield* Fiber.join(secondCreated);
837 yield* worker.drain();
838 yield* Fiber.join(secondRunning);
839 const secondContinuation = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
840 (run) => run.status === "running",
841 );
842 assert.ok(secondContinuation !== undefined);
843 const secondWaiting = yield* watch(
844 (event) =>
845 event.type === "run.updated" &&
846 event.payload.id === secondContinuation.id &&
847 event.payload.status === "waiting",
848 );
849 yield* offerAndWait(result("wake-2-result", false));
850 yield* Fiber.join(secondWaiting);
851 yield* worker.drain();
852 const settled = yield* orchestrator.getThreadProjection(threadId);
853 assert.equal(
854 settled.runs.find((run) => run.id === secondContinuation.id)?.status,
855 "completed",
856 );
857 assert.deepEqual(
858 settled.turnItems.flatMap((item) =>
859 item.runId === secondContinuation.id && item.type === "assistant_message"
860 ? [item.text]
861 : [],
862 ),
863 ["Background build finished (wake-2)."],
864 "the continuation must carry only its own wake's output",
865 );
866 assert.lengthOf(continuations, 2, "two wakes must offer exactly two continuations");
867 }).pipe(
868 Effect.provide(
869 ProviderReplayHarness.layerWithRegistry(
870 { name: "claude-cancelled-continuation" },
871 registry,
872 { runEffectWorker: false, runContinuationWorker: true },
873 ),
874 ),
875 );
876 }).pipe(
877 Effect.provide(
878 Layer.mergeAll(
879 IdAllocator.layer,
880 McpProviderSessions.layer,
881 NodeServices.layer,
882 NodeCrypto.layer,
883 ),
884 ),
885 ),
886);