Skip to content

Commit 46c1eef

Browse files
Leon-SK668obviyus
andauthored
fix(agents): surface failed subagent completion notices (#128512)
A failed subagent could leave a direct requester without a terminal result when requester-side synthesis failed on the same provider path. Use the trusted non-success completion event to send one fixed direct notice. Revalidate cancellation and source ownership before platform delivery, keep private failure text out of the notice, and preserve existing non-direct delivery paths. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent be67a8b commit 46c1eef

3 files changed

Lines changed: 178 additions & 5 deletions

File tree

‎src/agents/subagents/announce/subagent-announce-completion-delivery.ts‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
} from "../../embedded-agent-runner/delivery-evidence.js";
1616
import type { AgentInternalEvent } from "../../internal-events.js";
1717
import {
18+
SourceOwnerChangedError,
1819
sourceOwnerChangedResult,
1920
summarizeDeliveryError,
2021
} from "./subagent-announce-delivery-retry.js";
@@ -25,6 +26,9 @@ import {
2526
import type { SubagentAnnounceDeliveryResult } from "./subagent-announce-dispatch.js";
2627
import { inferDeliveryTargetChatType } from "./subagent-announce-origin.js";
2728

29+
const FAILED_COMPLETION_NOTICE =
30+
"A delegated task failed before it could report a result. Please retry the task.";
31+
2832
export function isGatewayAgentRunPending(response: unknown): boolean {
2933
if (!response || typeof response !== "object") {
3034
return false;
@@ -47,7 +51,13 @@ export function isDirectMessageDeliveryTarget(
4751
return deriveSessionChatTypeFromKey(requesterSessionKey) === "direct";
4852
}
4953

50-
function resolveTextCompletionDirectFallback(events: readonly AgentInternalEvent[] | undefined) {
54+
function resolveTextCompletionDirectFallback(
55+
events: readonly AgentInternalEvent[] | undefined,
56+
contentKind: "completed_result" | "failed_notice",
57+
) {
58+
if (contentKind === "failed_notice") {
59+
return FAILED_COMPLETION_NOTICE;
60+
}
5161
for (let index = (events?.length ?? 0) - 1; index >= 0; index -= 1) {
5262
const event = events?.[index];
5363
if (event?.type !== "task_completion" || event.source !== "subagent") {
@@ -94,10 +104,12 @@ export async function deliverCompletionDirect(params: {
94104
threadId?: string;
95105
};
96106
internalEvents?: readonly AgentInternalEvent[];
107+
contentKind: "completed_result" | "failed_notice";
108+
signal?: AbortSignal;
97109
onDeliveryResult?: (delivery: SubagentAnnounceDeliveryResult) => void;
98110
isSourceSessionEffectsAllowed?: () => boolean;
99111
}): Promise<SubagentAnnounceDeliveryResult | undefined> {
100-
const content = resolveTextCompletionDirectFallback(params.internalEvents);
112+
const content = resolveTextCompletionDirectFallback(params.internalEvents, params.contentKind);
101113
if (
102114
!content ||
103115
!params.deliveryTarget.deliver ||
@@ -121,6 +133,9 @@ export async function deliverCompletionDirect(params: {
121133
if (params.isSourceSessionEffectsAllowed?.() === false) {
122134
return sourceOwnerChangedResult();
123135
}
136+
if (params.signal?.aborted) {
137+
return { delivered: false, path: "none" };
138+
}
124139
const sendResult = await sendSubagentAnnounceMessage({
125140
cfg: params.cfg,
126141
channel: params.deliveryTarget.channel,
@@ -132,6 +147,14 @@ export async function deliverCompletionDirect(params: {
132147
conversationType: "direct",
133148
content,
134149
idempotencyKey,
150+
skipQueue: true,
151+
abortSignal: params.signal,
152+
onPlatformSendDispatch: async () => {
153+
params.signal?.throwIfAborted();
154+
if (params.isSourceSessionEffectsAllowed?.() === false) {
155+
throw new SourceOwnerChangedError();
156+
}
157+
},
135158
onDeliveryResult: () => {
136159
if (committedDelivery) {
137160
return;
@@ -170,6 +193,12 @@ export async function deliverCompletionDirect(params: {
170193
// retryable failure and send the same completion twice.
171194
return committedDelivery;
172195
}
196+
if (err instanceof SourceOwnerChangedError) {
197+
return sourceOwnerChangedResult();
198+
}
199+
if (params.signal?.aborted) {
200+
return { delivered: false, path: "none" };
201+
}
173202
return {
174203
delivered: false,
175204
path: "direct",

‎src/agents/subagents/announce/subagent-announce-delivery.test.ts‎

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,7 @@ async function deliverSlackThreadAnnouncement(params: {
355355
queueEmbeddedAgentMessageWithOutcome?: QueueEmbeddedAgentMessageWithOutcome;
356356
sendMessage?: typeof runtimeSendMessage;
357357
internalEvents?: AgentInternalEvent[];
358+
sourceSessionKey?: string;
358359
sourceTool?: string;
359360
requesterAbandoned?: boolean;
360361
isSourceSessionEffectsAllowed?: () => boolean;
@@ -416,6 +417,7 @@ async function deliverSlackThreadAnnouncement(params: {
416417
directIdempotencyKey: params.directIdempotencyKey,
417418
internalEvents: params.internalEvents,
418419
sourceRunId: "run-generated-media",
420+
sourceSessionKey: params.sourceSessionKey,
419421
sourceTool: params.sourceTool,
420422
isSourceSessionEffectsAllowed: params.isSourceSessionEffectsAllowed,
421423
isCompletionOwnedByRequesterYield: params.isCompletionOwnedByRequesterYield,
@@ -1951,6 +1953,134 @@ describe("deliverSubagentAnnouncement completion delivery", () => {
19511953
expect(sendMessage).not.toHaveBeenCalled();
19521954
});
19531955

1956+
it.each(["error", "timeout", "unknown"] as const)(
1957+
"sends one generic direct notice when requester synthesis repeats a %s child completion",
1958+
async (status) => {
1959+
const childSessionKey = `agent:worker:subagent:${status}-child`;
1960+
const providerFailure = "provider rejected private-model-alias with status 400";
1961+
const childResult = "private child output must not reach the requester";
1962+
const callGateway = vi.fn(async () => {
1963+
throw new Error(providerFailure);
1964+
}) as unknown as typeof runtimeCallGateway;
1965+
const sendMessage = createSendMessageMock();
1966+
1967+
const result = await deliverDiscordDirectMessageCompletion({
1968+
callGateway,
1969+
sendMessage,
1970+
sourceSessionKey: childSessionKey,
1971+
sourceTool: "subagent_announce",
1972+
internalEvents: taskCompletionEvents({
1973+
childSessionKey,
1974+
childSessionId: `${status}-child-session-id`,
1975+
status,
1976+
statusLabel: `${status}: ${providerFailure}`,
1977+
result: childResult,
1978+
}),
1979+
});
1980+
1981+
expectRecordFields(result, { delivered: true, path: "direct" });
1982+
expect(callGateway).toHaveBeenCalledOnce();
1983+
expect(sendMessage).toHaveBeenCalledOnce();
1984+
const content = mockCallArg(sendMessage, 0, 0).content;
1985+
expect(content).toBe(
1986+
"A delegated task failed before it could report a result. Please retry the task.",
1987+
);
1988+
expect(content).not.toContain(providerFailure);
1989+
expect(content).not.toContain(childResult);
1990+
},
1991+
);
1992+
1993+
it.each(["cancelled", "source owner changed"] as const)(
1994+
"stops a failed-child notice when %s at platform dispatch",
1995+
async (blockedBy) => {
1996+
const childSessionKey = `agent:worker:subagent:${blockedBy.replaceAll(" ", "-")}`;
1997+
const controller = new AbortController();
1998+
let sourceEffectsAllowed = true;
1999+
const platformSend = vi.fn();
2000+
const callGateway = vi.fn(async () => {
2001+
throw new Error("provider rejected requester synthesis");
2002+
}) as unknown as typeof runtimeCallGateway;
2003+
const sendMessage = vi.fn(async (params: Parameters<typeof runtimeSendMessage>[0]) => {
2004+
expect(params.skipQueue).toBe(true);
2005+
expect(params.abortSignal).toBe(controller.signal);
2006+
if (blockedBy === "cancelled") {
2007+
controller.abort();
2008+
} else {
2009+
sourceEffectsAllowed = false;
2010+
}
2011+
await params.onPlatformSendDispatch?.();
2012+
platformSend();
2013+
return {
2014+
channel: "discord",
2015+
to: "dm:U123",
2016+
via: "direct" as const,
2017+
mediaUrl: null,
2018+
result: { messageId: "msg-after-stale-dispatch" },
2019+
};
2020+
}) as unknown as typeof runtimeSendMessage;
2021+
2022+
const result = await deliverDiscordDirectMessageCompletion({
2023+
callGateway,
2024+
sendMessage,
2025+
signal: controller.signal,
2026+
sourceSessionKey: childSessionKey,
2027+
sourceTool: "subagent_announce",
2028+
isSourceSessionEffectsAllowed: () => sourceEffectsAllowed,
2029+
internalEvents: taskCompletionEvents({
2030+
childSessionKey,
2031+
status: "error",
2032+
statusLabel: "failed before fallback dispatch",
2033+
result: "private child output",
2034+
}),
2035+
});
2036+
2037+
expect(result).toMatchObject(
2038+
blockedBy === "cancelled"
2039+
? { delivered: false, path: "none" }
2040+
: { delivered: false, path: "none", reason: "source_owner_changed", terminal: true },
2041+
);
2042+
expect(sendMessage).toHaveBeenCalledOnce();
2043+
expect(platformSend).not.toHaveBeenCalled();
2044+
},
2045+
);
2046+
2047+
it("does not send a failed-child notice for an untrusted event or non-direct target", async () => {
2048+
const callGateway = vi.fn(async () => {
2049+
throw new Error("provider rejected requester synthesis");
2050+
}) as unknown as typeof runtimeCallGateway;
2051+
const sendMessage = createSendMessageMock();
2052+
2053+
const untrusted = await deliverDiscordDirectMessageCompletion({
2054+
callGateway,
2055+
sendMessage,
2056+
sourceSessionKey: "agent:worker:subagent:expected-child",
2057+
sourceTool: "subagent_announce",
2058+
internalEvents: taskCompletionEvents({
2059+
childSessionKey: "agent:worker:subagent:other-child",
2060+
status: "error",
2061+
statusLabel: "failed: provider rejected child run",
2062+
result: "private child output",
2063+
}),
2064+
});
2065+
const nonDirect = await deliverSlackThreadAnnouncement({
2066+
callGateway,
2067+
sendMessage,
2068+
directIdempotencyKey: "announce-failed-thread-child",
2069+
sourceSessionKey: "agent:worker:subagent:failed-thread-child",
2070+
sourceTool: "subagent_announce",
2071+
internalEvents: taskCompletionEvents({
2072+
childSessionKey: "agent:worker:subagent:failed-thread-child",
2073+
status: "error",
2074+
statusLabel: "failed: provider rejected child run",
2075+
result: "private child output",
2076+
}),
2077+
});
2078+
2079+
expectRecordFields(untrusted, { delivered: false, path: "direct" });
2080+
expectRecordFields(nonDirect, { delivered: false, path: "direct" });
2081+
expect(sendMessage).not.toHaveBeenCalled();
2082+
});
2083+
19542084
it("directly delivers unprefixed direct targets recognized by the channel grammar", async () => {
19552085
registerDirectTargetTestChannel("qa-channel");
19562086
const callGateway = createPayloadGatewayMock();

‎src/agents/subagents/announce/subagent-announce-direct-delivery.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,8 @@ export async function sendSubagentAnnounceDirectly(params: {
169169
subagentCompletionEvents[0]?.childSessionKey === params.sourceSessionKey
170170
? subagentCompletionEvents[0]
171171
: undefined;
172+
const hasFailedTrustedSubagentCompletion =
173+
trustedCompletionEvent !== undefined && trustedCompletionEvent.status !== "ok";
172174
const hasRequiredSubagentNoOutputCompletion =
173175
params.expectsCompletionMessage &&
174176
isSubagentCompletion &&
@@ -223,14 +225,18 @@ export async function sendSubagentAnnounceDirectly(params: {
223225
disposition: "intentional_non_delivery",
224226
};
225227
}
226-
const tryTextCompletionDirectDelivery = () =>
228+
const tryTextCompletionDirectDelivery = (
229+
contentKind: "completed_result" | "failed_notice" = "completed_result",
230+
) =>
227231
deliverCompletionDirect({
228232
cfg,
229233
requesterSessionKey: canonicalRequesterSessionKey,
230234
requesterAgentId: params.requesterAgentId,
231235
directIdempotencyKey: params.directIdempotencyKey,
232236
deliveryTarget,
233237
internalEvents: params.internalEvents,
238+
contentKind,
239+
signal: params.signal,
234240
onDeliveryResult: params.onDeliveryResult,
235241
isSourceSessionEffectsAllowed: isCompletionDeliveryAllowed,
236242
});
@@ -400,13 +406,21 @@ export async function sendSubagentAnnounceDirectly(params: {
400406
if (hasAnnounceSendEvidence(err)) {
401407
throw err;
402408
}
409+
if (params.signal?.aborted) {
410+
return { delivered: false, path: "none" };
411+
}
412+
const directCompletionFallbackKind = hasFailedTrustedSubagentCompletion
413+
? "failed_notice"
414+
: isIncompleteAnnounceAgentResultError(err)
415+
? "completed_result"
416+
: undefined;
403417
if (
404418
params.expectsCompletionMessage &&
405419
(shouldDeliverAgentFinal || subagentDirectMessageCompletionRequiresMessageTool) &&
406420
isSubagentCompletion &&
407-
isIncompleteAnnounceAgentResultError(err)
421+
directCompletionFallbackKind
408422
) {
409-
const textDelivery = await tryTextCompletionDirectDelivery();
423+
const textDelivery = await tryTextCompletionDirectDelivery(directCompletionFallbackKind);
410424
if (textDelivery) {
411425
return textDelivery;
412426
}

0 commit comments

Comments
 (0)