Skip to content

Commit afd98d7

Browse files
im-kvijayclaudeYash-Singh1
authored
fix(server): stopped native subagents no longer read as Running (pingdotgg#17223)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Yash Singh <[email protected]>
1 parent 8c777fb commit afd98d7

12 files changed

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

0 commit comments

Comments
 (0)