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

ClaudeAutomaticDelivery.integration.test.ts

513 lines20.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​
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 && id !== "build"
104 ? { tool_result_meta: [{ id, non_execution_kind: "cancelled" }] }
105 : {}),
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 const batchAbort = new AbortController();
144 const commandAbort = new AbortController();
145 let closes = 0;
146 const offersAtInterrupt: number[] = [];
147 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
148 instanceId: modelSelection.instanceId,
149 settings,
150 environment: {},
151 attachmentsDir: cwd,
152 fileSystem: yield* FileSystem.FileSystem,
153 path: yield* Path.Path,
154 crypto: yield* Crypto.Crypto,
155 idAllocator: yield* IdAllocator.IdAllocatorV2,
156 queryRunner: {
157 allocateSessionId: Effect.succeed(sessionId),
158 open: () =>
159 Effect.succeed({
160 messages: Stream.fromQueue(sdkMessages),
161 offer: (message) =>
162 Effect.sync(() => {
163 if (message.priority === "now") {
164 assert.isTrue(
165 commandAbort.signal.aborted,
166 "interrupt the foreground command before offering the steer",
167 );
168 }
169 offers.push(message);
170 nativeQueue.push(message);
171 // Claude Code 2.1.289's queue watcher aborts when a now-priority
172 // command arrives, including while Bash blocks pending reads.
173 if (nativeQueue.some((command) => command.priority === "now")) {
174 batchAbort.abort({ kind: "interrupt" });
175 }
176 }),
177 setModel: () => Effect.void,
178 applyFlagSettings: () => Effect.void,
179 setPermissionMode: () => Effect.void,
180 backgroundTasks: () => Effect.succeed(false),
181 stopTask: () => Effect.void,
182 interrupt:
183 delivery === "user steering" || delivery === "promoted queued message"
184 ? Effect.sync(() => {
185 offersAtInterrupt.push(offers.length);
186 commandAbort.abort();
187 })
188 : Effect.die("automatic delivery must never interrupt"),
189 close: Effect.sync(() => {
190 closes++;
191 }),
192 }),
193 forkSession: () => Effect.die("unused"),
194 subagentLaunchToolUseId: () => Effect.succeed(null),
195 assertComplete: Effect.void,
196 },
197 });
198 yield* Effect.gen(function* () {
199 const orchestrator = yield* Orchestrator.OrchestratorV2;
200 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
201 const threadId = ThreadId.make("thread:automatic-delivery");
202 const projectId = ProjectId.make("project:automatic-delivery");
203 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
204 orchestrator.streamDomainEvents.pipe(
205 Stream.filter(predicate),
206 Stream.take(1),
207 Stream.runDrain,
208 Effect.forkScoped,
209 );
210 yield* orchestrator.dispatch({
211 type: "thread.create",
212 commandId: CommandId.make("create"),
213 threadId,
214 projectId,
215 title: "Automatic delivery",
216 modelSelection,
217 runtimeMode: "full-access",
218 interactionMode: "default",
219 branch: null,
220 worktreePath: cwd,
221 createdBy: "user",
222 creationSource: "web",
223 });
224 const running = yield* watch(
225 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
226 );
227 yield* orchestrator.dispatch({
228 type: "message.dispatch",
229 commandId: CommandId.make("first"),
230 threadId,
231 messageId: MessageId.make("first"),
232 text: "Build and check all four tasks.",
233 attachments: [],
234 dispatchMode: { type: "start_immediately" },
235 createdBy: "user",
236 creationSource: "web",
237 });
238 yield* worker.drain();
239 yield* Fiber.join(running);
240 const pending = yield* watch(
241 (event) =>
242 event.type === "turn-item.updated" &&
243 event.payload.nativeItemRef?.nativeId === "status-4",
244 );
245 yield* Queue.offer(sdkMessages, batch);
246 yield* Fiber.join(pending);
247 const before = yield* orchestrator.getThreadProjection(threadId);
248 assert.equal(before.turnItems.filter((item) => item.status === "running").length, 5);
249 const parent = before.runs[0]!;
250 if (parent.rootNodeId === null) return yield* Effect.die("parent has no root node");
251 const messageId = MessageId.make("automatic-notice");
252 if (delivery === "child completion") {
253 const taskId = NodeId.make("completed-child");
254 const now = yield* DateTime.now;
255 const sink = yield* EventSink.EventSinkV2;
256 yield* sink.write({
257 events: [
258 {
259 id: EventId.make("cohort"),
260 type: "run.updated",
261 threadId,
262 runId: parent.id,
263 occurredAt: now,
264 payload: {
265 ...parent,
266 delegatedCompletion: {
267 disposition: "open",
268 nextGeneration: 2,
269 delivery: { generation: 1, messageId, taskIds: [taskId] },
270 },
271 },
272 },
273 {
274 id: EventId.make("child"),
275 type: "subagent.updated",
276 threadId,
277 runId: parent.id,
278 nodeId: taskId,
279 occurredAt: now,
280 payload: {
281 id: taskId,
282 threadId,
283 runId: parent.id,
284 parentNodeId: parent.rootNodeId,
285 origin: "app_owned",
286 createdBy: "agent",
287 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
288 providerInstanceId: modelSelection.instanceId,
289 providerThreadId: null,
290 childThreadId: null,
291 nativeTaskRef: null,
292 prompt: "Background work",
293 title: "Child",
294 model: null,
295 completionWake: "always",
296 completionDelivery: { state: "claimed", observedByRunId: null },
297 status: "completed",
298 result: "done",
299 startedAt: now,
300 completedAt: now,
301 updatedAt: now,
302 },
303 },
304 ],
305 });
306 const command = {
307 type: "message.dispatch" as const,
308 commandId: CommandId.make("completion"),
309 threadId,
310 messageId,
311 text: "Child completed",
312 attachments: [],
313 dispatchMode: { type: "queue_after_active" as const },
314 createdBy: "agent" as const,
315 creationSource: "server" as const,
316 delegatedCompletion: { parentRunId: parent.id, generation: 1, taskIds: [taskId] },
317 };
318 yield* orchestrator.dispatch(command);
319 yield* orchestrator.dispatch(command);
320 yield* orchestrator.recoverDelegatedTasks;
321 } else if (delivery === "scheduled message") {
322 yield* Effect.gen(function* () {
323 const service = yield* ScheduledTaskService.ScheduledTaskService;
324 const { task } = yield* service.upsert(
325 yield* decodeScheduledTask({
326 title: "Status check",
327 prompt: "Check the four tasks.",
328 enabled: true,
329 schedule: { type: "interval", everyMs: 60_000 },
330 projectId,
331 threadId,
332 workspaceStrategy: { type: "root" },
333 modelSelection,
334 runtimeMode: "full-access",
335 interactionMode: "default",
336 }),
337 );
338 const ran = yield* service.runNow({ id: task.id });
339 assert.equal(ran.task.lastRunStatus, "succeeded");
340 }).pipe(
341 Effect.provide(
342 ScheduledTaskService.layer.pipe(
343 Layer.provide(ThreadManagementService.layer),
344 Layer.provide(ServerSettings.layerTest()),
345 Layer.provide(
346 Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
347 ensureTranscript: () =>
348 Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
349 }),
350 ),
351 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
352 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
353 Layer.provide(
354 CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
355 ),
356 Layer.provide(
357 Layer.mergeAll(
358 NodeCrypto.layer,
359 Scheduler.layer,
360 SqlitePersistence.layerMemory,
361 ),
362 ),
363 ),
364 ),
365 );
366 } else if (delivery === "user steering") {
367 yield* orchestrator.dispatch({
368 type: "message.dispatch",
369 commandId: CommandId.make("steer"),
370 threadId,
371 messageId,
372 text: "Change direction now.",
373 attachments: [],
374 dispatchMode: { type: "steer_active", targetRunId: parent.id },
375 createdBy: "user",
376 creationSource: "web",
377 });
378 } else {
379 yield* orchestrator.dispatch({
380 type: "message.dispatch",
381 commandId: CommandId.make("queue"),
382 threadId,
383 messageId,
384 text: "Change direction now.",
385 attachments: [],
386 dispatchMode: { type: "queue_after_active" },
387 createdBy: "user",
388 creationSource: "web",
389 });
390 const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!;
391 yield* orchestrator.dispatch({
392 type: "queued-message.promote-to-steer",
393 commandId: CommandId.make("promote"),
394 threadId,
395 queuedRunId: queuedRun.id,
396 targetRunId: parent.id,
397 });
398 // Promotion cancels the queued run and moves its message into the
399 // running run as a steer that remembers where it came from.
400 const promoted = yield* orchestrator.getThreadProjection(threadId);
401 assert.equal(promoted.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled");
402 assert.equal(
403 promoted.messages.find((message) => message.id === messageId)?.runId,
404 parent.id,
405 );
406 const steer = promoted.turnItems.find(
407 (item) => item.type === "user_message" && item.messageId === messageId,
408 );
409 assert.ok(steer?.type === "user_message");
410 assert.equal(steer.inputIntent, "promoted_queued_to_steer");
411 }
412 yield* worker.drain();
413 const explicitSteer =
414 delivery === "user steering" || delivery === "promoted queued message";
415 assert.equal(batchAbort.signal.aborted, explicitSteer);
416 assert.equal(commandAbort.signal.aborted, explicitSteer);
417 assert.equal(closes, 0);
418 assert.equal(offers.length, explicitSteer ? 2 : 1);
419 assert.deepEqual(offersAtInterrupt, explicitSteer ? [1] : []);
420 const finished = yield* watch(
421 (event) =>
422 event.type === "run.updated" &&
423 event.payload.id === parent.id &&
424 event.payload.status === "waiting",
425 );
426 yield* Queue.offer(sdkMessages, toolResult("build", commandAbort.signal.aborted));
427 for (const id of statusIds)
428 yield* Queue.offer(sdkMessages, toolResult(id, batchAbort.signal.aborted));
429 if (explicitSteer) yield* Queue.offer(sdkMessages, result("aborted", true));
430 yield* Queue.offer(sdkMessages, result("completed", false));
431 yield* Fiber.join(finished);
432 yield* worker.drain();
433 yield* orchestrator.resumeQueuedRuns;
434 yield* worker.drain();
435 if (!explicitSteer) {
436 const queued = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!;
437 const noticeFinished = yield* watch(
438 (event) =>
439 event.type === "run.updated" &&
440 event.payload.id === queued.id &&
441 event.payload.status === "waiting",
442 );
443 const delivered =
444 delivery === "child completion"
445 ? yield* watch(
446 (event) =>
447 event.type === "subagent.updated" &&
448 event.payload.completionDelivery?.state === "delivered",
449 )
450 : null;
451 yield* Queue.offer(sdkMessages, result("notice-completed", false));
452 yield* Fiber.join(noticeFinished);
453 yield* worker.drain();
454 if (delivered !== null) yield* Fiber.join(delivered);
455 }
456 const after = yield* orchestrator.getThreadProjection(threadId);
457 assert.equal(closes, 0, "the steer must complete without closing the query");
458 if (explicitSteer) {
459 assert.lengthOf(
460 after.runs.filter((run) => run.status !== "cancelled"),
461 1,
462 );
463 assert.lengthOf(after.providerTurns, 1);
464 assert.equal(after.providerTurns[0]?.status, "completed");
465 }
466 const command = after.turnItems.find((item) => item.nativeItemRef?.nativeId === "build");
467 assert.equal(command?.status, explicitSteer ? "failed" : "completed");
468 const reads = after.turnItems.filter((item) =>
469 statusIds.includes(item.nativeItemRef?.nativeId ?? ""),
470 );
471 assert.equal(reads.length, 4);
472 for (const read of reads) {
473 assert.equal(read.status, explicitSteer ? "cancelled" : "completed");
474 assert.equal(read.toolNonExecutionKind, explicitSteer ? "cancelled" : undefined);
475 assert.equal(read.type === "dynamic_tool" && read.output === refusal, explicitSteer);
476 }
477 assert.equal(offers.length, 2);
478 assert.equal(
479 offers.filter((offer) => offer.priority === "now").length,
480 explicitSteer ? 1 : 0,
481 );
482 if (!explicitSteer) {
483 assert.equal(after.runs.length, 2);
484 if (delivery === "child completion") {
485 assert.equal(after.messages.filter((message) => message.id === messageId).length, 1);
486 assert.equal(after.subagents[0]?.completionDelivery?.state, "delivered");
487 } else {
488 assert.equal(
489 after.messages.filter((message) => message.scheduledTaskId !== undefined).length,
490 1,
491 );
492 }
493 }
494 yield* orchestrator.recoverDelegatedTasks;
495 yield* orchestrator.resumeQueuedRuns;
496 yield* worker.drain();
497 assert.equal(offers.length, 2);
498 }).pipe(
499 Effect.provide(
500 ProviderReplayHarness.layerWithRegistry(
501 { name: "claude-automatic-delivery" },
502 ProviderAdapterRegistry.layerSingle(adapter),
503 { runEffectWorker: false },
504 ),
505 ),
506 );
507 }).pipe(
508 Effect.provide(
509 Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
510 ),
511 ),
512 ),
513);