Skip to content

Commit 8853217

Browse files
authored
fix(gateway): cancel run-bound approvals on abort and expose approval-park lifecycle (#110993)
* fix: harden approval abort lifecycle * fix(gateway): recheck abort before committing detached exec authorization * fix(gateway): recheck abort after inline exec authorization commit * fix(gateway): propagate run-abort cancellation on the inline approval path * fix(ci): refresh approval protocol bindings
1 parent 3d03b60 commit 8853217

25 files changed

Lines changed: 692 additions & 15 deletions

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12571,6 +12571,9 @@ public struct ExecApprovalRequestParams: Codable, Sendable {
1257112571
public let agentid: AnyCodable?
1257212572
public let resolvedpath: AnyCodable?
1257312573
public let sessionkey: AnyCodable?
12574+
public let sessionid: AnyCodable?
12575+
public let runid: AnyCodable?
12576+
public let toolcallid: AnyCodable?
1257412577
public let turnsourcechannel: AnyCodable?
1257512578
public let turnsourceto: AnyCodable?
1257612579
public let turnsourceaccountid: AnyCodable?
@@ -12598,6 +12601,9 @@ public struct ExecApprovalRequestParams: Codable, Sendable {
1259812601
agentid: AnyCodable? = nil,
1259912602
resolvedpath: AnyCodable? = nil,
1260012603
sessionkey: AnyCodable? = nil,
12604+
sessionid: AnyCodable? = nil,
12605+
runid: AnyCodable? = nil,
12606+
toolcallid: AnyCodable? = nil,
1260112607
turnsourcechannel: AnyCodable? = nil,
1260212608
turnsourceto: AnyCodable? = nil,
1260312609
turnsourceaccountid: AnyCodable? = nil,
@@ -12624,6 +12630,9 @@ public struct ExecApprovalRequestParams: Codable, Sendable {
1262412630
self.agentid = agentid
1262512631
self.resolvedpath = resolvedpath
1262612632
self.sessionkey = sessionkey
12633+
self.sessionid = sessionid
12634+
self.runid = runid
12635+
self.toolcallid = toolcallid
1262712636
self.turnsourcechannel = turnsourcechannel
1262812637
self.turnsourceto = turnsourceto
1262912638
self.turnsourceaccountid = turnsourceaccountid
@@ -12652,6 +12661,9 @@ public struct ExecApprovalRequestParams: Codable, Sendable {
1265212661
case agentid = "agentId"
1265312662
case resolvedpath = "resolvedPath"
1265412663
case sessionkey = "sessionKey"
12664+
case sessionid = "sessionId"
12665+
case runid = "runId"
12666+
case toolcallid = "toolCallId"
1265512667
case turnsourcechannel = "turnSourceChannel"
1265612668
case turnsourceto = "turnSourceTo"
1265712669
case turnsourceaccountid = "turnSourceAccountId"

‎packages/gateway-protocol/src/schema/exec-approvals.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,9 @@ export const ExecApprovalRequestParamsSchema = closedObject({
288288
agentId: Type.Optional(Type.Union([Type.String(), Type.Null()])),
289289
resolvedPath: Type.Optional(Type.Union([Type.String(), Type.Null()])),
290290
sessionKey: Type.Optional(Type.Union([Type.String(), Type.Null()])),
291+
sessionId: Type.Optional(Type.Union([Type.String(), Type.Null()])),
292+
runId: Type.Optional(Type.Union([Type.String(), Type.Null()])),
293+
toolCallId: Type.Optional(Type.Union([Type.String(), Type.Null()])),
291294
turnSourceChannel: Type.Optional(Type.Union([Type.String(), Type.Null()])),
292295
turnSourceTo: Type.Optional(Type.Union([Type.String(), Type.Null()])),
293296
turnSourceAccountId: Type.Optional(Type.Union([Type.String(), Type.Null()])),

‎src/agents/agent-tools.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -745,6 +745,7 @@ function createOpenClawCodingToolsInternal(options?: OpenClawCodingToolsOptions)
745745
allowBackground,
746746
scopeKey,
747747
sessionKey: options?.sessionKey,
748+
runId: options?.runId,
748749
sessionId: options?.sessionId,
749750
sessionStore: options?.config?.session?.store,
750751
mainKey: options?.config?.session?.mainKey,

‎src/agents/bash-tools.exec-approval-request.test.ts‎

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ vi.mock("./tools/gateway.js", () => ({
3939

4040
let callGatewayTool: typeof import("./tools/gateway.js").callGatewayTool;
4141
let registerExecApprovalRequestForHostOrThrow: typeof import("./bash-tools.exec-approval-request.js").registerExecApprovalRequestForHostOrThrow;
42+
let resolveRegisteredExecApprovalDecision: typeof import("./bash-tools.exec-approval-request.js").resolveRegisteredExecApprovalDecision;
43+
let isExecApprovalRunAbortedError: typeof import("./bash-tools.exec-approval-request.js").isExecApprovalRunAbortedError;
4244

4345
const initialProcessPlatform = Object.getOwnPropertyDescriptor(process, "platform");
4446

@@ -59,6 +61,9 @@ function restoreProcessPlatformForTest(): void {
5961
type ApprovalRequestPayload = {
6062
approvalReviewerDeviceIds?: string[];
6163
commandSpans?: Array<{ startIndex: number; endIndex: number }>;
64+
sessionId?: string;
65+
runId?: string;
66+
toolCallId?: string;
6267
};
6368

6469
function requireApprovalRequestPayload(callIndex: number): ApprovalRequestPayload {
@@ -74,8 +79,11 @@ function requireApprovalRequestPayload(callIndex: number): ApprovalRequestPayloa
7479
describe("exec approval requests", () => {
7580
beforeAll(async () => {
7681
({ callGatewayTool } = await import("./tools/gateway.js"));
77-
({ registerExecApprovalRequestForHostOrThrow } =
78-
await import("./bash-tools.exec-approval-request.js"));
82+
({
83+
registerExecApprovalRequestForHostOrThrow,
84+
resolveRegisteredExecApprovalDecision,
85+
isExecApprovalRunAbortedError,
86+
} = await import("./bash-tools.exec-approval-request.js"));
7987
});
8088

8189
beforeEach(() => {
@@ -93,6 +101,47 @@ describe("exec approval requests", () => {
93101
expect(commandExplainerMock.importCount).toBe(0);
94102
});
95103

104+
it("binds approval registrations to their run and tool call", async () => {
105+
vi.mocked(callGatewayTool).mockResolvedValue({ id: "approval-id" });
106+
107+
await registerExecApprovalRequestForHostOrThrow({
108+
approvalId: "approval-id",
109+
command: "echo hi",
110+
workdir: "/tmp",
111+
host: "gateway",
112+
security: "allowlist",
113+
ask: "on-miss",
114+
sessionId: "session-1",
115+
runId: "run-1",
116+
toolCallId: "tool-1",
117+
});
118+
119+
expect(requireApprovalRequestPayload(0)).toMatchObject({
120+
sessionId: "session-1",
121+
runId: "run-1",
122+
toolCallId: "tool-1",
123+
});
124+
});
125+
126+
it("distinguishes run abort cancellation from unchanged timeout fallback", async () => {
127+
vi.mocked(callGatewayTool)
128+
.mockResolvedValueOnce({ decision: null, terminalReason: "timeout" })
129+
.mockResolvedValueOnce({ decision: null, terminalReason: "run-aborted" });
130+
131+
await expect(
132+
resolveRegisteredExecApprovalDecision({
133+
approvalId: "timeout-approval",
134+
preResolvedDecision: undefined,
135+
}),
136+
).resolves.toBeNull();
137+
await expect(
138+
resolveRegisteredExecApprovalDecision({
139+
approvalId: "aborted-approval",
140+
preResolvedDecision: undefined,
141+
}),
142+
).rejects.toSatisfy(isExecApprovalRunAbortedError);
143+
});
144+
96145
it("bounds missing registration expiries when the process clock is invalid", async () => {
97146
vi.mocked(callGatewayTool).mockResolvedValue({ id: "approval-id" });
98147
const dateNow = vi.spyOn(Date, "now").mockReturnValue(Number.NaN);

‎src/agents/bash-tools.exec-approval-request.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,9 @@ type RequestExecApprovalDecisionParams = {
5656
agentId?: string;
5757
resolvedPath?: string;
5858
sessionKey?: string;
59+
sessionId?: string;
60+
runId?: string;
61+
toolCallId?: string;
5962
turnSourceChannel?: string;
6063
turnSourceTo?: string;
6164
turnSourceAccountId?: string;
@@ -92,6 +95,9 @@ function buildExecApprovalRequestToolParams(
9295
agentId: params.agentId,
9396
resolvedPath: params.resolvedPath,
9497
sessionKey: params.sessionKey,
98+
sessionId: params.sessionId,
99+
runId: params.runId,
100+
toolCallId: params.toolCallId,
95101
turnSourceChannel: params.turnSourceChannel,
96102
turnSourceTo: params.turnSourceTo,
97103
turnSourceAccountId: params.turnSourceAccountId,
@@ -134,6 +140,17 @@ export type ExecApprovalRegistration = {
134140
finalDecision?: string | null;
135141
};
136142

143+
class ExecApprovalRunAbortedError extends Error {
144+
constructor() {
145+
super("Exec approval cancelled because its run was aborted");
146+
this.name = "ExecApprovalRunAbortedError";
147+
}
148+
}
149+
150+
export function isExecApprovalRunAbortedError(error: unknown): boolean {
151+
return error instanceof ExecApprovalRunAbortedError;
152+
}
153+
137154
/** Registers a two-phase exec approval request with the gateway. */
138155
async function registerExecApprovalRequest(
139156
params: RequestExecApprovalDecisionParams,
@@ -170,6 +187,13 @@ export async function resolveRegisteredExecApprovalDecision(params: {
170187
{ timeoutMs: DEFAULT_APPROVAL_REQUEST_TIMEOUT_MS },
171188
{ id: params.approvalId },
172189
);
190+
if (
191+
decisionResult &&
192+
typeof decisionResult === "object" &&
193+
(decisionResult as { terminalReason?: unknown }).terminalReason === "run-aborted"
194+
) {
195+
throw new ExecApprovalRunAbortedError();
196+
}
173197
return parseDecision(decisionResult).value;
174198
} catch (err) {
175199
// Timeout/cleanup path: treat missing/expired as no decision so askFallback applies.
@@ -199,6 +223,9 @@ type HostExecApprovalParams = {
199223
agentId?: string;
200224
resolvedPath?: string;
201225
sessionKey?: string;
226+
sessionId?: string;
227+
runId?: string;
228+
toolCallId?: string;
202229
turnSourceChannel?: string;
203230
turnSourceTo?: string;
204231
turnSourceAccountId?: string;
@@ -310,6 +337,9 @@ async function buildHostApprovalDecisionParams(
310337
sessionKey: params.sessionKey,
311338
}),
312339
resolvedPath: params.resolvedPath,
340+
sessionId: params.sessionId,
341+
runId: params.runId,
342+
toolCallId: params.toolCallId,
313343
requireDeliveryRoute: params.requireDeliveryRoute,
314344
suppressDelivery: params.suppressDelivery,
315345
approvalReviewerDeviceIds: params.approvalReviewerDeviceIds,

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

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import fs from "node:fs";
88
import os from "node:os";
99
import path from "node:path";
1010
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi, type Mock } from "vitest";
11+
import { onAgentEvent } from "../infra/agent-events.js";
1112
import {
1213
onInternalDiagnosticEvent,
1314
resetDiagnosticEventsForTest,
@@ -158,6 +159,7 @@ const commitExecAuthorizationMock = vi.hoisted(() => vi.fn(async () => undefined
158159
const resolveApprovalDecisionOrUndefinedMock = vi.hoisted(() =>
159160
vi.fn(async (): Promise<string | null | undefined> => undefined),
160161
);
162+
const runAbortedApprovalError = vi.hoisted(() => new Error("run aborted"));
161163
const resolveExecHostApprovalContextMock = vi.hoisted(() =>
162164
vi.fn(
163165
(): MockExecHostApprovalContext => ({
@@ -215,6 +217,7 @@ vi.mock("./bash-tools.exec-approval-request.js", () => ({
215217
buildExecApprovalRequesterContext: vi.fn(() => ({})),
216218
buildExecApprovalTurnSourceContext: vi.fn(() => ({})),
217219
registerExecApprovalRequestForHostOrThrow: vi.fn(async () => undefined),
220+
isExecApprovalRunAbortedError: (error: unknown) => error === runAbortedApprovalError,
218221
}));
219222

220223
vi.mock("./bash-tools.exec-host-shared.js", () => ({
@@ -2050,6 +2053,42 @@ EOF`,
20502053
expect(sendExecApprovalFollowupResultMock).not.toHaveBeenCalled();
20512054
});
20522055

2056+
it.each([
2057+
{ decision: "allow-once", deniedReason: null },
2058+
{ decision: "deny", deniedReason: "user-denied" },
2059+
] as const)("emits inline approval park and clear events for $decision", async (testCase) => {
2060+
resolveApprovalDecisionOrUndefinedMock.mockResolvedValue(testCase.decision);
2061+
createExecApprovalDecisionStateMock.mockReturnValue({
2062+
baseDecision: { timedOut: false },
2063+
approvedByAsk: testCase.decision === "allow-once",
2064+
deniedReason: testCase.deniedReason,
2065+
});
2066+
const events: Array<Record<string, unknown>> = [];
2067+
const unsubscribe = onAgentEvent((event) => {
2068+
if (event.runId === "run-inline" && event.stream === "lifecycle") {
2069+
events.push(event.data);
2070+
}
2071+
});
2072+
2073+
try {
2074+
await runGatewayAllowlist({
2075+
command: "pwd",
2076+
turnSourceChannel: "webchat",
2077+
runId: "run-inline",
2078+
toolCallId: "tool-inline",
2079+
sessionKey: "agent:main:main",
2080+
sessionId: "session-inline",
2081+
});
2082+
} finally {
2083+
unsubscribe();
2084+
}
2085+
2086+
expect(events).toEqual([
2087+
{ phase: "waiting-approval", approvalId: "req-1", toolCallId: "tool-inline" },
2088+
{ phase: "approval-resolved", approvalId: "req-1", toolCallId: "tool-inline" },
2089+
]);
2090+
});
2091+
20532092
it.each([
20542093
["telegram"],
20552094
["slack"],
@@ -2281,6 +2320,63 @@ EOF`,
22812320
expect(runExecProcessMock).toHaveBeenCalledTimes(1);
22822321
});
22832322

2323+
it("drops detached execution and follow-up when the owning run is aborted", async () => {
2324+
resolveApprovalDecisionOrUndefinedMock.mockRejectedValue(runAbortedApprovalError);
2325+
buildExecApprovalFollowupTargetMock.mockImplementation((value) => value);
2326+
2327+
const result = await runGatewayAllowlist({
2328+
command: "find . -maxdepth 1",
2329+
turnSourceChannel: "feishu",
2330+
runId: "run-aborted",
2331+
toolCallId: "tool-aborted",
2332+
});
2333+
2334+
expect(result.pendingResult?.details.status).toBe("approval-pending");
2335+
await vi.waitFor(() => {
2336+
expect(resolveApprovalDecisionOrUndefinedMock).toHaveBeenCalledOnce();
2337+
});
2338+
expect(commitExecAuthorizationMock).not.toHaveBeenCalled();
2339+
expect(runExecProcessMock).not.toHaveBeenCalled();
2340+
expect(sendExecApprovalFollowupResultMock).not.toHaveBeenCalled();
2341+
});
2342+
2343+
it("drops an allowed detached execution when abort wins before consumption", async () => {
2344+
let resolveApproval: (decision: ExecApprovalDecision) => void = () => {};
2345+
resolveApprovalDecisionOrUndefinedMock.mockReturnValue(
2346+
new Promise<ExecApprovalDecision>((resolve) => {
2347+
resolveApproval = resolve;
2348+
}),
2349+
);
2350+
createExecApprovalDecisionStateMock.mockReturnValue({
2351+
baseDecision: { timedOut: false },
2352+
approvedByAsk: true,
2353+
deniedReason: null,
2354+
});
2355+
buildExecApprovalFollowupTargetMock.mockImplementation((value) => value);
2356+
const abortController = new AbortController();
2357+
2358+
const result = await runGatewayAllowlist({
2359+
command: "find . -maxdepth 1",
2360+
turnSourceChannel: "feishu",
2361+
runId: "run-aborted-after-allow",
2362+
toolCallId: "tool-aborted-after-allow",
2363+
signal: abortController.signal,
2364+
});
2365+
expect(result.pendingResult?.details.status).toBe("approval-pending");
2366+
await vi.waitFor(() => {
2367+
expect(resolveApprovalDecisionOrUndefinedMock).toHaveBeenCalledOnce();
2368+
});
2369+
2370+
abortController.abort();
2371+
resolveApproval("allow-once");
2372+
await vi.waitFor(() => {
2373+
expect(createExecApprovalDecisionStateMock).toHaveBeenCalledOnce();
2374+
});
2375+
expect(commitExecAuthorizationMock).not.toHaveBeenCalled();
2376+
expect(runExecProcessMock).not.toHaveBeenCalled();
2377+
expect(sendExecApprovalFollowupResultMock).not.toHaveBeenCalled();
2378+
});
2379+
22842380
it("keeps the fire-and-forget path for headless cron approval followups", async () => {
22852381
resolveApprovalDecisionOrUndefinedMock.mockResolvedValue("allow-once");
22862382
createExecApprovalDecisionStateMock.mockReturnValue({

0 commit comments

Comments
 (0)