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

TaskCancelNativeSubagent.integration.test.ts

359 lines14.0 KB

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