Skip to content

Commit 2781abf

Browse files
committed
fix(agents): preserve timeout completion evidence
1 parent 42eda52 commit 2781abf

11 files changed

Lines changed: 305 additions & 17 deletions

‎extensions/qa-lab/src/providers/mock-openai/server.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2842,6 +2842,32 @@ describe("qa mock openai server", () => {
28422842
},
28432843
);
28442844

2845+
it.each(["visible", "silent", "fallback", "restart"])(
2846+
"uses explicit silence for the %s completion-agent direct fallback",
2847+
async (terminalCase) => {
2848+
const server = await startMockServer();
2849+
const payload = await expectNonStreamingResponsesJson(server, {
2850+
tools: [SESSIONS_SPAWN_TOOL, SESSIONS_YIELD_TOOL],
2851+
input: [
2852+
makeUserInput(`Subagent terminal reply QA check: ${terminalCase}.`),
2853+
makeUserInput(
2854+
TEST_RUNTIME_CONTEXT_CARRIER.replace(
2855+
"runtime metadata",
2856+
[
2857+
"[Internal task completion event]",
2858+
`Task: qa-terminal-${terminalCase}`,
2859+
`Result: QA-SUBAGENT-TERMINAL-${terminalCase.toUpperCase()}-OK`,
2860+
].join("\n"),
2861+
),
2862+
),
2863+
],
2864+
});
2865+
2866+
expect(outputItems(payload).some((item) => item.type === "function_call")).toBe(false);
2867+
expect(outputText(payload)).toBe("NO_REPLY");
2868+
},
2869+
);
2870+
28452871
it("uses the latest terminal-reply case in a shared parent transcript", async () => {
28462872
const server = await startMockServer();
28472873
const payload = await expectNonStreamingResponsesJson(server, {
@@ -2863,6 +2889,32 @@ describe("qa mock openai server", () => {
28632889
);
28642890
});
28652891

2892+
it("ignores a stale terminal-reply case in a later internal runtime carrier", async () => {
2893+
const server = await startMockServer();
2894+
const payload = await expectNonStreamingResponsesJson(server, {
2895+
tools: [SESSIONS_SPAWN_TOOL, SESSIONS_YIELD_TOOL],
2896+
input: [
2897+
makeUserInput("Subagent terminal reply QA check: fallback."),
2898+
makeUserInput(
2899+
TEST_RUNTIME_CONTEXT_CARRIER.replace(
2900+
"runtime metadata",
2901+
"Subagent terminal reply QA check: silent.",
2902+
),
2903+
),
2904+
],
2905+
});
2906+
2907+
expect(outputItems(payload).some((item) => item.type === "function_call")).toBe(true);
2908+
const debugRequest = requireRecord(
2909+
await (await fetch(`${server.baseUrl}/debug/last-request`)).json(),
2910+
"current terminal case debug request",
2911+
);
2912+
expect(debugRequest.plannedToolName).toBe("sessions_spawn");
2913+
expect(requireRecord(debugRequest.plannedToolArgs, "current terminal case args").label).toBe(
2914+
"qa-terminal-fallback",
2915+
);
2916+
});
2917+
28662918
it("does not treat prompt or instruction mentions as callable subagent tools", async () => {
28672919
const server = await startMockServer();
28682920
const payload = await expectNonStreamingResponsesJson(server, {

‎extensions/qa-lab/src/providers/mock-openai/server.ts‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -734,15 +734,11 @@ async function buildResponsesPayload(
734734
if (QA_SUBAGENT_DIRECT_FALLBACK_WORKER_RE.test(prompt)) {
735735
return buildAssistantEvents(QA_SUBAGENT_DIRECT_FALLBACK_MARKER);
736736
}
737-
const terminalCompletionCase = Array.from(
738-
allInputText.matchAll(
739-
new RegExp(
740-
QA_SUBAGENT_TERMINAL_MATRIX_PROMPT_RE.source,
741-
`${QA_SUBAGENT_TERMINAL_MATRIX_PROMPT_RE.flags.replaceAll("g", "")}g`,
742-
),
743-
),
737+
const terminalCompletionCase = extractLastMatchingUserTurn(
738+
input,
739+
QA_SUBAGENT_TERMINAL_MATRIX_PROMPT_RE,
744740
)
745-
.at(-1)?.[1]
741+
?.text.match(QA_SUBAGENT_TERMINAL_MATRIX_PROMPT_RE)?.[1]
746742
?.toLowerCase();
747743
if (terminalCompletionCase && /Internal task completion event/i.test(allInputText)) {
748744
if (terminalCompletionCase === "empty") {
@@ -767,8 +763,9 @@ async function buildResponsesPayload(
767763
return buildAssistantEvents(QA_SUBAGENT_TERMINAL_MARKERS.empty);
768764
}
769765
// The direct delivery fallback owns visible, silent, restart, and sanitized
770-
// fallback results when the resumed requester turn has no visible answer.
771-
return buildAssistantEvents("");
766+
// fallback results. Use explicit silence so generic empty-response recovery
767+
// cannot replay the historical spawn before that fallback runs.
768+
return buildAssistantEvents("NO_REPLY");
772769
}
773770
const terminalWorkerCase = Array.from(
774771
allInputText.matchAll(

‎qa/scenarios/agents/subagent-completion-direct-fallback.yaml‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,9 @@ flow:
150150
- set: preRestartOutbound
151151
value:
152152
expr: "state.getSnapshot().messages.filter((message) => message.direction === 'outbound' && verdicts.some((verdict) => verdict.conversationId === message.conversation.id)).map((message) => ({ id: message.id, conversationId: message.conversation.id, text: String(message.text ?? '') }))"
153+
- set: preRestartTerminalPayloads
154+
value:
155+
expr: "preRestartOutbound.filter((message) => verdicts.some((verdict) => verdict.capturedTerminalPayloads.includes(message.text)))"
153156
- set: restartPatch
154157
value:
155158
expr: "({ gateway: { controlUi: { allowedOrigins: [`http://127.0.0.1:${64000 + Math.floor(Math.random() * 999)}`] } } })"
@@ -180,9 +183,9 @@ flow:
180183
value:
181184
expr: "postRestartOutbound.filter((message) => !preRestartOutbound.some((before) => before.id === message.id))"
182185
- assert:
183-
expr: "JSON.stringify(postRestartTerminalPayloads) === JSON.stringify(preRestartOutbound)"
186+
expr: "JSON.stringify(postRestartTerminalPayloads) === JSON.stringify(preRestartTerminalPayloads)"
184187
message:
185-
expr: "`Gateway restart replayed or lost a prior terminal payload: before=${JSON.stringify(preRestartOutbound)} after=${JSON.stringify(postRestartTerminalPayloads)}`"
188+
expr: "`Gateway restart replayed or lost a prior terminal payload: before=${JSON.stringify(preRestartTerminalPayloads)} after=${JSON.stringify(postRestartTerminalPayloads)}`"
186189
- assert:
187190
expr: "restartInterruptionPayloads.length === 1 && restartInterruptionPayloads.every((message) => message.text.includes('interrupted by a gateway restart'))"
188191
message:
@@ -225,7 +228,7 @@ flow:
225228
expr: "`restart completion produced a failure diagnostic: outbound=${recentOutboundSummary(state)}`"
226229
- set: appendRestartVerdict
227230
value:
228-
expr: "verdicts.push({ case: 'restart', conversationId: restartConversationId, inputDisposition: 'visible', restart: true, fallback: true, preRestartTerminalMessageCount: preRestartOutbound.length, postRestartTerminalPayloadCount: postRestartTerminalPayloads.length, priorTerminalPayloadReplayCount: postRestartTerminalPayloads.length - preRestartOutbound.length, interruptedHandoffRepresentationCount: restartInterruptionPayloads.length, interruptedHandoffPayloads: restartInterruptionPayloads.map((message) => message.text), expectedTerminalSendCount: 1, actualTerminalSendCount: restartMatches.length, capturedTerminalPayloads: restartMatches.map((message) => String(message.text ?? '')), silenceTokenLeaked: false, internalMetadataLeak: false, pass: true })"
231+
expr: "verdicts.push({ case: 'restart', conversationId: restartConversationId, inputDisposition: 'visible', restart: true, fallback: true, preRestartTerminalMessageCount: preRestartTerminalPayloads.length, postRestartTerminalPayloadCount: postRestartTerminalPayloads.length, priorTerminalPayloadReplayCount: postRestartTerminalPayloads.length - preRestartTerminalPayloads.length, interruptedHandoffRepresentationCount: restartInterruptionPayloads.length, interruptedHandoffPayloads: restartInterruptionPayloads.map((message) => message.text), expectedTerminalSendCount: 1, actualTerminalSendCount: restartMatches.length, capturedTerminalPayloads: restartMatches.map((message) => String(message.text ?? '')), silenceTokenLeaked: false, internalMetadataLeak: false, pass: true })"
229232
- set: emptyStartIndex
230233
value:
231234
expr: state.getSnapshot().messages.length

‎src/agents/acp-spawn.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,8 @@ vi.mock("../config/sessions/session-accessor.js", async (importOriginal) => ({
224224

225225
vi.mock("../config/sessions.js", () => ({
226226
loadSessionStore: hoisted.loadSessionStoreMock,
227+
resolveAgentIdFromSessionKey: (sessionKey: string) =>
228+
sessionKey.match(/^agent:([^:]+)/)?.[1] ?? "main",
227229
resolveStorePath: hoisted.resolveStorePathMock,
228230
}));
229231

‎src/agents/subagent-announce-output.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,42 @@ describe("readSubagentOutput", () => {
168168
},
169169
);
170170

171+
it.each(["toolUse", "functionCall", "function_call"])(
172+
"summarizes provider-specific %s transcript blocks after a timeout",
173+
async (type) => {
174+
installOutputDeps({
175+
messages: [{ role: "assistant", content: [{ type, name: "read" }] }],
176+
});
177+
178+
await expect(
179+
readSubagentOutput("agent:main:subagent:child", { status: "timeout" }),
180+
).resolves.toBe("1 tool call(s) made without visible output.");
181+
},
182+
);
183+
184+
it.each(["toolCalls", "tool_calls"])("summarizes top-level %s after a timeout", async (field) => {
185+
installOutputDeps({
186+
messages: [{ role: "assistant", [field]: [{ name: "read" }, { name: "exec" }] }],
187+
});
188+
189+
await expect(
190+
readSubagentOutput("agent:main:subagent:child", { status: "timeout" }),
191+
).resolves.toBe("2 tool call(s) made without visible output.");
192+
});
193+
194+
it("keeps an intentional silent reply ahead of timeout tool progress", async () => {
195+
installOutputDeps({
196+
messages: [
197+
{ role: "assistant", content: [{ type: "toolCall", name: "read" }] },
198+
{ role: "assistant", content: [{ type: "text", text: "NO_REPLY" }] },
199+
],
200+
});
201+
202+
await expect(
203+
readSubagentOutput("agent:main:subagent:child", { status: "timeout" }),
204+
).resolves.toBe("NO_REPLY");
205+
});
206+
171207
it("returns final assistant output that arrives after a sessions_yield wait turn", async () => {
172208
installOutputDeps({
173209
messages: [
@@ -281,6 +317,29 @@ describe("readSubagentOutput", () => {
281317
await expect(readSubagentOutput("agent:main:subagent:child")).resolves.toBeUndefined();
282318
});
283319

320+
it("resets timeout tool progress at the latest user turn", async () => {
321+
installOutputDeps({
322+
messages: [
323+
{
324+
role: "assistant",
325+
content: [
326+
{ type: "toolCall", id: "old-read", name: "read", arguments: {} },
327+
{ type: "toolCall", id: "old-exec", name: "exec", arguments: {} },
328+
],
329+
},
330+
{ role: "user", content: [{ type: "text", text: "Start the next task." }] },
331+
{
332+
role: "assistant",
333+
content: [{ type: "toolCall", id: "current-call", name: "write", arguments: {} }],
334+
},
335+
],
336+
});
337+
338+
await expect(
339+
readSubagentOutput("agent:main:subagent:child", { status: "timeout" }),
340+
).resolves.toBe("1 tool call(s) made without visible output.");
341+
});
342+
284343
it("does not fall back to tool output when the last assistant turn is empty", async () => {
285344
installOutputDeps({
286345
messages: [

‎src/agents/subagent-announce-output.ts‎

Lines changed: 59 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@ const MAX_CHILD_COMPLETION_RESULT_CHARS = 512;
3333
const MAX_CHILD_COMPLETION_FIELD_CHARS = 256;
3434
const MAX_CHILD_COMPLETION_FINDINGS_CHARS = 4_096;
3535
const CHILD_RESULT_TRUNCATION_NOTICE = "\n[child result truncated]";
36+
const ASSISTANT_TOOL_CALL_BLOCK_TYPES = new Set([
37+
"toolCall",
38+
"tool_use",
39+
"toolUse",
40+
"functionCall",
41+
"function_call",
42+
]);
3643
type SubagentAnnounceOutputDeps = {
3744
callGateway: typeof callGateway;
3845
getRuntimeConfig: typeof getRuntimeConfig;
@@ -60,6 +67,7 @@ function isFastTestMode() {
6067
type SubagentOutputSnapshot = {
6168
latestAssistantText?: string;
6269
latestSilentText?: string;
70+
latestToolCallCount?: number;
6371
waitingForContinuation?: boolean;
6472
};
6573

@@ -121,6 +129,25 @@ function extractSubagentAssistantText(message: unknown): string {
121129
return extractAssistantText(message) ?? "";
122130
}
123131

132+
function countAssistantToolCalls(message: unknown): number {
133+
if (!message || typeof message !== "object") {
134+
return 0;
135+
}
136+
const content = (message as { content?: unknown }).content;
137+
const contentToolCalls = Array.isArray(content)
138+
? content.filter(
139+
(block) =>
140+
block &&
141+
typeof block === "object" &&
142+
ASSISTANT_TOOL_CALL_BLOCK_TYPES.has((block as { type?: string }).type ?? ""),
143+
).length
144+
: 0;
145+
const toolCalls =
146+
(message as { toolCalls?: unknown; tool_calls?: unknown }).toolCalls ??
147+
(message as { tool_calls?: unknown }).tool_calls;
148+
return contentToolCalls + (Array.isArray(toolCalls) ? toolCalls.length : 0);
149+
}
150+
124151
function summarizeSubagentOutputHistory(messages: Array<unknown>): SubagentOutputSnapshot {
125152
const snapshot: SubagentOutputSnapshot = {};
126153
let previousAssistantCalledYield = false;
@@ -141,6 +168,7 @@ function summarizeSubagentOutputHistory(messages: Array<unknown>): SubagentOutpu
141168
// when the current run fails or completes without visible output.
142169
snapshot.latestAssistantText = undefined;
143170
snapshot.latestSilentText = undefined;
171+
snapshot.latestToolCallCount = undefined;
144172
snapshot.waitingForContinuation = false;
145173
previousAssistantCalledYield = false;
146174
continue;
@@ -155,6 +183,8 @@ function summarizeSubagentOutputHistory(messages: Array<unknown>): SubagentOutpu
155183
}
156184
const text = extractSubagentAssistantText(message).trim();
157185
if (!text) {
186+
snapshot.latestToolCallCount =
187+
(snapshot.latestToolCallCount ?? 0) + countAssistantToolCalls(message);
158188
snapshot.waitingForContinuation = false;
159189
previousAssistantCalledYield = false;
160190
continue;
@@ -184,7 +214,10 @@ function summarizeSubagentOutputHistory(messages: Array<unknown>): SubagentOutpu
184214
return snapshot;
185215
}
186216

187-
function selectSubagentOutputText(snapshot: SubagentOutputSnapshot): string | undefined {
217+
function selectSubagentOutputText(
218+
snapshot: SubagentOutputSnapshot,
219+
outcome?: SubagentRunOutcome,
220+
): string | undefined {
188221
if (snapshot.waitingForContinuation) {
189222
return undefined;
190223
}
@@ -194,12 +227,21 @@ function selectSubagentOutputText(snapshot: SubagentOutputSnapshot): string | un
194227
if (snapshot.latestAssistantText) {
195228
return snapshot.latestAssistantText;
196229
}
230+
// Tool activity is partial-progress evidence only for a timed-out run. It is
231+
// not authoritative completion output when producer terminal facts are absent.
232+
if (
233+
outcome?.status === "timeout" &&
234+
snapshot.latestToolCallCount &&
235+
snapshot.latestToolCallCount > 0
236+
) {
237+
return `${snapshot.latestToolCallCount} tool call(s) made without visible output.`;
238+
}
197239
return undefined;
198240
}
199241

200242
export async function readSubagentOutput(
201243
sessionKey: string,
202-
_outcome?: SubagentRunOutcome,
244+
outcome?: SubagentRunOutcome,
203245
options?: { sessionTarget?: SessionTranscriptRuntimeTarget },
204246
): Promise<string | undefined> {
205247
let messages: unknown[] | undefined;
@@ -223,7 +265,7 @@ export async function readSubagentOutput(
223265
: undefined;
224266
const sourceMessages = messages ?? (Array.isArray(history?.messages) ? history.messages : []);
225267
const snapshot = summarizeSubagentOutputHistory(sourceMessages);
226-
const selected = selectSubagentOutputText(snapshot);
268+
const selected = selectSubagentOutputText(snapshot, outcome);
227269
if (selected?.trim()) {
228270
return selected;
229271
}
@@ -244,6 +286,20 @@ export async function readLatestSubagentOutputWithRetry(params: {
244286
});
245287
}
246288

289+
export async function readSubagentTimeoutProgress(
290+
sessionKey: string,
291+
maxWaitMs: number,
292+
outcome: SubagentRunOutcome,
293+
): Promise<string | undefined> {
294+
const initial = await readSubagentOutput(sessionKey, outcome);
295+
const progress = initial?.trim()
296+
? initial
297+
: await readLatestSubagentOutputWithRetry({ sessionKey, maxWaitMs, outcome });
298+
return progress && !isAnnounceSkip(progress) && !isSilentReplyText(progress, SILENT_REPLY_TOKEN)
299+
? progress
300+
: undefined;
301+
}
302+
247303
export async function waitForSubagentRunOutcome(
248304
runId: string,
249305
timeoutMs: number,

0 commit comments

Comments
 (0)