From 10897d6e27de89b013f7c7ad4e830ece0fa01b8a Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 19 Oct 2026 14:08:48 +0500 Subject: [PATCH 1/5] feat(browser,webview): screen_size and main_thread_lag_ms traces (ST4c) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit screen_size reports {width, height, dpr} as a held step trace, re-read on resize/orientationchange. main_thread_lag_ms is a MessageChannel round-trip delta, measured only while the page is visible (hidden aborts the ping and clears the value), re-armed on every receipt and emitted once per tick. Both come from the injected window and sit behind the lifecycle gate. ๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code) --- .../browser-screen-size-main-thread-lag.md | 11 + docs/PROGRESS.md | 3 +- packages/browser/src/launch.test.ts | 170 ++++++ .../src/trace-producers.screen-lag.test.ts | 222 ++++++++ packages/browser/src/trace-producers.ts | 101 +++- .../trackers/main-thread-lag-tracker.test.ts | 484 ++++++++++++++++++ .../src/trackers/main-thread-lag-tracker.ts | 159 ++++++ .../src/trackers/screen-size-tracker.test.ts | 198 +++++++ .../src/trackers/screen-size-tracker.ts | 108 ++++ packages/webview/src/launch.test.ts | 99 ++++ 10 files changed, 1550 insertions(+), 5 deletions(-) create mode 100644 .changeset/browser-screen-size-main-thread-lag.md create mode 100644 packages/browser/src/trace-producers.screen-lag.test.ts create mode 100644 packages/browser/src/trackers/main-thread-lag-tracker.test.ts create mode 100644 packages/browser/src/trackers/main-thread-lag-tracker.ts create mode 100644 packages/browser/src/trackers/screen-size-tracker.test.ts create mode 100644 packages/browser/src/trackers/screen-size-tracker.ts 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..b90ecf43 --- /dev/null +++ b/.changeset/browser-screen-size-main-thread-lag.md @@ -0,0 +1,11 @@ +--- +'@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`. +- `main_thread_lag_ms` is the delay of a `MessageChannel` round trip on the main thread, reported once a second. It is measured only while the page is visible: a hidden tab throttles timers and messages, so hiding aborts the ping and discards the last value, and a fresh measurement starts when the page is shown again. Nothing is reported until a ping has completed in the current visible run, and a window without `MessageChannel` or `performance.now` reports nothing. + +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`. `browserTraceEnvFrom` now also carries the window's `MessageChannel`. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index c75f5b12..4634ba60 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -402,7 +402,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). Still open in ST4: `main_thread_lag_ms` (needs the hidden-tab-vs-sync-block probe first), optional `screen_size`, ST4b events (`dark_mode_changed`, `freeze`/`resume`). +- **ST4a (DONE, `feat/browser-app-state-fps`):** `app_state` (`AppStateProducer`: `foreground`/`background`, held step trace; the viewer's table is `started`/`foreground`/`background`) and `fps` (`FpsTracker` + `FpsProducer`: a `requestAnimationFrame` counter that runs ONLY while the page is visible โ€” loop and timer torn down on hidden, a fresh window on visible, a zero-length window or no rAF emits nothing; nothing is reported before the first frame of a run, since rAF can be paused while the page says visible; afterwards the first frameless window is reported as 0 and a continuing stall goes quiet; no lifecycle = omitted). The traces env is now built from the INJECTED window + document (`browserTraceEnvFrom`; no fallback to `globalThis`, so a window without `performance.memory` omits the heap). Still open in ST4: ST4b events (`dark_mode_changed`, `freeze`/`resume`). +- **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) and `main_thread_lag_ms` (`MainThreadLagTracker` + `MainThreadLagProducer`: a `MessageChannel` post-to-receipt delta from the INJECTED window (`browserTraceEnvFrom` now carries `MessageChannel`), measured ONLY while visible โ€” hidden aborts the in-flight ping, CLEARS the delta and does not re-arm; while visible the ping re-arms on every receipt; the latest delta is emitted once per 1 s scheduler tick as a polled (`hold:false`) trace; nothing before the first completed ping of a visible run (never 0); no `MessageChannel` / `performance.now` / lifecycle = omitted, no timer; a late receipt from a dead run is dropped by a generation tag). 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); the continuous ping-pong keeps the main thread's message queue busy while visible โ€” measure its cost before relying on it in perf-sensitive pages. - **ST0โ€ฒ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container (per-producer start/stop isolation, last-value refresh so a rolling window never loses a rarely-changing diff --git a/packages/browser/src/launch.test.ts b/packages/browser/src/launch.test.ts index 0fc961d4..2b923f3d 100644 --- a/packages/browser/src/launch.test.ts +++ b/packages/browser/src/launch.test.ts @@ -1439,6 +1439,176 @@ 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 from the INJECTED window MessageChannel while visible, re-arming and clearing on hide', async () => { + stubSensors(); + const d = mkDoc(true); + const w = fakeWindow(); + let clock = 0; + Object.defineProperty(w.win, 'performance', { + value: { now: () => clock }, + configurable: true, + }); + const chans: Array<{ + posted: number; + closed: number; + port1: { onmessage: (() => void) | null }; + }> = []; + class Ch { + port1: { onmessage: (() => void) | null; close: () => void }; + port2: { postMessage: () => void; close: () => void }; + constructor() { + const c = { + posted: 0, + closed: 0, + port1: { + onmessage: null as (() => void) | null, + close: () => { + c.closed += 1; + }, + }, + }; + this.port1 = c.port1; + this.port2 = { + postMessage: () => { + c.posted += 1; + }, + close: () => { + c.closed += 1; + }, + }; + chans.push(c); + } + } + Object.assign(w.win, { MessageChannel: Ch }); + const ticks: Array<() => void> = []; + 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) ticks.push(cb); + return 'h'; + }, + clearInterval: () => {}, + }, + }), + ); + expect(chans).toHaveLength(1); + expect(chans[0]?.posted).toBe(1); + clock = 40; + chans[0]?.port1.onmessage?.(); + expect(chans[0]?.posted).toBe(2); // re-armed on receipt + for (const t of ticks) t(); + d.setVisible(false); + expect(chans[0]?.closed).toBe(2); // hidden: aborted + for (const t of ticks) t(); + expect(await rowsOf(store, 'main_thread_lag_ms')).toEqual([40]); + }); + + it('a hidden injected document never creates a MessageChannel', async () => { + stubSensors(); + const d = mkDoc(false); + const w = fakeWindow(); + let created = 0; + Object.assign(w.win, { + MessageChannel: class { + constructor() { + created += 1; + } + }, + }); + await launchTracked( + 'tok', + noSampler({ + window: w.win, + document: d.doc as unknown as Document, + captureStore: memStore(), + }), + ); + expect(created).toBe(0); + }); + + it('a hostile MessageChannel / devicePixelRatio getter never fails launch and is reported', async () => { + stubSensors(); + vi.stubGlobal('screen', { width: 390, height: 844 }); + const w = fakeWindow(); + for (const key of ['MessageChannel', 'devicePixelRatio']) { + Object.defineProperty(w.win, key, { + get(): never { + throw new Error(`${key} 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).toEqual( + expect.arrayContaining(['MessageChannel blocked', 'devicePixelRatio blocked']), + ); + expect(await rowsOf(store, 'screen_size')).toEqual([]); + await client.stop(); + }); + + it('a systemMetricsSampler override builds neither screen_size nor the lag ping', async () => { + stubSensors(); + vi.stubGlobal('screen', { width: 390, height: 844 }); + const d = mkDoc(true); + const w = fakeWindow(); + let created = 0; + Object.assign(w.win, { + devicePixelRatio: 2, + MessageChannel: class { + constructor() { + created += 1; + } + }, + }); + 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(created).toBe(0); + }); + 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..02859c7f --- /dev/null +++ b/packages/browser/src/trace-producers.screen-lag.test.ts @@ -0,0 +1,222 @@ +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 latest delta as a POLLED value (hold:false), and nothing before one is measured', () => { + 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; + let onmessage: (() => void) | null = null; + class Ch { + port1 = { + set onmessage(f: (() => void) | null) { + onmessage = f; + }, + close: () => {}, + }; + port2 = { postMessage: () => {}, close: () => {} }; + } + const tracker = new MainThreadLagTracker({ + lifecycle, + document: doc, + MessageChannel: Ch as never, + now: () => now, + scheduler: { + setInterval: (cb) => { + timer = cb; + return 1; + }, + clearInterval: () => {}, + }, + }); + const out: Emit[] = []; + const p = new MainThreadLagProducer(tracker); + p.start(sinkOf(out)); + timer?.(); + expect(out).toEqual([]); + now = 120; + (onmessage as (() => void) | null)?.(); + timer?.(); + expect(out).toEqual([{ name: 'main_thread_lag_ms', value: 120, hold: false }]); + expect(doc.count()).toBe(1); + p.stop(); + expect(doc.count()).toBe(0); + timer?.(); + expect(out).toHaveLength(1); + }); +}); + +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/MessageChannel/clock/scheduler into the trackers, nothing from globals', () => { + const win = Object.assign(mkTarget(), { + devicePixelRatio: 2, + screen: { width: 100, height: 200 }, + performance: { now: () => 7 }, + }); + const posted: number[] = []; + class Ch { + port1 = { onmessage: null as unknown, close: () => {} }; + port2 = { postMessage: () => void posted.push(1), close: () => {} }; + } + Object.assign(win, { MessageChannel: Ch }); + const doc = { visibilityState: 'visible' }; + const lifecycle = new PageLifecycleTracker({ + window: win, + document: Object.assign(mkTarget(), doc), + }); + const errors: unknown[] = []; + const ps = createBrowserSystemTraceProducers( + { ...browserTraceEnvFrom(win, doc), lifecycle }, + (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 }, + ]); + expect(posted).toHaveLength(1); // the lag ping went through the INJECTED window's channel + expect(errors).toEqual([]); + }); + + it('a window without a performance clock or MessageChannel starts no ping', () => { + 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), + }); + const env = browserTraceEnvFrom(win, doc); + expect(env.MessageChannel).toBeUndefined(); + const out: Emit[] = []; + const lag = createBrowserSystemTraceProducers({ ...env, lifecycle }).find( + (p) => p.name === 'main-thread-lag', + ); + expect(() => lag?.start(sinkOf(out))).not.toThrow(); + expect(out).toEqual([]); + }); +}); + +describe('browserTraceEnvFrom: MessageChannel', () => { + it("hands over THIS window's constructor, omits a non-constructor, and reports a hostile getter", () => { + class Ch {} + expect(browserTraceEnvFrom({ MessageChannel: Ch }, undefined).MessageChannel).toBe(Ch); + expect('MessageChannel' in browserTraceEnvFrom({ MessageChannel: 5 }, undefined)).toBe(false); + expect('MessageChannel' in browserTraceEnvFrom({}, undefined)).toBe(false); + const hostile = {}; + Object.defineProperty(hostile, 'MessageChannel', { + get(): never { + throw new Error('MessageChannel blocked'); + }, + }); + const errors: unknown[] = []; + const env = browserTraceEnvFrom(hostile, undefined, (e) => errors.push(e)); + expect('MessageChannel' in env).toBe(false); + expect((errors[0] as Error).message).toBe('MessageChannel blocked'); + }); +}); diff --git a/packages/browser/src/trace-producers.ts b/packages/browser/src/trace-producers.ts index 020f257c..4c65b4d0 100644 --- a/packages/browser/src/trace-producers.ts +++ b/packages/browser/src/trace-producers.ts @@ -13,6 +13,7 @@ import { ConnectionTracker, } from './trackers/connection-tracker'; import { type FpsEnv, FpsTracker } from './trackers/fps-tracker'; +import { type MainThreadLagEnv, MainThreadLagTracker } from './trackers/main-thread-lag-tracker'; import { type MemoryReading, type MemoryState, MemoryTracker } from './trackers/memory-tracker'; import { type OrientationEnv, @@ -20,6 +21,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 @@ -237,6 +243,63 @@ 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. + */ +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`: the latest `MessageChannel` round-trip delta, once per sampling tick, ONLY while the page + * is visible (a hidden tab's throttled timers would paint a hang that did not happen). Polled, so each value is + * emitted and never held or refreshed; nothing measured yet means nothing emitted. + */ +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 @@ -248,17 +311,19 @@ 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`. */ requestAnimationFrame?: FpsEnv['requestAnimationFrame']; cancelAnimationFrame?: FpsEnv['cancelAnimationFrame']; + /** `window.MessageChannel` (the injected window's constructor): drives `main_thread_lag_ms`. */ + MessageChannel?: MainThreadLagEnv['MessageChannel']; /** * `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. */ @@ -273,6 +338,7 @@ interface WindowSurfaces { screen?: BrowserTraceEnv['screen']; requestAnimationFrame?: (callback: (timestamp: number) => void) => number; cancelAnimationFrame?: (handle: number) => void; + MessageChannel?: BrowserTraceEnv['MessageChannel']; } /** @@ -308,6 +374,8 @@ export function browserTraceEnvFrom( const getBattery = nav === undefined ? undefined : read(() => nav.getBattery); const raf = read(() => win.requestAnimationFrame); const caf = read(() => win.cancelAnimationFrame); + // A constructor needs no `this`, so it is handed over as read (it still belongs to THIS window). + const messageChannel = read(() => win.MessageChannel); return { ...(nav !== undefined ? { navigator: nav } : {}), ...(performance !== undefined ? { performance } : {}), @@ -316,6 +384,7 @@ export function browserTraceEnvFrom( ...(document !== undefined ? { document } : {}), ...(typeof raf === 'function' ? { requestAnimationFrame: (cb) => raf.call(win, cb) } : {}), ...(typeof caf === 'function' ? { cancelAnimationFrame: (h) => caf.call(win, h) } : {}), + ...(typeof messageChannel === 'function' ? { MessageChannel: messageChannel } : {}), ...(nav !== undefined && typeof getBattery === 'function' ? { getBattery: () => getBattery.call(nav) } : {}), @@ -417,6 +486,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 } : {}), + ...(env.MessageChannel !== undefined ? { MessageChannel: env.MessageChannel } : {}), + ...(safePerformanceNow(env, onError) !== undefined + ? { now: () => (env.performance as { now(): number }).now() } + : {}), + ...(env.scheduler !== undefined ? { scheduler: env.scheduler } : {}), + }, + onError, + ), + ), new FpsProducer( new FpsTracker( { 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..25b016a9 --- /dev/null +++ b/packages/browser/src/trackers/main-thread-lag-tracker.test.ts @@ -0,0 +1,484 @@ +import type { Scheduler } from '@bugsee/core'; +import { describe, expect, it, vi } from 'vitest'; +import { MainThreadLagTracker } from './main-thread-lag-tracker'; + +// A controllable page: a fake MessageChannel whose posted messages are delivered by hand, a manual clock, +// a visibility lifecycle and a manual interval. +function mkEnv(over: { visible?: boolean; noChannel?: 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 scheduler: Scheduler = { + setInterval: (cb) => { + timerCb = cb; + timers.set += 1; + timers.live += 1; + return { id: timers.set }; + }, + clearInterval: () => { + timers.cleared += 1; + timers.live -= 1; + }, + }; + interface Chan { + port1: { onmessage: ((e: unknown) => void) | null; close: () => void }; + port2: { postMessage: (m: unknown) => void; close: () => void }; + queue: number; + closed: number; + deliver: () => void; + } + const channels: Chan[] = []; + const control = { postFails: 0, ctorFails: 0 }; + class FakeChannel { + port1: Chan['port1']; + port2: Chan['port2']; + constructor() { + if (control.ctorFails-- > 0) throw new Error('ctor'); + const chan: Chan = { + queue: 0, + closed: 0, + port1: { + onmessage: null, + close: () => { + chan.closed += 1; + }, + }, + port2: { + postMessage: () => { + if (control.postFails-- > 0) throw new Error('post'); + chan.queue += 1; + }, + close: () => { + chan.closed += 1; + }, + }, + deliver: () => { + // a message already in flight can still be delivered after close() in a real engine + const n = chan.queue; // a re-arm posts a NEW message; it is delivered by the next call + chan.queue = 0; + for (let i = 0; i < n; i++) chan.port1.onmessage?.({}); + }, + }; + this.port1 = chan.port1; + this.port2 = chan.port2; + channels.push(chan); + } + } + 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.noChannel ? {} : { MessageChannel: FakeChannel as never }), + ...(over.noNow ? {} : { now: () => now }), + scheduler, + }; + return { + env, + doc, + timers, + channels, + control, + advance: (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', () => { + it('attaches nothing until the first subscriber', () => { + const e = mkEnv(); + new MainThreadLagTracker(e.env); + expect(e.channels).toHaveLength(0); + expect(e.timers.set).toBe(0); + expect(e.listeners()).toBe(0); + }); + + it('while visible: posts one ping, and the delta is the clock distance between post and receipt', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + expect(e.channels).toHaveLength(1); + expect(e.channels[0]?.queue).toBe(1); + e.advance(37); + e.channels[0]?.port1.onmessage?.({}); + e.tick(); + expect(got).toEqual([37]); + }); + + it('omits until a ping has completed in this run (never 0 before the first receipt)', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + e.advance(1000); + e.tick(); + e.advance(1000); + e.tick(); + expect(got).toEqual([]); + }); + + it('RE-ARMS on every receipt, so the number tracks the main thread for the whole session', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + const chan = e.channels[0]; + e.advance(5); + chan?.deliver(); + expect(chan?.queue).toBe(1); // posted again + e.tick(); + e.advance(250); // the main thread blocked for a quarter second + chan?.port1.onmessage?.({}); + e.tick(); + expect(got).toEqual([5, 250]); + expect(e.channels).toHaveLength(1); // one channel per run, not one per ping + }); + + it('a polled trace: the latest delta is emitted on EVERY tick (not consumed)', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + e.advance(8); + e.channels[0]?.port1.onmessage?.({}); + e.tick(); + e.tick(); + expect(got).toEqual([8, 8]); + }); + + it('going hidden aborts the in-flight ping, CLEARS the delta, closes the channel and stops the timer', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + e.advance(3); + e.channels[0]?.port1.onmessage?.({}); + e.setVisible(false); + expect(e.timers.live).toBe(0); + expect(e.channels[0]?.closed).toBe(2); + expect(e.channels[0]?.port1.onmessage).toBeNull(); + e.tick(); // even a stray tick has nothing to say + expect(got).toEqual([]); + }); + + it('does NOT re-arm while hidden: a late receipt neither writes nor posts again', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + const chan = e.channels[0]; + const late = chan?.port1.onmessage; + e.setVisible(false); + e.advance(60_000); // a throttled hidden completion + late?.({}); + expect(chan?.queue).toBe(1); // only the original post; no re-arm + expect(e.channels).toHaveLength(1); + e.setVisible(true); + e.tick(); + expect(got).toEqual([]); // the hidden completion never became a sample + }); + + it('a late receipt from an aborted run can never write into the NEW run (generation guard)', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + const stale = e.channels[0]?.port1.onmessage; + e.setVisible(false); + e.advance(60_000); + e.setVisible(true); + expect(e.channels).toHaveLength(2); + stale?.({}); // arrives after the new run started + e.tick(); + expect(got).toEqual([]); + expect(e.channels[1]?.queue).toBe(1); // and did not post on the new run's behalf + e.advance(4); + e.channels[1]?.port1.onmessage?.({}); + e.tick(); + expect(got).toEqual([4]); + }); + + it('hide -> show: omits until a ping that STARTED and completed in the visible run lands', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + e.advance(10); + e.channels[0]?.port1.onmessage?.({}); + e.tick(); + e.setVisible(false); + e.setVisible(true); + e.tick(); + expect(got).toEqual([10]); // nothing from the previous run's state + }); + + it('hidden at start: no channel, no timer, nothing emitted', () => { + const e = mkEnv({ visible: false }); + const { got } = collect(new MainThreadLagTracker(e.env)); + expect(e.channels).toHaveLength(0); + expect(e.timers.live).toBe(0); + e.tick(); + expect(got).toEqual([]); + e.setVisible(true); + expect(e.channels).toHaveLength(1); + expect(e.timers.live).toBe(1); + }); + + it('duplicate visible/hidden events do not stack channels or timers', () => { + const e = mkEnv(); + collect(new MainThreadLagTracker(e.env)); + e.setVisible(true); + e.setVisible(true); + expect(e.channels).toHaveLength(1); + expect(e.timers.live).toBe(1); + e.setVisible(false); + e.setVisible(false); + expect(e.timers.live).toBe(0); + expect(e.channels[0]?.closed).toBe(2); + }); + + it('the last unsubscribe stops everything; a re-subscribe restarts with a fresh channel', () => { + 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); + expect(e.channels[0]?.closed).toBe(2); + collect(t); + expect(e.channels).toHaveLength(2); + expect(e.timers.live).toBe(1); + }); + + it('a runtime without MessageChannel is omitted: no timer, no subscription, no error', () => { + const e = mkEnv({ noChannel: 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('without a clock it measures nothing (no host fallback, no wall-clock guess)', () => { + const e = mkEnv({ noNow: true }); + collect(new MainThreadLagTracker(e.env)); + expect(e.channels).toHaveLength(0); + expect(e.timers.set).toBe(0); + }); + + 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.channels).toHaveLength(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.channels).toHaveLength(0); + expect((errors[0] as Error).message).toBe('vis'); + }); + + it('a throwing MessageChannel constructor is reported and rolls the start 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.ctorFails = 1; + e.setVisible(true); + expect((errors[0] as Error).message).toBe('ctor'); + expect(e.timers.live).toBe(0); + e.setVisible(true); + expect(e.channels).toHaveLength(1); + expect(e.timers.live).toBe(1); + }); + + it('a throwing postMessage is reported, rolls back, and closes the half-built channel', () => { + const e = mkEnv({ visible: false }); + const errors: unknown[] = []; + collect(new MainThreadLagTracker(e.env, (x) => errors.push(x))); + e.control.postFails = 1; + e.setVisible(true); + expect((errors[0] as Error).message).toBe('post'); + expect(e.timers.live).toBe(0); + expect(e.channels[0]?.closed).toBe(2); + e.setVisible(true); + expect(e.timers.live).toBe(1); + }); + + it('a throwing clock at start is reported and rolls back like any setup failure', () => { + 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 clock that throws at receipt is reported, drops the sample and stops re-arming', () => { + const e = mkEnv(); + const errors: unknown[] = []; + let calls = 0; + const { got } = collect( + new MainThreadLagTracker( + { + ...e.env, + now: () => { + if (++calls > 1) throw new Error('clock'); + return 0; + }, + }, + (x) => errors.push(x), + ), + ); + expect(() => e.channels[0]?.port1.onmessage?.({})).not.toThrow(); + e.tick(); + expect((errors[0] as Error).message).toBe('clock'); + expect(got).toEqual([]); + expect(e.channels[0]?.queue).toBe(1); // no re-arm + }); + + it('a postMessage that throws while re-arming is reported and the stale delta is CLEARED', () => { + const e = mkEnv(); + const errors: unknown[] = []; + const { got } = collect(new MainThreadLagTracker(e.env, (x) => errors.push(x))); + e.advance(2); + e.channels[0]?.port1.onmessage?.({}); + e.tick(); + e.control.postFails = 1; + e.advance(2); + expect(() => e.channels[0]?.port1.onmessage?.({})).not.toThrow(); + expect((errors[0] as Error).message).toBe('post'); + e.tick(); + expect(got).toEqual([2]); // not a frozen last number + }); + + it('a negative or non-finite delta is discarded, never reported as a lag', () => { + const e = mkEnv(); + let t = 100; + const { got } = collect(new MainThreadLagTracker({ ...e.env, now: () => t })); + t = 90; // a backwards clock + e.channels[0]?.port1.onmessage?.({}); + e.tick(); + t = Number.NaN; + e.channels[0]?.port1.onmessage?.({}); + e.tick(); + expect(got).toEqual([]); + }); + + it('an infinite delta is discarded too', () => { + const e = mkEnv(); + let t = 0; + const { got } = collect(new MainThreadLagTracker({ ...e.env, now: () => t })); + t = Number.POSITIVE_INFINITY; + e.channels[0]?.port1.onmessage?.({}); + e.tick(); + expect(got).toEqual([]); + }); + + it('a throwing port close is swallowed on stop', () => { + const e = mkEnv(); + collect(new MainThreadLagTracker(e.env)); + const chan = e.channels[0]; + if (chan !== undefined) + chan.port1.close = () => { + throw new Error('close'); + }; + expect(() => e.setVisible(false)).not.toThrow(); + expect(chan?.closed).toBe(1); // port2 was still closed + }); + + it('samples every second by default and honors intervalMs', () => { + 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]); + }); + + 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 = 9; + e.channels[0]?.port1.onmessage?.({}); + vi.advanceTimersByTime(1000); + expect(got).toEqual([9]); + 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, () => { + throw new Error('reporter'); + }); + t.on('lag', () => {}); + e.control.ctorFails = 1; + 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..608221f2 --- /dev/null +++ b/packages/browser/src/trackers/main-thread-lag-tracker.ts @@ -0,0 +1,159 @@ +import { InterceptorBase, type Scheduler } from '@bugsee/core'; +import type { PageLifecycleTracker } from './page-lifecycle-tracker'; + +// Browser main-thread responsiveness TRACKER (`main_thread_lag_ms`): the delay between posting a message on a +// `MessageChannel` and receiving it back on the same thread, i.e. how long a fresh task waited behind whatever +// the main thread was doing. `MessageChannel`, not `setTimeout(0)`: timers are clamped to 4 ms. +// +// Measured ONLY while the page is visible (the same rule as `fps`). A hidden tab clamps timers and message +// delivery to ~1 s and then ~1 min, so a hidden round-trip measures the browser's throttling and would paint a +// hang that never happened. On hidden the run is torn down โ€” the in-flight ping is aborted, the last delta is +// CLEARED, nothing re-arms โ€” and a fresh run starts on visible, reporting nothing until a ping that started AND +// completed inside it lands. While visible the ping RE-ARMS on every receipt (a one-shot ping would freeze one +// number for the whole session) and the latest delta is emitted once per sampling tick. No delta yet, no +// MessageChannel, no clock, no lifecycle, or hidden: emit NOTHING โ€” omit, never zero. + +export interface MessageChannelLike { + port1: { onmessage: ((event: unknown) => void) | null; close(): void }; + port2: { postMessage(message: unknown): void; close(): void }; +} + +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 }; + /** The INJECTED window's `MessageChannel` constructor; absent omits the trace. */ + MessageChannel?: new () => MessageChannelLike; + /** 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; + #subscription: (() => void) | undefined; + #timer: unknown = null; + #channel: MessageChannelLike | undefined; + #running = false; + #lastDelta: number | undefined; + #run = 0; + + constructor(env: MainThreadLagEnv, onError?: (error: unknown) => void) { + // A throwing reporter must not escape into the host's message/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; + } + + // 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 { + // Nothing to ping with, nothing to time it with, or no visibility events to gate on (a hidden tab must + // never keep a ping loop): omit. + if ( + typeof this.#env.MessageChannel !== 'function' || + 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; + this.#lastDelta = undefined; + try { + const Channel = this.#env.MessageChannel as new () => MessageChannelLike; + const channel = new Channel(); + this.#channel = channel; + this.#arm(channel, this.#run); + this.#timer = this.#scheduler.setInterval(() => this.#tick(), this.#env.intervalMs ?? 1000); + } catch (error) { + this.#report(error); + this.#stopRun(); // never leave a half-started run (or its channel) behind + } + } + + #stopRun(): void { + this.#running = false; + this.#run += 1; // a receipt still in flight belongs to a dead run and must never write + this.#lastDelta = undefined; // a hidden stretch must not leave a stale number to be re-emitted + if (this.#timer !== null) this.#scheduler.clearInterval(this.#timer); + this.#timer = null; + const channel = this.#channel; + this.#channel = undefined; + if (channel === undefined) return; + channel.port1.onmessage = null; + for (const port of [channel.port1, channel.port2]) { + try { + port.close(); + } catch { + /* best-effort */ + } + } + } + + // Posts one ping and installs the receipt handler that stores the delta and re-arms. Throws on a failing + // clock/channel: `#startRun` rolls back on it, the receipt handler reports it. + #arm(channel: MessageChannelLike, run: number): void { + const now = this.#env.now as () => number; + const startedAt = now(); + channel.port1.onmessage = () => { + if (run !== this.#run) return; // `#stopRun` bumps the generation: a dead run's receipt is dropped + try { + const delta = now() - startedAt; + if (Number.isFinite(delta) && delta >= 0) this.#lastDelta = delta; + this.#arm(channel, run); + } catch (error) { + this.#lastDelta = undefined; // an unreadable clock/channel must not leave a frozen number behind + this.#report(error); + } + }; + channel.port2.postMessage(undefined); + } + + #tick(): void { + if (this.#lastDelta !== undefined) this.emit('lag', this.#lastDelta); + } +} 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..44de591b --- /dev/null +++ b/packages/browser/src/trackers/screen-size-tracker.test.ts @@ -0,0 +1,198 @@ +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 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..e6eb5b9e --- /dev/null +++ b/packages/browser/src/trackers/screen-size-tracker.ts @@ -0,0 +1,108 @@ +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). + +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 #onError: ((error: unknown) => void) | undefined; + #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) { + super(onError); + this.#env = env; + this.#onError = onError; + } + + /** 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) { + try { + this.#onError?.(error); + } catch { + /* the reporter itself failed */ + } + 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.#onError?.(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 73a40b1b..eab531cb 100644 --- a/packages/webview/src/launch.test.ts +++ b/packages/webview/src/launch.test.ts @@ -1015,6 +1015,105 @@ 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 a lag delta 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, + }); + let onmessage: (() => void) | null = null; + let created = 0; + class Ch { + port1 = { + set onmessage(f: (() => void) | null) { + onmessage = f; + }, + close: () => {}, + }; + port2 = { postMessage: () => {}, close: () => {} }; + constructor() { + created += 1; + } + } + Object.assign(w.win, { devicePixelRatio: 3, MessageChannel: Ch }); + 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 }]); + expect(created).toBe(1); + clock = 25; + (onmessage as (() => void) | null)?.(); + for (const t of ticks) t(); + expect(rowsOf(fake, 'main_thread_lag_ms')).toEqual([25]); + + // a hidden page never creates a channel + 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(created).toBe(1); + } finally { + vi.unstubAllGlobals(); + } + }); + + it('a hostile MessageChannel / devicePixelRatio getter never fails launch and is reported', () => { + stubSensors(); + try { + const w = fakeWin(); + for (const key of ['MessageChannel', 'devicePixelRatio']) { + Object.defineProperty(w.win, key, { + get(): never { + throw new Error(`${key} 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( + 'MessageChannel 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 { From 780859563b6f8be063c318f4e14a13b74d443ce5 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 19 Oct 2026 14:15:02 +0500 Subject: [PATCH 2/5] test(browser): ST4c producer test tolerates the lifecycle's freeze/resume document listeners MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code) --- packages/browser/src/trace-producers.screen-lag.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/browser/src/trace-producers.screen-lag.test.ts b/packages/browser/src/trace-producers.screen-lag.test.ts index 02859c7f..b88393ae 100644 --- a/packages/browser/src/trace-producers.screen-lag.test.ts +++ b/packages/browser/src/trace-producers.screen-lag.test.ts @@ -115,6 +115,7 @@ describe('MainThreadLagProducer', () => { }); const out: Emit[] = []; const p = new MainThreadLagProducer(tracker); + expect(doc.count()).toBe(0); p.start(sinkOf(out)); timer?.(); expect(out).toEqual([]); @@ -122,7 +123,7 @@ describe('MainThreadLagProducer', () => { (onmessage as (() => void) | null)?.(); timer?.(); expect(out).toEqual([{ name: 'main_thread_lag_ms', value: 120, hold: false }]); - expect(doc.count()).toBe(1); + expect(doc.count()).toBeGreaterThan(0); // the lifecycle attached its document listeners for us p.stop(); expect(doc.count()).toBe(0); timer?.(); From 728d1931d8d38012c5a70f4b4d014ef4de0c1be5 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 19 Oct 2026 14:23:22 +0500 Subject: [PATCH 3/5] fix(browser): main_thread_lag_ms pings once per tick, not in a loop (ST4c review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Re-arming on every receipt was a continuous task loop and overwrote a long-task delta with a ~0 one. A receipt now only stores the delta; each 1 s tick emits it and posts ONE new ping, and a ping still in flight at a tick reports its age (a lower bound) instead of posting another. Also: wire the clock only when performance.now is a function, wrap the screen-size tracker's reporter, and document screen_size staleness. ๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code) --- .../browser-screen-size-main-thread-lag.md | 3 +- docs/PROGRESS.md | 2 +- packages/browser/src/launch.test.ts | 5 +- .../src/trace-producers.screen-lag.test.ts | 33 ++- packages/browser/src/trace-producers.ts | 12 +- .../trackers/main-thread-lag-tracker.test.ts | 257 +++++++++++++----- .../src/trackers/main-thread-lag-tracker.ts | 79 ++++-- .../src/trackers/screen-size-tracker.test.ts | 35 +++ .../src/trackers/screen-size-tracker.ts | 26 +- 9 files changed, 337 insertions(+), 115 deletions(-) diff --git a/.changeset/browser-screen-size-main-thread-lag.md b/.changeset/browser-screen-size-main-thread-lag.md index b90ecf43..556f88b2 100644 --- a/.changeset/browser-screen-size-main-thread-lag.md +++ b/.changeset/browser-screen-size-main-thread-lag.md @@ -6,6 +6,7 @@ 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`. -- `main_thread_lag_ms` is the delay of a `MessageChannel` round trip on the main thread, reported once a second. It is measured only while the page is visible: a hidden tab throttles timers and messages, so hiding aborts the ping and discards the last value, and a fresh measurement starts when the page is shown again. Nothing is reported until a ping has completed in the current visible run, and a window without `MessageChannel` or `performance.now` reports nothing. +- `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 the delay of a `MessageChannel` round trip on the main thread, one ping per second (never a continuous loop). A ping that is still pending at the next tick reports its age instead of posting another, so a freeze shows up while it is happening. It is measured only while the page is visible: a hidden tab throttles timers and messages, so hiding aborts the ping and discards the last value, and a fresh measurement starts when the page is shown again. Nothing is reported before the first tick of a visible run, and a window without `MessageChannel` or a `performance.now` function reports nothing. 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`. `browserTraceEnvFrom` now also carries the window's `MessageChannel`. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 26e92ece..c0e7dc2d 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -403,7 +403,7 @@ solid), in slices: 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`). 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) and `main_thread_lag_ms` (`MainThreadLagTracker` + `MainThreadLagProducer`: a `MessageChannel` post-to-receipt delta from the INJECTED window (`browserTraceEnvFrom` now carries `MessageChannel`), measured ONLY while visible โ€” hidden aborts the in-flight ping, CLEARS the delta and does not re-arm; while visible the ping re-arms on every receipt; the latest delta is emitted once per 1 s scheduler tick as a polled (`hold:false`) trace; nothing before the first completed ping of a visible run (never 0); no `MessageChannel` / `performance.now` / lifecycle = omitted, no timer; a late receipt from a dead run is dropped by a generation tag). 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); the continuous ping-pong keeps the main thread's message queue busy while visible โ€” measure its cost before relying on it in perf-sensitive pages. +- **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`: a `MessageChannel` post-to-receipt delta from the INJECTED window (`browserTraceEnvFrom` now carries `MessageChannel`), measured ONLY while visible โ€” hidden aborts the in-flight ping, CLEARS the delta and stops the timer; ONE ping per 1 s scheduler tick, never a loop: a receipt stores the delta and does NOT post again (re-arming on receipt was a continuous task loop โ€” ~2M receipts/s, a whole core โ€” and overwrote a long-task delta with a ~0 one); the next tick emits the stored delta (polled, `hold:false`, consumed) and posts ONE new ping, and if a ping is STILL in flight at a tick (thread blocked) it posts nothing and emits its age `now - startedAt` as a lower bound, so a freeze is visible while it happens; a failed post/clock is reported, clears the delta, and the next tick retries; nothing before the first tick of a visible run (never 0); no `MessageChannel` / `performance.now` / lifecycle = omitted, no timer; a late receipt from a dead run is dropped by a generation tag; the clock is wired only when `performance.now` is a function). 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). - **ST0โ€ฒ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container (per-producer start/stop isolation, last-value refresh so a rolling window never loses a rarely-changing diff --git a/packages/browser/src/launch.test.ts b/packages/browser/src/launch.test.ts index eaa8780f..efde774c 100644 --- a/packages/browser/src/launch.test.ts +++ b/packages/browser/src/launch.test.ts @@ -1588,7 +1588,7 @@ describe('launch', () => { expect(await rowsOf(store, 'screen_size')).toEqual([]); }); - it('records main_thread_lag_ms from the INJECTED window MessageChannel while visible, re-arming and clearing on hide', async () => { + it('records main_thread_lag_ms from the INJECTED window MessageChannel while visible, one ping per tick, clearing on hide', async () => { stubSensors(); const d = mkDoc(true); const w = fakeWindow(); @@ -1650,8 +1650,9 @@ describe('launch', () => { expect(chans[0]?.posted).toBe(1); clock = 40; chans[0]?.port1.onmessage?.(); - expect(chans[0]?.posted).toBe(2); // re-armed on receipt + expect(chans[0]?.posted).toBe(1); // a receipt never posts again for (const t of ticks) t(); + expect(chans[0]?.posted).toBe(2); // the tick emitted 40 and re-armed with exactly one ping d.setVisible(false); expect(chans[0]?.closed).toBe(2); // hidden: aborted for (const t of ticks) t(); diff --git a/packages/browser/src/trace-producers.screen-lag.test.ts b/packages/browser/src/trace-producers.screen-lag.test.ts index b88393ae..a0f11683 100644 --- a/packages/browser/src/trace-producers.screen-lag.test.ts +++ b/packages/browser/src/trace-producers.screen-lag.test.ts @@ -117,10 +117,10 @@ describe('MainThreadLagProducer', () => { const p = new MainThreadLagProducer(tracker); expect(doc.count()).toBe(0); p.start(sinkOf(out)); - timer?.(); - expect(out).toEqual([]); + expect(out).toEqual([]); // nothing before the first tick now = 120; (onmessage as (() => void) | null)?.(); + now = 1000; timer?.(); expect(out).toEqual([{ name: 'main_thread_lag_ms', value: 120, hold: false }]); expect(doc.count()).toBeGreaterThan(0); // the lifecycle attached its document listeners for us @@ -203,6 +203,35 @@ describe('createBrowserSystemTraceProducers: screen_size + main_thread_lag_ms', }); }); +describe('main_thread_lag_ms clock wiring', () => { + it('a performance.now that is not a function omits the trace quietly (no ping, no error)', () => { + const win = mkTarget(); + const doc = Object.assign(mkTarget(), { visibilityState: 'visible' }); + const lifecycle = new PageLifecycleTracker({ window: win, document: doc }); + let created = 0; + class Ch { + constructor() { + created += 1; + } + } + const errors: unknown[] = []; + const lag = createBrowserSystemTraceProducers( + { + lifecycle, + document: doc, + MessageChannel: Ch as never, + performance: { now: 5 as never }, + }, + (e) => errors.push(e), + ).find((p) => p.name === 'main-thread-lag'); + const out: Emit[] = []; + lag?.start(sinkOf(out)); + expect(created).toBe(0); + expect(errors).toEqual([]); + expect(out).toEqual([]); + }); +}); + describe('browserTraceEnvFrom: MessageChannel', () => { it("hands over THIS window's constructor, omits a non-constructor, and reports a hostile getter", () => { class Ch {} diff --git a/packages/browser/src/trace-producers.ts b/packages/browser/src/trace-producers.ts index 4c65b4d0..7db12b14 100644 --- a/packages/browser/src/trace-producers.ts +++ b/packages/browser/src/trace-producers.ts @@ -248,6 +248,10 @@ export class FpsProducer extends TraceProducerBase { * 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'; @@ -277,8 +281,9 @@ export class ScreenSizeProducer extends TraceProducerBase { /** * `main_thread_lag_ms`: the latest `MessageChannel` round-trip delta, once per sampling tick, ONLY while the page - * is visible (a hidden tab's throttled timers would paint a hang that did not happen). Polled, so each value is - * emitted and never held or refreshed; nothing measured yet means nothing emitted. + * is visible (a hidden tab's throttled timers would paint a hang that did not happen). One ping per tick, never a + * loop; a ping still pending at a tick reports its age. Polled, so each value is emitted and never held or + * refreshed; nothing measured yet means nothing emitted. */ export class MainThreadLagProducer extends TraceProducerBase { readonly name = 'main-thread-lag'; @@ -502,7 +507,8 @@ export function createBrowserSystemTraceProducers( lifecycle: env.lifecycle, ...(env.document !== undefined ? { document: env.document } : {}), ...(env.MessageChannel !== undefined ? { MessageChannel: env.MessageChannel } : {}), - ...(safePerformanceNow(env, onError) !== undefined + // Only a real clock function is wired; anything else omits the trace quietly (no error). + ...(typeof safePerformanceNow(env, onError) === 'function' ? { now: () => (env.performance as { now(): number }).now() } : {}), ...(env.scheduler !== undefined ? { scheduler: env.scheduler } : {}), diff --git a/packages/browser/src/trackers/main-thread-lag-tracker.test.ts b/packages/browser/src/trackers/main-thread-lag-tracker.test.ts index 25b016a9..f3b65273 100644 --- a/packages/browser/src/trackers/main-thread-lag-tracker.test.ts +++ b/packages/browser/src/trackers/main-thread-lag-tracker.test.ts @@ -2,9 +2,11 @@ import type { Scheduler } from '@bugsee/core'; import { describe, expect, it, vi } from 'vitest'; import { MainThreadLagTracker } from './main-thread-lag-tracker'; -// A controllable page: a fake MessageChannel whose posted messages are delivered by hand, a manual clock, -// a visibility lifecycle and a manual interval. -function mkEnv(over: { visible?: boolean; noChannel?: boolean; noNow?: boolean } = {}) { +// A controllable page: a fake MessageChannel whose posted messages are delivered by hand (or automatically, +// synchronously, with `auto`), a manual clock, a visibility lifecycle and a manual interval. +function mkEnv( + over: { visible?: boolean; noChannel?: boolean; noNow?: boolean; auto?: number } = {}, +) { let now = 0; const doc = { visibilityState: over.visible === false ? 'hidden' : 'visible' }; const visListeners = new Set<(e: { visible: boolean }) => void>(); @@ -26,11 +28,12 @@ function mkEnv(over: { visible?: boolean; noChannel?: boolean; noNow?: boolean } port1: { onmessage: ((e: unknown) => void) | null; close: () => void }; port2: { postMessage: (m: unknown) => void; close: () => void }; queue: number; + posts: number; closed: number; deliver: () => void; } const channels: Chan[] = []; - const control = { postFails: 0, ctorFails: 0 }; + const control = { postFails: 0, ctorFails: 0, auto: over.auto }; class FakeChannel { port1: Chan['port1']; port2: Chan['port2']; @@ -38,6 +41,7 @@ function mkEnv(over: { visible?: boolean; noChannel?: boolean; noNow?: boolean } if (control.ctorFails-- > 0) throw new Error('ctor'); const chan: Chan = { queue: 0, + posts: 0, closed: 0, port1: { onmessage: null, @@ -48,15 +52,19 @@ function mkEnv(over: { visible?: boolean; noChannel?: boolean; noNow?: boolean } port2: { postMessage: () => { if (control.postFails-- > 0) throw new Error('post'); + chan.posts += 1; chan.queue += 1; + if (control.auto !== undefined) { + now += control.auto; // the round trip takes `auto` ms, delivered at once + chan.deliver(); + } }, close: () => { chan.closed += 1; }, }, deliver: () => { - // a message already in flight can still be delivered after close() in a real engine - const n = chan.queue; // a re-arm posts a NEW message; it is delivered by the next call + const n = chan.queue; chan.queue = 0; for (let i = 0; i < n; i++) chan.port1.onmessage?.({}); }, @@ -85,6 +93,7 @@ function mkEnv(over: { visible?: boolean; noChannel?: boolean; noNow?: boolean } timers, channels, control, + posts: () => channels.reduce((n, c) => n + c.posts, 0), advance: (ms: number) => { now += ms; }, @@ -112,57 +121,82 @@ describe('MainThreadLagTracker', () => { expect(e.listeners()).toBe(0); }); - it('while visible: posts one ping, and the delta is the clock distance between post and receipt', () => { + it('while visible: posts ONE ping at start; its receipt stores the delta, which is emitted on the NEXT tick', () => { const e = mkEnv(); const { got } = collect(new MainThreadLagTracker(e.env)); - expect(e.channels).toHaveLength(1); - expect(e.channels[0]?.queue).toBe(1); + expect(e.posts()).toBe(1); e.advance(37); - e.channels[0]?.port1.onmessage?.({}); + e.channels[0]?.deliver(); + expect(got).toEqual([]); // a receipt never posts and never emits by itself + expect(e.posts()).toBe(1); + e.advance(963); e.tick(); expect(got).toEqual([37]); + expect(e.posts()).toBe(2); // the tick re-armed with exactly one ping }); - it('omits until a ping has completed in this run (never 0 before the first receipt)', () => { + it('a delta is emitted once (consumed); the tick after it with no new receipt reports the stall instead', () => { const e = mkEnv(); const { got } = collect(new MainThreadLagTracker(e.env)); + e.advance(8); + e.channels[0]?.deliver(); + e.tick(); // emits 8, posts at t=8 e.advance(1000); - e.tick(); - e.advance(1000); - e.tick(); - expect(got).toEqual([]); + e.tick(); // the ping posted at the last tick has not come back for 1000 ms + expect(got).toEqual([8, 1000]); }); - it('RE-ARMS on every receipt, so the number tracks the main thread for the whole session', () => { + it('FLOOD GUARD: at most one post per tick however long it runs, with a channel that delivers instantly', () => { + const e = mkEnv({ auto: 3 }); + const { got } = collect(new MainThreadLagTracker(e.env)); + expect(e.posts()).toBe(1); // a delivered ping does not post again by itself + for (let i = 0; i < 50; i++) { + e.advance(997); + e.tick(); + } + expect(e.posts()).toBe(51); // the start ping + one per tick, never more + expect(got).toHaveLength(50); + expect(got.every((v) => v === 3)).toBe(true); + }); + + it('a long task between post and receipt shows in the emitted value (receipt delivered before the tick)', () => { const e = mkEnv(); const { got } = collect(new MainThreadLagTracker(e.env)); - const chan = e.channels[0]; - e.advance(5); - chan?.deliver(); - expect(chan?.queue).toBe(1); // posted again - e.tick(); - e.advance(250); // the main thread blocked for a quarter second - chan?.port1.onmessage?.({}); + e.advance(300); // the main thread was blocked for 300 ms with the ping queued + e.channels[0]?.deliver(); + e.advance(700); e.tick(); - expect(got).toEqual([5, 250]); - expect(e.channels).toHaveLength(1); // one channel per run, not one per ping + expect(got).toEqual([300]); }); - it('a polled trace: the latest delta is emitted on EVERY tick (not consumed)', () => { + it('a long task shows even when the TICK runs first: a ping still in flight reports its age and posts nothing', () => { const e = mkEnv(); const { got } = collect(new MainThreadLagTracker(e.env)); - e.advance(8); - e.channels[0]?.port1.onmessage?.({}); + e.advance(1300); + e.tick(); // still in flight after 1.3 s + expect(got).toEqual([1300]); + expect(e.posts()).toBe(1); + e.advance(500); e.tick(); + expect(got).toEqual([1300, 1800]); // the age keeps growing while blocked, and still one ping total + expect(e.posts()).toBe(1); + e.channels[0]?.deliver(); // the thread frees up e.tick(); - expect(got).toEqual([8, 8]); + expect(got).toEqual([1300, 1800, 1800]); // the completed measurement, then re-armed + expect(e.posts()).toBe(2); + }); + + it('a freshly started run with a ping in flight reports it only once the tick finds it still pending', () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + expect(got).toEqual([]); // nothing measured and nothing emitted before the first tick }); it('going hidden aborts the in-flight ping, CLEARS the delta, closes the channel and stops the timer', () => { const e = mkEnv(); const { got } = collect(new MainThreadLagTracker(e.env)); e.advance(3); - e.channels[0]?.port1.onmessage?.({}); + e.channels[0]?.deliver(); e.setVisible(false); expect(e.timers.live).toBe(0); expect(e.channels[0]?.closed).toBe(2); @@ -171,7 +205,7 @@ describe('MainThreadLagTracker', () => { expect(got).toEqual([]); }); - it('does NOT re-arm while hidden: a late receipt neither writes nor posts again', () => { + it('a hidden completion is dropped: a late receipt neither writes nor posts', () => { const e = mkEnv(); const { got } = collect(new MainThreadLagTracker(e.env)); const chan = e.channels[0]; @@ -179,41 +213,93 @@ describe('MainThreadLagTracker', () => { e.setVisible(false); e.advance(60_000); // a throttled hidden completion late?.({}); - expect(chan?.queue).toBe(1); // only the original post; no re-arm - expect(e.channels).toHaveLength(1); + expect(e.posts()).toBe(1); e.setVisible(true); + e.advance(1000); e.tick(); - expect(got).toEqual([]); // the hidden completion never became a sample + expect(got).toEqual([1000]); // aged from the NEW run's ping, never the 60 s hidden stretch }); - it('a late receipt from an aborted run can never write into the NEW run (generation guard)', () => { + it('hide -> show: the first visible tick sees only the NEW run (no hidden-throttled sample, no stale number)', () => { const e = mkEnv(); const { got } = collect(new MainThreadLagTracker(e.env)); const stale = e.channels[0]?.port1.onmessage; - e.setVisible(false); + e.advance(10); + e.channels[0]?.deliver(); // a sample exists... + e.setVisible(false); // ...and is cleared e.advance(60_000); e.setVisible(true); - expect(e.channels).toHaveLength(2); - stale?.({}); // arrives after the new run started + stale?.({}); // an aborted run's receipt arriving late + e.advance(5); + e.channels[1]?.deliver(); + e.advance(995); e.tick(); - expect(got).toEqual([]); - expect(e.channels[1]?.queue).toBe(1); // and did not post on the new run's behalf - e.advance(4); - e.channels[1]?.port1.onmessage?.({}); + expect(got).toEqual([5]); // measured entirely inside the visible run + }); + + it("a stale receipt from an aborted run cannot complete the NEW run's ping", () => { + const e = mkEnv(); + const { got } = collect(new MainThreadLagTracker(e.env)); + const stale = e.channels[0]?.port1.onmessage; + e.setVisible(false); + e.advance(60_000); + e.setVisible(true); + stale?.({}); + e.advance(1000); e.tick(); - expect(got).toEqual([4]); + expect(got).toEqual([1000]); // still in flight, aged from the new post (not a stale ~0 sample) + expect(e.posts()).toBe(2); }); - it('hide -> show: omits until a ping that STARTED and completed in the visible run lands', () => { + it("hide -> show clears the previous run's sample: it is never emitted in the new run", () => { const e = mkEnv(); const { got } = collect(new MainThreadLagTracker(e.env)); e.advance(10); - e.channels[0]?.port1.onmessage?.({}); - e.tick(); + e.channels[0]?.deliver(); // sample 10 stored e.setVisible(false); e.setVisible(true); + e.advance(1000); + e.tick(); // the new ping is still pending: its age, not the old 10 + expect(got).toEqual([1000]); + }); + + it("a previous run's sample cannot resurface through a later DISCARDED receipt", () => { + const e = mkEnv(); + let t = 0; + const { got } = collect(new MainThreadLagTracker({ ...e.env, now: () => t })); + t = 10; + e.channels[0]?.deliver(); // sample 10 stored + e.setVisible(false); + t = 100; + e.setVisible(true); + t = 50; // backwards: the new run's receipt is discarded + e.channels[1]?.deliver(); + e.tick(); + expect(got).toEqual([]); + }); + + it('a discarded (backwards-clock) receipt after an emitted sample does not re-emit the old sample', () => { + const e = mkEnv(); + let t = 0; + const { got } = collect(new MainThreadLagTracker({ ...e.env, now: () => t })); + t = 20; + e.channels[0]?.deliver(); + e.tick(); // emits 20, posts at t=20 + t = 5; // backwards + e.channels[0]?.deliver(); // discarded e.tick(); - expect(got).toEqual([10]); // nothing from the previous run's state + expect(got).toEqual([20]); + }); + + it('an unreadable age is not emitted: a backwards or infinite clock while a ping is pending', () => { + const e = mkEnv(); + let t = 100; + const { got } = collect(new MainThreadLagTracker({ ...e.env, now: () => t })); + t = 50; + e.tick(); + t = Number.POSITIVE_INFINITY; + e.tick(); + expect(got).toEqual([]); }); it('hidden at start: no channel, no timer, nothing emitted', () => { @@ -309,7 +395,7 @@ describe('MainThreadLagTracker', () => { expect(e.timers.live).toBe(1); }); - it('a throwing postMessage is reported, rolls back, and closes the half-built channel', () => { + it('a throwing postMessage at start is reported, rolls back, and closes the half-built channel', () => { const e = mkEnv({ visible: false }); const errors: unknown[] = []; collect(new MainThreadLagTracker(e.env, (x) => errors.push(x))); @@ -346,42 +432,72 @@ describe('MainThreadLagTracker', () => { expect(e.timers.live).toBe(1); }); - it('a clock that throws at receipt is reported, drops the sample and stops re-arming', () => { + it('a postMessage that throws at a tick is reported, the stale delta is CLEARED, and the NEXT tick retries', () => { const e = mkEnv(); const errors: unknown[] = []; - let calls = 0; + const { got } = collect(new MainThreadLagTracker(e.env, (x) => errors.push(x))); + e.advance(2); + e.channels[0]?.deliver(); + e.control.postFails = 1; + e.tick(); // emits 2, then fails to re-arm + expect(got).toEqual([2]); + expect((errors[0] as Error).message).toBe('post'); + e.advance(1000); + e.tick(); // nothing in flight, nothing stored: it retries and does not invent a number + expect(got).toEqual([2]); + expect(e.posts()).toBe(2); // start + the retry + e.advance(4); + e.channels[0]?.deliver(); + e.tick(); + expect(got).toEqual([2, 4]); + }); + + it('a clock that throws at a tick is reported, drops that tick, and the next tick recovers', () => { + const e = mkEnv(); + const errors: unknown[] = []; + let boom = false; + let t = 0; const { got } = collect( new MainThreadLagTracker( { ...e.env, now: () => { - if (++calls > 1) throw new Error('clock'); - return 0; + if (boom) throw new Error('clock'); + return t; }, }, (x) => errors.push(x), ), ); - expect(() => e.channels[0]?.port1.onmessage?.({})).not.toThrow(); - e.tick(); + boom = true; + expect(() => e.tick()).not.toThrow(); // in flight: the age cannot be read expect((errors[0] as Error).message).toBe('clock'); expect(got).toEqual([]); - expect(e.channels[0]?.queue).toBe(1); // no re-arm + boom = false; + t = 40; + e.tick(); + expect(got).toEqual([40]); }); - it('a postMessage that throws while re-arming is reported and the stale delta is CLEARED', () => { + it('a clock that throws at receipt is reported, drops the sample and frees the next tick to retry', () => { const e = mkEnv(); const errors: unknown[] = []; - const { got } = collect(new MainThreadLagTracker(e.env, (x) => errors.push(x))); - e.advance(2); - e.channels[0]?.port1.onmessage?.({}); - e.tick(); - e.control.postFails = 1; - e.advance(2); - expect(() => e.channels[0]?.port1.onmessage?.({})).not.toThrow(); - expect((errors[0] as Error).message).toBe('post'); - e.tick(); - expect(got).toEqual([2]); // not a frozen last number + let calls = 0; + const { got } = collect( + new MainThreadLagTracker( + { + ...e.env, + now: () => { + if (++calls > 1) throw new Error('clock'); + return 0; + }, + }, + (x) => errors.push(x), + ), + ); + expect(() => e.channels[0]?.deliver()).not.toThrow(); + expect((errors[0] as Error).message).toBe('clock'); + expect(got).toEqual([]); }); it('a negative or non-finite delta is discarded, never reported as a lag', () => { @@ -389,10 +505,7 @@ describe('MainThreadLagTracker', () => { let t = 100; const { got } = collect(new MainThreadLagTracker({ ...e.env, now: () => t })); t = 90; // a backwards clock - e.channels[0]?.port1.onmessage?.({}); - e.tick(); - t = Number.NaN; - e.channels[0]?.port1.onmessage?.({}); + e.channels[0]?.deliver(); e.tick(); expect(got).toEqual([]); }); @@ -402,7 +515,7 @@ describe('MainThreadLagTracker', () => { let t = 0; const { got } = collect(new MainThreadLagTracker({ ...e.env, now: () => t })); t = Number.POSITIVE_INFINITY; - e.channels[0]?.port1.onmessage?.({}); + e.channels[0]?.deliver(); e.tick(); expect(got).toEqual([]); }); @@ -444,7 +557,7 @@ describe('MainThreadLagTracker', () => { const got: number[] = []; const off = t.on('lag', (v) => got.push(v)); now = 9; - e.channels[0]?.port1.onmessage?.({}); + e.channels[0]?.deliver(); vi.advanceTimersByTime(1000); expect(got).toEqual([9]); off(); diff --git a/packages/browser/src/trackers/main-thread-lag-tracker.ts b/packages/browser/src/trackers/main-thread-lag-tracker.ts index 608221f2..f3765def 100644 --- a/packages/browser/src/trackers/main-thread-lag-tracker.ts +++ b/packages/browser/src/trackers/main-thread-lag-tracker.ts @@ -5,13 +5,18 @@ import type { PageLifecycleTracker } from './page-lifecycle-tracker'; // `MessageChannel` and receiving it back on the same thread, i.e. how long a fresh task waited behind whatever // the main thread was doing. `MessageChannel`, not `setTimeout(0)`: timers are clamped to 4 ms. // +// ONE ping per sampling tick, never a loop. A receipt must NOT post again: re-arming on receipt is a continuous +// task loop (a whole core, starved idle callbacks) and it also overwrites a long-task delta with a ~0 one a few +// microseconds later. Instead each tick, while visible: +// - no ping in flight: emit the delta the last receipt stored (if any, consumed), then post ONE new ping; +// - ping STILL in flight (the thread has been blocked since the last tick): post nothing and emit its age, +// `now - startedAt`, a lower bound on the lag, so a freeze is visible while it is happening. The completed +// delta is emitted on the following tick (the same stall is thus reported twice: its floor, then its size). // Measured ONLY while the page is visible (the same rule as `fps`). A hidden tab clamps timers and message // delivery to ~1 s and then ~1 min, so a hidden round-trip measures the browser's throttling and would paint a -// hang that never happened. On hidden the run is torn down โ€” the in-flight ping is aborted, the last delta is -// CLEARED, nothing re-arms โ€” and a fresh run starts on visible, reporting nothing until a ping that started AND -// completed inside it lands. While visible the ping RE-ARMS on every receipt (a one-shot ping would freeze one -// number for the whole session) and the latest delta is emitted once per sampling tick. No delta yet, no -// MessageChannel, no clock, no lifecycle, or hidden: emit NOTHING โ€” omit, never zero. +// hang that never happened. On hidden the run is torn down โ€” the in-flight ping is aborted, the delta CLEARED โ€” +// and a fresh run starts on visible. A failed post or clock is reported, clears the delta, and the next tick +// retries. No MessageChannel, no clock, no lifecycle, or hidden: emit NOTHING โ€” omit, never zero. export interface MessageChannelLike { port1: { onmessage: ((event: unknown) => void) | null; close(): void }; @@ -46,6 +51,8 @@ export class MainThreadLagTracker extends InterceptorBase<{ lag: number }> { #channel: MessageChannelLike | undefined; #running = false; #lastDelta: number | undefined; + #inFlight = false; + #startedAt = 0; #run = 0; constructor(env: MainThreadLagEnv, onError?: (error: unknown) => void) { @@ -102,12 +109,13 @@ export class MainThreadLagTracker extends InterceptorBase<{ lag: number }> { #startRun(): void { if (this.#running) return; this.#running = true; - this.#lastDelta = undefined; try { const Channel = this.#env.MessageChannel as new () => MessageChannelLike; const channel = new Channel(); this.#channel = channel; - this.#arm(channel, this.#run); + const run = this.#run; + channel.port1.onmessage = () => this.#onReceipt(run); + this.#ping(channel); this.#timer = this.#scheduler.setInterval(() => this.#tick(), this.#env.intervalMs ?? 1000); } catch (error) { this.#report(error); @@ -134,26 +142,47 @@ export class MainThreadLagTracker extends InterceptorBase<{ lag: number }> { } } - // Posts one ping and installs the receipt handler that stores the delta and re-arms. Throws on a failing - // clock/channel: `#startRun` rolls back on it, the receipt handler reports it. - #arm(channel: MessageChannelLike, run: number): void { - const now = this.#env.now as () => number; - const startedAt = now(); - channel.port1.onmessage = () => { - if (run !== this.#run) return; // `#stopRun` bumps the generation: a dead run's receipt is dropped - try { - const delta = now() - startedAt; - if (Number.isFinite(delta) && delta >= 0) this.#lastDelta = delta; - this.#arm(channel, run); - } catch (error) { - this.#lastDelta = undefined; // an unreadable clock/channel must not leave a frozen number behind - this.#report(error); - } - }; - channel.port2.postMessage(undefined); + // Posts ONE ping. `#inFlight` is set before the post so a synchronous delivery is still seen as a receipt; + // a failed post un-sets it and throws (`#startRun` rolls back on it, `#tick` reports it). + #ping(channel: MessageChannelLike): void { + this.#startedAt = (this.#env.now as () => number)(); + this.#inFlight = true; + try { + channel.port2.postMessage(undefined); + } catch (error) { + this.#inFlight = false; + throw error; + } + } + + #onReceipt(run: number): void { + if (run !== this.#run) return; // `#stopRun` bumps the generation: a dead run's receipt is dropped + this.#inFlight = false; + try { + const delta = (this.#env.now as () => number)() - this.#startedAt; + if (Number.isFinite(delta) && delta >= 0) this.#lastDelta = delta; + } catch (error) { + this.#lastDelta = undefined; + this.#report(error); + } } #tick(): void { - if (this.#lastDelta !== undefined) this.emit('lag', this.#lastDelta); + const channel = this.#channel; + if (channel === undefined) return; + try { + if (this.#inFlight) { + // Blocked since the last tick: its age so far is the (lower-bound) lag. No second ping. + const age = (this.#env.now as () => number)() - this.#startedAt; + if (Number.isFinite(age) && age >= 0) this.emit('lag', age); + return; + } + const delta = this.#lastDelta; + this.#lastDelta = undefined; + if (delta !== undefined) this.emit('lag', delta); + this.#ping(channel); + } catch (error) { + this.#report(error); // nothing stale to clear: the delta was consumed above, or a ping is in flight + } } } diff --git a/packages/browser/src/trackers/screen-size-tracker.test.ts b/packages/browser/src/trackers/screen-size-tracker.test.ts index 44de591b..5b79285a 100644 --- a/packages/browser/src/trackers/screen-size-tracker.test.ts +++ b/packages/browser/src/trackers/screen-size-tracker.test.ts @@ -166,6 +166,41 @@ describe('ScreenSizeTracker', () => { 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 }) diff --git a/packages/browser/src/trackers/screen-size-tracker.ts b/packages/browser/src/trackers/screen-size-tracker.ts index e6eb5b9e..b29a3022 100644 --- a/packages/browser/src/trackers/screen-size-tracker.ts +++ b/packages/browser/src/trackers/screen-size-tracker.ts @@ -9,6 +9,10 @@ import type { PageLifecycleTracker } from './page-lifecycle-tracker'; // 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; @@ -32,7 +36,7 @@ const positive = (v: unknown): v is number => typeof v === 'number' && Number.is export class ScreenSizeTracker extends InterceptorBase<{ state: ScreenSizeState }> { readonly name = 'browser-screen-size'; readonly #env: ScreenSizeEnv; - readonly #onError: ((error: unknown) => void) | undefined; + readonly #report: (error: unknown) => void; #attached: Array<{ target: Partial; type: string }> = []; #subscriptions: Array<() => void> = []; @@ -42,9 +46,17 @@ export class ScreenSizeTracker extends InterceptorBase<{ state: ScreenSizeState }; constructor(env: ScreenSizeEnv, onError?: (error: unknown) => void) { - super(onError); + // 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.#onError = onError; + this.#report = report; } /** The live size, or undefined when the screen or the pixel ratio is absent / not a finite positive number. */ @@ -59,11 +71,7 @@ export class ScreenSizeTracker extends InterceptorBase<{ state: ScreenSizeState ? { width, height, dpr } : undefined; } catch (error) { - try { - this.#onError?.(error); - } catch { - /* the reporter itself failed */ - } + this.#report(error); return undefined; } } @@ -80,7 +88,7 @@ export class ScreenSizeTracker extends InterceptorBase<{ state: ScreenSizeState this.#listen('orientationchange'); } } catch (error) { - this.#onError?.(error); + this.#report(error); } } From ebe9ca3849d214ebf1796015fdcea03dd48048d2 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 19 Oct 2026 14:31:54 +0500 Subject: [PATCH 4/5] fix(browser): main_thread_lag_ms is timer drift, not a MessageChannel ping (ST4c review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A ping only sees a block that begins while it is in flight, so most real freezes read ~0.1 ms in Chromium. The tracker now measures how late the 1 s sampling timer fires (max(0, now - (previousTick + interval))), emitted every tick while visible, with a fresh baseline on every visible start. The MessageChannel machinery and its env plumbing are deleted. ๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code) --- .../browser-screen-size-main-thread-lag.md | 4 +- docs/PROGRESS.md | 2 +- packages/browser/src/launch.test.ts | 131 +++-- .../src/trace-producers.screen-lag.test.ts | 116 +++-- packages/browser/src/trace-producers.ts | 18 +- .../trackers/main-thread-lag-tracker.test.ts | 453 +++++------------- .../src/trackers/main-thread-lag-tracker.ts | 138 ++---- packages/webview/src/launch.test.ts | 55 +-- 8 files changed, 305 insertions(+), 612 deletions(-) diff --git a/.changeset/browser-screen-size-main-thread-lag.md b/.changeset/browser-screen-size-main-thread-lag.md index 556f88b2..fab30ed0 100644 --- a/.changeset/browser-screen-size-main-thread-lag.md +++ b/.changeset/browser-screen-size-main-thread-lag.md @@ -7,6 +7,6 @@ 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 the delay of a `MessageChannel` round trip on the main thread, one ping per second (never a continuous loop). A ping that is still pending at the next tick reports its age instead of posting another, so a freeze shows up while it is happening. It is measured only while the page is visible: a hidden tab throttles timers and messages, so hiding aborts the ping and discards the last value, and a fresh measurement starts when the page is shown again. Nothing is reported before the first tick of a visible run, and a window without `MessageChannel` or a `performance.now` function reports nothing. +- `main_thread_lag_ms` is timer drift, the classic event-loop-lag measurement: how late the 1 s sampling timer fired on the page's main thread (a long task or synchronous block delays it by its length), emitted every tick while the page is visible; a measured 0 is a real value. 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. Honest limit: it also reads as lag when the browser throttles the timer of a page that still says `visible` (an occluded or minimised window). -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`. `browserTraceEnvFrom` now also carries the window's `MessageChannel`. +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 c0e7dc2d..e2b8a773 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -403,7 +403,7 @@ solid), in slices: 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`). 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`: a `MessageChannel` post-to-receipt delta from the INJECTED window (`browserTraceEnvFrom` now carries `MessageChannel`), measured ONLY while visible โ€” hidden aborts the in-flight ping, CLEARS the delta and stops the timer; ONE ping per 1 s scheduler tick, never a loop: a receipt stores the delta and does NOT post again (re-arming on receipt was a continuous task loop โ€” ~2M receipts/s, a whole core โ€” and overwrote a long-task delta with a ~0 one); the next tick emits the stored delta (polled, `hold:false`, consumed) and posts ONE new ping, and if a ping is STILL in flight at a tick (thread blocked) it posts nothing and emits its age `now - startedAt` as a lower bound, so a freeze is visible while it happens; a failed post/clock is reported, clears the delta, and the next tick retries; nothing before the first tick of a visible run (never 0); no `MessageChannel` / `performance.now` / lifecycle = omitted, no timer; a late receipt from a dead run is dropped by a generation tag; the clock is wired only when `performance.now` is a function). 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). +- **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, the classic event-loop-lag technique (as Node's monitor): 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. 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:** it measures how late the sampling timer fires โ€” real jank/long tasks, but ALSO timer throttling the browser applies to a page that still says `visible` (occluded/minimised window, background tab without a `visibilitychange`). **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). - **ST0โ€ฒ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container (per-producer start/stop isolation, last-value refresh so a rolling window never loses a rarely-changing diff --git a/packages/browser/src/launch.test.ts b/packages/browser/src/launch.test.ts index 523c4c67..6401348c 100644 --- a/packages/browser/src/launch.test.ts +++ b/packages/browser/src/launch.test.ts @@ -1588,48 +1588,17 @@ describe('launch', () => { expect(await rowsOf(store, 'screen_size')).toEqual([]); }); - it('records main_thread_lag_ms from the INJECTED window MessageChannel while visible, one ping per tick, clearing on hide', async () => { + 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 = 0; + let clock = 5_000; Object.defineProperty(w.win, 'performance', { value: { now: () => clock }, configurable: true, }); - const chans: Array<{ - posted: number; - closed: number; - port1: { onmessage: (() => void) | null }; - }> = []; - class Ch { - port1: { onmessage: (() => void) | null; close: () => void }; - port2: { postMessage: () => void; close: () => void }; - constructor() { - const c = { - posted: 0, - closed: 0, - port1: { - onmessage: null as (() => void) | null, - close: () => { - c.closed += 1; - }, - }, - }; - this.port1 = c.port1; - this.port2 = { - postMessage: () => { - c.posted += 1; - }, - close: () => { - c.closed += 1; - }, - }; - chans.push(c); - } - } - Object.assign(w.win, { MessageChannel: Ch }); - const ticks: Array<() => void> = []; + const live = new Map void>(); + let nextHandle = 1; const store = memStore(); await launchTracked( 'tok', @@ -1639,37 +1608,47 @@ describe('launch', () => { captureStore: store, scheduler: { setInterval: (cb, ms) => { - if (ms === 1000) ticks.push(cb); - return 'h'; + if (ms !== 1000) return 'other'; + const h = nextHandle++; + live.set(h, cb); + return h; }, - clearInterval: () => {}, + clearInterval: (h) => void live.delete(h as number), }, }), ); - expect(chans).toHaveLength(1); - expect(chans[0]?.posted).toBe(1); - clock = 40; - chans[0]?.port1.onmessage?.(); - expect(chans[0]?.posted).toBe(1); // a receipt never posts again - for (const t of ticks) t(); - expect(chans[0]?.posted).toBe(2); // the tick emitted 40 and re-armed with exactly one ping + 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); - expect(chans[0]?.closed).toBe(2); // hidden: aborted - for (const t of ticks) t(); - expect(await rowsOf(store, 'main_thread_lag_ms')).toEqual([40]); + 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 creates a MessageChannel', async () => { + 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 created = 0; - Object.assign(w.win, { - MessageChannel: class { - constructor() { - created += 1; - } + let reads = 0; + Object.defineProperty(w.win, 'performance', { + value: { + now: () => { + reads += 1; + return 0; + }, }, + configurable: true, }); await launchTracked( 'tok', @@ -1679,21 +1658,19 @@ describe('launch', () => { captureStore: memStore(), }), ); - expect(created).toBe(0); + expect(reads).toBe(0); }); - it('a hostile MessageChannel / devicePixelRatio getter never fails launch and is reported', async () => { + it('a hostile devicePixelRatio getter never fails launch and is reported', async () => { stubSensors(); vi.stubGlobal('screen', { width: 390, height: 844 }); const w = fakeWindow(); - for (const key of ['MessageChannel', 'devicePixelRatio']) { - Object.defineProperty(w.win, key, { - get(): never { - throw new Error(`${key} blocked`); - }, - configurable: true, - }); - } + 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( @@ -1701,26 +1678,26 @@ describe('launch', () => { noSampler({ window: w.win, captureStore: store, onError }), ); const messages = onError.mock.calls.map((c) => (c[0] as Error).message); - expect(messages).toEqual( - expect.arrayContaining(['MessageChannel blocked', 'devicePixelRatio blocked']), - ); + 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 ping', async () => { + 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 created = 0; - Object.assign(w.win, { - devicePixelRatio: 2, - MessageChannel: class { - constructor() { - created += 1; - } + 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( @@ -1732,7 +1709,7 @@ describe('launch', () => { }), ); expect(await rowsOf(store, 'screen_size')).toEqual([]); - expect(created).toBe(0); + 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 () => { diff --git a/packages/browser/src/trace-producers.screen-lag.test.ts b/packages/browser/src/trace-producers.screen-lag.test.ts index a0f11683..78d7f2a7 100644 --- a/packages/browser/src/trace-producers.screen-lag.test.ts +++ b/packages/browser/src/trace-producers.screen-lag.test.ts @@ -84,26 +84,15 @@ describe('ScreenSizeProducer', () => { }); describe('MainThreadLagProducer', () => { - it('emits each tick latest delta as a POLLED value (hold:false), and nothing before one is measured', () => { + 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; - let onmessage: (() => void) | null = null; - class Ch { - port1 = { - set onmessage(f: (() => void) | null) { - onmessage = f; - }, - close: () => {}, - }; - port2 = { postMessage: () => {}, close: () => {} }; - } const tracker = new MainThreadLagTracker({ lifecycle, document: doc, - MessageChannel: Ch as never, now: () => now, scheduler: { setInterval: (cb) => { @@ -118,16 +107,19 @@ describe('MainThreadLagProducer', () => { expect(doc.count()).toBe(0); p.start(sinkOf(out)); expect(out).toEqual([]); // nothing before the first tick - now = 120; - (onmessage as (() => void) | null)?.(); now = 1000; timer?.(); - expect(out).toEqual([{ name: 'main_thread_lag_ms', value: 120, hold: false }]); + 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(1); + expect(out).toHaveLength(2); }); }); @@ -153,26 +145,32 @@ describe('createBrowserSystemTraceProducers: screen_size + main_thread_lag_ms', ]); }); - it('wires the env window/screen/document/MessageChannel/clock/scheduler into the trackers, nothing from globals', () => { + 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: () => 7 }, + performance: { now: () => t }, }); - const posted: number[] = []; - class Ch { - port1 = { onmessage: null as unknown, close: () => {} }; - port2 = { postMessage: () => void posted.push(1), close: () => {} }; - } - Object.assign(win, { MessageChannel: Ch }); 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 }, + { + ...browserTraceEnvFrom(win, doc), + lifecycle, + scheduler: { + setInterval: (cb) => { + timer = cb; + return 1; + }, + clearInterval: () => {}, + }, + }, (e) => errors.push(e), ); const out: Emit[] = []; @@ -181,72 +179,70 @@ describe('createBrowserSystemTraceProducers: screen_size + main_thread_lag_ms', expect(out).toEqual([ { name: 'screen_size', value: { width: 100, height: 200, dpr: 2 }, hold: true }, ]); - expect(posted).toHaveLength(1); // the lag ping went through the INJECTED window's channel + 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 or MessageChannel starts no ping', () => { + 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), }); - const env = browserTraceEnvFrom(win, doc); - expect(env.MessageChannel).toBeUndefined(); + 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[] = []; - const lag = createBrowserSystemTraceProducers({ ...env, lifecycle }).find( - (p) => p.name === 'main-thread-lag', - ); 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('main_thread_lag_ms clock wiring', () => { - it('a performance.now that is not a function omits the trace quietly (no ping, no error)', () => { + 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 created = 0; - class Ch { - constructor() { - created += 1; - } - } + let timers = 0; const errors: unknown[] = []; const lag = createBrowserSystemTraceProducers( { lifecycle, document: doc, - MessageChannel: Ch as never, 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(created).toBe(0); + expect(timers).toBe(0); expect(errors).toEqual([]); expect(out).toEqual([]); }); }); - -describe('browserTraceEnvFrom: MessageChannel', () => { - it("hands over THIS window's constructor, omits a non-constructor, and reports a hostile getter", () => { - class Ch {} - expect(browserTraceEnvFrom({ MessageChannel: Ch }, undefined).MessageChannel).toBe(Ch); - expect('MessageChannel' in browserTraceEnvFrom({ MessageChannel: 5 }, undefined)).toBe(false); - expect('MessageChannel' in browserTraceEnvFrom({}, undefined)).toBe(false); - const hostile = {}; - Object.defineProperty(hostile, 'MessageChannel', { - get(): never { - throw new Error('MessageChannel blocked'); - }, - }); - const errors: unknown[] = []; - const env = browserTraceEnvFrom(hostile, undefined, (e) => errors.push(e)); - expect('MessageChannel' in env).toBe(false); - expect((errors[0] as Error).message).toBe('MessageChannel blocked'); - }); -}); diff --git a/packages/browser/src/trace-producers.ts b/packages/browser/src/trace-producers.ts index 7db12b14..d92e7fe0 100644 --- a/packages/browser/src/trace-producers.ts +++ b/packages/browser/src/trace-producers.ts @@ -13,7 +13,7 @@ import { ConnectionTracker, } from './trackers/connection-tracker'; import { type FpsEnv, FpsTracker } from './trackers/fps-tracker'; -import { type MainThreadLagEnv, MainThreadLagTracker } from './trackers/main-thread-lag-tracker'; +import { MainThreadLagTracker } from './trackers/main-thread-lag-tracker'; import { type MemoryReading, type MemoryState, MemoryTracker } from './trackers/memory-tracker'; import { type OrientationEnv, @@ -280,10 +280,11 @@ export class ScreenSizeProducer extends TraceProducerBase { } /** - * `main_thread_lag_ms`: the latest `MessageChannel` round-trip delta, once per sampling tick, ONLY while the page - * is visible (a hidden tab's throttled timers would paint a hang that did not happen). One ping per tick, never a - * loop; a ping still pending at a tick reports its age. Polled, so each value is emitted and never held or - * refreshed; nothing measured yet means nothing emitted. + * `main_thread_lag_ms`: TIMER DRIFT โ€” how late the 1 s sampling timer fired on the page's main thread (a long + * task or block delays it by its length), 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. + * Includes timer throttling the browser applies to a page that still says `visible` (occluded window). + * Polled, so each value is emitted and never held or refreshed. */ export class MainThreadLagProducer extends TraceProducerBase { readonly name = 'main-thread-lag'; @@ -324,8 +325,6 @@ export interface BrowserTraceEnv extends BatteryEnv { /** `window.requestAnimationFrame` / `cancelAnimationFrame` (bound to that window): drive `fps`. */ requestAnimationFrame?: FpsEnv['requestAnimationFrame']; cancelAnimationFrame?: FpsEnv['cancelAnimationFrame']; - /** `window.MessageChannel` (the injected window's constructor): drives `main_thread_lag_ms`. */ - MessageChannel?: MainThreadLagEnv['MessageChannel']; /** * `false` builds the battery producer ONLY: a caller-supplied `systemMetricsSampler` replaces the heap, * 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. @@ -343,7 +342,6 @@ interface WindowSurfaces { screen?: BrowserTraceEnv['screen']; requestAnimationFrame?: (callback: (timestamp: number) => void) => number; cancelAnimationFrame?: (handle: number) => void; - MessageChannel?: BrowserTraceEnv['MessageChannel']; } /** @@ -379,8 +377,6 @@ export function browserTraceEnvFrom( const getBattery = nav === undefined ? undefined : read(() => nav.getBattery); const raf = read(() => win.requestAnimationFrame); const caf = read(() => win.cancelAnimationFrame); - // A constructor needs no `this`, so it is handed over as read (it still belongs to THIS window). - const messageChannel = read(() => win.MessageChannel); return { ...(nav !== undefined ? { navigator: nav } : {}), ...(performance !== undefined ? { performance } : {}), @@ -389,7 +385,6 @@ export function browserTraceEnvFrom( ...(document !== undefined ? { document } : {}), ...(typeof raf === 'function' ? { requestAnimationFrame: (cb) => raf.call(win, cb) } : {}), ...(typeof caf === 'function' ? { cancelAnimationFrame: (h) => caf.call(win, h) } : {}), - ...(typeof messageChannel === 'function' ? { MessageChannel: messageChannel } : {}), ...(nav !== undefined && typeof getBattery === 'function' ? { getBattery: () => getBattery.call(nav) } : {}), @@ -506,7 +501,6 @@ export function createBrowserSystemTraceProducers( { lifecycle: env.lifecycle, ...(env.document !== undefined ? { document: env.document } : {}), - ...(env.MessageChannel !== undefined ? { MessageChannel: env.MessageChannel } : {}), // Only a real clock function is wired; anything else omits the trace quietly (no error). ...(typeof safePerformanceNow(env, onError) === 'function' ? { 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 index f3b65273..51e137d0 100644 --- a/packages/browser/src/trackers/main-thread-lag-tracker.test.ts +++ b/packages/browser/src/trackers/main-thread-lag-tracker.test.ts @@ -2,18 +2,18 @@ import type { Scheduler } from '@bugsee/core'; import { describe, expect, it, vi } from 'vitest'; import { MainThreadLagTracker } from './main-thread-lag-tracker'; -// A controllable page: a fake MessageChannel whose posted messages are delivered by hand (or automatically, -// synchronously, with `auto`), a manual clock, a visibility lifecycle and a manual interval. -function mkEnv( - over: { visible?: boolean; noChannel?: boolean; noNow?: boolean; auto?: number } = {}, -) { +// 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; @@ -24,56 +24,6 @@ function mkEnv( timers.live -= 1; }, }; - interface Chan { - port1: { onmessage: ((e: unknown) => void) | null; close: () => void }; - port2: { postMessage: (m: unknown) => void; close: () => void }; - queue: number; - posts: number; - closed: number; - deliver: () => void; - } - const channels: Chan[] = []; - const control = { postFails: 0, ctorFails: 0, auto: over.auto }; - class FakeChannel { - port1: Chan['port1']; - port2: Chan['port2']; - constructor() { - if (control.ctorFails-- > 0) throw new Error('ctor'); - const chan: Chan = { - queue: 0, - posts: 0, - closed: 0, - port1: { - onmessage: null, - close: () => { - chan.closed += 1; - }, - }, - port2: { - postMessage: () => { - if (control.postFails-- > 0) throw new Error('post'); - chan.posts += 1; - chan.queue += 1; - if (control.auto !== undefined) { - now += control.auto; // the round trip takes `auto` ms, delivered at once - chan.deliver(); - } - }, - close: () => { - chan.closed += 1; - }, - }, - deliver: () => { - const n = chan.queue; - chan.queue = 0; - for (let i = 0; i < n; i++) chan.port1.onmessage?.({}); - }, - }; - this.port1 = chan.port1; - this.port2 = chan.port2; - channels.push(chan); - } - } const env = { document: doc, lifecycle: { @@ -83,20 +33,19 @@ function mkEnv( return () => void visListeners.delete(fn as never); }, }, - ...(over.noChannel ? {} : { MessageChannel: FakeChannel as never }), ...(over.noNow ? {} : { now: () => now }), scheduler, }; return { env, - doc, timers, - channels, control, - posts: () => channels.reduce((n, c) => n + c.posts, 0), advance: (ms: number) => { now += ms; }, + setNow: (ms: number) => { + now = ms; + }, tick: () => timerCb?.(), setVisible: (visible: boolean) => { doc.visibilityState = visible ? 'visible' : 'hidden'; @@ -112,222 +61,141 @@ const collect = (t: MainThreadLagTracker) => { return { got, off }; }; -describe('MainThreadLagTracker', () => { +describe('MainThreadLagTracker (timer drift)', () => { it('attaches nothing until the first subscriber', () => { const e = mkEnv(); new MainThreadLagTracker(e.env); - expect(e.channels).toHaveLength(0); expect(e.timers.set).toBe(0); expect(e.listeners()).toBe(0); }); - it('while visible: posts ONE ping at start; its receipt stores the delta, which is emitted on the NEXT tick', () => { + 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)); - expect(e.posts()).toBe(1); - e.advance(37); - e.channels[0]?.deliver(); - expect(got).toEqual([]); // a receipt never posts and never emits by itself - expect(e.posts()).toBe(1); - e.advance(963); + e.advance(1000); e.tick(); - expect(got).toEqual([37]); - expect(e.posts()).toBe(2); // the tick re-armed with exactly one ping - }); - - it('a delta is emitted once (consumed); the tick after it with no new receipt reports the stall instead', () => { - const e = mkEnv(); - const { got } = collect(new MainThreadLagTracker(e.env)); - e.advance(8); - e.channels[0]?.deliver(); - e.tick(); // emits 8, posts at t=8 e.advance(1000); - e.tick(); // the ping posted at the last tick has not come back for 1000 ms - expect(got).toEqual([8, 1000]); - }); - - it('FLOOD GUARD: at most one post per tick however long it runs, with a channel that delivers instantly', () => { - const e = mkEnv({ auto: 3 }); - const { got } = collect(new MainThreadLagTracker(e.env)); - expect(e.posts()).toBe(1); // a delivered ping does not post again by itself - for (let i = 0; i < 50; i++) { - e.advance(997); - e.tick(); - } - expect(e.posts()).toBe(51); // the start ping + one per tick, never more - expect(got).toHaveLength(50); - expect(got.every((v) => v === 3)).toBe(true); - }); - - it('a long task between post and receipt shows in the emitted value (receipt delivered before the tick)', () => { - const e = mkEnv(); - const { got } = collect(new MainThreadLagTracker(e.env)); - e.advance(300); // the main thread was blocked for 300 ms with the ping queued - e.channels[0]?.deliver(); - e.advance(700); e.tick(); - expect(got).toEqual([300]); + expect(got).toEqual([0, 0]); }); - it('a long task shows even when the TICK runs first: a ping still in flight reports its age and posts nothing', () => { + it('a block spanning a tick shows as the lateness of that tick: N ms block => N - interval... of drift', () => { const e = mkEnv(); const { got } = collect(new MainThreadLagTracker(e.env)); - e.advance(1300); - e.tick(); // still in flight after 1.3 s - expect(got).toEqual([1300]); - expect(e.posts()).toBe(1); - e.advance(500); + 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([1300, 1800]); // the age keeps growing while blocked, and still one ping total - expect(e.posts()).toBe(1); - e.channels[0]?.deliver(); // the thread frees up + 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([1300, 1800, 1800]); // the completed measurement, then re-armed - expect(e.posts()).toBe(2); + expect(got).toEqual([0, 700, 0]); }); - it('a freshly started run with a ping in flight reports it only once the tick finds it still pending', () => { + it('the first tick is measured against the run start + interval', () => { const e = mkEnv(); + e.setNow(5000); const { got } = collect(new MainThreadLagTracker(e.env)); - expect(got).toEqual([]); // nothing measured and nothing emitted before the first tick + e.setNow(5000 + 1000 + 250); + e.tick(); + expect(got).toEqual([250]); }); - it('going hidden aborts the in-flight ping, CLEARS the delta, closes the channel and stops the timer', () => { + 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(3); - e.channels[0]?.deliver(); - e.setVisible(false); - expect(e.timers.live).toBe(0); - expect(e.channels[0]?.closed).toBe(2); - expect(e.channels[0]?.port1.onmessage).toBeNull(); - e.tick(); // even a stray tick has nothing to say - expect(got).toEqual([]); + e.advance(998); + e.tick(); + expect(got).toEqual([0]); }); - it('a hidden completion is dropped: a late receipt neither writes nor posts', () => { + 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(); - const { got } = collect(new MainThreadLagTracker(e.env)); - const chan = e.channels[0]; - const late = chan?.port1.onmessage; - e.setVisible(false); - e.advance(60_000); // a throttled hidden completion - late?.({}); - expect(e.posts()).toBe(1); - e.setVisible(true); - e.advance(1000); - e.tick(); - expect(got).toEqual([1000]); // aged from the NEW run's ping, never the 60 s hidden stretch + 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('hide -> show: the first visible tick sees only the NEW run (no hidden-throttled sample, no stale number)', () => { + it('uses the INJECTED clock: its distinctive value, and nothing else, decides the drift', () => { const e = mkEnv(); - const { got } = collect(new MainThreadLagTracker(e.env)); - const stale = e.channels[0]?.port1.onmessage; - e.advance(10); - e.channels[0]?.deliver(); // a sample exists... - e.setVisible(false); // ...and is cleared - e.advance(60_000); - e.setVisible(true); - stale?.({}); // an aborted run's receipt arriving late - e.advance(5); - e.channels[1]?.deliver(); - e.advance(995); + 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([5]); // measured entirely inside the visible run + expect(got).toEqual([77]); + expect(reads).toEqual([123_456, 123_456 + 1077]); }); - it("a stale receipt from an aborted run cannot complete the NEW run's ping", () => { + 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)); - const stale = e.channels[0]?.port1.onmessage; e.setVisible(false); - e.advance(60_000); - e.setVisible(true); - stale?.({}); + expect(e.timers.live).toBe(0); e.advance(1000); e.tick(); - expect(got).toEqual([1000]); // still in flight, aged from the new post (not a stale ~0 sample) - expect(e.posts()).toBe(2); + expect(got).toEqual([]); }); - it("hide -> show clears the previous run's sample: it is never emitted in the new run", () => { + 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(10); - e.channels[0]?.deliver(); // sample 10 stored - e.setVisible(false); - e.setVisible(true); e.advance(1000); - e.tick(); // the new ping is still pending: its age, not the old 10 - expect(got).toEqual([1000]); - }); - - it("a previous run's sample cannot resurface through a later DISCARDED receipt", () => { - const e = mkEnv(); - let t = 0; - const { got } = collect(new MainThreadLagTracker({ ...e.env, now: () => t })); - t = 10; - e.channels[0]?.deliver(); // sample 10 stored + e.tick(); e.setVisible(false); - t = 100; + e.advance(60_000); e.setVisible(true); - t = 50; // backwards: the new run's receipt is discarded - e.channels[1]?.deliver(); - e.tick(); - expect(got).toEqual([]); - }); - - it('a discarded (backwards-clock) receipt after an emitted sample does not re-emit the old sample', () => { - const e = mkEnv(); - let t = 0; - const { got } = collect(new MainThreadLagTracker({ ...e.env, now: () => t })); - t = 20; - e.channels[0]?.deliver(); - e.tick(); // emits 20, posts at t=20 - t = 5; // backwards - e.channels[0]?.deliver(); // discarded - e.tick(); - expect(got).toEqual([20]); - }); - - it('an unreadable age is not emitted: a backwards or infinite clock while a ping is pending', () => { - const e = mkEnv(); - let t = 100; - const { got } = collect(new MainThreadLagTracker({ ...e.env, now: () => t })); - t = 50; - e.tick(); - t = Number.POSITIVE_INFINITY; + e.advance(1000); e.tick(); - expect(got).toEqual([]); + expect(got).toEqual([0, 0]); }); - it('hidden at start: no channel, no timer, nothing emitted', () => { + 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.channels).toHaveLength(0); expect(e.timers.live).toBe(0); e.tick(); expect(got).toEqual([]); e.setVisible(true); - expect(e.channels).toHaveLength(1); expect(e.timers.live).toBe(1); }); - it('duplicate visible/hidden events do not stack channels or timers', () => { + 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.channels).toHaveLength(1); expect(e.timers.live).toBe(1); e.setVisible(false); e.setVisible(false); expect(e.timers.live).toBe(0); - expect(e.channels[0]?.closed).toBe(2); + expect(e.timers.cleared).toBe(1); }); - it('the last unsubscribe stops everything; a re-subscribe restarts with a fresh channel', () => { + 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); @@ -335,14 +203,16 @@ describe('MainThreadLagTracker', () => { off(); expect(e.listeners()).toBe(0); expect(e.timers.live).toBe(0); - expect(e.channels[0]?.closed).toBe(2); - collect(t); - expect(e.channels).toHaveLength(2); + e.advance(30_000); + const { got } = collect(t); expect(e.timers.live).toBe(1); + e.advance(1000); + e.tick(); + expect(got).toEqual([0]); }); - it('a runtime without MessageChannel is omitted: no timer, no subscription, no error', () => { - const e = mkEnv({ noChannel: true }); + 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); @@ -352,19 +222,12 @@ describe('MainThreadLagTracker', () => { expect(errors).toEqual([]); }); - it('without a clock it measures nothing (no host fallback, no wall-clock guess)', () => { - const e = mkEnv({ noNow: true }); - collect(new MainThreadLagTracker(e.env)); - expect(e.channels).toHaveLength(0); - expect(e.timers.set).toBe(0); - }); - 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.channels).toHaveLength(0); + expect(e.timers.set).toBe(0); expect(errors).toEqual([]); }); @@ -378,37 +241,11 @@ describe('MainThreadLagTracker', () => { }, }); collect(new MainThreadLagTracker({ ...e.env, document: doc }, (x) => errors.push(x))); - expect(e.channels).toHaveLength(0); + expect(e.timers.set).toBe(0); expect((errors[0] as Error).message).toBe('vis'); }); - it('a throwing MessageChannel constructor is reported and rolls the start 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.ctorFails = 1; - e.setVisible(true); - expect((errors[0] as Error).message).toBe('ctor'); - expect(e.timers.live).toBe(0); - e.setVisible(true); - expect(e.channels).toHaveLength(1); - expect(e.timers.live).toBe(1); - }); - - it('a throwing postMessage at start is reported, rolls back, and closes the half-built channel', () => { - const e = mkEnv({ visible: false }); - const errors: unknown[] = []; - collect(new MainThreadLagTracker(e.env, (x) => errors.push(x))); - e.control.postFails = 1; - e.setVisible(true); - expect((errors[0] as Error).message).toBe('post'); - expect(e.timers.live).toBe(0); - expect(e.channels[0]?.closed).toBe(2); - e.setVisible(true); - expect(e.timers.live).toBe(1); - }); - - it('a throwing clock at start is reported and rolls back like any setup failure', () => { + 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; @@ -432,27 +269,19 @@ describe('MainThreadLagTracker', () => { expect(e.timers.live).toBe(1); }); - it('a postMessage that throws at a tick is reported, the stale delta is CLEARED, and the NEXT tick retries', () => { - const e = mkEnv(); + it('a throwing scheduler is reported and rolls back; the next visible event retries', () => { + const e = mkEnv({ visible: false }); const errors: unknown[] = []; - const { got } = collect(new MainThreadLagTracker(e.env, (x) => errors.push(x))); - e.advance(2); - e.channels[0]?.deliver(); - e.control.postFails = 1; - e.tick(); // emits 2, then fails to re-arm - expect(got).toEqual([2]); - expect((errors[0] as Error).message).toBe('post'); - e.advance(1000); - e.tick(); // nothing in flight, nothing stored: it retries and does not invent a number - expect(got).toEqual([2]); - expect(e.posts()).toBe(2); // start + the retry - e.advance(4); - e.channels[0]?.deliver(); - e.tick(); - expect(got).toEqual([2, 4]); + 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, drops that tick, and the next tick recovers', () => { + 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; @@ -470,81 +299,31 @@ describe('MainThreadLagTracker', () => { ), ); boom = true; - expect(() => e.tick()).not.toThrow(); // in flight: the age cannot be read + t = 1000; + expect(() => e.tick()).not.toThrow(); expect((errors[0] as Error).message).toBe('clock'); expect(got).toEqual([]); boom = false; - t = 40; + t = 2000; e.tick(); - expect(got).toEqual([40]); - }); - - it('a clock that throws at receipt is reported, drops the sample and frees the next tick to retry', () => { - const e = mkEnv(); - const errors: unknown[] = []; - let calls = 0; - const { got } = collect( - new MainThreadLagTracker( - { - ...e.env, - now: () => { - if (++calls > 1) throw new Error('clock'); - return 0; - }, - }, - (x) => errors.push(x), - ), - ); - expect(() => e.channels[0]?.deliver()).not.toThrow(); - expect((errors[0] as Error).message).toBe('clock'); - expect(got).toEqual([]); - }); - - it('a negative or non-finite delta is discarded, never reported as a lag', () => { - const e = mkEnv(); - let t = 100; - const { got } = collect(new MainThreadLagTracker({ ...e.env, now: () => t })); - t = 90; // a backwards clock - e.channels[0]?.deliver(); + expect(got).toEqual([0]); // not ~1000 + t = 3000 + 90; e.tick(); - expect(got).toEqual([]); + expect(got).toEqual([0, 90]); }); - it('an infinite delta is discarded too', () => { + 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.channels[0]?.deliver(); e.tick(); expect(got).toEqual([]); - }); - - it('a throwing port close is swallowed on stop', () => { - const e = mkEnv(); - collect(new MainThreadLagTracker(e.env)); - const chan = e.channels[0]; - if (chan !== undefined) - chan.port1.close = () => { - throw new Error('close'); - }; - expect(() => e.setVisible(false)).not.toThrow(); - expect(chan?.closed).toBe(1); // port2 was still closed - }); - - it('samples every second by default and honors intervalMs', () => { - 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]); + 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', () => { @@ -556,10 +335,9 @@ describe('MainThreadLagTracker', () => { const t = new MainThreadLagTracker({ ...rest, now: () => now }); const got: number[] = []; const off = t.on('lag', (v) => got.push(v)); - now = 9; - e.channels[0]?.deliver(); + now = 1000; vi.advanceTimersByTime(1000); - expect(got).toEqual([9]); + expect(got).toEqual([0]); off(); expect(vi.getTimerCount()).toBe(0); } finally { @@ -587,11 +365,18 @@ describe('MainThreadLagTracker', () => { it('a throwing reporter never escapes', () => { const e = mkEnv({ visible: false }); - const t = new MainThreadLagTracker(e.env, () => { - throw new Error('reporter'); - }); + const t = new MainThreadLagTracker( + { + ...e.env, + now: () => { + throw new Error('clock'); + }, + }, + () => { + throw new Error('reporter'); + }, + ); t.on('lag', () => {}); - e.control.ctorFails = 1; 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 index f3765def..f18473aa 100644 --- a/packages/browser/src/trackers/main-thread-lag-tracker.ts +++ b/packages/browser/src/trackers/main-thread-lag-tracker.ts @@ -1,35 +1,31 @@ import { InterceptorBase, type Scheduler } from '@bugsee/core'; import type { PageLifecycleTracker } from './page-lifecycle-tracker'; -// Browser main-thread responsiveness TRACKER (`main_thread_lag_ms`): the delay between posting a message on a -// `MessageChannel` and receiving it back on the same thread, i.e. how long a fresh task waited behind whatever -// the main thread was doing. `MessageChannel`, not `setTimeout(0)`: timers are clamped to 4 ms. +// Browser main-thread responsiveness TRACKER (`main_thread_lag_ms`): TIMER DRIFT, the classic event-loop-lag +// technique (the same one Node's monitor uses). 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: a long task, a layout storm +// or a synchronous block delays the next tick by exactly its length. The first tick compares against the run's +// start time + interval. A measured ~0 is a TRUE measurement and is emitted every tick. // -// ONE ping per sampling tick, never a loop. A receipt must NOT post again: re-arming on receipt is a continuous -// task loop (a whole core, starved idle callbacks) and it also overwrites a long-task delta with a ~0 one a few -// microseconds later. Instead each tick, while visible: -// - no ping in flight: emit the delta the last receipt stored (if any, consumed), then post ONE new ping; -// - ping STILL in flight (the thread has been blocked since the last tick): post nothing and emit its age, -// `now - startedAt`, a lower bound on the lag, so a freeze is visible while it is happening. The completed -// delta is emitted on the following tick (the same stall is thus reported twice: its floor, then its size). -// Measured ONLY while the page is visible (the same rule as `fps`). A hidden tab clamps timers and message -// delivery to ~1 s and then ~1 min, so a hidden round-trip measures the browser's throttling and would paint a -// hang that never happened. On hidden the run is torn down โ€” the in-flight ping is aborted, the delta CLEARED โ€” -// and a fresh run starts on visible. A failed post or clock is reported, clears the delta, and the next tick -// retries. No MessageChannel, no clock, no lifecycle, or hidden: emit NOTHING โ€” omit, never zero. - -export interface MessageChannelLike { - port1: { onmessage: ((event: unknown) => void) | null; close(): void }; - port2: { postMessage(message: unknown): void; close(): void }; -} +// 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". Timer drift sees every block that spans a tick. +// +// Honest limit: it measures how late the sampling timer fires. That includes real jank, and ALSO timer +// throttling the browser applies while the page still says `visible` (an occluded or minimised window, or a +// background tab that never fired `visibilitychange`); such a stretch reads as lag even though nothing in the +// page was slow. +// +// 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 }; - /** The INJECTED window's `MessageChannel` constructor; absent omits the trace. */ - MessageChannel?: new () => MessageChannelLike; /** Monotonic ms (the injected `performance.now`); absent omits the trace โ€” no wall-clock guess. */ now?: () => number; scheduler?: Scheduler; @@ -46,17 +42,15 @@ export class MainThreadLagTracker extends InterceptorBase<{ lag: number }> { readonly #env: MainThreadLagEnv; readonly #report: (error: unknown) => void; readonly #scheduler: Scheduler; + readonly #interval: number; #subscription: (() => void) | undefined; #timer: unknown = null; - #channel: MessageChannelLike | undefined; #running = false; - #lastDelta: number | undefined; - #inFlight = false; - #startedAt = 0; - #run = 0; + /** 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 message/timer dispatch. + // A throwing reporter must not escape into the host's timer dispatch. const report = (error: unknown): void => { try { onError?.(error); @@ -68,19 +62,14 @@ export class MainThreadLagTracker extends InterceptorBase<{ lag: number }> { 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 { - // Nothing to ping with, nothing to time it with, or no visibility events to gate on (a hidden tab must - // never keep a ping loop): omit. - if ( - typeof this.#env.MessageChannel !== 'function' || - typeof this.#env.now !== 'function' || - this.#env.lifecycle === undefined - ) - return; + // 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(), @@ -110,79 +99,38 @@ export class MainThreadLagTracker extends InterceptorBase<{ lag: number }> { if (this.#running) return; this.#running = true; try { - const Channel = this.#env.MessageChannel as new () => MessageChannelLike; - const channel = new Channel(); - this.#channel = channel; - const run = this.#run; - channel.port1.onmessage = () => this.#onReceipt(run); - this.#ping(channel); - this.#timer = this.#scheduler.setInterval(() => this.#tick(), this.#env.intervalMs ?? 1000); + // 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 (or its channel) behind + this.#stopRun(); // never leave a half-started run behind } } #stopRun(): void { this.#running = false; - this.#run += 1; // a receipt still in flight belongs to a dead run and must never write - this.#lastDelta = undefined; // a hidden stretch must not leave a stale number to be re-emitted if (this.#timer !== null) this.#scheduler.clearInterval(this.#timer); this.#timer = null; - const channel = this.#channel; - this.#channel = undefined; - if (channel === undefined) return; - channel.port1.onmessage = null; - for (const port of [channel.port1, channel.port2]) { - try { - port.close(); - } catch { - /* best-effort */ - } - } - } - - // Posts ONE ping. `#inFlight` is set before the post so a synchronous delivery is still seen as a receipt; - // a failed post un-sets it and throws (`#startRun` rolls back on it, `#tick` reports it). - #ping(channel: MessageChannelLike): void { - this.#startedAt = (this.#env.now as () => number)(); - this.#inFlight = true; - try { - channel.port2.postMessage(undefined); - } catch (error) { - this.#inFlight = false; - throw error; - } - } - - #onReceipt(run: number): void { - if (run !== this.#run) return; // `#stopRun` bumps the generation: a dead run's receipt is dropped - this.#inFlight = false; - try { - const delta = (this.#env.now as () => number)() - this.#startedAt; - if (Number.isFinite(delta) && delta >= 0) this.#lastDelta = delta; - } catch (error) { - this.#lastDelta = undefined; - this.#report(error); - } } #tick(): void { - const channel = this.#channel; - if (channel === undefined) return; + if (!this.#running) return; + let now: number; try { - if (this.#inFlight) { - // Blocked since the last tick: its age so far is the (lower-bound) lag. No second ping. - const age = (this.#env.now as () => number)() - this.#startedAt; - if (Number.isFinite(age) && age >= 0) this.emit('lag', age); - return; - } - const delta = this.#lastDelta; - this.#lastDelta = undefined; - if (delta !== undefined) this.emit('lag', delta); - this.#ping(channel); + now = (this.#env.now as () => number)(); } catch (error) { - this.#report(error); // nothing stale to clear: the delta was consumed above, or a ping is in flight + 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/webview/src/launch.test.ts b/packages/webview/src/launch.test.ts index 818f21ca..4eb0171d 100644 --- a/packages/webview/src/launch.test.ts +++ b/packages/webview/src/launch.test.ts @@ -1081,7 +1081,7 @@ describe('launch (webview)', () => { .filter((d) => d.name === name) .map((d) => d.value); - it('streams screen_size {width,height,dpr} and a lag delta from the INJECTED window; none from a hidden page', async () => { + 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 { @@ -1092,21 +1092,7 @@ describe('launch (webview)', () => { value: { now: () => clock }, configurable: true, }); - let onmessage: (() => void) | null = null; - let created = 0; - class Ch { - port1 = { - set onmessage(f: (() => void) | null) { - onmessage = f; - }, - close: () => {}, - }; - port2 = { postMessage: () => {}, close: () => {} }; - constructor() { - created += 1; - } - } - Object.assign(w.win, { devicePixelRatio: 3, MessageChannel: Ch }); + Object.assign(w.win, { devicePixelRatio: 3 }); const dom = fakeDomDocument(); Object.assign(dom.document, { visibilityState: 'visible' }); const ticks: Array<() => void> = []; @@ -1127,13 +1113,21 @@ describe('launch (webview)', () => { ); await new Promise((r) => setTimeout(r, 0)); expect(rowsOf(fake, 'screen_size')).toEqual([{ width: 360, height: 640, dpr: 3 }]); - expect(created).toBe(1); - clock = 25; - (onmessage as (() => void) | null)?.(); + 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 creates a channel + // 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( @@ -1144,28 +1138,27 @@ describe('launch (webview)', () => { document: hidden.document as unknown as Document, }), ); - expect(created).toBe(1); + expect(hiddenReads).toBe(0); } finally { vi.unstubAllGlobals(); } }); - it('a hostile MessageChannel / devicePixelRatio getter never fails launch and is reported', () => { + it('a hostile devicePixelRatio getter never fails launch and is reported', () => { stubSensors(); + vi.stubGlobal('screen', { width: 360, height: 640 }); try { const w = fakeWin(); - for (const key of ['MessageChannel', 'devicePixelRatio']) { - Object.defineProperty(w.win, key, { - get(): never { - throw new Error(`${key} blocked`); - }, - configurable: true, - }); - } + 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( - 'MessageChannel blocked', + 'devicePixelRatio blocked', ); } finally { vi.unstubAllGlobals(); From e2589b91a98305143065503407d828a38ed67830 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 19 Oct 2026 14:42:09 +0500 Subject: [PATCH 5/5] docs+test(browser): state the real drift semantics; pin performance.now binding; read the clock once (ST4c review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code) --- .../browser-screen-size-main-thread-lag.md | 2 +- docs/PROGRESS.md | 2 +- .../src/trace-producers.screen-lag.test.ts | 65 +++++++++++++++++++ packages/browser/src/trace-producers.ts | 15 +++-- .../trackers/main-thread-lag-tracker.test.ts | 11 +++- .../src/trackers/main-thread-lag-tracker.ts | 27 +++++--- 6 files changed, 103 insertions(+), 19 deletions(-) diff --git a/.changeset/browser-screen-size-main-thread-lag.md b/.changeset/browser-screen-size-main-thread-lag.md index fab30ed0..9be34a2f 100644 --- a/.changeset/browser-screen-size-main-thread-lag.md +++ b/.changeset/browser-screen-size-main-thread-lag.md @@ -7,6 +7,6 @@ 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, the classic event-loop-lag measurement: how late the 1 s sampling timer fired on the page's main thread (a long task or synchronous block delays it by its length), emitted every tick while the page is visible; a measured 0 is a real value. 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. Honest limit: it also reads as lag when the browser throttles the timer of a page that still says `visible` (an occluded or minimised window). +- `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 e2b8a773..fb6990a3 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -403,7 +403,7 @@ solid), in slices: 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`). 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, the classic event-loop-lag technique (as Node's monitor): 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. 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:** it measures how late the sampling timer fires โ€” real jank/long tasks, but ALSO timer throttling the browser applies to a page that still says `visible` (occluded/minimised window, background tab without a `visibilitychange`). **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). +- **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). - **ST0โ€ฒ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container (per-producer start/stop isolation, last-value refresh so a rolling window never loses a rarely-changing diff --git a/packages/browser/src/trace-producers.screen-lag.test.ts b/packages/browser/src/trace-producers.screen-lag.test.ts index 78d7f2a7..9f127490 100644 --- a/packages/browser/src/trace-producers.screen-lag.test.ts +++ b/packages/browser/src/trace-producers.screen-lag.test.ts @@ -217,6 +217,71 @@ describe('createBrowserSystemTraceProducers: screen_size + main_thread_lag_ms', }); }); +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(); diff --git a/packages/browser/src/trace-producers.ts b/packages/browser/src/trace-producers.ts index d92e7fe0..f5127ddd 100644 --- a/packages/browser/src/trace-producers.ts +++ b/packages/browser/src/trace-producers.ts @@ -280,10 +280,11 @@ export class ScreenSizeProducer extends TraceProducerBase { } /** - * `main_thread_lag_ms`: TIMER DRIFT โ€” how late the 1 s sampling timer fired on the page's main thread (a long - * task or block delays it by its length), 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. - * Includes timer throttling the browser applies to a page that still says `visible` (occluded window). + * `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 { @@ -452,6 +453,8 @@ export function createBrowserSystemTraceProducers( new BatteryTracker(env.getBattery ? { getBattery: env.getBattery } : {}, 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( @@ -502,7 +505,7 @@ export function createBrowserSystemTraceProducers( 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 safePerformanceNow(env, onError) === 'function' + ...(typeof clock === 'function' ? { now: () => (env.performance as { now(): number }).now() } : {}), ...(env.scheduler !== undefined ? { scheduler: env.scheduler } : {}), @@ -521,7 +524,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 index 51e137d0..d1b0aa94 100644 --- a/packages/browser/src/trackers/main-thread-lag-tracker.test.ts +++ b/packages/browser/src/trackers/main-thread-lag-tracker.test.ts @@ -79,7 +79,7 @@ describe('MainThreadLagTracker (timer drift)', () => { expect(got).toEqual([0, 0]); }); - it('a block spanning a tick shows as the lateness of that tick: N ms block => N - interval... of drift', () => { + 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); @@ -92,6 +92,15 @@ describe('MainThreadLagTracker (timer drift)', () => { 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); diff --git a/packages/browser/src/trackers/main-thread-lag-tracker.ts b/packages/browser/src/trackers/main-thread-lag-tracker.ts index f18473aa..3dfd4c8e 100644 --- a/packages/browser/src/trackers/main-thread-lag-tracker.ts +++ b/packages/browser/src/trackers/main-thread-lag-tracker.ts @@ -1,20 +1,27 @@ 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 classic event-loop-lag -// technique (the same one Node's monitor uses). 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: a long task, a layout storm -// or a synchronous block delays the next tick by exactly its length. The first tick compares against the run's -// start time + interval. A measured ~0 is a TRUE measurement and is emitted every tick. +// 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". Timer drift sees every block that spans a tick. +// "still in flight". // -// Honest limit: it measures how late the sampling timer fires. That includes real jank, and ALSO timer -// throttling the browser applies while the page still says `visible` (an occluded or minimised window, or a -// background tab that never fired `visibilitychange`); such a stretch reads as lag even though nothing in the -// page was slow. +// 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