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
11 changes: 11 additions & 0 deletions .changeset/application-tracker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@bugsee/browser': minor
'@bugsee/webview': minor
'@bugsee/trackers': minor
---

`PageLifecycleTracker` becomes the domain `ApplicationTracker` (`applicationTrackerFor`, `ApplicationEnv`, `ApplicationEvents`, `ApplicationState` exported from `@bugsee/trackers/browser` and re-exported by `@bugsee/browser`). It is a singleton per document (else window), gains an aggregated, de-duplicated `state` stage (`foreground`/`background`) and `current()`, and retains the last known state while no one is subscribed (DOM listeners still attach on the first subscriber and detach on the last). `AppStateProducer` consumes `state`; the `app_state` trace and the `events.system` names and shapes are unchanged. `online`/`offline`/`orientationchange` remain on it until the Connectivity and UI trackers take them.

Two behaviour changes on an UNREADABLE document (missing, non-string or throwing `visibilityState`): the `app_state` trace no longer reports `background`, and no `visibility` is emitted at all, so `process_background` is no longer recorded and the fps sampler is no longer paused on a fabricated hide. The tracker is shared per document, and the latest launch's `onError` is the reporter. An injected window without a document no longer borrows the host document in the events-source fallback.

Behaviour change for standalone `createBrowserSystemEventsSource` callers that pass NO `lifecycle`: the host-global fallback is all-or-nothing. If either `window` or `document` is injected, the other is never taken from the host globals (an injected env must not borrow the host's), so e.g. `{ document }` alone no longer also receives the host window's `pagehide`/`online`/`offline`/`orientationchange` events. Pass both, or neither, to keep full coverage. Browser and webview launch always pass a tracker and are unaffected.
1 change: 1 addition & 0 deletions docs/PROGRESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,7 @@ solid), in slices:
- **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.
- **TR1 (DONE, `feat/application-tracker`; design §15):** `PageLifecycleTracker` is now the domain **`ApplicationTracker`** (`packages/trackers/src/browser/application-tracker.ts`). Stages: `pagehide`, `visibility`, `freeze`, `resume`, plus the NEW aggregated `state` (`{state: 'foreground'|'background'}`, Android vocabulary, emitted when a visibility change CHANGES it) and `current()` (read live from the document, else the retained value; undefined when never known — an unreadable document emits no `state`, never a fabricated background). **Singleton per key** via `createTrackerRegistry`: `applicationTrackerFor(env, onError?)` keys by the document, else the window, else one shared key; a window-only env and a window+document env are DISTINCT trackers (pair a document with its own window); `resetApplicationTracker(env)` is exported from `@bugsee/trackers/browser` for internal/test use and is NOT re-exported by `@bugsee/browser`. Browser + webview launch and the events-source fallback obtain it through the registry. **Retention rule (tested):** DOM listeners attach on the first subscriber and detach on the last, the last known `state` is retained and recomputed silently from the document on re-activation, so the first subscriber after a gap is correct at once and the de-dup baseline is never stale. `AppStateProducer` now takes the tracker only (`on('state')` + `current()` for the initial value); trace/event names and wire shapes are unchanged. **Keying rule:** document, else window, else one module key (design §15.1 #5 will be amended from "one per window" to this). **Latest launch wins** through the registry `rebind`: a defined `onError` replaces the shared reporter (undefined keeps it); while IDLE the window/document are merged (a target the request omits is kept), while ACTIVE the binding is kept and a window/document mismatch (only a target the request supplies is compared; the error names which) is reported once. The shared sink is never released on stop: a relaunch with no `onError` keeps the previous launch's (accepted limitation). `resetApplicationTracker` is `@internal` test/teardown use: exported from `@bugsee/trackers/browser` but not re-exported by `@bugsee/browser` (`reset()` removes all subscribers). An unreadable document emits neither `visibility` nor `state` (no fabricated `process_background`/fps pause). **Stays for later:** `online`/`offline` (move to Connectivity, TR3) and `orientationchange` (UI/Display, TR2) remain stages on this tracker so ConnectionTracker/OrientationTracker are untouched.
- **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
Expand Down
12 changes: 7 additions & 5 deletions packages/browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ export {
type LifecycleEventsListener,
type LifecycleEventType,
} from '@bugsee/core';
export {
type ApplicationEnv,
type ApplicationEvents,
type ApplicationState,
ApplicationTracker,
applicationTrackerFor,
} from '@bugsee/trackers/browser';
export { COMPONENT_ATTRIBUTE, componentNameFromElement } from './component-name';
export {
createUnhandledRejectionProvider,
Expand Down Expand Up @@ -92,11 +99,6 @@ export {
createBrowserSystemTraceProducers,
defaultBrowserTraceEnv,
} from './trace-producers';
export {
type PageLifecycleEnv,
type PageLifecycleEvents,
PageLifecycleTracker,
} from './trackers/page-lifecycle-tracker';
export {
createUiBreadcrumbProvider,
createUiBreadcrumbSource,
Expand Down
75 changes: 75 additions & 0 deletions packages/browser/src/launch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import {
type RequestJson,
Severity,
} from '@bugsee/protocol';
import { applicationTrackerFor } from '@bugsee/trackers/browser';
import { strFromU8, unzipSync } from '@bugsee/util';
import { IDBFactory } from 'fake-indexeddb';
import { afterEach, describe, expect, it, vi } from 'vitest';
Expand Down Expand Up @@ -492,6 +493,80 @@ describe('launch', () => {
expect(doc.count('visibilitychange')).toBe(0);
});

describe('launch goes through the ApplicationTracker registry', () => {
const blockedDoc = () => {
const doc = fakeWindow();
const boom = new Error('visibilityState blocked');
const state = { armed: false };
Object.defineProperty(doc.win, 'visibilityState', {
get() {
if (state.armed) throw boom;
return 'visible';
},
});
return { doc, boom, state, document: doc.win as unknown as Document };
};

it('shares ONE tracker per document: a lookup for the launched document sees the launch listeners, not a second set', async () => {
const w = fakeWindow();
const { document } = blockedDoc();
await launchTracked(
'tok',
baseOptions({ window: w.win, document, captureStore: memStore() }),
);
expect(w.count('online')).toBe(1);
const shared = applicationTrackerFor({ window: w.win as never, document });
const off = shared.on('online', () => {});
expect(w.count('online')).toBe(1); // the SAME tracker: one listener serves launch and this subscriber
off();
});

it("the latest launch's onError becomes the reporter; a relaunch without one keeps it", async () => {
const w = fakeWindow();
const { doc, boom, state, document } = blockedDoc();
const first = vi.fn();
const second = vi.fn();
// The tracker's own read fails only while the event is dispatched (launch itself reads the document too).
const fireBlocked = () => {
state.armed = true;
try {
doc.emit('visibilitychange', {});
} catch {
/* a real DOM dispatch never propagates a listener's throw */
} finally {
state.armed = false;
}
};
const run = async (onError?: (e: unknown) => void) => {
const client = await launch(
'tok',
baseOptions({
window: w.win,
document,
captureStore: memStore(),
...(onError !== undefined ? { onError } : {}),
}),
);
return client;
};
await (await run(first)).stop();
await (await run(second)).stop();
first.mockClear();
second.mockClear();
const live = await run(second);
clients.push(live);
fireBlocked();
expect(second).toHaveBeenCalledWith(boom);
expect(first).not.toHaveBeenCalledWith(boom);
await live.stop();
second.mockClear();
const bare = await run(); // no onError: must NOT silence the earlier launch's sink
clients.push(bare);
fireBlocked();
expect(second).toHaveBeenCalledWith(boom);
});
});

describe('dark mode, freeze and resume events (from the injected window + document)', () => {
const mkMedia = () => {
const l = new Set<(e: { matches: boolean }) => void>();
Expand Down
4 changes: 2 additions & 2 deletions packages/browser/src/launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ import {
type UploadResult,
} from '@bugsee/core';
import { BugseeOption, type EnvironmentEnvelope } from '@bugsee/protocol';
import { applicationTrackerFor } from '@bugsee/trackers/browser';
import { reportGuarded } from '@bugsee/util';
import { BROWSER_APP_VERSION_HINT, metaAppIdentity, warnToConsole } from './app-identity';
import type { WindowEvents } from './detection-providers';
Expand All @@ -97,7 +98,6 @@ import {
import { parseStack } from './stack';
import { createBrowserSystemEventsSource } from './system-events';
import { browserTraceEnvFrom, createBrowserSystemTraceProducers } from './trace-producers';
import { PageLifecycleTracker } from './trackers/page-lifecycle-tracker';
import { createUiBreadcrumbProvider, createUiBreadcrumbSource } from './ui-breadcrumb-source';
import { createUserIdentifierStore } from './user-identifier-store';
import { createBrowserViewportSource } from './viewport-source';
Expand Down Expand Up @@ -878,7 +878,7 @@ async function buildLaunch(
client.addCaptureProvider(network.provider);
// ONE lifecycle tracker over the injected window+document, shared by the traces' connection/orientation
// producers and the events source: the listeners are bound in a single place.
const lifecycle = new PageLifecycleTracker(
const lifecycle = applicationTrackerFor(
{ window: win, ...(domDocument !== undefined ? { document: domDocument } : {}) },
options.onError,
);
Expand Down
44 changes: 40 additions & 4 deletions packages/browser/src/system-events.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { SystemEvent } from '@bugsee/capture';
import { ApplicationTracker, resetApplicationTracker } from '@bugsee/trackers/browser';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { type BrowserSystemEventsEnv, createBrowserSystemEventsSource } from './system-events';
import { PageLifecycleTracker } from './trackers/page-lifecycle-tracker';

afterEach(() => {
vi.unstubAllGlobals();
Expand Down Expand Up @@ -302,9 +302,45 @@ describe('createBrowserSystemEventsSource', () => {
off();
});

it('without an injected tracker, two sources over the same document share the registry singleton (one listener set)', () => {
const { env, win, doc } = fakeEnv();
const a = activate({ ...env, window: win as never });
const b = activate({ ...env, window: win as never });
expect(doc.count('visibilitychange')).toBe(1);
a.off();
expect(doc.count('visibilitychange')).toBe(1);
b.off();
expect(doc.count('visibilitychange')).toBe(0);
resetApplicationTracker({ document: env.document as never });
});

it('an injected window without a document never borrows the host document (nor binds its singleton)', () => {
const hostWin = target();
const hostDoc = target();
vi.stubGlobal('window', hostWin);
vi.stubGlobal('document', { ...hostDoc, visibilityState: 'visible' });
const injected = target();
const off = createBrowserSystemEventsSource({ window: injected as never }).onAny(() => {});
expect(injected.count('pagehide')).toBe(1);
expect(hostDoc.count('visibilitychange')).toBe(0);
expect(hostWin.count('pagehide')).toBe(0);
off();
});

it('an injected document without a window never borrows the host window', () => {
const hostWin = target();
vi.stubGlobal('window', hostWin);
const doc = target();
const off = createBrowserSystemEventsSource({
document: { ...doc, visibilityState: 'visible' } as never,
}).onAny(() => {});
expect(hostWin.count('pagehide')).toBe(0);
off();
});

it('subscribes to an injected shared lifecycle tracker instead of attaching its own listeners', () => {
const { env, win, doc } = fakeEnv();
const lifecycle = new PageLifecycleTracker({ window: win, document: env.document as never });
const lifecycle = new ApplicationTracker({ window: win, document: env.document as never });
const a = activate({ ...env, lifecycle });
const b = activate({ ...env, lifecycle });
// two sources over ONE tracker → one listener per type
Expand All @@ -329,14 +365,14 @@ describe('createBrowserSystemEventsSource', () => {
});
const { off } = activate({ ...env, onError });
expect(() => doc.emit('visibilitychange', {})).not.toThrow();
expect(onError).toHaveBeenCalledTimes(1);
expect(onError).toHaveBeenCalledTimes(2); // the activation read + the event read, each reported once
expect(win.count('pagehide')).toBe(1);
off();
});

it('over a shared tracker, re-subscribing after a full release re-emits process_started and resubscribes', () => {
const { env, win } = fakeEnv();
const lifecycle = new PageLifecycleTracker({ window: win, document: env.document as never });
const lifecycle = new ApplicationTracker({ window: win, document: env.document as never });
const source = createBrowserSystemEventsSource({ ...env, lifecycle });
const events: SystemEvent[] = [];
const first = source.onAny((_s, e) => events.push(e));
Expand Down
Loading