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

ClaudeAutomaticDelivery.integration.test.ts

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