Skip to content

Commit b85c6e3

Browse files
authored
fix(agents): interactive process prompts stall during timed polls (#130081)
* fix(agents): return pending process output without waiting * refactor(agents): retire obsolete process length exemption
1 parent 1e6844b commit b85c6e3

4 files changed

Lines changed: 114 additions & 71 deletions

File tree

‎config/max-lines-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,6 @@ src/agents/bash-tools.exec-host-gateway.ts
319319
src/agents/bash-tools.exec-host-node.test.ts
320320
src/agents/bash-tools.exec-runtime.ts
321321
src/agents/bash-tools.exec.approval-id.test.ts
322-
src/agents/bash-tools.process.ts
323322
src/agents/btw.test.ts
324323
src/agents/btw.ts
325324
src/agents/cli-runner.reliability.test.ts

‎src/agents/bash-tools.process.e2e.test.ts‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,19 @@ test.skipIf(process.platform === "win32").each([
111111

112112
const outcome = await run.promise;
113113
const notification = peekSystemEventEntries(scopeKey)[0]?.text;
114-
const poll = await pendingPoll;
114+
let poll = await pendingPoll;
115+
if ((poll.details as { status?: string }).status === "running") {
116+
expect(poll.details).toMatchObject({
117+
status: "running",
118+
sessionId: run.session.id,
119+
aggregated: "REAL_CHILD_OUTPUT",
120+
});
121+
expect(textContent(poll)).toContain("REAL_CHILD_OUTPUT");
122+
poll = await processTool.execute(`process-terminal-final-poll-${name}`, {
123+
action: "poll",
124+
sessionId: run.session.id,
125+
});
126+
}
115127
const details = poll.details as { status?: string; exitCode?: number };
116128

117129
expect(outcome.status).toBe(expectedStatus);
@@ -317,11 +329,11 @@ test.skipIf(process.platform === "win32")(
317329
)
318330
.toContain("READY");
319331

320-
const readyPoll = await processTool.execute("process-control-ready-poll", {
321-
action: "poll",
322-
sessionId,
323-
timeout: 1_000,
324-
});
332+
const readyPoll = await processTool.execute(
333+
"process-control-ready-poll",
334+
{ action: "poll", sessionId, timeout: 30_000 },
335+
AbortSignal.timeout(1_000),
336+
);
325337
expect(readyPoll.details).toMatchObject({
326338
status: "running",
327339
sessionId,

‎src/agents/bash-tools.process.poll-timeout.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,81 @@ test("process poll waits for completion when timeout is provided", async () => {
112112
});
113113
});
114114

115+
test.each([
116+
{ name: "buffered stdout", stream: "stdout", arrivesDuringWait: false, dropped: false },
117+
{ name: "buffered stderr", stream: "stderr", arrivesDuringWait: false, dropped: false },
118+
{ name: "new stdout", stream: "stdout", arrivesDuringWait: true, dropped: false },
119+
{ name: "new stderr", stream: "stderr", arrivesDuringWait: true, dropped: false },
120+
{ name: "buffered capped output", stream: "stdout", arrivesDuringWait: false, dropped: true },
121+
] as const)(
122+
"process poll returns $name before the requested wait expires",
123+
async ({ name, stream, arrivesDuringWait, dropped }) => {
124+
vi.useFakeTimers();
125+
const sessionId = `sess-prompt-${name.replaceAll(" ", "-")}`;
126+
const { processTool, session } = createProcessSessionHarness(sessionId);
127+
const controller = new AbortController();
128+
const appendPendingOutput = () => {
129+
if (dropped) {
130+
appendOversizedPendingOutput(session);
131+
} else {
132+
appendOutput(session, stream, "interactive prompt\n");
133+
}
134+
};
135+
if (arrivesDuringWait) {
136+
setTimeout(appendPendingOutput, 10);
137+
} else {
138+
appendPendingOutput();
139+
}
140+
141+
let settled = false;
142+
const observedPoll = pollSession(
143+
processTool,
144+
"toolcall-prompt",
145+
sessionId,
146+
30_000,
147+
controller.signal,
148+
).then(
149+
(result) => {
150+
settled = true;
151+
return result;
152+
},
153+
() => undefined,
154+
);
155+
156+
try {
157+
await vi.advanceTimersByTimeAsync(arrivesDuringWait ? 250 : 0);
158+
expect(settled).toBe(true);
159+
160+
const poll = await observedPoll;
161+
expect(poll?.details).toMatchObject({ status: "running", sessionId });
162+
expect(poll?.content[0]).toMatchObject({
163+
type: "text",
164+
text: expect.stringContaining(
165+
dropped ? "earlier output is omitted from this poll" : "interactive prompt",
166+
),
167+
});
168+
expect(session.pendingOutput).toHaveLength(0);
169+
} finally {
170+
controller.abort();
171+
await observedPoll;
172+
vi.useRealTimers();
173+
}
174+
},
175+
);
176+
177+
test("process poll rejects an already-aborted signal without consuming buffered output", async () => {
178+
const sessionId = "sess-prompt-already-aborted";
179+
const { processTool, session } = createProcessSessionHarness(sessionId);
180+
appendOutput(session, "stdout", "interactive prompt\n");
181+
const controller = new AbortController();
182+
controller.abort();
183+
184+
await expect(
185+
pollSession(processTool, "toolcall-prompt-aborted", sessionId, 30_000, controller.signal),
186+
).rejects.toMatchObject({ name: "AbortError" });
187+
expect(session.pendingOutput).toEqual([{ stream: "stdout", text: "interactive prompt\n" }]);
188+
});
189+
115190
test("waiting poll returns only output appended since the previous poll", async () => {
116191
vi.useFakeTimers();
117192
try {

‎src/agents/bash-tools.process.ts‎

Lines changed: 21 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -380,46 +380,38 @@ export function createProcessTool(
380380
}
381381

382382
if (!params.sessionId) {
383-
return {
384-
content: [{ type: "text", text: "sessionId is required for this action." }],
385-
details: { status: "failed" },
386-
};
383+
return failText("sessionId is required for this action.");
387384
}
388385

389386
const session = getSession(params.sessionId);
390387
const finished = getFinishedSession(params.sessionId);
391388
const scopedSession = isInScope(session) ? session : undefined;
392389
const scopedFinished = isInScope(finished) ? finished : undefined;
393390

394-
const failedResult = (text: string): AgentToolResult<unknown> => ({
395-
content: [{ type: "text", text }],
396-
details: { status: "failed" },
397-
});
398-
399391
const resolveBackgroundedWritableStdin = () => {
400392
if (!scopedSession) {
401393
return {
402394
ok: false as const,
403-
result: failedResult(`No active session found for ${params.sessionId}`),
395+
result: failText(`No active session found for ${params.sessionId}`),
404396
};
405397
}
406398
if (!scopedSession.backgrounded) {
407399
return {
408400
ok: false as const,
409-
result: failedResult(`Session ${params.sessionId} is not backgrounded.`),
401+
result: failText(`Session ${params.sessionId} is not backgrounded.`),
410402
};
411403
}
412404
if (scopedSession.finalizing) {
413405
return {
414406
ok: false as const,
415-
result: failedResult(`Session ${params.sessionId} is finalizing.`),
407+
result: failText(`Session ${params.sessionId} is finalizing.`),
416408
};
417409
}
418410
const stdin = resolveSessionStdin(scopedSession);
419411
if (!isWritableStdin(stdin)) {
420412
return {
421413
ok: false as const,
422-
result: failedResult(`Session ${params.sessionId} stdin is not writable.`),
414+
result: failText(`Session ${params.sessionId} stdin is not writable.`),
423415
};
424416
}
425417
return { ok: true as const, session: scopedSession, stdin };
@@ -451,8 +443,17 @@ export function createProcessTool(
451443
}
452444
const pollWaitMs = resolvePollWaitMs(params.timeout);
453445
if (pollWaitMs > 0 && !scopedSession.exited) {
446+
if (signal?.aborted) {
447+
throw createAbortError(signal.reason);
448+
}
454449
const deadline = Date.now() + pollWaitMs;
455-
while (!scopedSession.exited && Date.now() < deadline) {
450+
// Interactive children cannot progress until their pending prompt reaches the model.
451+
while (
452+
!scopedSession.exited &&
453+
scopedSession.pendingOutput.length === 0 &&
454+
!scopedSession.pendingOutputDropped &&
455+
Date.now() < deadline
456+
) {
456457
await sleepPollInterval(Math.max(0, Math.min(250, deadline - Date.now())), signal);
457458
}
458459
}
@@ -501,15 +502,7 @@ export function createProcessTool(
501502
case "log": {
502503
if (scopedSession) {
503504
if (!scopedSession.backgrounded) {
504-
return {
505-
content: [
506-
{
507-
type: "text",
508-
text: `Session ${params.sessionId} is not backgrounded.`,
509-
},
510-
],
511-
details: { status: "failed" },
512-
};
505+
return failText(`Session ${params.sessionId} is not backgrounded.`);
513506
}
514507
const window = resolveLogSliceWindow(params.offset, params.limit);
515508
const { slice, totalLines, totalChars } = sliceLogLines(
@@ -570,15 +563,7 @@ export function createProcessTool(
570563
},
571564
};
572565
}
573-
return {
574-
content: [
575-
{
576-
type: "text",
577-
text: `No session found for ${params.sessionId}`,
578-
},
579-
],
580-
details: { status: "failed" },
581-
};
566+
return failText(`No session found for ${params.sessionId}`);
582567
}
583568

584569
case "write": {
@@ -632,15 +617,7 @@ export function createProcessTool(
632617
}
633618
const payload = encodePaste(params.text ?? "", params.bracketed !== false);
634619
if (!payload) {
635-
return {
636-
content: [
637-
{
638-
type: "text",
639-
text: "No paste text provided.",
640-
},
641-
],
642-
details: { status: "failed" },
643-
};
620+
return failText("No paste text provided.");
644621
}
645622
await writeProcessStdin(resolved.stdin, payload);
646623
return runningSessionResult(
@@ -690,15 +667,7 @@ export function createProcessTool(
690667
details: { status: "completed" },
691668
};
692669
}
693-
return {
694-
content: [
695-
{
696-
type: "text",
697-
text: `No finished session found for ${params.sessionId}`,
698-
},
699-
],
700-
details: { status: "failed" },
701-
};
670+
return failText(`No finished session found for ${params.sessionId}`);
702671
}
703672

704673
case "remove": {
@@ -741,26 +710,14 @@ export function createProcessTool(
741710
details: { status: "completed" },
742711
};
743712
}
744-
return {
745-
content: [
746-
{
747-
type: "text",
748-
text: `No session found for ${params.sessionId}`,
749-
},
750-
],
751-
details: { status: "failed" },
752-
};
713+
return failText(`No session found for ${params.sessionId}`);
753714
}
754715
}
755716

756-
return {
757-
content: [{ type: "text", text: `Unknown action ${params.action as string}` }],
758-
details: { status: "failed" },
759-
};
717+
return failText(`Unknown action ${params.action as string}`);
760718
},
761719
};
762720
}
763721

764722
/** Shared process-control tool instance used by the default Bash tool barrel. */
765723
export const processTool = createProcessTool();
766-
/* oxlint-disable max-lines -- TODO: split this grandfathered oversized file. */

0 commit comments

Comments
 (0)