Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 2 additions & 1 deletion docs/electron.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,8 @@ The engine adds `--no-sandbox` on Linux automatically.
masks can't reach, screenshots of that window are withheld.
- **Local file boundary:** if a window navigates to a `file:` path outside
your app's directory, the agent gets no observation and screenshots are
refused.
refused. When `app.appPath` names a main script, the app's directory is
the script's package inside the project.
- **Inspector port:** window automation runs over a private pipe, while the
main process listens on an unauthenticated loopback port for
`electron.evaluate()` during each test.
Expand Down
18 changes: 11 additions & 7 deletions packages/electron/src/app-process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,12 @@ export class AppProcess {
let first = await window();
opened = true;
// Still inside the launch: an app that quits here, or a caller that stopped waiting, fails it.
await raceAbort(() => Promise.race([this.setUp(app, setup, left), quitEarly]), operation.signal, 'setting up the app');
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();
const { appPath } = setup.app;
// The window the launch ends on, which need not be the first registered: that one may be a splash or a blank page.
this.directory = appDirectory({ reported, declared: appPath === undefined ? undefined : path.resolve(setup.projectRoot, appPath), firstDocument: first.url(), projectRoot: setup.projectRoot });
// The window that loaded is the one read, not one still on its way.
this.windows.show(open().indexOf(first));
} catch (cause) {
Expand All @@ -194,8 +197,12 @@ export class AppProcess {
}
}

/** What a launch does once the app has a window: its main process connected, its downloads placed, its versions reported. */
private async setUp(app: RunningApp, setup: LaunchSetup, left: () => number): Promise<void> {
/**
* What a launch does once the app has a window that loaded: its main
* process connected, its downloads placed, its versions reported. Resolves
* to the app path the main process reports, or undefined when it cannot be asked.
*/
private async setUp(app: RunningApp, setup: LaunchSetup, left: () => number): Promise<string | undefined> {
// Only now is an app with no inspector known to have none: the address is printed before the app's own code runs.
// One that printed it is being connected to, and that has a bound of its own.
setTimeout(() => {
Expand All @@ -212,10 +219,7 @@ export class AppProcess {
}
const versions = await answerWithin(readVersions(app, main), left());
if (versions !== undefined) setup.attempt.environment(versions);
const reported = main === undefined ? undefined : await answerWithin(main.evaluate(({ app: electronApp }) => electronApp.getAppPath(), undefined), Math.min(left(), ANSWER_MS));
const { appPath } = setup.app;
const firstDocument = this.windows.current()?.page.url() ?? '';
this.directory = appDirectory({ reported, declared: appPath === undefined ? undefined : path.resolve(setup.projectRoot, appPath), firstDocument });
return main === undefined ? undefined : await answerWithin(main.evaluate(({ app: electronApp }) => electronApp.getAppPath(), undefined), Math.min(left(), ANSWER_MS));
}

/** Starts the binary. Nothing is awaited: a binary that cannot start shows as a process that ended. */
Expand Down
13 changes: 11 additions & 2 deletions packages/electron/src/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,20 @@ export async function withPixels(devtools: DevTools, raw: RawRead, snapshot: Eng
/**
* `app.screenshot(label)`: the window with its masks painted over, written
* under the attempt's artifacts as `screenshots/<n>-<label>.png`. Refused
* with `POLICY_DENIED` when the capture is withheld.
* with `POLICY_DENIED` when the capture is withheld, when `refused` says why
* the window is not one to capture, or when the window loaded another
* document while the capture waited its turn: the pixels are of the document
* `refused` approved, or none are kept.
*/
export async function screenshotFile(devtools: DevTools, window: AppWindow, artifactsDir: string, name: string): Promise<string> {
export async function screenshotFile(devtools: DevTools, window: AppWindow, artifactsDir: string, name: string, refused: () => string | undefined): Promise<string> {
const before = refused();
if (before !== undefined) throw new ConfigurationError('POLICY_DENIED', before);
const generation = window.page.generation;
const capture = await maskedCapture(devtools, window, await unmaskable(devtools, window), 'device');
if ('withheld' in capture) throw new ConfigurationError('POLICY_DENIED', capture.withheld);
if (window.page.generation !== generation) throw new ConfigurationError('POLICY_DENIED', 'the window loaded another document while the screenshot was taken, so the screenshot is withheld');
const after = refused();
if (after !== undefined) throw new ConfigurationError('POLICY_DENIED', after);
const relative = path.posix.join('screenshots', name);
const absolute = path.join(artifactsDir, relative);
mkdirSync(path.dirname(absolute), { recursive: true });
Expand Down
44 changes: 40 additions & 4 deletions packages/electron/src/file-bound.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* captured.
*/

import { realpathSync, statSync } from 'node:fs';
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

Expand All @@ -17,14 +17,21 @@ export interface AppFiles {
readonly declared: string | undefined;
/** The first document the app showed. */
readonly firstDocument: string;
/** The project's root: a main script's package is looked for no higher. */
readonly projectRoot: string;
}

/**
* The directory the app's own pages are in, or undefined when nothing says:
* what the main process reports, else the declared app path, else the
* archive or directory of the first local page the app showed.
* for a declared main script, the package it belongs to; else what the main
* process reports, else the declared app path, else the archive or directory
* of the first local page the app showed.
*/
export function appDirectory({ reported, declared, firstDocument }: AppFiles): string | undefined {
export function appDirectory({ reported, declared, firstDocument, projectRoot }: AppFiles): string | undefined {
// Electron reports a main script's own directory, and a build can put the pages beside it (`out/main/index.js`
// and `out/renderer/`): the app is the package the script is in, as it is for an app path that names the directory.
// An `.asar` archive is a file too, and the app itself, as Electron reports it: its bound is the archive.
if (declared !== undefined && !/\.asar$/i.test(declared) && statSync(declared, { throwIfNoEntry: false })?.isFile() === true) return canonical(packageOf(declared, projectRoot) ?? path.dirname(declared));
if (reported !== undefined && reported !== '') return canonical(reported);
if (declared !== undefined) return canonical(statSync(declared, { throwIfNoEntry: false })?.isDirectory() === true ? declared : path.dirname(declared));
const file = localFile(firstDocument);
Expand All @@ -49,6 +56,35 @@ export function outsideApp(location: string, directory: string | undefined): str
return inside ? undefined : `the window left the app's directory for ${shown}, a local file outside it, so it is not read`;
}

/**
* The nearest directory above `file`, up to the project's root, with a
* `package.json` that names a package, or undefined when none has one: a
* manifest above the project (a home directory's, a monorepo's) is no package
* of this app's. A manifest that only sets the module type
* (`{"type":"commonjs"}`, which build tools write into their output) marks
* how Node loads the files there, not a package of its own.
*/
function packageOf(file: string, projectRoot: string): string | undefined {
const top = path.resolve(projectRoot);
for (let directory = path.dirname(path.resolve(file)); ; directory = path.dirname(directory)) {
const relative = path.relative(top, directory);
if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) return undefined;
const manifest = path.join(directory, 'package.json');
if (existsSync(manifest) && !onlyModuleType(manifest)) return directory;
if (relative === '') return undefined;
}
}

function onlyModuleType(manifest: string): boolean {
try {
const parsed: unknown = JSON.parse(readFileSync(manifest, 'utf8'));
return typeof parsed === 'object' && parsed !== null && Object.keys(parsed).join() === 'type';
} catch {
// A manifest that cannot be read is no proof the package is elsewhere: the nearer directory is the narrower bound.
return false;
}
}

function localFile(location: string): string | undefined {
try {
return fileURLToPath(location);
Expand Down
3 changes: 2 additions & 1 deletion packages/electron/src/in-page/masks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ export function placeMasks(selector: string): MaskState {

const resume: Animation[] = [];
for (const animation of document.getAnimations()) {
if (animation.effect === null || animation.playbackRate === 0) continue;
// A paused animation holds still already; one the capture cancelled is played again after it, which would start it.
if (animation.effect === null || animation.playbackRate === 0 || animation.playState === 'paused') continue;
const end = animation.effect.getComputedTiming().endTime;
try {
if (Number.isFinite(Number(end))) {
Expand Down
4 changes: 1 addition & 3 deletions packages/electron/src/surface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -602,10 +602,8 @@ export class ElectronSurface {
const attempt = this.attempt;
if (attempt === undefined) throw invalidState('a screenshot is taken inside a test');
return await withBudget(operation, 'screenshot', async () => {
const left = this.leftApp(window);
if (left !== undefined) throw new ConfigurationError('POLICY_DENIED', left);
this.artifactCounter += 1;
return await screenshotFile(this.devtools, window, attempt.artifactsDir, screenshotName(this.artifactCounter, label));
return await screenshotFile(this.devtools, window, attempt.artifactsDir, screenshotName(this.artifactCounter, label), () => this.leftApp(window));
});
}

Expand Down
50 changes: 48 additions & 2 deletions packages/electron/tests/integration/launch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import { execFileSync, spawnSync } from 'node:child_process';
import { Transformer } from '@napi-rs/image';
import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
Expand Down Expand Up @@ -357,6 +357,29 @@ describe('an app with no inspector', () => {
await launched.windows.require().page.evaluate(() => document.querySelector('a')?.click());
await expect.poll(() => (existsSync(path.join(data, 'Downloads')) ? readdirSync(path.join(data, 'Downloads')) : [])).toContain('saved.txt');
});

it.skipIf(process.platform === 'win32')('takes its own directory from the window the launch ends on, when the splash it waited for closes during setup', async () => {
const launched = appWith(`app.on('window-all-closed', () => {}); app.whenReady().then(() => {
const splash = new BrowserWindow({ show: false });
splash.webContents.once('did-finish-load', () => setTimeout(() => {
splash.destroy();
new BrowserWindow({ show: false }).loadFile(require('node:path').join(__dirname, 'bundle', 'ui', 'index.html'));
}, 150));
splash.loadFile(require('node:path').join(__dirname, 'bundle', 'splash', 'index.html'));
});`);
for (const part of ['splash', 'ui']) {
mkdirSync(path.join(launched.directory, 'bundle', part), { recursive: true });
writeFileSync(path.join(launched.directory, 'bundle', part, 'index.html'), `<title>${part}</title>`);
}
// A packaged app's binary: no app path on the command line, and no inspector to report one.
const wrapper = path.join(launched.directory, 'packaged');
writeFileSync(wrapper, `#!/bin/sh\nshift\nexec "${electronBinary()}" "${launched.directory}" "$@"\n`, { mode: 0o755 });
const attempt = { appLog: (entry: { readonly text: string }) => void launched.logs.push(entry.text), navigation: () => undefined, environment: () => undefined } as unknown as EngineAttemptContext;
const setup: LaunchSetup = { executable: wrapper, projectRoot: launched.directory, app: {}, env: process.env, userDataDir: path.join(launched.directory, 'data'), attempt };
await launched.app.launch(setup, { signal: new AbortController().signal, timeoutMs: 20_000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext);
expect(await launched.windows.require().page.title()).toBe('ui');
expect(launched.app.appDirectory).toBe(realpathSync(path.join(launched.directory, 'bundle', 'ui')));
});
});

describe('pixels', () => {
Expand Down Expand Up @@ -412,12 +435,35 @@ describe('pixels', () => {
const refusal = async (reaction: string): Promise<string> => {
const { windows, launch, directory } = appWith(`app.whenReady().then(() => new BrowserWindow({ show: ${SHOWN}, width: 300, height: 200 }).loadURL('data:text/html,' + ${JSON.stringify(encodeURIComponent(`<body style="margin:0">${RED_FRAME}${onMasks(reaction)}</body>`))}));`);
await launch();
return String(await screenshotFile(new DevTools(), windows.require(), directory, 'shot.png').then(() => 'taken', (error: unknown) => error));
return String(await screenshotFile(new DevTools(), windows.require(), directory, 'shot.png', () => undefined).then(() => 'taken', (error: unknown) => error));
};
expect(await refusal(`const field = document.createElement('input'); field.type = 'password'; document.body.append(field);`)).toMatch(/appeared while the screenshot was taken/);
expect(await refusal(`document.querySelector('iframe').style.marginLeft = '60px';`)).toMatch(/moved while the screenshot was taken/);
});

it('writes no screenshot of a window that left the app while it was captured', async () => {
const { windows, launch, directory } = appWith(`app.whenReady().then(() => new BrowserWindow({ show: ${process.platform === 'linux'}, width: 300, height: 200 }).loadURL('data:text/html,<title>Loaded</title>'));`);
await launch();
// In the app when the screenshot is asked for, gone from it once the capture is done.
const answers = [undefined, 'the window left the app'];
const refused = await screenshotFile(new DevTools(), windows.require(), directory, 'left.png', () => answers.shift()).then(() => undefined, (error: unknown) => error);
expect(refused).toMatchObject({ code: 'POLICY_DENIED', message: expect.stringMatching(/left the app/) });
expect(existsSync(path.join(directory, 'screenshots', 'left.png'))).toBe(false);
});

it('writes no screenshot when the window loaded another document while it was captured', async () => {
const { windows, launch, directory } = appWith(`app.whenReady().then(() => new BrowserWindow({ show: ${process.platform === 'linux'}, width: 300, height: 200 }).loadURL('data:text/html,<title>Loaded</title>'));`);
await launch();
const window = windows.require();
// In the app at both checks, with another document loaded in between, as two navigations would leave it.
const refused = await screenshotFile(new DevTools(), window, directory, 'swapped.png', () => {
setTimeout(() => window.page.documentChanged(), 0);
return undefined;
}).then(() => undefined, (error: unknown) => error);
expect(refused).toMatchObject({ code: 'POLICY_DENIED', message: expect.stringMatching(/loaded another document/) });
expect(existsSync(path.join(directory, 'screenshots', 'swapped.png'))).toBe(false);
});

it('gives each of two captures taken at once its own masks', async () => {
const { windows, launch } = appWith(`app.whenReady().then(() => new BrowserWindow({ show: ${SHOWN}, width: 300, height: 200 }).loadURL('data:text/html,<body style="margin:0"><iframe style="border:0;width:300px;height:200px" srcdoc="<body style=margin:0;background:red>"></iframe></body>'));`);
await launch();
Expand Down
13 changes: 13 additions & 0 deletions packages/electron/tests/integration/node-ops.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { Deadline, type OperationContext } from '@e2e-dev/core/engine';
import { waitReady } from '../../src/actionability.ts';
import { DevTools } from '../../src/devtools.ts';
import { placeMasks, removeMasks } from '../../src/in-page/masks.ts';
import { activeUnder, queryAll, type NodeOps } from '../../src/in-page/node-ops.ts';
import type { AppWindow } from '../../src/windows.ts';
import { openTestWindow, type TestWindow } from './test-window.ts';
Expand Down Expand Up @@ -341,3 +342,15 @@ describe('waitReady', () => {
expect(await selects('#background')).toMatchObject({ message: expect.stringMatching(INERT) });
});
});

describe('masks', () => {
it('leaves an animation the app paused paused, and plays an endless one again after the capture', async () => {
await window.setContent(`<div id="paused"></div><div id="running"></div><script>
for (const id of ['paused', 'running']) document.getElementById(id).animate([{ opacity: 0 }, { opacity: 1 }], { duration: 1000, iterations: Infinity });
document.getElementById('paused').getAnimations()[0].pause();
</script>`);
await window.page.evaluate(placeMasks, 'input[type=password i]');
await window.page.evaluate(removeMasks, 'input[type=password i]');
expect(await window.inPage(() => ['paused', 'running'].map((id) => document.getElementById(id)!.getAnimations()[0]?.playState))).toEqual(['paused', 'running']);
});
});
Loading
Loading