diff --git a/.changeset/electron-power-display-app-trackers.md b/.changeset/electron-power-display-app-trackers.md new file mode 100644 index 00000000..07c3dc44 --- /dev/null +++ b/.changeset/electron-power-display-app-trackers.md @@ -0,0 +1,6 @@ +--- +'@bugsee/electron': minor +'@bugsee/trackers': minor +--- + +Electron main now records power, display and window telemetry. The power and display domains turn on when `powerMonitor` / `screen` is passed to `launchMain`. The window domain (`window_*`, `renderer_*`) turns on whenever `app` is passed, so existing callers that already pass `app` now get two extra `app` listeners (`browser-window-created`, `web-contents-created`) and these events while `captureSystemEvents` is on; pass `captureWindowEvents: false` to opt out, and `BrowserWindow` only adds windows that already exist. Electron's real `screen` throws until the app is ready: pass it after `app.whenReady()` (a throwing object turns that domain off and is reported, never failing the launch). On `events.system`: `power_suspend`, `power_resume`, `power_lock`, `power_unlock`, `power_ac`, `power_battery` (platform dependent: `lock-screen` and `on-ac` are macOS/Windows, `on-battery` is macOS only); `display_added`, `display_removed` and `display_metrics_changed`; `window_focus`, `window_blur`, `window_show`, `window_hide` (`{ windowId }`) and `renderer_unresponsive` / `renderer_responsive` (`{ webContentsId }`, listened for on `webContents` only so a hang is never recorded twice). The `electron_displays` system trace (`{ displays: [{ id, width, height, scale_factor?, rotation?, internal?, refresh_rate_hz? }] }`, JS-specific name) is written when the display list changes (it is held: a later unreadable list leaves the previous one recorded). Listeners attach only while `captureSystemEvents` / system traces are on and are removed by `client.stop()`. They come from three new per-object domain trackers in `@bugsee/trackers/electron`: `ElectronPowerTracker`, `ElectronDisplayTracker` and `ElectronApplicationTracker`. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 46cfe9b3..247eb023 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -415,7 +415,8 @@ 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. +- **TR9 part 1 (implemented on `feat/electron-process-tracker`; Electron main-process PROCESS tracker; power/screen/window events are in part 2 below):** 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. +- **TR9 part 2 (implemented on `feat/electron-power-display-app-trackers`; the remaining Electron-main DOMAIN trackers):** three more per-object singleton trackers in `@bugsee/trackers/electron`, all with Electron INJECTED structurally (no electron/DOM dependency), a shared `stage-tracker.ts` (`ElectronStageTracker` base + `bindAll`: per-STAGE lazy attach on a stage's first listener and release on its last, all-or-nothing attach with rollback, a source with no `removeListener`/`off` is never attached to, every wrapper is liveness-guarded so a listener whose removal failed can never emit, a throwing/async reporter is absorbed; `process-tracker.ts` now shares its `reportTo`). **`ElectronPowerTracker`** (`electronPowerTrackerFor({powerMonitor}, onError?)`, `resetElectronPowerTracker(key)`; keyed on the monitor; stages `suspendResume` `{state:'suspend'|'resume'}`, `lockScreen` `{state:'lock'|'unlock'}` (macOS/Windows; never fires on Linux), `powerSource` `{source:'ac'|'battery'}`; `current('powerSource')` is a LIVE `isOnBatteryPower()` read, undefined without the method / non-boolean / throw (reported), never guessed; `thermal-state-change`/`speed-limit-change` deliberately NOT mapped: macOS-only and the thermal state is not Android's int enum). **`ElectronDisplayTracker`** (`electronDisplayTrackerFor({screen}, onError?)`; stages `displayAdded`/`displayRemoved` -> `DisplayInfo`, `displayMetricsChanged` -> `{display, changed: string[]}`, `displays` -> `{displays: DisplayInfo[]}` re-read from `getAllDisplays()` after any of the three; `current('displays')` is live; `DisplayInfo = {id, width, height, scaleFactor?, rotation?: 0|90|180|270, internal?, refreshRate?}` from Electron's `size` (bounds fallback), `label`/position/`workArea` are NOT kept, a display with no finite id or positive size is dropped, an empty/unreadable list is undefined, never `[]`). **`ElectronApplicationTracker`** (`electronApplicationTrackerFor({app, BrowserWindow?}, onError?)`, keyed on `app`; `rebind` re-arms when the `BrowserWindow` seam changes; stages `windowFocus` `{focused, windowId?}`, `windowVisibility` `{visible, windowId?}`, `rendererResponsiveness` `{responsive, webContentsId?}`; each stage watches the objects that EXIST at arm time (`BrowserWindow.getAllWindows()`, and each window's `webContents`) AND those created later (`app.on('browser-window-created')` / `app.on('web-contents-created')`), binds each object once, forgets it on `closed`/`destroyed` without touching the dead object, skips `isDestroyed()` objects at bind and at release, tolerates a throwing `getAllWindows`/`id`/`isDestroyed`; **the hang pair is on `webContents` ONLY** because `BrowserWindow` re-emits it; ids are Electron's numeric `id`, omitted when absent; titles/URLs are never read). **Wire names (`@bugsee/electron`):** `events.system` `power_suspend`, `power_resume`, `power_lock`, `power_unlock`, `power_ac`, `power_battery` (no params); `display_added`/`display_removed` params `{id, width, height, scaleFactor?, rotation?, internal?, refreshRate?}`, `display_metrics_changed` params the same plus `changed: string[]`; `window_focus`/`window_blur`/`window_show`/`window_hide` params `{windowId?}`; `renderer_unresponsive`/`renderer_responsive` params `{webContentsId?}` (snake_case names like `process_*`/`child_process_gone`, camelCase params like `exitCode`). Trace **`electron_displays`** = `{displays: [{id, width, height, scale_factor?, rotation?, internal?, refresh_rate_hz?}]}`, a HELD step trace (`emitIfChanged`: baseline at start, then the fresh list after each display change), absent when Electron gives no usable list. **Name choice:** `displays` stays RESERVED: nothing in `@bugsee/protocol`/`@bugsee/capture` defines an Android-shaped display list (only a comment that mobile-only `displays` is not sampled) and the viewer shape is unconfirmed (Q5), so the JS-specific `electron_displays` is used. `system-events.ts` mux now takes `{process?, power?, display?, application?}` and forwards all of the above lazily (nothing attached at construction or with `captureSystemEvents:false`; every release guarded); `system-traces.ts` `createElectronSystemTraceProducers({process?, display?})` adds the displays producer. `LaunchMainOptions` gains optional `powerMonitor`, `screen`, `BrowserWindow` (destructured out of `...nodeOptions`); `ElectronAppLike` gains `on('browser-window-created'|'web-contents-created')` and widened `removeListener`/`off`; each tracker is built THROUGH its registry accessor, skipped on a repeat launch (carrier client present) and absent when its object was not injected (a `powerMonitor` alone still gets the mux, a `screen` alone still gets the displays producer; the legacy `systemMetricsSampler` still suppresses producers). **Tests:** per-tracker unit tests with the mutator loop (about 40 mutations over the three trackers/base, 0 survivors after strengthening: forgetting on closed/destroyed, release skipping destroyed objects, rotation mapping), mux/producer unit tests, launch-level accessor spies (mutating any of the three to `new` fails) and real-launch integration tests (events + trace in the uploaded bundle, a window created AFTER launch records focus, `webContents` hang recorded ONCE although the window re-emits it and `win.emit('unresponsive')` alone records nothing, option off -> no listeners, `client.stop()` -> all released, a throwing Electron getter never fails launch, a repeat launch leaves the running trackers' reporter untouched). **NOT verified without a real Electron (source/doc-verified, not run):** the real `powerMonitor` event firing and `isOnBatteryPower()` semantics per OS, the real `Display` object shape (`size`, `displayFrequency`, `rotation`) and `display-metrics-changed` argument order `(event, display, changedMetrics)`, `browser-window-created`/`web-contents-created` ordering, `BrowserWindow` re-emitting `unresponsive` after ~50 ms, and `webContents` `destroyed`/window `closed` timing. **Review fixes (#91):** every host property read in `isReleasable`/`bindAll`/`current()` is guarded (Electron's real `screen` is a Proxy that throws on ANY property read before app ready: a throwing object = that domain off, reported, never a failed launch); `sync()` guards `attachStage`; the mux isolates EVERY subscription in `onActivate` (it never throws, so the provider always gets its unsubscribe and `stop()` releases the inner source's handlers too); display id -1 ('invalid or not yet known') is dropped, -10 (virtual unified display) is kept as reported; `on-ac` (darwin/win32) and `on-battery` (darwin only) are platform dependent and `current('powerSource')` is the live truth; new launch option `captureWindowEvents` (default true, opt-out) for the window domain, which is ON whenever `app` is passed. **OPEN OWNER DECISION (held values), now also covering `electron_displays`:** a refresh that cannot read a usable list emits nothing and a held trace cannot be retracted, so the previous list stays held and is re-recorded every `refreshMs` (absent only before the first emit); same class as `storage_estimate` / `user_idle_state`. Known limits: a `webContents` that existed before `launchMain` and has no `BrowserWindow` (an earlier `BrowserView`/``) is not discovered; `screen` must be injected after `app` is ready (a throwing one turns the display domain off); viewer support for `electron_displays` and the new event names is unconfirmed (Q5). - **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/option-directions.test.ts b/packages/bugsee/src/option-directions.test.ts index eb682bd1..fd0d9956 100644 --- a/packages/bugsee/src/option-directions.test.ts +++ b/packages/bugsee/src/option-directions.test.ts @@ -109,6 +109,11 @@ const RAW_STRICT: Record = { safe: 'on', why: 'INTERNAL hold, forwarded to the browser read above', }, + 'electron:captureWindowEvents': { + safe: 'off', + why: 'default ON, records window focus/renderer hangs: an invalid value is OFF + onError', + check: ['electron', /resolveFailClosedBoolean\(\s*captureWindowEvents/], + }, 'electron:recover': { safe: 'n/a', why: 'durability behaviour' }, 'node:recover': { safe: 'n/a', why: 'durability of already-persisted data' }, 'node:exitOnUncaught': { safe: 'n/a', why: 'process policy' }, diff --git a/packages/bugsee/src/relaunch-options.test.ts b/packages/bugsee/src/relaunch-options.test.ts index a79d8159..be4fe965 100644 --- a/packages/bugsee/src/relaunch-options.test.ts +++ b/packages/bugsee/src/relaunch-options.test.ts @@ -108,7 +108,7 @@ function optionKeys(pkg: string, file: string, name: string): string[] { * "this is not deployment identity and not an integration seam". Notes on the ones that look otherwise: * - `lifecycleEventsListener` is held on the carrier slot (`setProcessLifecycleEventsListener`), so it * survives a relaunch without being re-passed; - * - the Electron handles (`app`, `ipcMain`, `crashReporter`, `gpuInfoType`, `bridge`, `post`, `launch`, `onSessionId`, + * - the Electron handles (`app`, `ipcMain`, `crashReporter`, `powerMonitor`, `screen`, `BrowserWindow`, `gpuInfoType`, `bridge`, `post`, `launch`, `onSessionId`, * `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, @@ -133,8 +133,10 @@ function optionKeys(pkg: string, file: string, name: string): string[] { * serving `hardware.gpu`. */ const RESET_OPTIONS: readonly string[] = [ + 'BrowserWindow', 'app', 'appToken', + 'captureWindowEvents', 'flushTimeoutMs', 'gpuInfoType', 'injectTraceMeta', @@ -194,6 +196,7 @@ const RESET_OPTIONS: readonly string[] = [ 'performanceUploadMode', 'persistUserIdentifier', 'post', + 'powerMonitor', 'profiling', 'profilingSamplingIntervalMicros', 'propagateTrace', @@ -208,6 +211,7 @@ const RESET_OPTIONS: readonly string[] = [ 'reportPrioritySelectorEnabled', 'reportSummaryRequired', 'reportTrigger', + 'screen', 'shutdownTimeoutMs', 'startInBlackout', 'systemTraceProducers', diff --git a/packages/electron/README.md b/packages/electron/README.md index eebfeaf4..bf966da6 100644 --- a/packages/electron/README.md +++ b/packages/electron/README.md @@ -51,7 +51,7 @@ launchRenderer('YOUR_APP_TOKEN'); ## Options -`launchMain(appToken, options)` takes `ipcMain` (required), `app`, `crashReporter`, `crashReporterExtra` and `video`, plus every `@bugsee/node` launch option (`appVersion`, `captureLogs`, `captureNetwork`, `maxRecordingTime`, `dataDir` and others). +`launchMain(appToken, options)` takes `ipcMain` (required), `app`, `powerMonitor`, `screen`, `BrowserWindow`, `gpuInfoType`, `captureWindowEvents`, `crashReporter`, `crashReporterExtra` and `video`, plus every `@bugsee/node` launch option (`appVersion`, `captureLogs`, `captureNetwork`, `maxRecordingTime`, `dataDir` and others). `launchRenderer(appToken, options)` takes the `@bugsee/browser` launch options. Session replay is on by default and streams to the main process; pass `replay: false` to opt out. @@ -76,7 +76,19 @@ If you pass `app` to `launchMain`, the main process also reports what Electron c - 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. +A `relaunch()` from `@bugsee/node` or `@bugsee/bugsee` is not Electron-aware: after it `hardware.gpu` is still served, but `app_metrics`, `child_process_gone` and the power, display and window telemetry below stop until `launchMain` runs again. + +## Power, display and window telemetry + +Pass any of `powerMonitor`, `screen` and `BrowserWindow` (the Electron objects, injected like `app`) to `launchMain`; a domain whose object is absent is simply off. + +**Pass `screen` safely.** Electron's real `screen` throws on any property read until the app is ready, so `import { screen } from 'electron'` and passing it straight to a `launchMain` call made before `app.whenReady()` turns the display domain off (the failure is reported through `onError`; the launch and the other domains are unaffected). To get display telemetry, either call `launchMain` after `app.whenReady()`, or leave `screen` out of the early call. The `powerMonitor` has the same rule on some platforms. + +- `powerMonitor` -> `events.system`: `power_suspend`, `power_resume`, `power_lock`, `power_unlock`, `power_ac`, `power_battery`. No params. Platform dependent, per Electron's typings: `lock-screen`/`unlock-screen` are macOS and Windows, `on-ac` is macOS and Windows, and `on-battery` is macOS only, so an event that never fires is not evidence about the power state. +- `screen` -> `events.system`: `display_added` and `display_removed` (`{ id, width, height, scaleFactor, rotation, internal, refreshRate }`, absent keys omitted; a display whose id is -1, Electron's "invalid or not yet known" marker, is ignored) and `display_metrics_changed` (the same plus `changed`, Electron's changed metrics). It also feeds the `electron_displays` system trace (`{ displays: [{ id, width, height, scale_factor, rotation, internal, refresh_rate_hz }] }`, written when it changes). The trace is absent only before its first value: if a later refresh cannot read a usable list, the previous list stays held and keeps being re-recorded (the same open decision as other held traces). The name is JS-specific: `displays` is reserved until an Android-shaped list is confirmed against the viewer. +- `app` (plus `BrowserWindow` for windows that already exist) -> `events.system`: `window_focus`, `window_blur`, `window_show`, `window_hide` (`{ windowId }`), and `renderer_unresponsive` / `renderer_responsive` (`{ webContentsId }`). These are on whenever `app` is passed (they add two `app` listeners, `browser-window-created` and `web-contents-created`); pass `captureWindowEvents: false` to opt out. Windows created after `launchMain` are tracked too. The hang pair is listened for on `webContents` only, because `BrowserWindow` re-emits it and each hang would otherwise be recorded twice; a `` or `BrowserView` is covered when Electron announces it through `web-contents-created`. + +All of these events are recorded only while `captureSystemEvents` is on, the listeners are removed again by `client.stop()`, and a throwing Electron getter is reported through `onError` and never fails the launch. Window titles and URLs are never read. ## Links diff --git a/packages/electron/src/launch-main.test.ts b/packages/electron/src/launch-main.test.ts index 2e939f37..72bb24c1 100644 --- a/packages/electron/src/launch-main.test.ts +++ b/packages/electron/src/launch-main.test.ts @@ -8,7 +8,12 @@ import { } from '@bugsee/core'; import type { Bugsee, BugseeLaunchOptions } from '@bugsee/node'; import { resetProcessTracker } from '@bugsee/node'; -import { electronProcessTrackerFor } from '@bugsee/trackers/electron'; +import { + electronApplicationTrackerFor, + electronDisplayTrackerFor, + electronPowerTrackerFor, + 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'; @@ -25,7 +30,13 @@ import type { VideoCaptureSource } from './video-capture'; // (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) }; + return { + ...actual, + electronProcessTrackerFor: vi.fn(actual.electronProcessTrackerFor), + electronPowerTrackerFor: vi.fn(actual.electronPowerTrackerFor), + electronDisplayTrackerFor: vi.fn(actual.electronDisplayTrackerFor), + electronApplicationTrackerFor: vi.fn(actual.electronApplicationTrackerFor), + }; }); afterEach(() => { @@ -1078,3 +1089,244 @@ describe('launchMain — Electron process tracker composition (TR9, part 1)', () }); }); }); + +describe('launchMain — Electron domain trackers: power, display, application windows (TR9, part 2)', () => { + const optsOf = (f: ReturnType) => + (f.received as { options: BugseeLaunchOptions }).options; + type L = (...a: unknown[]) => void; + class FakeEmitter { + table = new Map(); + on = vi.fn((e: string, l: L) => { + this.table.set(e, [...(this.table.get(e) ?? []), l]); + }); + removeListener = vi.fn((e: string, l: L) => { + this.table.set( + e, + (this.table.get(e) ?? []).filter((x) => x !== l), + ); + }); + emit(e: string, ...a: unknown[]) { + for (const l of [...(this.table.get(e) ?? [])]) l({}, ...a); + } + total() { + return [...this.table.values()].reduce((n, l) => n + l.length, 0); + } + } + const accessors = () => ({ + power: vi.mocked(electronPowerTrackerFor), + display: vi.mocked(electronDisplayTrackerFor), + application: vi.mocked(electronApplicationTrackerFor), + }); + const clear = () => { + for (const a of Object.values(accessors())) a.mockClear(); + }; + class Inner extends InterceptorBase<{ event: SystemEvent }> { + readonly name = 'inner'; + protected onActivate(): void {} + } + const wrapOf = (f: ReturnType) => + optsOf(f).wrapSystemEventsSource as NonNullable; + const producersOf = (f: ReturnType) => + (optsOf(f).systemTraceProducers ?? []).map((p: TraceProducer) => p.name); + + it('builds each tracker THROUGH its registry accessor, keyed on the injected object, with the launch onError', () => { + clear(); + const powerMonitor = new FakeEmitter(); + const screen = Object.assign(new FakeEmitter(), { getAllDisplays: () => [] }); + const app = new FakeEmitter(); + const BrowserWindow = { getAllWindows: () => [] }; + const onError = vi.fn(); + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app, + powerMonitor, + screen, + BrowserWindow, + onError, + }); + const a = accessors(); + expect(a.power).toHaveBeenCalledExactlyOnceWith({ powerMonitor }, onError); + expect(a.display).toHaveBeenCalledExactlyOnceWith({ screen }, onError); + expect(a.application).toHaveBeenCalledExactlyOnceWith({ app, BrowserWindow }, onError); + }); + + it('the application tracker is built without a BrowserWindow key when none was injected', () => { + clear(); + const app = new FakeEmitter(); + const f = fakeLaunch(); + launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch, app }); + expect(accessors().application).toHaveBeenCalledExactlyOnceWith({ app }, undefined); + }); + + it('absent Electron objects mean those domains are simply off: no accessor, no producer, no wrapper', () => { + clear(); + const f = fakeLaunch(); + launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch }); + for (const a of Object.values(accessors())) expect(a).not.toHaveBeenCalled(); + expect(optsOf(f).systemTraceProducers).toBeUndefined(); + expect(optsOf(f).wrapSystemEventsSource).toBeUndefined(); + }); + + it('a powerMonitor alone is enough for the events mux (no app needed) and adds no trace producer', () => { + const powerMonitor = new FakeEmitter(); + const f = fakeLaunch(); + launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch, powerMonitor }); + expect(optsOf(f).systemTraceProducers).toBeUndefined(); + const mux = wrapOf(f)(new Inner()); + expect(powerMonitor.total()).toBe(0); // lazy + const seen = vi.fn(); + mux.on('event', seen); + powerMonitor.emit('suspend'); + expect(seen).toHaveBeenCalledWith({ name: 'power_suspend' }); + }); + + it('a screen adds the electron_displays producer next to the node set, once', () => { + const screen = Object.assign(new FakeEmitter(), { getAllDisplays: () => [] }); + const f = fakeLaunch(); + launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch, screen }); + const names = producersOf(f); + expect(names).toContain('process-memory'); + expect(names.filter((n: string) => n === 'electron-displays')).toHaveLength(1); + expect(names).not.toContain('electron-app-metrics'); + }); + + it('an app adds app_metrics but not displays; a screen without app adds displays but not app_metrics', () => { + const f = fakeLaunch(); + launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch, app: new FakeEmitter() }); + expect(producersOf(f)).toContain('electron-app-metrics'); + expect(producersOf(f)).not.toContain('electron-displays'); + }); + + it('a legacy systemMetricsSampler with only a screen builds no producer list', () => { + const screen = Object.assign(new FakeEmitter(), { getAllDisplays: () => [] }); + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + screen, + systemMetricsSampler: () => [], + }); + expect(optsOf(f).systemTraceProducers).toBeUndefined(); + }); + + it('NEVER forwards the Electron objects or captureWindowEvents to the node launch', () => { + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app: new FakeEmitter(), + powerMonitor: new FakeEmitter(), + screen: new FakeEmitter(), + BrowserWindow: { getAllWindows: () => [] }, + captureWindowEvents: true, + }); + const keys = Object.keys(optsOf(f)); + for (const key of [ + 'app', + 'powerMonitor', + 'screen', + 'BrowserWindow', + 'captureWindowEvents', + 'ipcMain', + ]) { + expect(keys).not.toContain(key); + } + }); + + it('captureWindowEvents:false turns the window domain off (no application tracker, no app listeners); the others stay', () => { + clear(); + const app = new FakeEmitter(); + const powerMonitor = new FakeEmitter(); + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app, + powerMonitor, + captureWindowEvents: false, + }); + expect(accessors().application).not.toHaveBeenCalled(); + expect(accessors().power).toHaveBeenCalledOnce(); + const mux = wrapOf(f)(new Inner()); + mux.on('event', () => {}); + expect(app.table.get('browser-window-created')).toBeUndefined(); + expect(app.table.get('web-contents-created')).toBeUndefined(); + expect(powerMonitor.total()).toBe(6); + }); + + it.each([ + null, + 0, + '', + 'false', + 'true', + 1, + {}, + ])('an invalid captureWindowEvents (%j) is OFF and reported (fail closed)', (value) => { + clear(); + const onError = vi.fn(); + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app: new FakeEmitter(), + onError, + captureWindowEvents: value as never, + }); + expect(accessors().application).not.toHaveBeenCalled(); + expect(onError).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ message: expect.stringContaining('captureWindowEvents') }), + ); + }); + + it('captureWindowEvents:true and undefined keep the window domain on, without a report', () => { + for (const value of [true, undefined]) { + clear(); + const onError = vi.fn(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: fakeLaunch().launch, + app: new FakeEmitter(), + onError, + ...(value !== undefined ? { captureWindowEvents: value } : {}), + }); + expect(accessors().application).toHaveBeenCalledOnce(); + expect(onError).not.toHaveBeenCalled(); + } + }); + + it('the mux handed to node is LAZY: until subscribed no domain listener exists; subscribing attaches all, unsubscribing releases all', () => { + const powerMonitor = new FakeEmitter(); + const screen = Object.assign(new FakeEmitter(), { getAllDisplays: () => [] }); + const app = new FakeEmitter(); + const win = Object.assign(new FakeEmitter(), { + id: 1, + isDestroyed: () => false, + webContents: Object.assign(new FakeEmitter(), { id: 11, isDestroyed: () => false }), + }); + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app, + powerMonitor, + screen, + BrowserWindow: { getAllWindows: () => [win] }, + }); + const mux = wrapOf(f)(new Inner()); + const owned = () => + powerMonitor.total() + screen.total() + win.total() + win.webContents.total(); + // launchMain itself registers render-process-gone on app; the domain listeners are the REST + const appBefore = app.total(); + expect(owned()).toBe(0); + const off = mux.on('event', () => {}); + expect(powerMonitor.total()).toBe(6); + expect(screen.total()).toBe(3); + expect(win.total()).toBe(6); // focus, blur, show, hide + one `closed` per window stage + off(); + expect(owned()).toBe(0); + expect(app.total()).toBe(appBefore); + }); +}); diff --git a/packages/electron/src/launch-main.ts b/packages/electron/src/launch-main.ts index 4f6961db..55803f83 100644 --- a/packages/electron/src/launch-main.ts +++ b/packages/electron/src/launch-main.ts @@ -6,7 +6,13 @@ // import { launchMain } from '@bugsee/electron/main'; // import { ipcMain } from 'electron'; // launchMain(appToken, { ipcMain }); -import { type AppIdentity, BlackoutToken, CaptureStoreToken, getCarrierClient } from '@bugsee/core'; +import { + type AppIdentity, + BlackoutToken, + CaptureStoreToken, + getCarrierClient, + resolveFailClosedBoolean, +} from '@bugsee/core'; import { type Bugsee, type BugseeLaunchOptions, @@ -14,7 +20,16 @@ import { launchCore, sanitizeHardwareGpu, } from '@bugsee/node'; -import { electronProcessTrackerFor, type GpuInfoType } from '@bugsee/trackers/electron'; +import { + type BrowserWindowSource, + electronApplicationTrackerFor, + electronDisplayTrackerFor, + electronPowerTrackerFor, + electronProcessTrackerFor, + type GpuInfoType, + type PowerMonitorSource, + type ScreenSource, +} from '@bugsee/trackers/electron'; import { type CrashReporterLike, getCrashDumpsDirectory, @@ -38,11 +53,22 @@ export interface ElectronAppLike { * be released on `client.stop()`). */ on(event: 'child-process-gone', listener: (event: unknown, details: unknown) => void): unknown; + /** + * `browser-window-created` / `web-contents-created` are watched ONLY while system events are captured, through the + * shared ElectronApplicationTracker (window focus/blur/show/hide and renderer hangs); same release rule as above. + */ + on( + event: 'browser-window-created' | 'web-contents-created', + listener: (event: unknown, created: unknown) => void, + ): unknown; removeListener?( - event: 'child-process-gone', + event: 'child-process-gone' | 'browser-window-created' | 'web-contents-created', + listener: (event: unknown, details: unknown) => void, + ): unknown; + off?( + event: 'child-process-gone' | 'browser-window-created' | 'web-contents-created', 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). @@ -105,6 +131,27 @@ export interface LaunchMainOptions extends BugseeLaunchOptions { * different type (a failed re-ask keeps the earlier usable value). */ gpuInfoType?: GpuInfoType; + /** + * Electron's `powerMonitor` — optional. When present and system events are captured, `power_suspend`/`power_resume`/ + * `power_lock`/`power_unlock`/`power_ac`/`power_battery` are recorded on `events.system`. Absent: that domain is off. + */ + powerMonitor?: PowerMonitorSource; + /** + * Electron's `screen` — optional. When present, `display_added`/`display_removed`/`display_metrics_changed` are recorded + * on `events.system` (system events on) and the `electron_displays` list is traced (system traces on). Absent: off. + * Pass it only after `app` is ready (Electron throws if `screen` is touched earlier). + */ + screen?: ScreenSource; + /** + * Electron's `BrowserWindow` class — optional. With `app`, windows that exist when system events start are tracked + * for `window_*`/`renderer_*` events too (windows created later are always tracked through `app`). + */ + BrowserWindow?: BrowserWindowSource; + /** + * Record `window_*` / `renderer_*` events (default `true`). They are ON whenever `app` is passed (and system events are + * captured), which adds two `app` listeners (`browser-window-created`, `web-contents-created`); pass `false` to opt out (any non-boolean value is OFF and reported). + */ + captureWindowEvents?: boolean; /** Electron's `crashReporter` — when provided, native minidumps are captured, session-correlated. */ crashReporter?: CrashReporterLike; /** Extra params attached to native crash minidumps (merged under the session correlation). */ @@ -147,6 +194,10 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee const { ipcMain, app, + powerMonitor, + screen, + BrowserWindow, + captureWindowEvents, gpuInfoType, crashReporter, crashReporterExtra, @@ -215,33 +266,71 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee nodeOptions.onError, ) : undefined; + // The DOMAIN trackers (power / display / application windows) follow the same rule: built THROUGH their registry + // accessors, once per injected object, never on a repeat call, and absent when their Electron object was not injected. + const power = + powerMonitor !== undefined && !repeat + ? electronPowerTrackerFor({ powerMonitor }, nodeOptions.onError) + : undefined; + const display = + screen !== undefined && !repeat + ? electronDisplayTrackerFor({ screen }, nodeOptions.onError) + : undefined; + // Default ON; fail closed like the other capture switches: anything but a boolean is OFF, and reported. + const windowEvents = resolveFailClosedBoolean(captureWindowEvents, true); + if (captureWindowEvents !== undefined && typeof captureWindowEvents !== 'boolean') { + reportGuarded( + nodeOptions.onError, + new TypeError('captureWindowEvents must be a boolean: window events are OFF'), + ); + } + const application = + app !== undefined && !repeat && windowEvents + ? electronApplicationTrackerFor( + { app, ...(BrowserWindow !== undefined ? { BrowserWindow } : {}) }, + nodeOptions.onError, + ) + : undefined; + const hasElectronTrackers = [tracker, power, display, application].some((t) => t !== 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) { + // node set never emits (`app_metrics`, `electron_displays`). Not built when the legacy `systemMetricsSampler` replaces + // the producer list (they would never start). + if ( + (tracker !== undefined || display !== undefined) && + nodeOptions.systemMetricsSampler === undefined + ) { nodeOptions.systemTraceProducers = [ ...(nodeOptions.systemTraceProducers ?? createNodeSystemTraceProducers({ ...(nodeOptions.scheduler !== undefined ? { scheduler: nodeOptions.scheduler } : {}), ...(nodeOptions.onError !== undefined ? { onError: nodeOptions.onError } : {}), })), - ...createElectronSystemTraceProducers(tracker), + ...createElectronSystemTraceProducers({ + ...(tracker !== undefined ? { process: tracker } : {}), + ...(display !== undefined ? { display } : {}), + }), ]; } // 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) { + // `child_process_gone`, `power_*`, `display_*`, `window_*` and `renderer_(un)responsive`. The mux attaches (inner node + // handlers + every Electron listener) only when the provider subscribes, i.e. only while `captureSystemEvents` is on, + // and releases all of them on `client.stop()`. A caller-supplied wrapper is applied first (it sees the plain node + // source), ours wraps its result. + if (hasElectronTrackers) { const callerWrap = nodeOptions.wrapSystemEventsSource; nodeOptions.wrapSystemEventsSource = (inner) => createElectronSystemEventsSource( callerWrap === undefined ? inner : callerWrap(inner), - tracker, + { + ...(tracker !== undefined ? { process: tracker } : {}), + ...(power !== undefined ? { power } : {}), + ...(display !== undefined ? { display } : {}), + ...(application !== undefined ? { application } : {}), + }, nodeOptions.onError, ); } @@ -256,8 +345,9 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee // 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). + // every Electron trace and event (`app_metrics`, `electron_displays`, `child_process_gone`, `power_*`, `display_*`, + // `window_*`, `renderer_*`) stops 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 = () => { diff --git a/packages/electron/src/system-events.test.ts b/packages/electron/src/system-events.test.ts index 1fd81e68..2de981e6 100644 --- a/packages/electron/src/system-events.test.ts +++ b/packages/electron/src/system-events.test.ts @@ -1,6 +1,11 @@ import type { SystemEvent } from '@bugsee/capture'; import { type EventSubscribable, InterceptorBase } from '@bugsee/core'; -import { ElectronProcessTracker } from '@bugsee/trackers/electron'; +import { + ElectronApplicationTracker, + ElectronDisplayTracker, + ElectronPowerTracker, + ElectronProcessTracker, +} from '@bugsee/trackers/electron'; import { describe, expect, it, vi } from 'vitest'; import { createElectronSystemEventsSource } from './system-events'; @@ -37,7 +42,7 @@ function setup() { const onError = vi.fn(); const tracker = new ElectronProcessTracker({ app }, onError); const inner = new FakeInner(); - const mux = createElectronSystemEventsSource(inner, tracker, onError); + const mux = createElectronSystemEventsSource(inner, { process: tracker }, onError); return { app, listeners, tracker, inner, mux, onError }; } @@ -165,7 +170,7 @@ describe('createElectronSystemEventsSource (lazy mux)', () => { }; const tracker = new ElectronProcessTracker({ app }, () => {}); const inner = new FakeInner(); - const mux = createElectronSystemEventsSource(inner, tracker, sink); + const mux = createElectronSystemEventsSource(inner, { process: tracker }, sink); const off = mux.on('event', vi.fn()); vi.spyOn(inner, 'off').mockImplementation(() => { throw new Error('inner off'); @@ -203,3 +208,259 @@ describe('createElectronSystemEventsSource (lazy mux)', () => { tracker.reset(); }); }); + +// ---- domain trackers (power / display / application windows) ------------------------------------------------- + +type L = (...a: unknown[]) => void; +class FakeEmitter { + table = new Map(); + on = vi.fn((e: string, l: L) => { + this.table.set(e, [...(this.table.get(e) ?? []), l]); + }); + removeListener = vi.fn((e: string, l: L) => { + this.table.set( + e, + (this.table.get(e) ?? []).filter((x) => x !== l), + ); + }); + emit(e: string, ...a: unknown[]) { + for (const l of [...(this.table.get(e) ?? [])]) l({}, ...a); + } + total() { + return [...this.table.values()].reduce((n, l) => n + l.length, 0); + } +} +class FakeWebContents extends FakeEmitter { + constructor(public id: number) { + super(); + } + isDestroyed = () => false; +} +class FakeWindow extends FakeEmitter { + webContents: FakeWebContents; + constructor(public id: number) { + super(); + this.webContents = new FakeWebContents(id + 100); + // Electron's BrowserWindow RE-EMITS its webContents' hang pair: recording both would double every hang + this.webContents.on('unresponsive', () => this.emit('unresponsive')); + this.webContents.on('responsive', () => this.emit('responsive')); + } + isDestroyed = () => false; +} +const display = (id: number) => ({ id, size: { width: 800, height: 600 }, scaleFactor: 2 }); + +function domains(existing: FakeWindow[] = []) { + const powerMonitor = new FakeEmitter(); + const screen = Object.assign(new FakeEmitter(), { getAllDisplays: () => [display(1)] }); + const app = new FakeEmitter(); + const BrowserWindow = { getAllWindows: () => existing }; + const onError = vi.fn(); + const power = new ElectronPowerTracker({ powerMonitor }, onError); + const disp = new ElectronDisplayTracker({ screen }, onError); + const application = new ElectronApplicationTracker({ app, BrowserWindow }, onError); + const inner = new FakeInner(); + const mux = createElectronSystemEventsSource( + inner, + { power, display: disp, application }, + onError, + ); + const seen = vi.fn(); + return { + powerMonitor, + screen, + app, + inner, + mux, + seen, + onError, + subscribe: () => mux.on('event', seen), + events: () => seen.mock.calls.map((c) => c[0] as SystemEvent), + total: () => powerMonitor.total() + screen.total() + app.total(), + }; +} + +describe('createElectronSystemEventsSource: domain trackers', () => { + it('attaches NOTHING at construction, everything on the first subscriber, nothing after the last leaves', () => { + const d = domains([new FakeWindow(1)]); + expect(d.total()).toBe(0); + const off = d.subscribe(); + expect(d.powerMonitor.total()).toBe(6); + expect(d.screen.total()).toBe(3); + expect(d.app.total()).toBe(3); // browser-window-created x2 (focus, visibility) + web-contents-created + off(); + expect(d.total()).toBe(0); + expect(d.inner.deactivations).toBe(1); + }); + + it('records the six power events with no params', () => { + const d = domains(); + d.subscribe(); + for (const e of ['suspend', 'resume', 'lock-screen', 'unlock-screen', 'on-ac', 'on-battery']) { + d.powerMonitor.emit(e); + } + expect(d.events().slice(1)).toEqual([ + { name: 'power_suspend' }, + { name: 'power_resume' }, + { name: 'power_lock' }, + { name: 'power_unlock' }, + { name: 'power_ac' }, + { name: 'power_battery' }, + ]); + }); + + it('records display_added / display_removed / display_metrics_changed with the mapped display', () => { + const d = domains(); + d.subscribe(); + d.screen.emit('display-added', display(2)); + d.screen.emit('display-removed', display(3)); + d.screen.emit('display-metrics-changed', display(4), ['bounds']); + expect(d.events().slice(1)).toEqual([ + { name: 'display_added', params: { id: 2, width: 800, height: 600, scaleFactor: 2 } }, + { name: 'display_removed', params: { id: 3, width: 800, height: 600, scaleFactor: 2 } }, + { + name: 'display_metrics_changed', + params: { id: 4, width: 800, height: 600, scaleFactor: 2, changed: ['bounds'] }, + }, + ]); + }); + + it('a window created AFTER the mux attached still records focus; existing windows too; ids included', () => { + const early = new FakeWindow(1); + const d = domains([early]); + d.subscribe(); + early.emit('focus'); + const late = new FakeWindow(2); + d.app.emit('browser-window-created', late); + late.emit('focus'); + late.emit('blur'); + late.emit('hide'); + late.emit('show'); + expect(d.events().slice(1)).toEqual([ + { name: 'window_focus', params: { windowId: 1 } }, + { name: 'window_focus', params: { windowId: 2 } }, + { name: 'window_blur', params: { windowId: 2 } }, + { name: 'window_hide', params: { windowId: 2 } }, + { name: 'window_show', params: { windowId: 2 } }, + ]); + }); + + it('webContents.emit("unresponsive") records ONCE although the window re-emits it; win.emit alone records nothing', () => { + const win = new FakeWindow(1); + const d = domains([win]); + d.subscribe(); + win.emit('unresponsive'); + win.emit('responsive'); + expect(d.events()).toHaveLength(1); // only process_started + win.webContents.emit('unresponsive'); + win.webContents.emit('responsive'); + expect(d.events().slice(1)).toEqual([ + { name: 'renderer_unresponsive', params: { webContentsId: 101 } }, + { name: 'renderer_responsive', params: { webContentsId: 101 } }, + ]); + }); + + it('a web contents without a window (BrowserView) created later is recorded', () => { + const d = domains(); + d.subscribe(); + const view = new FakeWebContents(9); + d.app.emit('web-contents-created', view); + view.emit('unresponsive'); + expect(d.events().slice(1)).toEqual([ + { name: 'renderer_unresponsive', params: { webContentsId: 9 } }, + ]); + }); + + it('omits the id param when the object has none (never a made-up id)', () => { + const d = domains(); + d.subscribe(); + const noId = new FakeWindow(1); + (noId as { id: unknown }).id = undefined; + (noId.webContents as { id: unknown }).id = undefined; + d.app.emit('browser-window-created', noId); + d.app.emit('web-contents-created', noId.webContents); + noId.emit('focus'); + noId.webContents.emit('unresponsive'); + expect(d.events().slice(1)).toEqual([ + { name: 'window_focus' }, + { name: 'renderer_unresponsive' }, + ]); + }); + + it('release removes the listeners from existing and late windows and webContents too', () => { + const early = new FakeWindow(1); + const d = domains([early]); + const off = d.subscribe(); + const late = new FakeWindow(2); + d.app.emit('browser-window-created', late); + d.app.emit('web-contents-created', late.webContents); + off(); + expect(early.total()).toBe(0); + expect(late.total()).toBe(0); + expect(d.app.total()).toBe(0); + // only the test fake's own re-emit hook is left on the webContents + expect(early.webContents.total()).toBe(2); + d.app.emit('browser-window-created', new FakeWindow(3)); + early.emit('focus'); + expect(d.events()).toHaveLength(1); + }); + + it('with no domain trackers (only the process one or none) the mux attaches only the inner source', () => { + const inner = new FakeInner(); + const mux = createElectronSystemEventsSource(inner, {}); + const seen = vi.fn(); + mux.on('event', seen)(); + expect(names(seen)).toEqual(['process_started']); + expect(inner.deactivations).toBe(1); + }); +}); + +describe('createElectronSystemEventsSource: a throwing domain subscription', () => { + it('is reported, does not abort the other domains, and stop() still releases the inner source and the rest', () => { + const powerMonitor = new FakeEmitter(); + const app = new FakeEmitter(); + const onError = vi.fn(); + const power = new ElectronPowerTracker({ powerMonitor }, onError); + const application = new ElectronApplicationTracker({ app }, onError); + const display = { + on: () => { + throw new Error('display subscribe'); + }, + } as unknown as ElectronDisplayTracker; + const inner = new FakeInner(); + const mux = createElectronSystemEventsSource(inner, { power, display, application }, onError); + const seen = vi.fn(); + let off: () => void = () => {}; + expect(() => { + off = mux.on('event', seen); + }).not.toThrow(); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'display subscribe' })); + // the domains AFTER the throwing one still work + app.emit( + 'browser-window-created', + Object.assign(new FakeEmitter(), { id: 1, isDestroyed: () => false }), + ); + powerMonitor.emit('suspend'); + expect(names(seen)).toEqual(['process_started', 'power_suspend']); + off(); + expect(inner.deactivations).toBe(1); + expect(powerMonitor.total()).toBe(0); + expect(app.total()).toBe(0); + }); + + it('a throwing inner subscription is reported and the Electron domains still attach', () => { + const powerMonitor = new FakeEmitter(); + const onError = vi.fn(); + const power = new ElectronPowerTracker({ powerMonitor }, onError); + const inner = { + on: () => { + throw new Error('inner'); + }, + } as unknown as FakeInner; + const mux = createElectronSystemEventsSource(inner, { power }, onError); + const seen = vi.fn(); + expect(() => mux.on('event', seen)).not.toThrow(); + powerMonitor.emit('on-ac'); + expect(names(seen)).toEqual(['power_ac']); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'inner' })); + }); +}); diff --git a/packages/electron/src/system-events.ts b/packages/electron/src/system-events.ts index 00cf9f7f..28347386 100644 --- a/packages/electron/src/system-events.ts +++ b/packages/electron/src/system-events.ts @@ -1,6 +1,11 @@ import type { SystemEvent, SystemEventSource } from '@bugsee/capture'; import { type Interceptor, InterceptorBase } from '@bugsee/core'; -import type { ElectronProcessTracker } from '@bugsee/trackers/electron'; +import type { + ElectronApplicationTracker, + ElectronDisplayTracker, + ElectronPowerTracker, + 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 @@ -15,6 +20,19 @@ import { reportGuarded } from '@bugsee/util'; // 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()`. // +// DOMAIN TRACKERS. Besides the process tracker's `childProcessGone` it forwards the stages of the Power, Display and +// Application (window) domain trackers, each of which arms its own Electron listeners only while the mux is subscribed: +// +// power_suspend / power_resume / power_lock / power_unlock / power_ac / power_battery (no params) +// display_added / display_removed params { id, width, height, scaleFactor?, rotation?, internal?, refreshRate? } +// display_metrics_changed params { ...display, changed: string[] } (`changed` = Electron's changedMetrics) +// window_focus / window_blur / window_show / window_hide params { windowId? } +// renderer_unresponsive / renderer_responsive params { webContentsId? } (webContents ONLY: see the +// application tracker, a window re-emits the pair) +// +// Event names are snake_case like the existing `process_*`/`child_process_gone`; params stay camelCase like `exitCode`. +// A domain whose tracker is absent (no `powerMonitor`/`screen`/`app` injected) is simply off. +// // 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`). @@ -23,43 +41,112 @@ type Events = { event: SystemEvent }; class ElectronSystemEventsSource extends InterceptorBase { readonly name = 'electron-system-events'; - #offInner: (() => void) | undefined; - #offGone: (() => void) | undefined; + #offs: Array<() => void> = []; constructor( private readonly inner: SystemEventSource, - private readonly tracker: ElectronProcessTracker, + private readonly trackers: ElectronEventTrackers, private readonly onError: ((error: unknown) => void) | undefined, ) { super(onError); } + #send(name: string, params?: Record): void { + this.emit('event', params === undefined ? { name } : { name, params }); + } + + /** + * Subscribe once, isolated: a throwing subscription (a hostile Electron object) is reported and costs only itself. + * `onActivate` therefore never throws, so the provider always receives its unsubscribe and `stop()` always releases + * everything that DID attach (the inner node source's signal handlers included). + */ + #sub(subscribe: () => () => void): void { + try { + this.#offs.push(subscribe()); + } catch (error) { + reportGuarded(this.onError, error); + } + } + protected onActivate(): void { + this.#offs = []; // 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 } }), - ); + this.#sub(() => this.inner.on('event', (event) => this.emit('event', event))); + const { process, power, display, application } = this.trackers; + if (process !== undefined) { + this.#sub(() => + process.on('childProcessGone', (gone) => this.#send('child_process_gone', { ...gone })), + ); + } + if (power !== undefined) { + this.#sub(() => power.on('suspendResume', (p) => this.#send(`power_${p.state}`))); + this.#sub(() => power.on('lockScreen', (p) => this.#send(`power_${p.state}`))); + this.#sub(() => power.on('powerSource', (p) => this.#send(`power_${p.source}`))); + } + if (display !== undefined) { + this.#sub(() => display.on('displayAdded', (d) => this.#send('display_added', { ...d }))); + this.#sub(() => display.on('displayRemoved', (d) => this.#send('display_removed', { ...d }))); + this.#sub(() => + display.on('displayMetricsChanged', (m) => + this.#send('display_metrics_changed', { ...m.display, changed: [...m.changed] }), + ), + ); + } + if (application !== undefined) { + this.#sub(() => + application.on('windowFocus', (w) => + this.#send(w.focused ? 'window_focus' : 'window_blur', ids(w, 'windowId')), + ), + ); + this.#sub(() => + application.on('windowVisibility', (w) => + this.#send(w.visible ? 'window_show' : 'window_hide', ids(w, 'windowId')), + ), + ); + this.#sub(() => + application.on('rendererResponsiveness', (r) => + this.#send( + r.responsive ? 'renderer_responsive' : 'renderer_unresponsive', + ids(r, 'webContentsId'), + ), + ), + ); + } } protected override onDeactivate(): void { - const offInner = this.#offInner; - const offGone = this.#offGone; - for (const off of [offInner, offGone]) { + const offs = this.#offs; + this.#offs = []; + for (const off of offs) { try { - off?.(); + off(); } catch (error) { - reportGuarded(this.onError, error); // a throwing reporter must not skip the other release + reportGuarded(this.onError, error); // a throwing reporter must not skip the other releases } } } } +/** The id param only when the tracker had one (`{}` otherwise: never a made-up id). */ +const ids = ( + source: { windowId?: number; webContentsId?: number }, + key: 'windowId' | 'webContentsId', +): Record | undefined => + source[key] === undefined ? undefined : { [key]: source[key] }; + +/** The domain trackers the mux forwards; a domain whose tracker is absent is off. */ +export interface ElectronEventTrackers { + process?: ElectronProcessTracker; + power?: ElectronPowerTracker; + display?: ElectronDisplayTracker; + application?: ElectronApplicationTracker; +} + /** The mux. `inner` is the node `events.system` source handed to `wrapSystemEventsSource`. */ export function createElectronSystemEventsSource( inner: SystemEventSource, - tracker: ElectronProcessTracker, + trackers: ElectronEventTrackers, onError?: (error: unknown) => void, ): Interceptor { - return new ElectronSystemEventsSource(inner, tracker, onError); + return new ElectronSystemEventsSource(inner, trackers, onError); } diff --git a/packages/electron/src/system-telemetry.integration.test.ts b/packages/electron/src/system-telemetry.integration.test.ts index ef60ee1f..eee53e9f 100644 --- a/packages/electron/src/system-telemetry.integration.test.ts +++ b/packages/electron/src/system-telemetry.integration.test.ts @@ -106,6 +106,10 @@ function launchWith( scheduler?: ReturnType; carrier?: object; onError?: (error: unknown) => void; + captureSystemTraces?: boolean; + powerMonitor?: object; + screen?: object; + BrowserWindow?: { getAllWindows(): unknown }; }, fp = fakeProcess(), ) { @@ -122,6 +126,12 @@ function launchWith( systemProbe: realSystemProbe, onError: over.onError ?? vi.fn(), carrier: over.carrier ?? {}, + ...(over.powerMonitor !== undefined ? { powerMonitor: over.powerMonitor } : {}), + ...(over.screen !== undefined ? { screen: over.screen } : {}), + ...(over.BrowserWindow !== undefined ? { BrowserWindow: over.BrowserWindow } : {}), + ...(over.captureSystemTraces !== undefined + ? { captureSystemTraces: over.captureSystemTraces } + : {}), ...(over.captureSystemEvents !== undefined ? { captureSystemEvents: over.captureSystemEvents } : {}), @@ -255,3 +265,263 @@ describe('Electron main telemetry -> real node launch -> assembled report', () = expect(scheduler.armed).toBe(0); }); }); + +// ---- TR9 part 2: power / display / application-window domain trackers ------------------------------------------- + +type EL = (...a: unknown[]) => void; +class Emitter { + table = new Map(); + on = vi.fn((e: string, l: EL) => { + this.table.set(e, [...(this.table.get(e) ?? []), l]); + }); + removeListener = vi.fn((e: string, l: EL) => { + this.table.set( + e, + (this.table.get(e) ?? []).filter((x) => x !== l), + ); + }); + emit(e: string, ...a: unknown[]) { + for (const l of [...(this.table.get(e) ?? [])]) l({}, ...a); + } + count(e: string) { + return this.table.get(e)?.length ?? 0; + } + total() { + return [...this.table.values()].reduce((n, l) => n + l.length, 0); + } +} +class Contents extends Emitter { + constructor(public id: number) { + super(); + } + isDestroyed = () => false; +} +class Win extends Emitter { + webContents: Contents; + constructor(public id: number) { + super(); + this.webContents = new Contents(id + 100); + // like Electron's BrowserWindow, re-emit the webContents' hang pair + this.webContents.on('unresponsive', () => this.emit('unresponsive')); + } + isDestroyed = () => false; +} +const displayOf = (id: number) => ({ + id, + size: { width: 1440, height: 900 }, + scaleFactor: 2, + internal: true, +}); + +function domainWorld(existing: Win[] = []) { + const powerMonitor = new Emitter(); + const displays = [displayOf(1)]; + const screen = Object.assign(new Emitter(), { getAllDisplays: () => [...displays] }); + const app = new Emitter(); + const BrowserWindow = { getAllWindows: () => existing }; + return { powerMonitor, screen, app, BrowserWindow, displays }; +} +const domainListeners = (w: ReturnType) => + w.powerMonitor.total() + + w.screen.total() + + w.app.count('browser-window-created') + + w.app.count('web-contents-created'); + +describe('Electron domain trackers -> real node launch -> assembled report', () => { + const launchDomains = ( + w: ReturnType, + over: Parameters[0] = {}, + fp = fakeProcess(), + ) => + launchWith( + { + app: w.app as never, + powerMonitor: w.powerMonitor, + screen: w.screen, + BrowserWindow: w.BrowserWindow, + ...over, + }, + fp, + ); + + it('power, display and window events AND the electron_displays trace land in the uploaded bundle', async () => { + const early = new Win(1); + const w = domainWorld([early]); + const { client, puts } = launchDomains(w); + // activity after launch: power, a display plugged in, an existing window focused, a window created LATER + w.powerMonitor.emit('suspend'); + w.powerMonitor.emit('resume'); + w.powerMonitor.emit('on-battery'); + w.displays.push(displayOf(2)); + w.screen.emit('display-added', displayOf(2)); + early.emit('focus'); + const late = new Win(2); + w.app.emit('browser-window-created', late); + late.emit('blur'); + late.emit('hide'); + // the hang pair: the webContents records ONCE although the window re-emits it; the window alone records nothing + late.webContents.emit('unresponsive'); + w.app.emit('web-contents-created', late.webContents); + late.webContents.emit('unresponsive'); + late.emit('unresponsive'); + await client.logException(new Error('x')); + const events = fileOf<{ name: string; params?: Record }>( + puts[0] as Uint8Array, + 'events.system.json', + ); + const byName = (n: string) => events.filter((e) => e.name === n); + expect(byName('process_started')).toHaveLength(1); + expect(byName('power_suspend')).toHaveLength(1); + expect(byName('power_resume')).toHaveLength(1); + expect(byName('power_battery')).toHaveLength(1); + expect(byName('display_added')[0]?.params).toEqual({ + id: 2, + width: 1440, + height: 900, + scaleFactor: 2, + internal: true, + }); + expect(byName('window_focus')[0]?.params).toEqual({ windowId: 1 }); + expect(byName('window_blur')[0]?.params).toEqual({ windowId: 2 }); + expect(byName('window_hide')[0]?.params).toEqual({ windowId: 2 }); + // the very first unresponsive fired before the webContents was announced (not watched yet): exactly ONE recorded + expect(byName('renderer_unresponsive')).toEqual([ + expect.objectContaining({ params: { webContentsId: 102 } }), + ]); + const traces = fileOf<{ name: string; value: unknown }>( + puts[0] as Uint8Array, + 'traces.system.json', + ).filter((t) => t.name === 'electron_displays'); + expect(traces.map((t) => (t.value as { displays: unknown[] }).displays.length)).toEqual([1, 2]); + expect(traces[0]?.value).toEqual({ + displays: [{ id: 1, width: 1440, height: 900, scale_factor: 2, internal: true }], + }); + await client.stop(); + }); + + it('captureSystemEvents OFF: no power/window/display-event listeners (the displays TRACE keeps only its own); both off: none at all', async () => { + const w = domainWorld([new Win(1)]); + const { client } = launchDomains(w, { captureSystemEvents: false }); + expect(w.powerMonitor.total()).toBe(0); + expect(w.app.count('browser-window-created')).toBe(0); + expect(w.app.count('web-contents-created')).toBe(0); + expect(w.screen.total()).toBe(3); // the electron_displays trace producer, not the events + await client.stop(); + expect(w.screen.total()).toBe(0); + + const w2 = domainWorld([new Win(1)]); + const both = launchDomains(w2, { captureSystemEvents: false, captureSystemTraces: false }); + expect(domainListeners(w2)).toBe(0); + await both.client.stop(); + }); + + it('client.stop() releases every power, display and window listener', async () => { + const win = new Win(1); + const w = domainWorld([win]); + const { client } = launchDomains(w); + expect(w.powerMonitor.total()).toBe(6); + expect(w.screen.total()).toBe(6); // events (3) + the displays trace (3) + expect(w.app.count('browser-window-created')).toBe(2); + expect(w.app.count('web-contents-created')).toBe(1); + expect(win.total()).toBe(6); + await client.stop(); + expect(domainListeners(w)).toBe(0); + expect(win.total()).toBe(0); + expect(win.webContents.count('responsive')).toBe(0); + expect(win.webContents.count('destroyed')).toBe(0); + }); + + it("a REPEAT launchMain leaves the running launch's power/display/application trackers (reporter, listeners) untouched", async () => { + const carrier = {}; + const win = new Win(1); + const w = domainWorld([win]); + const firstOnError = vi.fn(); + const secondOnError = vi.fn(); + const first = launchDomains(w, { carrier, onError: firstOnError }); + const attached = domainListeners(w); + const second = launchDomains(w, { carrier, onError: secondOnError }); + expect(second.client).toBe(first.client); + expect(domainListeners(w)).toBe(attached); + // every removal now fails: the tracker that reports it must still be the FIRST launch's + for (const e of [w.powerMonitor, w.screen, win]) { + e.removeListener.mockImplementation(() => { + throw new Error(`remove-${e === win ? 'win' : 'x'}`); + }); + } + await first.client.stop(); + const messages = (fn: ReturnType) => + fn.mock.calls.map((c) => (c[0] as Error).message); + expect(messages(firstOnError)).toEqual(expect.arrayContaining(['remove-x', 'remove-win'])); + expect(messages(secondOnError).filter((m) => m.startsWith('remove-'))).toEqual([]); + }); + + const notReady = (message: string) => + new Proxy( + {}, + { + get() { + throw new Error(message); + }, + }, + ); + + it.each([ + ['screen', 'screen not ready'], + ['powerMonitor', 'power not ready'], + ['BrowserWindow', 'window class not ready'], + ] as const)('an Electron %s whose property reads THROW (not ready) turns only that domain off: reported, other domains work, and stop() leaves NOTHING attached', async (which, message) => { + const w = domainWorld([]); + const onError = vi.fn(); + const fp = fakeProcess(); + const hostile = notReady(message); + const { client, puts } = launchDomains( + { ...w, [which]: hostile } as ReturnType, + { onError }, + fp, + ); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message })); + // the node source is live and every healthy domain still records + expect(fp.count('warning')).toBe(1); + if (which !== 'powerMonitor') w.powerMonitor.emit('suspend'); + const win = new Win(3); + w.app.emit('browser-window-created', win); + win.emit('focus'); + await client.logException(new Error('x')); + const names = fileOf<{ name: string }>(puts[0] as Uint8Array, 'events.system.json').map( + (e) => e.name, + ); + expect(names).toContain('window_focus'); + if (which !== 'powerMonitor') expect(names).toContain('power_suspend'); + await client.stop(); + expect(fp.count('warning')).toBe(0); + expect(fp.count('beforeExit')).toBe(0); + expect(w.app.count('child-process-gone')).toBe(0); + expect(domainListeners(w)).toBe(0); + expect(win.total()).toBe(0); + if (which !== 'screen') expect(w.screen.total()).toBe(0); + if (which !== 'powerMonitor') expect(w.powerMonitor.total()).toBe(0); + }); + + it('a throwing powerMonitor/screen/BrowserWindow never fails launch; the other domains still work', async () => { + const w = domainWorld([]); + const onError = vi.fn(); + const boom = () => { + throw new Error('electron'); + }; + w.powerMonitor.on.mockImplementation(boom); + (w.screen as { getAllDisplays: () => unknown }).getAllDisplays = boom; + w.BrowserWindow.getAllWindows = boom; + const { client, puts } = launchDomains(w, { onError }); + const win = new Win(5); + w.app.emit('browser-window-created', win); + win.emit('focus'); + await client.logException(new Error('x')); + const names = fileOf<{ name: string }>(puts[0] as Uint8Array, 'events.system.json').map( + (e) => e.name, + ); + expect(names).toContain('window_focus'); + expect(names).not.toContain('power_suspend'); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'electron' })); + await client.stop(); + }); +}); diff --git a/packages/electron/src/system-traces.test.ts b/packages/electron/src/system-traces.test.ts index c5f19699..5366bf85 100644 --- a/packages/electron/src/system-traces.test.ts +++ b/packages/electron/src/system-traces.test.ts @@ -1,5 +1,5 @@ import type { TraceSink } from '@bugsee/capture'; -import { ElectronProcessTracker } from '@bugsee/trackers/electron'; +import { ElectronDisplayTracker, ElectronProcessTracker } from '@bugsee/trackers/electron'; import { describe, expect, it, vi } from 'vitest'; import { createElectronSystemTraceProducers } from './system-traces'; @@ -36,7 +36,7 @@ function setup(getAppMetrics: () => unknown) { const sink: TraceSink = { emit: (name, value, _display, options) => emitted.push({ name, value, hold: options?.hold }), }; - const producers = createElectronSystemTraceProducers(tracker); + const producers = createElectronSystemTraceProducers({ process: tracker }); return { tracker, scheduler, onError, emitted, sink, producers }; } @@ -147,3 +147,141 @@ describe('createElectronSystemTraceProducers', () => { tracker.reset(); }); }); + +// ---- electron_displays ---------------------------------------------------------------------------------------- + +describe('electron_displays producer', () => { + type L = (...a: unknown[]) => void; + const display = (over: Record = {}) => ({ + id: 1, + size: { width: 1440, height: 900 }, + scaleFactor: 2, + rotation: 90, + internal: true, + displayFrequency: 120, + label: 'secret', + ...over, + }); + function displays(list: () => unknown) { + const table = new Map(); + const screen = { + getAllDisplays: vi.fn(list), + on: vi.fn((e: string, l: L) => { + table.set(e, [...(table.get(e) ?? []), l]); + }), + removeListener: vi.fn((e: string, l: L) => { + table.set( + e, + (table.get(e) ?? []).filter((x) => x !== l), + ); + }), + }; + const onError = vi.fn(); + const tracker = new ElectronDisplayTracker({ screen }, onError); + const emitted: Array<{ name: string; value: unknown; hold: boolean | undefined }> = []; + const sink: TraceSink = { + emit: (name, value, _d, options) => emitted.push({ name, value, hold: options?.hold }), + }; + const [producer] = createElectronSystemTraceProducers({ display: tracker }); + return { + screen, + tracker, + emitted, + sink, + producer: producer as NonNullable, + fire: (e: string) => { + for (const l of [...(table.get(e) ?? [])]) l({}, display(), []); + }, + listeners: () => [...table.values()].reduce((n, l) => n + l.length, 0), + onError, + }; + } + + it('builds exactly the displays producer for a display tracker, nothing for none', () => { + const d = displays(() => [display()]); + expect(createElectronSystemTraceProducers({ display: d.tracker }).map((p) => p.name)).toEqual([ + 'electron-displays', + ]); + expect(createElectronSystemTraceProducers({})).toEqual([]); + }); + + it('touches nothing until started; then emits the baseline list as a HELD step trace with the documented shape', () => { + const d = displays(() => [ + display(), + display({ id: 2, size: { width: 10, height: 20 }, rotation: 7 }), + ]); + expect(d.screen.on).not.toHaveBeenCalled(); + d.producer.start(d.sink); + expect(d.emitted).toStrictEqual([ + { + name: 'electron_displays', + hold: true, + value: { + displays: [ + { + id: 1, + width: 1440, + height: 900, + scale_factor: 2, + rotation: 90, + internal: true, + refresh_rate_hz: 120, + }, + { id: 2, width: 10, height: 20, scale_factor: 2, internal: true, refresh_rate_hz: 120 }, + ], + }, + }, + ]); + expect(JSON.stringify(d.emitted)).not.toContain('secret'); + d.producer.stop(); + }); + + it('re-emits only when the list changed (display added/removed/metrics-changed re-read it)', () => { + let list: unknown[] = [display()]; + const d = displays(() => list); + d.producer.start(d.sink); + d.fire('display-metrics-changed'); // same list: not re-emitted + expect(d.emitted).toHaveLength(1); + list = [display(), display({ id: 2 })]; + d.fire('display-added'); + expect(d.emitted).toHaveLength(2); + list = [display()]; + d.fire('display-removed'); + expect(d.emitted).toHaveLength(3); + d.producer.stop(); + }); + + it('emits NOTHING (never an empty list) when Electron cannot give a list; a later change still lands', () => { + let list: unknown = []; + const d = displays(() => list); + d.producer.start(d.sink); + expect(d.emitted).toEqual([]); + list = [display()]; + d.fire('display-added'); + expect(d.emitted).toHaveLength(1); + d.producer.stop(); + }); + + it('a throwing getAllDisplays at start is reported and the producer still starts', () => { + const d = displays(() => { + throw new Error('displays'); + }); + expect(() => d.producer.start(d.sink)).not.toThrow(); + expect(d.emitted).toEqual([]); + expect(d.onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'displays' })); + d.producer.stop(); + }); + + it('stop() releases the screen listeners and a restart works', () => { + const d = displays(() => [display()]); + d.producer.start(d.sink); + expect(d.listeners()).toBe(3); + d.producer.stop(); + expect(d.listeners()).toBe(0); + d.fire('display-added'); + expect(d.emitted).toHaveLength(1); + d.producer.start(d.sink); + expect(d.emitted).toHaveLength(2); + d.producer.stop(); + }); +}); diff --git a/packages/electron/src/system-traces.ts b/packages/electron/src/system-traces.ts index da421d45..bb958b5f 100644 --- a/packages/electron/src/system-traces.ts +++ b/packages/electron/src/system-traces.ts @@ -1,6 +1,11 @@ import { type TraceProducer, TraceProducerBase } from '@bugsee/capture'; import { bytesToMegabytes } from '@bugsee/protocol'; -import type { AppProcessMetric, ElectronProcessTracker } from '@bugsee/trackers/electron'; +import type { + AppProcessMetric, + DisplayInfo, + ElectronDisplayTracker, + 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 @@ -21,6 +26,18 @@ import type { AppProcessMetric, ElectronProcessTracker } from '@bugsee/trackers/ // 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. +// +// `electron_displays` (JS-SPECIFIC name, deliberately NOT Android's `displays`: that name is reserved until an +// Android-shaped display list is specified and confirmed against the viewer, Q5; nothing in the JS protocol defines it): +// +// electron_displays = { displays: [{ id, width, height, scale_factor?, rotation?, internal?, refresh_rate_hz? }] } +// +// `width`/`height` are Electron's device-independent pixels (`Display.size`), `rotation` is 0/90/180/270, `refresh_rate_hz` +// is `displayFrequency`; a key is omitted when Electron did not supply it, a display with no id/size (or id -1) is dropped, and +// the trace is never `{displays: []}`. It is a HELD step trace (`emitIfChanged`): the list when the producer starts, then +// the fresh list after every display added/removed/metrics-changed. HELD-VALUE CAVEAT: it is absent only BEFORE its first +// emit. A later refresh that cannot read a usable list emits nothing and cannot retract, so the previous list stays held and +// is re-recorded every refreshMs (same open owner decision as storage_estimate / user_idle_state, docs/PROGRESS.md). /** At most two decimals: Electron's float noise is not information. */ const round2 = (value: number): number => Math.round(value * 100) / 100; @@ -61,9 +78,51 @@ class AppMetricsProducer extends TraceProducerBase { } } -/** The Electron producers, each subscribed to ONE stage of the shared tracker. */ +function wireDisplay(d: DisplayInfo): Record { + return { + id: d.id, + width: d.width, + height: d.height, + ...(d.scaleFactor !== undefined ? { scale_factor: d.scaleFactor } : {}), + ...(d.rotation !== undefined ? { rotation: d.rotation } : {}), + ...(d.internal !== undefined ? { internal: d.internal } : {}), + ...(d.refreshRate !== undefined ? { refresh_rate_hz: d.refreshRate } : {}), + }; +} + +class DisplaysProducer extends TraceProducerBase { + readonly name = 'electron-displays'; + #off: (() => void) | undefined; + constructor(private readonly tracker: ElectronDisplayTracker) { + super(); + } + protected onStart(): void { + // subscribe FIRST (arming the tracker's listeners), then the baseline read: no change can fall between the two + this.#off = this.tracker.on('displays', (list) => this.#publish(list)); + const list = this.tracker.current('displays'); + if (list !== undefined) this.#publish(list); + } + protected override onStop(): void { + this.#off?.(); + this.#off = undefined; + } + #publish(list: { displays: DisplayInfo[] }): void { + this.emitIfChanged('electron_displays', { displays: list.displays.map(wireDisplay) }); + } +} + +/** The trackers the Electron producers read; a domain whose tracker is absent is simply off. */ +export interface ElectronTraceTrackers { + process?: ElectronProcessTracker; + display?: ElectronDisplayTracker; +} + +/** The Electron producers, each subscribed to ONE stage of a shared tracker. */ export function createElectronSystemTraceProducers( - tracker: ElectronProcessTracker, + trackers: ElectronTraceTrackers, ): TraceProducer[] { - return [new AppMetricsProducer(tracker)]; + return [ + ...(trackers.process !== undefined ? [new AppMetricsProducer(trackers.process)] : []), + ...(trackers.display !== undefined ? [new DisplaysProducer(trackers.display)] : []), + ]; } diff --git a/packages/trackers/README.md b/packages/trackers/README.md index 5b248f58..dbca662d 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`; 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 `./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 domain trackers, with every Electron object injected structurally and never imported: the `ElectronProcessTracker` (`electronProcessTrackerFor`, `resetElectronProcessTracker`; stages `appMetrics`, `childProcessGone` and a once-only GPU read), the `ElectronPowerTracker` (`electronPowerTrackerFor`, keyed on `powerMonitor`; stages `suspendResume`, `lockScreen`, `powerSource` and a live `current('powerSource')`), the `ElectronDisplayTracker` (`electronDisplayTrackerFor`, keyed on `screen`; stages `displayAdded`, `displayRemoved`, `displayMetricsChanged`, `displays` and a live `current('displays')`) and the `ElectronApplicationTracker` (`electronApplicationTrackerFor`, keyed on `app`; stages `windowFocus`, `windowVisibility` and `rendererResponsiveness`, which listens on `webContents` only), plus `mapGpuInfo` and `mapDisplay`. Each stage attaches its Electron listeners only while it has a subscriber and removes them when the last leaves. 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 cc0229ed..7ad0b7f9 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 an ./electron entry (the Electron main-process ProcessTracker: app metrics, child-process-gone and the once-only GPU info read)", + "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, PowerTracker, DisplayTracker and ApplicationTracker: app metrics, child-process-gone, the once-only GPU info read, power events, displays and window focus/visibility/renderer hangs)", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", diff --git a/packages/trackers/src/electron/application-tracker.test.ts b/packages/trackers/src/electron/application-tracker.test.ts new file mode 100644 index 00000000..f75cd458 --- /dev/null +++ b/packages/trackers/src/electron/application-tracker.test.ts @@ -0,0 +1,481 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + ElectronApplicationTracker, + electronApplicationTrackerFor, + resetElectronApplicationTracker, +} from './application-tracker'; + +type L = (...a: unknown[]) => void; + +class FakeEmitter { + table = new Map(); + on = vi.fn((e: string, l: L) => { + this.table.set(e, [...(this.table.get(e) ?? []), l]); + }); + removeListener = vi.fn((e: string, l: L) => { + this.table.set( + e, + (this.table.get(e) ?? []).filter((x) => x !== l), + ); + }); + emit(e: string, ...a: unknown[]) { + for (const l of [...(this.table.get(e) ?? [])]) l({}, ...a); + } + count(e: string) { + return this.table.get(e)?.length ?? 0; + } + total() { + return [...this.table.values()].reduce((n, l) => n + l.length, 0); + } +} + +class FakeWebContents extends FakeEmitter { + constructor(public id: unknown = 100) { + super(); + } + gone = false; + isDestroyed = () => this.gone; +} + +/** A window that, like Electron's, RE-EMITS its webContents' unresponsive/responsive. */ +class FakeWindow extends FakeEmitter { + webContents: FakeWebContents; + gone = false; + constructor(public id: unknown = 1) { + super(); + this.webContents = new FakeWebContents((id as number) + 100); + this.webContents.on('unresponsive', () => this.emit('unresponsive')); + } + isDestroyed = () => this.gone; + close() { + this.gone = true; + this.webContents.gone = true; + this.emit('closed'); + this.webContents.emit('destroyed'); + } +} + +function setup(existing: FakeWindow[] = []) { + const app = new FakeEmitter(); + const BrowserWindow = { getAllWindows: vi.fn(() => existing) }; + return { app, BrowserWindow }; +} + +const keys: object[] = []; +afterEach(() => { + for (const k of keys.splice(0)) resetElectronApplicationTracker(k); +}); +const track = ( + s: ReturnType, + onError?: (e: unknown) => unknown, + withBrowserWindow = true, +) => { + keys.push(s.app); + return electronApplicationTrackerFor( + { app: s.app, ...(withBrowserWindow ? { BrowserWindow: s.BrowserWindow } : {}) }, + onError, + ); +}; + +describe('ElectronApplicationTracker', () => { + it('attaches nothing until a stage has a listener', () => { + const s = setup([new FakeWindow()]); + track(s); + expect(s.app.on).not.toHaveBeenCalled(); + expect(s.BrowserWindow.getAllWindows).not.toHaveBeenCalled(); + }); + + it('windowFocus: a window that ALREADY exists records focus/blur with its id', () => { + const win = new FakeWindow(7); + const s = setup([win]); + const t = track(s); + const seen = vi.fn(); + t.on('windowFocus', seen); + win.emit('focus'); + win.emit('blur'); + expect(seen.mock.calls.map((c) => c[0])).toEqual([ + { focused: true, windowId: 7 }, + { focused: false, windowId: 7 }, + ]); + }); + + it('windowFocus: a window created AFTER arming still records focus', () => { + const s = setup(); + const t = track(s); + const seen = vi.fn(); + t.on('windowFocus', seen); + const late = new FakeWindow(3); + s.app.emit('browser-window-created', late); + late.emit('focus'); + expect(seen).toHaveBeenCalledExactlyOnceWith({ focused: true, windowId: 3 }); + }); + + it('windowVisibility: show/hide', () => { + const win = new FakeWindow(2); + const s = setup([win]); + const t = track(s); + const seen = vi.fn(); + t.on('windowVisibility', seen); + win.emit('show'); + win.emit('hide'); + expect(seen.mock.calls.map((c) => c[0])).toEqual([ + { visible: true, windowId: 2 }, + { visible: false, windowId: 2 }, + ]); + // focus is a different stage: not listened for here + expect(win.count('focus')).toBe(0); + }); + + it('a window found both at arm time and via the creation event is bound ONCE', () => { + const win = new FakeWindow(); + const s = setup([win]); + const t = track(s); + const seen = vi.fn(); + t.on('windowFocus', seen); + s.app.emit('browser-window-created', win); + win.emit('focus'); + expect(seen).toHaveBeenCalledOnce(); + }); + + it('rendererResponsiveness: webContents.emit("unresponsive") records ONCE even though the owning window re-emits it', () => { + const win = new FakeWindow(1); + const s = setup([win]); + const t = track(s); + const seen = vi.fn(); + t.on('rendererResponsiveness', seen); + win.webContents.emit('unresponsive'); // the fake window re-emits on itself, as Electron does + expect(seen).toHaveBeenCalledExactlyOnceWith({ responsive: false, webContentsId: 101 }); + win.webContents.emit('responsive'); + expect(seen).toHaveBeenLastCalledWith({ responsive: true, webContentsId: 101 }); + }); + + it('rendererResponsiveness: win.emit("unresponsive") ALONE does not record (nothing listens on the window)', () => { + const win = new FakeWindow(); + const s = setup([win]); + const t = track(s); + const seen = vi.fn(); + t.on('rendererResponsiveness', seen); + win.emit('unresponsive'); + win.emit('responsive'); + expect(seen).not.toHaveBeenCalled(); + expect(win.count('unresponsive')).toBe(0); + expect(win.count('responsive')).toBe(0); + }); + + it('rendererResponsiveness: a web contents created later (a BrowserView/webview) is watched through web-contents-created', () => { + const s = setup(); + const t = track(s); + const seen = vi.fn(); + t.on('rendererResponsiveness', seen); + const view = new FakeWebContents(55); + s.app.emit('web-contents-created', view); + view.emit('unresponsive'); + expect(seen).toHaveBeenCalledExactlyOnceWith({ responsive: false, webContentsId: 55 }); + }); + + it('omits an id that is not a finite number, and survives an id getter that throws', () => { + const s = setup(); + const t = track(s); + const seen = vi.fn(); + t.on('windowFocus', seen); + const noId = new FakeWindow('x'); + s.app.emit('browser-window-created', noId); + noId.emit('focus'); + const boom = new FakeWindow(); + Object.defineProperty(boom, 'id', { + get() { + throw new Error('destroyed'); + }, + }); + s.app.emit('browser-window-created', boom); + boom.emit('focus'); + expect(seen.mock.calls.map((c) => c[0])).toEqual([{ focused: true }, { focused: true }]); + }); + + it('a non-finite window/webContents id (NaN, Infinity) is omitted, a finite one kept', () => { + const s = setup(); + const t = track(s); + const seen = vi.fn(); + t.on('windowFocus', seen); + for (const id of [Number.NaN, Number.POSITIVE_INFINITY, 0]) { + const w = new FakeWindow(1); + w.id = id; + s.app.emit('browser-window-created', w); + w.emit('focus'); + } + expect(seen.mock.calls.map((c) => c[0])).toEqual([ + { focused: true }, + { focused: true }, + { focused: true, windowId: 0 }, + ]); + }); + + it('a BrowserWindow whose property reads throw is reported once; windows created later are still tracked', () => { + const s = setup(); + const onError = vi.fn(); + keys.push(s.app); + const hostile = new Proxy( + {}, + { + get() { + throw new Error('not ready'); + }, + }, + ); + const t = electronApplicationTrackerFor({ app: s.app, BrowserWindow: hostile }, onError); + const seen = vi.fn(); + t.on('windowFocus', seen); + expect(onError).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ message: 'not ready' }), + ); + const late = new FakeWindow(2); + s.app.emit('browser-window-created', late); + late.emit('focus'); + expect(seen).toHaveBeenCalledOnce(); + }); + + it('an app whose property reads throw: subscribing never throws, nothing attaches, reported', () => { + const onError = vi.fn(); + const hostileApp = new Proxy( + {}, + { + get() { + throw new Error('app'); + }, + }, + ); + keys.push(hostileApp); + const t = electronApplicationTrackerFor({ app: hostileApp }, onError); + expect(() => t.on('windowFocus', () => {})).not.toThrow(); + expect(onError).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: 'app' })); + }); + + it("release removes EVERY listener: the app creation listener and each object's", () => { + const w1 = new FakeWindow(1); + const s = setup([w1]); + const t = track(s); + const off1 = t.on('windowFocus', () => {}); + const off2 = t.on('windowVisibility', () => {}); + const off3 = t.on('rendererResponsiveness', () => {}); + const late = new FakeWindow(2); + s.app.emit('browser-window-created', late); + expect(s.app.count('browser-window-created')).toBe(2); + expect(s.app.count('web-contents-created')).toBe(1); + off1(); + off2(); + off3(); + expect(s.app.total()).toBe(0); + expect(w1.count('focus') + w1.count('blur') + w1.count('show') + w1.count('hide')).toBe(0); + expect(w1.count('closed')).toBe(0); + expect(late.total()).toBe(0); + // webContents: only the fake's own re-emit hook remains (it is the test's, not ours) + expect(w1.webContents.count('unresponsive')).toBe(1); + expect(w1.webContents.count('responsive')).toBe(0); + expect(w1.webContents.count('destroyed')).toBe(0); + }); + + it('a late creation event after release is ignored', () => { + const s = setup(); + const t = track(s); + const off = t.on('windowFocus', () => {}); + const creation = s.app.table.get('browser-window-created')?.[0] as L; + off(); + const late = new FakeWindow(); + creation({}, late); + expect(late.total()).toBe(0); + }); + + it('a destroyed window is never bound, forgets itself on closed, does not leak and release does not touch it', () => { + const dead = new FakeWindow(4); + dead.gone = true; + const win = new FakeWindow(5); + const s = setup([dead, win]); + const t = track(s); + const off = t.on('windowFocus', () => {}); + expect(dead.total()).toBe(0); + expect(win.count('focus')).toBe(1); + win.close(); // 'closed' -> forgotten + win.removeListener.mockClear(); + off(); + expect(win.removeListener).not.toHaveBeenCalled(); // destroyed: nothing to remove, nothing thrown + }); + + it('a window/webContents that reports closed/destroyed is forgotten: release never touches it, even if isDestroyed is still false', () => { + const win = new FakeWindow(5); + const s = setup([win]); + const t = track(s); + const offF = t.on('windowFocus', () => {}); + const offR = t.on('rendererResponsiveness', () => {}); + win.emit('closed'); + win.webContents.emit('destroyed'); + win.removeListener.mockClear(); + win.webContents.removeListener.mockClear(); + offF(); + offR(); + expect(win.removeListener).not.toHaveBeenCalled(); + expect(win.webContents.removeListener).not.toHaveBeenCalled(); + }); + + it('release skips an object that became destroyed without ever emitting closed', () => { + const win = new FakeWindow(5); + const s = setup([win]); + const off = track(s).on('windowFocus', () => {}); + win.gone = true; + win.removeListener.mockClear(); + off(); + expect(win.removeListener).not.toHaveBeenCalled(); + }); + + it('a window that throws on isDestroyed is treated as destroyed (not bound)', () => { + const win = new FakeWindow(); + win.isDestroyed = () => { + throw new Error('gone'); + }; + const s = setup([win]); + track(s).on('windowFocus', () => {}); + expect(win.total()).toBe(0); + }); + + it('release is robust when an object throws on removal (reported, others still released)', () => { + const a = new FakeWindow(1); + const b = new FakeWindow(2); + const s = setup([a, b]); + const onError = vi.fn(); + const t = track(s, onError); + const off = t.on('windowFocus', () => {}); + a.removeListener.mockImplementation(() => { + throw new Error('remove'); + }); + off(); + expect(onError).toHaveBeenCalled(); + expect(b.count('focus')).toBe(0); + expect(s.app.count('browser-window-created')).toBe(0); + }); + + it('a throwing getAllWindows is reported, and windows created later are still tracked', () => { + const s = setup(); + s.BrowserWindow.getAllWindows.mockImplementation(() => { + throw new Error('list'); + }); + const onError = vi.fn(); + const t = track(s, onError); + const seen = vi.fn(); + t.on('windowFocus', seen); + expect(onError).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: 'list' })); + const late = new FakeWindow(); + s.app.emit('browser-window-created', late); + late.emit('focus'); + expect(seen).toHaveBeenCalledOnce(); + }); + + it('a non-array getAllWindows, a missing BrowserWindow, and a window whose webContents throws are tolerated', () => { + const s = setup(); + s.BrowserWindow.getAllWindows.mockReturnValue('nope' as never); + track(s).on('rendererResponsiveness', () => {}); + const s2 = setup(); + track(s2, undefined, false).on('windowFocus', () => {}); + expect(s2.app.count('browser-window-created')).toBe(1); + const win = new FakeWindow(); + Object.defineProperty(win, 'webContents', { + get() { + throw new Error('destroyed'); + }, + }); + const s3 = setup([win]); + const onError = vi.fn(); + track(s3, onError).on('rendererResponsiveness', () => {}); + expect(onError).not.toHaveBeenCalled(); + expect(s3.app.count('web-contents-created')).toBe(1); + }); + + it('ignores a non-object creation payload', () => { + const s = setup(); + track(s).on('windowFocus', () => {}); + expect(() => { + s.app.emit('browser-window-created', null); + s.app.emit('browser-window-created', 'x'); + s.app.emit('browser-window-created'); + }).not.toThrow(); + }); + + it('an object that cannot be listened on is skipped and reported; the rest still work', () => { + const bad = new FakeWindow(9); + bad.on = vi.fn(() => { + throw new Error('on'); + }); + const good = new FakeWindow(8); + const s = setup([bad, good]); + const onError = vi.fn(); + const seen = vi.fn(); + track(s, onError).on('windowFocus', seen); + good.emit('focus'); + expect(seen).toHaveBeenCalledOnce(); + expect(onError).toHaveBeenCalledOnce(); + }); + + it('an app that cannot be released (or has no `on`) is never attached to', () => { + const s = setup([new FakeWindow()]); + (s.app as unknown as { removeListener?: unknown }).removeListener = undefined; + track(s).on('windowFocus', () => {}); + expect(s.app.on).not.toHaveBeenCalled(); + expect(s.BrowserWindow.getAllWindows).not.toHaveBeenCalled(); + }); + + it('a tracker with no app attaches nothing', () => { + new ElectronApplicationTracker().on('windowFocus', () => {}); + }); + + describe('registry / rebind', () => { + it('is a singleton per app; throws without one', () => { + const s = setup(); + expect(track(s)).toBe(track(s)); + expect(() => electronApplicationTrackerFor({})).toThrow(TypeError); + }); + + it('a relaunch rebinds onError (latest wins, absent keeps)', () => { + const s = setup(); + const first = vi.fn(); + const second = vi.fn(); + const t = track(s, first); + track(s, second); + track(s, undefined); + t.on('windowFocus', () => { + throw new Error('sub'); + }); + const win = new FakeWindow(); + s.app.emit('browser-window-created', win); + win.emit('focus'); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledOnce(); + }); + + it('a CHANGED BrowserWindow re-arms against it; an unchanged or absent one restarts nothing', () => { + const s = setup(); + const t = track(s); + t.on('windowFocus', () => {}); + const created = s.app.on.mock.calls.length; + track(s); // same BrowserWindow + track(s, undefined, false); // absent: keeps ours + expect(s.app.on.mock.calls.length).toBe(created); + const win = new FakeWindow(6); + const other = { getAllWindows: vi.fn(() => [win]) }; + electronApplicationTrackerFor({ app: s.app, BrowserWindow: other }); + expect(other.getAllWindows).toHaveBeenCalledOnce(); + expect(s.BrowserWindow.getAllWindows).toHaveBeenCalledOnce(); // only the original arm + expect(s.app.count('browser-window-created')).toBe(1); // old creation listener released + expect(win.count('focus')).toBe(1); + }); + + it('reset releases everything and the next for() builds a fresh tracker', () => { + const win = new FakeWindow(); + const s = setup([win]); + const t = track(s); + t.on('windowFocus', () => {}); + t.on('rendererResponsiveness', () => {}); + resetElectronApplicationTracker(s.app); + expect(s.app.total()).toBe(0); + expect(win.count('focus')).toBe(0); + expect(track(s)).not.toBe(t); + }); + }); +}); diff --git a/packages/trackers/src/electron/application-tracker.ts b/packages/trackers/src/electron/application-tracker.ts new file mode 100644 index 00000000..ba72e464 --- /dev/null +++ b/packages/trackers/src/electron/application-tracker.ts @@ -0,0 +1,235 @@ +import { createTrackerRegistry } from '../tracker-registry'; +import { bindAll, ElectronStageTracker, type EmitterSource } from './stage-tracker'; + +// Electron MAIN-process APPLICATION tracker (domain tracker, design §15.2/§15.4 TR9; Android reference: +// BugseeTrackerApplication). It owns the app's WINDOWS and renderers as THREE stages, each armed only while it has a +// subscriber and released when the last leaves: +// +// windowFocus BrowserWindow 'focus' / 'blur' -> { focused: boolean, windowId? } +// windowVisibility BrowserWindow 'show' / 'hide' -> { visible: boolean, windowId? } +// rendererResponsiveness webContents 'unresponsive' / 'responsive' -> { responsive: boolean, webContentsId? } +// +// DISCOVERY. Apps typically call `launchMain` and then `createWindow()` from `whenReady()`, so a stage watches BOTH the +// objects that already exist (`BrowserWindow.getAllWindows()`, and each window's `webContents`) AND the ones created +// later (`app.on('browser-window-created')` / `app.on('web-contents-created')`). Each object is bound at most once. +// +// HANG PAIR ON `webContents` ONLY. Electron documents `unresponsive`/`responsive` on BOTH `BrowserWindow` and +// `webContents`, and `BrowserWindow` RE-EMITS the `webContents` event, so listening on both would record every hang +// twice. `webContents` is the single source because it also covers renderers with no window (a `BrowserView`, a +// ``). Only the web contents that are reachable through `app.on('web-contents-created')` or an existing +// window are watched. +// +// DESTROYED OBJECTS. An object that is (or becomes) destroyed is never bound, and is forgotten on its `closed` +// (window) / `destroyed` (webContents) event WITHOUT removing listeners from it (touching a destroyed Electron object +// throws, and its listeners died with it); at release, destroyed objects are skipped. Nothing here keeps a closed window. +// +// Ids are Electron's numeric `id`, omitted when absent: the window TITLE/URL is never read. `electron` is never +// imported: `app` and `BrowserWindow` are INJECTED structurally. SINGLETON per `app` object +// (`electronApplicationTrackerFor`); a relaunch rebinds the reporter and the `BrowserWindow` seam. + +/** The slice of Electron's `app` this tracker uses. */ +export type ApplicationAppSource = EmitterSource; + +/** The slice of Electron's `BrowserWindow` class this tracker uses: only the static `getAllWindows`. */ +export interface BrowserWindowSource { + getAllWindows?(): unknown; +} + +export interface ElectronApplicationEvents { + windowFocus: { focused: boolean; windowId?: number }; + windowVisibility: { visible: boolean; windowId?: number }; + rendererResponsiveness: { responsive: boolean; webContentsId?: number }; +} + +export interface ElectronApplicationEnv { + /** Electron's `app` (the singleton key). */ + app?: ApplicationAppSource; + /** Electron's `BrowserWindow` class, to find windows that already exist when a stage arms. */ + BrowserWindow?: BrowserWindowSource; +} + +type AppStage = keyof ElectronApplicationEvents; + +interface Watched extends EmitterSource { + id?: unknown; + isDestroyed?(): unknown; + webContents?: unknown; +} + +interface WatchConfig { + createdEvent: string; + closeEvent: string; + /** Existing objects at arm time. */ + existing(env: ElectronApplicationEnv): unknown[]; + /** Electron event -> payload, per object. */ + events: Record ElectronApplicationEvents[S]>; + idKey: 'windowId' | 'webContentsId'; +} + +const withId = (key: K, id: number | undefined): { [P in K]?: number } => + (id === undefined ? {} : { [key]: id }) as { [P in K]?: number }; + +const windowsOf = (env: ElectronApplicationEnv): unknown[] => { + const all = env.BrowserWindow?.getAllWindows?.(); + return Array.isArray(all) ? all : []; +}; + +const WATCH: { [S in AppStage]: WatchConfig } = { + windowFocus: { + createdEvent: 'browser-window-created', + closeEvent: 'closed', + existing: windowsOf, + idKey: 'windowId', + events: { + focus: (id) => ({ focused: true, ...withId('windowId', id) }), + blur: (id) => ({ focused: false, ...withId('windowId', id) }), + }, + }, + windowVisibility: { + createdEvent: 'browser-window-created', + closeEvent: 'closed', + existing: windowsOf, + idKey: 'windowId', + events: { + show: (id) => ({ visible: true, ...withId('windowId', id) }), + hide: (id) => ({ visible: false, ...withId('windowId', id) }), + }, + }, + rendererResponsiveness: { + createdEvent: 'web-contents-created', + closeEvent: 'destroyed', + existing: (env) => + windowsOf(env).map((w) => { + try { + return (w as Watched).webContents; + } catch { + return undefined; // a destroyed window throws on `webContents` + } + }), + idKey: 'webContentsId', + events: { + unresponsive: (id) => ({ responsive: false, ...withId('webContentsId', id) }), + responsive: (id) => ({ responsive: true, ...withId('webContentsId', id) }), + }, + }, +}; + +const destroyed = (obj: Watched): boolean => { + try { + return obj.isDestroyed?.() === true; + } catch { + return true; // an object that throws on the question is not one to bind to + } +}; + +const idOf = (obj: Watched): number | undefined => { + try { + return typeof obj.id === 'number' && Number.isFinite(obj.id) ? obj.id : undefined; + } catch { + return undefined; + } +}; + +export class ElectronApplicationTracker extends ElectronStageTracker { + readonly name = 'electron-application'; + protected readonly stages: readonly AppStage[] = [ + 'windowFocus', + 'windowVisibility', + 'rendererResponsiveness', + ]; + readonly #app: ApplicationAppSource | undefined; + #env: ElectronApplicationEnv; + + constructor(env: ElectronApplicationEnv = {}, onError?: (error: unknown) => unknown) { + super(onError); + this.#app = env.app; + this.#env = env; + } + + /** + * Hand the latest launch's seams to this shared tracker: a defined `onError` replaces the reporter, a defined + * `BrowserWindow` replaces ours (an undefined one never clobbers). When the `BrowserWindow` changed, every stage is + * released and re-armed against it. + */ + rebind(env: ElectronApplicationEnv, onError?: (error: unknown) => unknown): void { + this.setReporter(onError); + const next = env.BrowserWindow ?? this.#env.BrowserWindow; + if (next === this.#env.BrowserWindow) return; + this.detachAll(); + this.#env = { ...this.#env, BrowserWindow: next }; + this.sync(); + } + + protected attachStage(stage: AppStage): (() => void) | undefined { + const app = this.#app; + if (app === undefined) return undefined; + const config = WATCH[stage] as WatchConfig; + const tracked = new Map void>(); + const add = (candidate: unknown): void => { + if (typeof candidate !== 'object' || candidate === null || tracked.has(candidate)) { + return; + } + const obj = candidate as Watched; + if (destroyed(obj)) return; + const bindings = Object.entries(config.events).map(([event, payload]) => ({ + src: obj, + event, + listener: () => this.emit(stage, payload(idOf(obj)) as never), + })); + bindings.push({ + src: obj, + event: config.closeEvent, + // closed/destroyed: forget it without touching the (dead) object + listener: () => { + tracked.delete(candidate); + }, + }); + const release = bindAll(bindings, this.report); + if (release !== undefined) tracked.set(candidate, release); + }; + const releaseApp = bindAll( + [{ src: app, event: config.createdEvent, listener: (_event, created) => add(created) }], + this.report, + ); + if (releaseApp === undefined) return undefined; + try { + for (const existing of config.existing(this.#env)) add(existing); + } catch (error) { + this.report(error); // the creation listener still covers everything created from now on + } + return () => { + releaseApp(); // bindAll's release never throws: failed removals are reported inside it + for (const [candidate, release] of [...tracked]) { + if (!destroyed(candidate as Watched)) release(); + } + }; + } +} + +const registry = createTrackerRegistry(); + +/** + * The singleton ElectronApplicationTracker for `env.app` (keyed on that object; without one the call throws). Every call + * (a relaunch included) hands the shared tracker the latest launch's `onError` and `BrowserWindow`. + */ +export function electronApplicationTrackerFor( + env: ElectronApplicationEnv, + onError?: (error: unknown) => unknown, +): ElectronApplicationTracker { + const key = env.app; + if (key === undefined) throw new TypeError('electronApplicationTrackerFor needs an `app`'); + const seams: ElectronApplicationEnv = { + app: key, + ...(env.BrowserWindow !== undefined ? { BrowserWindow: env.BrowserWindow } : {}), + }; + return registry.for( + key, + () => new ElectronApplicationTracker(seams, onError), + (tracker) => tracker.rebind(seams, onError), + ); +} + +/** Test/teardown: drop the app's tracker (resetting it, so every Electron listener is released). */ +export function resetElectronApplicationTracker(key: object): void { + registry.reset(key); +} diff --git a/packages/trackers/src/electron/display-tracker.test.ts b/packages/trackers/src/electron/display-tracker.test.ts new file mode 100644 index 00000000..952c08dd --- /dev/null +++ b/packages/trackers/src/electron/display-tracker.test.ts @@ -0,0 +1,299 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + ElectronDisplayTracker, + electronDisplayTrackerFor, + mapDisplay, + resetElectronDisplayTracker, + type ScreenSource, +} from './display-tracker'; + +type L = (...a: unknown[]) => void; +const display = (over: Record = {}) => ({ + id: 1, + size: { width: 1440, height: 900 }, + bounds: { x: 0, y: 0, width: 1440, height: 900 }, + scaleFactor: 2, + rotation: 0, + internal: true, + displayFrequency: 60, + label: 'Built-in Retina Display', + ...over, +}); + +function fakeScreen(list: () => unknown = () => [display()], over: Record = {}) { + const table = new Map(); + const screen = { + getAllDisplays: vi.fn(list), + on: vi.fn((e: string, l: L) => { + table.set(e, [...(table.get(e) ?? []), l]); + }), + removeListener: vi.fn((e: string, l: L) => { + table.set( + e, + (table.get(e) ?? []).filter((x) => x !== l), + ); + }), + ...over, + }; + return { + screen: screen as ScreenSource & typeof screen, + fire: (e: string, ...a: unknown[]) => { + for (const l of [...(table.get(e) ?? [])]) l({}, ...a); + }, + count: (e: string) => table.get(e)?.length ?? 0, + total: () => [...table.values()].reduce((n, l) => n + l.length, 0), + }; +} + +const keys: object[] = []; +afterEach(() => { + for (const k of keys.splice(0)) resetElectronDisplayTracker(k); +}); +const track = (s: ReturnType, onError?: (e: unknown) => unknown) => { + keys.push(s.screen); + return electronDisplayTrackerFor({ screen: s.screen }, onError); +}; + +describe('mapDisplay', () => { + it('keeps id, size, scale, rotation, internal and refresh rate; drops label/bounds/workArea', () => { + expect(mapDisplay(display({ workArea: { x: 0 } }))).toEqual({ + id: 1, + width: 1440, + height: 900, + scaleFactor: 2, + rotation: 0, + internal: true, + refreshRate: 60, + }); + }); + it('falls back to bounds for the size and omits absent/unusable optional fields', () => { + expect( + mapDisplay({ + id: 3, + bounds: { width: 800, height: 600 }, + scaleFactor: 0, + rotation: 45, + internal: 'yes', + displayFrequency: Number.NaN, + }), + ).toEqual({ id: 3, width: 800, height: 600 }); + }); + it('accepts every rotation Electron defines', () => { + for (const r of [0, 90, 180, 270]) + expect(mapDisplay(display({ rotation: r }))?.rotation).toBe(r); + }); + it('drops id -1 (invalid / not yet known) but keeps -10 (the virtual unified display)', () => { + expect(mapDisplay(display({ id: -1 }))).toBeUndefined(); + expect(mapDisplay(display({ id: -10 }))?.id).toBe(-10); + expect(mapDisplay(display({ id: 0 }))?.id).toBe(0); + }); + it('is undefined without a finite id or a positive size, and for non-objects', () => { + expect(mapDisplay(display({ id: undefined }))).toBeUndefined(); + expect(mapDisplay(display({ id: Number.NaN }))).toBeUndefined(); + expect(mapDisplay(display({ size: { width: 0, height: 5 } }))).toBeUndefined(); + expect(mapDisplay(display({ size: { width: 5, height: -1 } }))).toBeUndefined(); + expect(mapDisplay({ id: 1 })).toBeUndefined(); + expect(mapDisplay(null)).toBeUndefined(); + expect(mapDisplay('x')).toBeUndefined(); + }); +}); + +describe('ElectronDisplayTracker', () => { + it('attaches nothing until a stage has a listener', () => { + const s = fakeScreen(); + track(s); + expect(s.screen.on).not.toHaveBeenCalled(); + }); + + it('displayAdded: maps the new display and attaches only display-added', () => { + const s = fakeScreen(); + const t = track(s); + const seen = vi.fn(); + const off = t.on('displayAdded', seen); + expect(s.total()).toBe(1); + s.fire('display-added', display({ id: 2, label: 'secret' })); + expect(seen).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ id: 2, width: 1440, height: 900 }), + ); + expect(seen.mock.calls[0]?.[0]).not.toHaveProperty('label'); + off(); + expect(s.total()).toBe(0); + }); + + it('displayRemoved: maps the removed display', () => { + const s = fakeScreen(); + const t = track(s); + const seen = vi.fn(); + t.on('displayRemoved', seen); + expect(s.count('display-removed')).toBe(1); + s.fire('display-removed', display({ id: 9 })); + expect(seen).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ id: 9 })); + }); + + it('displayMetricsChanged: carries the display and the changed metrics (strings only)', () => { + const s = fakeScreen(); + const t = track(s); + const seen = vi.fn(); + t.on('displayMetricsChanged', seen); + s.fire('display-metrics-changed', display({ id: 4 }), ['bounds', 7, 'scaleFactor']); + s.fire('display-metrics-changed', display({ id: 4 }), 'not-an-array'); + expect(seen.mock.calls.map((c) => c[0].changed)).toEqual([['bounds', 'scaleFactor'], []]); + expect(seen.mock.calls[0]?.[0].display.id).toBe(4); + }); + + it('an unmappable display argument is ignored, not emitted', () => { + const s = fakeScreen(); + const t = track(s); + const seen = vi.fn(); + t.on('displayAdded', seen); + s.fire('display-added', { id: 'x' }); + s.fire('display-added'); + expect(seen).not.toHaveBeenCalled(); + }); + + it('displays: re-reads the fresh list after each of the three changes', () => { + let list: unknown[] = [display()]; + const s = fakeScreen(() => list); + const t = track(s); + const seen = vi.fn(); + const off = t.on('displays', seen); + expect(s.total()).toBe(3); + list = [display(), display({ id: 2 })]; + s.fire('display-added', display({ id: 2 })); + expect(seen.mock.calls[0]?.[0].displays.map((d: { id: number }) => d.id)).toEqual([1, 2]); + list = [display()]; + s.fire('display-removed', display({ id: 2 })); + s.fire('display-metrics-changed', display(), ['bounds']); + expect(seen).toHaveBeenCalledTimes(3); + expect(seen.mock.calls[2]?.[0].displays).toHaveLength(1); + off(); + expect(s.total()).toBe(0); + }); + + it('displays: emits nothing when the list cannot be read (omit, never an empty list)', () => { + let list: unknown = [display()]; + const s = fakeScreen(() => list); + const t = track(s); + const seen = vi.fn(); + t.on('displays', seen); + list = []; + s.fire('display-added', display()); + list = 'nope'; + s.fire('display-added', display()); + expect(seen).not.toHaveBeenCalled(); + }); + + it('stages sharing an Electron event each keep their own listener (releasing one leaves the other)', () => { + const s = fakeScreen(); + const t = track(s); + const off = t.on('displayAdded', () => {}); + t.on('displays', () => {}); + expect(s.count('display-added')).toBe(2); + off(); + expect(s.count('display-added')).toBe(1); + }); + + describe("current('displays')", () => { + it('is the live mapped list, dropping unusable entries', () => { + const s = fakeScreen(() => [display(), { id: 2 }, display({ id: 3 })]); + expect( + track(s) + .current('displays') + ?.displays.map((d) => d.id), + ).toEqual([1, 3]); + }); + it('is undefined for an empty list, a non-array, no getAllDisplays, or an unknown stage', () => { + expect(track(fakeScreen(() => [])).current('displays')).toBeUndefined(); + expect(track(fakeScreen(() => ({}))).current('displays')).toBeUndefined(); + const quiet = vi.fn(); + expect( + track(fakeScreen(undefined, { getAllDisplays: undefined }), quiet).current('displays'), + ).toBeUndefined(); + expect(quiet).not.toHaveBeenCalled(); // a missing method is absence, not an error + expect(track(fakeScreen()).current('x' as 'displays')).toBeUndefined(); + expect(new ElectronDisplayTracker().current('displays')).toBeUndefined(); + }); + it('reports a throwing read and answers undefined', () => { + const onError = vi.fn(); + const s = fakeScreen(() => { + throw new Error('read'); + }); + expect(track(s, onError).current('displays')).toBeUndefined(); + expect(onError).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: 'read' })); + }); + }); + + it('a screen that cannot be released, or has no `on`, is never attached to', () => { + const noRelease = fakeScreen(undefined, { removeListener: undefined }); + track(noRelease).on('displayAdded', () => {}); + expect(noRelease.screen.on).not.toHaveBeenCalled(); + const noOn = fakeScreen(undefined, { on: undefined }); + expect(() => track(noOn).on('displays', () => {})).not.toThrow(); + }); + + it('a tracker with no screen attaches nothing', () => { + new ElectronDisplayTracker().on('displayAdded', () => {}); + }); + + describe('a screen whose property reads throw (Electron before app ready)', () => { + const hostile = (message: string) => + new Proxy( + {}, + { + get() { + throw new Error(message); + }, + }, + ) as ScreenSource; + + it('subscribing never throws, nothing attaches, one report per stage attempt', () => { + const onError = vi.fn(); + const screen = hostile('screen'); + keys.push(screen); + const t = electronDisplayTrackerFor({ screen }, onError); + expect(() => t.on('displayAdded', () => {})).not.toThrow(); + expect(onError).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ message: 'screen' }), + ); + }); + + it("current('displays') is undefined and reported: the getAllDisplays read is inside the guard", () => { + const onError = vi.fn(); + const screen = hostile('read'); + keys.push(screen); + const t = electronDisplayTrackerFor({ screen }, onError); + expect(t.current('displays')).toBeUndefined(); + expect(onError).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: 'read' })); + }); + }); + + it('a list that is not an array (null, undefined, an object) is simply no list: undefined and NOT reported', () => { + for (const value of [null, undefined, {}, 'x']) { + const onError = vi.fn(); + const s = fakeScreen(() => value); + expect(track(s, onError).current('displays')).toBeUndefined(); + expect(onError).not.toHaveBeenCalled(); + } + }); + + describe('registry', () => { + it('is a singleton per screen; throws without one; relaunch rebinds onError; reset releases', () => { + const s = fakeScreen(); + const first = vi.fn(); + const second = vi.fn(); + const t = track(s, first); + expect(track(s, second)).toBe(t); + track(s); + expect(() => electronDisplayTrackerFor({})).toThrow(TypeError); + t.on('displayAdded', () => { + throw new Error('sub'); + }); + s.fire('display-added', display()); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledOnce(); + resetElectronDisplayTracker(s.screen); + expect(s.total()).toBe(0); + expect(track(s)).not.toBe(t); + }); + }); +}); diff --git a/packages/trackers/src/electron/display-tracker.ts b/packages/trackers/src/electron/display-tracker.ts new file mode 100644 index 00000000..ae8246ec --- /dev/null +++ b/packages/trackers/src/electron/display-tracker.ts @@ -0,0 +1,196 @@ +import { createTrackerRegistry } from '../tracker-registry'; +import { bindAll, ElectronStageTracker, type EmitterSource } from './stage-tracker'; + +// Electron MAIN-process DISPLAY tracker (domain tracker, design §15.2/§15.4 TR9; Android reference: BugseeTrackerDisplay). +// It owns what Electron's `screen` can say, as FOUR stages, each arming its own `screen` listeners only while it has a +// subscriber: +// +// displayAdded 'display-added' -> DisplayInfo +// displayRemoved 'display-removed' -> DisplayInfo +// displayMetricsChanged 'display-metrics-changed' -> { display: DisplayInfo, changed: string[] } +// displays any of the three above -> { displays: DisplayInfo[] } (the fresh `getAllDisplays()` list) +// +// `current('displays')` is a LIVE `screen.getAllDisplays()` read. {@link DisplayInfo} keeps only what is safe and stable: +// `id`, `width`/`height` (Electron's `size`, device-independent pixels; `bounds` as a fallback), and, when Electron gave +// them, `scaleFactor`, `rotation` (0/90/180/270), `internal`, `refreshRate` (Hz). A display with no usable id or size is +// DROPPED (id -1 is Electron's 'invalid or not yet known' marker; id -10, the virtual unified display, is kept as +// reported), an empty list is `undefined`, and a throwing/hostile `getAllDisplays` is reported and omitted: nothing is +// fabricated and absence is never zero. Display `label`, `bounds` position and `workArea` are not kept. +// `electron` is never imported: `screen` is INJECTED as a structural {@link ScreenSource}. +// +// HELD-VALUE CAVEAT for the `electron_displays` trace built on `displays`: a refresh that cannot read a usable list +// emits nothing, so the previous list stays held (and is re-recorded every refreshMs). Absence is true only BEFORE the first +// emit. This is the same open owner decision as storage_estimate / user_idle_state (docs/PROGRESS.md). +// +// SINGLETON per `screen` object (`electronDisplayTrackerFor`); a relaunch only rebinds the reporter. + +/** The slice of Electron's `screen` this tracker reads. */ +export interface ScreenSource extends EmitterSource { + getAllDisplays?(): unknown; +} + +export interface DisplayInfo { + id: number; + /** Device-independent pixels (Electron's `size`). */ + width: number; + height: number; + scaleFactor?: number; + rotation?: 0 | 90 | 180 | 270; + internal?: boolean; + /** Hz. */ + refreshRate?: number; +} + +export interface ElectronDisplayEvents { + displayAdded: DisplayInfo; + displayRemoved: DisplayInfo; + displayMetricsChanged: { display: DisplayInfo; changed: string[] }; + displays: { displays: DisplayInfo[] }; +} + +export interface ElectronDisplayEnv { + /** Electron's `screen` (or a structural fake). */ + screen?: ScreenSource; +} + +type DisplayStage = keyof ElectronDisplayEvents; + +const record = (value: unknown): Record | undefined => + typeof value === 'object' && value !== null ? (value as Record) : undefined; + +const finite = (value: unknown): number | undefined => + typeof value === 'number' && Number.isFinite(value) ? value : undefined; + +const positive = (value: unknown): number | undefined => { + const n = finite(value); + return n !== undefined && n > 0 ? n : undefined; +}; + +/** Maps one Electron `Display`; undefined unless it has an id and a positive size. */ +export function mapDisplay(raw: unknown): DisplayInfo | undefined { + const d = record(raw); + if (d === undefined) return undefined; + const id = finite(d.id); + // -1 is Electron's 'invalid or not yet known' id: never a real display. (-10 is the virtual unified display and is kept.) + if (id === -1) return undefined; + const size = record(d.size) ?? record(d.bounds); + const width = positive(size?.width); + const height = positive(size?.height); + if (id === undefined || width === undefined || height === undefined) return undefined; + const scaleFactor = positive(d.scaleFactor); + const rotation = + d.rotation === 0 || d.rotation === 90 || d.rotation === 180 || d.rotation === 270 + ? d.rotation + : undefined; + const refreshRate = positive(d.displayFrequency); + return { + id, + width, + height, + ...(scaleFactor !== undefined ? { scaleFactor } : {}), + ...(rotation !== undefined ? { rotation } : {}), + ...(typeof d.internal === 'boolean' ? { internal: d.internal } : {}), + ...(refreshRate !== undefined ? { refreshRate } : {}), + }; +} + +export class ElectronDisplayTracker extends ElectronStageTracker { + readonly name = 'electron-display'; + protected readonly stages: readonly DisplayStage[] = [ + 'displayAdded', + 'displayRemoved', + 'displayMetricsChanged', + 'displays', + ]; + readonly #screen: ScreenSource | undefined; + + constructor(env: ElectronDisplayEnv = {}, onError?: (error: unknown) => unknown) { + super(onError); + this.#screen = env.screen; + } + + /** Hand the latest launch's reporter to this shared tracker (a defined `onError` replaces it, undefined keeps it). */ + rebind(onError?: (error: unknown) => unknown): void { + this.setReporter(onError); + } + + /** The live display list, or undefined when Electron cannot say (never an empty/zero list). */ + current(stage: 'displays'): ElectronDisplayEvents['displays'] | undefined { + const screen = this.#screen; + if (stage !== 'displays' || screen === undefined) return undefined; + try { + // inside the guard: Electron's real `screen` throws on ANY property read before the app is ready + if (typeof screen.getAllDisplays !== 'function') return undefined; + const raw = screen.getAllDisplays(); + if (!Array.isArray(raw)) return undefined; + const displays = raw.map(mapDisplay).filter((d): d is DisplayInfo => d !== undefined); + return displays.length > 0 ? { displays } : undefined; + } catch (error) { + this.report(error); + return undefined; + } + } + + protected attachStage(stage: DisplayStage): (() => void) | undefined { + const screen = this.#screen; + if (screen === undefined) return undefined; + const events: Array<[string, (...args: unknown[]) => void]> = []; + const mapped = + (fn: (display: DisplayInfo, args: unknown[]) => void) => + (...args: unknown[]) => { + const display = mapDisplay(args[1]); + if (display !== undefined) fn(display, args); + }; + if (stage === 'displayAdded') { + events.push(['display-added', mapped((d) => this.emit('displayAdded', d))]); + } else if (stage === 'displayRemoved') { + events.push(['display-removed', mapped((d) => this.emit('displayRemoved', d))]); + } else if (stage === 'displayMetricsChanged') { + events.push([ + 'display-metrics-changed', + mapped((display, args) => + this.emit('displayMetricsChanged', { display, changed: changedList(args[2]) }), + ), + ]); + } else { + const refresh = (): void => { + const list = this.current('displays'); + if (list !== undefined) this.emit('displays', list); + }; + for (const event of ['display-added', 'display-removed', 'display-metrics-changed']) { + events.push([event, refresh]); + } + } + return bindAll( + events.map(([event, listener]) => ({ src: screen, event, listener })), + this.report, + ); + } +} + +const changedList = (value: unknown): string[] => + Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []; + +const registry = createTrackerRegistry(); + +/** + * The singleton ElectronDisplayTracker for `env.screen` (keyed on that object; without one the call throws). Every call + * (a relaunch included) hands the shared tracker the latest launch's `onError`. + */ +export function electronDisplayTrackerFor( + env: ElectronDisplayEnv, + onError?: (error: unknown) => unknown, +): ElectronDisplayTracker { + const key = env.screen; + if (key === undefined) throw new TypeError('electronDisplayTrackerFor needs a `screen`'); + return registry.for( + key, + () => new ElectronDisplayTracker(env, onError), + (tracker) => tracker.rebind(onError), + ); +} + +/** Test/teardown: drop the screen's tracker (resetting it, so every Electron listener is released). */ +export function resetElectronDisplayTracker(key: object): void { + registry.reset(key); +} diff --git a/packages/trackers/src/electron/index.test.ts b/packages/trackers/src/electron/index.test.ts index 351ede96..c77e0301 100644 --- a/packages/trackers/src/electron/index.test.ts +++ b/packages/trackers/src/electron/index.test.ts @@ -5,9 +5,19 @@ import * as electronEntry from './index'; describe('@bugsee/trackers/electron public surface', () => { it('exports the electron tracker values', () => { expect(Object.keys(electronEntry).sort()).toEqual([ + 'ElectronApplicationTracker', + 'ElectronDisplayTracker', + 'ElectronPowerTracker', 'ElectronProcessTracker', + 'electronApplicationTrackerFor', + 'electronDisplayTrackerFor', + 'electronPowerTrackerFor', 'electronProcessTrackerFor', + 'mapDisplay', 'mapGpuInfo', + 'resetElectronApplicationTracker', + 'resetElectronDisplayTracker', + 'resetElectronPowerTracker', 'resetElectronProcessTracker', ]); }); diff --git a/packages/trackers/src/electron/index.ts b/packages/trackers/src/electron/index.ts index 859d28d9..c4e61434 100644 --- a/packages/trackers/src/electron/index.ts +++ b/packages/trackers/src/electron/index.ts @@ -1,8 +1,37 @@ // `@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 +// src/electron/ and are exported from here. Electron is never imported: the `app`, `powerMonitor`, `screen` and +// `BrowserWindow` objects are injected as structural sources (`ElectronAppSource`, `PowerMonitorSource`, `ScreenSource`, +// `BrowserWindowSource`), so this entry has no dependency on `electron` or the DOM. The portable root entry must never // import from this directory. + +export { + type ApplicationAppSource, + type BrowserWindowSource, + type ElectronApplicationEnv, + type ElectronApplicationEvents, + ElectronApplicationTracker, + electronApplicationTrackerFor, + resetElectronApplicationTracker, +} from './application-tracker'; +export { + type DisplayInfo, + type ElectronDisplayEnv, + type ElectronDisplayEvents, + ElectronDisplayTracker, + electronDisplayTrackerFor, + mapDisplay, + resetElectronDisplayTracker, + type ScreenSource, +} from './display-tracker'; export { type ElectronGpu, mapGpuInfo } from './gpu-info'; +export { + type ElectronPowerEnv, + type ElectronPowerEvents, + ElectronPowerTracker, + electronPowerTrackerFor, + type PowerMonitorSource, + resetElectronPowerTracker, +} from './power-tracker'; export { type AppProcessMetric, type ChildProcessGone, diff --git a/packages/trackers/src/electron/power-tracker.test.ts b/packages/trackers/src/electron/power-tracker.test.ts new file mode 100644 index 00000000..f115fe29 --- /dev/null +++ b/packages/trackers/src/electron/power-tracker.test.ts @@ -0,0 +1,248 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + ElectronPowerTracker, + electronPowerTrackerFor, + type PowerMonitorSource, + resetElectronPowerTracker, +} from './power-tracker'; + +type L = (...a: unknown[]) => void; +function fakeMonitor(over: Record = {}) { + const table = new Map(); + const monitor = { + on: vi.fn((e: string, l: L) => { + table.set(e, [...(table.get(e) ?? []), l]); + }), + removeListener: vi.fn((e: string, l: L) => { + table.set( + e, + (table.get(e) ?? []).filter((x) => x !== l), + ); + }), + isOnBatteryPower: vi.fn((): unknown => false), + ...over, + }; + return { + monitor: monitor as PowerMonitorSource & typeof monitor, + fire: (e: string) => { + for (const l of [...(table.get(e) ?? [])]) l(); + }, + count: (e: string) => table.get(e)?.length ?? 0, + total: () => [...table.values()].reduce((n, l) => n + l.length, 0), + }; +} + +const keys: object[] = []; +afterEach(() => { + for (const k of keys.splice(0)) resetElectronPowerTracker(k); +}); +const track = (m: ReturnType, onError?: (e: unknown) => unknown) => { + keys.push(m.monitor); + return electronPowerTrackerFor({ powerMonitor: m.monitor }, onError); +}; + +describe('ElectronPowerTracker', () => { + it('attaches NOTHING until a stage has a listener', () => { + const m = fakeMonitor(); + track(m); + expect(m.monitor.on).not.toHaveBeenCalled(); + }); + + it('suspendResume: maps suspend/resume, attaches only its own two events, releases on the last unsubscribe', () => { + const m = fakeMonitor(); + const t = track(m); + const seen = vi.fn(); + const off = t.on('suspendResume', seen); + expect(m.count('suspend')).toBe(1); + expect(m.count('resume')).toBe(1); + expect(m.total()).toBe(2); + m.fire('suspend'); + m.fire('resume'); + expect(seen.mock.calls.map((c) => c[0])).toEqual([{ state: 'suspend' }, { state: 'resume' }]); + off(); + expect(m.total()).toBe(0); + m.fire('suspend'); + expect(seen).toHaveBeenCalledTimes(2); + }); + + it('lockScreen: maps lock-screen/unlock-screen', () => { + const m = fakeMonitor(); + const t = track(m); + const seen = vi.fn(); + t.on('lockScreen', seen); + m.fire('lock-screen'); + m.fire('unlock-screen'); + expect(seen.mock.calls.map((c) => c[0])).toEqual([{ state: 'lock' }, { state: 'unlock' }]); + expect(m.total()).toBe(2); + }); + + it('powerSource: maps on-ac/on-battery', () => { + const m = fakeMonitor(); + const t = track(m); + const seen = vi.fn(); + t.on('powerSource', seen); + m.fire('on-battery'); + m.fire('on-ac'); + expect(seen.mock.calls.map((c) => c[0])).toEqual([{ source: 'battery' }, { source: 'ac' }]); + expect(m.total()).toBe(2); + }); + + it('each emission is a fresh object (mutating one never corrupts the next)', () => { + const m = fakeMonitor(); + const t = track(m); + const states: string[] = []; + t.on('suspendResume', (p) => { + states.push(p.state); + (p as { state: string }).state = 'mutated'; + }); + m.fire('suspend'); + m.fire('suspend'); + expect(states).toEqual(['suspend', 'suspend']); + }); + + it('stages are independent: releasing one leaves the others attached', () => { + const m = fakeMonitor(); + const t = track(m); + const off = t.on('lockScreen', () => {}); + t.on('powerSource', () => {}); + off(); + expect(m.count('lock-screen')).toBe(0); + expect(m.count('on-ac')).toBe(1); + }); + + it('a throwing attach is reported, nothing stays attached, and the next listener change retries', () => { + let fail = true; + const m = fakeMonitor(); + const original = m.monitor.on.getMockImplementation() as (e: string, l: L) => void; + m.monitor.on.mockImplementation((e: string, l: L) => { + if (fail && e === 'resume') throw new Error('attach'); + original(e, l); + }); + const onError = vi.fn(); + const t = track(m, onError); + t.on('suspendResume', () => {}); + expect(onError).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: 'attach' })); + expect(m.total()).toBe(0); + fail = false; + t.on('lockScreen', () => {}); + expect(m.count('suspend')).toBe(1); // suspendResume re-armed by the retry + }); + + it('a monitor that cannot be released is never attached to', () => { + const m = fakeMonitor({ removeListener: undefined }); + const t = track(m); + t.on('suspendResume', () => {}); + expect(m.monitor.on).not.toHaveBeenCalled(); + }); + + it('a monitor without `on` simply has no events', () => { + const m = fakeMonitor({ on: undefined }); + const t = track(m); + expect(() => t.on('powerSource', () => {})).not.toThrow(); + }); + + it('a tracker built with no monitor (direct construction) attaches nothing', () => { + const t = new ElectronPowerTracker(); + t.on('suspendResume', () => {}); + expect(t.current('powerSource')).toBeUndefined(); + }); + + describe("current('powerSource')", () => { + it('reads isOnBatteryPower live', () => { + const m = fakeMonitor(); + const t = track(m); + m.monitor.isOnBatteryPower.mockReturnValue(true); + expect(t.current('powerSource')).toEqual({ source: 'battery' }); + m.monitor.isOnBatteryPower.mockReturnValue(false); + expect(t.current('powerSource')).toEqual({ source: 'ac' }); + }); + it('is undefined (never guessed) without the method, with a non-boolean, or when it throws (reported)', () => { + const quiet = vi.fn(); + expect( + track(fakeMonitor({ isOnBatteryPower: undefined }), quiet).current('powerSource'), + ).toBeUndefined(); + expect(quiet).not.toHaveBeenCalled(); // a missing method is absence, not an error + const odd = fakeMonitor({ isOnBatteryPower: () => 'yes' }); + expect(track(odd).current('powerSource')).toBeUndefined(); + const onError = vi.fn(); + const bad = fakeMonitor({ + isOnBatteryPower: () => { + throw new Error('read'); + }, + }); + expect(track(bad, onError).current('powerSource')).toBeUndefined(); + expect(onError).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: 'read' })); + }); + it('rejects an unknown stage name', () => { + const t = track(fakeMonitor()); + expect(t.current('other' as 'powerSource')).toBeUndefined(); + }); + }); + + describe('a monitor whose property reads throw (host object not ready)', () => { + const hostile = (message: string) => + new Proxy( + {}, + { + get() { + throw new Error(message); + }, + }, + ) as PowerMonitorSource; + + it('subscribing never throws, nothing attaches, the failure is reported once per attempt', () => { + const onError = vi.fn(); + const monitor = hostile('power'); + keys.push(monitor); + const t = electronPowerTrackerFor({ powerMonitor: monitor }, onError); + expect(() => t.on('suspendResume', () => {})).not.toThrow(); + expect(onError).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ message: 'power' }), + ); + }); + + it("current('powerSource') answers undefined and reports (the property read is inside the guard)", () => { + const onError = vi.fn(); + const monitor = hostile('read'); + keys.push(monitor); + const t = electronPowerTrackerFor({ powerMonitor: monitor }, onError); + expect(t.current('powerSource')).toBeUndefined(); + expect(onError).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: 'read' })); + }); + }); + + describe('registry', () => { + it('is a singleton per monitor object; different monitors are independent', () => { + const a = fakeMonitor(); + const b = fakeMonitor(); + expect(track(a)).toBe(track(a)); + expect(track(a)).not.toBe(track(b)); + }); + it('throws without a monitor', () => { + expect(() => electronPowerTrackerFor({})).toThrow(TypeError); + }); + it('a relaunch rebinds onError (latest wins) and an absent one keeps the earlier', () => { + const m = fakeMonitor(); + const first = vi.fn(); + const second = vi.fn(); + const t = track(m, first); + track(m, second); + track(m, undefined); + t.on('suspendResume', () => { + throw new Error('sub'); + }); + m.fire('suspend'); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledOnce(); + }); + it('reset releases every listener and the next for() builds a fresh tracker', () => { + const m = fakeMonitor(); + const t = track(m); + t.on('suspendResume', () => {}); + t.on('powerSource', () => {}); + resetElectronPowerTracker(m.monitor); + expect(m.total()).toBe(0); + expect(track(m)).not.toBe(t); + }); + }); +}); diff --git a/packages/trackers/src/electron/power-tracker.ts b/packages/trackers/src/electron/power-tracker.ts new file mode 100644 index 00000000..22f3fe1e --- /dev/null +++ b/packages/trackers/src/electron/power-tracker.ts @@ -0,0 +1,122 @@ +import { createTrackerRegistry } from '../tracker-registry'; +import { bindAll, ElectronStageTracker, type EmitterSource } from './stage-tracker'; + +// Electron MAIN-process POWER tracker (domain tracker, design §15.2/§15.4 TR9; Android reference: BugseeTrackerPower). +// It owns what Electron's `powerMonitor` can say, as THREE stages, each arming its own pair of `powerMonitor` +// listeners only while it has a subscriber and releasing them when the last leaves: +// +// suspendResume 'suspend' / 'resume' -> { state: 'suspend' | 'resume' } +// lockScreen 'lock-screen' / 'unlock-screen' -> { state: 'lock' | 'unlock' } (macOS/Windows; never fires on Linux) +// powerSource 'on-ac' / 'on-battery' -> { source: 'ac' | 'battery' } +// +// `current('powerSource')` is a LIVE read of `powerMonitor.isOnBatteryPower()`; it answers undefined when the monitor has +// no such method, it throws (reported) or returns a non-boolean: a source is never guessed. `thermal-state-change` and +// `speed-limit-change` are deliberately NOT mapped: they are macOS-only and the thermal state is not Android's int enum. +// PLATFORM DEPENDENT: per Electron's typings `on-ac` is documented for macOS and Windows and `on-battery` for macOS +// only, so on Linux (and `on-battery` on Windows) the event may simply never fire; `lock-screen`/`unlock-screen` are +// macOS/Windows. Absence of an event is never evidence of a state: read `current('powerSource')` for the live value. +// `electron` is never imported: the monitor is INJECTED as a structural {@link PowerMonitorSource}. +// +// SINGLETON per `powerMonitor` object (`electronPowerTrackerFor`); a relaunch only rebinds the reporter. + +/** The slice of Electron's `powerMonitor` this tracker reads. Every member is optional: an absent one means the stage is absent. */ +export interface PowerMonitorSource extends EmitterSource { + isOnBatteryPower?(): unknown; +} + +export interface ElectronPowerEvents { + suspendResume: { state: 'suspend' | 'resume' }; + lockScreen: { state: 'lock' | 'unlock' }; + powerSource: { source: 'ac' | 'battery' }; +} + +export interface ElectronPowerEnv { + /** Electron's `powerMonitor` (or a structural fake). */ + powerMonitor?: PowerMonitorSource; +} + +type PowerStage = keyof ElectronPowerEvents; + +const STAGE_EVENTS: Record> = { + suspendResume: [ + ['suspend', { state: 'suspend' }], + ['resume', { state: 'resume' }], + ], + lockScreen: [ + ['lock-screen', { state: 'lock' }], + ['unlock-screen', { state: 'unlock' }], + ], + powerSource: [ + ['on-ac', { source: 'ac' }], + ['on-battery', { source: 'battery' }], + ], +}; + +export class ElectronPowerTracker extends ElectronStageTracker { + readonly name = 'electron-power'; + protected readonly stages: readonly PowerStage[] = ['suspendResume', 'lockScreen', 'powerSource']; + readonly #monitor: PowerMonitorSource | undefined; + + constructor(env: ElectronPowerEnv = {}, onError?: (error: unknown) => unknown) { + super(onError); + this.#monitor = env.powerMonitor; + } + + /** Hand the latest launch's reporter to this shared tracker (a defined `onError` replaces it, undefined keeps it). */ + rebind(onError?: (error: unknown) => unknown): void { + this.setReporter(onError); + } + + /** The live power source: `battery` / `ac`, or undefined when the monitor cannot say (never guessed). */ + current(stage: 'powerSource'): ElectronPowerEvents['powerSource'] | undefined { + const monitor = this.#monitor; + if (stage !== 'powerSource' || monitor === undefined) return undefined; + try { + // inside the guard: a host object that is not ready can throw on ANY property read + if (typeof monitor.isOnBatteryPower !== 'function') return undefined; + const onBattery = monitor.isOnBatteryPower(); + if (typeof onBattery !== 'boolean') return undefined; + return { source: onBattery ? 'battery' : 'ac' }; + } catch (error) { + this.report(error); + return undefined; + } + } + + protected attachStage(stage: PowerStage): (() => void) | undefined { + const monitor = this.#monitor; + if (monitor === undefined) return undefined; + return bindAll( + STAGE_EVENTS[stage].map(([event, payload]) => ({ + src: monitor, + event, + listener: () => this.emit(stage, { ...payload } as never), + })), + this.report, + ); + } +} + +const registry = createTrackerRegistry(); + +/** + * The singleton ElectronPowerTracker for `env.powerMonitor` (keyed on that object; without one there is nothing to key + * on and the call throws). Every call (a relaunch included) hands the shared tracker the latest launch's `onError`. + */ +export function electronPowerTrackerFor( + env: ElectronPowerEnv, + onError?: (error: unknown) => unknown, +): ElectronPowerTracker { + const key = env.powerMonitor; + if (key === undefined) throw new TypeError('electronPowerTrackerFor needs a `powerMonitor`'); + return registry.for( + key, + () => new ElectronPowerTracker(env, onError), + (tracker) => tracker.rebind(onError), + ); +} + +/** Test/teardown: drop the monitor's tracker (resetting it, so every Electron listener is released). */ +export function resetElectronPowerTracker(key: object): void { + registry.reset(key); +} diff --git a/packages/trackers/src/electron/process-tracker.ts b/packages/trackers/src/electron/process-tracker.ts index 032d2c67..003e9203 100644 --- a/packages/trackers/src/electron/process-tracker.ts +++ b/packages/trackers/src/electron/process-tracker.ts @@ -2,6 +2,7 @@ import { InterceptorBase } from '../interceptor-base'; import type { ProcessTimers } from '../node/process-tracker'; import { createTrackerRegistry } from '../tracker-registry'; import { type ElectronGpu, mapGpuInfo } from './gpu-info'; +import { reportTo } from './stage-tracker'; // 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 @@ -450,16 +451,6 @@ export class ElectronProcessTracker extends InterceptorBase 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). */ diff --git a/packages/trackers/src/electron/stage-tracker.test.ts b/packages/trackers/src/electron/stage-tracker.test.ts new file mode 100644 index 00000000..cfa0ff5c --- /dev/null +++ b/packages/trackers/src/electron/stage-tracker.test.ts @@ -0,0 +1,308 @@ +import { describe, expect, it, vi } from 'vitest'; +import { bindAll, ElectronStageTracker, isReleasable, reportTo } from './stage-tracker'; + +type L = (...a: unknown[]) => void; +function emitter() { + const table = new Map(); + return { + table, + on: vi.fn((e: string, l: L) => { + table.set(e, [...(table.get(e) ?? []), l]); + }), + removeListener: vi.fn((e: string, l: L) => { + table.set( + e, + (table.get(e) ?? []).filter((x) => x !== l), + ); + }), + fire: (e: string, ...a: unknown[]) => { + for (const l of [...(table.get(e) ?? [])]) l(...a); + }, + count: (e: string) => table.get(e)?.length ?? 0, + }; +} + +describe('reportTo', () => { + it('delivers the error to the reporter', () => { + const fn = vi.fn(); + reportTo({ fn }, new Error('x')); + expect(fn).toHaveBeenCalledOnce(); + }); + it('absorbs a throwing reporter, a rejecting reporter and a missing one', async () => { + expect(() => + reportTo( + { + fn: () => { + throw new Error('r'); + }, + }, + 1, + ), + ).not.toThrow(); + expect(() => reportTo({ fn: () => Promise.reject(new Error('r')) }, 1)).not.toThrow(); + expect(() => reportTo({ fn: undefined }, 1)).not.toThrow(); + await new Promise((r) => setImmediate(r)); // the rejection was handled: no unhandledrejection + }); +}); + +const throwingProxy = (message = 'not ready') => + new Proxy( + {}, + { + get() { + throw new Error(message); + }, + }, + ); + +describe('isReleasable', () => { + it('a source that throws on property read is NOT releasable, and the read is reported', () => { + const report = vi.fn(); + expect(isReleasable(throwingProxy('screen'), report)).toBe(false); + expect(report).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: 'screen' })); + expect(() => isReleasable(throwingProxy())).not.toThrow(); // no reporter: still silent + }); + + it('needs on AND (removeListener or off)', () => { + expect(isReleasable(undefined)).toBe(false); + expect(isReleasable({})).toBe(false); + expect(isReleasable({ on: () => 0 })).toBe(false); + expect(isReleasable({ on: () => 0, removeListener: () => 0 })).toBe(true); + expect(isReleasable({ on: () => 0, off: () => 0 })).toBe(true); + expect(isReleasable({ removeListener: () => 0 })).toBe(false); + }); +}); + +describe('bindAll', () => { + it('a source whose property reads throw: nothing attached, undefined, reported exactly once, never thrown', () => { + const a = emitter(); + const report = vi.fn(); + const release = bindAll( + [ + { src: throwingProxy('proxy'), event: 'x', listener: () => {} }, + { src: a, event: 'y', listener: () => {} }, + ], + report, + ); + expect(release).toBeUndefined(); + expect(a.on).not.toHaveBeenCalled(); + expect(report).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: 'proxy' })); + }); + + it('attaches every binding and the release removes the very wrappers it attached', () => { + const a = emitter(); + const b = emitter(); + const seen = vi.fn(); + const release = bindAll( + [ + { src: a, event: 'x', listener: seen }, + { src: b, event: 'y', listener: seen }, + ], + vi.fn(), + ); + expect(a.count('x')).toBe(1); + expect(b.count('y')).toBe(1); + a.fire('x', 1, 2); + expect(seen).toHaveBeenCalledWith(1, 2); + release?.(); + expect(a.count('x')).toBe(0); + expect(b.count('y')).toBe(0); + }); + + it('uses `off` when there is no removeListener', () => { + const table: L[] = []; + const src = { + on: (_e: string, l: L) => table.push(l), + off: vi.fn((_e: string, l: L) => table.splice(table.indexOf(l), 1)), + }; + bindAll([{ src, event: 'x', listener: () => {} }], vi.fn())?.(); + expect(src.off).toHaveBeenCalledOnce(); + expect(table).toHaveLength(0); + }); + + it('attaches nothing, silently, when any source cannot be released', () => { + const a = emitter(); + const report = vi.fn(); + const release = bindAll( + [ + { src: a, event: 'x', listener: () => {} }, + { src: { on: () => 0 }, event: 'y', listener: () => {} }, + ], + report, + ); + expect(release).toBeUndefined(); + expect(a.on).not.toHaveBeenCalled(); + expect(report).not.toHaveBeenCalled(); + }); + + it('is all-or-nothing: a throwing attach rolls back the earlier ones and reports', () => { + const a = emitter(); + const bad = { + on: () => { + throw new Error('attach'); + }, + removeListener: () => {}, + }; + const report = vi.fn(); + const release = bindAll( + [ + { src: a, event: 'x', listener: () => {} }, + { src: bad, event: 'y', listener: () => {} }, + ], + report, + ); + expect(release).toBeUndefined(); + expect(a.count('x')).toBe(0); + expect(report).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: 'attach' })); + }); + + it('a failing removal is reported and does not strand the others; a wrapper whose removal failed never fires again', () => { + const a = emitter(); + const stuck = { + on: vi.fn(), + removeListener: () => { + throw new Error('remove'); + }, + }; + const report = vi.fn(); + const seen = vi.fn(); + const release = bindAll( + [ + { src: stuck, event: 'y', listener: seen }, + { src: a, event: 'x', listener: seen }, + ], + report, + ); + release?.(); + expect(a.count('x')).toBe(0); + expect(report).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: 'remove' })); + // the stuck wrapper is still registered on `stuck`, but disarmed + (stuck.on.mock.calls[0]?.[1] as L)(); + expect(seen).not.toHaveBeenCalled(); + }); +}); + +describe('ElectronStageTracker', () => { + class T extends ElectronStageTracker<{ a: number; b: number }> { + readonly name = 't'; + protected readonly stages = ['a', 'b'] as const; + attached: string[] = []; + released: string[] = []; + refuse = new Set(); + throwOnRelease = false; + protected attachStage(stage: 'a' | 'b') { + if (this.refuse.has(stage)) return undefined; + this.attached.push(stage); + return () => { + this.released.push(stage); + if (this.throwOnRelease) throw new Error(`rel-${stage}`); + }; + } + rebindReporter(fn?: () => void) { + this.setReporter(fn); + } + syncNow() { + this.sync(); + } + dropAll() { + this.detachAll(); + } + failReport(e: unknown) { + this.report(e); + } + } + + it('arms a stage on its first listener and releases on its last; other stages stay idle', () => { + const t = new T(); + const off1 = t.on('a', () => {}); + const off2 = t.on('a', () => {}); + expect(t.attached).toEqual(['a']); + off1(); + expect(t.released).toEqual([]); + off2(); + expect(t.released).toEqual(['a']); + expect(t.attached).toEqual(['a']); + }); + + it('retries a refused stage on the next listener change', () => { + const t = new T(); + t.refuse.add('a'); + t.on('a', () => {}); + expect(t.attached).toEqual([]); + t.refuse.clear(); + t.on('b', () => {}); + expect(t.attached).toEqual(['a', 'b']); + }); + + it('detachAll releases every armed stage and sync re-arms them', () => { + const t = new T(); + t.on('a', () => {}); + t.on('b', () => {}); + t.dropAll(); + expect(t.released.sort()).toEqual(['a', 'b']); + t.syncNow(); + expect(t.attached).toHaveLength(4); + }); + + it('a throwing release is reported and does not block the next', () => { + const onError = vi.fn(); + const t = new T(onError); + t.throwOnRelease = true; + t.on('a', () => {}); + t.on('b', () => {}); + t.dropAll(); + expect(t.released).toEqual(['a', 'b']); + expect(onError).toHaveBeenCalledTimes(2); + }); + + it('a stage whose attach THROWS is reported, never thrown at the subscriber, and retried on the next change', () => { + const onError = vi.fn(); + const t = new T(onError); + let boom = true; + const original = (t as unknown as { attachStage: (s: 'a' | 'b') => unknown }).attachStage.bind( + t, + ); + (t as unknown as { attachStage: (s: 'a' | 'b') => unknown }).attachStage = (stage) => { + if (boom) throw new Error('attach'); + return original(stage); + }; + expect(() => t.on('a', () => {})).not.toThrow(); + expect(onError).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: 'attach' })); + boom = false; + t.on('b', () => {}); + expect(t.attached).toEqual(['a', 'b']); + }); + + it('reset drops every listener and releases', () => { + const t = new T(); + t.on('a', () => {}); + t.reset(); + expect(t.released).toEqual(['a']); + }); + + it('a throwing subscriber is isolated to the reporter; setReporter replaces, undefined keeps', () => { + const first = vi.fn(); + const second = vi.fn(); + const t = new T(first); + t.rebindReporter(second); + t.rebindReporter(undefined); + t.on('a', () => { + throw new Error('sub'); + }); + t.emit('a', 1); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledOnce(); + t.failReport(new Error('direct')); + expect(second).toHaveBeenCalledTimes(2); + }); + + it('a throwing reporter never escapes emit', () => { + const t = new T(() => { + throw new Error('r'); + }); + t.on('a', () => { + throw new Error('sub'); + }); + expect(() => t.emit('a', 1)).not.toThrow(); + }); +}); diff --git a/packages/trackers/src/electron/stage-tracker.ts b/packages/trackers/src/electron/stage-tracker.ts new file mode 100644 index 00000000..bb433580 --- /dev/null +++ b/packages/trackers/src/electron/stage-tracker.ts @@ -0,0 +1,176 @@ +import { InterceptorBase } from '../interceptor-base'; + +// Shared machinery of the Electron DOMAIN trackers (power, display, application). It is NOT a tracker of its own: it +// is the one place that knows how to attach/release Electron listeners safely, so each domain tracker only says WHICH +// Electron events feed WHICH of its stages. `electron` is never imported: every source is a structural object. +// +// PER-STAGE ACTIVATION. A stage's Electron listeners are attached when the stage gets its first listener and released +// when its last one leaves (`onListenersChanged`), never at construction. A source that cannot be RELEASED (no +// `removeListener`/`off`) is never attached to, because a listener that could not be removed would outlive +// `client.stop()`. Attaching is ALL-OR-NOTHING per stage: a throwing `on` rolls back what was attached and reports. +// Every attached listener is wrapped in a liveness guard, so one whose removal failed can never emit afterwards. + +/** An Electron-style emitter. Parameters are `never` so any concrete overloaded `on`/`removeListener` is assignable. */ +export interface EmitterSource { + on?(event: never, listener: never): unknown; + removeListener?(event: never, listener: never): unknown; + off?(event: never, listener: never): unknown; +} + +type Listener = (...args: unknown[]) => void; +type RawEmitter = { + on(event: string, listener: Listener): unknown; + removeListener?(event: string, listener: Listener): unknown; + off?(event: string, listener: Listener): unknown; +}; + +/** One listener to bind: `listener` runs for `event` on `src`. */ +export interface Binding { + src: EmitterSource; + event: string; + listener: Listener; +} + +export type Report = (error: unknown) => void; + +/** Calls the reporter; it may throw or return a rejecting Promise (both are absorbed: trackers are silent toward the host). */ +export 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 */ + } +} + +/** + * True when `src` can be listened to AND released again. Every host property read is guarded: Electron's real `screen` + * is a Proxy that THROWS on any property read before the app is ready, and that must mean "domain off", never a failed + * launch. A throwing read is reported (when a reporter is given) and answers false. + */ +export function isReleasable(src: EmitterSource | undefined, report?: Report): boolean { + if (src === undefined) return false; + try { + return ( + typeof src.on === 'function' && + (typeof src.removeListener === 'function' || typeof src.off === 'function') + ); + } catch (error) { + report?.(error); + return false; + } +} + +/** + * Attach every binding, all or nothing. Returns the release function, or undefined when a source cannot be released + * (silent: the capability is absent) or an attach threw (reported; what was attached is rolled back). The release + * disarms the wrappers first, then removes each listener in its own guard so one failing removal strands no other. + */ +export function bindAll(bindings: readonly Binding[], report: Report): (() => void) | undefined { + if (!bindings.every((b) => isReleasable(b.src, report))) return undefined; // reported at most once: `every` stops + let live = true; + const removers: Array<() => void> = []; + const release = (): void => { + live = false; + for (const remove of removers.splice(0)) { + try { + remove(); + } catch (error) { + report(error); + } + } + }; + for (const { src, event, listener } of bindings) { + const raw = src as RawEmitter; + const wrapper: Listener = (...args) => { + if (live) listener(...args); + }; + try { + raw.on(event, wrapper); + } catch (error) { + release(); + report(error); + return undefined; + } + removers.push(() => { + if (typeof raw.removeListener === 'function') raw.removeListener(event, wrapper); + else raw.off?.(event, wrapper); + }); + } + return release; +} + +/** + * Base of the Electron domain trackers. A subclass lists its `stages` and says, per stage, how to attach the Electron + * listeners that feed it ({@link attachStage}); this class arms/releases them with the stage's listener count. + */ +export abstract class ElectronStageTracker extends InterceptorBase { + /** Mutable indirection: the SHARED tracker outlives launches, so the reporter is always the latest launch's. */ + protected readonly reporter: { fn: ((error: unknown) => unknown) | undefined }; + readonly #released = new Map void>(); + + protected abstract readonly stages: readonly (keyof E)[]; + /** Attach the Electron listeners feeding `stage`; the returned function releases them. Undefined: nothing attached. */ + protected abstract attachStage(stage: keyof E): (() => void) | undefined; + + constructor(onError?: (error: unknown) => unknown) { + const reporter = { fn: onError }; + // A throwing reporter must not escape into the emitter's dispatch (which runs inside the host's events). + super((error) => reportTo(reporter, error)); + this.reporter = reporter; + } + + /** A defined `onError` replaces the reporter (undefined keeps it): the latest launch wins. */ + protected setReporter(onError?: (error: unknown) => unknown): void { + if (onError !== undefined) this.reporter.fn = onError; + } + + protected report = (error: unknown): void => reportTo(this.reporter, error); + + // Activation is per stage (onListenersChanged); the whole-tracker hook has nothing to do. + protected onActivate(): void {} + + protected override onListenersChanged(): void { + this.sync(); + } + + /** Arm every stage that has listeners and is not armed; release every armed stage that has none. */ + protected sync(): void { + for (const stage of this.stages) { + const armed = this.#released.get(stage); + if (this.listenerCount(stage) === 0) { + if (armed !== undefined) this.#detach(stage, armed); + } else if (armed === undefined) { + let release: (() => void) | undefined; + try { + release = this.attachStage(stage); // retried on the next listener change / rebind when undefined + } catch (error) { + this.report(error); // a hostile host object must not fail the subscriber (or the launch) + } + if (release !== undefined) this.#released.set(stage, release); + } + } + } + + /** Release every armed stage (their listeners stay subscribed to the tracker); `sync()` re-arms them. */ + protected detachAll(): void { + for (const [stage, release] of [...this.#released]) this.#detach(stage, release); + } + + #detach(stage: keyof E, release: () => void): void { + this.#released.delete(stage); + try { + release(); + } catch (error) { + this.report(error); + } + } + + /** Test/teardown: drop EVERY listener, releasing every Electron listener. */ + reset(): void { + this.removeAllListeners(); + } +}