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

ClaudeAutomaticDelivery.integration.test.ts

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