Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
80890c6
fix(electron): end an attempt's state even when its user-data directo…
kdy1 Nov 29, 2026
2391d7c
fix(electron): keep a dialog handler that outlives its attempt out of…
kdy1 Nov 29, 2026
79f2dff
fix(electron): leave a failed launch the time to say why
kdy1 Nov 29, 2026
ff0eeb6
fix(electron): set up an app whose window loaded as the wait for one …
kdy1 Nov 29, 2026
e39955a
test(electron): end the integration window's Electron when it never o…
kdy1 Nov 29, 2026
f89d8ba
fix(electron): keep only a moment of a launch's time for saying why i…
kdy1 Nov 29, 2026
03f6df5
fix(electron): keep macOS from asking to reopen the windows of an app…
kdy1 Nov 29, 2026
4ed9f75
docs(electron): list app.open()'s failure when no window loads in its…
kdy1 Nov 29, 2026
36d79e9
fix(electron): quote the start of each stderr line a failed launch shows
kdy1 Nov 29, 2026
7f2ddf0
fix(electron): quote a long stderr line only up to white space
kdy1 Nov 29, 2026
aa55c2e
fix(electron): wait only a moment for the exit of an app a failed lau…
kdy1 Nov 29, 2026
2b89ed4
chore(electron): add a changeset for the launch failure fixes
kdy1 Nov 29, 2026
5158813
fix(electron): quote no part of a stderr line too long to quote whole
kdy1 Nov 29, 2026
f408967
chore(electron): say how the changeset's launch failure quotes a long…
kdy1 Nov 29, 2026
09b2729
docs(electron): say the app sees a bare YES after the macOS persisten…
kdy1 Nov 29, 2026
8bee58d
docs(electron): note that a very short launch can still end in TEST_T…
kdy1 Nov 29, 2026
718c294
docs(electron): say the app's argv keeps both words of the macOS pers…
kdy1 Nov 29, 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-launch-failures.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@e2e-dev/electron': patch
---

A failed `app.open()` says why it failed instead of `TEST_TIMEOUT`: the launch keeps a moment of the operation's time to ask the app and end it. A launch whose window loaded just as the wait ran out still sets the app up. On macOS the engine starts the app with `-ApplePersistenceIgnoreState YES`, so an app the engine killed in an earlier test no longer stalls its next launch behind a "reopen windows?" alert. A launch failure quotes a stderr line over 500 characters by its length only, a dialog handler from one attempt never answers the next one's dialogs, and an attempt ends cleanly when its user-data directory cannot be removed.
6 changes: 4 additions & 2 deletions docs/reference/electron.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -183,14 +183,15 @@ export default {
| --- | --- |
| `INVALID_CONFIG` | At config load: an `app.url`, an `app.bundleId`, or `app.permissions`; neither `app.appPath` nor `executablePath`; or an `app.launchArguments` entry the engine owns (see [Launch arguments](#launch-arguments)). |
| `INVALID_CONFIG` | When the worker starts: `app.appPath` does not name an app the binary can run. The message says what is wrong with the path. |
| `APP_NOT_OPEN` | The app quit before it opened a window, or right after it opened its first one. The message quotes the last lines the app wrote to stderr. |
| `APP_NOT_OPEN` | The app quit before it opened a window, or right after it opened its first one. The message quotes the last lines the app wrote to stderr; a line over 500 characters shows only its length. |
| `APP_NOT_OPEN` | No window loaded a page in the launch's time: the app opened none, its windows loaded nothing, or Electron never became ready. The message says which, and on macOS suggests `--use-mock-keychain` for an app that waits on a keychain prompt. |
| `ENGINE_FAILURE` | The operating system refused to start the binary. |

#### Launch arguments

The engine starts every app with switches of its own, before the target's
`app.launchArguments` and a test's
[`launch({ launchArguments })`](#launch). An app with a strict argument parser must allow
[`launch({ launchArguments })`](#launch), and on macOS one after them. An app with a strict argument parser must allow
them.

| Switch | Why |
Expand All @@ -202,6 +203,7 @@ them.
| `--disable-features=CalculateNativeWinOcclusion` | The same. Left out when your arguments set `--disable-features`. |
| `--no-sandbox` | On Linux only. |
| `--user-data-dir=<directory>` | The test's own [user-data directory](#userdatadir). |
| `-ApplePersistenceIgnoreState YES` | On macOS only, after your arguments: an app the engine killed is not asked, in a modal alert, whether to reopen its windows. |

`app.launchArguments` and `launch({ launchArguments })` must not set `--user-data-dir`,
`--inspect`, `--inspect-brk`, `--remote-debugging-port`, or
Expand Down
72 changes: 58 additions & 14 deletions packages/electron/src/app-process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ const ANSWER_MS = 500;
/** How long a killed app gets to exit, and let go of its files, before its data is deleted. */
const EXIT_WAIT_MS = 2_000;

/** How long a failed launch waits for each answer it asks the app for, to say why it failed. */
const FAILURE_ANSWER_MS = 250;

/**
* What a failed launch keeps of its time to say why and end the app: the main
* process and its ready state asked, then the app killed and its exit waited
* for as long again.
*/
const FAILURE_REPORT_MS = 3 * FAILURE_ANSWER_MS;

/** How long setting the downloads directory may take of a launch's budget. */
const DOWNLOADS_SETUP_MS = 2_000;

Expand All @@ -73,6 +83,9 @@ const INSPECTOR_GRACE_MS = 500;
/** How many of the app's last stderr lines a failed launch quotes. */
const QUOTED_STDERR_LINES = 10;

/** The longest stderr line a launch failure quotes, in characters. */
const QUOTED_LINE_CHARS = 500;

/** One launched app. */
interface RunningApp {
readonly process: ElectronProcess;
Expand Down Expand Up @@ -101,6 +114,8 @@ export interface AppDownload {
export class AppProcess {
private app: RunningApp | undefined;
private exit: string | undefined;
/** The exit of an app a failed launch killed, which the next quit waits for. */
private exiting: Promise<unknown> | undefined;
private directory: string | undefined;
private queue: Promise<void> = Promise.resolve();

Expand Down Expand Up @@ -138,14 +153,20 @@ export class AppProcess {
}

/** Quits the running app, if any: a graceful quit within `graceMs` and the budget, then its process tree killed. */
async quit(budget: { readonly timeoutMs: number }, graceMs: number): Promise<void> {
async quit(budget: { readonly timeoutMs: number }, graceMs: number, exitWaitMs = EXIT_WAIT_MS): Promise<void> {
// A failed launch waited only briefly for the app it killed: its files in the user-data directory, removed after
// this quit, are let go of first.
const exiting = this.exiting;
this.exiting = undefined;
if (exiting !== undefined) await answerWithin(exiting, EXIT_WAIT_MS);
Comment thread
kdy1 marked this conversation as resolved.
Resolved
const app = this.app;
this.app = undefined;
this.exit = undefined;
this.directory = undefined;
this.windows.clear();
if (app === undefined) return;
await stop(app, Math.min(budget.timeoutMs, graceMs));
await stop(app, Math.min(budget.timeoutMs, graceMs), exitWaitMs);
if (app.process.ended === undefined && exitWaitMs < EXIT_WAIT_MS) this.exiting = app.process.exited;
}

/**
Expand All @@ -158,9 +179,10 @@ export class AppProcess {
// rather than the operation timing out; each phase gets what the ones before it left.
// An operation cancelled, or out of time after the quit before it, starts no app.
budget.check();
const timeout = Math.max(1, budget.waits.remaining());
// A failed launch then asks the app why and quits it: that is left out of the launch's own time, up to half of it.
const available = budget.waits.remaining();
const timeout = Math.max(1, available - Math.min(FAILURE_REPORT_MS, available / 2));
Comment thread
kdy1 marked this conversation as resolved.
Resolved
const deadline = new Deadline(timeout);
const left = (): number => Math.max(1, deadline.remaining());
let app: RunningApp;
let opened = false;
try {
Expand All @@ -181,7 +203,10 @@ export class AppProcess {
const window = (): Promise<PageTarget> => raceAbort(() => Promise.race([loaded(open, deadline, operation.signal), quitEarly]), operation.signal, 'waiting for the first window to load');
let first = await window();
opened = true;
// Still inside the launch: an app that quits here, or a caller that stopped waiting, fails it.
// Still inside the launch: an app that quits here, or a caller that stopped waiting, fails it. A window that loaded
// as the wait for one ran out still gets the operation's time to connect its main process and place its downloads:
// with none left, an app with an inspector would be taken for one with none, and save downloads where it likes.
const left = (): number => Math.max(1, budget.waits.remaining());
Comment thread
kdy1 marked this conversation as resolved.
Resolved
const reported = await raceAbort(() => Promise.race([this.setUp(app, setup, left), quitEarly]), operation.signal, 'setting up the app');
// A splash screen can close while the app is set up: the launch ends on a window that is there.
while (first.isClosed()) first = await window();
Expand All @@ -193,11 +218,13 @@ export class AppProcess {
} catch (cause) {
// Read before the engine's own quit, which ends the process too.
const exited = app.process.ended;
const main = exited === undefined ? await answerWithin(app.main, ANSWER_MS) : undefined;
const main = exited === undefined ? await answerWithin(app.main, FAILURE_ANSWER_MS) : undefined;
Comment thread
kdy1 marked this conversation as resolved.
Resolved
// Electron can stall before its ready event on a loaded machine; say so rather than blame the app's window.
const ready = main === undefined ? undefined : await answerWithin(main.evaluate(({ app: electronApp }) => electronApp.isReady(), undefined), ANSWER_MS);
const ready = main === undefined ? undefined : await answerWithin(main.evaluate(({ app: electronApp }) => electronApp.isReady(), undefined), FAILURE_ANSWER_MS);
const stuck = [...app.pages.values()].filter((page) => !this.windows.has(page)).length;
await this.quit({ timeoutMs: DISCARD_CLOSE_MS }, DISCARD_CLOSE_MS);
// Killed, with no graceful quit and only a moment's wait for its exit: an app that failed to launch has nothing to
// save, and the time is the report's. The next quit waits for the rest.
await this.quit({ timeoutMs: 0 }, 0, FAILURE_ANSWER_MS);
if (cause instanceof EngineError) throw cause;
throw launchError(setup, app.process, { exited, ready, stuck, timeout, opened }, cause);
}
Expand Down Expand Up @@ -444,13 +471,32 @@ export class AppProcess {
}
}

/**
* A stderr line as a failed launch quotes it: whole up to `QUOTED_LINE_CHARS`
* characters, and only its length past that. Any cut, at white space too,
* could keep the start of a secret, which the run's redaction, matching whole
* values only, would let through.
*/
function quotedLine(line: string): string {
return line.length <= QUOTED_LINE_CHARS ? line : `(a line of ${line.length} characters)`;
}

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';

/** 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> {
async function stop(app: RunningApp, graceMs: number, exitWaitMs: number): Promise<void> {
const { process } = app;
if (process.ended !== undefined) return;
if (graceMs > 0 && (await quitGracefully(app, graceMs))) return;
process.killNow();
// Its files in the user-data directory are deleted next: wait, briefly, until it has let go of them.
await answerWithin(process.exited, exitWaitMs);
}

/** Asks the app to quit, and whether it exited within `graceMs`. */
async function quitGracefully(app: RunningApp, graceMs: number): Promise<boolean> {
const { process } = app;
const main = await answerWithin(app.main, ANSWER_MS);
if (main === undefined) {
void process.browser.root.send('Browser.close').catch(() => undefined);
Expand All @@ -465,10 +511,7 @@ async function stop(app: RunningApp, graceMs: number): Promise<void> {
);
void main.evaluate(({ app: electronApp }) => electronApp.quit(), undefined).catch(() => undefined);
}
if ((await answerWithin(process.exited, graceMs)) !== undefined) return;
process.killNow();
// Its files in the user-data directory are deleted next: wait, briefly, until it has let go of them.
await answerWithin(process.exited, EXIT_WAIT_MS);
return (await answerWithin(process.exited, graceMs)) !== undefined;
}

/** The first of the app's open windows, in the order they opened, to have a parsed document: a window is read from then on. */
Expand Down Expand Up @@ -532,7 +575,8 @@ function launchError(

/** What the app wrote to stderr, for a failure's message; empty when it wrote nothing. */
function stderrQuote(process: ElectronProcess): string {
const lines = process.stderrTail(QUOTED_STDERR_LINES);
// A longer line is left out: a minified stack or a data: URL in one would fill the report.
const lines = process.stderrTail(QUOTED_STDERR_LINES).map(quotedLine);
return lines.length === 0 ? '' : `. The app wrote to stderr:\n${lines.join('\n')}`;
}

Expand Down
14 changes: 10 additions & 4 deletions packages/electron/src/dialogs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ function classified(cause: unknown): cause is Error {
export class DialogRouter {
private registrations: { readonly handler: DialogHandler }[] = [];
private pending: Error | undefined;
private readonly running = new Set<Promise<void>>();
private running = new Set<Promise<void>>();
/** Bumped by `reset`: a handler of an earlier attempt that is still running reports into none of the next one's state. */
private generation = 0;

/** Registers a handler, the newest winning, and returns what removes it. */
add(handler: DialogHandler): () => void {
Expand All @@ -49,6 +51,8 @@ export class DialogRouter {
reset(): void {
this.registrations = [];
this.pending = undefined;
this.running = new Set();
this.generation += 1;
}

/** The failure a dialog left for the next step, once. */
Expand All @@ -66,16 +70,18 @@ export class DialogRouter {
/** Answers one dialog through the newest handler. */
dispatch(dialog: OpenDialog): void {
const work = this.route(dialog).catch(() => undefined);
this.running.add(work);
void work.then(() => this.running.delete(work));
const { running } = this;
running.add(work);
void work.then(() => running.delete(work));
}

private async route(dialog: OpenDialog): Promise<void> {
const handler = this.registrations.at(-1)?.handler;
const { type, message } = dialog;
const { generation } = this;
// The first failure is the one to report: the app's later dialogs follow from it.
const fail = (error: Error): void => {
this.pending ??= error;
if (this.generation === generation) this.pending ??= error;
};
if (handler === undefined) {
fail(new EngineError('INVALID_STATE', `unhandled ${type} dialog: ${message}; answer it with electron.onDialog('accept'), 'dismiss', or a handler`, { retryable: false }));
Expand Down
16 changes: 14 additions & 2 deletions packages/electron/src/launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,20 @@ export interface ProcessExit {
readonly signal: NodeJS.Signals | null;
}

/** The command line an app starts with: the engine's switches, the caller's own (the app path first), then the engine's for the OS. */
export function processArguments(args: readonly string[], platform: NodeJS.Platform = process.platform): string[] {
return [
...engineArguments(args, platform),
...args,
// macOS asks, in a modal alert before the app is ready, whether to reopen the windows of an app that quit uncleanly,
// as the engine's kills leave it: the launch would wait out its timeout. After the app's own arguments, since Electron
// takes the first one that is no switch as the app's path.
...(platform === 'darwin' ? ['-ApplePersistenceIgnoreState', 'YES'] : []),
];
}

/** The switches the engine starts every app with, before the caller's own. */
export function engineArguments(args: readonly string[], platform: NodeJS.Platform = process.platform): string[] {
function engineArguments(args: readonly string[], platform: NodeJS.Platform): string[] {
return [
// The main process's inspector, on a port of its own choosing, for electron.evaluate.
'--inspect=0',
Expand Down Expand Up @@ -86,7 +98,7 @@ export class ElectronProcess {

constructor(command: LaunchCommand) {
killAtExit();
this.child = spawn(command.executable, [...engineArguments(command.args), ...command.args], {
this.child = spawn(command.executable, processArguments(command.args), {
cwd: command.cwd,
env: command.env,
// fd 3 carries the engine's commands and fd 4 the browser's answers. stdout is not read: an unread pipe would stall the app.
Expand Down
11 changes: 8 additions & 3 deletions packages/electron/src/surface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,14 +136,19 @@ export class ElectronSurface {
this.recorder = undefined;
await uncollected?.abandon().catch(() => undefined);
await this.app.serialized(() => this.app.quit(context, DISCARD_CLOSE_MS));
// Retried: Chromium's helper processes can still be closing their files in it.
if (this.userDataDir !== undefined) rmSync(this.userDataDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
const { userDataDir, uploadsDir } = this;
Comment thread
kdy1 marked this conversation as resolved.
Resolved
this.userDataDir = undefined;
if (this.uploadsDir !== undefined) rmSync(this.uploadsDir, { recursive: true, force: true });
this.uploadsDir = undefined;
this.attempt = undefined;
// settleAttempt reported what the attempt's dialogs left; its handlers go with it.
this.dialogs.reset();
try {
// Retried: Chromium's helper processes can still be closing their files in it.
if (userDataDir !== undefined) rmSync(userDataDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
} finally {
// Removed even when the user-data directory could not be, so the next attempt never finds this one's files.
if (uploadsDir !== undefined) rmSync(uploadsDir, { recursive: true, force: true });
}
}

/** A dialog the test's last step opened has no next step to fail: the attempt fails with it, as a step would. */
Expand Down
24 changes: 24 additions & 0 deletions packages/electron/tests/integration/launch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,14 @@ describe('launch', () => {
expect(String(await launch().then(() => undefined, (error: unknown) => error))).toMatch(/license failure/);
});

it('quotes no part of a long stderr line, which could cut a secret that holds white space', async () => {
const { launch } = appWith(`process.stderr.write('short line\\n' + 'x'.repeat(498) + ' secret value ' + 'y'.repeat(5000) + '\\n'); process.exit(3);`);
const message = String(await launch().then(() => undefined, (error: unknown) => error));
expect(message).toContain('short line\n(a line of 5512 characters)');
expect(message).not.toMatch(/x{2}|secret/);
expect(message.length).toBeLessThan(2000);
});

it('says how the app ended, with what it wrote to stderr, when it quits before a window', async () => {
const { directory, launch } = appWith(`console.error('license check failed'); process.exit(3);`);
const failure = await launch().then(() => undefined, (error: unknown) => error);
Expand All @@ -183,6 +191,22 @@ describe('launch', () => {
expect(String(failure)).toMatch(/1 window has loaded nothing yet/);
});

it('reports why a launch failed within the operation\'s time, for an app whose main process is stuck', async () => {
const { directory, launch } = appWith(`app.whenReady().then(() => { new BrowserWindow({ show: false }); const until = Date.now() + 60_000; while (Date.now() < until); });`);
const started = Date.now();
const failure = await launch(8000, AbortSignal.timeout(8000)).then(() => undefined, (error: unknown) => error);
// Its reasons and its quit fit in what the launch left, so the caller's own timeout never takes the failure's place.
expect(Date.now() - started).toBeLessThan(8000);
expect(String(failure)).toMatch(/the app opened no window within \d+ms/);
expect(await gone(directory)).toBe(true);
});

it('gives the first window nearly all of the launch\'s time, keeping only a moment to say why it failed', async () => {
const { windows, launch } = appWith(`app.whenReady().then(() => setTimeout(() => { ${LOADED}; }, 2500));`);
await launch(4000);
expect(windows.open()).toHaveLength(1);
});

it('starts no app when the operation spent all its time before the launch', async () => {
const { directory, launch } = appWith(`require('node:fs').writeFileSync(require('node:path').join(__dirname, 'started'), '1'); app.whenReady().then(() => { ${LOADED}; });`);
const failure = await launch(500, AbortSignal.timeout(5000), 700).then(() => undefined, (error: unknown) => error);
Expand Down
Loading
Loading