diff --git a/.changeset/browser-screen-size-main-thread-lag.md b/.changeset/browser-screen-size-main-thread-lag.md new file mode 100644 index 00000000..9be34a2f --- /dev/null +++ b/.changeset/browser-screen-size-main-thread-lag.md @@ -0,0 +1,12 @@ +--- +'@bugsee/browser': minor +'@bugsee/webview': minor +--- + +Browser and WebView system traces gain `screen_size` and `main_thread_lag_ms`: + +- `screen_size` reports `{ width, height, dpr }` (CSS pixels of `screen.width` / `screen.height` and `devicePixelRatio`) as a held step trace: an initial value at start, then on every `resize` and `orientationchange`, de-duplicated. It is omitted when the screen or the pixel ratio cannot be read as finite positive numbers. It is deliberately not named `displays`. +- `screen_size` can go stale when the window moves to a monitor with the same pixel ratio but a different size (no `resize` fires), and iOS Safari's `screen.width` / `screen.height` do not swap on rotation. +- `main_thread_lag_ms` is timer drift: how late the 1 s sampling timer fired on the page's main thread, emitted every tick while the page is visible; a measured 0 is a real value. A freeze of 1 s or more reads between its length minus one second and its length; a block shorter than one second that crosses no due tick reads 0, so short jank can go unseen (a finer timer or `PerformanceObserver('longtask')` would be the follow-up). It is measured only while the page is visible: hiding stops the timer, and every time the page is shown a fresh baseline is taken so a hidden stretch never counts as lag. A window without a `performance.now` function reports nothing. Timer throttling of a page that still says visible (an occluded window) may also read as lag; this is unverified. + +Both come from the window passed to `launch()`, are built only with the other lifecycle-based traces, and are replaced together with the sensor traces by a `systemMetricsSampler`. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 78eaf496..19646a99 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -403,7 +403,8 @@ solid), in slices: `navigator`/`performance`/`screen`/`window` (`defaultBrowserTraceEnv()`); the old sampler copied `navigator` with a spread, which drops the prototype accessors (`onLine`, `connection`, `deviceMemory`) on a real browser. Launch passes its injected `window` and `scheduler`. The shared `PageLifecycleTracker` is done: the events source and the connection/orientation trackers subscribe to it. -- **ST4a (DONE, `feat/browser-app-state-fps`):** `app_state` (`AppStateProducer`: `foreground`/`background`, held step trace; the viewer's table is `started`/`foreground`/`background`) and `fps` (`FpsTracker` + `FpsProducer`: a `requestAnimationFrame` counter that runs ONLY while the page is visible — loop and timer torn down on hidden, a fresh window on visible, a zero-length window or no rAF emits nothing; nothing is reported before the first frame of a run, since rAF can be paused while the page says visible; afterwards the first frameless window is reported as 0 and a continuing stall goes quiet; no lifecycle = omitted). The traces env is now built from the INJECTED window + document (`browserTraceEnvFrom`; no fallback to `globalThis`, so a window without `performance.memory` omits the heap). **ST4b (DONE, `feat/browser-dark-freeze-events`):** `events.system` gains `dark_mode_changed` (`{dark}`; `matchMedia` taken from the INJECTED window, bound to it, per-attach guarded) and Page Lifecycle `freeze`/`resume` (document listeners via the shared `PageLifecycleTracker`). Still open in ST4: `main_thread_lag_ms` (needs the hidden-tab-vs-sync-block probe first) and optional `screen_size`. +- **ST4a (DONE, `feat/browser-app-state-fps`):** `app_state` (`AppStateProducer`: `foreground`/`background`, held step trace; the viewer's table is `started`/`foreground`/`background`) and `fps` (`FpsTracker` + `FpsProducer`: a `requestAnimationFrame` counter that runs ONLY while the page is visible — loop and timer torn down on hidden, a fresh window on visible, a zero-length window or no rAF emits nothing; nothing is reported before the first frame of a run, since rAF can be paused while the page says visible; afterwards the first frameless window is reported as 0 and a continuing stall goes quiet; no lifecycle = omitted). The traces env is now built from the INJECTED window + document (`browserTraceEnvFrom`; no fallback to `globalThis`, so a window without `performance.memory` omits the heap). **ST4b (DONE, `feat/browser-dark-freeze-events`):** `events.system` gains `dark_mode_changed` (`{dark}`; `matchMedia` taken from the INJECTED window, bound to it, per-attach guarded) and Page Lifecycle `freeze`/`resume` (document listeners via the shared `PageLifecycleTracker`). ST4 has nothing left open (ST4c below). +- **ST4c (DONE, `feat/browser-screen-size-main-thread-lag`):** `screen_size` (`ScreenSizeTracker` + `ScreenSizeProducer`: value shape `{width, height, dpr}` in CSS px — NOT `displays`; held, de-duplicated step trace; initial value at start; re-read on `resize` (listened for on the injected window by the tracker — no new shared-lifecycle event, since nothing else consumes it and it would change every lifecycle subscriber's listener count) and `orientationchange` (via the shared lifecycle); omitted entirely when `screen` or `devicePixelRatio` is not a finite positive number; known staleness: moving the window to a monitor with the same DPR but a different size fires no `resize`, and iOS Safari's `screen.width/height` do not swap on rotation — a `(resolution: Xdppx)` matchMedia/`screen` change listener is a follow-up) and `main_thread_lag_ms` (`MainThreadLagTracker` + `MainThreadLagProducer`: TIMER DRIFT: on each 1 s scheduler tick on the page's main thread, `lag = max(0, now - (previousTickTime + intervalMs))` with the injected `performance.now`; the first tick compares against the run's start + interval; emitted EVERY tick as a polled (`hold:false`) trace — a measured ~0 is a true value. **What a reading means (measured in Chromium):** a tick fires late by (block end − the first due time the block covered), so a block B ≥ 1 s reads between B−1000 and B (1800 ms read 907..1797; 2500 ms read 1807), while a block shorter than 1 s that crosses no due tick reads exactly 0 (probability ≈ 1 − B/1000: ~30% for 700 ms, ~90% for 100 ms); one block is reported once (the next tick clamps to 0). It is NOT Node's ~10 ms event-loop monitor — sampling every 1000 ms is why short blocks can go unseen. Measured ONLY while visible: hidden tears the timer down and every visible start takes a FRESH baseline, so a hidden stretch never counts as lag. A throwing clock/scheduler at start rolls back; a throwing or non-finite clock at a tick is reported/skipped without reading the skipped interval as lag. No clock (`performance.now` must be a function), lifecycle, or a hidden page = omitted, no timer. **Honest limit:** long freezes are reported reliably, short jank only by luck; follow-ups if short jank matters: a finer internal timer reporting the MAX drift per 1 s window, or `PerformanceObserver('longtask')` where supported. Timer throttling the browser applies to a page that still says `visible` (occluded/minimised window, background tab without a `visibilitychange`) may also read as lag — UNVERIFIED, it could not be reproduced headless. **History:** a `MessageChannel` ping (re-arm on receipt, then once per tick) was built and rejected after measuring real Chromium: re-arming on receipt was a ~2.2M/s task loop, and a ping per tick reads ~0.1 ms for a block that starts after the ping returned — a plausible-healthy lie; it was deleted entirely, no `MessageChannel` in the traces env). Both are built under the same `env.lifecycle` gate as `app_state`/`fps`, so a `systemMetricsSampler` (`sensors:false`) replaces them too. Open: the viewer has no definition for either name yet (generic value block, design §13.3). - **TR4 (DONE, `feat/power-tracker`):** `BatteryTracker` became the domain **`PowerTracker`** (`packages/trackers/src/browser/power-tracker.ts`), a singleton per window via `createTrackerRegistry` (`powerTrackerFor(env, onError)`, keyed on `env.window`, else `env.navigator`, else the env object; host key reads are guarded and reported). It takes ONLY `getBattery` from the env; every call (a relaunch included) goes through the registry `rebind`, handing the shared tracker the latest launch's `onError` (a defined one replaces, undefined keeps; the reporter is a mutable indirection) and `getBattery` (a defined one replaces; a tracker that had none kicks the request at once if running). It exposes a SINGLE `state` stage (rather than one per Battery Status event): `{level?, charging, chargingTimeS?, dischargingTimeS?}`, published on `levelchange`/`chargingchange`/`chargingtimechange`/`dischargingtimechange`. Omitted, never fabricated: a `level` that is not a number in [0,1] (so no `battery` trace, never NaN); non-finite or negative times; a zero `chargingTime` when full and charging (a battery-less desktop reports level 1, charging, 0); a zero `dischargingTime`. A throwing time getter costs only that field. **Retention rule (tested):** the resolved BatteryManager and the last snapshot survive the last unsubscribe (no second `getBattery()`); the DOM listeners do not, and re-attach with a fresh snapshot on the next subscriber. A `getBattery()` in flight at stop is ignored and re-requested next activation. `BatteryProducer` keeps `battery`/`charging` unchanged and adds `battery_charging_time_s`/`battery_discharging_time_s` (integer seconds). **Held-value disappearance rule:** the provider's held values cannot be retracted (it re-records them every `refreshMs`), so the two time traces use plain non-held `emit` with a producer-side change-only guard; a vanished time records nothing and is forgotten (a stale estimate is never refreshed). Consequence: an unchanged time AGES OUT of the rolling capture window; owner decision pending on a retract/release or end-marker mechanism. - **ST0′ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container diff --git a/packages/browser/src/launch.test.ts b/packages/browser/src/launch.test.ts index 8668860b..6401348c 100644 --- a/packages/browser/src/launch.test.ts +++ b/packages/browser/src/launch.test.ts @@ -1564,6 +1564,154 @@ describe('launch', () => { expect(armed).toBe(0); }); + it('records screen_size {width,height,dpr} from the INJECTED window and follows its resize', async () => { + stubSensors(); + vi.stubGlobal('screen', { width: 390, height: 844 }); + const w = fakeWindow(); + Object.assign(w.win, { devicePixelRatio: 2 }); + const store = memStore(); + await launchTracked('tok', noSampler({ window: w.win, captureStore: store })); + Object.assign(w.win, { devicePixelRatio: 3 }); + w.emit('resize', {}); + expect(await rowsOf(store, 'screen_size')).toEqual([ + { width: 390, height: 844, dpr: 2 }, + { width: 390, height: 844, dpr: 3 }, + ]); + }); + + it('screen_size is omitted (not 0) when the window has no readable screen or pixel ratio', async () => { + stubSensors(); // the stubbed screen has no width/height + const w = fakeWindow(); + Object.assign(w.win, { devicePixelRatio: 2 }); + const store = memStore(); + await launchTracked('tok', noSampler({ window: w.win, captureStore: store })); + expect(await rowsOf(store, 'screen_size')).toEqual([]); + }); + + it('records main_thread_lag_ms as timer drift on the INJECTED window clock, visible only, with a fresh baseline after a hide', async () => { + stubSensors(); + const d = mkDoc(true); + const w = fakeWindow(); + let clock = 5_000; + Object.defineProperty(w.win, 'performance', { + value: { now: () => clock }, + configurable: true, + }); + const live = new Map void>(); + let nextHandle = 1; + const store = memStore(); + await launchTracked( + 'tok', + noSampler({ + window: w.win, + document: d.doc as unknown as Document, + captureStore: store, + scheduler: { + setInterval: (cb, ms) => { + if (ms !== 1000) return 'other'; + const h = nextHandle++; + live.set(h, cb); + return h; + }, + clearInterval: (h) => void live.delete(h as number), + }, + }), + ); + const runTicks = (): void => { + for (const cb of [...live.values()]) cb(); + }; + clock += 1000; + runTicks(); // on time + clock += 1000 + 300; // a 300 ms block spans the next tick + runTicks(); + const before = live.size; + d.setVisible(false); + const hiddenTimers = live.size; + clock += 60_000; + d.setVisible(true); // a fresh baseline: the hidden minute is not lag + clock += 1000; + runTicks(); + // fps shares the 1 s cadence but emits its own name; only the lag rows are read here + expect(await rowsOf(store, 'main_thread_lag_ms')).toEqual([0, 300, 0]); + expect(hiddenTimers).toBeLessThan(before); // hiding tore the sampling timer(s) down + }); + + it('a hidden injected document never reads the clock for lag (no timer is started)', async () => { + stubSensors(); + const d = mkDoc(false); + const w = fakeWindow(); + let reads = 0; + Object.defineProperty(w.win, 'performance', { + value: { + now: () => { + reads += 1; + return 0; + }, + }, + configurable: true, + }); + await launchTracked( + 'tok', + noSampler({ + window: w.win, + document: d.doc as unknown as Document, + captureStore: memStore(), + }), + ); + expect(reads).toBe(0); + }); + + it('a hostile devicePixelRatio getter never fails launch and is reported', async () => { + stubSensors(); + vi.stubGlobal('screen', { width: 390, height: 844 }); + const w = fakeWindow(); + Object.defineProperty(w.win, 'devicePixelRatio', { + get(): never { + throw new Error('devicePixelRatio blocked'); + }, + configurable: true, + }); + const onError = vi.fn(); + const store = memStore(); + const client = await launchTracked( + 'tok', + noSampler({ window: w.win, captureStore: store, onError }), + ); + const messages = onError.mock.calls.map((c) => (c[0] as Error).message); + expect(messages).toContain('devicePixelRatio blocked'); + expect(await rowsOf(store, 'screen_size')).toEqual([]); + await client.stop(); + }); + + it('a systemMetricsSampler override builds neither screen_size nor the lag timer', async () => { + stubSensors(); + vi.stubGlobal('screen', { width: 390, height: 844 }); + const d = mkDoc(true); + const w = fakeWindow(); + let reads = 0; + Object.assign(w.win, { devicePixelRatio: 2 }); + Object.defineProperty(w.win, 'performance', { + value: { + now: () => { + reads += 1; + return 0; + }, + }, + configurable: true, + }); + const store = memStore(); + await launchTracked( + 'tok', + baseOptions({ + window: w.win, + document: d.doc as unknown as Document, + captureStore: store, + }), + ); + expect(await rowsOf(store, 'screen_size')).toEqual([]); + expect(reads).toBe(0); // no lag timer was even built + }); + it('a systemMetricsSampler override omits app_state and fps with the other sensor traces', async () => { stubSensors(); const d = mkDoc(true); diff --git a/packages/browser/src/trace-producers.screen-lag.test.ts b/packages/browser/src/trace-producers.screen-lag.test.ts new file mode 100644 index 00000000..9f127490 --- /dev/null +++ b/packages/browser/src/trace-producers.screen-lag.test.ts @@ -0,0 +1,313 @@ +import type { TraceProducer } from '@bugsee/capture'; +import { describe, expect, it } from 'vitest'; +import { + browserTraceEnvFrom, + createBrowserSystemTraceProducers, + MainThreadLagProducer, + ScreenSizeProducer, +} from './trace-producers'; +import { MainThreadLagTracker } from './trackers/main-thread-lag-tracker'; +import { PageLifecycleTracker } from './trackers/page-lifecycle-tracker'; +import { ScreenSizeTracker } from './trackers/screen-size-tracker'; + +function mkTarget() { + const l = new Map void>>(); + return { + addEventListener: (t: string, f: (e: unknown) => void) => { + const s = l.get(t) ?? new Set<(e: unknown) => void>(); + s.add(f); + l.set(t, s); + }, + removeEventListener: (t: string, f: (e: unknown) => void) => void l.get(t)?.delete(f), + fire: (t: string) => + l.get(t)?.forEach((f) => { + f({}); + }), + count: () => [...l.values()].reduce((n, s) => n + s.size, 0), + }; +} +type Emit = { name: string; value: unknown; hold: boolean | undefined }; +const sinkOf = (out: Emit[]) => ({ + emit: (name: string, value: unknown, _d?: number, o?: { hold?: boolean }) => + void out.push({ name, value, hold: o?.hold }), +}); +const names = (ps: TraceProducer[]) => ps.map((p) => p.name); + +describe('ScreenSizeProducer', () => { + const mk = (screen: unknown = { width: 390, height: 844 }) => { + const win = Object.assign(mkTarget(), { devicePixelRatio: 2 }); + const tracker = new ScreenSizeTracker({ window: win, screen: screen as never }); + return { win, tracker }; + }; + + it('emits {width,height,dpr} at start as a HELD step trace, then follows resize, de-duplicated', () => { + const { win, tracker } = mk(); + const out: Emit[] = []; + new ScreenSizeProducer(tracker).start(sinkOf(out)); + expect(out).toEqual([ + { name: 'screen_size', value: { width: 390, height: 844, dpr: 2 }, hold: true }, + ]); + win.fire('resize'); // nothing moved + expect(out).toHaveLength(1); + win.devicePixelRatio = 3; + win.fire('resize'); + win.fire('orientationchange'); + expect(out.map((o) => o.value)).toEqual([ + { width: 390, height: 844, dpr: 2 }, + { width: 390, height: 844, dpr: 3 }, + ]); + }); + + it('is omitted entirely when the screen is absent or unreadable (never 0)', () => { + for (const screen of [undefined, { width: 0, height: 844 }, { width: 390 }]) { + const win = Object.assign(mkTarget(), { devicePixelRatio: 2 }); + const out: Emit[] = []; + new ScreenSizeProducer( + new ScreenSizeTracker({ window: win, ...(screen ? { screen } : {}) }), + ).start(sinkOf(out)); + expect(out).toEqual([]); + } + }); + + it('stop() releases the window listeners and later events write nothing', () => { + const { win, tracker } = mk(); + const out: Emit[] = []; + const p = new ScreenSizeProducer(tracker); + p.start(sinkOf(out)); + expect(win.count()).toBeGreaterThan(0); + p.stop(); + expect(win.count()).toBe(0); + win.devicePixelRatio = 5; + win.fire('resize'); + expect(out).toHaveLength(1); + }); +}); + +describe('MainThreadLagProducer', () => { + it('emits each tick drift as a POLLED value (hold:false), including a true 0, and releases on stop', () => { + const win = mkTarget(); + const doc = Object.assign(mkTarget(), { visibilityState: 'visible' }); + const lifecycle = new PageLifecycleTracker({ window: win, document: doc }); + let timer: (() => void) | undefined; + let now = 0; + const tracker = new MainThreadLagTracker({ + lifecycle, + document: doc, + now: () => now, + scheduler: { + setInterval: (cb) => { + timer = cb; + return 1; + }, + clearInterval: () => {}, + }, + }); + const out: Emit[] = []; + const p = new MainThreadLagProducer(tracker); + expect(doc.count()).toBe(0); + p.start(sinkOf(out)); + expect(out).toEqual([]); // nothing before the first tick + now = 1000; + timer?.(); + now = 2000 + 120; // a 120 ms block spanning the second tick + timer?.(); + expect(out).toEqual([ + { name: 'main_thread_lag_ms', value: 0, hold: false }, + { name: 'main_thread_lag_ms', value: 120, hold: false }, + ]); + expect(doc.count()).toBeGreaterThan(0); // the lifecycle attached its document listeners for us + p.stop(); + expect(doc.count()).toBe(0); + timer?.(); + expect(out).toHaveLength(2); + }); +}); + +describe('createBrowserSystemTraceProducers: screen_size + main_thread_lag_ms', () => { + it('are added with a lifecycle (same gate as app_state/fps) and absent without one', () => { + const win = mkTarget(); + const lifecycle = new PageLifecycleTracker({ window: win }); + expect(names(createBrowserSystemTraceProducers({ lifecycle }))).toEqual( + expect.arrayContaining(['screen-size', 'main-thread-lag']), + ); + expect(names(createBrowserSystemTraceProducers({}))).not.toEqual( + expect.arrayContaining(['screen-size']), + ); + expect(names(createBrowserSystemTraceProducers({}))).not.toEqual( + expect.arrayContaining(['main-thread-lag']), + ); + }); + + it('sensors:false builds the battery producer only', () => { + const lifecycle = new PageLifecycleTracker({ window: mkTarget() }); + expect(names(createBrowserSystemTraceProducers({ lifecycle, sensors: false }))).toEqual([ + 'battery', + ]); + }); + + it('wires the env window/screen/document/clock/scheduler into the trackers, nothing from globals', () => { + let t = 777_000; // a distinctive clock value: only the INJECTED window's performance can produce it + const win = Object.assign(mkTarget(), { + devicePixelRatio: 2, + screen: { width: 100, height: 200 }, + performance: { now: () => t }, + }); + const doc = { visibilityState: 'visible' }; + const lifecycle = new PageLifecycleTracker({ + window: win, + document: Object.assign(mkTarget(), doc), + }); + let timer: (() => void) | undefined; + const errors: unknown[] = []; + const ps = createBrowserSystemTraceProducers( + { + ...browserTraceEnvFrom(win, doc), + lifecycle, + scheduler: { + setInterval: (cb) => { + timer = cb; + return 1; + }, + clearInterval: () => {}, + }, + }, + (e) => errors.push(e), + ); + const out: Emit[] = []; + for (const p of ps) + if (p.name === 'screen-size' || p.name === 'main-thread-lag') p.start(sinkOf(out)); + expect(out).toEqual([ + { name: 'screen_size', value: { width: 100, height: 200, dpr: 2 }, hold: true }, + ]); + t += 1000 + 33; + timer?.(); + expect(out[1]).toEqual({ name: 'main_thread_lag_ms', value: 33, hold: false }); + expect(errors).toEqual([]); + }); + + it('a window without a performance clock starts no timer and reports nothing (no error)', () => { + const win = Object.assign(mkTarget(), { screen: { width: 1, height: 1 }, devicePixelRatio: 1 }); + const doc = { visibilityState: 'visible' }; + const lifecycle = new PageLifecycleTracker({ + window: win, + document: Object.assign(mkTarget(), doc), + }); + let timers = 0; + const errors: unknown[] = []; + const lag = createBrowserSystemTraceProducers( + { + ...browserTraceEnvFrom(win, doc), + lifecycle, + scheduler: { + setInterval: () => { + timers += 1; + return 1; + }, + clearInterval: () => {}, + }, + }, + (e) => errors.push(e), + ).find((p) => p.name === 'main-thread-lag'); + const out: Emit[] = []; + expect(() => lag?.start(sinkOf(out))).not.toThrow(); + expect(out).toEqual([]); + expect(errors).toEqual([]); + // the other lifecycle trace that needs a clock (fps) also uses its own timer; only count the lag producer's + expect(timers).toBe(0); + }); +}); + +describe('performance.now wiring (lag and fps)', () => { + // `now` throws unless it is invoked as a method of THIS performance object, like a real Performance. + const mkPerf = () => { + const perf = { + t: 0, + reads: 0, + now(this: unknown): number { + if (this !== perf) throw new TypeError('Illegal invocation'); + perf.reads += 1; + return perf.t; + }, + }; + return perf; + }; + const mkLifecycle = () => { + const doc = Object.assign(mkTarget(), { visibilityState: 'visible' }); + return { doc, lifecycle: new PageLifecycleTracker({ window: mkTarget(), document: doc }) }; + }; + + it('the lag and fps clocks are called as performance.now() (this === performance), with no error', () => { + const perf = mkPerf(); + const { doc, lifecycle } = mkLifecycle(); + const errors: unknown[] = []; + const ticks: Array<() => void> = []; + const ps = createBrowserSystemTraceProducers( + { + lifecycle, + document: doc, + performance: perf, + requestAnimationFrame: () => 1, + scheduler: { + setInterval: (cb) => { + ticks.push(cb); + return 1; + }, + clearInterval: () => {}, + }, + }, + (e) => errors.push(e), + ); + const out: Emit[] = []; + for (const p of ps) if (p.name === 'main-thread-lag' || p.name === 'fps') p.start(sinkOf(out)); + perf.t = 1000 + 12; + for (const tick of ticks) tick(); + expect(errors).toEqual([]); + expect(out.find((o) => o.name === 'main_thread_lag_ms')?.value).toBe(12); + expect(perf.reads).toBeGreaterThanOrEqual(2); // fps and lag both read it at start + }); + + it('a performance.now getter that throws is reported ONCE, not once per consumer', () => { + const { doc, lifecycle } = mkLifecycle(); + const perf = {}; + Object.defineProperty(perf, 'now', { + get(): never { + throw new Error('now blocked'); + }, + }); + const errors: unknown[] = []; + createBrowserSystemTraceProducers({ lifecycle, document: doc, performance: perf }, (e) => + errors.push(e), + ); + expect(errors.map((e) => (e as Error).message)).toEqual(['now blocked']); + }); +}); + +describe('main_thread_lag_ms clock wiring', () => { + it('a performance.now that is not a function omits the trace quietly (no timer, no error)', () => { + const win = mkTarget(); + const doc = Object.assign(mkTarget(), { visibilityState: 'visible' }); + const lifecycle = new PageLifecycleTracker({ window: win, document: doc }); + let timers = 0; + const errors: unknown[] = []; + const lag = createBrowserSystemTraceProducers( + { + lifecycle, + document: doc, + performance: { now: 5 as never }, + scheduler: { + setInterval: () => { + timers += 1; + return 1; + }, + clearInterval: () => {}, + }, + }, + (e) => errors.push(e), + ).find((p) => p.name === 'main-thread-lag'); + const out: Emit[] = []; + lag?.start(sinkOf(out)); + expect(timers).toBe(0); + expect(errors).toEqual([]); + expect(out).toEqual([]); + }); +}); diff --git a/packages/browser/src/trace-producers.ts b/packages/browser/src/trace-producers.ts index 44482f61..60484fe1 100644 --- a/packages/browser/src/trace-producers.ts +++ b/packages/browser/src/trace-producers.ts @@ -14,6 +14,7 @@ import { ConnectionTracker, } from './trackers/connection-tracker'; import { type FpsEnv, FpsTracker } from './trackers/fps-tracker'; +import { MainThreadLagTracker } from './trackers/main-thread-lag-tracker'; import { type MemoryReading, type MemoryState, MemoryTracker } from './trackers/memory-tracker'; import { type OrientationEnv, @@ -21,6 +22,11 @@ import { OrientationTracker, } from './trackers/orientation-tracker'; import type { PageLifecycleTracker } from './trackers/page-lifecycle-tracker'; +import { + type ScreenSizeEnv, + type ScreenSizeState, + ScreenSizeTracker, +} from './trackers/screen-size-tracker'; // Browser `traces.system` producers (mirrors the mobile tracker/producer split). Each producer subscribes to // one shared tracker in start() and turns its state into the Android-vocabulary wire values; the trackers own @@ -260,6 +266,70 @@ export class FpsProducer extends TraceProducerBase { } } +/** + * `screen_size` (JS-specific; deliberately NOT Android's `displays`, a display LIST): `{ width, height, dpr }` in + * CSS px, re-read on `resize` / `orientationchange`. 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 (a `(resolution: Xdppx)` media-query / `screen` + * change listener is a follow-up); and iOS Safari's `screen.width/height` do not swap on rotation. + */ +export class ScreenSizeProducer extends TraceProducerBase { + readonly name = 'screen-size'; + readonly #tracker: ScreenSizeTracker; + #off: (() => void) | undefined; + + constructor(tracker: ScreenSizeTracker) { + super(); + this.#tracker = tracker; + } + + protected onStart(): void { + this.#off = this.#tracker.on('state', (s) => this.#publish(s)); // subscribing attaches the listeners + const cur = this.#tracker.current(); + if (cur !== undefined) this.#publish(cur); + } + + protected override onStop(): void { + this.#off?.(); + this.#off = undefined; + } + + #publish(s: ScreenSizeState): void { + this.emitIfChanged('screen_size', { width: s.width, height: s.height, dpr: s.dpr }); + } +} + +/** + * `main_thread_lag_ms`: TIMER DRIFT — how late the 1 s sampling timer fired on the page's main thread, emitted + * every tick, ONLY while the page is visible (a hidden tab's throttled timers would paint a hang that did not + * happen). A measured ~0 is a true value and is emitted. A block of B >= 1 s reads between B - 1000 and B; a block + * shorter than 1 s that crosses no due tick reads 0 (see the tracker header for the numbers and the follow-ups). + * Throttling of a page that still says `visible` (occluded window) may read as lag (unverified). + * Polled, so each value is emitted and never held or refreshed. + */ +export class MainThreadLagProducer extends TraceProducerBase { + readonly name = 'main-thread-lag'; + readonly #tracker: MainThreadLagTracker; + #off: (() => void) | undefined; + + constructor(tracker: MainThreadLagTracker) { + super(); + this.#tracker = tracker; + } + + protected onStart(): void { + this.#off = this.#tracker.on('lag', (ms) => this.emit('main_thread_lag_ms', ms)); + } + + protected override onStop(): void { + this.#off?.(); + this.#off = undefined; + } +} + /** * Injected browser surfaces. Each is optional and an absent one is simply not sampled; pass the LIVE * objects (`navigator`, `performance`, `screen`, `window`) — never a spread copy, since a real @@ -271,9 +341,9 @@ export interface BrowserTraceEnv extends BatteryEnv { /** `navigator.deviceMemory` in GiB — a coarse bucket, not a measurement. */ readonly deviceMemory?: number; }; - screen?: OrientationEnv['screen']; - /** Source of `online` / `offline` / `orientationchange`. */ - window?: ConnectionEnv['window']; + screen?: OrientationEnv['screen'] & ScreenSizeEnv['screen']; + /** Source of `online` / `offline` / `orientationchange` / `resize`, and the live `devicePixelRatio`. */ + window?: ConnectionEnv['window'] & ScreenSizeEnv['window']; /** The document the SDK is bound to: visibility for `app_state` and `fps`. */ document?: FpsEnv['document']; /** `window.requestAnimationFrame` / `cancelAnimationFrame` (bound to that window): drive `fps`. */ @@ -281,7 +351,7 @@ export interface BrowserTraceEnv extends BatteryEnv { cancelAnimationFrame?: FpsEnv['cancelAnimationFrame']; /** * `false` builds the battery producer ONLY: a caller-supplied `systemMetricsSampler` replaces the heap, - * connection, orientation, `app_state` and `fps` traces (as on Node), so the sensor producers must not also emit them. + * connection, orientation, `app_state`, `fps`, `screen_size` and `main_thread_lag_ms` traces (as on Node), so the sensor producers must not also emit them. */ sensors?: boolean; /** Drives the heap poll; default the global timers. */ @@ -404,6 +474,8 @@ export function createBrowserSystemTraceProducers( const nav = env.navigator; const battery = new BatteryProducer(powerTrackerFor(env, onError)); if (env.sensors === false) return [battery]; + // Read ONCE: a hostile `performance.now` getter must report one error, not one per consumer. + const clock = safePerformanceNow(env, onError); return [ battery, new MemoryProducer( @@ -438,6 +510,30 @@ export function createBrowserSystemTraceProducers( ...(env.lifecycle !== undefined ? [ new AppStateProducer(env.lifecycle, env.document), + new ScreenSizeProducer( + new ScreenSizeTracker( + { + lifecycle: env.lifecycle, + ...(env.window !== undefined ? { window: env.window } : {}), + ...(env.screen !== undefined ? { screen: env.screen } : {}), + }, + onError, + ), + ), + new MainThreadLagProducer( + new MainThreadLagTracker( + { + lifecycle: env.lifecycle, + ...(env.document !== undefined ? { document: env.document } : {}), + // Only a real clock function is wired; anything else omits the trace quietly (no error). + ...(typeof clock === 'function' + ? { now: () => (env.performance as { now(): number }).now() } + : {}), + ...(env.scheduler !== undefined ? { scheduler: env.scheduler } : {}), + }, + onError, + ), + ), new FpsProducer( new FpsTracker( { @@ -449,7 +545,7 @@ export function createBrowserSystemTraceProducers( ...(env.cancelAnimationFrame !== undefined ? { cancelAnimationFrame: env.cancelAnimationFrame } : {}), - ...(safePerformanceNow(env, onError) !== undefined + ...(clock !== undefined ? // A clock that becomes unreadable later THROWS (the tracker's tick reports and skips the window) // rather than answering a made-up 0. { now: () => (env.performance as { now(): number }).now() } diff --git a/packages/browser/src/trackers/main-thread-lag-tracker.test.ts b/packages/browser/src/trackers/main-thread-lag-tracker.test.ts new file mode 100644 index 00000000..d1b0aa94 --- /dev/null +++ b/packages/browser/src/trackers/main-thread-lag-tracker.test.ts @@ -0,0 +1,391 @@ +import type { Scheduler } from '@bugsee/core'; +import { describe, expect, it, vi } from 'vitest'; +import { MainThreadLagTracker } from './main-thread-lag-tracker'; + +// A controllable page. Tests are REAL-ORDER aware: a main-thread block is modelled as "advance the clock by N ms +// between two tick callbacks" — the late tick then fires after the block, exactly as a real timer does. +function mkEnv(over: { visible?: boolean; noNow?: boolean } = {}) { + let now = 0; + const doc = { visibilityState: over.visible === false ? 'hidden' : 'visible' }; + const visListeners = new Set<(e: { visible: boolean }) => void>(); + let timerCb: (() => void) | undefined; + const timers = { set: 0, cleared: 0, live: 0 }; + const control = { setFails: 0 }; + const scheduler: Scheduler = { + setInterval: (cb) => { + if (control.setFails-- > 0) throw new Error('timer'); + timerCb = cb; + timers.set += 1; + timers.live += 1; + return { id: timers.set }; + }, + clearInterval: () => { + timers.cleared += 1; + timers.live -= 1; + }, + }; + const env = { + document: doc, + lifecycle: { + on: (type: string, fn: (e: never) => void) => { + expect(type).toBe('visibility'); + visListeners.add(fn as never); + return () => void visListeners.delete(fn as never); + }, + }, + ...(over.noNow ? {} : { now: () => now }), + scheduler, + }; + return { + env, + timers, + control, + advance: (ms: number) => { + now += ms; + }, + setNow: (ms: number) => { + now = ms; + }, + tick: () => timerCb?.(), + setVisible: (visible: boolean) => { + doc.visibilityState = visible ? 'visible' : 'hidden'; + for (const l of [...visListeners]) l({ visible }); + }, + listeners: () => visListeners.size, + }; +} + +const collect = (t: MainThreadLagTracker) => { + const got: number[] = []; + const off = t.on('lag', (v) => got.push(v)); + return { got, off }; +}; + +describe('MainThreadLagTracker (timer drift)', () => { + it('attaches nothing until the first subscriber', () => { + const e = mkEnv(); + new MainThreadLagTracker(e.env); + expect(e.timers.set).toBe(0); + expect(e.listeners()).toBe(0); + }); + + it('two ticks exactly on time report 0 (a measured zero is a value, and is emitted)', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + e.advance(1000); + e.tick(); + e.advance(1000); + e.tick(); + expect(got).toEqual([0, 0]); + }); + + it('a block spanning a due tick shows as the lateness of that tick, once; the next on-time tick reads 0', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + e.advance(1000); + e.tick(); // on time + e.advance(1000 + 700); // a 700 ms synchronous block, then the overdue tick fires + e.tick(); + expect(got).toEqual([0, 700]); + e.advance(1000); // and the NEXT interval is measured from the late tick, so the block is not counted twice + e.tick(); + expect(got).toEqual([0, 700, 0]); + }); + + it('a block shorter than the interval that crosses no due tick reads exactly 0 (the documented limit)', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + e.advance(100); // a 100 ms block mid-interval... + e.advance(900); // ...the tick still fires on schedule + e.tick(); + expect(got).toEqual([0]); + }); + + it('the first tick is measured against the run start + interval', () => { + const e = mkEnv(); + e.setNow(5000); + const { got } = collect(new MainThreadLagTracker(e.env)); + e.setNow(5000 + 1000 + 250); + e.tick(); + expect(got).toEqual([250]); + }); + + it('a tick that fires a hair early is on time (never a negative lag)', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + e.advance(998); + e.tick(); + expect(got).toEqual([0]); + }); + + it('honors intervalMs (default 1000) as both the timer period and the drift baseline', () => { + const seen: number[] = []; + const scheduler: Scheduler = { + setInterval: (_cb, ms) => { + seen.push(ms); + return 1; + }, + clearInterval: () => {}, + }; + const e = mkEnv(); + new MainThreadLagTracker({ ...e.env, scheduler }).on('lag', () => {}); + new MainThreadLagTracker({ ...e.env, scheduler, intervalMs: 250 }).on('lag', () => {}); + expect(seen).toEqual([1000, 250]); + const f = mkEnv(); + const { got } = collect(new MainThreadLagTracker({ ...f.env, intervalMs: 250 })); + f.advance(250); + f.tick(); + f.advance(250 + 40); + f.tick(); + expect(got).toEqual([0, 40]); + }); + + it('uses the INJECTED clock: its distinctive value, and nothing else, decides the drift', () => { + const e = mkEnv(); + const reads: number[] = []; + let t = 123_456; + const { got } = collect( + new MainThreadLagTracker({ + ...e.env, + now: () => { + reads.push(t); + return t; + }, + }), + ); + t = 123_456 + 1000 + 77; + e.tick(); + expect(got).toEqual([77]); + expect(reads).toEqual([123_456, 123_456 + 1077]); + }); + + it('hidden: the timer is torn down and nothing is emitted, even by a stray tick', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + e.setVisible(false); + expect(e.timers.live).toBe(0); + e.advance(1000); + e.tick(); + expect(got).toEqual([]); + }); + + it('a hidden stretch never counts as lag: hide 60 s, show, the first tick reports ~0 — a FRESH baseline', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + e.advance(1000); + e.tick(); + e.setVisible(false); + e.advance(60_000); + e.setVisible(true); + e.advance(1000); + e.tick(); + expect(got).toEqual([0, 0]); + }); + + it('hidden at start: no timer, nothing emitted; the first visible event starts a run', () => { + const e = mkEnv({ visible: false }); + const { got } = collect(new MainThreadLagTracker(e.env)); + expect(e.timers.live).toBe(0); + e.tick(); + expect(got).toEqual([]); + e.setVisible(true); + expect(e.timers.live).toBe(1); + }); + + it('duplicate visible/hidden events do not stack timers', () => { + const e = mkEnv(); + collect(new MainThreadLagTracker(e.env)); + e.setVisible(true); + e.setVisible(true); + expect(e.timers.live).toBe(1); + e.setVisible(false); + e.setVisible(false); + expect(e.timers.live).toBe(0); + expect(e.timers.cleared).toBe(1); + }); + + it('the last unsubscribe stops the timer and the subscription; a re-subscribe restarts with a fresh baseline', () => { + const e = mkEnv(); + const t = new MainThreadLagTracker(e.env); + const { off } = collect(t); + expect(e.listeners()).toBe(1); + off(); + expect(e.listeners()).toBe(0); + expect(e.timers.live).toBe(0); + e.advance(30_000); + const { got } = collect(t); + expect(e.timers.live).toBe(1); + e.advance(1000); + e.tick(); + expect(got).toEqual([0]); + }); + + it('without a clock it measures nothing: no timer, no subscription, no error (no wall-clock guess)', () => { + const e = mkEnv({ noNow: true }); + const errors: unknown[] = []; + const { got } = collect(new MainThreadLagTracker(e.env, (x) => errors.push(x))); + expect(e.timers.set).toBe(0); + expect(e.listeners()).toBe(0); + e.tick(); + expect(got).toEqual([]); + expect(errors).toEqual([]); + }); + + it('with no lifecycle it measures nothing: a hidden tab could not be gated', () => { + const e = mkEnv(); + const { lifecycle: _l, ...rest } = e.env; + const errors: unknown[] = []; + collect(new MainThreadLagTracker(rest, (x) => errors.push(x))); + expect(e.timers.set).toBe(0); + expect(errors).toEqual([]); + }); + + it('an unreadable visibilityState counts as hidden and is reported', () => { + const e = mkEnv(); + const errors: unknown[] = []; + const doc = {}; + Object.defineProperty(doc, 'visibilityState', { + get(): never { + throw new Error('vis'); + }, + }); + collect(new MainThreadLagTracker({ ...e.env, document: doc }, (x) => errors.push(x))); + expect(e.timers.set).toBe(0); + expect((errors[0] as Error).message).toBe('vis'); + }); + + it('a throwing clock at start is reported and rolls back; the next visible event retries', () => { + const e = mkEnv({ visible: false }); + const errors: unknown[] = []; + let boom = true; + collect( + new MainThreadLagTracker( + { + ...e.env, + now: () => { + if (boom) throw new Error('clock'); + return 0; + }, + }, + (x) => errors.push(x), + ), + ); + e.setVisible(true); + expect((errors[0] as Error).message).toBe('clock'); + expect(e.timers.live).toBe(0); + boom = false; + e.setVisible(true); + expect(e.timers.live).toBe(1); + }); + + it('a throwing scheduler is reported and rolls back; the next visible event retries', () => { + const e = mkEnv({ visible: false }); + const errors: unknown[] = []; + collect(new MainThreadLagTracker(e.env, (x) => errors.push(x))); + e.control.setFails = 1; + e.setVisible(true); + expect((errors[0] as Error).message).toBe('timer'); + expect(e.timers.live).toBe(0); + e.setVisible(true); + expect(e.timers.live).toBe(1); + }); + + it('a clock that throws at a tick is reported, skips it, and the next tick does not read the skipped interval as lag', () => { + const e = mkEnv(); + const errors: unknown[] = []; + let boom = false; + let t = 0; + const { got } = collect( + new MainThreadLagTracker( + { + ...e.env, + now: () => { + if (boom) throw new Error('clock'); + return t; + }, + }, + (x) => errors.push(x), + ), + ); + boom = true; + t = 1000; + expect(() => e.tick()).not.toThrow(); + expect((errors[0] as Error).message).toBe('clock'); + expect(got).toEqual([]); + boom = false; + t = 2000; + e.tick(); + expect(got).toEqual([0]); // not ~1000 + t = 3000 + 90; + e.tick(); + expect(got).toEqual([0, 90]); + }); + + it('a non-finite clock reading is dropped without poisoning the baseline', () => { + const e = mkEnv(); + let t = 0; + const { got } = collect(new MainThreadLagTracker({ ...e.env, now: () => t })); + t = Number.NaN; + e.tick(); + t = Number.POSITIVE_INFINITY; + e.tick(); + expect(got).toEqual([]); + t = 3000 + 5; // three intervals elapsed in total, two of them skipped + e.tick(); + expect(got).toEqual([5]); + }); + + it('uses the global timers by default, and releases them on the last unsubscribe', () => { + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); + try { + const e = mkEnv(); + const { scheduler: _s, ...rest } = e.env; + let now = 0; + const t = new MainThreadLagTracker({ ...rest, now: () => now }); + const got: number[] = []; + const off = t.on('lag', (v) => got.push(v)); + now = 1000; + vi.advanceTimersByTime(1000); + expect(got).toEqual([0]); + off(); + expect(vi.getTimerCount()).toBe(0); + } finally { + vi.useRealTimers(); + } + }); + + it('a lifecycle that throws on subscribe is reported, not thrown out of on()', () => { + const e = mkEnv(); + const errors: unknown[] = []; + const t = new MainThreadLagTracker( + { + ...e.env, + lifecycle: { + on: () => { + throw new Error('lifecycle'); + }, + }, + }, + (x) => errors.push(x), + ); + expect(() => t.on('lag', () => {})).not.toThrow(); + expect((errors[0] as Error).message).toBe('lifecycle'); + }); + + it('a throwing reporter never escapes', () => { + const e = mkEnv({ visible: false }); + const t = new MainThreadLagTracker( + { + ...e.env, + now: () => { + throw new Error('clock'); + }, + }, + () => { + throw new Error('reporter'); + }, + ); + t.on('lag', () => {}); + expect(() => e.setVisible(true)).not.toThrow(); + }); +}); diff --git a/packages/browser/src/trackers/main-thread-lag-tracker.ts b/packages/browser/src/trackers/main-thread-lag-tracker.ts new file mode 100644 index 00000000..3dfd4c8e --- /dev/null +++ b/packages/browser/src/trackers/main-thread-lag-tracker.ts @@ -0,0 +1,143 @@ +import { InterceptorBase, type Scheduler } from '@bugsee/core'; +import type { PageLifecycleTracker } from './page-lifecycle-tracker'; + +// Browser main-thread responsiveness TRACKER (`main_thread_lag_ms`): TIMER DRIFT. The sampling timer runs on the +// page's main thread, so on every tick `lag = max(0, now - (previousTickTime + intervalMs))` is how late it fired. +// The first tick compares against the run's start time + interval. A measured ~0 is a TRUE measurement and is +// emitted every tick. +// +// What a reading means (measured in Chromium): a tick fires late by (block END - the first due time the block +// covered). A block B >= 1 s therefore reads between B - 1000 and B (a 1800 ms block read 907..1797, a 2500 ms +// block 1807). A block SHORTER than 1 s that does not cross a due tick reads exactly 0 — the chance is about +// 1 - B/1000, so ~30% for a 700 ms block and ~90% for a 100 ms one. One block is reported once: the tick after +// it is measured from the late tick and clamps to 0. This is NOT Node's event-loop monitor, which samples every +// ~10 ms; sampling every 1000 ms is why short blocks can go unseen. +// +// Why not a MessageChannel ping: a ping only sees a block that begins while it is in flight, so most real +// freezes read ~0.1 ms (measured in Chromium), and a tick that runs on the same thread never sees a ping +// "still in flight". +// +// Honest limit: it reports long freezes reliably and short jank only by luck. If short jank matters, the +// follow-ups are a finer internal timer reporting the MAX drift per 1 s window, or +// `PerformanceObserver('longtask')` where supported. It may also read timer throttling that a browser applies +// to a page that still says `visible` (an occluded or minimised window, a background tab that never fired +// `visibilitychange`) as lag; that is UNVERIFIED (it could not be reproduced headless). +// +// Measured ONLY while the page is visible (the same rule as `fps`). A hidden tab throttles timers to ~1 s then +// ~1 min, which would paint a hang that never happened, so the timer is torn down on hidden and every visible +// start takes a FRESH baseline: a hidden stretch can never count as lag. No clock, no lifecycle, or hidden: +// emit NOTHING. + +export interface MainThreadLagEnv { + /** Shared lifecycle tracker for visibility changes. */ + lifecycle?: Pick; + /** Visibility is read here at activation; unknown (absent) counts as not visible. */ + document?: { readonly visibilityState?: string }; + /** Monotonic ms (the injected `performance.now`); absent omits the trace — no wall-clock guess. */ + now?: () => number; + scheduler?: Scheduler; + intervalMs?: number; +} + +const defaultScheduler: Scheduler = { + setInterval: (cb, ms) => setInterval(cb, ms), + clearInterval: (h) => clearInterval(h as ReturnType), +}; + +export class MainThreadLagTracker extends InterceptorBase<{ lag: number }> { + readonly name = 'browser-main-thread-lag'; + readonly #env: MainThreadLagEnv; + readonly #report: (error: unknown) => void; + readonly #scheduler: Scheduler; + readonly #interval: number; + #subscription: (() => void) | undefined; + #timer: unknown = null; + #running = false; + /** When the next tick is due: previous tick time + interval (the run's start + interval before the first). */ + #expectedAt = 0; + + constructor(env: MainThreadLagEnv, onError?: (error: unknown) => void) { + // A throwing reporter must not escape into the host's timer dispatch. + const report = (error: unknown): void => { + try { + onError?.(error); + } catch { + /* the reporter itself failed; nothing left to tell */ + } + }; + super(report); + this.#env = env; + this.#report = report; + this.#scheduler = env.scheduler ?? defaultScheduler; + this.#interval = env.intervalMs ?? 1000; + } + + // Guarded: the tracker is already marked active before this runs, so a throwing environment must be + // reported here rather than leak out of `on()`. + protected onActivate(): void { + // No clock to time it with, or no visibility events to gate on (a hidden tab must never keep a timer): omit. + if (typeof this.#env.now !== 'function' || this.#env.lifecycle === undefined) return; + try { + this.#subscription = this.#env.lifecycle.on('visibility', ({ visible }) => + visible ? this.#startRun() : this.#stopRun(), + ); + if (this.#isVisible()) this.#startRun(); + } catch (error) { + this.#report(error); + } + } + + protected override onDeactivate(): void { + this.#subscription?.(); + this.#subscription = undefined; + this.#stopRun(); + } + + #isVisible(): boolean { + try { + return this.#env.document?.visibilityState === 'visible'; + } catch (error) { + this.#report(error); + return false; + } + } + + #startRun(): void { + if (this.#running) return; + this.#running = true; + try { + // The clock read is inside the guarded setup: a throwing clock rolls the run back like any other setup + // failure, or `#running` would stay true with no timer and block every later start. + this.#expectedAt = (this.#env.now as () => number)() + this.#interval; // a FRESH baseline every run + this.#timer = this.#scheduler.setInterval(() => this.#tick(), this.#interval); + } catch (error) { + this.#report(error); + this.#stopRun(); // never leave a half-started run behind + } + } + + #stopRun(): void { + this.#running = false; + if (this.#timer !== null) this.#scheduler.clearInterval(this.#timer); + this.#timer = null; + } + + #tick(): void { + if (!this.#running) return; + let now: number; + try { + now = (this.#env.now as () => number)(); + } catch (error) { + this.#report(error); // an unreadable clock skips this tick; it runs inside the host's timer dispatch + this.#expectedAt += this.#interval; // the skipped interval must not read as lag on the next tick + return; + } + if (!Number.isFinite(now)) { + this.#expectedAt += this.#interval; + return; + } + const lag = Math.max(0, now - this.#expectedAt); // fired early (a hair) is on time, not negative lag + this.#expectedAt = now + this.#interval; + this.emit('lag', lag); + } +} diff --git a/packages/browser/src/trackers/screen-size-tracker.test.ts b/packages/browser/src/trackers/screen-size-tracker.test.ts new file mode 100644 index 00000000..5b79285a --- /dev/null +++ b/packages/browser/src/trackers/screen-size-tracker.test.ts @@ -0,0 +1,233 @@ +import { describe, expect, it } from 'vitest'; +import { ScreenSizeTracker } from './screen-size-tracker'; + +function mkWin(over: { screen?: unknown; dpr?: unknown } = {}) { + const l = new Map void>>(); + const win: Record = { + devicePixelRatio: 'dpr' in over ? over.dpr : 2, + addEventListener: (t: string, f: () => void) => { + const s = l.get(t) ?? new Set<() => void>(); + s.add(f); + l.set(t, s); + }, + removeEventListener: (t: string, f: () => void) => void l.get(t)?.delete(f), + }; + const screen = 'screen' in over ? over.screen : { width: 390, height: 844 }; + return { + win: win as never, + screen: screen as never, + set: (k: string, v: unknown) => { + win[k] = v; + }, + fire: (t: string) => + l.get(t)?.forEach((f) => { + f(); + }), + count: () => [...l.values()].reduce((n, s) => n + s.size, 0), + types: () => + [...l.entries()] + .filter(([, s]) => s.size > 0) + .map(([t]) => t) + .sort(), + }; +} + +describe('ScreenSizeTracker', () => { + it('attaches nothing until the first subscriber, then resize + orientationchange on the injected window', () => { + const w = mkWin(); + const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }); + expect(w.count()).toBe(0); + const off = t.on('state', () => {}); + expect(w.types()).toEqual(['orientationchange', 'resize']); + off(); + expect(w.count()).toBe(0); + }); + + it('with a shared lifecycle, orientationchange comes from IT (no extra window listener); resize stays on the window', () => { + const w = mkWin(); + const subs = new Set<() => void>(); + const lifecycle = { + on: (type: string, fn: () => void) => { + expect(type).toBe('orientationchange'); + subs.add(fn); + return () => void subs.delete(fn); + }, + }; + const t = new ScreenSizeTracker({ + lifecycle: lifecycle as never, + window: w.win, + screen: w.screen, + }); + const got: unknown[] = []; + const off = t.on('state', (s) => got.push(s)); + expect(w.types()).toEqual(['resize']); + expect(subs.size).toBe(1); + w.set('devicePixelRatio', 3); + for (const f of subs) f(); + expect(got).toEqual([{ width: 390, height: 844, dpr: 3 }]); + off(); + expect(subs.size).toBe(0); + expect(w.count()).toBe(0); + }); + + it('current() reads {width, height, dpr} live', () => { + const w = mkWin(); + const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }); + expect(t.current()).toEqual({ width: 390, height: 844, dpr: 2 }); + w.set('devicePixelRatio', 3); + expect(t.current()).toEqual({ width: 390, height: 844, dpr: 3 }); + }); + + it('emits the new state on resize and on orientationchange', () => { + const w = mkWin(); + const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }); + const got: unknown[] = []; + t.on('state', (s) => got.push(s)); + w.set('devicePixelRatio', 1.5); + w.fire('resize'); + w.set('devicePixelRatio', 2); + w.fire('orientationchange'); + expect(got).toEqual([ + { width: 390, height: 844, dpr: 1.5 }, + { width: 390, height: 844, dpr: 2 }, + ]); + }); + + it('omits (never 0 / NaN) when screen is absent or any value is not a finite positive number', () => { + const bad: unknown[] = [0, -1, NaN, Infinity, '390', null, undefined]; + for (const v of bad) { + for (const field of ['width', 'height'] as const) { + const w = mkWin({ screen: { width: 390, height: 844, [field]: v } }); + expect( + new ScreenSizeTracker({ window: w.win, screen: w.screen }).current(), + ).toBeUndefined(); + } + const w = mkWin({ dpr: v }); + expect(new ScreenSizeTracker({ window: w.win, screen: w.screen }).current()).toBeUndefined(); + } + const noScreen = mkWin(); + expect(new ScreenSizeTracker({ window: noScreen.win }).current()).toBeUndefined(); + expect(new ScreenSizeTracker({}).current()).toBeUndefined(); + }); + + it('an unreadable change emits nothing', () => { + const w = mkWin(); + const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }); + const got: unknown[] = []; + t.on('state', (s) => got.push(s)); + w.set('devicePixelRatio', 0); + w.fire('resize'); + expect(got).toEqual([]); + }); + + it('hostile getters are reported, never thrown (current and the event path)', () => { + const errors: unknown[] = []; + const hostile = { + get width(): number { + throw new Error('w'); + }, + height: 1, + }; + const w = mkWin({ screen: hostile }); + const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }, (e) => errors.push(e)); + expect(t.current()).toBeUndefined(); + expect(errors).toHaveLength(1); + t.on('state', () => {}); + expect(() => w.fire('resize')).not.toThrow(); + expect(errors).toHaveLength(2); + const dprBlocked = mkWin(); + Object.defineProperty(dprBlocked.win, 'devicePixelRatio', { + get(): never { + throw new Error('dpr'); + }, + }); + const t2 = new ScreenSizeTracker({ window: dprBlocked.win, screen: dprBlocked.screen }, (e) => + errors.push(e), + ); + expect(t2.current()).toBeUndefined(); + expect((errors[2] as Error).message).toBe('dpr'); + }); + + it('a throwing addEventListener is reported, and what attached is still released', () => { + const errors: unknown[] = []; + const w = mkWin(); + const real = (w.win as { addEventListener: (t: string, f: () => void) => void }) + .addEventListener; + let n = 0; + (w.win as { addEventListener: unknown }).addEventListener = (t: string, f: () => void) => { + if (n++ === 1) throw new Error('add'); + real(t, f); + }; + const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }, (e) => errors.push(e)); + const off = t.on('state', () => {}); + expect((errors[0] as Error).message).toBe('add'); + expect(w.count()).toBe(1); + off(); + expect(w.count()).toBe(0); + }); + + it('a throwing reporter never escapes on() or the event path', () => { + const w = mkWin(); + (w.win as { addEventListener: unknown }).addEventListener = () => { + throw new Error('add'); + }; + const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }, () => { + throw new Error('reporter'); + }); + expect(() => t.on('state', () => {})).not.toThrow(); + const hostile = mkWin({ + screen: { + get width(): number { + throw new Error('w'); + }, + height: 1, + }, + }); + expect( + new ScreenSizeTracker({ window: hostile.win, screen: hostile.screen }, () => { + throw new Error('reporter'); + }).current(), + ).toBeUndefined(); + }); + + it('a throwing subscriber with a throwing reporter does not escape the event dispatch', () => { + const w = mkWin(); + const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }, () => { + throw new Error('reporter'); + }); + t.on('state', () => { + throw new Error('subscriber'); + }); + expect(() => w.fire('resize')).not.toThrow(); + }); + + it('a throwing removeEventListener does not leak the other listener', () => { + const w = mkWin(); + const real = (w.win as { removeEventListener: (t: string, f: () => void) => void }) + .removeEventListener; + let first = true; + (w.win as { removeEventListener: unknown }).removeEventListener = ( + t: string, + f: () => void, + ) => { + if (first) { + first = false; + throw new Error('rm'); + } + real(t, f); + }; + const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }); + const off = t.on('state', () => {}); + expect(() => off()).not.toThrow(); + expect(w.count()).toBe(1); // only the one whose removal threw stays + }); + + it('works on a window with no addEventListener (initial value only)', () => { + const t = new ScreenSizeTracker({ + window: { devicePixelRatio: 1 }, + screen: { width: 1, height: 2 }, + }); + expect(() => t.on('state', () => {})).not.toThrow(); + expect(t.current()).toEqual({ width: 1, height: 2, dpr: 1 }); + }); +}); diff --git a/packages/browser/src/trackers/screen-size-tracker.ts b/packages/browser/src/trackers/screen-size-tracker.ts new file mode 100644 index 00000000..b29a3022 --- /dev/null +++ b/packages/browser/src/trackers/screen-size-tracker.ts @@ -0,0 +1,116 @@ +import { InterceptorBase } from '@bugsee/core'; +import type { PageLifecycleTracker } from './page-lifecycle-tracker'; + +// Browser screen-size TRACKER (the producer is `screen_size`; deliberately NOT Android's `displays`, which is a +// display LIST): reports `{ width, height, dpr }` — CSS px of `screen.width/height` and `devicePixelRatio` — on +// every `resize` and `orientationchange` of the injected window. `resize` is also what a page-zoom (a dpr +// change) fires, and the producer's de-duplication drops a resize that moved neither. `orientationchange` comes +// from the shared PageLifecycleTracker (like the orientation tracker; without one, from the window), but `resize` +// is listened for here, on the injected window: nothing else consumes it, and a new lifecycle event would +// change the listener count of every lifecycle subscriber for one trace. Attached on the first subscriber, +// removed on the last. Any non-finite-positive value omits the whole reading (never 0). +// +// Known staleness: moving the window to a monitor with the SAME pixel ratio but a different size fires no +// `resize`, so the value can go stale (a `(resolution: Xdppx)` media-query / `screen` change listener is a +// follow-up); and iOS Safari's `screen.width/height` do not swap on rotation. + +export interface ScreenSizeState { + width: number; + height: number; + dpr: number; +} +interface TargetLike { + addEventListener(type: string, listener: () => void): void; + removeEventListener(type: string, listener: () => void): void; +} +export interface ScreenSizeEnv { + /** Shared lifecycle tracker for `orientationchange`; when absent it is listened for on `window`. */ + lifecycle?: Pick; + /** The injected window: `resize`/`orientationchange` source AND the LIVE `devicePixelRatio` (zoom changes it). */ + window?: Partial & { readonly devicePixelRatio?: unknown }; + screen?: { readonly width?: unknown; readonly height?: unknown }; +} + +const positive = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v) && v > 0; + +export class ScreenSizeTracker extends InterceptorBase<{ state: ScreenSizeState }> { + readonly name = 'browser-screen-size'; + readonly #env: ScreenSizeEnv; + readonly #report: (error: unknown) => void; + #attached: Array<{ target: Partial; type: string }> = []; + #subscriptions: Array<() => void> = []; + + readonly #onChange = (): void => { + const state = this.current(); // reports its own failures; never throws into the browser's event dispatch + if (state !== undefined) this.emit('state', state); + }; + + constructor(env: ScreenSizeEnv, onError?: (error: unknown) => void) { + // A throwing reporter must not escape into the host's event dispatch or out of `on()`. + const report = (error: unknown): void => { + try { + onError?.(error); + } catch { + /* the reporter itself failed; nothing left to tell */ + } + }; + super(report); + this.#env = env; + this.#report = report; + } + + /** The live size, or undefined when the screen or the pixel ratio is absent / not a finite positive number. */ + current(): ScreenSizeState | undefined { + try { + const screen = this.#env.screen; + if (screen === undefined) return undefined; + const width = screen.width; + const height = screen.height; + const dpr = this.#env.window?.devicePixelRatio; + return positive(width) && positive(height) && positive(dpr) + ? { width, height, dpr } + : undefined; + } catch (error) { + this.#report(error); + return undefined; + } + } + + // Guarded: the tracker is already marked active before this runs; whatever attached before a throw is still + // removed on deactivation. + protected onActivate(): void { + try { + this.#listen('resize'); + const lifecycle = this.#env.lifecycle; + if (lifecycle !== undefined) { + this.#subscriptions.push(lifecycle.on('orientationchange', this.#onChange)); + } else { + this.#listen('orientationchange'); + } + } catch (error) { + this.#report(error); + } + } + + protected override onDeactivate(): void { + const subscriptions = this.#subscriptions; + this.#subscriptions = []; + for (const off of subscriptions) off(); + const attached = this.#attached; + this.#attached = []; + for (const { target, type } of attached) { + try { + target.removeEventListener?.(type, this.#onChange); + } catch { + /* best-effort: one failed removal must not leak the other */ + } + } + } + + #listen(type: string): void { + const target = this.#env.window; + if (typeof target?.addEventListener !== 'function') return; + target.addEventListener(type, this.#onChange); + this.#attached.push({ target, type }); + } +} diff --git a/packages/webview/src/launch.test.ts b/packages/webview/src/launch.test.ts index e3082ce1..4eb0171d 100644 --- a/packages/webview/src/launch.test.ts +++ b/packages/webview/src/launch.test.ts @@ -1074,6 +1074,98 @@ describe('launch (webview)', () => { } }); + describe('screen_size and main_thread_lag_ms (from the injected window)', () => { + const rowsOf = (fake: ReturnType, name: string): unknown[] => + entriesOfType(fake.msgs(), 'traces.system') + .map((e) => (e.p as unknown as { data: { name: string; value: unknown } }).data) + .filter((d) => d.name === name) + .map((d) => d.value); + + it('streams screen_size {width,height,dpr} and timer-drift lag from the INJECTED window; none from a hidden page', async () => { + stubSensors(); + vi.stubGlobal('screen', { width: 360, height: 640 }); + try { + const fake = fakeGlobal(); + const w = fakeWin(); + let clock = 0; + Object.defineProperty(w.win, 'performance', { + value: { now: () => clock }, + configurable: true, + }); + Object.assign(w.win, { devicePixelRatio: 3 }); + const dom = fakeDomDocument(); + Object.assign(dom.document, { visibilityState: 'visible' }); + const ticks: Array<() => void> = []; + track( + 'tok', + baseOptions({ + global: fake.global, + window: w.win, + document: dom.document as unknown as Document, + scheduler: { + setInterval: (cb, ms) => { + if (ms === 1000) ticks.push(cb as () => void); + return 0 as unknown as ReturnType; + }, + clearInterval: () => {}, + }, + }), + ); + await new Promise((r) => setTimeout(r, 0)); + expect(rowsOf(fake, 'screen_size')).toEqual([{ width: 360, height: 640, dpr: 3 }]); + clock = 1000 + 25; // the first 1 s tick fires 25 ms late + for (const t of ticks) t(); + expect(rowsOf(fake, 'main_thread_lag_ms')).toEqual([25]); + + // a hidden page never reads the clock for lag (no timer) + let hiddenReads = 0; + Object.defineProperty(w.win, 'performance', { + value: { + now: () => { + hiddenReads += 1; + return 0; + }, + }, + configurable: true, + }); + const hidden = fakeDomDocument(); + Object.assign(hidden.document, { visibilityState: 'hidden' }); + track( + 'tok2', + baseOptions({ + global: fakeGlobal().global, + window: w.win, + document: hidden.document as unknown as Document, + }), + ); + expect(hiddenReads).toBe(0); + } finally { + vi.unstubAllGlobals(); + } + }); + + it('a hostile devicePixelRatio getter never fails launch and is reported', () => { + stubSensors(); + vi.stubGlobal('screen', { width: 360, height: 640 }); + try { + const w = fakeWin(); + Object.defineProperty(w.win, 'devicePixelRatio', { + get(): never { + throw new Error('devicePixelRatio blocked'); + }, + configurable: true, + }); + const onError = vi.fn(); + expect(() => track('tok', baseOptions({ window: w.win, onError }))).not.toThrow(); + expect(onError.mock.calls.map((c) => (c[0] as Error).message)).toContain( + 'devicePixelRatio blocked', + ); + } finally { + vi.unstubAllGlobals(); + } + }); + }); + it('the document comes from the INJECTED window, not the host global (a blocked host document is never even read)', () => { stubSensors(); try {