diff --git a/.changeset/electron-gpu-hardware-extras.md b/.changeset/electron-gpu-hardware-extras.md new file mode 100644 index 00000000..6baa2e93 --- /dev/null +++ b/.changeset/electron-gpu-hardware-extras.md @@ -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. diff --git a/.changeset/util-report-once.md b/.changeset/util-report-once.md new file mode 100644 index 00000000..e3efbb1a --- /dev/null +++ b/.changeset/util-report-once.md @@ -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. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 19646a99..3b13f666 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -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. diff --git a/packages/bugsee/src/relaunch-options.test.ts b/packages/bugsee/src/relaunch-options.test.ts index 9b421043..9a76227c 100644 --- a/packages/bugsee/src/relaunch-options.test.ts +++ b/packages/bugsee/src/relaunch-options.test.ts @@ -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, @@ -131,6 +131,7 @@ const RESET_OPTIONS: readonly string[] = [ 'app', 'appToken', 'flushTimeoutMs', + 'gpuInfoType', 'injectTraceMeta', 'instanceIdentity', 'onSpanProcessor', diff --git a/packages/core/src/carrier.ts b/packages/core/src/carrier.ts index bf3e12e2..3b1840f3 100644 --- a/packages/core/src/carrier.ts +++ b/packages/core/src/carrier.ts @@ -255,6 +255,7 @@ export const RELAUNCH_KEPT_OPTIONS: readonly string[] = [ 'triggerPipeline', 'reportSnapshots', 'fileEncoders', + 'hardwareExtras', 'process', 'window', 'document', diff --git a/packages/electron/src/gpu-hardware.integration.test.ts b/packages/electron/src/gpu-hardware.integration.test.ts new file mode 100644 index 00000000..e9021a44 --- /dev/null +++ b/packages/electron/src/gpu-hardware.integration.test.ts @@ -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((resolve) => setImmediate(resolve)); + +function recordingTransport() { + const puts: Uint8Array[] = []; + const fn = vi.fn(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 }; + } + ).environment.hardware; + +function launchWith(app: { on: () => void; getGPUInfo?: (t: 'basic') => Promise }) { + 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((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); + } + }); +}); diff --git a/packages/electron/src/gpu-info-cache.test.ts b/packages/electron/src/gpu-info-cache.test.ts new file mode 100644 index 00000000..c1b2d057 --- /dev/null +++ b/packages/electron/src/gpu-info-cache.test.ts @@ -0,0 +1,337 @@ +import { describe, expect, it, vi } from 'vitest'; +import { createGpuInfoCache, mapGpuInfo } from './gpu-info-cache'; + +const flush = () => new Promise((resolve) => setImmediate(resolve)); + +function deferred() { + let resolve!: (v: T) => void; + let reject!: (e: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +const basic = (devices: unknown[]) => ({ gpuDevice: devices }); + +describe('mapGpuInfo', () => { + it('uses the ACTIVE device strings, wherever it is in the list', () => { + const dev = (active: boolean, name: string) => ({ + vendorId: 1, + deviceId: 2, + active, + vendorString: `${name}-vendor`, + deviceString: `${name}-device`, + }); + const expected = (name: string) => ({ vendor: `${name}-vendor`, renderer: `${name}-device` }); + expect(mapGpuInfo(basic([dev(true, 'A'), dev(false, 'B'), dev(false, 'C')]))).toEqual( + expected('A'), + ); + expect(mapGpuInfo(basic([dev(false, 'A'), dev(true, 'B'), dev(false, 'C')]))).toEqual( + expected('B'), + ); + expect(mapGpuInfo(basic([dev(false, 'A'), dev(false, 'B'), dev(true, 'C')]))).toEqual( + expected('C'), + ); + }); + + it('takes the FIRST active device, and only a literal `active: true` counts', () => { + expect( + mapGpuInfo( + basic([ + { active: true, vendorString: 'First' }, + { active: true, vendorString: 'Second' }, + ]), + ), + ).toEqual({ vendor: 'First' }); + expect( + mapGpuInfo( + basic([ + { active: 1, vendorString: 'A' }, + { active: 'yes', vendorString: 'B' }, + ]), + ), + ).toBeUndefined(); + }); + + it('uses the only device when none is flagged active, but never guesses among several', () => { + expect(mapGpuInfo(basic([{ vendorString: 'V', deviceString: 'R' }]))).toEqual({ + vendor: 'V', + renderer: 'R', + }); + expect( + mapGpuInfo( + basic([ + { vendorString: 'A', deviceString: 'a' }, + { vendorString: 'B', deviceString: 'b' }, + ]), + ), + ).toBeUndefined(); + }); + + it('omits a field whose string is missing; never invents a vendor from a numeric id', () => { + expect(mapGpuInfo(basic([{ active: true, vendorId: 4318, vendorString: 'NVIDIA' }]))).toEqual({ + vendor: 'NVIDIA', + }); + expect(mapGpuInfo(basic([{ active: true, deviceString: 'RTX' }]))).toEqual({ renderer: 'RTX' }); + expect(mapGpuInfo(basic([{ active: true, vendorId: 4318, deviceId: 7 }]))).toBeUndefined(); + expect( + mapGpuInfo(basic([{ active: true, vendorString: ' ', deviceString: 5 }])), + ).toBeUndefined(); + }); + + it('fills vendor/renderer/gl_version/gl_extensions from auxAttributes (trimmed)', () => { + expect( + mapGpuInfo({ + gpuDevice: [ + { vendorId: 4318, deviceId: 7, active: true, vendorString: '', deviceString: '' }, + ], + auxAttributes: { + glVendor: ' NVIDIA Corporation ', + glRenderer: 'RTX 4090/PCIe', + glVersion: 'OpenGL ES 3.0', + glExtensions: 'GL_A GL_B', + }, + }), + ).toEqual({ + vendor: 'NVIDIA Corporation', + renderer: 'RTX 4090/PCIe', + gl_version: 'OpenGL ES 3.0', + gl_extensions: 'GL_A GL_B', + }); + }); + + it('works from auxAttributes alone (no gpuDevice), and device strings win over aux per field', () => { + expect(mapGpuInfo({ auxAttributes: { glRenderer: 'R' } })).toEqual({ renderer: 'R' }); + expect( + mapGpuInfo({ + gpuDevice: [{ active: true, vendorString: 'DevVendor' }], + auxAttributes: { glVendor: 'AuxVendor', glRenderer: 'AuxRenderer' }, + }), + ).toEqual({ vendor: 'DevVendor', renderer: 'AuxRenderer' }); + }); + + it('drops blank / non-string aux values and ignores a non-object aux; ids never become names', () => { + expect( + mapGpuInfo({ + gpuDevice: [{ active: true, vendorId: 4318, deviceId: 1 }], + auxAttributes: { glVendor: ' ', glRenderer: 5, glVersion: null, glExtensions: ['A'] }, + }), + ).toBeUndefined(); + expect(mapGpuInfo({ gpuDevice: [], auxAttributes: 'x' })).toBeUndefined(); + expect(mapGpuInfo({ gpuDevice: [], auxAttributes: null })).toBeUndefined(); + }); + + it.each([ + ['undefined', undefined], + ['null', null], + ['a string', 'gpu'], + ['no gpuDevice', {}], + ['a non-array gpuDevice', { gpuDevice: 'x' }], + ['an empty list', { gpuDevice: [] }], + ['non-object devices', { gpuDevice: [1, null, 'x'] }], + ])('returns undefined for %s', (_n, value) => { + expect(mapGpuInfo(value)).toBeUndefined(); + }); +}); + +describe('createGpuInfoCache', () => { + const info = basic([{ active: true, vendorString: 'V', deviceString: 'R' }]); + + it('is undefined until the Promise settles, then serves the mapped gpu', async () => { + const d = deferred(); + const getGPUInfo = vi.fn(() => d.promise); + const cache = createGpuInfoCache({ source: { getGPUInfo } }); + cache.start(); + expect(getGPUInfo).toHaveBeenCalledExactlyOnceWith('basic'); + expect(cache.current()).toBeUndefined(); + d.resolve(info); + await flush(); + expect(cache.current()).toEqual({ gpu: { vendor: 'V', renderer: 'R' } }); + }); + + it("passes the configured type to getGPUInfo (default 'basic')", () => { + const complete = vi.fn(() => new Promise(() => {})); + createGpuInfoCache({ source: { getGPUInfo: complete }, type: 'complete' }).start(); + expect(complete).toHaveBeenCalledExactlyOnceWith('complete'); + const dflt = vi.fn(() => new Promise(() => {})); + createGpuInfoCache({ source: { getGPUInfo: dflt } }).start(); + expect(dflt).toHaveBeenCalledExactlyOnceWith('basic'); + }); + + it('kicks getGPUInfo once even when start() is called repeatedly', () => { + const getGPUInfo = vi.fn(() => new Promise(() => {})); + const cache = createGpuInfoCache({ source: { getGPUInfo } }); + cache.start(); + cache.start(); + expect(getGPUInfo).toHaveBeenCalledTimes(1); + }); + + it('returns a copy, so a consumer cannot mutate the cache', async () => { + const cache = createGpuInfoCache({ source: { getGPUInfo: async () => info } }); + cache.start(); + await flush(); + (cache.current() as { gpu: { vendor?: string } }).gpu.vendor = 'hacked'; + expect(cache.current()).toEqual({ gpu: { vendor: 'V', renderer: 'R' } }); + }); + + it('a rejection becomes omit + onError, with NO unhandledRejection', async () => { + const unhandled = vi.fn(); + process.on('unhandledRejection', unhandled); + try { + const boom = new Error('no acceleration'); + const onError = vi.fn(); + const cache = createGpuInfoCache({ + source: { getGPUInfo: () => Promise.reject(boom) }, + onError, + }); + cache.start(); + await flush(); + await flush(); + expect(cache.current()).toBeUndefined(); + expect(onError).toHaveBeenCalledExactlyOnceWith(boom); + expect(unhandled).not.toHaveBeenCalled(); + } finally { + process.off('unhandledRejection', unhandled); + } + }); + + it('a rejection with no onError, and a throwing onError, stay silent', async () => { + const unhandled = vi.fn(); + process.on('unhandledRejection', unhandled); + try { + createGpuInfoCache({ source: { getGPUInfo: () => Promise.reject(new Error('x')) } }).start(); + const c2 = createGpuInfoCache({ + source: { getGPUInfo: () => Promise.reject(new Error('y')) }, + onError: () => { + throw new Error('sink'); + }, + }); + c2.start(); + await flush(); + await flush(); + expect(c2.current()).toBeUndefined(); + expect(unhandled).not.toHaveBeenCalled(); + } finally { + process.off('unhandledRejection', unhandled); + } + }); + + it('an async onError that rejects leaves NO unhandledRejection', async () => { + const unhandled = vi.fn(); + process.on('unhandledRejection', unhandled); + try { + createGpuInfoCache({ + source: { getGPUInfo: () => Promise.reject(new Error('x')) }, + onError: async () => { + throw new Error('async sink'); + }, + }).start(); + await flush(); + await flush(); + await new Promise((r) => setTimeout(r, 10)); + expect(unhandled).not.toHaveBeenCalled(); + } finally { + process.off('unhandledRejection', unhandled); + } + }); + + it('a synchronous throw from getGPUInfo is reported, not propagated', () => { + const boom = new Error('sync'); + const onError = vi.fn(); + const cache = createGpuInfoCache({ + source: { + getGPUInfo: () => { + throw boom; + }, + }, + onError, + }); + expect(() => cache.start()).not.toThrow(); + expect(onError).toHaveBeenCalledExactlyOnceWith(boom); + expect(cache.current()).toBeUndefined(); + }); + + it('a hostile result whose mapping throws is reported and omitted', async () => { + const hostile = { + get gpuDevice(): unknown { + throw new Error('getter'); + }, + }; + const onError = vi.fn(); + const cache = createGpuInfoCache({ source: { getGPUInfo: async () => hostile }, onError }); + cache.start(); + await flush(); + expect(cache.current()).toBeUndefined(); + expect(onError).toHaveBeenCalledTimes(1); + }); + + it('a late resolve after stop() is ignored (no cache write) and a late reject is not reported', async () => { + const d = deferred(); + const onError = vi.fn(); + const cache = createGpuInfoCache({ source: { getGPUInfo: () => d.promise }, onError }); + cache.start(); + cache.stop(); + d.resolve(info); + await flush(); + expect(cache.current()).toBeUndefined(); + + const d2 = deferred(); + const cache2 = createGpuInfoCache({ source: { getGPUInfo: () => d2.promise }, onError }); + cache2.start(); + cache2.stop(); + d2.reject(new Error('late')); + await flush(); + expect(onError).not.toHaveBeenCalled(); + }); + + it('stop() KEEPS an already-resolved value (reports still draining during stop must carry it)', async () => { + const cache = createGpuInfoCache({ source: { getGPUInfo: async () => info } }); + cache.start(); + await flush(); + cache.stop(); + expect(cache.current()).toEqual({ gpu: { vendor: 'V', renderer: 'R' } }); + }); + + it('a start() after stop() begins afresh, and the OLD promise cannot write into the new run', async () => { + const first = deferred(); + const second = deferred(); + const getGPUInfo = vi + .fn() + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise); + const cache = createGpuInfoCache({ source: { getGPUInfo } }); + cache.start(); + cache.stop(); + cache.start(); + expect(getGPUInfo).toHaveBeenCalledTimes(2); + first.resolve(basic([{ active: true, vendorString: 'OLD' }])); + await flush(); + expect(cache.current()).toBeUndefined(); + second.resolve(basic([{ active: true, vendorString: 'NEW' }])); + await flush(); + expect(cache.current()).toEqual({ gpu: { vendor: 'NEW' } }); + }); + + it.each([ + ['no source', undefined], + ['a source without getGPUInfo', {}], + ['a non-function getGPUInfo', { getGPUInfo: 5 as never }], + ])('%s: nothing cached, no error', (_n, source) => { + const onError = vi.fn(); + const cache = createGpuInfoCache({ source, onError }); + expect(() => { + cache.start(); + cache.stop(); + }).not.toThrow(); + expect(cache.current()).toBeUndefined(); + expect(onError).not.toHaveBeenCalled(); + }); + + it('tolerates being used with no options at all', () => { + const cache = createGpuInfoCache(); + cache.start(); + expect(cache.current()).toBeUndefined(); + }); +}); diff --git a/packages/electron/src/gpu-info-cache.ts b/packages/electron/src/gpu-info-cache.ts new file mode 100644 index 00000000..c7055e03 --- /dev/null +++ b/packages/electron/src/gpu-info-cache.ts @@ -0,0 +1,123 @@ +// GpuInfoCache — the Electron main process's GPU description, for `environment.hardware.gpu`. +// +// `app.getGPUInfo('basic')` returns a PROMISE, and the environment is assembled synchronously, so the +// answer is kicked once at launch, cached when (if) it settles, and read live through `current()`. Until +// it settles — or forever, when it rejects (a Linux host without GPU acceleration does) — `current()` is +// `undefined` and the report simply carries no `hardware.gpu`. Nothing here may throw into the host app or +// leave a rejected Promise unhandled (the session owner's own unhandled-rejection detection would report it). +// +// `electron` is injected (`ElectronGpuSourceLike`); this package keeps no electron dependency. + +import type { HardwareExtras, HardwareGpu } from '@bugsee/node'; +import { reportGuarded } from '@bugsee/util'; + +/** The slice of Electron's `app` the cache needs. Optional on `ElectronAppLike`: older Electron has none. */ +export interface ElectronGpuSourceLike { + getGPUInfo(type: GpuInfoType): Promise; +} + +/** Electron's `app.getGPUInfo` argument. */ +export type GpuInfoType = 'basic' | 'complete'; + +export interface GpuInfoCacheOptions { + /** Electron's `app` (or anything with `getGPUInfo`). When absent or without `getGPUInfo`, nothing is ever cached. */ + source?: Partial | undefined; + /** The `getGPUInfo` argument. Default `'basic'`. */ + type?: GpuInfoType; + /** Sink for a rejected/throwing `getGPUInfo` (omit-never-fabricate: the error is reported, the field is absent). */ + onError?: (error: unknown) => void; +} + +export interface GpuInfoCache { + /** Kick `getGPUInfo(type)` once. A second call while started is a no-op. Never throws. */ + start(): void; + /** Abort the in-flight read: a late resolve/reject is ignored. An ALREADY-resolved value is kept (reports still draining on stop need it). */ + stop(): void; + /** The cached `hardware` extra, or `undefined` while unsettled / failed / unusable. */ + current(): HardwareExtras | undefined; +} + +const nonEmpty = (value: unknown): string | undefined => + typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined; + +/** + * Maps Electron's GPU info to the `hardware.gpu` block, defensively. The shapes are UNVERIFIED against a real + * Electron: `'basic'` is documented as `{ gpuDevice: [{ vendorId, deviceId, active, vendorString?, + * deviceString?, … }], auxAttributes? }` and often carries only the numeric ids; `'complete'` is heavier and + * is expected to carry `auxAttributes.glVendor/glRenderer/glVersion/glExtensions`. + * + * The ACTIVE device is used (or the only device when exactly one is listed — never a guess among several): + * `vendorString` -> `vendor`, `deviceString` -> `renderer`. `auxAttributes` (when present) fills what the + * device left empty: `glVendor` -> `vendor`, `glRenderer` -> `renderer`, `glVersion` -> `gl_version`, + * `glExtensions` -> `gl_extensions` (a string). Values are trimmed and empty/whitespace-only ones dropped; a + * numeric id is NEVER turned into a name. Nothing usable -> `undefined`. + */ +export function mapGpuInfo(info: unknown): HardwareGpu | undefined { + if (typeof info !== 'object' || info === null) return undefined; + const { gpuDevice, auxAttributes } = info as { gpuDevice?: unknown; auxAttributes?: unknown }; + const objects = Array.isArray(gpuDevice) + ? gpuDevice.filter((d): d is Record => typeof d === 'object' && d !== null) + : []; + const device = + objects.find((d) => d.active === true) ?? (objects.length === 1 ? objects[0] : undefined); + const aux = + typeof auxAttributes === 'object' && auxAttributes !== null + ? (auxAttributes as Record) + : {}; + const vendor = nonEmpty(device?.vendorString) ?? nonEmpty(aux.glVendor); + const renderer = nonEmpty(device?.deviceString) ?? nonEmpty(aux.glRenderer); + const glVersion = nonEmpty(aux.glVersion); + const glExtensions = nonEmpty(aux.glExtensions); + const gpu: HardwareGpu = { + ...(vendor !== undefined ? { vendor } : {}), + ...(renderer !== undefined ? { renderer } : {}), + ...(glVersion !== undefined ? { gl_version: glVersion } : {}), + ...(glExtensions !== undefined ? { gl_extensions: glExtensions } : {}), + }; + return Object.keys(gpu).length > 0 ? gpu : undefined; +} + +export function createGpuInfoCache(options: GpuInfoCacheOptions = {}): GpuInfoCache { + let generation = 0; + let started = false; + let gpu: HardwareGpu | undefined; + + // absorbs a throwing sink AND a rejected promise from an async one; the cache stays silent toward the host + const report = (error: unknown): void => reportGuarded(options.onError, error); + + return { + start(): void { + if (started) return; + started = true; + const mine = ++generation; + const source = options.source; + if (source === undefined || typeof source.getGPUInfo !== 'function') return; + try { + Promise.resolve(source.getGPUInfo(options.type ?? 'basic')).then( + (info) => { + if (mine !== generation) return; // stopped (or restarted) since: ignore, never write + try { + gpu = mapGpuInfo(info); + } catch (error) { + report(error); + } + }, + (error: unknown) => { + if (mine === generation) report(error); + }, + ); + } catch (error) { + report(error); // getGPUInfo threw synchronously + } + }, + stop(): void { + started = false; + generation++; // a late resolve/reject of the in-flight read is now ignored + // The cached value is deliberately KEPT: core `stop()` drains pending reports AFTER this runs, and + // they must still carry hardware.gpu. A new `launchMain` builds a new cache, so nothing leaks. + }, + current(): HardwareExtras | undefined { + return gpu === undefined ? undefined : { gpu: { ...gpu } }; + }, + }; +} diff --git a/packages/electron/src/launch-main.test.ts b/packages/electron/src/launch-main.test.ts index 9ce96e99..93c074a8 100644 --- a/packages/electron/src/launch-main.test.ts +++ b/packages/electron/src/launch-main.test.ts @@ -509,6 +509,253 @@ describe('launchMain - blackout is forwarded to every renderer (privacy)', () => }); }); +describe('launchMain — GPU info as environment.hardware.gpu (ST6a)', () => { + const flush = () => new Promise((resolve) => setImmediate(resolve)); + const gpuInfo = { + gpuDevice: [ + { vendorId: 4318, deviceId: 1, active: true, vendorString: 'NVIDIA', deviceString: 'RTX' }, + ], + }; + const extrasOf = (f: ReturnType) => + (f.received as { options: BugseeLaunchOptions }).options.hardwareExtras as () => unknown; + const appWith = (getGPUInfo?: (t: 'basic') => Promise) => ({ + on: vi.fn(), + ...(getGPUInfo !== undefined ? { getGPUInfo } : {}), + }); + + it('a resolved getGPUInfo shows up on the NEXT environment assemble, not before', async () => { + let resolve!: (v: unknown) => void; + const getGPUInfo = vi.fn(() => new Promise((r) => (resolve = r))); + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app: appWith(getGPUInfo), + }); + expect(getGPUInfo).toHaveBeenCalledExactlyOnceWith('basic'); + expect(extrasOf(f)()).toBeUndefined(); + resolve(gpuInfo); + await flush(); + expect(extrasOf(f)()).toEqual({ gpu: { vendor: 'NVIDIA', renderer: 'RTX' } }); + }); + + it('a rejected getGPUInfo: launch succeeds, no unhandledRejection, no gpu, error reported', async () => { + const unhandled = vi.fn(); + process.on('unhandledRejection', unhandled); + try { + const boom = new Error('no acceleration'); + const onError = vi.fn(); + const f = fakeLaunch(); + const client = launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app: appWith(() => Promise.reject(boom)), + onError, + }); + await flush(); + await flush(); + expect(client).toBe(f.client); + expect(extrasOf(f)()).toBeUndefined(); + expect(onError).toHaveBeenCalledWith(boom); + expect(unhandled).not.toHaveBeenCalled(); + } finally { + process.off('unhandledRejection', unhandled); + } + }); + + it('a late resolve after client.stop() is ignored', async () => { + let resolve!: (v: unknown) => void; + const f = fakeLaunch(); + const client = launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app: appWith(() => new Promise((r) => (resolve = r))), + }); + await client.stop(); + resolve(gpuInfo); + await flush(); + expect(extrasOf(f)()).toBeUndefined(); + }); + + it('the wrapper keeps serving an already-resolved GPU after client.stop() (reports still draining)', async () => { + const f = fakeLaunch(); + const client = launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app: appWith(async () => gpuInfo), + }); + await flush(); + await client.stop(); + expect(extrasOf(f)()).toEqual({ gpu: { vendor: 'NVIDIA', renderer: 'RTX' } }); + }); + + it('an app without getGPUInfo (older Electron / bare fake) just omits, no error', async () => { + const onError = vi.fn(); + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app: appWith(), + onError, + }); + await flush(); + expect(extrasOf(f)()).toBeUndefined(); + expect(onError).not.toHaveBeenCalled(); + }); + + it('no app at all: hardwareExtras is still wired and answers undefined', () => { + const f = fakeLaunch(); + launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch }); + expect(extrasOf(f)()).toBeUndefined(); + }); + + it('a caller gpu overrides the cache FIELD-WISE: its non-empty fields win, the rest come from the cache', async () => { + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app: appWith(async () => gpuInfo), + hardwareExtras: () => ({ gpu: { vendor: 'Mine', gl_version: ' 3.0 ' } }), + }); + await flush(); + expect(extrasOf(f)()).toEqual({ + gpu: { vendor: 'Mine', renderer: 'RTX', gl_version: '3.0' }, + }); + }); + + it('a caller gpu that is the ONLY source (cache unsettled) is reported as given', () => { + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app: appWith(() => new Promise(() => {})), + hardwareExtras: () => ({ gpu: { vendor: 'Mine' } }), + }); + expect(extrasOf(f)()).toEqual({ gpu: { vendor: 'Mine' } }); + }); + + it.each([ + ['no gpu', {}], + ['an empty gpu', { gpu: {} }], + ['a null gpu', { gpu: null }], + ['a blank vendor', { gpu: { vendor: '' } }], + ['a whitespace vendor', { gpu: { vendor: ' ' } }], + ['undefined', undefined], + ])('a caller extra returning %s does NOT hide the cache GPU', async (_n, value) => { + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app: appWith(async () => gpuInfo), + hardwareExtras: () => value as never, + }); + await flush(); + expect(extrasOf(f)()).toEqual({ gpu: { vendor: 'NVIDIA', renderer: 'RTX' } }); + }); + + it('a throwing caller extra falls back to the cache and is reported (a throwing sink is survived)', async () => { + const boom = new Error('caller'); + const onError = vi.fn(); + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app: appWith(async () => gpuInfo), + hardwareExtras: () => { + throw boom; + }, + onError, + }); + await flush(); + expect(extrasOf(f)()).toEqual({ gpu: { vendor: 'NVIDIA', renderer: 'RTX' } }); + expect(onError).toHaveBeenCalledWith(boom); + // polled on every report build: the same failure reaches the sink ONCE, a different one is still reported + extrasOf(f)(); + extrasOf(f)(); + expect(onError).toHaveBeenCalledTimes(1); + + const f2 = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f2.launch, + app: appWith(async () => gpuInfo), + hardwareExtras: () => { + throw boom; + }, + onError: () => { + throw new Error('sink'); + }, + }); + await flush(); + expect(extrasOf(f2)()).toEqual({ gpu: { vendor: 'NVIDIA', renderer: 'RTX' } }); + }); + + it("passes gpuInfoType to getGPUInfo (default 'basic') and does not forward it to node launch", () => { + const getGPUInfo = vi.fn(() => new Promise(() => {})); + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app: appWith(getGPUInfo), + gpuInfoType: 'complete', + }); + expect(getGPUInfo).toHaveBeenCalledExactlyOnceWith('complete'); + expect('gpuInfoType' in (f.received?.options ?? {})).toBe(false); + }); + + it('a throwing onError sink cannot stop client.stop() from running', async () => { + const ipc = fakeIpcMain(); + ipc.ipcMain.removeListener.mockImplementation(() => { + throw new Error('ipc broke'); + }); + const f = fakeLaunch(); + const client = launchMain('tok', { + ipcMain: ipc.ipcMain, + launch: f.launch, + onError: () => { + throw new Error('sink'); + }, + }); + await expect(client.stop()).resolves.toBe(true); + expect(f.stop).toHaveBeenCalled(); + }); + + it('an async onError that rejects during stop leaves NO unhandledRejection', async () => { + const unhandled = vi.fn(); + process.on('unhandledRejection', unhandled); + try { + const ipc = fakeIpcMain(); + ipc.ipcMain.removeListener.mockImplementation(() => { + throw new Error('ipc broke'); + }); + const f = fakeLaunch(); + const client = launchMain('tok', { + ipcMain: ipc.ipcMain, + launch: f.launch, + onError: async () => { + throw new Error('async sink'); + }, + }); + await expect(client.stop()).resolves.toBe(true); + await new Promise((r) => setTimeout(r, 10)); + expect(unhandled).not.toHaveBeenCalled(); + } finally { + process.off('unhandledRejection', unhandled); + } + }); + + it('a repeat launch (no internals) does not start the GPU read', () => { + const getGPUInfo = vi.fn(async () => gpuInfo); + const f = fakeLaunch({ internals: false }); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app: appWith(getGPUInfo), + }); + expect(getGPUInfo).not.toHaveBeenCalled(); + }); +}); + describe('launchMain — app identity', () => { const identityOf = (over: Partial[1]>) => { const f = fakeLaunch(); diff --git a/packages/electron/src/launch-main.ts b/packages/electron/src/launch-main.ts index 66ffc1f5..4719a99e 100644 --- a/packages/electron/src/launch-main.ts +++ b/packages/electron/src/launch-main.ts @@ -7,7 +7,12 @@ // import { ipcMain } from 'electron'; // launchMain(appToken, { ipcMain }); import { type AppIdentity, BlackoutToken, CaptureStoreToken } from '@bugsee/core'; -import { type Bugsee, type BugseeLaunchOptions, launchCore } from '@bugsee/node'; +import { + type Bugsee, + type BugseeLaunchOptions, + launchCore, + sanitizeHardwareGpu, +} from '@bugsee/node'; import { type CrashReporterLike, getCrashDumpsDirectory, @@ -25,9 +30,17 @@ export interface ElectronAppLike { details: { reason: string; exitCode?: number }, ) => void, ): unknown; + /** + * Electron's `app.getGPUInfo` — optional. When present, `getGPUInfo('basic')` is kicked once at launch and + * the active device's strings (when Electron supplies them) are reported as `environment.hardware.gpu` on + * every report assembled after it settles. A rejection, or an app without it, just omits the field. + */ + getGPUInfo?(type: 'basic' | 'complete'): Promise; } import type { CrashpadSessionMarker } from '@bugsee/core'; +import { reportGuarded, reportOncePerMessage } from '@bugsee/util'; +import { createGpuInfoCache, type GpuInfoType } from './gpu-info-cache'; import { createElectronMainControl, type IpcMainControlLike } from './main-control'; import { createElectronMainReceiver, type IpcMainLike } from './main-receiver'; import { createElectronNativeCrashSource, createNodeCrashDumpFs } from './native-crash-source'; @@ -63,6 +76,14 @@ export interface LaunchMainOptions extends BugseeLaunchOptions { * `ipcMain`, so @bugsee/electron keeps no electron dependency. */ app?: ElectronAppLike; + /** + * The `app.getGPUInfo` argument used for `environment.hardware.gpu`. Default `'basic'`. `'complete'` is + * expected to carry `auxAttributes.glRenderer`/`glVendor`/`glVersion` (more useful names) but is heavier. + * UNVERIFIED against a real Electron: on macOS/Linux `'basic'` commonly yields only numeric vendor/device + * ids, in which case `hardware.gpu` is absent (never guessed) until confirmed on a real Electron; pass + * `'complete'` for the GL strings. + */ + gpuInfoType?: GpuInfoType; /** Electron's `crashReporter` — when provided, native minidumps are captured, session-correlated. */ crashReporter?: CrashReporterLike; /** Extra params attached to native crash minidumps (merged under the session correlation). */ @@ -102,8 +123,16 @@ const chainAppIdentity = /** Launch Bugsee in the Electron main process: it owns the session and merges all renderers' capture. */ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee { - const { ipcMain, app, crashReporter, crashReporterExtra, video, launch, ...nodeOptions } = - options; + const { + ipcMain, + app, + gpuInfoType, + crashReporter, + crashReporterExtra, + video, + launch, + ...nodeOptions + } = options; // The Electron app knows its own version (package.json of the packaged app); offer it behind any source // the caller supplied, which is asked first. @@ -144,6 +173,34 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee } } + // GPU for environment.hardware.gpu: the cache is read LIVE by the node environment builder on every + // assemble (so a GPU that settles after launch lands on the next report); it is only STARTED once this + // launch is known to be the first (below). Precedence is FIELD-WISE: the cache's fields, overridden by + // whatever non-empty string fields a caller-supplied `hardwareExtras` gives (so a caller that supplies only + // `gl_version` keeps the cache's vendor/renderer). A caller gpu that cleans up to nothing, or a caller that + // throws (reported), leaves the cache's GPU untouched. + // `hardwareExtras` is a KEPT relaunch option, so a node/umbrella `relaunch()` in an Electron main keeps THIS + // wrapper (closing over this cache): it keeps serving the cached GPU after a relaunch (stop() does not clear + // it), but a GPU that had not yet resolved before the relaunch is not re-requested. + const gpuCache = createGpuInfoCache({ + source: app, + ...(gpuInfoType !== undefined ? { type: gpuInfoType } : {}), + ...(nodeOptions.onError !== undefined ? { onError: nodeOptions.onError } : {}), + }); + const callerExtras = nodeOptions.hardwareExtras; + const reportExtrasOnce = reportOncePerMessage(nodeOptions.onError); + nodeOptions.hardwareExtras = () => { + const cached = gpuCache.current(); + if (callerExtras === undefined) return cached; + try { + const own = sanitizeHardwareGpu(callerExtras()?.gpu); + return own === undefined ? cached : { gpu: { ...cached?.gpu, ...own } }; + } catch (error) { + reportExtrasOnce(error); // a throwing caller extra is polled on every report: tell the host once + return cached; + } + }; + const { client, internals } = (launch ?? launchCore)(appToken, nodeOptions); // `internals` is present only on the FIRST launch (the SDK is a per-process singleton); a repeat launch @@ -152,6 +209,8 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee return client; } + gpuCache.start(); + // The main client's blackout: the one state the whole session follows (renderers and pixel video). const blackout = client.getService(BlackoutToken); @@ -248,12 +307,13 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee (client as { stop: Bugsee['stop'] }).stop = ((timeout?: number): ReturnType => { // Electron cleanup must NEVER block the real shutdown: guard it so `stop(timeout)` always runs. try { + gpuCache.stop(); // a late getGPUInfo resolve must not write after stop (an already-resolved GPU is kept) offBlackout(); control.stop(); // broadcast stop to renderers + remove the hello listener receiver.stop(); videoController?.stop(); // stop pixel capture } catch (error) { - nodeOptions.onError?.(error); + reportGuarded(nodeOptions.onError, error); } return stop(timeout); }) as Bugsee['stop']; diff --git a/packages/node/src/environment.test.ts b/packages/node/src/environment.test.ts index cd40ff56..3f23fd7f 100644 --- a/packages/node/src/environment.test.ts +++ b/packages/node/src/environment.test.ts @@ -6,6 +6,7 @@ import { osPlatformToWire, realSystemProbe, type SystemProbe, + sanitizeHardwareGpu, } from './environment'; const fakeProbe: SystemProbe = { @@ -211,3 +212,153 @@ describe('realSystemProbe', () => { expect(typeof realSystemProbe.locale()).toBe('string'); }); }); + +describe('buildNodeEnvironment — hardwareExtras (hardware.gpu)', () => { + const closed = { + model: 'arm64', + manufacturer: 'Darwin', + cpu_count: 8, + memory_total: 16_384, + device_id: null, + }; + const build = (extras?: () => unknown, onError?: (e: unknown) => void): Record => + buildNodeEnvironment( + { + sdkVersion: '1.0.0', + ...(extras !== undefined + ? { hardwareExtras: extras as () => { gpu?: { vendor?: string } } } + : {}), + ...(onError !== undefined ? { onError } : {}), + }, + fakeProbe, + ).hardware as Record; + + it('merges a full gpu block alongside the closed fields', () => { + const gpu = { + vendor: 'Apple', + renderer: 'M3', + gl_version: 'OpenGL ES 3.0', + gl_extensions: 'A B', + }; + expect(build(() => ({ gpu }))).toEqual({ ...closed, gpu }); + }); + + it('accepts a partial block with gl_extensions as a string', () => { + expect(build(() => ({ gpu: { renderer: 'R', gl_extensions: 'A B' } })).gpu).toEqual({ + renderer: 'R', + gl_extensions: 'A B', + }); + }); + + it('reads the extra LIVE on every build', () => { + let value: unknown; + const extras = () => value; + expect(build(extras)).toEqual(closed); + value = { gpu: { vendor: 'V' } }; + expect(build(extras).gpu).toEqual({ vendor: 'V' }); + }); + + it.each([ + ['undefined', undefined], + ['an empty object', {}], + ['an empty gpu', { gpu: {} }], + ['a non-object gpu', { gpu: 'nvidia' }], + ['a null gpu', { gpu: null }], + [ + 'only ill-typed / blank / array fields', + { gpu: { vendor: 5, renderer: '', gl_version: ' ', gl_extensions: ['A'] } }, + ], + ])('adds nothing when the extra returns %s', (_name, value) => { + expect(build(() => value)).toEqual(closed); + }); + + it('null / non-object gpu is ignored quietly (not via a swallowed throw), and an empty gl_extensions string is dropped', () => { + const errors: unknown[] = []; + expect( + build( + () => ({ gpu: null }), + (e) => errors.push(e), + ), + ).toEqual(closed); + expect(errors).toEqual([]); + expect(build(() => ({ gpu: { vendor: 'V', gl_extensions: ' ' } })).gpu).toEqual({ + vendor: 'V', + }); + }); + + it('trims strings and drops whitespace-only ones', () => { + expect( + build(() => ({ gpu: { vendor: ' Apple ', renderer: ' \t', gl_version: ' 3.0\n' } })).gpu, + ).toEqual({ vendor: 'Apple', gl_version: '3.0' }); + }); + + it('drops unknown keys, at the top level and inside gpu', () => { + const hw = build(() => ({ gpu: { vendor: 'V', secret: 'x' }, model: 'evil', extra: 1 })); + expect(hw).toEqual({ ...closed, gpu: { vendor: 'V' } }); + }); + + it('never overrides the closed fields, even for a gpu-shaped hostile object', () => { + const hw = build(() => ({ gpu: { vendor: 'V' }, cpu_count: 99, device_id: 'x' })); + expect(hw.cpu_count).toBe(8); + expect(hw.device_id).toBeNull(); + }); + + it('a throwing extra adds nothing and is reported through onError', () => { + const boom = new Error('boom'); + const errors: unknown[] = []; + const hw = build( + () => { + throw boom; + }, + (e) => errors.push(e), + ); + expect(hw).toEqual(closed); + expect(errors).toEqual([boom]); + }); + + it('a throwing extra without onError, or with a throwing onError, still builds', () => { + const thrower = () => { + throw new Error('x'); + }; + expect(build(thrower)).toEqual(closed); + expect( + build(thrower, () => { + throw new Error('sink'); + }), + ).toEqual(closed); + }); +}); + +describe('sanitizeHardwareGpu: length bounds (the environment is rebuilt for every report)', () => { + it('truncates over-long fields (256 chars; gl_extensions 8192) and keeps values at the cap unchanged', () => { + const gpu = sanitizeHardwareGpu({ + vendor: 'v'.repeat(300), + renderer: 'r'.repeat(256), + gl_version: 'g'.repeat(257), + gl_extensions: 'e'.repeat(10_000), + }); + expect(gpu?.vendor).toBe('v'.repeat(256)); + expect(gpu?.renderer).toBe('r'.repeat(256)); + expect(gpu?.gl_version).toBe('g'.repeat(256)); + expect(gpu?.gl_extensions).toBe('e'.repeat(8192)); + expect(sanitizeHardwareGpu({ gl_extensions: 'x'.repeat(8192) })?.gl_extensions).toHaveLength( + 8192, + ); + expect(sanitizeHardwareGpu({ gl_extensions: 'x'.repeat(8193) })?.gl_extensions).toHaveLength( + 8192, + ); + }); + + it('trims BEFORE bounding, so padding does not eat the budget', () => { + expect(sanitizeHardwareGpu({ vendor: ` ${'v'.repeat(256)} ` })?.vendor).toBe('v'.repeat(256)); + }); +}); + +describe('sanitizeHardwareGpu (exported)', () => { + it('returns a trimmed copy of the known keys, or undefined', () => { + expect(sanitizeHardwareGpu({ vendor: ' V ', junk: 1 })).toEqual({ vendor: 'V' }); + expect(sanitizeHardwareGpu({ vendor: ' ' })).toBeUndefined(); + expect(sanitizeHardwareGpu(null)).toBeUndefined(); + expect(sanitizeHardwareGpu('x')).toBeUndefined(); + }); +}); diff --git a/packages/node/src/environment.ts b/packages/node/src/environment.ts index 7279bfb2..1c037238 100644 --- a/packages/node/src/environment.ts +++ b/packages/node/src/environment.ts @@ -57,6 +57,69 @@ export const realSystemProbe: SystemProbe = { locale: () => new Intl.DateTimeFormat().resolvedOptions().locale, }; +/** The GPU block of `environment.hardware.gpu` (the viewer reads exactly these keys). */ +export interface HardwareGpu { + vendor?: string; + renderer?: string; + gl_version?: string; + gl_extensions?: string; +} + +/** + * Extra `hardware` data a platform extension knows and Node cannot (e.g. Electron's GPU). Only the typed + * `gpu` key is merged; anything else the function returns is dropped. + */ +export interface HardwareExtras { + gpu?: HardwareGpu; +} + +const GPU_KEYS = ['vendor', 'renderer', 'gl_version', 'gl_extensions'] as const; + +// The environment is rebuilt for EVERY report (and persisted with each queued bundle), so a block cannot be +// unbounded: a GL extension list is a single multi-KB string. Longer values are TRUNCATED (kept, bounded). +const MAX_GPU_FIELD_CHARS = 256; +const MAX_GPU_EXTENSIONS_CHARS = 8192; + +/** + * Defensive copy of a GPU block: only the four known keys, only strings, trimmed, whitespace-only dropped, and + * length-bounded (256 chars per field, 8192 for `gl_extensions`; longer values are truncated, not dropped). + * Returns undefined when nothing usable remains, so no empty `gpu: {}` is ever reported. Exported so a + * platform composition (Electron) merges caller/cache GPU blocks by the same rules. + */ +export function sanitizeHardwareGpu(raw: unknown): HardwareGpu | undefined { + if (typeof raw !== 'object' || raw === null) return undefined; + const source = raw as Record; + const gpu: HardwareGpu = {}; + for (const key of GPU_KEYS) { + const value = source[key]; + if (typeof value !== 'string') continue; + const text = value.trim(); + if (text === '') continue; + const cap = key === 'gl_extensions' ? MAX_GPU_EXTENSIONS_CHARS : MAX_GPU_FIELD_CHARS; + gpu[key] = text.length > cap ? text.slice(0, cap) : text; + } + return Object.keys(gpu).length > 0 ? gpu : undefined; +} + +// Reads the extras LIVE; never throws (a throwing extra is reported and contributes nothing). +function readHardwareExtras( + extras: (() => HardwareExtras | undefined) | undefined, + onError: ((error: unknown) => void) | undefined, +): { gpu: HardwareGpu } | undefined { + if (extras === undefined) return undefined; + try { + const gpu = sanitizeHardwareGpu(extras()?.gpu); + return gpu !== undefined ? { gpu } : undefined; + } catch (error) { + try { + onError?.(error); + } catch { + // the error sink itself failed; nothing more to do + } + return undefined; + } +} + export interface NodeEnvironmentInput { /** SDK package version (sdk.version). */ sdkVersion: string; @@ -74,6 +137,10 @@ export interface NodeEnvironmentInput { debuggable?: boolean; /** hardware.device_id — persisted UUID supplied by the caller (null when none). */ deviceId?: string; + /** Live source of extra hardware data (hardware.gpu), read on every build. */ + hardwareExtras?: () => HardwareExtras | undefined; + /** Sink for a throwing `hardwareExtras`. */ + onError?: (error: unknown) => void; } // os.platform() → the wire's platform.type. Named for the OS as a user knows it, and matching the set @@ -115,6 +182,8 @@ export function buildNodeEnvironment( version: probe.runtimeVersion(), }, hardware: { + // Typed extras first so the closed fields below always win. + ...readHardwareExtras(input.hardwareExtras, input.onError), model: probe.machine(), manufacturer: probe.osType(), cpu_count: probe.cpuCount(), diff --git a/packages/node/src/index.test.ts b/packages/node/src/index.test.ts index bd886092..8724f939 100644 --- a/packages/node/src/index.test.ts +++ b/packages/node/src/index.test.ts @@ -65,6 +65,7 @@ const EXPECTED_EXPORTS = [ 'openServerRequest', 'realSystemProbe', 'runServerRequest', + 'sanitizeHardwareGpu', 'startServerSpan', 'wrapFetchHandler', ] as const; diff --git a/packages/node/src/index.ts b/packages/node/src/index.ts index 256ed750..d6438284 100644 --- a/packages/node/src/index.ts +++ b/packages/node/src/index.ts @@ -46,9 +46,12 @@ export { } from './detection-providers'; export { buildNodeEnvironment, + type HardwareExtras, + type HardwareGpu, type NodeEnvironmentInput, realSystemProbe, type SystemProbe, + sanitizeHardwareGpu, } from './environment'; export { createEventLoopWatchdog, diff --git a/packages/node/src/launch.test.ts b/packages/node/src/launch.test.ts index 9b7ba2ac..8e13cf30 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -3296,6 +3296,95 @@ describe('launch — application frame paths', () => { }); }); +describe('launch — hardwareExtras (environment.hardware.gpu seam)', () => { + const sessionHardware = (transport: ReturnType) => + ( + JSON.parse(String((transport.mock.calls[0]?.[1] as HttpRequestOptions).body)) as { + environment: EnvironmentEnvelope; + } + ).environment.hardware as Record; + + it('a report assembled after the extra settles carries hardware.gpu; one before does not', async () => { + let gpu: { vendor: string; renderer: string } | undefined; + const { fn: transport, puts } = recordingTransport(); + const client = launchTracked( + 'tok', + baseOptions({ + transport, + captureStore: memStore(), + hardwareExtras: () => (gpu ? { gpu } : undefined), + }), + ); + const hardwareOf = (put: Uint8Array) => + ( + JSON.parse(strFromU8(unzipSync(put)['request.json'] as Uint8Array)) as { + environment: EnvironmentEnvelope; + } + ).environment.hardware as Record; + + await client.logException(new Error('before')); + expect(puts).toHaveLength(1); + expect(hardwareOf(puts[0] as Uint8Array)).not.toHaveProperty('gpu'); + + gpu = { vendor: 'Apple', renderer: 'M3' }; + await client.logException(new Error('after')); + expect(puts).toHaveLength(2); + expect(hardwareOf(puts[1] as Uint8Array).gpu).toEqual({ vendor: 'Apple', renderer: 'M3' }); + }); + + it('the uploaded session environment carries hardware.gpu, and a throwing extra reaches onError without failing the report', async () => { + const transport = uploadTransport(); + const client = launchTracked( + 'tok', + baseOptions({ + transport, + captureStore: memStore(), + hardwareExtras: () => ({ gpu: { vendor: 'V', renderer: 'R' } }), + }), + ); + await client.logException(new Error('x')); + expect(sessionHardware(transport).gpu).toEqual({ vendor: 'V', renderer: 'R' }); + + const transport2 = uploadTransport(); + const errors: unknown[] = []; + const boom = new Error('boom'); + const client2 = launchTracked( + 'tok', + baseOptions({ + transport: transport2, + captureStore: memStore(), + carrier: {}, + onError: (e) => errors.push(e), + hardwareExtras: () => { + throw boom; + }, + }), + ); + await client2.logException(new Error('y')); + expect(sessionHardware(transport2)).not.toHaveProperty('gpu'); + expect(errors).toContain(boom); + }); + + it('a hardwareExtras that throws on EVERY report build reaches onError once per distinct error, not once per report', async () => { + const errors: unknown[] = []; + const { fn: transport, puts } = recordingTransport(); + const client = launchTracked( + 'tok', + baseOptions({ + transport, + captureStore: memStore(), + onError: (e) => errors.push(e), + hardwareExtras: () => { + throw new Error('always broken'); + }, + }), + ); + for (let i = 0; i < 3; i++) await client.logException(new Error(`r${i}`)); + expect(puts).toHaveLength(3); // every report was still built and uploaded + expect(errors.filter((e) => (e as Error).message === 'always broken')).toHaveLength(1); + }); +}); + describe('app identity detection', () => { const launchIdentity = (over: Partial = {}) => { const transport = uploadTransport(); diff --git a/packages/node/src/launch.ts b/packages/node/src/launch.ts index 1f279a90..27a03862 100644 --- a/packages/node/src/launch.ts +++ b/packages/node/src/launch.ts @@ -80,6 +80,7 @@ import { } from '@bugsee/node-utils'; import type { ActiveSpanStore } from '@bugsee/performance'; import { BugseeOption, DEFAULT_FILENAMES, type EnvironmentEnvelope } from '@bugsee/protocol'; +import { reportOncePerMessage } from '@bugsee/util'; import { createRequestScopedActiveSpanStore } from './active-span-store'; import { createNodeAppIdentitySource } from './app-identity-source'; import { type CpuProfiler, createCpuProfiler } from './cpu-profiler'; @@ -92,6 +93,7 @@ import { import { createDiskSpaceProducer, type StatFs } from './disk-space-producer'; import { buildNodeEnvironment, + type HardwareExtras, realSystemProbe, type SystemProbe, SystemProbeToken, @@ -404,6 +406,15 @@ export interface BugseeLaunchOptions { captureStore?: CaptureStore; /** System probe for the environment envelope. Default realSystemProbe. */ systemProbe?: SystemProbe; + /** + * Extra `environment.hardware` data a platform extension can supply (today only `gpu`: + * `{vendor?, renderer?, gl_version?, gl_extensions?}`; @bugsee/electron fills it from `app.getGPUInfo`). + * Called LIVE on every environment assemble, so a value that settles after launch appears on the next + * report and is simply absent before. Only the typed `gpu` key is merged (unknown keys are dropped); it + * never overrides the built-in hardware fields; `undefined`, an empty/unusable result, or a throw adds + * nothing (a throw is reported through `onError`). + */ + hardwareExtras?: () => HardwareExtras | undefined; /** CPU profiler override (advanced / tests — avoids the real node:inspector). Default the V8 profiler. */ cpuProfiler?: CpuProfiler; /** Hang watchdog factory (advanced / tests — avoids the real worker_threads). Default the real one. */ @@ -697,6 +708,7 @@ function buildLaunch(appToken: string, options: BugseeLaunchOptions = {}): Launc // (dotted) options are wire-translated to colon form inside buildNodeEnvironment. const probe = options.systemProbe ?? realSystemProbe; services.addService(defineService(SystemProbeToken, () => probe)); // container service + const environmentOnError = reportOncePerMessage(options.onError); const getEnvironment = () => buildNodeEnvironment( { @@ -706,6 +718,9 @@ function buildLaunch(appToken: string, options: BugseeLaunchOptions = {}): Launc ...(appIdentity.version !== undefined ? { appVersion: appIdentity.version } : {}), ...(appIdentity.build !== undefined ? { appBuild: appIdentity.build } : {}), ...(options.deviceId !== undefined ? { deviceId: options.deviceId } : {}), + ...(options.hardwareExtras !== undefined ? { hardwareExtras: options.hardwareExtras } : {}), + // a hardwareExtras that throws on every report build reaches the host sink once, not once per report + ...(options.onError !== undefined ? { onError: environmentOnError } : {}), }, probe, ); diff --git a/packages/util/src/index.test.ts b/packages/util/src/index.test.ts index a4f24bb3..220d9a5a 100644 --- a/packages/util/src/index.test.ts +++ b/packages/util/src/index.test.ts @@ -13,6 +13,7 @@ describe('@bugsee/util public surface', () => { 'createDeferred', 'describeValue', 'reportGuarded', + 'reportOncePerMessage', 'isBrowser', 'isBun', 'isCloudflareWorker', diff --git a/packages/util/src/index.ts b/packages/util/src/index.ts index 9f7f81b4..9f94bb8e 100644 --- a/packages/util/src/index.ts +++ b/packages/util/src/index.ts @@ -25,6 +25,7 @@ export { gunzipSync, gzipSync, strFromU8, strToU8, unzipSync, zipSync } from './ export { jsonSafeStringify } from './json-safe-stringify'; export { randomId } from './random-id'; export { reportGuarded } from './report-guarded'; +export { reportOncePerMessage } from './report-once'; export { sha256Hex } from './sha256'; export { resolveTimeOrigin } from './time-origin'; export { utf8ByteLength } from './utf8-byte-length'; diff --git a/packages/util/src/report-once.test.ts b/packages/util/src/report-once.test.ts new file mode 100644 index 00000000..afc7bf63 --- /dev/null +++ b/packages/util/src/report-once.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it, vi } from 'vitest'; +import { reportOncePerMessage } from './report-once'; + +describe('reportOncePerMessage (a repeating failure reaches the host sink once, not once per call)', () => { + it('forwards the first occurrence and drops repeats of the same error text', () => { + const sink = vi.fn(); + const report = reportOncePerMessage(sink); + report(new Error('boom')); + report(new Error('boom')); + report(new Error('boom')); + expect(sink).toHaveBeenCalledTimes(1); + }); + + it('forwards a different message, and distinguishes error types with the same text', () => { + const sink = vi.fn(); + const report = reportOncePerMessage(sink); + report(new Error('a')); + report(new Error('b')); + report(new TypeError('a')); + expect(sink.mock.calls.map((c) => String((c[0] as Error).message))).toEqual(['a', 'b', 'a']); + }); + + it('keys non-Error values by their text', () => { + const sink = vi.fn(); + const report = reportOncePerMessage(sink); + report('oops'); + report('oops'); + report(42); + report(42); + expect(sink).toHaveBeenCalledTimes(2); + }); + + it('remembers a bounded number of distinct messages (memory stays bounded) and then stops reporting NEW ones too', () => { + const sink = vi.fn(); + const report = reportOncePerMessage(sink); + for (let i = 0; i < 100; i++) report(new Error(`e${i}`)); + expect(sink).toHaveBeenCalledTimes(32); + }); + + it('without a sink it is a harmless no-op, and a throwing sink never escapes', () => { + expect(() => reportOncePerMessage(undefined)(new Error('x'))).not.toThrow(); + const throwing = vi.fn(() => { + throw new Error('sink'); + }); + expect(() => reportOncePerMessage(throwing)(new Error('x'))).not.toThrow(); + expect(throwing).toHaveBeenCalledTimes(1); + }); + + it('a value whose text cannot be read is still reported once', () => { + const sink = vi.fn(); + const report = reportOncePerMessage(sink); + const hostile = { + toString() { + throw new Error('no text'); + }, + }; + report(hostile); + report(hostile); + expect(sink).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/util/src/report-once.ts b/packages/util/src/report-once.ts new file mode 100644 index 00000000..391caa38 --- /dev/null +++ b/packages/util/src/report-once.ts @@ -0,0 +1,28 @@ +import { reportGuarded } from './report-guarded'; + +// Distinct failures remembered per reporter. A repeating failure is almost always ONE root cause polled many +// times (a reader that throws on every report build); the host needs to hear about it once, and the bound keeps a +// pathological stream of ever-different messages from growing memory without limit. +const MAX_DISTINCT = 32; + +/** + * Wrap a host `onError` sink so each distinct failure (error type + message, or the text of a non-Error) is + * delivered once; once {@link MAX_DISTINCT} distinct failures were forwarded, further new ones are dropped too. + * Delivery itself is {@link reportGuarded}: a throwing or rejecting sink never escapes. + */ +export function reportOncePerMessage( + onError: ((error: unknown) => unknown) | undefined, +): (error: unknown) => void { + const seen = new Set(); + return (error) => { + let key: string; + try { + key = error instanceof Error ? `${error.name}: ${error.message}` : String(error); + } catch { + key = ''; + } + if (seen.has(key) || seen.size >= MAX_DISTINCT) return; + seen.add(key); + reportGuarded(onError, error); + }; +}