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

ClaudeAutomaticDelivery.integration.test.ts

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