Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(tasks): handle inline and background subagent completions (#130050)

Georgiy Tarasovc543b028589a
diff --git a/packages/agent/packages/agent/src/adapters/claude/claude-agent.task-notification.test.ts b/packages/agent/packages/agent/src/adapters/claude/claude-agent.task-notification.test.ts
index 907f570aba84..92bf5397340b 100644
--- a/packages/agent/packages/agent/src/adapters/claude/claude-agent.task-notification.test.ts
+++ b/packages/agent/packages/agent/src/adapters/claude/claude-agent.task-notification.test.ts
@@ -148,10 +148,14 @@ function taskNotificationUserMessage(sessionId: string, event: string) {
};
}
-function taskNotificationResult(sessionId: string, uuid: string) {
+function taskNotificationResult(
+ sessionId: string,
+ uuid: string,
+ runId?: string,
+) {
return {
...resultSuccess(sessionId, uuid),
- origin: { kind: "task-notification" },
+ origin: { kind: "task-notification", runId },
};
}
@@ -210,9 +214,92 @@ describe("ClaudeAcpAgent — task-notification results", () => {
).toHaveLength(0);
});
- it.each(["completed", "failed", "stopped"])(
- "waits for every sub-agent and the parent's reply when a worker %s",
- async (status) => {
+ it.each(["after_response", "during_response"])(
+ "preserves an early echo %s until its separate result arrives",
+ async (delivery) => {
+ const { agent, client } = makeAgent();
+ const sessionId = "s-early-echo";
+ const { query, input } = installFakeSession(agent, sessionId, true);
+ const settled = vi.fn();
+ const prompt = agent
+ .prompt({ sessionId, prompt: [{ type: "text", text: "Research." }] })
+ .then(settled);
+ await tick();
+ await echoUserMessage(query, input);
+ try {
+ await send(query, {
+ type: "system",
+ subtype: "task_started",
+ task_id: "worker",
+ run_id: "run-worker",
+ task_type: "local_agent",
+ is_backgrounded: true,
+ });
+ if (delivery === "during_response") {
+ await send(query, {
+ type: "stream_event",
+ parent_tool_use_id: null,
+ session_id: sessionId,
+ event: {
+ type: "message_start",
+ message: { id: "waiting", usage: {}, content: [] },
+ },
+ });
+ } else {
+ await send(
+ query,
+ assistantMessage(sessionId, "waiting", "Research is pending."),
+ );
+ }
+ await send(query, {
+ type: "system",
+ subtype: "task_notification",
+ task_id: "worker",
+ run_id: "run-worker",
+ status: "completed",
+ summary: "Worker ended.",
+ });
+ await send(query, {
+ ...taskNotificationUserMessage(sessionId, "worker"),
+ origin: { kind: "task-notification", runId: "run-worker" },
+ isReplay: true,
+ });
+ await send(
+ query,
+ assistantMessage(sessionId, "waiting", "Still pending."),
+ );
+ await send(query, resultSuccess(sessionId, "initial"));
+ expect(settled).not.toHaveBeenCalled();
+ await send(
+ query,
+ assistantMessage(sessionId, "final", '{"repository":"example/app"}'),
+ );
+ await send(
+ query,
+ taskNotificationResult(sessionId, "final", "run-worker"),
+ );
+ expect(settled).toHaveBeenCalledOnce();
+ await prompt;
+ expect(
+ extNotificationCalls(
+ client.extNotification.mock.calls,
+ "_posthog/background_turn_complete",
+ ),
+ ).toHaveLength(0);
+ } finally {
+ await agent.cancel({ sessionId });
+ }
+ },
+ );
+
+ it.each([
+ ...["completed", "failed", "stopped"].flatMap((status) =>
+ [true, false].map((echo) => ({ status, echo, inline: false })),
+ ),
+ { status: "completed", echo: true, inline: true },
+ ])(
+ "waits for every sub-agent and the parent's reply when a worker $status (echo: $echo, inline: $inline)",
+ async ({ status, echo, inline }) => {
const { agent, client } = makeAgent();
const sessionId = "s-pending-subagents";
const { query, input } = installFakeSession(agent, sessionId, true);
@@ -233,6 +320,7 @@ describe("ClaudeAcpAgent — task-notification results", () => {
type: "system",
subtype: "task_started",
task_id: taskId,
+ run_id: taskId,
task_type: "local_agent",
is_backgrounded: true,
});
@@ -241,10 +329,12 @@ describe("ClaudeAcpAgent — task-notification results", () => {
query,
assistantMessage(sessionId, "waiting", "Research is pending."),
);
- await send(query, {
- ...resultSuccess(sessionId, "initial"),
- usage: { output_tokens: 3 },
- });
+ if (!inline) {
+ await send(query, {
+ ...resultSuccess(sessionId, "initial"),
+ usage: { output_tokens: 3 },
+ });
+ }
expect(settled).not.toHaveBeenCalled();
for (const taskId of ["worker-a", "worker-b"]) {
@@ -252,12 +342,15 @@ describe("ClaudeAcpAgent — task-notification results", () => {
type: "system",
subtype: "task_notification",
task_id: taskId,
+ run_id: taskId,
status,
summary: "Worker ended.",
output_file: "/tmp/worker-output",
});
expect(settled).not.toHaveBeenCalled();
- await send(query, taskNotificationUserMessage(sessionId, taskId));
+ if (echo) {
+ await send(query, taskNotificationUserMessage(sessionId, taskId));
+ }
await send(
query,
assistantMessage(
@@ -268,12 +361,21 @@ describe("ClaudeAcpAgent — task-notification results", () => {
: "Another worker remains.",
),
);
+ if (!inline) {
+ await send(query, {
+ ...taskNotificationResult(sessionId, taskId, taskId),
+ usage: { output_tokens: 5 },
+ });
+ }
+ if (taskId === "worker-a") expect(settled).not.toHaveBeenCalled();
+ }
+ if (inline) {
await send(query, {
- ...taskNotificationResult(sessionId, taskId),
- usage: { output_tokens: 5 },
+ ...resultSuccess(sessionId, "initial"),
+ usage: { output_tokens: 13 },
});
- if (taskId === "worker-a") expect(settled).not.toHaveBeenCalled();
}
+ expect(settled).toHaveBeenCalledOnce();
await expect(prompt).resolves.toMatchObject({
stopReason: "end_turn",
usage: { outputTokens: 13 },
@@ -294,7 +396,14 @@ describe("ClaudeAcpAgent — task-notification results", () => {
},
);
- it.each(["overlapping", "batched", "late_snapshot", "late_start", "resumed"])(
+ it.each([
+ "overlapping",
+ "missing_echo",
+ "batched",
+ "late_snapshot",
+ "late_start",
+ "resumed",
+ ])(
"handles %s notifications without accepting an unrelated wakeup",
async (delivery) => {
const { agent } = makeAgent();
@@ -358,9 +467,17 @@ describe("ClaudeAcpAgent — task-notification results", () => {
status: "completed",
summary: "Worker ended.",
});
- if (delivery === "overlapping") {
+ if (delivery === "overlapping" || delivery === "missing_echo") {
await send(query, workerNotification("worker-b"));
- await send(query, taskNotificationResult(sessionId, "worker-a"));
+ await send(
+ query,
+ taskNotificationResult(sessionId, "unrelated", "unrelated-run"),
+ );
+ expect(settled).not.toHaveBeenCalled();
+ await send(
+ query,
+ taskNotificationResult(sessionId, "worker-a", "worker-a"),
+ );
expect(settled).not.toHaveBeenCalled();
} else {
await send(query, {
@@ -403,7 +520,14 @@ describe("ClaudeAcpAgent — task-notification results", () => {
run_id: delivery === "resumed" ? "worker-b-2" : "worker-b",
});
}
- await send(query, taskNotificationResult(sessionId, "final"));
+ await send(
+ query,
+ taskNotificationResult(
+ sessionId,
+ "final",
+ delivery === "missing_echo" ? "worker-b" : undefined,
+ ),
+ );
if (delivery === "resumed") {
expect(settled).not.toHaveBeenCalled();
await send(query, {
@@ -414,15 +538,19 @@ describe("ClaudeAcpAgent — task-notification results", () => {
status: "completed",
summary: "Worker ended.",
});
- await send(query, {
- ...taskNotificationUserMessage(sessionId, "worker-b"),
- origin: { kind: "task-notification", runId: "worker-b-2" },
- });
+ await send(
+ query,
+ taskNotificationResult(sessionId, "stale", "worker-b"),
+ );
+ expect(settled).not.toHaveBeenCalled();
await send(
query,
assistantMessage(sessionId, "resumed", "Research complete."),
);
- await send(query, taskNotificationResult(sessionId, "resumed"));
+ await send(
+ query,
+ taskNotificationResult(sessionId, "resumed", "worker-b-2"),
+ );
}
expect(settled).toHaveBeenCalledOnce();
await prompt;
diff --git a/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts b/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts
index 00fd413c6511..81a8db99907c 100644
--- a/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts
+++ b/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts
@@ -1133,11 +1133,24 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
}
pendingSubagents.set(taskId, runId);
};
- const subagentReplyBatches: Set<string>[] = [];
+ interface SubagentReplyBatch {
+ runId?: string;
+ replyMessageId?: string;
+ tasks: Map<string, string | undefined>;
+ }
+ const subagentReplyBatches: SubagentReplyBatch[] = [];
+ let parentReplyMessageId: string | undefined;
+ const recordParentReply = (messageId: string): void => {
+ if (messageId === parentReplyMessageId) return;
+ parentReplyMessageId = messageId;
+ for (const batch of subagentReplyBatches) {
+ batch.replyMessageId = messageId;
+ }
+ };
const hasPendingSubagents = () =>
pendingSubagents.size > 0 ||
completedSubagents.size > 0 ||
- subagentReplyBatches.some((batch) => batch.size > 0);
+ subagentReplyBatches.some((batch) => batch.tasks.size > 0);
// Read live: model switches reset session.lastContextWindowSize.
const windowSize = () =>
@@ -1202,6 +1215,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
completedSubagents.clear();
endedSubagentRuns.clear();
subagentReplyBatches.length = 0;
+ parentReplyMessageId = undefined;
lastAssistantTotalUsage = null;
lastRefusalExplanation = null;
lastRefusalCategory = null;
@@ -1603,12 +1617,45 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
break;
case "result": {
- const isTaskNotification =
- (message as { origin?: { kind?: string } }).origin?.kind ===
- "task-notification";
- const subagentReply = isTaskNotification
- ? subagentReplyBatches.shift()
- : undefined;
+ const origin = message.origin;
+ const isTaskNotification = origin?.kind === "task-notification";
+ let subagentReply: Map<string, string | undefined> | undefined;
+ if (isTaskNotification) {
+ const runId = origin.runId;
+ const batchIndex = runId
+ ? subagentReplyBatches.findIndex(
+ (batch) =>
+ batch.runId === runId ||
+ [...batch.tasks.values()].includes(runId),
+ )
+ : 0;
+ if (batchIndex >= 0) {
+ subagentReply = subagentReplyBatches.splice(batchIndex, 1)[0]
+ ?.tasks;
+ }
+ // The SDK can omit the notification's user echo, but its result still identifies the run.
+ if (runId) {
+ for (const [taskId, completedRunId] of completedSubagents) {
+ if (completedRunId === runId) {
+ subagentReply ??= new Map();
+ subagentReply.set(taskId, completedRunId);
+ completedSubagents.delete(taskId);
+ }
+ }
+ }
+ } else {
+ // An early echo can precede the old result; require a new parent response before retiring it.
+ for (let i = subagentReplyBatches.length - 1; i >= 0; i--) {
+ if (
+ parentReplyMessageId !== undefined &&
+ subagentReplyBatches[i]?.replyMessageId ===
+ parentReplyMessageId
+ ) {
+ subagentReplyBatches.splice(i, 1);
+ session.backgroundTurnActive = false;
+ }
+ }
+ }
const isSubagentContinuation =
session.activeTurn != null && (subagentReply?.size ?? 0) > 0;
const isBackgroundResult =
@@ -1865,6 +1912,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
message.event.type === "message_delta")
) {
if (message.event.type === "message_start") {
+ recordParentReply(message.event.message.id);
const u = message.event.message.usage;
lastStreamUsage = {
input_tokens: u.input_tokens ?? 0,
@@ -1906,6 +1954,12 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
case "user":
case "assistant": {
+ if (
+ message.type === "assistant" &&
+ message.parent_tool_use_id === null
+ ) {
+ recordParentReply(message.message.id);
+ }
if (
message.type === "user" &&
(message as { origin?: { kind?: string } }).origin?.kind ===
@@ -1922,18 +1976,21 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("\n");
- const batch = new Set<string>();
+ const batch = new Map<string, string | undefined>();
for (const [taskId, runId] of completedSubagents) {
if (
origin?.runId
? runId === origin.runId
: text.includes(`<task-id>${taskId}</task-id>`)
) {
- batch.add(taskId);
+ batch.set(taskId, runId);
completedSubagents.delete(taskId);
}
}
- subagentReplyBatches.push(batch);
+ subagentReplyBatches.push({
+ runId: origin?.runId,
+ tasks: batch,
+ });
}
}
// The SDK can echo a task notification before the previous