Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/browser-screen-size-main-thread-lag.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@bugsee/browser': minor
'@bugsee/webview': minor
---

Browser and WebView system traces gain `screen_size` and `main_thread_lag_ms`:

- `screen_size` reports `{ width, height, dpr }` (CSS pixels of `screen.width` / `screen.height` and `devicePixelRatio`) as a held step trace: an initial value at start, then on every `resize` and `orientationchange`, de-duplicated. It is omitted when the screen or the pixel ratio cannot be read as finite positive numbers. It is deliberately not named `displays`.
- `screen_size` can go stale when the window moves to a monitor with the same pixel ratio but a different size (no `resize` fires), and iOS Safari's `screen.width` / `screen.height` do not swap on rotation.
- `main_thread_lag_ms` is timer drift: how late the 1 s sampling timer fired on the page's main thread, emitted every tick while the page is visible; a measured 0 is a real value. A freeze of 1 s or more reads between its length minus one second and its length; a block shorter than one second that crosses no due tick reads 0, so short jank can go unseen (a finer timer or `PerformanceObserver('longtask')` would be the follow-up). It is measured only while the page is visible: hiding stops the timer, and every time the page is shown a fresh baseline is taken so a hidden stretch never counts as lag. A window without a `performance.now` function reports nothing. Timer throttling of a page that still says visible (an occluded window) may also read as lag; this is unverified.

Both come from the window passed to `launch()`, are built only with the other lifecycle-based traces, and are replaced together with the sensor traces by a `systemMetricsSampler`.
3 changes: 2 additions & 1 deletion docs/PROGRESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,8 @@ solid), in slices:
`navigator`/`performance`/`screen`/`window` (`defaultBrowserTraceEnv()`); the old sampler copied `navigator` with a
spread, which drops the prototype accessors (`onLine`, `connection`, `deviceMemory`) on a real browser. Launch passes
its injected `window` and `scheduler`. The shared `PageLifecycleTracker` is done: the events source and the connection/orientation trackers subscribe to it.
- **ST4a (DONE, `feat/browser-app-state-fps`):** `app_state` (`AppStateProducer`: `foreground`/`background`, held step trace; the viewer's table is `started`/`foreground`/`background`) and `fps` (`FpsTracker` + `FpsProducer`: a `requestAnimationFrame` counter that runs ONLY while the page is visible — loop and timer torn down on hidden, a fresh window on visible, a zero-length window or no rAF emits nothing; nothing is reported before the first frame of a run, since rAF can be paused while the page says visible; afterwards the first frameless window is reported as 0 and a continuing stall goes quiet; no lifecycle = omitted). The traces env is now built from the INJECTED window + document (`browserTraceEnvFrom`; no fallback to `globalThis`, so a window without `performance.memory` omits the heap). **ST4b (DONE, `feat/browser-dark-freeze-events`):** `events.system` gains `dark_mode_changed` (`{dark}`; `matchMedia` taken from the INJECTED window, bound to it, per-attach guarded) and Page Lifecycle `freeze`/`resume` (document listeners via the shared `PageLifecycleTracker`). Still open in ST4: `main_thread_lag_ms` (needs the hidden-tab-vs-sync-block probe first) and optional `screen_size`.
- **ST4a (DONE, `feat/browser-app-state-fps`):** `app_state` (`AppStateProducer`: `foreground`/`background`, held step trace; the viewer's table is `started`/`foreground`/`background`) and `fps` (`FpsTracker` + `FpsProducer`: a `requestAnimationFrame` counter that runs ONLY while the page is visible — loop and timer torn down on hidden, a fresh window on visible, a zero-length window or no rAF emits nothing; nothing is reported before the first frame of a run, since rAF can be paused while the page says visible; afterwards the first frameless window is reported as 0 and a continuing stall goes quiet; no lifecycle = omitted). The traces env is now built from the INJECTED window + document (`browserTraceEnvFrom`; no fallback to `globalThis`, so a window without `performance.memory` omits the heap). **ST4b (DONE, `feat/browser-dark-freeze-events`):** `events.system` gains `dark_mode_changed` (`{dark}`; `matchMedia` taken from the INJECTED window, bound to it, per-attach guarded) and Page Lifecycle `freeze`/`resume` (document listeners via the shared `PageLifecycleTracker`). ST4 has nothing left open (ST4c below).
- **ST4c (DONE, `feat/browser-screen-size-main-thread-lag`):** `screen_size` (`ScreenSizeTracker` + `ScreenSizeProducer`: value shape `{width, height, dpr}` in CSS px — NOT `displays`; held, de-duplicated step trace; initial value at start; re-read on `resize` (listened for on the injected window by the tracker — no new shared-lifecycle event, since nothing else consumes it and it would change every lifecycle subscriber's listener count) and `orientationchange` (via the shared lifecycle); omitted entirely when `screen` or `devicePixelRatio` is not a finite positive number; known staleness: moving the window to a monitor with the same DPR but a different size fires no `resize`, and iOS Safari's `screen.width/height` do not swap on rotation — a `(resolution: Xdppx)` matchMedia/`screen` change listener is a follow-up) and `main_thread_lag_ms` (`MainThreadLagTracker` + `MainThreadLagProducer`: TIMER DRIFT: on each 1 s scheduler tick on the page's main thread, `lag = max(0, now - (previousTickTime + intervalMs))` with the injected `performance.now`; the first tick compares against the run's start + interval; emitted EVERY tick as a polled (`hold:false`) trace — a measured ~0 is a true value. **What a reading means (measured in Chromium):** a tick fires late by (block end − the first due time the block covered), so a block B ≥ 1 s reads between B−1000 and B (1800 ms read 907..1797; 2500 ms read 1807), while a block shorter than 1 s that crosses no due tick reads exactly 0 (probability ≈ 1 − B/1000: ~30% for 700 ms, ~90% for 100 ms); one block is reported once (the next tick clamps to 0). It is NOT Node's ~10 ms event-loop monitor — sampling every 1000 ms is why short blocks can go unseen. Measured ONLY while visible: hidden tears the timer down and every visible start takes a FRESH baseline, so a hidden stretch never counts as lag. A throwing clock/scheduler at start rolls back; a throwing or non-finite clock at a tick is reported/skipped without reading the skipped interval as lag. No clock (`performance.now` must be a function), lifecycle, or a hidden page = omitted, no timer. **Honest limit:** long freezes are reported reliably, short jank only by luck; follow-ups if short jank matters: a finer internal timer reporting the MAX drift per 1 s window, or `PerformanceObserver('longtask')` where supported. Timer throttling the browser applies to a page that still says `visible` (occluded/minimised window, background tab without a `visibilitychange`) may also read as lag — UNVERIFIED, it could not be reproduced headless. **History:** a `MessageChannel` ping (re-arm on receipt, then once per tick) was built and rejected after measuring real Chromium: re-arming on receipt was a ~2.2M/s task loop, and a ping per tick reads ~0.1 ms for a block that starts after the ping returned — a plausible-healthy lie; it was deleted entirely, no `MessageChannel` in the traces env). Both are built under the same `env.lifecycle` gate as `app_state`/`fps`, so a `systemMetricsSampler` (`sensors:false`) replaces them too. Open: the viewer has no definition for either name yet (generic value block, design §13.3).
- **TR4 (DONE, `feat/power-tracker`):** `BatteryTracker` became the domain **`PowerTracker`** (`packages/trackers/src/browser/power-tracker.ts`), a singleton per window via `createTrackerRegistry` (`powerTrackerFor(env, onError)`, keyed on `env.window`, else `env.navigator`, else the env object; host key reads are guarded and reported). It takes ONLY `getBattery` from the env; every call (a relaunch included) goes through the registry `rebind`, handing the shared tracker the latest launch's `onError` (a defined one replaces, undefined keeps; the reporter is a mutable indirection) and `getBattery` (a defined one replaces; a tracker that had none kicks the request at once if running). It exposes a SINGLE `state` stage (rather than one per Battery Status event): `{level?, charging, chargingTimeS?, dischargingTimeS?}`, published on `levelchange`/`chargingchange`/`chargingtimechange`/`dischargingtimechange`. Omitted, never fabricated: a `level` that is not a number in [0,1] (so no `battery` trace, never NaN); non-finite or negative times; a zero `chargingTime` when full and charging (a battery-less desktop reports level 1, charging, 0); a zero `dischargingTime`. A throwing time getter costs only that field. **Retention rule (tested):** the resolved BatteryManager and the last snapshot survive the last unsubscribe (no second `getBattery()`); the DOM listeners do not, and re-attach with a fresh snapshot on the next subscriber. A `getBattery()` in flight at stop is ignored and re-requested next activation. `BatteryProducer` keeps `battery`/`charging` unchanged and adds `battery_charging_time_s`/`battery_discharging_time_s` (integer seconds). **Held-value disappearance rule:** the provider's held values cannot be retracted (it re-records them every `refreshMs`), so the two time traces use plain non-held `emit` with a producer-side change-only guard; a vanished time records nothing and is forgotten (a stale estimate is never refreshed). Consequence: an unchanged time AGES OUT of the rolling capture window; owner decision pending on a retract/release or end-marker mechanism.
- **ST0′ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers.
`@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container
Expand Down
148 changes: 148 additions & 0 deletions packages/browser/src/launch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1564,6 +1564,154 @@ describe('launch', () => {
expect(armed).toBe(0);
});

it('records screen_size {width,height,dpr} from the INJECTED window and follows its resize', async () => {
stubSensors();
vi.stubGlobal('screen', { width: 390, height: 844 });
const w = fakeWindow();
Object.assign(w.win, { devicePixelRatio: 2 });
const store = memStore();
await launchTracked('tok', noSampler({ window: w.win, captureStore: store }));
Object.assign(w.win, { devicePixelRatio: 3 });
w.emit('resize', {});
expect(await rowsOf(store, 'screen_size')).toEqual([
{ width: 390, height: 844, dpr: 2 },
{ width: 390, height: 844, dpr: 3 },
]);
});

it('screen_size is omitted (not 0) when the window has no readable screen or pixel ratio', async () => {
stubSensors(); // the stubbed screen has no width/height
const w = fakeWindow();
Object.assign(w.win, { devicePixelRatio: 2 });
const store = memStore();
await launchTracked('tok', noSampler({ window: w.win, captureStore: store }));
expect(await rowsOf(store, 'screen_size')).toEqual([]);
});

it('records main_thread_lag_ms as timer drift on the INJECTED window clock, visible only, with a fresh baseline after a hide', async () => {
stubSensors();
const d = mkDoc(true);
const w = fakeWindow();
let clock = 5_000;
Object.defineProperty(w.win, 'performance', {
value: { now: () => clock },
configurable: true,
});
const live = new Map<number, () => void>();
let nextHandle = 1;
const store = memStore();
await launchTracked(
'tok',
noSampler({
window: w.win,
document: d.doc as unknown as Document,
captureStore: store,
scheduler: {
setInterval: (cb, ms) => {
if (ms !== 1000) return 'other';
const h = nextHandle++;
live.set(h, cb);
return h;
},
clearInterval: (h) => void live.delete(h as number),
},
}),
);
const runTicks = (): void => {
for (const cb of [...live.values()]) cb();
};
clock += 1000;
runTicks(); // on time
clock += 1000 + 300; // a 300 ms block spans the next tick
runTicks();
const before = live.size;
d.setVisible(false);
const hiddenTimers = live.size;
clock += 60_000;
d.setVisible(true); // a fresh baseline: the hidden minute is not lag
clock += 1000;
runTicks();
// fps shares the 1 s cadence but emits its own name; only the lag rows are read here
expect(await rowsOf(store, 'main_thread_lag_ms')).toEqual([0, 300, 0]);
expect(hiddenTimers).toBeLessThan(before); // hiding tore the sampling timer(s) down
});

it('a hidden injected document never reads the clock for lag (no timer is started)', async () => {
stubSensors();
const d = mkDoc(false);
const w = fakeWindow();
let reads = 0;
Object.defineProperty(w.win, 'performance', {
value: {
now: () => {
reads += 1;
return 0;
},
},
configurable: true,
});
await launchTracked(
'tok',
noSampler({
window: w.win,
document: d.doc as unknown as Document,
captureStore: memStore(),
}),
);
expect(reads).toBe(0);
});

it('a hostile devicePixelRatio getter never fails launch and is reported', async () => {
stubSensors();
vi.stubGlobal('screen', { width: 390, height: 844 });
const w = fakeWindow();
Object.defineProperty(w.win, 'devicePixelRatio', {
get(): never {
throw new Error('devicePixelRatio blocked');
},
configurable: true,
});
const onError = vi.fn();
const store = memStore();
const client = await launchTracked(
'tok',
noSampler({ window: w.win, captureStore: store, onError }),
);
const messages = onError.mock.calls.map((c) => (c[0] as Error).message);
expect(messages).toContain('devicePixelRatio blocked');
expect(await rowsOf(store, 'screen_size')).toEqual([]);
await client.stop();
});

it('a systemMetricsSampler override builds neither screen_size nor the lag timer', async () => {
stubSensors();
vi.stubGlobal('screen', { width: 390, height: 844 });
const d = mkDoc(true);
const w = fakeWindow();
let reads = 0;
Object.assign(w.win, { devicePixelRatio: 2 });
Object.defineProperty(w.win, 'performance', {
value: {
now: () => {
reads += 1;
return 0;
},
},
configurable: true,
});
const store = memStore();
await launchTracked(
'tok',
baseOptions({
window: w.win,
document: d.doc as unknown as Document,
captureStore: store,
}),
);
expect(await rowsOf(store, 'screen_size')).toEqual([]);
expect(reads).toBe(0); // no lag timer was even built
});

it('a systemMetricsSampler override omits app_state and fps with the other sensor traces', async () => {
stubSensors();
const d = mkDoc(true);
Expand Down
Loading