Skip to content
10 changes: 10 additions & 0 deletions .changeset/electron-gpu-hardware-extras.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@bugsee/node': minor
'@bugsee/electron': minor
---

New `@bugsee/node` launch option `hardwareExtras`: a function read live on every environment assemble whose `gpu` (`{vendor?, renderer?, gl_version?, gl_extensions?}`) is merged into `environment.hardware`. Only that typed key is merged, it never overrides the built-in hardware fields, and `undefined`, an unusable result, or a throw adds nothing (a throw goes to `onError`).

`@bugsee/electron` uses it to report the GPU as `environment.hardware.gpu`: `launchMain` reads `app.getGPUInfo('basic')` once (when `app` provides it), maps the active device's `vendorString`/`deviceString`, and the field appears on every report assembled after it settles. A rejection, an app without `getGPUInfo`, or a result with no usable strings omits the field; a late result after `client.stop()` is ignored. `gpuInfoType` (`'basic'` default, or `'complete'`) selects the `getGPUInfo` argument; `auxAttributes` GL strings are used when present. A caller-supplied `hardwareExtras` overrides the Electron GPU field by field.

`@bugsee/node` also exports `sanitizeHardwareGpu(raw)`, the helper that normalizes a GPU block (known keys only, strings trimmed, blanks dropped), so compositions merge GPU blocks by the same rules.
7 changes: 7 additions & 0 deletions .changeset/util-report-once.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@bugsee/util': minor
'@bugsee/node': patch
'@bugsee/electron': patch
---

`@bugsee/util` gains `reportOncePerMessage(onError)`: a wrapper that delivers each distinct failure to the host sink once (bounded memory). `hardwareExtras` (node, and the Electron composition of a caller-supplied one) now uses it, so an extra that throws on every report build reaches `onError` once instead of once per report. GPU block strings are now length-bounded (256 characters per field, 8192 for `gl_extensions`; longer values are truncated) because the environment is rebuilt for every report and stored with each queued bundle.
1 change: 1 addition & 0 deletions docs/PROGRESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,7 @@ solid), in slices:
`navigator`/`performance`/`screen`/`window` (`defaultBrowserTraceEnv()`); the old sampler copied `navigator` with a
spread, which drops the prototype accessors (`onLine`, `connection`, `deviceMemory`) on a real browser. Launch passes
its injected `window` and `scheduler`. The shared `PageLifecycleTracker` is done: the events source and the connection/orientation trackers subscribe to it.
- **ST6a (DONE, `feat/electron-gpu-hardware-extras`):** GPU info is ENVIRONMENT data (`environment.hardware.gpu`), through a new `@bugsee/node` launch option `hardwareExtras` (`() => {gpu?: {vendor?, renderer?, gl_version?, gl_extensions?}} | undefined`), read LIVE on every `getEnvironment()` and merged by `buildNodeEnvironment` (typed key only, sanitized, closed fields always win, undefined/empty/throw adds nothing, a throw goes to `onError`). `@bugsee/electron` `launchMain` passes a `GpuInfoCache` closure: `app.getGPUInfo('basic')` is kicked once after the first launch (optional on `ElectronAppLike`), `.catch` omits + reports (no unhandledRejection), a generation token drops a late resolve after `client.stop()`. Mapping is DEFENSIVE and UNVERIFIED against a real Electron: the active device (or the sole device) `vendorString` -> `vendor`, `deviceString` -> `renderer`, then `auxAttributes` (`glVendor`/`glRenderer`/`glVersion`/`glExtensions` -> `vendor`/`renderer`/`gl_version`/`gl_extensions`, all strings, trimmed, blanks dropped) fills the gaps; never a name from a numeric id; nothing usable -> no field. `launchMain({gpuInfoType: 'basic' | 'complete'})` (default `'basic'`; `'complete'` is expected to carry the `auxAttributes` GL strings but is heavier — also unverified) picks the `getGPUInfo` argument. A caller `hardwareExtras` gpu overrides the cache FIELD-WISE (its non-empty fields win; a gpu that cleans to nothing or a throw leaves the cache's). `hardwareExtras` is a KEPT relaunch option (a public node/bun/deno seam, like `systemProbe`); A node/umbrella `relaunch()` in an Electron main keeps the `launchMain` wrapper: it keeps serving the cached GPU after a relaunch (`stop()` aborts the in-flight read but never clears a resolved value, so reports draining during stop still carry it); a GPU that had not yet resolved before the relaunch is not re-requested. On macOS/Linux `'basic'` commonly yields only numeric ids, so `hardware.gpu` may be ABSENT until confirmed on a real Electron; the default stays `'basic'` (unverifiable here) and `'complete'` is available via `gpuInfoType`. Still open: the ST6 Electron trace/event producers.
- **ST4a (DONE, `feat/browser-app-state-fps`):** `app_state` (`AppStateProducer`: `foreground`/`background`, held step trace; the viewer's table is `started`/`foreground`/`background`) and `fps` (`FpsTracker` + `FpsProducer`: a `requestAnimationFrame` counter that runs ONLY while the page is visible — loop and timer torn down on hidden, a fresh window on visible, a zero-length window or no rAF emits nothing; nothing is reported before the first frame of a run, since rAF can be paused while the page says visible; afterwards the first frameless window is reported as 0 and a continuing stall goes quiet; no lifecycle = omitted). The traces env is now built from the INJECTED window + document (`browserTraceEnvFrom`; no fallback to `globalThis`, so a window without `performance.memory` omits the heap). **ST4b (DONE, `feat/browser-dark-freeze-events`):** `events.system` gains `dark_mode_changed` (`{dark}`; `matchMedia` taken from the INJECTED window, bound to it, per-attach guarded) and Page Lifecycle `freeze`/`resume` (document listeners via the shared `PageLifecycleTracker`). ST4 has nothing left open (ST4c below).
- **ST4c (DONE, `feat/browser-screen-size-main-thread-lag`):** `screen_size` (`ScreenSizeTracker` + `ScreenSizeProducer`: value shape `{width, height, dpr}` in CSS px — NOT `displays`; held, de-duplicated step trace; initial value at start; re-read on `resize` (listened for on the injected window by the tracker — no new shared-lifecycle event, since nothing else consumes it and it would change every lifecycle subscriber's listener count) and `orientationchange` (via the shared lifecycle); omitted entirely when `screen` or `devicePixelRatio` is not a finite positive number; known staleness: moving the window to a monitor with the same DPR but a different size fires no `resize`, and iOS Safari's `screen.width/height` do not swap on rotation — a `(resolution: Xdppx)` matchMedia/`screen` change listener is a follow-up) and `main_thread_lag_ms` (`MainThreadLagTracker` + `MainThreadLagProducer`: TIMER DRIFT: on each 1 s scheduler tick on the page's main thread, `lag = max(0, now - (previousTickTime + intervalMs))` with the injected `performance.now`; the first tick compares against the run's start + interval; emitted EVERY tick as a polled (`hold:false`) trace — a measured ~0 is a true value. **What a reading means (measured in Chromium):** a tick fires late by (block end − the first due time the block covered), so a block B ≥ 1 s reads between B−1000 and B (1800 ms read 907..1797; 2500 ms read 1807), while a block shorter than 1 s that crosses no due tick reads exactly 0 (probability ≈ 1 − B/1000: ~30% for 700 ms, ~90% for 100 ms); one block is reported once (the next tick clamps to 0). It is NOT Node's ~10 ms event-loop monitor — sampling every 1000 ms is why short blocks can go unseen. Measured ONLY while visible: hidden tears the timer down and every visible start takes a FRESH baseline, so a hidden stretch never counts as lag. A throwing clock/scheduler at start rolls back; a throwing or non-finite clock at a tick is reported/skipped without reading the skipped interval as lag. No clock (`performance.now` must be a function), lifecycle, or a hidden page = omitted, no timer. **Honest limit:** long freezes are reported reliably, short jank only by luck; follow-ups if short jank matters: a finer internal timer reporting the MAX drift per 1 s window, or `PerformanceObserver('longtask')` where supported. Timer throttling the browser applies to a page that still says `visible` (occluded/minimised window, background tab without a `visibilitychange`) may also read as lag — UNVERIFIED, it could not be reproduced headless. **History:** a `MessageChannel` ping (re-arm on receipt, then once per tick) was built and rejected after measuring real Chromium: re-arming on receipt was a ~2.2M/s task loop, and a ping per tick reads ~0.1 ms for a block that starts after the ping returned — a plausible-healthy lie; it was deleted entirely, no `MessageChannel` in the traces env). Both are built under the same `env.lifecycle` gate as `app_state`/`fps`, so a `systemMetricsSampler` (`sensors:false`) replaces them too. Open: the viewer has no definition for either name yet (generic value block, design §13.3).
- **TR4 (DONE, `feat/power-tracker`):** `BatteryTracker` became the domain **`PowerTracker`** (`packages/trackers/src/browser/power-tracker.ts`), a singleton per window via `createTrackerRegistry` (`powerTrackerFor(env, onError)`, keyed on `env.window`, else `env.navigator`, else the env object; host key reads are guarded and reported). It takes ONLY `getBattery` from the env; every call (a relaunch included) goes through the registry `rebind`, handing the shared tracker the latest launch's `onError` (a defined one replaces, undefined keeps; the reporter is a mutable indirection) and `getBattery` (a defined one replaces; a tracker that had none kicks the request at once if running). It exposes a SINGLE `state` stage (rather than one per Battery Status event): `{level?, charging, chargingTimeS?, dischargingTimeS?}`, published on `levelchange`/`chargingchange`/`chargingtimechange`/`dischargingtimechange`. Omitted, never fabricated: a `level` that is not a number in [0,1] (so no `battery` trace, never NaN); non-finite or negative times; a zero `chargingTime` when full and charging (a battery-less desktop reports level 1, charging, 0); a zero `dischargingTime`. A throwing time getter costs only that field. **Retention rule (tested):** the resolved BatteryManager and the last snapshot survive the last unsubscribe (no second `getBattery()`); the DOM listeners do not, and re-attach with a fresh snapshot on the next subscriber. A `getBattery()` in flight at stop is ignored and re-requested next activation. `BatteryProducer` keeps `battery`/`charging` unchanged and adds `battery_charging_time_s`/`battery_discharging_time_s` (integer seconds). **Held-value disappearance rule:** the provider's held values cannot be retracted (it re-records them every `refreshMs`), so the two time traces use plain non-held `emit` with a producer-side change-only guard; a vanished time records nothing and is forgotten (a stale estimate is never refreshed). Consequence: an unchanged time AGES OUT of the rolling capture window; owner decision pending on a retract/release or end-marker mechanism.
Expand Down
3 changes: 2 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`, `bridge`, `post`, `launch`, `onSessionId`,
* - the Electron handles (`app`, `ipcMain`, `crashReporter`, `gpuInfoType`, `bridge`, `post`, `launch`, `onSessionId`,
* `nativeCrash`, `video`) belong to compositions that `relaunchWith` never re-runs (Electron has no
* `relaunch()`), 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 @@ -131,6 +131,7 @@ const RESET_OPTIONS: readonly string[] = [
'app',
'appToken',
'flushTimeoutMs',
'gpuInfoType',
'injectTraceMeta',
'instanceIdentity',
'onSpanProcessor',
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/carrier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ export const RELAUNCH_KEPT_OPTIONS: readonly string[] = [
'triggerPipeline',
'reportSnapshots',
'fileEncoders',
'hardwareExtras',
'process',
'window',
'document',
Expand Down
125 changes: 125 additions & 0 deletions packages/electron/src/gpu-hardware.integration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// launchMain -> the REAL @bugsee/node launch -> a really assembled + uploaded bundle: `request.json`'s
// environment.hardware.gpu appears once the (fake) app.getGPUInfo settles, and is absent before it.

import type { HttpRequestOptions, HttpResponse, HttpTransport } from '@bugsee/core';
import { createMemoryCaptureStore } from '@bugsee/core';
import { type NodeRuntime, realSystemProbe } from '@bugsee/node';
import { strFromU8, unzipSync } from '@bugsee/util';
import { describe, expect, it, vi } from 'vitest';
import { launchMain } from './launch-main';

const jsonBody = (obj: unknown): Uint8Array => new Uint8Array(Buffer.from(JSON.stringify(obj)));
const flush = () => new Promise<void>((resolve) => setImmediate(resolve));

function recordingTransport() {
const puts: Uint8Array[] = [];
const fn = vi.fn<HttpTransport>(async (url: string, options: HttpRequestOptions = {}) => {
if (url.endsWith('/v2/sessions')) {
return { status: 200, headers: {}, body: jsonBody({ access_token: 'access' }) };
}
if (url.endsWith('/v2/issues')) {
return {
status: 200,
headers: {},
body: jsonBody({ endpoint: 'https://s3.test/put', issueId: 'i1', recordingId: 'r1' }),
};
}
if (url === 'https://s3.test/put') {
puts.push(options.body as Uint8Array);
}
return { status: 200, headers: {}, body: new Uint8Array() } satisfies HttpResponse;
});
return { fn, puts };
}

const fakeProcess = (): NodeRuntime => {
const proc = { on: () => proc, off: () => proc, exit: () => {} } as unknown as NodeRuntime;
return proc;
};

const ipcMain = { on: () => {}, removeListener: () => {} };

const bundleOf = (put: Uint8Array) => unzipSync(put);
const hardwareOf = (put: Uint8Array) =>
(
JSON.parse(strFromU8(bundleOf(put)['request.json'] as Uint8Array)) as {
environment: { hardware: Record<string, unknown> };
}
).environment.hardware;

function launchWith(app: { on: () => void; getGPUInfo?: (t: 'basic') => Promise<unknown> }) {
const { fn: transport, puts } = recordingTransport();
const client = launchMain('tok', {
ipcMain,
app,
transport,
captureStore: createMemoryCaptureStore({ maxRecordingTimeMs: Number.POSITIVE_INFINITY }),
captureNetwork: false,
capturedDataStore: 'memory',
detectHangs: false,
process: fakeProcess(),
systemProbe: realSystemProbe,
systemMetricsSampler: () => [{ name: 'process_memory_rss', value: 42 }],
onError: vi.fn(),
carrier: {},
});
return { client, puts };
}

describe('Electron GPU -> real node launch -> assembled report', () => {
it('carries hardware.gpu on a report assembled after getGPUInfo resolves, and not before', async () => {
let resolve!: (v: unknown) => void;
const { client, puts } = launchWith({
on: () => {},
getGPUInfo: () => new Promise<unknown>((r) => (resolve = r)),
});

await client.logException(new Error('before'));
expect(puts).toHaveLength(1);
expect(hardwareOf(puts[0] as Uint8Array)).not.toHaveProperty('gpu');

resolve({ gpuDevice: [{ active: true, vendorString: 'NVIDIA', deviceString: 'RTX' }] });
await flush();
await client.logException(new Error('after'));
expect(puts).toHaveLength(2);
expect(hardwareOf(puts[1] as Uint8Array).gpu).toEqual({ vendor: 'NVIDIA', renderer: 'RTX' });
await client.stop();
});

it('a report still draining while client.stop() runs keeps hardware.gpu', async () => {
const { client, puts } = launchWith({
on: () => {},
getGPUInfo: async () => ({ gpuDevice: [{ active: true, vendorString: 'NVIDIA' }] }),
});
await flush();
void client.logException(new Error('in flight'));
await client.stop(5000);
expect(puts).toHaveLength(1);
expect(hardwareOf(puts[0] as Uint8Array).gpu).toEqual({ vendor: 'NVIDIA' });
});

it('a rejected getGPUInfo: launch succeeds, no unhandledRejection, node traces still emit, no gpu', async () => {
const unhandled = vi.fn();
process.on('unhandledRejection', unhandled);
try {
const { client, puts } = launchWith({
on: () => {},
getGPUInfo: () => Promise.reject(new Error('no acceleration')),
});
await flush();
await flush();
await client.logException(new Error('x'));
expect(puts).toHaveLength(1);
expect(hardwareOf(puts[0] as Uint8Array)).not.toHaveProperty('gpu');
const files = bundleOf(puts[0] as Uint8Array);
const traces = JSON.parse(strFromU8(files['traces.system.json'] as Uint8Array)) as Array<{
name: string;
}>;
expect(traces.map((t) => t.name)).toContain('process_memory_rss');
expect(unhandled).not.toHaveBeenCalled();
await client.stop();
} finally {
process.off('unhandledRejection', unhandled);
}
});
});
Loading