Open History to see the last commit
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;
63}
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 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(
354 NodeCrypto.layer,
355 Scheduler.layer,
356 SqlitePersistence.layerMemory,
357 ),
358 ),
359 ),
360 ),
361 );
362 } else if (delivery === "user steering") {
363 yield* orchestrator.dispatch({
364 type: "message.dispatch",
365 commandId: CommandId.make("steer"),
366 threadId,
367 messageId,
368 text: "Change direction now.",
369 attachments: [],
370 dispatchMode: { type: "steer_active", targetRunId: parent.id },
371 createdBy: "user",
372 creationSource: "web",
373 });
374 } else {
375 yield* orchestrator.dispatch({
376 type: "message.dispatch",
377 commandId: CommandId.make("queue"),
378 threadId,
379 messageId,
380 text: "Change direction now.",
381 attachments: [],
382 dispatchMode: { type: "queue_after_active" },
383 createdBy: "user",
384 creationSource: "web",
385 });
386 const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!;
387 yield* orchestrator.dispatch({
388 type: "queued-message.promote-to-steer",
389 commandId: CommandId.make("promote"),
390 threadId,
391 queuedRunId: queuedRun.id,
392 targetRunId: parent.id,
393 });
394 const promoted = yield* orchestrator.getThreadProjection(threadId);
395 assert.equal(promoted.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled");
396 assert.equal(
397 promoted.messages.find((message) => message.id === messageId)?.runId,
398 parent.id,
399 );
400 const steer = promoted.turnItems.find(
401 (item) => item.type === "user_message" && item.messageId === messageId,
402 );
403 assert.ok(steer?.type === "user_message");
404 assert.equal(steer.inputIntent, "promoted_queued_to_steer");
405 }
406 yield* worker.drain();
407 const explicitSteer =
408 delivery === "user steering" || delivery === "promoted queued message";
409 assert.equal(batchAbort.signal.aborted, explicitSteer);
410 assert.equal(offers.length, explicitSteer ? 2 : 1);
411 const finished = yield* watch(
412 (event) =>
413 event.type === "run.updated" &&
414 event.payload.id === parent.id &&
415 event.payload.status === "waiting",
416 );
417 yield* Queue.offer(sdkMessages, toolResult("build", false));
418 for (const id of statusIds)
419 yield* Queue.offer(sdkMessages, toolResult(id, batchAbort.signal.aborted));
420 if (explicitSteer) yield* Queue.offer(sdkMessages, result("aborted", true));
421 yield* Queue.offer(sdkMessages, result("completed", false));
422 yield* Fiber.join(finished);
423 yield* worker.drain();
424 yield* orchestrator.resumeQueuedRuns;
425 yield* worker.drain();
426 if (!explicitSteer) {
427 const queued = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!;
428 const noticeFinished = yield* watch(
429 (event) =>
430 event.type === "run.updated" &&
431 event.payload.id === queued.id &&
432 event.payload.status === "waiting",
433 );
434 const delivered =
435 delivery === "child completion"
436 ? yield* watch(
437 (event) =>
438 event.type === "subagent.updated" &&
439 event.payload.completionDelivery?.state === "delivered",
440 )
441 : null;
442 yield* Queue.offer(sdkMessages, result("notice-completed", false));
443 yield* Fiber.join(noticeFinished);
444 yield* worker.drain();
445 if (delivered !== null) yield* Fiber.join(delivered);
446 }
447 const after = yield* orchestrator.getThreadProjection(threadId);
448 const reads = after.turnItems.filter((item) =>
449 statusIds.includes(item.nativeItemRef?.nativeId ?? ""),
450 );
451 assert.equal(reads.length, 4);
452 for (const read of reads) {
453 assert.equal(read.status, explicitSteer ? "cancelled" : "completed");
454 assert.equal(read.toolNonExecutionKind, explicitSteer ? "cancelled" : undefined);
455 assert.equal(read.type === "dynamic_tool" && read.output === refusal, explicitSteer);
456 }
457 assert.equal(offers.length, 2);
458 assert.equal(
459 offers.filter((offer) => offer.priority === "now").length,
460 explicitSteer ? 1 : 0,
461 );
462 if (!explicitSteer) {
463 assert.equal(after.runs.length, 2);
464 if (delivery === "child completion") {
465 assert.equal(after.messages.filter((message) => message.id === messageId).length, 1);
466 assert.equal(after.subagents[0]?.completionDelivery?.state, "delivered");
467 } else {
468 assert.equal(
469 after.messages.filter((message) => message.scheduledTaskId !== undefined).length,
470 1,
471 );
472 }
473 }
474 yield* orchestrator.recoverDelegatedTasks;
475 yield* orchestrator.resumeQueuedRuns;
476 yield* worker.drain();
477 assert.equal(offers.length, 2);
478 }).pipe(
479 Effect.provide(
480 ProviderReplayHarness.layerWithRegistry(
481 { name: "claude-automatic-delivery" },
482 ProviderAdapterRegistry.layerSingle(adapter),
483 { runEffectWorker: false },
484 ),
485 ),
486 );
487 }).pipe(
488 Effect.provide(
489 Layer.mergeAll(
490 IdAllocator.layer,
491 McpProviderSessions.layer,
492 NodeServices.layer,
493 NodeCrypto.layer,
494 ),
495 ),
496 ),
497 ),
498);
499
500it.effect("applies an effort change to the running Claude query without waiting for a turn", () =>
501 Effect.scoped(
502 Effect.gen(function* () {
503 const cwd = yield* checkpointWorkspace("claude-live-effort");
504 const sdkMessages = yield* Queue.unbounded<SDKMessage>();
505 const flagSettings: unknown[] = [];
506 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
507 instanceId: modelSelection.instanceId,
508 settings,
509 environment: {},
510 attachmentsDir: cwd,
511 fileSystem: yield* FileSystem.FileSystem,
512 path: yield* Path.Path,
513 random: yield* SecureRandom.SecureRandom,
514 idAllocator: yield* IdAllocator.IdAllocatorV2,
515 queryRunner: {
516 allocateSessionId: Effect.succeed(sessionId),
517 open: () =>
518 Effect.succeed({
519 messages: Stream.fromQueue(sdkMessages),
520 offer: () => Effect.void,
521 setModel: () => Effect.void,
522 applyFlagSettings: (flags) =>
523 Effect.sync(() => {
524 flagSettings.push(flags);
525 }),
526 setPermissionMode: () => Effect.void,
527 backgroundTasks: () => Effect.succeed(false),
528 mcpServerStatus: Effect.succeed([]),
529 readMcpResource: () => Effect.die("unexpected MCP resource read"),
530 callMcpTool: () => Effect.die("unexpected MCP tool call"),
531 listPermissionRules: Effect.die("unexpected permission rules read"),
532 stopTask: () => Effect.void,
533 interrupt: Effect.die("an effort change must not interrupt the turn"),
534 close: Effect.void,
535 }),
536 forkSession: () => Effect.die("unused"),
537 subagentLaunchToolUseId: () => Effect.succeed(null),
538 assertComplete: Effect.void,
539 },
540 });
541 yield* Effect.gen(function* () {
542 const orchestrator = yield* Orchestrator.OrchestratorV2;
543 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
544 const threadId = ThreadId.make("thread:live-effort");
545 const high = { ...modelSelection, options: [{ id: "effort", value: "high" }] };
546 const running = yield* orchestrator.streamDomainEvents.pipe(
547 Stream.filter(
548 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
549 ),
550 Stream.take(1),
551 Stream.runDrain,
552 Effect.forkScoped,
553 );
554 yield* orchestrator.dispatch({
555 type: "thread.create",
556 commandId: CommandId.make("create"),
557 threadId,
558 projectId: ProjectId.make("project:live-effort"),
559 title: "Live effort",
560 modelSelection: high,
561 runtimeMode: "full-access",
562 interactionMode: "default",
563 branch: null,
564 worktreePath: cwd,
565 createdBy: "user",
566 creationSource: "web",
567 });
568 yield* orchestrator.dispatch({
569 type: "message.dispatch",
570 commandId: CommandId.make("first"),
571 threadId,
572 messageId: MessageId.make("first"),
573 text: "Keep working.",
574 attachments: [],
575 dispatchMode: { type: "start_immediately" },
576 createdBy: "user",
577 creationSource: "web",
578 });
579 yield* worker.drain();
580 yield* Fiber.join(running);
581 assert.deepEqual(flagSettings, []);
582
583 yield* orchestrator.dispatch({
584 type: "thread.model-selection.set",
585 commandId: CommandId.make("medium"),
586 threadId,
587 modelSelection: { ...modelSelection, options: [{ id: "effort", value: "medium" }] },
588 });
589 yield* worker.drain();
590
591 assert.deepEqual(flagSettings, [
592 { effortLevel: "medium", fastMode: null, ultracode: null },
593 ]);
594 }).pipe(
595 Effect.provide(
596 ProviderReplayHarness.layerWithRegistry(
597 { name: "claude-live-effort" },
598 ProviderAdapterRegistry.layerSingle(adapter),
599 { runEffectWorker: false },
600 ),
601 ),
602 );
603 }).pipe(
604 Effect.provide(
605 Layer.mergeAll(
606 IdAllocator.layer,
607 McpProviderSessions.layer,
608 NodeServices.layer,
609 NodeCrypto.layer,
610 ),
611 ),
612 ),
613 ),
614);
615
616const backgroundTaskStarted = (taskId: string) =>
617 frame({
618 type: "system",
619 subtype: "task_started",
620 task_id: taskId,
621 tool_use_id: `tool-${taskId}`,
622 description: "Background build",
623 is_backgrounded: true,
624 task_type: "local_bash",
625 uuid: `started-${taskId}`,
626 session_id: sessionId,
627 });
628
629const backgroundTaskNotification = (taskId: string) =>
630 frame({
631 type: "system",
632 subtype: "task_notification",
633 task_id: taskId,
634 tool_use_id: `tool-${taskId}`,
635 status: "completed",
636 output_file: `/tmp/claude-replay/tasks/${taskId}.output`,
637 summary: `Background build ${taskId} completed`,
638 uuid: `notification-${taskId}`,
639 session_id: sessionId,
640 });
641
642const wakeAssistant = (uuid: string) =>
643 frame({
644 type: "assistant",
645 uuid,
646 session_id: sessionId,
647 parent_tool_use_id: null,
648 message: {
649 id: `msg-${uuid}`,
650 role: "assistant",
651 type: "message",
652 model: modelSelection.model,
653 content: [{ type: "text", text: `Background build finished (${uuid}).` }],
654 stop_reason: null,
655 stop_sequence: null,
656 usage: { input_tokens: 1, output_tokens: 1 },
657 },
658 });
659
660it.effect("offers a continuation for a later wake after a queued continuation is cancelled", () =>
661 Effect.scoped(
662 Effect.gen(function* () {
663 const cwd = yield* checkpointWorkspace("claude-cancelled-continuation");
664 const sdkMessages = yield* Queue.unbounded<SDKMessage>();
665 const processed = new WeakMap<SDKMessage, Deferred.Deferred<void>>();
666 const offerAndWait = Effect.fnUntraced(function* (message: SDKMessage) {
667 const done = yield* Deferred.make<void>();
668 processed.set(message, done);
669 yield* Queue.offer(sdkMessages, message);
670 yield* Deferred.await(done);
671 });
672 const fileSystem = yield* FileSystem.FileSystem;
673 const path = yield* Path.Path;
674 const random = yield* SecureRandom.SecureRandom;
675 const idAllocator = yield* IdAllocator.IdAllocatorV2;
676 const continuations: ProviderContinuationRequests.ProviderContinuationRequest[] = [];
677 const services =
678 yield* Effect.context<
679 Effect.Services<ReturnType<typeof ClaudeAdapterV2.makeClaudeAdapterV2>>
680 >();
681 const registry = ProviderAdapterRegistry.layerFromAdaptersEffect(
682 Effect.gen(function* () {
683 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
684 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
685 instanceId: modelSelection.instanceId,
686 settings,
687 environment: {},
688 attachmentsDir: cwd,
689 fileSystem,
690 path,
691 random,
692 idAllocator,
693 continuationRequests: {
694 offer: (request) =>
695 Effect.sync(() => continuations.push(request)).pipe(
696 Effect.andThen(requests.offer(request)),
697 ),
698 },
699 queryRunner: {
700 allocateSessionId: Effect.succeed(sessionId),
701 open: () =>
702 Effect.succeed({
703 // Resolve each frame's Deferred once the adapter pulls the next one.
704 messages: Stream.fromQueue(sdkMessages).pipe(
705 Stream.flatMap((message) =>
706 Stream.make(message).pipe(
707 Stream.concat(
708 Stream.fromEffect(
709 Effect.suspend(() => {
710 const done = processed.get(message);
711 return done === undefined
712 ? Effect.void
713 : Deferred.succeed(done, undefined);
714 }),
715 ).pipe(Stream.drain),
716 ),
717 ),
718 ),
719 ),
720 offer: () => Effect.void,
721 setModel: () => Effect.void,
722 applyFlagSettings: () => Effect.void,
723 setPermissionMode: () => Effect.void,
724 backgroundTasks: () => Effect.succeed(false),
725 mcpServerStatus: Effect.succeed([]),
726 readMcpResource: () => Effect.die("unexpected MCP resource read"),
727 callMcpTool: () => Effect.die("unexpected MCP tool call"),
728 listPermissionRules: Effect.die("unexpected permission rules read"),
729 stopTask: () => Effect.void,
730 interrupt: Effect.void,
731 close: Effect.void,
732 }),
733 forkSession: () => Effect.die("unused"),
734 subagentLaunchToolUseId: () => Effect.succeed(null),
735 assertComplete: Effect.void,
736 },
737 }).pipe(Effect.provideContext(services));
738 return [adapter];
739 }),
740 );
741 yield* Effect.gen(function* () {
742 const orchestrator = yield* Orchestrator.OrchestratorV2;
743 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
744 const threadId = ThreadId.make("thread:cancelled-continuation");
745 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
746 orchestrator.streamDomainEvents.pipe(
747 Stream.filter(predicate),
748 Stream.take(1),
749 Stream.runDrain,
750 Effect.forkScoped,
751 );
752 const runUpdated = (messageId: string, status: string) =>
753 watch(
754 (event) =>
755 event.type === "run.updated" &&
756 event.payload.userMessageId === messageId &&
757 event.payload.status === status,
758 );
759 // A user turn that leaves a background task running when it ends.
760 const userTurnWithBackgroundTask = Effect.fnUntraced(function* (
761 id: string,
762 taskId: string,
763 ) {
764 const running = yield* runUpdated(id, "running");
765 yield* orchestrator.dispatch({
766 type: "message.dispatch",
767 commandId: CommandId.make(id),
768 threadId,
769 messageId: MessageId.make(id),
770 text: "Run the build in the background.",
771 attachments: [],
772 dispatchMode: { type: "start_immediately" },
773 createdBy: "user",
774 creationSource: "web",
775 });
776 yield* worker.drain();
777 yield* Fiber.join(running);
778 const waiting = yield* runUpdated(id, "waiting");
779 yield* Queue.offer(sdkMessages, backgroundTaskStarted(taskId));
780 yield* Queue.offer(sdkMessages, result(`result-${id}`, false));
781 yield* Fiber.join(waiting);
782 });
783 yield* orchestrator.dispatch({
784 type: "thread.create",
785 commandId: CommandId.make("create"),
786 threadId,
787 projectId: ProjectId.make("project:cancelled-continuation"),
788 title: "Cancelled continuation",
789 modelSelection,
790 runtimeMode: "full-access",
791 interactionMode: "default",
792 branch: null,
793 worktreePath: cwd,
794 createdBy: "user",
795 creationSource: "web",
796 });
797
798 // The first run is still finalizing when its background task wakes Claude.
799 yield* userTurnWithBackgroundTask("first", "build-1");
800 const queued = yield* watch(
801 (event) => event.type === "run.created" && event.payload.status === "queued",
802 );
803 yield* offerAndWait(backgroundTaskNotification("build-1"));
804 yield* offerAndWait(wakeAssistant("wake-1"));
805 yield* Fiber.join(queued);
806 assert.lengthOf(continuations, 1);
807 const continuationRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
808 (run) => run.status === "queued",
809 );
810 assert.ok(continuationRun !== undefined);
811 yield* orchestrator.dispatch({
812 type: "queued-run.cancel",
813 commandId: CommandId.make("cancel"),
814 threadId,
815 runId: continuationRun.id,
816 });
817 yield* offerAndWait(result("wake-1-result", false));
818 yield* worker.drain();
819 yield* orchestrator.resumeQueuedRuns;
820 yield* worker.drain();
821 const idle = yield* orchestrator.getThreadProjection(threadId);
822 assert.equal(idle.runs.find((run) => run.id === continuationRun.id)?.status, "cancelled");
823 assert.isFalse(idle.runs.some((run) => run.status === "queued"));
824
825 yield* userTurnWithBackgroundTask("second", "build-2");
826 yield* worker.drain();
827 // The second user run has completed, so this continuation starts without queueing.
828 const isContinuationRun = (
829 event: OrchestrationV2DomainEvent,
830 type: string,
831 status: string,
832 ) =>
833 (event.type === "run.created" || event.type === "run.updated") &&
834 event.type === type &&
835 event.payload.status === status &&
836 event.payload.userMessageId !== MessageId.make("first") &&
837 event.payload.userMessageId !== MessageId.make("second");
838 const secondCreated = yield* watch((event) =>
839 isContinuationRun(event, "run.created", "starting"),
840 );
841 const secondRunning = yield* watch((event) =>
842 isContinuationRun(event, "run.updated", "running"),
843 );
844 yield* offerAndWait(backgroundTaskNotification("build-2"));
845 yield* offerAndWait(wakeAssistant("wake-2"));
846 assert.lengthOf(
847 continuations,
848 2,
849 "the wake after a cancelled queued continuation must offer a new continuation",
850 );
851 yield* Fiber.join(secondCreated);
852 yield* worker.drain();
853 yield* Fiber.join(secondRunning);
854 const secondContinuation = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
855 (run) => run.status === "running",
856 );
857 assert.ok(secondContinuation !== undefined);
858 const secondWaiting = yield* watch(
859 (event) =>
860 event.type === "run.updated" &&
861 event.payload.id === secondContinuation.id &&
862 event.payload.status === "waiting",
863 );
864 yield* offerAndWait(result("wake-2-result", false));
865 yield* Fiber.join(secondWaiting);
866 yield* worker.drain();
867 const settled = yield* orchestrator.getThreadProjection(threadId);
868 assert.equal(
869 settled.runs.find((run) => run.id === secondContinuation.id)?.status,
870 "completed",
871 );
872 assert.deepEqual(
873 settled.turnItems.flatMap((item) =>
874 item.runId === secondContinuation.id && item.type === "assistant_message"
875 ? [item.text]
876 : [],
877 ),
878 ["Background build finished (wake-2)."],
879 "the continuation must carry only its own wake's output",
880 );
881 assert.lengthOf(continuations, 2, "two wakes must offer exactly two continuations");
882 }).pipe(
883 Effect.provide(
884 ProviderReplayHarness.layerWithRegistry(
885 { name: "claude-cancelled-continuation" },
886 registry,
887 { runEffectWorker: false, runContinuationWorker: true },
888 ),
889 ),
890 );
891 }).pipe(
892 Effect.provide(
893 Layer.mergeAll(
894 IdAllocator.layer,
895 McpProviderSessions.layer,
896 NodeServices.layer,
897 NodeCrypto.layer,
898 ),
899 ),
900 ),
901 ),
902);