Skip to content

Commit d2be70d

Browse files
authored
fix(agents): preserve exec outcomes across lifecycle races (#125532)
* fix(agents): preserve exec outcomes across lifecycle races Detached Gateway follow-up failures no longer escape after dispatch, and sandbox finalization cannot be falsely backgrounded. Related: #125529 * fix(agents): own detached approval failures * style(agents): format approval continuation
1 parent 79095b5 commit d2be70d

6 files changed

Lines changed: 220 additions & 42 deletions

‎src/agents/bash-tools.exec-host-gateway.test.ts‎

Lines changed: 111 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import crypto from "node:crypto";
77
import fs from "node:fs";
88
import os from "node:os";
99
import path from "node:path";
10+
import { setImmediate } from "node:timers/promises";
1011
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi, type Mock } from "vitest";
1112
import { onAgentEvent } from "../infra/agent-events.js";
1213
import {
@@ -395,6 +396,19 @@ function requireApprovalFollowupInput(
395396
return call[0];
396397
}
397398

399+
function captureProcessUnhandledRejections() {
400+
const reasons: unknown[] = [];
401+
const originalProcessEmit = process.emit.bind(process);
402+
const processEmit = vi.spyOn(process, "emit").mockImplementation((event, ...args) => {
403+
if (event === "unhandledRejection") {
404+
reasons.push(args[0]);
405+
return true;
406+
}
407+
return originalProcessEmit(event, ...args);
408+
});
409+
return { reasons, restore: () => processEmit.mockRestore() };
410+
}
411+
398412
function captureSecurityEvents(): {
399413
events: DiagnosticSecurityEvent[];
400414
stop: () => void;
@@ -522,11 +536,15 @@ describe("processGatewayAllowlist", () => {
522536
outcome: ExecApprovalFollowupOutcome;
523537
sessionId?: string;
524538
}) {
525-
resolveApprovalDecisionOrUndefinedMock.mockResolvedValue("allow-once");
526-
createExecApprovalDecisionStateMock.mockReturnValue({
527-
baseDecision: { timedOut: false },
528-
approvedByAsk: true,
529-
deniedReason: null,
539+
resolveExecApprovalWaitOutcomeMock.mockResolvedValueOnce({
540+
kind: "resolved",
541+
decision: "allow-once",
542+
state: {
543+
baseDecision: { timedOut: false },
544+
approvedByAsk: true,
545+
deniedReason: null,
546+
timeoutContext: undefined,
547+
},
530548
});
531549
runExecProcessMock.mockResolvedValue({
532550
session: { id: params.sessionId ?? "sess-1" },
@@ -2201,6 +2219,94 @@ EOF`,
22012219
expect(requireSentFollowupText(0)).toContain("done");
22022220
});
22032221

2222+
it("keeps a completed detached outcome terminal when agent follow-up registration fails", async () => {
2223+
const unhandledRejections = captureProcessUnhandledRejections();
2224+
const completedOutcome = {
2225+
status: "completed" as const,
2226+
exitCode: 0,
2227+
timedOut: false,
2228+
aggregated: "completed output",
2229+
};
2230+
const approvalFollowup = vi.fn<ExecApprovalFollowupFactory>(() => undefined);
2231+
mockApprovedDetachedExec({ outcome: completedOutcome });
2232+
sendExecApprovalFollowupResultMock.mockRejectedValueOnce(
2233+
new Error("synchronous runtime-handoff registration failure"),
2234+
);
2235+
2236+
try {
2237+
const result = await runGatewayAllowlist({
2238+
command: "side-effecting-command",
2239+
approvalFollowupMode: "agent",
2240+
approvalFollowup,
2241+
turnSourceChannel: "webchat",
2242+
});
2243+
2244+
expect(result.pendingResult?.details.status).toBe("approval-pending");
2245+
await vi.waitFor(() => expect(approvalFollowup).toHaveBeenCalledOnce());
2246+
await setImmediate();
2247+
2248+
expect(requireApprovalFollowupInput(approvalFollowup, 0).outcome).toEqual(completedOutcome);
2249+
expect(unhandledRejections.reasons).toEqual([]);
2250+
expect(sendExecApprovalFollowupResultMock).toHaveBeenCalledOnce();
2251+
expect(requireSentFollowupText(0)).toContain("completed output");
2252+
expect(requireSentFollowupText(0)).not.toContain("Exec denied");
2253+
} finally {
2254+
unhandledRejections.restore();
2255+
}
2256+
});
2257+
2258+
it.each([
2259+
{
2260+
name: "request failure",
2261+
outcome: { kind: "request-failed" as const },
2262+
firstFollowupReason: "approval-request-failed",
2263+
},
2264+
{
2265+
name: "denial",
2266+
outcome: {
2267+
kind: "resolved" as const,
2268+
decision: "deny",
2269+
state: {
2270+
baseDecision: { timedOut: false },
2271+
approvedByAsk: false,
2272+
deniedReason: "user-denied",
2273+
timeoutContext: undefined,
2274+
},
2275+
},
2276+
firstFollowupReason: "user-denied",
2277+
},
2278+
])("consumes rejected detached pre-dispatch $name and fallback follow-ups", async (scenario) => {
2279+
const unhandledRejections = captureProcessUnhandledRejections();
2280+
resolveExecApprovalWaitOutcomeMock.mockResolvedValueOnce(scenario.outcome);
2281+
buildExecApprovalFollowupTargetMock.mockImplementation((value) => value);
2282+
sendExecApprovalFollowupResultMock.mockRejectedValue(
2283+
new Error("pre-dispatch denial follow-up failed"),
2284+
);
2285+
2286+
try {
2287+
const result = await runGatewayAllowlist({
2288+
command: "side-effecting-command",
2289+
approvalFollowupMode: "agent",
2290+
turnSourceChannel: "webchat",
2291+
});
2292+
2293+
expect(result.pendingResult?.details.status).toBe("approval-pending");
2294+
await vi.waitFor(() => expect(sendExecApprovalFollowupResultMock).toHaveBeenCalledTimes(2));
2295+
await setImmediate();
2296+
2297+
expect(unhandledRejections.reasons).toEqual([]);
2298+
expect(requireSentFollowupText(0)).toBe(
2299+
`Exec denied (gateway id=req-1, ${scenario.firstFollowupReason}): side-effecting-command`,
2300+
);
2301+
expect(requireSentFollowupText(1)).toBe(
2302+
"Exec denied (gateway id=req-1, approval-request-failed): side-effecting-command",
2303+
);
2304+
expect(runExecProcessMock).not.toHaveBeenCalled();
2305+
} finally {
2306+
unhandledRejections.restore();
2307+
}
2308+
});
2309+
22042310
it("keeps multiline gateway approval follow-up output intact", async () => {
22052311
resolveExecHostApprovalContextMock.mockReturnValue({
22062312
approvals: { allowlist: [], file: { version: 1, agents: {} } },

‎src/agents/bash-tools.exec-host-gateway.ts‎

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1122,7 +1122,7 @@ export async function processGatewayAllowlist(
11221122
allowlistEval.segments[0]?.resolution ?? null,
11231123
params.workdir,
11241124
);
1125-
const resolveApprovalForExecution = async (onFailure: () => void) => {
1125+
const resolveApprovalForExecution = async (onFailure: () => void | Promise<void>) => {
11261126
const approvalOutcome = await resolveExecApprovalWaitOutcome({
11271127
approvalId,
11281128
preResolvedDecision,
@@ -1151,7 +1151,7 @@ export async function processGatewayAllowlist(
11511151
};
11521152
}
11531153
if (approvalOutcome.kind === "request-failed") {
1154-
onFailure();
1154+
await onFailure();
11551155
emitGatewayExecApprovalSecurityEvent({
11561156
action: "exec.approval.denied",
11571157
outcome: "error",
@@ -1318,21 +1318,18 @@ export async function processGatewayAllowlist(
13181318
`Exec denied (gateway id=${approvalId}, approval-state-write-failed): ${params.command}`,
13191319
);
13201320
};
1321-
1322-
void (async () => {
1323-
let approvalDecision: Awaited<ReturnType<typeof resolveApprovalForExecution>>;
1324-
try {
1325-
approvalDecision = await resolveApprovalForExecution(
1326-
() =>
1327-
void sendExecApprovalFollowupResult(
1328-
followupTarget,
1329-
`Exec denied (gateway id=${approvalId}, approval-request-failed): ${params.command}`,
1330-
),
1321+
const sendApprovalRequestFailedFollowup = async () => {
1322+
if (!params.signal?.aborted) {
1323+
await sendExecApprovalFollowupResult(
1324+
followupTarget,
1325+
`Exec denied (gateway id=${approvalId}, approval-request-failed): ${params.command}`,
13311326
);
1332-
} catch {
1333-
await denyApprovalStateWriteFailure();
1334-
return;
13351327
}
1328+
};
1329+
let gatewayInvocationStarted = false;
1330+
1331+
void (async () => {
1332+
const approvalDecision = await resolveApprovalForExecution(sendApprovalRequestFailedFollowup);
13361333
if (approvalDecision.requestFailed) {
13371334
return;
13381335
}
@@ -1395,6 +1392,7 @@ export async function processGatewayAllowlist(
13951392

13961393
let run: Awaited<ReturnType<typeof runExecProcess>>;
13971394
try {
1395+
gatewayInvocationStarted = true;
13981396
run = await runExecProcess({
13991397
command: params.command,
14001398
execCommand: approvalDecision.execCommandOverride,
@@ -1480,7 +1478,15 @@ export async function processGatewayAllowlist(
14801478
approvalFollowupText,
14811479
});
14821480
await sendExecApprovalFollowupResult(followupTarget, summary);
1483-
})();
1481+
})()
1482+
.catch(async (): Promise<void> => {
1483+
// Once dispatch starts, a delivery failure cannot mean execution was denied.
1484+
if (gatewayInvocationStarted || params.signal?.aborted) {
1485+
return;
1486+
}
1487+
await sendApprovalRequestFailedFollowup();
1488+
})
1489+
.catch(() => undefined);
14841490

14851491
return {
14861492
pendingResult: buildExecApprovalPendingToolResult({

‎src/agents/bash-tools.exec-host-node.test.ts‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -937,12 +937,13 @@ describe("executeNodeHostCommand", () => {
937937
}
938938
});
939939

940-
it("reports unexpected detached node approval failures without an unhandled rejection", async () => {
940+
it("consumes rejected detached node approval recovery and fallback follow-ups", async () => {
941941
const unhandledRejections = captureProcessUnhandledRejections();
942942

943943
try {
944-
resolveApprovalDecisionOrUndefinedMock.mockRejectedValueOnce(
945-
new Error("approval wait unavailable"),
944+
resolveExecApprovalWaitOutcomeMock.mockResolvedValueOnce({ kind: "request-failed" });
945+
sendExecApprovalFollowupResultMock.mockRejectedValue(
946+
new Error("approval failure follow-up unavailable"),
946947
);
947948
resolveExecHostApprovalContextMock.mockReturnValue({
948949
approvals: { allowlist: [], file: { version: 1, agents: {} } },
@@ -954,14 +955,19 @@ describe("executeNodeHostCommand", () => {
954955
const result = await executeNodeHostCommand(createNodeHostRequest({}));
955956

956957
expect(result.details?.status).toBe("approval-pending");
957-
await vi.waitFor(() => {
958-
expect(sendExecApprovalFollowupResultMock).toHaveBeenCalledWith(
959-
expect.objectContaining({ approvalId: "approval-1" }),
960-
"Exec denied (node=node-1 id=approval-1, approval-request-failed): bun ./script.ts",
961-
);
962-
});
958+
await vi.waitFor(() => expect(sendExecApprovalFollowupResultMock).toHaveBeenCalledTimes(2));
963959
await setImmediate();
964960
expect(unhandledRejections.reasons).toEqual([]);
961+
expect(sendExecApprovalFollowupResultMock).toHaveBeenNthCalledWith(
962+
1,
963+
expect.objectContaining({ approvalId: "approval-1" }),
964+
"Exec denied (node=node-1 id=approval-1, approval-request-failed): bun ./script.ts",
965+
);
966+
expect(sendExecApprovalFollowupResultMock).toHaveBeenNthCalledWith(
967+
2,
968+
expect.objectContaining({ approvalId: "approval-1" }),
969+
"Exec denied (node=node-1 id=approval-1, approval-request-failed): bun ./script.ts",
970+
);
965971
expect(
966972
callGatewayToolMock.mock.calls.some(
967973
([method, , params]) =>

‎src/agents/bash-tools.exec-host-node.ts‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -606,17 +606,19 @@ export async function executeNodeHostCommand(
606606
`Exec denied (node=${target.nodeId} id=${approvalId}, invoke-failed): ${params.command}`,
607607
);
608608
}
609-
})().catch(async (error: unknown): Promise<void> => {
610-
// Once dispatch starts, a delivery failure cannot mean execution was denied.
611-
if (
612-
nodeInvocationStarted ||
613-
params.signal?.aborted ||
614-
isExecApprovalRunAbortedError(error)
615-
) {
616-
return;
617-
}
618-
await sendApprovalRequestFailedFollowup();
619-
});
609+
})()
610+
.catch(async (error: unknown): Promise<void> => {
611+
// Once dispatch starts, a delivery failure cannot mean execution was denied.
612+
if (
613+
nodeInvocationStarted ||
614+
params.signal?.aborted ||
615+
isExecApprovalRunAbortedError(error)
616+
) {
617+
return;
618+
}
619+
await sendApprovalRequestFailedFollowup();
620+
})
621+
.catch(() => undefined);
620622

621623
return execHostShared.buildExecApprovalPendingToolResult({
622624
host: "node",

‎src/agents/bash-tools.exec-run.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -679,7 +679,7 @@ export function createExecTool(
679679
};
680680

681681
const onYieldNow = () => {
682-
if (yielded || toolAborted) {
682+
if (yielded || toolAborted || run.session.finalizing) {
683683
return;
684684
}
685685
if (settledOutcome) {

‎src/agents/bash-tools.exec-task-wiring.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import { createDeferred } from "../../test/helpers/promise.js";
23

34
const taskTracking = vi.hoisted(() => ({
45
createBackgroundExecTask: vi.fn(),
@@ -9,6 +10,7 @@ vi.mock("./bash-tools.exec-task-tracking.js", () => taskTracking);
910

1011
import { getFinishedSession } from "./bash-process-registry.js";
1112
import { createExecTool } from "./bash-tools.exec-run.js";
13+
import type { BashSandboxConfig } from "./bash-tools.shared.js";
1214

1315
describe("exec background task wiring", () => {
1416
beforeEach(() => {
@@ -38,6 +40,62 @@ describe("exec background task wiring", () => {
3840
});
3941
});
4042

43+
it("does not background a terminal process while sandbox finalization is pending", async () => {
44+
const yieldMs = 250;
45+
const finalizationStarted = createDeferred();
46+
const finalization = createDeferred();
47+
const finalizeExec = vi.fn<NonNullable<BashSandboxConfig["finalizeExec"]>>(async () => {
48+
finalizationStarted.resolve();
49+
await finalization.promise;
50+
});
51+
vi.useFakeTimers();
52+
53+
try {
54+
const tool = createExecTool({
55+
host: "sandbox",
56+
security: "full",
57+
ask: "off",
58+
allowBackground: true,
59+
sessionKey: "agent:main:main",
60+
sandbox: {
61+
containerName: "sandbox",
62+
workspaceDir: process.cwd(),
63+
containerWorkdir: process.cwd(),
64+
buildExecSpec: async () => ({
65+
argv: [process.execPath, "-e", ""],
66+
env: process.env,
67+
stdinMode: "pipe-closed",
68+
finalizeToken: "sandbox-token",
69+
}),
70+
finalizeExec,
71+
},
72+
});
73+
74+
const execution = tool.execute("terminal-during-finalize", {
75+
command: "sandbox-command",
76+
yieldMs,
77+
});
78+
const executionSettled = vi.fn();
79+
void execution.then(executionSettled, executionSettled);
80+
await finalizationStarted.promise;
81+
await vi.advanceTimersByTimeAsync(yieldMs + 1);
82+
83+
expect(executionSettled).not.toHaveBeenCalled();
84+
expect(taskTracking.createBackgroundExecTask).not.toHaveBeenCalled();
85+
finalization.resolve();
86+
const result = await execution;
87+
88+
expect(result.details.status).toBe("completed");
89+
expect(taskTracking.finalizeBackgroundExecTask).toHaveBeenCalledWith({
90+
handle: null,
91+
outcome: expect.objectContaining({ status: "completed" }),
92+
});
93+
} finally {
94+
finalization.resolve();
95+
vi.useRealTimers();
96+
}
97+
});
98+
4199
it.each([
42100
{
43101
label: "foreground execution",

0 commit comments

Comments
 (0)