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

ClaudeAutomaticDelivery.integration.test.ts

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