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

ClaudeAutomaticDelivery.integration.test.ts

496 lines19.9 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 SecureRandom from "effect/crypto/SecureRandom";
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 ManagedPolicy from "../policy/ManagedPolicy.ts";
29import * as SecretRequests from "../secrets/SecretRequests.ts";
30import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
31import * as Scheduler from "../scheduling/Scheduler.ts";
32import * as SqlitePersistence from "../persistence/Sqlite.ts";
33import * as ClaudeAdapterV2 from "./Adapters/ClaudeAdapterV2.ts";
34import * as CommandReceiptStore from "./CommandReceiptStore.ts";
35import * as EffectWorker from "./EffectWorker.ts";
36import * as EventSink from "./EventSink.ts";
37import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
38import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
39import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
40import * as Orchestrator from "./Orchestrator.ts";
41import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
42import * as ThreadLaunchService from "./ThreadLaunchService.ts";
43import * as ThreadManagementService from "./ThreadManagementService.ts";
44import * as ServerSettings from "../serverSettings.ts";
45import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
46import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
47​
48const sessionId = "automatic-delivery-session";
49const settings = Schema.decodeSync(ClaudeSettings)({});
50const decodeScheduledTask = Schema.decodeEffect(ScheduledTaskUpsertInput);
51const refusal =
52 "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.";
53const statusIds = ["status-1", "status-2", "status-3", "status-4"];
54const modelSelection = {
55 instanceId: ProviderInstanceId.make("claudeAgent"),
56 model: "claude-sonnet-4-6",
57};
58​
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​
127const deliveries = [
128 "child completion",
129 "scheduled message",
130 "user steering",
131 "promoted queued message",
132] as const;
133​
134it.effect.each(deliveries)(
135 "delivers %s with Claude's native pending-tool cancellation behavior",
136 (delivery) =>
137 Effect.scoped(
138 Effect.gen(function* () {
139 const cwd = yield* checkpointWorkspace("claude-automatic-delivery");
140 const sdkMessages = yield* Queue.unbounded<SDKMessage>();
141 const offers: SDKUserMessage[] = [];
142 const nativeQueue: SDKUserMessage[] = [];
143 // @effect-diagnostics-next-line abortControllerInEffect:off - The fake SDK interrupts its batch independently of the test fiber.
144 const batchAbort = new AbortController();
145 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
146 instanceId: modelSelection.instanceId,
147 settings,
148 environment: {},
149 attachmentsDir: cwd,
150 fileSystem: yield* FileSystem.FileSystem,
151 path: yield* Path.Path,
152 random: yield* SecureRandom.SecureRandom,
153 idAllocator: yield* IdAllocator.IdAllocatorV2,
154 queryRunner: {
155 allocateSessionId: Effect.succeed(sessionId),
156 open: () =>
157 Effect.succeed({
158 messages: Stream.fromQueue(sdkMessages),
159 offer: (message) =>
160 Effect.sync(() => {
161 offers.push(message);
162 nativeQueue.push(message);
163 // Claude Code 2.1.289 aborts on now-priority commands even while Bash blocks reads.
164 if (nativeQueue.some((command) => command.priority === "now")) {
165 batchAbort.abort({ kind: "interrupt" });
166 }
167 }),
168 setModel: () => Effect.void,
169 applyFlagSettings: () => Effect.void,
170 setPermissionMode: () => Effect.void,
171 backgroundTasks: () => Effect.succeed(false),
172 mcpServerStatus: Effect.succeed([]),
173 readMcpResource: () => Effect.die("unexpected MCP resource read"),
174 callMcpTool: () => Effect.die("unexpected MCP tool call"),
175 listPermissionRules: Effect.die("unexpected permission rules read"),
176 stopTask: () => Effect.void,
177 interrupt: Effect.die("automatic delivery must never interrupt"),
178 close: Effect.void,
179 }),
180 forkSession: () => Effect.die("unused"),
181 subagentLaunchToolUseId: () => Effect.succeed(null),
182 assertComplete: Effect.void,
183 },
184 });
185 yield* Effect.gen(function* () {
186 const orchestrator = yield* Orchestrator.OrchestratorV2;
187 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
188 const threadId = ThreadId.make("thread:automatic-delivery");
189 const projectId = ProjectId.make("project:automatic-delivery");
190 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
191 orchestrator.streamDomainEvents.pipe(
192 Stream.filter(predicate),
193 Stream.take(1),
194 Stream.runDrain,
195 Effect.forkScoped,
196 );
197 yield* orchestrator.dispatch({
198 type: "thread.create",
199 commandId: CommandId.make("create"),
200 threadId,
201 projectId,
202 title: "Automatic delivery",
203 modelSelection,
204 runtimeMode: "full-access",
205 interactionMode: "default",
206 branch: null,
207 worktreePath: cwd,
208 createdBy: "user",
209 creationSource: "web",
210 });
211 const running = yield* watch(
212 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
213 );
214 yield* orchestrator.dispatch({
215 type: "message.dispatch",
216 commandId: CommandId.make("first"),
217 threadId,
218 messageId: MessageId.make("first"),
219 text: "Build and check all four tasks.",
220 attachments: [],
221 dispatchMode: { type: "start_immediately" },
222 createdBy: "user",
223 creationSource: "web",
224 });
225 yield* worker.drain();
226 yield* Fiber.join(running);
227 const pending = yield* watch(
228 (event) =>
229 event.type === "turn-item.updated" &&
230 event.payload.nativeItemRef?.nativeId === "status-4",
231 );
232 yield* Queue.offer(sdkMessages, batch);
233 yield* Fiber.join(pending);
234 const before = yield* orchestrator.getThreadProjection(threadId);
235 assert.equal(before.turnItems.filter((item) => item.status === "running").length, 5);
236 const parent = before.runs[0]!;
237 if (parent.rootNodeId === null) return yield* Effect.die("parent has no root node");
238 const messageId = MessageId.make("automatic-notice");
239 if (delivery === "child completion") {
240 const taskId = NodeId.make("completed-child");
241 const now = yield* DateTime.now;
242 const sink = yield* EventSink.EventSinkV2;
243 yield* sink.write({
244 events: [
245 {
246 id: EventId.make("cohort"),
247 type: "run.updated",
248 threadId,
249 runId: parent.id,
250 occurredAt: now,
251 payload: {
252 ...parent,
253 delegatedCompletion: {
254 disposition: "open",
255 nextGeneration: 2,
256 delivery: { generation: 1, messageId, taskIds: [taskId] },
257 },
258 },
259 },
260 {
261 id: EventId.make("child"),
262 type: "subagent.updated",
263 threadId,
264 runId: parent.id,
265 nodeId: taskId,
266 occurredAt: now,
267 payload: {
268 id: taskId,
269 threadId,
270 runId: parent.id,
271 parentNodeId: parent.rootNodeId,
272 origin: "app_owned",
273 createdBy: "agent",
274 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
275 providerInstanceId: modelSelection.instanceId,
276 providerThreadId: null,
277 childThreadId: null,
278 nativeTaskRef: null,
279 prompt: "Background work",
280 title: "Child",
281 model: null,
282 completionWake: "always",
283 completionDelivery: { state: "claimed", observedByRunId: null },
284 status: "completed",
285 result: "done",
286 startedAt: now,
287 completedAt: now,
288 updatedAt: now,
289 },
290 },
291 ],
292 });
293 const command = {
294 type: "message.dispatch" as const,
295 commandId: CommandId.make("completion"),
296 threadId,
297 messageId,
298 text: "Child completed",
299 attachments: [],
300 dispatchMode: { type: "queue_after_active" as const },
301 createdBy: "agent" as const,
302 creationSource: "server" as const,
303 delegatedCompletion: { parentRunId: parent.id, generation: 1, taskIds: [taskId] },
304 };
305 yield* orchestrator.dispatch(command);
306 yield* orchestrator.dispatch(command);
307 yield* orchestrator.recoverDelegatedTasks;
308 } else if (delivery === "scheduled message") {
309 yield* Effect.gen(function* () {
310 const service = yield* ScheduledTaskService.ScheduledTaskService;
311 const { task } = yield* service.upsert(
312 yield* decodeScheduledTask({
313 title: "Status check",
314 prompt: "Check the four tasks.",
315 enabled: true,
316 schedule: { type: "interval", everyMs: 60_000 },
317 projectId,
318 threadId,
319 workspaceStrategy: { type: "root" },
320 modelSelection,
321 runtimeMode: "full-access",
322 interactionMode: "default",
323 }),
324 );
325 const ran = yield* service.runNow({ id: task.id });
326 assert.equal(ran.task.lastRunStatus, "succeeded");
327 }).pipe(
328 Effect.provide(
329 ScheduledTaskService.layer.pipe(
330 Layer.provide(ThreadManagementService.layer),
331 Layer.provide(ServerSettings.layerTest()),
332 Layer.provide(
333 Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
334 ensureTranscript: () =>
335 Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
336 }),
337 ),
338 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
339 Layer.provide(ManagedPolicy.layerTest()),
340 Layer.provide(
341 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
342 namedProjectsRoot: "/projects",
343 isScratchProject: () => Effect.succeed(false),
344 }),
345 ),
346 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
347 Layer.provide(
348 CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
349 ),
350 Layer.provide(
351 Layer.mergeAll(
352 NodeCrypto.layer,
353 Scheduler.layer,
354 SqlitePersistence.layerMemory,
355 ),
356 ),
357 ),
358 ),
359 );
360 } else if (delivery === "user steering") {
361 yield* orchestrator.dispatch({
362 type: "message.dispatch",
363 commandId: CommandId.make("steer"),
364 threadId,
365 messageId,
366 text: "Change direction now.",
367 attachments: [],
368 dispatchMode: { type: "steer_active", targetRunId: parent.id },
369 createdBy: "user",
370 creationSource: "web",
371 });
372 } else {
373 yield* orchestrator.dispatch({
374 type: "message.dispatch",
375 commandId: CommandId.make("queue"),
376 threadId,
377 messageId,
378 text: "Change direction now.",
379 attachments: [],
380 dispatchMode: { type: "queue_after_active" },
381 createdBy: "user",
382 creationSource: "web",
383 });
384 const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!;
385 yield* orchestrator.dispatch({
386 type: "queued-message.promote-to-steer",
387 commandId: CommandId.make("promote"),
388 threadId,
389 queuedRunId: queuedRun.id,
390 targetRunId: parent.id,
391 });
392 const promoted = yield* orchestrator.getThreadProjection(threadId);
393 assert.equal(promoted.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled");
394 assert.equal(
395 promoted.messages.find((message) => message.id === messageId)?.runId,
396 parent.id,
397 );
398 const steer = promoted.turnItems.find(
399 (item) => item.type === "user_message" && item.messageId === messageId,
400 );
401 assert.ok(steer?.type === "user_message");
402 assert.equal(steer.inputIntent, "promoted_queued_to_steer");
403 }
404 yield* worker.drain();
405 const explicitSteer =
406 delivery === "user steering" || delivery === "promoted queued message";
407 assert.equal(batchAbort.signal.aborted, explicitSteer);
408 assert.equal(offers.length, explicitSteer ? 2 : 1);
409 const finished = yield* watch(
410 (event) =>
411 event.type === "run.updated" &&
412 event.payload.id === parent.id &&
413 event.payload.status === "waiting",
414 );
415 yield* Queue.offer(sdkMessages, toolResult("build", false));
416 for (const id of statusIds)
417 yield* Queue.offer(sdkMessages, toolResult(id, batchAbort.signal.aborted));
418 if (explicitSteer) yield* Queue.offer(sdkMessages, result("aborted", true));
419 yield* Queue.offer(sdkMessages, result("completed", false));
420 yield* Fiber.join(finished);
421 yield* worker.drain();
422 yield* orchestrator.resumeQueuedRuns;
423 yield* worker.drain();
424 if (!explicitSteer) {
425 const queued = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!;
426 const noticeFinished = yield* watch(
427 (event) =>
428 event.type === "run.updated" &&
429 event.payload.id === queued.id &&
430 event.payload.status === "waiting",
431 );
432 const delivered =
433 delivery === "child completion"
434 ? yield* watch(
435 (event) =>
436 event.type === "subagent.updated" &&
437 event.payload.completionDelivery?.state === "delivered",
438 )
439 : null;
440 yield* Queue.offer(sdkMessages, result("notice-completed", false));
441 yield* Fiber.join(noticeFinished);
442 yield* worker.drain();
443 if (delivered !== null) yield* Fiber.join(delivered);
444 }
445 const after = yield* orchestrator.getThreadProjection(threadId);
446 const reads = after.turnItems.filter((item) =>
447 statusIds.includes(item.nativeItemRef?.nativeId ?? ""),
448 );
449 assert.equal(reads.length, 4);
450 for (const read of reads) {
451 assert.equal(read.status, explicitSteer ? "cancelled" : "completed");
452 assert.equal(read.toolNonExecutionKind, explicitSteer ? "cancelled" : undefined);
453 assert.equal(read.type === "dynamic_tool" && read.output === refusal, explicitSteer);
454 }
455 assert.equal(offers.length, 2);
456 assert.equal(
457 offers.filter((offer) => offer.priority === "now").length,
458 explicitSteer ? 1 : 0,
459 );
460 if (!explicitSteer) {
461 assert.equal(after.runs.length, 2);
462 if (delivery === "child completion") {
463 assert.equal(after.messages.filter((message) => message.id === messageId).length, 1);
464 assert.equal(after.subagents[0]?.completionDelivery?.state, "delivered");
465 } else {
466 assert.equal(
467 after.messages.filter((message) => message.scheduledTaskId !== undefined).length,
468 1,
469 );
470 }
471 }
472 yield* orchestrator.recoverDelegatedTasks;
473 yield* orchestrator.resumeQueuedRuns;
474 yield* worker.drain();
475 assert.equal(offers.length, 2);
476 }).pipe(
477 Effect.provide(
478 ProviderReplayHarness.layerWithRegistry(
479 { name: "claude-automatic-delivery" },
480 ProviderAdapterRegistry.layerSingle(adapter),
481 { runEffectWorker: false },
482 ),
483 ),
484 );
485 }).pipe(
486 Effect.provide(
487 Layer.mergeAll(
488 IdAllocator.layer,
489 McpProviderSessions.layer,
490 NodeServices.layer,
491 NodeCrypto.layer,
492 ),
493 ),
494 ),
495 ),
496);