Skip to content

Commit 4823b23

Browse files
authored
fix(browser): stop cancelled downloads from capturing later files (#124382)
* fix(browser): cancel abandoned download waits * fix(browser): cancel in-flight download clicks
1 parent 148229b commit 4823b23

9 files changed

Lines changed: 385 additions & 15 deletions

‎extensions/browser/src/browser-tool.actions.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,7 @@ export async function executeDownloadAction(params: {
395395
baseUrl?: string;
396396
profile?: string;
397397
proxyRequest: BrowserProxyRequest | null;
398+
signal?: AbortSignal;
398399
onTabActivity?: (targetId: string | undefined) => void;
399400
}): Promise<AgentToolResult<unknown>> {
400401
const { action, input, baseUrl, profile, proxyRequest } = params;
@@ -419,12 +420,14 @@ export async function executeDownloadAction(params: {
419420
targetId,
420421
timeoutMs,
421422
profile,
423+
signal: params.signal,
422424
})
423425
: await browserToolActionDeps.browserWaitForDownload(baseUrl, {
424426
path: request.path,
425427
targetId,
426428
timeoutMs,
427429
profile,
430+
signal: params.signal,
428431
});
429432
params.onTabActivity?.(readStringValue((result as { targetId?: unknown }).targetId) ?? targetId);
430433
return formatBrowserExternalToolResult({ kind: "download", payload: result });

‎extensions/browser/src/browser-tool.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -932,6 +932,7 @@ export function createBrowserTool(opts?: {
932932
baseUrl,
933933
profile,
934934
proxyRequest,
935+
signal,
935936
onTabActivity: sessionTabs.touch,
936937
});
937938
case "upload": {

‎extensions/browser/src/browser/client-actions-core.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,13 +64,15 @@ async function postDownloadRequest(
6464
body: Record<string, unknown>,
6565
profile?: string,
6666
timeoutMs?: number,
67+
signal?: AbortSignal,
6768
): Promise<BrowserDownloadActionResult> {
6869
const q = buildProfileQuery(profile);
6970
return await fetchBrowserJson<BrowserDownloadActionResult>(withBaseUrl(baseUrl, `${route}${q}`), {
7071
method: "POST",
7172
headers: { "Content-Type": "application/json" },
7273
body: JSON.stringify(body),
7374
timeoutMs: resolveBrowserOperationRequestTimeoutMs(timeoutMs),
75+
signal,
7476
});
7577
}
7678

@@ -160,6 +162,7 @@ export async function browserWaitForDownload(
160162
targetId?: string;
161163
timeoutMs?: number;
162164
profile?: string;
165+
signal?: AbortSignal;
163166
},
164167
): Promise<BrowserDownloadActionResult> {
165168
return await postDownloadRequest(
@@ -172,6 +175,7 @@ export async function browserWaitForDownload(
172175
},
173176
opts.profile,
174177
opts.timeoutMs,
178+
opts.signal,
175179
);
176180
}
177181

@@ -184,6 +188,7 @@ export async function browserDownload(
184188
targetId?: string;
185189
timeoutMs?: number;
186190
profile?: string;
191+
signal?: AbortSignal;
187192
},
188193
): Promise<BrowserDownloadActionResult> {
189194
return await postDownloadRequest(
@@ -197,6 +202,7 @@ export async function browserDownload(
197202
},
198203
opts.profile,
199204
opts.timeoutMs,
205+
opts.signal,
200206
);
201207
}
202208

Lines changed: 271 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
1+
import fs from "node:fs/promises";
2+
import { createServer, type Server } from "node:http";
3+
import type { AddressInfo } from "node:net";
4+
import path from "node:path";
5+
import { afterEach, describe, expect, it } from "vitest";
6+
import { useAutoCleanupTempDirTracker } from "../../test-support.js";
7+
import { playwrightCore } from "./playwright-core.runtime.js";
8+
import { ensurePageState } from "./pw-session-state.js";
9+
import { closePlaywrightBrowserConnection, getPageForTargetId } from "./pw-session.js";
10+
import { downloadViaPlaywright, waitForDownloadViaPlaywright } from "./pw-tools-core.downloads.js";
11+
import { getFreePort } from "./test-port.js";
12+
13+
const runChromiumProof = process.env.OPENCLAW_BROWSER_DOWNLOAD_E2E === "1";
14+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
15+
16+
function listen(server: Server): Promise<number> {
17+
return new Promise((resolve, reject) => {
18+
server.once("error", reject);
19+
server.listen(0, "127.0.0.1", () => {
20+
resolve((server.address() as AddressInfo).port);
21+
});
22+
});
23+
}
24+
25+
function closeServer(server: Server): Promise<void> {
26+
return new Promise((resolve, reject) => {
27+
server.close((error) => (error ? reject(error) : resolve()));
28+
});
29+
}
30+
31+
async function readTargetId(page: import("playwright-core").Page): Promise<string> {
32+
const session = await page.context().newCDPSession(page);
33+
try {
34+
const { targetInfo } = await session.send("Target.getTargetInfo");
35+
return targetInfo.targetId;
36+
} finally {
37+
await session.detach();
38+
}
39+
}
40+
41+
describe.runIf(runChromiumProof)("managed Chromium download cancellation", () => {
42+
const cleanup: Array<() => Promise<void>> = [];
43+
44+
afterEach(async () => {
45+
for (const dispose of cleanup.splice(0).toReversed()) {
46+
await dispose();
47+
}
48+
});
49+
50+
it("does not let a cancelled waiter capture and write a later download", async () => {
51+
const rootDir = tempDirs.make("openclaw-download-cancel-");
52+
cleanup.push(async () => await fs.rm(rootDir, { recursive: true, force: true }));
53+
54+
const abandonedPayload = Buffer.from("abandoned-click-download\n");
55+
const successorPayload = Buffer.from("successor-download\n");
56+
const downloadServer = createServer((request, response) => {
57+
if (request.url === "/late.txt") {
58+
response.writeHead(200, {
59+
"content-disposition": 'attachment; filename="duplicate.txt"',
60+
"content-length": String(abandonedPayload.byteLength),
61+
"content-type": "text/plain",
62+
});
63+
response.end(abandonedPayload);
64+
return;
65+
}
66+
if (request.url === "/successor.txt") {
67+
response.writeHead(200, {
68+
"content-disposition": 'attachment; filename="duplicate.txt"',
69+
"content-length": String(successorPayload.byteLength),
70+
"content-type": "text/plain",
71+
});
72+
response.end(successorPayload);
73+
return;
74+
}
75+
response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
76+
response.end(
77+
'<button id="delayed" disabled onclick="location.href=\'/late.txt\'">Delayed Download</button>' +
78+
'<a id="download" href="/successor.txt" download>Download</a>',
79+
);
80+
});
81+
const downloadPort = await listen(downloadServer);
82+
cleanup.push(async () => await closeServer(downloadServer));
83+
84+
const cdpPort = await getFreePort();
85+
const profileDir = path.join(rootDir, "profile");
86+
const context = await playwrightCore.chromium.launchPersistentContext(profileDir, {
87+
headless: true,
88+
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
89+
args: [`--remote-debugging-port=${cdpPort}`],
90+
});
91+
cleanup.push(async () => await context.close());
92+
const page = context.pages()[0] ?? (await context.newPage());
93+
await page.goto(`http://127.0.0.1:${downloadPort}/`);
94+
95+
const cdpUrl = `http://127.0.0.1:${cdpPort}`;
96+
const targetId = await readTargetId(page);
97+
cleanup.push(async () => await closePlaywrightBrowserConnection({ cdpUrl }));
98+
const outputRoot = path.join(rootDir, "downloads");
99+
const outputPath = path.join(outputRoot, "cancelled.txt");
100+
const controller = new AbortController();
101+
const wait = waitForDownloadViaPlaywright({
102+
cdpUrl,
103+
targetId,
104+
path: outputPath,
105+
rootDir: outputRoot,
106+
timeoutMs: 5_000,
107+
signal: controller.signal,
108+
});
109+
const outcome = wait.then(
110+
(download) => ({ kind: "resolved" as const, download }),
111+
(error: unknown) => ({
112+
kind: "rejected" as const,
113+
message: error instanceof Error ? error.message : String(error),
114+
}),
115+
);
116+
117+
const controlledPage = await getPageForTargetId({ cdpUrl, targetId });
118+
await expect.poll(() => ensurePageState(controlledPage).downloadWaiterDepth).toBe(1);
119+
controller.abort(new Error("request aborted"));
120+
const afterAbort = await Promise.race([
121+
outcome,
122+
new Promise<{ kind: "pending" }>((resolve) => {
123+
setTimeout(() => resolve({ kind: "pending" }), 200);
124+
}),
125+
]);
126+
127+
const successorPath = path.join(outputRoot, "successor.txt");
128+
const successor = waitForDownloadViaPlaywright({
129+
cdpUrl,
130+
targetId,
131+
path: successorPath,
132+
rootDir: outputRoot,
133+
timeoutMs: 5_000,
134+
});
135+
await expect.poll(() => ensurePageState(controlledPage).downloadWaiterDepth).toBe(1);
136+
await page.locator("#download").click();
137+
const finalOutcome = await outcome;
138+
const written = await fs.readFile(outputPath).catch(() => undefined);
139+
const successorResult = await successor;
140+
141+
expect({
142+
afterAbort,
143+
finalOutcome,
144+
written: written?.toString("utf8"),
145+
successor: {
146+
bytes: await fs.readFile(successorResult.path, "utf8"),
147+
suggestedFilename: successorResult.suggestedFilename,
148+
},
149+
}).toEqual({
150+
afterAbort: { kind: "rejected", message: "request aborted" },
151+
finalOutcome: { kind: "rejected", message: "request aborted" },
152+
written: undefined,
153+
successor: {
154+
bytes: successorPayload.toString("utf8"),
155+
suggestedFilename: "duplicate.txt",
156+
},
157+
});
158+
159+
const pageState = ensurePageState(controlledPage);
160+
pageState.roleRefs = { e1: { role: "button", name: "Delayed Download" } };
161+
pageState.roleRefsMode = "role";
162+
await page.evaluate(() => {
163+
setTimeout(() => {
164+
const delayed = document.querySelector<HTMLButtonElement>("#delayed");
165+
if (delayed) {
166+
delayed.disabled = false;
167+
}
168+
}, 500);
169+
});
170+
const sharedPath = path.join(outputRoot, "shared.txt");
171+
const clickController = new AbortController();
172+
const cancelledClick = downloadViaPlaywright({
173+
cdpUrl,
174+
targetId,
175+
ref: "e1",
176+
path: sharedPath,
177+
rootDir: outputRoot,
178+
timeoutMs: 5_000,
179+
signal: clickController.signal,
180+
});
181+
const clickOutcome = cancelledClick.then(
182+
() => ({ kind: "resolved" as const }),
183+
(error: unknown) => ({
184+
kind: "rejected" as const,
185+
message: error instanceof Error ? error.message : String(error),
186+
}),
187+
);
188+
await expect.poll(() => pageState.downloadWaiterDepth).toBe(1);
189+
clickController.abort(new Error("click request aborted"));
190+
const clickAfterAbort = await Promise.race([
191+
clickOutcome,
192+
new Promise<{ kind: "pending" }>((resolve) => {
193+
setTimeout(() => resolve({ kind: "pending" }), 200);
194+
}),
195+
]);
196+
expect(clickAfterAbort).toEqual({ kind: "rejected", message: "click request aborted" });
197+
expect(pageState.downloadWaiterDepth).toBe(0);
198+
199+
const clickSuccessor = waitForDownloadViaPlaywright({
200+
cdpUrl,
201+
targetId,
202+
path: sharedPath,
203+
rootDir: outputRoot,
204+
timeoutMs: 5_000,
205+
});
206+
await expect.poll(() => pageState.downloadWaiterDepth).toBe(1);
207+
const beforeSuccessorClick = await Promise.race([
208+
clickSuccessor.then(() => "resolved" as const),
209+
new Promise<"pending">((resolve) => {
210+
setTimeout(() => resolve("pending"), 700);
211+
}),
212+
]);
213+
expect(beforeSuccessorClick).toBe("pending");
214+
await expect(fs.access(sharedPath)).rejects.toMatchObject({ code: "ENOENT" });
215+
await page.locator("#download").click();
216+
const clickSuccessorResult = await clickSuccessor;
217+
await expect(fs.readFile(clickSuccessorResult.path, "utf8")).resolves.toBe(
218+
successorPayload.toString("utf8"),
219+
);
220+
221+
await closePlaywrightBrowserConnection({ cdpUrl });
222+
await context.close();
223+
224+
const restartedCdpPort = await getFreePort();
225+
const restartedContext = await playwrightCore.chromium.launchPersistentContext(profileDir, {
226+
headless: true,
227+
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
228+
args: [`--remote-debugging-port=${restartedCdpPort}`],
229+
});
230+
cleanup.push(async () => await restartedContext.close());
231+
const restartedPage = restartedContext.pages()[0] ?? (await restartedContext.newPage());
232+
await restartedPage.goto(`http://127.0.0.1:${downloadPort}/`);
233+
const restartedCdpUrl = `http://127.0.0.1:${restartedCdpPort}`;
234+
const restartedTargetId = await readTargetId(restartedPage);
235+
cleanup.push(async () => await closePlaywrightBrowserConnection({ cdpUrl: restartedCdpUrl }));
236+
237+
const downloadAfterRestart = async () => {
238+
const pending = waitForDownloadViaPlaywright({
239+
cdpUrl: restartedCdpUrl,
240+
targetId: restartedTargetId,
241+
rootDir: outputRoot,
242+
timeoutMs: 5_000,
243+
});
244+
const connected = await getPageForTargetId({
245+
cdpUrl: restartedCdpUrl,
246+
targetId: restartedTargetId,
247+
});
248+
await expect.poll(() => ensurePageState(connected).downloadWaiterDepth).toBe(1);
249+
await restartedPage.locator("#download").click();
250+
return await pending;
251+
};
252+
const firstDuplicate = await downloadAfterRestart();
253+
const secondDuplicate = await downloadAfterRestart();
254+
255+
expect(firstDuplicate.suggestedFilename).toBe("duplicate.txt");
256+
expect(secondDuplicate.suggestedFilename).toBe("duplicate.txt");
257+
expect(firstDuplicate.path).not.toBe(secondDuplicate.path);
258+
await expect(fs.readFile(firstDuplicate.path, "utf8")).resolves.toBe(
259+
successorPayload.toString("utf8"),
260+
);
261+
await expect(fs.readFile(secondDuplicate.path, "utf8")).resolves.toBe(
262+
successorPayload.toString("utf8"),
263+
);
264+
expect((await fs.readdir(outputRoot)).some((name) => name.endsWith(".part"))).toBe(false);
265+
266+
await closePlaywrightBrowserConnection({ cdpUrl: restartedCdpUrl });
267+
await restartedContext.close();
268+
await fs.rm(rootDir, { recursive: true, force: true });
269+
await expect(fs.access(rootDir)).rejects.toMatchObject({ code: "ENOENT" });
270+
}, 30_000);
271+
});

‎extensions/browser/src/browser/pw-download-capture.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export type BrowserDownloadCaptureOptions = {
1616
mode?: "passive" | "explicit";
1717
outputPath?: string;
1818
outputRoot?: string;
19+
signal?: AbortSignal;
1920
timeoutMessage?: string;
2021
};
2122

@@ -85,6 +86,7 @@ export function createDownloadCaptureForPage(
8586
let depthReleased = false;
8687
let timer: NodeJS.Timeout | undefined;
8788
let handler: ((download: unknown) => void) | undefined;
89+
let abort = () => {};
8890

8991
const cleanup = () => {
9092
if (!depthReleased) {
@@ -99,6 +101,7 @@ export function createDownloadCaptureForPage(
99101
page.off("download", handler as never);
100102
handler = undefined;
101103
}
104+
opts.signal?.removeEventListener("abort", abort);
102105
};
103106

104107
const promise = new Promise<BrowserDownloadResult>((resolve, reject) => {
@@ -123,6 +126,19 @@ export function createDownloadCaptureForPage(
123126
Math.max(1, timeoutMs),
124127
);
125128
timer.unref?.();
129+
abort = () => {
130+
if (done) {
131+
return;
132+
}
133+
done = true;
134+
cleanup();
135+
const reason = opts.signal?.reason;
136+
reject(reason instanceof Error ? reason : new Error("Download wait was cancelled"));
137+
};
138+
opts.signal?.addEventListener("abort", abort, { once: true });
139+
if (opts.signal?.aborted) {
140+
abort();
141+
}
126142
});
127143

128144
return {

0 commit comments

Comments
 (0)