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

TaskCancelNativeSubagent.integration.test.ts

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