The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.
JavaScript agent-skillsai-agentautomationbrowserbrowser-automationclaude-codecodexhermes-agentskillsskills-sh
fix(ego-browser): share one guid-named download directory across Pages and processes
Zhuowei Wang59c67fc4b248
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjsindex 48e3efe..e41a308 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs@@ -51,6 +51,7 @@ import {} from "./page-action-latency.mjs";import {concurrentTaskSpaceDownloadCase,+ concurrentPageSlowDownloadCase,pageDownloadCase,pageDownloadPrepareRoundCase,pagePdfViewerDownloadCase,@@ -202,6 +203,10 @@ export const e2eCases = [name: "Concurrent TaskSpace downloads",body: concurrentTaskSpaceDownloadCase,},+ {+ name: "Concurrent Page downloads: slow response",+ body: concurrentPageSlowDownloadCase,+ },{name: "Page Chromium PDF viewer download",body: pagePdfViewerDownloadCase,diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-download.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-download.mjsindex 13000be..bfa4549 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-download.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-download.mjs@@ -131,10 +131,9 @@ export function concurrentTaskSpaceDownloadCase() {firstDownload.path(),secondDownload.path(),]);- const { dirname } = await import("node:path");assert(- dirname(firstTemporaryPath) !== dirname(secondTemporaryPath),- "concurrent TaskSpaces use isolated temporary directories"+ firstTemporaryPath !== secondTemporaryPath,+ "concurrent TaskSpaces receive distinct temporary files");const firstSavedPath = join(tempDir, "task-space-first-download.txt");@@ -197,6 +196,95 @@ export function concurrentTaskSpaceDownloadCase() {`;}+export function concurrentPageSlowDownloadCase() {+ return `+ // Two Pages of one TaskSpace start downloads from script, like a button+ // whose handler fetches first, against servers that answer late, like an+ // export generated on demand. The second Page arms while the first+ // download still waits for its headers, so Chromium picks the first+ // download's target under the second Page's setting, and neither download+ // finishes before the other starts. Both files must still reach their own+ // Page. (Two TaskSpaces would exercise the same shared Chromium setting,+ // but a navigation left pending while another TaskSpace is operated does+ // not currently survive the switch.)+ const task = await taskSpace(taskName);+ const firstPage = await newPageAt(task, baseUrl + "/?download-page=first-slow");+ const secondPage = await newPageAt(task, baseUrl + "/?download-page=second-slow");+ try {+ await Promise.all([+ firstPage.evaluate((downloadUrl) => {+ const link = document.createElement("a");+ link.id = "slow-download";+ link.href = downloadUrl;+ link.textContent = "Download first Page file slowly";+ document.body.append(link);+ }, baseUrl + "/api/download?space=first&delay=1500"),+ secondPage.evaluate((downloadUrl) => {+ const link = document.createElement("a");+ link.id = "slow-download";+ link.href = downloadUrl;+ link.textContent = "Download second Page file slowly";+ document.body.append(link);+ }, baseUrl + "/api/download?space=second&delay=1500"),+ ]);++ const firstPending = firstPage.waitForEvent("download", {+ timeout: 10_000,+ });+ const secondPending = secondPage.waitForEvent("download", {+ timeout: 10_000,+ });+ const clickedAt = Date.now();+ await firstPage.evaluate(() => {+ document.getElementById("slow-download").click();+ });+ await secondPage.evaluate(() => {+ document.getElementById("slow-download").click();+ });+ const [firstDownload, secondDownload] = await Promise.all([+ firstPending,+ secondPending,+ ]);+ assert(+ Date.now() - clickedAt >= 1_400,+ "the fixture held the download headers back"+ );++ assertEqual(+ firstDownload.suggestedFilename(),+ "ego-first-download.txt",+ "the first Page receives its own download"+ );+ assertEqual(+ secondDownload.suggestedFilename(),+ "ego-second-download.txt",+ "the second Page receives its own download"+ );+ const [firstTemporaryPath, secondTemporaryPath] = await Promise.all([+ firstDownload.path(),+ secondDownload.path(),+ ]);+ assert(+ firstTemporaryPath !== secondTemporaryPath,+ "the two downloads land in distinct temporary files"+ );+ assertEqual(+ await readFile(firstTemporaryPath, "utf8"),+ "ego-browser first TaskSpace download\\n",+ "the first download reaches its Page although the second armed after it started"+ );+ assertEqual(+ await readFile(secondTemporaryPath, "utf8"),+ "ego-browser second TaskSpace download\\n",+ "the second download is not mixed up with the first"+ );+ await Promise.all([firstDownload.delete(), secondDownload.delete()]);+ } finally {+ await Promise.all([firstPage.close(), secondPage.close()]);+ }+ `;+}+export function pagePdfViewerDownloadCase() {return `const task = await taskSpace(taskName);diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjsindex e67a3ed..88c8baf 100644--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs@@ -64,13 +64,22 @@ export async function startFixtureServer(taskName) {? `ego-browser ${space} TaskSpace download\n`: "ego-browser download fixture\n";const filename = space ? `ego-${space}-download.txt` : "ego-download.txt";- res.writeHead(200, {- "content-type": "text/plain",- "content-length": Buffer.byteLength(body),- "content-disposition": `attachment; filename="${filename}"`,- "cache-control": "no-store",- });- res.end(body);+ // `delay` holds the response headers back, like a server that generates+ // an export before it answers: Chromium only creates the download, and+ // picks its target directory, once the headers arrive.+ const delayMs = Math.min(+ Number(url.searchParams.get("delay")) || 0,+ 10_000,+ );+ setTimeout(() => {+ res.writeHead(200, {+ "content-type": "text/plain",+ "content-length": Buffer.byteLength(body),+ "content-disposition": `attachment; filename="${filename}"`,+ "cache-control": "no-store",+ });+ res.end(body);+ }, delayMs);return;}if (url.pathname === "/api/openai-gpt-4-system-card.pdf") {diff --git a/package/ego-browser/skill-body/SKILL.md b/package/ego-browser/skill-body/SKILL.mdindex 7d549e9..179c77c 100644--- a/package/ego-browser/skill-body/SKILL.md+++ b/package/ego-browser/skill-body/SKILL.md@@ -485,11 +485,13 @@ await download.saveAs("/absolute/path/report.pdf");````download.saveAs()` waits for completion and creates missing parent-directories. `download.path()` returns the round-local temporary file;-`failure()`, `cancel()`, and `delete()` manage its lifecycle. Temporary download-files are removed when the SDK round is disposed, so call `saveAs()` before the-script ends. Do not set a global download directory with raw CDP; each download-wait configures and restores only the addressed Page session.+directories. `download.path()` returns the round-local temporary file, named+after Chromium's download id inside a directory shared by every ego-browser+process; `failure()`, `cancel()`, and `delete()` manage its lifecycle.+Temporary download files are removed when the SDK round is disposed, so call+`saveAs()` before the script ends. Do not set a download directory with raw+CDP: the browser keeps one download behavior for all TaskSpaces, and the+download wait restores the default only once no process waits any more.`page.fetch()` runs `window.fetch()` in the Page: relative URLs, cookies, andservice workers use that Page, and browser CORS still applies. It returnsdiff --git a/package/ego-browser/src/driver/downloads.test.mjs b/package/ego-browser/src/driver/downloads.test.mjsindex 9b75a65..fe23527 100644--- a/package/ego-browser/src/driver/downloads.test.mjs+++ b/package/ego-browser/src/driver/downloads.test.mjs@@ -1,128 +1,127 @@import test from "node:test";import assert from "node:assert/strict";-import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { spawnSync } from "node:child_process";+import { mkdtempSync } from "node:fs";+import {+ access,+ mkdtemp,+ readFile,+ rename,+ rm,+ writeFile,+} from "node:fs/promises";import { join } from "node:path";import { tmpdir } from "node:os";-import {- disposeDownloadArtifacts,- preparePageDownload,-} from "../../dist/src/driver/downloads.js";--test("a page download is isolated in a temporary directory and can be saved", async () => {- const calls = [];- const listeners = new Set();- const services = {+// The shared download directory lives under the runtime state directory;+// keep this test process away from the user's real one.+const stateDir = mkdtempSync(join(tmpdir(), "ego-download-state-"));+process.env.EGO_BROWSER_STATE_DIR = stateDir;++const { disposeDownloadArtifacts, downloadDirectory, preparePageDownload } =+ await import("../../dist/src/driver/downloads.js");++const sharedDirectory = join(stateDir, "downloads");+const waiterMarker = (pid) => join(sharedDirectory, "waiters", String(pid));++function recordingServices(calls = [], listeners = new Map()) {+ return {+ calls,+ listeners,async cdp(method, params, sessionId) {calls.push({ method, params, sessionId });return {};},- subscribePageEvents(_targetId, listener) {- listeners.add(listener);- return () => listeners.delete(listener);+ subscribePageEvents(targetId, listener) {+ listeners.set(targetId, listener);+ return () => listeners.delete(targetId);},};+}++function beginDownload(services, targetId, guid, suggestedFilename) {+ services.listeners.get(targetId)({+ method: "Page.downloadWillBegin",+ params: { guid, url: `https://example.test/${guid}`, suggestedFilename },+ });+}++function completeDownload(services, targetId, guid) {+ services.listeners.get(targetId)({+ method: "Page.downloadProgress",+ params: { guid, state: "completed" },+ });+}++function behaviorCalls(calls) {+ return calls+ .filter((call) => call.method === "Page.setDownloadBehavior")+ .map((call) => ({+ behavior: call.params.behavior,+ sessionId: call.sessionId,+ }));+}++test("a page download lands in the shared directory under its guid and can be saved", async () => {+ const services = recordingServices();const interception = preparePageDownload(services, "target-1", {timeoutMs: 1_000,});await interception.ready("session-1");- const allow = calls.find(- (call) =>- call.method === "Page.setDownloadBehavior" &&- call.params.behavior === "allow",+ const armed = services.calls.find(+ (call) => call.method === "Page.setDownloadBehavior",);- assert(allow);- assert.equal(allow.sessionId, "session-1");-- for (const listener of listeners) {- listener({- method: "Page.downloadWillBegin",- params: {- guid: "guid-1",- url: "https://example.test/report",- suggestedFilename: "report.txt",- },- });- }+ assert.deepEqual(armed, {+ method: "Page.setDownloadBehavior",+ params: { behavior: "allowAndName", downloadPath: sharedDirectory },+ sessionId: "session-1",+ });+ assert.equal(downloadDirectory(), sharedDirectory);+ await access(waiterMarker(process.pid));++ beginDownload(services, "target-1", "guid-1", "report.txt");const download = await interception.event;- await writeFile(join(allow.params.downloadPath, "report.txt"), "contents");- for (const listener of listeners) {- listener({- method: "Page.downloadProgress",- params: {- guid: "guid-1",- state: "completed",- totalBytes: 8,- receivedBytes: 8,- },- });- }+ await writeFile(join(sharedDirectory, "guid-1"), "contents");+ completeDownload(services, "target-1", "guid-1");const outputDir = await mkdtemp(join(tmpdir(), "ego-download-output-"));const outputPath = join(outputDir, "saved.txt");- assert.equal(download.url, "https://example.test/report");+ assert.equal(download.url, "https://example.test/guid-1");assert.equal(download.suggestedFilename, "report.txt");assert.equal(await download.failure(), null);await download.cancel();assert.equal(- calls.some((call) => call.method === "Browser.cancelDownload"),+ services.calls.some((call) => call.method === "Browser.cancelDownload"),false,"cancel is a no-op after completion",);- assert.equal(- await download.path(),- join(allow.params.downloadPath, "report.txt"),- );+ assert.equal(await download.path(), join(sharedDirectory, "guid-1"));await download.saveAs(outputPath);assert.equal(await readFile(outputPath, "utf8"), "contents");- assert(- calls.some(- (call) =>- call.method === "Page.setDownloadBehavior" &&- call.params.behavior === "default",- ),+ assert.deepEqual(behaviorCalls(services.calls).at(-1), {+ behavior: "default",+ sessionId: "session-1",+ });+ await assert.rejects(+ access(waiterMarker(process.pid)),+ "the last waiter removes its marker",);await download.delete();- await assert.rejects(access(join(allow.params.downloadPath, "report.txt")));+ await assert.rejects(access(join(sharedDirectory, "guid-1")));+ await access(sharedDirectory);await rm(outputDir, { recursive: true, force: true });disposeDownloadArtifacts();});test("saveAs waits for an in-progress download", async () => {- const listeners = new Set();- let downloadPath;- const interception = preparePageDownload(- {- async cdp(method, params) {- if (- method === "Page.setDownloadBehavior" &&- params.behavior === "allow"- ) {- downloadPath = params.downloadPath;- }- return {};- },- subscribePageEvents(_targetId, listener) {- listeners.add(listener);- return () => listeners.delete(listener);- },- },- "target-slow",- { timeoutMs: 1_000 },- );+ const services = recordingServices();+ const interception = preparePageDownload(services, "target-slow", {+ timeoutMs: 1_000,+ });await interception.ready("session-slow");- for (const listener of listeners) {- listener({- method: "Page.downloadWillBegin",- params: {- guid: "guid-slow",- url: "https://example.test/slow",- suggestedFilename: "slow.txt",- },- });- }+ beginDownload(services, "target-slow", "guid-slow", "slow.txt");const download = await interception.event;const outputDir = await mkdtemp(join(tmpdir(), "ego-download-output-"));const outputPath = join(outputDir, "slow.txt");@@ -133,13 +132,8 @@ test("saveAs waits for an in-progress download", async () => {await new Promise((resolve) => setImmediate(resolve));assert.equal(saved, false);- await writeFile(join(downloadPath, "slow.txt"), "slow contents");- for (const listener of listeners) {- listener({- method: "Page.downloadProgress",- params: { guid: "guid-slow", state: "completed" },- });- }+ await writeFile(join(sharedDirectory, "guid-slow"), "slow contents");+ completeDownload(services, "target-slow", "guid-slow");await save;assert.equal(await readFile(outputPath, "utf8"), "slow contents");@@ -149,44 +143,27 @@ test("saveAs waits for an in-progress download", async () => {});test("saveAs detects a completed file without a final progress event", async () => {- const listeners = new Set();- let downloadPath;+ const services = recordingServices();const interception = preparePageDownload(+ services,+ "target-without-progress",{- async cdp(method, params) {- if (- method === "Page.setDownloadBehavior" &&- params.behavior === "allow"- ) {- downloadPath = params.downloadPath;- }- return {};- },- subscribePageEvents(_targetId, listener) {- listeners.add(listener);- return () => listeners.delete(listener);- },+ timeoutMs: 1_000,},- "target-without-progress",- { timeoutMs: 1_000 },);await interception.ready("session-without-progress");- for (const listener of listeners) {- listener({- method: "Page.downloadWillBegin",- params: {- guid: "guid-without-progress",- url: "https://example.test/without-progress",- suggestedFilename: "without-progress.txt",- },- });- }+ beginDownload(+ services,+ "target-without-progress",+ "guid-without-progress",+ "without-progress.txt",+ );const download = await interception.event;const outputDir = await mkdtemp(join(tmpdir(), "ego-download-output-"));const outputPath = join(outputDir, "without-progress.txt");const save = download.saveAs(outputPath).then(() => "saved");await writeFile(- join(downloadPath, "without-progress.txt"),+ join(sharedDirectory, "guid-without-progress"),"completed without progress",);@@ -202,56 +179,60 @@ test("saveAs detects a completed file without a final progress event", async ()assert.equal(outcome, "saved");});-test("cancel scopes the download guid to its browser context", async () => {- const calls = [];- const listeners = new Set();- let downloadPath;- const interception = preparePageDownload(- {- async cdp(method, params, sessionId) {- calls.push({ method, params, sessionId });- if (- method === "Page.setDownloadBehavior" &&- params.behavior === "allow"- ) {- downloadPath = params.downloadPath;- }- if (method === "Target.getTargetInfo") {- return { targetInfo: { browserContextId: "context-1" } };- }- return {};- },- subscribePageEvents(_targetId, listener) {- listeners.add(listener);- return () => listeners.delete(listener);- },+test("a partial .crdownload file does not complete the download", async () => {+ const services = recordingServices();+ const interception = preparePageDownload(services, "target-partial", {+ timeoutMs: 1_000,+ });+ await interception.ready("session-partial");+ beginDownload(services, "target-partial", "guid-partial", "partial.bin");+ const download = await interception.event;+ const partialPath = join(sharedDirectory, "guid-partial.crdownload");+ await writeFile(partialPath, "partial");+ let state = "pending";+ const path = download.path().then(+ (value) => {+ state = "resolved";+ return value;+ },+ () => {+ state = "rejected";},- "target-1",- { timeoutMs: 1_000 },);++ await new Promise((resolve) => setTimeout(resolve, 200));+ assert.equal(state, "pending", "the intermediate file is not the download");++ await rename(partialPath, join(sharedDirectory, "guid-partial"));+ assert.equal(await path, join(sharedDirectory, "guid-partial"));+ await download.delete();+ disposeDownloadArtifacts();+});++test("cancel scopes the download guid to its browser context", async () => {+ const services = recordingServices();+ services.cdp = async (method, params, sessionId) => {+ services.calls.push({ method, params, sessionId });+ if (method === "Target.getTargetInfo") {+ return { targetInfo: { browserContextId: "context-1" } };+ }+ return {};+ };+ const interception = preparePageDownload(services, "target-1", {+ timeoutMs: 1_000,+ });await interception.ready("session-1");- for (const listener of listeners) {- listener({- method: "Page.downloadWillBegin",- params: {- guid: "guid-cancel",- url: "https://example.test/archive",- suggestedFilename: "archive.zip",- },- });- }+ beginDownload(services, "target-1", "guid-cancel", "archive.zip");const download = await interception.event;await download.cancel();- for (const listener of listeners) {- listener({- method: "Page.downloadProgress",- params: { guid: "guid-cancel", state: "canceled" },- });- }+ services.listeners.get("target-1")({+ method: "Page.downloadProgress",+ params: { guid: "guid-cancel", state: "canceled" },+ });assert(- calls.some(+ services.calls.some((call) =>call.method === "Browser.cancelDownload" &&call.params.guid === "guid-cancel" &&@@ -260,27 +241,20 @@ test("cancel scopes the download guid to its browser context", async () => {),);assert.equal(- calls.some((call) => call.method === "Browser.setDownloadBehavior"),+ services.calls.some(+ (call) => call.method === "Browser.setDownloadBehavior",+ ),false,);assert.equal(await download.failure(), "canceled");await assert.rejects(download.path(), /download failed: canceled/);await download.delete();- await assert.rejects(access(downloadPath));+ await assert.rejects(access(join(sharedDirectory, "guid-cancel")));disposeDownloadArtifacts();});-test("one target cannot arm two download directories at the same time", async () => {- const listeners = new Set();- const services = {- async cdp() {- return {};- },- subscribePageEvents(_targetId, listener) {- listeners.add(listener);- return () => listeners.delete(listener);- },- };+test("one target cannot arm two download waits at the same time", async () => {+ const services = recordingServices();const first = preparePageDownload(services, "target-shared", {timeoutMs: 1_000,});@@ -298,107 +272,71 @@ test("one target cannot arm two download directories at the same time", async ()disposeDownloadArtifacts();});-test("different targets download concurrently into isolated directories", async () => {- const listeners = new Map();- const downloadPaths = new Map();- const services = {- async cdp(method, params, sessionId) {- if (- method === "Page.setDownloadBehavior" &&- params.behavior === "allow"- ) {- downloadPaths.set(sessionId, params.downloadPath);- }- return {};- },- subscribePageEvents(targetId, listener) {- listeners.set(targetId, listener);- return () => listeners.delete(targetId);- },- };+test("different targets download concurrently into the shared directory under their own guids", async () => {+ const services = recordingServices();const first = preparePageDownload(services, "target-a", {timeoutMs: 1_000,});const second = preparePageDownload(services, "target-b", {timeoutMs: 1_000,});- await Promise.all([first.ready("session-a"), second.ready("session-b")]);- assert.notEqual(- downloadPaths.get("session-a"),- downloadPaths.get("session-b"),+ await first.ready("session-a");+ // The first download starts before the second Page arms, so Chromium+ // determines its target under whichever setting is current: identical.+ beginDownload(services, "target-a", "guid-a", "a.txt");+ await second.ready("session-b");+ beginDownload(services, "target-b", "guid-b", "b.txt");+ const armed = services.calls.filter(+ (call) => call.method === "Page.setDownloadBehavior",+ );+ assert.deepEqual(+ armed.map((call) => call.params),+ [+ { behavior: "allowAndName", downloadPath: sharedDirectory },+ { behavior: "allowAndName", downloadPath: sharedDirectory },+ ],+ "every Page applies the same shared setting",);- listeners.get("target-a")({- method: "Page.downloadWillBegin",- params: {- guid: "guid-a",- url: "https://example.test/a",- suggestedFilename: "a.txt",- },- });- listeners.get("target-b")({- method: "Page.downloadWillBegin",- params: {- guid: "guid-b",- url: "https://example.test/b",- suggestedFilename: "b.txt",- },- });const [downloadA, downloadB] = await Promise.all([first.event, second.event]);await Promise.all([- writeFile(join(downloadPaths.get("session-a"), "a.txt"), "contents-a"),- writeFile(join(downloadPaths.get("session-b"), "b.txt"), "contents-b"),+ writeFile(join(sharedDirectory, "guid-a"), "contents-a"),+ writeFile(join(sharedDirectory, "guid-b"), "contents-b"),]);- listeners.get("target-b")({- method: "Page.downloadProgress",- params: { guid: "guid-b", state: "completed" },- });- listeners.get("target-a")({- method: "Page.downloadProgress",- params: { guid: "guid-a", state: "completed" },- });+ completeDownload(services, "target-b", "guid-b");+ completeDownload(services, "target-a", "guid-a");assert.equal(await readFile(await downloadA.path(), "utf8"), "contents-a");assert.equal(await readFile(await downloadB.path(), "utf8"), "contents-b");+ assert.equal(+ behaviorCalls(services.calls).filter((call) => call.behavior === "default")+ .length,+ 1,+ "only the last waiter restores the default behavior",+ );await Promise.all([downloadA.delete(), downloadB.delete()]);disposeDownloadArtifacts();});test("a download wait times out and restores the Page default", async () => {- const calls = [];- const interception = preparePageDownload(- {- async cdp(method, params, sessionId) {- calls.push({ method, params, sessionId });- return {};- },- subscribePageEvents() {- return () => {};- },- },- "target-timeout",- { timeoutMs: 5 },- );+ const services = recordingServices();+ const interception = preparePageDownload(services, "target-timeout", {+ timeoutMs: 5,+ });await interception.ready("session-timeout");await assert.rejects(interception.event,/page\.waitForEvent\("download"\) timed out after 5ms/,);- assert(- calls.some(- (call) =>- call.method === "Page.setDownloadBehavior" &&- call.params.behavior === "default" &&- call.sessionId === "session-timeout",- ),- );+ assert.deepEqual(behaviorCalls(services.calls).at(-1), {+ behavior: "default",+ sessionId: "session-timeout",+ });disposeDownloadArtifacts();});test("the target stays reserved until its Page behavior is restored", async () => {- const listeners = new Set();- let downloadPath;let restoreDefault;let markRestoreStarted;const restoreStarted = new Promise((resolve) => {@@ -407,50 +345,30 @@ test("the target stays reserved until its Page behavior is restored", async () =const defaultRestored = new Promise((resolve) => {restoreDefault = resolve;});- const services = {- async cdp(method, params) {- if (- method === "Page.setDownloadBehavior" &&- params.behavior === "allow"- ) {- downloadPath = params.downloadPath;- }- if (- method === "Page.setDownloadBehavior" &&- params.behavior === "default"- ) {- markRestoreStarted();- await defaultRestored;- }- return {};- },- subscribePageEvents(_targetId, listener) {- listeners.add(listener);- return () => listeners.delete(listener);- },+ const services = recordingServices();+ services.cdp = async (method, params) => {+ if (+ method === "Page.setDownloadBehavior" &&+ params.behavior === "default"+ ) {+ markRestoreStarted();+ await defaultRestored;+ }+ return {};};const first = preparePageDownload(services, "target-restoring", {timeoutMs: 1_000,});await first.ready("session-restoring");- for (const listener of listeners) {- listener({- method: "Page.downloadWillBegin",- params: {- guid: "guid-restoring",- url: "https://example.test/restoring",- suggestedFilename: "restoring.txt",- },- });- }+ beginDownload(+ services,+ "target-restoring",+ "guid-restoring",+ "restoring.txt",+ );const download = await first.event;- await writeFile(join(downloadPath, "restoring.txt"), "restored");- for (const listener of listeners) {- listener({- method: "Page.downloadProgress",- params: { guid: "guid-restoring", state: "completed" },- });- }+ await writeFile(join(sharedDirectory, "guid-restoring"), "restored");+ completeDownload(services, "target-restoring", "guid-restoring");const completed = download.failure();await restoreStarted;@@ -469,76 +387,119 @@ test("the target stays reserved until its Page behavior is restored", async () =});void next.event.catch(() => {});await next.dispose();+ await download.delete();disposeDownloadArtifacts();});-test("a finished download hands the shared behavior to a still-armed target", async () => {- const calls = [];- const listeners = new Map();- const services = {- async cdp(method, params, sessionId) {- calls.push({ method, params, sessionId });- return {};- },- subscribePageEvents(targetId, listener) {- listeners.set(targetId, listener);- return () => listeners.delete(targetId);- },- };+test("a finished download keeps the shared behavior while another target still waits", async () => {+ const services = recordingServices();const first = preparePageDownload(services, "target-a", { timeoutMs: 1_000 });const second = preparePageDownload(services, "target-b", {timeoutMs: 1_000,});await first.ready("session-a");await second.ready("session-b");- const pathA = calls.find((c) => c.sessionId === "session-a").params- .downloadPath;- const pathB = calls.find((c) => c.sessionId === "session-b").params- .downloadPath;- listeners.get("target-a")({- method: "Page.downloadWillBegin",- params: {- guid: "guid-a",- url: "https://example.test/a",- suggestedFilename: "a.txt",- },- });+ beginDownload(services, "target-a", "guid-a", "a.txt");const downloadA = await first.event;- await writeFile(join(pathA, "a.txt"), "contents-a");- listeners.get("target-a")({- method: "Page.downloadProgress",- params: { guid: "guid-a", state: "completed" },- });+ await writeFile(join(sharedDirectory, "guid-a"), "contents-a");+ completeDownload(services, "target-a", "guid-a");await downloadA.path();- const afterFinish = calls.filter(- (c) =>- c.method === "Page.setDownloadBehavior" && c.sessionId !== "session-a",- );- assert.deepEqual(- afterFinish.at(-1),- {- method: "Page.setDownloadBehavior",- params: { behavior: "allow", downloadPath: pathB },- sessionId: "session-b",- },- "finishing the first download re-applies the second target's directory",- );assert.equal(- calls.some(- (c) => c.sessionId === "session-a" && c.params.behavior === "default",- ),+ behaviorCalls(services.calls).some((call) => call.behavior === "default"),false,- "the shared behavior is not reset to default while another target waits",+ "the shared behavior is not reset while another target waits",);+ await access(waiterMarker(process.pid));await second.dispose();- assert.equal(- calls.at(-1).params.behavior,- "default",- "the last interception to go restores the default behavior",+ assert.deepEqual(+ behaviorCalls(services.calls).at(-1),+ { behavior: "default", sessionId: "session-b" },+ "the last waiter to go restores the default behavior",);await downloadA.delete();disposeDownloadArtifacts();});++test("the default behavior waits for a live waiter in another process", async () => {+ // The test runner's parent process stands in for another ego-browser round.+ const foreignMarker = waiterMarker(process.ppid);+ await writeFile(foreignMarker, JSON.stringify({ pid: process.ppid }));+ const services = recordingServices();+ const interception = preparePageDownload(services, "target-foreign", {+ timeoutMs: 1_000,+ });+ await interception.ready("session-foreign");+ beginDownload(services, "target-foreign", "guid-foreign", "foreign.txt");+ const download = await interception.event;+ await writeFile(join(sharedDirectory, "guid-foreign"), "foreign");+ completeDownload(services, "target-foreign", "guid-foreign");+ await download.path();++ assert.equal(+ behaviorCalls(services.calls).some((call) => call.behavior === "default"),+ false,+ "another process still waits, so the behavior stays",+ );+ await assert.rejects(+ access(waiterMarker(process.pid)),+ "this process still removes its own marker",+ );+ await access(foreignMarker);+ await rm(foreignMarker, { force: true });+ await download.delete();+ disposeDownloadArtifacts();+});++test("a marker left by a dead process does not block the default behavior", async () => {+ const exited = spawnSync(process.execPath, ["-e", ""], { encoding: "utf8" });+ assert.equal(exited.status, 0);+ const staleMarker = waiterMarker(exited.pid);+ await writeFile(staleMarker, JSON.stringify({ pid: exited.pid }));+ const services = recordingServices();+ const interception = preparePageDownload(services, "target-stale", {+ timeoutMs: 1_000,+ });+ await interception.ready("session-stale");+ beginDownload(services, "target-stale", "guid-stale", "stale.txt");+ const download = await interception.event;+ await writeFile(join(sharedDirectory, "guid-stale"), "stale");+ completeDownload(services, "target-stale", "guid-stale");+ await download.path();++ assert.deepEqual(behaviorCalls(services.calls).at(-1), {+ behavior: "default",+ sessionId: "session-stale",+ });+ await assert.rejects(access(staleMarker), "the stale marker is removed");+ await download.delete();+ disposeDownloadArtifacts();+});++test("disposing the SDK removes only this process's download files", async () => {+ const services = recordingServices();+ const interception = preparePageDownload(services, "target-dispose", {+ timeoutMs: 1_000,+ });+ await interception.ready("session-dispose");+ beginDownload(services, "target-dispose", "guid-dispose", "dispose.txt");+ await interception.event;+ const ownPartial = join(sharedDirectory, "guid-dispose.crdownload");+ const foreignFile = join(sharedDirectory, "guid-of-another-process");+ await writeFile(ownPartial, "partial");+ await writeFile(foreignFile, "theirs");++ disposeDownloadArtifacts();++ await assert.rejects(access(ownPartial));+ await assert.rejects(access(waiterMarker(process.pid)));+ assert.equal(await readFile(foreignFile, "utf8"), "theirs");+ await access(sharedDirectory);+ await rm(foreignFile, { force: true });+});++test.after(async () => {+ await rm(stateDir, { recursive: true, force: true });+});diff --git a/package/ego-browser/src/driver/downloads.ts b/package/ego-browser/src/driver/downloads.tsindex ced8603..0d6883b 100644--- a/package/ego-browser/src/driver/downloads.ts+++ b/package/ego-browser/src/driver/downloads.ts@@ -1,7 +1,14 @@-import { mkdtempSync, rmSync } from "node:fs";-import { copyFile, mkdir, readdir, rm } from "node:fs/promises";-import { tmpdir } from "node:os";+import {+ type Dirent,+ mkdirSync,+ readdirSync,+ rmSync,+ statSync,+ writeFileSync,+} from "node:fs";+import { copyFile, mkdir, rm, stat } from "node:fs/promises";import { dirname, isAbsolute, join } from "node:path";+import { runtimeStateDir } from "../env.js";type DownloadServices = {cdp(@@ -35,21 +42,41 @@ export type DownloadInterception = {dispose(reason?: Error): Promise<void>;};-const artifactDirectories = new Set<string>();+// Chromium keeps one download behavior per BrowserContext, and every ego lite+// TaskSpace shares one context, so Page.setDownloadBehavior from any Page, in+// any ego-browser process, overrides the others: the most recent call wins+// and "default" from one Page strips the directory from everyone. Downloads+// therefore all use the same directory with Chromium's `allowAndName`+// behavior, which names each file after its download guid. Re-applying the+// identical setting is harmless, and a waiter finds its own file by guid no+// matter which Page armed last. The behavior goes back to default only when+// no process on this machine still waits for a download.+const WAITERS_DIRECTORY = "waiters";+const STALE_WAITER_MS = 60 * 60 * 1_000;+const STALE_FILE_MS = 24 * 60 * 60 * 1_000;+const FILE_POLL_INTERVAL_MS = 50;++let sharedDirectory: string | undefined;+const ownedFiles = new Set<string>();+const armedInterceptions = new Set<symbol>();const activeInterceptions = new Set<() => void>();const activeDownloadTargets = new Set<string>();-// Page.setDownloadBehavior is applied to the shared browser context, so the-// most recently armed interception wins. Remember every armed interception so-// that one finishing can hand the behavior back to another that still waits,-// instead of resetting to default underneath it.-const armedDownloadBehaviors = new Map<- string,- { sessionId: string; downloadPath: string }->();/**- * Arm one Page session for its next download without changing the shared- * Chromium BrowserContext download behavior.+ * The directory every ego-browser process on this machine downloads into.+ * Files are named after their Chromium download guid.+ */+export function downloadDirectory(): string {+ if (sharedDirectory) return sharedDirectory;+ const directory = join(runtimeStateDir(), "downloads");+ mkdirSync(join(directory, WAITERS_DIRECTORY), { recursive: true });+ removeStaleFiles(directory);+ sharedDirectory = directory;+ return directory;+}++/**+ * Arm one Page session for its next download.*/export function preparePageDownload(services: DownloadServices,@@ -60,11 +87,10 @@ export function preparePageDownload(throw new Error(`${targetId} is already waiting for a download`);}activeDownloadTargets.add(targetId);- const directory = mkdtempSync(join(tmpdir(), "ego-browser-download-"));- artifactDirectories.add(directory);- const directoryPromise = Promise.resolve(directory);+ const token = Symbol(targetId);const configuredSessions = new Set<string>();let guid: string | undefined;+ let filePath: string | undefined;let disposed = false;let settled = false;let filePollTimer: ReturnType<typeof setTimeout> | undefined;@@ -80,24 +106,13 @@ export function preparePageDownload(resolveCompletion = resolve;});- const resetBehavior = async () => {+ // Decide synchronously whether this waiter was the last one, and send the+ // reset in the same tick, so a `ready()` that follows in this process always+ // sends its setting after the reset.+ const restoreBehavior = async () => {const sessions = [...configuredSessions];configuredSessions.clear();- armedDownloadBehaviors.delete(targetId);- const stillArmed = [...armedDownloadBehaviors.values()].at(-1);- if (stillArmed) {- // Another Page is still waiting for its download: re-apply its- // directory rather than resetting the shared behavior to default.- await services- .cdp(- "Page.setDownloadBehavior",- { behavior: "allow", downloadPath: stillArmed.downloadPath },- stillArmed.sessionId,- 1_000,- )- .catch(() => {});- return;- }+ if (!releaseSharedBehavior(token)) return;await Promise.all(sessions.map((sessionId) =>services@@ -118,28 +133,34 @@ export function preparePageDownload(if (filePollTimer) clearTimeout(filePollTimer);unsubscribe();activeInterceptions.delete(disposeSynchronously);- await resetBehavior();+ await restoreBehavior();activeDownloadTargets.delete(targetId);resolveCompletion(result);};+ // Chromium writes `<guid>.crdownload` and renames it to `<guid>` once the+ // download completes, so the final name appearing is the completion signal+ // even when the final progress event never arrives.const checkForDownloadedFile = async () => {filePollTimer = undefined;- if (disposed || settled || !guid) return;+ if (disposed || settled || !filePath) return;try {- const path = await directoryPromise.then(findDownloadedFile);- if (path) {- await finish({ path, failure: null });+ await stat(filePath);+ } catch (error) {+ if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {+ scheduleFileCheck();return;}- } catch (error) {await finish({ failure: asError(error).message });return;}- scheduleFileCheck();+ await finish({ path: filePath, failure: null });};const scheduleFileCheck = () => {if (disposed || settled || filePollTimer) return;- filePollTimer = setTimeout(() => void checkForDownloadedFile(), 50);+ filePollTimer = setTimeout(+ () => void checkForDownloadedFile(),+ FILE_POLL_INTERVAL_MS,+ );};const onEvent = (message: any) => {const params = message?.params;@@ -152,6 +173,8 @@ export function preparePageDownload(return;}guid = params.guid;+ filePath = join(downloadDirectory(), params.guid);+ ownedFiles.add(filePath);clearTimeout(timer);resolveEvent(new PageDownloadArtifact(@@ -160,7 +183,7 @@ export function preparePageDownload(params.guid,params.url,params.suggestedFilename,- directoryPromise,+ filePath,completion,),);@@ -186,7 +209,7 @@ export function preparePageDownload(if (filePollTimer) clearTimeout(filePollTimer);unsubscribe();activeDownloadTargets.delete(targetId);- void resetBehavior();+ void restoreBehavior();rejectEvent(new Error("download waiter was disposed"));resolveCompletion({ failure: "download waiter was disposed" });};@@ -197,7 +220,7 @@ export function preparePageDownload(unsubscribe();activeInterceptions.delete(disposeSynchronously);void (async () => {- await resetBehavior();+ await restoreBehavior();activeDownloadTargets.delete(targetId);rejectEvent(new Error(@@ -205,7 +228,6 @@ export function preparePageDownload(),);resolveCompletion({ failure: "download did not start" });- await directoryPromise.then(removeArtifactDirectory);})();}, timeoutMs);@@ -214,14 +236,14 @@ export function preparePageDownload(if (disposed || settled) {throw new Error("download waiter is no longer active");}- const downloadPath = await directoryPromise;+ const downloadPath = downloadDirectory();+ claimSharedBehavior(token);await services.cdp("Page.setDownloadBehavior",- { behavior: "allow", downloadPath },+ { behavior: "allowAndName", downloadPath },sessionId,);configuredSessions.add(sessionId);- armedDownloadBehaviors.set(targetId, { sessionId, downloadPath });},event,async dispose(reason = new Error("download waiter was disposed")) {@@ -231,11 +253,10 @@ export function preparePageDownload(if (filePollTimer) clearTimeout(filePollTimer);unsubscribe();activeInterceptions.delete(disposeSynchronously);- await resetBehavior();+ await restoreBehavior();activeDownloadTargets.delete(targetId);rejectEvent(reason);resolveCompletion({ failure: reason.message });- await directoryPromise.then(removeArtifactDirectory);},};}@@ -247,7 +268,7 @@ class PageDownloadArtifact implements DownloadArtifact {readonly #services: DownloadServices;readonly #targetId: string;readonly #guid: string;- readonly #directory: Promise<string>;+ readonly #filePath: string;readonly #completion: Promise<DownloadCompletion>;#completionResult?: DownloadCompletion;@@ -257,7 +278,7 @@ class PageDownloadArtifact implements DownloadArtifact {guid: string,url: string,suggestedFilename: string,- directory: Promise<string>,+ filePath: string,completion: Promise<DownloadCompletion>,) {this.#services = services;@@ -265,7 +286,7 @@ class PageDownloadArtifact implements DownloadArtifact {this.#guid = guid;this.url = url;this.suggestedFilename = suggestedFilename;- this.#directory = directory;+ this.#filePath = filePath;this.#completion = completion;this.finished = completion.then((result) => {this.#completionResult = result;@@ -310,28 +331,95 @@ class PageDownloadArtifact implements DownloadArtifact {async delete(): Promise<void> {await this.#completion;- await removeArtifactDirectory(await this.#directory);+ ownedFiles.delete(this.#filePath);+ await rm(this.#filePath, { force: true });}}-async function findDownloadedFile(- directory: string,-): Promise<string | undefined> {- const entries = await readdir(directory, { withFileTypes: true });- const files = entries.filter(- (entry) => entry.isFile() && !entry.name.endsWith(".crdownload"),- );- if (files.length > 1) {- throw new Error(- `download completed with ${files.length} files in its temporary directory`,+// Every process that waits for a download leaves `waiters/<pid>` in the shared+// directory while it waits. The last live waiter restores the default+// behavior; the others leave it alone so their downloads keep landing here.+function claimSharedBehavior(token: symbol): void {+ armedInterceptions.add(token);+ try {+ writeFileSync(+ waiterMarkerPath(),+ JSON.stringify({ pid: process.pid, since: Date.now() }),);+ } catch {+ // A read-only state directory only loses cross-process coordination.}- return files.length === 1 ? join(directory, files[0].name) : undefined;}-async function removeArtifactDirectory(directory: string): Promise<void> {- artifactDirectories.delete(directory);- await rm(directory, { recursive: true, force: true });+function releaseSharedBehavior(token: symbol): boolean {+ armedInterceptions.delete(token);+ if (armedInterceptions.size > 0) return false;+ rmSync(waiterMarkerPath(), { force: true });+ return !hasOtherLiveWaiter();+}++function waiterMarkerPath(): string {+ return join(downloadDirectory(), WAITERS_DIRECTORY, String(process.pid));+}++function hasOtherLiveWaiter(): boolean {+ const waitersDirectory = join(downloadDirectory(), WAITERS_DIRECTORY);+ let names: string[];+ try {+ names = readdirSync(waitersDirectory);+ } catch {+ return false;+ }+ const now = Date.now();+ for (const name of names) {+ const path = join(waitersDirectory, name);+ const pid = Number(name);+ if (pid === process.pid) continue;+ let stale = !Number.isInteger(pid) || !isProcessAlive(pid);+ if (!stale) {+ try {+ stale = now - statSync(path).mtimeMs > STALE_WAITER_MS;+ } catch {+ continue;+ }+ }+ if (stale) {+ rmSync(path, { force: true });+ continue;+ }+ return true;+ }+ return false;+}++function isProcessAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return (error as NodeJS.ErrnoException)?.code === "EPERM";+ }+}++// Files a process could not clean up (a crash mid-download) would otherwise+// stay forever; anything older than a day is nobody's pending download.+function removeStaleFiles(directory: string): void {+ let entries: Dirent[];+ try {+ entries = readdirSync(directory, { withFileTypes: true });+ } catch {+ return;+ }+ const cutoff = Date.now() - STALE_FILE_MS;+ for (const entry of entries) {+ if (!entry.isFile()) continue;+ const path = join(directory, entry.name);+ try {+ if (statSync(path).mtimeMs < cutoff) rmSync(path, { force: true });+ } catch {+ // Another process may have removed it first.+ }+ }}function assertAbsolutePath(path: string, method: string): void {@@ -344,13 +432,18 @@ function asError(error: unknown): Error {return error instanceof Error ? error : new Error(String(error));}-/** Remove round-local files and stop pending waits during SDK disposal. */+/** Remove this process's download files and stop pending waits during SDK disposal. */export function disposeDownloadArtifacts(): void {for (const dispose of [...activeInterceptions]) dispose();activeInterceptions.clear();activeDownloadTargets.clear();- for (const directory of artifactDirectories) {- rmSync(directory, { recursive: true, force: true });+ if (armedInterceptions.size > 0) {+ armedInterceptions.clear();+ if (sharedDirectory) rmSync(waiterMarkerPath(), { force: true });+ }+ for (const path of ownedFiles) {+ rmSync(path, { force: true });+ rmSync(`${path}.crdownload`, { force: true });}- artifactDirectories.clear();+ ownedFiles.clear();}diff --git a/package/ego-browser/src/env.ts b/package/ego-browser/src/env.tsindex d20af3b..8486573 100644--- a/package/ego-browser/src/env.ts+++ b/package/ego-browser/src/env.ts@@ -1,5 +1,6 @@import { existsSync } from "node:fs";-import { dirname, resolve } from "node:path";+import { homedir } from "node:os";+import { dirname, join, resolve } from "node:path";import { loadEnvFile as loadNodeEnvFile } from "node:process";import { fileURLToPath } from "node:url";@@ -19,6 +20,17 @@ export function agentWorkspace() {return resolve(REPO_ROOT, "..", "..", "skills", "ego-browser");}+/**+ * Root of the per-user state ego-browser keeps between rounds: Page ledgers+ * and the shared download directory.+ */+export function runtimeStateDir() {+ return resolvePath(+ process.env.EGO_BROWSER_STATE_DIR ||+ join(homedir(), ".ego-browser", "state"),+ );+}+function resolvePath(path) {if (path.startsWith("~")) {return resolve(diff --git a/package/ego-browser/src/page-ledger.ts b/package/ego-browser/src/page-ledger.tsindex 9659479..3a5ab36 100644--- a/package/ego-browser/src/page-ledger.ts+++ b/package/ego-browser/src/page-ledger.ts@@ -8,9 +8,9 @@ import {stat,writeFile,} from "node:fs/promises";-import { homedir } from "node:os";import { join } from "node:path";import { setTimeout as sleep } from "node:timers/promises";+import { runtimeStateDir } from "./env.js";import {validatePageRefState,type PageRefState,@@ -130,10 +130,7 @@ export class PageLedgerStore {#cleanup?: Promise<void>;constructor(options: PageLedgerStoreOptions = {}) {- this.rootDir =- options.rootDir ||- process.env.EGO_BROWSER_STATE_DIR ||- join(homedir(), ".ego-browser", "state");+ this.rootDir = options.rootDir || runtimeStateDir();this.#browserInstanceId = options.browserInstanceId;this.#staleAfterMs =options.staleAfterMs === undefineddiff --git a/package/ego-browser/src/sdk-lifecycle.test.mjs b/package/ego-browser/src/sdk-lifecycle.test.mjsindex 2355306..5f9ccbc 100644--- a/package/ego-browser/src/sdk-lifecycle.test.mjs+++ b/package/ego-browser/src/sdk-lifecycle.test.mjs@@ -1,6 +1,9 @@import test from "node:test";import assert from "node:assert/strict";import { spawnSync } from "node:child_process";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";test("disposeEgoSdk releases native callbacks and rejects pending CDP work", () => {const sdkUrl = new URL("../dist/src/index.js", import.meta.url).href;@@ -12,6 +15,7 @@ test("disposeEgoSdk releases native callbacks and rejects pending CDP work", ()).href;const script = `const { existsSync } = await import("node:fs");+ const { join } = await import("node:path");globalThis.ego = {respond: true,sendCDPMessage(payload) {@@ -43,12 +47,14 @@ test("disposeEgoSdk releases native callbacks and rejects pending CDP work", ()void downloadWait.event.catch(() => {});await downloadWait.ready("session-download");if (!existsSync(downloadPath)) throw new Error("download directory was not created");+ const waiterMarker = join(downloadPath, "waiters", String(process.pid));+ if (!existsSync(waiterMarker)) throw new Error("download waiter marker was not created");await sdk.disposeEgoSdk();if (ego.onCDPMessage !== undefined || ego.onSendCDPMessageError !== undefined) {throw new Error("disposeEgoSdk left native callbacks installed");}- if (existsSync(downloadPath)) {- throw new Error("disposeEgoSdk left temporary downloads behind");+ if (existsSync(waiterMarker)) {+ throw new Error("disposeEgoSdk left its download waiter marker behind");}await pending.then(() => { throw new Error("pending CDP work unexpectedly resolved"); },@@ -58,16 +64,22 @@ test("disposeEgoSdk releases native callbacks and rejects pending CDP work", ());process.stderr.write("sdk lifecycle ok");`;- const result = spawnSync(- process.execPath,- ["--input-type=module", "--eval", script],- {- encoding: "utf8",- },- );+ const stateDir = mkdtempSync(join(tmpdir(), "ego-sdk-lifecycle-state-"));+ try {+ const result = spawnSync(+ process.execPath,+ ["--input-type=module", "--eval", script],+ {+ encoding: "utf8",+ env: { ...process.env, EGO_BROWSER_STATE_DIR: stateDir },+ },+ );- assert.equal(result.status, 0, result.stderr);- assert.match(result.stderr, /sdk lifecycle ok/);+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stderr, /sdk lifecycle ok/);+ } finally {+ rmSync(stateDir, { recursive: true, force: true });+ }});test("the embedded SDK explains that browser globals belong inside Page.evaluate", () => {