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

ClaudeAutomaticDelivery.integration.test.ts

441 lines17.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 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;
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 applyFlagSettings: () => Effect.void,
163 setPermissionMode: () => Effect.void,
164 stopTask: () => Effect.void,
165 interrupt: Effect.die("automatic delivery must never interrupt"),
166 close: Effect.void,
167 }),
168 forkSession: () => Effect.die("unused"),
169 subagentLaunchToolUseId: () => Effect.succeed(null),
170 assertComplete: Effect.void,
171 },
172 });
173 yield* Effect.gen(function* () {
174 const orchestrator = yield* Orchestrator.OrchestratorV2;
175 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
176 const threadId = ThreadId.make("thread:automatic-delivery");
177 const projectId = ProjectId.make("project:automatic-delivery");
178 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
179 orchestrator.streamDomainEvents.pipe(
180 Stream.filter(predicate),
181 Stream.take(1),
182 Stream.runDrain,
183 Effect.forkScoped,
184 );
185 yield* orchestrator.dispatch({
186 type: "thread.create",
187 commandId: CommandId.make("create"),
188 threadId,
189 projectId,
190 title: "Automatic delivery",
191 modelSelection,
192 runtimeMode: "full-access",
193 interactionMode: "default",
194 branch: null,
195 worktreePath: cwd,
196 createdBy: "user",
197 creationSource: "web",
198 });
199 const running = yield* watch(
200 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
201 );
202 yield* orchestrator.dispatch({
203 type: "message.dispatch",
204 commandId: CommandId.make("first"),
205 threadId,
206 messageId: MessageId.make("first"),
207 text: "Build and check all four tasks.",
208 attachments: [],
209 dispatchMode: { type: "start_immediately" },
210 createdBy: "user",
211 creationSource: "web",
212 });
213 yield* worker.drain();
214 yield* Fiber.join(running);
215 const pending = yield* watch(
216 (event) =>
217 event.type === "turn-item.updated" &&
218 event.payload.nativeItemRef?.nativeId === "status-4",
219 );
220 yield* Queue.offer(sdkMessages, batch);
221 yield* Fiber.join(pending);
222 const before = yield* orchestrator.getThreadProjection(threadId);
223 assert.equal(before.turnItems.filter((item) => item.status === "running").length, 5);
224 const parent = before.runs[0]!;
225 if (parent.rootNodeId === null) return yield* Effect.die("parent has no root node");
226 const messageId = MessageId.make("automatic-notice");
227 if (delivery === "child completion") {
228 const taskId = NodeId.make("completed-child");
229 const now = yield* DateTime.now;
230 const sink = yield* EventSink.EventSinkV2;
231 yield* sink.write({
232 events: [
233 {
234 id: EventId.make("cohort"),
235 type: "run.updated",
236 threadId,
237 runId: parent.id,
238 occurredAt: now,
239 payload: {
240 ...parent,
241 delegatedCompletion: {
242 disposition: "open",
243 nextGeneration: 2,
244 delivery: { generation: 1, messageId, taskIds: [taskId] },
245 },
246 },
247 },
248 {
249 id: EventId.make("child"),
250 type: "subagent.updated",
251 threadId,
252 runId: parent.id,
253 nodeId: taskId,
254 occurredAt: now,
255 payload: {
256 id: taskId,
257 threadId,
258 runId: parent.id,
259 parentNodeId: parent.rootNodeId,
260 origin: "app_owned",
261 createdBy: "agent",
262 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
263 providerInstanceId: modelSelection.instanceId,
264 providerThreadId: null,
265 childThreadId: null,
266 nativeTaskRef: null,
267 prompt: "Background work",
268 title: "Child",
269 model: null,
270 completionWake: "always",
271 completionDelivery: { state: "claimed", observedByRunId: null },
272 status: "completed",
273 result: "done",
274 startedAt: now,
275 completedAt: now,
276 updatedAt: now,
277 },
278 },
279 ],
280 });
281 const command = {
282 type: "message.dispatch" as const,
283 commandId: CommandId.make("completion"),
284 threadId,
285 messageId,
286 text: "Child completed",
287 attachments: [],
288 dispatchMode: { type: "queue_after_active" as const },
289 createdBy: "agent" as const,
290 creationSource: "server" as const,
291 delegatedCompletion: { parentRunId: parent.id, generation: 1, taskIds: [taskId] },
292 };
293 yield* orchestrator.dispatch(command);
294 yield* orchestrator.dispatch(command);
295 yield* orchestrator.recoverDelegatedTasks;
296 } else if (delivery === "scheduled message") {
297 yield* Effect.gen(function* () {
298 const service = yield* ScheduledTaskService.ScheduledTaskService;
299 const { task } = yield* service.upsert(
300 yield* decodeScheduledTask({
301 title: "Status check",
302 prompt: "Check the four tasks.",
303 enabled: true,
304 schedule: { type: "interval", everyMs: 60_000 },
305 projectId,
306 threadId,
307 workspaceStrategy: { type: "root" },
308 modelSelection,
309 runtimeMode: "full-access",
310 interactionMode: "default",
311 }),
312 );
313 const ran = yield* service.runNow({ id: task.id });
314 assert.equal(ran.task.lastRunStatus, "succeeded");
315 }).pipe(
316 Effect.provide(
317 ScheduledTaskService.layer.pipe(
318 Layer.provide(ThreadManagementService.layer),
319 Layer.provide(ServerSettings.layerTest()),
320 Layer.provide(
321 Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
322 ensureTranscript: () =>
323 Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
324 }),
325 ),
326 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
327 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
328 Layer.provide(
329 CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
330 ),
331 Layer.provide(
332 Layer.mergeAll(
333 NodeCrypto.layer,
334 Scheduler.layer,
335 SqlitePersistence.layerMemory,
336 ),
337 ),
338 ),
339 ),
340 );
341 } else {
342 yield* orchestrator.dispatch({
343 type: "message.dispatch",
344 commandId: CommandId.make("steer"),
345 threadId,
346 messageId,
347 text: "Change direction now.",
348 attachments: [],
349 dispatchMode: { type: "steer_active", targetRunId: parent.id },
350 createdBy: "user",
351 creationSource: "web",
352 });
353 }
354 yield* worker.drain();
355 const explicitSteer = delivery === "user steering";
356 assert.equal(batchAbort.signal.aborted, explicitSteer);
357 assert.equal(offers.length, explicitSteer ? 2 : 1);
358 const finished = yield* watch(
359 (event) =>
360 event.type === "run.updated" &&
361 event.payload.id === parent.id &&
362 event.payload.status === "waiting",
363 );
364 // Bash finishes before the pending status reads, as in the capture.
365 yield* Queue.offer(sdkMessages, toolResult("build", false));
366 for (const id of statusIds)
367 yield* Queue.offer(sdkMessages, toolResult(id, batchAbort.signal.aborted));
368 if (explicitSteer) yield* Queue.offer(sdkMessages, result("aborted", true));
369 yield* Queue.offer(sdkMessages, result("completed", false));
370 yield* Fiber.join(finished);
371 yield* worker.drain();
372 yield* orchestrator.resumeQueuedRuns;
373 yield* worker.drain();
374 if (!explicitSteer) {
375 const queued = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!;
376 const noticeFinished = yield* watch(
377 (event) =>
378 event.type === "run.updated" &&
379 event.payload.id === queued.id &&
380 event.payload.status === "waiting",
381 );
382 const delivered =
383 delivery === "child completion"
384 ? yield* watch(
385 (event) =>
386 event.type === "subagent.updated" &&
387 event.payload.completionDelivery?.state === "delivered",
388 )
389 : null;
390 yield* Queue.offer(sdkMessages, result("notice-completed", false));
391 yield* Fiber.join(noticeFinished);
392 yield* worker.drain();
393 if (delivered !== null) yield* Fiber.join(delivered);
394 }
395 const after = yield* orchestrator.getThreadProjection(threadId);
396 const reads = after.turnItems.filter((item) =>
397 statusIds.includes(item.nativeItemRef?.nativeId ?? ""),
398 );
399 assert.equal(reads.length, 4);
400 for (const read of reads) {
401 assert.equal(read.status, explicitSteer ? "cancelled" : "completed");
402 assert.equal(read.toolNonExecutionKind, explicitSteer ? "cancelled" : undefined);
403 assert.equal(read.type === "dynamic_tool" && read.output === refusal, explicitSteer);
404 }
405 assert.equal(offers.length, 2);
406 assert.equal(
407 offers.filter((offer) => offer.priority === "now").length,
408 explicitSteer ? 1 : 0,
409 );
410 if (!explicitSteer) {
411 assert.equal(after.runs.length, 2);
412 if (delivery === "child completion") {
413 assert.equal(after.messages.filter((message) => message.id === messageId).length, 1);
414 assert.equal(after.subagents[0]?.completionDelivery?.state, "delivered");
415 } else {
416 assert.equal(
417 after.messages.filter((message) => message.scheduledTaskId !== undefined).length,
418 1,
419 );
420 }
421 }
422 yield* orchestrator.recoverDelegatedTasks;
423 yield* orchestrator.resumeQueuedRuns;
424 yield* worker.drain();
425 assert.equal(offers.length, 2);
426 }).pipe(
427 Effect.provide(
428 ProviderReplayHarness.layerWithRegistry(
429 { name: "claude-automatic-delivery" },
430 ProviderAdapterRegistry.layerSingle(adapter),
431 { runEffectWorker: false },
432 ),
433 ),
434 );
435 }).pipe(
436 Effect.provide(
437 Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
438 ),
439 ),
440 ),
441);