|
| 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 | +}); |
0 commit comments