diff --git a/.changeset/displays-trace-unification.md b/.changeset/displays-trace-unification.md index 22cc8ee6..3ed6f556 100644 --- a/.changeset/displays-trace-unification.md +++ b/.changeset/displays-trace-unification.md @@ -9,9 +9,9 @@ BREAKING (beta): the browser `screen_size` trace and the Electron `electron_displays` trace are retired and replaced by `displays`, the mobile-layout list (a bare array of display objects, snake_case keys). - Browser: one entry `{id: 0, state: "on", width, height, scale, rotation?}` with `width`/`height` in device pixels (`round(screen.width * devicePixelRatio)`), `scale` the ratio used and `rotation` the screen-orientation angle in quarter turns. Approximate under Chromium page zoom. Not written by WebViews or Electron renderers (the host writes it): new `hostOwnedTraces` browser launch option, set by `launchRenderer` and the WebView launch. -- Electron main: one entry per display (`id` stable per-session index with the primary first, `native_id`, `state` on the primary, `type`, device-pixel `width`/`height`, `natural_width`/`natural_height`, `scale`, `max_fps`, `rotation` in quarter turns). +- Electron main: one entry per display (`id` numbered from the key window's display (0) then ascending Electron id, `native_id`, `state` on id 0, `type`, device-pixel `width`/`height`, `natural_width`/`natural_height`, `scale`, `max_fps`, `rotation` in quarter turns). - `display_added`, `display_removed` and `display_metrics_changed` event params are now the same keys in camelCase: `id`, `nativeId`, `width`, `height`, `naturalWidth`, `naturalHeight`, `scale`, `maxFps`, `rotation`, `type` (plus `changed`). The old `scaleFactor`, `internal` and `refreshRate` params are gone, and `width`/`height` are device pixels rather than DIP. - Electron sessions need `screen`: renderers never write `displays` and main writes it only when `screen` is passed to `launchMain` (after app ready), so without `screen` there is no display trace at all. -- Display `id` numbering restarts at 0 (primary first) for each session. Browser `scale` is rounded to 2 decimals. `rotation` direction is unverified on a real rotated display (Electron documents clockwise degrees; the field means Android's `Surface.ROTATION_*`). +- Display `id` is recomputed on every read (the key window's display is 0; the primary display when there is no window). Browser `scale` is rounded to 2 decimals. `rotation` direction is unverified on a real rotated display (Electron documents clockwise degrees; the field means Android's `Surface.ROTATION_*`). - `@bugsee/core`: `hostOwnedTraces` is kept across `relaunch()` (`RELAUNCH_KEPT_OPTIONS`). - `@bugsee/trackers`: the Electron display tracker's `DisplayInfo` has the new shape (`mapDisplay` returns `MappedDisplay`, now exported from `@bugsee/trackers/electron`). diff --git a/.changeset/displays-zoom-key-window.md b/.changeset/displays-zoom-key-window.md new file mode 100644 index 00000000..011db996 --- /dev/null +++ b/.changeset/displays-zoom-key-window.md @@ -0,0 +1,7 @@ +--- +'@bugsee/browser': minor +'@bugsee/electron': minor +'@bugsee/trackers': minor +--- + +Browser `displays` now carries a `zoom` field and recovers the physical size from it, but only when the page zoom can be trusted: Chromium, the top-level window, a pointer-fine device, and `outerWidth / innerWidth` within 1.5% of a real browser zoom preset (it is snapped to the preset, so the value does not flap). Otherwise `zoom` is omitted and `width`/`height`/`scale` use `devicePixelRatio` alone, as before. That is the case with a docked DevTools or side panel (the common developer setup), a custom zoom step, Firefox and Safari. Changes are written after 250 ms of quiet, so a window maximize animation does not write a burst of values. Electron `displays` ids follow the key window: id 0 is the display showing the focused window (else the most recently focused, else the first visible/created), the rest ascend by Electron id, `state: "on"` marks id 0, and the list is re-written when focus or a window move changes that display (moves are debounced 200 ms). `display_*` event ids are positions in the current list; correlate by `nativeId`. With `screen` passed, the displays trace keeps focus and move listeners on `app` and on each window even with `captureWindowEvents: false`. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 4e8cd940..df5a56b9 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -419,6 +419,7 @@ solid), in slices: - **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). - **Displays unification (C3, C4, C5, `feat/displays-trace-unification`):** the browser `screen_size` and the Electron `electron_displays` traces are RETIRED and replaced by the mobile-layout **`displays`** trace (spec `bundle/traces.md#displays`, a bare ARRAY of display objects, snake_case keys, held step trace). Browser/WebView-less: ONE entry `{id:0, state:'on', width:round(screen.width*dpr), height:round(screen.height*dpr), scale:dpr, rotation?:angle/90}` (`DisplaysProducer`, fed by the UiTracker `screenSize` + `orientation` stages; **approximate under Chromium page zoom**, `scale` records the ratio used). Electron main: one entry per display `{id, native_id, state?, type?, width, height, natural_width?, natural_height?, scale?, max_fps?, rotation?}` in DEVICE pixels (`size` x `scaleFactor`), `id` a stable per-session index (primary first, never reused, assigned by the display tracker so the trace and the events agree), `state:'on'` on the current primary only. `display_added`/`display_removed`/`display_metrics_changed` params are now the same keys in camelCase (`id, nativeId, width, height, naturalWidth, naturalHeight, scale, maxFps, rotation (quarter turns), type, changed?`). Renderers must not write host-owned `displays`: new browser launch option `hostOwnedTraces` (`['displays']`), set by `launchRenderer` (after the caller's options) and always by the WebView launch. BREAKING for any consumer of the old names (SDK is beta). **Electron needs `screen`:** renderers suppress `displays` unconditionally (host-owned, spec table) and main writes it only when `screen` is passed (and not on a repeat launch), so an Electron session launched WITHOUT `screen` has NO display trace at all: pass `screen` after app ready to get `displays` (documented in `packages/electron/README.md` and the changeset). **Session numbering:** the display tracker forgets its id map when its last subscriber leaves, so each session (stop / relaunch) numbers from 0 with the then-current primary first. A throwing `getPrimaryDisplay` is guarded separately (reported once; the list is still written, without `state`). Browser `scale` is rounded to 2 decimals (zoom gives 1.100000023841858) and de-duplication runs on the rounded value. Without `getAllDisplays` an event's display takes the next unused number (0 if first seen) even if it is not the primary. **UNVERIFIED on a real rotated display:** Electron documents `Display.rotation` as clockwise degrees while the spec says the field is Android's `Surface.ROTATION_*`; the SDK writes degrees/90 as is (Electron) and `angle/90` (browser) with no direction adjustment, and neither mapping has been checked on a real rotated display. +- **Displays zoom + key window (C27, C26 for the Electron `displays` trace; `feat/displays-zoom-key-window`; specs PR bugsee/specs#62):** (1) BROWSER (revised after a measured review in real Chrome 151, Firefox 151 and WebKit): the UiTracker `screenSize` state gained `zoom` + `deviceScale` (`devicePixelRatio / zoom`, UNROUNDED, the spec formula), but the derivation is TRUSTED only when ALL hold: Chromium (`navigator.userAgentData.brands` has Chromium / Google Chrome / Microsoft Edge, else `window.chrome`), the top-level window (`window.top` is the window; a frame sees the top's `outerWidth`), a pointer-fine device (`(pointer: coarse)` is also watched), and `outerWidth/innerWidth` within 1.5% of a real zoom preset (25, 33, 50, 67, 75, 80, 90, 100, 110, 125, 150, 175, 200, 250, 300, 400, 500 %), to which it is SNAPPED (no flapping from the integer `innerWidth`; 500% reads 5.02). Not trusted: `zoom` is OMITTED and `width/height/scale` use `devicePixelRatio` alone, exactly as before. Consequences, all deliberate: a docked DevTools / side panel (common for developers) matches no preset so the entry keeps the dpr-only size; Chrome's custom 1.2^n zoom steps are not presets and are omitted; Firefox (its `outerWidth` scales with zoom, a false `zoom:1`) and Safari (older `devicePixelRatio` excludes zoom, fingerprinting protection hides `outerWidth`) never derive a zoom. `DisplaysProducer` SETTLES changes: the first value is immediate, later ones are written after 250 ms of quiet (a macOS maximize/fullscreen animation fires ~20 out-of-step `resize` events; injectable `scheduler`). The tracker re-reads on `resize`/`orientationchange`/screen `change`, a `(resolution: Ndppx)` change (re-armed per ratio) and a `(pointer: coarse)` change. **Unverified:** Safari builds with the fixed `devicePixelRatio` (WebKit 303397@main+) are simply not trusted. (2) ELECTRON key window: the application tracker resolves ONE key window (`getFocusedWindow`, else the most recently focused, remembered while `windowFocus` is armed, else the first of `getAllWindows`) and exposes `keyWindowBounds()`; the display tracker (new `keyWindowBounds` seam + `getDisplayMatching`) numbers STATELESSLY on every read: id 0 = the key window's display, the rest ascending by Electron id, `state:'on'` on id 0 only (the old session-index map is gone); with no key window the primary takes 0, with no primary the lowest Electron id. New `windowMoved` stage (`moved`: on macOS an alias of `move`, firing throughout a drag; Windows fires at the end of a drag; Linux fires only `move`, so there a drag across displays re-reads on the next focus change); the producer re-reads on it with a 200 ms trailing debounce. The first-created fallback prefers a VISIBLE window (`getAllWindows()` order is undocumented, in practice creation order); the most-recently-focused memory is cleared when the `windowFocus` stage is released; a relaunch without `app` clears the display tracker's key-window source. `DisplaysProducer` also subscribes to `windowFocus`/`windowMoved` and re-reads (`emitIfChanged` drops no-ops). `launchMain` builds the application tracker whenever `screen` is injected even with `captureWindowEvents:false` (that switch governs only the `window_*` EVENTS: with `screen` passed the displays producer still arms the `windowFocus` and `windowMoved` stages, i.e. two `browser-window-created` listeners plus per-window focus/blur/moved/closed; with events on, `app` carries three). Sharing one creation listener across stages is a follow-up. `display_*` event ids are the display's position in the CURRENT list (a removed display, absent from it, takes the number after the last listed one, so it no longer matches its last trace entry: `nativeId` is the stable correlation key). Windows on other displays are not recorded. NOT done here: per-window traces from ONE key window for renderers (`app_state`/`orientation`/... in `launch-renderer`/WebView; the rest of C26), and `displayId` is simply never written by these producers (it never was). - **Cleanup migrations (DONE; review round 1 fixed the same day: the carrier-shared viewport source no longer pins the first launch's `onError` onto the shared UiTracker (latest launch wins), no re-baseline of running stages when it activates, online/offline semantics preserved via `transition`; `refactor/trackers-cleanup-migrations`; supersedes the "bound twice" note in TR3 and "Stays for later" in TR1):** three follow-ups so the domain trackers, not their consumers, own the system listeners. (1) **`video.aux` viewport source on the UiTracker:** `packages/browser/src/viewport-source.ts` binds no DOM listener any more; it subscribes to the UiTracker `viewport`, `screenSize` and the NEW `visualViewport` stage and treats each notification as a "re-measure" wake-up, still reading `innerWidth/innerHeight/devicePixelRatio/visualViewport` itself, so the `video.aux` events are unchanged (frame in CSS px, `density`, `scale`/`offset*`/`visible*`, one-per-frame coalescing, unconditional first event, dedupe). `screenSize` is subscribed because it dedupes on `devicePixelRatio` (a window moved to another monitor changes density, not `innerWidth`) and needs the window's `screen`, which the source reads guarded; without a `screen` a density-only change with an unchanged inner size is not noticed. `UiTracker` gained the `visualViewport` stage (`{scale?, offsetLeft?, offsetTop?, width?, height?}`, omit-never-zero; its `resize`/`scroll` listeners attach only while subscribed; env field `visualViewport`, DEFAULTING to the window's own, read live and guarded — so no consumer needs to pass it, and only an explicit injection can look like a source change to running stages) and `VisualViewportState` is exported. Listener effect on the window: the source's own `resize` is gone, the tracker's single shared `resize` + `orientationchange` serve it (net +1 `orientationchange` on a launch that otherwise had it unused, e.g. `captureSystemTraces:false, captureSystemEvents:false`; zero extra when traces/events already run). (2) **`ApplicationTracker` no longer has `online`/`offline`** (type change in `@bugsee/trackers/browser` `ApplicationEvents`; its window listeners are gone): the events source's `online`/`offline` events now come from the `ConnectivityTracker` (per-window singleton) through a NEW stage, `transition {online}`: one per DOM `online`/`offline` EVENT with its kind taken from the event type (never a `navigator.onLine` read), so the old semantics are preserved exactly (an offline/online flap that reads true on both is not lost, an absent `onLine` drops nothing, a synthetic `dispatchEvent` counts, no navigator needed) and there is NO baseline (attach, a late join or a rebind announces nothing). The existing `online`/`networkInfo`/`state` stages are unchanged except that `navigator.connection` `change` and the navigator reads are now attached/made only while one of them has a listener (a transition-only subscriber shares the one window `online`/`offline` pair and nothing else). `online`/`offline` are bound ONCE per window (were twice). (3) **`display_mode_changed`** `events.system` entry (browser + webview, the source is shared) from the UiTracker `displayMode` stage: params `{mode: 'fullscreen'|'standalone'|'minimal-ui'|'browser', previousMode?}`, mirrored on `dark_mode_changed` (de-duplicated by the tracker, baseline silent, lazy subscription, nothing without `matchMedia`; `previousMode` is the mode the source last knew, omitted when it was unreadable). The `EnvironmentTracker` still does not own `displayMode`. - **C15 + C16 (DONE, `feat/elu-percent-gc-event`; specs PR bugsee/specs#62):** (C16) `event_loop_utilization` is on the wire as PERCENT 0-100, one decimal (`round(x*1000)/10`), like `cpu_usage_process`: `createGuardedElu` converts perf_hooks' fraction, the tracker `utilization` stage payload is now `{ utilizationPercent }` (the injected `eventLoopUtilization` seam also answers percent), omit-never-zero unchanged (Bun/Deno still omit on idle+active both 0). (C15) the `gc_count`/`gc_pause_ms`/`gc_pause_max_ms` TRACES are retired (`createNodeSystemTraceProducers` now builds nine producers); GC is the `gc` `events.system` event, params `{count, pauseMs, maxPauseMs}` (camelCase), one per 1 s interval with at least one collection, a quiet interval writes nothing. It is emitted by the node events source (`createNodeSystemEventsSource(proc, { processTracker })`, wired in `launch()` from the shared per-process tracker): it subscribes to the tracker's `gc` stage LAZILY (first event subscriber), releases on stop, and attaches nothing with `captureSystemEvents:false`; the tracker still owns the single observer and arms it only while a `gc` listener exists, so no second observer exists. Bun/Deno keep `measuresGc:false` (blind observer): never emitted. Electron main composes the node source, so the event passes through the mux once, untouched. Because the events source now arms the tracker's shared sampling timer, `captureSystemTraces:false` no longer implies a timer-free launch unless `captureSystemEvents:false` too. - **C2 (DONE, `feat/shared-event-names-android`; specs PR bugsee/specs#62):** the shared browser/WebView `events.system` names take ANDROID's: `orientation_changed` -> `OrientationChanged {current, prev?, type, angle}` (`current`/`prev` are the Android `orientation` trace ints, `prev` omitted when the earlier orientation was unreadable; a bare event with no params when type or angle is unreadable), `dark_mode_changed` -> `DarkModeChanged {dark}`, `process_foreground` -> `UIApplicationDidBecomeActiveNotification`, `process_background` -> `UIApplicationDidEnterBackgroundNotification` (verified against the Android SDK `EventApplicationLifecycleTest` / `EventConfiguration`). JS-only events keep snake_case names. Event PARAMS are camelCase with no exception: an audit of the browser, node and electron sources found every key already camelCase, and a per-package conformance test (keys derived from the events the real sources emit) plus a repo-wide retired-name guard (`packages/instrumentation-tests/test/event-names.guard.test.ts`) now lock it in. Follow-ups owned by other PRs: the `display_*` param keys (`scaleFactor`, `refreshRate`, `internal`, rotation in degrees -> the `displays` camelCase keys, C5) and the future `gc` event. (Older entries in this file keep the names as they were when written.) `OrientationChanged` fires only when the Android orientation int really changes (a raw `{type, angle}` change that maps to the same int is silent). Spec note: the spec row lists `current` as required, while the event is bare (no params) when type/angle is unreadable. diff --git a/packages/browser/src/launch.test.ts b/packages/browser/src/launch.test.ts index 732b2154..4ee0d081 100644 --- a/packages/browser/src/launch.test.ts +++ b/packages/browser/src/launch.test.ts @@ -672,7 +672,7 @@ describe('launch', () => { 'tok', baseOptions({ window: w.win, captureStore: store }), ); - expect(m.thisSeen).toHaveLength(11); // dark: baseline read + watch (2); display mode: 3 queries x (baseline read + watch + previous-mode read) (9) + expect(m.thisSeen).toHaveLength(12); // dark: baseline read + watch (2); display mode: 3 queries x (baseline read + watch + previous-mode read) (9); displays: the (pointer: coarse) watch (1) expect(m.thisSeen.every((t) => t === w.win)).toBe(true); // always called as a method of ITS window for (const f of [...m.l]) f({ matches: true }); expect((await names(store)).filter((e) => e.name === 'DarkModeChanged')).toEqual([ @@ -2122,9 +2122,19 @@ describe('launch', () => { const w = fakeWindow(); Object.assign(w.win, { devicePixelRatio: 2 }); const store = memStore(); - await launchTracked('tok', noSampler({ window: w.win, captureStore: store })); + const settle: Array<() => void> = []; + const scheduler = { + setInterval: (cb: () => void, ms: number) => { + if (ms === 250) settle.push(cb); // the displays settle timer (never cleared in this test) + return settle.length; + }, + clearInterval: () => {}, + }; + await launchTracked('tok', noSampler({ window: w.win, captureStore: store, scheduler })); Object.assign(w.win, { devicePixelRatio: 3 }); w.emit('resize', {}); + expect(settle).toHaveLength(1); // settled, not written immediately + settle[0]?.(); expect(await rowsOf(store, 'displays')).toEqual([ [{ id: 0, state: 'on', width: 780, height: 1688, scale: 2 }], [{ id: 0, state: 'on', width: 1170, height: 2532, scale: 3 }], diff --git a/packages/browser/src/trace-producers.screen-lag.test.ts b/packages/browser/src/trace-producers.screen-lag.test.ts index d75a90d2..246a330d 100644 --- a/packages/browser/src/trace-producers.screen-lag.test.ts +++ b/packages/browser/src/trace-producers.screen-lag.test.ts @@ -1,6 +1,6 @@ import type { TraceProducer } from '@bugsee/capture'; import { ApplicationTracker, ProcessTracker, UiTracker } from '@bugsee/trackers/browser'; -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { browserTraceEnvFrom, createBrowserSystemTraceProducers, @@ -31,6 +31,33 @@ const sinkOf = (out: Emit[]) => ({ }); const names = (ps: TraceProducer[]) => ps.map((p) => p.name); +/** A manual scheduler: the producer's settle timer fires only when `advance` covers it. */ +function manualScheduler() { + let now = 0; + let next = 1; + const timers = new Map void }>(); + return { + setInterval: (cb: () => void, ms: number) => { + const id = next++; + timers.set(id, { at: now + ms, cb }); + return id; + }, + clearInterval: (id: unknown) => void timers.delete(id as number), + advance: (ms: number) => { + now += ms; + for (const [id, t] of [...timers]) { + if (t.at <= now) { + timers.delete(id); + t.cb(); + } + } + }, + pending: () => timers.size, + }; +} +const chromeWin = (extra: Record = {}) => + Object.assign(mkTarget(), { chrome: {}, ...extra }); + describe('DisplaysProducer', () => { const mk = (screen: unknown = { width: 390, height: 844 }) => { const win = Object.assign(mkTarget(), { devicePixelRatio: 2 }); @@ -41,7 +68,8 @@ describe('DisplaysProducer', () => { it('emits the one-entry mobile list at start (device pixels, scale, state on) as a HELD step trace, then follows resize, de-duplicated', () => { const { win, tracker } = mk(); const out: Emit[] = []; - new DisplaysProducer(tracker).start(sinkOf(out)); + const sched = manualScheduler(); + new DisplaysProducer(tracker, sched).start(sinkOf(out)); expect(out).toEqual([ { name: 'displays', @@ -50,16 +78,125 @@ describe('DisplaysProducer', () => { }, ]); win.fire('resize'); // nothing moved + sched.advance(1000); expect(out).toHaveLength(1); win.devicePixelRatio = 3; win.fire('resize'); win.fire('orientationchange'); + sched.advance(250); expect(out.map((o) => o.value)).toEqual([ [{ id: 0, state: 'on', width: 780, height: 1688, scale: 2 }], [{ id: 0, state: 'on', width: 1170, height: 2532, scale: 3 }], ]); }); + it('trusted page zoom: width/height use screen x dpr / zoom (no drift across zoom levels) and zoom is written', () => { + // Chrome, device scale 2, screen 1440x900: 125% then 100% then 200%: the physical size never moves + const win = chromeWin({ devicePixelRatio: 2.5, outerWidth: 1440, innerWidth: 1152 }); + const out: Emit[] = []; + const sched = manualScheduler(); + new DisplaysProducer( + new UiTracker({ window: win, screen: { width: 1440, height: 900 } as never }), + sched, + ).start(sinkOf(out)); + expect(out[0]?.value).toEqual([ + { id: 0, state: 'on', width: 2880, height: 1800, scale: 2, zoom: 1.25 }, + ]); + Object.assign(win, { devicePixelRatio: 2, innerWidth: 1440 }); + win.fire('resize'); + sched.advance(250); + Object.assign(win, { devicePixelRatio: 4, innerWidth: 720 }); + win.fire('resize'); + sched.advance(250); + expect(out.map((o) => o.value)).toEqual([ + [{ id: 0, state: 'on', width: 2880, height: 1800, scale: 2, zoom: 1.25 }], + [{ id: 0, state: 'on', width: 2880, height: 1800, scale: 2, zoom: 1 }], + [{ id: 0, state: 'on', width: 2880, height: 1800, scale: 2, zoom: 2 }], + ]); + }); + + it('untrusted zoom (docked DevTools): dpr-only size, no zoom key (strict: not even undefined)', () => { + // 1200 window, innerWidth 645 at 100% zoom, dpr 2, screen 1920x1080: the old exact value + const win = chromeWin({ devicePixelRatio: 2, outerWidth: 1200, innerWidth: 645 }); + const out: Emit[] = []; + new DisplaysProducer( + new UiTracker({ window: win, screen: { width: 1920, height: 1080 } as never }), + ).start(sinkOf(out)); + expect(out[0]?.value).toStrictEqual([ + { id: 0, state: 'on', width: 3840, height: 2160, scale: 2 }, + ]); + }); + + it('a Safari-like (non-Chromium) window keeps dpr-only sizes and omits zoom', () => { + const win = Object.assign(mkTarget(), { + devicePixelRatio: 2, + outerWidth: 1600, + innerWidth: 1280, + navigator: { userAgentData: undefined }, + }); + const out: Emit[] = []; + new DisplaysProducer( + new UiTracker({ window: win, screen: { width: 1600, height: 900 } as never }), + ).start(sinkOf(out)); + expect(out[0]?.value).toStrictEqual([ + { id: 0, state: 'on', width: 3200, height: 1800, scale: 2 }, + ]); + }); + + it('SETTLES changes: a burst of out-of-step resize values (maximize animation) writes ONE value after 250 ms quiet; the first value is immediate', () => { + const win = chromeWin({ devicePixelRatio: 2, outerWidth: 1000, innerWidth: 1000 }); + const out: Emit[] = []; + const sched = manualScheduler(); + new DisplaysProducer( + new UiTracker({ window: win, screen: { width: 1000, height: 500 } as never }), + sched, + ).start(sinkOf(out)); + expect(out).toHaveLength(1); // immediate + for (const [outer, inner] of [ + [1200, 1000], + [1500, 1000], + [1800, 1000], + [2000, 2000], + ] as const) { + Object.assign(win, { outerWidth: outer, innerWidth: inner }); + win.fire('resize'); + sched.advance(100); // each event arrives inside the previous one's window: the timer restarts + } + expect(out).toHaveLength(1); + expect(sched.pending()).toBe(1); + sched.advance(150); + expect(out).toHaveLength(1); // settled to the same value: de-duplicated + Object.assign(win, { devicePixelRatio: 3, outerWidth: 1000, innerWidth: 1000 }); + win.fire('resize'); + sched.advance(249); + expect(out).toHaveLength(1); + sched.advance(1); + expect(out).toHaveLength(2); + }); + + it('without a scheduler the global timers are used (a settle is armed and cancelled on stop)', () => { + vi.useFakeTimers(); + try { + const win = Object.assign(mkTarget(), { devicePixelRatio: 2 }); + const out: Emit[] = []; + const p = new DisplaysProducer( + new UiTracker({ window: win, screen: { width: 100, height: 100 } as never }), + ); + p.start(sinkOf(out)); + win.devicePixelRatio = 3; + win.fire('resize'); + vi.advanceTimersByTime(250); + expect(out).toHaveLength(2); + win.devicePixelRatio = 4; + win.fire('resize'); + p.stop(); + vi.advanceTimersByTime(1000); + expect(out).toHaveLength(2); + } finally { + vi.useRealTimers(); + } + }); + it('rounds the device pixels from a fractional ratio and records the ratio used in scale', () => { const win = Object.assign(mkTarget(), { devicePixelRatio: 1.25 }); const out: Emit[] = []; @@ -95,12 +232,15 @@ describe('DisplaysProducer', () => { it('rounds the zoom-polluted ratio to 2 decimals and de-duplicates on the rounded value', () => { const win = Object.assign(mkTarget(), { devicePixelRatio: 1.100000023841858 }); const out: Emit[] = []; + const sched = manualScheduler(); new DisplaysProducer( new UiTracker({ window: win, screen: { width: 1000, height: 1000 } as never }), + sched, ).start(sinkOf(out)); expect(out[0]?.value).toEqual([{ id: 0, state: 'on', width: 1100, height: 1100, scale: 1.1 }]); win.devicePixelRatio = 1.1; win.fire('resize'); + sched.advance(250); expect(out).toHaveLength(1); }); @@ -109,7 +249,8 @@ describe('DisplaysProducer', () => { const screen = { width: 390, height: 844, orientation: { type: 'portrait-primary', angle: 0 } }; const out: Emit[] = []; const tracker = new UiTracker({ window: win, screen: screen as never }); - new DisplaysProducer(tracker).start(sinkOf(out)); + const sched = manualScheduler(); + new DisplaysProducer(tracker, sched).start(sinkOf(out)); const rot = () => (out.at(-1)?.value as Array<{ rotation?: number }>)[0]?.rotation; expect(rot()).toBe(0); for (const [angle, turns] of [ @@ -121,10 +262,12 @@ describe('DisplaysProducer', () => { ] as const) { screen.orientation.angle = angle; win.fire('orientationchange'); + sched.advance(250); expect(rot()).toBe(turns); } screen.orientation.angle = 45; // not a quarter turn: omitted, not rounded win.fire('orientationchange'); + sched.advance(250); expect(out.at(-1)?.value).toEqual([{ id: 0, state: 'on', width: 780, height: 1688, scale: 2 }]); const noAngle: Emit[] = []; new DisplaysProducer( @@ -159,13 +302,19 @@ describe('DisplaysProducer', () => { it('stop() releases the window listeners and later events write nothing', () => { const { win, tracker } = mk(); const out: Emit[] = []; - const p = new DisplaysProducer(tracker); + const sched = manualScheduler(); + const p = new DisplaysProducer(tracker, sched); p.start(sinkOf(out)); expect(win.count()).toBeGreaterThan(0); + win.devicePixelRatio = 4; + win.fire('resize'); // a settle is pending + expect(sched.pending()).toBe(1); p.stop(); + expect(sched.pending()).toBe(0); // the pending write is cancelled expect(win.count()).toBe(0); win.devicePixelRatio = 5; win.fire('resize'); + sched.advance(1000); expect(out).toHaveLength(1); }); }); diff --git a/packages/browser/src/trace-producers.ts b/packages/browser/src/trace-producers.ts index fbb15898..aebed54e 100644 --- a/packages/browser/src/trace-producers.ts +++ b/packages/browser/src/trace-producers.ts @@ -321,42 +321,63 @@ export class FpsProducer extends TraceProducerBase { /** * `displays` (the MOBILE name and list shape, spec bundle/traces.md `displays`; it replaces the retired JS-specific - * `screen_size`): a ONE-entry list `[{ id: 0, state: 'on', width, height, scale, rotation? }]` where `width`/`height` are - * DEVICE pixels, `round(screen.width * devicePixelRatio)` / `round(screen.height * devicePixelRatio)`, `scale` is the - * `devicePixelRatio` used, and `rotation` is the Screen Orientation `angle` / 90 (quarter turns; the trace field means Android's - * `Surface.ROTATION_*`, and the direction of the web `angle` against it is UNVERIFIED on a real rotated device), omitted when the engine gives no angle or one that is not a multiple of 90. The browser - * cannot tell the display `type`, `natural_*` or `max_fps`, so those keys are omitted. `state:'on'` marks the display the - * page is on, as iOS does (a page cannot observe power). + * `screen_size`): a ONE-entry list `[{ id: 0, state: 'on', width, height, scale, zoom?, rotation? }]`. `width`/`height` are + * DEVICE pixels, `round(screen.width * deviceScale)` / `round(screen.height * deviceScale)`, `scale` is that device scale + * factor, `zoom` the page zoom (`1` = 100%) and `rotation` the Screen Orientation `angle` / 90 (quarter turns; the trace field + * means Android's `Surface.ROTATION_*`, and the direction of the web `angle` against it is UNVERIFIED on a real rotated device), + * omitted when the engine gives no angle or one that is not a multiple of 90. The browser cannot tell the display `type`, + * `natural_*` or `max_fps`, so those keys are omitted. `state:'on'` marks the display the page is on, as iOS does (a page + * cannot observe power). * - * KNOWN LIMITATION, approximate under page zoom on Chromium: Blink reports `screen.width/height` in device-independent - * pixels that IGNORE page zoom, while `devicePixelRatio` INCLUDES it, so the product drifts when the user zooms (Blink - * source; not measured in a live browser). No web API exposes a zoom-independent device ratio, so `scale` records the - * ratio actually used for the product. iOS Safari is reported not to swap `screen.width/height` on rotation (unverified): - * there the entry is portrait-only like native iOS. + * PAGE ZOOM (spec C27). On Chromium `screen.width/height` are device-independent pixels that IGNORE page zoom, while + * `devicePixelRatio` INCLUDES it. The UiTracker `screenSize` stage derives `zoom = outerWidth / innerWidth` and + * `deviceScale = devicePixelRatio / zoom` (measured in Chrome 156 at 69%-144%), but TRUSTS it only when the ratio is within + * 1.5% of a real browser zoom preset (it is then snapped to the preset), on a Chromium engine, in the top-level window and on + * a pointer-fine device. Trusted: `width/height = round(screen.* x devicePixelRatio / zoom)`, `scale = devicePixelRatio / zoom` + * (2 decimals) and the `zoom` key (2 decimals). NOT trusted: `zoom` is OMITTED and the product uses `devicePixelRatio` alone. + * A docked DevTools or side panel (the common case for developers) narrows `innerWidth`, the ratio then matches no preset + * and the entry keeps the `devicePixelRatio`-only size; a custom (non-preset) zoom, Firefox (its `outerWidth` scales with + * zoom) and Safari (older `devicePixelRatio` excludes zoom, fingerprinting protection hides `outerWidth`) behave the same. + * iOS Safari is reported not to swap `screen.width/height` on rotation (unverified): there the entry is portrait-only like + * native iOS. * - * Re-read on `resize` / `orientationchange` / `screen` `change` (UiTracker `screenSize` + `orientation` stages). A step - * curve, so it is held and de-duplicated (a resize that moved nothing is dropped); the initial value is emitted at start. - * Omitted entirely when the screen or the pixel ratio cannot be read as finite positive numbers. - * - * Known staleness: moving the window to another monitor with the SAME pixel ratio but a different size fires no - * `resize`, so the value can go stale until the next one, unless the engine fires the `screen` `change` event the - * tracker listens for (a `(resolution: Xdppx)` media-query listener is a follow-up). + * Re-read on `resize` / `orientationchange` / `screen` `change`, a `(resolution: Ndppx)` change and a `(pointer: coarse)` + * change (UiTracker `screenSize` + `orientation` stages). The first value is emitted at start; later changes are SETTLED: + * published once the inputs have been quiet for {@link DISPLAYS_SETTLE_MS} (a macOS maximize/fullscreen animation fires about + * twenty `resize` events with `outerWidth`/`innerWidth` out of step, which must not each become a trace value). A step + * curve, so held and de-duplicated. Omitted entirely when the screen or the pixel ratio cannot be read as finite positive + * numbers. */ +/** How long the displays inputs must stay unchanged before a change is written (the first value is immediate). */ +export const DISPLAYS_SETTLE_MS = 250; + +const globalTimers = globalThis as unknown as { + setInterval(callback: () => void, ms: number): unknown; + clearInterval(handle: unknown): void; +}; + export class DisplaysProducer extends TraceProducerBase { readonly name = 'displays'; readonly #tracker: UiTracker; + readonly #scheduler: Scheduler; #offs: Array<() => void> = []; + #timer: unknown; + #pending = false; - constructor(tracker: UiTracker) { + constructor(tracker: UiTracker, scheduler?: Scheduler) { super(); this.#tracker = tracker; + this.#scheduler = scheduler ?? { + setInterval: (cb, ms) => globalTimers.setInterval(cb, ms), + clearInterval: (h) => globalTimers.clearInterval(h), + }; } protected onStart(): void { // subscribing attaches the listeners; both stages re-publish the whole entry (the angle and the size can change apart) this.#offs = [ - this.#tracker.on('screenSize', () => this.#publish()), - this.#tracker.on('orientation', () => this.#publish()), + this.#tracker.on('screenSize', () => this.#settle()), + this.#tracker.on('orientation', () => this.#settle()), ]; this.#publish(); } @@ -364,16 +385,35 @@ export class DisplaysProducer extends TraceProducerBase { protected override onStop(): void { for (const off of this.#offs) off(); this.#offs = []; + this.#cancel(); + } + + #cancel(): void { + if (this.#pending) this.#scheduler.clearInterval(this.#timer); + this.#pending = false; + this.#timer = undefined; + } + + /** Trailing debounce: the value is written once no change has arrived for DISPLAYS_SETTLE_MS. */ + #settle(): void { + this.#cancel(); + this.#pending = true; + this.#timer = this.#scheduler.setInterval(() => { + this.#cancel(); + this.#publish(); + }, DISPLAYS_SETTLE_MS); } #publish(): void { const s = this.#tracker.current('screenSize'); if (s === undefined) return; - const width = Math.round(s.width * s.dpr); - const height = Math.round(s.height * s.dpr); + // dpr / zoom when the page zoom is trusted (spec formula), else the pixel ratio alone + const factor = s.deviceScale ?? s.dpr; + const width = Math.round(s.width * factor); + const height = Math.round(s.height * factor); if (!(width > 0) || !(height > 0)) return; // at most 2 decimals (zoom gives 1.100000023841858), like the Electron producer; the held value is the rounded one - const scale = Math.round(s.dpr * 100) / 100 || s.dpr; + const scale = Math.round(factor * 100) / 100 || factor; const angle = this.#tracker.current('orientation')?.angle; const turns = angle !== undefined && angle % 90 === 0 ? (((angle / 90) % 4) + 4) % 4 : undefined; @@ -384,6 +424,7 @@ export class DisplaysProducer extends TraceProducerBase { width, height, scale, + ...(s.zoom !== undefined ? { zoom: s.zoom } : {}), ...(turns !== undefined ? { rotation: turns } : {}), }, ]); @@ -762,7 +803,7 @@ export function createBrowserSystemTraceProducers( new AppStateProducer(env.lifecycle), ...(Array.isArray(env.hostOwnedTraces) && env.hostOwnedTraces.includes('displays') ? [] - : [new DisplaysProducer(ui)]), + : [new DisplaysProducer(ui, env.scheduler)]), new MainThreadLagProducer(processTracker), new MainThreadIdleProducer(processTracker), new FpsProducer(ui), diff --git a/packages/electron/README.md b/packages/electron/README.md index ffe0fbb7..4310f12f 100644 --- a/packages/electron/README.md +++ b/packages/electron/README.md @@ -85,8 +85,8 @@ Pass any of `powerMonitor`, `screen` and `BrowserWindow` (the Electron objects, **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` (camelCase `{ id, nativeId, width, height, naturalWidth, naturalHeight, scale, maxFps, rotation, type }`, absent keys omitted; `id` is the stable per-session display index the `displays` trace uses, `width`/`height` are device pixels, `rotation` is quarter turns; 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). **Pass `screen` (after app ready) to get the `displays` trace: without it an Electron session has no display trace at all, because renderers never write it (the host owns it).** It also feeds the `displays` system trace, the mobile layout: a list `[{ id, native_id, state?, type?, width, height, natural_width?, natural_height?, scale?, max_fps?, rotation? }]` (`id` 0 is the display that was primary at the session's first read, later displays take the next number even if one becomes primary; `state: "on"` marks the CURRENT primary display, which can have another `id` after a mid-session change; the retired `electron_displays` name is gone), 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). -- `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`. +- `screen` -> `events.system`: `display_added` and `display_removed` (camelCase `{ id, nativeId, width, height, naturalWidth, naturalHeight, scale, maxFps, rotation, type }`, absent keys omitted; `id` is the display's number in the CURRENT `displays` list (a removed display is no longer listed and takes the number after the last listed one, so correlate display events by `nativeId`, which is the stable key), `width`/`height` are device pixels, `rotation` is quarter turns; 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). **Pass `screen` (after app ready) to get the `displays` trace: without it an Electron session has no display trace at all, because renderers never write it (the host owns it).** It also feeds the `displays` system trace, the mobile layout: a list `[{ id, native_id, state?, type?, width, height, natural_width?, natural_height?, scale?, max_fps?, rotation? }]` (`id` 0 is the display showing the KEY window (the focused window, else the most recently focused, else the first created; the primary display when there is no window yet), the others follow in ascending order of Electron's id with Electron's own id in `native_id`; the numbering is recomputed, and the list re-written, when focus or a window move changes the key window's display; `state: "on"` marks id 0; windows on other displays are not recorded; the retired `electron_displays` name is gone), 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). +- `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 `browser-window-created` listeners, for focus and for show/hide, and one `web-contents-created` listener); pass `captureWindowEvents: false` to opt out of the events. That switch does NOT stop key-window tracking: when `screen` is passed the `displays` trace follows the focused window, so two `browser-window-created` listeners (focus, moved) and focus/blur/moved/closed listeners on every window stay armed even with the option off (with window events on and `screen` passed, `app` carries three `browser-window-created` listeners). 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. diff --git a/packages/electron/src/launch-main.test.ts b/packages/electron/src/launch-main.test.ts index c268fea3..ed273c54 100644 --- a/packages/electron/src/launch-main.test.ts +++ b/packages/electron/src/launch-main.test.ts @@ -1148,7 +1148,10 @@ describe('launchMain — Electron domain trackers: power, display, application w }); const a = accessors(); expect(a.power).toHaveBeenCalledExactlyOnceWith({ powerMonitor }, onError); - expect(a.display).toHaveBeenCalledExactlyOnceWith({ screen }, onError); + expect(a.display).toHaveBeenCalledExactlyOnceWith( + { screen, keyWindowBounds: expect.any(Function) }, + onError, + ); expect(a.application).toHaveBeenCalledExactlyOnceWith({ app, BrowserWindow }, onError); }); @@ -1256,6 +1259,32 @@ describe('launchMain — Electron domain trackers: power, display, application w expect(powerMonitor.total()).toBe(6); }); + it('with a screen, the application tracker is built for the KEY window even when captureWindowEvents is false; the display tracker reads its bounds; no window EVENTS are forwarded', () => { + clear(); + const app = new FakeEmitter(); + const screen = Object.assign(new FakeEmitter(), { getAllDisplays: () => [] }); + const bounds = { x: 5, y: 6, width: 7, height: 8 }; + const BrowserWindow = { + getAllWindows: () => [], + getFocusedWindow: () => ({ isDestroyed: () => false, getBounds: () => bounds }), + }; + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + app, + screen, + BrowserWindow, + captureWindowEvents: false, + }); + expect(accessors().application).toHaveBeenCalledOnce(); + const env = vi.mocked(electronDisplayTrackerFor).mock.calls[0]?.[0]; + expect(env?.keyWindowBounds?.()).toEqual(bounds); + const mux = wrapOf(f)(new Inner()); + mux.on('event', () => {}); + expect(app.table.get('browser-window-created')).toBeUndefined(); // the events mux arms none + }); + it.each([ null, 0, diff --git a/packages/electron/src/launch-main.ts b/packages/electron/src/launch-main.ts index 3eb2055b..5d9f2a80 100644 --- a/packages/electron/src/launch-main.ts +++ b/packages/electron/src/launch-main.ts @@ -167,7 +167,11 @@ export interface LaunchMainOptions extends BugseeLaunchOptions { 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). + * captured), which adds two `app` listeners for windows (`browser-window-created` for focus and for show/hide) and one `web-contents-created`; + * pass `false` to opt out of the EVENTS (any non-boolean value is OFF and reported). It does NOT opt out of key-window tracking: when `screen` is + * passed, the `displays` trace needs the focused/moved window, so the application tracker still arms its `windowFocus` and `windowMoved` + * stages, i.e. two `browser-window-created` listeners and focus/blur/moved/closed listeners on every window even with this option `false` + * (with window events on AND `screen` passed, `app` carries three `browser-window-created` listeners). */ captureWindowEvents?: boolean; /** Electron's `crashReporter` — when provided, native minidumps are captured, session-correlated. */ @@ -290,10 +294,6 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee 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') { @@ -302,13 +302,30 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee new TypeError('captureWindowEvents must be a boolean: window events are OFF'), ); } - const application = - app !== undefined && !repeat && windowEvents + // ONE shared application tracker serves two jobs: the `window_*`/`renderer_*` EVENTS (gated by `captureWindowEvents`) and + // the KEY window (focused, else most recently focused, else first created) that decides which display is `displays` id 0 + // and re-reads the list on focus/move. The key-window job needs the tracker whenever `screen` is injected, independent + // of `captureWindowEvents` (which only governs the events below). + const appTracker = + app !== undefined && !repeat && (windowEvents || screen !== undefined) ? electronApplicationTrackerFor( { app, ...(BrowserWindow !== undefined ? { BrowserWindow } : {}) }, nodeOptions.onError, ) : undefined; + const application = windowEvents ? appTracker : undefined; + const display = + screen !== undefined && !repeat + ? electronDisplayTrackerFor( + { + screen, + ...(appTracker !== undefined + ? { keyWindowBounds: () => appTracker.keyWindowBounds() } + : {}), + }, + 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, @@ -329,6 +346,8 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee ...createElectronSystemTraceProducers({ ...(tracker !== undefined ? { process: tracker } : {}), ...(display !== undefined ? { display } : {}), + ...(screen !== undefined && appTracker !== undefined ? { application: appTracker } : {}), + ...(nodeOptions.scheduler !== undefined ? { scheduler: nodeOptions.scheduler } : {}), }), ]; } diff --git a/packages/electron/src/system-events.test.ts b/packages/electron/src/system-events.test.ts index 47a58a14..3bf3a074 100644 --- a/packages/electron/src/system-events.test.ts +++ b/packages/electron/src/system-events.test.ts @@ -324,18 +324,19 @@ describe('createElectronSystemEventsSource: domain trackers', () => { d.screen.emit('display-removed', display(3)); d.screen.emit('display-metrics-changed', display(4), ['bounds']); expect(d.events().slice(1)).toEqual([ - // ids are the SESSION indexes (display 1 is seeded as 0 by the baseline read), device pixels, camelCase + // ids are the position in the CURRENT list (only display 1 is listed; an unlisted display takes the next number), + // device pixels, camelCase { name: 'display_added', params: { id: 1, nativeId: 2, width: 1600, height: 1200, scale: 2 }, }, { name: 'display_removed', - params: { id: 2, nativeId: 3, width: 1600, height: 1200, scale: 2 }, + params: { id: 1, nativeId: 3, width: 1600, height: 1200, scale: 2 }, }, { name: 'display_metrics_changed', - params: { id: 3, nativeId: 4, width: 1600, height: 1200, scale: 2, changed: ['bounds'] }, + params: { id: 1, nativeId: 4, width: 1600, height: 1200, scale: 2, changed: ['bounds'] }, }, ]); }); diff --git a/packages/electron/src/system-events.ts b/packages/electron/src/system-events.ts index 090a15b0..d9d79819 100644 --- a/packages/electron/src/system-events.ts +++ b/packages/electron/src/system-events.ts @@ -25,7 +25,7 @@ import { reportGuarded } from '@bugsee/util'; // // power_suspend / power_resume / power_lock / power_unlock / power_ac / power_battery (no params) // display_added / display_removed params { id, nativeId, width, height, naturalWidth?, naturalHeight?, scale?, maxFps?, rotation?, type? } -// (a `displays` entry in camelCase: `id` is the SAME session index the trace uses, device pixels, rotation in quarter turns) +// (a `displays` entry in camelCase: `id` is the display's position in the CURRENT `displays` list (0 = the key window's display; a removed display is no longer listed and takes the next number, so correlate by `nativeId`), device pixels, rotation in quarter turns) // 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 diff --git a/packages/electron/src/system-telemetry.integration.test.ts b/packages/electron/src/system-telemetry.integration.test.ts index ecd0154c..1b9ff930 100644 --- a/packages/electron/src/system-telemetry.integration.test.ts +++ b/packages/electron/src/system-telemetry.integration.test.ts @@ -432,7 +432,8 @@ describe('Electron domain trackers -> real node launch -> assembled report', () 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); + // no window/renderer EVENTS, but the displays trace follows the key window: windowFocus + windowMoved only + expect(w.app.count('browser-window-created')).toBe(2); expect(w.app.count('web-contents-created')).toBe(0); expect(w.screen.total()).toBe(3); // the displays trace producer, not the events await client.stop(); @@ -450,9 +451,9 @@ describe('Electron domain trackers -> real node launch -> assembled report', () 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('browser-window-created')).toBe(3); // focus, visibility, moved (the displays trace's key window) expect(w.app.count('web-contents-created')).toBe(1); - expect(win.total()).toBe(6); + expect(win.total()).toBe(8); // focus, blur, show, hide, moved + closed x3 await client.stop(); expect(domainListeners(w)).toBe(0); expect(win.total()).toBe(0); diff --git a/packages/electron/src/system-traces.test.ts b/packages/electron/src/system-traces.test.ts index 3123c14a..b0d9d79a 100644 --- a/packages/electron/src/system-traces.test.ts +++ b/packages/electron/src/system-traces.test.ts @@ -1,5 +1,9 @@ import type { TraceSink } from '@bugsee/capture'; -import { ElectronDisplayTracker, ElectronProcessTracker } from '@bugsee/trackers/electron'; +import { + ElectronApplicationTracker, + ElectronDisplayTracker, + ElectronProcessTracker, +} from '@bugsee/trackers/electron'; import { describe, expect, it, vi } from 'vitest'; import { createElectronSystemTraceProducers } from './system-traces'; @@ -313,3 +317,223 @@ describe('displays producer', () => { d.producer.stop(); }); }); + +describe('displays producer follows the key window (C26)', () => { + type L = (...a: unknown[]) => void; + class Emitter { + table = new Map(); + on = (e: string, l: L) => void this.table.set(e, [...(this.table.get(e) ?? []), l]); + removeListener = (e: string, l: L) => + void this.table.set( + e, + (this.table.get(e) ?? []).filter((x) => x !== l), + ); + emit(e: string) { + for (const l of [...(this.table.get(e) ?? [])]) l({}); + } + total() { + return [...this.table.values()].reduce((n, l) => n + l.length, 0); + } + } + class Win extends Emitter { + gone = false; + constructor( + readonly id: number, + public x: number, + ) { + super(); + } + isDestroyed = () => this.gone; + getBounds = () => ({ x: this.x, y: 0, width: 100, height: 100 }); + } + const mkDisplay = (id: number) => ({ + id, + size: { width: 1000, height: 500 }, + scaleFactor: 1, + }); + + function world(wins: Win[]) { + let focused: Win | null = null; + const app = new Emitter(); + const screen = Object.assign(new Emitter(), { + getAllDisplays: () => [mkDisplay(1), mkDisplay(2)], + getPrimaryDisplay: () => mkDisplay(1), + getDisplayMatching: (r: { x: number }) => mkDisplay(r.x < 1000 ? 1 : 2), + }); + const application = new ElectronApplicationTracker({ + app, + BrowserWindow: { getAllWindows: () => wins, getFocusedWindow: () => focused }, + }); + const display = new ElectronDisplayTracker({ + screen, + keyWindowBounds: () => application.keyWindowBounds(), + }); + const clock = { now: 0, next: 1, timers: new Map void }>() }; + const scheduler = { + setInterval: (cb: () => void, ms: number) => { + const id = clock.next++; + clock.timers.set(id, { at: clock.now + ms, cb }); + return id; + }, + clearInterval: (id: unknown) => void clock.timers.delete(id as number), + }; + const advance = (ms: number) => { + clock.now += ms; + for (const [id, t] of [...clock.timers]) { + if (t.at <= clock.now) { + clock.timers.delete(id); + t.cb(); + } + } + }; + const [producer] = createElectronSystemTraceProducers({ display, application, scheduler }); + const emitted: Array<{ name: string; value: unknown }> = []; + const sink: TraceSink = { emit: (name, value) => emitted.push({ name, value }) }; + const nativeIds = () => + (emitted.at(-1)?.value as Array<{ native_id: number }>).map((d) => d.native_id); + return { + advance, + pendingTimers: () => clock.timers.size, + app, + screen, + application, + producer: producer as NonNullable, + emitted, + sink, + nativeIds, + focus: (w: Win | null) => { + focused = w; + w?.emit('focus'); + }, + }; + } + + it('id 0 is the key window display; the list is re-emitted when focus moves it to another display, and not when it does not', () => { + const a = new Win(1, 10); // on display 1 + const b = new Win(2, 2000); // on display 2 + const w = world([a, b]); + w.producer.start(w.sink); + expect(w.nativeIds()).toEqual([1, 2]); // no focus yet: the first created (a) is the key window + w.focus(b); + expect(w.nativeIds()).toEqual([2, 1]); + expect(w.emitted).toHaveLength(2); + expect(w.emitted.at(-1)?.value).toMatchObject([{ id: 0, state: 'on' }, { id: 1 }]); + w.focus(a); + expect(w.nativeIds()).toEqual([1, 2]); + w.focus(null); // blur: the most recently focused (a) stays the key window + a.emit('blur'); + expect(w.emitted).toHaveLength(3); + w.producer.stop(); + }); + + it('re-emits when the key window is moved to another display (windowMoved)', () => { + const a = new Win(1, 10); + const w = world([a]); + w.producer.start(w.sink); + expect(w.nativeIds()).toEqual([1, 2]); + a.x = 1500; + a.emit('moved'); + expect(w.nativeIds()).toEqual([1, 2]); // debounced: not yet + w.advance(199); + expect(w.nativeIds()).toEqual([1, 2]); + w.advance(1); + expect(w.nativeIds()).toEqual([2, 1]); + w.producer.stop(); + }); + + it('a drag (many `moved` events) is debounced to ONE re-read after the window is still for 200 ms; stop cancels a pending one', () => { + const a = new Win(1, 10); + const w = world([a]); + w.producer.start(w.sink); + const reads = vi.spyOn(w.screen, 'getAllDisplays'); + for (let i = 0; i < 10; i++) { + a.x = 1500; + a.emit('moved'); + w.advance(100); // each event restarts the timer + } + expect(reads).not.toHaveBeenCalled(); + w.advance(100); + expect(reads).toHaveBeenCalledTimes(1); + expect(w.nativeIds()).toEqual([2, 1]); + a.emit('moved'); + expect(w.pendingTimers()).toBe(1); + w.producer.stop(); + expect(w.pendingTimers()).toBe(0); + w.advance(1000); + expect(reads).toHaveBeenCalledTimes(1); + }); + + it('the default scheduler is the global timers', () => { + vi.useFakeTimers(); + try { + const a = new Win(1, 10); + const app = new Emitter(); + const screen = Object.assign(new Emitter(), { + getAllDisplays: () => [mkDisplay(1), mkDisplay(2)], + getPrimaryDisplay: () => mkDisplay(1), + getDisplayMatching: (r: { x: number }) => mkDisplay(r.x < 1000 ? 1 : 2), + }); + const application = new ElectronApplicationTracker({ + app, + BrowserWindow: { getAllWindows: () => [a] }, + }); + const display = new ElectronDisplayTracker({ + screen, + keyWindowBounds: () => application.keyWindowBounds(), + }); + const [producer] = createElectronSystemTraceProducers({ display, application }); + const emitted: Array<{ value: unknown }> = []; + producer?.start({ emit: (_n, value) => emitted.push({ value }) }); + a.x = 1500; + a.emit('moved'); + vi.advanceTimersByTime(200); + expect(emitted).toHaveLength(2); + a.emit('moved'); + producer?.stop(); + vi.advanceTimersByTime(1000); + expect(emitted).toHaveLength(2); + } finally { + vi.useRealTimers(); + } + }); + + it('stop() releases the window listeners too (focus and moved) and nothing re-emits afterwards', () => { + const a = new Win(1, 10); + const w = world([a]); + w.producer.start(w.sink); + expect(a.total()).toBeGreaterThan(0); + w.producer.stop(); + expect(a.total()).toBe(0); + expect(w.app.total()).toBe(0); + expect(w.screen.total()).toBe(0); + a.x = 1500; + a.emit('moved'); + expect(w.emitted).toHaveLength(1); + }); + + it('without an application tracker the list follows the primary display only; with no readable list nothing is emitted', () => { + const screen = Object.assign(new Emitter(), { + getAllDisplays: () => [mkDisplay(1), mkDisplay(2)], + getPrimaryDisplay: () => mkDisplay(2), + }); + const [producer] = createElectronSystemTraceProducers({ + display: new ElectronDisplayTracker({ screen }), + }); + const emitted: Array<{ name: string; value: unknown }> = []; + producer?.start({ emit: (name, value) => emitted.push({ name, value }) }); + expect((emitted[0]?.value as Array<{ native_id: number }>).map((d) => d.native_id)).toEqual([ + 2, 1, + ]); + producer?.stop(); + + const lone = new Win(1, 10); + const w = world([lone]); + (w.screen as { getAllDisplays: () => unknown }).getAllDisplays = () => { + throw new Error('hostile'); + }; + w.producer.start(w.sink); + w.focus(lone); + expect(w.emitted).toEqual([]); + w.producer.stop(); + }); +}); diff --git a/packages/electron/src/system-traces.ts b/packages/electron/src/system-traces.ts index 6435aef2..76e64271 100644 --- a/packages/electron/src/system-traces.ts +++ b/packages/electron/src/system-traces.ts @@ -1,8 +1,10 @@ import { type TraceProducer, TraceProducerBase } from '@bugsee/capture'; +import type { Scheduler } from '@bugsee/core'; import { bytesToMegabytes } from '@bugsee/protocol'; import type { AppProcessMetric, DisplayInfo, + ElectronApplicationTracker, ElectronDisplayTracker, ElectronProcessTracker, } from '@bugsee/trackers/electron'; @@ -32,8 +34,12 @@ import type { // // [{ id, native_id, state?, type?, width, height, natural_width?, natural_height?, scale?, max_fps?, rotation? }] // -// `id` is the stable per-session index (primary first, never reused), `native_id` Electron's own id, `width`/`height` DEVICE -// pixels in the current orientation, `rotation` quarter turns, `state:'on'` on the primary display only (see the tracker). +// `id` `0` is the display showing the KEY window (focused window, else most recently focused, else first created; the primary +// display when there is none), the others follow in ascending order of Electron's id; `native_id` is Electron's own id, +// `width`/`height` DEVICE pixels in the current orientation, `rotation` quarter turns, `state:'on'` on id 0 only (see the +// tracker). `displayId` is never written. The numbering moves with the key window, so the list is ALSO re-read when a window +// gains/loses focus or has moved (debounced 200 ms: macOS fires `moved` throughout a drag) (the application tracker's `windowFocus` / `windowMoved` stages, armed only while +// this producer runs); a re-read that changes nothing is dropped by `emitIfChanged`. Windows on other displays are not recorded. // 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 // `[]`. 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 @@ -95,21 +101,67 @@ function wireDisplay(d: DisplayInfo): Record { }; } +/** A window drag re-reads the display list once it has been still this long (trailing debounce). */ +export const MOVE_SETTLE_MS = 200; +const timers = globalThis as unknown as { + setInterval(callback: () => void, ms: number): unknown; + clearInterval(handle: unknown): void; +}; +const globalScheduler: Scheduler = { + setInterval: (cb, ms) => timers.setInterval(cb, ms), + clearInterval: (h) => timers.clearInterval(h), +}; + class DisplaysProducer extends TraceProducerBase { readonly name = 'displays'; #off: (() => void) | undefined; - constructor(private readonly tracker: ElectronDisplayTracker) { + #offKey: Array<() => void> = []; + #moveTimer: unknown; + #movePending = false; + constructor( + private readonly tracker: ElectronDisplayTracker, + private readonly application?: ElectronApplicationTracker, + private readonly scheduler: Scheduler = globalScheduler, + ) { 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)); + // the key window can change display without any screen event: re-read when focus or position changes + if (this.application !== undefined) { + const reread = (): void => { + const list = this.tracker.current('displays'); + if (list !== undefined) this.#publish(list); + }; + // `moved` is an alias of `move` on macOS (fires throughout a drag): re-read once the window has been still + const rereadSoon = (): void => { + this.#cancelMove(); + this.#movePending = true; + this.#moveTimer = this.scheduler.setInterval(() => { + this.#cancelMove(); + reread(); + }, MOVE_SETTLE_MS); + }; + this.#offKey = [ + this.application.on('windowFocus', reread), + this.application.on('windowMoved', rereadSoon), + ]; + } const list = this.tracker.current('displays'); if (list !== undefined) this.#publish(list); } protected override onStop(): void { this.#off?.(); this.#off = undefined; + for (const off of this.#offKey) off(); + this.#offKey = []; + this.#cancelMove(); + } + #cancelMove(): void { + if (this.#movePending) this.scheduler.clearInterval(this.#moveTimer); + this.#movePending = false; + this.#moveTimer = undefined; } #publish(list: { displays: DisplayInfo[] }): void { this.emitIfChanged('displays', list.displays.map(wireDisplay)); @@ -120,6 +172,10 @@ class DisplaysProducer extends TraceProducerBase { export interface ElectronTraceTrackers { process?: ElectronProcessTracker; display?: ElectronDisplayTracker; + /** Resolves the key window; without it the `displays` list follows the primary display (and no focus changes). */ + application?: ElectronApplicationTracker; + /** Timer source for the window-move debounce (default: the global timers). */ + scheduler?: Scheduler; } /** The Electron producers, each subscribed to ONE stage of a shared tracker. */ @@ -128,6 +184,8 @@ export function createElectronSystemTraceProducers( ): TraceProducer[] { return [ ...(trackers.process !== undefined ? [new AppMetricsProducer(trackers.process)] : []), - ...(trackers.display !== undefined ? [new DisplaysProducer(trackers.display)] : []), + ...(trackers.display !== undefined + ? [new DisplaysProducer(trackers.display, trackers.application, trackers.scheduler)] + : []), ]; } diff --git a/packages/trackers/README.md b/packages/trackers/README.md index 47f62d35..9b1fe07e 100644 --- a/packages/trackers/README.md +++ b/packages/trackers/README.md @@ -24,6 +24,8 @@ Trackers are the abstraction over system and runtime APIs. The package root is r The `./browser` entry exports the `ApplicationTracker` (`applicationTrackerFor`, `resetApplicationTracker`; stages `pagehide`, `visibility`, `state`, `freeze`, `resume`; `online`/`offline` belong to the `ConnectivityTracker` and `orientationchange` to the `UiTracker`), the `PowerTracker` (`powerTrackerFor`, `resetPowerTracker`), the `ConnectivityTracker` (`connectivityTrackerFor`, `resetConnectivityTracker`; stages `online`, `networkInfo`, `state` and `transition`, one per DOM online/offline event with its kind from the event type), 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, visualViewport (pinch zoom and pan), 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. +Page zoom: the `UiTracker` `screenSize` state carries `zoom` and `deviceScale` (`devicePixelRatio / zoom`) only when the derivation is trusted: Chromium, the top-level window, a pointer-fine device, and `outerWidth / innerWidth` within 1.5% of a browser zoom preset (it is snapped to the preset). Otherwise both are omitted and consumers use `devicePixelRatio` alone (docked DevTools, custom zoom, Firefox and Safari). Electron key window: `ElectronApplicationTracker.keyWindowBounds()` (focused window, else most recently focused, else the first visible/created one; new `windowMoved` stage) feeds `ElectronDisplayTracker`'s `keyWindowBounds` seam, which numbers `displays` ids statelessly (key window's display is `0`, the rest ascending by Electron id). + 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 eight stages (`memory`, `systemMemory`, `cpu`, `eventLoop`, `utilization`, `gc`, `v8Heap`, `memoryLimit`) are each armed only while they have listeners, behind one shared sampling timer. The `utilization` stage reports `{ utilizationPercent }` (percent 0-100, one decimal, of the window the loop was not idle; `createGuardedElu` converts perf_hooks' 0..1 fraction). The `gc` stage feeds the `gc` system event (not a trace). 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, and the V8 heap on Bun are gated by the `measures*` flags the platform packages pass in). `systemMemory.free` is memory available to new work in bytes (Android `availMem`): Electron `process.getSystemMemoryInfo()` or Deno `systemMemoryInfo().available` on macOS first, then `/proc/meminfo` MemAvailable where `readsProcMeminfo` is true (Bun only), then `os.freemem()` (not on macOS). Node and Bun on macOS omit it, and it is omitted whenever no source is plausible. Inside a container it is the host's figure; the cap is `process_memory_limit`. 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`, `createSystemFreeReader`, `createElectronMemoryReader`, `createDenoMemoryReader`, `createProcMeminfoReader`, `parseMemAvailable`). The `./node` entry also exports the disk `StorageTracker` (`storageTrackerFor`, `resetStorageTracker`; one singleton per resolved data directory, so launches over the same directory share a tracker and launches over different directories never affect each other; a launch without a data directory gets the shared inert `process`-keyed tracker, and an explicit `key` overrides, for tests) behind the opt-in `disk_mem_free` / `disk_mem_total` traces. Its one stage, `disk` (`{freeBytes, totalBytes}`), reads the volume of the launch's data directory with `fs.promises.statfs` (not `/` or the working directory) at once when a listener arrives and then on its own unref'd 5 s timer, and does nothing while no one listens, when there is no data directory, or when the runtime has no `statfs`. An unreadable or unsane reading emits nothing (a full disk is a true 0 free), and failures are reported once per failure streak. Within one directory's tracker, `onError`, `scheduler` and `statfs` are latest-launch-wins, an omitted seam keeps the earlier one, and a changed seam is applied (and re-read) immediately. Only the merged seams survive the last unsubscribe; the last reading does not. diff --git a/packages/trackers/src/browser/ui-tracker.test.ts b/packages/trackers/src/browser/ui-tracker.test.ts index 3568c1fb..cebcd367 100644 --- a/packages/trackers/src/browser/ui-tracker.test.ts +++ b/packages/trackers/src/browser/ui-tracker.test.ts @@ -196,6 +196,276 @@ describe('UiTracker screenSize and viewport', () => { }); }); +describe('UiTracker page zoom (screenSize.zoom / deviceScale)', () => { + // Chrome, device scale 2: outerWidth is fixed, innerWidth = outer / zoom, devicePixelRatio = zoom x 2. + const at = (outer: unknown, inner: unknown, dpr: number, extra: Record = {}) => { + const w = mkWorld(); + Object.assign(w.win, { + outerWidth: outer, + innerWidth: inner, + devicePixelRatio: dpr, + chrome: {}, + }); + Object.assign(w.win, extra); + return { w, t: new UiTracker(w.env) }; + }; + const bare = { width: 1000, height: 2000, dpr: 2 }; + + it('snaps the derived ratio to the nearest preset and recovers the device scale from it', () => { + expect(at(1600, 1600, 2).t.current('screenSize')).toEqual({ + ...bare, + zoom: 1, + deviceScale: 2, + }); + // every preset, with the integer-rounded innerWidth a real browser reports + const presets: Array<[number, number]> = [ + [0.25, 0.25], + [1 / 3, 0.33], + [0.5, 0.5], + [2 / 3, 0.67], + [0.75, 0.75], + [0.8, 0.8], + [0.9, 0.9], + [1.1, 1.1], + [1.25, 1.25], + [1.5, 1.5], + [1.75, 1.75], + [2, 2], + [2.5, 2.5], + [3, 3], + [4, 4], + [5, 5], + ]; + for (const [preset, field] of presets) { + const s = at(1920, Math.round(1920 / preset), 2 * preset).t.current('screenSize'); + expect(s?.zoom).toBe(field); + expect(s?.deviceScale).toBeCloseTo(2, 5); + } + }); + + it('the device scale is dpr / preset UNROUNDED (the spec formula); only the zoom field is rounded', () => { + expect(at(1600, 1280, 2.5000001).t.current('screenSize')?.deviceScale).toBe(2.5000001 / 1.25); + }); + + it('500% (ratio 5.02 with an integer innerWidth) and 300% (3.01) are trusted and do not flap', () => { + expect(at(1920, 382, 10).t.current('screenSize')).toMatchObject({ zoom: 5 }); // 1920/382 = 5.026 + expect(at(1920, 637, 6).t.current('screenSize')).toMatchObject({ zoom: 3 }); // 3.014 + expect(at(1920, 638, 6).t.current('screenSize')).toMatchObject({ zoom: 3 }); // 3.009 + }); + + it('a resize sweep around one real zoom re-emits nothing (the snapped value is stable)', () => { + const { w, t } = at(1920, 640, 6); + const got: unknown[] = []; + t.on('screenSize', (s) => got.push(s)); + for (const inner of [638, 639, 640, 641, 637]) { + w.win.innerWidth = inner; + w.win.fire('resize'); + } + expect(got).toEqual([]); + }); + + it('docked DevTools / side panel (ratio matches no preset): zoom and deviceScale are omitted, never guessed', () => { + // 1200 window at 100% zoom, DevTools docked: innerWidth 645 -> ratio 1.86 + expect(at(1200, 645, 2).t.current('screenSize')).toEqual(bare); + // 200% zoom with a docked panel: ratio over 5 + expect(at(1200, 200, 4).t.current('screenSize')).toEqual({ ...bare, dpr: 4 }); + }); + + it('frame borders and scrollbars: within 1.5% still snaps, beyond it is omitted', () => { + expect(at(1936, 1920, 2).t.current('screenSize')).toMatchObject({ zoom: 1 }); // +0.83% + expect(at(1950, 1920, 2).t.current('screenSize')).toEqual(bare); // +1.56% + expect(at(1920, 1960, 2).t.current('screenSize')).toEqual(bare); // -2.0% + expect(at(1920, 1900, 2).t.current('screenSize')).toMatchObject({ zoom: 1 }); // +1.05% + }); + + it('a custom (non-preset) zoom such as Chrome 1.2^n steps is omitted', () => { + expect(at(1600, 1600 / 1.44, 2.88).t.current('screenSize')).toEqual({ ...bare, dpr: 2.88 }); + }); + + it('omits zoom (keeping width/height/dpr) when the widths are not usable', () => { + for (const [outer, inner] of [ + [undefined, 800], + [1600, undefined], + [0, 800], + [1600, 0], + [-1600, 800], + [Number.NaN, 800], + [1600, Infinity], + ['1600', 800], + ]) { + expect(at(outer, inner, 2).t.current('screenSize')).toEqual(bare); + } + }); + + it('is trusted ONLY on Chromium: Firefox / Safari-like windows keep dpr-only values and no zoom', () => { + // Firefox at 150%: outerWidth scales with zoom too, so outer == inner and the ratio says 100% + const firefox = mkWorld(); + Object.assign(firefox.win, { outerWidth: 853, innerWidth: 853, devicePixelRatio: 3 }); + expect(new UiTracker(firefox.env).current('screenSize')).toEqual({ ...bare, dpr: 3 }); + // Safari with a plausible ratio of exactly 1.25 and no Chromium tell + const safari = mkWorld(); + Object.assign(safari.win, { + outerWidth: 1600, + innerWidth: 1280, + devicePixelRatio: 2, + navigator: { userAgentData: undefined }, + }); + expect(new UiTracker(safari.env).current('screenSize')).toEqual(bare); + // a non-Chromium brand list is not trusted even with a stray window.chrome absent + expect( + at(1600, 1600, 2, { + chrome: undefined, + navigator: { userAgentData: { brands: [{ brand: 'Safari' }] } }, + }).t.current('screenSize'), + ).toEqual(bare); + }); + + it('Chromium is recognised by its brands (Chromium, Google Chrome, Microsoft Edge) or by window.chrome', () => { + for (const brand of ['Chromium', 'Google Chrome', 'Microsoft Edge']) { + expect( + at(1600, 1600, 2, { + chrome: undefined, + navigator: { userAgentData: { brands: [{ brand: 'Not A;Brand' }, { brand: brand }] } }, + }).t.current('screenSize'), + ).toMatchObject({ zoom: 1 }); + } + // brands present but not Chromium wins over a stray window.chrome + expect( + at(1600, 1600, 2, { + chrome: {}, + navigator: { userAgentData: { brands: [{ brand: 'Safari' }, null, { brand: 7 }] } }, + }).t.current('screenSize'), + ).toEqual(bare); + // window.chrome alone (no userAgentData) is enough + expect(at(1600, 1600, 2, { navigator: {} }).t.current('screenSize')).toMatchObject({ zoom: 1 }); + expect(at(1600, 1600, 2, { chrome: null }).t.current('screenSize')).toEqual(bare); + }); + + it('is not derived inside a frame (window.top is another window), but an absent or equal top is the top window', () => { + expect(at(1200, 400, 2, { top: {} }).t.current('screenSize')).toEqual(bare); + const w = mkWorld(); + Object.assign(w.win, { outerWidth: 1600, innerWidth: 1600, chrome: {}, top: w.win }); + expect(new UiTracker(w.env).current('screenSize')).toMatchObject({ zoom: 1 }); + expect(at(1600, 1600, 2).t.current('screenSize')).toMatchObject({ zoom: 1 }); + }); + + it('omits zoom on a touch-first device (pinch zoom is not page zoom) but keeps it when the query is false or unanswered', () => { + const { w, t } = at(1600, 1600, 2); + t.current('screenSize'); // the fake creates a query list on first ask + q(w, '(pointer: coarse)').matches = true; + expect(t.current('screenSize')).toEqual(bare); + q(w, '(pointer: coarse)').matches = false; + expect(t.current('screenSize')).toMatchObject({ zoom: 1 }); + const noMm = mkWorld(); + Object.assign(noMm.win, { outerWidth: 1600, innerWidth: 1600, chrome: {} }); + const { matchMedia: _drop, ...env } = noMm.env; + expect(new UiTracker(env).current('screenSize')).toMatchObject({ zoom: 1 }); + }); + + it('re-evaluates when (pointer: coarse) changes (touch emulation toggled) without a resize', () => { + const { w, t } = at(1600, 1600, 2); + const got: unknown[] = []; + const off = t.on('screenSize', (s) => got.push(s)); + const coarse = q(w, '(pointer: coarse)'); + expect(coarse.count('change')).toBe(1); + coarse.matches = true; + coarse.fire('change', {}); + coarse.matches = false; + coarse.fire('change', {}); + expect(got).toEqual([bare, { ...bare, zoom: 1, deviceScale: 2 }]); + off(); + expect(coarse.count('change')).toBe(0); + }); + + it('hostile outerWidth / innerWidth / top / navigator / chrome getters never fail the read and are reported', () => { + const boom = (name: string) => ({ + get() { + throw new Error(name); + }, + }); + for (const prop of ['outerWidth', 'innerWidth', 'top', 'navigator', 'chrome']) { + const w = mkWorld(); + const errors: unknown[] = []; + Object.assign(w.win, { outerWidth: 1600, innerWidth: 1600 }); + if (prop !== 'chrome') Object.assign(w.win, { chrome: {} }); + Object.defineProperty(w.win, prop, { ...boom(prop), configurable: true }); + const t = new UiTracker(w.env, (e) => errors.push(e)); + // an unreadable width or `chrome` cannot be trusted; an unreadable `top`/`navigator` falls back to the other tells + const trusted = prop === 'top' || prop === 'navigator'; + expect(t.current('screenSize')).toEqual( + trusted ? { ...bare, zoom: 1, deviceScale: 2 } : bare, + ); + expect(errors.length).toBeGreaterThan(0); + } + }); + + it('re-emits on a resize that changes the zoom, and de-duplicates when nothing moved', () => { + const { w, t } = at(1600, 1600, 2); + const got: unknown[] = []; + t.on('screenSize', (s) => got.push(s)); + w.win.fire('resize'); + expect(got).toEqual([]); + Object.assign(w.win, { innerWidth: 1280, devicePixelRatio: 2.5 }); + w.win.fire('resize'); + expect(got).toEqual([{ ...bare, dpr: 2.5, zoom: 1.25, deviceScale: 2 }]); + }); + + it('watches the (resolution) query for the current ratio, re-arms it on the new ratio after a change, and releases it', () => { + const { w, t } = at(1600, 1600, 2); + const got: unknown[] = []; + const off = t.on('screenSize', (s) => got.push(s)); + const first = q(w, '(resolution: 2dppx)'); + expect(first.count('change')).toBe(1); + // zoom to 125% with NO resize event: only the resolution query fires + Object.assign(w.win, { innerWidth: 1280, devicePixelRatio: 2.5 }); + first.fire('change', {}); + expect(got).toEqual([{ ...bare, dpr: 2.5, zoom: 1.25, deviceScale: 2 }]); + expect(first.count('change')).toBe(0); // old query released + const second = q(w, '(resolution: 2.5dppx)'); + expect(second.count('change')).toBe(1); + off(); + expect(second.count('change')).toBe(0); + }); + + it('a change delivered after release neither re-arms nor publishes', () => { + const { w, t } = at(1600, 1600, 2); + const list = w.env.matchMedia('(resolution: 2dppx)') as unknown as ReturnType; + let late: ((e?: unknown) => void) | undefined; + const add = list.addEventListener; + list.addEventListener = (type, l) => { + late = l; + add(type, l); + }; + const got: unknown[] = []; + const off = t.on('screenSize', (s) => got.push(s)); + off(); + Object.assign(w.win, { innerWidth: 1280, devicePixelRatio: 2.5 }); + late?.({}); + expect(got).toEqual([]); + expect(w.queries.has('(resolution: 2.5dppx)')).toBe(false); + }); + + it('does not watch the resolution query when the ratio is unreadable, and a hostile matchMedia never throws', () => { + const w = mkWorld(); + w.win.devicePixelRatio = 0; + const t = new UiTracker(w.env); + t.on('screenSize', () => {}); + expect([...w.queries.keys()].some((k) => k.startsWith('(resolution'))).toBe(false); + const errors: unknown[] = []; + const hostile = new UiTracker( + { + ...mkWorld().env, + matchMedia: () => { + throw new Error('mm boom'); + }, + }, + (e) => errors.push(e), + ); + expect(() => hostile.on('screenSize', () => {})).not.toThrow(); + expect(errors.length).toBeGreaterThan(0); + }); +}); + describe('UiTracker visualViewport stage', () => { const mkVv = () => Object.assign(mkTarget(), { diff --git a/packages/trackers/src/browser/ui-tracker.ts b/packages/trackers/src/browser/ui-tracker.ts index 7893518b..11a46f70 100644 --- a/packages/trackers/src/browser/ui-tracker.ts +++ b/packages/trackers/src/browser/ui-tracker.ts @@ -41,6 +41,17 @@ export interface ScreenSizeState { width: number; height: number; dpr: number; + /** + * The PAGE zoom (`1` = 100%), TRUSTED only: `outerWidth / innerWidth` must land within 1.5% of a real browser zoom preset + * (25, 33, 50, 67, 75, 80, 90, 100, 110, 125, 150, 175, 200, 250, 300, 400, 500 %) and is SNAPPED to it (so the integer + * `innerWidth` cannot make it flap), on a CHROMIUM engine (Firefox scales `outerWidth` with zoom; older Safari's + * `devicePixelRatio` excludes it), in the TOP-level window, on a pointer-fine device. Otherwise omitted: a docked + * DevTools / side panel, a frame border or custom zoom (Chrome's 1.2^n steps) is not a preset, and the consumer falls back + * to `devicePixelRatio` alone. Rounded to 2 decimals. + */ + zoom?: number; + /** `devicePixelRatio / zoom` (UNROUNDED, the snapped preset): the zoom-independent device scale. Present exactly when `zoom` is. */ + deviceScale?: number; } export interface ViewportState { width: number; @@ -106,6 +117,11 @@ export interface UiEnv { readonly devicePixelRatio?: unknown; readonly innerWidth?: unknown; readonly innerHeight?: unknown; + readonly outerWidth?: unknown; + /** Engine tells for the zoom derivation: `chrome` (Chromium), `navigator.userAgentData.brands`, and `top` (the frame check). */ + readonly chrome?: unknown; + readonly navigator?: unknown; + readonly top?: unknown; /** Where `visualViewport` defaults from when the env supplies none. */ readonly visualViewport?: UiEnv['visualViewport'] | null; }; @@ -168,6 +184,34 @@ const UI_STAGES: readonly UiStage[] = [ 'displayMode', 'frameRate', ]; +/** Chrome's zoom presets as factors (33% and 67% are really 1/3 and 2/3). */ +const ZOOM_PRESETS: readonly number[] = [ + 0.25, + 1 / 3, + 0.5, + 2 / 3, + 0.75, + 0.8, + 0.9, + 1, + 1.1, + 1.25, + 1.5, + 1.75, + 2, + 2.5, + 3, + 4, + 5, +]; +/** A derived ratio is trusted only within this relative distance of a preset (the integer `innerWidth` rounding is < 0.3% at 500%). */ +const ZOOM_TOLERANCE = 0.015; +const CHROMIUM_BRANDS: ReadonlySet = new Set([ + 'Chromium', + 'Google Chrome', + 'Microsoft Edge', +]); +const COARSE_POINTER = '(pointer: coarse)'; const DARK = '(prefers-color-scheme: dark)'; const REDUCED = '(prefers-reduced-motion: reduce)'; const DISPLAY_MODES = ['fullscreen', 'standalone', 'minimal-ui'] as const; @@ -358,9 +402,8 @@ export class UiTracker extends MultiKeyEmitterBase { const width = hostRead(() => screen.width, report); const height = hostRead(() => screen.height, report); const dpr = hostRead(() => this.#env.window?.devicePixelRatio, report); - return positive(width) && positive(height) && positive(dpr) - ? { width, height, dpr } - : undefined; + if (!(positive(width) && positive(height) && positive(dpr))) return undefined; + return { width, height, dpr, ...this.#zoomOf(dpr) }; } case 'viewport': { const win = hostRead(() => this.#env.window, report); @@ -408,6 +451,56 @@ export class UiTracker extends MultiKeyEmitterBase { return fromWindow ?? undefined; } + /** Chromium (its brands, else `window.chrome`) AND the top-level window: the only place the derivation is trusted. */ + #zoomTrusted(): boolean { + const report = this.#report; + const win = hostRead(() => this.#env.window, report); + // a frame sees the TOP window's `outerWidth` but its own `innerWidth`: the ratio is a layout ratio, not a zoom + const top = hostRead(() => win?.top, report); + if (top !== undefined && top !== win) return false; + const brands = hostRead( + () => + (win?.navigator as { userAgentData?: { brands?: unknown } } | null | undefined) + ?.userAgentData?.brands, + report, + ); + if (Array.isArray(brands)) { + return brands.some( + (b: unknown) => + typeof (b as { brand?: unknown } | null)?.brand === 'string' && + CHROMIUM_BRANDS.has((b as { brand: string }).brand), + ); + } + const chrome = hostRead(() => win?.chrome, report); + return typeof chrome === 'object' && chrome !== null; + } + + /** + * The page zoom and the device scale it implies (see {@link ScreenSizeState.zoom}); `{}` unless the derivation is + * trusted. The measured ratio is snapped to the nearest zoom preset within {@link ZOOM_TOLERANCE}. + */ + #zoomOf(dpr: number): { zoom?: number; deviceScale?: number } { + const report = this.#report; + if (!this.#zoomTrusted()) return {}; + const outer = hostRead(() => this.#env.window?.outerWidth, report); + const inner = hostRead(() => this.#env.window?.innerWidth, report); + if (!(positive(outer) && positive(inner))) return {}; + const ratio = outer / inner; + let preset: number | undefined; + let best = ZOOM_TOLERANCE; + for (const p of ZOOM_PRESETS) { + const off = Math.abs(ratio / p - 1); + if (off <= best) { + best = off; + preset = p; + } + } + if (preset === undefined) return {}; + // pinch zoom (`visualViewport.scale`) is not page zoom: a touch-first device does not derive one + if (this.#matches(COARSE_POINTER) === true) return {}; + return { zoom: Math.round(preset * 100) / 100, deviceScale: dpr / preset }; + } + #matches(query: string): boolean | undefined { const report = this.#report; const mm = hostRead(() => this.#env.matchMedia, report); @@ -527,6 +620,49 @@ export class UiTracker extends MultiKeyEmitterBase { this.#guarded(() => this.#refresh(['screenSize'])), ), }, + { + // touch emulation / a pointer-type change flips whether the zoom may be derived at all + id: 'pointer', + kinds: ['screenSize'], + attach: (offs) => + this.#watchQuery( + offs, + COARSE_POINTER, + this.#guarded(() => this.#refresh(['screenSize'])), + ), + }, + { + // A change of the pixel ratio (page zoom, another monitor) fires no `resize` on every engine, but it does flip + // the `(resolution: Ndppx)` query for the CURRENT ratio; re-arm it on the new ratio after every change. + id: 'dpr', + kinds: ['screenSize'], + attach: (offs) => { + let live = true; + let release: Array<() => void> = []; + const disarm = (): void => { + for (const off of release) off(); + release = []; + }; + offs.push(() => { + live = false; + disarm(); + }); + const arm = (): void => { + disarm(); + const dpr = hostRead(() => env().window?.devicePixelRatio, this.#report); + if (!live || !positive(dpr)) return; + this.#watchQuery( + release, + `(resolution: ${dpr}dppx)`, + this.#guarded(() => { + this.#refresh(['screenSize']); + arm(); + }), + ); + }; + arm(); + }, + }, { id: 'visualViewport', kinds: ['visualViewport'], diff --git a/packages/trackers/src/electron/application-tracker.test.ts b/packages/trackers/src/electron/application-tracker.test.ts index f75cd458..1edcd56d 100644 --- a/packages/trackers/src/electron/application-tracker.test.ts +++ b/packages/trackers/src/electron/application-tracker.test.ts @@ -425,6 +425,220 @@ describe('ElectronApplicationTracker', () => { new ElectronApplicationTracker().on('windowFocus', () => {}); }); + it('windowMoved: records the `moved` event (not the continuous `move`) with the window id, released with the stage', () => { + const win = new FakeWindow(4); + const s = setup([win]); + const t = track(s); + const seen = vi.fn(); + const off = t.on('windowMoved', seen); + win.emit('moved'); + win.emit('move'); // continuous `move` is not subscribed + expect(seen.mock.calls).toEqual([[{ windowId: 4 }]]); + expect(win.count('moved')).toBe(1); + off(); + expect(win.count('moved')).toBe(0); + expect(s.app.total()).toBe(0); + }); + + describe('keyWindowBounds', () => { + class BoundsWindow extends FakeWindow { + bounds: unknown; + constructor(id: number, bounds: unknown = { x: id * 100, y: 0, width: 10, height: 10 }) { + super(id); + this.bounds = bounds; + } + getBounds = vi.fn(() => this.bounds); + } + const keyOf = ( + wins: BoundsWindow[], + focused?: () => unknown, + onError?: (e: unknown) => unknown, + ) => { + const s = setup(wins); + const BW = { + getAllWindows: vi.fn(() => wins), + ...(focused !== undefined ? { getFocusedWindow: vi.fn(focused) } : {}), + }; + keys.push(s.app); + return { + s, + BW, + t: electronApplicationTrackerFor({ app: s.app, BrowserWindow: BW }, onError), + }; + }; + + it('is the FOCUSED window (getFocusedWindow) first', () => { + const a = new BoundsWindow(1); + const b = new BoundsWindow(2); + expect(keyOf([a, b], () => b).t.keyWindowBounds()).toEqual({ + x: 200, + y: 0, + width: 10, + height: 10, + }); + }); + + it('else the most recently focused (remembered while windowFocus is armed), else the first created', () => { + const a = new BoundsWindow(1); + const b = new BoundsWindow(2); + const { t } = keyOf([a, b], () => null); + // nothing focused yet and nothing remembered: the first created + expect(t.keyWindowBounds()).toEqual({ x: 100, y: 0, width: 10, height: 10 }); + t.on('windowFocus', () => undefined); + b.emit('focus'); + b.emit('blur'); + a.emit('blur'); // a blur is not a focus: b stays the most recently focused + expect(t.keyWindowBounds()).toEqual({ x: 200, y: 0, width: 10, height: 10 }); + a.emit('focus'); + expect(t.keyWindowBounds()).toEqual({ x: 100, y: 0, width: 10, height: 10 }); + }); + + it('a closed or destroyed window is never the key window: falls through to the next rule', () => { + const a = new BoundsWindow(1); + const b = new BoundsWindow(2); + const c = new BoundsWindow(3); + const { t } = keyOf([a, b, c], () => c); + t.on('windowFocus', () => undefined); + b.emit('focus'); + c.close(); // focused (destroyed) -> most recent (b) + expect(t.keyWindowBounds()).toEqual({ x: 200, y: 0, width: 10, height: 10 }); + b.close(); // forgotten on `closed` -> first listed that is alive (a) + expect(t.keyWindowBounds()).toEqual({ x: 100, y: 0, width: 10, height: 10 }); + a.gone = true; // destroyed without a `closed` event + expect(t.keyWindowBounds()).toBeUndefined(); + }); + + it('the FOCUSED window outranks the most recently focused one when they disagree', () => { + const a = new BoundsWindow(1); + const b = new BoundsWindow(2); + let focused: BoundsWindow | null = a; + const { t } = keyOf([a, b], () => focused); + t.on('windowFocus', () => undefined); + b.emit('focus'); // remembered as most recent... + expect(t.keyWindowBounds()).toEqual({ x: 100, y: 0, width: 10, height: 10 }); // ...but Electron says a is focused + focused = null; + expect(t.keyWindowBounds()).toEqual({ x: 200, y: 0, width: 10, height: 10 }); + }); + + it('the most-recently-focused memory is dropped when the windowFocus stage is released (a re-arm never trusts a stale window)', () => { + const a = new BoundsWindow(1); + const b = new BoundsWindow(2); + const { t } = keyOf([a, b], () => null); + const off = t.on('windowFocus', () => undefined); + b.emit('focus'); + expect(t.keyWindowBounds()).toEqual({ x: 200, y: 0, width: 10, height: 10 }); + off(); + expect(t.keyWindowBounds()).toEqual({ x: 100, y: 0, width: 10, height: 10 }); + // an unrelated stage's release does not drop it + const off2 = t.on('windowFocus', () => undefined); + b.emit('focus'); + const offOther = t.on('windowMoved', () => undefined); + offOther(); + expect(t.keyWindowBounds()).toEqual({ x: 200, y: 0, width: 10, height: 10 }); + off2(); + }); + + it('with nothing focused, a VISIBLE window is preferred over a hidden first one; none visible falls back to the first', () => { + const hidden = new BoundsWindow(1); + const shown = new BoundsWindow(2); + (hidden as unknown as { isVisible: () => boolean }).isVisible = () => false; + (shown as unknown as { isVisible: () => boolean }).isVisible = () => true; + expect(keyOf([hidden, shown], () => null).t.keyWindowBounds()).toEqual({ + x: 200, + y: 0, + width: 10, + height: 10, + }); + // a window that cannot say (no isVisible) is not counted as visible + const mute = new BoundsWindow(5); + expect(keyOf([mute, shown], () => null).t.keyWindowBounds()).toEqual({ + x: 200, + y: 0, + width: 10, + height: 10, + }); + const h2 = new BoundsWindow(3); + (h2 as unknown as { isVisible: () => boolean }).isVisible = () => false; + const throwing = new BoundsWindow(4); + (throwing as unknown as { isVisible: () => never }).isVisible = () => { + throw new Error('vis'); + }; + expect(keyOf([h2, throwing], () => null).t.keyWindowBounds()).toEqual({ + x: 300, + y: 0, + width: 10, + height: 10, + }); + }); + + it('a most-recently-focused window that closed (event only) or was destroyed (no event) is not remembered', () => { + const a = new BoundsWindow(1); + const b = new BoundsWindow(2); + const { t } = keyOf([a, b], () => null); + t.on('windowFocus', () => undefined); + b.emit('focus'); + b.emit('closed'); // forgotten on the event even though isDestroyed is still false + expect(t.keyWindowBounds()).toEqual({ x: 100, y: 0, width: 10, height: 10 }); + b.emit('focus'); // (its listeners are gone after closed; re-remember through a fresh arm is not possible) + const c = new BoundsWindow(3); + const d = new BoundsWindow(4); + const second = keyOf([c, d], () => null); + second.t.on('windowFocus', () => undefined); + d.emit('focus'); + d.gone = true; // destroyed without `closed` + expect(second.t.keyWindowBounds()).toEqual({ x: 300, y: 0, width: 10, height: 10 }); + }); + + it('is undefined with no windows, without BrowserWindow, or without getBounds', () => { + expect(keyOf([]).t.keyWindowBounds()).toBeUndefined(); + const s = setup([]); + expect(track(s, undefined, false).keyWindowBounds()).toBeUndefined(); + const noBounds = new FakeWindow(1); + expect(keyOf([noBounds as BoundsWindow]).t.keyWindowBounds()).toBeUndefined(); + }); + + it('hostile getFocusedWindow / getAllWindows / getBounds never throw and are reported', () => { + const onError = vi.fn(); + const a = new BoundsWindow(1); + const { t } = keyOf( + [a], + () => { + throw new Error('focused'); + }, + onError, + ); + expect(t.keyWindowBounds()).toEqual({ x: 100, y: 0, width: 10, height: 10 }); // falls to first created + expect(onError).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ message: 'focused' }), + ); + const onError2 = vi.fn(); + const s = setup([]); + keys.push(s.app); + const t2 = electronApplicationTrackerFor( + { + app: s.app, + BrowserWindow: { + getAllWindows: () => { + throw new Error('all'); + }, + }, + }, + onError2, + ); + expect(t2.keyWindowBounds()).toBeUndefined(); + expect(onError2).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: 'all' })); + const onError3 = vi.fn(); + const bad = new BoundsWindow(1); + bad.getBounds = vi.fn(() => { + throw new Error('bounds'); + }); + expect(keyOf([bad], undefined, onError3).t.keyWindowBounds()).toBeUndefined(); + expect(onError3).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ message: 'bounds' }), + ); + }); + }); + describe('registry / rebind', () => { it('is a singleton per app; throws without one', () => { const s = setup(); diff --git a/packages/trackers/src/electron/application-tracker.ts b/packages/trackers/src/electron/application-tracker.ts index ba72e464..7d45403f 100644 --- a/packages/trackers/src/electron/application-tracker.ts +++ b/packages/trackers/src/electron/application-tracker.ts @@ -2,11 +2,13 @@ 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 +// BugseeTrackerApplication). It owns the app's WINDOWS and renderers as FOUR 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? } +// windowMoved BrowserWindow 'moved' -> { windowId? } (macOS: an alias of `move`, so it fires +// throughout a drag; Windows: end of drag; consumers debounce) // rendererResponsiveness webContents 'unresponsive' / 'responsive' -> { responsive: boolean, webContentsId? } // // DISCOVERY. Apps typically call `launchMain` and then `createWindow()` from `whenReady()`, so a stage watches BOTH the @@ -23,6 +25,11 @@ import { bindAll, ElectronStageTracker, type EmitterSource } from './stage-track // (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. // +// KEY WINDOW (spec platforms/javascript.md "Several windows in one session"): `keyWindowBounds()` resolves the ONE window +// the session records per-window state for: the focused `BrowserWindow` (`getFocusedWindow`), else the most recently +// focused one (remembered while the `windowFocus` stage is armed; forgotten on its `closed`), else the first window +// `getAllWindows()` lists (creation order). Every read is guarded and reported; a destroyed window is never the key 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. @@ -33,11 +40,14 @@ export type ApplicationAppSource = EmitterSource; /** The slice of Electron's `BrowserWindow` class this tracker uses: only the static `getAllWindows`. */ export interface BrowserWindowSource { getAllWindows?(): unknown; + /** The focused window, or null when the app is not focused. */ + getFocusedWindow?(): unknown; } export interface ElectronApplicationEvents { windowFocus: { focused: boolean; windowId?: number }; windowVisibility: { visible: boolean; windowId?: number }; + windowMoved: { windowId?: number }; rendererResponsiveness: { responsive: boolean; webContentsId?: number }; } @@ -54,6 +64,8 @@ interface Watched extends EmitterSource { id?: unknown; isDestroyed?(): unknown; webContents?: unknown; + getBounds?(): unknown; + isVisible?(): unknown; } interface WatchConfig { @@ -95,6 +107,15 @@ const WATCH: { [S in AppStage]: WatchConfig } = { hide: (id) => ({ visible: false, ...withId('windowId', id) }), }, }, + windowMoved: { + createdEvent: 'browser-window-created', + closeEvent: 'closed', + existing: windowsOf, + idKey: 'windowId', + events: { + moved: (id) => withId('windowId', id), + }, + }, rendererResponsiveness: { createdEvent: 'web-contents-created', closeEvent: 'destroyed', @@ -114,6 +135,14 @@ const WATCH: { [S in AppStage]: WatchConfig } = { }, }; +const visible = (w: Watched): boolean => { + try { + return w.isVisible?.() === true; + } catch { + return false; + } +}; + const destroyed = (obj: Watched): boolean => { try { return obj.isDestroyed?.() === true; @@ -135,10 +164,13 @@ export class ElectronApplicationTracker extends ElectronStageTracker unknown) { super(onError); @@ -160,6 +192,41 @@ export class ElectronApplicationTracker extends ElectronStageTracker + typeof w === 'object' && w !== null && !destroyed(w as Watched); + try { + const focused = this.#env.BrowserWindow?.getFocusedWindow?.(); + if (usable(focused)) return focused; + } catch (error) { + this.report(error); + } + const last = this.#lastFocused; + if (last !== undefined && usable(last)) return last; + try { + // `getAllWindows()` order is not documented (in practice creation order): the first VISIBLE window is preferred so a hidden + // background window (a tray/worker window) is not taken as the first created; with none visible, the first usable one. + const all = windowsOf(this.#env).filter(usable); + return all.find(visible) ?? all[0]; + } catch (error) { + this.report(error); + return undefined; + } + } + + /** The key window's bounds (a rectangle), or undefined when there is no key window or it cannot say. Never throws. */ + keyWindowBounds(): unknown { + const win = this.#keyWindow(); + if (win === undefined) return undefined; + try { + return win.getBounds?.(); + } catch (error) { + this.report(error); + return undefined; + } + } + protected attachStage(stage: AppStage): (() => void) | undefined { const app = this.#app; if (app === undefined) return undefined; @@ -174,7 +241,10 @@ export class ElectronApplicationTracker extends ElectronStageTracker ({ src: obj, event, - listener: () => this.emit(stage, payload(idOf(obj)) as never), + listener: () => { + if (event === 'focus') this.#lastFocused = obj; // only the windowFocus stage binds `focus` + this.emit(stage, payload(idOf(obj)) as never); + }, })); bindings.push({ src: obj, @@ -182,6 +252,7 @@ export class ElectronApplicationTracker extends ElectronStageTracker { tracked.delete(candidate); + if (this.#lastFocused === obj) this.#lastFocused = undefined; }, }); const release = bindAll(bindings, this.report); @@ -198,6 +269,8 @@ export class ElectronApplicationTracker extends ElectronStageTracker { + // the most-recently-focused memory is only valid while focus is observed: a re-arm must not trust a stale window + if (stage === 'windowFocus') this.#lastFocused = undefined; releaseApp(); // bindAll's release never throws: failed removals are reported inside it for (const [candidate, release] of [...tracked]) { if (!destroyed(candidate as Watched)) release(); diff --git a/packages/trackers/src/electron/display-tracker.test.ts b/packages/trackers/src/electron/display-tracker.test.ts index 83bb564d..66abd2b1 100644 --- a/packages/trackers/src/electron/display-tracker.test.ts +++ b/packages/trackers/src/electron/display-tracker.test.ts @@ -247,67 +247,147 @@ describe('ElectronDisplayTracker', () => { expect(s.count('display-added')).toBe(1); }); - describe('session ids and state', () => { - it('numbers the PRIMARY display 0 even when getAllDisplays lists it later, then the rest in order', () => { - const s = fakeScreen(() => [display({ id: 7 }), display({ id: 5 }), display({ id: 6 })], { - getPrimaryDisplay: vi.fn(() => display({ id: 5 })), + describe('key-window numbering and state', () => { + const trackKey = ( + s: ReturnType, + keyWindowBounds?: () => unknown, + onError?: (e: unknown) => unknown, + ) => { + keys.push(s.screen); + return electronDisplayTrackerFor( + { screen: s.screen, ...(keyWindowBounds !== undefined ? { keyWindowBounds } : {}) }, + onError, + ); + }; + /** A screen whose getDisplayMatching answers by the rectangle's `x` (display id = x). */ + const keyed = (ids: number[], primary = ids[0] as number) => + fakeScreen(() => ids.map((id) => display({ id })), { + getPrimaryDisplay: vi.fn(() => display({ id: primary })), + getDisplayMatching: vi.fn((r: { x: number }) => display({ id: r.x })), }); - const list = track(s).current('displays')?.displays; - expect(list?.map((d) => [d.nativeId, d.id])).toEqual([ - [7, 1], - [5, 0], - [6, 2], + + it('numbers the KEY window display 0 and the rest ascending by Electron id, state:on on id 0 only', () => { + const s = keyed([7, 5, 6], 7); + const list = trackKey(s, () => ({ x: 6, y: 0, width: 1, height: 1 })).current( + 'displays', + )?.displays; + expect(list?.map((d) => [d.nativeId, d.id, d.state])).toEqual([ + [6, 0, 'on'], + [5, 1, undefined], + [7, 2, undefined], ]); + expect(s.screen.getDisplayMatching).toHaveBeenCalledWith({ x: 6, y: 0, width: 1, height: 1 }); }); - it('marks state:on on the primary display only', () => { - const s = fakeScreen(() => [display({ id: 7 }), display({ id: 5 })], { - getPrimaryDisplay: vi.fn(() => display({ id: 5 })), + it('is recomputed on every read: the key window moving display renumbers (no session memory)', () => { + const s = keyed([1, 2, 3]); + let x = 1; + const t = trackKey(s, () => ({ x })); + expect(t.current('displays')?.displays.map((d) => [d.nativeId, d.id])).toEqual([ + [1, 0], + [2, 1], + [3, 2], + ]); + x = 3; + expect(t.current('displays')?.displays.map((d) => [d.nativeId, d.id])).toEqual([ + [3, 0], + [1, 1], + [2, 2], + ]); + x = 2; + expect(t.current('displays')?.displays.map((d) => [d.nativeId, d.id, d.state])).toEqual([ + [2, 0, 'on'], + [1, 1, undefined], + [3, 2, undefined], + ]); + }); + it('falls back to the PRIMARY display for id 0 when there is no key window (or no source)', () => { + const ids = [7, 5, 6]; + for (const source of [undefined, () => undefined, () => 'not a rect']) { + const s = keyed(ids, 6); + const list = trackKey(s, source).current('displays')?.displays; + expect(list?.map((d) => [d.nativeId, d.id, d.state])).toEqual([ + [6, 0, 'on'], + [5, 1, undefined], + [7, 2, undefined], + ]); + expect(s.screen.getDisplayMatching).not.toHaveBeenCalled(); + resetElectronDisplayTracker(s.screen); + } + }); + it('falls back to the primary when getDisplayMatching is missing or names a display not in the list', () => { + const a = keyed([2, 1], 2); + const noMatch = { ...a, screen: a.screen }; + (noMatch.screen as { getDisplayMatching?: unknown }).getDisplayMatching = undefined; + expect( + trackKey(noMatch, () => ({ x: 1 })) + .current('displays') + ?.displays.map((d) => d.nativeId), + ).toEqual([2, 1]); + const b = keyed([2, 1], 2); + expect( + trackKey(b, () => ({ x: 99 })) + .current('displays') + ?.displays.map((d) => d.nativeId), + ).toEqual([2, 1]); + const c = fakeScreen(() => [display({ id: 4 }), display({ id: 2 })], { + getPrimaryDisplay: undefined, + getDisplayMatching: vi.fn(() => null), }); - const list = track(s).current('displays')?.displays; - expect(list?.map((d) => d.state)).toEqual([undefined, 'on']); + expect( + trackKey(c, () => ({ x: 1 })) + .current('displays') + ?.displays.map((d) => [d.nativeId, d.id, d.state]), + ).toEqual([ + [2, 0, 'on'], + [4, 1, undefined], + ]); }); - it('without getPrimaryDisplay: numbering follows getAllDisplays and no state is written', () => { + it('without getPrimaryDisplay and without a key window: ascending Electron id, id 0 still carries state:on', () => { const s = fakeScreen(() => [display({ id: 7 }), display({ id: 5 })], { getPrimaryDisplay: undefined, }); - const list = track(s).current('displays')?.displays; - expect(list?.map((d) => [d.id, d.state])).toEqual([ - [0, undefined], - [1, undefined], + expect( + track(s) + .current('displays') + ?.displays.map((d) => [d.nativeId, d.id, d.state]), + ).toEqual([ + [5, 0, 'on'], + [7, 1, undefined], ]); }); - it('never reuses a number: a removed display keeps its id, a later one takes the next unused', () => { - let list: unknown[] = [display({ id: 1 }), display({ id: 2 })]; - const s = fakeScreen(() => list); - const t = track(s); - expect(t.current('displays')?.displays.map((d) => d.id)).toEqual([0, 1]); - list = [display({ id: 1 })]; - expect(t.current('displays')?.displays.map((d) => d.id)).toEqual([0]); - list = [display({ id: 1 }), display({ id: 3 })]; - expect(t.current('displays')?.displays.map((d) => [d.nativeId, d.id])).toEqual([ - [1, 0], - [3, 2], + it('a throwing / hostile key-window source or getDisplayMatching is reported and the list is still produced', () => { + const onError = vi.fn(); + const a = keyed([3, 1], 3); + const list = trackKey( + a, + () => { + throw new Error('bounds'); + }, + onError, + ).current('displays')?.displays; + expect(list?.map((d) => [d.nativeId, d.id])).toEqual([ + [3, 0], + [1, 1], ]); - list = [display({ id: 1 }), display({ id: 2 }), display({ id: 3 })]; - expect(t.current('displays')?.displays.map((d) => d.id)).toEqual([0, 1, 2]); - }); - it('only the FIRST read puts the primary first: displays appearing later are numbered in list order even if one became primary', () => { - let list: unknown[] = [display({ id: 1 })]; - let primary = 1; - const s = fakeScreen(() => list, { - getPrimaryDisplay: vi.fn(() => display({ id: primary })), + expect(onError).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ message: 'bounds' }), + ); + const onError2 = vi.fn(); + const b = fakeScreen(() => [display({ id: 3 }), display({ id: 1 })], { + getDisplayMatching: vi.fn(() => { + throw new Error('matching'); + }), }); - const t = track(s); - expect(t.current('displays')?.displays.map((d) => d.id)).toEqual([0]); - list = [display({ id: 1 }), display({ id: 8 }), display({ id: 9 })]; - primary = 9; - expect(t.current('displays')?.displays.map((d) => [d.nativeId, d.id])).toEqual([ - [1, 0], - [8, 1], - [9, 2], - ]); + expect( + trackKey(b, () => ({ x: 1 }), onError2) + .current('displays') + ?.displays.map((d) => d.nativeId), + ).toEqual([3, 1]); + expect(onError2).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ message: 'matching' }), + ); }); - it('a throwing getPrimaryDisplay is reported ONCE and the list is still produced, without state', () => { + it('a throwing getPrimaryDisplay is reported ONCE and the list is still produced (ascending, id 0 on)', () => { const onError = vi.fn(); const s = fakeScreen(() => [display({ id: 7 }), display({ id: 5 })], { getPrimaryDisplay: vi.fn(() => { @@ -316,51 +396,37 @@ describe('ElectronDisplayTracker', () => { }); const list = track(s, onError).current('displays')?.displays; expect(list?.map((d) => [d.nativeId, d.id, d.state])).toEqual([ - [7, 0, undefined], - [5, 1, undefined], + [5, 0, 'on'], + [7, 1, undefined], ]); expect(onError).toHaveBeenCalledTimes(1); }); - it('numbering restarts at 0 (primary first) for a new session: forgotten when the last subscriber leaves', () => { - let primary = 1; - const s = fakeScreen(() => [display({ id: 1 }), display({ id: 2 })], { - getPrimaryDisplay: vi.fn(() => display({ id: primary })), - }); - const t = track(s); - const off = t.on('displays', () => undefined); - expect(t.current('displays')?.displays.map((d) => [d.nativeId, d.id])).toEqual([ - [1, 0], - [2, 1], - ]); - const other = t.on('displayAdded', () => undefined); - off(); - // still subscribed through another stage: same session, numbering kept - primary = 2; - expect(t.current('displays')?.displays.map((d) => [d.nativeId, d.id])).toEqual([ - [1, 0], - [2, 1], - ]); - other(); - t.on('displays', () => undefined); - expect(t.current('displays')?.displays.map((d) => [d.nativeId, d.id])).toEqual([ - [1, 1], - [2, 0], - ]); + it('a relaunch hands the shared tracker the new key-window source; one without a source CLEARS the old (it would read a stale tracker)', () => { + const s = keyed([1, 2]); + const t = trackKey(s, () => ({ x: 2 })); + expect(t.current('displays')?.displays[0]?.nativeId).toBe(2); + electronDisplayTrackerFor({ screen: s.screen, keyWindowBounds: () => ({ x: 1 }) }); + expect(t.current('displays')?.displays[0]?.nativeId).toBe(1); + expect(electronDisplayTrackerFor({ screen: s.screen })).toBe(t); + expect(t.current('displays')?.displays[0]?.nativeId).toBe(1); // no key window now: the primary (1) + expect(s.screen.getDisplayMatching).toHaveBeenCalledTimes(2); // not consulted by the cleared third read }); - it('events carry the same session id as the list, seeding the numbering on a first event', () => { - const s = fakeScreen(() => [display({ id: 9 }), display({ id: 4 })], { + it('events carry the id the display has in the CURRENT list; a removed display takes the next number; no state', () => { + let list: unknown[] = [display({ id: 9 }), display({ id: 4 })]; + const s = fakeScreen(() => list, { getPrimaryDisplay: vi.fn(() => display({ id: 4 })), }); const t = track(s); - const seen = vi.fn(); - t.on('displayAdded', seen); + const added = vi.fn(); + const removed = vi.fn(); + t.on('displayAdded', added); + t.on('displayRemoved', removed); s.fire('display-added', display({ id: 9 })); - expect(seen.mock.calls[0]?.[0]).toMatchObject({ nativeId: 9, id: 1 }); - expect(seen.mock.calls[0]?.[0]).not.toHaveProperty('state'); - expect(t.current('displays')?.displays.map((d) => [d.nativeId, d.id])).toEqual([ - [9, 1], - [4, 0], - ]); + expect(added.mock.calls[0]?.[0]).toMatchObject({ nativeId: 9, id: 1 }); + expect(added.mock.calls[0]?.[0]).not.toHaveProperty('state'); + list = [display({ id: 4 })]; + s.fire('display-removed', display({ id: 9 })); + expect(removed.mock.calls[0]?.[0]).toMatchObject({ nativeId: 9, id: 1 }); }); it('a throwing getAllDisplays at the first event is reported and the display still gets the next number', () => { const onError = vi.fn(); diff --git a/packages/trackers/src/electron/display-tracker.ts b/packages/trackers/src/electron/display-tracker.ts index 5c31ed27..b10e7f28 100644 --- a/packages/trackers/src/electron/display-tracker.ts +++ b/packages/trackers/src/electron/display-tracker.ts @@ -11,15 +11,20 @@ import { bindAll, ElectronStageTracker, type EmitterSource } from './stage-track // displays any of the three above -> { displays: DisplayInfo[] } (the fresh `getAllDisplays()` list) // // `current('displays')` is a LIVE `screen.getAllDisplays()` read. {@link DisplayInfo} is the MOBILE `displays` entry in -// camelCase (spec bundle/traces.md `displays`): `id` is a small per-session index (the display set at the first read is -// numbered from 0 with `screen.getPrimaryDisplay()` FIRST, later displays take the next unused number, a number is NEVER -// reused within a SESSION even after a display is removed; the numbering is forgotten when the LAST subscriber leaves -// (a session stop / relaunch), so the next session numbers again from 0 with the then-current primary first), `nativeId` is Electron's own id (can exceed int32), +// camelCase (spec bundle/traces.md `displays`; platforms/javascript.md "Several windows in one session"). `id` follows +// the iOS rule and is STATELESS, recomputed on every read: `0` is the display showing the KEY window (the focused window, +// else the most recently focused, else the first created: resolved by the application tracker and injected as +// `keyWindowBounds`, matched to a display with `screen.getDisplayMatching`), the other displays follow in ASCENDING order +// of Electron's id. With no key window (none created yet, or the bounds unreadable) the PRIMARY display takes `0`, and +// with no primary either the lowest Electron id does. Because the numbering moves with the key window, the producer +// re-reads on focus / window-moved changes too. `nativeId` is Electron's own id (can exceed int32), // `width`/`height` are DEVICE pixels in the CURRENT orientation (`size` x `scaleFactor`, rounded), `naturalWidth`/ // `naturalHeight` the rotation-0 device pixels (swapped for quarter turns 1 and 3; omitted when the rotation is unknown), // `scale` = `scaleFactor`, `maxFps` = `displayFrequency` rounded, `rotation` in QUARTER TURNS 0-3 (Electron's 0/90/180/270 -// divided by 90), `type` internal|external from `internal`, and `state:'on'` on the CURRENT primary display only (Electron -// cannot observe power; the spec says a producer that cannot observe power marks the one display the app is on). +// divided by 90), `type` internal|external from `internal`, and `state:'on'` on id 0 ONLY (Electron cannot observe power; +// the spec says a producer that cannot observe power marks the one display the app is recorded on). +// Event payloads (`displayAdded`/`Removed`/`MetricsChanged`) carry the id the display has in the CURRENT list; a REMOVED +// display is no longer in the list and takes the number after the last listed one. Windows on other displays are not recorded. // 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. Without a readable `scaleFactor` the factor is 1 @@ -30,15 +35,17 @@ import { bindAll, ElectronStageTracker, type EmitterSource } from './stage-track // 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. +// SINGLETON per `screen` object (`electronDisplayTrackerFor`); a relaunch only rebinds the reporter and the key-window source. /** The slice of Electron's `screen` this tracker reads. */ export interface ScreenSource extends EmitterSource { getAllDisplays?(): unknown; getPrimaryDisplay?(): unknown; + /** The display a rectangle (a window's bounds) mostly sits on. */ + getDisplayMatching?(rect: unknown): unknown; } -/** What one Electron `Display` says, before the session index is assigned (see {@link DisplayInfo}). */ +/** What one Electron `Display` says, before its `id` is assigned (see {@link DisplayInfo}). */ export interface MappedDisplay { /** Electron's own display id (`Display.id`). */ nativeId: number; @@ -57,7 +64,7 @@ export interface MappedDisplay { type?: 'internal' | 'external'; } -/** A {@link MappedDisplay} with its stable per-session `id` (and `state` on the primary display of a list read). */ +/** A {@link MappedDisplay} with its `id` (0 = the key window's display) and `state:'on'` on id 0 of a list read. */ export interface DisplayInfo extends MappedDisplay { id: number; state?: 'on'; @@ -73,6 +80,8 @@ export interface ElectronDisplayEvents { export interface ElectronDisplayEnv { /** Electron's `screen` (or a structural fake). */ screen?: ScreenSource; + /** The KEY window's bounds (a rectangle for `screen.getDisplayMatching`), or undefined when there is none. May throw. */ + keyWindowBounds?: () => unknown; } type DisplayStage = keyof ElectronDisplayEvents; @@ -148,38 +157,27 @@ export class ElectronDisplayTracker extends ElectronStageTracker the session index. Grows within a session (a number is never reused); cleared with the last subscriber. */ - readonly #ids = new Map(); + #keyWindowBounds: (() => unknown) | undefined; constructor(env: ElectronDisplayEnv = {}, onError?: (error: unknown) => unknown) { super(onError); this.#screen = env.screen; + this.#keyWindowBounds = env.keyWindowBounds; } - /** Hand the latest launch's reporter to this shared tracker (a defined `onError` replaces it, undefined keeps it). */ - rebind(onError?: (error: unknown) => unknown): void { + /** + * Hand the latest launch's reporter (a defined one replaces, undefined keeps) and key-window source to this shared tracker. + * The key-window source is the LAUNCH's: a relaunch without one (no `app`) clears the previous launch's, which would + * otherwise keep reading a stale application tracker. + */ + rebind(onError?: (error: unknown) => unknown, keyWindowBounds?: () => unknown): void { this.setReporter(onError); - } - - /** The session index for an Electron display id: the first sight takes the next unused number. */ - #indexOf(nativeId: number): number { - let id = this.#ids.get(nativeId); - if (id === undefined) { - id = this.#ids.size; - this.#ids.set(nativeId, id); - } - return id; - } - - /** A new session starts numbering from 0 again: forget the numbers once nothing listens any more. */ - protected override onListenersChanged(): void { - super.onListenersChanged(); - if (this.stages.every((stage) => this.listenerCount(stage) === 0)) this.#ids.clear(); + this.#keyWindowBounds = keyWindowBounds; } /** - * The Electron id of the primary display, GUARDED on its own: a throwing/hostile `getPrimaryDisplay` is reported once - * and answers undefined, so the list is still produced (just without `state`, and not primary-first). + * The Electron id of the primary display, GUARDED on its own: a throwing/hostile `getPrimaryDisplay` is reported and + * answers undefined, so the list is still produced. */ #primaryNativeId(screen: ScreenSource): number | undefined { try { @@ -191,11 +189,38 @@ export class ElectronDisplayTracker extends ElectronStageTracker 0) return; - if (primary !== undefined) this.#indexOf(primary); - for (const d of all) this.#indexOf(d.nativeId); + /** The Electron id of the display showing the key window, GUARDED (a throwing source or `getDisplayMatching` is reported). */ + #keyNativeId(screen: ScreenSource): number | undefined { + try { + const bounds = this.#keyWindowBounds?.(); + if (record(bounds) === undefined || typeof screen.getDisplayMatching !== 'function') { + return undefined; + } + return mapDisplay(screen.getDisplayMatching(bounds))?.nativeId; + } catch (error) { + this.report(error); + return undefined; + } + } + + /** The list in id order: the key display (else the primary) first, the rest ascending by Electron id. */ + #ordered(screen: ScreenSource, mapped: readonly MappedDisplay[]): MappedDisplay[] { + const key = this.#keyNativeId(screen); + const first = mapped.some((d) => d.nativeId === key) ? key : this.#primaryNativeId(screen); + return [...mapped].sort( + (a, b) => + Number(b.nativeId === first) - Number(a.nativeId === first) || a.nativeId - b.nativeId, + ); + } + + /** The mapped, non-empty display list from `getAllDisplays()`; throws on a hostile screen (callers guard). */ + #readAll(screen: ScreenSource): MappedDisplay[] | undefined { + // inside the callers' 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 mapped = raw.map(mapDisplay).filter((d): d is MappedDisplay => d !== undefined); + return mapped.length === 0 ? undefined : mapped; } /** The live display list, or undefined when Electron cannot say (never an empty/zero list). */ @@ -203,20 +228,10 @@ export class ElectronDisplayTracker extends ElectronStageTracker d !== undefined); - if (mapped.length === 0) return undefined; - const primary = this.#primaryNativeId(screen); - this.#seed(primary, mapped); - const displays = mapped.map( - (d): DisplayInfo => ({ - id: this.#indexOf(d.nativeId), - ...d, - ...(d.nativeId === primary ? { state: 'on' as const } : {}), - }), + const mapped = this.#readAll(screen); + if (mapped === undefined) return undefined; + const displays = this.#ordered(screen, mapped).map( + (d, id): DisplayInfo => ({ id, ...d, ...(id === 0 ? { state: 'on' as const } : {}) }), ); return { displays }; } catch (error) { @@ -225,27 +240,20 @@ export class ElectronDisplayTracker extends ElectronStageTracker d !== undefined) - : [], - ); - } + const mapped = this.#readAll(screen); + if (mapped !== undefined) listed = this.#ordered(screen, mapped); } catch (error) { this.report(error); } - // Without `getAllDisplays` nothing seeds the numbering, so an event's display takes the next unused number (0 when it - // is the first thing seen) even when it is not the primary. - return { id: this.#indexOf(display.nativeId), ...display }; + const at = listed.findIndex((d) => d.nativeId === display.nativeId); + return { id: at === -1 ? listed.length : at, ...display }; } protected attachStage(stage: DisplayStage): (() => void) | undefined { @@ -303,7 +311,7 @@ export function electronDisplayTrackerFor( return registry.for( key, () => new ElectronDisplayTracker(env, onError), - (tracker) => tracker.rebind(onError), + (tracker) => tracker.rebind(onError, env.keyWindowBounds), ); }