Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import {
4 CommandId,
5 EnvironmentId,
6 MessageId,
7 NodeId,
8 ProjectId,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 ProviderThreadId,
12 ProviderTurnId,
13 ThreadId,
14 TurnItemId,
15 type OrchestrationV2DomainEvent,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Fiber from "effect/Fiber";
20import * as Layer from "effect/Layer";
21import * as Queue from "effect/Queue";
22import * as Stream from "effect/Stream";
23
24import { ClaudeProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
25import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
26import * as EffectWorker from "../orchestration-v2/EffectWorker.ts";
27import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
28import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
29import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
30import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
31import * as ServerSettings from "../serverSettings.ts";
32import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
33import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
34import * as SqlitePersistence from "../persistence/Sqlite.ts";
35import * as ProjectService from "../project/ProjectService.ts";
36import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
37import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
38import * as SecretRequests from "../secrets/SecretRequests.ts";
39import type { McpInvocationScope } from "./McpInvocationContext.ts";
40import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
41
42const driver = ProviderDriverKind.make("claudeAgent");
43const instanceId = ProviderInstanceId.make("claudeAgent");
44const modelSelection = { instanceId, model: "claude-test" };
45
46// A delegated Claude child ends its turn while a background native subagent it
47// started keeps running (#17154). Cancelling the task stops the child, which
48// ends that subagent's process, so the task must end instead of waiting on it.
49it.effect("task_cancel ends a delegated child's background native subagent", () =>
50 Effect.scoped(
51 Effect.gen(function* () {
52 const cwd = yield* checkpointWorkspace("task-cancel-native-subagent");
53 const turns: Array<{
54 readonly turn: ProviderAdapter.ProviderAdapterV2TurnInput;
55 readonly events: Queue.Queue<ProviderAdapter.ProviderAdapterV2Event>;
56 }> = [];
57 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
58 instanceId,
59 driver,
60 getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2),
61 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
62 openSession: (input) =>
63 Effect.gen(function* () {
64 const now = yield* DateTime.now;
65 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
66 return {
67 instanceId,
68 driver,
69 providerSessionId: input.providerSessionId,
70 providerSession: {
71 id: input.providerSessionId,
72 driver,
73 providerInstanceId: instanceId,
74 status: "ready",
75 cwd,
76 model: modelSelection.model,
77 capabilities: ClaudeProviderCapabilitiesV2,
78 createdAt: now,
79 updatedAt: now,
80 lastError: null,
81 },
82 events: Stream.fromQueue(events),
83 ensureThread: ({ threadId }) =>
84 Effect.succeed({
85 id: ProviderThreadId.make(`provider-thread:${threadId}`),
86 driver,
87 providerInstanceId: instanceId,
88 providerSessionId: input.providerSessionId,
89 appThreadId: threadId,
90 ownerNodeId: null,
91 nativeThreadRef: { driver, nativeId: `native:${threadId}`, strength: "strong" },
92 nativeConversationHeadRef: null,
93 status: "idle",
94 firstRunOrdinal: null,
95 lastRunOrdinal: null,
96 handoffIds: [],
97 forkedFrom: null,
98 createdAt: now,
99 updatedAt: now,
100 }),
101 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
102 startTurn: (turn) =>
103 Effect.gen(function* () {
104 turns.push({ turn, events });
105 yield* Queue.offer(events, {
106 type: "provider_turn.updated",
107 driver,
108 providerTurn: {
109 id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
110 providerThreadId: turn.providerThread.id,
111 nodeId: turn.rootNodeId,
112 runAttemptId: turn.attemptId,
113 nativeTurnRef: null,
114 ordinal: turn.providerTurnOrdinal,
115 status: "running",
116 startedAt: now,
117 completedAt: null,
118 },
119 });
120 }),
121 steerTurn: () => Effect.die("unused"),
122 interruptTurn: () => Effect.void,
123 respondToRuntimeRequest: () => Effect.die("unused"),
124 readThreadSnapshot: () => Effect.die("unused"),
125 rollbackThread: () => Effect.die("unused"),
126 forkThread: () => Effect.die("unused"),
127 };
128 }),
129 };
130 const layerAdapters = ProviderAdapterRegistry.layerSingle(adapter);
131 const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
132 { name: "task-cancel-native-subagent" },
133 layerAdapters,
134 { runEffectWorker: false },
135 );
136 const layerOrchestration = Layer.merge(
137 layerOrchestrator,
138 ThreadManagementService.layer.pipe(
139 Layer.provide(layerOrchestrator),
140 Layer.provide(ServerSettings.layerTest()),
141 Layer.provide(
142 CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
143 ),
144 ),
145 );
146 const layerTest = OrchestratorMcpService.layer.pipe(
147 Layer.provideMerge(layerOrchestration),
148 Layer.provide(
149 Layer.mergeAll(
150 layerAdapters,
151 Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
152 Layer.mock(ProjectService.ProjectService)({}),
153 Layer.mock(SecretRequests.SecretRequests)({}),
154 ServerSettings.layerTest(),
155 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
156 NodeServices.layer,
157 ),
158 ),
159 );
160
161 yield* Effect.gen(function* () {
162 const orchestrator = yield* Orchestrator.OrchestratorV2;
163 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
164 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
165 const parentThreadId = ThreadId.make("thread:task-cancel-parent");
166 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
167 orchestrator.streamDomainEvents.pipe(
168 Stream.filter(predicate),
169 Stream.take(1),
170 Stream.runDrain,
171 Effect.forkScoped,
172 );
173 const turnRunning = () =>
174 watch(
175 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
176 );
177 yield* orchestrator.dispatch({
178 type: "thread.create",
179 commandId: CommandId.make("create-parent"),
180 threadId: parentThreadId,
181 projectId: ProjectId.make("project:task-cancel"),
182 title: "Parent",
183 modelSelection,
184 runtimeMode: "full-access",
185 interactionMode: "default",
186 branch: null,
187 worktreePath: cwd,
188 createdBy: "user",
189 creationSource: "web",
190 });
191 const parentRunning = yield* turnRunning();
192 yield* orchestrator.dispatch({
193 type: "message.dispatch",
194 commandId: CommandId.make("start-parent"),
195 threadId: parentThreadId,
196 messageId: MessageId.make("message:start-parent"),
197 text: "Delegate a review",
198 attachments: [],
199 dispatchMode: { type: "start_immediately" },
200 createdBy: "user",
201 creationSource: "web",
202 });
203 yield* worker.drain();
204 yield* Fiber.join(parentRunning);
205
206 const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
207 const childRunning = yield* turnRunning();
208 yield* orchestrator.dispatch({
209 type: "delegated_task.request",
210 commandId: CommandId.make("delegate"),
211 parentThreadId,
212 parentRunId: parentRun.id,
213 parentNodeId: parentRun.rootNodeId!,
214 task: "Review the change",
215 modelSelection,
216 runtimeMode: "full-access",
217 interactionMode: "default",
218 completionWake: "always",
219 createdBy: "agent",
220 creationSource: "mcp",
221 });
222 yield* worker.drain();
223 yield* Fiber.join(childRunning);
224 const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!;
225 const child = turns.find((entry) => entry.turn.threadId === task.childThreadId)!;
226 const childTurn = (yield* orchestrator.getThreadProjection(task.childThreadId!))
227 .providerTurns[0]!;
228
229 // The child starts a background native subagent, then ends its turn.
230 const now = yield* DateTime.now;
231 const subagentId = NodeId.make("node:native-subagent");
232 const native = {
233 threadId: task.childThreadId!,
234 runId: child.turn.runId,
235 origin: "provider_native",
236 driver,
237 providerInstanceId: instanceId,
238 providerThreadId: childTurn.providerThreadId,
239 childThreadId: null,
240 prompt: "Check the tests",
241 title: null,
242 status: "running",
243 result: null,
244 startedAt: now,
245 completedAt: null,
246 updatedAt: now,
247 } as const;
248 const waiting = yield* watch(
249 (event) =>
250 event.type === "run.updated" &&
251 event.payload.id === child.turn.runId &&
252 event.payload.status === "waiting",
253 );
254 for (const event of [
255 {
256 type: "node.updated",
257 driver,
258 node: {
259 id: subagentId,
260 threadId: native.threadId,
261 runId: native.runId,
262 parentNodeId: child.turn.rootNodeId,
263 rootNodeId: child.turn.rootNodeId,
264 kind: "subagent",
265 status: "running",
266 countsForRun: false,
267 providerThreadId: childTurn.providerThreadId,
268 providerTurnId: childTurn.id,
269 nativeItemRef: null,
270 runtimeRequestId: null,
271 checkpointScopeId: null,
272 startedAt: now,
273 completedAt: null,
274 },
275 },
276 {
277 type: "subagent.updated",
278 driver,
279 subagent: {
280 ...native,
281 id: subagentId,
282 parentNodeId: child.turn.rootNodeId,
283 createdBy: "agent",
284 nativeTaskRef: null,
285 model: null,
286 },
287 },
288 {
289 type: "turn_item.updated",
290 driver,
291 turnItem: {
292 ...native,
293 id: TurnItemId.make("turn-item:native-subagent"),
294 nodeId: subagentId,
295 providerTurnId: childTurn.id,
296 nativeItemRef: null,
297 parentItemId: null,
298 ordinal: 1,
299 type: "subagent",
300 subagentId,
301 },
302 },
303 {
304 type: "provider_turn.updated",
305 driver,
306 providerTurn: { ...childTurn, status: "completed", completedAt: now },
307 },
308 {
309 type: "turn.terminal",
310 driver,
311 providerThreadId: childTurn.providerThreadId,
312 providerTurnId: childTurn.id,
313 runOrdinal: child.turn.runOrdinal,
314 status: "completed",
315 failure: null,
316 threadDisposition: "reusable",
317 },
318 ] satisfies ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>) {
319 yield* Queue.offer(child.events, event);
320 }
321 yield* Fiber.join(waiting);
322 yield* worker.drain();
323
324 const scope: McpInvocationScope = {
325 environmentId: EnvironmentId.make("environment:task-cancel"),
326 requestNamespace: "provider-session:task-cancel",
327 thread: {
328 threadId: parentThreadId,
329 providerSessionId: "provider-session:task-cancel",
330 providerInstanceId: instanceId,
331 },
332 client: undefined,
333 capabilities: new Set(["orchestration"]),
334 issuedAt: 1,
335 };
336 const before = yield* service.taskStatus(scope, task.id);
337 assert.equal(before.status, "running");
338 assert.equal(before.workState, "waiting_for_children");
339
340 const cancelled = yield* service.cancelTask(scope, {
341 taskId: task.id,
342 clientRequestId: "cancel-task",
343 });
344 assert.equal(cancelled.status, "cancel_requested");
345 yield* worker.drain();
346
347 const childAfter = yield* orchestrator.getThreadProjection(task.childThreadId!);
348 assert.equal(
349 childAfter.subagents.find((entry) => entry.id === subagentId)?.status,
350 "interrupted",
351 );
352 assert.equal(
353 childAfter.nodes.find((entry) => entry.id === subagentId)?.status,
354 "interrupted",
355 );
356 assert.equal(
357 childAfter.turnItems.find((item) => item.type === "subagent")?.status,
358 "interrupted",
359 );
360 // The child's own turn had completed, so the task keeps that result.
361 const after = yield* service.taskStatus(scope, task.id);
362 assert.equal(after.status, "completed");
363 assert.notEqual(after.workState, "waiting_for_children");
364 }).pipe(Effect.provide(layerTest));
365 }),
366 ),
367);