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 Crypto from "effect/Crypto";
19import * as Effect from "effect/Effect";
20import * as FileSystem from "effect/FileSystem";
21import * as Fiber from "effect/Fiber";
22import * as Layer from "effect/Layer";
23import * as Path from "effect/Path";
24import * as Queue from "effect/Queue";
25import * as Schema from "effect/Schema";
26import * as Stream from "effect/Stream";
27import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
28import * as SecretRequests from "../secrets/SecretRequests.ts";
29import * as Scheduler from "../scheduling/Scheduler.ts";
30import * as SqlitePersistence from "../persistence/Sqlite.ts";
31import * as ClaudeAdapterV2 from "./Adapters/ClaudeAdapterV2.ts";
32import * as CommandReceiptStore from "./CommandReceiptStore.ts";
33import * as EffectWorker from "./EffectWorker.ts";
34import * as EventSink from "./EventSink.ts";
35import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
36import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
37import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
38import * as Orchestrator from "./Orchestrator.ts";
39import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
40import * as ThreadLaunchService from "./ThreadLaunchService.ts";
41import * as ThreadManagementService from "./ThreadManagementService.ts";
42import * as ServerSettings from "../serverSettings.ts";
43import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
44import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
45
46const sessionId = "automatic-delivery-session";
47const settings = Schema.decodeSync(ClaudeSettings)({});
48const decodeScheduledTask = Schema.decodeEffect(ScheduledTaskUpsertInput);
49const refusal =
50 "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.";
51const statusIds = ["status-1", "status-2", "status-3", "status-4"];
52const modelSelection = {
53 instanceId: ProviderInstanceId.make("claudeAgent"),
54 model: "claude-sonnet-4-6",
55};
56
57// Native frames match the captured Bash/status batch and tool_result_meta shape.
58// The external SDK boundary is replayed; the adapter and durable dispatch are real.
59function frame(value: unknown): SDKMessage {
60 return value as SDKMessage;
61}
62
63const batch = frame({
64 type: "assistant",
65 uuid: "batch",
66 session_id: sessionId,
67 parent_tool_use_id: null,
68 message: {
69 id: "tool-batch",
70 role: "assistant",
71 type: "message",
72 model: modelSelection.model,
73 content: [
74 { type: "tool_use", id: "build", name: "Bash", input: { command: "make" } },
75 ...statusIds.map((id) => ({
76 type: "tool_use",
77 id,
78 name: "mcp__t3-code__task_status",
79 input: { taskId: id },
80 })),
81 ],
82 stop_reason: "tool_use",
83 stop_sequence: null,
84 usage: { input_tokens: 1, output_tokens: 1 },
85 },
86});
87
88const toolResult = (id: string, cancelled: boolean) =>
89 frame({
90 type: "user",
91 uuid: `result-${id}`,
92 session_id: sessionId,
93 parent_tool_use_id: null,
94 message: {
95 role: "user",
96 content: [
97 {
98 type: "tool_result",
99 tool_use_id: id,
100 is_error: cancelled,
101 content: cancelled ? refusal : id === "build" ? "build OK" : "Task completed normally",
102 },
103 ],
104 },
105 ...(cancelled ? { tool_result_meta: [{ id, non_execution_kind: "cancelled" }] } : {}),
106 });
107
108const result = (uuid: string, aborted: boolean) =>
109 frame({
110 type: "result",
111 subtype: "success",
112 uuid,
113 session_id: sessionId,
114 is_error: false,
115 num_turns: 1,
116 result: "",
117 stop_reason: "end_turn",
118 terminal_reason: aborted ? "aborted_tools" : "completed",
119 permission_denials: [],
120 duration_ms: 1,
121 duration_api_ms: 1,
122 total_cost_usd: 0,
123 usage: { input_tokens: 1, output_tokens: 1 },
124 modelUsage: {},
125 });
126
127it.effect.each(["child completion", "scheduled message", "user steering"] as const)(
128 "delivers %s with Claude's native pending-tool cancellation behavior",
129 (delivery) =>
130 Effect.scoped(
131 Effect.gen(function* () {
132 const cwd = yield* checkpointWorkspace("claude-automatic-delivery");
133 const sdkMessages = yield* Queue.unbounded<SDKMessage>();
134 const offers: SDKUserMessage[] = [];
135 const nativeQueue: SDKUserMessage[] = [];
136 const batchAbort = new AbortController();
137 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
138 instanceId: modelSelection.instanceId,
139 settings,
140 environment: {},
141 attachmentsDir: cwd,
142 fileSystem: yield* FileSystem.FileSystem,
143 path: yield* Path.Path,
144 crypto: yield* Crypto.Crypto,
145 idAllocator: yield* IdAllocator.IdAllocatorV2,
146 queryRunner: {
147 allocateSessionId: Effect.succeed(sessionId),
148 open: () =>
149 Effect.succeed({
150 messages: Stream.fromQueue(sdkMessages),
151 offer: (message) =>
152 Effect.sync(() => {
153 offers.push(message);
154 nativeQueue.push(message);
155 // Claude Code 2.1.289's queue watcher aborts when a now-priority
156 // command arrives, including while Bash blocks pending reads.
157 if (nativeQueue.some((command) => command.priority === "now")) {
158 batchAbort.abort({ kind: "interrupt" });
159 }
160 }),
161 setModel: () => Effect.void,
162 setPermissionMode: () => Effect.void,
163 stopTask: () => Effect.void,
164 interrupt: Effect.die("automatic delivery must never interrupt"),
165 close: Effect.void,
166 }),
167 forkSession: () => Effect.die("unused"),
168 subagentLaunchToolUseId: () => Effect.succeed(null),
169 assertComplete: Effect.void,
170 },
171 });
172 yield* Effect.gen(function* () {
173 const orchestrator = yield* Orchestrator.OrchestratorV2;
174 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
175 const threadId = ThreadId.make("thread:automatic-delivery");
176 const projectId = ProjectId.make("project:automatic-delivery");
177 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
178 orchestrator.streamDomainEvents.pipe(
179 Stream.filter(predicate),
180 Stream.take(1),
181 Stream.runDrain,
182 Effect.forkScoped,
183 );
184 yield* orchestrator.dispatch({
185 type: "thread.create",
186 commandId: CommandId.make("create"),
187 threadId,
188 projectId,
189 title: "Automatic delivery",
190 modelSelection,
191 runtimeMode: "full-access",
192 interactionMode: "default",
193 branch: null,
194 worktreePath: cwd,
195 createdBy: "user",
196 creationSource: "web",
197 });
198 const running = yield* watch(
199 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
200 );
201 yield* orchestrator.dispatch({
202 type: "message.dispatch",
203 commandId: CommandId.make("first"),
204 threadId,
205 messageId: MessageId.make("first"),
206 text: "Build and check all four tasks.",
207 attachments: [],
208 dispatchMode: { type: "start_immediately" },
209 createdBy: "user",
210 creationSource: "web",
211 });
212 yield* worker.drain();
213 yield* Fiber.join(running);
214 const pending = yield* watch(
215 (event) =>
216 event.type === "turn-item.updated" &&
217 event.payload.nativeItemRef?.nativeId === "status-4",
218 );
219 yield* Queue.offer(sdkMessages, batch);
220 yield* Fiber.join(pending);
221 const before = yield* orchestrator.getThreadProjection(threadId);
222 assert.equal(before.turnItems.filter((item) => item.status === "running").length, 5);
223 const parent = before.runs[0]!;
224 if (parent.rootNodeId === null) return yield* Effect.die("parent has no root node");
225 const messageId = MessageId.make("automatic-notice");
226 if (delivery === "child completion") {
227 const taskId = NodeId.make("completed-child");
228 const now = yield* DateTime.now;
229 const sink = yield* EventSink.EventSinkV2;
230 yield* sink.write({
231 events: [
232 {
233 id: EventId.make("cohort"),
234 type: "run.updated",
235 threadId,
236 runId: parent.id,
237 occurredAt: now,
238 payload: {
239 ...parent,
240 delegatedCompletion: {
241 disposition: "open",
242 nextGeneration: 2,
243 delivery: { generation: 1, messageId, taskIds: [taskId] },
244 },
245 },
246 },
247 {
248 id: EventId.make("child"),
249 type: "subagent.updated",
250 threadId,
251 runId: parent.id,
252 nodeId: taskId,
253 occurredAt: now,
254 payload: {
255 id: taskId,
256 threadId,
257 runId: parent.id,
258 parentNodeId: parent.rootNodeId,
259 origin: "app_owned",
260 createdBy: "agent",
261 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
262 providerInstanceId: modelSelection.instanceId,
263 providerThreadId: null,
264 childThreadId: null,
265 nativeTaskRef: null,
266 prompt: "Background work",
267 title: "Child",
268 model: null,
269 completionWake: "always",
270 completionDelivery: { state: "claimed", observedByRunId: null },
271 status: "completed",
272 result: "done",
273 startedAt: now,
274 completedAt: now,
275 updatedAt: now,
276 },
277 },
278 ],
279 });
280 const command = {
281 type: "message.dispatch" as const,
282 commandId: CommandId.make("completion"),
283 threadId,
284 messageId,
285 text: "Child completed",
286 attachments: [],
287 dispatchMode: { type: "queue_after_active" as const },
288 createdBy: "agent" as const,
289 creationSource: "server" as const,
290 delegatedCompletion: { parentRunId: parent.id, generation: 1, taskIds: [taskId] },
291 };
292 yield* orchestrator.dispatch(command);
293 yield* orchestrator.dispatch(command);
294 yield* orchestrator.recoverDelegatedTasks;
295 } else if (delivery === "scheduled message") {
296 yield* Effect.gen(function* () {
297 const service = yield* ScheduledTaskService.ScheduledTaskService;
298 const { task } = yield* service.upsert(
299 yield* decodeScheduledTask({
300 title: "Status check",
301 prompt: "Check the four tasks.",
302 enabled: true,
303 schedule: { type: "interval", everyMs: 60_000 },
304 projectId,
305 threadId,
306 workspaceStrategy: { type: "root" },
307 modelSelection,
308 runtimeMode: "full-access",
309 interactionMode: "default",
310 }),
311 );
312 const ran = yield* service.runNow({ id: task.id });
313 assert.equal(ran.task.lastRunStatus, "succeeded");
314 }).pipe(
315 Effect.provide(
316 ScheduledTaskService.layer.pipe(
317 Layer.provide(ThreadManagementService.layer),
318 Layer.provide(ServerSettings.layerTest()),
319 Layer.provide(
320 Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
321 ensureTranscript: () =>
322 Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
323 }),
324 ),
325 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
326 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
327 Layer.provide(
328 CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
329 ),
330 Layer.provide(
331 Layer.mergeAll(
332 NodeCrypto.layer,
333 Scheduler.layer,
334 SqlitePersistence.layerMemory,
335 ),
336 ),
337 ),
338 ),
339 );
340 } else {
341 yield* orchestrator.dispatch({
342 type: "message.dispatch",
343 commandId: CommandId.make("steer"),
344 threadId,
345 messageId,
346 text: "Change direction now.",
347 attachments: [],
348 dispatchMode: { type: "steer_active", targetRunId: parent.id },
349 createdBy: "user",
350 creationSource: "web",
351 });
352 }
353 yield* worker.drain();
354 const explicitSteer = delivery === "user steering";
355 assert.equal(batchAbort.signal.aborted, explicitSteer);
356 assert.equal(offers.length, explicitSteer ? 2 : 1);
357 const finished = yield* watch(
358 (event) =>
359 event.type === "run.updated" &&
360 event.payload.id === parent.id &&
361 event.payload.status === "waiting",
362 );
363 // Bash finishes before the pending status reads, as in the capture.
364 yield* Queue.offer(sdkMessages, toolResult("build", false));
365 for (const id of statusIds)
366 yield* Queue.offer(sdkMessages, toolResult(id, batchAbort.signal.aborted));
367 if (explicitSteer) yield* Queue.offer(sdkMessages, result("aborted", true));
368 yield* Queue.offer(sdkMessages, result("completed", false));
369 yield* Fiber.join(finished);
370 yield* worker.drain();
371 yield* orchestrator.resumeQueuedRuns;
372 yield* worker.drain();
373 if (!explicitSteer) {
374 const queued = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!;
375 const noticeFinished = yield* watch(
376 (event) =>
377 event.type === "run.updated" &&
378 event.payload.id === queued.id &&
379 event.payload.status === "waiting",
380 );
381 const delivered =
382 delivery === "child completion"
383 ? yield* watch(
384 (event) =>
385 event.type === "subagent.updated" &&
386 event.payload.completionDelivery?.state === "delivered",
387 )
388 : null;
389 yield* Queue.offer(sdkMessages, result("notice-completed", false));
390 yield* Fiber.join(noticeFinished);
391 yield* worker.drain();
392 if (delivered !== null) yield* Fiber.join(delivered);
393 }
394 const after = yield* orchestrator.getThreadProjection(threadId);
395 const reads = after.turnItems.filter((item) =>
396 statusIds.includes(item.nativeItemRef?.nativeId ?? ""),
397 );
398 assert.equal(reads.length, 4);
399 for (const read of reads) {
400 assert.equal(read.status, explicitSteer ? "cancelled" : "completed");
401 assert.equal(read.toolNonExecutionKind, explicitSteer ? "cancelled" : undefined);
402 assert.equal(read.type === "dynamic_tool" && read.output === refusal, explicitSteer);
403 }
404 assert.equal(offers.length, 2);
405 assert.equal(
406 offers.filter((offer) => offer.priority === "now").length,
407 explicitSteer ? 1 : 0,
408 );
409 if (!explicitSteer) {
410 assert.equal(after.runs.length, 2);
411 if (delivery === "child completion") {
412 assert.equal(after.messages.filter((message) => message.id === messageId).length, 1);
413 assert.equal(after.subagents[0]?.completionDelivery?.state, "delivered");
414 } else {
415 assert.equal(
416 after.messages.filter((message) => message.scheduledTaskId !== undefined).length,
417 1,
418 );
419 }
420 }
421 yield* orchestrator.recoverDelegatedTasks;
422 yield* orchestrator.resumeQueuedRuns;
423 yield* worker.drain();
424 assert.equal(offers.length, 2);
425 }).pipe(
426 Effect.provide(
427 ProviderReplayHarness.layerWithRegistry(
428 { name: "claude-automatic-delivery" },
429 ProviderAdapterRegistry.layerSingle(adapter),
430 { runEffectWorker: false },
431 ),
432 ),
433 );
434 }).pipe(
435 Effect.provide(
436 Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
437 ),
438 ),
439 ),
440);