Skip to content
Merged
Show file tree
Hide file tree
Changes from 25 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
5ab6e6f
docs(electron): list waitForDownload's no-inspector failure
kdy1 Nov 29, 2026
25b056a
fix(electron): take no window waitForWindow's trigger opened after it…
kdy1 Nov 29, 2026
ad7edfc
fix(electron): name waitForDownload where an app with no inspector is…
kdy1 Nov 29, 2026
c4c4ecf
docs(electron): say where a download before the first window goes, in…
kdy1 Nov 29, 2026
bf12a7b
fix(electron): bound waitForWindow's and waitForDownload's triggers b…
kdy1 Nov 29, 2026
08408e9
fix(electron): bound waitForDownload's reads of the app's downloads b…
kdy1 Nov 29, 2026
40a98ed
fix(electron): wait on a trigger that returns no promise
kdy1 Nov 29, 2026
1942e9e
test(electron): accept either timeout message for a download wait wit…
kdy1 Nov 29, 2026
9747ba0
fix(electron): run no download trigger for a step cancelled while the…
kdy1 Nov 29, 2026
cfe9716
fix(electron): show no window for a waitForWindow cancelled while its…
kdy1 Nov 29, 2026
6312a81
fix(electron): give no download a name the app took itself in the dow…
kdy1 Nov 29, 2026
772ab23
docs(electron): say a download is numbered around a file the app wrot…
kdy1 Nov 29, 2026
371d309
fix(electron): end a window or download wait as cancelled when its st…
kdy1 Nov 29, 2026
69bfadf
fix(electron): end a download wait as cancelled while it asks a busy …
kdy1 Nov 29, 2026
e050a7a
fix(electron): run no window wait's trigger for a step cancelled befo…
kdy1 Nov 29, 2026
9727ec0
fix(electron): number a download only around names the app took in th…
kdy1 Nov 29, 2026
8c81353
chore(electron): add a changeset for the window and download wait fixes
kdy1 Nov 29, 2026
a418b54
docs(electron): keep the download naming rules in the reference only
kdy1 Nov 29, 2026
59091af
fix(electron): show no window for a step cancelled while the window i…
kdy1 Nov 29, 2026
0337141
test(electron-testbed): accept the busy-main-process message for the …
kdy1 Nov 29, 2026
893e2c8
test(electron-testbed): say what the late waitForWindow case checks
kdy1 Nov 29, 2026
a6535dd
docs(electron): say which downloads the engine places and numbers
kdy1 Nov 29, 2026
e9ba4f0
fix(electron): word a cancelled waitForDownload the same on every path
kdy1 Nov 29, 2026
539067f
fix(electron): time out a download wait whose last read the deadline …
kdy1 Nov 30, 2026
07c9562
test(electron): number a download around a name the app took before i…
kdy1 Nov 30, 2026
7b0cf60
test(electron): wait for the held download's file before the test rem…
kdy1 Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/electron-window-download-waits.md
Original file line number Diff line number Diff line change
@@ -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.
23 changes: 21 additions & 2 deletions apps/electron-testbed/tests/parity.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,27 @@ 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);
expect(none).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/no download finished/) });
// 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<void>((resolve) => setTimeout(resolve, 3000)), { timeout: 500 }).then(() => undefined, (error: unknown) => error);
// 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)$/) });
Comment thread
kdy1 marked this conversation as resolved.
Resolved
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 }) => {
Expand Down
13 changes: 13 additions & 0 deletions apps/electron-testbed/tests/sign-in.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,14 @@ 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 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();
Comment thread
kdy1 marked this conversation as resolved.
Resolved
await new Promise((resolve) => setTimeout(resolve, 800));
}, { timeout: 500 }).then(() => undefined, (error: unknown) => error);
expect(late).toMatchObject({ code: 'ACTION_FAILED', message: 'electron.waitForWindow exceeded its timeout of 500ms while its trigger ran' });
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 }) => {
Expand All @@ -409,6 +417,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<void>);
expect(await unreturned.title()).toBe('Settings');
});

test('types into a field inside a closed shadow root', async ({ app, screen, electron }) => {
Expand Down
14 changes: 7 additions & 7 deletions docs/electron.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -267,11 +267,10 @@ 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
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 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

Expand Down Expand Up @@ -313,8 +312,9 @@ Forge's default) keeps a launcher of the same name beside its `app-<version>`
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
Expand Down
19 changes: 14 additions & 5 deletions docs/reference/electron.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <n>ms; the trigger resolved after <m>ms`. |
| `ACTION_FAILED` | No window opened in time. The message is `no window opened within <n>ms; the trigger resolved after <m>ms`, or `electron.waitForWindow exceeded its timeout of <n>ms while its trigger ran`. |

#### `window`

Expand Down Expand Up @@ -470,15 +470,24 @@ expect(file.suggestedFilename).toBe('report.csv');
- It registers the file as a `download` artifact, saved as
`downloads/<NNN>-<name>`, 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).
- A trigger that throws fails with its own error.
- 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.

| Throws | When |
| --- | --- |
| `INVALID_ARGUMENT` | `trigger` is not a function. |
| `ACTION_FAILED` | No download finished in time. The message is `no download finished within <n>ms of the trigger`. |
| `ACTION_FAILED` | No download finished in time. The message is `no download finished within <n>ms; the trigger resolved after <m>ms`, `electron.waitForDownload exceeded its timeout of <n>ms while its trigger ran`, or `no download finished within <n>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. |

#### `onDialog`

Expand Down
13 changes: 10 additions & 3 deletions packages/electron/src/app-process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
Expand Down Expand Up @@ -573,11 +573,15 @@ 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;
Comment thread
kdy1 marked this conversation as resolved.
Resolved
// 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, ''];
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;
};
Expand All @@ -588,7 +592,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 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 ??= []);
Expand Down
76 changes: 62 additions & 14 deletions packages/electron/src/surface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, raceAbort, sleep, TestError, validateComputedStyleProperties, withTimeout } from '@e2e-dev/core/engine';
import type {
ComputedStyleProperty,
ComputedStyleValues,
Expand Down Expand Up @@ -455,8 +455,14 @@ export class ElectronSurface {
/** `window.activate()`: reads and acts in the window from now on. */
async activateWindow(window: AppWindow, operation: OperationContext): Promise<void> {
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, one cancelled
// while the window is raised included: the window `screen` reads changes last.
budget.check();
await window.page.bringToFront().catch(() => undefined);
budget.check();
Comment thread
kdy1 marked this conversation as resolved.
Resolved
this.windowList.activate(window);
});
}

/** `window.close()`: any window, the app's last one too. */
Expand Down Expand Up @@ -503,19 +509,21 @@ export class ElectronSurface {
this.failOnDialog();
if (!this.app.running) throw this.app.notRunning();
const before = new Set(this.windowList.open());
const started = Date.now();
await trigger();
const triggerMs = Date.now() - started;
const deadline = new Deadline(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();
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);
Expand Down Expand Up @@ -587,21 +595,39 @@ export class ElectronSurface {
const attempt = this.attempt;
if (attempt === undefined) throw invalidState('a download is waited for inside a test');
this.failOnDialog();
const before = (await this.app.downloads()).length;
await trigger();
const deadline = new Deadline(operation.timeoutMs);
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<readonly AppDownload[]> =>
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 });
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`);
// 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: new Deadline(operation.timeoutMs),
deadline,
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;
},
onTimeout: () => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms of the trigger`),
});
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;
Expand Down Expand Up @@ -646,3 +672,25 @@ 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<void>, deadline: Deadline, api: string, operation: OperationContext): Promise<number> {
const started = Date.now();
// 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;
}
Loading
Loading