@e2e-dev/electron 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/surface.js CHANGED
@@ -13,7 +13,7 @@
13
13
  import { copyFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
14
14
  import { tmpdir } from 'node:os';
15
15
  import path from 'node:path';
16
- import { ConfigurationError, Deadline, EngineError, pollCondition, sleep, TestError, validateComputedStyleProperties } from '@e2e-dev/core/engine';
16
+ import { ConfigurationError, Deadline, EngineError, pollCondition, raceAbort, sleep, TestError, validateComputedStyleProperties, withTimeout } from '@e2e-dev/core/engine';
17
17
  import { performAtPoint, performOnNode, pressKey, swipeWindow, typeText } from './actions.js';
18
18
  import { AppProcess, DISCARD_CLOSE_MS, RESTART_CLOSE_MS } from './app-process.js';
19
19
  import { answerWithin, Budget, withBudget } from './budget.js';
@@ -102,16 +102,22 @@ export class ElectronSurface {
102
102
  this.recorder = undefined;
103
103
  await uncollected?.abandon().catch(() => undefined);
104
104
  await this.app.serialized(() => this.app.quit(context, DISCARD_CLOSE_MS));
105
- // Retried: Chromium's helper processes can still be closing their files in it.
106
- if (this.userDataDir !== undefined)
107
- rmSync(this.userDataDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
105
+ const { userDataDir, uploadsDir } = this;
108
106
  this.userDataDir = undefined;
109
- if (this.uploadsDir !== undefined)
110
- rmSync(this.uploadsDir, { recursive: true, force: true });
111
107
  this.uploadsDir = undefined;
112
108
  this.attempt = undefined;
113
109
  // settleAttempt reported what the attempt's dialogs left; its handlers go with it.
114
110
  this.dialogs.reset();
111
+ try {
112
+ // Retried: Chromium's helper processes can still be closing their files in it.
113
+ if (userDataDir !== undefined)
114
+ rmSync(userDataDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
115
+ }
116
+ finally {
117
+ // Removed even when the user-data directory could not be, so the next attempt never finds this one's files.
118
+ if (uploadsDir !== undefined)
119
+ rmSync(uploadsDir, { recursive: true, force: true });
120
+ }
115
121
  }
116
122
  /** A dialog the test's last step opened has no next step to fail: the attempt fails with it, as a step would. */
117
123
  async settleAttempt(context) {
@@ -414,8 +420,14 @@ export class ElectronSurface {
414
420
  /** `window.activate()`: reads and acts in the window from now on. */
415
421
  async activateWindow(window, operation) {
416
422
  this.failOnDialog();
417
- this.windowList.activate(window);
418
- await withBudget(operation, 'activate window', () => window.page.bringToFront().catch(() => undefined));
423
+ await withBudget(operation, 'activate window', async (budget) => {
424
+ // A call cancelled meanwhile (a waitForWindow whose trigger outlasted the step) shows no other window, one cancelled
425
+ // while the window is raised included: the window `screen` reads changes last.
426
+ budget.check();
427
+ await window.page.bringToFront().catch(() => undefined);
428
+ budget.check();
429
+ this.windowList.activate(window);
430
+ });
419
431
  }
420
432
  /** `window.close()`: any window, the app's last one too. */
421
433
  async closeWindow(window, operation) {
@@ -462,19 +474,22 @@ export class ElectronSurface {
462
474
  if (!this.app.running)
463
475
  throw this.app.notRunning();
464
476
  const before = new Set(this.windowList.open());
465
- const started = Date.now();
466
- await trigger();
467
- const triggerMs = Date.now() - started;
477
+ const deadline = new Deadline(operation.timeoutMs);
478
+ const triggerMs = await runTrigger(trigger, deadline, 'electron.waitForWindow', operation);
479
+ const timedOut = () => new TestError('ACTION_FAILED', `no window opened within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`);
480
+ // The wait includes the trigger's own time: a window it opened after that ran out is not taken.
481
+ if (deadline.expired())
482
+ throw timedOut();
468
483
  let opened;
469
484
  await pollCondition({
470
- deadline: new Deadline(Math.max(1, operation.timeoutMs - triggerMs)),
485
+ deadline,
471
486
  signal: operation.signal,
472
487
  negated: false,
473
488
  evaluate: () => {
474
489
  opened = this.windowList.open().find((window) => !before.has(window));
475
490
  return Promise.resolve(opened !== undefined);
476
491
  },
477
- onTimeout: () => new TestError('ACTION_FAILED', `no window opened within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`),
492
+ onTimeout: timedOut,
478
493
  });
479
494
  if (opened === undefined)
480
495
  throw invalidState('the window was lost');
@@ -492,6 +507,60 @@ export class ElectronSurface {
492
507
  return document;
493
508
  return (await this.app.windowTitle(window.page)) ?? '';
494
509
  }
510
+ /**
511
+ * The title `expect(electron).toHaveTitle` polls: the document's, read
512
+ * within the operation so a read the deadline cuts off is a timeout and
513
+ * never another title, else the OS window's for a document with none. A
514
+ * window whose renderer crashed is waited on as `readShown` waits on it:
515
+ * briefly, for the app to load it again, and then said to have crashed.
516
+ */
517
+ async currentTitle(window, operation) {
518
+ const { page } = window;
519
+ const read = async () => {
520
+ const document = await page.title();
521
+ // The OS title is read within the operation too: a main process that answers late has said nothing, not ''.
522
+ return document !== '' ? document : await this.app.answeredWindowTitle(page);
523
+ };
524
+ return await withBudget(operation, 'window title', async (budget) => {
525
+ for (;;) {
526
+ if (this.windowList.isCrashed(window)) {
527
+ let stopListening = () => undefined;
528
+ const loadedOrClosed = new Promise((resolve) => {
529
+ const stops = [page.on('load', resolve), page.on('close', resolve)];
530
+ stopListening = () => stops.forEach((stop) => stop());
531
+ });
532
+ await answerWithin(loadedOrClosed, Math.min(CRASH_RELOAD_WAIT_MS, budget.waits.remaining()));
533
+ stopListening();
534
+ if (page.isClosed())
535
+ throw invalidState('the window closed');
536
+ if (this.windowList.isCrashed(window))
537
+ throw crashed();
538
+ }
539
+ // A read the renderer's crash leaves pending would never settle: the crash ends it, and the next pass waits.
540
+ let stopWaiting = () => undefined;
541
+ const crash = new Promise((resolve) => {
542
+ stopWaiting = page.on('crash', () => resolve('crashed'));
543
+ });
544
+ try {
545
+ const title = await Promise.race([read(), crash]);
546
+ if (title !== 'crashed' || !this.windowList.isCrashed(window))
547
+ return title;
548
+ }
549
+ finally {
550
+ stopWaiting();
551
+ }
552
+ }
553
+ });
554
+ }
555
+ /** Whether the shown window's renderer crashed: a wait on the window ends with that, where a closing window is waited through. */
556
+ get shownCrashed() {
557
+ const window = this.windowList.current();
558
+ return window !== undefined && this.windowList.isCrashed(window);
559
+ }
560
+ /** Whether the app is running: a wait on its window goes on through a window closing or loading, and ends when the app is gone. */
561
+ get appRunning() {
562
+ return this.app.running;
563
+ }
495
564
  /** `electron.onDialog()`: answers the app's dialogs from now on, until what it returns is called. */
496
565
  onDialog(handler) {
497
566
  return this.dialogs.add(handler);
@@ -540,22 +609,42 @@ export class ElectronSurface {
540
609
  if (attempt === undefined)
541
610
  throw invalidState('a download is waited for inside a test');
542
611
  this.failOnDialog();
543
- const before = (await this.app.downloads()).length;
544
- await trigger();
612
+ const deadline = new Deadline(operation.timeoutMs);
613
+ const unanswered = () => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms: the app's main process did not answer`);
614
+ // Read in the main process, which a busy app keeps from answering: each read ends with the wait. Its timeout is an
615
+ // operation timeout, which the poll takes for a read the deadline cut off when it started with under a tick left.
616
+ const readTimedOut = () => new EngineError('OPERATION_TIMEOUT', 'electron.waitForDownload: the app\'s main process did not answer', { retryable: false });
617
+ // A step cancelled while the app was asked ends then, as cancelled.
618
+ const downloads = () => raceAbort(() => withTimeout(this.app.downloads(), Math.max(1, deadline.remaining()), readTimedOut), operation.signal, 'electron.waitForDownload');
619
+ // Any other read that timed out had time to answer in: the main process did not.
620
+ const blocked = (cause) => (cause instanceof EngineError && cause.code === 'OPERATION_TIMEOUT' ? unanswered() : cause);
621
+ const before = (await downloads().catch((cause) => Promise.reject(blocked(cause)))).length;
622
+ // A trigger never runs once the wait is out of time, or its step was cancelled while the app was asked.
623
+ // Worded as raceAbort words the same cancel.
624
+ if (operation.signal.aborted)
625
+ throw new EngineError('CANCELLED', 'electron.waitForDownload cancelled', { retryable: false });
626
+ if (deadline.expired())
627
+ throw unanswered();
628
+ const triggerMs = await runTrigger(trigger, deadline, 'electron.waitForDownload', operation);
629
+ const timedOut = () => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`);
630
+ // The wait includes the trigger's own time, as the window wait's does.
631
+ if (deadline.expired())
632
+ throw timedOut();
545
633
  let finished;
634
+ // The last read starts at the deadline with almost no time: the poll ends that one with the ordinary timeout.
546
635
  await pollCondition({
547
- deadline: new Deadline(operation.timeoutMs),
636
+ deadline,
548
637
  signal: operation.signal,
549
638
  negated: false,
550
639
  evaluate: async () => {
551
- const next = (await this.app.downloads())[before];
640
+ const next = (await downloads())[before];
552
641
  if (next === undefined || next.state === 'progressing')
553
642
  return false;
554
643
  finished = next;
555
644
  return true;
556
645
  },
557
- onTimeout: () => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms of the trigger`),
558
- });
646
+ onTimeout: timedOut,
647
+ }).catch((cause) => Promise.reject(blocked(cause)));
559
648
  if (finished === undefined)
560
649
  throw invalidState('the download was lost');
561
650
  if (finished.state !== 'completed')
@@ -600,3 +689,20 @@ export class ElectronSurface {
600
689
  return (await recorder?.stop()) ?? [];
601
690
  }
602
691
  }
692
+ /**
693
+ * Runs a wait's trigger, test code, within the wait's deadline, and returns
694
+ * how long it took. A trigger still running at the deadline fails the wait
695
+ * and is left to finish on its own; its error, before then, is its own.
696
+ */
697
+ async function runTrigger(trigger, deadline, api, operation) {
698
+ const started = Date.now();
699
+ // A step cancelled before its trigger runs never runs it; one cancelled while it runs ends then, as cancelled, not at
700
+ // its timeout.
701
+ await raceAbort(() => {
702
+ // Test code: a trigger written in JavaScript, or one that does not return its promise, returns none.
703
+ const running = (async () => await trigger())();
704
+ running.catch(() => undefined);
705
+ return withTimeout(running, Math.max(1, deadline.remaining()), () => new TestError('ACTION_FAILED', `${api} exceeded its timeout of ${operation.timeoutMs}ms while its trigger ran`));
706
+ }, operation.signal, api);
707
+ return Date.now() - started;
708
+ }
package/dist/video.d.ts CHANGED
@@ -31,6 +31,19 @@ export declare class Recorder {
31
31
  * ever shown.
32
32
  */
33
33
  stop(): Promise<readonly VideoFile[]>;
34
+ /**
35
+ * Waits for the window switch in progress, for at most `SWITCH_WAIT_MS`: a
36
+ * window that does not answer the switch's DevTools calls holds it up for
37
+ * good. A switch that answers later backs out (`stopped`).
38
+ */
39
+ private settleSwitching;
40
+ /**
41
+ * Runs the end of a recording with the encoder killed once it has had
42
+ * `CLOSE_TIMEOUT_MS`: an ffmpeg that stops reading holds a frame's write,
43
+ * and the window switch and the last snapshot that wait on it, before its
44
+ * own close would start a timer.
45
+ */
46
+ private withinCloseTime;
34
47
  /**
35
48
  * Adds the shown window as it stands to the video. A screencast sends a
36
49
  * frame only when the window repaints, so a still window is captured here:
package/dist/video.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * to the window shown next, and the gap holds the last frame.
6
6
  */
7
7
  import { spawn } from 'node:child_process';
8
- import { existsSync, mkdirSync, rmSync } from 'node:fs';
8
+ import { existsSync, mkdirSync, rmSync, statSync } from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { EngineError } from '@e2e-dev/core/engine';
11
11
  import { answerWithin } from './budget.js';
@@ -20,6 +20,10 @@ const CLOSE_TIMEOUT_MS = 10_000;
20
20
  const STDERR_TAIL = 2_000;
21
21
  /** How long a window gets to hand over its last screen when the recording stops. */
22
22
  const LAST_SCREEN_MS = 2_000;
23
+ /** How long the end of a recording waits for a window switch, which a window that does not answer can hold up. */
24
+ const SWITCH_WAIT_MS = 2_000;
25
+ /** How long a window gets to answer the end of its screencast: a busy main process answers no DevTools call. */
26
+ const STOP_SCREENCAST_MS = 2_000;
23
27
  export class Recorder {
24
28
  ffmpeg;
25
29
  relative;
@@ -50,12 +54,18 @@ export class Recorder {
50
54
  if (this.stopped || this.source?.page === page)
51
55
  return;
52
56
  await this.source?.stop();
57
+ // The recording ended while the window before was stopped: the window shown next gets no screencast.
58
+ if (this.stopped)
59
+ return;
53
60
  this.source = undefined;
54
61
  if (page === undefined || page.isClosed())
55
62
  return;
56
63
  const { session } = page;
57
64
  if (this.encoder === undefined) {
58
65
  const { cssVisualViewport } = await session.send('Page.getLayoutMetrics');
66
+ // The recording ended while the window was asked: it gets no encoder.
67
+ if (this.stopped)
68
+ return;
59
69
  // Even sides: the encoder's pixel format halves them.
60
70
  const size = { width: Math.max(2, Math.floor(cssVisualViewport.clientWidth / 2) * 2), height: Math.max(2, Math.floor(cssVisualViewport.clientHeight / 2) * 2) };
61
71
  mkdirSync(path.dirname(this.absolute), { recursive: true });
@@ -74,9 +84,10 @@ export class Recorder {
74
84
  stop: async () => {
75
85
  off();
76
86
  page.recording = false;
77
- await session.send('Page.stopScreencast').catch(() => undefined);
87
+ await answerWithin(session.send('Page.stopScreencast'), STOP_SCREENCAST_MS);
78
88
  },
79
89
  };
90
+ const source = this.source;
80
91
  try {
81
92
  await session.send('Page.startScreencast', { format: 'jpeg', quality: JPEG_QUALITY, maxWidth: encoder.size.width, maxHeight: encoder.size.height });
82
93
  }
@@ -87,6 +98,11 @@ export class Recorder {
87
98
  this.source = undefined;
88
99
  return;
89
100
  }
101
+ // The recording ended while the screencast started: it sends no frame to an encoder that closed.
102
+ if (this.stopped && this.source !== source) {
103
+ await source.stop();
104
+ return;
105
+ }
90
106
  // A window shown again repaints nothing: the video would hold the window before it.
91
107
  await this.snap();
92
108
  }
@@ -95,24 +111,51 @@ export class Recorder {
95
111
  * ever shown.
96
112
  */
97
113
  async stop() {
98
- await this.switching;
114
+ return await this.withinCloseTime(async () => {
115
+ await this.settleSwitching();
116
+ const { source, encoder, startedAt } = this;
117
+ if (encoder === undefined || startedAt === undefined)
118
+ return [];
119
+ try {
120
+ await this.snap();
121
+ await source?.stop();
122
+ }
123
+ finally {
124
+ this.source = undefined;
125
+ await encoder.close().catch((cause) => {
126
+ // What ffmpeg wrote before it failed still plays; an empty file is no video.
127
+ if ((statSync(this.absolute, { throwIfNoEntry: false })?.size ?? 0) > 0)
128
+ return;
129
+ rmSync(this.absolute, { force: true });
130
+ throw new EngineError('ENGINE_FAILURE', `the video ${this.relative} could not be finalized: ${cause instanceof Error ? cause.message : String(cause)}`, { retryable: false, cause });
131
+ });
132
+ }
133
+ return existsSync(this.absolute) ? [{ path: this.relative, startedAt }] : [];
134
+ });
135
+ }
136
+ /**
137
+ * Waits for the window switch in progress, for at most `SWITCH_WAIT_MS`: a
138
+ * window that does not answer the switch's DevTools calls holds it up for
139
+ * good. A switch that answers later backs out (`stopped`).
140
+ */
141
+ async settleSwitching() {
142
+ await answerWithin(this.switching, SWITCH_WAIT_MS);
99
143
  this.stopped = true;
100
- const { source, encoder, startedAt } = this;
101
- if (encoder === undefined || startedAt === undefined)
102
- return [];
144
+ }
145
+ /**
146
+ * Runs the end of a recording with the encoder killed once it has had
147
+ * `CLOSE_TIMEOUT_MS`: an ffmpeg that stops reading holds a frame's write,
148
+ * and the window switch and the last snapshot that wait on it, before its
149
+ * own close would start a timer.
150
+ */
151
+ async withinCloseTime(end) {
152
+ const stuck = setTimeout(() => this.encoder?.kill(), CLOSE_TIMEOUT_MS);
103
153
  try {
104
- await this.snap();
105
- await source?.stop();
154
+ return await end();
106
155
  }
107
156
  finally {
108
- this.source = undefined;
109
- await encoder.close().catch((cause) => {
110
- if (!existsSync(this.absolute)) {
111
- throw new EngineError('ENGINE_FAILURE', `the video ${this.relative} could not be finalized: ${cause instanceof Error ? cause.message : String(cause)}`, { retryable: false, cause });
112
- }
113
- });
157
+ clearTimeout(stuck);
114
158
  }
115
- return existsSync(this.absolute) ? [{ path: this.relative, startedAt }] : [];
116
159
  }
117
160
  /**
118
161
  * Adds the shown window as it stands to the video. A screencast sends a
@@ -123,17 +166,21 @@ export class Recorder {
123
166
  const { source, encoder } = this;
124
167
  if (source === undefined || encoder === undefined || source.page.isClosed() || !this.allowed(source.page))
125
168
  return;
169
+ const { generation } = source.page;
126
170
  const screen = await answerWithin(source.page.session.send('Page.captureScreenshot', { format: 'jpeg', quality: JPEG_QUALITY }), LAST_SCREEN_MS);
127
- if (screen !== undefined)
128
- await encoder.frame(Buffer.from(screen.data, 'base64'));
171
+ // A window that loaded another document while it was captured may show what no frame may: the capture is dropped.
172
+ if (screen === undefined || source.page.generation !== generation || !this.allowed(source.page))
173
+ return;
174
+ await encoder.frame(Buffer.from(screen.data, 'base64'));
129
175
  }
130
176
  /** Ends a recording nobody collects: the file it wrote is removed. */
131
177
  async abandon() {
132
- await this.switching;
133
- this.stopped = true;
134
- await this.source?.stop();
135
- this.source = undefined;
136
- await this.encoder?.abort();
178
+ await this.withinCloseTime(async () => {
179
+ await this.settleSwitching();
180
+ await this.source?.stop();
181
+ this.source = undefined;
182
+ await this.encoder?.abort();
183
+ });
137
184
  }
138
185
  }
139
186
  /**
@@ -212,6 +259,12 @@ class FrameEncoder {
212
259
  if (code !== 0)
213
260
  throw new Error(`ffmpeg ${signal === null ? `exited with ${String(code)}` : `was killed (${signal})`}${this.stderr === '' ? '' : `: ${this.stderr.trim()}`}`);
214
261
  }
262
+ /** Kills the encoder: the frames it holds are dropped, and a write waiting on it returns. */
263
+ kill() {
264
+ this.process.kill('SIGKILL');
265
+ // Its input closes on this side too, so a write waiting for room in it returns whatever still holds the pipe.
266
+ this.process.stdin?.destroy();
267
+ }
215
268
  /** Kills the encoder and removes what it wrote. */
216
269
  async abort() {
217
270
  this.process.kill('SIGKILL');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e2e-dev/electron",
3
- "version": "0.0.0",
3
+ "version": "0.1.0",
4
4
  "description": "Electron engine for e2e agentic end-to-end testing: launches an Electron app and drives its windows through Chromium's accessibility tree",
5
5
  "keywords": [
6
6
  "e2e",
@@ -52,11 +52,11 @@
52
52
  }
53
53
  },
54
54
  "devDependencies": {
55
- "@e2e-dev/core": "0.25.0",
55
+ "@e2e-dev/core": "0.26.0",
56
56
  "@napi-rs/image": "1.16.0",
57
57
  "@types/node": "26.6.11",
58
58
  "devtools-protocol": "0.0.1756183",
59
- "e2e": "0.25.0",
59
+ "e2e": "0.26.0",
60
60
  "electron": "45.5.0",
61
61
  "typescript": "7.0.2",
62
62
  "vitest": "5.1.2"