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

Browser and WebView `orientation`, `screen_size` and `fps` traces and the `orientation_changed` / `dark_mode_changed` events are now fed by one per-window singleton `UiTracker` (new in `@bugsee/trackers/browser`), which also exposes `viewport`, `colorScheme`, `reducedMotion` and `displayMode` stages. Trace and event names and wire shapes are unchanged. `orientation_changed` is now de-duplicated (one event per real orientation change) and also fires when only `screen.orientation` emits `change`. In `@bugsee/trackers`, `ApplicationEvents` loses its `orientationchange` key (a type change: the UiTracker owns it) and the emitter base gains `listenerCount` and an `onListenersChanged` hook.
11 changes: 6 additions & 5 deletions docs/PROGRESS.md

Large diffs are not rendered by default.

25 changes: 24 additions & 1 deletion packages/browser/src/launch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ import {
applicationTrackerFor,
connectivityTrackerFor,
resetStorageTracker,
resetUiTracker,
storageTrackerFor,
uiTrackerFor,
} from '@bugsee/trackers/browser';
import { strFromU8, unzipSync } from '@bugsee/util';
import { IDBFactory } from 'fake-indexeddb';
Expand Down Expand Up @@ -606,7 +608,8 @@ describe('launch', () => {
'tok',
baseOptions({ window: w.win, captureStore: store }),
);
expect(m.thisSeen).toEqual([w.win]); // called as a method of ITS window
expect(m.thisSeen).toHaveLength(2); // the baseline read + the change watch
expect(m.thisSeen.every((t) => t === w.win)).toBe(true); // always called as a method of ITS window
for (const f of [...m.l]) f({ matches: true });
expect((await names(store)).filter((e) => e.name === 'dark_mode_changed')).toEqual([
expect.objectContaining({ name: 'dark_mode_changed', params: { dark: true } }),
Expand Down Expand Up @@ -1464,6 +1467,26 @@ describe('launch', () => {
expect(w.count('orientationchange')).toBe(0);
});

it('goes through the per-window UiTracker singleton (orientation/screen_size/fps/events share ONE set of listeners)', async () => {
stubSensors();
const w = fakeWindow();
const client = await launchTracked(
'tok',
noSampler({ window: w.win, captureStore: memStore() }),
);
const before = w.count('orientationchange');
expect(before).toBe(1); // traces' orientation + the events source's orientation_changed: one listener
// Asking for the window's tracker returns the SAME one: subscribing adds no new window listener.
const ui = uiTrackerFor({ window: w.win });
const seen: unknown[] = [];
const off = ui.on('orientation', (s) => seen.push(s));
expect(w.count('orientationchange')).toBe(before);
off();
await client.stop();
expect(w.count('orientationchange')).toBe(0);
resetUiTracker({ window: w.win });
});

it('launch goes through the per-window ConnectivityTracker singleton: a second consumer shares its listeners, and downlinkMax reaches the trace', async () => {
vi.stubGlobal('navigator', {
onLine: true,
Expand Down
5 changes: 3 additions & 2 deletions packages/browser/src/launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -876,8 +876,9 @@ async function buildLaunch(
const maxBodyBytes = resolved.options.get(BugseeOption.CaptureNetworkBodySizeLimit, 20480);
const network = installNetworkCapture({ carrier, captureBodies, maxBodyBytes });
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.
// ONE lifecycle tracker over the injected window+document, shared by the traces' connection/app_state
// producers and the events source: the listeners are bound in a single place. (Orientation, screen size, fps and
// dark mode come from the per-window UiTracker, not from here.)
const lifecycle = applicationTrackerFor(
{ window: win, ...(domDocument !== undefined ? { document: domDocument } : {}) },
options.onError,
Expand Down
67 changes: 63 additions & 4 deletions packages/browser/src/system-events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ describe('createBrowserSystemEventsSource: dark mode, freeze and resume', () =>
const { env } = fakeEnv();
const m = fakeMedia();
const { events } = activate({ ...env, matchMedia: m.matchMedia });
expect(m.queries).toEqual(['(prefers-color-scheme: dark)']);
expect(new Set(m.queries)).toEqual(new Set(['(prefers-color-scheme: dark)'])); // baseline read + watch
m.fire(true);
m.fire(false);
expect(events.filter((e) => e.name === 'dark_mode_changed')).toEqual([
Expand All @@ -89,6 +89,31 @@ describe('createBrowserSystemEventsSource: dark mode, freeze and resume', () =>
]);
});

it('a throwing onError never escapes into the tracker-fed event dispatch', () => {
const { env, win, orientation } = fakeEnv();
const m = fakeMedia();
const { events } = activate({
...env,
matchMedia: m.matchMedia,
onError: () => {
throw new Error('reporter');
},
});
const source = createBrowserSystemEventsSource({
...env,
matchMedia: m.matchMedia,
onError: () => {
throw new Error('reporter');
},
});
source.on('event', () => {
throw new Error('consumer');
});
orientation.angle = 90;
expect(() => win.emit('orientationchange', {})).not.toThrow();
expect(events.map((e) => e.name)).toContain('orientation_changed');
});

it('removes the media listener on deactivate', () => {
const { env } = fakeEnv();
const m = fakeMedia();
Expand Down Expand Up @@ -116,7 +141,10 @@ describe('createBrowserSystemEventsSource: dark mode, freeze and resume', () =>
});
win.emit('online', {});
expect(events.map((e) => e.name)).toEqual(['process_started', 'online']);
expect(errors.map((e) => (e as Error).message)).toEqual(['matchMedia blocked']);
expect(errors.length).toBeGreaterThan(0);
expect(new Set(errors.map((e) => (e as Error).message))).toEqual(
new Set(['matchMedia blocked']),
);
});

it('a media list without addEventListener is a plain absence: skipped silently, other signals unaffected', () => {
Expand Down Expand Up @@ -257,13 +285,13 @@ describe('createBrowserSystemEventsSource', () => {
'screen blocked',
'window blocked',
]);
// a supplied lifecycle owns the window/document: they are not read (or reported) again
// a supplied lifecycle owns the DOCUMENT (not read again); the window is still read for the UI tracker
const none: unknown[] = [];
createBrowserSystemEventsSource({
lifecycle: { on: () => () => {} },
onError: (e) => none.push(e),
});
expect(none.map((e) => (e as Error).message)).toEqual(['screen blocked']); // only screen is still read
expect(none.map((e) => (e as Error).message)).toEqual(['window blocked', 'screen blocked']);
} finally {
for (const [key, d] of originals) {
if (d !== undefined) Object.defineProperty(globalThis, key, d);
Expand Down Expand Up @@ -302,6 +330,37 @@ describe('createBrowserSystemEventsSource', () => {
off();
});

it('without an injected window the UI tracker gets the host window (and its screen), like the lifecycle tracker', () => {
const win = target();
const screen = { orientation: { type: 'portrait-primary', angle: 0 } };
vi.stubGlobal('window', win);
vi.stubGlobal('screen', screen);
const source = createBrowserSystemEventsSource();
const events: SystemEvent[] = [];
const off = source.onAny((_s, e) => events.push(e));
expect(win.count('orientationchange')).toBe(1);
screen.orientation = { type: 'landscape-primary', angle: 90 };
win.emit('orientationchange', {});
expect(events.at(-1)).toEqual({
name: 'orientation_changed',
params: { type: 'landscape-primary', angle: 90 },
});
off();
expect(win.count('orientationchange')).toBe(0);
});

it('an injected window never borrows the host window or screen', () => {
const hostWin = target();
vi.stubGlobal('window', hostWin);
vi.stubGlobal('screen', { orientation: { type: 'portrait-primary', angle: 0 } });
const injected = target();
const { events, off } = activate({ window: injected as never });
expect(hostWin.count('orientationchange')).toBe(0);
injected.emit('orientationchange', {});
expect(events.at(-1)).toEqual({ name: 'orientation_changed' }); // the host's screen was not used
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 });
Expand Down
99 changes: 45 additions & 54 deletions packages/browser/src/system-events.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import type { SystemEvent } from '@bugsee/capture';
import { type Interceptor, InterceptorBase } from '@bugsee/core';
import { type ApplicationTracker, applicationTrackerFor } from '@bugsee/trackers/browser';
import {
type ApplicationTracker,
applicationTrackerFor,
type UiTracker,
uiTrackerFor,
} from '@bugsee/trackers/browser';
import type { WindowEvents } from './detection-providers';
import { hostGlobal } from './host-global';
import { hostGlobal, hostRead } from './host-global';

// Browser system-event SOURCE for @bugsee/capture's systemEventsProvider (the node lifecycle-source
// analog). A listenable InterceptorBase: on activate it emits a 'process_started' marker and subscribes
Expand All @@ -11,7 +16,8 @@ import { hostGlobal } from './host-global';
// pagehide → process_exiting (the best "about to unload — flush now" signal + bfcache flag)
// visibilitychange → process_foreground / process_background (app fg/bg, from document.visibilityState)
// online / offline → online / offline (connectivity transitions)
// orientationchange → orientation_changed ({type, angle} from screen.orientation)
// orientation (UiTracker: screen.orientation change + orientationchange) → orientation_changed ({type, angle})
// colorScheme (UiTracker) → dark_mode_changed ({dark} from prefers-color-scheme)
// Each signal degrades gracefully where its global is absent (e.g. no document/screen in a worker).

/** The document surface the source needs: visibilitychange + the current visibility state. */
Expand All @@ -23,6 +29,8 @@ interface ScreenLike {
readonly orientation?: { readonly type: OrientationType; readonly angle: number };
}

type UiEnvWindow = NonNullable<Parameters<typeof uiTrackerFor>[0]['window']>;

/** The slice of a `MediaQueryList` the dark-mode event needs. */
interface MediaQueryLike {
readonly matches: boolean;
Expand Down Expand Up @@ -51,15 +59,12 @@ export interface BrowserSystemEventsEnv {
class BrowserSystemEventsSource extends InterceptorBase<{ event: SystemEvent }> {
readonly name = 'browser-system-events';
readonly #lifecycle: Pick<ApplicationTracker, 'on'>;
readonly #screen: ScreenLike | undefined;
readonly #matchMedia: ((query: string) => MediaQueryLike) | undefined;
readonly #onError: (error: unknown) => void;
readonly #ui: Pick<UiTracker, 'on'>;
#unsubscribe: Array<() => void> = [];

constructor(
lifecycle: Pick<ApplicationTracker, 'on'>,
screenLike: ScreenLike | undefined,
matchMedia?: (query: string) => MediaQueryLike,
ui: Pick<UiTracker, 'on'>,
onError?: (error: unknown) => void,
) {
// A throwing reporter must not escape into the browser's event dispatch or abort activation.
Expand All @@ -72,9 +77,7 @@ class BrowserSystemEventsSource extends InterceptorBase<{ event: SystemEvent }>
};
super(report);
this.#lifecycle = lifecycle;
this.#screen = screenLike;
this.#matchMedia = matchMedia;
this.#onError = report;
this.#ui = ui;
}

protected onActivate(): void {
Expand All @@ -91,44 +94,18 @@ class BrowserSystemEventsSource extends InterceptorBase<{ event: SystemEvent }>
l.on('resume', () => this.emit('event', { name: 'resume' })),
l.on('online', () => this.emit('event', { name: 'online' })),
l.on('offline', () => this.emit('event', { name: 'offline' })),
l.on('orientationchange', () => {
const orientation = this.#screen?.orientation;
// The UiTracker de-duplicates the double delivery (screen.orientation change + window orientationchange); an
// engine without a readable orientation still announces the bare event.
this.#ui.on('orientation', ({ type, angle }) =>
this.emit('event', {
name: 'orientation_changed',
...(orientation !== undefined
? { params: { type: orientation.type, angle: orientation.angle } }
: {}),
});
}),
...(type !== undefined && angle !== undefined ? { params: { type, angle } } : {}),
}),
),
this.#ui.on('colorScheme', ({ dark }) =>
this.emit('event', { name: 'dark_mode_changed', params: { dark } }),
),
];
this.#watchDarkMode();
}

// `prefers-color-scheme` is a MediaQueryList you listen on (not a window event). Attached on its own, guarded:
// an unguarded throw here would abort the capture coordinator's start and every provider registered after
// the events source (input, viewtree, ...).
#watchDarkMode(): void {
try {
const list = this.#matchMedia?.('(prefers-color-scheme: dark)');
if (list === undefined || typeof list.addEventListener !== 'function') return;
const onChange = (event: { readonly matches: boolean }): void => {
try {
this.emit('event', { name: 'dark_mode_changed', params: { dark: event.matches } });
} catch (error) {
this.#onError(error); // never throw into the browser's event dispatch
}
};
list.addEventListener('change', onChange);
this.#unsubscribe.push(() => {
try {
list.removeEventListener?.('change', onChange);
} catch {
/* best-effort */
}
});
} catch (error) {
this.#onError(error);
}
}

protected override onDeactivate(): void {
Expand All @@ -141,13 +118,14 @@ class BrowserSystemEventsSource extends InterceptorBase<{ event: SystemEvent }>
export function createBrowserSystemEventsSource(
env: BrowserSystemEventsEnv = {},
): Interceptor<{ event: SystemEvent }> {
// The host globals are read only when no lifecycle tracker was supplied: a supplied one already owns them.
// Host globals (window, document) only when NEITHER window nor document was injected: an injected env never
// borrows the host's window or document. ONE read of the window serves the lifecycle tracker and the UI tracker.
const injected = env.window !== undefined || env.document !== undefined;
const win = injected ? env.window : hostGlobal<WindowEvents>('window', env.onError);
// The document is read only when no lifecycle tracker was supplied: a supplied one already owns it.
const lifecycle =
env.lifecycle ??
((): ApplicationTracker => {
// Host globals only when NEITHER was injected: an injected window never borrows the host's document.
const injected = env.window !== undefined || env.document !== undefined;
const win = injected ? env.window : hostGlobal('window', env.onError);
const doc = injected ? env.document : hostGlobal('document', env.onError);
return applicationTrackerFor(
{
Expand All @@ -157,10 +135,23 @@ export function createBrowserSystemEventsSource(
env.onError,
);
})();
return new BrowserSystemEventsSource(
lifecycle,
env.screen ?? hostGlobal('screen', env.onError),
env.matchMedia,
// An injected WINDOW brings ITS screen (read guarded), so a window whose `screen` is blocked never borrows the
// host's into the shared per-window UI tracker. Without an injected window — including an env that injected only a
// document, as before — the host's screen global applies.
const screen =
env.screen ??
(env.window !== undefined
? hostRead(() => (env.window as { screen?: ScreenLike }).screen, env.onError)
: hostGlobal('screen', env.onError));
// The SAME per-window tracker the traces use (keyed on the window; a relaunch's seams merge into it). Without an
// injected window it gets the host's, exactly as the lifecycle tracker does above.
const ui = uiTrackerFor(
{
...(win !== undefined ? { window: win as UiEnvWindow } : {}),
...(screen !== undefined ? { screen } : {}),
...(env.matchMedia !== undefined ? { matchMedia: env.matchMedia } : {}),
},
env.onError,
);
return new BrowserSystemEventsSource(lifecycle, ui, env.onError);
}
11 changes: 5 additions & 6 deletions packages/browser/src/trace-producers.screen-lag.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { TraceProducer } from '@bugsee/capture';
import { ApplicationTracker } from '@bugsee/trackers/browser';
import { ApplicationTracker, UiTracker } from '@bugsee/trackers/browser';
import { describe, expect, it } from 'vitest';
import {
browserTraceEnvFrom,
Expand All @@ -8,7 +8,6 @@ import {
ScreenSizeProducer,
} from './trace-producers';
import { MainThreadLagTracker } from './trackers/main-thread-lag-tracker';
import { ScreenSizeTracker } from './trackers/screen-size-tracker';

function mkTarget() {
const l = new Map<string, Set<(e: unknown) => void>>();
Expand Down Expand Up @@ -36,7 +35,7 @@ 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 });
const tracker = new UiTracker({ window: win, screen: screen as never });
return { win, tracker };
};

Expand All @@ -62,9 +61,9 @@ describe('ScreenSizeProducer', () => {
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));
new ScreenSizeProducer(new UiTracker({ window: win, ...(screen ? { screen } : {}) })).start(
sinkOf(out),
);
expect(out).toEqual([]);
}
});
Expand Down
Loading