From 5ab6e6f47b632722ec81e7d952d0818756ea81d8 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 13:05:40 +0900 Subject: [PATCH 01/26] docs(electron): list waitForDownload's no-inspector failure waitForDownload reads the app's downloads in the main process, so an app that opened no inspector fails it with UNSUPPORTED_CAPABILITY, as electron.evaluate does. Its Throws table left that out. Co-Authored-By: Claude Opus 5.5 --- docs/reference/electron.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/reference/electron.mdx b/docs/reference/electron.mdx index 4768325d94..67103e2ad7 100644 --- a/docs/reference/electron.mdx +++ b/docs/reference/electron.mdx @@ -479,6 +479,7 @@ expect(file.suggestedFilename).toBe('report.csv'); | `INVALID_ARGUMENT` | `trigger` is not a function. | | `ACTION_FAILED` | No download finished in time. The message is `no download finished within ms of the trigger`. | | `ENGINE_FAILURE` | The download ended without completing, such as one the app cancelled. | +| `UNSUPPORTED_CAPABILITY` | The main process opened no inspector, as a packaged app built with the `EnableNodeCliInspectArguments` fuse off does: the engine reads the app's downloads there. | #### `onDialog` From 25b056a1e0abe8cb0771b054d9ec971e111363b8 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 13:09:11 +0900 Subject: [PATCH 02/26] fix(electron): take no window waitForWindow's trigger opened after its time ran out The wait includes the trigger's own time, as the reference says, but after a slow trigger the poll still got at least a millisecond and looked for a window before it checked the deadline, so a window that opened after the timeout was returned and activated. Start the deadline before the trigger and fail once it has passed. Co-Authored-By: Claude Opus 5.5 --- apps/electron-testbed/tests/sign-in.e2e.ts | 7 +++++++ packages/electron/src/surface.ts | 8 ++++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/apps/electron-testbed/tests/sign-in.e2e.ts b/apps/electron-testbed/tests/sign-in.e2e.ts index e3f0069957..61c5223de1 100644 --- a/apps/electron-testbed/tests/sign-in.e2e.ts +++ b/apps/electron-testbed/tests/sign-in.e2e.ts @@ -386,6 +386,13 @@ test.describe('windows', () => { const none = await electron.waitForWindow(() => Promise.resolve(), { timeout: 500 }).then(() => undefined, (error: unknown) => error); expect(none).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/no window opened within 500ms/) }); expect(await electron.evaluate(() => (globalThis as unknown as { testbedState: { settingsOpened: number } }).testbedState.settingsOpened)).toBe(1); + // The wait includes the trigger's own time: a window the trigger opens after that ran out is not taken. + const late = await electron.waitForWindow(async () => { + await screen.getByRole('button', 'Open settings').tap(); + await new Promise((resolve) => setTimeout(resolve, 800)); + }, { timeout: 500 }).then(() => undefined, (error: unknown) => error); + expect(late).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/no window opened within 500ms; the trigger resolved after \d+ms/) }); + expect(main!.isActive()).toBe(true); }); test('gives a window with no document title the OS window\'s, which is a title it is found by', async ({ app, electron }) => { diff --git a/packages/electron/src/surface.ts b/packages/electron/src/surface.ts index a4c46454a9..fe2d694127 100644 --- a/packages/electron/src/surface.ts +++ b/packages/electron/src/surface.ts @@ -503,19 +503,23 @@ export class ElectronSurface { this.failOnDialog(); if (!this.app.running) throw this.app.notRunning(); const before = new Set(this.windowList.open()); + const deadline = new Deadline(operation.timeoutMs); const started = Date.now(); await trigger(); const triggerMs = Date.now() - started; + const timedOut = (): TestError => new TestError('ACTION_FAILED', `no window opened within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`); + // The wait includes the trigger's own time: a window it opened after that ran out is not taken. + if (deadline.expired()) throw timedOut(); let opened: AppWindow | undefined; await pollCondition({ - deadline: new Deadline(Math.max(1, operation.timeoutMs - triggerMs)), + deadline, signal: operation.signal, negated: false, evaluate: () => { opened = this.windowList.open().find((window) => !before.has(window)); return Promise.resolve(opened !== undefined); }, - onTimeout: () => new TestError('ACTION_FAILED', `no window opened within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`), + onTimeout: timedOut, }); if (opened === undefined) throw invalidState('the window was lost'); await this.activateWindow(opened, operation); From ad7edfc254e2a0211d479638fcaf698203d4399c Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 14:07:30 +0900 Subject: [PATCH 03/26] fix(electron): name waitForDownload where an app with no inspector is described waitForDownload reads the app's downloads in its main process, so it fails on an app built with the EnableNodeCliInspectArguments fuse off. The no-inspector message and the guide's list of what that build loses named electron.evaluate only. Co-Authored-By: Claude Opus 5.5 --- docs/electron.mdx | 5 +++-- packages/electron/src/app-process.ts | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/electron.mdx b/docs/electron.mdx index f1e755647b..dd31936df0 100644 --- a/docs/electron.mdx +++ b/docs/electron.mdx @@ -313,8 +313,9 @@ Forge's default) keeps a launcher of the same name beside its `app-` folders. Name the `.exe` inside the version folder. - If the build disables the `EnableNodeCliInspectArguments` fuse, `screen`, - `expect`, and the agent still work, but `electron.evaluate()` fails and - `electron.window({ title })` matches document titles only. On Windows and + `expect`, and the agent still work, but `electron.evaluate()` and + `electron.waitForDownload()` fail and `electron.window({ title })` matches + document titles only. On Windows and Linux, a screenshot of a window the app hid with `hide()` also times out, and a recording of one has no frames. - On macOS, an unsigned build that reads the keychain (`safeStorage`) can diff --git a/packages/electron/src/app-process.ts b/packages/electron/src/app-process.ts index e0f5d57430..72bff48e8a 100644 --- a/packages/electron/src/app-process.ts +++ b/packages/electron/src/app-process.ts @@ -445,7 +445,7 @@ export class AppProcess { } const NO_INSPECTOR = - 'the app\'s main process opened no inspector, so electron.evaluate cannot run in it and windows are known by their document titles only: a packaged app built with the EnableNodeCliInspectArguments fuse off ignores --inspect'; + 'the app\'s main process opened no inspector, so electron.evaluate and electron.waitForDownload cannot run in it and windows are known by their document titles only: a packaged app built with the EnableNodeCliInspectArguments fuse off ignores --inspect'; /** Ends an app: a graceful quit within `graceMs`, then its process tree killed and waited for. */ async function stop(app: RunningApp, graceMs: number): Promise { From c4c4ecf9acdfb8ffdcf48b0513f73bebefc93b4c Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 14:07:36 +0900 Subject: [PATCH 04/26] docs(electron): say where a download before the first window goes, in the reference too The guide said a download that starts before the app's first window loads goes where the app would save it, but opened with "never", and the waitForDownload reference promised the user-data directory without the exception. The engine places downloads once the first window has loaded. Co-Authored-By: Claude Opus 5.5 --- docs/electron.mdx | 4 ++-- docs/reference/electron.mdx | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/electron.mdx b/docs/electron.mdx index dd31936df0..600e41d47c 100644 --- a/docs/electron.mdx +++ b/docs/electron.mdx @@ -267,8 +267,8 @@ expect(file.suggestedFilename).toBe('report.csv'); // file.absolutePath is the saved file ``` -Downloads never land in your own Downloads folder: the app saves them inside -the test's user-data directory. A name a file there had at launch, or another +The app saves downloads inside the test's user-data directory, not your own +Downloads folder. A name a file there had at launch, or another download took, gets a number, as `note (1).txt`; a file the app writes there itself is not counted. A download that starts before the app's first window loads goes where the app would save it. diff --git a/docs/reference/electron.mdx b/docs/reference/electron.mdx index 67103e2ad7..5d6addb1e7 100644 --- a/docs/reference/electron.mdx +++ b/docs/reference/electron.mdx @@ -470,8 +470,10 @@ expect(file.suggestedFilename).toBe('report.csv'); - It registers the file as a `download` artifact, saved as `downloads/-`, and returns that relative `path`, the `absolutePath` of the saved copy, and `suggestedFilename`. -- Downloads never land in your own Downloads folder: the app saves them in - the `Downloads` folder of the test's [user-data directory](#userdatadir). +- The app saves downloads in the `Downloads` folder of the test's + [user-data directory](#userdatadir), not your own Downloads folder. A + download that starts before the app's first window loads goes where the + app would save it, and `waitForDownload` does not see it. - A trigger that throws fails with its own error. | Throws | When | From bf12a7b08d1b15c3157a05a22c7fdc758546cf70 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 14:10:55 +0900 Subject: [PATCH 05/26] fix(electron): bound waitForWindow's and waitForDownload's triggers by their timeout Both fixtures turn off the harness's timeout for themselves, and awaited the trigger with no bound, so a trigger waiting on something slow held the step until it returned, however short its timeout; waitForDownload then started a fresh timeout for the download. Run each trigger within one deadline for the whole call, as the web engine's waits do: a trigger still running then fails the wait, and the download wait includes the trigger's time too. Co-Authored-By: Claude Opus 5.5 --- apps/electron-testbed/tests/parity.e2e.ts | 7 +++++- apps/electron-testbed/tests/sign-in.e2e.ts | 2 +- docs/reference/electron.mdx | 7 +++--- packages/electron/src/surface.ts | 29 ++++++++++++++++------ 4 files changed, 33 insertions(+), 12 deletions(-) diff --git a/apps/electron-testbed/tests/parity.e2e.ts b/apps/electron-testbed/tests/parity.e2e.ts index 2e93a4ccba..7ca6969d48 100644 --- a/apps/electron-testbed/tests/parity.e2e.ts +++ b/apps/electron-testbed/tests/parity.e2e.ts @@ -50,7 +50,12 @@ test.describe('what an Electron target shares with the web', () => { expect(file.path).toMatch(/^downloads\/\d+-note\.txt$/); expect(readFileSync(file.absolutePath, 'utf8')).toBe('downloaded note'); const none = await electron.waitForDownload(() => Promise.resolve(), { timeout: 500 }).then(() => undefined, (error: unknown) => error); - expect(none).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/no download finished/) }); + expect(none).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/no download finished within 500ms; the trigger resolved after \d+ms/) }); + // The wait includes the trigger's own time: one still running when it is out fails the wait then, not when it returns. + const started = Date.now(); + const slow = await electron.waitForDownload(() => new Promise((resolve) => setTimeout(resolve, 3000)), { timeout: 500 }).then(() => undefined, (error: unknown) => error); + expect(slow).toMatchObject({ code: 'ACTION_FAILED', message: 'electron.waitForDownload exceeded its timeout of 500ms while its trigger ran' }); + expect(Date.now() - started).toBeLessThan(2500); }); test('refuses a tap on a link another element covers, though both sit in a checkbox label', async ({ screen }) => { diff --git a/apps/electron-testbed/tests/sign-in.e2e.ts b/apps/electron-testbed/tests/sign-in.e2e.ts index 61c5223de1..004894bb36 100644 --- a/apps/electron-testbed/tests/sign-in.e2e.ts +++ b/apps/electron-testbed/tests/sign-in.e2e.ts @@ -391,7 +391,7 @@ test.describe('windows', () => { await screen.getByRole('button', 'Open settings').tap(); await new Promise((resolve) => setTimeout(resolve, 800)); }, { timeout: 500 }).then(() => undefined, (error: unknown) => error); - expect(late).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/no window opened within 500ms; the trigger resolved after \d+ms/) }); + expect(late).toMatchObject({ code: 'ACTION_FAILED', message: 'electron.waitForWindow exceeded its timeout of 500ms while its trigger ran' }); expect(main!.isActive()).toBe(true); }); diff --git a/docs/reference/electron.mdx b/docs/reference/electron.mdx index 5d6addb1e7..e1139003f2 100644 --- a/docs/reference/electron.mdx +++ b/docs/reference/electron.mdx @@ -430,7 +430,7 @@ const settings = await electron.waitForWindow(() => | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | `trigger` is not a function. | -| `ACTION_FAILED` | No window opened in time. The message is `no window opened within ms; the trigger resolved after ms`. | +| `ACTION_FAILED` | No window opened in time. The message is `no window opened within ms; the trigger resolved after ms`, or `electron.waitForWindow exceeded its timeout of ms while its trigger ran`. | #### `window` @@ -474,12 +474,13 @@ expect(file.suggestedFilename).toBe('report.csv'); [user-data directory](#userdatadir), not your own Downloads folder. A download that starts before the app's first window loads goes where the app would save it, and `waitForDownload` does not see it. -- A trigger that throws fails with its own error. +- The wait includes the trigger's own time. A trigger that throws fails with + its own error. | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | `trigger` is not a function. | -| `ACTION_FAILED` | No download finished in time. The message is `no download finished within ms of the trigger`. | +| `ACTION_FAILED` | No download finished in time. The message is `no download finished within ms; the trigger resolved after ms`, or `electron.waitForDownload exceeded its timeout of ms while its trigger ran`. | | `ENGINE_FAILURE` | The download ended without completing, such as one the app cancelled. | | `UNSUPPORTED_CAPABILITY` | The main process opened no inspector, as a packaged app built with the `EnableNodeCliInspectArguments` fuse off does: the engine reads the app's downloads there. | diff --git a/packages/electron/src/surface.ts b/packages/electron/src/surface.ts index fe2d694127..1accc3caa7 100644 --- a/packages/electron/src/surface.ts +++ b/packages/electron/src/surface.ts @@ -14,7 +14,7 @@ import { copyFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; -import { ConfigurationError, Deadline, EngineError, pollCondition, sleep, TestError, validateComputedStyleProperties } from '@e2e-dev/core/engine'; +import { ConfigurationError, Deadline, EngineError, pollCondition, sleep, TestError, validateComputedStyleProperties, withTimeout } from '@e2e-dev/core/engine'; import type { ComputedStyleProperty, ComputedStyleValues, @@ -504,9 +504,7 @@ export class ElectronSurface { if (!this.app.running) throw this.app.notRunning(); const before = new Set(this.windowList.open()); const deadline = new Deadline(operation.timeoutMs); - const started = Date.now(); - await trigger(); - const triggerMs = Date.now() - started; + const triggerMs = await runTrigger(trigger, deadline, 'electron.waitForWindow', operation.timeoutMs); const timedOut = (): TestError => new TestError('ACTION_FAILED', `no window opened within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`); // The wait includes the trigger's own time: a window it opened after that ran out is not taken. if (deadline.expired()) throw timedOut(); @@ -591,11 +589,15 @@ export class ElectronSurface { const attempt = this.attempt; if (attempt === undefined) throw invalidState('a download is waited for inside a test'); this.failOnDialog(); + const deadline = new Deadline(operation.timeoutMs); const before = (await this.app.downloads()).length; - await trigger(); + const triggerMs = await runTrigger(trigger, deadline, 'electron.waitForDownload', operation.timeoutMs); + const timedOut = (): TestError => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`); + // The wait includes the trigger's own time, as the window wait's does. + if (deadline.expired()) throw timedOut(); let finished: AppDownload | undefined; await pollCondition({ - deadline: new Deadline(operation.timeoutMs), + deadline, signal: operation.signal, negated: false, evaluate: async () => { @@ -604,7 +606,7 @@ export class ElectronSurface { finished = next; return true; }, - onTimeout: () => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms of the trigger`), + onTimeout: timedOut, }); if (finished === undefined) throw invalidState('the download was lost'); if (finished.state !== 'completed') throw new EngineError('ENGINE_FAILURE', `the download of ${finished.filename} was ${finished.state}`, { retryable: false }); @@ -650,3 +652,16 @@ export class ElectronSurface { return (await recorder?.stop()) ?? []; } } + +/** + * Runs a wait's trigger, test code, within the wait's deadline, and returns + * how long it took. A trigger still running at the deadline fails the wait + * and is left to finish on its own; its error, before then, is its own. + */ +async function runTrigger(trigger: () => Promise, deadline: Deadline, api: string, timeoutMs: number): Promise { + const started = Date.now(); + const running = trigger(); + running.catch(() => undefined); + await withTimeout(running, Math.max(1, deadline.remaining()), () => new TestError('ACTION_FAILED', `${api} exceeded its timeout of ${timeoutMs}ms while its trigger ran`)); + return Date.now() - started; +} From 08408e97bf5b9b16503d7fe96178138ce15f0a3a Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 14:27:26 +0900 Subject: [PATCH 06/26] fix(electron): bound waitForDownload's reads of the app's downloads by its timeout waitForDownload read the download log in the main process before the trigger and on every poll with no bound, so while an app's main process was busy the step waited for it, not for its timeout, and ran the trigger after the timeout had passed. Bound each read by the wait's deadline, and run no trigger once it is out of time. Co-Authored-By: Claude Opus 5.5 --- docs/reference/electron.mdx | 2 +- packages/electron/src/surface.ts | 9 +++++-- .../electron/tests/integration/launch.test.ts | 25 +++++++++++++++++++ 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/docs/reference/electron.mdx b/docs/reference/electron.mdx index e1139003f2..fb6f28cebd 100644 --- a/docs/reference/electron.mdx +++ b/docs/reference/electron.mdx @@ -480,7 +480,7 @@ expect(file.suggestedFilename).toBe('report.csv'); | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | `trigger` is not a function. | -| `ACTION_FAILED` | No download finished in time. The message is `no download finished within ms; the trigger resolved after ms`, or `electron.waitForDownload exceeded its timeout of ms while its trigger ran`. | +| `ACTION_FAILED` | No download finished in time. The message is `no download finished within ms; the trigger resolved after ms`, `electron.waitForDownload exceeded its timeout of ms while its trigger ran`, or `no download finished within ms: the app's main process did not answer` while it is too busy to. | | `ENGINE_FAILURE` | The download ended without completing, such as one the app cancelled. | | `UNSUPPORTED_CAPABILITY` | The main process opened no inspector, as a packaged app built with the `EnableNodeCliInspectArguments` fuse off does: the engine reads the app's downloads there. | diff --git a/packages/electron/src/surface.ts b/packages/electron/src/surface.ts index 1accc3caa7..98c8f7cbe5 100644 --- a/packages/electron/src/surface.ts +++ b/packages/electron/src/surface.ts @@ -590,7 +590,12 @@ export class ElectronSurface { if (attempt === undefined) throw invalidState('a download is waited for inside a test'); this.failOnDialog(); const deadline = new Deadline(operation.timeoutMs); - const before = (await this.app.downloads()).length; + // Read in the main process, which a busy app keeps from answering: each read ends with the wait. + const unanswered = (): TestError => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms: the app's main process did not answer`); + const downloads = (): Promise => withTimeout(this.app.downloads(), Math.max(1, deadline.remaining()), unanswered); + const before = (await downloads()).length; + // A trigger never runs once the wait is out of time. + if (deadline.expired()) throw unanswered(); const triggerMs = await runTrigger(trigger, deadline, 'electron.waitForDownload', operation.timeoutMs); const timedOut = (): TestError => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`); // The wait includes the trigger's own time, as the window wait's does. @@ -601,7 +606,7 @@ export class ElectronSurface { signal: operation.signal, negated: false, evaluate: async () => { - const next = (await this.app.downloads())[before]; + const next = (await downloads())[before]; if (next === undefined || next.state === 'progressing') return false; finished = next; return true; diff --git a/packages/electron/tests/integration/launch.test.ts b/packages/electron/tests/integration/launch.test.ts index 88f397ee2e..3fd53d6c8c 100644 --- a/packages/electron/tests/integration/launch.test.ts +++ b/packages/electron/tests/integration/launch.test.ts @@ -17,6 +17,7 @@ import { DevTools } from '../../src/devtools.ts'; import { ensureFfmpeg } from '../../src/ffmpeg.ts'; import { readWindow } from '../../src/locate.ts'; import { resolveOptions } from '../../src/options.ts'; +import { ElectronSurface } from '../../src/surface.ts'; import { Recorder } from '../../src/video.ts'; import { DialogRouter } from '../../src/dialogs.ts'; import { Windows, type AppWindow } from '../../src/windows.ts'; @@ -327,6 +328,30 @@ describe('dialogs', () => { }); }); +describe('electron.waitForDownload', () => { + it('fails in its time, and runs no trigger, while the app\'s main process is too busy to answer', async () => { + const { app, windows, dialogs, directory, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); + await launch(); + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { app, windowList: windows, dialogs, attempt: { artifactsDir: path.join(directory, 'artifacts') } }); + // The main process loops for four seconds: nothing it is asked is answered until then. + void app.evaluate(() => { + const until = Date.now() + 4000; + while (Date.now() < until); + }, undefined).catch(() => undefined); + let triggered = false; + const operation = { signal: new AbortController().signal, timeoutMs: 1000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; + const started = Date.now(); + const failure = await surface.waitForDownload(() => { + triggered = true; + return Promise.resolve(); + }, operation).then(() => undefined, (error: unknown) => error); + expect(failure).toMatchObject({ code: 'ACTION_FAILED', message: 'no download finished within 1000ms: the app\'s main process did not answer' }); + expect(Date.now() - started).toBeLessThan(2000); + expect(triggered).toBe(false); + }); +}); + describe('electron.evaluate', () => { it('returns a number JSON has no word for, and refuses an argument that is not JSON as the test\'s own mistake', async () => { const { app, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); From 40a98ed2d162b2fbadd1d136d4dfbd2646dfb5ff Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 14:44:03 +0900 Subject: [PATCH 07/26] fix(electron): wait on a trigger that returns no promise runTrigger called .catch() on what the trigger returned, so a trigger written in JavaScript, or one that started a tap without returning it, failed waitForWindow and waitForDownload with a bare TypeError. Await it inside an async function, as the web engine's waits do. Co-Authored-By: Claude Opus 5.5 --- apps/electron-testbed/tests/sign-in.e2e.ts | 5 +++++ packages/electron/src/surface.ts | 3 ++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/electron-testbed/tests/sign-in.e2e.ts b/apps/electron-testbed/tests/sign-in.e2e.ts index 004894bb36..789e10b325 100644 --- a/apps/electron-testbed/tests/sign-in.e2e.ts +++ b/apps/electron-testbed/tests/sign-in.e2e.ts @@ -416,6 +416,11 @@ test.describe('windows', () => { expect(electron.windows()[0]?.isActive()).toBe(true); await expect(screen.getByTestId('status')).toHaveText('Not signed in'); expect(await settings.activate().then(() => undefined, (error: unknown) => error)).toMatchObject({ code: 'ACTION_FAILED' }); + // A trigger that does not return its promise, as JavaScript allows: the window it opens is still waited for. + const unreturned = await electron.waitForWindow((() => { + void screen.getByRole('button', 'Open settings').tap(); + }) as unknown as () => Promise); + expect(await unreturned.title()).toBe('Settings'); }); test('types into a field inside a closed shadow root', async ({ app, screen, electron }) => { diff --git a/packages/electron/src/surface.ts b/packages/electron/src/surface.ts index 98c8f7cbe5..37bd49ddeb 100644 --- a/packages/electron/src/surface.ts +++ b/packages/electron/src/surface.ts @@ -665,7 +665,8 @@ export class ElectronSurface { */ async function runTrigger(trigger: () => Promise, deadline: Deadline, api: string, timeoutMs: number): Promise { const started = Date.now(); - const running = trigger(); + // Test code: a trigger written in JavaScript, or one that does not return its promise, returns none. + const running = (async () => await trigger())(); running.catch(() => undefined); await withTimeout(running, Math.max(1, deadline.remaining()), () => new TestError('ACTION_FAILED', `${api} exceeded its timeout of ${timeoutMs}ms while its trigger ran`)); return Date.now() - started; From 1942e9ee5fce8fddd3194395f9ef0046b50a1faf Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 15:35:44 +0900 Subject: [PATCH 08/26] test(electron): accept either timeout message for a download wait with no trigger With its reads of the downloads bounded, a waitForDownload whose main process takes the whole 500 ms to answer under a parallel run says so rather than how long the trigger took; both are a wait that ran out. Co-Authored-By: Claude Opus 5.5 --- apps/electron-testbed/tests/parity.e2e.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/electron-testbed/tests/parity.e2e.ts b/apps/electron-testbed/tests/parity.e2e.ts index 7ca6969d48..a74fdabeee 100644 --- a/apps/electron-testbed/tests/parity.e2e.ts +++ b/apps/electron-testbed/tests/parity.e2e.ts @@ -50,7 +50,8 @@ test.describe('what an Electron target shares with the web', () => { expect(file.path).toMatch(/^downloads\/\d+-note\.txt$/); expect(readFileSync(file.absolutePath, 'utf8')).toBe('downloaded note'); const none = await electron.waitForDownload(() => Promise.resolve(), { timeout: 500 }).then(() => undefined, (error: unknown) => error); - expect(none).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/no download finished within 500ms; the trigger resolved after \d+ms/) }); + // On a loaded machine the app's main process can take the whole half second to answer, which the message says instead. + expect(none).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/^no download finished within 500ms(; the trigger resolved after \d+ms|: the app's main process did not answer)$/) }); // The wait includes the trigger's own time: one still running when it is out fails the wait then, not when it returns. const started = Date.now(); const slow = await electron.waitForDownload(() => new Promise((resolve) => setTimeout(resolve, 3000)), { timeout: 500 }).then(() => undefined, (error: unknown) => error); From 9747ba0b84b26252449b779e68f1bc4c6232f937 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 15:58:21 +0900 Subject: [PATCH 09/26] fix(electron): run no download trigger for a step cancelled while the app was asked waitForDownload checked its deadline, not its operation's signal, after the first read of the app's downloads, so a step cancelled during that read still ran the test's trigger and read the downloads again. Stop with CANCELLED before the trigger. Co-Authored-By: Claude Opus 5.5 --- packages/electron/src/surface.ts | 3 ++- .../electron/tests/integration/launch.test.ts | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/packages/electron/src/surface.ts b/packages/electron/src/surface.ts index 37bd49ddeb..f79c01b81a 100644 --- a/packages/electron/src/surface.ts +++ b/packages/electron/src/surface.ts @@ -594,7 +594,8 @@ export class ElectronSurface { const unanswered = (): TestError => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms: the app's main process did not answer`); const downloads = (): Promise => withTimeout(this.app.downloads(), Math.max(1, deadline.remaining()), unanswered); const before = (await downloads()).length; - // A trigger never runs once the wait is out of time. + // A trigger never runs once the wait is out of time, or its step was cancelled while the app was asked. + if (operation.signal.aborted) throw new EngineError('CANCELLED', 'electron.waitForDownload was cancelled', { retryable: false }); if (deadline.expired()) throw unanswered(); const triggerMs = await runTrigger(trigger, deadline, 'electron.waitForDownload', operation.timeoutMs); const timedOut = (): TestError => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`); diff --git a/packages/electron/tests/integration/launch.test.ts b/packages/electron/tests/integration/launch.test.ts index 3fd53d6c8c..109f95821d 100644 --- a/packages/electron/tests/integration/launch.test.ts +++ b/packages/electron/tests/integration/launch.test.ts @@ -350,6 +350,23 @@ describe('electron.waitForDownload', () => { expect(Date.now() - started).toBeLessThan(2000); expect(triggered).toBe(false); }); + + it('runs no trigger for a step cancelled while the app was asked for its downloads', async () => { + const { app, windows, dialogs, directory, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); + await launch(); + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { app, windowList: windows, dialogs, attempt: { artifactsDir: path.join(directory, 'artifacts') } }); + const cancel = new AbortController(); + cancel.abort(); + let triggered = false; + const operation = { signal: cancel.signal, timeoutMs: 5000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; + const failure = await surface.waitForDownload(() => { + triggered = true; + return Promise.resolve(); + }, operation).then(() => undefined, (error: unknown) => error); + expect(failure).toMatchObject({ code: 'CANCELLED' }); + expect(triggered).toBe(false); + }); }); describe('electron.evaluate', () => { From cfe97160a5c0af161ccca91287ab4c340d5301a3 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 17:13:03 +0900 Subject: [PATCH 10/26] fix(electron): show no window for a waitForWindow cancelled while its trigger ran activateWindow made the window the shown one before it checked its operation, so a wait cancelled during its trigger rejected with CANCELLED but left the new window shown, and a later teardown step read and acted on it. Check the operation's budget first. Co-Authored-By: Claude Opus 5.5 --- packages/electron/src/surface.ts | 8 ++++++-- .../electron/tests/integration/launch.test.ts | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/packages/electron/src/surface.ts b/packages/electron/src/surface.ts index f79c01b81a..1bf2500e2e 100644 --- a/packages/electron/src/surface.ts +++ b/packages/electron/src/surface.ts @@ -455,8 +455,12 @@ export class ElectronSurface { /** `window.activate()`: reads and acts in the window from now on. */ async activateWindow(window: AppWindow, operation: OperationContext): Promise { this.failOnDialog(); - this.windowList.activate(window); - await withBudget(operation, 'activate window', () => window.page.bringToFront().catch(() => undefined)); + await withBudget(operation, 'activate window', async (budget) => { + // A call cancelled meanwhile (a waitForWindow whose trigger outlasted the step) shows no other window. + budget.check(); + this.windowList.activate(window); + await window.page.bringToFront().catch(() => undefined); + }); } /** `window.close()`: any window, the app's last one too. */ diff --git a/packages/electron/tests/integration/launch.test.ts b/packages/electron/tests/integration/launch.test.ts index 109f95821d..45736dfa57 100644 --- a/packages/electron/tests/integration/launch.test.ts +++ b/packages/electron/tests/integration/launch.test.ts @@ -328,6 +328,25 @@ describe('dialogs', () => { }); }); +describe('electron.waitForWindow', () => { + it('shows no window for a wait cancelled while its trigger ran', async () => { + const { app, windows, dialogs, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); + await launch(); + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { app, windowList: windows, dialogs }); + const first = windows.require(); + const cancel = new AbortController(); + const operation = { signal: cancel.signal, timeoutMs: 5000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; + const failure = await surface.waitForWindow(async () => { + await app.evaluate(({ BrowserWindow }) => void new BrowserWindow({ show: false }).loadURL('data:text/html,Second'), undefined); + await expect.poll(() => windows.open().length).toBe(2); + cancel.abort(); + }, operation).then(() => undefined, (error: unknown) => error); + expect(failure).toMatchObject({ code: 'CANCELLED' }); + expect(windows.current()).toBe(first); + }); +}); + describe('electron.waitForDownload', () => { it('fails in its time, and runs no trigger, while the app\'s main process is too busy to answer', async () => { const { app, windows, dialogs, directory, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); From 6312a81ef647416b2a29fc2ee12edb438f4b2253 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 17:16:41 +0900 Subject: [PATCH 11/26] fix(electron): give no download a name the app took itself in the downloads folder The engine numbered a download against the names in the folder at launch and the ones it gave out. A download the app saved there itself, and a file the app wrote there after launch, were in neither, so the next download of that name was given the same path and replaced it. Take the name of a path the app chose, and look on disk before giving out a name. Co-Authored-By: Claude Opus 5.5 --- packages/electron/src/app-process.ts | 9 +++-- .../electron/tests/integration/launch.test.ts | 33 ++++++++++++++++++- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/packages/electron/src/app-process.ts b/packages/electron/src/app-process.ts index 72bff48e8a..2f9de3a0a0 100644 --- a/packages/electron/src/app-process.ts +++ b/packages/electron/src/app-process.ts @@ -573,11 +573,13 @@ async function placeDownloads(main: MainProcess, directory: string, withinMs: nu electronApp.setPath('downloads', downloads); // Compared without case: two names that differ only in case are one file on macOS and Windows. const taken = new Set(earlier.map((name) => name.toLowerCase())); + // A file the app wrote there itself since launch is taken too; an Electron before getBuiltinModule knows only the list. + const files = (process as { getBuiltinModule?: (id: string) => unknown }).getBuiltinModule?.('node:fs') as { existsSync(file: string): boolean } | undefined; const unique = (name: string): string => { const dot = name.lastIndexOf('.'); const [stem, extension] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, '']; let candidate = name; - for (let count = 1; taken.has(candidate.toLowerCase()); count += 1) candidate = `${stem} (${count})${extension}`; + for (let count = 1; taken.has(candidate.toLowerCase()) || files?.existsSync(`${downloads}/${candidate}`) === true; count += 1) candidate = `${stem} (${count})${extension}`; taken.add(candidate.toLowerCase()); return candidate; }; @@ -588,7 +590,10 @@ async function placeDownloads(main: MainProcess, directory: string, withinMs: nu if (placed.has(target)) return; placed.add(target); target.on('will-download', (_event, item) => { - if (item.getSavePath() === '') item.setSavePath(`${downloads}/${unique(item.getFilename())}`); + const chosen = item.getSavePath(); + if (chosen === '') item.setSavePath(`${downloads}/${unique(item.getFilename())}`); + // A path the app chose is taken, so a later download is not given it. + else taken.add((chosen.split(/[\\/]/).pop() ?? '').toLowerCase()); // What `electron.waitForDownload` reads: each download the app started, and how it ended. const entry = { filename: item.getFilename(), path: item.getSavePath(), state: 'progressing' }; const log = ((globalThis as { e2eDownloads?: (typeof entry)[] }).e2eDownloads ??= []); diff --git a/packages/electron/tests/integration/launch.test.ts b/packages/electron/tests/integration/launch.test.ts index 45736dfa57..78a34712af 100644 --- a/packages/electron/tests/integration/launch.test.ts +++ b/packages/electron/tests/integration/launch.test.ts @@ -5,7 +5,7 @@ import { execFileSync, spawnSync } from 'node:child_process'; import { Transformer } from '@napi-rs/image'; -import { existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; @@ -425,6 +425,37 @@ describe('downloads', () => { await expect.poll(() => (existsSync(downloads) ? readdirSync(downloads) : [])).toContain('later.txt'); expect(existsSync(path.join(launched.directory, 'outside', 'later.txt'))).toBe(false); }); + + it.skipIf(process.platform === 'win32')('numbers a download whose name the app took itself, by a download or a file written after launch', async () => { + const launched = appWith(`let first = true; + app.whenReady().then(() => { + require('electron').session.defaultSession.on('will-download', (_event, item) => { + // The app saves its first download itself, under the name it suggests. + if (first) item.setSavePath(require('node:path').join(app.getPath('downloads'), item.getFilename())); + first = false; + }); + const server = require('node:http').createServer((request, response) => { + if (request.url === '/') return response.end('Loaded'); + response.setHeader('Content-Disposition', 'attachment; filename="' + request.url.slice(1) + '"'); + response.end(request.url); + }); + server.listen(0, '127.0.0.1', () => new BrowserWindow({ show: false }).loadURL('http://127.0.0.1:' + server.address().port + '/')); + });`); + await launched.launch(); + const origin = new URL(launched.windows.require().page.url()).origin; + const downloads = path.join(launched.directory, 'data', 'Downloads'); + const download = async (name: string, expected: string): Promise => { + await launched.app.evaluate(({ BrowserWindow }, url) => BrowserWindow.getAllWindows()[0]?.webContents.downloadURL(url), `${origin}/${name}`); + await expect.poll(() => (existsSync(downloads) ? readdirSync(downloads).toSorted() : [])).toContain(expected); + }; + await download('report.txt', 'report.txt'); + await download('report.txt', 'report (1).txt'); + // A file the app wrote there itself after launch. + writeFileSync(path.join(downloads, 'notes.txt'), 'the app\'s own'); + await download('notes.txt', 'notes (1).txt'); + expect(readFileSync(path.join(downloads, 'report.txt'), 'utf8')).toBe('/report.txt'); + expect(readFileSync(path.join(downloads, 'notes.txt'), 'utf8')).toBe('the app\'s own'); + }); }); describe('an app with no inspector', () => { From 772ab2381e3628d1d2bcf54238aad4efabe0c55e Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 17:31:05 +0900 Subject: [PATCH 12/26] docs(electron): say a download is numbered around a file the app wrote itself The guide said a file the app writes into its downloads folder is not counted; since 613f95dfc the engine looks on disk (through process.getBuiltinModule, Node 20.16 in Electron 32 and later) and numbers a download around it. Co-Authored-By: Claude Opus 5.5 --- docs/electron.mdx | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/electron.mdx b/docs/electron.mdx index 600e41d47c..da86756a34 100644 --- a/docs/electron.mdx +++ b/docs/electron.mdx @@ -268,10 +268,11 @@ expect(file.suggestedFilename).toBe('report.csv'); ``` The app saves downloads inside the test's user-data directory, not your own -Downloads folder. A name a file there had at launch, or another -download took, gets a number, as `note (1).txt`; a file the app writes there -itself is not counted. A download that starts before the app's first window -loads goes where the app would save it. +Downloads folder. A download whose name a file there already has gets a +number, as `note (1).txt`: a file that was there at launch, one the app wrote +or saved there itself, or another download. An Electron older than 32 knows +only the files there at launch and the downloads. A download that starts +before the app's first window loads goes where the app would save it. ## Record video From 371d30994acd665c80c78676cfc89348655c8d63 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 17:33:22 +0900 Subject: [PATCH 13/26] fix(electron): end a window or download wait as cancelled when its step is cancelled during the trigger runTrigger raced the trigger against the wait's deadline only, so a step cancelled while its trigger still ran held both waits open until their timeout and then failed them with ACTION_FAILED. Race it against the operation's signal too: the wait ends at once, as CANCELLED. Co-Authored-By: Claude Opus 5.5 --- packages/electron/src/surface.ts | 11 ++++++----- packages/electron/tests/integration/launch.test.ts | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/packages/electron/src/surface.ts b/packages/electron/src/surface.ts index 1bf2500e2e..b1deeb6f59 100644 --- a/packages/electron/src/surface.ts +++ b/packages/electron/src/surface.ts @@ -14,7 +14,7 @@ import { copyFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; -import { ConfigurationError, Deadline, EngineError, pollCondition, sleep, TestError, validateComputedStyleProperties, withTimeout } from '@e2e-dev/core/engine'; +import { ConfigurationError, Deadline, EngineError, pollCondition, raceAbort, sleep, TestError, validateComputedStyleProperties, withTimeout } from '@e2e-dev/core/engine'; import type { ComputedStyleProperty, ComputedStyleValues, @@ -508,7 +508,7 @@ export class ElectronSurface { if (!this.app.running) throw this.app.notRunning(); const before = new Set(this.windowList.open()); const deadline = new Deadline(operation.timeoutMs); - const triggerMs = await runTrigger(trigger, deadline, 'electron.waitForWindow', operation.timeoutMs); + const triggerMs = await runTrigger(trigger, deadline, 'electron.waitForWindow', operation); const timedOut = (): TestError => new TestError('ACTION_FAILED', `no window opened within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`); // The wait includes the trigger's own time: a window it opened after that ran out is not taken. if (deadline.expired()) throw timedOut(); @@ -601,7 +601,7 @@ export class ElectronSurface { // A trigger never runs once the wait is out of time, or its step was cancelled while the app was asked. if (operation.signal.aborted) throw new EngineError('CANCELLED', 'electron.waitForDownload was cancelled', { retryable: false }); if (deadline.expired()) throw unanswered(); - const triggerMs = await runTrigger(trigger, deadline, 'electron.waitForDownload', operation.timeoutMs); + const triggerMs = await runTrigger(trigger, deadline, 'electron.waitForDownload', operation); const timedOut = (): TestError => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`); // The wait includes the trigger's own time, as the window wait's does. if (deadline.expired()) throw timedOut(); @@ -668,11 +668,12 @@ export class ElectronSurface { * how long it took. A trigger still running at the deadline fails the wait * and is left to finish on its own; its error, before then, is its own. */ -async function runTrigger(trigger: () => Promise, deadline: Deadline, api: string, timeoutMs: number): Promise { +async function runTrigger(trigger: () => Promise, deadline: Deadline, api: string, operation: OperationContext): Promise { const started = Date.now(); // Test code: a trigger written in JavaScript, or one that does not return its promise, returns none. const running = (async () => await trigger())(); running.catch(() => undefined); - await withTimeout(running, Math.max(1, deadline.remaining()), () => new TestError('ACTION_FAILED', `${api} exceeded its timeout of ${timeoutMs}ms while its trigger ran`)); + // A step cancelled while its trigger runs ends then, as cancelled, not at its timeout. + await raceAbort(() => withTimeout(running, Math.max(1, deadline.remaining()), () => new TestError('ACTION_FAILED', `${api} exceeded its timeout of ${operation.timeoutMs}ms while its trigger ran`)), operation.signal, api); return Date.now() - started; } diff --git a/packages/electron/tests/integration/launch.test.ts b/packages/electron/tests/integration/launch.test.ts index 78a34712af..ac1ec00cfd 100644 --- a/packages/electron/tests/integration/launch.test.ts +++ b/packages/electron/tests/integration/launch.test.ts @@ -345,6 +345,20 @@ describe('electron.waitForWindow', () => { expect(failure).toMatchObject({ code: 'CANCELLED' }); expect(windows.current()).toBe(first); }); + + it('ends as cancelled, then, when its step is cancelled while its trigger still runs', async () => { + const { app, windows, dialogs, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); + await launch(); + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { app, windowList: windows, dialogs }); + const cancel = new AbortController(); + setTimeout(() => cancel.abort(), 50); + const operation = { signal: cancel.signal, timeoutMs: 2000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; + const started = Date.now(); + const failure = await surface.waitForWindow(() => new Promise(() => undefined), operation).then(() => undefined, (error: unknown) => error); + expect(failure).toMatchObject({ code: 'CANCELLED' }); + expect(Date.now() - started).toBeLessThan(1000); + }); }); describe('electron.waitForDownload', () => { From 69bfadf1c4c0683527560ed9e021260ee7ee4ea0 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 17:56:26 +0900 Subject: [PATCH 14/26] fix(electron): end a download wait as cancelled while it asks a busy main process waitForDownload bounded its reads of the app's downloads by its deadline only, so a step cancelled while a busy main process was asked waited for the deadline and failed with ACTION_FAILED. Race each read against the operation's signal too. Co-Authored-By: Claude Opus 5.5 --- packages/electron/src/surface.ts | 4 +++- .../electron/tests/integration/launch.test.ts | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/packages/electron/src/surface.ts b/packages/electron/src/surface.ts index b1deeb6f59..1f52d1a9a4 100644 --- a/packages/electron/src/surface.ts +++ b/packages/electron/src/surface.ts @@ -596,7 +596,9 @@ export class ElectronSurface { const deadline = new Deadline(operation.timeoutMs); // Read in the main process, which a busy app keeps from answering: each read ends with the wait. const unanswered = (): TestError => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms: the app's main process did not answer`); - const downloads = (): Promise => withTimeout(this.app.downloads(), Math.max(1, deadline.remaining()), unanswered); + // A step cancelled while the app was asked ends then, as cancelled. + const downloads = (): Promise => + raceAbort(() => withTimeout(this.app.downloads(), Math.max(1, deadline.remaining()), unanswered), operation.signal, 'electron.waitForDownload'); const before = (await downloads()).length; // A trigger never runs once the wait is out of time, or its step was cancelled while the app was asked. if (operation.signal.aborted) throw new EngineError('CANCELLED', 'electron.waitForDownload was cancelled', { retryable: false }); diff --git a/packages/electron/tests/integration/launch.test.ts b/packages/electron/tests/integration/launch.test.ts index ac1ec00cfd..193db297c4 100644 --- a/packages/electron/tests/integration/launch.test.ts +++ b/packages/electron/tests/integration/launch.test.ts @@ -384,6 +384,24 @@ describe('electron.waitForDownload', () => { expect(triggered).toBe(false); }); + it('ends as cancelled, at once, when its step is cancelled while the busy main process is asked', async () => { + const { app, windows, dialogs, directory, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); + await launch(); + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { app, windowList: windows, dialogs, attempt: { artifactsDir: path.join(directory, 'artifacts') } }); + void app.evaluate(() => { + const until = Date.now() + 1500; + while (Date.now() < until); + }, undefined).catch(() => undefined); + const cancel = new AbortController(); + setTimeout(() => cancel.abort(), 50); + const operation = { signal: cancel.signal, timeoutMs: 1000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; + const started = Date.now(); + const failure = await surface.waitForDownload(() => Promise.resolve(), operation).then(() => undefined, (error: unknown) => error); + expect(failure).toMatchObject({ code: 'CANCELLED' }); + expect(Date.now() - started).toBeLessThan(500); + }); + it('runs no trigger for a step cancelled while the app was asked for its downloads', async () => { const { app, windows, dialogs, directory, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); await launch(); From e050a7a428817eca43f3a0bc8917b50e873f0261 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 19:28:36 +0900 Subject: [PATCH 15/26] fix(electron): run no window wait's trigger for a step cancelled before it starts Review: runTrigger started the trigger before raceAbort checked the signal, so a step already cancelled still ran test code that can open a window or submit a form, and only then failed as cancelled. The trigger now starts inside raceAbort's work, after its check. Co-Authored-By: Claude Opus 5.5 --- packages/electron/src/surface.ts | 17 ++++++++++++----- .../electron/tests/integration/launch.test.ts | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/packages/electron/src/surface.ts b/packages/electron/src/surface.ts index 1f52d1a9a4..eb0b742dde 100644 --- a/packages/electron/src/surface.ts +++ b/packages/electron/src/surface.ts @@ -672,10 +672,17 @@ export class ElectronSurface { */ async function runTrigger(trigger: () => Promise, deadline: Deadline, api: string, operation: OperationContext): Promise { const started = Date.now(); - // Test code: a trigger written in JavaScript, or one that does not return its promise, returns none. - const running = (async () => await trigger())(); - running.catch(() => undefined); - // A step cancelled while its trigger runs ends then, as cancelled, not at its timeout. - await raceAbort(() => withTimeout(running, Math.max(1, deadline.remaining()), () => new TestError('ACTION_FAILED', `${api} exceeded its timeout of ${operation.timeoutMs}ms while its trigger ran`)), operation.signal, api); + // A step cancelled before its trigger runs never runs it; one cancelled while it runs ends then, as cancelled, not at + // its timeout. + await raceAbort( + () => { + // Test code: a trigger written in JavaScript, or one that does not return its promise, returns none. + const running = (async () => await trigger())(); + running.catch(() => undefined); + return withTimeout(running, Math.max(1, deadline.remaining()), () => new TestError('ACTION_FAILED', `${api} exceeded its timeout of ${operation.timeoutMs}ms while its trigger ran`)); + }, + operation.signal, + api, + ); return Date.now() - started; } diff --git a/packages/electron/tests/integration/launch.test.ts b/packages/electron/tests/integration/launch.test.ts index 193db297c4..2684d17931 100644 --- a/packages/electron/tests/integration/launch.test.ts +++ b/packages/electron/tests/integration/launch.test.ts @@ -359,6 +359,23 @@ describe('electron.waitForWindow', () => { expect(failure).toMatchObject({ code: 'CANCELLED' }); expect(Date.now() - started).toBeLessThan(1000); }); + + it('runs no trigger for a step cancelled before it starts', async () => { + const { app, windows, dialogs, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); + await launch(); + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { app, windowList: windows, dialogs }); + const cancel = new AbortController(); + cancel.abort(); + const operation = { signal: cancel.signal, timeoutMs: 2000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; + let triggered = false; + const failure = await surface.waitForWindow(() => { + triggered = true; + return Promise.resolve(); + }, operation).then(() => undefined, (error: unknown) => error); + expect(failure).toMatchObject({ code: 'CANCELLED' }); + expect(triggered).toBe(false); + }); }); describe('electron.waitForDownload', () => { From 9727ec00248532802df5086d9a7cb0320a9354ac Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 19:29:06 +0900 Subject: [PATCH 16/26] fix(electron): number a download only around names the app took in the downloads folder Review: the engine took the name of every path the app chose for a download, wherever it was, so after the app saved exports/report.txt itself, the next report.txt the engine placed in the downloads folder became report (1).txt. Take the name only when the app's path is in the downloads folder. Co-Authored-By: Claude Opus 5.5 --- packages/electron/src/app-process.ts | 6 ++-- .../electron/tests/integration/launch.test.ts | 28 +++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/packages/electron/src/app-process.ts b/packages/electron/src/app-process.ts index 2f9de3a0a0..293e27dd68 100644 --- a/packages/electron/src/app-process.ts +++ b/packages/electron/src/app-process.ts @@ -575,6 +575,8 @@ async function placeDownloads(main: MainProcess, directory: string, withinMs: nu const taken = new Set(earlier.map((name) => name.toLowerCase())); // A file the app wrote there itself since launch is taken too; an Electron before getBuiltinModule knows only the list. const files = (process as { getBuiltinModule?: (id: string) => unknown }).getBuiltinModule?.('node:fs') as { existsSync(file: string): boolean } | undefined; + // A file's folder, its separators either way round: an app on Windows may write either. + const folderOf = (file: string): string => file.replace(/[\\/][^\\/]*$/, '').replaceAll('\\', '/').toLowerCase(); const unique = (name: string): string => { const dot = name.lastIndexOf('.'); const [stem, extension] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, '']; @@ -592,8 +594,8 @@ async function placeDownloads(main: MainProcess, directory: string, withinMs: nu target.on('will-download', (_event, item) => { const chosen = item.getSavePath(); if (chosen === '') item.setSavePath(`${downloads}/${unique(item.getFilename())}`); - // A path the app chose is taken, so a later download is not given it. - else taken.add((chosen.split(/[\\/]/).pop() ?? '').toLowerCase()); + // A path the app chose in the downloads folder is taken, so a later download is not given it. + else if (folderOf(chosen) === folderOf(`${downloads}/-`)) taken.add((chosen.split(/[\\/]/).pop() ?? '').toLowerCase()); // What `electron.waitForDownload` reads: each download the app started, and how it ended. const entry = { filename: item.getFilename(), path: item.getSavePath(), state: 'progressing' }; const log = ((globalThis as { e2eDownloads?: (typeof entry)[] }).e2eDownloads ??= []); diff --git a/packages/electron/tests/integration/launch.test.ts b/packages/electron/tests/integration/launch.test.ts index 2684d17931..58584dac73 100644 --- a/packages/electron/tests/integration/launch.test.ts +++ b/packages/electron/tests/integration/launch.test.ts @@ -505,6 +505,34 @@ describe('downloads', () => { expect(readFileSync(path.join(downloads, 'report.txt'), 'utf8')).toBe('/report.txt'); expect(readFileSync(path.join(downloads, 'notes.txt'), 'utf8')).toBe('the app\'s own'); }); + + it.skipIf(process.platform === 'win32')('gives a download the name of one the app saved in a folder of its own', async () => { + const launched = appWith(`let first = true; + app.whenReady().then(() => { + require('electron').session.defaultSession.on('will-download', (_event, item) => { + // The app saves its first download itself, in a folder outside the downloads folder. + if (first) item.setSavePath(require('node:path').join(__dirname, 'exports', item.getFilename())); + first = false; + }); + const server = require('node:http').createServer((request, response) => { + if (request.url === '/') return response.end('Loaded'); + response.setHeader('Content-Disposition', 'attachment; filename="' + request.url.slice(1) + '"'); + response.end(request.url); + }); + server.listen(0, '127.0.0.1', () => new BrowserWindow({ show: false }).loadURL('http://127.0.0.1:' + server.address().port + '/')); + });`); + await launched.launch(); + const origin = new URL(launched.windows.require().page.url()).origin; + const downloads = path.join(launched.directory, 'data', 'Downloads'); + const exports = path.join(launched.directory, 'exports'); + const download = async (name: string): Promise => { + await launched.app.evaluate(({ BrowserWindow }, url) => BrowserWindow.getAllWindows()[0]?.webContents.downloadURL(url), `${origin}/${name}`); + }; + await download('report.txt'); + await expect.poll(() => (existsSync(exports) ? readdirSync(exports) : [])).toContain('report.txt'); + await download('report.txt'); + await expect.poll(() => (existsSync(downloads) ? readdirSync(downloads) : [])).toEqual(['report.txt']); + }); }); describe('an app with no inspector', () => { From 8c81353de2e7b83474aca0d9f127168ab1ab4560 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 19:29:14 +0900 Subject: [PATCH 17/26] chore(electron): add a changeset for the window and download wait fixes Co-Authored-By: Claude Opus 5.5 --- .changeset/electron-window-download-waits.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/electron-window-download-waits.md diff --git a/.changeset/electron-window-download-waits.md b/.changeset/electron-window-download-waits.md new file mode 100644 index 0000000000..45cf22d10e --- /dev/null +++ b/.changeset/electron-window-download-waits.md @@ -0,0 +1,5 @@ +--- +'@e2e-dev/electron': patch +--- + +`electron.waitForWindow()` and `electron.waitForDownload()` count their trigger's time in their timeout, as `browser.waitForPopup()` and `browser.waitForDownload()` do: a trigger that hangs fails the wait at its timeout, and a window or download that arrives after it is not taken. A wait whose step is cancelled ends as `CANCELLED` at once, runs no trigger when cancelled before it starts, and shows no window it opened. A download wait also ends in its time while the app's main process is too busy to answer. A download the engine saves is numbered around a file of that name the app wrote in the downloads folder itself, rather than replacing it. From a418b54d58594aeadc9a2481cddf271df8bb420a Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 19:37:38 +0900 Subject: [PATCH 18/26] docs(electron): keep the download naming rules in the reference only The guide and the reference both described where downloads go; the guide now says it in one sentence and links the rules. Co-Authored-By: Claude Opus 5.5 --- docs/electron.mdx | 7 ++----- docs/reference/electron.mdx | 8 ++++++-- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/electron.mdx b/docs/electron.mdx index da86756a34..b5676ed5c4 100644 --- a/docs/electron.mdx +++ b/docs/electron.mdx @@ -268,11 +268,8 @@ expect(file.suggestedFilename).toBe('report.csv'); ``` The app saves downloads inside the test's user-data directory, not your own -Downloads folder. A download whose name a file there already has gets a -number, as `note (1).txt`: a file that was there at launch, one the app wrote -or saved there itself, or another download. An Electron older than 32 knows -only the files there at launch and the downloads. A download that starts -before the app's first window loads goes where the app would save it. +Downloads folder, and numbers a name already taken there, as `note (1).txt` +([details](/reference/electron#waitfordownload)). ## Record video diff --git a/docs/reference/electron.mdx b/docs/reference/electron.mdx index fb6f28cebd..9c019b8272 100644 --- a/docs/reference/electron.mdx +++ b/docs/reference/electron.mdx @@ -472,8 +472,12 @@ expect(file.suggestedFilename).toBe('report.csv'); `absolutePath` of the saved copy, and `suggestedFilename`. - The app saves downloads in the `Downloads` folder of the test's [user-data directory](#userdatadir), not your own Downloads folder. A - download that starts before the app's first window loads goes where the - app would save it, and `waitForDownload` does not see it. + download whose name is taken there gets a number, as `note (1).txt`: by a + file there at launch, one the app wrote or saved there itself, or another + download. An Electron older than 32 knows only the files there at launch + and the downloads. A download that starts before the app's first window + loads goes where the app would save it, and `waitForDownload` does not see + it. - The wait includes the trigger's own time. A trigger that throws fails with its own error. From 59091afc86fab5a9e1fa99e2cd87e4c9444ed631 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 23:13:20 +0900 Subject: [PATCH 19/26] fix(electron): show no window for a step cancelled while the window is raised Review: activateWindow made the window the one screen reads before it awaited bringToFront, so a step cancelled during that call still left the new window active. It now raises the window first, checks the budget again, and changes the window list last. Co-Authored-By: Claude Opus 5.5 --- packages/electron/src/surface.ts | 6 +++-- .../electron/tests/integration/launch.test.ts | 24 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/packages/electron/src/surface.ts b/packages/electron/src/surface.ts index eb0b742dde..2e2233e016 100644 --- a/packages/electron/src/surface.ts +++ b/packages/electron/src/surface.ts @@ -456,10 +456,12 @@ export class ElectronSurface { async activateWindow(window: AppWindow, operation: OperationContext): Promise { this.failOnDialog(); await withBudget(operation, 'activate window', async (budget) => { - // A call cancelled meanwhile (a waitForWindow whose trigger outlasted the step) shows no other window. + // A call cancelled meanwhile (a waitForWindow whose trigger outlasted the step) shows no other window, one cancelled + // while the window is raised included: the window `screen` reads changes last. budget.check(); - this.windowList.activate(window); await window.page.bringToFront().catch(() => undefined); + budget.check(); + this.windowList.activate(window); }); } diff --git a/packages/electron/tests/integration/launch.test.ts b/packages/electron/tests/integration/launch.test.ts index 58584dac73..468ea2a4a8 100644 --- a/packages/electron/tests/integration/launch.test.ts +++ b/packages/electron/tests/integration/launch.test.ts @@ -346,6 +346,30 @@ describe('electron.waitForWindow', () => { expect(windows.current()).toBe(first); }); + it('shows no window for a wait cancelled while the window is brought to the front', async () => { + const { app, windows, dialogs, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); + await launch(); + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { app, windowList: windows, dialogs }); + const first = windows.require(); + const cancel = new AbortController(); + const operation = { signal: cancel.signal, timeoutMs: 5000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; + const failure = await surface.waitForWindow(async () => { + await app.evaluate(({ BrowserWindow }) => void new BrowserWindow({ show: false }).loadURL('data:text/html,Second'), undefined); + await expect.poll(() => windows.open().length).toBe(2); + const second = windows.open()[1]!; + // The step is cancelled while the engine raises the new window. + Object.assign(second.page, { + bringToFront: () => { + cancel.abort(); + return Promise.resolve(); + }, + }); + }, operation).then(() => undefined, (error: unknown) => error); + expect(failure).toMatchObject({ code: 'CANCELLED' }); + expect(windows.current()).toBe(first); + }); + it('ends as cancelled, then, when its step is cancelled while its trigger still runs', async () => { const { app, windows, dialogs, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); await launch(); From 0337141fa993c3eb2cc194ebf98be5b369cb4fd4 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 23:13:31 +0900 Subject: [PATCH 20/26] test(electron-testbed): accept the busy-main-process message for the slow download trigger Review: the slow-trigger waitForDownload reads the app's downloads before it runs the trigger, and that read shares the 500ms timeout. On a loaded machine the read can use all of it and the wait ends with the documented main-process message, which the assertion above it already accepts. Co-Authored-By: Claude Opus 5.5 --- apps/electron-testbed/tests/parity.e2e.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/electron-testbed/tests/parity.e2e.ts b/apps/electron-testbed/tests/parity.e2e.ts index a74fdabeee..b5a2eeefa6 100644 --- a/apps/electron-testbed/tests/parity.e2e.ts +++ b/apps/electron-testbed/tests/parity.e2e.ts @@ -55,7 +55,8 @@ test.describe('what an Electron target shares with the web', () => { // The wait includes the trigger's own time: one still running when it is out fails the wait then, not when it returns. const started = Date.now(); const slow = await electron.waitForDownload(() => new Promise((resolve) => setTimeout(resolve, 3000)), { timeout: 500 }).then(() => undefined, (error: unknown) => error); - expect(slow).toMatchObject({ code: 'ACTION_FAILED', message: 'electron.waitForDownload exceeded its timeout of 500ms while its trigger ran' }); + // The read before the trigger shares that half second, so a loaded machine can end the wait there too. + expect(slow).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/^(electron\.waitForDownload exceeded its timeout of 500ms while its trigger ran|no download finished within 500ms: the app's main process did not answer)$/) }); expect(Date.now() - started).toBeLessThan(2500); }); From 893e2c899a1b2020e7d34272d1f7d0d979d59fc2 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 23:13:31 +0900 Subject: [PATCH 21/26] test(electron-testbed): say what the late waitForWindow case checks Review: the comment said the window opened after the time ran out, but the trigger taps first and opens the window in time, then outlasts the wait. The test checks that such a window is not taken, which main did take; the comment now says so. Co-Authored-By: Claude Opus 5.5 --- apps/electron-testbed/tests/sign-in.e2e.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/electron-testbed/tests/sign-in.e2e.ts b/apps/electron-testbed/tests/sign-in.e2e.ts index 789e10b325..956b9ecfa0 100644 --- a/apps/electron-testbed/tests/sign-in.e2e.ts +++ b/apps/electron-testbed/tests/sign-in.e2e.ts @@ -386,7 +386,8 @@ test.describe('windows', () => { const none = await electron.waitForWindow(() => Promise.resolve(), { timeout: 500 }).then(() => undefined, (error: unknown) => error); expect(none).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/no window opened within 500ms/) }); expect(await electron.evaluate(() => (globalThis as unknown as { testbedState: { settingsOpened: number } }).testbedState.settingsOpened)).toBe(1); - // The wait includes the trigger's own time: a window the trigger opens after that ran out is not taken. + // The wait includes the trigger's own time: a trigger still running when it ran out fails the wait, and the window + // it opened before then is not taken. const late = await electron.waitForWindow(async () => { await screen.getByRole('button', 'Open settings').tap(); await new Promise((resolve) => setTimeout(resolve, 800)); From a6535dd9b5d2eed20014aa7e3e82361058bb1231 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Sun, 29 Nov 2026 23:13:58 +0900 Subject: [PATCH 22/26] docs(electron): say which downloads the engine places and numbers Review: the guide said every download goes to the test's user-data directory, and the reference numbered every download whose name was taken. Neither holds for a path the app sets in its own will-download handler, which the engine leaves as it is, or, in the guide, for a download before the first window loads. Both pages now name those exceptions. Co-Authored-By: Claude Opus 5.5 --- docs/electron.mdx | 7 ++++--- docs/reference/electron.mdx | 17 +++++++++-------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/docs/electron.mdx b/docs/electron.mdx index b5676ed5c4..e67d16e99f 100644 --- a/docs/electron.mdx +++ b/docs/electron.mdx @@ -267,9 +267,10 @@ expect(file.suggestedFilename).toBe('report.csv'); // file.absolutePath is the saved file ``` -The app saves downloads inside the test's user-data directory, not your own -Downloads folder, and numbers a name already taken there, as `note (1).txt` -([details](/reference/electron#waitfordownload)). +Downloads go inside the test's user-data directory, not your own Downloads +folder, unless the app picks the path itself or the download starts before its +first window loads. A name already taken there gets a number, as +`note (1).txt` ([details](/reference/electron#waitfordownload)). ## Record video diff --git a/docs/reference/electron.mdx b/docs/reference/electron.mdx index 9c019b8272..63046409c4 100644 --- a/docs/reference/electron.mdx +++ b/docs/reference/electron.mdx @@ -470,14 +470,15 @@ expect(file.suggestedFilename).toBe('report.csv'); - It registers the file as a `download` artifact, saved as `downloads/-`, and returns that relative `path`, the `absolutePath` of the saved copy, and `suggestedFilename`. -- The app saves downloads in the `Downloads` folder of the test's - [user-data directory](#userdatadir), not your own Downloads folder. A - download whose name is taken there gets a number, as `note (1).txt`: by a - file there at launch, one the app wrote or saved there itself, or another - download. An Electron older than 32 knows only the files there at launch - and the downloads. A download that starts before the app's first window - loads goes where the app would save it, and `waitForDownload` does not see - it. +- The engine saves a download in the `Downloads` folder of the test's + [user-data directory](#userdatadir), not your own Downloads folder. A name + already taken there gets a number, as `note (1).txt`: by a file there at + launch, one the app wrote or saved there itself, or another download. An + Electron older than 32 knows only the files there at launch and the + downloads. A path the app sets in its own `will-download` handler stays as + the app set it, with no number. A download that starts before the app's + first window loads goes where the app would save it, and `waitForDownload` + does not see it. - The wait includes the trigger's own time. A trigger that throws fails with its own error. From e9ba4f066a55cae7b1374d17b1fef60078d5cb3a Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Mon, 30 Nov 2026 01:13:06 +0900 Subject: [PATCH 23/26] fix(electron): word a cancelled waitForDownload the same on every path Review nit: the check after the first read of the app's downloads threw "electron.waitForDownload was cancelled", while raceAbort, which ends the same wait on the same cancel, says "electron.waitForDownload cancelled". Both now read the raceAbort way, and the cancellation tests pin the message. Co-Authored-By: Claude Opus 5.5 --- packages/electron/src/surface.ts | 3 ++- packages/electron/tests/integration/launch.test.ts | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/electron/src/surface.ts b/packages/electron/src/surface.ts index 2e2233e016..043876679f 100644 --- a/packages/electron/src/surface.ts +++ b/packages/electron/src/surface.ts @@ -603,7 +603,8 @@ export class ElectronSurface { raceAbort(() => withTimeout(this.app.downloads(), Math.max(1, deadline.remaining()), unanswered), operation.signal, 'electron.waitForDownload'); const before = (await downloads()).length; // A trigger never runs once the wait is out of time, or its step was cancelled while the app was asked. - if (operation.signal.aborted) throw new EngineError('CANCELLED', 'electron.waitForDownload was cancelled', { retryable: false }); + // Worded as raceAbort words the same cancel. + if (operation.signal.aborted) throw new EngineError('CANCELLED', 'electron.waitForDownload cancelled', { retryable: false }); if (deadline.expired()) throw unanswered(); const triggerMs = await runTrigger(trigger, deadline, 'electron.waitForDownload', operation); const timedOut = (): TestError => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`); diff --git a/packages/electron/tests/integration/launch.test.ts b/packages/electron/tests/integration/launch.test.ts index 468ea2a4a8..d4ccf56ed3 100644 --- a/packages/electron/tests/integration/launch.test.ts +++ b/packages/electron/tests/integration/launch.test.ts @@ -439,7 +439,7 @@ describe('electron.waitForDownload', () => { const operation = { signal: cancel.signal, timeoutMs: 1000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; const started = Date.now(); const failure = await surface.waitForDownload(() => Promise.resolve(), operation).then(() => undefined, (error: unknown) => error); - expect(failure).toMatchObject({ code: 'CANCELLED' }); + expect(failure).toMatchObject({ code: 'CANCELLED', message: 'electron.waitForDownload cancelled' }); expect(Date.now() - started).toBeLessThan(500); }); @@ -456,7 +456,7 @@ describe('electron.waitForDownload', () => { triggered = true; return Promise.resolve(); }, operation).then(() => undefined, (error: unknown) => error); - expect(failure).toMatchObject({ code: 'CANCELLED' }); + expect(failure).toMatchObject({ code: 'CANCELLED', message: 'electron.waitForDownload cancelled' }); expect(triggered).toBe(false); }); }); From 539067fdab44c5fe5adb829a7ae3125750367de9 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Mon, 30 Nov 2026 18:36:56 +0900 Subject: [PATCH 24/26] fix(electron): time out a download wait whose last read the deadline cut short as no download The last read of waitForDownload's poll starts at the deadline and gets a millisecond to answer. Its timeout was the main-process message, an ACTION_FAILED the poll does not read as a read the deadline cut off, so a responsive app that started no download could fail with "the app's main process did not answer". The read now times out as OPERATION_TIMEOUT, which pollCondition ends with the ordinary no-download timeout when the read started with under a tick left; a read that timed out with time to answer in still says the main process did not answer. The testbed's no-download case now requires the ordinary message, and a separate case holds the main-process message for a busy main process. Co-Authored-By: Claude Opus 5.5 --- apps/electron-testbed/tests/parity.e2e.ts | 18 ++++++++-- packages/electron/src/surface.ts | 13 ++++--- .../electron/tests/unit/download-wait.test.ts | 36 +++++++++++++++++++ 3 files changed, 60 insertions(+), 7 deletions(-) create mode 100644 packages/electron/tests/unit/download-wait.test.ts diff --git a/apps/electron-testbed/tests/parity.e2e.ts b/apps/electron-testbed/tests/parity.e2e.ts index b5a2eeefa6..f15338d181 100644 --- a/apps/electron-testbed/tests/parity.e2e.ts +++ b/apps/electron-testbed/tests/parity.e2e.ts @@ -49,9 +49,9 @@ test.describe('what an Electron target shares with the web', () => { expect(file.suggestedFilename).toBe('note.txt'); expect(file.path).toMatch(/^downloads\/\d+-note\.txt$/); expect(readFileSync(file.absolutePath, 'utf8')).toBe('downloaded note'); - const none = await electron.waitForDownload(() => Promise.resolve(), { timeout: 500 }).then(() => undefined, (error: unknown) => error); - // On a loaded machine the app's main process can take the whole half second to answer, which the message says instead. - expect(none).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/^no download finished within 500ms(; the trigger resolved after \d+ms|: the app's main process did not answer)$/) }); + // A second leaves a loaded machine's main process time to answer the read before the trigger. + const none = await electron.waitForDownload(() => Promise.resolve(), { timeout: 1000 }).then(() => undefined, (error: unknown) => error); + expect(none).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/^no download finished within 1000ms; the trigger resolved after \d+ms$/) }); // The wait includes the trigger's own time: one still running when it is out fails the wait then, not when it returns. const started = Date.now(); const slow = await electron.waitForDownload(() => new Promise((resolve) => setTimeout(resolve, 3000)), { timeout: 500 }).then(() => undefined, (error: unknown) => error); @@ -60,6 +60,18 @@ test.describe('what an Electron target shares with the web', () => { expect(Date.now() - started).toBeLessThan(2500); }); + test('says the app did not answer when its main process is too busy to list its downloads', async ({ electron }) => { + // The main process loops for two seconds once this call has returned. + await electron.evaluate(() => { + setTimeout(() => { + const until = Date.now() + 2000; + while (Date.now() < until); + }, 0); + }); + const blocked = await electron.waitForDownload(() => Promise.resolve(), { timeout: 500 }).then(() => undefined, (error: unknown) => error); + expect(blocked).toMatchObject({ code: 'ACTION_FAILED', message: 'no download finished within 500ms: the app\'s main process did not answer' }); + }); + test('refuses a tap on a link another element covers, though both sit in a checkbox label', async ({ screen }) => { const refused = await screen.getByTestId('more-info').tap({ timeout: 800 }).then(() => undefined, (error: unknown) => error); expect(refused).toMatchObject({ code: 'ACTION_FAILED' }); diff --git a/packages/electron/src/surface.ts b/packages/electron/src/surface.ts index 043876679f..740ee9592c 100644 --- a/packages/electron/src/surface.ts +++ b/packages/electron/src/surface.ts @@ -596,12 +596,16 @@ export class ElectronSurface { if (attempt === undefined) throw invalidState('a download is waited for inside a test'); this.failOnDialog(); const deadline = new Deadline(operation.timeoutMs); - // Read in the main process, which a busy app keeps from answering: each read ends with the wait. const unanswered = (): TestError => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms: the app's main process did not answer`); + // Read in the main process, which a busy app keeps from answering: each read ends with the wait. Its timeout is an + // operation timeout, which the poll takes for a read the deadline cut off when it started with under a tick left. + const readTimedOut = (): EngineError => new EngineError('OPERATION_TIMEOUT', 'electron.waitForDownload: the app\'s main process did not answer', { retryable: false }); // A step cancelled while the app was asked ends then, as cancelled. const downloads = (): Promise => - raceAbort(() => withTimeout(this.app.downloads(), Math.max(1, deadline.remaining()), unanswered), operation.signal, 'electron.waitForDownload'); - const before = (await downloads()).length; + raceAbort(() => withTimeout(this.app.downloads(), Math.max(1, deadline.remaining()), readTimedOut), operation.signal, 'electron.waitForDownload'); + // Any other read that timed out had time to answer in: the main process did not. + const blocked = (cause: unknown): unknown => (cause instanceof EngineError && cause.code === 'OPERATION_TIMEOUT' ? unanswered() : cause); + const before = (await downloads().catch((cause: unknown) => Promise.reject(blocked(cause)))).length; // A trigger never runs once the wait is out of time, or its step was cancelled while the app was asked. // Worded as raceAbort words the same cancel. if (operation.signal.aborted) throw new EngineError('CANCELLED', 'electron.waitForDownload cancelled', { retryable: false }); @@ -611,6 +615,7 @@ export class ElectronSurface { // The wait includes the trigger's own time, as the window wait's does. if (deadline.expired()) throw timedOut(); let finished: AppDownload | undefined; + // The last read starts at the deadline with almost no time: the poll ends that one with the ordinary timeout. await pollCondition({ deadline, signal: operation.signal, @@ -622,7 +627,7 @@ export class ElectronSurface { return true; }, onTimeout: timedOut, - }); + }).catch((cause: unknown) => Promise.reject(blocked(cause))); if (finished === undefined) throw invalidState('the download was lost'); if (finished.state !== 'completed') throw new EngineError('ENGINE_FAILURE', `the download of ${finished.filename} was ${finished.state}`, { retryable: false }); this.artifactCounter += 1; diff --git a/packages/electron/tests/unit/download-wait.test.ts b/packages/electron/tests/unit/download-wait.test.ts new file mode 100644 index 0000000000..6791d78280 --- /dev/null +++ b/packages/electron/tests/unit/download-wait.test.ts @@ -0,0 +1,36 @@ +import type { OperationContext } from '@e2e-dev/core/engine'; +import { describe, expect, it } from 'vitest'; +import type { AppDownload } from '../../src/app-process.ts'; +import { resolveOptions } from '../../src/options.ts'; +import { ElectronSurface } from '../../src/surface.ts'; + +/** A surface mid-attempt whose app lists its downloads through `downloads`. */ +function surfaceWith(downloads: () => Promise): ElectronSurface { + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { attempt: { artifactsDir: '/nonexistent' } }); + Object.assign(Reflect.get(surface, 'app') as object, { downloads }); + return surface; +} + +const operation = (timeoutMs: number): OperationContext => ({ signal: new AbortController().signal, timeoutMs, runId: 'run', attemptId: 'attempt', origin: 'test' }) as OperationContext; + +describe('electron.waitForDownload with no download', () => { + it('times out as no download, not as an app that did not answer, when the app answers each read in a few milliseconds', async () => { + // The last read starts at the deadline, with a millisecond to answer in: fewer than this app takes. + const surface = surfaceWith(() => new Promise((resolve) => setTimeout(() => resolve([]), 5))); + await expect(surface.waitForDownload(() => Promise.resolve(), operation(300))).rejects.toMatchObject({ + code: 'ACTION_FAILED', + message: expect.stringMatching(/^no download finished within 300ms; the trigger resolved after \d+ms$/), + }); + }); + + it('says the app did not answer when a read with time left gets no answer', async () => { + let reads = 0; + // The first read answers; every later one hangs, as a main process stuck in a loop does. + const surface = surfaceWith(() => (reads++ === 0 ? Promise.resolve([]) : new Promise(() => undefined))); + await expect(surface.waitForDownload(() => Promise.resolve(), operation(300))).rejects.toMatchObject({ + code: 'ACTION_FAILED', + message: 'no download finished within 300ms: the app\'s main process did not answer', + }); + }); +}); From 07c95621cf2953dfd8fcad4c1e7aa55999e3b007 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Mon, 30 Nov 2026 18:39:50 +0900 Subject: [PATCH 25/26] test(electron): number a download around a name the app took before its file is on disk The existing collision test numbers the second download after the first file is written, which the disk check alone covers: it still passed with the reservation of an app-chosen name removed. This case keeps the app's first download unfinished and removes its file (Electron writes it as soon as the app names it, even paused), so only the reservation can give the second download "report (1).txt". It fails with the reservation removed. Co-Authored-By: Claude Opus 5.5 --- .../electron/tests/integration/launch.test.ts | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/packages/electron/tests/integration/launch.test.ts b/packages/electron/tests/integration/launch.test.ts index d4ccf56ed3..07719a4645 100644 --- a/packages/electron/tests/integration/launch.test.ts +++ b/packages/electron/tests/integration/launch.test.ts @@ -530,6 +530,40 @@ describe('downloads', () => { expect(readFileSync(path.join(downloads, 'notes.txt'), 'utf8')).toBe('the app\'s own'); }); + it.skipIf(process.platform === 'win32')('numbers a download whose name the app took for one still downloading, with no file of that name on disk', async () => { + const launched = appWith(`let first = true; + app.whenReady().then(() => { + require('electron').session.defaultSession.on('will-download', (_event, item) => { + // The app saves its first download itself, under the name it suggests. + if (first) item.setSavePath(require('node:path').join(app.getPath('downloads'), item.getFilename())); + first = false; + }); + const server = require('node:http').createServer((request, response) => { + if (request.url === '/') return response.end('Loaded'); + response.setHeader('Content-Disposition', 'attachment; filename="report.txt"'); + if (request.url === '/now') return response.end('now'); + // The first download never finishes: Chromium starts a download once it has a kilobyte of the body. + response.write(' '.repeat(2048)); + }); + server.listen(0, '127.0.0.1', () => new BrowserWindow({ show: false }).loadURL('http://127.0.0.1:' + server.address().port + '/')); + });`); + await launched.launch(); + const origin = new URL(launched.windows.require().page.url()).origin; + const downloads = path.join(launched.directory, 'data', 'Downloads'); + const download = (route: string): Promise => launched.app.evaluate(({ BrowserWindow }, url) => BrowserWindow.getAllWindows()[0]?.webContents.downloadURL(url), `${origin}${route}`); + const placed = async (): Promise => (await launched.app.downloads()).map(({ path: saved, state }) => [path.basename(saved), state]); + await download('/held'); + await expect.poll(placed).toEqual([['report.txt', 'progressing']]); + // Chromium writes the file as soon as the app names it, so it is removed: only the name the app took is left to number around. + rmSync(path.join(downloads, 'report.txt')); + await download('/now'); + await expect.poll(placed).toEqual([ + ['report.txt', 'progressing'], + ['report (1).txt', 'completed'], + ]); + expect(readFileSync(path.join(downloads, 'report (1).txt'), 'utf8')).toBe('now'); + }); + it.skipIf(process.platform === 'win32')('gives a download the name of one the app saved in a folder of its own', async () => { const launched = appWith(`let first = true; app.whenReady().then(() => { From 7b0cf60ad5e733b652fcd27506ca8ff6fd8bbdb4 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Mon, 30 Nov 2026 19:08:33 +0900 Subject: [PATCH 26/26] test(electron): wait for the held download's file before the test removes it The app records a download as progressing in its will-download handler, before Chromium creates the file, so the test could reach rmSync first and fail with ENOENT, or remove nothing and leave the disk check in play. It now waits for the file to exist. Co-Authored-By: Claude Opus 5.5 --- packages/electron/tests/integration/launch.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/electron/tests/integration/launch.test.ts b/packages/electron/tests/integration/launch.test.ts index 07719a4645..c9729a972b 100644 --- a/packages/electron/tests/integration/launch.test.ts +++ b/packages/electron/tests/integration/launch.test.ts @@ -555,6 +555,7 @@ describe('downloads', () => { await download('/held'); await expect.poll(placed).toEqual([['report.txt', 'progressing']]); // Chromium writes the file as soon as the app names it, so it is removed: only the name the app took is left to number around. + await expect.poll(() => existsSync(path.join(downloads, 'report.txt'))).toBe(true); rmSync(path.join(downloads, 'report.txt')); await download('/now'); await expect.poll(placed).toEqual([