Skip to content

Commit 45a5757

Browse files
authored
fix(gateway): publish approval timeout expiry to reviewer surfaces (#123950)
* fix(gateway): publish approval timeout expiry to reviewer surfaces Timer-driven timeout expiry was the only terminal approval transition never published: forceDeny settles the durable row and local waiter, but no exec/plugin.approval.resolved event fires, so every reviewer surface prunes expired approvals on its own clock. With operator clock skew the web card stays actionable after the gateway already denied (clicking Allow then silently vanishes via the stale-conflict path), or actionable approvals are pruned early. Add an onExpired manager hook and route it through the existing pending-publication queue used by run-abort/authority-close, so timeout publishes exactly like a resolve. * test(gateway): move timeout-expiry publication coverage to a focused file Main's growth pushed exec-approval-manager.test.ts past the counted max-lines cap once the onExpired test landed on top; the focused sibling file keeps the regression without a suppression.
1 parent d6e6d67 commit 45a5757

4 files changed

Lines changed: 147 additions & 6 deletions

File tree

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// Focused coverage for timer-driven approval expiry publication; the main
2+
// exec-approval-manager suite sits at the max-lines cap.
3+
import fs from "node:fs";
4+
import os from "node:os";
5+
import path from "node:path";
6+
import { afterEach, describe, expect, it, vi } from "vitest";
7+
import type { ExecApprovalRequestPayload } from "../infra/exec-approvals.js";
8+
import { closeOpenClawStateDatabase } from "../state/openclaw-state-db.js";
9+
import { ExecApprovalManager } from "./exec-approval-manager.js";
10+
11+
type TimeoutCallback = Parameters<typeof setTimeout>[0];
12+
type MockTimerHandle = ReturnType<typeof setTimeout> & {
13+
unref: ReturnType<typeof vi.fn>;
14+
};
15+
16+
describe("ExecApprovalManager timeout expiry publication", () => {
17+
const tempDirs: string[] = [];
18+
19+
afterEach(() => {
20+
vi.restoreAllMocks();
21+
closeOpenClawStateDatabase();
22+
for (const dir of tempDirs.splice(0)) {
23+
fs.rmSync(dir, { recursive: true, force: true });
24+
}
25+
});
26+
27+
function installTimerMocks() {
28+
const timers: Array<{
29+
callback: TimeoutCallback;
30+
delay: number | undefined;
31+
handle: MockTimerHandle;
32+
}> = [];
33+
vi.spyOn(globalThis, "setTimeout").mockImplementation(((
34+
callback: TimeoutCallback,
35+
delay?: number,
36+
) => {
37+
const handle = { unref: vi.fn() } as unknown as MockTimerHandle;
38+
timers.push({ callback, delay, handle });
39+
return handle;
40+
}) as unknown as typeof setTimeout);
41+
vi.spyOn(globalThis, "clearTimeout").mockImplementation(
42+
(() => undefined) as typeof clearTimeout,
43+
);
44+
return timers;
45+
}
46+
47+
it("publishes timer-driven timeout expiry through onExpired", async () => {
48+
const timers = installTimerMocks();
49+
vi.spyOn(Date, "now").mockReturnValue(1_000);
50+
const expirations: Array<{ recordId: string; status: string; requestCommand?: string }> = [];
51+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-approval-expired-"));
52+
tempDirs.push(dir);
53+
const manager = new ExecApprovalManager<ExecApprovalRequestPayload>({
54+
approvalKind: "exec",
55+
persistence: {
56+
runtimeEpoch: "runtime-a",
57+
databaseOptions: { path: path.join(dir, "s.sqlite") },
58+
},
59+
resolveAllowedDecisions: () => ["allow-once", "deny"],
60+
onExpired: (record, liveRecord) =>
61+
expirations.push({
62+
recordId: record.id,
63+
status: record.status,
64+
requestCommand: liveRecord.request.command,
65+
}),
66+
});
67+
const record = manager.create({ command: "echo expired" }, 60_000, "approval-on-expired");
68+
const decisionPromise = manager.register(record, 60_000);
69+
vi.mocked(Date.now).mockReturnValue(record.expiresAtMs);
70+
71+
const timer = timers[0];
72+
if (!timer || typeof timer.callback !== "function") {
73+
throw new Error("expected timer callback");
74+
}
75+
timer.callback();
76+
77+
await expect(decisionPromise).resolves.toBeNull();
78+
// The gateway clock owns expiry: reviewer surfaces get the terminal fact
79+
// (with the live request for the event payload) instead of inferring it.
80+
expect(expirations).toEqual([
81+
{ recordId: record.id, status: "expired", requestCommand: "echo expired" },
82+
]);
83+
});
84+
});

‎src/gateway/exec-approval-manager.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,11 @@ type ExecApprovalManagerOptions<TPayload> = {
128128
context: { approvalId: string; approvalKind: OperatorApprovalKind; operation: "expire" },
129129
) => void;
130130
onLifecycle?: (event: OperatorApprovalLifecycleEvent) => void;
131+
/** Timer-driven timeout expiry. The gateway owns the approval clock, so this
132+
* is the only place reviewer surfaces can learn an approval expired without
133+
* trusting their own (skewed) clocks; resolve/authority-close paths publish
134+
* through their own callers. */
135+
onExpired?: (record: OperatorApprovalRecord, liveRecord: ExecApprovalRecord<TPayload>) => void;
131136
validateAgentRuntimeDelegatedAuthority?: (authority: AgentRuntimeDelegatedAuthority) => boolean;
132137
};
133138

@@ -898,7 +903,15 @@ export class ExecApprovalManager<TPayload = ExecApprovalRequestPayload> {
898903
this.scheduleExpiryTimer(entry);
899904
return false;
900905
}
901-
return result.outcome === "denied" || result.outcome === "expired";
906+
const expired = result.outcome === "denied" || result.outcome === "expired";
907+
if (expired && "record" in result && result.liveRecord) {
908+
try {
909+
this.options.onExpired?.(result.record, result.liveRecord);
910+
} catch (error) {
911+
this.reportError(error, { approvalId: recordId, operation: "expire" });
912+
}
913+
}
914+
return expired;
902915
}
903916

904917
private resolveLocal(

‎src/gateway/server-aux-handlers.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,44 @@ describe("gateway aux handlers", () => {
325325
gatewayAux.unregisterApprovalAuthorityObserver();
326326
});
327327

328+
it("publishes exec.approval.resolved when the gateway timeout expires an approval", async () => {
329+
vi.useFakeTimers();
330+
try {
331+
const gatewayAux = createSecretsReloadHarness({
332+
activateRuntimeSecrets: mockResolvedSecrets(asConfig({})),
333+
});
334+
const broadcast = vi.fn();
335+
const publishResolved = vi.fn();
336+
gatewayAux.bindApprovalPublicationContext({
337+
broadcast,
338+
broadcastToConnIds: vi.fn(),
339+
approvalEvents: { publishResolved },
340+
logGateway: { error: vi.fn() },
341+
} as never);
342+
const record = gatewayAux.execApprovalManager.create(
343+
{ command: "echo expires" },
344+
1_000,
345+
"exec-timeout-publish",
346+
);
347+
const decision = gatewayAux.execApprovalManager.register(record, 1_000);
348+
349+
await vi.advanceTimersByTimeAsync(2_000);
350+
351+
await expect(decision).resolves.toBeNull();
352+
// The gateway clock owns expiry: reviewer surfaces must receive the
353+
// terminal event instead of pruning on their own (skewed) clocks.
354+
await vi.waitFor(() => expect(publishResolved).toHaveBeenCalledTimes(1));
355+
expect(broadcast).toHaveBeenCalledWith(
356+
"exec.approval.resolved",
357+
expect.objectContaining({ id: "exec-timeout-publish", decision: "deny" }),
358+
expect.anything(),
359+
);
360+
gatewayAux.unregisterApprovalAuthorityObserver();
361+
} finally {
362+
vi.useRealTimers();
363+
}
364+
});
365+
328366
it("settles and publishes both approval kinds from the production worker-claim observer", async () => {
329367
const root = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), "openclaw-aux-worker-"));
330368
closeOpenClawStateDatabaseForTest();

‎src/gateway/server-aux-handlers.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,11 +157,17 @@ export function createGatewayAuxHandlers(params: {
157157
resolveAudienceSessionKeys: resolveApprovalSessionAudienceWithFallback,
158158
resolveAllowedDecisions,
159159
onLifecycle: params.onApprovalLifecycle,
160-
...(params.validateAgentRuntimeDelegatedAuthority
161-
? {
162-
validateAgentRuntimeDelegatedAuthority: params.validateAgentRuntimeDelegatedAuthority,
163-
}
164-
: {}),
160+
// Timeout expiry is gateway-clock truth: publish the terminal like a
161+
// resolve so reviewer surfaces need not infer it from their own clocks.
162+
// system-agent approvals have no forwarder/push route to notify.
163+
onExpired: (record, liveRecord) => {
164+
if (approvalKind === "system-agent") {
165+
return;
166+
}
167+
const publication = { kind: approvalKind, record, liveRecord };
168+
publishAuthorityClosure(publication as PendingAuthorityPublication);
169+
},
170+
validateAgentRuntimeDelegatedAuthority: params.validateAgentRuntimeDelegatedAuthority,
165171
onError: (error, context) =>
166172
params.log.error?.(
167173
`${context.approvalKind} approval ${context.operation} failed for ${context.approvalId}: ${String(error)}`,

0 commit comments

Comments
 (0)