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

TaskCancelNativeSubagent.integration.test.ts

374 lines14.5 KB

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