From ac85f43826c3fdd830720fe758a5e50064245310 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 19 Oct 2026 14:01:34 +0500 Subject: [PATCH 1/4] feat(node,electron): hardwareExtras environment seam; Electron GPU as hardware.gpu (ST6a) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/electron-gpu-hardware-extras.md | 8 + docs/PROGRESS.md | 1 + packages/bugsee/src/relaunch-options.test.ts | 3 + packages/electron/src/gpu-info-cache.test.ts | 246 +++++++++++++++++++ packages/electron/src/gpu-info-cache.ts | 110 +++++++++ packages/electron/src/launch-main.test.ts | 140 +++++++++++ packages/electron/src/launch-main.ts | 31 +++ packages/node/src/environment.test.ts | 105 ++++++++ packages/node/src/environment.ts | 63 +++++ packages/node/src/index.ts | 2 + packages/node/src/launch.test.ts | 60 +++++ packages/node/src/launch.ts | 12 + 12 files changed, 781 insertions(+) create mode 100644 .changeset/electron-gpu-hardware-extras.md create mode 100644 packages/electron/src/gpu-info-cache.test.ts create mode 100644 packages/electron/src/gpu-info-cache.ts diff --git a/.changeset/electron-gpu-hardware-extras.md b/.changeset/electron-gpu-hardware-extras.md new file mode 100644 index 00000000..672ea226 --- /dev/null +++ b/.changeset/electron-gpu-hardware-extras.md @@ -0,0 +1,8 @@ +--- +'@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. A caller-supplied `hardwareExtras` gpu takes precedence. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index c75f5b12..aa516c89 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -402,6 +402,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`, never a name from a numeric id; no strings -> no field. A caller `hardwareExtras` gpu wins over the cache. 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). Still open in ST4: `main_thread_lag_ms` (needs the hidden-tab-vs-sync-block probe first), optional `screen_size`, ST4b events (`dark_mode_changed`, `freeze`/`resume`). - **ST0′ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container diff --git a/packages/bugsee/src/relaunch-options.test.ts b/packages/bugsee/src/relaunch-options.test.ts index b90c76ed..172e9f28 100644 --- a/packages/bugsee/src/relaunch-options.test.ts +++ b/packages/bugsee/src/relaunch-options.test.ts @@ -122,6 +122,8 @@ function optionKeys(pkg: string, file: string, name: string): string[] { * so a relaunch builds a fresh one; * - `captureNonce`, `controlNonce`, `otelExportHeaders` and `otelExportUrl` are secrets or per-launch * credentials: never kept (`setCarrierLastLaunch` stores only the kept list); + * - `hardwareExtras` (node; set by the Electron composition from its GPU cache) is a per-launch closure over + * that composition's own state, like the Electron handles above, so a relaunch does not keep it; * - `systemTraceProducers` (node/bun/deno) holds STATEFUL producer instances: a producer's `start()` is a * no-op while it is already started, so an instance still running on another client would silently no-op * on the new one, and its trackers stay bound to the scheduler/onError of the launch that built them. A @@ -161,6 +163,7 @@ const RESET_OPTIONS: readonly string[] = [ 'hangFairMs', 'hangMediumMs', 'hangSevereMs', + 'hardwareExtras', 'holdBlackout', 'instrumentIncomingRequests', 'ipcMain', 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..404cd97d --- /dev/null +++ b/packages/electron/src/gpu-info-cache.test.ts @@ -0,0 +1,246 @@ +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', () => { + expect( + mapGpuInfo( + basic([ + { vendorId: 1, deviceId: 2, active: false, vendorString: 'Intel', deviceString: 'UHD' }, + { + vendorId: 4318, + deviceId: 9, + active: true, + vendorString: 'NVIDIA', + deviceString: 'RTX', + }, + ]), + ), + ).toEqual({ vendor: 'NVIDIA', renderer: 'RTX' }); + }); + + 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.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('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('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() drops an already-cached value', async () => { + const cache = createGpuInfoCache({ source: { getGPUInfo: async () => info } }); + cache.start(); + await flush(); + expect(cache.current()).toBeDefined(); + cache.stop(); + expect(cache.current()).toBeUndefined(); + }); + + 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..ffa3f023 --- /dev/null +++ b/packages/electron/src/gpu-info-cache.ts @@ -0,0 +1,110 @@ +// 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'; + +/** The slice of Electron's `app` the cache needs. Optional on `ElectronAppLike`: older Electron has none. */ +export interface ElectronGpuSourceLike { + getGPUInfo(type: 'basic'): Promise; +} + +export interface GpuInfoCacheOptions { + /** Electron's `app` (or anything with `getGPUInfo`). When absent or without `getGPUInfo`, nothing is ever cached. */ + source?: Partial | undefined; + /** 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('basic')` once. A second call while started is a no-op. Never throws. */ + start(): void; + /** Abort: a late resolve is ignored and the cached value is dropped. A later `start()` begins afresh. */ + 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 : undefined; + +/** + * Maps Electron's `'basic'` GPU info to `{vendor, renderer}` defensively. The shape is UNVERIFIED against a + * real Electron: `basic` is documented as `{ gpuDevice: [{ vendorId, deviceId, active, vendorString?, + * deviceString?, … }] }`. The ACTIVE device is used (or the only device when exactly one is listed — never a + * guess among several); `vendorString`/`deviceString` fill `vendor`/`renderer` ONLY when they are real + * strings. A numeric id is never turned into a vendor name. Nothing usable → `undefined`. + */ +export function mapGpuInfo(info: unknown): HardwareGpu | undefined { + if (typeof info !== 'object' || info === null) return undefined; + const devices = (info as { gpuDevice?: unknown }).gpuDevice; + if (!Array.isArray(devices)) return undefined; + const objects = devices.filter( + (d): d is Record => typeof d === 'object' && d !== null, + ); + const device = + objects.find((d) => d.active === true) ?? (objects.length === 1 ? objects[0] : undefined); + if (device === undefined) return undefined; + const vendor = nonEmpty(device.vendorString); + const renderer = nonEmpty(device.deviceString); + if (vendor === undefined && renderer === undefined) return undefined; + return { + ...(vendor !== undefined ? { vendor } : {}), + ...(renderer !== undefined ? { renderer } : {}), + }; +} + +export function createGpuInfoCache(options: GpuInfoCacheOptions = {}): GpuInfoCache { + let generation = 0; + let started = false; + let gpu: HardwareGpu | undefined; + + const report = (error: unknown): void => { + try { + options.onError?.(error); + } catch { + // the error sink itself failed; the cache must stay silent toward the host app + } + }; + + 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('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++; + gpu = undefined; + }, + 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 d3f85ac2..4cc4f93f 100644 --- a/packages/electron/src/launch-main.test.ts +++ b/packages/electron/src/launch-main.test.ts @@ -508,3 +508,143 @@ describe('launchMain - blackout is forwarded to every renderer (privacy)', () => expect(calls).toEqual(['start', 'stop', 'clear', 'start']); }); }); + +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('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-supplied hardwareExtras gpu WINS over the cache', async () => { + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app: appWith(async () => gpuInfo), + hardwareExtras: () => ({ gpu: { vendor: 'Mine' } }), + }); + await flush(); + expect(extrasOf(f)()).toEqual({ gpu: { vendor: 'Mine' } }); + }); + + it('a caller extra with no gpu, or that throws, falls back to the cache (throw reported)', 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); + + const f2 = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f2.launch, + app: appWith(async () => gpuInfo), + hardwareExtras: () => ({}), + }); + await flush(); + expect(extrasOf(f2)()).toEqual({ gpu: { vendor: 'NVIDIA', renderer: 'RTX' } }); + }); + + 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(); + }); +}); diff --git a/packages/electron/src/launch-main.ts b/packages/electron/src/launch-main.ts index 2b397d9a..1ab2e893 100644 --- a/packages/electron/src/launch-main.ts +++ b/packages/electron/src/launch-main.ts @@ -23,9 +23,16 @@ 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'): Promise; } import type { CrashpadSessionMarker } from '@bugsee/core'; +import { createGpuInfoCache } 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'; @@ -107,6 +114,27 @@ 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). A caller-supplied `hardwareExtras` WINS for `gpu`; the cache + // fills in only when the caller supplied none (or it threw / returned no gpu). + const gpuCache = createGpuInfoCache({ + source: app, + ...(nodeOptions.onError !== undefined ? { onError: nodeOptions.onError } : {}), + }); + const callerExtras = nodeOptions.hardwareExtras; + nodeOptions.hardwareExtras = () => { + if (callerExtras !== undefined) { + try { + const own = callerExtras(); + if (own?.gpu !== undefined) return own; + } catch (error) { + nodeOptions.onError?.(error); + } + } + return gpuCache.current(); + }; + 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 @@ -115,6 +143,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); @@ -211,6 +241,7 @@ 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 offBlackout(); control.stop(); // broadcast stop to renderers + remove the hello listener receiver.stop(); diff --git a/packages/node/src/environment.test.ts b/packages/node/src/environment.test.ts index cd40ff56..0174df1c 100644 --- a/packages/node/src/environment.test.ts +++ b/packages/node/src/environment.test.ts @@ -211,3 +211,108 @@ 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 gl_extensions as a string and a partial block', () => { + 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 fields', { gpu: { vendor: 5, renderer: '', gl_extensions: [1, ''] } }], + ])('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('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); + }); +}); diff --git a/packages/node/src/environment.ts b/packages/node/src/environment.ts index 7279bfb2..b6ee7f53 100644 --- a/packages/node/src/environment.ts +++ b/packages/node/src/environment.ts @@ -57,6 +57,63 @@ 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[] | 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_STRING_KEYS = ['vendor', 'renderer', 'gl_version'] as const; + +// Defensive copy of the GPU block: only the four known keys, only well-typed non-empty values. Returns +// undefined when nothing usable remains, so no empty `gpu: {}` is ever reported. +function sanitizeGpu(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_STRING_KEYS) { + const value = source[key]; + if (typeof value === 'string' && value !== '') gpu[key] = value; + } + const ext = source.gl_extensions; + if (typeof ext === 'string' && ext !== '') { + gpu.gl_extensions = ext; + } else if (Array.isArray(ext)) { + const list = ext.filter((e): e is string => typeof e === 'string' && e !== ''); + if (list.length > 0) gpu.gl_extensions = list; + } + 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 = sanitizeGpu(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 +131,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 +176,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.ts b/packages/node/src/index.ts index 5f8fb01a..bb7a3b01 100644 --- a/packages/node/src/index.ts +++ b/packages/node/src/index.ts @@ -46,6 +46,8 @@ export { } from './detection-providers'; export { buildNodeEnvironment, + type HardwareExtras, + type HardwareGpu, type NodeEnvironmentInput, realSystemProbe, type SystemProbe, diff --git a/packages/node/src/launch.test.ts b/packages/node/src/launch.test.ts index bf0d4491..4d22b2e9 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -3163,3 +3163,63 @@ 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 launched = launchCore( + 'tok', + baseOptions({ + carrier: {}, + captureStore: memStore(), + hardwareExtras: () => (gpu ? { gpu } : undefined), + }), + ); + clients.push(launched.client); + const before = launched.internals?.getEnvironment().hardware as Record; + expect(before).not.toHaveProperty('gpu'); + gpu = { vendor: 'Apple', renderer: 'M3' }; + const after = launched.internals?.getEnvironment().hardware as Record; + expect(after.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); + }); +}); diff --git a/packages/node/src/launch.ts b/packages/node/src/launch.ts index b815933d..0a26d417 100644 --- a/packages/node/src/launch.ts +++ b/packages/node/src/launch.ts @@ -87,6 +87,7 @@ import { } from './detection-providers'; import { buildNodeEnvironment, + type HardwareExtras, realSystemProbe, type SystemProbe, SystemProbeToken, @@ -379,6 +380,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. */ @@ -657,6 +667,8 @@ function buildLaunch(appToken: string, options: BugseeLaunchOptions = {}): Launc ...(options.appVersion !== undefined ? { appVersion: options.appVersion } : {}), ...(options.appBuild !== undefined ? { appBuild: options.appBuild } : {}), ...(options.deviceId !== undefined ? { deviceId: options.deviceId } : {}), + ...(options.hardwareExtras !== undefined ? { hardwareExtras: options.hardwareExtras } : {}), + ...(options.onError !== undefined ? { onError: options.onError } : {}), }, probe, ); From ea3452dcdba50204388f48b47dd49cd95c27fd43 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 19 Oct 2026 14:12:46 +0500 Subject: [PATCH 2/4] =?UTF-8?q?fix(node,electron):=20GPU=20review=20follow?= =?UTF-8?q?-ups=20=E2=80=94=20auxAttributes=20mapping,=20gpuInfoType,=20fi?= =?UTF-8?q?eld-wise=20merge,=20kept=20relaunch=20option=20(ST6a)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/electron-gpu-hardware-extras.md | 2 +- docs/PROGRESS.md | 2 +- packages/bugsee/src/relaunch-options.test.ts | 6 +- packages/core/src/carrier.ts | 1 + .../src/gpu-hardware.integration.test.ts | 113 ++++++++++++++++++ packages/electron/src/gpu-info-cache.test.ts | 51 ++++++++ packages/electron/src/gpu-info-cache.ts | 54 ++++++--- packages/electron/src/launch-main.test.ts | 75 +++++++++++- packages/electron/src/launch-main.ts | 64 +++++++--- packages/node/src/environment.test.ts | 29 ++++- packages/node/src/environment.ts | 26 ++-- packages/node/src/index.test.ts | 1 + packages/node/src/index.ts | 1 + packages/node/src/launch.test.ts | 24 ++-- 14 files changed, 378 insertions(+), 71 deletions(-) create mode 100644 packages/electron/src/gpu-hardware.integration.test.ts diff --git a/.changeset/electron-gpu-hardware-extras.md b/.changeset/electron-gpu-hardware-extras.md index 672ea226..e473dc54 100644 --- a/.changeset/electron-gpu-hardware-extras.md +++ b/.changeset/electron-gpu-hardware-extras.md @@ -5,4 +5,4 @@ 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. A caller-supplied `hardwareExtras` gpu takes precedence. +`@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. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index aa516c89..3a695215 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -402,7 +402,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`, never a name from a numeric id; no strings -> no field. A caller `hardwareExtras` gpu wins over the cache. Still open: the ST6 Electron trace/event producers. +- **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`); Electron has no `relaunch()` and rebuilds its closure per `launchMain`. 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). Still open in ST4: `main_thread_lag_ms` (needs the hidden-tab-vs-sync-block probe first), optional `screen_size`, ST4b events (`dark_mode_changed`, `freeze`/`resume`). - **ST0′ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container diff --git a/packages/bugsee/src/relaunch-options.test.ts b/packages/bugsee/src/relaunch-options.test.ts index 172e9f28..8e073ac9 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, @@ -122,8 +122,6 @@ function optionKeys(pkg: string, file: string, name: string): string[] { * so a relaunch builds a fresh one; * - `captureNonce`, `controlNonce`, `otelExportHeaders` and `otelExportUrl` are secrets or per-launch * credentials: never kept (`setCarrierLastLaunch` stores only the kept list); - * - `hardwareExtras` (node; set by the Electron composition from its GPU cache) is a per-launch closure over - * that composition's own state, like the Electron handles above, so a relaunch does not keep it; * - `systemTraceProducers` (node/bun/deno) holds STATEFUL producer instances: a producer's `start()` is a * no-op while it is already started, so an instance still running on another client would silently no-op * on the new one, and its trackers stay bound to the scheduler/onError of the launch that built them. A @@ -133,6 +131,7 @@ const RESET_OPTIONS: readonly string[] = [ 'app', 'appToken', 'flushTimeoutMs', + 'gpuInfoType', 'injectTraceMeta', 'instanceIdentity', 'onSpanProcessor', @@ -163,7 +162,6 @@ const RESET_OPTIONS: readonly string[] = [ 'hangFairMs', 'hangMediumMs', 'hangSevereMs', - 'hardwareExtras', 'holdBlackout', 'instrumentIncomingRequests', 'ipcMain', diff --git a/packages/core/src/carrier.ts b/packages/core/src/carrier.ts index f6f2fe7a..5f6a595c 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..a64e9af4 --- /dev/null +++ b/packages/electron/src/gpu-hardware.integration.test.ts @@ -0,0 +1,113 @@ +// 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 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 index 404cd97d..c750f59a 100644 --- a/packages/electron/src/gpu-info-cache.test.ts +++ b/packages/electron/src/gpu-info-cache.test.ts @@ -59,6 +59,48 @@ describe('mapGpuInfo', () => { ).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], @@ -87,6 +129,15 @@ describe('createGpuInfoCache', () => { 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 } }); diff --git a/packages/electron/src/gpu-info-cache.ts b/packages/electron/src/gpu-info-cache.ts index ffa3f023..a629521a 100644 --- a/packages/electron/src/gpu-info-cache.ts +++ b/packages/electron/src/gpu-info-cache.ts @@ -12,18 +12,23 @@ import type { HardwareExtras, HardwareGpu } from '@bugsee/node'; /** The slice of Electron's `app` the cache needs. Optional on `ElectronAppLike`: older Electron has none. */ export interface ElectronGpuSourceLike { - getGPUInfo(type: 'basic'): Promise; + 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('basic')` once. A second call while started is a no-op. Never throws. */ + /** Kick `getGPUInfo(type)` once. A second call while started is a no-op. Never throws. */ start(): void; /** Abort: a late resolve is ignored and the cached value is dropped. A later `start()` begins afresh. */ stop(): void; @@ -32,32 +37,43 @@ export interface GpuInfoCache { } const nonEmpty = (value: unknown): string | undefined => - typeof value === 'string' && value.trim() !== '' ? value : undefined; + typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined; /** - * Maps Electron's `'basic'` GPU info to `{vendor, renderer}` defensively. The shape is UNVERIFIED against a - * real Electron: `basic` is documented as `{ gpuDevice: [{ vendorId, deviceId, active, vendorString?, - * deviceString?, … }] }`. The ACTIVE device is used (or the only device when exactly one is listed — never a - * guess among several); `vendorString`/`deviceString` fill `vendor`/`renderer` ONLY when they are real - * strings. A numeric id is never turned into a vendor name. Nothing usable → `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 devices = (info as { gpuDevice?: unknown }).gpuDevice; - if (!Array.isArray(devices)) return undefined; - const objects = devices.filter( - (d): d is Record => typeof d === 'object' && d !== null, - ); + 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); - if (device === undefined) return undefined; - const vendor = nonEmpty(device.vendorString); - const renderer = nonEmpty(device.deviceString); - if (vendor === undefined && renderer === undefined) return undefined; - return { + 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 { @@ -81,7 +97,7 @@ export function createGpuInfoCache(options: GpuInfoCacheOptions = {}): GpuInfoCa const source = options.source; if (source === undefined || typeof source.getGPUInfo !== 'function') return; try { - Promise.resolve(source.getGPUInfo('basic')).then( + Promise.resolve(source.getGPUInfo(options.type ?? 'basic')).then( (info) => { if (mine !== generation) return; // stopped (or restarted) since: ignore, never write try { diff --git a/packages/electron/src/launch-main.test.ts b/packages/electron/src/launch-main.test.ts index 4cc4f93f..4f44f9b2 100644 --- a/packages/electron/src/launch-main.test.ts +++ b/packages/electron/src/launch-main.test.ts @@ -597,19 +597,51 @@ describe('launchMain — GPU info as environment.hardware.gpu (ST6a)', () => { expect(extrasOf(f)()).toBeUndefined(); }); - it('a caller-supplied hardwareExtras gpu WINS over the cache', async () => { + 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' } }), + 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('a caller extra with no gpu, or that throws, falls back to the cache (throw reported)', async () => { + 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(); @@ -631,12 +663,47 @@ describe('launchMain — GPU info as environment.hardware.gpu (ST6a)', () => { ipcMain: fakeIpcMain().ipcMain, launch: f2.launch, app: appWith(async () => gpuInfo), - hardwareExtras: () => ({}), + 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('a repeat launch (no internals) does not start the GPU read', () => { const getGPUInfo = vi.fn(async () => gpuInfo); const f = fakeLaunch({ internals: false }); diff --git a/packages/electron/src/launch-main.ts b/packages/electron/src/launch-main.ts index 1ab2e893..26c2f27a 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 { 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, @@ -28,11 +33,11 @@ export interface ElectronAppLike { * 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'): Promise; + getGPUInfo?(type: 'basic' | 'complete'): Promise; } import type { CrashpadSessionMarker } from '@bugsee/core'; -import { createGpuInfoCache } from './gpu-info-cache'; +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'; @@ -45,6 +50,15 @@ import { createRendererGoneHandler } from './renderer-gone'; import { type RendererGoneIncident, RendererIncidentProvider } from './renderer-incident-provider'; import type { VideoCaptureSource } from './video-capture'; +// An error sink must never throw into the host app's shutdown/launch path. +function reportSafely(sink: ((error: unknown) => void) | undefined, error: unknown): void { + try { + sink?.(error); + } catch { + // the sink itself failed + } +} + /** The node `launchCore` shape, injectable for tests. */ type NodeLaunch = typeof launchCore; @@ -68,6 +82,13 @@ 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: `'basic'` often has only numeric vendor/device ids, in which case no + * `hardware.gpu` is reported rather than a guess. + */ + 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). */ @@ -80,8 +101,16 @@ export interface LaunchMainOptions extends BugseeLaunchOptions { /** 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; // Opt-in pixel video: build the permission-gated controller and forward its report-time snapshot + // the `video` binary encoder into the node launch (merged with any the caller passed directly). @@ -116,23 +145,26 @@ 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). A caller-supplied `hardwareExtras` WINS for `gpu`; the cache - // fills in only when the caller supplied none (or it threw / returned no gpu). + // 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. const gpuCache = createGpuInfoCache({ source: app, + ...(gpuInfoType !== undefined ? { type: gpuInfoType } : {}), ...(nodeOptions.onError !== undefined ? { onError: nodeOptions.onError } : {}), }); const callerExtras = nodeOptions.hardwareExtras; nodeOptions.hardwareExtras = () => { - if (callerExtras !== undefined) { - try { - const own = callerExtras(); - if (own?.gpu !== undefined) return own; - } catch (error) { - nodeOptions.onError?.(error); - } + 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) { + reportSafely(nodeOptions.onError, error); + return cached; } - return gpuCache.current(); }; const { client, internals } = (launch ?? launchCore)(appToken, nodeOptions); @@ -247,7 +279,7 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee receiver.stop(); videoController?.stop(); // stop pixel capture } catch (error) { - nodeOptions.onError?.(error); + reportSafely(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 0174df1c..26f875dc 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 = { @@ -237,12 +238,12 @@ describe('buildNodeEnvironment — hardwareExtras (hardware.gpu)', () => { vendor: 'Apple', renderer: 'M3', gl_version: 'OpenGL ES 3.0', - gl_extensions: ['A', 'B'], + gl_extensions: 'A B', }; expect(build(() => ({ gpu }))).toEqual({ ...closed, gpu }); }); - it('accepts gl_extensions as a string and a partial block', () => { + 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', @@ -263,7 +264,10 @@ describe('buildNodeEnvironment — hardwareExtras (hardware.gpu)', () => { ['an empty gpu', { gpu: {} }], ['a non-object gpu', { gpu: 'nvidia' }], ['a null gpu', { gpu: null }], - ['only ill-typed fields', { gpu: { vendor: 5, renderer: '', gl_extensions: [1, ''] } }], + [ + '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); }); @@ -277,7 +281,15 @@ describe('buildNodeEnvironment — hardwareExtras (hardware.gpu)', () => { ), ).toEqual(closed); expect(errors).toEqual([]); - expect(build(() => ({ gpu: { vendor: 'V', gl_extensions: '' } })).gpu).toEqual({ vendor: 'V' }); + 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', () => { @@ -316,3 +328,12 @@ describe('buildNodeEnvironment — hardwareExtras (hardware.gpu)', () => { ).toEqual(closed); }); }); + +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 b6ee7f53..2ad35de9 100644 --- a/packages/node/src/environment.ts +++ b/packages/node/src/environment.ts @@ -62,7 +62,7 @@ export interface HardwareGpu { vendor?: string; renderer?: string; gl_version?: string; - gl_extensions?: string[] | string; + gl_extensions?: string; } /** @@ -73,24 +73,20 @@ export interface HardwareExtras { gpu?: HardwareGpu; } -const GPU_STRING_KEYS = ['vendor', 'renderer', 'gl_version'] as const; +const GPU_KEYS = ['vendor', 'renderer', 'gl_version', 'gl_extensions'] as const; -// Defensive copy of the GPU block: only the four known keys, only well-typed non-empty values. Returns -// undefined when nothing usable remains, so no empty `gpu: {}` is ever reported. -function sanitizeGpu(raw: unknown): HardwareGpu | undefined { +/** + * Defensive copy of a GPU block: only the four known keys, only strings, trimmed, whitespace-only 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_STRING_KEYS) { + for (const key of GPU_KEYS) { const value = source[key]; - if (typeof value === 'string' && value !== '') gpu[key] = value; - } - const ext = source.gl_extensions; - if (typeof ext === 'string' && ext !== '') { - gpu.gl_extensions = ext; - } else if (Array.isArray(ext)) { - const list = ext.filter((e): e is string => typeof e === 'string' && e !== ''); - if (list.length > 0) gpu.gl_extensions = list; + if (typeof value === 'string' && value.trim() !== '') gpu[key] = value.trim(); } return Object.keys(gpu).length > 0 ? gpu : undefined; } @@ -102,7 +98,7 @@ function readHardwareExtras( ): { gpu: HardwareGpu } | undefined { if (extras === undefined) return undefined; try { - const gpu = sanitizeGpu(extras()?.gpu); + const gpu = sanitizeHardwareGpu(extras()?.gpu); return gpu !== undefined ? { gpu } : undefined; } catch (error) { try { diff --git a/packages/node/src/index.test.ts b/packages/node/src/index.test.ts index 97a83a45..9ba71395 100644 --- a/packages/node/src/index.test.ts +++ b/packages/node/src/index.test.ts @@ -63,6 +63,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 bb7a3b01..3a160da4 100644 --- a/packages/node/src/index.ts +++ b/packages/node/src/index.ts @@ -51,6 +51,7 @@ export { 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 4d22b2e9..26c14f78 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -3174,20 +3174,30 @@ describe('launch — hardwareExtras (environment.hardware.gpu seam)', () => { it('a report assembled after the extra settles carries hardware.gpu; one before does not', async () => { let gpu: { vendor: string; renderer: string } | undefined; - const launched = launchCore( + const { fn: transport, puts } = recordingTransport(); + const client = launchTracked( 'tok', baseOptions({ - carrier: {}, + transport, captureStore: memStore(), hardwareExtras: () => (gpu ? { gpu } : undefined), }), ); - clients.push(launched.client); - const before = launched.internals?.getEnvironment().hardware as Record; - expect(before).not.toHaveProperty('gpu'); + 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' }; - const after = launched.internals?.getEnvironment().hardware as Record; - expect(after.gpu).toEqual({ 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 () => { From 82c68ae32216271a581a191026173f038659025e Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 19 Oct 2026 14:19:41 +0500 Subject: [PATCH 3/4] fix(electron): keep the resolved GPU across stop so draining reports carry hardware.gpu (ST6a) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/electron-gpu-hardware-extras.md | 2 + docs/PROGRESS.md | 2 +- .../src/gpu-hardware.integration.test.ts | 12 +++++ packages/electron/src/gpu-info-cache.test.ts | 47 ++++++++++++++----- packages/electron/src/gpu-info-cache.ts | 7 +-- packages/electron/src/launch-main.test.ts | 12 +++++ packages/electron/src/launch-main.ts | 10 ++-- 7 files changed, 72 insertions(+), 20 deletions(-) diff --git a/.changeset/electron-gpu-hardware-extras.md b/.changeset/electron-gpu-hardware-extras.md index e473dc54..6baa2e93 100644 --- a/.changeset/electron-gpu-hardware-extras.md +++ b/.changeset/electron-gpu-hardware-extras.md @@ -6,3 +6,5 @@ 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/docs/PROGRESS.md b/docs/PROGRESS.md index 3a695215..3254d73d 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -402,7 +402,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`); Electron has no `relaunch()` and rebuilds its closure per `launchMain`. Still open: the ST6 Electron trace/event producers. +- **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). Still open in ST4: `main_thread_lag_ms` (needs the hidden-tab-vs-sync-block probe first), optional `screen_size`, ST4b events (`dark_mode_changed`, `freeze`/`resume`). - **ST0′ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container diff --git a/packages/electron/src/gpu-hardware.integration.test.ts b/packages/electron/src/gpu-hardware.integration.test.ts index a64e9af4..e9021a44 100644 --- a/packages/electron/src/gpu-hardware.integration.test.ts +++ b/packages/electron/src/gpu-hardware.integration.test.ts @@ -86,6 +86,18 @@ describe('Electron GPU -> real node launch -> assembled report', () => { 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); diff --git a/packages/electron/src/gpu-info-cache.test.ts b/packages/electron/src/gpu-info-cache.test.ts index c750f59a..af656dd9 100644 --- a/packages/electron/src/gpu-info-cache.test.ts +++ b/packages/electron/src/gpu-info-cache.test.ts @@ -16,21 +16,43 @@ function deferred() { const basic = (devices: unknown[]) => ({ gpuDevice: devices }); describe('mapGpuInfo', () => { - it('uses the ACTIVE device strings', () => { + 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([ - { vendorId: 1, deviceId: 2, active: false, vendorString: 'Intel', deviceString: 'UHD' }, - { - vendorId: 4318, - deviceId: 9, - active: true, - vendorString: 'NVIDIA', - deviceString: 'RTX', - }, + { active: true, vendorString: 'First' }, + { active: true, vendorString: 'Second' }, ]), ), - ).toEqual({ vendor: 'NVIDIA', renderer: 'RTX' }); + ).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', () => { @@ -245,13 +267,12 @@ describe('createGpuInfoCache', () => { expect(onError).not.toHaveBeenCalled(); }); - it('stop() drops an already-cached value', async () => { + 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(); - expect(cache.current()).toBeDefined(); cache.stop(); - expect(cache.current()).toBeUndefined(); + 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 () => { diff --git a/packages/electron/src/gpu-info-cache.ts b/packages/electron/src/gpu-info-cache.ts index a629521a..65c04a69 100644 --- a/packages/electron/src/gpu-info-cache.ts +++ b/packages/electron/src/gpu-info-cache.ts @@ -30,7 +30,7 @@ export interface GpuInfoCacheOptions { export interface GpuInfoCache { /** Kick `getGPUInfo(type)` once. A second call while started is a no-op. Never throws. */ start(): void; - /** Abort: a late resolve is ignored and the cached value is dropped. A later `start()` begins afresh. */ + /** 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; @@ -116,8 +116,9 @@ export function createGpuInfoCache(options: GpuInfoCacheOptions = {}): GpuInfoCa }, stop(): void { started = false; - generation++; - gpu = undefined; + 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 4f44f9b2..80e00aec 100644 --- a/packages/electron/src/launch-main.test.ts +++ b/packages/electron/src/launch-main.test.ts @@ -577,6 +577,18 @@ describe('launchMain — GPU info as environment.hardware.gpu (ST6a)', () => { 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(); diff --git a/packages/electron/src/launch-main.ts b/packages/electron/src/launch-main.ts index 26c2f27a..338d3ca9 100644 --- a/packages/electron/src/launch-main.ts +++ b/packages/electron/src/launch-main.ts @@ -85,8 +85,9 @@ export interface LaunchMainOptions extends BugseeLaunchOptions { /** * 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: `'basic'` often has only numeric vendor/device ids, in which case no - * `hardware.gpu` is reported rather than a guess. + * 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. */ @@ -149,6 +150,9 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee // 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 } : {}), @@ -273,7 +277,7 @@ 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 + 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(); From 54abb78cb5e693060ba8d5978cc6ea0d99943520 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 20 Oct 2026 12:55:37 +0500 Subject: [PATCH 4/4] fix(electron): absorb rejected promises from an async onError (reportGuarded) in gpu cache and launchMain stop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- packages/electron/src/gpu-info-cache.test.ts | 19 ++++++++++++++++ packages/electron/src/gpu-info-cache.ts | 10 +++----- packages/electron/src/launch-main.test.ts | 24 ++++++++++++++++++++ packages/electron/src/launch-main.ts | 13 ++--------- 4 files changed, 48 insertions(+), 18 deletions(-) diff --git a/packages/electron/src/gpu-info-cache.test.ts b/packages/electron/src/gpu-info-cache.test.ts index af656dd9..c1b2d057 100644 --- a/packages/electron/src/gpu-info-cache.test.ts +++ b/packages/electron/src/gpu-info-cache.test.ts @@ -218,6 +218,25 @@ describe('createGpuInfoCache', () => { } }); + 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(); diff --git a/packages/electron/src/gpu-info-cache.ts b/packages/electron/src/gpu-info-cache.ts index 65c04a69..c7055e03 100644 --- a/packages/electron/src/gpu-info-cache.ts +++ b/packages/electron/src/gpu-info-cache.ts @@ -9,6 +9,7 @@ // `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 { @@ -81,13 +82,8 @@ export function createGpuInfoCache(options: GpuInfoCacheOptions = {}): GpuInfoCa let started = false; let gpu: HardwareGpu | undefined; - const report = (error: unknown): void => { - try { - options.onError?.(error); - } catch { - // the error sink itself failed; the cache must stay silent toward the host app - } - }; + // 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 { diff --git a/packages/electron/src/launch-main.test.ts b/packages/electron/src/launch-main.test.ts index da4e7860..93c074a8 100644 --- a/packages/electron/src/launch-main.test.ts +++ b/packages/electron/src/launch-main.test.ts @@ -720,6 +720,30 @@ describe('launchMain — GPU info as environment.hardware.gpu (ST6a)', () => { 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 }); diff --git a/packages/electron/src/launch-main.ts b/packages/electron/src/launch-main.ts index c723ffbc..4719a99e 100644 --- a/packages/electron/src/launch-main.ts +++ b/packages/electron/src/launch-main.ts @@ -39,7 +39,7 @@ export interface ElectronAppLike { } import type { CrashpadSessionMarker } from '@bugsee/core'; -import { reportOncePerMessage } from '@bugsee/util'; +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'; @@ -53,15 +53,6 @@ import { createRendererGoneHandler } from './renderer-gone'; import { type RendererGoneIncident, RendererIncidentProvider } from './renderer-incident-provider'; import type { VideoCaptureSource } from './video-capture'; -// An error sink must never throw into the host app's shutdown/launch path. -function reportSafely(sink: ((error: unknown) => void) | undefined, error: unknown): void { - try { - sink?.(error); - } catch { - // the sink itself failed - } -} - /** The node `launchCore` shape, injectable for tests. */ type NodeLaunch = typeof launchCore; @@ -322,7 +313,7 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee receiver.stop(); videoController?.stop(); // stop pixel capture } catch (error) { - reportSafely(nodeOptions.onError, error); + reportGuarded(nodeOptions.onError, error); } return stop(timeout); }) as Bugsee['stop'];