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
6 changes: 6 additions & 0 deletions .changeset/electron-power-display-app-trackers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@bugsee/electron': minor
'@bugsee/trackers': minor
---

Electron main now records power, display and window telemetry. The power and display domains turn on when `powerMonitor` / `screen` is passed to `launchMain`. The window domain (`window_*`, `renderer_*`) turns on whenever `app` is passed, so existing callers that already pass `app` now get two extra `app` listeners (`browser-window-created`, `web-contents-created`) and these events while `captureSystemEvents` is on; pass `captureWindowEvents: false` to opt out, and `BrowserWindow` only adds windows that already exist. Electron's real `screen` throws until the app is ready: pass it after `app.whenReady()` (a throwing object turns that domain off and is reported, never failing the launch). On `events.system`: `power_suspend`, `power_resume`, `power_lock`, `power_unlock`, `power_ac`, `power_battery` (platform dependent: `lock-screen` and `on-ac` are macOS/Windows, `on-battery` is macOS only); `display_added`, `display_removed` and `display_metrics_changed`; `window_focus`, `window_blur`, `window_show`, `window_hide` (`{ windowId }`) and `renderer_unresponsive` / `renderer_responsive` (`{ webContentsId }`, listened for on `webContents` only so a hang is never recorded twice). The `electron_displays` system trace (`{ displays: [{ id, width, height, scale_factor?, rotation?, internal?, refresh_rate_hz? }] }`, JS-specific name) is written when the display list changes (it is held: a later unreadable list leaves the previous one recorded). Listeners attach only while `captureSystemEvents` / system traces are on and are removed by `client.stop()`. They come from three new per-object domain trackers in `@bugsee/trackers/electron`: `ElectronPowerTracker`, `ElectronDisplayTracker` and `ElectronApplicationTracker`.
3 changes: 2 additions & 1 deletion docs/PROGRESS.md

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions packages/bugsee/src/option-directions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ const RAW_STRICT: Record<string, RawEntry> = {
safe: 'on',
why: 'INTERNAL hold, forwarded to the browser read above',
},
'electron:captureWindowEvents': {
safe: 'off',
why: 'default ON, records window focus/renderer hangs: an invalid value is OFF + onError',
check: ['electron', /resolveFailClosedBoolean\(\s*captureWindowEvents/],
},
'electron:recover': { safe: 'n/a', why: 'durability behaviour' },
'node:recover': { safe: 'n/a', why: 'durability of already-persisted data' },
'node:exitOnUncaught': { safe: 'n/a', why: 'process policy' },
Expand Down
6 changes: 5 additions & 1 deletion packages/bugsee/src/relaunch-options.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ function optionKeys(pkg: string, file: string, name: string): string[] {
* "this is not deployment identity and not an integration seam". Notes on the ones that look otherwise:
* - `lifecycleEventsListener` is held on the carrier slot (`setProcessLifecycleEventsListener`), so it
* survives a relaunch without being re-passed;
* - the Electron handles (`app`, `ipcMain`, `crashReporter`, `gpuInfoType`, `bridge`, `post`, `launch`, `onSessionId`,
* - the Electron handles (`app`, `ipcMain`, `crashReporter`, `powerMonitor`, `screen`, `BrowserWindow`, `gpuInfoType`, `bridge`, `post`, `launch`, `onSessionId`,
* `nativeCrash`, `video`) belong to compositions that `relaunchWith` never re-runs (it re-runs the node
* launch, not `launchMain`), and keeping them would pin Electron objects on `globalThis` for nothing;
* - `appToken` (the Cloudflare and Nuxt adapters accept it inside their options object) is the token itself,
Expand All @@ -133,8 +133,10 @@ function optionKeys(pkg: string, file: string, name: string): string[] {
* serving `hardware.gpu`.
*/
const RESET_OPTIONS: readonly string[] = [
'BrowserWindow',
'app',
'appToken',
'captureWindowEvents',
'flushTimeoutMs',
'gpuInfoType',
'injectTraceMeta',
Expand Down Expand Up @@ -194,6 +196,7 @@ const RESET_OPTIONS: readonly string[] = [
'performanceUploadMode',
'persistUserIdentifier',
'post',
'powerMonitor',
'profiling',
'profilingSamplingIntervalMicros',
'propagateTrace',
Expand All @@ -208,6 +211,7 @@ const RESET_OPTIONS: readonly string[] = [
'reportPrioritySelectorEnabled',
'reportSummaryRequired',
'reportTrigger',
'screen',
'shutdownTimeoutMs',
'startInBlackout',
'systemTraceProducers',
Expand Down
16 changes: 14 additions & 2 deletions packages/electron/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ launchRenderer('YOUR_APP_TOKEN');

## Options

`launchMain(appToken, options)` takes `ipcMain` (required), `app`, `crashReporter`, `crashReporterExtra` and `video`, plus every `@bugsee/node` launch option (`appVersion`, `captureLogs`, `captureNetwork`, `maxRecordingTime`, `dataDir` and others).
`launchMain(appToken, options)` takes `ipcMain` (required), `app`, `powerMonitor`, `screen`, `BrowserWindow`, `gpuInfoType`, `captureWindowEvents`, `crashReporter`, `crashReporterExtra` and `video`, plus every `@bugsee/node` launch option (`appVersion`, `captureLogs`, `captureNetwork`, `maxRecordingTime`, `dataDir` and others).

`launchRenderer(appToken, options)` takes the `@bugsee/browser` launch options. Session replay is on by default and streams to the main process; pass `replay: false` to opt out.

Expand All @@ -76,7 +76,19 @@ If you pass `app` to `launchMain`, the main process also reports what Electron c
- A `child_process_gone` system event (`{ type, reason, exitCode, name }`) when a GPU or utility process exits, including a normal exit (`reason: 'clean-exit'`), so filter on `reason` if you only want crashes. It is recorded only while `captureSystemEvents` is on, and the `child-process-gone` listener is removed again by `client.stop()`.
- `environment.hardware.gpu` from `app.getGPUInfo(gpuInfoType)` (`'basic'` by default). A usable result is kept; a failed read, or a different `gpuInfoType` on a later launch, asks again.

A `relaunch()` from `@bugsee/node` or `@bugsee/bugsee` is not Electron-aware: after it `hardware.gpu` is still served, but `app_metrics` and `child_process_gone` stop until `launchMain` runs again.
A `relaunch()` from `@bugsee/node` or `@bugsee/bugsee` is not Electron-aware: after it `hardware.gpu` is still served, but `app_metrics`, `child_process_gone` and the power, display and window telemetry below stop until `launchMain` runs again.

## Power, display and window telemetry

Pass any of `powerMonitor`, `screen` and `BrowserWindow` (the Electron objects, injected like `app`) to `launchMain`; a domain whose object is absent is simply off.

**Pass `screen` safely.** Electron's real `screen` throws on any property read until the app is ready, so `import { screen } from 'electron'` and passing it straight to a `launchMain` call made before `app.whenReady()` turns the display domain off (the failure is reported through `onError`; the launch and the other domains are unaffected). To get display telemetry, either call `launchMain` after `app.whenReady()`, or leave `screen` out of the early call. The `powerMonitor` has the same rule on some platforms.

- `powerMonitor` -> `events.system`: `power_suspend`, `power_resume`, `power_lock`, `power_unlock`, `power_ac`, `power_battery`. No params. Platform dependent, per Electron's typings: `lock-screen`/`unlock-screen` are macOS and Windows, `on-ac` is macOS and Windows, and `on-battery` is macOS only, so an event that never fires is not evidence about the power state.
- `screen` -> `events.system`: `display_added` and `display_removed` (`{ id, width, height, scaleFactor, rotation, internal, refreshRate }`, absent keys omitted; a display whose id is -1, Electron's "invalid or not yet known" marker, is ignored) and `display_metrics_changed` (the same plus `changed`, Electron's changed metrics). It also feeds the `electron_displays` system trace (`{ displays: [{ id, width, height, scale_factor, rotation, internal, refresh_rate_hz }] }`, written when it changes). The trace is absent only before its first value: if a later refresh cannot read a usable list, the previous list stays held and keeps being re-recorded (the same open decision as other held traces). The name is JS-specific: `displays` is reserved until an Android-shaped list is confirmed against the viewer.
- `app` (plus `BrowserWindow` for windows that already exist) -> `events.system`: `window_focus`, `window_blur`, `window_show`, `window_hide` (`{ windowId }`), and `renderer_unresponsive` / `renderer_responsive` (`{ webContentsId }`). These are on whenever `app` is passed (they add two `app` listeners, `browser-window-created` and `web-contents-created`); pass `captureWindowEvents: false` to opt out. Windows created after `launchMain` are tracked too. The hang pair is listened for on `webContents` only, because `BrowserWindow` re-emits it and each hang would otherwise be recorded twice; a `<webview>` or `BrowserView` is covered when Electron announces it through `web-contents-created`.

All of these events are recorded only while `captureSystemEvents` is on, the listeners are removed again by `client.stop()`, and a throwing Electron getter is reported through `onError` and never fails the launch. Window titles and URLs are never read.

## Links

Expand Down
256 changes: 254 additions & 2 deletions packages/electron/src/launch-main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ import {
} from '@bugsee/core';
import type { Bugsee, BugseeLaunchOptions } from '@bugsee/node';
import { resetProcessTracker } from '@bugsee/node';
import { electronProcessTrackerFor } from '@bugsee/trackers/electron';
import {
electronApplicationTrackerFor,
electronDisplayTrackerFor,
electronPowerTrackerFor,
electronProcessTrackerFor,
} from '@bugsee/trackers/electron';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { launchMain } from './launch-main';
import type { IpcMainEventLike, IpcMainListener } from './main-receiver';
Expand All @@ -25,7 +30,13 @@ import type { VideoCaptureSource } from './video-capture';
// (mutating launchMain to `new ElectronProcessTracker(...)` makes the spy go uncalled). Behaviour is untouched.
vi.mock('@bugsee/trackers/electron', async (importOriginal) => {
const actual = await importOriginal<typeof import('@bugsee/trackers/electron')>();
return { ...actual, electronProcessTrackerFor: vi.fn(actual.electronProcessTrackerFor) };
return {
...actual,
electronProcessTrackerFor: vi.fn(actual.electronProcessTrackerFor),
electronPowerTrackerFor: vi.fn(actual.electronPowerTrackerFor),
electronDisplayTrackerFor: vi.fn(actual.electronDisplayTrackerFor),
electronApplicationTrackerFor: vi.fn(actual.electronApplicationTrackerFor),
};
});

afterEach(() => {
Expand Down Expand Up @@ -1078,3 +1089,244 @@ describe('launchMain — Electron process tracker composition (TR9, part 1)', ()
});
});
});

describe('launchMain — Electron domain trackers: power, display, application windows (TR9, part 2)', () => {
const optsOf = (f: ReturnType<typeof fakeLaunch>) =>
(f.received as { options: BugseeLaunchOptions }).options;
type L = (...a: unknown[]) => void;
class FakeEmitter {
table = new Map<string, L[]>();
on = vi.fn((e: string, l: L) => {
this.table.set(e, [...(this.table.get(e) ?? []), l]);
});
removeListener = vi.fn((e: string, l: L) => {
this.table.set(
e,
(this.table.get(e) ?? []).filter((x) => x !== l),
);
});
emit(e: string, ...a: unknown[]) {
for (const l of [...(this.table.get(e) ?? [])]) l({}, ...a);
}
total() {
return [...this.table.values()].reduce((n, l) => n + l.length, 0);
}
}
const accessors = () => ({
power: vi.mocked(electronPowerTrackerFor),
display: vi.mocked(electronDisplayTrackerFor),
application: vi.mocked(electronApplicationTrackerFor),
});
const clear = () => {
for (const a of Object.values(accessors())) a.mockClear();
};
class Inner extends InterceptorBase<{ event: SystemEvent }> {
readonly name = 'inner';
protected onActivate(): void {}
}
const wrapOf = (f: ReturnType<typeof fakeLaunch>) =>
optsOf(f).wrapSystemEventsSource as NonNullable<BugseeLaunchOptions['wrapSystemEventsSource']>;
const producersOf = (f: ReturnType<typeof fakeLaunch>) =>
(optsOf(f).systemTraceProducers ?? []).map((p: TraceProducer) => p.name);

it('builds each tracker THROUGH its registry accessor, keyed on the injected object, with the launch onError', () => {
clear();
const powerMonitor = new FakeEmitter();
const screen = Object.assign(new FakeEmitter(), { getAllDisplays: () => [] });
const app = new FakeEmitter();
const BrowserWindow = { getAllWindows: () => [] };
const onError = vi.fn();
const f = fakeLaunch();
launchMain('tok', {
ipcMain: fakeIpcMain().ipcMain,
launch: f.launch,
app,
powerMonitor,
screen,
BrowserWindow,
onError,
});
const a = accessors();
expect(a.power).toHaveBeenCalledExactlyOnceWith({ powerMonitor }, onError);
expect(a.display).toHaveBeenCalledExactlyOnceWith({ screen }, onError);
expect(a.application).toHaveBeenCalledExactlyOnceWith({ app, BrowserWindow }, onError);
});

it('the application tracker is built without a BrowserWindow key when none was injected', () => {
clear();
const app = new FakeEmitter();
const f = fakeLaunch();
launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch, app });
expect(accessors().application).toHaveBeenCalledExactlyOnceWith({ app }, undefined);
});

it('absent Electron objects mean those domains are simply off: no accessor, no producer, no wrapper', () => {
clear();
const f = fakeLaunch();
launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch });
for (const a of Object.values(accessors())) expect(a).not.toHaveBeenCalled();
expect(optsOf(f).systemTraceProducers).toBeUndefined();
expect(optsOf(f).wrapSystemEventsSource).toBeUndefined();
});

it('a powerMonitor alone is enough for the events mux (no app needed) and adds no trace producer', () => {
const powerMonitor = new FakeEmitter();
const f = fakeLaunch();
launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch, powerMonitor });
expect(optsOf(f).systemTraceProducers).toBeUndefined();
const mux = wrapOf(f)(new Inner());
expect(powerMonitor.total()).toBe(0); // lazy
const seen = vi.fn();
mux.on('event', seen);
powerMonitor.emit('suspend');
expect(seen).toHaveBeenCalledWith({ name: 'power_suspend' });
});

it('a screen adds the electron_displays producer next to the node set, once', () => {
const screen = Object.assign(new FakeEmitter(), { getAllDisplays: () => [] });
const f = fakeLaunch();
launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch, screen });
const names = producersOf(f);
expect(names).toContain('process-memory');
expect(names.filter((n: string) => n === 'electron-displays')).toHaveLength(1);
expect(names).not.toContain('electron-app-metrics');
});

it('an app adds app_metrics but not displays; a screen without app adds displays but not app_metrics', () => {
const f = fakeLaunch();
launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch, app: new FakeEmitter() });
expect(producersOf(f)).toContain('electron-app-metrics');
expect(producersOf(f)).not.toContain('electron-displays');
});

it('a legacy systemMetricsSampler with only a screen builds no producer list', () => {
const screen = Object.assign(new FakeEmitter(), { getAllDisplays: () => [] });
const f = fakeLaunch();
launchMain('tok', {
ipcMain: fakeIpcMain().ipcMain,
launch: f.launch,
screen,
systemMetricsSampler: () => [],
});
expect(optsOf(f).systemTraceProducers).toBeUndefined();
});

it('NEVER forwards the Electron objects or captureWindowEvents to the node launch', () => {
const f = fakeLaunch();
launchMain('tok', {
ipcMain: fakeIpcMain().ipcMain,
launch: f.launch,
app: new FakeEmitter(),
powerMonitor: new FakeEmitter(),
screen: new FakeEmitter(),
BrowserWindow: { getAllWindows: () => [] },
captureWindowEvents: true,
});
const keys = Object.keys(optsOf(f));
for (const key of [
'app',
'powerMonitor',
'screen',
'BrowserWindow',
'captureWindowEvents',
'ipcMain',
]) {
expect(keys).not.toContain(key);
}
});

it('captureWindowEvents:false turns the window domain off (no application tracker, no app listeners); the others stay', () => {
clear();
const app = new FakeEmitter();
const powerMonitor = new FakeEmitter();
const f = fakeLaunch();
launchMain('tok', {
ipcMain: fakeIpcMain().ipcMain,
launch: f.launch,
app,
powerMonitor,
captureWindowEvents: false,
});
expect(accessors().application).not.toHaveBeenCalled();
expect(accessors().power).toHaveBeenCalledOnce();
const mux = wrapOf(f)(new Inner());
mux.on('event', () => {});
expect(app.table.get('browser-window-created')).toBeUndefined();
expect(app.table.get('web-contents-created')).toBeUndefined();
expect(powerMonitor.total()).toBe(6);
});

it.each([
null,
0,
'',
'false',
'true',
1,
{},
])('an invalid captureWindowEvents (%j) is OFF and reported (fail closed)', (value) => {
clear();
const onError = vi.fn();
const f = fakeLaunch();
launchMain('tok', {
ipcMain: fakeIpcMain().ipcMain,
launch: f.launch,
app: new FakeEmitter(),
onError,
captureWindowEvents: value as never,
});
expect(accessors().application).not.toHaveBeenCalled();
expect(onError).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ message: expect.stringContaining('captureWindowEvents') }),
);
});

it('captureWindowEvents:true and undefined keep the window domain on, without a report', () => {
for (const value of [true, undefined]) {
clear();
const onError = vi.fn();
launchMain('tok', {
ipcMain: fakeIpcMain().ipcMain,
launch: fakeLaunch().launch,
app: new FakeEmitter(),
onError,
...(value !== undefined ? { captureWindowEvents: value } : {}),
});
expect(accessors().application).toHaveBeenCalledOnce();
expect(onError).not.toHaveBeenCalled();
}
});

it('the mux handed to node is LAZY: until subscribed no domain listener exists; subscribing attaches all, unsubscribing releases all', () => {
const powerMonitor = new FakeEmitter();
const screen = Object.assign(new FakeEmitter(), { getAllDisplays: () => [] });
const app = new FakeEmitter();
const win = Object.assign(new FakeEmitter(), {
id: 1,
isDestroyed: () => false,
webContents: Object.assign(new FakeEmitter(), { id: 11, isDestroyed: () => false }),
});
const f = fakeLaunch();
launchMain('tok', {
ipcMain: fakeIpcMain().ipcMain,
launch: f.launch,
app,
powerMonitor,
screen,
BrowserWindow: { getAllWindows: () => [win] },
});
const mux = wrapOf(f)(new Inner());
const owned = () =>
powerMonitor.total() + screen.total() + win.total() + win.webContents.total();
// launchMain itself registers render-process-gone on app; the domain listeners are the REST
const appBefore = app.total();
expect(owned()).toBe(0);
const off = mux.on('event', () => {});
expect(powerMonitor.total()).toBe(6);
expect(screen.total()).toBe(3);
expect(win.total()).toBe(6); // focus, blur, show, hide + one `closed` per window stage
off();
expect(owned()).toBe(0);
expect(app.total()).toBe(appBefore);
});
});
Loading