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
70 changes: 70 additions & 0 deletions .github/workflows/electron-compat.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
name: Electron compat (non-blocking)

# Early-warning lane for upcoming Electron majors (issue #116). It runs the REAL-Electron smoke
# (packages/instrumentation-tests/harness/electron-smoke.mts: real launchMain + launchRenderer in a
# `sandbox: true` window) against a chosen Electron dist-tag.
#
# NON-BLOCKING BY DESIGN: it only triggers on a schedule and by hand, never on push / pull_request, so it can
# never be a required check on a PR. A red alpha therefore shows up as a failed run on the Actions tab (and
# notifies the schedule's owner) without blocking anything. There is deliberately NO `continue-on-error`:
# GitHub reports a job that has it as successful, which would hide exactly the failure this lane exists for.
# The repo has no Electron dependency on purpose; the binary is installed into a scratch dir.

on:
schedule:
- cron: '17 4 * * *' # nightly
workflow_dispatch:
inputs:
electron:
description: 'Electron version or dist-tag to test (npm), e.g. alpha, latest, 46.0.0-alpha.1'
default: alpha
required: false

permissions:
contents: read

concurrency:
group: electron-compat-${{ github.ref }}-${{ inputs.electron || 'alpha' }}
cancel-in-progress: true

jobs:
smoke:
name: Real Electron smoke (${{ inputs.electron || 'alpha' }})
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v7

- name: Install pnpm
uses: pnpm/action-setup@v6

- name: Setup Node
uses: actions/setup-node@v7
with:
node-version: 22

- name: Install dependencies
run: pnpm install --frozen-lockfile

# The one network use: fetching the Electron binary (postinstall) into a scratch dir outside the repo.
- name: Install Electron
env:
ELECTRON_SPEC: ${{ inputs.electron || 'alpha' }}
run: |
mkdir -p "$RUNNER_TEMP/electron"
cd "$RUNNER_TEMP/electron"
npm init -y >/dev/null
npm install --no-audit --no-fund "electron@${ELECTRON_SPEC}"
# Fetch the binary explicitly: `require('electron')` downloads lazily and prints progress to stdout.
node node_modules/electron/install.js
node -e "process.stdout.write('ELECTRON_BIN=' + require('electron') + '\n')" >> "$GITHUB_ENV"
cat "$GITHUB_ENV"

# Chromium needs libs the runner image may lack; xvfb gives it a display for the (hidden) window.
- name: Install Electron runtime libraries
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends xvfb libgtk-3-0 libnss3 libasound2t64 libgbm1 libxss1 libxtst6

- name: Real-Electron smoke
run: xvfb-run -a pnpm --filter @bugsee/instrumentation-tests test:electron-smoke
6 changes: 5 additions & 1 deletion packages/electron/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,11 @@ Notes for Electron 45 and later:

- Screen, window and tab capture requests (`getDisplayMedia()`, and `getUserMedia()` with `chromeMediaSource`; `desktopCapturer.getSources()` itself only lists sources) reach `session.setPermissionRequestHandler` as `display-capture`, no longer `media`. If your app allows only `media`, a `getDisplayMedia`-based source will be denied. Allow `display-capture` for the window that hosts your source, and if your app also installs `session.setPermissionCheckHandler`, allow it there too. The `capturePage` source needs no permission.
- To capture a WebContents with your own `MediaRecorder` stream, use `chromeMediaSource: 'tab'` with `webContents.getMediaSourceId()`, or `session.setDisplayMediaRequestHandler`. The old `chromeMediaSource: 'desktop'` form with a WebContents source id fails with "Invalid state". The SDK never builds this stream itself; it records the one you supply.
- Sandboxed renderers (`sandbox: true`): a sandboxed preload must be CommonJS, and its `require` can load only Electron's built-in modules, not an external package or a sibling file. Bundle `@bugsee/electron/preload` into your single preload file (esbuild, webpack, Vite); copying `dist/preload.cjs` next to your preload does not work. The preload entry is a thin wrapper over `contextBridge` and `ipcRenderer`, and a test checks its TypeScript sources import nothing else and use none of the Node polyfills (`events`, `timers`, `url`, `Buffer`, `setImmediate`, `clearImmediate`) that Electron 45 removed from sandboxed preloads. The built output is not covered by a test: in one local `tsup` build, `dist/preload.cjs` contained no `require(` calls (the ESM build splits shared code into chunks, so use the CommonJS one). We have not run a real `sandbox: true` window on Electron 45.
- Sandboxed renderers (`sandbox: true`): a sandboxed preload must be CommonJS, and its `require` can load only Electron's built-in modules, not an external package or a sibling file. Bundle `@bugsee/electron/preload` into your single preload file (esbuild, webpack, Vite); copying `dist/preload.cjs` next to your preload does not work. The preload entry is a thin wrapper over `contextBridge` and `ipcRenderer`, and a test checks its TypeScript sources import nothing else and use none of the Node polyfills (`events`, `timers`, `url`, `Buffer`, `setImmediate`, `clearImmediate`) that Electron 45 removed from sandboxed preloads. The built output is not covered by a test: in one local `tsup` build, `dist/preload.cjs` contained no `require(` calls (the ESM build splits shared code into chunks, so use the CommonJS one).

Measured on a real Electron 45.0.0 (Chromium 156, Node 24.22) on macOS arm64, with the real `launchMain` and `launchRenderer` in a `sandbox: true`, `contextIsolation: true`, `nodeIntegration: false` window whose single-file preload bundles `@bugsee/electron/preload`: `process.sandboxed` was `true`; `Buffer` and `setImmediate` were `undefined` in the preload; the preload ran with no `preload-error` and exposed the bridge; the renderer received the owner session id over IPC; a renderer `console.log` landed in `logs.json` of the one bundle main uploaded (alongside `replay.bin`, `crash.json`, system traces and events); `onError` collected nothing. A preload that does `require('./sibling.cjs')` fails with "module not found", which is why it must be one file. `getDisplayMedia()` with a user gesture reached `setPermissionRequestHandler` as `display-capture` (not `media`), and denying it gave `NotAllowedError`. `packages/instrumentation-tests/harness/electron-smoke.mts` commits the sandbox, handshake, convergence and `onError` subset of these as assertions (it bundles the TypeScript sources, not the built `dist/preload.cjs`; the sibling-`require` failure and the `display-capture` routing are not asserted, `display-capture` is only printed), and the non-blocking `electron-compat` workflow runs it nightly and on demand against the npm `alpha` dist-tag of `electron` (observed passing on Linux under xvfb with 46.0.0-alpha.2; on Linux it runs with Chromium's `--no-sandbox`, so it covers the sandboxed-preload environment but not the OS-sandboxed renderer path).

Not run: Windows crash capture with the `<app>_wer.dll` WER helper; a real `crashReporter` crash and minidump (only `start()` was exercised); the opt-in pixel-video path (`capturePage` / `MediaRecorder`) on real Electron 45; the ASAR `fs.open` change against a packaged `app.asar`.

## Native crashes on Windows

Expand Down
7 changes: 7 additions & 0 deletions packages/instrumentation-tests/harness/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,10 @@ loss would hide. Every other artifact in those cases is still judged normally, a
control in that set is the safety rail: an unknown staging time must NEVER expire, or the launch after
an SDK upgrade deletes every pending crash report. Injecting `firstSeenMs ?? 0` there is caught by the
pre-existing P2 in set H, 23 times over.

## Real-Electron smoke

`electron-smoke.mts` boots the real `launchMain` + `launchRenderer` in a `sandbox: true` window on a real
Electron binary (the repo has no Electron dependency, so pass one): `ELECTRON_BIN=/path/to/electron pnpm --filter
@bugsee/instrumentation-tests test:electron-smoke` (on Linux wrap it in `xvfb-run -a`). No network; the transport is
a recorder. Run nightly and on demand, non-blocking, by `.github/workflows/electron-compat.yml` (issue #116).
126 changes: 126 additions & 0 deletions packages/instrumentation-tests/harness/electron-smoke.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/**
* Real-Electron smoke: the real `launchMain` + `launchRenderer` in a `sandbox: true` window on a REAL
* Electron binary. Every other Electron test in the repo drives a fake IPC bus; this is the only one
* that proves the sandboxed-preload + session-handshake + renderer→main convergence path on the real thing.
*
* ELECTRON_BIN=/path/to/electron pnpm --filter @bugsee/instrumentation-tests exec tsx harness/electron-smoke.mts
*
* The repo deliberately has no Electron dependency, so the binary is supplied (the `electron-compat`
* workflow installs `electron@alpha` into a scratch dir). No network is used: the transport is a recorder.
* On Linux run it under a display (`xvfb-run -a …`); the window is created hidden.
*
* Exit code: 0 all assertions held, 1 an assertion failed, 2 the harness could not run.
*/
import { spawnSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { buildSync } from 'esbuild';

const here = dirname(fileURLToPath(import.meta.url));
const bin = process.env.ELECTRON_BIN;
if (!bin) {
console.error('electron-smoke: set ELECTRON_BIN to a real Electron executable');
process.exit(2);
}

const dir = mkdtempSync(join(tmpdir(), 'bugsee-electron-smoke-'));
try {
const common = { bundle: true, logLevel: 'error' as const, sourcemap: false };
// Main + preload run under Electron's Node (CJS, `electron` is the runtime-provided built-in).
for (const [entry, outfile] of [
['main-entry.ts', 'main.cjs'],
['preload-entry.ts', 'preload.cjs'],
] as const) {
buildSync({
...common,
entryPoints: [join(here, 'electron-smoke', entry)],
outfile: join(dir, outfile),
platform: 'node',
format: 'cjs',
external: ['electron'],
});
}
buildSync({
...common,
entryPoints: [join(here, 'electron-smoke/renderer-entry.ts')],
outfile: join(dir, 'renderer.js'),
platform: 'browser',
format: 'iife',
});
writeFileSync(
join(dir, 'index.html'),
'<!doctype html><html><body><script src="renderer.js"></script></body></html>',
);
writeFileSync(
join(dir, 'package.json'),
JSON.stringify({ name: 'bugsee-electron-smoke', main: 'main.cjs' }),
);
} catch (e) {
console.error('electron-smoke: bundling failed', e);
rmSync(dir, { recursive: true, force: true });
process.exit(2);
}

const env: NodeJS.ProcessEnv = { ...process.env, BUGSEE_SMOKE_DIR: dir };
delete env.ELECTRON_RUN_AS_NODE; // would make the binary a plain Node and skip the app entirely
// `--no-sandbox` turns off Chromium's OS-level renderer sandbox, which a CI container cannot set up (no SUID
// helper). So on Linux this lane covers the sandboxed-PRELOAD environment (`sandbox: true`: no Node polyfills,
// built-ins-only `require`, `process.sandboxed`), NOT the OS-sandboxed renderer path; only a run without the
// flag (e.g. the macOS measurement in the README) exercises that.
const args = process.platform === 'linux' ? ['--no-sandbox', dir] : [dir];
Comment thread
krassx marked this conversation as resolved.
Resolved
const run = spawnSync(bin, args, { env, encoding: 'utf8', timeout: 120_000 });
rmSync(dir, { recursive: true, force: true });

const line = `${run.stdout ?? ''}`.split('\n').find((l) => l.startsWith('RESULT_JSON '));
if (!line) {
console.error('electron-smoke: no RESULT_JSON from Electron', {
status: run.status,
signal: run.signal,
});
console.error(run.stdout, run.stderr);
process.exit(2);
}
// biome-ignore lint/suspicious/noExplicitAny: the result is an ad-hoc probe object asserted field by field below.
const r: any = JSON.parse(line.slice('RESULT_JSON '.length));

const checks: Array<[string, boolean]> = [
['main process did not throw', r.fatal === undefined],
['sandboxed preload ran without error', r.preloadError === undefined],
['renderer launched', r.renderer?.ok === true],
[
'renderer received the owner session id over IPC',
typeof r.renderer?.sid === 'string' && r.renderer.sid.length > 0,
],
['preload exposed the bridge', r.renderer?.bridge === 'object'],
[
'preload runs in a sandboxed context (process.sandboxed)',
r.renderer?.probe?.sandboxed === true,
],
['no Buffer in sandboxed preload', r.renderer?.probe?.hasBuffer === 'undefined'],
['no setImmediate in sandboxed preload', r.renderer?.probe?.hasSetImmediate === 'undefined'],
['no node globals in the renderer', r.rendererGlobals === 'undefined/undefined'],
['main uploaded exactly one bundle', r.bundles === 1],
[
'bundle carries logs, replay and crash files',
['logs.json', 'replay.bin', 'crash.json'].every((f) => r.files?.includes(f)),
],
[
'renderer console landed in the main bundle (convergence)',
JSON.stringify(r.logs ?? '').includes('RENDERER-LOG-MARKER'),
],
['onError collected nothing', Array.isArray(r.errors) && r.errors.length === 0],
];
console.log(
`electron ${r.electron} · chrome ${r.chrome} · node ${r.node} · getDisplayMedia ${r.displayMedia} · perms ${JSON.stringify(r.perms)}`,
);
let failed = 0;
for (const [name, ok] of checks) {
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}`);
if (!ok) failed++;
}
if (failed) {
console.error(JSON.stringify({ ...r, logs: undefined }, null, 2));
process.exit(1);
}
121 changes: 121 additions & 0 deletions packages/instrumentation-tests/harness/electron-smoke/main-entry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Main-process half of the real-Electron smoke (see ../electron-smoke.mts). Bundled by the runner and
// executed INSIDE a real Electron main process: real `app` / `ipcMain` / `BrowserWindow` / `crashReporter`
// are handed to the real `launchMain`; only the HTTP transport is a recorder (no network is touched).
import { strFromU8, unzipSync } from 'fflate';
import { launchMain } from '../../../electron/src/main';

// The bundle runs under Electron's main process, where `require` is the CJS one.
// biome-ignore lint/suspicious/noExplicitAny: the Electron module is injected by the runtime, untyped here.
declare const require: (id: string) => any;
const electron = require('electron');
const { app, BrowserWindow, ipcMain, crashReporter, powerMonitor, screen, session } = electron;

const dir = process.env.BUGSEE_SMOKE_DIR as string;
const puts: Uint8Array[] = [];
const perms: string[] = [];
const json = (o: unknown) => new Uint8Array(Buffer.from(JSON.stringify(o)));
const none = { status: 200, headers: {}, body: new Uint8Array() };
const transport = async (url: string, o: { body?: Uint8Array } = {}) => {
if (url.endsWith('/v2/sessions'))
return { status: 200, headers: {}, body: json({ access_token: 'a' }) };
if (url.endsWith('/v2/issues'))
return {
status: 200,
headers: {},
body: json({ endpoint: 'https://s3.test/put', issueId: 'i', recordingId: 'r' }),
};
if (url === 'https://s3.test/put' && o.body) puts.push(o.body);
return none;
};
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
// Bound a step that is not itself asserted, so a hang there cannot swallow the assertions that matter.
const within = <T>(p: Promise<T>, ms = 10_000): Promise<T | string> =>
Promise.race([p, sleep(ms).then(() => `timed out after ${ms} ms`)]);
// Poll a condition instead of sleeping a fixed time, so a slow runner waits and a fast one does not.
async function until<T>(
read: () => Promise<T | undefined> | T | undefined,
tries = 80,
): Promise<T | undefined> {
for (let i = 0; i < tries; i++) {
const v = await read();
if (v) return v;
await sleep(250);
}
return undefined;
}

const out: Record<string, unknown> = {
electron: process.versions.electron,
chrome: process.versions.chrome,
node: process.versions.node,
};

app.whenReady().then(async () => {
try {
const errors: string[] = [];
session.defaultSession.setPermissionRequestHandler(
(_wc: unknown, permission: string, cb: (ok: boolean) => void) => {
perms.push(permission);
cb(false);
},
);
const client = launchMain('tok', {
ipcMain,
app,
powerMonitor,
screen,
BrowserWindow,
crashReporter,
transport,
captureNetwork: false,
capturedDataStore: 'memory',
detectHangs: false,
onError: (e: unknown) => errors.push(String((e as Error)?.stack ?? e)),
} as never);
// The configuration the README documents as the recommended one: sandboxed, isolated, no node.
const win = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
preload: `${dir}/preload.cjs`,
},
});
win.webContents.on('preload-error', (_e: unknown, _p: string, err: Error) => {
out.preloadError = String(err?.stack ?? err);
});
await win.loadFile(`${dir}/index.html`);
out.renderer = await until(() => win.webContents.executeJavaScript('window.__result'));
out.rendererGlobals = await win.webContents.executeJavaScript(
'typeof require + "/" + typeof process',
);
await client.logException(new Error('electron smoke'));
const bundle = await until(() => puts[0]);
if (bundle) {
const files = unzipSync(bundle);
out.files = Object.keys(files);
out.logs = JSON.parse(strFromU8(files['logs.json'] as Uint8Array));
}
await sleep(1000); // settle: a stray second upload would arrive after the first
out.bundles = puts.length;
out.errors = errors;
// Informational only (not asserted): which permission Electron routes getDisplayMedia through.
try {
out.displayMedia = await within(
win.webContents.executeJavaScript(
'navigator.mediaDevices.getDisplayMedia({video:true}).then(()=>"granted",e=>"denied:"+e.name)',
true,
),
);
} catch (e) {
out.displayMedia = `threw ${e}`;
}
out.perms = perms;
await within(client.stop());
} catch (e) {
out.fatal = String((e as Error)?.stack ?? e);
}
console.log(`RESULT_JSON ${JSON.stringify(out)}`);
app.exit(0);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// The single-file sandboxed preload an app is told to build (README: bundle `@bugsee/electron/preload`).
// A sandboxed preload can `require` only Electron's built-ins, so the runner bundles this to ONE file.
import { registerBugseePreload } from '../../../electron/src/preload';

// biome-ignore lint/suspicious/noExplicitAny: the Electron module is injected by the runtime, untyped here.
declare const require: (id: string) => any;
const electron = require('electron');
registerBugseePreload(electron);
// Probe what the sandbox really provides (Electron 45 removed the Node polyfills from sandboxed preloads).
electron.contextBridge.exposeInMainWorld('__probe', {
sandboxed: (process as unknown as { sandboxed?: boolean }).sandboxed,
hasBuffer: typeof Buffer,
hasSetImmediate: typeof setImmediate,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Renderer half of the real-Electron smoke: the real `launchRenderer` inside a sandboxed window.
import { launchRenderer } from '../../../electron/src/renderer';

const w = window as unknown as Record<string, unknown>;
(async () => {
try {
let sid: string | undefined;
await launchRenderer('tok', {
onSessionId: (s: string) => {
sid = s;
},
} as never);
console.log('RENDERER-LOG-MARKER hello from renderer');
// Let the streamed capture reach main before the result is published.
await new Promise((r) => setTimeout(r, 1500));
w.__result = { ok: true, sid, bridge: typeof w.__bugseeElectron, probe: w.__probe };
} catch (e) {
w.__result = { ok: false, err: String((e as Error)?.stack ?? e) };
}
})();
1 change: 1 addition & 0 deletions packages/instrumentation-tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"test:e2e": "vitest run",
"test:unit": "vitest run --config vitest.unit.config.ts",
"typecheck": "tsc --noEmit",
"test:electron-smoke": "tsx harness/electron-smoke.mts",
"test:invariants": "tsx harness/invariants.mts"
},
"dependencies": {
Expand Down
Loading