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

TaskCancelNativeSubagent.integration.test.ts

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