From ffdf9af096353ace8253462d024384f753f9bd4c Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 12:28:55 +0500 Subject: [PATCH 1/4] fix(replay): record inline by default; keep / blocked blockAllMedia's selector included svg, so every inline SVG replayed as an empty placeholder. SVG vector DOM is now recorded under the normal masking rules while raster-bearing / stay blocked. Human guided, AI implemented --- packages/replay/src/masking.integration.test.ts | 14 ++++++++++++-- packages/replay/src/masking.test.ts | 8 ++++++++ packages/replay/src/masking.ts | 7 +++++-- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/packages/replay/src/masking.integration.test.ts b/packages/replay/src/masking.integration.test.ts index e67d9ed1d..d0ed006f8 100644 --- a/packages/replay/src/masking.integration.test.ts +++ b/packages/replay/src/masking.integration.test.ts @@ -326,8 +326,7 @@ describe('attribute masking is fail-CLOSED — an allowlist, not an 11-entry den }); it('leaves SVG geometry untouched, so icons still draw', async () => { - // `svg` is inside MEDIA_SELECTOR, so it is blocked (and its attributes absent) at defaults — this is - // only observable with media un-blocked. Masking `d`/`viewBox` would silently destroy every icon. + // Masking `d`/`viewBox` would silently destroy every icon (inline svg is recorded at defaults too — see below). const { json } = await drive( '', { @@ -339,6 +338,17 @@ describe('attribute masking is fail-CLOSED — an allowlist, not an 11-entry den } }); + it('records inline at DEFAULTS (children + geometry) while an SVG stays blocked', async () => { + const { json } = await drive( + '' + + '', + ); + for (const structural of ['0 0 24 24', 'M4 4 L8 8', '#abc']) { + expect(json, structural).toContain(structural); + } + expect(json).not.toContain('SECRETPIXELS'); + }); + it('masks attributes on DESCENDANTS of a `.bugsee-mask` element', async () => { // `matches()` tests the marked element ALONE, so marking a container did nothing for the fields inside // it — which is how anyone would expect to use the mark, and how it reads in the docs. Every text-side diff --git a/packages/replay/src/masking.test.ts b/packages/replay/src/masking.test.ts index 3d469741b..370acef65 100644 --- a/packages/replay/src/masking.test.ts +++ b/packages/replay/src/masking.test.ts @@ -174,6 +174,14 @@ describe('resolveReplayMaskingOptions — fail-closed defaults', () => { ); }); + it('does NOT block inline by default, but still blocks SVG (embedded rasters)', () => { + const tags = MEDIA_SELECTOR.split(','); + expect(tags).not.toContain('svg'); + expect(tags).toContain('image'); + expect(tags).toContain('feImage'); // SVG filter primitive that carries a raster/data-URI href + expect(resolveReplayMaskingOptions().blockSelector?.split(',')).not.toContain('svg'); + }); + it('excludes iframes (blocked) — part of the media set', () => { expect(MEDIA_SELECTOR).toContain('iframe'); expect(resolveReplayMaskingOptions().blockSelector).toContain('iframe'); diff --git a/packages/replay/src/masking.ts b/packages/replay/src/masking.ts index 212d0a65c..458db8e13 100644 --- a/packages/replay/src/masking.ts +++ b/packages/replay/src/masking.ts @@ -38,10 +38,13 @@ import { import type { recordOptions } from '@bugsee/rrweb'; /** Media/embedded elements blocked (rendered as same-size placeholders, contents not recorded) when - * `blockAllMedia`. Includes `iframe`: a blocked iframe is a placeholder and its document is never recorded + * `blockAllMedia`. Inline `` is deliberately NOT here: it is vector DOM (icons, charts), and blocking it + * replayed every one as an empty box. Its raster-bearing children `` and `` ARE blocked (rrweb tests the selector per + * element), and its `` follows the normal text-masking rules. Includes `iframe`: a blocked iframe is a placeholder and its document is never recorded * (same-origin or not; see `iframe-guard.ts`). `.bugsee-show` on an iframe opts it back in, and its content is then * recorded under the normal masking rules. */ -export const MEDIA_SELECTOR = 'img,svg,image,video,audio,object,picture,embed,map,source,iframe'; +export const MEDIA_SELECTOR = + 'img,image,feImage,video,audio,object,picture,embed,map,source,iframe'; /** All `` elements — blocked (placeholder, contents not recorded) when `blockAllCanvas`, so canvas * recording then captures ONLY canvases explicitly opted in via `.bugsee-show`/`[data-bugsee-show]`. */ From 276e8bb2ea0fc49cc9f56358a945ad069cb8297f Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 12:28:55 +0500 Subject: [PATCH 2/4] feat(node,vercel-edge,cloudflare): detect app version from more automatic sources Node/Bun fall back to the entry script's directory (never under node_modules); edge launches accept `bindings` (Workers env) and read CF_VERSION_METADATA. `bindings` is kept across relaunch. Browser README documents the Angular define recipe. Human guided, AI implemented --- packages/browser/README.md | 11 +++ packages/core/src/carrier.ts | 1 + .../test/instrumentation.e2e.ts | 5 +- packages/node/src/app-identity-source.test.ts | 74 +++++++++++++++++++ packages/node/src/app-identity-source.ts | 34 +++++++-- packages/node/src/launch.test.ts | 26 +++++++ packages/node/src/launch.ts | 14 +++- packages/vercel-edge/src/app-identity.test.ts | 61 ++++++++++++++- packages/vercel-edge/src/app-identity.ts | 72 +++++++++++------- packages/vercel-edge/src/launch.test.ts | 11 +++ packages/vercel-edge/src/launch.ts | 10 ++- 11 files changed, 279 insertions(+), 40 deletions(-) diff --git a/packages/browser/README.md b/packages/browser/README.md index f186a6307..e1dbe0c21 100644 --- a/packages/browser/README.md +++ b/packages/browser/README.md @@ -24,6 +24,17 @@ await launch('', { appVersion: '2.4.1', appBuild: '381' }); Bugsee can also pick them up at build time. The Bugsee Vite and webpack plugins inject the constants `__BUGSEE_APP_VERSION__` and `__BUGSEE_APP_BUILD__` automatically when you give `appVersion` and `appBuild` to the plugin, or when `BUGSEE_APP_VERSION` and `BUGSEE_APP_BUILD` are set in the build environment. You can also define those two constants yourself in your bundler, or set `__BUGSEE_APP_VERSION__` and `__BUGSEE_APP_BUILD__` as globals before launching (for example `window.__BUGSEE_APP_VERSION__ = '2.4.1'`). Options passed to `launch` always win over the build-time values. +**Angular (esbuild `application` builder) and other builds without a Bugsee plugin.** A browser cannot read your `package.json` at runtime, so the version has to be baked in at build time. Angular's builder takes a `define` map in `angular.json` (`projects..architect.build.options.define`): + +```json +"define": { + "__BUGSEE_APP_VERSION__": "\"2.4.1\"", + "__BUGSEE_APP_BUILD__": "\"381\"" +} +``` + +Generate those two lines in CI from your own version and commit id (a small script that writes `angular.json`, or `ng build --configuration` with a configuration-specific `define`). The same two constants work for any bundler that supports `define` (esbuild, Rollup, Vite, webpack `DefinePlugin`). Without any of these the report shows `0.0.0` and the SDK warns once in the console. + If no version can be found, Bugsee logs a single warning to the console and reports the version as `0.0.0` and the build as `0`. A page can also declare them in its HTML: ```html diff --git a/packages/core/src/carrier.ts b/packages/core/src/carrier.ts index 3a210d818..bd7e63bca 100644 --- a/packages/core/src/carrier.ts +++ b/packages/core/src/carrier.ts @@ -293,6 +293,7 @@ export const RELAUNCH_KEPT_OPTIONS: readonly string[] = [ 'appId', 'appVersion', 'appBuild', + 'bindings', // edge env bindings (version/build source): dropped on relaunch, the version would fall back to 0.0.0 'appIdentitySource', 'platformType', 'sdkVersion', diff --git a/packages/instrumentation-tests/test/instrumentation.e2e.ts b/packages/instrumentation-tests/test/instrumentation.e2e.ts index 49db61342..8de863009 100644 --- a/packages/instrumentation-tests/test/instrumentation.e2e.ts +++ b/packages/instrumentation-tests/test/instrumentation.e2e.ts @@ -139,8 +139,11 @@ describe.each( const env = collector.sessions[0]?.environment as { platform: { type: string; version: string }; runtime: { type: string; version: string }; - app: { uptime_s?: number }; + app: { uptime_s?: number; version?: string; build?: string }; }; + // The identity the app supplied reaches the session envelope: never the 0.0.0 placeholder. + expect(env.app.version).toBe('1.2.3'); + expect(env.app.version).not.toBe('0.0.0'); // C14: process uptime at session start is a whole-second snapshot in environment.app (replaces the // retired per-second `process_uptime_s` trace); process.uptime() answers on real node and bun. expect(Number.isInteger(env.app.uptime_s)).toBe(true); diff --git a/packages/node/src/app-identity-source.test.ts b/packages/node/src/app-identity-source.test.ts index ae2114c0e..2aca097df 100644 --- a/packages/node/src/app-identity-source.test.ts +++ b/packages/node/src/app-identity-source.test.ts @@ -221,3 +221,77 @@ describe('createNodeAppIdentitySource build', () => { expect(createNodeAppIdentitySource({ env: {}, cwd: () => undefined })()).toEqual({}); }); }); + +describe('createNodeAppIdentitySource entry-point fallback', () => { + it('reads the entry script’s package.json when the working directory has none', () => { + const readFile = files({ '/srv/app/package.json': '{"version":"4.2.0"}' }); + const source = createNodeAppIdentitySource({ + env: {}, + cwd: () => '/', + entryPoint: () => '/srv/app/dist/main.js', + readFile, + }); + expect(source()).toEqual({ version: '4.2.0' }); + }); + + it('prefers the working directory’s manifest over the entry script’s', () => { + const source = createNodeAppIdentitySource({ + env: {}, + cwd: () => '/work', + entryPoint: () => '/srv/app/main.js', + readFile: files({ + '/work/package.json': '{"version":"1.0.0"}', + '/srv/app/package.json': '{"version":"9.9.9"}', + }), + }); + expect(source()?.version).toBe('1.0.0'); + }); + + it('does not consult the entry point when appRoot is given', () => { + const entryPoint = vi.fn(() => '/srv/app/main.js'); + const source = createNodeAppIdentitySource({ + env: {}, + appRoot: '/root', + entryPoint, + readFile: files({ '/srv/app/package.json': '{"version":"9.9.9"}' }), + }); + expect(source()?.version).toBeUndefined(); + expect(entryPoint).not.toHaveBeenCalled(); + }); + + it('never adopts a tool’s or dependency’s manifest found under node_modules via the entry script', () => { + const source = createNodeAppIdentitySource({ + env: {}, + cwd: () => '/', + entryPoint: () => '/proj/node_modules/tsx/dist/cli.mjs', + readFile: files({ '/proj/node_modules/tsx/package.json': '{"version":"4.19.0"}' }), + }); + expect(source()?.version).toBeUndefined(); + const windows = createNodeAppIdentitySource({ + env: {}, + cwd: () => '/', + entryPoint: () => '/proj/node_modules/.bin/vitest', + readFile: files({ '/proj/node_modules/.bin/package.json': '{"version":"1.1.1"}' }), + }); + expect(windows()?.version).toBeUndefined(); + }); + + it('survives a missing or throwing entry point', () => { + const none = createNodeAppIdentitySource({ + env: {}, + cwd: () => '/', + entryPoint: () => undefined, + readFile: files({}), + }); + expect(none()?.version).toBeUndefined(); + const throwing = createNodeAppIdentitySource({ + env: {}, + cwd: () => '/', + entryPoint: () => { + throw new Error('boom'); + }, + readFile: files({}), + }); + expect(throwing()?.version).toBeUndefined(); + }); +}); diff --git a/packages/node/src/app-identity-source.ts b/packages/node/src/app-identity-source.ts index 0c5847363..34007598d 100644 --- a/packages/node/src/app-identity-source.ts +++ b/packages/node/src/app-identity-source.ts @@ -26,6 +26,12 @@ export interface NodeAppIdentitySourceOptions { readFile?: (path: string) => string; /** Directory to start looking for `package.json` in. Default the working directory. */ appRoot?: string; + /** + * The running entry script (a file path). Consulted only when no `appRoot` is given AND the working + * directory's search found no version (a container `WORKDIR /`, a service manager's cwd): its directory is + * then searched the same way. Default none; the launch passes `process.argv[1]` / `Bun.main`. + */ + entryPoint?: () => string | undefined; } const defaultCwd = (): string | undefined => { @@ -70,14 +76,26 @@ export const createNodeAppIdentitySource = ( let searched: { value: string | undefined } | undefined; const fromPackageJson = (): string | undefined => { if (searched === undefined) { - const start = - options.appRoot !== undefined && options.appRoot !== '' ? options.appRoot : cwd(); - searched = { - value: - start === undefined - ? undefined - : findNearestPackageVersion(start, { readFile, dirname, join }), - }; + const explicitRoot = + options.appRoot !== undefined && options.appRoot !== '' ? options.appRoot : undefined; + const find = (start: string | undefined): string | undefined => + start === undefined + ? undefined + : findNearestPackageVersion(start, { readFile, dirname, join }); + let value = find(explicitRoot ?? cwd()); + if (value === undefined && explicitRoot === undefined && options.entryPoint !== undefined) { + try { + const entry = options.entryPoint(); + // An entry under node_modules is a TOOL's script (tsx/vitest/npx resolve argv[1] there), never the app: + // walking up from it would stamp the report with the tool's version. + const underModules = entry !== undefined && /(^|[\\/])node_modules([\\/]|$)/.test(entry); + value = + entry === undefined || entry === '' || underModules ? undefined : find(dirname(entry)); + } catch { + value = undefined; // an entry point that cannot be read is simply unknown + } + } + searched = { value }; } return searched.value; }; diff --git a/packages/node/src/launch.test.ts b/packages/node/src/launch.test.ts index 10b2cc918..578c412d2 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -3983,6 +3983,7 @@ describe('app identity detection', () => { afterEach(() => { vi.unstubAllEnvs(); + vi.unstubAllGlobals(); vi.restoreAllMocks(); }); @@ -4027,11 +4028,35 @@ describe('app identity detection', () => { expect(launchIdentity({ appRoot: dir }).internals?.appVersion).toBe('3.3.3'); }); + it('falls back to the entry script’s package.json when the working directory has none', () => { + vi.stubEnv('BUGSEE_APP_VERSION', ''); + const dir = mkdtempSync(join(tmpdir(), 'bugsee-entry-')); + writeFileSync(join(dir, 'package.json'), '{"version":"6.6.6"}'); + vi.spyOn(process, 'cwd').mockImplementation(() => { + throw new Error('gone'); + }); + vi.spyOn(process, 'argv', 'get').mockReturnValue(['node', join(dir, 'main.js')]); + expect(launchIdentity().internals?.appVersion).toBe('6.6.6'); + }); + + it('prefers Bun.main over argv[1] for the entry script', () => { + vi.stubEnv('BUGSEE_APP_VERSION', ''); + const dir = mkdtempSync(join(tmpdir(), 'bugsee-bun-')); + writeFileSync(join(dir, 'package.json'), '{"version":"5.5.5"}'); + vi.spyOn(process, 'cwd').mockImplementation(() => { + throw new Error('gone'); + }); + vi.spyOn(process, 'argv', 'get').mockReturnValue(['bun', '/nowhere/x.js']); + vi.stubGlobal('Bun', { main: join(dir, 'server.ts') }); + expect(launchIdentity().internals?.appVersion).toBe('5.5.5'); + }); + it('a repeat launch() is ignored before identity is resolved: no second package.json read or warning', () => { vi.stubEnv('BUGSEE_APP_VERSION', ''); const cwd = vi.spyOn(process, 'cwd').mockImplementation(() => { throw new Error('gone'); }); + vi.spyOn(process, 'argv', 'get').mockReturnValue(['node']); const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); const carrier = {}; const identitySource = vi.fn(() => undefined); @@ -4063,6 +4088,7 @@ describe('app identity detection', () => { vi.spyOn(process, 'cwd').mockImplementation(() => { throw new Error('gone'); }); + vi.spyOn(process, 'argv', 'get').mockReturnValue(['node']); // no entry script to fall back to const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); const { internals } = launchIdentity({ appRoot: '' }); expect(internals?.appVersion).toBeUndefined(); diff --git a/packages/node/src/launch.ts b/packages/node/src/launch.ts index d48269f0e..0016f07cb 100644 --- a/packages/node/src/launch.ts +++ b/packages/node/src/launch.ts @@ -607,6 +607,13 @@ const internalTagged = (transport: HttpTransport): HttpTransport => const EXPORT_FILE_MAX_AGE_MS = 60 * 60 * 1000; /** `process.cwd()` can throw when the working directory has been deleted out from under the process. */ +/** The running entry script: Bun's `Bun.main`, else Node's `process.argv[1]`. */ +const runtimeEntryPoint = (): string | undefined => { + const main = (globalThis as unknown as { Bun?: { main?: unknown } }).Bun?.main; + const entry = typeof main === 'string' && main !== '' ? main : process.argv[1]; + return typeof entry === 'string' && entry !== '' ? entry : undefined; +}; + const safeCwd = (): string | undefined => { try { return process.cwd(); @@ -677,9 +684,10 @@ function buildLaunch(appToken: string, options: BugseeLaunchOptions = {}): Launc [ bundledAppIdentity, ...(options.appIdentitySource !== undefined ? [options.appIdentitySource] : []), - createNodeAppIdentitySource( - options.appRoot !== undefined ? { appRoot: options.appRoot } : {}, - ), + createNodeAppIdentitySource({ + ...(options.appRoot !== undefined ? { appRoot: options.appRoot } : {}), + entryPoint: runtimeEntryPoint, + }), ], warnToConsole, 'Pass `appVersion` (and `appBuild`) to launch(), set BUGSEE_APP_VERSION (and BUGSEE_APP_BUILD), or give your package.json a version.', diff --git a/packages/vercel-edge/src/app-identity.test.ts b/packages/vercel-edge/src/app-identity.test.ts index 04bfe03a7..b554d3167 100644 --- a/packages/vercel-edge/src/app-identity.test.ts +++ b/packages/vercel-edge/src/app-identity.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; -import { edgeAppIdentity } from './app-identity'; +import { createEdgeAppIdentity, edgeAppIdentity } from './app-identity'; afterEach(() => vi.unstubAllEnvs()); @@ -25,3 +25,62 @@ describe('edgeAppIdentity', () => { expect(edgeAppIdentity()).toEqual({}); }); }); + +describe('createEdgeAppIdentity bindings (Cloudflare env)', () => { + it('reads BUGSEE_APP_VERSION / BUGSEE_APP_BUILD from the bindings, trimmed', () => { + vi.stubEnv('BUGSEE_APP_VERSION', ''); + vi.stubEnv('BUGSEE_APP_BUILD', ''); + vi.stubEnv('VERCEL_GIT_COMMIT_SHA', ''); + expect( + createEdgeAppIdentity({ BUGSEE_APP_VERSION: ' 2.0.0\n', BUGSEE_APP_BUILD: ' 12 ' })(), + ).toEqual({ version: '2.0.0', build: '12' }); + }); + + it('takes the version tag and id from a CF_VERSION_METADATA binding', () => { + vi.stubEnv('BUGSEE_APP_VERSION', ''); + vi.stubEnv('BUGSEE_APP_BUILD', ''); + vi.stubEnv('VERCEL_GIT_COMMIT_SHA', ''); + expect( + createEdgeAppIdentity({ CF_VERSION_METADATA: { id: ' abc-123 ', tag: ' v7 ' } })(), + ).toEqual({ version: 'v7', build: 'abc-123' }); + }); + + it('ignores blank/odd metadata fields and a non-object binding', () => { + vi.stubEnv('BUGSEE_APP_VERSION', ''); + vi.stubEnv('BUGSEE_APP_BUILD', ''); + vi.stubEnv('VERCEL_GIT_COMMIT_SHA', ''); + expect(createEdgeAppIdentity({ CF_VERSION_METADATA: { id: ' ', tag: 5 } })()).toEqual({}); + expect(createEdgeAppIdentity({ CF_VERSION_METADATA: 'x' })()).toEqual({}); + expect(createEdgeAppIdentity({ BUGSEE_APP_VERSION: 7 })()).toEqual({}); + }); + + it('process.env wins over bindings, which fill what it lacks', () => { + vi.stubEnv('BUGSEE_APP_VERSION', '1.0.0'); + vi.stubEnv('BUGSEE_APP_BUILD', ''); + vi.stubEnv('VERCEL_GIT_COMMIT_SHA', ''); + expect( + createEdgeAppIdentity({ + BUGSEE_APP_VERSION: '9.9.9', + CF_VERSION_METADATA: { id: 'vid', tag: 't' }, + })(), + ).toEqual({ version: '1.0.0', build: 'vid' }); + }); + + it('explicit BUGSEE_APP_VERSION binding beats the metadata tag', () => { + vi.stubEnv('BUGSEE_APP_VERSION', ''); + vi.stubEnv('BUGSEE_APP_BUILD', ''); + vi.stubEnv('VERCEL_GIT_COMMIT_SHA', ''); + expect( + createEdgeAppIdentity({ + BUGSEE_APP_VERSION: '3.0.0', + BUGSEE_APP_BUILD: 'b', + CF_VERSION_METADATA: { id: 'vid', tag: 't' }, + })(), + ).toEqual({ version: '3.0.0', build: 'b' }); + }); + + it('without bindings it equals edgeAppIdentity', () => { + vi.stubEnv('BUGSEE_APP_VERSION', '4.0.0'); + expect(createEdgeAppIdentity()()).toEqual(edgeAppIdentity()); + }); +}); diff --git a/packages/vercel-edge/src/app-identity.ts b/packages/vercel-edge/src/app-identity.ts index 4abf027c3..71072d25f 100644 --- a/packages/vercel-edge/src/app-identity.ts +++ b/packages/vercel-edge/src/app-identity.ts @@ -7,34 +7,56 @@ export const warnToConsole = (message: string): void => { /** How an edge function is told its version. */ export const EDGE_APP_VERSION_HINT = - 'Pass `appVersion` (and `appBuild`) to launch(), use the Bugsee Vite or webpack plugin (it defines `__BUGSEE_APP_VERSION__`), or set BUGSEE_APP_VERSION (and BUGSEE_APP_BUILD) in the environment.'; + 'Pass `appVersion` (and `appBuild`) to launch(), use the Bugsee Vite or webpack plugin (it defines `__BUGSEE_APP_VERSION__`), set BUGSEE_APP_VERSION (and BUGSEE_APP_BUILD) in the environment, or (Cloudflare) pass the `env` object as `bindings`.'; const present = (value: unknown): value is string => typeof value === 'string' && value.trim() !== ''; +const trimmed = (value: unknown): string | undefined => (present(value) ? value.trim() : undefined); + /** - * Identity from the edge process environment, below the bundled constants: `BUGSEE_APP_VERSION` and - * `BUGSEE_APP_BUILD`; for the build alone, on Vercel the deployed commit is the fallback (the version has - * no platform-provided equivalent). Blank values are skipped and a throwing environment is no environment. + * Identity from the edge process environment, then from the host's bindings, below the bundled constants. + * `BUGSEE_APP_VERSION` / `BUGSEE_APP_BUILD` are read from `process.env` first (workerd populates it only for + * newer compatibility dates), then from `bindings` (Cloudflare's per-deployment `env` object, which is the + * reliable carrier there). A Cloudflare `CF_VERSION_METADATA` binding supplies the rest: its `tag` is the + * version and its `id` the build, each only when nothing explicit answered. For the build alone, on Vercel + * the deployed commit is the last fallback (the version has no platform-provided equivalent). Blank values + * are skipped and a throwing environment is no environment. */ -export const edgeAppIdentity = (): AppIdentity | undefined => { - let env: Record | undefined; - try { - env = (globalThis as unknown as { process?: { env?: Record } }) - .process?.env; - } catch { - return undefined; - } - if (env === undefined) { - return undefined; - } - const identity: AppIdentity = {}; - if (present(env.BUGSEE_APP_VERSION)) { - identity.version = env.BUGSEE_APP_VERSION.trim(); - } - const build = [env.BUGSEE_APP_BUILD, env.VERCEL_GIT_COMMIT_SHA].find(present); - if (build !== undefined) { - identity.build = build.trim(); - } - return identity; -}; +export const createEdgeAppIdentity = + (bindings?: Record) => (): AppIdentity | undefined => { + let env: Record | undefined; + try { + env = (globalThis as unknown as { process?: { env?: Record } }) + .process?.env; + } catch { + env = undefined; + } + const metadata = ((): { id?: unknown; tag?: unknown } => { + const value = bindings?.CF_VERSION_METADATA; + return typeof value === 'object' && value !== null ? value : {}; + })(); + if (env === undefined && bindings === undefined) { + return undefined; + } + const identity: AppIdentity = {}; + const version = + trimmed(env?.BUGSEE_APP_VERSION) ?? + trimmed(bindings?.BUGSEE_APP_VERSION) ?? + trimmed(metadata.tag); + if (version !== undefined) { + identity.version = version; + } + const build = + trimmed(env?.BUGSEE_APP_BUILD) ?? + trimmed(bindings?.BUGSEE_APP_BUILD) ?? + trimmed(metadata.id) ?? + trimmed(env?.VERCEL_GIT_COMMIT_SHA); + if (build !== undefined) { + identity.build = build; + } + return identity; + }; + +/** Identity from the edge process environment only; see {@link createEdgeAppIdentity}. */ +export const edgeAppIdentity = createEdgeAppIdentity(); diff --git a/packages/vercel-edge/src/launch.test.ts b/packages/vercel-edge/src/launch.test.ts index b5202b148..bed56845e 100644 --- a/packages/vercel-edge/src/launch.test.ts +++ b/packages/vercel-edge/src/launch.test.ts @@ -1071,6 +1071,17 @@ describe('app identity resolution', () => { }); }); + it('reads the version and build from the `bindings` option (Cloudflare env + version metadata)', async () => { + vi.stubEnv('BUGSEE_APP_VERSION', ''); + vi.stubEnv('BUGSEE_APP_BUILD', ''); + vi.stubEnv('VERCEL_GIT_COMMIT_SHA', ''); + expect( + await reportedApp({ + bindings: { BUGSEE_APP_VERSION: '8.1.0', CF_VERSION_METADATA: { id: 'ver-1', tag: 'x' } }, + }), + ).toMatchObject({ version: '8.1.0', build: 'ver-1' }); + }); + it('takes the build from VERCEL_GIT_COMMIT_SHA when nothing else supplies it', async () => { vi.stubEnv('VERCEL_GIT_COMMIT_SHA', 'abc123'); vi.stubGlobal('__BUGSEE_APP_VERSION__', '4.5.6'); diff --git a/packages/vercel-edge/src/launch.ts b/packages/vercel-edge/src/launch.ts index 62146df46..4244a744e 100644 --- a/packages/vercel-edge/src/launch.ts +++ b/packages/vercel-edge/src/launch.ts @@ -45,7 +45,7 @@ import { } from '@bugsee/core'; import { BugseeOption, type RuntimeType } from '@bugsee/protocol'; import { describeValue, reportGuarded } from '@bugsee/util'; -import { EDGE_APP_VERSION_HINT, edgeAppIdentity, warnToConsole } from './app-identity'; +import { createEdgeAppIdentity, EDGE_APP_VERSION_HINT, warnToConsole } from './app-identity'; import { createEdgeUnhandledRejectionProvider, type EdgeGlobalEvents } from './detection'; import { buildEdgeEnvironment } from './environment'; import { @@ -133,6 +133,12 @@ export interface BugseeEdgeLaunchOptions { appId?: string; appVersion?: string; appBuild?: string; + /** + * The host's bindings object (Cloudflare's per-deployment `env`), read for the app identity when + * `process.env` is empty: `BUGSEE_APP_VERSION` / `BUGSEE_APP_BUILD`, and a `CF_VERSION_METADATA` binding + * (its `tag` is the version, its `id` the build). Only those keys are read, once, at launch. + */ + bindings?: Record; /** Capture console output as logs. Default true. */ captureLogs?: boolean; @@ -285,7 +291,7 @@ export function launchEdge(appToken: string, options: BugseeEdgeLaunchOptions = const appIdentity = resolveAppIdentity( { version: options.appVersion, build: options.appBuild }, - [bundledAppIdentity, edgeAppIdentity], + [bundledAppIdentity, createEdgeAppIdentity(options.bindings)], warnToConsole, EDGE_APP_VERSION_HINT, ); From 33435adfc380d469a33097ed569140dc09ed4b9c Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 12:28:55 +0500 Subject: [PATCH 3/4] fix(core,capture,browser): traces cover the whole capture range in throttled/hidden tabs Add optional CaptureProvider.prepareSnapshot hook; traces provider carries held traces to the window start and re-records at the end (only when the refresh timer did not run), takes an on-demand heap sample. Report end is the end of the frozen capture (capped at assembly clock), report-time extras are clamped into the plan range. Raise webview bundle budget accordingly. Human guided, AI implemented --- docs/PROGRESS.md | 13 + .../src/trace-producers.process.test.ts | 33 ++ packages/browser/src/trace-producers.ts | 9 + .../src/system-traces-provider.test.ts | 287 ++++++++++++++++++ .../capture/src/system-traces-provider.ts | 111 ++++++- packages/capture/src/trace-producer.ts | 8 +- .../core/src/bundle-stream-assembler.test.ts | 158 +++++++++- packages/core/src/bundle-stream-assembler.ts | 39 ++- packages/core/src/capture-coordinator.test.ts | 76 +++++ packages/core/src/capture-coordinator.ts | 27 +- packages/core/src/client.test.ts | 128 +++++++- packages/core/src/client.ts | 21 +- packages/core/src/contracts.ts | 15 + packages/core/src/index.ts | 1 + .../test/webview-bundle.e2e.ts | 8 +- 15 files changed, 907 insertions(+), 27 deletions(-) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 7e9c5aa9d..6fcb9eec1 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -8,6 +8,13 @@ Read this first; then `docs/design/sdk-design.md` (Draft v3) for the full archit --- +## 2026-11-23 — system traces: honest window for throttled/frozen tabs and report dialogs +Sweep of the 14 open BWD reports: traces often started mid-window or stopped early. Two causes. (1) Every late-start report had `app_state=background` at report time: a hidden tab stops rAF (fps) and throttles/freezes timers, so neither the 1 Hz polls nor the held-value refresh ran, the store evicted what had been written before the window, and the window head was empty (BWD-13/2/4/7/10/6; BWD-11 = iOS page frozen after 6 s). (2) `code_dialog` reports (BWD-15): the capture is frozen when the dialog OPENS but `manifest.time.end` was the assembly clock at Send, so the range had a 7 s empty tail. +Fix: `CaptureProvider.prepareSnapshot(window)` (optional, core contract) + `CaptureCoordinator.prepareSnapshot` (isolated like start/stop), invoked by the client right before a report snapshot (`openCapture`, window = resolved `Duration`). `SystemTracesProvider` implements it: each producer may `sampleNow()` (browser `MemoryProducer` reads `performance.memory`, still readable when hidden); every HELD trace is re-recorded at the window end ONLY when its last row is at least `refreshMs` old (the refresh timer evidently did not run; a healthy page has a row within `refreshMs` and a twin a few ms before the end was an Electron-integration flake) and carried to the window start with the value in force there (per-trace change history, capped at 64). The carried values are RETURNED from the hook and ride along as report-time extras (`openCapture` merges them), not written: the store trims by a range read from its own clock, which can sit a ms past the window start and would drop a seed stamped exactly there. Polled values (fps, lag) are never carried — a hidden tab's fps stays an honest gap. `bundle-stream-assembler` ends the manifest AND the stream encoders' session (replay/video) at the snapshot range end (never before the newest streamed record, never past the assembly clock; report-time extras don't count). Report-time extras of a non-encoder type that predate the planned start (a carried seed stamped a ms before the store's own range) are copied and clamped up to `plan.start`, payload `timestamp` included, because the viewer drops events before the manifest start. Late-tick catch-up (held refresh on the first tick after a throttled sleep) already existed and is now pinned by a test. Tests: provider, coordinator, client, assembler, browser producer + a coordinator→exporter integration test; mutator loop run (survivors are memory-only/equivalent: stopped-guard, young-session guard, history prune/dedupe/cap). + +## 2026-11-23 — replay: inline `` no longer blocked by default +BWD production reports showed every `` as an empty box: `MEDIA_SELECTOR` contained `svg`, and `blockAllMedia` (default on) turned each into a size-only placeholder (verified in a real BWD-15 snapshot: all svg nodes childless, only `rr_width`/`rr_height`). `svg` is removed from `MEDIA_SELECTOR` (`packages/replay/src/masking.ts`); the raster-bearing `` stays blocked (rrweb tests the selector per element), svg `` follows the normal text-masking rules, and `blockAllMedia` for img/video/iframe/etc is unchanged. Tests: `masking.test.ts` + `masking.integration.test.ts` (svg recorded at defaults, `` data URI absent). Not verified: the viewer-side replayer (`createElementNS`/`xlink:href`/``) lives outside this repo. + ## 1. What's implemented ### Tier-0 (foundations — no Bugsee dependencies, pure libs) @@ -1528,3 +1535,9 @@ Verified against current majors, all green with no adapter code changes: `@bugse `launch(undefined)` on Node/Bun died with an opaque `TypeError ... reading 'length'` inside `hashAppToken`, crashing the host at startup. Every runtime composition root (`@bugsee/node` + bun, `@bugsee/electron` `launchMain`/`launchRenderer` (guard before any wiring; a bad-token renderer sends no hello and takes no page slot), `@bugsee/browser` + umbrella/electron-renderer, `@bugsee/vercel-edge` + cloudflare, `@bugsee/webworker`) now calls the shared `createDisabledClientForMissingToken` (`@bugsee/core` `app-token.ts`) first: a missing / empty / whitespace-only / non-string token reports ONE `Bugsee: the app token is missing ...` error through `onError` (else `console.warn`) and returns a DISABLED client (never started, `launch()` is a no-op, claims no carrier slot, so a later valid launch works; the browser one resolves it, `showReportDialog()` resolves `null`). `@bugsee/webview` is untouched (the native host owns the token; the JS side never uses it on the wire). Tests: `app-token.test.ts` + `launch-missing-token.test.ts` per entry. **Follow-up 2 (issue #11).** `sveltekit-e2e` now wires `sveltekit({ preprocess: [componentAnnotatePreprocessor()] })` (the `@bugsee/sveltekit` README Kit 3 call, with the plugin imported by path) and asserts the SSR HTML carries `data-bugsee-component` (mutation-checked: removing `preprocess` fails it). The plugin is imported from its built dist (the e2e builds it first) because Kit 3 re-loads `vite.config.ts` in a plain-Node post-build process that cannot resolve the workspace's extensionless TS source. The README nits were already fixed (#157). Only Rollup 5 (still prerelease, `5.0.0-2` on the `beta` tag) remains open: keep watching. + +### App version/build auto-detection gaps (2026-11-23) +**Finding.** `environment.app.version` read `0.0.0` on the BWD dashboard (Angular, esbuild builder, no Bugsee plugin): the browser has no runtime source for the version (no package.json, no env), so it needs a build-time `define` of `__BUGSEE_APP_VERSION__`/`__BUGSEE_APP_BUILD__`. Every other runtime already detected it (core `resolveAppIdentity`; node/bun/electron: `BUGSEE_APP_VERSION`, nearest package.json, Electron `app.getVersion()`; edge: env vars). +**Added.** (1) Node/Bun: when the cwd search finds no version (container `WORKDIR /`, service-manager cwd), the entry script's directory (`Bun.main`, else `process.argv[1]`) is searched next (`entryPoint` seam on `createNodeAppIdentitySource`; never overrides `appRoot` or a cwd hit). (2) Edge/Cloudflare: new `bindings` launch option + `createEdgeAppIdentity(bindings)` reads `BUGSEE_APP_VERSION`/`BUGSEE_APP_BUILD` from the Workers `env` and a `CF_VERSION_METADATA` binding (`tag` = version, `id` = build) since workerd `process.env` is often empty. (3) Browser README: Angular `define` recipe. +**Deliberately not added.** `npm_package_version` (node doc comment: inherited by child processes, wrong in workspaces); generic `` / PWA manifest guessing (false positives); Angular's `ng-version` (framework version, not the app's). +**Still manual.** Browser and Web/Service Workers without a bundler define or `appVersion`; Cloudflare needs `bindings: env` (or a `BUGSEE_APP_VERSION` var) passed to `launch()`. diff --git a/packages/browser/src/trace-producers.process.test.ts b/packages/browser/src/trace-producers.process.test.ts index a156f5c95..285d207de 100644 --- a/packages/browser/src/trace-producers.process.test.ts +++ b/packages/browser/src/trace-producers.process.test.ts @@ -385,6 +385,39 @@ describe('createBrowserSystemTraceProducers: process traces', () => { } }); + it('the memory producer takes a fresh heap reading on demand (a hidden tab ran no poll) and never invents one', () => { + const memoryInfo = { usedJSHeapSize: 10, totalJSHeapSize: 20, jsHeapSizeLimit: 100 }; + const win = Object.assign(mkTarget(), { performance: { memory: memoryInfo, now: () => 1 } }); + try { + const memory = createBrowserSystemTraceProducers({ + ...browserTraceEnvFrom(win, undefined), + window: win, + }).find((p) => p.name === 'memory') as TraceProducer; + const out = start(memory); + out.length = 0; // the baseline + memoryInfo.usedJSHeapSize = 40; + memory.sampleNow?.(); + expect(out.map((r) => [r.name, r.value])).toEqual([ + ['ram_js_heap_total', 100], + ['ram_js_heap_free', 60], + ['ram_js_heap_used', 40], + ]); + expect(out.every((r) => r.hold === false)).toBe(true); // polled, never held + memory.stop(); + out.length = 0; + memory.sampleNow?.(); // stopped: nothing is written + expect(out).toEqual([]); + // an engine with no reading (Safari/Firefox) emits nothing + (win.performance as { memory?: unknown }).memory = undefined; + const again = start(memory); + again.length = 0; + memory.sampleNow?.(); + expect(again).toEqual([]); + } finally { + resetProcessTracker({ window: win }); + } + }); + it('all process traces share ONE tracker per window and the env seams reach it (idle + user idle)', async () => { const win = Object.assign(mkTarget(), { performance: { diff --git a/packages/browser/src/trace-producers.ts b/packages/browser/src/trace-producers.ts index 27853c4ee..60210e600 100644 --- a/packages/browser/src/trace-producers.ts +++ b/packages/browser/src/trace-producers.ts @@ -171,6 +171,15 @@ export class MemoryProducer extends TraceProducerBase { this.#off = undefined; } + /** + * One live reading on demand, right before a report snapshot: a hidden tab throttles (or freezes) the tracker's polling + * timer, but `performance.memory` stays readable, so the report still ends with a real sample. No reading, no emit. + */ + sampleNow(): void { + const cur = this.#tracker.currentHeap(); + if (cur !== undefined) this.#publish(cur); + } + #publish(m: HeapState): void { this.poll(() => { this.emit(TraceName.RAM_JS_HEAP_TOTAL, m.limit); diff --git a/packages/capture/src/system-traces-provider.test.ts b/packages/capture/src/system-traces-provider.test.ts index ef4fc0af1..5248b6d7d 100644 --- a/packages/capture/src/system-traces-provider.test.ts +++ b/packages/capture/src/system-traces-provider.test.ts @@ -1,4 +1,5 @@ import { + type CaptureDataEntry, type CaptureProviderInit, type CaptureStore, createCaptureAggregator, @@ -1274,3 +1275,289 @@ describe('withoutTraceNames', () => { ]); }); }); + +// A producer driven by hand: `set` is a change-driven (held) value, `read` a polled one; `sampleNow` takes a fresh reading. +class Manual extends TraceProducerBase { + readonly name = 'manual'; + samples = 0; + failSample = false; + protected onStart(): void {} + set(name: string, value: unknown): void { + this.emitIfChanged(name as TraceName, value); + } + read(name: string, value: unknown): void { + this.emit(name as TraceName, value); + } + sampleNow(): void { + this.samples += 1; + if (this.failSample) throw new Error('sample failed'); + this.read('heap', this.samples); + } +} + +describe('createSystemTracesProvider — prepareSnapshot (a throttled or frozen runtime)', () => { + type Win = { start: number; end: number }; + type Row = { timestamp: number; name: string; value: unknown; displayId?: number }; + const rig = (extra: Partial[0]> = {}) => { + const store = mkStore(); + const fs = fakeScheduler(); + const clock = { t: 0 }; + const producer = new Manual(); + const errors: unknown[] = []; + const provider = createSystemTracesProvider({ + producers: [producer], + scheduler: fs.scheduler, + now: () => clock.t, + refreshMs: 10_000, + onError: (e) => errors.push(e), + ...extra, + }); + provider.init(buildInit(store)); + return { store, fs, clock, producer, provider, errors }; + }; + const rows = async (store: CaptureStore): Promise => + ((await drainSystem(store)) ?? []).map((e) => e.data as Row); + // The seeds are RETURNED (report-time extras), never written to the store. + const prepare = (provider: ReturnType, w: Win): Row[] => + ( + ( + provider as { prepareSnapshot?: (w: Win) => CaptureDataEntry[] | undefined } + ).prepareSnapshot?.(w) ?? [] + ).map((e) => { + expect(e.type).toBe('traces.system'); + expect(e.timestamp).toBe((e.data as Row).timestamp); + return e.data as Row; + }); + + it('carries a held value that predates the window to the window start (frozen tab: the refresh never ran)', async () => { + const r = rig(); + r.clock.t = 1_000; + r.provider.start(options); + r.producer.set('app_state', 'foreground'); + const seeds = prepare(r.provider, { start: 50_000, end: 110_000 }); + expect(seeds).toEqual([{ timestamp: 50_000, name: 'app_state', value: 'foreground' }]); + expect((await rows(r.store)).filter((x) => x.timestamp === 50_000)).toEqual([]); // returned, not written + }); + + it('keeps a display id on the carried value', () => { + const r = rig(); + const display = new Fixed('d', [['displays', { w: 1 }, 7]], { held: true }); + const p = createSystemTracesProvider({ + producers: [display], + scheduler: r.fs.scheduler, + now: () => 1_000, + }); + p.init(buildInit(r.store)); + p.start(options); + expect(prepare(p, { start: 50_000, end: 110_000 })).toEqual([ + { timestamp: 50_000, name: 'displays', value: { w: 1 }, displayId: 7 }, + ]); + }); + + it('seeds the value in force at the window start, not the latest one', () => { + const r = rig(); + r.clock.t = 1_000; + r.provider.start(options); + r.producer.set('app_state', 'foreground'); + r.clock.t = 20_000; + r.producer.set('app_state', 'background'); // before the window start + r.clock.t = 70_000; + r.producer.set('app_state', 'foreground'); // inside the window + expect(prepare(r.provider, { start: 50_000, end: 110_000 })).toEqual([ + { timestamp: 50_000, name: 'app_state', value: 'background' }, + ]); + }); + + it('does not seed a value whose first record is inside the window (a session younger than the window)', () => { + const r = rig(); + r.clock.t = 60_000; + r.provider.start(options); + r.producer.set('app_state', 'foreground'); + expect(prepare(r.provider, { start: 50_000, end: 110_000 })).toEqual([]); + }); + + it('a change recorded exactly at the window start is the value in force there (no older value is seeded)', () => { + const r = rig(); + r.clock.t = 1_000; + r.provider.start(options); + r.producer.set('app_state', 'background'); + r.clock.t = 50_000; + r.producer.set('app_state', 'foreground'); + expect(prepare(r.provider, { start: 50_000, end: 110_000 })).toEqual([]); + }); + + it('re-records every held value at the window end, with its last value', async () => { + const r = rig(); + r.clock.t = 1_000; + r.provider.start(options); + r.producer.set('connection', { type: 'wifi' }); + prepare(r.provider, { start: 50_000, end: 110_000 }); + const end = (await rows(r.store)).filter( + (x) => x.timestamp === 110_000 && x.name === 'connection', + ); + expect(end).toEqual([{ timestamp: 110_000, name: 'connection', value: { type: 'wifi' } }]); + }); + + it('does not re-record a held value whose last row is younger than the refresh interval (a healthy page needs no end row)', async () => { + const r = rig(); // refreshMs 10_000 + r.clock.t = 101_000; + r.provider.start(options); + r.producer.set('connection', 'x'); + prepare(r.provider, { start: 50_000, end: 110_000 }); // 9 s old: the refresh would not have fired yet + expect((await rows(r.store)).filter((x) => x.name === 'connection')).toHaveLength(1); + r.clock.t = 101_000; + prepare(r.provider, { start: 50_000, end: 111_000 }); // exactly refreshMs old: due + expect( + (await rows(r.store)).filter((x) => x.name === 'connection' && x.timestamp === 111_000), + ).toHaveLength(1); + }); + + it('does not re-record a held value that was just recorded at the window end', async () => { + const r = rig(); + r.clock.t = 110_000; + r.provider.start(options); + r.producer.set('connection', 'x'); + prepare(r.provider, { start: 50_000, end: 110_000 }); + expect((await rows(r.store)).filter((x) => x.name === 'connection')).toHaveLength(1); + }); + + it('asks each producer for a fresh polled reading, and isolates a failing one', async () => { + const r = rig(); + r.clock.t = 110_000; + r.provider.start(options); + prepare(r.provider, { start: 50_000, end: 110_000 }); + expect(r.producer.samples).toBe(1); + expect((await rows(r.store)).filter((x) => x.name === 'heap')).toEqual([ + { timestamp: 110_000, name: 'heap', value: 1 }, + ]); + r.producer.failSample = true; + prepare(r.provider, { start: 50_000, end: 110_000 }); + expect(r.errors).toHaveLength(1); + }); + + it('never fabricates a polled value: a polled trace is not carried or re-recorded', async () => { + const r = rig(); + r.clock.t = 1_000; + r.provider.start(options); + r.producer.read('fps', 60); + expect(prepare(r.provider, { start: 50_000, end: 110_000 })).toEqual([]); + expect((await rows(r.store)).filter((x) => x.name === 'fps')).toHaveLength(1); + }); + + it('does nothing when the provider is stopped, and for a producer without the hook', async () => { + const r = rig(); + r.clock.t = 1_000; + r.provider.start(options); + r.producer.set('app_state', 'foreground'); + r.provider.stop(); + const before = (await rows(r.store)).length; + expect(prepare(r.provider, { start: 50_000, end: 110_000 })).toEqual([]); + expect((await rows(r.store)).length).toBe(before); + const plain = createSystemTracesProvider({ + producers: [new Fixed('f', [])], + scheduler: fakeScheduler().scheduler, + }); + plain.init(buildInit(mkStore())); + plain.start(options); + expect(prepare(plain, { start: 0, end: 1 })).toEqual([]); + }); + + it('writes neither the seed nor the end refresh for a name the host owns (suppressed)', async () => { + const suppression = createTraceSuppression({ host: ['app_state'] }); + const r = rig({ suppression }); + r.clock.t = 1_000; + r.provider.start(options); + r.producer.set('app_state', 'foreground'); + expect(prepare(r.provider, { start: 50_000, end: 110_000 })).toEqual([]); + expect((await rows(r.store)).filter((x) => x.name === 'app_state')).toEqual([]); + }); + + it('a flapping value keeps at most 64 changes: the seed cannot reach back past them', () => { + const r = rig(); + r.clock.t = 0; + r.provider.start(options); + for (let i = 1; i <= 100; i += 1) { + r.clock.t = i * 10; + r.producer.set('app_state', `v${i}`); + } + // 100 changes at t=10..1000; only the newest 64 (t=370..1000) are kept, so a window starting at 305 has no value in + // force to carry (asked first: choosing a base prunes what is older)… + expect(prepare(r.provider, { start: 305, end: 2_000 })).toEqual([]); + // …while change 37 (t=370) is the oldest still held, in force at 375. + expect(prepare(r.provider, { start: 375, end: 2_000 })).toEqual([ + { timestamp: 375, name: 'app_state', value: 'v37' }, + ]); + }); + + it('re-recording an unchanged value does not add to the history (refreshes must not evict the real base)', () => { + const r = rig(); + r.clock.t = 1; + r.provider.start(options); + r.producer.set('app_state', 'foreground'); + for (let i = 1; i <= 100; i += 1) { + r.clock.t = 1 + i * 10_000; // each tick finds the held value stale and re-records it + r.fs.tick(); + } + expect(prepare(r.provider, { start: 50_000, end: 2_000_000 })).toEqual([ + { timestamp: 50_000, name: 'app_state', value: 'foreground' }, + ]); + }); + + it('drops history that can no longer be in force once a base is chosen', () => { + const r = rig(); + r.clock.t = 1_000; + r.provider.start(options); + r.producer.set('app_state', 'a'); + r.clock.t = 2_000; + r.producer.set('app_state', 'b'); + r.clock.t = 3_000; + r.producer.set('app_state', 'c'); + expect(prepare(r.provider, { start: 2_500, end: 9_000 })).toEqual([ + { timestamp: 2_500, name: 'app_state', value: 'b' }, + ]); + // 'a' was pruned with the first report, so an (impossible) earlier window finds nothing rather than a stale value + expect(prepare(r.provider, { start: 1_500, end: 9_000 })).toEqual([]); + }); + + it('a late tick (timers were throttled) re-records the stale held values at once', async () => { + const r = rig(); + r.clock.t = 1_000; + r.provider.start(options); + r.producer.set('connection', 'x'); + r.clock.t = 200_000; // the tab slept; the first tick after the wake-up + r.fs.tick(); + expect( + (await rows(r.store)).filter((x) => x.name === 'connection' && x.timestamp === 200_000), + ).toHaveLength(1); + }); +}); + +describe('createSystemTracesProvider — through the real coordinator and exporter', () => { + it('a window prepared by the coordinator yields the carried seed as an extra and the end refresh in the store', async () => { + const store = mkStore(); + const coordinator = createCaptureCoordinator(buildInit(store)); + const producer = new Manual(); + let t = 1_000; + coordinator.addProvider( + createSystemTracesProvider({ + producers: [producer], + scheduler: fakeScheduler().scheduler, + now: () => t, + }), + ); + coordinator.start(options, () => true); + producer.set('app_state', 'background'); + t = 120_000; // the tab was frozen the whole time; the report wakes it + const extras = coordinator.prepareSnapshot({ start: 60_000, end: 120_000 }); + expect(extras.map((e) => [e.type, e.timestamp, (e.data as { name: string }).name])).toEqual([ + ['traces.system', 60_000, 'app_state'], + ]); + const exported = ((await drainSystem(store)) ?? []).map( + (e) => e.data as { timestamp: number; name: string }, + ); + expect(exported.filter((e) => e.name === 'app_state').map((e) => e.timestamp)).toEqual([ + 1_000, 120_000, + ]); + expect(exported.some((e) => e.name === 'heap' && e.timestamp === 120_000)).toBe(true); + }); +}); diff --git a/packages/capture/src/system-traces-provider.ts b/packages/capture/src/system-traces-provider.ts index fa3115558..0abb749df 100644 --- a/packages/capture/src/system-traces-provider.ts +++ b/packages/capture/src/system-traces-provider.ts @@ -1,6 +1,13 @@ -import { type CaptureProvider, CaptureProviderBase, type Scheduler } from '@bugsee/core'; +import { + type CaptureDataEntry, + CaptureDataEntryBase, + type CaptureProvider, + CaptureProviderBase, + type Scheduler, + type SnapshotWindow, +} from '@bugsee/core'; import { BugseeOption } from '@bugsee/protocol'; -import type { TraceProducer, TraceSink } from './trace-producer'; +import { sameValue, type TraceProducer, type TraceSink } from './trace-producer'; import type { TraceSuppression } from './trace-suppression'; // Runtime-agnostic SYSTEM TRACES provider (Android traces.system parity). A trace is a @@ -92,6 +99,16 @@ interface Held { displayId: number | undefined; } +/** The CHANGES of one held trace (oldest first): what lets a report window start with the value that was in force. */ +interface HeldHistory { + name: string; + displayId: number | undefined; + changes: Array<{ timestamp: number; value: unknown }>; +} + +/** A flapping held value keeps at most this many changes; older ones fall off (the seed then simply cannot reach back that far). */ +const MAX_HISTORY = 64; + /** * Which running provider owns a producer instance. Producers are stateful (`start()` is a no-op while started, held * values live on the instance), so one instance driven by two providers would interleave start/stop. First owner wins; @@ -116,6 +133,7 @@ class SystemTracesProvider extends CaptureProviderBase { readonly #suppression: TraceSuppression | undefined; #offSuppression: (() => void) | undefined; readonly #held = new Map(); + readonly #history = new Map(); #started: TraceProducer[] = []; #running = false; #timer: unknown = null; @@ -151,6 +169,7 @@ class SystemTracesProvider extends CaptureProviderBase { protected onStart(): void { this.#held.clear(); + this.#history.clear(); this.#running = true; this.#offSuppression = this.#suppression?.subscribe((released) => this.#rerecord(released)); for (const producer of this.#producers) { @@ -200,7 +219,63 @@ class SystemTracesProvider extends CaptureProviderBase { this.#stopProducers(); this.#running = false; this.#held.clear(); + this.#history.clear(); + } + } + + /** + * A report snapshot is about to freeze `window` (CaptureProvider.prepareSnapshot). In a throttled / frozen / hidden runtime + * neither the producers' polls nor the held-value refresh ran, and the store has long evicted what they wrote before, so + * the window's head (and tail) would be empty and every trace would appear to start mid-way. So, honestly: + * - each producer takes one fresh reading (a hidden tab's heap is still readable; fps, derived from frames, is not and + * stays a gap); + * - every HELD (state) trace is carried to the window start with the value that was in force there, and re-recorded at + * the window end with its last value. A polled value is never carried or refreshed: that would fabricate a flat line. + */ + prepareSnapshot(window: SnapshotWindow): CaptureDataEntry[] { + if (!this.#running) return []; + for (const producer of this.#started) { + try { + producer.sampleNow?.(); + } catch (error) { + this.#onError(error); + } } + // The carried values are RETURNED, not written: the store trims by a range it reads from its own clock (possibly a + // millisecond after `window.start`), which would drop a seed stamped exactly at the window start. Returned entries ride + // along with the report untrimmed. + const seeds: CaptureDataEntry[] = []; + for (const history of this.#history.values()) { + const { changes } = history; + let inForce = -1; + while ( + inForce + 1 < changes.length && + (changes[inForce + 1] as { timestamp: number }).timestamp <= window.start + ) { + inForce += 1; + } + if (inForce < 0) continue; // first recorded inside the window (a young session): nothing predates it + const base = changes[inForce] as { timestamp: number; value: unknown }; + changes.splice(0, inForce); // older changes can never be in force again; the base stays for the next report + if (base.timestamp < window.start && !this.#suppression?.has(history.name)) { + seeds.push( + new CaptureDataEntryBase('traces.system', window.start, { + timestamp: window.start, + name: history.name, + value: base.value, + ...(history.displayId !== undefined ? { displayId: history.displayId } : {}), + }), + ); + } + } + for (const held of [...this.#held.values()]) { + // Only a value the refresh timer would already have re-recorded (older than `refreshMs`, i.e. the timer did not run): a + // healthy page keeps a row within `refreshMs` of any instant, and a row a few ms before the end is not worth a twin. + if (window.end - held.timestamp >= this.#refreshMs) { + this.#record(held.name, held.value, held.displayId, window.end, true); + } + } + return seeds; } #tick(): void { @@ -236,20 +311,30 @@ class SystemTracesProvider extends CaptureProviderBase { timestamp: number, hold: boolean, ): void { - if (!this.#suppression?.has(name)) { - this.capture('traces.system', timestamp, { - timestamp, - name, - value, - ...(displayId !== undefined ? { displayId } : {}), - }); - } + this.#write(name, value, displayId, timestamp); if (!hold) return; - this.#held.set(displayId === undefined ? name : `${displayId}:${name}`, { + const key = displayId === undefined ? name : `${displayId}:${name}`; + this.#held.set(key, { name, value, timestamp, displayId }); + let history = this.#history.get(key); + if (history === undefined) { + history = { name, displayId, changes: [] }; + this.#history.set(key, history); + } + const last = history.changes.at(-1); + if (last === undefined || !sameValue(last.value, value)) { + history.changes.push({ timestamp, value }); + if (history.changes.length > MAX_HISTORY) history.changes.shift(); + } + } + + /** Write one entry (unless the name is suppressed) without touching the held / history state. */ + #write(name: string, value: unknown, displayId: number | undefined, timestamp: number): void { + if (this.#suppression?.has(name)) return; + this.capture('traces.system', timestamp, { + timestamp, name, value, - timestamp, - displayId, + ...(displayId !== undefined ? { displayId } : {}), }); } diff --git a/packages/capture/src/trace-producer.ts b/packages/capture/src/trace-producer.ts index 0dca6957a..d79c57e96 100644 --- a/packages/capture/src/trace-producer.ts +++ b/packages/capture/src/trace-producer.ts @@ -42,6 +42,12 @@ export interface TraceProducer { start(sink: TraceSink): void; /** Unsubscribe from everything start() attached. Idempotent; a no-op before start(). */ stop(): void; + /** + * Optional: take ONE fresh reading of the polled values NOW and emit it. The provider calls it right before a report + * snapshot, so a runtime whose timers were throttled or frozen (a hidden browser tab) still has a sample at the report's + * end. Never fabricate: a producer with nothing readable emits nothing. + */ + sampleNow?(): void; } // BigInt has no JSON form: tag it so it compares by value and is distinct from a string @@ -50,7 +56,7 @@ const bigintSafe = (_key: string, v: unknown): unknown => typeof v === 'bigint' ? { $bigint: v.toString() } : v; /** Total: never throws. An uncomparable value (circular, throwing toJSON) counts as CHANGED. */ -const sameValue = (a: unknown, b: unknown): boolean => { +export const sameValue = (a: unknown, b: unknown): boolean => { if (Object.is(a, b)) return true; if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) return false; try { diff --git a/packages/core/src/bundle-stream-assembler.test.ts b/packages/core/src/bundle-stream-assembler.test.ts index fe7a25003..cba58470c 100644 --- a/packages/core/src/bundle-stream-assembler.test.ts +++ b/packages/core/src/bundle-stream-assembler.test.ts @@ -426,11 +426,45 @@ describe('assembleBundleStream — time plan', () => { expect(manifestOf(files).time).toEqual({ start: NOW - 5000, end: NOW }); }); - it('ends the manifest time at the trigger moment (the clock), not the snapshot range end', async () => { - const files = await run([], { start: NOW - 5000, end: NOW - 10 }); + it('ends the manifest time at the snapshot range end, not the (later) assembly clock', async () => { + // A report dialog freezes the capture when it OPENS; assembly runs when Send is pressed, seconds later. The data stops at + // the freeze, so the range must too (an end at the clock painted an empty tail on every trace). + const files = await run([], { start: NOW - 5000, end: NOW - 7000 }); + expect(manifestOf(files).time.end).toBe(NOW - 7000); + }); + + it('never ends the manifest time before the newest streamed record', async () => { + const files = await run([entry('log', NOW - 6990, 'late')], { + start: NOW - 5000, + end: NOW - 7000, + }); + expect(manifestOf(files).time.end).toBe(NOW - 6990); + }); + + it('never ends the manifest after the assembly clock, even for a future-stamped streamed record', async () => { + const files = await run([entry('log', NOW + 60_000, 'future')], { + start: NOW - 5000, + end: NOW - 10, + }); + expect(manifestOf(files).time.end).toBe(NOW); + }); + + it('caps a snapshot range end that lies past the assembly clock', async () => { + const files = await run([], { start: NOW - 5000, end: NOW + 500 }); expect(manifestOf(files).time.end).toBe(NOW); }); + it('does not let a report-time extra (taken at the clock) stretch the planned end', async () => { + const request = createReportingRequest({ source: { type: 'error' }, id: 'r1' }); + const bundle = await assembleBundleStream( + request, + withRange([], { start: NOW - 5000, end: NOW - 7000 }), + context(), + new Map([['log', [entry('log', NOW, 'extra')]]]), + ); + expect(manifestOf(members(await bundle.body.bytes())).time.end).toBe(NOW - 7000); + }); + it('drops non-replay records older than the plan start and keeps those at or after it', async () => { const files = await run( [ @@ -498,6 +532,112 @@ describe('assembleBundleStream — time plan', () => { expect(manifestOf(files).time.start).toBe(NOW - 5000); }); + describe('report-time extras that predate the planned start are clamped up to it', () => { + const planned = async ( + extras: CaptureDataEntry[], + range: { start: number; end: number } | undefined, + over: Partial = {}, + ) => { + const request = createReportingRequest({ source: { type: 'error' }, id: 'r1' }); + const bundle = await assembleBundleStream( + request, + withRange([], range), + context(over), + new Map([[extras[0]?.type as FileType, extras]]), + ); + return members(await bundle.body.bytes()); + }; + const seed = (timestamp: number) => + entry('traces.system', timestamp, { timestamp, name: 'app_state', value: 'background' }); + + it('re-stamps the entry AND the payload timestamp (the viewer filters on the payload) to the plan start', async () => { + const files = await planned([seed(NOW - 5001)], { start: NOW - 5000, end: NOW }); + expect(JSON.parse(strFromU8(files['traces.system.json'] as Uint8Array))).toEqual([ + { timestamp: NOW - 5000, name: 'app_state', value: 'background' }, + ]); + }); + + it('leaves an extra at or after the plan start untouched', async () => { + const files = await planned([seed(NOW - 5000), seed(NOW - 10)], { + start: NOW - 5000, + end: NOW, + }); + const rows = JSON.parse(strFromU8(files['traces.system.json'] as Uint8Array)) as Array<{ + timestamp: number; + }>; + expect(rows.map((r) => r.timestamp)).toEqual([NOW - 5000, NOW - 10]); + }); + + it('keeps a payload whose own timestamp differs from the entry time, and a non-object payload', async () => { + const odd = entry('traces.system', NOW - 9000, { timestamp: 5, name: 'x' }); + const plain = entry('events.user', NOW - 9000, 'plain'); + const f1 = await planned([odd], { start: NOW - 5000, end: NOW }); + expect(JSON.parse(strFromU8(f1['traces.system.json'] as Uint8Array))).toEqual([ + { timestamp: 5, name: 'x' }, + ]); + const f2 = await planned([plain], { start: NOW - 5000, end: NOW }); + expect(JSON.parse(strFromU8(f2['events.user.json'] as Uint8Array))).toEqual(['plain']); + }); + + it('leaves an extra of an encoder-owned type as it is (a file encoder and a stream encoder clamp for themselves)', async () => { + const old = NOW - 9000; + const filePayloads: unknown[] = []; + await planned( + [entry('replay', old, { timestamp: old })], + { start: NOW - 5000, end: NOW }, + { + fileEncoders: { + replay: (payloads) => { + filePayloads.push(...payloads); + return new Uint8Array([1]); + }, + }, + }, + ); + expect(filePayloads).toEqual([{ timestamp: old }]); + const streamed: number[] = []; + await planned( + [entry('replay', old, { timestamp: old })], + { start: NOW - 5000, end: NOW }, + { + streamEncoders: { + replay: { + begin: () => ({ + write: (e) => { + streamed.push(e.timestamp); + return []; + }, + end: () => [], + }), + }, + }, + }, + ); + expect(streamed).toEqual([old]); + }); + + it('does not clamp without a plan, nor a type an encoder owns', async () => { + const f1 = await planned([seed(NOW - 9000)], undefined); + expect(JSON.parse(strFromU8(f1['traces.system.json'] as Uint8Array))).toEqual([ + { timestamp: NOW - 9000, name: 'app_state', value: 'background' }, + ]); + const seen: unknown[][] = []; + await planned( + [entry('replay', NOW - 9000, 'r')], + { start: NOW - 5000, end: NOW }, + { + fileEncoders: { + replay: (payloads) => { + seen.push(payloads); + return new Uint8Array([1]); + }, + }, + }, + ); + expect(seen).toEqual([['r']]); + }); + }); + it('end to end: a real chunk store, through the exporter, bounds the manifest and trims old logs', async () => { let now = NOW - 20_000; const clock = { wallNow: () => now, monotonicNow: () => 0 }; @@ -586,6 +726,16 @@ describe('assembleBundleStream — time plan', () => { expect(mf(files).files.map((f) => f.filename)).toContain('replay.bin'); }); + it('begins the session at the snapshot range end (matching manifest.time.end), not the later assembly clock', async () => { + const { encoder, plans } = recorder(); + await runEnc( + [entry('replay', NOW2 - 9000, 'a')], + { start: NOW2 - 15_000, end: NOW2 - 7000 }, + { streamEncoders: { replay: encoder } }, + ); + expect(plans).toEqual([{ start: NOW2 - 15_000, end: NOW2 - 7000 }]); + }); + it('begins the session with an absent start when the source states no range', async () => { const { encoder, plans } = recorder(); await runEnc([entry('replay', NOW2 - 100, 'a')], undefined, { @@ -783,11 +933,11 @@ describe('assembleBundleStream — time plan', () => { expect(closed).toBe(true); }); - it('passes the clock moment, not the snapshot range end, as plan.end', async () => { + it('caps the session end at the assembly clock when the snapshot range end lies past it', async () => { const { encoder, plans } = recorder(); await runEnc( [entry('replay', NOW2 - 100, 'a')], - { start: NOW2 - 5000, end: NOW2 - 77 }, + { start: NOW2 - 5000, end: NOW2 + 77 }, { streamEncoders: { replay: encoder }, }, diff --git a/packages/core/src/bundle-stream-assembler.ts b/packages/core/src/bundle-stream-assembler.ts index 521a7b162..291779c8f 100644 --- a/packages/core/src/bundle-stream-assembler.ts +++ b/packages/core/src/bundle-stream-assembler.ts @@ -223,6 +223,13 @@ async function buildInto( // With a plan the report starts where the plan says (the window), whatever the records are; without one, at the earliest // record. The plan also bounds the ROLLING records: older ones (the store keeps up to a second of slack) are dropped. let start = plan?.start ?? now; + // Where the report ends. Without a plan, the assembly clock. With one, the snapshot's own end: a report dialog freezes the + // capture when it OPENS and assembles when Send is pressed, and an end at the clock stretched every trace over an empty + // tail. A streamed record may still sit a few ms past the range end (clock skew), so the end never precedes the newest one; + // report-time extras are taken at the clock by design and do not count. Never past the assembly clock: an explicitly + // future-stamped record (client.trace(…, timestamp)) must not stretch the report into the future. + const planEnd = plan === undefined ? now : Math.min(plan.end, now); + let end = planEnd; const order: string[] = []; // member keys: a type, or `type\0lane` for one visual source of a stream-encoded type const streamed = new Map(); const collected = new Map(); // types with an injected encoder @@ -241,8 +248,34 @@ async function buildInto( member.file.push(chunk, false); } }; - const take = (entry: CaptureDataEntry, rolling: boolean): void => { + const take = (original: CaptureDataEntry, rolling: boolean): void => { + let entry = original; const type = entry.type; + if ( + !rolling && + plan !== undefined && + entry.timestamp < plan.start && + context.fileEncoders?.[type] === undefined && + context.streamEncoders?.[type] === undefined + ) { + // A report-time extra (e.g. a trace value carried to the window start) can be stamped a few ms before the range the + // store actually exported; the viewer drops events before the manifest start, so it is moved up to it. The payload's + // own timestamp (what the viewer reads) follows when it was the entry's. A copy: the caller's entry is not mutated. + const data = entry.data; + const restamped = + typeof data === 'object' && + data !== null && + (data as { timestamp?: unknown }).timestamp === entry.timestamp + ? { ...data, timestamp: plan.start } + : data; + entry = Object.assign(Object.create(Object.getPrototypeOf(entry)), entry, { + timestamp: plan.start, + data: restamped, + }) as CaptureDataEntry; + } + if (rolling && plan !== undefined && entry.timestamp > end) { + end = Math.min(entry.timestamp, now); + } if (plan === undefined) { if (entry.timestamp < start) { start = entry.timestamp; @@ -266,7 +299,7 @@ async function buildInto( encoded.set(key, { type, lane: entry.lane, - session: streamEncoder.begin({ start: plan?.start, end: now }), + session: streamEncoder.begin({ start: plan?.start, end: planEnd }), file: undefined, name: undefined, }); @@ -370,7 +403,7 @@ async function buildInto( addWhole(member.name, member.data); } files.push(...reportMembers.files); - addWhole(MANIFEST_JSON_FILENAME, JSON.stringify(buildManifest(context, start, now, files))); + addWhole(MANIFEST_JSON_FILENAME, JSON.stringify(buildManifest(context, start, end, files))); zip.end(); await done.promise; await queue.settle(); diff --git a/packages/core/src/capture-coordinator.test.ts b/packages/core/src/capture-coordinator.test.ts index 32797882a..ace46125d 100644 --- a/packages/core/src/capture-coordinator.test.ts +++ b/packages/core/src/capture-coordinator.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from 'vitest'; import { createCaptureCoordinator } from './capture-coordinator'; +import { CaptureDataEntryBase } from './capture-data-entry'; import type { CaptureProvider, CaptureProviderInit, OptionsContainer } from './contracts'; import { createOptionsContainer } from './options'; @@ -359,3 +360,78 @@ describe('createCaptureCoordinator — re-entrant reporters cannot corrupt a ses expect(b.stop).toHaveBeenCalledTimes(2); // the relaunched session is still tracked and stops normally }); }); + +describe('createCaptureCoordinator — prepareSnapshot', () => { + const window = { start: 100, end: 160 }; + + it('hands the window to every STARTED provider that implements prepareSnapshot', () => { + const co = createCaptureCoordinator(init); + const a = { ...makeProvider('a'), prepareSnapshot: vi.fn() }; + const gatedOff = { ...makeProvider('b', 'captureNetwork'), prepareSnapshot: vi.fn() }; + const plain = makeProvider('c'); // no hook: skipped without error + co.addProvider(a); + co.addProvider(gatedOff); + co.addProvider(plain); + co.start(options, (option) => option !== 'captureNetwork'); + co.prepareSnapshot(window); + expect(a.prepareSnapshot).toHaveBeenCalledWith(window); + expect(gatedOff.prepareSnapshot).not.toHaveBeenCalled(); + }); + + it('returns the entries providers hand back (report-time extras), ignoring providers that return nothing', () => { + const co = createCaptureCoordinator(init); + const e1 = new CaptureDataEntryBase('traces.system', 1, { a: 1 }); + const e2 = new CaptureDataEntryBase('traces.system', 2, { a: 2 }); + co.addProvider({ ...makeProvider('a'), prepareSnapshot: () => [e1] }); + co.addProvider({ ...makeProvider('void'), prepareSnapshot: () => undefined }); + co.addProvider({ ...makeProvider('b'), prepareSnapshot: () => [e2] }); + co.addProvider(makeProvider('plain')); + co.start(options, enableAll); + expect(co.prepareSnapshot(window)).toEqual([e1, e2]); + }); + + it('does nothing before start and after stop', () => { + const co = createCaptureCoordinator(init); + const a = { ...makeProvider('a'), prepareSnapshot: vi.fn() }; + co.addProvider(a); + expect(co.prepareSnapshot(window)).toEqual([]); + co.start(options, enableAll); + co.stop(); + expect(co.prepareSnapshot(window)).toEqual([]); + expect(a.prepareSnapshot).not.toHaveBeenCalled(); + }); + + it('isolates a throwing provider: reported, the others still run', () => { + const onError = vi.fn(); + const co = createCaptureCoordinator(init, onError); + const boom = new Error('boom'); + const bad = { + ...makeProvider('bad'), + prepareSnapshot: vi.fn(() => { + throw boom; + }), + }; + const good = { ...makeProvider('good'), prepareSnapshot: vi.fn() }; + co.addProvider(bad); + co.addProvider(good); + co.start(options, enableAll); + co.prepareSnapshot(window); + expect(onError).toHaveBeenCalledWith(boom); + expect(good.prepareSnapshot).toHaveBeenCalledWith(window); + }); + + it('survives a throwing error reporter', () => { + const co = createCaptureCoordinator(init, () => { + throw new Error('reporter'); + }); + const bad = { + ...makeProvider('bad'), + prepareSnapshot: () => { + throw new Error('x'); + }, + }; + co.addProvider(bad); + co.start(options, enableAll); + expect(() => co.prepareSnapshot(window)).not.toThrow(); + }); +}); diff --git a/packages/core/src/capture-coordinator.ts b/packages/core/src/capture-coordinator.ts index c2649947c..995fd99f2 100644 --- a/packages/core/src/capture-coordinator.ts +++ b/packages/core/src/capture-coordinator.ts @@ -1,4 +1,10 @@ -import type { CaptureProvider, CaptureProviderInit, OptionsContainer } from './contracts'; +import type { + CaptureDataEntry, + CaptureProvider, + CaptureProviderInit, + OptionsContainer, + SnapshotWindow, +} from './contracts'; // Capture-provider lifecycle manager (Android BugseeCaptureCoordinator parity). Holds // the capture-pipeline init (hubs/operations/aggregator) and injects it into each provider ONCE at @@ -24,6 +30,12 @@ export interface CaptureCoordinator { start(options: OptionsContainer, isEnabled: OptionGate): void; /** Stop all started providers; idempotent. */ stop(): void; + /** + * Tell every started provider that a report snapshot over `window` is about to be taken (CaptureProvider.prepareSnapshot). + * Isolated like start/stop: a throwing provider is reported and never costs the others. Returns the report-time extras + * the providers handed back, in provider order. + */ + prepareSnapshot(window: SnapshotWindow): CaptureDataEntry[]; /** A copy of the registered providers. */ readonly providers: readonly CaptureProvider[]; } @@ -108,6 +120,19 @@ export function createCaptureCoordinator( } }, + prepareSnapshot(window: SnapshotWindow): CaptureDataEntry[] { + const extras: CaptureDataEntry[] = []; + for (const provider of [...started]) { + try { + const entries = provider.prepareSnapshot?.(window); + if (entries !== undefined) extras.push(...entries); + } catch (error) { + report(error); + } + } + return extras; + }, + stop(): void { // Detach the session first and report only AFTER every stop() has run: a reporter that relaunches would // otherwise have its fresh providers stopped by this (stale) loop. diff --git a/packages/core/src/client.test.ts b/packages/core/src/client.test.ts index 8cf0fd3b5..733b949ab 100644 --- a/packages/core/src/client.test.ts +++ b/packages/core/src/client.test.ts @@ -1,4 +1,4 @@ -import type { EnvironmentEnvelope, FileType } from '@bugsee/protocol'; +import { BugseeOption, type EnvironmentEnvelope, type FileType } from '@bugsee/protocol'; import { createServiceContainer, defineService, serviceToken } from '@bugsee/service'; import { strFromU8, unzipSync } from '@bugsee/util'; import { describe, expect, it, vi } from 'vitest'; @@ -609,6 +609,132 @@ describe('createClient — streaming export', () => { expect(logs.map((l) => l.msg)).toEqual(['new']); }); + it('lets a started provider prepare the snapshot: it gets the recording window, writes land and returned entries ride along as extras', async () => { + const t = mutableClock(100_000); + const store = createMemoryCaptureStore({ maxRecordingTimeMs: 5000, clock: t.clock }); + const { uploadPipeline, enqueue } = fakeUpload(); + const client = createClient({ + captureStore: store, + clock: t.clock, + maxRecordingTime: 5, + reportSnapshots: [ + () => [new CaptureDataEntryBase('log', 106_000, { msg: 'snapshot-source' })], + ], + uploadPipeline, + appToken: 'tok', + getEnvironment, + }); + const windows: unknown[] = []; + client.addCaptureProvider({ + name: 'seeder', + init: () => {}, + start: () => {}, + stop: () => {}, + prepareSnapshot: (w) => { + windows.push(w); + client.captureAggregator.addEntry( + new CaptureDataEntryBase('log', w.end, { msg: 'written' }), + ); + return [new CaptureDataEntryBase('log', w.start, { msg: 'returned' })]; + }, + }); + client.launch(); + t.set(106_000); + await client.logException(new Error('x')); + expect(windows).toEqual([{ start: 101_000, end: 106_000 }]); + const bundle = enqueue.mock.calls[0]?.[0] as Bundle; + const logs = JSON.parse(strFromU8(filesOf(bundle)['logs.json'] as Uint8Array)) as Array<{ + msg: string; + }>; + expect(logs.map((l) => l.msg)).toEqual( + expect.arrayContaining(['written', 'returned', 'snapshot-source']), + ); + }); + + it('keeps a carried seed, clamped to the manifest start, when the clock ticks between the window read and the snapshot', async () => { + let now = 100_000; + const clock: Clock = { wallNow: () => (now += 1), monotonicNow: () => now }; // every read advances 1 ms + const store = createMemoryCaptureStore({ maxRecordingTimeMs: 5000, clock }); + const { uploadPipeline, enqueue } = fakeUpload(); + const client = createClient({ + captureStore: store, + clock, + maxRecordingTime: 5, + uploadPipeline, + appToken: 'tok', + getEnvironment, + }); + client.addCaptureProvider({ + name: 'seeder', + init: () => {}, + start: () => {}, + stop: () => {}, + prepareSnapshot: (w) => [ + new CaptureDataEntryBase('traces.system', w.start, { + timestamp: w.start, + name: 'app_state', + value: 'background', + }), + ], + }); + client.launch(); + await client.logException(new Error('x')); + const bundle = enqueue.mock.calls[0]?.[0] as Bundle; + const rows = JSON.parse( + strFromU8(filesOf(bundle)['traces.system.json'] as Uint8Array), + ) as Array<{ + timestamp: number; + name: string; + }>; + const seed = rows.find((r) => r.name === 'app_state'); + expect(seed).toBeDefined(); + // the store's range starts a ms after the window start (the clock advanced); the seed is moved up to the manifest start + expect(seed?.timestamp).toBe(manifestOf(bundle).time.start); + }); + + it('takes the snapshot window from the resolved Duration option when one is set', async () => { + const t = mutableClock(100_000); + const { uploadPipeline } = fakeUpload(); + const client = createClient({ + clock: t.clock, + launchOptions: createOptionsContainer({ [BugseeOption.Duration]: 20 }), + uploadPipeline, + appToken: 'tok', + getEnvironment, + }); + const windows: unknown[] = []; + client.addCaptureProvider({ + name: 'w', + init: () => {}, + start: () => {}, + stop: () => {}, + prepareSnapshot: (w) => void windows.push(w), + }); + client.launch(); + await client.logException(new Error('x')); + expect(windows).toEqual([{ start: 80_000, end: 100_000 }]); + }); + + it('ends the manifest at the snapshot a report dialog froze, not at the later Send', async () => { + const t = mutableClock(100_000); + const store = createMemoryCaptureStore({ maxRecordingTimeMs: 5000, clock: t.clock }); + const { uploadPipeline, enqueue } = fakeUpload(); + const client = createClient({ + captureStore: store, + clock: t.clock, + uploadPipeline, + appToken: 'tok', + getEnvironment, + }); + t.set(102_000); + const prepared = client.prepareUpload(); + await flushMicrotasks(); + t.set(109_000); // the person sits in the dialog for 7 s + await prepared?.send({ summary: 's' }); + const bundle = enqueue.mock.calls[0]?.[0] as Bundle; + expect(manifestOf(bundle).time.end).toBe(102_000); + }); + it('threads streamEncoders, which win over fileEncoders and see the window plan', async () => { const t = mutableClock(100_000); const { uploadPipeline, enqueue } = fakeUpload(); diff --git a/packages/core/src/client.ts b/packages/core/src/client.ts index 11d33339b..cba627d0c 100644 --- a/packages/core/src/client.ts +++ b/packages/core/src/client.ts @@ -1104,9 +1104,28 @@ export function createClient(options: CreateClientOptions = {}): CreatedClient { return extras; }; openCapture = async (owner?: string): Promise => { + // Let providers make their window honest BEFORE it is frozen (a throttled/frozen tab ran none of their timers); the + // window is the span the snapshot will cover. Isolated: a failing provider never blocks the report. What they RETURN + // rides along as report-time extras (never trimmed by the store's own range, which is read from a separate clock). + const windowEnd = clock.wallNow(); + const prepared = captureCoordinator.prepareSnapshot({ + start: + windowEnd - + launchOptions.get(BugseeOption.Duration, options.maxRecordingTime ?? 60) * 1000, + end: windowEnd, + }); const stream = captureExporter.stream(owner !== undefined ? { owner } : undefined); try { - return { source: stream, extras: await gatherSnapshots() }; + const extras = await gatherSnapshots(); + for (const entry of prepared) { + const existing = extras.get(entry.type); + if (existing !== undefined) { + existing.push(entry); + } else { + extras.set(entry.type, [entry]); + } + } + return { source: stream, extras }; } catch (error) { await stream.return?.(); // the snapshot is pinned until released throw error; diff --git a/packages/core/src/contracts.ts b/packages/core/src/contracts.ts index 35bd1f520..0ffd1b65b 100644 --- a/packages/core/src/contracts.ts +++ b/packages/core/src/contracts.ts @@ -274,6 +274,21 @@ export interface CaptureProvider { /** (Re)configure from launch options and begin capturing; may be cycled across launches. */ start(options: OptionsContainer): void; stop(): void; + /** + * Optional: called synchronously right BEFORE a report's capture snapshot is taken, with the wall-clock window that + * snapshot will cover. A provider whose values are produced by timers or events that a throttled / frozen / backgrounded + * runtime may not have run (a hidden browser tab) uses it to make the window honest. It may WRITE entries (they land in + * the snapshot) and/or RETURN entries that ride along with the report as report-time extras: extras are not trimmed by the + * window, so a value carried to the window start survives however the store rounds its own range. Must not throw into + * the host. + */ + prepareSnapshot?(window: SnapshotWindow): void | readonly CaptureDataEntry[]; +} + +/** The wall-clock span (ms) a report's capture snapshot covers. */ +export interface SnapshotWindow { + readonly start: number; + readonly end: number; } /** Decides when to assemble & upload a report. */ diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 1e83d9d5e..3d07b6631 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -158,6 +158,7 @@ export type { OperationDispatcher, OperationObserver, OptionsContainer, + SnapshotWindow, StoredEntry, } from './contracts'; export { CaptureStoreToken } from './contracts'; diff --git a/packages/instrumentation-tests/test/webview-bundle.e2e.ts b/packages/instrumentation-tests/test/webview-bundle.e2e.ts index a6e327206..29556b231 100644 --- a/packages/instrumentation-tests/test/webview-bundle.e2e.ts +++ b/packages/instrumentation-tests/test/webview-bundle.e2e.ts @@ -35,9 +35,11 @@ const KB = 1024; // field cost ~340 bytes gzip). Raised again, on purpose (2026-11-01), to 69 KiB gzip / 204 KiB raw: the shared core grew by about // 1 KB raw (~0.2 KB gzip) with the per-source visual lanes (lane routing in the chunk store, the per-lane members in the bundle // assembler, the lane in the part meta), which the webview bundles but does not use; the bundle measured 201.0 KB raw / 67.8 KB -// gzip against the old 200 / 68 limits. The artifact size stays logged by the test below. -const GZIP_BUDGET = 69 * KB; -const RAW_BUDGET = 204 * KB; +// gzip against the old 200 / 68 limits. Raised on purpose again (2026-11-23), to 206 KiB raw / 70 KiB gzip: the traces-gap fix (the +// prepareSnapshot hook, held-trace carry-forward in the traces provider, the manifest-end/extras clamp in the assembler) +// grew the shared core+capture by ~0.9 KB raw (209,751 bytes against 208,896) and ~0.2 KB gzip (70,868 against 70,656). The artifact size stays logged by the test below. +const GZIP_BUDGET = 70 * KB; +const RAW_BUDGET = 206 * KB; const IIFE_ENTRY = fileURLToPath(new URL('../../webview/src/iife.ts', import.meta.url)); From 7f88841635053edbb2d2c742815319893089e9c9 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 14:40:50 +0500 Subject: [PATCH 4/4] fix(core): keep 'bindings' in RELAUNCH_KEPT_OPTIONS, sanitised to identity fields The relaunch-options classification test (single source of truth) requires every launch option to be listed; 'bindings' is listed again and its value is reduced to an identity-only copy when retained. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- packages/core/src/carrier.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/packages/core/src/carrier.ts b/packages/core/src/carrier.ts index f3070f098..5b8c1b30f 100644 --- a/packages/core/src/carrier.ts +++ b/packages/core/src/carrier.ts @@ -293,7 +293,7 @@ export const RELAUNCH_KEPT_OPTIONS: readonly string[] = [ 'appId', 'appVersion', 'appBuild', - // `bindings` (the edge env, the version/build source) is NOT listed: it is retained as an identity-only copy, see below + 'bindings', // edge env (version/build source): kept on relaunch, as an identity-only copy (see identityOnlyBindings), else the version falls back to 0.0.0 'appIdentitySource', 'platformType', 'sdkVersion', @@ -341,15 +341,12 @@ export function setCarrierLastLaunch( const retained: Record = {}; if (typeof options === 'object' && options !== null) { for (const key of RELAUNCH_KEPT_OPTIONS) { - const value = (options as Record)[key]; + const raw = (options as Record)[key]; + const value = key === 'bindings' ? identityOnlyBindings(raw) : raw; if (value !== undefined) { retained[key] = value; } } - const bindings = identityOnlyBindings((options as Record).bindings); - if (bindings !== undefined) { - retained.bindings = bindings; - } } getCarrier(globalObj).lastLaunch = { appToken, options: retained }; // Remember the custom host on the default slot, so a plain relaunch() can find it.