Skip to content

Commit bba7e30

Browse files
authored
fix(browser): preserve nested timeouts and cancellation across node actions (#114131)
1 parent 01f8bd9 commit bba7e30

4 files changed

Lines changed: 496 additions & 31 deletions

File tree

Lines changed: 307 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,307 @@
1+
// Browser tests cover independently bounded delegated node-proxy requests.
2+
import { MAX_TIMER_TIMEOUT_MS } from "openclaw/plugin-sdk/number-runtime";
3+
import { beforeEach, describe, expect, it, vi } from "vitest";
4+
5+
type BrowserNodeRequest = {
6+
nodeId: string;
7+
command: string;
8+
timeoutMs: number;
9+
idempotencyKey: string;
10+
params: {
11+
method: string;
12+
path: string;
13+
timeoutMs: number;
14+
profile?: string;
15+
errorEnvelope: string;
16+
};
17+
};
18+
19+
type BrowserNodeResponse = {
20+
payload: { result: { ok: true; profile?: string } };
21+
};
22+
23+
type BrowserGatewayCall = (
24+
method: string,
25+
options: { timeoutMs: number },
26+
request: BrowserNodeRequest,
27+
extra: { scopes: string[]; signal?: AbortSignal },
28+
) => Promise<BrowserNodeResponse>;
29+
30+
const runtimeMocks = vi.hoisted(() => ({
31+
callGatewayTool: vi.fn<BrowserGatewayCall>(),
32+
persistBrowserProxyFiles: vi.fn<(_files?: unknown) => Promise<Map<string, string>>>(),
33+
applyBrowserProxyPaths: vi.fn<(result: unknown, mapping: Map<string, string>) => void>(),
34+
fetchBrowserJson: vi.fn<(...args: unknown[]) => Promise<unknown>>(),
35+
}));
36+
37+
vi.mock("./browser-tool.runtime.js", () => runtimeMocks);
38+
39+
import { createBrowserNodeProxyRequest } from "./browser-node-proxy.js";
40+
41+
function createSessionProxy() {
42+
return createBrowserNodeProxyRequest({
43+
nodeTarget: { nodeId: "node-1" },
44+
allowAutomaticHostFallback: false,
45+
});
46+
}
47+
48+
function readGatewayCall(index = 0) {
49+
const call = runtimeMocks.callGatewayTool.mock.calls[index];
50+
if (!call) {
51+
throw new Error(`Expected Browser node invocation ${index}`);
52+
}
53+
const [method, gateway, node, extra] = call;
54+
return { method, gateway, node, extra };
55+
}
56+
57+
beforeEach(() => {
58+
runtimeMocks.callGatewayTool.mockReset();
59+
runtimeMocks.callGatewayTool.mockResolvedValue({ payload: { result: { ok: true } } });
60+
runtimeMocks.persistBrowserProxyFiles.mockReset();
61+
runtimeMocks.persistBrowserProxyFiles.mockResolvedValue(new Map<string, string>());
62+
runtimeMocks.applyBrowserProxyPaths.mockReset();
63+
runtimeMocks.fetchBrowserJson.mockReset();
64+
});
65+
66+
describe("Browser node proxy nested watchdogs", () => {
67+
it("keeps a requested action inside separate node and Gateway watchdogs", async () => {
68+
const signal = new AbortController().signal;
69+
70+
await createSessionProxy()({
71+
method: "GET",
72+
path: "/snapshot",
73+
profile: "work",
74+
timeoutMs: 7_777,
75+
signal,
76+
});
77+
78+
const { method, gateway, node, extra } = readGatewayCall();
79+
expect(method).toBe("node.invoke");
80+
expect(node.nodeId).toBe("node-1");
81+
expect(node.command).toBe("browser.proxy");
82+
expect([node.params.timeoutMs, node.timeoutMs, gateway.timeoutMs]).toEqual([
83+
7_777, 12_777, 17_777,
84+
]);
85+
expect(node.params.errorEnvelope).toBe("browser-v1");
86+
expect(extra).toEqual({ scopes: ["operator.admin"], signal });
87+
expect(runtimeMocks.fetchBrowserJson).not.toHaveBeenCalled();
88+
});
89+
90+
it("binds the tool execution signal to node requests without their own signal", async () => {
91+
const signal = new AbortController().signal;
92+
const proxy = createBrowserNodeProxyRequest({
93+
nodeTarget: { nodeId: "node-1" },
94+
allowAutomaticHostFallback: false,
95+
signal,
96+
});
97+
98+
await proxy({ method: "GET", path: "/snapshot" });
99+
100+
expect(readGatewayCall().extra).toEqual({ scopes: ["operator.admin"], signal });
101+
});
102+
103+
it("keeps an explicit request signal ahead of the bound tool execution signal", async () => {
104+
const toolSignal = new AbortController().signal;
105+
const requestSignal = new AbortController().signal;
106+
const proxy = createBrowserNodeProxyRequest({
107+
nodeTarget: { nodeId: "node-1" },
108+
allowAutomaticHostFallback: false,
109+
signal: toolSignal,
110+
});
111+
112+
await proxy({ method: "GET", path: "/snapshot", signal: requestSignal });
113+
114+
expect(readGatewayCall().extra).toEqual({
115+
scopes: ["operator.admin"],
116+
signal: requestSignal,
117+
});
118+
});
119+
120+
it("keeps the bound tool execution signal when a node falls back to the host", async () => {
121+
const signal = new AbortController().signal;
122+
runtimeMocks.callGatewayTool.mockRejectedValueOnce(
123+
new Error("Browser control host is not reachable on 127.0.0.1:18791."),
124+
);
125+
runtimeMocks.fetchBrowserJson.mockResolvedValueOnce({ ok: true, source: "gateway-host" });
126+
const proxy = createBrowserNodeProxyRequest({
127+
nodeTarget: { nodeId: "node-1" },
128+
allowAutomaticHostFallback: true,
129+
signal,
130+
});
131+
132+
await expect(proxy({ method: "GET", path: "/snapshot" })).resolves.toMatchObject({
133+
ok: true,
134+
source: "gateway-host",
135+
});
136+
137+
expect(runtimeMocks.fetchBrowserJson).toHaveBeenCalledWith(
138+
"/snapshot",
139+
expect.objectContaining({ method: "GET", signal }),
140+
);
141+
});
142+
143+
it("keeps default action, node, and Gateway watchdogs strictly nested", async () => {
144+
await createSessionProxy()({ method: "GET", path: "/snapshot" });
145+
146+
const { gateway, node } = readGatewayCall();
147+
expect([node.params.timeoutMs, node.timeoutMs, gateway.timeoutMs]).toEqual([
148+
20_000, 25_000, 30_000,
149+
]);
150+
});
151+
152+
it.each([
153+
Number.MAX_SAFE_INTEGER,
154+
MAX_TIMER_TIMEOUT_MS,
155+
MAX_TIMER_TIMEOUT_MS - 1,
156+
MAX_TIMER_TIMEOUT_MS - 4_999,
157+
MAX_TIMER_TIMEOUT_MS - 5_000,
158+
MAX_TIMER_TIMEOUT_MS - 9_999,
159+
MAX_TIMER_TIMEOUT_MS - 10_000,
160+
MAX_TIMER_TIMEOUT_MS - 10_001,
161+
])("reserves both Node-safe watchdog windows for %i ms", async (timeoutMs) => {
162+
await createSessionProxy()({ method: "GET", path: "/snapshot", timeoutMs });
163+
164+
const actionTimeoutMs = Math.min(timeoutMs, MAX_TIMER_TIMEOUT_MS - 10_000);
165+
const { gateway, node } = readGatewayCall();
166+
expect([node.params.timeoutMs, node.timeoutMs, gateway.timeoutMs]).toEqual([
167+
actionTimeoutMs,
168+
actionTimeoutMs + 5_000,
169+
actionTimeoutMs + 10_000,
170+
]);
171+
expect(gateway.timeoutMs).toBeLessThanOrEqual(MAX_TIMER_TIMEOUT_MS);
172+
});
173+
174+
it("finishes ten independently owned, concurrently blocked Browser sessions", async () => {
175+
let release!: () => void;
176+
const barrier = new Promise<void>((resolve) => {
177+
release = resolve;
178+
});
179+
runtimeMocks.callGatewayTool.mockImplementation(async (_method, _gateway, node) => {
180+
await barrier;
181+
return { payload: { result: { ok: true, profile: node.params.profile } } };
182+
});
183+
184+
const sessions = Array.from({ length: 10 }, (_, index) => ({
185+
profile: `session-${index}`,
186+
timeoutMs: 7_777 + index,
187+
signal: new AbortController().signal,
188+
proxy: createSessionProxy(),
189+
}));
190+
const completed = new Set<string>();
191+
const pending = sessions.map(async ({ profile, timeoutMs, signal, proxy }) => {
192+
const result = await proxy({ method: "GET", path: "/snapshot", profile, timeoutMs, signal });
193+
completed.add(profile);
194+
return result;
195+
});
196+
197+
try {
198+
expect(runtimeMocks.callGatewayTool).toHaveBeenCalledTimes(10);
199+
expect(completed.size).toBe(0);
200+
expect(runtimeMocks.persistBrowserProxyFiles).not.toHaveBeenCalled();
201+
const invocationIds = new Set<string>();
202+
203+
sessions.forEach(({ profile, timeoutMs, signal }, index) => {
204+
const { method, gateway, node, extra } = readGatewayCall(index);
205+
expect(method).toBe("node.invoke");
206+
expect(node.nodeId).toBe("node-1");
207+
expect(node.command).toBe("browser.proxy");
208+
expect(node.params.profile).toBe(profile);
209+
expect(node.params.errorEnvelope).toBe("browser-v1");
210+
expect([node.params.timeoutMs, node.timeoutMs, gateway.timeoutMs]).toEqual([
211+
timeoutMs,
212+
timeoutMs + 5_000,
213+
timeoutMs + 10_000,
214+
]);
215+
expect(extra).toEqual({ scopes: ["operator.admin"], signal });
216+
invocationIds.add(node.idempotencyKey);
217+
});
218+
219+
expect(invocationIds.size).toBe(10);
220+
expect(runtimeMocks.fetchBrowserJson).not.toHaveBeenCalled();
221+
} finally {
222+
release();
223+
}
224+
225+
await expect(Promise.all(pending)).resolves.toEqual(
226+
sessions.map(({ profile }) => ({ ok: true, profile })),
227+
);
228+
expect(completed.size).toBe(10);
229+
expect(runtimeMocks.persistBrowserProxyFiles).toHaveBeenCalledTimes(10);
230+
expect(runtimeMocks.applyBrowserProxyPaths).toHaveBeenCalledTimes(10);
231+
expect(runtimeMocks.fetchBrowserJson).not.toHaveBeenCalled();
232+
expect(sessions.every(({ proxy }) => !proxy.isHostFallbackActive())).toBe(true);
233+
});
234+
235+
it("keeps one session cancellation isolated from nine concurrent sessions", async () => {
236+
let release!: () => void;
237+
const barrier = new Promise<void>((resolve) => {
238+
release = resolve;
239+
});
240+
runtimeMocks.callGatewayTool.mockImplementation(
241+
(_method, _gateway, node, extra) =>
242+
new Promise<BrowserNodeResponse>((resolve, reject) => {
243+
const onAbort = () => {
244+
const reason = extra.signal?.reason;
245+
reject(reason instanceof Error ? reason : new Error("Browser session cancelled"));
246+
};
247+
if (extra.signal?.aborted) {
248+
onAbort();
249+
return;
250+
}
251+
extra.signal?.addEventListener("abort", onAbort, { once: true });
252+
void barrier.then(() => {
253+
extra.signal?.removeEventListener("abort", onAbort);
254+
if (!extra.signal?.aborted) {
255+
resolve({ payload: { result: { ok: true, profile: node.params.profile } } });
256+
}
257+
});
258+
}),
259+
);
260+
261+
const sessions = Array.from({ length: 10 }, (_, index) => ({
262+
profile: `session-${index}`,
263+
timeoutMs: 7_777 + index,
264+
controller: new AbortController(),
265+
proxy: createSessionProxy(),
266+
}));
267+
const pending = sessions.map(({ profile, timeoutMs, controller, proxy }) =>
268+
proxy({
269+
method: "GET",
270+
path: "/snapshot",
271+
profile,
272+
timeoutMs,
273+
signal: controller.signal,
274+
}),
275+
);
276+
const completion = Promise.allSettled(pending);
277+
const cancelledSession = sessions.at(3);
278+
const cancelledRun = pending.at(3);
279+
if (!cancelledSession || !cancelledRun) {
280+
release();
281+
throw new Error("Expected a dedicated cancellation session");
282+
}
283+
const abortError = new Error("session-3 cancelled");
284+
285+
try {
286+
expect(runtimeMocks.callGatewayTool).toHaveBeenCalledTimes(10);
287+
cancelledSession.controller.abort(abortError);
288+
await expect(cancelledRun).rejects.toBe(abortError);
289+
expect(runtimeMocks.persistBrowserProxyFiles).not.toHaveBeenCalled();
290+
expect(runtimeMocks.fetchBrowserJson).not.toHaveBeenCalled();
291+
} finally {
292+
release();
293+
}
294+
295+
await expect(completion).resolves.toEqual(
296+
sessions.map(({ profile }, index) =>
297+
index === 3
298+
? { status: "rejected", reason: abortError }
299+
: { status: "fulfilled", value: { ok: true, profile } },
300+
),
301+
);
302+
expect(runtimeMocks.persistBrowserProxyFiles).toHaveBeenCalledTimes(9);
303+
expect(runtimeMocks.applyBrowserProxyPaths).toHaveBeenCalledTimes(9);
304+
expect(runtimeMocks.fetchBrowserJson).not.toHaveBeenCalled();
305+
expect(sessions.every(({ proxy }) => !proxy.isHostFallbackActive())).toBe(true);
306+
});
307+
});

‎extensions/browser/src/browser-node-proxy.ts‎

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
import crypto from "node:crypto";
2+
import {
3+
addTimerTimeoutGraceMs,
4+
MAX_TIMER_TIMEOUT_MS,
5+
resolveTimerTimeoutMs,
6+
} from "openclaw/plugin-sdk/number-runtime";
27
import { createSubsystemLogger } from "openclaw/plugin-sdk/runtime-env";
38
import { isBrowserControlHostUnavailableError } from "./browser-node-fallback.js";
49
import {
@@ -65,11 +70,18 @@ async function callBrowserProxy(params: {
6570
profile?: string;
6671
signal?: AbortSignal;
6772
}): Promise<BrowserProxySuccess> {
68-
const proxyTimeoutMs =
69-
typeof params.timeoutMs === "number" && Number.isFinite(params.timeoutMs)
70-
? Math.max(1, Math.floor(params.timeoutMs))
71-
: DEFAULT_BROWSER_PROXY_TIMEOUT_MS;
72-
const gatewayTimeoutMs = proxyTimeoutMs + BROWSER_PROXY_GATEWAY_TIMEOUT_SLACK_MS;
73+
// Reserve both watchdog windows before clamping so timer saturation cannot
74+
// make an outer watchdog expire alongside the browser action.
75+
const proxyTimeoutMs = Math.min(
76+
resolveTimerTimeoutMs(params.timeoutMs, DEFAULT_BROWSER_PROXY_TIMEOUT_MS),
77+
MAX_TIMER_TIMEOUT_MS - 2 * BROWSER_PROXY_GATEWAY_TIMEOUT_SLACK_MS,
78+
);
79+
const nodeInvokeTimeoutMs =
80+
addTimerTimeoutGraceMs(proxyTimeoutMs, BROWSER_PROXY_GATEWAY_TIMEOUT_SLACK_MS) ??
81+
proxyTimeoutMs;
82+
const gatewayTimeoutMs =
83+
addTimerTimeoutGraceMs(nodeInvokeTimeoutMs, BROWSER_PROXY_GATEWAY_TIMEOUT_SLACK_MS) ??
84+
nodeInvokeTimeoutMs;
7385
let payload: { payload?: unknown; payloadJSON?: unknown } | null;
7486
try {
7587
payload = await callGatewayTool<{ payload?: unknown; payloadJSON?: unknown }>(
@@ -78,9 +90,9 @@ async function callBrowserProxy(params: {
7890
{
7991
nodeId: params.nodeId,
8092
command: "browser.proxy",
81-
// node.invoke owns a separate watchdog from browser.proxy. Keep both
82-
// bounded, with enough outer slack for the proxy result to cross back.
83-
timeoutMs: gatewayTimeoutMs,
93+
// Keep the browser action, node watchdog, and Gateway RPC on distinct
94+
// budgets so a detailed node timeout can cross both outer boundaries.
95+
timeoutMs: nodeInvokeTimeoutMs,
8496
params: {
8597
method: params.method,
8698
path: params.path,
@@ -136,17 +148,24 @@ async function callLocalBrowserControl(params: Parameters<BrowserProxyRequest>[0
136148
export function createBrowserNodeProxyRequest(params: {
137149
nodeTarget: { nodeId: string; label?: string };
138150
allowAutomaticHostFallback: boolean;
151+
signal?: AbortSignal;
139152
}): BrowserProxyRequest {
140153
let hostFallbackActive = false;
141154
const dispatch = async (request: Parameters<BrowserProxyRequest>[0]) => {
155+
// Bind cancellation once so every node action and its safe host fallback
156+
// inherit their execution signal without overriding an explicit request.
157+
const requestWithSignal =
158+
request.signal || params.signal
159+
? { ...request, signal: request.signal ?? params.signal }
160+
: request;
142161
if (hostFallbackActive) {
143-
return await callLocalBrowserControl(request);
162+
return await callLocalBrowserControl(requestWithSignal);
144163
}
145164
try {
146165
const proxy = await callBrowserProxy({
147166
nodeId: params.nodeTarget.nodeId,
148167
markControlHostUnavailable: params.allowAutomaticHostFallback,
149-
...request,
168+
...requestWithSignal,
150169
});
151170
const mapping = await persistBrowserProxyFiles(proxy.files);
152171
applyBrowserProxyPaths(proxy.result, mapping);
@@ -164,7 +183,7 @@ export function createBrowserNodeProxyRequest(params: {
164183
logger.warn(
165184
`browser node ${params.nodeTarget.label ?? params.nodeTarget.nodeId} control host unavailable; falling back to Gateway host`,
166185
);
167-
return await callLocalBrowserControl(request);
186+
return await callLocalBrowserControl(requestWithSignal);
168187
}
169188
};
170189
return Object.assign(dispatch, {

0 commit comments

Comments
 (0)