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

ClaudeAutomaticDelivery.integration.test.ts

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