diff --git a/.changeset/electron-process-tracker.md b/.changeset/electron-process-tracker.md new file mode 100644 index 00000000..9b778633 --- /dev/null +++ b/.changeset/electron-process-tracker.md @@ -0,0 +1,7 @@ +--- +'@bugsee/electron': minor +'@bugsee/trackers': minor +'@bugsee/node': minor +--- + +Electron main now reports per-process CPU and memory and child-process crashes. The `app_metrics` system trace (`{ processes: [{ type, pid, cpu_percent?, working_set_mb?, peak_working_set_mb?, private_mb? }] }`; `cpu_percent` is the share of the whole machine and is omitted on a process's first appearance; polled from `app.getAppMetrics()` when the `app` passed to `launchMain` has it; fields Electron does not supply are omitted) is emitted next to the existing node traces, and a `child_process_gone` system event (`{ type, reason, exitCode?, name? }`) is recorded when a GPU or utility process dies, only while `captureSystemEvents` is on. Both come from a new per-`app` `ElectronProcessTracker` in `@bugsee/trackers/electron`, which also takes over the `app.getGPUInfo` read behind `environment.hardware.gpu`: same `hardware.gpu` output, but a later launch now asks again when the earlier read failed or a different `gpuInfoType` is requested. `@bugsee/node` gains the advanced `wrapSystemEventsSource` launch option, which lets a platform mux extra events into the single `events.system` provider. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 5a17dbb1..46cfe9b3 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -415,6 +415,7 @@ solid), in slices: - **TR5 (implemented on `feat/process-tracker`, PR #83; multi-agent review rounds still in progress, one owner decision open — see "Known limit" below):** domain **`ProcessTracker`** (`packages/trackers/src/browser/process-tracker.ts`), singleton per window via `createTrackerRegistry` (`processTrackerFor(env, onError?)`, `resetProcessTracker`; keyed window -> performance -> env object, `rebind` merge-not-drop: a seam change on a RUNNING tracker first detaches every armed stage with the seams it was armed with, then swaps and restarts). It ABSORBS and replaces the per-signal `MemoryTracker` and `MainThreadLagTracker` (files + tests deleted; `MemoryProducer`/`MainThreadLagProducer` now subscribe to it; trace names and wire shapes unchanged). Five stages, each armed ONLY while it has listeners (via the `listenerCount(name)` / `onListenersChanged()` hooks `MultiKeyEmitterBase` already has on `main` from TR2; this PR does not touch the emitter; `start()`/`stop()` do nothing here): `heap` `{used, limit}` (`performance.memory`, polled; a figure that is not a finite non-negative number omits the reading), `mainThreadLag` `{lagMs}` (TIMER DRIFT, algorithm and visible-only gating unchanged: block >= 1 s always shows, shorter that crosses no due tick reads 0, reported once, fresh baseline each visible start), `idle` `{idleMs}` (NEW, ONE `requestIdleCallback` probe per sampling tick, never a loop and at most one in flight, visible pages only, `timeRemaining()` clamped to <= 50 ms; a tick whose callback never runs yields NO sample, never 0; omitted without rIC, e.g. Safari), `userIdle` `{userState: 'active'|'idle', screenState?: 'locked'|'unlocked'}` (NEW, Idle Detection API), `uptime` `{uptimeMs}` (`performance.now()`, omitted without a clock; no trace consumes it yet). **Idle Detection permission rule (binding): the SDK NEVER prompts.** `IdleDetector.requestPermission()` is never called; the detector starts ONLY when `navigator.permissions.query({name:'idle-detection'})` ALREADY reports `granted` (an engine that does not know the name rejects = stage inert, silent). The permission is re-queried on every activation and watched through its `change` event (granted later -> starts; revoked -> aborts and drops the tracker's retained state). Threshold floored at the spec's 60 s; stop aborts via `AbortController`; every async continuation is guarded by its run. **Retention rule (tested):** the last `userIdle` state survives the last unsubscribe (`currentUserIdle()`; `currentUserIdleFresh()`, which `UserIdleProducer` seeds from, answers only once the ARMED stage's detector has PUBLISHED in this run (permission re-confirmed and its `start()` settled; no age bound, a live detector reports changes only) and is undefined while the async permission re-query or `start()` is pending, or after a refusal/revoke; with NO armed stage it serves the state only while younger than 2 detector thresholds, via a new injectable `now` seam defaulting to `Date.now`, mirroring TR6's `currentFresh()`. A revoke while no stage is armed is therefore only noticed by the next activation's re-query (the plain `currentUserIdle()` read keeps the snapshot until then), but it can never seed a held trace); heap is read live; idle/lag/uptime keep nothing (a stale baseline would be a lie); timers, lifecycle subscription, pending probe and detector are released. New JS-specific traces (`BrowserTraceEnv` gains `requestIdleCallback`/`cancelIdleCallback`/`IdleDetector`/`AbortController`, bound/taken from the injected window by `browserTraceEnvFrom`): `main_thread_idle_ms` (ms, polled/not held; built under the same lifecycle gate as lag/fps) and `user_idle_state` (a STRING like `app_state`: `active` | `idle` | `locked`, where a locked screen wins over `userState`; held, de-duplicated; no trace at all unless the permission was already granted). **`user_idle_state` is OPT-IN (review P2; the maintainer's decision, PENDING OWNER CONFIRMATION): the host page's `idle-detection` grant shows only that the page was given the permission, not consent to record and upload idle/locked state. So `createBrowserSystemTraceProducers` builds `UserIdleProducer` only for `BrowserTraceEnv.captureUserIdle === true`, fed by the new browser + WebView launch option `captureUserIdle` (default false, strict boolean: any other value stays off and is reported; local key `com.bugsee.option.browser.capture-user-idle`, exported as `CAPTURE_USER_IDLE_OPTION_KEY`). Even when on, the tracker starts a detector only if the permission ALREADY reports `granted` (the SDK still never prompts). Without the opt-in the permission is not even queried. This applies ONLY to `user_idle_state`; private-mode detection is opt-out by a separate owner decision.** The viewer has no definition for either name yet (generic value block, design §13.3). **Known limit (OWNER DECISION PENDING — no retract mechanism invented):** `user_idle_state` is a HELD trace and the tracker emits nothing when the permission is revoked, so a producer that already published a value keeps having it re-recorded every `refreshMs` until the producer stops (the revoke only drops the tracker's retained copy and so stops NEW seeds; the seed is gated as above). Resolving it needs a decision on a retract/clear signal for held traces (same family as TR6's held `storage_estimate`). Other hardening from review: a hostile `performance.now` getter is reported exactly once in total (the factory reads silently, the tracker reports; only a SUCCESSFUL clock read is memoised per env, a failed one is retried on the next activation); `ProcessTracker.reset()` now drops every listener (like `ApplicationTracker`), so a later listener change cannot re-arm a stage for a gone subscriber; `browserTraceEnvFrom` now hands back stable bound closures per (window, function), so a no-op relaunch no longer restarts armed stages; a non-finite lag baseline omits that tick's `main_thread_lag_ms` instead of sending NaN; the gated teardown always closes the run. Launch-level test proves browser launch goes through `processTrackerFor` (the window's singleton can read the heap through launch's seams); the WebView launch shares the producers. `sensors:false` (a `systemMetricsSampler`) still builds only the battery producer. - **TR8 part 1 (implemented on `feat/node-process-tracker`; Process only, Storage/disk is part 2 below):** the node/bun/deno **`ProcessTracker`** (`packages/trackers/src/node/process-tracker.ts`, `@bugsee/trackers/node`) ABSORBS and REPLACES `@bugsee/node`'s per-signal `ProcessStatsTracker` (files + tests deleted from `packages/node/src/trackers/`); `gc-observer`, `guarded-event-loop` and `runtime-readers` moved (with their tests) to `packages/trackers/src/node/` unchanged apart from `EventLoopSource` now living beside the histogram source. Singleton per process via the registry (`processTrackerFor(env, onError?)`, key `env.key` else the `process` object; `resetProcessTracker(key?)`); `rebind` merges (defined seams replace, undefined never clobber; an UNCHANGED relaunch restarts nothing; a changed seam tears every armed stage down with the OLD seams, the timer is cleared on the scheduler that armed it, then re-arms on the new ones; latest `onError` wins). Ten **per-stage-activated** stages (one shared unref'd timer exists only while some stage has a listener; each stage's machinery only while it is wanted): `memory`, `systemMemory`, `cpu` `{userDelta, systemDelta, processPct}`, `eventLoop` `{meanMs, maxMs, p99Ms}`, `utilization` `{utilization}`, `gc` `{count, pauseMs, maxPauseMs}`, `v8Heap`, `memoryLimit` `{bytes}`, `availableMemory` `{bytes}`, `uptime` `{seconds}`. Trace names and wire values are unchanged. Honesty rules are unchanged and still tracker-owned: a stage that cannot answer EMITS NOTHING (ELU zeros on Bun/Deno, an unsampled histogram, a blind/refusing GC observer, untrue heap/limit/available readings), and the runtime-identity GATES (`measuresEventLoopDelay`/`measuresV8Heap`/`measuresAvailableMemory`/`measuresGc`) are now tracker env flags that the platform composition roots (`@bugsee/{deno,bun}` via `createNodeSystemTraceProducers`) pass through; an injected source/reader wins over its gate. **Retention rule (stated and tested):** only the resolved seams and the "this runtime refused" memory inside the guarded sources survive the last unsubscribe; the CPU baseline, ELU baseline, histogram, GC interval and the last windowed sample all start FRESH on the next subscription. `current(stage)` reads stateless stages LIVE (guarded, copies) and answers the last emitted sample of a windowed stage (`cpu` is seeded with a zero-length window when it arms, so a producer has a baseline). Hardening: reporter indirection that swallows a throwing `onError`, generation-guarded timer callbacks (a timer whose clear failed never emits), each stage read isolated (one throwing reader drops only itself; a failed CPU read never advances the baseline), a failing source start leaves its stage unarmed (never half-armed, retried on the next listener change/rebind), a timer that cannot be armed unwinds the stages armed for it, one failing stop never strands another, emitted payloads are copies. `@bugsee/node`'s `trace-producers.ts` is now composition only (ten producers, each subscribed to ONE stage; `NodeTraceProducerDeps` = tracker env + `onError`), and `@bugsee/node` re-exports `processTrackerFor`/`resetProcessTracker`/`ProcessTracker` (and drops the `ProcessStatsTracker`/`ProcessStats` exports). **Behaviour notes:** (1) the tracker is one per PROCESS now, so a second producer set / relaunch shares it and its seams are rebound (tests that inject fakes must pass a private `key` or call `resetProcessTracker()`); (2) per-stage activation means the GC observer and the delay histogram exist only while their producer is subscribed (before, they ran whenever any producer was); (3) the ELU baseline is taken when its stage arms (before: when the producers were built), so the first sample no longer spans an idle gap; (4) the activation CPU/baseline read and the poll are per stage, so one failing reader no longer fails the whole poll (before: an `uptime` failure dropped the whole row); (5) there is NO CPU start value any more: before, the producer published a microsecond-window noise reading at start (`processPct` 7-43%, never a true share), now the tracker keeps its internal counters but the CPU producer has an empty `baseline()` and `current('cpu')` is undefined until the first tick (as for gc/event-loop-lag/utilization); an unusable core count (`os.cpus()` empty) now omits the cpu sample instead of emitting Infinity/NaN; (6) **seams merge, never drop:** the tracker outlives launches, so a later launch that omits `scheduler`/`onError`/a reader KEEPS the previous launch's (it can replace a seam, never shed one), and merely BUILDING a producer set rebinds the shared tracker (including the Bun/Deno default sets built before `...options` in their `launch.ts`); tests must use a private `key` or `resetProcessTracker()` (added to the afterEach of the node, bun, deno and elysia launch tests). **Tooling:** `@bugsee/trackers` gained `@types/node` (devDependency) and `tsconfig.json` now carries `types: ["node"]` for `src/node`; `tsconfig.portable.json` re-typechecks the portable root + browser entries WITHOUT node types (`pnpm typecheck` runs both) so a node global cannot leak into code shipped to browsers. `@bugsee/node` gained the `@bugsee/trackers` workspace dependency. Launch tests prove the default producers go through the registry accessor (mutating the producer factory to `new ProcessTracker` fails them) and that the Bun/Deno gates reach the shared tracker end to end. - **TR8 part 2 (implemented on `feat/node-storage-tracker`; Storage/disk):** the node/bun/deno **`StorageTracker`** (`packages/trackers/src/node/storage-tracker.ts`, `@bugsee/trackers/node`) ABSORBS the statfs polling of `@bugsee/node`'s `disk-space-producer.ts`, which is now composition only (one `StorageTracker` stage `disk` -> `disk_mem_free`/`disk_mem_total`; the old timer/streak/generation machinery and its tests were deleted; the producer tests were rewritten over the tracker). Singleton per VOLUME IDENTITY (`storageTrackerFor(env, onError?)`; key = the interned RESOLVED data dir, so launches over the same dir share one tracker and launches over different dirs get different ones; an explicit `env.key` overrides (tests); no data dir -> the shared inert `process`-keyed tracker; `resetStorageTracker(key?: object | dir)` drops one, no argument drops all). ONE stage, `disk` `{freeBytes, totalBytes}` (bytes; the producer converts to integer binary MB with `bytesToMegabytes`, free then total, `hold:false`, so a failing statfs leaves a gap). Activation is by listener: the first listener reads the data dir's volume at once and arms an unref'd 5 s timer (injectable scheduler/`intervalMs`); no listener, no data dir, or `statfs: null`/no `fs.promises.statfs` (Node < 18.15, as the old producer handled it) means no timer and no read. Reads never overlap (in-flight latch), every read and timer callback is guarded by the generation that armed it (a stop, a path change or a seam change abandons it: it can neither emit nor report), failures are reported ONCE per failure streak (a success, an unsane answer, a new run or a new path starts a new one), an unsane answer (non-positive block size/total, negative or non-finite free, overflowing product, non-numbers) is omitted without an error and never zeroed (a full disk is a true 0 free). `rebind` merges seams within one key (defined replaces, undefined never clobbers; `statfs: null` is a defined seam): `onError`/`scheduler`/`statfs`/`intervalMs` are latest-launch-wins per key, while the data dir is part of the key, so a running launch can never be redirected to (or have its failures reported to) another launch's dir/`onError`; a CHANGED seam while a listener is attached tears the poll down on the scheduler that armed it and starts again at once (a changed path is re-read immediately and the old path's reading and failure streak do not leak); an unchanged relaunch restarts nothing; idle rebinds only store. Merely BUILDING the producer rebinds the shared tracker. **Retention rule (stated and tested):** only the merged seams survive the last unsubscribe; the last reading does not (`current()` is undefined with no listener, and is dropped on a failed/unsane read and on a path change); payloads and `current()` are copies. Hardening: reporter indirection that swallows a throwing `onError`, a timer that cannot be armed is reported and leaves the tracker inert, a throwing `clearInterval` is reported. The disk producer is NOT built when the legacy `systemMetricsSampler` replaces the producer list (it would never start, and building it touches the shared tracker). Launch tests wrap `storageTrackerFor` and prove the opt-in launch goes through it (mutating the producer to `new StorageTracker` fails) and that no tracker is requested when the opt-in is off or there is no data dir. `@bugsee/node` also re-exports `storageTrackerFor`/`resetStorageTracker`/`StorageTracker`. **Behaviour notes:** (1) the tracker is one per DATA DIR, so a second launch over the same dir shares it (and hands it its `onError`/seams) while a launch over another dir has its own (tests that inject `diskStatfs` must pass a private `key` or call `resetStorageTracker()`; added to the node launch test afterEach); (2) within one dir, seams merge, so a later launch without `diskStatfs`/`scheduler` keeps an earlier launch's; (3) wire behaviour is unchanged (each producer polls its own dir and reports to its own `onError`, as the pre-tracker code did); a relaunch over the same dir with a changed seam re-reads at once. An earlier revision keyed the singleton on the `process` object and let a later launch's data dir replace a running launch's: fixed in review. +- **TR9 part 1 (implemented on `feat/electron-process-tracker`; Electron main-process PROCESS tracker; power/screen/window-focus/hang events are part 2):** the **`ElectronProcessTracker`** (`packages/trackers/src/electron/process-tracker.ts`, `@bugsee/trackers/electron`, previously an empty placeholder) ABSORBS `@bugsee/electron`'s `GpuInfoCache` (file, tests and `mapGpuInfo` moved: `mapGpuInfo` now lives in `packages/trackers/src/electron/gpu-info.ts` and returns a neutral `ElectronGpu`, structurally the `HardwareGpu` of `@bugsee/node`). Singleton per `app` object (`electronProcessTrackerFor({app, scheduler?, intervalMs?, key?}, onError?)`, `resetElectronProcessTracker(key)`; no `app` and no `key` throws, a shared anonymous tracker would have no owner). Electron is INJECTED as the structural `ElectronAppSource` (`getAppMetrics`/`getGPUInfo`/`on`/`removeListener`|`off`); the package depends on neither `electron` nor the DOM. THREE stages: `appMetrics` (one unref'd timer, default 1 s, armed only while it has a listener; `{processes: [{type, pid, cpuPct?, workingSetBytes?, peakWorkingSetBytes?, privateBytes?}]}`, Electron's KiB converted to bytes, a field Electron did not give is omitted never zeroed, a process with no usable metric is dropped, an empty/non-array result emits nothing; it is WINDOWED, so arming makes ONE discarded PRIMING `getAppMetrics` read and the first emission is the first tick; Chromium returns 0 on the FIRST CPU call per process (Electron keeps one metrics object per child process), so the tracker remembers the pids of the previous read and omits `cpuPct` for a pid's first sighting (a renderer or restarted GPU/utility process appearing later, same type new pid), and where Electron reports `cpu.cumulativeCPUUsage` a process without it also has no `cpuPct` (Electron sends 0 "for compatibility"); `cpuPct` is the share of the WHOLE machine, 0-100; `current('appMetrics')` is the last sample of the run), `childProcessGone` (`app.on('child-process-gone')` attached only while a listener exists and removed with the same function when the last leaves; `{type, reason, exitCode?, name?}`, malformed details ignored; not attached at all when the app has neither `removeListener` nor `off`, since it could never be released), and `gpu` (`requestGpuInfo(type = 'basic')` / `cancelGpuInfo()` / `current('gpu')`: a USABLE settled value is kept and not re-requested for the same type; it asks again after a rejection/throw/unmappable result or for a DIFFERENT type, and a failed re-ask keeps the earlier usable value; a rejection or throw is reported and no unhandled rejection results, a late result after `cancelGpuInfo()` is ignored; the `gpu` stage fires on each usable settle). `render-process-gone` is NOT part of the tracker: it is an incident path and `renderer-gone.ts` is unchanged. Seams merge never drop, `rebind` on a changed seam tears the run down with the OLD seams and re-arms (re-primes) on the new, generation-guarded timer callbacks, a throwing/async reporter never escapes. **Retention rule (stated and tested):** only the merged seams and the once-only GPU result survive the last unsubscribe; the priming read is repeated and the last sample dropped; `reset()` drops everything including the GPU. **Producers in `@bugsee/electron` (composition only):** `system-traces.ts` (`createElectronSystemTraceProducers(tracker)` -> one `app_metrics` producer) and `system-events.ts` (`createElectronSystemEventsSource(inner, tracker, onError?)`, a LAZY mux: nothing attached at construction; on the first subscriber it subscribes to the inner node source (its `process_started` and signal/exit handlers) AND the tracker's `childProcessGone`, releasing both, each guarded, on the last unsubscribe; it never emits `process_started` itself). **Wire shapes:** trace `app_metrics` = `{processes: [{type, pid, cpu_percent?, working_set_mb?, peak_working_set_mb?, private_mb?}]}` (Electron's process type verbatim, `cpu_percent` the whole-machine share rounded to 2 decimals, integer binary MB via `bytesToMegabytes`, `hold:false` so a failing read leaves a gap; JS-specific name, neither Android nor the viewer has an entry, so it is an open object like `storage_estimate`; **viewer support is UNCONFIRMED (Q5)** and flat per-type totals are the alternative shape); event `child_process_gone` on `events.system` with params `{type, reason, exitCode?, name?}` (`exitCode` stays camelCase: the existing multi-word event params, e.g. the browser's `previousLanguage`, are camelCase; it also fires with `reason: 'clean-exit'`). **`@bugsee/node`:** new advanced launch option `wrapSystemEventsSource(inner)` (the seam P3 asks for): the provider subscribes to the SOURCE it returns, a throwing factory is reported and the plain node source is used. **`launchMain`:** with an `app` and when this is NOT a repeat call (a repeat is detected up front from the carrier client, exactly `launchCore`'s own test, so it can never rebind the running launch's shared trackers) it builds the tracker THROUGH `electronProcessTrackerFor`, passes `systemTraceProducers = [...(caller's ?? createNodeSystemTraceProducers({scheduler, onError})), ...electron producers]` (not when the legacy `systemMetricsSampler` is set), composes `wrapSystemEventsSource` (a caller wrapper first, ours around it), and serves `hardware.gpu` from `tracker.current('gpu')` (same field-wise `hardwareExtras` precedence and `sanitizeHardwareGpu` as ST6a; `gpuInfoType` still `'basic'|'complete'`); the GPU read is requested once on the FIRST launch and cancelled in `client.stop()`. `@bugsee/electron` gained the `@bugsee/trackers` and `@bugsee/capture` workspace dependencies. **Tests:** tracker unit tests (100% with the mutator loop), producer/mux unit tests, launch-level tests (accessor spy: mutating launchMain to `new ElectronProcessTracker` fails; node + Electron traces both present with no name twice; a throwing `getAppMetrics` leaves the node producers emitting) and a real-launch integration test (`system-telemetry.integration.test.ts`: `app_metrics` next to node traces in the uploaded bundle, `child_process_gone` on `events.system`, `captureSystemEvents:false` -> no node handlers and no `child-process-gone` listener, `client.stop()` releases handlers, listener and timers). **Not verified without a real Electron (source-verified by review, not run):** the real `getAppMetrics` shape and units (KiB), `child-process-gone` details, and `getGPUInfo` output. - **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 (per-producer start/stop isolation, last-value refresh so a rolling window never loses a rarely-changing diff --git a/packages/bugsee/src/relaunch-options.test.ts b/packages/bugsee/src/relaunch-options.test.ts index 58ba22ba..a79d8159 100644 --- a/packages/bugsee/src/relaunch-options.test.ts +++ b/packages/bugsee/src/relaunch-options.test.ts @@ -109,8 +109,8 @@ function optionKeys(pkg: string, file: string, name: string): string[] { * - `lifecycleEventsListener` is held on the carrier slot (`setProcessLifecycleEventsListener`), so it * survives a relaunch without being re-passed; * - the Electron handles (`app`, `ipcMain`, `crashReporter`, `gpuInfoType`, `bridge`, `post`, `launch`, `onSessionId`, - * `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; + * `nativeCrash`, `video`) belong to compositions that `relaunchWith` never re-runs (it re-runs the node + * launch, not `launchMain`), and keeping them would pin Electron objects on `globalThis` for nothing; * - `appToken` (the Cloudflare and Nuxt adapters accept it inside their options object) is the token itself, * which `setCarrierLastLaunch` stores separately as `lastLaunch.appToken`; it is never part of the kept options; * - `onSpanProcessor` and `setupOtelProvider` (Next.js server) wire the Bugsee span processor into an OTel @@ -125,7 +125,12 @@ function optionKeys(pkg: string, file: string, name: string): string[] { * - `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 - * relaunch therefore builds the runtime's fresh default set. + * relaunch therefore builds the runtime's fresh default set; + * - `wrapSystemEventsSource` (node, set by `@bugsee/electron`'s `launchMain`) is a platform composition seam whose + * wrapper is bound to the launch's tracker and reporter. A node/umbrella `relaunch()` in an Electron main re-runs + * the NODE launch, so like `systemTraceProducers` it is not re-applied: the relaunched client has the plain node + * producers and events source (no `app_metrics`/`child_process_gone`), while the kept `hardwareExtras` keeps + * serving `hardware.gpu`. */ const RESET_OPTIONS: readonly string[] = [ 'app', @@ -213,6 +218,7 @@ const RESET_OPTIONS: readonly string[] = [ 'traceResponse', 'unhandledRejections', 'video', + 'wrapSystemEventsSource', ]; // Builds a TypeScript program per platform interface: far slower on a shared CI runner than locally. diff --git a/packages/electron/README.md b/packages/electron/README.md index 43c996bc..eebfeaf4 100644 --- a/packages/electron/README.md +++ b/packages/electron/README.md @@ -68,6 +68,16 @@ If you pass `app` to `launchMain`, the SDK reports `app.getVersion()` as your ap Electron does not expose a build number, so set `appBuild` (or `BUGSEE_APP_BUILD`) if you want one; in CI the commit hash is picked up automatically. +## Process telemetry + +If you pass `app` to `launchMain`, the main process also reports what Electron can say about the app's processes, next to the usual Node traces (`process_memory_*`, `cpu_*`, `event_loop_*`): + +- The `app_metrics` system trace, polled from `app.getAppMetrics()` once a second while system traces are captured: `{ processes: [{ type, pid, cpu_percent, working_set_mb, peak_working_set_mb, private_mb }] }`. `type` is Electron's process type (`Browser`, `Tab`, `GPU`, `Utility`, ...). `cpu_percent` is the share of the whole machine (0-100, rounded to 2 decimals), measured since the previous call. A field Electron does not supply is left out, never sent as zero, there is no sample for the first interval, and a process's first appearance (a new renderer, a restarted GPU or utility process) carries no `cpu_percent` because Chromium has no CPU window for it yet. +- A `child_process_gone` system event (`{ type, reason, exitCode, name }`) when a GPU or utility process exits, including a normal exit (`reason: 'clean-exit'`), so filter on `reason` if you only want crashes. It is recorded only while `captureSystemEvents` is on, and the `child-process-gone` listener is removed again by `client.stop()`. +- `environment.hardware.gpu` from `app.getGPUInfo(gpuInfoType)` (`'basic'` by default). A usable result is kept; a failed read, or a different `gpuInfoType` on a later launch, asks again. + +A `relaunch()` from `@bugsee/node` or `@bugsee/bugsee` is not Electron-aware: after it `hardware.gpu` is still served, but `app_metrics` and `child_process_gone` stop until `launchMain` runs again. + ## Links - Repository: https://github.com/bugsee/bugsee-javascript/tree/main/packages/electron diff --git a/packages/electron/package.json b/packages/electron/package.json index a33106c7..3d6fd16e 100644 --- a/packages/electron/package.json +++ b/packages/electron/package.json @@ -41,9 +41,11 @@ }, "dependencies": { "@bugsee/browser": "workspace:*", + "@bugsee/capture": "workspace:*", "@bugsee/core": "workspace:*", "@bugsee/node": "workspace:*", - "@bugsee/protocol": "workspace:*" + "@bugsee/protocol": "workspace:*", + "@bugsee/trackers": "workspace:*" }, "devDependencies": { "@bugsee/util": "workspace:*", diff --git a/packages/electron/src/gpu-info-cache.test.ts b/packages/electron/src/gpu-info-cache.test.ts deleted file mode 100644 index c1b2d057..00000000 --- a/packages/electron/src/gpu-info-cache.test.ts +++ /dev/null @@ -1,337 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; -import { createGpuInfoCache, mapGpuInfo } from './gpu-info-cache'; - -const flush = () => new Promise((resolve) => setImmediate(resolve)); - -function deferred() { - let resolve!: (v: T) => void; - let reject!: (e: unknown) => void; - const promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); - return { promise, resolve, reject }; -} - -const basic = (devices: unknown[]) => ({ gpuDevice: devices }); - -describe('mapGpuInfo', () => { - it('uses the ACTIVE device strings, wherever it is in the list', () => { - const dev = (active: boolean, name: string) => ({ - vendorId: 1, - deviceId: 2, - active, - vendorString: `${name}-vendor`, - deviceString: `${name}-device`, - }); - const expected = (name: string) => ({ vendor: `${name}-vendor`, renderer: `${name}-device` }); - expect(mapGpuInfo(basic([dev(true, 'A'), dev(false, 'B'), dev(false, 'C')]))).toEqual( - expected('A'), - ); - expect(mapGpuInfo(basic([dev(false, 'A'), dev(true, 'B'), dev(false, 'C')]))).toEqual( - expected('B'), - ); - expect(mapGpuInfo(basic([dev(false, 'A'), dev(false, 'B'), dev(true, 'C')]))).toEqual( - expected('C'), - ); - }); - - it('takes the FIRST active device, and only a literal `active: true` counts', () => { - expect( - mapGpuInfo( - basic([ - { active: true, vendorString: 'First' }, - { active: true, vendorString: 'Second' }, - ]), - ), - ).toEqual({ vendor: 'First' }); - expect( - mapGpuInfo( - basic([ - { active: 1, vendorString: 'A' }, - { active: 'yes', vendorString: 'B' }, - ]), - ), - ).toBeUndefined(); - }); - - it('uses the only device when none is flagged active, but never guesses among several', () => { - expect(mapGpuInfo(basic([{ vendorString: 'V', deviceString: 'R' }]))).toEqual({ - vendor: 'V', - renderer: 'R', - }); - expect( - mapGpuInfo( - basic([ - { vendorString: 'A', deviceString: 'a' }, - { vendorString: 'B', deviceString: 'b' }, - ]), - ), - ).toBeUndefined(); - }); - - it('omits a field whose string is missing; never invents a vendor from a numeric id', () => { - expect(mapGpuInfo(basic([{ active: true, vendorId: 4318, vendorString: 'NVIDIA' }]))).toEqual({ - vendor: 'NVIDIA', - }); - expect(mapGpuInfo(basic([{ active: true, deviceString: 'RTX' }]))).toEqual({ renderer: 'RTX' }); - expect(mapGpuInfo(basic([{ active: true, vendorId: 4318, deviceId: 7 }]))).toBeUndefined(); - expect( - mapGpuInfo(basic([{ active: true, vendorString: ' ', deviceString: 5 }])), - ).toBeUndefined(); - }); - - it('fills vendor/renderer/gl_version/gl_extensions from auxAttributes (trimmed)', () => { - expect( - mapGpuInfo({ - gpuDevice: [ - { vendorId: 4318, deviceId: 7, active: true, vendorString: '', deviceString: '' }, - ], - auxAttributes: { - glVendor: ' NVIDIA Corporation ', - glRenderer: 'RTX 4090/PCIe', - glVersion: 'OpenGL ES 3.0', - glExtensions: 'GL_A GL_B', - }, - }), - ).toEqual({ - vendor: 'NVIDIA Corporation', - renderer: 'RTX 4090/PCIe', - gl_version: 'OpenGL ES 3.0', - gl_extensions: 'GL_A GL_B', - }); - }); - - it('works from auxAttributes alone (no gpuDevice), and device strings win over aux per field', () => { - expect(mapGpuInfo({ auxAttributes: { glRenderer: 'R' } })).toEqual({ renderer: 'R' }); - expect( - mapGpuInfo({ - gpuDevice: [{ active: true, vendorString: 'DevVendor' }], - auxAttributes: { glVendor: 'AuxVendor', glRenderer: 'AuxRenderer' }, - }), - ).toEqual({ vendor: 'DevVendor', renderer: 'AuxRenderer' }); - }); - - it('drops blank / non-string aux values and ignores a non-object aux; ids never become names', () => { - expect( - mapGpuInfo({ - gpuDevice: [{ active: true, vendorId: 4318, deviceId: 1 }], - auxAttributes: { glVendor: ' ', glRenderer: 5, glVersion: null, glExtensions: ['A'] }, - }), - ).toBeUndefined(); - expect(mapGpuInfo({ gpuDevice: [], auxAttributes: 'x' })).toBeUndefined(); - expect(mapGpuInfo({ gpuDevice: [], auxAttributes: null })).toBeUndefined(); - }); - - it.each([ - ['undefined', undefined], - ['null', null], - ['a string', 'gpu'], - ['no gpuDevice', {}], - ['a non-array gpuDevice', { gpuDevice: 'x' }], - ['an empty list', { gpuDevice: [] }], - ['non-object devices', { gpuDevice: [1, null, 'x'] }], - ])('returns undefined for %s', (_n, value) => { - expect(mapGpuInfo(value)).toBeUndefined(); - }); -}); - -describe('createGpuInfoCache', () => { - const info = basic([{ active: true, vendorString: 'V', deviceString: 'R' }]); - - it('is undefined until the Promise settles, then serves the mapped gpu', async () => { - const d = deferred(); - const getGPUInfo = vi.fn(() => d.promise); - const cache = createGpuInfoCache({ source: { getGPUInfo } }); - cache.start(); - expect(getGPUInfo).toHaveBeenCalledExactlyOnceWith('basic'); - expect(cache.current()).toBeUndefined(); - d.resolve(info); - await flush(); - expect(cache.current()).toEqual({ gpu: { vendor: 'V', renderer: 'R' } }); - }); - - it("passes the configured type to getGPUInfo (default 'basic')", () => { - const complete = vi.fn(() => new Promise(() => {})); - createGpuInfoCache({ source: { getGPUInfo: complete }, type: 'complete' }).start(); - expect(complete).toHaveBeenCalledExactlyOnceWith('complete'); - const dflt = vi.fn(() => new Promise(() => {})); - createGpuInfoCache({ source: { getGPUInfo: dflt } }).start(); - expect(dflt).toHaveBeenCalledExactlyOnceWith('basic'); - }); - - it('kicks getGPUInfo once even when start() is called repeatedly', () => { - const getGPUInfo = vi.fn(() => new Promise(() => {})); - const cache = createGpuInfoCache({ source: { getGPUInfo } }); - cache.start(); - cache.start(); - expect(getGPUInfo).toHaveBeenCalledTimes(1); - }); - - it('returns a copy, so a consumer cannot mutate the cache', async () => { - const cache = createGpuInfoCache({ source: { getGPUInfo: async () => info } }); - cache.start(); - await flush(); - (cache.current() as { gpu: { vendor?: string } }).gpu.vendor = 'hacked'; - expect(cache.current()).toEqual({ gpu: { vendor: 'V', renderer: 'R' } }); - }); - - it('a rejection becomes omit + onError, with NO unhandledRejection', async () => { - const unhandled = vi.fn(); - process.on('unhandledRejection', unhandled); - try { - const boom = new Error('no acceleration'); - const onError = vi.fn(); - const cache = createGpuInfoCache({ - source: { getGPUInfo: () => Promise.reject(boom) }, - onError, - }); - cache.start(); - await flush(); - await flush(); - expect(cache.current()).toBeUndefined(); - expect(onError).toHaveBeenCalledExactlyOnceWith(boom); - expect(unhandled).not.toHaveBeenCalled(); - } finally { - process.off('unhandledRejection', unhandled); - } - }); - - it('a rejection with no onError, and a throwing onError, stay silent', async () => { - const unhandled = vi.fn(); - process.on('unhandledRejection', unhandled); - try { - createGpuInfoCache({ source: { getGPUInfo: () => Promise.reject(new Error('x')) } }).start(); - const c2 = createGpuInfoCache({ - source: { getGPUInfo: () => Promise.reject(new Error('y')) }, - onError: () => { - throw new Error('sink'); - }, - }); - c2.start(); - await flush(); - await flush(); - expect(c2.current()).toBeUndefined(); - expect(unhandled).not.toHaveBeenCalled(); - } finally { - process.off('unhandledRejection', unhandled); - } - }); - - it('an async onError that rejects leaves NO unhandledRejection', async () => { - const unhandled = vi.fn(); - process.on('unhandledRejection', unhandled); - try { - createGpuInfoCache({ - source: { getGPUInfo: () => Promise.reject(new Error('x')) }, - onError: async () => { - throw new Error('async sink'); - }, - }).start(); - await flush(); - await flush(); - await new Promise((r) => setTimeout(r, 10)); - expect(unhandled).not.toHaveBeenCalled(); - } finally { - process.off('unhandledRejection', unhandled); - } - }); - - it('a synchronous throw from getGPUInfo is reported, not propagated', () => { - const boom = new Error('sync'); - const onError = vi.fn(); - const cache = createGpuInfoCache({ - source: { - getGPUInfo: () => { - throw boom; - }, - }, - onError, - }); - expect(() => cache.start()).not.toThrow(); - expect(onError).toHaveBeenCalledExactlyOnceWith(boom); - expect(cache.current()).toBeUndefined(); - }); - - it('a hostile result whose mapping throws is reported and omitted', async () => { - const hostile = { - get gpuDevice(): unknown { - throw new Error('getter'); - }, - }; - const onError = vi.fn(); - const cache = createGpuInfoCache({ source: { getGPUInfo: async () => hostile }, onError }); - cache.start(); - await flush(); - expect(cache.current()).toBeUndefined(); - expect(onError).toHaveBeenCalledTimes(1); - }); - - it('a late resolve after stop() is ignored (no cache write) and a late reject is not reported', async () => { - const d = deferred(); - const onError = vi.fn(); - const cache = createGpuInfoCache({ source: { getGPUInfo: () => d.promise }, onError }); - cache.start(); - cache.stop(); - d.resolve(info); - await flush(); - expect(cache.current()).toBeUndefined(); - - const d2 = deferred(); - const cache2 = createGpuInfoCache({ source: { getGPUInfo: () => d2.promise }, onError }); - cache2.start(); - cache2.stop(); - d2.reject(new Error('late')); - await flush(); - expect(onError).not.toHaveBeenCalled(); - }); - - it('stop() KEEPS an already-resolved value (reports still draining during stop must carry it)', async () => { - const cache = createGpuInfoCache({ source: { getGPUInfo: async () => info } }); - cache.start(); - await flush(); - cache.stop(); - expect(cache.current()).toEqual({ gpu: { vendor: 'V', renderer: 'R' } }); - }); - - it('a start() after stop() begins afresh, and the OLD promise cannot write into the new run', async () => { - const first = deferred(); - const second = deferred(); - const getGPUInfo = vi - .fn() - .mockReturnValueOnce(first.promise) - .mockReturnValueOnce(second.promise); - const cache = createGpuInfoCache({ source: { getGPUInfo } }); - cache.start(); - cache.stop(); - cache.start(); - expect(getGPUInfo).toHaveBeenCalledTimes(2); - first.resolve(basic([{ active: true, vendorString: 'OLD' }])); - await flush(); - expect(cache.current()).toBeUndefined(); - second.resolve(basic([{ active: true, vendorString: 'NEW' }])); - await flush(); - expect(cache.current()).toEqual({ gpu: { vendor: 'NEW' } }); - }); - - it.each([ - ['no source', undefined], - ['a source without getGPUInfo', {}], - ['a non-function getGPUInfo', { getGPUInfo: 5 as never }], - ])('%s: nothing cached, no error', (_n, source) => { - const onError = vi.fn(); - const cache = createGpuInfoCache({ source, onError }); - expect(() => { - cache.start(); - cache.stop(); - }).not.toThrow(); - expect(cache.current()).toBeUndefined(); - expect(onError).not.toHaveBeenCalled(); - }); - - it('tolerates being used with no options at all', () => { - const cache = createGpuInfoCache(); - cache.start(); - expect(cache.current()).toBeUndefined(); - }); -}); diff --git a/packages/electron/src/gpu-info-cache.ts b/packages/electron/src/gpu-info-cache.ts deleted file mode 100644 index c7055e03..00000000 --- a/packages/electron/src/gpu-info-cache.ts +++ /dev/null @@ -1,123 +0,0 @@ -// GpuInfoCache — the Electron main process's GPU description, for `environment.hardware.gpu`. -// -// `app.getGPUInfo('basic')` returns a PROMISE, and the environment is assembled synchronously, so the -// answer is kicked once at launch, cached when (if) it settles, and read live through `current()`. Until -// it settles — or forever, when it rejects (a Linux host without GPU acceleration does) — `current()` is -// `undefined` and the report simply carries no `hardware.gpu`. Nothing here may throw into the host app or -// leave a rejected Promise unhandled (the session owner's own unhandled-rejection detection would report it). -// -// `electron` is injected (`ElectronGpuSourceLike`); this package keeps no electron dependency. - -import type { HardwareExtras, HardwareGpu } from '@bugsee/node'; -import { reportGuarded } from '@bugsee/util'; - -/** The slice of Electron's `app` the cache needs. Optional on `ElectronAppLike`: older Electron has none. */ -export interface ElectronGpuSourceLike { - getGPUInfo(type: GpuInfoType): Promise; -} - -/** Electron's `app.getGPUInfo` argument. */ -export type GpuInfoType = 'basic' | 'complete'; - -export interface GpuInfoCacheOptions { - /** Electron's `app` (or anything with `getGPUInfo`). When absent or without `getGPUInfo`, nothing is ever cached. */ - source?: Partial | undefined; - /** The `getGPUInfo` argument. Default `'basic'`. */ - type?: GpuInfoType; - /** Sink for a rejected/throwing `getGPUInfo` (omit-never-fabricate: the error is reported, the field is absent). */ - onError?: (error: unknown) => void; -} - -export interface GpuInfoCache { - /** Kick `getGPUInfo(type)` once. A second call while started is a no-op. Never throws. */ - start(): void; - /** Abort the in-flight read: a late resolve/reject is ignored. An ALREADY-resolved value is kept (reports still draining on stop need it). */ - stop(): void; - /** The cached `hardware` extra, or `undefined` while unsettled / failed / unusable. */ - current(): HardwareExtras | undefined; -} - -const nonEmpty = (value: unknown): string | undefined => - typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined; - -/** - * Maps Electron's GPU info to the `hardware.gpu` block, defensively. The shapes are UNVERIFIED against a real - * Electron: `'basic'` is documented as `{ gpuDevice: [{ vendorId, deviceId, active, vendorString?, - * deviceString?, … }], auxAttributes? }` and often carries only the numeric ids; `'complete'` is heavier and - * is expected to carry `auxAttributes.glVendor/glRenderer/glVersion/glExtensions`. - * - * The ACTIVE device is used (or the only device when exactly one is listed — never a guess among several): - * `vendorString` -> `vendor`, `deviceString` -> `renderer`. `auxAttributes` (when present) fills what the - * device left empty: `glVendor` -> `vendor`, `glRenderer` -> `renderer`, `glVersion` -> `gl_version`, - * `glExtensions` -> `gl_extensions` (a string). Values are trimmed and empty/whitespace-only ones dropped; a - * numeric id is NEVER turned into a name. Nothing usable -> `undefined`. - */ -export function mapGpuInfo(info: unknown): HardwareGpu | undefined { - if (typeof info !== 'object' || info === null) return undefined; - const { gpuDevice, auxAttributes } = info as { gpuDevice?: unknown; auxAttributes?: unknown }; - const objects = Array.isArray(gpuDevice) - ? gpuDevice.filter((d): d is Record => typeof d === 'object' && d !== null) - : []; - const device = - objects.find((d) => d.active === true) ?? (objects.length === 1 ? objects[0] : undefined); - const aux = - typeof auxAttributes === 'object' && auxAttributes !== null - ? (auxAttributes as Record) - : {}; - const vendor = nonEmpty(device?.vendorString) ?? nonEmpty(aux.glVendor); - const renderer = nonEmpty(device?.deviceString) ?? nonEmpty(aux.glRenderer); - const glVersion = nonEmpty(aux.glVersion); - const glExtensions = nonEmpty(aux.glExtensions); - const gpu: HardwareGpu = { - ...(vendor !== undefined ? { vendor } : {}), - ...(renderer !== undefined ? { renderer } : {}), - ...(glVersion !== undefined ? { gl_version: glVersion } : {}), - ...(glExtensions !== undefined ? { gl_extensions: glExtensions } : {}), - }; - return Object.keys(gpu).length > 0 ? gpu : undefined; -} - -export function createGpuInfoCache(options: GpuInfoCacheOptions = {}): GpuInfoCache { - let generation = 0; - let started = false; - let gpu: HardwareGpu | undefined; - - // absorbs a throwing sink AND a rejected promise from an async one; the cache stays silent toward the host - const report = (error: unknown): void => reportGuarded(options.onError, error); - - return { - start(): void { - if (started) return; - started = true; - const mine = ++generation; - const source = options.source; - if (source === undefined || typeof source.getGPUInfo !== 'function') return; - try { - Promise.resolve(source.getGPUInfo(options.type ?? 'basic')).then( - (info) => { - if (mine !== generation) return; // stopped (or restarted) since: ignore, never write - try { - gpu = mapGpuInfo(info); - } catch (error) { - report(error); - } - }, - (error: unknown) => { - if (mine === generation) report(error); - }, - ); - } catch (error) { - report(error); // getGPUInfo threw synchronously - } - }, - stop(): void { - started = false; - generation++; // a late resolve/reject of the in-flight read is now ignored - // The cached value is deliberately KEPT: core `stop()` drains pending reports AFTER this runs, and - // they must still carry hardware.gpu. A new `launchMain` builds a new cache, so nothing leaks. - }, - current(): HardwareExtras | undefined { - return gpu === undefined ? undefined : { gpu: { ...gpu } }; - }, - }; -} diff --git a/packages/electron/src/launch-main.test.ts b/packages/electron/src/launch-main.test.ts index 93c074a8..2e939f37 100644 --- a/packages/electron/src/launch-main.test.ts +++ b/packages/electron/src/launch-main.test.ts @@ -1,11 +1,15 @@ +import type { SystemEvent, TraceProducer, TraceSink } from '@bugsee/capture'; import { BlackoutToken, CaptureDataEntryBase, CaptureStoreToken, createBlackoutState, + InterceptorBase, } from '@bugsee/core'; import type { Bugsee, BugseeLaunchOptions } from '@bugsee/node'; -import { describe, expect, it, vi } from 'vitest'; +import { resetProcessTracker } from '@bugsee/node'; +import { electronProcessTrackerFor } from '@bugsee/trackers/electron'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { launchMain } from './launch-main'; import type { IpcMainEventLike, IpcMainListener } from './main-receiver'; import { encodePixelVideo } from './pixel-video-controller'; @@ -17,6 +21,17 @@ import { import { decodeControl, encodeHello, encodeStreamEntry } from './protocol'; import type { VideoCaptureSource } from './video-capture'; +// Wraps (never replaces) the registry accessor so a launch-level test can prove launchMain builds its tracker THROUGH it +// (mutating launchMain to `new ElectronProcessTracker(...)` makes the spy go uncalled). Behaviour is untouched. +vi.mock('@bugsee/trackers/electron', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, electronProcessTrackerFor: vi.fn(actual.electronProcessTrackerFor) }; +}); + +afterEach(() => { + resetProcessTracker(); // the node tracker is a process singleton: a test's fake scheduler must not leak +}); + function fakeIpcMain() { const listeners = new Map(); return { @@ -816,3 +831,250 @@ describe('launchMain — app identity', () => { expect(identityOf({ app: appWith(() => 5 as never) })?.()).toEqual({}); }); }); + +describe('launchMain — Electron process tracker composition (TR9, part 1)', () => { + const optsOf = (f: ReturnType) => + (f.received as { options: BugseeLaunchOptions }).options; + + function fakeScheduler() { + const armed = new Map void>(); + let next = 1; + return { + setInterval: (callback: () => void) => { + const id = next++; + armed.set(id, callback); + return id; + }, + clearInterval: (id: unknown) => { + armed.delete(id as number); + }, + tick: () => { + for (const cb of [...armed.values()]) cb(); + }, + }; + } + + type GoneL = (event: unknown, details: unknown) => void; + function appWith(getAppMetrics?: () => unknown) { + // `render-process-gone` is registered on this app by launchMain itself: only the child-process-gone ones are tracked + const listeners: GoneL[] = []; + return { + listeners, + app: { + on: vi.fn((event: string, l: GoneL) => { + if (event === 'child-process-gone') listeners.push(l); + }), + removeListener: vi.fn((event: string, l: GoneL) => { + const i = listeners.indexOf(l); + if (event === 'child-process-gone' && i >= 0) listeners.splice(i, 1); + }), + ...(getAppMetrics !== undefined ? { getAppMetrics } : {}), + }, + }; + } + const metric = { + pid: 1, + type: 'Browser', + cpu: { percentCPUUsage: 2 }, + memory: { workingSetSize: 1024 }, + }; + + const sinkOf = () => { + const emitted: Array<{ name: string; value: unknown }> = []; + const sink: TraceSink = { emit: (name, value) => emitted.push({ name, value }) }; + return { emitted, sink }; + }; + + it('builds the tracker THROUGH the registry accessor, keyed on the injected app, with the launch scheduler/onError', () => { + const accessor = vi.mocked(electronProcessTrackerFor); + accessor.mockClear(); + const { app } = appWith(); + const scheduler = fakeScheduler(); + const onError = vi.fn(); + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app, + scheduler, + onError, + }); + expect(accessor).toHaveBeenCalledExactlyOnceWith({ app, scheduler }, onError); + }); + + it('builds no tracker, no producers and no events wrapper without an app', () => { + const accessor = vi.mocked(electronProcessTrackerFor); + accessor.mockClear(); + const f = fakeLaunch(); + launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch }); + expect(accessor).not.toHaveBeenCalled(); + expect(optsOf(f).systemTraceProducers).toBeUndefined(); + expect(optsOf(f).wrapSystemEventsSource).toBeUndefined(); + }); + + it('passes node producers PLUS app_metrics, with no producer or trace name twice', () => { + const { app } = appWith(() => [metric]); + const f = fakeLaunch(); + const scheduler = fakeScheduler(); + launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch, app, scheduler }); + const producers = optsOf(f).systemTraceProducers as readonly TraceProducer[]; + const names = producers.map((p) => p.name); + expect(names).toContain('process-memory'); + expect(names).toContain('event-loop-lag'); + expect(names).toContain('electron-app-metrics'); + expect(new Set(names).size).toBe(names.length); + // Which TRACE names does each producer emit? Start them one at a time so the owner of every name is known. + const owners = new Map(); + for (const p of producers) { + const { emitted, sink } = sinkOf(); + p.start(sink); + scheduler.tick(); // every producer's tracker is tick-driven on the launch scheduler + scheduler.tick(); + p.stop(); + for (const name of new Set(emitted.map((e) => e.name))) { + owners.set(name, [...(owners.get(name) ?? []), p.name]); + } + } + expect(owners.get('app_metrics')).toEqual(['electron-app-metrics']); // really emitted (after the first tick) + expect(owners.get('process_memory_rss')).toEqual(['process-memory']); + expect(owners.get('cpu_usage_process')).toEqual(['cpu']); + const twice = [...owners].filter(([, by]) => by.length > 1).map(([name]) => name); + expect(twice).toEqual([]); + }); + + it('a caller-supplied systemTraceProducers is kept and the Electron producer is ADDED to it', () => { + const own: TraceProducer = { name: 'mine', start: () => {}, stop: () => {} }; + const { app } = appWith(); + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app, + systemTraceProducers: [own], + }); + expect((optsOf(f).systemTraceProducers as readonly TraceProducer[]).map((p) => p.name)).toEqual( + ['mine', 'electron-app-metrics'], + ); + }); + + it('a legacy systemMetricsSampler is left alone: no producer list is built', () => { + const { app } = appWith(); + const f = fakeLaunch(); + const sampler = () => []; + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app, + systemMetricsSampler: sampler, + }); + expect(optsOf(f).systemTraceProducers).toBeUndefined(); + expect(optsOf(f).systemMetricsSampler).toBe(sampler); + }); + + it('the app_metrics producer reads the SAME tracker the accessor returned (shared per app)', () => { + const accessor = vi.mocked(electronProcessTrackerFor); + accessor.mockClear(); + const getAppMetrics = vi.fn(() => [metric]); + const { app } = appWith(getAppMetrics); + const scheduler = fakeScheduler(); + const f = fakeLaunch(); + launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch, app, scheduler }); + const producer = (optsOf(f).systemTraceProducers as readonly TraceProducer[]).find( + (p) => p.name === 'electron-app-metrics', + ) as TraceProducer; + const { emitted, sink } = sinkOf(); + producer.start(sink); + scheduler.tick(); + // the tracker the accessor returned holds the very sample the producer just published + expect(accessor.mock.results[0]?.value.current('appMetrics')).toEqual({ + processes: [{ type: 'Browser', pid: 1, cpuPct: 2, workingSetBytes: 1024 * 1024 }], + }); + expect(emitted).toEqual([ + { + name: 'app_metrics', + value: { processes: [{ type: 'Browser', pid: 1, cpu_percent: 2, working_set_mb: 1 }] }, + }, + ]); + producer.stop(); + }); + + it('a getAppMetrics that throws drops only app_metrics: the node producers still start and emit', () => { + const onError = vi.fn(); + const { app } = appWith(() => { + throw new Error('metrics'); + }); + const scheduler = fakeScheduler(); + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app, + scheduler, + onError, + }); + const producers = optsOf(f).systemTraceProducers as readonly TraceProducer[]; + const { emitted, sink } = sinkOf(); + expect(() => { + for (const p of producers) p.start(sink); + }).not.toThrow(); + scheduler.tick(); + for (const p of producers) p.stop(); + expect(emitted.map((e) => e.name)).toContain('process_memory_rss'); + expect(emitted.map((e) => e.name)).not.toContain('app_metrics'); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'metrics' })); + }); + + describe('the events wrapper handed to node', () => { + class Inner extends InterceptorBase<{ event: SystemEvent }> { + readonly name = 'inner'; + protected onActivate(): void { + this.emit('event', { name: 'process_started' }); + } + } + + it('wraps lazily: nothing is attached until subscribed, and everything is released on unsubscribe', () => { + const { app, listeners } = appWith(); + const f = fakeLaunch(); + launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch, app }); + const wrap = optsOf(f).wrapSystemEventsSource as NonNullable< + BugseeLaunchOptions['wrapSystemEventsSource'] + >; + const inner = new Inner(); + const mux = wrap(inner); + expect(app.on).not.toHaveBeenCalledWith('child-process-gone', expect.anything()); + const seen = vi.fn(); + const off = mux.on('event', seen); + expect(listeners).toHaveLength(1); + expect(seen.mock.calls.map((c) => (c[0] as SystemEvent).name)).toEqual(['process_started']); + listeners[0]?.({}, { type: 'GPU', reason: 'crashed', exitCode: 1 }); + expect((seen.mock.calls[1]?.[0] as SystemEvent).name).toBe('child_process_gone'); + off(); + expect(listeners).toHaveLength(0); + }); + + it('composes with a caller wrapper: the caller sees the plain source, ours wraps its result', () => { + const { app } = appWith(); + const f = fakeLaunch(); + const seenInner: unknown[] = []; + const callerResult = new Inner(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app, + wrapSystemEventsSource: (inner) => { + seenInner.push(inner); + return callerResult; + }, + }); + const wrap = optsOf(f).wrapSystemEventsSource as NonNullable< + BugseeLaunchOptions['wrapSystemEventsSource'] + >; + const plain = new Inner(); + const mux = wrap(plain); + const seen = vi.fn(); + mux.on('event', seen); + expect(seenInner).toEqual([plain]); + expect(seen).toHaveBeenCalledWith({ name: 'process_started' }); // came through the caller's source + }); + }); +}); diff --git a/packages/electron/src/launch-main.ts b/packages/electron/src/launch-main.ts index 4719a99e..4f6961db 100644 --- a/packages/electron/src/launch-main.ts +++ b/packages/electron/src/launch-main.ts @@ -6,13 +6,15 @@ // import { launchMain } from '@bugsee/electron/main'; // import { ipcMain } from 'electron'; // launchMain(appToken, { ipcMain }); -import { type AppIdentity, BlackoutToken, CaptureStoreToken } from '@bugsee/core'; +import { type AppIdentity, BlackoutToken, CaptureStoreToken, getCarrierClient } from '@bugsee/core'; import { type Bugsee, type BugseeLaunchOptions, + createNodeSystemTraceProducers, launchCore, sanitizeHardwareGpu, } from '@bugsee/node'; +import { electronProcessTrackerFor, type GpuInfoType } from '@bugsee/trackers/electron'; import { type CrashReporterLike, getCrashDumpsDirectory, @@ -30,6 +32,22 @@ export interface ElectronAppLike { details: { reason: string; exitCode?: number }, ) => void, ): unknown; + /** + * `child-process-gone` (a GPU/utility process died) is watched ONLY while system events are captured, through the + * shared ElectronProcessTracker. When `removeListener`/`off` is missing the listener is never attached (it could not + * be released on `client.stop()`). + */ + on(event: 'child-process-gone', listener: (event: unknown, details: unknown) => void): unknown; + removeListener?( + event: 'child-process-gone', + listener: (event: unknown, details: unknown) => void, + ): unknown; + off?(event: 'child-process-gone', listener: (event: unknown, details: unknown) => void): unknown; + /** + * Electron's `app.getAppMetrics` — optional. When present and system traces are captured, per-process CPU/memory is + * reported as the `app_metrics` trace (polled by the ElectronProcessTracker; absent fields are omitted, never zero). + */ + getAppMetrics?(): 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 @@ -40,7 +58,6 @@ export interface ElectronAppLike { import type { CrashpadSessionMarker } from '@bugsee/core'; import { reportGuarded, reportOncePerMessage } from '@bugsee/util'; -import { createGpuInfoCache, type GpuInfoType } from './gpu-info-cache'; import { createElectronMainControl, type IpcMainControlLike } from './main-control'; import { createElectronMainReceiver, type IpcMainLike } from './main-receiver'; import { createElectronNativeCrashSource, createNodeCrashDumpFs } from './native-crash-source'; @@ -51,6 +68,8 @@ import { } from './pixel-video-controller'; import { createRendererGoneHandler } from './renderer-gone'; import { type RendererGoneIncident, RendererIncidentProvider } from './renderer-incident-provider'; +import { createElectronSystemEventsSource } from './system-events'; +import { createElectronSystemTraceProducers } from './system-traces'; import type { VideoCaptureSource } from './video-capture'; /** The node `launchCore` shape, injectable for tests. */ @@ -81,7 +100,9 @@ export interface LaunchMainOptions extends BugseeLaunchOptions { * expected to carry `auxAttributes.glRenderer`/`glVendor`/`glVersion` (more useful names) but is heavier. * UNVERIFIED against a real Electron: on macOS/Linux `'basic'` commonly yields only numeric vendor/device * ids, in which case `hardware.gpu` is absent (never guessed) until confirmed on a real Electron; pass - * `'complete'` for the GL strings. + * `'complete'` for the GL strings. A usable result is kept for the life of the `app` object; a later launch (after + * `client.stop()`) asks again when the earlier read rejected or returned nothing usable, or when it asks for a + * different type (a failed re-ask keeps the earlier usable value). */ gpuInfoType?: GpuInfoType; /** Electron's `crashReporter` — when provided, native minidumps are captured, session-correlated. */ @@ -173,24 +194,75 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee } } - // GPU for environment.hardware.gpu: the cache is read LIVE by the node environment builder on every - // assemble (so a GPU that settles after launch lands on the next report); it is only STARTED once this - // launch is known to be the first (below). Precedence is FIELD-WISE: the cache's fields, overridden by + // The Electron PROCESS tracker (`@bugsee/trackers/electron`): the one per-`app` singleton that owns everything the + // `app` object can say about the app's processes, and so feeds ALL of the following (this file is composition): + // - the `app_metrics` trace (a producer subscribed to its `appMetrics` stage); + // - the `child_process_gone` system event (the lazy mux subscribes to its `childProcessGone` stage); + // - `environment.hardware.gpu` (its once-only `getGPUInfo` read, below). + // Without an `app` there is nothing to read, so there is no tracker and none of it is wired. The SAME is true of a + // REPEAT call: `launchCore` returns the running client untouched, but building the tracker (or the node producers) + // first would rebind the shared trackers' onError/scheduler and tear down the live launch's timer and listener. So a + // repeat is detected up front (the carrier already holds a client, exactly `launchCore`'s own test) and touches + // nothing. + const repeat = getCarrierClient(nodeOptions.carrier) !== undefined; + const tracker = + app !== undefined && !repeat + ? electronProcessTrackerFor( + { + app, + ...(nodeOptions.scheduler !== undefined ? { scheduler: nodeOptions.scheduler } : {}), + }, + nodeOptions.onError, + ) + : undefined; + + // Trace producers: `systemTraceProducers` REPLACES the node defaults when supplied, so pass the node set (the caller's, + // else the default one wired to this launch's scheduler/onError) PLUS the Electron producers. The node producers keep + // `process_memory_*`/`cpu_*`/`event_loop_*` for the process that owns the session; the Electron ones only add names the + // node set never emits. Not built when the legacy `systemMetricsSampler` replaces the producer list (they would never + // start). + if (tracker !== undefined && nodeOptions.systemMetricsSampler === undefined) { + nodeOptions.systemTraceProducers = [ + ...(nodeOptions.systemTraceProducers ?? + createNodeSystemTraceProducers({ + ...(nodeOptions.scheduler !== undefined ? { scheduler: nodeOptions.scheduler } : {}), + ...(nodeOptions.onError !== undefined ? { onError: nodeOptions.onError } : {}), + })), + ...createElectronSystemTraceProducers(tracker), + ]; + } + + // System events: ONE `events.system` provider exists, so the node events source is wrapped by a LAZY mux that adds + // `child_process_gone`. The mux attaches (inner node handlers + the `app` listener) only when the provider subscribes, + // i.e. only while `captureSystemEvents` is on, and releases both on `client.stop()`. A caller-supplied wrapper is + // applied first (it sees the plain node source), ours wraps its result. + if (tracker !== undefined) { + const callerWrap = nodeOptions.wrapSystemEventsSource; + nodeOptions.wrapSystemEventsSource = (inner) => + createElectronSystemEventsSource( + callerWrap === undefined ? inner : callerWrap(inner), + tracker, + nodeOptions.onError, + ); + } + + // GPU for environment.hardware.gpu: the tracker's settled GPU is read LIVE by the node environment builder on every + // assemble (so a GPU that settles after launch lands on the next report); the read is only REQUESTED once this + // launch is known to be the first (below). Precedence is FIELD-WISE: the tracker's fields, overridden by // whatever non-empty string fields a caller-supplied `hardwareExtras` gives (so a caller that supplies only - // `gl_version` keeps the cache's vendor/renderer). A caller gpu that cleans up to nothing, or a caller that - // throws (reported), leaves the cache's GPU untouched. - // `hardwareExtras` is a KEPT relaunch option, so a node/umbrella `relaunch()` in an Electron main keeps THIS - // wrapper (closing over this cache): it keeps serving the cached GPU after a relaunch (stop() does not clear - // it), but a GPU that had not yet resolved before the relaunch is not re-requested. - const gpuCache = createGpuInfoCache({ - source: app, - ...(gpuInfoType !== undefined ? { type: gpuInfoType } : {}), - ...(nodeOptions.onError !== undefined ? { onError: nodeOptions.onError } : {}), - }); + // `gl_version` keeps the tracker's vendor/renderer). A caller gpu that cleans up to nothing, or a caller that + // throws (reported), leaves the tracker's GPU untouched. + // RELAUNCH: `@bugsee/node`/the umbrella do export `relaunch()`, and it is not Electron-aware. `hardwareExtras` is a KEPT + // relaunch option, so a relaunch keeps THIS wrapper (closing over the tracker) and `hardware.gpu` keeps being served + // (stop() does not clear it; a GPU that had not yet resolved is not re-requested). `systemTraceProducers` and + // `wrapSystemEventsSource` are RESET options, so a relaunched client has the plain node producers and events source: + // `app_metrics` and `child_process_gone` stop until `launchMain` is called again (the carrier client must be cleared + // by a stop for that, as for any launch). const callerExtras = nodeOptions.hardwareExtras; const reportExtrasOnce = reportOncePerMessage(nodeOptions.onError); nodeOptions.hardwareExtras = () => { - const cached = gpuCache.current(); + const gpu = tracker?.current('gpu'); + const cached = gpu === undefined ? undefined : { gpu }; if (callerExtras === undefined) return cached; try { const own = sanitizeHardwareGpu(callerExtras()?.gpu); @@ -204,12 +276,13 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee 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 - // returns the already-wired client untouched, so all Electron wiring hangs off the first-launch internals. + // returns the already-wired client untouched (nothing above bound the shared trackers for it, see `repeat`), so all + // Electron wiring hangs off the first-launch internals. if (internals === undefined) { return client; } - gpuCache.start(); + tracker?.requestGpuInfo(gpuInfoType); // The main client's blackout: the one state the whole session follows (renderers and pixel video). const blackout = client.getService(BlackoutToken); @@ -307,7 +380,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 (an already-resolved GPU is kept) + tracker?.cancelGpuInfo(); // 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(); diff --git a/packages/electron/src/system-events.test.ts b/packages/electron/src/system-events.test.ts new file mode 100644 index 00000000..1fd81e68 --- /dev/null +++ b/packages/electron/src/system-events.test.ts @@ -0,0 +1,205 @@ +import type { SystemEvent } from '@bugsee/capture'; +import { type EventSubscribable, InterceptorBase } from '@bugsee/core'; +import { ElectronProcessTracker } from '@bugsee/trackers/electron'; +import { describe, expect, it, vi } from 'vitest'; +import { createElectronSystemEventsSource } from './system-events'; + +type Events = { event: SystemEvent }; + +/** Stands in for the node events source: emits process_started on activation, tracks active/idle. */ +class FakeInner extends InterceptorBase { + readonly name = 'fake-inner'; + activations = 0; + deactivations = 0; + protected onActivate(): void { + this.activations++; + this.emit('event', { name: 'process_started' }); + } + protected override onDeactivate(): void { + this.deactivations++; + } + fire(event: SystemEvent): void { + this.emit('event', event); + } +} + +function setup() { + const listeners: Array<(event: unknown, details: unknown) => void> = []; + const app = { + on: vi.fn((_e: string, l: (event: unknown, details: unknown) => void) => { + listeners.push(l); + }), + removeListener: vi.fn((_e: string, l: (event: unknown, details: unknown) => void) => { + const i = listeners.indexOf(l); + if (i >= 0) listeners.splice(i, 1); + }), + }; + const onError = vi.fn(); + const tracker = new ElectronProcessTracker({ app }, onError); + const inner = new FakeInner(); + const mux = createElectronSystemEventsSource(inner, tracker, onError); + return { app, listeners, tracker, inner, mux, onError }; +} + +const names = (seen: ReturnType) => + seen.mock.calls.map((c) => (c[0] as SystemEvent).name); + +describe('createElectronSystemEventsSource (lazy mux)', () => { + it('attaches NOTHING at construction: no inner subscription, no app listener', () => { + const { app, inner, mux, tracker } = setup(); + expect(inner.activations).toBe(0); + expect(app.on).not.toHaveBeenCalled(); + expect(mux).toBeDefined(); + tracker.reset(); + }); + + it('on subscribe: attaches the inner source AND child-process-gone; process_started arrives exactly once', () => { + const { app, inner, mux, listeners, tracker } = setup(); + const seen = vi.fn(); + mux.on('event', seen); + expect(inner.activations).toBe(1); + expect(app.on).toHaveBeenCalledExactlyOnceWith('child-process-gone', expect.any(Function)); + expect(names(seen)).toEqual(['process_started']); + inner.fire({ name: 'process_exiting', params: { code: 0 } }); + expect(names(seen)).toEqual(['process_started', 'process_exiting']); + expect(listeners).toHaveLength(1); + tracker.reset(); + }); + + it('forwards the inner events untouched, params included', () => { + const { inner, mux, tracker } = setup(); + const seen = vi.fn(); + mux.on('event', seen); + inner.fire({ name: 'process_signal', params: { signal: 'SIGTERM' } }); + expect(seen).toHaveBeenLastCalledWith({ + name: 'process_signal', + params: { signal: 'SIGTERM' }, + }); + tracker.reset(); + }); + + it('records child_process_gone with {type, reason, exitCode?, name?} and no undefined keys', () => { + const { mux, listeners, tracker } = setup(); + const seen = vi.fn(); + mux.on('event', seen); + listeners[0]?.({}, { type: 'GPU', reason: 'crashed', exitCode: 139, name: 'GPU Process' }); + listeners[0]?.({}, { type: 'Utility', reason: 'oom' }); + expect(seen.mock.calls.slice(1).map((c) => c[0])).toEqual([ + { + name: 'child_process_gone', + params: { type: 'GPU', reason: 'crashed', exitCode: 139, name: 'GPU Process' }, + }, + { name: 'child_process_gone', params: { type: 'Utility', reason: 'oom' } }, + ]); + expect(Object.keys((seen.mock.calls[2]?.[0] as SystemEvent).params ?? {})).toEqual([ + 'type', + 'reason', + ]); + tracker.reset(); + }); + + it('the last unsubscribe releases BOTH: inner deactivated, the very same app listener removed', () => { + const { app, inner, mux, listeners, tracker } = setup(); + const off1 = mux.on('event', vi.fn()); + const off2 = mux.on('event', vi.fn()); + expect(inner.activations).toBe(1); // one attach however many subscribers + off1(); + expect(inner.deactivations).toBe(0); + expect(listeners).toHaveLength(1); + off2(); + expect(inner.deactivations).toBe(1); + expect(listeners).toHaveLength(0); + expect(app.removeListener).toHaveBeenCalledExactlyOnceWith( + 'child-process-gone', + app.on.mock.calls[0]?.[1], + ); + tracker.reset(); + }); + + it('re-subscribing after release attaches again (and process_started fires again with the inner source)', () => { + const { app, inner, mux, tracker } = setup(); + mux.on('event', vi.fn())(); + const seen = vi.fn(); + mux.on('event', seen); + expect(inner.activations).toBe(2); + expect(app.on).toHaveBeenCalledTimes(2); + expect(names(seen)).toEqual(['process_started']); + tracker.reset(); + }); + + it('a failing release of one side cannot strand the other (reported)', () => { + const { app, inner, mux, listeners, onError, tracker } = setup(); + const off = mux.on('event', vi.fn()); + const boom = new Error('inner off'); + const innerOff = vi.spyOn(inner, 'off').mockImplementation(() => { + throw boom; + }); + off(); + expect(innerOff).toHaveBeenCalled(); + expect(onError).toHaveBeenCalledWith(boom); + expect(listeners).toHaveLength(0); + expect(app.removeListener).toHaveBeenCalledTimes(1); + tracker.reset(); + }); + + it('a throwing inner release AND a throwing reporter still release child-process-gone (and an async reporter is silent)', async () => { + const unhandled = vi.fn(); + process.on('unhandledRejection', unhandled); + try { + for (const sink of [ + () => { + throw new Error('sink'); + }, + async () => { + throw new Error('async sink'); + }, + ]) { + const listeners: Array<(event: unknown, details: unknown) => void> = []; + const app = { + on: (_e: string, l: (event: unknown, details: unknown) => void) => { + listeners.push(l); + }, + removeListener: vi.fn(() => { + listeners.length = 0; + }), + }; + const tracker = new ElectronProcessTracker({ app }, () => {}); + const inner = new FakeInner(); + const mux = createElectronSystemEventsSource(inner, tracker, sink); + const off = mux.on('event', vi.fn()); + vi.spyOn(inner, 'off').mockImplementation(() => { + throw new Error('inner off'); + }); + expect(() => off()).not.toThrow(); + expect(app.removeListener).toHaveBeenCalledTimes(1); + expect(listeners).toHaveLength(0); + tracker.reset(); + } + await new Promise((r) => setTimeout(r, 10)); + expect(unhandled).not.toHaveBeenCalled(); + } finally { + process.off('unhandledRejection', unhandled); + } + }); + + it('a throwing subscriber cannot break the other side (isolated + reported)', () => { + const { mux, listeners, onError, tracker } = setup(); + const ok = vi.fn(); + const boom = new Error('subscriber'); + mux.on('event', () => { + throw boom; + }); + mux.on('event', ok); + listeners[0]?.({}, { type: 'GPU', reason: 'killed' }); + expect(names(ok)).toContain('child_process_gone'); + expect(onError).toHaveBeenCalledWith(boom); + tracker.reset(); + }); + + it('exposes the standard subscribable surface', () => { + const { mux, tracker } = setup(); + const sub: EventSubscribable = mux; + expect(typeof sub.on).toBe('function'); + tracker.reset(); + }); +}); diff --git a/packages/electron/src/system-events.ts b/packages/electron/src/system-events.ts new file mode 100644 index 00000000..00cf9f7f --- /dev/null +++ b/packages/electron/src/system-events.ts @@ -0,0 +1,65 @@ +import type { SystemEvent, SystemEventSource } from '@bugsee/capture'; +import { type Interceptor, InterceptorBase } from '@bugsee/core'; +import type { ElectronProcessTracker } from '@bugsee/trackers/electron'; +import { reportGuarded } from '@bugsee/util'; + +// Electron-main `events.system` source: a LAZY MUX over the node events source plus the ElectronProcessTracker's +// `childProcessGone` stage. A second `events.system` provider is rejected (unique provider name), so `launchMain` hands +// this to @bugsee/node's `wrapSystemEventsSource` seam and the ONE provider subscribes to the mux. +// +// LAZY. Nothing is attached when the mux is built. `onActivate` (the first subscriber, i.e. the events provider +// starting, which only happens while `captureSystemEvents` is on) subscribes to the inner node source (which is what +// installs its SIGTERM/SIGINT/`exit`/`beforeExit`/`warning` handlers and emits `process_started`) AND to the tracker's +// `childProcessGone` stage (which is what adds the `app` listener); `onDeactivate` (the last subscriber leaving, i.e. +// `client.stop()`) releases both, each in its own guard so one failing release cannot strand the other. Subscribing at +// construction would, with `captureSystemEvents:false`, still activate the node source's handlers (they suppress +// default signal termination) and keep a `child-process-gone` listener with nowhere to go, surviving `client.stop()`. +// +// The mux forwards the inner events untouched and NEVER emits `process_started` itself (the inner source already does). +// `child_process_gone` params are `{ type, reason, exitCode?, name? }` (Electron's strings verbatim; absent keys omitted; +// `exitCode` stays camelCase like the other multi-word event params, e.g. the browser's `previousLanguage`). + +type Events = { event: SystemEvent }; + +class ElectronSystemEventsSource extends InterceptorBase { + readonly name = 'electron-system-events'; + #offInner: (() => void) | undefined; + #offGone: (() => void) | undefined; + + constructor( + private readonly inner: SystemEventSource, + private readonly tracker: ElectronProcessTracker, + private readonly onError: ((error: unknown) => void) | undefined, + ) { + super(onError); + } + + protected onActivate(): void { + // inner FIRST: its `process_started` marker precedes anything the Electron side can say + this.#offInner = this.inner.on('event', (event) => this.emit('event', event)); + this.#offGone = this.tracker.on('childProcessGone', (gone) => + this.emit('event', { name: 'child_process_gone', params: { ...gone } }), + ); + } + + protected override onDeactivate(): void { + const offInner = this.#offInner; + const offGone = this.#offGone; + for (const off of [offInner, offGone]) { + try { + off?.(); + } catch (error) { + reportGuarded(this.onError, error); // a throwing reporter must not skip the other release + } + } + } +} + +/** The mux. `inner` is the node `events.system` source handed to `wrapSystemEventsSource`. */ +export function createElectronSystemEventsSource( + inner: SystemEventSource, + tracker: ElectronProcessTracker, + onError?: (error: unknown) => void, +): Interceptor { + return new ElectronSystemEventsSource(inner, tracker, onError); +} diff --git a/packages/electron/src/system-telemetry.integration.test.ts b/packages/electron/src/system-telemetry.integration.test.ts new file mode 100644 index 00000000..ef60ee1f --- /dev/null +++ b/packages/electron/src/system-telemetry.integration.test.ts @@ -0,0 +1,257 @@ +// launchMain -> the REAL @bugsee/node launch (real providers, real tracker, real events mux) -> a really assembled + +// uploaded bundle: `app_metrics` rides traces.system next to the node traces, `child_process_gone` lands on +// events.system, and the lazy mux attaches/releases exactly with `captureSystemEvents` / `client.stop()`. + +import type { HttpRequestOptions, HttpResponse, HttpTransport } from '@bugsee/core'; +import { createMemoryCaptureStore } from '@bugsee/core'; +import { type NodeRuntime, realSystemProbe, resetProcessTracker } from '@bugsee/node'; +import { strFromU8, unzipSync } from '@bugsee/util'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { launchMain } from './launch-main'; + +const jsonBody = (obj: unknown): Uint8Array => new Uint8Array(Buffer.from(JSON.stringify(obj))); + +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 }; +} + +/** A process whose listener table is observable (the node events source registers on it). */ +function fakeProcess() { + const table = new Map void>>(); + const proc = { + on: (e: string, l: (...a: unknown[]) => void) => { + table.set(e, [...(table.get(e) ?? []), l]); + return proc; + }, + off: (e: string, l: (...a: unknown[]) => void) => { + table.set( + e, + (table.get(e) ?? []).filter((x) => x !== l), + ); + return proc; + }, + listeners: (e: string) => [...(table.get(e) ?? [])], + exit: () => {}, + kill: () => {}, + stderr: { write: () => true }, + pid: process.pid, + } as unknown as NodeRuntime; + return { proc, count: (e: string) => table.get(e)?.length ?? 0 }; +} + +/** Fires EVERY armed interval on `tick()` (the provider refresh and the tracker poll share it). */ +function manualScheduler() { + const armed = new Map void>(); + let next = 1; + return { + setInterval: (cb: () => void) => { + const id = next++; + armed.set(id, cb); + return id; + }, + clearInterval: (id: unknown) => { + armed.delete(id as number); + }, + tick: () => { + for (const cb of [...armed.values()]) cb(); + }, + get armed() { + return armed.size; + }, + }; +} + +type GoneL = (event: unknown, details: unknown) => void; +function fakeApp(getAppMetrics?: () => unknown) { + const gone: GoneL[] = []; + const app = { + on: vi.fn((event: string, l: GoneL) => { + if (event === 'child-process-gone') gone.push(l); + }), + removeListener: vi.fn((event: string, l: GoneL) => { + const i = gone.indexOf(l); + if (event === 'child-process-gone' && i >= 0) gone.splice(i, 1); + }), + ...(getAppMetrics !== undefined ? { getAppMetrics } : {}), + }; + return { app, gone }; +} + +const metric = { + pid: 7, + type: 'GPU', + cpu: { percentCPUUsage: 4 }, + memory: { workingSetSize: 2048, peakWorkingSetSize: 4096 }, +}; + +function launchWith( + over: { + app?: ReturnType['app']; + captureSystemEvents?: boolean; + scheduler?: ReturnType; + carrier?: object; + onError?: (error: unknown) => void; + }, + fp = fakeProcess(), +) { + const { fn: transport, puts } = recordingTransport(); + const client = launchMain('tok', { + ipcMain: { on: () => {}, removeListener: () => {} }, + ...(over.app !== undefined ? { app: over.app } : {}), + transport, + captureStore: createMemoryCaptureStore({ maxRecordingTimeMs: Number.POSITIVE_INFINITY }), + captureNetwork: false, + capturedDataStore: 'memory', + detectHangs: false, + process: fp.proc, + systemProbe: realSystemProbe, + onError: over.onError ?? vi.fn(), + carrier: over.carrier ?? {}, + ...(over.captureSystemEvents !== undefined + ? { captureSystemEvents: over.captureSystemEvents } + : {}), + ...(over.scheduler !== undefined ? { scheduler: over.scheduler } : {}), + }); + return { client, puts, fp }; +} + +const fileOf = (put: Uint8Array, name: string): T[] => + JSON.parse(strFromU8(unzipSync(put)[name] as Uint8Array)) as T[]; + +afterEach(() => { + resetProcessTracker(); +}); + +describe('Electron main telemetry -> real node launch -> assembled report', () => { + it('app_metrics rides traces.system NEXT TO the node traces, once, with the documented shape', async () => { + const scheduler = manualScheduler(); + const { app } = fakeApp(() => [metric]); + const { client, puts } = launchWith({ app, scheduler }); + scheduler.tick(); // first poll: the priming read happened at arm, so this is the first sample + scheduler.tick(); + await client.logException(new Error('x')); + const traces = fileOf<{ name: string; value: unknown }>( + puts[0] as Uint8Array, + 'traces.system.json', + ); + const names = traces.map((t) => t.name); + expect(names).toContain('process_memory_rss'); // the node set still emits + expect(names).toContain('app_metrics'); + const metrics = traces.find((t) => t.name === 'app_metrics'); + expect(metrics?.value).toEqual({ + processes: [ + { type: 'GPU', pid: 7, cpu_percent: 4, working_set_mb: 2, peak_working_set_mb: 4 }, + ], + }); + await client.stop(); + }); + + it('a getAppMetrics that throws: node traces still emit, no app_metrics', async () => { + const scheduler = manualScheduler(); + const { app } = fakeApp(() => { + throw new Error('metrics'); + }); + const { client, puts } = launchWith({ app, scheduler }); + scheduler.tick(); + await client.logException(new Error('x')); + const names = fileOf<{ name: string }>(puts[0] as Uint8Array, 'traces.system.json').map( + (t) => t.name, + ); + expect(names).toContain('process_memory_rss'); + expect(names).not.toContain('app_metrics'); + await client.stop(); + }); + + it('captureSystemEvents ON: node handlers AND the child-process-gone listener attach; child_process_gone lands on events.system; process_started once', async () => { + const { app, gone } = fakeApp(); + const { client, puts, fp } = launchWith({ app }); + expect(fp.count('warning')).toBe(1); // the node source is live + expect(gone).toHaveLength(1); + gone[0]?.({}, { type: 'GPU', reason: 'crashed', exitCode: 139, name: 'GPU Process' }); + await client.logException(new Error('x')); + const events = fileOf<{ name: string; params?: unknown }>( + puts[0] as Uint8Array, + 'events.system.json', + ); + expect(events.filter((e) => e.name === 'process_started')).toHaveLength(1); + expect(events.find((e) => e.name === 'child_process_gone')?.params).toEqual({ + type: 'GPU', + reason: 'crashed', + exitCode: 139, + name: 'GPU Process', + }); + await client.stop(); + }); + + it('captureSystemEvents OFF: NO node handlers and NO child-process-gone listener', async () => { + const { app, gone } = fakeApp(); + const { client, fp } = launchWith({ app, captureSystemEvents: false }); + expect(fp.count('warning')).toBe(0); + expect(fp.count('beforeExit')).toBe(0); + // launch itself keeps a SIGTERM hook for flush-on-signal; the node EVENTS source must add none on top of it + const bare = launchWith({ captureSystemEvents: false }); + expect(fp.count('SIGTERM')).toBe(bare.fp.count('SIGTERM')); + expect(fp.count('SIGINT')).toBe(bare.fp.count('SIGINT')); + await bare.client.stop(); + expect(app.on).not.toHaveBeenCalledWith('child-process-gone', expect.anything()); + expect(gone).toHaveLength(0); + await client.stop(); + }); + + it("a REPEAT launchMain leaves the running launch's onError/scheduler/listener untouched", async () => { + const carrier = {}; + const firstScheduler = manualScheduler(); + const firstOnError = vi.fn(); + let broken = false; + const { app, gone } = fakeApp(() => { + if (broken) throw new Error('metrics'); + return [metric]; + }); + const first = launchWith({ app, scheduler: firstScheduler, onError: firstOnError, carrier }); + const armed = firstScheduler.armed; + const listeners = gone.length; + const secondScheduler = manualScheduler(); + const secondOnError = vi.fn(); + const second = launchWith({ app, scheduler: secondScheduler, onError: secondOnError, carrier }); + expect(second.client).toBe(first.client); + // the repeat touched nothing: same timers on the FIRST scheduler, none on the second, same app listener + expect(firstScheduler.armed).toBe(armed); + expect(secondScheduler.armed).toBe(0); + expect(gone).toHaveLength(listeners); + broken = true; + firstScheduler.tick(); + expect(firstOnError).toHaveBeenCalledWith(expect.objectContaining({ message: 'metrics' })); + expect(secondOnError).not.toHaveBeenCalledWith(expect.objectContaining({ message: 'metrics' })); + await first.client.stop(); + }); + + it('client.stop() releases the node handlers, the child-process-gone listener and the metrics timer', async () => { + const scheduler = manualScheduler(); + const { app, gone } = fakeApp(() => [metric]); + const { client, fp } = launchWith({ app, scheduler }); + expect(gone).toHaveLength(1); + expect(fp.count('warning')).toBe(1); + const armedBefore = scheduler.armed; + expect(armedBefore).toBeGreaterThan(0); + await client.stop(); + expect(gone).toHaveLength(0); + expect(app.removeListener).toHaveBeenCalledWith('child-process-gone', expect.any(Function)); + expect(fp.count('warning')).toBe(0); + expect(scheduler.armed).toBe(0); + }); +}); diff --git a/packages/electron/src/system-traces.test.ts b/packages/electron/src/system-traces.test.ts new file mode 100644 index 00000000..c5f19699 --- /dev/null +++ b/packages/electron/src/system-traces.test.ts @@ -0,0 +1,149 @@ +import type { TraceSink } from '@bugsee/capture'; +import { ElectronProcessTracker } from '@bugsee/trackers/electron'; +import { describe, expect, it, vi } from 'vitest'; +import { createElectronSystemTraceProducers } from './system-traces'; + +function fakeScheduler() { + let cb: (() => void) | undefined; + return { + setInterval: (callback: () => void) => { + cb = callback; + return 1; + }, + clearInterval: () => { + cb = undefined; + }, + tick: () => cb?.(), + get armed() { + return cb !== undefined; + }, + }; +} + +const metric = (over: Record = {}) => ({ + pid: 10, + type: 'Browser', + cpu: { percentCPUUsage: 3.5 }, + memory: { workingSetSize: 3 * 1024, peakWorkingSetSize: 5 * 1024 }, + ...over, +}); + +function setup(getAppMetrics: () => unknown) { + const scheduler = fakeScheduler(); + const onError = vi.fn(); + const tracker = new ElectronProcessTracker({ app: { getAppMetrics }, scheduler }, onError); + const emitted: Array<{ name: string; value: unknown; hold: boolean | undefined }> = []; + const sink: TraceSink = { + emit: (name, value, _display, options) => emitted.push({ name, value, hold: options?.hold }), + }; + const producers = createElectronSystemTraceProducers(tracker); + return { tracker, scheduler, onError, emitted, sink, producers }; +} + +describe('createElectronSystemTraceProducers', () => { + it('builds exactly the app_metrics producer', () => { + const { producers, tracker } = setup(() => []); + expect(producers.map((p) => p.name)).toEqual(['electron-app-metrics']); + tracker.reset(); + }); + + it('does not touch Electron until started, then arms the tracker stage (priming read, no start sample)', () => { + const getAppMetrics = vi.fn(() => [metric()]); + const { producers, scheduler, emitted, sink, tracker } = setup(getAppMetrics); + expect(getAppMetrics).not.toHaveBeenCalled(); + producers[0]?.start(sink); + expect(getAppMetrics).toHaveBeenCalledTimes(1); + expect(scheduler.armed).toBe(true); + expect(emitted).toEqual([]); + producers[0]?.stop(); + tracker.reset(); + }); + + it('emits ONE app_metrics value per tick: integer MB, snake_case, polled (never held), absent fields omitted', () => { + const { producers, scheduler, emitted, sink, tracker } = setup(() => [ + metric(), + metric({ + pid: 11, + type: 'GPU', + cpu: undefined, + memory: { workingSetSize: 2048 * 1024 + 512, privateBytes: 1024 }, + }), + ]); + producers[0]?.start(sink); + scheduler.tick(); + expect(emitted).toStrictEqual([ + { + name: 'app_metrics', + hold: false, + value: { + processes: [ + { + type: 'Browser', + pid: 10, + cpu_percent: 3.5, + working_set_mb: 3, + peak_working_set_mb: 5, + }, + { type: 'GPU', pid: 11, working_set_mb: 2048, private_mb: 1 }, + ], + }, + }, + ]); + producers[0]?.stop(); + tracker.reset(); + }); + + it('rounds cpu_percent to at most 2 decimals (and keeps a true 0)', () => { + const { producers, scheduler, emitted, sink, tracker } = setup(() => [ + metric({ cpu: { percentCPUUsage: 12.3456 } }), + metric({ pid: 2, cpu: { percentCPUUsage: 0 } }), + metric({ pid: 3, cpu: { percentCPUUsage: 0.004 } }), + ]); + producers[0]?.start(sink); + scheduler.tick(); + const procs = (emitted[0]?.value as { processes: Array<{ cpu_percent: number }> }).processes; + expect(procs.map((p) => p.cpu_percent)).toEqual([12.35, 0, 0]); + producers[0]?.stop(); + tracker.reset(); + }); + + it('stop() releases the tracker stage (timer cleared) and a late emit writes nothing', () => { + const { producers, scheduler, emitted, sink, tracker } = setup(() => [metric()]); + producers[0]?.start(sink); + producers[0]?.stop(); + expect(scheduler.armed).toBe(false); + scheduler.tick(); + expect(emitted).toEqual([]); + tracker.reset(); + }); + + it('a getAppMetrics that throws yields no trace and reports through the tracker (other producers unaffected)', () => { + const boom = new Error('boom'); + let throwing = false; + const { producers, scheduler, emitted, sink, onError, tracker } = setup(() => { + if (throwing) throw boom; + return [metric()]; + }); + producers[0]?.start(sink); + throwing = true; + scheduler.tick(); + expect(emitted).toEqual([]); + expect(onError).toHaveBeenCalledWith(boom); + throwing = false; + scheduler.tick(); + expect(emitted).toHaveLength(1); + producers[0]?.stop(); + tracker.reset(); + }); + + it('can be restarted after stop (the TraceProducer contract)', () => { + const { producers, scheduler, emitted, sink, tracker } = setup(() => [metric()]); + producers[0]?.start(sink); + producers[0]?.stop(); + producers[0]?.start(sink); + scheduler.tick(); + expect(emitted).toHaveLength(1); + producers[0]?.stop(); + tracker.reset(); + }); +}); diff --git a/packages/electron/src/system-traces.ts b/packages/electron/src/system-traces.ts new file mode 100644 index 00000000..da421d45 --- /dev/null +++ b/packages/electron/src/system-traces.ts @@ -0,0 +1,69 @@ +import { type TraceProducer, TraceProducerBase } from '@bugsee/capture'; +import { bytesToMegabytes } from '@bugsee/protocol'; +import type { AppProcessMetric, ElectronProcessTracker } from '@bugsee/trackers/electron'; + +// Electron-main `traces.system` producers. COMPOSITION only: `launchMain` appends these to the node producer set (the +// node set keeps `process_memory_*`/`cpu_*`/`event_loop_*` for the process that owns the session; nothing here emits a +// name the node set does), and every Electron read, timer and omit-never-zero rule belongs to the shared +// ElectronProcessTracker (`@bugsee/trackers/electron`). A producer only subscribes to a tracker stage in `onStart` and +// releases it in `onStop`, so one that is never started costs nothing and a throwing `getAppMetrics` is the tracker's +// to report (it drops that tick only, never another producer's values). +// +// WIRE SHAPE (JS-specific name; Android has no per-process-type trace and the viewer table has no entry for it, so the +// value is an OPEN object the viewer renders as detail, like `storage_estimate`/`connection`): +// +// app_metrics = { processes: [{ type, pid, cpu_percent?, working_set_mb?, peak_working_set_mb?, private_mb? }] } +// +// `type` is Electron's process type verbatim (`Browser`, `Tab`, `GPU`, `Utility`, …). Sizes are integer binary MB +// (`bytesToMegabytes`, like `disk_mem_*`/`storage_estimate`; Electron reports KiB). `cpu_percent` is Electron's +// `percentCPUUsage`: the share of the WHOLE machine (Electron divides by the processor count), 0-100, since the +// previous read, rounded to at most 2 decimals. A key is omitted when Electron did not supply it, and `cpu_percent` is +// also omitted for a process's first sighting (Chromium reports 0 on the first CPU call per process; see the tracker). +// The viewer's support for this trace (Q5) is UNCONFIRMED; flat per-type totals are the alternative shape. +// Emitted every tick and NOT held: a failing read leaves a gap rather than a frozen line. + +/** At most two decimals: Electron's float noise is not information. */ +const round2 = (value: number): number => Math.round(value * 100) / 100; + +const mb = (bytes: number | undefined): number | undefined => + bytes === undefined ? undefined : bytesToMegabytes(bytes); + +function wireProcess(p: AppProcessMetric): Record { + const workingSet = mb(p.workingSetBytes); + const peak = mb(p.peakWorkingSetBytes); + const priv = mb(p.privateBytes); + return { + type: p.type, + pid: p.pid, + ...(p.cpuPct !== undefined ? { cpu_percent: round2(p.cpuPct) } : {}), + ...(workingSet !== undefined ? { working_set_mb: workingSet } : {}), + ...(peak !== undefined ? { peak_working_set_mb: peak } : {}), + ...(priv !== undefined ? { private_mb: priv } : {}), + }; +} + +class AppMetricsProducer extends TraceProducerBase { + readonly name = 'electron-app-metrics'; + #off: (() => void) | undefined; + constructor(private readonly tracker: ElectronProcessTracker) { + super(); + } + // Subscribing arms the tracker's stage (a priming read, then its own timer): there is NO start sample, because the + // first CPU window has not elapsed. + protected onStart(): void { + this.#off = this.tracker.on('appMetrics', (m) => + this.emit('app_metrics', { processes: m.processes.map(wireProcess) }), + ); + } + protected override onStop(): void { + this.#off?.(); + this.#off = undefined; + } +} + +/** The Electron producers, each subscribed to ONE stage of the shared tracker. */ +export function createElectronSystemTraceProducers( + tracker: ElectronProcessTracker, +): TraceProducer[] { + return [new AppMetricsProducer(tracker)]; +} diff --git a/packages/node/src/launch.test.ts b/packages/node/src/launch.test.ts index 64a1316d..f502c888 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -558,6 +558,126 @@ describe('launch', () => { expect(events?.map((e) => (e.data as { name: string }).name)).toContain('process_started'); }); + describe('wrapSystemEventsSource (platform extension seam)', () => { + type Src = import('@bugsee/capture').SystemEventSource; + // A pass-through mux that also emits one extra event of its own; counts how often it is subscribed. + const makeMux = (inner: Src, extra?: string) => { + const listeners = new Set<(e: { name: string }) => void>(); + const calls = { on: 0, off: 0, offInner: undefined as (() => void) | undefined }; + const mux = { + on: (name: 'event', l: (e: { name: string }) => void) => { + calls.on++; + listeners.add(l); + calls.offInner = inner.on(name, (e) => l(e)); + if (extra !== undefined) l({ name: extra }); + return () => { + calls.off++; + listeners.delete(l); + calls.offInner?.(); + }; + }, + } as unknown as Src; + return { mux, calls, listeners }; + }; + + it('lets the platform wrap the node events source; the provider consumes the wrapper', async () => { + const store = memStore(); + let seenInner: Src | undefined; + let made: ReturnType | undefined; + launchTracked( + 'tok', + baseOptions({ + captureStore: store, + wrapSystemEventsSource: (inner) => { + seenInner = inner; + made = makeMux(inner, 'platform_event'); + return made.mux; + }, + }), + ); + const names = (await drain(store, 'events.system'))?.map( + (e) => (e.data as { name: string }).name, + ); + expect(seenInner).toBeDefined(); + expect(made?.calls.on).toBe(1); + expect(names).toContain('platform_event'); + expect(names?.filter((n) => n === 'process_started')).toHaveLength(1); // the node source still runs, once + }); + + it('captureSystemEvents:false: the wrapper is built but NEVER subscribed (no extra node handlers either)', async () => { + const counts = (fp: ReturnType) => + ['SIGTERM', 'SIGINT', 'warning', 'beforeExit', 'exit'].map((e) => fp.count(e)); + const plain = fakeProcess(); + const plainClient = launchTracked( + 'tok', + baseOptions({ process: plain.proc, captureSystemEvents: false }), + ); + const baseline = counts(plain); // read while live: stop() removes the handlers again + await plainClient.stop(); + delete (globalThis as { __BUGSEE__?: unknown }).__BUGSEE__; + + const fp = fakeProcess(); + let made: ReturnType | undefined; + launchTracked( + 'tok', + baseOptions({ + process: fp.proc, + captureSystemEvents: false, + wrapSystemEventsSource: (inner) => { + made = makeMux(inner, 'platform_event'); + return made.mux; + }, + }), + ); + expect(made).toBeDefined(); + expect(made?.calls.on).toBe(0); + // identical to the launch without a wrapper: the node source's handlers were never installed + expect(counts(fp)).toEqual(baseline); + // and enabling events DOES add them (the baseline above is not vacuous) + delete (globalThis as { __BUGSEE__?: unknown }).__BUGSEE__; + const on = fakeProcess(); + launchTracked('tok2', baseOptions({ process: on.proc, wrapSystemEventsSource: (i) => i })); + expect(on.count('warning')).toBe((counts(fp)[2] ?? 0) + 1); + }); + + it('client.stop() releases the wrapper subscription', async () => { + let made: ReturnType | undefined; + const client = launchTracked( + 'tok', + baseOptions({ + wrapSystemEventsSource: (inner) => { + made = makeMux(inner); + return made.mux; + }, + }), + ); + expect(made?.calls.off).toBe(0); + await client.stop(); + expect(made?.calls.off).toBe(1); + }); + + it('a throwing wrap factory is reported and the plain node source is used', async () => { + const store = memStore(); + const boom = new Error('wrap'); + const onError = vi.fn(); + launchTracked( + 'tok', + baseOptions({ + captureStore: store, + onError, + wrapSystemEventsSource: () => { + throw boom; + }, + }), + ); + expect(onError).toHaveBeenCalledWith(boom); + const names = (await drain(store, 'events.system'))?.map( + (e) => (e.data as { name: string }).name, + ); + expect(names).toContain('process_started'); + }); + }); + it('takes an initial system-traces sample from the injected sampler', async () => { const store = memStore(); launchTracked('tok', baseOptions({ captureStore: store })); diff --git a/packages/node/src/launch.ts b/packages/node/src/launch.ts index 4eefa93b..12e34b37 100644 --- a/packages/node/src/launch.ts +++ b/packages/node/src/launch.ts @@ -9,6 +9,7 @@ import { deriveRefreshMs, installNetworkCapture, type NetworkCapture, + type SystemEventSource, type TraceProducer, type TraceSample, } from '@bugsee/capture'; @@ -80,7 +81,7 @@ import { } from '@bugsee/node-utils'; import type { ActiveSpanStore } from '@bugsee/performance'; import { BugseeOption, DEFAULT_FILENAMES, type EnvironmentEnvelope } from '@bugsee/protocol'; -import { reportOncePerMessage } from '@bugsee/util'; +import { reportGuarded, reportOncePerMessage } from '@bugsee/util'; import { createRequestScopedActiveSpanStore } from './active-span-store'; import { createNodeAppIdentitySource } from './app-identity-source'; import { type CpuProfiler, createCpuProfiler } from './cpu-profiler'; @@ -285,6 +286,17 @@ export interface BugseeLaunchOptions { captureDiskSpace?: boolean; /** Test seam: replaces `fs.promises.statfs` for `captureDiskSpace`. */ diskStatfs?: StatFs; + /** + * Platform-extension seam (advanced; `@bugsee/electron` uses it). Called ONCE at launch with the node + * `events.system` source; the SOURCE it returns is what the events provider subscribes to, so a platform can mux its + * own events (e.g. Electron's `child-process-gone`) into the one `events.system` provider (a second provider with + * the same name is rejected). The wrapper MUST attach lazily — in its own `on()`/activation, never when built — and + * release on its last unsubscribe: it is only subscribed while `captureSystemEvents` is on, and unsubscribed on + * `client.stop()`; subscribing to `inner` at construction would install the node source's signal handlers even with + * system events off. It must not re-emit `process_started` (the inner source already does). A throwing factory is + * reported through `onError` and the plain node source is used. + */ + wrapSystemEventsSource?: (inner: SystemEventSource) => SystemEventSource; /** Detect uncaught exceptions + unhandled rejections. Default true. */ detectCrashes?: boolean; /** Report outbound HTTP SERVER errors (500-599) as `error` reports, once per session per (method, templated URL, status); 4xx, transport failures and aborts are not reported (mobile parity). Default false. */ @@ -975,7 +987,16 @@ function buildLaunch(appToken: string, options: BugseeLaunchOptions = {}): Launc ...(options.scheduler !== undefined ? { scheduler: options.scheduler } : {}), }), ); - client.addCaptureProvider(createSystemEventsProvider(createNodeSystemEventsSource(proc))); + const nodeEventsSource = createNodeSystemEventsSource(proc); + let eventsSource: SystemEventSource = nodeEventsSource; + if (options.wrapSystemEventsSource !== undefined) { + try { + eventsSource = options.wrapSystemEventsSource(nodeEventsSource); + } catch (error) { + reportGuarded(options.onError, error); // a broken platform extension must not cost the node events + } + } + client.addCaptureProvider(createSystemEventsProvider(eventsSource)); // Detection providers: uncaughtException → crash, unhandledRejection → error, event-loop hang → error // (Android BugseeDetectionHang). Each is gated by its controllingOption (the coordinator skips it when diff --git a/packages/trackers/README.md b/packages/trackers/README.md index 891094a1..5b248f58 100644 --- a/packages/trackers/README.md +++ b/packages/trackers/README.md @@ -22,7 +22,7 @@ Trackers are the abstraction over system and runtime APIs. The package root is r - `@bugsee/trackers/node` (`src/node/`) - `@bugsee/trackers/electron` (`src/electron/`) -The `./browser` entry exports the `ApplicationTracker` (`applicationTrackerFor`, `resetApplicationTracker`), the `PowerTracker` (`powerTrackerFor`, `resetPowerTracker`), the `ConnectivityTracker` (`connectivityTrackerFor`, `resetConnectivityTracker`), the `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; stages `heap`, `mainThreadLag` (timer drift), `idle` (`requestIdleCallback`), `userIdle` (Idle Detection) and `uptime`, each armed only while it has listeners; the SDK never prompts, so `userIdle` runs only when the `idle-detection` permission is already granted; the SDK's `user_idle_state` trace additionally needs the browser/WebView launch option `captureUserIdle: true`, because a page's own grant is not consent to record and upload idle/locked state), the UI/display `UiTracker` (`uiTrackerFor`, `resetUiTracker`: orientation, screenSize, viewport, colorScheme, reducedMotion, displayMode, frameRate), the `StorageTracker` (`storageTrackerFor`, `resetStorageTracker`; an approximate origin quota estimate, not device free space: browsers may pad `usage`, and `quota` can roughly reveal the device's disk size, so treat it as potentially identifying), the `EnvironmentTracker` (`environmentTrackerFor`, `resetEnvironmentTracker`; language, time zone, and, only when a consumer sets `observeHints` / `queryPermissions`, environment hints and Permissions API states queried without ever prompting; the private-browsing heuristic runs when `detectPrivateMode` is set (the browser launch sets it by default; opt out with `captureEnvironmentHints: false`) and is never reported as a certainty) and `hostRead`; `./electron` is reserved in `exports` and currently exports nothing. Its API is internal and may change between releases. +The `./browser` entry exports the `ApplicationTracker` (`applicationTrackerFor`, `resetApplicationTracker`), the `PowerTracker` (`powerTrackerFor`, `resetPowerTracker`), the `ConnectivityTracker` (`connectivityTrackerFor`, `resetConnectivityTracker`), the `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; stages `heap`, `mainThreadLag` (timer drift), `idle` (`requestIdleCallback`), `userIdle` (Idle Detection) and `uptime`, each armed only while it has listeners; the SDK never prompts, so `userIdle` runs only when the `idle-detection` permission is already granted; the SDK's `user_idle_state` trace additionally needs the browser/WebView launch option `captureUserIdle: true`, because a page's own grant is not consent to record and upload idle/locked state), the UI/display `UiTracker` (`uiTrackerFor`, `resetUiTracker`: orientation, screenSize, viewport, colorScheme, reducedMotion, displayMode, frameRate), the `StorageTracker` (`storageTrackerFor`, `resetStorageTracker`; an approximate origin quota estimate, not device free space: browsers may pad `usage`, and `quota` can roughly reveal the device's disk size, so treat it as potentially identifying), the `EnvironmentTracker` (`environmentTrackerFor`, `resetEnvironmentTracker`; language, time zone, and, only when a consumer sets `observeHints` / `queryPermissions`, environment hints and Permissions API states queried without ever prompting; the private-browsing heuristic runs when `detectPrivateMode` is set (the browser launch sets it by default; opt out with `captureEnvironmentHints: false`) and is never reported as a certainty) and `hostRead`; the `./electron` entry exports the Electron main-process `ElectronProcessTracker` (`electronProcessTrackerFor`, `resetElectronProcessTracker`; stages `appMetrics`, `childProcessGone` and a once-only GPU read, with the Electron `app` injected structurally, never imported) and `mapGpuInfo`. Its API is internal and may change between releases. The `./node` entry is shared by Node, Bun and Deno and exports the process `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; a per-process singleton, keyed on the `process` object by default). Its ten stages (`memory`, `systemMemory`, `cpu`, `eventLoop`, `utilization`, `gc`, `v8Heap`, `memoryLimit`, `availableMemory`, `uptime`) are each armed only while they have listeners, behind one shared sampling timer. A stage the runtime cannot honestly measure emits nothing rather than zero (event-loop utilization on Bun/Deno is dropped by its own tell, idle and active both zero; the event-loop delay histogram on Deno, the GC observer on Bun/Deno, the V8 heap on Bun and available memory on Bun/Deno are gated by the `measures*` flags the platform packages pass in). The CPU stage has no start value: it reports from the first tick. Seams merge and are never dropped: a later launch that omits `scheduler` or `onError` keeps the previous launch's, and building a producer set already rebinds the shared tracker, so tests that inject fakes need a private `key` or `resetProcessTracker()`. It also exports the guarded runtime sources it is built from (`createGuardedEventLoopSource`, `createGuardedElu`, `createGcSource`, `createV8HeapReader`, `createMemoryLimitReader`, `createAvailableMemoryReader`). diff --git a/packages/trackers/package.json b/packages/trackers/package.json index 1d8637d0..cc0229ed 100644 --- a/packages/trackers/package.json +++ b/packages/trackers/package.json @@ -7,7 +7,7 @@ "url": "git+https://github.com/bugsee/bugsee-javascript.git", "directory": "packages/trackers" }, - "description": "Domain-tracker foundation: multi-key emitter, InterceptorBase and the per-window tracker registry, with a ./browser entry (ApplicationTracker, ConnectivityTracker, PowerTracker, ProcessTracker, StorageTracker, UiTracker, EnvironmentTracker, hostRead), a ./node entry shared by Node, Bun and Deno (ProcessTracker, StorageTracker and their guarded runtime sources) and a reserved ./electron platform entry", + "description": "Domain-tracker foundation: multi-key emitter, InterceptorBase and the per-window tracker registry, with a ./browser entry (ApplicationTracker, ConnectivityTracker, PowerTracker, ProcessTracker, StorageTracker, UiTracker, EnvironmentTracker, hostRead), a ./node entry shared by Node, Bun and Deno (ProcessTracker, StorageTracker and their guarded runtime sources) and an ./electron entry (the Electron main-process ProcessTracker: app metrics, child-process-gone and the once-only GPU info read)", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", diff --git a/packages/trackers/src/electron/gpu-info.test.ts b/packages/trackers/src/electron/gpu-info.test.ts new file mode 100644 index 00000000..397920f7 --- /dev/null +++ b/packages/trackers/src/electron/gpu-info.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, it } from 'vitest'; +import { mapGpuInfo } from './gpu-info'; + +const basic = (devices: unknown[]) => ({ gpuDevice: devices }); + +describe('mapGpuInfo', () => { + it('uses the ACTIVE device strings, wherever it is in the list', () => { + const dev = (active: boolean, name: string) => ({ + vendorId: 1, + deviceId: 2, + active, + vendorString: `${name}-vendor`, + deviceString: `${name}-device`, + }); + const expected = (name: string) => ({ vendor: `${name}-vendor`, renderer: `${name}-device` }); + expect(mapGpuInfo(basic([dev(true, 'A'), dev(false, 'B'), dev(false, 'C')]))).toEqual( + expected('A'), + ); + expect(mapGpuInfo(basic([dev(false, 'A'), dev(true, 'B'), dev(false, 'C')]))).toEqual( + expected('B'), + ); + expect(mapGpuInfo(basic([dev(false, 'A'), dev(false, 'B'), dev(true, 'C')]))).toEqual( + expected('C'), + ); + }); + + it('takes the FIRST active device, and only a literal `active: true` counts', () => { + expect( + mapGpuInfo( + basic([ + { active: true, vendorString: 'First' }, + { active: true, vendorString: 'Second' }, + ]), + ), + ).toEqual({ vendor: 'First' }); + expect( + mapGpuInfo( + basic([ + { active: 1, vendorString: 'A' }, + { active: 'yes', vendorString: 'B' }, + ]), + ), + ).toBeUndefined(); + }); + + it('uses the only device when none is flagged active, but never guesses among several', () => { + expect(mapGpuInfo(basic([{ vendorString: 'V', deviceString: 'R' }]))).toEqual({ + vendor: 'V', + renderer: 'R', + }); + expect( + mapGpuInfo( + basic([ + { vendorString: 'A', deviceString: 'a' }, + { vendorString: 'B', deviceString: 'b' }, + ]), + ), + ).toBeUndefined(); + }); + + it('omits a field whose string is missing; never invents a vendor from a numeric id', () => { + expect(mapGpuInfo(basic([{ active: true, vendorId: 4318, vendorString: 'NVIDIA' }]))).toEqual({ + vendor: 'NVIDIA', + }); + expect(mapGpuInfo(basic([{ active: true, deviceString: 'RTX' }]))).toEqual({ renderer: 'RTX' }); + expect(mapGpuInfo(basic([{ active: true, vendorId: 4318, deviceId: 7 }]))).toBeUndefined(); + expect( + mapGpuInfo(basic([{ active: true, vendorString: ' ', deviceString: 5 }])), + ).toBeUndefined(); + }); + + it('fills vendor/renderer/gl_version/gl_extensions from auxAttributes (trimmed)', () => { + expect( + mapGpuInfo({ + gpuDevice: [ + { vendorId: 4318, deviceId: 7, active: true, vendorString: '', deviceString: '' }, + ], + auxAttributes: { + glVendor: ' NVIDIA Corporation ', + glRenderer: 'RTX 4090/PCIe', + glVersion: 'OpenGL ES 3.0', + glExtensions: 'GL_A GL_B', + }, + }), + ).toEqual({ + vendor: 'NVIDIA Corporation', + renderer: 'RTX 4090/PCIe', + gl_version: 'OpenGL ES 3.0', + gl_extensions: 'GL_A GL_B', + }); + }); + + it('works from auxAttributes alone (no gpuDevice), and device strings win over aux per field', () => { + expect(mapGpuInfo({ auxAttributes: { glRenderer: 'R' } })).toEqual({ renderer: 'R' }); + expect( + mapGpuInfo({ + gpuDevice: [{ active: true, vendorString: 'DevVendor' }], + auxAttributes: { glVendor: 'AuxVendor', glRenderer: 'AuxRenderer' }, + }), + ).toEqual({ vendor: 'DevVendor', renderer: 'AuxRenderer' }); + }); + + it('drops blank / non-string aux values and ignores a non-object aux; ids never become names', () => { + expect( + mapGpuInfo({ + gpuDevice: [{ active: true, vendorId: 4318, deviceId: 1 }], + auxAttributes: { glVendor: ' ', glRenderer: 5, glVersion: null, glExtensions: ['A'] }, + }), + ).toBeUndefined(); + expect(mapGpuInfo({ gpuDevice: [], auxAttributes: 'x' })).toBeUndefined(); + expect(mapGpuInfo({ gpuDevice: [], auxAttributes: null })).toBeUndefined(); + }); + + it.each([ + ['undefined', undefined], + ['null', null], + ['a string', 'gpu'], + ['no gpuDevice', {}], + ['a non-array gpuDevice', { gpuDevice: 'x' }], + ['an empty list', { gpuDevice: [] }], + ['non-object devices', { gpuDevice: [1, null, 'x'] }], + ])('returns undefined for %s', (_n, value) => { + expect(mapGpuInfo(value)).toBeUndefined(); + }); +}); diff --git a/packages/trackers/src/electron/gpu-info.ts b/packages/trackers/src/electron/gpu-info.ts new file mode 100644 index 00000000..0ba28d4d --- /dev/null +++ b/packages/trackers/src/electron/gpu-info.ts @@ -0,0 +1,53 @@ +// Electron GPU description -> a neutral `{vendor?, renderer?, gl_version?, gl_extensions?}` block (the same +// field names `environment.hardware.gpu` carries; `@bugsee/node` types that as `HardwareGpu`, which this block is +// structurally assignable to; this package does not depend on it). +// +// The shapes of `app.getGPUInfo` are UNVERIFIED against a real Electron (see mapGpuInfo). + +/** The mapped GPU description. Every field is optional and only present when Electron supplied a usable string. */ +export interface ElectronGpu { + vendor?: string; + renderer?: string; + gl_version?: string; + gl_extensions?: string; +} + +const nonEmpty = (value: unknown): string | undefined => + typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined; + +/** + * Maps Electron's GPU info to the `hardware.gpu` block, defensively. The shapes are UNVERIFIED against a real + * Electron: `'basic'` is documented as `{ gpuDevice: [{ vendorId, deviceId, active, vendorString?, + * deviceString?, … }], auxAttributes? }` and often carries only the numeric ids; `'complete'` is heavier and + * is expected to carry `auxAttributes.glVendor/glRenderer/glVersion/glExtensions`. + * + * The ACTIVE device is used (or the only device when exactly one is listed — never a guess among several): + * `vendorString` -> `vendor`, `deviceString` -> `renderer`. `auxAttributes` (when present) fills what the + * device left empty: `glVendor` -> `vendor`, `glRenderer` -> `renderer`, `glVersion` -> `gl_version`, + * `glExtensions` -> `gl_extensions` (a string). Values are trimmed and empty/whitespace-only ones dropped; a + * numeric id is NEVER turned into a name. Nothing usable -> `undefined`. + */ +export function mapGpuInfo(info: unknown): ElectronGpu | undefined { + if (typeof info !== 'object' || info === null) return undefined; + const { gpuDevice, auxAttributes } = info as { gpuDevice?: unknown; auxAttributes?: unknown }; + const objects = Array.isArray(gpuDevice) + ? gpuDevice.filter((d): d is Record => typeof d === 'object' && d !== null) + : []; + const device = + objects.find((d) => d.active === true) ?? (objects.length === 1 ? objects[0] : undefined); + const aux = + typeof auxAttributes === 'object' && auxAttributes !== null + ? (auxAttributes as Record) + : {}; + const vendor = nonEmpty(device?.vendorString) ?? nonEmpty(aux.glVendor); + const renderer = nonEmpty(device?.deviceString) ?? nonEmpty(aux.glRenderer); + const glVersion = nonEmpty(aux.glVersion); + const glExtensions = nonEmpty(aux.glExtensions); + const gpu: ElectronGpu = { + ...(vendor !== undefined ? { vendor } : {}), + ...(renderer !== undefined ? { renderer } : {}), + ...(glVersion !== undefined ? { gl_version: glVersion } : {}), + ...(glExtensions !== undefined ? { gl_extensions: glExtensions } : {}), + }; + return Object.keys(gpu).length > 0 ? gpu : undefined; +} diff --git a/packages/trackers/src/electron/index.test.ts b/packages/trackers/src/electron/index.test.ts new file mode 100644 index 00000000..351ede96 --- /dev/null +++ b/packages/trackers/src/electron/index.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from 'vitest'; +import * as electronEntry from './index'; + +// Kept beside the entry (not in ../index.test.ts): the portable typecheck program must never reach src/electron. +describe('@bugsee/trackers/electron public surface', () => { + it('exports the electron tracker values', () => { + expect(Object.keys(electronEntry).sort()).toEqual([ + 'ElectronProcessTracker', + 'electronProcessTrackerFor', + 'mapGpuInfo', + 'resetElectronProcessTracker', + ]); + }); +}); diff --git a/packages/trackers/src/electron/index.ts b/packages/trackers/src/electron/index.ts index 41af26a8..859d28d9 100644 --- a/packages/trackers/src/electron/index.ts +++ b/packages/trackers/src/electron/index.ts @@ -1,5 +1,17 @@ -// Reserved `@bugsee/trackers/electron` entry. Platform tracker implementations that need Electron main/renderer APIs live -// under src/electron/ and are exported from here; nothing is implemented yet, so this entry is a documented -// placeholder. Keeping the subpath in package.json `exports` now means later slices add files WITHOUT -// changing the package contract. The portable root entry must never import from this directory. -export {}; +// `@bugsee/trackers/electron` entry. Platform tracker implementations that need Electron main-process APIs live under +// src/electron/ and are exported from here. Electron is never imported: the `app` object is injected as a structural +// `ElectronAppSource`, so this entry has no dependency on `electron` or the DOM. The portable root entry must never +// import from this directory. +export { type ElectronGpu, mapGpuInfo } from './gpu-info'; +export { + type AppProcessMetric, + type ChildProcessGone, + type ElectronAppSource, + type ElectronProcessEnv, + type ElectronProcessEvents, + ElectronProcessTracker, + type ElectronProcessTrackerEnv, + electronProcessTrackerFor, + type GpuInfoType, + resetElectronProcessTracker, +} from './process-tracker'; diff --git a/packages/trackers/src/electron/process-tracker.test.ts b/packages/trackers/src/electron/process-tracker.test.ts new file mode 100644 index 00000000..90b133be --- /dev/null +++ b/packages/trackers/src/electron/process-tracker.test.ts @@ -0,0 +1,1154 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { ProcessTimers } from '../node/process-tracker'; +import { + type ElectronAppSource, + ElectronProcessTracker, + electronProcessTrackerFor, + resetElectronProcessTracker, +} from './process-tracker'; + +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 }; +} + +/** A manual scheduler: `tick()` fires the armed callback; records arm/clear. */ +function fakeScheduler() { + let cb: (() => void) | undefined; + const api = { + setInterval: vi.fn((callback: () => void, _ms: number) => { + cb = callback; + return { id: api.setInterval.mock.calls.length }; + }), + clearInterval: vi.fn(() => { + cb = undefined; + }), + tick: () => cb?.(), + get armed() { + return cb !== undefined; + }, + callback: () => cb, + }; + return api satisfies ProcessTimers & Record; +} + +const proc = (over: Record = {}) => ({ + pid: 100, + type: 'Browser', + cpu: { percentCPUUsage: 12.5, idleWakeupsPerSecond: 3 }, + memory: { workingSetSize: 2048, peakWorkingSetSize: 4096 }, + ...over, +}); + +type GoneListener = (event: unknown, details: unknown) => void; +function fakeApp(over: Partial = {}) { + const listeners: GoneListener[] = []; + const raw = { + getAppMetrics: vi.fn((): unknown => [proc()]), + on: vi.fn((_event: string, l: GoneListener): unknown => { + listeners.push(l); + return undefined; + }), + removeListener: vi.fn((_event: string, l: GoneListener): unknown => { + const i = listeners.indexOf(l); + if (i >= 0) listeners.splice(i, 1); + return undefined; + }), + }; + const app = { ...raw, ...over } as unknown as ElectronAppSource; + return { app, raw, listeners }; +} + +const created: object[] = []; +const make = ( + app: ElectronAppSource, + extra: { scheduler?: ProcessTimers; intervalMs?: number } = {}, + onError?: (e: unknown) => unknown, +) => { + const tracker = new ElectronProcessTracker({ app, ...extra }, onError); + created.push(tracker); + return tracker; +}; + +afterEach(() => { + for (const t of created.splice(0)) (t as ElectronProcessTracker).reset(); +}); + +describe('appMetrics stage', () => { + it('does nothing without a listener: no read, no timer', () => { + const { app, raw } = fakeApp(); + const sch = fakeScheduler(); + make(app, { scheduler: sch }); + expect(raw.getAppMetrics).not.toHaveBeenCalled(); + expect(sch.setInterval).not.toHaveBeenCalled(); + }); + + it('arms with ONE priming read that is NOT emitted, on the injected scheduler at the default 1 s', () => { + const { app, raw } = fakeApp(); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const seen = vi.fn(); + t.on('appMetrics', seen); + expect(raw.getAppMetrics).toHaveBeenCalledTimes(1); + expect(seen).not.toHaveBeenCalled(); + expect(sch.setInterval).toHaveBeenCalledExactlyOnceWith(expect.any(Function), 1000); + expect(t.current('appMetrics')).toBeUndefined(); // no start sample + }); + + it('honours intervalMs and emits the mapped processes on each tick (KiB -> bytes)', () => { + const { app, raw } = fakeApp(); + raw.getAppMetrics.mockReturnValue([ + proc(), + proc({ + pid: 7, + type: 'GPU', + memory: { workingSetSize: 1, peakWorkingSetSize: 2, privateBytes: 3 }, + }), + ]); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch, intervalMs: 250 }); + const seen = vi.fn(); + t.on('appMetrics', seen); + expect(sch.setInterval).toHaveBeenCalledWith(expect.any(Function), 250); + sch.tick(); + expect(seen).toHaveBeenCalledExactlyOnceWith({ + processes: [ + { + type: 'Browser', + pid: 100, + cpuPct: 12.5, + workingSetBytes: 2048 * 1024, + peakWorkingSetBytes: 4096 * 1024, + }, + { + type: 'GPU', + pid: 7, + cpuPct: 12.5, + workingSetBytes: 1024, + peakWorkingSetBytes: 2048, + privateBytes: 3072, + }, + ], + }); + }); + + it('omits every field Electron did not supply (never zero), keeping a true 0', () => { + const { app, raw } = fakeApp(); + raw.getAppMetrics.mockReturnValue([ + { pid: 1, type: 'Tab', cpu: { percentCPUUsage: 0 }, memory: {} }, + { pid: 2, type: 'Utility', memory: { workingSetSize: 5 } }, + { + pid: 3, + type: 'Zygote', + cpu: { percentCPUUsage: Number.NaN }, + memory: { workingSetSize: -1 }, + }, + { pid: 4, type: 'GPU', cpu: { percentCPUUsage: '5' }, memory: { peakWorkingSetSize: 9 } }, + ]); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const seen = vi.fn(); + t.on('appMetrics', seen); + sch.tick(); + expect(seen).toHaveBeenCalledExactlyOnceWith({ + processes: [ + { type: 'Tab', pid: 1, cpuPct: 0 }, + { type: 'Utility', pid: 2, workingSetBytes: 5120 }, + { type: 'GPU', pid: 4, peakWorkingSetBytes: 9216 }, + ], + }); + }); + + it.each([ + ['not an array', { pid: 1 }], + ['an empty list', []], + ['only non-objects', [1, null, 'x']], + [ + 'entries without a usable type/pid', + [ + { pid: 1 }, + { type: '', pid: 1, cpu: { percentCPUUsage: 1 } }, + { type: 'Tab', pid: 'x', cpu: { percentCPUUsage: 1 } }, + { type: 'Tab', pid: Number.POSITIVE_INFINITY, cpu: { percentCPUUsage: 1 } }, + ], + ], + [ + 'only infinite readings', + [ + { + pid: 1, + type: 'Tab', + cpu: { percentCPUUsage: Number.POSITIVE_INFINITY }, + memory: { workingSetSize: Number.POSITIVE_INFINITY }, + }, + ], + ], + [ + 'entries with nothing measurable', + [ + { pid: 1, type: 'Tab' }, + { pid: 2, type: 'Tab', cpu: null, memory: null }, + ], + ], + ])('emits nothing for %s (and reports nothing)', (_n, value) => { + const { app, raw } = fakeApp(); + raw.getAppMetrics.mockReturnValue(value); + const onError = vi.fn(); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }, onError); + const seen = vi.fn(); + t.on('appMetrics', seen); + sch.tick(); + expect(seen).not.toHaveBeenCalled(); + expect(t.current('appMetrics')).toBeUndefined(); + expect(onError).not.toHaveBeenCalled(); + }); + + describe("cpu is omitted on a process's FIRST sighting (Chromium reports 0 on the first call per process)", () => { + it('a process that appears after arming has no cpuPct on its first tick, and has one on the next', () => { + const { app, raw } = fakeApp(); + raw.getAppMetrics.mockReturnValue([proc()]); // priming read: only pid 100 exists + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const seen = vi.fn(); + t.on('appMetrics', seen); + raw.getAppMetrics.mockReturnValue([ + proc(), + proc({ pid: 200, type: 'Tab', cpu: { percentCPUUsage: 0 } }), + ]); + sch.tick(); + expect(seen.mock.calls[0]?.[0].processes).toEqual([ + expect.objectContaining({ pid: 100, cpuPct: 12.5 }), + { type: 'Tab', pid: 200, workingSetBytes: 2048 * 1024, peakWorkingSetBytes: 4096 * 1024 }, + ]); + expect(seen.mock.calls[0]?.[0].processes[1]).not.toHaveProperty('cpuPct'); + sch.tick(); + expect(seen.mock.calls[1]?.[0].processes[1]).toHaveProperty('cpuPct', 0); + }); + + it('a restarted process (same type, NEW pid) is a first sighting again', () => { + const { app, raw } = fakeApp(); + raw.getAppMetrics.mockReturnValue([proc({ pid: 5, type: 'GPU' })]); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const seen = vi.fn(); + t.on('appMetrics', seen); + sch.tick(); + expect(seen.mock.calls[0]?.[0].processes[0]).toHaveProperty('cpuPct'); + raw.getAppMetrics.mockReturnValue([proc({ pid: 6, type: 'GPU' })]); + sch.tick(); + expect(seen.mock.calls[1]?.[0].processes[0]).toMatchObject({ pid: 6, type: 'GPU' }); + expect(seen.mock.calls[1]?.[0].processes[0]).not.toHaveProperty('cpuPct'); + }); + + it('a process that was absent for a tick is a first sighting again when it returns', () => { + const { app, raw } = fakeApp(); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const seen = vi.fn(); + t.on('appMetrics', seen); + raw.getAppMetrics.mockReturnValue([]); + sch.tick(); + raw.getAppMetrics.mockReturnValue([proc()]); + sch.tick(); + expect(seen.mock.calls[0]?.[0].processes[0]).not.toHaveProperty('cpuPct'); + }); + + it('a process only a cpu reading would describe is dropped on its first sighting', () => { + const { app, raw } = fakeApp(); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const seen = vi.fn(); + t.on('appMetrics', seen); + raw.getAppMetrics.mockReturnValue([{ pid: 9, type: 'Tab', cpu: { percentCPUUsage: 0 } }]); + sch.tick(); + expect(seen).not.toHaveBeenCalled(); + }); + + it('re-arming re-primes: the sightings of the previous run do not carry over', () => { + const { app } = fakeApp(); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const off = t.on('appMetrics', vi.fn()); + sch.tick(); + off(); + const seen = vi.fn(); + t.on('appMetrics', seen); // priming read sees pid 100 again + sch.tick(); + expect(seen.mock.calls[0]?.[0].processes[0]).toHaveProperty('cpuPct'); + }); + + it('a priming read of a malformed list leaves no sightings', () => { + const { app, raw } = fakeApp(); + raw.getAppMetrics.mockReturnValue('nope'); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const seen = vi.fn(); + t.on('appMetrics', seen); + raw.getAppMetrics.mockReturnValue([proc()]); + sch.tick(); + expect(seen.mock.calls[0]?.[0].processes[0]).not.toHaveProperty('cpuPct'); + }); + }); + + describe('cumulativeCPUUsage (newer Electron sends cpu 0 "for compatibility" when it cannot read CPU)', () => { + const withCum = (pid: number, cumulativeCPUUsage?: unknown) => + proc({ + pid, + cpu: { + percentCPUUsage: 7, + ...(cumulativeCPUUsage !== undefined ? { cumulativeCPUUsage } : {}), + }, + }); + + it('omits cpuPct for a process lacking it when the runtime reports it for others; keeps it where present', () => { + const { app, raw } = fakeApp(); + raw.getAppMetrics.mockReturnValue([withCum(1, 3), withCum(2)]); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const seen = vi.fn(); + t.on('appMetrics', seen); + sch.tick(); + const [a, b] = seen.mock.calls[0]?.[0].processes ?? []; + expect(a).toHaveProperty('cpuPct', 7); + expect(b).not.toHaveProperty('cpuPct'); + }); + + it('does not apply the rule on an Electron that reports no cumulativeCPUUsage at all', () => { + const { app, raw } = fakeApp(); + raw.getAppMetrics.mockReturnValue([withCum(1), withCum(2)]); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const seen = vi.fn(); + t.on('appMetrics', seen); + sch.tick(); + expect(seen.mock.calls[0]?.[0].processes.map((p: { cpuPct?: number }) => p.cpuPct)).toEqual([ + 7, 7, + ]); + }); + + it('a non-numeric cumulativeCPUUsage counts as missing', () => { + const { app, raw } = fakeApp(); + raw.getAppMetrics.mockReturnValue([withCum(1, 3), withCum(2, 'x'), withCum(3, Number.NaN)]); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const seen = vi.fn(); + t.on('appMetrics', seen); + sch.tick(); + expect(seen.mock.calls[0]?.[0].processes.map((p: { cpuPct?: number }) => p.cpuPct)).toEqual([ + 7, + undefined, + undefined, + ]); + }); + }); + + it('a throwing getAppMetrics drops only that tick: reported, the stage stays armed and recovers', () => { + const { app, raw } = fakeApp(); + const sch = fakeScheduler(); + const onError = vi.fn(); + const t = make(app, { scheduler: sch }, onError); + const seen = vi.fn(); + t.on('appMetrics', seen); + const boom = new Error('metrics'); + raw.getAppMetrics.mockImplementationOnce(() => { + throw boom; + }); + sch.tick(); + expect(onError).toHaveBeenCalledExactlyOnceWith(boom); + expect(seen).not.toHaveBeenCalled(); + sch.tick(); + expect(seen).toHaveBeenCalledTimes(1); + }); + + it('a PERSISTENT getAppMetrics failure is reported once per failure streak, not once per tick', () => { + const { app, raw } = fakeApp(); + const sch = fakeScheduler(); + const onError = vi.fn(); + const t = make(app, { scheduler: sch }, onError); + const seen = vi.fn(); + t.on('appMetrics', seen); + const boom = new Error('persistent'); + raw.getAppMetrics.mockImplementation(() => { + throw boom; + }); + for (let i = 0; i < 5; i++) sch.tick(); + expect(onError).toHaveBeenCalledExactlyOnceWith(boom); + // a successful read ends the streak: the NEXT failure is reported again, once + raw.getAppMetrics.mockReturnValue([proc()]); + sch.tick(); + expect(seen).toHaveBeenCalledTimes(1); + const boom2 = new Error('again'); + raw.getAppMetrics.mockImplementation(() => { + throw boom2; + }); + sch.tick(); + sch.tick(); + expect(onError).toHaveBeenCalledTimes(2); + expect(onError).toHaveBeenLastCalledWith(boom2); + }); + + it('a failure streak ends on re-arm, so a new run reports its first failure again', () => { + const { app, raw } = fakeApp(); + const sch = fakeScheduler(); + const onError = vi.fn(); + const t = make(app, { scheduler: sch }, onError); + const off = t.on('appMetrics', vi.fn()); + const fail = () => + raw.getAppMetrics.mockImplementation(() => { + throw new Error('x'); + }); + fail(); + sch.tick(); + sch.tick(); + expect(onError).toHaveBeenCalledTimes(1); + off(); + raw.getAppMetrics.mockReturnValue([proc()]); // priming succeeds + t.on('appMetrics', vi.fn()); + fail(); + sch.tick(); + sch.tick(); + expect(onError).toHaveBeenCalledTimes(2); + }); + + it('reset() ends a failure streak too', () => { + const { app, raw } = fakeApp(); + const sch = fakeScheduler(); + const onError = vi.fn(); + const t = make(app, { scheduler: sch }, onError); + t.on('appMetrics', vi.fn()); + raw.getAppMetrics.mockImplementation(() => { + throw new Error('x'); + }); + sch.tick(); + t.reset(); + raw.getAppMetrics.mockReturnValueOnce([proc()]); // priming of the next run + t.on('appMetrics', vi.fn()); + sch.tick(); + expect(onError).toHaveBeenCalledTimes(2); + }); + + it('a throwing PRIMING read is reported and leaves the stage unarmed (no timer), retried on the next listener change', () => { + const { app, raw } = fakeApp(); + const sch = fakeScheduler(); + const onError = vi.fn(); + const t = make(app, { scheduler: sch }, onError); + const boom = new Error('prime'); + raw.getAppMetrics.mockImplementationOnce(() => { + throw boom; + }); + t.on('appMetrics', vi.fn()); + expect(onError).toHaveBeenCalledExactlyOnceWith(boom); + expect(sch.setInterval).not.toHaveBeenCalled(); + t.on('appMetrics', vi.fn()); // another listener: retried + expect(sch.setInterval).toHaveBeenCalledTimes(1); + }); + + it('a scheduler that cannot arm is reported and leaves the stage unarmed; later ticks of nothing never emit', () => { + const { app } = fakeApp(); + const boom = new Error('no timer'); + const sch = fakeScheduler(); + sch.setInterval.mockImplementationOnce(() => { + throw boom; + }); + const onError = vi.fn(); + const t = make(app, { scheduler: sch }, onError); + t.on('appMetrics', vi.fn()); + expect(onError).toHaveBeenCalledExactlyOnceWith(boom); + expect(t.current('appMetrics')).toBeUndefined(); + t.on('appMetrics', vi.fn()); // retried, now arms + expect(sch.armed).toBe(true); + }); + + it.each([ + ['no app', undefined], + ['an app without getAppMetrics', {}], + ])('%s: the stage is absent, no timer, no error', (_n, app) => { + const sch = fakeScheduler(); + const onError = vi.fn(); + const t = new ElectronProcessTracker( + { ...(app !== undefined ? { app } : {}), scheduler: sch }, + onError, + ); + created.push(t); + t.on('appMetrics', vi.fn()); + expect(sch.setInterval).not.toHaveBeenCalled(); + expect(onError).not.toHaveBeenCalled(); + }); + + it('the last unsubscribe clears the timer and drops the sample; a new subscription re-primes (fresh window)', () => { + const { app, raw } = fakeApp(); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const off = t.on('appMetrics', vi.fn()); + sch.tick(); + expect(t.current('appMetrics')).toBeDefined(); + off(); + expect(sch.clearInterval).toHaveBeenCalledTimes(1); + expect(sch.armed).toBe(false); + expect(t.current('appMetrics')).toBeUndefined(); + const reads = raw.getAppMetrics.mock.calls.length; + const seen = vi.fn(); + t.on('appMetrics', seen); + expect(raw.getAppMetrics.mock.calls.length).toBe(reads + 1); // priming read again + expect(seen).not.toHaveBeenCalled(); + expect(t.current('appMetrics')).toBeUndefined(); + }); + + it('a second listener shares the one timer and one priming read; removing one keeps it armed', () => { + const { app, raw } = fakeApp(); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const off1 = t.on('appMetrics', vi.fn()); + t.on('appMetrics', vi.fn()); + expect(sch.setInterval).toHaveBeenCalledTimes(1); + expect(raw.getAppMetrics).toHaveBeenCalledTimes(1); + off1(); + expect(sch.clearInterval).not.toHaveBeenCalled(); + }); + + it('an onAny listener arms the stage too', () => { + const { app } = fakeApp(); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const off = t.onAny(vi.fn()); + expect(sch.armed).toBe(true); + off(); + expect(sch.armed).toBe(false); + }); + + it('current() is the last emitted sample, as a COPY; emitted payloads are copies too', () => { + const { app } = fakeApp(); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + let payload: { processes: { cpuPct?: number }[] } | undefined; + t.on('appMetrics', (p) => { + payload = p; + (p.processes[0] as { cpuPct?: number }).cpuPct = 99; + }); + sch.tick(); + expect(payload).toBeDefined(); + const cur = t.current('appMetrics'); + expect(cur?.processes[0]?.cpuPct).toBe(12.5); + (cur?.processes[0] as { cpuPct?: number }).cpuPct = 1; + expect(t.current('appMetrics')?.processes[0]?.cpuPct).toBe(12.5); + }); + + it('a callback of a torn-down run can never emit (even when its clear failed)', () => { + const { app } = fakeApp(); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + const seen = vi.fn(); + const off = t.on('appMetrics', seen); + const stale = sch.callback() as () => void; + sch.clearInterval.mockImplementationOnce(() => { + throw new Error('clear failed'); + }); + const onError = vi.fn(); + t.rebind({}, onError); + off(); + expect(onError).toHaveBeenCalledTimes(1); + stale(); + expect(seen).not.toHaveBeenCalled(); + }); + + it('a callback of a replaced run cannot emit even while a listener is still attached', () => { + const { app } = fakeApp(); + const a = fakeScheduler(); + const b = fakeScheduler(); + const t = make(app, { scheduler: a }); + const seen = vi.fn(); + t.on('appMetrics', seen); + const stale = a.callback() as () => void; + t.rebind({ scheduler: b }); + stale(); + expect(seen).not.toHaveBeenCalled(); + b.tick(); + expect(seen).toHaveBeenCalledTimes(1); + }); + + it('a callback registered by a setInterval that then threw can never emit', () => { + const { app } = fakeApp(); + const sch = fakeScheduler(); + let registered: (() => void) | undefined; + sch.setInterval.mockImplementationOnce((cb: () => void) => { + registered = cb; + throw new Error('late failure'); + }); + const t = make(app, { scheduler: sch }, () => {}); + const seen = vi.fn(); + t.on('appMetrics', seen); + registered?.(); + expect(seen).not.toHaveBeenCalled(); + }); + + it('a throwing clearInterval is reported (and does not strand teardown)', () => { + const { app } = fakeApp(); + const sch = fakeScheduler(); + sch.clearInterval.mockImplementation(() => { + throw new Error('clear'); + }); + const onError = vi.fn(); + const t = make(app, { scheduler: sch }, onError); + const off = t.on('appMetrics', vi.fn()); + off(); + expect(onError).toHaveBeenCalledTimes(1); + expect(t.current('appMetrics')).toBeUndefined(); + }); + + it("uses the real (unref'd) timers by default, and stops them", () => { + vi.useFakeTimers(); + try { + const { app, raw } = fakeApp(); + const t = make(app); + const seen = vi.fn(); + const off = t.on('appMetrics', seen); + vi.advanceTimersByTime(2100); + expect(seen).toHaveBeenCalledTimes(2); + off(); + vi.advanceTimersByTime(5000); + expect(seen).toHaveBeenCalledTimes(2); + expect(raw.getAppMetrics).toHaveBeenCalledTimes(3); + } finally { + vi.useRealTimers(); + } + }); + + it('a throwing or async-rejecting reporter never escapes into the host', async () => { + const unhandled = vi.fn(); + process.on('unhandledRejection', unhandled); + try { + for (const sink of [ + () => { + throw new Error('sink'); + }, + async () => { + throw new Error('async sink'); + }, + ]) { + const { app, raw } = fakeApp(); + raw.getAppMetrics.mockImplementation(() => { + throw new Error('x'); + }); + const t = make(app, { scheduler: fakeScheduler() }, sink); + expect(() => t.on('appMetrics', vi.fn())).not.toThrow(); + } + await flush(); + await flush(); + expect(unhandled).not.toHaveBeenCalled(); + } finally { + process.off('unhandledRejection', unhandled); + } + }); + + it('a throwing subscriber cannot break the tick or another subscriber (reported)', () => { + const { app } = fakeApp(); + const sch = fakeScheduler(); + const onError = vi.fn(); + const t = make(app, { scheduler: sch }, onError); + const second = vi.fn(); + t.on('appMetrics', () => { + throw new Error('listener'); + }); + t.on('appMetrics', second); + sch.tick(); + expect(second).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledTimes(1); + }); +}); + +describe('childProcessGone stage', () => { + it('attaches NO app listener until subscribed, and removes the SAME listener when the last leaves', () => { + const { app, raw, listeners } = fakeApp(); + const t = make(app); + expect(raw.on).not.toHaveBeenCalled(); + const off1 = t.on('childProcessGone', vi.fn()); + const off2 = t.on('childProcessGone', vi.fn()); + expect(raw.on).toHaveBeenCalledExactlyOnceWith('child-process-gone', expect.any(Function)); + expect(listeners).toHaveLength(1); + off1(); + expect(listeners).toHaveLength(1); + off2(); + expect(listeners).toHaveLength(0); + expect(raw.removeListener).toHaveBeenCalledExactlyOnceWith( + 'child-process-gone', + raw.on.mock.calls[0]?.[1], + ); + }); + + it('maps details: type, reason, exitCode and a trimmed name; omits what is absent', () => { + const { app, listeners } = fakeApp(); + const t = make(app); + const seen = vi.fn(); + t.on('childProcessGone', seen); + const fire = (details: unknown) => listeners[0]?.({}, details); + fire({ + type: 'GPU', + reason: 'crashed', + exitCode: 139, + name: ' Network Service ', + serviceName: 'x', + }); + fire({ type: 'Utility', reason: 'oom' }); + fire({ type: 'Utility', reason: 'killed', exitCode: Number.NaN, name: ' ' }); + fire({ type: 'Utility', reason: 'killed', exitCode: '1', name: 5 }); + expect(seen.mock.calls.map((c) => c[0])).toEqual([ + { type: 'GPU', reason: 'crashed', exitCode: 139, name: 'Network Service' }, + { type: 'Utility', reason: 'oom' }, + { type: 'Utility', reason: 'killed' }, + { type: 'Utility', reason: 'killed' }, + ]); + }); + + it.each([ + ['undefined', undefined], + ['a string', 'gone'], + ['no type', { reason: 'crashed' }], + ['an empty type', { type: '', reason: 'crashed' }], + ['no reason', { type: 'GPU' }], + ['an empty reason', { type: 'GPU', reason: '' }], + ['non-string type/reason', { type: 1, reason: 2 }], + ])('ignores malformed details: %s', (_n, details) => { + const { app, listeners } = fakeApp(); + const t = make(app); + const seen = vi.fn(); + t.on('childProcessGone', seen); + listeners[0]?.({}, details); + expect(seen).not.toHaveBeenCalled(); + }); + + it('falls back to app.off when there is no removeListener', () => { + const off = vi.fn(); + const { app, raw } = fakeApp({ removeListener: undefined, off }); + const t = make(app); + t.on('childProcessGone', vi.fn())(); + expect(off).toHaveBeenCalledExactlyOnceWith('child-process-gone', raw.on.mock.calls[0]?.[1]); + }); + + it('does not attach at all when the listener could never be removed (or there is no on)', () => { + const noRemove = fakeApp({ removeListener: undefined }); + make(noRemove.app).on('childProcessGone', vi.fn()); + expect(noRemove.raw.on).not.toHaveBeenCalled(); + const noOn = fakeApp({ on: undefined }); + const onError = vi.fn(); + make(noOn.app, {}, onError).on('childProcessGone', vi.fn()); + expect(onError).not.toHaveBeenCalled(); + const t = new ElectronProcessTracker({}, onError); + created.push(t); + t.on('childProcessGone', vi.fn()); // no app + expect(onError).not.toHaveBeenCalled(); + }); + + it('a throwing app.on is reported and retried on the next listener change', () => { + const { app, raw, listeners } = fakeApp(); + const boom = new Error('on'); + raw.on.mockImplementationOnce(() => { + throw boom; + }); + const onError = vi.fn(); + const t = make(app, {}, onError); + t.on('childProcessGone', vi.fn()); + expect(onError).toHaveBeenCalledExactlyOnceWith(boom); + expect(listeners).toHaveLength(0); + t.on('childProcessGone', vi.fn()); + expect(listeners).toHaveLength(1); + }); + + it('a throwing removeListener is reported (and the tracker still considers itself detached)', () => { + const { app, raw } = fakeApp(); + raw.removeListener.mockImplementation(() => { + throw new Error('remove'); + }); + const onError = vi.fn(); + const t = make(app, {}, onError); + const off = t.on('childProcessGone', vi.fn()); + off(); + expect(onError).toHaveBeenCalledTimes(1); + t.on('childProcessGone', vi.fn()); + expect(raw.on).toHaveBeenCalledTimes(2); // re-attaches: it did not think it was still attached + }); +}); + +describe('gpu one-shot', () => { + const info = { gpuDevice: [{ active: true, vendorString: 'V', deviceString: 'R' }] }; + const withGpu = (getGPUInfo: (type: 'basic' | 'complete') => Promise) => + make({ getGPUInfo }, {}); + + it('is undefined until the Promise settles, then serves the mapped gpu and fires the gpu stage once', async () => { + const d = deferred(); + const getGPUInfo = vi.fn(() => d.promise); + const t = withGpu(getGPUInfo); + const seen = vi.fn(); + t.on('gpu', seen); + t.requestGpuInfo(); + expect(getGPUInfo).toHaveBeenCalledExactlyOnceWith('basic'); + expect(t.current('gpu')).toBeUndefined(); + d.resolve(info); + await flush(); + expect(t.current('gpu')).toEqual({ vendor: 'V', renderer: 'R' }); + expect(seen).toHaveBeenCalledExactlyOnceWith({ vendor: 'V', renderer: 'R' }); + }); + + it("passes the requested type to getGPUInfo (default 'basic')", () => { + const complete = vi.fn(() => new Promise(() => {})); + withGpu(complete).requestGpuInfo('complete'); + expect(complete).toHaveBeenCalledExactlyOnceWith('complete'); + }); + + it('keeps a USABLE settled value of the same type: repeat requests are no-ops while pending and after a value', async () => { + const pending = vi.fn(() => new Promise(() => {})); + const a = withGpu(pending); + a.requestGpuInfo(); + a.requestGpuInfo(); + expect(pending).toHaveBeenCalledTimes(1); + + const ok = vi.fn(async () => info); + const b = withGpu(ok); + b.requestGpuInfo(); + await flush(); + b.requestGpuInfo(); + b.requestGpuInfo('basic'); + expect(ok).toHaveBeenCalledTimes(1); + }); + + it('re-asks after a REJECTION, and after an UNUSABLE result (nothing worth keeping was settled)', async () => { + const bad = vi.fn(() => Promise.reject(new Error('x'))); + const c = make({ getGPUInfo: bad }, {}, () => {}); + c.requestGpuInfo(); + await flush(); + c.requestGpuInfo(); + expect(bad).toHaveBeenCalledTimes(2); + + const empty = vi.fn(async () => ({ gpuDevice: [{ active: true, vendorId: 1 }] })); + const d = withGpu(empty); + d.requestGpuInfo(); + await flush(); + d.requestGpuInfo(); + expect(empty).toHaveBeenCalledTimes(2); + }); + + it('re-asks when the requested type differs from the one read; the old value stays until a new usable one replaces it', async () => { + const calls: string[] = []; + let answer: unknown = { gpuDevice: [{ active: true, vendorString: 'BASIC' }] }; + const t = withGpu(async (type) => { + calls.push(type); + if (answer instanceof Error) throw answer; + return answer; + }); + t.requestGpuInfo('basic'); + await flush(); + answer = new Error('complete failed'); + t.requestGpuInfo('complete'); + await flush(); + expect(calls).toEqual(['basic', 'complete']); + expect(t.current('gpu')).toEqual({ vendor: 'BASIC' }); // a failed re-ask keeps the usable value + t.requestGpuInfo('complete'); // the failed 'complete' read is not a settled usable one + await flush(); + expect(calls).toEqual(['basic', 'complete', 'complete']); + answer = { gpuDevice: [{ active: true, vendorString: 'COMPLETE' }] }; + t.requestGpuInfo('complete'); + await flush(); + expect(t.current('gpu')).toEqual({ vendor: 'COMPLETE' }); + t.requestGpuInfo('complete'); + expect(calls).toEqual(['basic', 'complete', 'complete', 'complete']); + }); + + it('returns a copy, so a consumer cannot mutate the result', async () => { + const t = withGpu(async () => info); + t.requestGpuInfo(); + await flush(); + (t.current('gpu') as { vendor?: string }).vendor = 'hacked'; + expect(t.current('gpu')).toEqual({ vendor: 'V', renderer: 'R' }); + }); + + it('a rejection becomes omit + onError, with NO unhandledRejection and no gpu event', async () => { + const unhandled = vi.fn(); + process.on('unhandledRejection', unhandled); + try { + const boom = new Error('no acceleration'); + const onError = vi.fn(); + const t = make({ getGPUInfo: () => Promise.reject(boom) }, {}, onError); + const seen = vi.fn(); + t.on('gpu', seen); + t.requestGpuInfo(); + await flush(); + await flush(); + expect(t.current('gpu')).toBeUndefined(); + expect(onError).toHaveBeenCalledExactlyOnceWith(boom); + expect(seen).not.toHaveBeenCalled(); + expect(unhandled).not.toHaveBeenCalled(); + } finally { + process.off('unhandledRejection', unhandled); + } + }); + + it('an async onError that rejects leaves NO unhandledRejection', async () => { + const unhandled = vi.fn(); + process.on('unhandledRejection', unhandled); + try { + make({ getGPUInfo: () => Promise.reject(new Error('x')) }, {}, async () => { + throw new Error('async sink'); + }).requestGpuInfo(); + await flush(); + await flush(); + await new Promise((r) => setTimeout(r, 10)); + expect(unhandled).not.toHaveBeenCalled(); + } finally { + process.off('unhandledRejection', unhandled); + } + }); + + it('a synchronous throw is reported, not propagated, and does not block a later request', () => { + const boom = new Error('sync'); + const onError = vi.fn(); + const getGPUInfo = vi.fn(() => { + throw boom; + }); + const t = make({ getGPUInfo }, {}, onError); + expect(() => t.requestGpuInfo()).not.toThrow(); + expect(onError).toHaveBeenCalledExactlyOnceWith(boom); + expect(t.current('gpu')).toBeUndefined(); + t.cancelGpuInfo(); // nothing in flight: a no-op + t.requestGpuInfo(); + expect(getGPUInfo).toHaveBeenCalledTimes(2); + }); + + 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 t = make({ getGPUInfo: async () => hostile }, {}, onError); + t.requestGpuInfo(); + await flush(); + expect(t.current('gpu')).toBeUndefined(); + expect(onError).toHaveBeenCalledTimes(1); + }); + + it('an unusable result (nothing mappable) is omitted silently', async () => { + const onError = vi.fn(); + const t = make( + { getGPUInfo: async () => ({ gpuDevice: [{ active: true, vendorId: 1 }] }) }, + {}, + onError, + ); + const seen = vi.fn(); + t.on('gpu', seen); + t.requestGpuInfo(); + await flush(); + expect(t.current('gpu')).toBeUndefined(); + expect(seen).not.toHaveBeenCalled(); + expect(onError).not.toHaveBeenCalled(); + }); + + it('cancel: a late resolve is ignored, a late reject is not reported, and a later request starts afresh', async () => { + const first = deferred(); + const second = deferred(); + const getGPUInfo = vi + .fn() + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise); + const onError = vi.fn(); + const t = make({ getGPUInfo }, {}, onError); + t.requestGpuInfo(); + t.cancelGpuInfo(); + first.resolve({ gpuDevice: [{ active: true, vendorString: 'OLD' }] }); + await flush(); + expect(t.current('gpu')).toBeUndefined(); + t.requestGpuInfo(); + expect(getGPUInfo).toHaveBeenCalledTimes(2); + second.resolve({ gpuDevice: [{ active: true, vendorString: 'NEW' }] }); + await flush(); + expect(t.current('gpu')).toEqual({ vendor: 'NEW' }); + + const d = deferred(); + const t2 = make({ getGPUInfo: () => d.promise }, {}, onError); + t2.requestGpuInfo(); + t2.cancelGpuInfo(); + d.reject(new Error('late')); + await flush(); + expect(onError).not.toHaveBeenCalled(); + }); + + it('cancel KEEPS an already-resolved value (reports still draining must carry it)', async () => { + const t = withGpu(async () => info); + t.requestGpuInfo(); + await flush(); + t.cancelGpuInfo(); + expect(t.current('gpu')).toEqual({ vendor: 'V', renderer: 'R' }); + t.requestGpuInfo(); // same type, usable value kept: not re-asked + expect(t.current('gpu')).toEqual({ vendor: 'V', renderer: 'R' }); + }); + + it.each([ + ['no app', {}], + ['an app without getGPUInfo', { app: {} }], + ['a non-function getGPUInfo', { app: { getGPUInfo: 5 } }], + ])('%s: nothing requested, no error, and a later app can still be asked', (_n, env) => { + const onError = vi.fn(); + const t = new ElectronProcessTracker(env as never, onError); + created.push(t); + expect(() => t.requestGpuInfo()).not.toThrow(); + expect(t.current('gpu')).toBeUndefined(); + expect(onError).not.toHaveBeenCalled(); + const getGPUInfo = vi.fn(() => new Promise(() => {})); + t.rebind({ app: { getGPUInfo } }); + t.requestGpuInfo(); + expect(getGPUInfo).toHaveBeenCalledTimes(1); + }); +}); + +describe('reset', () => { + it('releases the timer, the app listener and the GPU result', async () => { + const { app, listeners } = fakeApp({ + getGPUInfo: async () => ({ gpuDevice: [{ active: true, vendorString: 'V' }] }), + }); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch }); + t.on('appMetrics', vi.fn()); + t.on('childProcessGone', vi.fn()); + t.requestGpuInfo(); + await flush(); + expect(t.current('gpu')).toBeDefined(); + t.reset(); + expect(sch.armed).toBe(false); + expect(listeners).toHaveLength(0); + expect(t.current('gpu')).toBeUndefined(); + t.requestGpuInfo(); // the latch is reopened + await flush(); + expect(t.current('gpu')).toBeDefined(); + }); + + it('a read in flight at reset can no longer write', async () => { + const d = deferred(); + const t = withGpuOnly(d.promise); + t.requestGpuInfo(); + t.reset(); + d.resolve({ gpuDevice: [{ active: true, vendorString: 'V' }] }); + await flush(); + expect(t.current('gpu')).toBeUndefined(); + }); +}); + +const withGpuOnly = (promise: Promise) => make({ getGPUInfo: () => promise }, {}); + +describe('rebind (seams merge, never drop)', () => { + it('a changed scheduler tears the armed run down on the OLD scheduler, then re-arms (and re-primes) on the new one', () => { + const { app, raw } = fakeApp(); + const a = fakeScheduler(); + const b = fakeScheduler(); + const t = make(app, { scheduler: a }); + const seen = vi.fn(); + t.on('appMetrics', seen); + a.tick(); + expect(seen).toHaveBeenCalledTimes(1); + const reads = raw.getAppMetrics.mock.calls.length; + t.rebind({ scheduler: b }); + expect(a.clearInterval).toHaveBeenCalledTimes(1); + expect(b.setInterval).toHaveBeenCalledTimes(1); + expect(raw.getAppMetrics.mock.calls.length).toBe(reads + 1); + expect(t.current('appMetrics')).toBeUndefined(); + b.tick(); + expect(seen).toHaveBeenCalledTimes(2); + }); + + it('an unchanged rebind restarts nothing; an omitted seam never clobbers an earlier one', () => { + const { app, raw } = fakeApp(); + const sch = fakeScheduler(); + const t = make(app, { scheduler: sch, intervalMs: 500 }); + t.on('appMetrics', vi.fn()); + t.rebind({ scheduler: sch, intervalMs: 500 }); + t.rebind({}); + expect(sch.setInterval).toHaveBeenCalledTimes(1); + expect(sch.clearInterval).not.toHaveBeenCalled(); + expect(raw.getAppMetrics).toHaveBeenCalledTimes(1); + // the kept intervalMs survives a rebind that changes only the scheduler + const other = fakeScheduler(); + t.rebind({ scheduler: other }); + expect(other.setInterval).toHaveBeenCalledWith(expect.any(Function), 500); + }); + + it('a changed app moves the child-process-gone listener (removed from the OLD app, attached to the new one)', () => { + const one = fakeApp(); + const two = fakeApp(); + const t = make(one.app); + t.on('childProcessGone', vi.fn()); + t.rebind({ app: two.app }); + expect(one.listeners).toHaveLength(0); + expect(one.raw.removeListener).toHaveBeenCalledTimes(1); + expect(two.listeners).toHaveLength(1); + }); + + it('the latest defined onError wins; undefined keeps it', () => { + const { app, raw } = fakeApp(); + const first = vi.fn(); + const second = vi.fn(); + const t = make(app, { scheduler: fakeScheduler() }, first); + t.rebind({}, second); + t.rebind({}); + raw.getAppMetrics.mockImplementationOnce(() => { + throw new Error('x'); + }); + t.on('appMetrics', vi.fn()); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledTimes(1); + }); +}); + +describe('electronProcessTrackerFor (registry)', () => { + it('is a singleton per app object, hands later launches their seams, and reset drops it', () => { + const { app } = fakeApp(); + const a = fakeScheduler(); + const b = fakeScheduler(); + const first = electronProcessTrackerFor({ app, scheduler: a }); + try { + expect(electronProcessTrackerFor({ app, scheduler: a })).toBe(first); + first.on('appMetrics', vi.fn()); + expect(a.armed).toBe(true); + expect(electronProcessTrackerFor({ app, scheduler: b })).toBe(first); + expect(a.armed).toBe(false); + expect(b.armed).toBe(true); + const other = fakeApp(); + const otherTracker = electronProcessTrackerFor({ app: other.app }); + expect(otherTracker).not.toBe(first); + resetElectronProcessTracker(other.app); + } finally { + resetElectronProcessTracker(app); + } + expect(b.armed).toBe(false); + expect(electronProcessTrackerFor({ app })).not.toBe(first); + resetElectronProcessTracker(app); + }); + + it('an explicit key overrides the app as the registry key, and onError reaches the shared tracker', () => { + const { app, raw } = fakeApp(); + raw.getAppMetrics.mockImplementation(() => { + throw new Error('x'); + }); + const key = {}; + const onError = vi.fn(); + const t = electronProcessTrackerFor({ app, key, scheduler: fakeScheduler() }, onError); + try { + expect(electronProcessTrackerFor({ app }, undefined)).not.toBe(t); + expect(electronProcessTrackerFor({ app, key })).toBe(t); + t.on('appMetrics', vi.fn()); + expect(onError).toHaveBeenCalledTimes(1); + } finally { + resetElectronProcessTracker(key); + resetElectronProcessTracker(app); + } + }); + + it('refuses to build an anonymous tracker (no app, no key)', () => { + expect(() => electronProcessTrackerFor({})).toThrow(TypeError); + }); +}); diff --git a/packages/trackers/src/electron/process-tracker.ts b/packages/trackers/src/electron/process-tracker.ts new file mode 100644 index 00000000..032d2c67 --- /dev/null +++ b/packages/trackers/src/electron/process-tracker.ts @@ -0,0 +1,502 @@ +import { InterceptorBase } from '../interceptor-base'; +import type { ProcessTimers } from '../node/process-tracker'; +import { createTrackerRegistry } from '../tracker-registry'; +import { type ElectronGpu, mapGpuInfo } from './gpu-info'; + +// Electron MAIN-process PROCESS tracker (domain tracker, design §15.2/§15.4 TR9; Android reference: +// BugseeTrackerProcess). It owns what Electron's `app` can say about the app's processes, as THREE independent +// stages. `electron` is never imported: the app object is INJECTED as a structural {@link ElectronAppSource}. +// +// appMetrics app.getAppMetrics() polled on one timer -> { processes: [{ type, pid, cpuPct?, workingSetBytes?, ... }] } +// childProcessGone app.on('child-process-gone') -> { type, reason, exitCode?, name? } +// gpu app.getGPUInfo(type), kept once usable -> { vendor?, renderer?, gl_version?, gl_extensions? } +// +// `render-process-gone` is deliberately NOT here: it is an INCIDENT path (a renderer that died is reported, with its +// capture and minidump, by `@bugsee/electron`'s renderer-gone handler) and shares no behaviour with these stages. +// +// PER-STAGE ACTIVATION. Nothing runs at construction. `appMetrics` arms (one unref'd timer) only while it has a +// listener; `childProcessGone` attaches its single `app` listener only while it has a listener and removes THAT +// listener when the last one leaves (a tracker with no subscriber leaves no handler on the host's `app`). `gpu` is +// not listener-driven: it is a one-shot read requested with {@link ElectronProcessTracker.requestGpuInfo} and its +// result is served through `current('gpu')` (and the `gpu` stage fires each time a usable result settles). +// +// ABSENCE IS NEVER ZERO / NO FABRICATED START SAMPLES. `percentCPUUsage` is "since the previous getAppMetrics call" +// and Chromium returns 0 on the FIRST CPU-usage call per process (Electron keeps one metrics object per child +// process), so a CPU figure exists only for a pid the PREVIOUS read already listed: arming makes one PRIMING read +// whose values are discarded (its pids are remembered), the first emission is the first tick, and a process that +// appears later (a new renderer, a restarted GPU/utility process: same type, new pid) reports no `cpuPct` on its first +// tick. Where Electron reports `cpu.cumulativeCPUUsage`, a process without it has no `cpuPct` either (Electron sends 0 +// "for compatibility" when it cannot read CPU). A field Electron +// did not supply (or supplied as a non-finite/negative number) is omitted from its process entry, a process with no +// usable metric is dropped, an empty result emits nothing, and a rejected/throwing/hostile GPU read leaves the GPU +// absent. `appMetrics` is a WINDOWED stage (a live read would consume the CPU window), so `current('appMetrics')` +// answers the last emitted sample of the current run: undefined until the first tick and while unarmed. +// +// SINGLETON per key object (`electronProcessTrackerFor`: the `app` object by default). SEAMS MERGE, NEVER DROP: a later +// launch that omits `scheduler`/`onError` keeps the previous launch's (it can replace a seam, never shed one). +// RETENTION rule — what survives a stage's last unsubscribe: ONLY the merged seams and a usable GPU result +// (static hardware description that a late report still needs; re-requested only for a different type or when nothing usable settled). Everything windowed starts +// FRESH on the next subscription: the priming read is repeated and the last sample is dropped. `reset()` drops +// everything including the GPU result. Every timer callback is guarded by the run that armed it, so a timer whose +// clear failed can never emit; a source that fails to arm is reported and left unarmed (retried on the next listener +// change or rebind); a throwing/async reporter never escapes into the host. + +export type GpuInfoType = 'basic' | 'complete'; + +/** The slice of Electron's `app` this tracker reads. Every member is optional: an absent one just means the stage is absent. */ +export interface ElectronAppSource { + getAppMetrics?(): unknown; + getGPUInfo?(type: GpuInfoType): Promise; + on?(event: 'child-process-gone', listener: (event: unknown, details: unknown) => void): unknown; + removeListener?( + event: 'child-process-gone', + listener: (event: unknown, details: unknown) => void, + ): unknown; + off?(event: 'child-process-gone', listener: (event: unknown, details: unknown) => void): unknown; +} + +/** One process of `app.getAppMetrics()`. Sizes are BYTES (Electron reports kilobytes); every metric is omitted when unknown. */ +export interface AppProcessMetric { + /** Electron's process type, verbatim (`Browser`, `Tab`, `GPU`, `Utility`, …). */ + type: string; + pid: number; + /** Share of the WHOLE machine used since the previous read, 0-100, as Electron reports it (it divides by the processor count). */ + cpuPct?: number; + workingSetBytes?: number; + peakWorkingSetBytes?: number; + /** Windows only (Electron omits it elsewhere). */ + privateBytes?: number; +} + +export interface ChildProcessGone { + /** Electron's child process type (`GPU`, `Utility`, …), verbatim. */ + type: string; + /** Electron's reason (`crashed`, `oom`, `killed`, `clean-exit`, …), verbatim. */ + reason: string; + exitCode?: number; + /** The utility's service name (`Network Service`, …) when Electron supplies it. */ + name?: string; +} + +export interface ElectronProcessEvents { + appMetrics: { processes: AppProcessMetric[] }; + childProcessGone: ChildProcessGone; + gpu: ElectronGpu; +} + +/** What the tracker needs from a launch. */ +export interface ElectronProcessEnv { + /** Electron's `app` (or a structural fake). */ + app?: ElectronAppSource; + /** Drives the metrics timer; default the global timers, unref'd so the tracker never holds a process alive. */ + scheduler?: ProcessTimers; + /** `getAppMetrics` period in ms (default 1000). */ + intervalMs?: number; +} + +const DEFAULT_INTERVAL_MS = 1000; + +const defaultScheduler: ProcessTimers = { + setInterval: (cb, ms) => { + const h = setInterval(cb, ms); + (h as { unref?: () => void }).unref?.(); + return h; + }, + clearInterval: (h) => clearInterval(h as ReturnType), +}; + +const SEAM_KEYS = [ + 'app', + 'scheduler', + 'intervalMs', +] as const satisfies readonly (keyof ElectronProcessEnv)[]; + +const KIB = 1024; + +const finiteNonNegative = (value: unknown): number | undefined => + typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined; + +const kibToBytes = (value: unknown): number | undefined => { + const kib = finiteNonNegative(value); + return kib === undefined ? undefined : kib * KIB; +}; + +const record = (value: unknown): Record | undefined => + typeof value === 'object' && value !== null ? (value as Record) : undefined; + +const hasCumulative = (p: Record): boolean => + finiteNonNegative(record(p.cpu)?.cumulativeCPUUsage) !== undefined; + +interface MappedMetrics { + /** Undefined when nothing usable came back. */ + metrics: { processes: AppProcessMetric[] } | undefined; + /** Every pid this read listed (usable or not): the next read's "already seen" set. */ + pids: Set; +} + +/** + * Maps `app.getAppMetrics()` defensively. `cpuPct` is only reported for a pid that `seen` already listed in the + * PREVIOUS read: Chromium returns 0 on the first CPU-usage call per process (and Electron keeps one metrics object per + * child process), so a process that appeared since (a new renderer, a restarted GPU/utility process) has no true CPU + * figure yet. On an Electron that reports `cpu.cumulativeCPUUsage` for some processes, a process lacking it also has no + * `cpuPct` (Electron sends 0 "for compatibility" when it cannot read CPU). + */ +function mapAppMetrics(raw: unknown, seen: ReadonlySet): MappedMetrics { + const pids = new Set(); + if (!Array.isArray(raw)) return { metrics: undefined, pids }; + const entries = raw.map(record); + const reportsCumulative = entries.some((p) => p !== undefined && hasCumulative(p)); + const processes: AppProcessMetric[] = []; + for (const p of entries) { + if (p === undefined) continue; + const { type, pid } = p; + if ( + typeof type !== 'string' || + type === '' || + typeof pid !== 'number' || + !Number.isFinite(pid) + ) { + continue; + } + pids.add(pid); + const cpuPct = + seen.has(pid) && (!reportsCumulative || hasCumulative(p)) + ? finiteNonNegative(record(p.cpu)?.percentCPUUsage) + : undefined; + const memory = record(p.memory); + const workingSetBytes = kibToBytes(memory?.workingSetSize); + const peakWorkingSetBytes = kibToBytes(memory?.peakWorkingSetSize); + const privateBytes = kibToBytes(memory?.privateBytes); + if ( + cpuPct === undefined && + workingSetBytes === undefined && + peakWorkingSetBytes === undefined && + privateBytes === undefined + ) { + continue; // a process we know nothing measurable about is not a sample + } + processes.push({ + type, + pid, + ...(cpuPct !== undefined ? { cpuPct } : {}), + ...(workingSetBytes !== undefined ? { workingSetBytes } : {}), + ...(peakWorkingSetBytes !== undefined ? { peakWorkingSetBytes } : {}), + ...(privateBytes !== undefined ? { privateBytes } : {}), + }); + } + return { metrics: processes.length > 0 ? { processes } : undefined, pids }; +} + +const copyMetrics = (m: { processes: AppProcessMetric[] }): { processes: AppProcessMetric[] } => ({ + processes: m.processes.map((p) => ({ ...p })), +}); + +/** Maps a `child-process-gone` details object. Undefined unless Electron gave a type and a reason. */ +function mapChildGone(details: unknown): ChildProcessGone | undefined { + const d = record(details); + if (d === undefined) return undefined; + const { type, reason, exitCode, name } = d; + if (typeof type !== 'string' || type === '' || typeof reason !== 'string' || reason === '') { + return undefined; + } + return { + type, + reason, + ...(typeof exitCode === 'number' && Number.isFinite(exitCode) ? { exitCode } : {}), + ...(typeof name === 'string' && name.trim() !== '' ? { name: name.trim() } : {}), + }; +} + +type GoneListener = (event: unknown, details: unknown) => void; + +export class ElectronProcessTracker extends InterceptorBase { + readonly name = 'electron-process'; + #env: ElectronProcessEnv; + /** The metrics run: armed once its priming read succeeded. */ + #metricsArmed = false; + #last: { processes: AppProcessMetric[] } | undefined; + /** The pids the previous read listed (the priming read seeds it). */ + #seenPids: ReadonlySet = new Set(); + /** True while the polls keep failing (the failure was already reported). */ + #metricsFailing = false; + #timer: { handle: unknown; scheduler: ProcessTimers } | null = null; + /** Bumped whenever the timer is torn down: a callback of an older run never emits. */ + #gen = 0; + /** The attached `child-process-gone` listener, with the app it is attached to (so removal hits the right one). */ + #gone: { app: ElectronAppSource; listener: GoneListener } | undefined; + // GPU: `#gpuGen` invalidates an in-flight read; `#gpuType` is the type the kept value was read with. + #gpuGen = 0; + #gpuType: GpuInfoType | undefined; + /** True from the request until it settles (or is cancelled). */ + #gpuPending = false; + #gpu: ElectronGpu | undefined; + // Mutable indirection: the SHARED tracker outlives launches, so the reporter is always the latest launch's. + readonly #report: { fn: ((error: unknown) => unknown) | undefined }; + + constructor(env: ElectronProcessEnv = {}, onError?: (error: unknown) => unknown) { + const report = { fn: onError }; + // A throwing reporter must not escape into the emitter's dispatch (which runs inside the host's events). + super((error) => reportTo(report, error)); + this.#report = report; + this.#env = env; + } + + /** + * Hand the latest launch's seams to this shared tracker. A defined `onError` replaces the reporter (undefined keeps + * it); every defined seam REPLACES ours, an undefined one never clobbers an earlier one. When a seam actually + * changed, the metrics run and the `child-process-gone` listener are torn down with the seams they were ARMED with, + * then the merged seams are swapped in and whatever still has listeners starts again (fresh baseline). An unchanged + * relaunch restarts nothing. + */ + rebind(env: ElectronProcessEnv, onError?: (error: unknown) => unknown): void { + if (onError !== undefined) this.#report.fn = onError; + const merged: Record = {}; + let changed = false; + for (const key of SEAM_KEYS) { + const next = env[key] ?? this.#env[key]; + if (next !== undefined) merged[key] = next; + if (next !== this.#env[key]) changed = true; + } + if (!changed) return; + this.#stopMetrics(); // OLD seams + this.#detachGone(); + this.#env = merged as ElectronProcessEnv; + this.#sync(); + } + + /** + * Request the one-shot `app.getGPUInfo(type)` read. A no-op while one is in flight, and while a USABLE value of the + * SAME type is already settled (static hardware description: it is kept). It asks again when nothing usable was + * settled (the earlier read rejected, threw, or returned nothing mappable) or when a different `type` is requested + * (`'complete'` after `'basic'`); a failed re-ask keeps the earlier usable value. Never throws, never leaves a + * rejected Promise unhandled (a Linux host without GPU acceleration rejects, and the session owner's own + * unhandled-rejection detection would report it); a failure is reported and the GPU stays as it was. + */ + requestGpuInfo(type: GpuInfoType = 'basic'): void { + if (this.#gpuPending) return; + if (this.#gpuType === type) return; // a usable value of this type is kept + const app = this.#env.app; + if (app === undefined || typeof app.getGPUInfo !== 'function') return; + this.#gpuPending = true; + const mine = ++this.#gpuGen; + try { + Promise.resolve(app.getGPUInfo(type)).then( + (info) => { + if (mine !== this.#gpuGen) return; // cancelled (or reset) since: never write + this.#gpuPending = false; + try { + const gpu = mapGpuInfo(info); + if (gpu === undefined) return; + this.#gpu = gpu; + this.#gpuType = type; + this.emit('gpu', { ...gpu }); + } catch (error) { + this.#onError(error); + } + }, + (error: unknown) => { + if (mine !== this.#gpuGen) return; + this.#gpuPending = false; + this.#onError(error); + }, + ); + } catch (error) { + this.#gpuPending = false; + this.#onError(error); // getGPUInfo threw synchronously + } + } + + /** + * Abort an IN-FLIGHT GPU read: a late resolve/reject is ignored and a later request starts afresh. A value that + * already settled is kept (reports still draining on stop need it). + */ + cancelGpuInfo(): void { + if (!this.#gpuPending) return; + this.#gpuGen++; + this.#gpuPending = false; + } + + /** + * The latest reading of `stage`. `gpu` is the settled result. `appMetrics` is windowed (a live read would + * consume the CPU window), so it answers the last sample of the current run: undefined until the first tick and while + * unarmed. Always a copy. + */ + current(stage: 'appMetrics'): { processes: AppProcessMetric[] } | undefined; + current(stage: 'gpu'): ElectronGpu | undefined; + current(stage: 'appMetrics' | 'gpu'): unknown { + if (stage === 'gpu') return this.#gpu === undefined ? undefined : { ...this.#gpu }; + return this.#metricsArmed && this.#last !== undefined ? copyMetrics(this.#last) : undefined; + } + + /** Test/teardown: drop EVERY listener (releasing the timer and the `app` listener) and forget the GPU result. */ + reset(): void { + this.removeAllListeners(); + this.#gpuGen++; + this.#gpuPending = false; + this.#gpuType = undefined; + this.#gpu = undefined; + } + + // Activation is per stage (onListenersChanged); the whole-tracker hook has nothing to do. + protected onActivate(): void {} + + protected override onListenersChanged(): void { + this.#sync(); + } + + #onError(error: unknown): void { + reportTo(this.#report, error); + } + + #sync(): void { + if (this.listenerCount('appMetrics') === 0) this.#stopMetrics(); + else if (!this.#metricsArmed) this.#startMetrics(); + if (this.listenerCount('childProcessGone') === 0) this.#detachGone(); + else if (this.#gone === undefined) this.#attachGone(); + } + + #startMetrics(): void { + const app = this.#env.app; + if (app === undefined || typeof app.getAppMetrics !== 'function') return; + try { + // PRIMING read: CPU is "since the previous call", so this opens the window for the processes that exist now; its + // values are discarded, only the pids are remembered + this.#seenPids = mapAppMetrics(app.getAppMetrics(), new Set()).pids; + } catch (error) { + this.#onError(error); // left unarmed: retried on the next listener change / rebind + return; + } + const scheduler = this.#env.scheduler ?? defaultScheduler; + const gen = ++this.#gen; + try { + const handle = scheduler.setInterval(() => { + if (gen === this.#gen) this.#tick(app); + }, this.#env.intervalMs ?? DEFAULT_INTERVAL_MS); + this.#timer = { handle, scheduler }; + this.#metricsArmed = true; + } catch (error) { + this.#gen += 1; + this.#onError(error); // nothing would ever read it: stay unarmed + } + } + + #stopMetrics(): void { + const timer = this.#timer; + this.#timer = null; + this.#metricsArmed = false; + this.#last = undefined; + this.#metricsFailing = false; + this.#gen += 1; + if (timer === null) return; + try { + timer.scheduler.clearInterval(timer.handle); + } catch (error) { + this.#onError(error); + } + } + + #tick(app: ElectronAppSource): void { + let metrics: MappedMetrics['metrics']; + try { + const mapped = mapAppMetrics(app.getAppMetrics?.(), this.#seenPids); + metrics = mapped.metrics; + this.#seenPids = mapped.pids; + } catch (error) { + // this tick only; the stage stays armed. A PERSISTENT failure is reported once per failure streak (a poll runs + // every second): a successful read, a re-arm or a stop ends the streak. + if (!this.#metricsFailing) { + this.#metricsFailing = true; + this.#onError(error); + } + return; + } + this.#metricsFailing = false; + if (metrics === undefined) return; // absence, never zero + this.#last = metrics; + // Emitted payloads are copies: a subscriber cannot mutate the retained sample. + this.emit('appMetrics', copyMetrics(metrics)); + } + + #attachGone(): void { + const app = this.#env.app; + if (app === undefined || typeof app.on !== 'function') return; + // A listener that cannot be removed again would outlive `client.stop()`: only attach when it can be released. + if (typeof app.removeListener !== 'function' && typeof app.off !== 'function') return; + const listener: GoneListener = (_event, details) => { + const gone = mapChildGone(details); + if (gone !== undefined) this.emit('childProcessGone', gone); + }; + try { + app.on('child-process-gone', listener); + this.#gone = { app, listener }; + } catch (error) { + this.#onError(error); // left unattached: retried on the next listener change / rebind + } + } + + #detachGone(): void { + const gone = this.#gone; + this.#gone = undefined; + if (gone === undefined) return; + try { + if (typeof gone.app.removeListener === 'function') { + gone.app.removeListener('child-process-gone', gone.listener); + } else { + gone.app.off?.('child-process-gone', gone.listener); + } + } catch (error) { + this.#onError(error); + } + } +} + +/** Calls the reporter; it may throw or return a rejecting Promise (both are absorbed: the tracker is silent toward the host). */ +function reportTo(report: { fn: ((error: unknown) => unknown) | undefined }, error: unknown): void { + try { + const result = report.fn?.(error); + if (result instanceof Promise) result.catch(() => undefined); + } catch { + /* the reporter itself failed */ + } +} + +const registry = createTrackerRegistry(); + +/** A {@link ElectronProcessEnv} plus the object the singleton is keyed on (default: the `app` object). */ +export interface ElectronProcessTrackerEnv extends ElectronProcessEnv { + key?: object; +} + +function seamsOf(env: ElectronProcessTrackerEnv): ElectronProcessEnv { + const seams: Record = {}; + for (const key of SEAM_KEYS) { + const value = env[key]; + if (value !== undefined) seams[key] = value; + } + return seams as ElectronProcessEnv; +} + +/** + * The singleton ElectronProcessTracker for the env's key (the `app` object by default; with neither a `key` nor an + * `app` there is nothing to key on and the call throws, because a shared anonymous tracker would be a global with no + * owner). Every call (a relaunch included) hands the shared tracker the latest launch's `onError` and seams (see + * {@link ElectronProcessTracker.rebind}); nothing else of the env is kept. + */ +export function electronProcessTrackerFor( + env: ElectronProcessTrackerEnv, + onError?: (error: unknown) => unknown, +): ElectronProcessTracker { + const key = env.key ?? env.app; + if (key === undefined) throw new TypeError('electronProcessTrackerFor needs an `app` or a `key`'); + const seams = seamsOf(env); + return registry.for( + key, + () => new ElectronProcessTracker(seams, onError), + (tracker) => tracker.rebind(seams, onError), + ); +} + +/** Test/teardown: drop the key's tracker (resetting it, so its timer, listener and GPU result are released). */ +export function resetElectronProcessTracker(key: object): void { + registry.reset(key); +} diff --git a/packages/trackers/src/index.test.ts b/packages/trackers/src/index.test.ts index a42997cd..0f760fa7 100644 --- a/packages/trackers/src/index.test.ts +++ b/packages/trackers/src/index.test.ts @@ -11,10 +11,6 @@ describe('@bugsee/trackers public surface', () => { ]); }); - it('reserves the electron entry as an empty placeholder', async () => { - expect(Object.keys(await import('./electron/index'))).toEqual([]); - }); - it('exports the browser tracker values from ./browser', async () => { expect(Object.keys(await import('./browser/index')).sort()).toEqual([ 'ApplicationTracker', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cbec8245..5894e11f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -509,6 +509,9 @@ importers: '@bugsee/browser': specifier: workspace:* version: link:../browser + '@bugsee/capture': + specifier: workspace:* + version: link:../capture '@bugsee/core': specifier: workspace:* version: link:../core @@ -518,6 +521,9 @@ importers: '@bugsee/protocol': specifier: workspace:* version: link:../protocol + '@bugsee/trackers': + specifier: workspace:* + version: link:../trackers devDependencies: '@bugsee/util': specifier: workspace:*