🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(boot-metrics): guard hidden-page pollution, fix cold semantics & totalMs contract (#16606)
Inneif69ca72989fd
diff --git a/src/libs/bootMetrics/buildPayload.test.ts b/src/libs/bootMetrics/buildPayload.test.tsindex 11427ca3abb..738f4bd4dd4 100644--- a/src/libs/bootMetrics/buildPayload.test.ts+++ b/src/libs/bootMetrics/buildPayload.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { buildBootMetricsPayload } from './buildPayload';+import { BOOT_SPAN_NAMES, buildBootMetricsPayload } from './buildPayload';const baseDimensions = {appVersion: '1.0.0',@@ -11,6 +11,12 @@ const baseDimensions = {const emptySnapshot = { marks: {}, spans: [] };+// most span-behavior tests need a valid totalMs source (first-paint mark) to get a non-null payload+const paintSnapshot = (+ spans: { durMs: number; name: string; startMs: number }[] = [],+ extraMarks: Record<string, number> = {},+) => ({ marks: { 'first-paint': 1000, ...extraMarks }, spans });+describe('buildBootMetricsPayload', () => {describe('totalMs', () => {it('uses first-paint mark when present', () => {@@ -18,29 +24,58 @@ describe('buildBootMetricsPayload', () => {dimensions: baseDimensions,snapshot: { marks: { 'first-paint': 420 }, spans: [] },});- expect(result.totalMs).toBe(420);+ expect(result?.totalMs).toBe(420);});- it('falls back to max span end when first-paint is absent', () => {+ it('falls back to fcpMs when first-paint is absent', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,- snapshot: {- marks: {},- spans: [- { durMs: 100, name: 'a', startMs: 50 },- { durMs: 200, name: 'b', startMs: 0 },- ],- },+ fcpMs: 350,+ snapshot: emptySnapshot,});- expect(result.totalMs).toBe(200);+ expect(result?.totalMs).toBe(350);});- it('returns 0 when no marks and no spans', () => {+ it('returns null when neither first-paint nor fcp is available', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,snapshot: emptySnapshot,});- expect(result.totalMs).toBe(0);+ expect(result).toBeNull();+ });++ it('returns null when negative fcp is the only source', () => {+ const result = buildBootMetricsPayload({+ dimensions: baseDimensions,+ fcpMs: -1,+ snapshot: emptySnapshot,+ });+ expect(result).toBeNull();+ });++ it('returns null when first-paint exceeds the 120s cap', () => {+ const result = buildBootMetricsPayload({+ dimensions: baseDimensions,+ snapshot: { marks: { 'first-paint': 120_001 }, spans: [] },+ });+ expect(result).toBeNull();+ });++ it('returns null when fcp fallback exceeds the 120s cap', () => {+ const result = buildBootMetricsPayload({+ dimensions: baseDimensions,+ fcpMs: 130_000,+ snapshot: emptySnapshot,+ });+ expect(result).toBeNull();+ });++ it('keeps totalMs at exactly the 120s cap', () => {+ const result = buildBootMetricsPayload({+ dimensions: baseDimensions,+ snapshot: { marks: { 'first-paint': 120_000 }, spans: [] },+ });+ expect(result?.totalMs).toBe(120_000);});});@@ -53,8 +88,8 @@ describe('buildBootMetricsPayload', () => {spans: [{ durMs: 1415.2, name: 'bundle', startMs: 46.7000000029 }],},});- expect(result.totalMs).toBe(1746);- expect(result.spans[0]).toEqual({ durMs: 1415, name: 'bundle', startMs: 47 });+ expect(result?.totalMs).toBe(1746);+ expect(result?.spans[0]).toEqual({ durMs: 1415, name: 'bundle', startMs: 47 });});it('rounds derived spans (ttfb/fcp) to integers', () => {@@ -64,7 +99,7 @@ describe('buildBootMetricsPayload', () => {navResponseStartMs: 23.9,snapshot: { marks: { 'first-paint': 1000 }, spans: [] },});- const byName = Object.fromEntries(result.spans.map((s) => [s.name, s]));+ const byName = Object.fromEntries((result?.spans ?? []).map((s) => [s.name, s]));expect(byName.ttfb.durMs).toBe(24);expect(byName.fcp.durMs).toBe(901);});@@ -81,14 +116,14 @@ describe('buildBootMetricsPayload', () => {platform: 'desktop',userId: 'u42',},- snapshot: emptySnapshot,+ snapshot: paintSnapshot(),});- expect(result.appVersion).toBe('2.0.0');- expect(result.platform).toBe('desktop');- expect(result.isLogin).toBe(true);- expect(result.cold).toBe(false);- expect(result.userId).toBe('u42');- expect(result.anonId).toBe('a123');+ expect(result?.appVersion).toBe('2.0.0');+ expect(result?.platform).toBe('desktop');+ expect(result?.isLogin).toBe(true);+ expect(result?.cold).toBe(false);+ expect(result?.userId).toBe('u42');+ expect(result?.anonId).toBe('a123');});});@@ -97,9 +132,74 @@ describe('buildBootMetricsPayload', () => {const span = { durMs: 10, name: 'core-init', startMs: 5 };const result = buildBootMetricsPayload({dimensions: baseDimensions,- snapshot: { marks: {}, spans: [span] },+ snapshot: paintSnapshot([span]),});- expect(result.spans).toContainEqual(span);+ expect(result?.spans).toContainEqual(span);+ });+ });++ describe('span-name allowlist', () => {+ it('exports the exact allowlist', () => {+ expect([...BOOT_SPAN_NAMES].sort()).toEqual(+ [+ 'bundle',+ 'cache-hydration',+ 'core-init',+ 'doc',+ 'fcp',+ 'import-settings',+ 'store-gate',+ 'tool-surfaces',+ 'ttfb',+ ].sort(),+ );+ });++ it('drops snapshot spans whose name is not in the allowlist', () => {+ const result = buildBootMetricsPayload({+ dimensions: baseDimensions,+ snapshot: paintSnapshot([+ { durMs: 5, name: 'core-init', startMs: 0 },+ { durMs: 5, name: 'random-junk', startMs: 0 },+ ]),+ });+ expect(result?.spans.find((s) => s.name === 'core-init')).toBeDefined();+ expect(result?.spans.find((s) => s.name === 'random-junk')).toBeUndefined();+ });++ it('drops resource timings whose name is not in the allowlist', () => {+ const result = buildBootMetricsPayload({+ dimensions: baseDimensions,+ resourceTimings: [{ durMs: 10, name: 'fetch:server-config', startMs: 0 }],+ snapshot: paintSnapshot(),+ });+ expect(result?.spans.find((s) => s.name === 'fetch:server-config')).toBeUndefined();+ });+ });++ describe('span time cap', () => {+ it('drops a span whose durMs exceeds the 120s cap', () => {+ const result = buildBootMetricsPayload({+ dimensions: baseDimensions,+ snapshot: paintSnapshot([{ durMs: 130_000, name: 'core-init', startMs: 0 }]),+ });+ expect(result?.spans.find((s) => s.name === 'core-init')).toBeUndefined();+ });++ it('drops a span whose startMs exceeds the 120s cap', () => {+ const result = buildBootMetricsPayload({+ dimensions: baseDimensions,+ snapshot: paintSnapshot([{ durMs: 5, name: 'core-init', startMs: 130_000 }]),+ });+ expect(result?.spans.find((s) => s.name === 'core-init')).toBeUndefined();+ });++ it('keeps a span at exactly the 120s cap', () => {+ const result = buildBootMetricsPayload({+ dimensions: baseDimensions,+ snapshot: paintSnapshot([{ durMs: 120_000, name: 'core-init', startMs: 120_000 }]),+ });+ expect(result?.spans).toContainEqual({ durMs: 120_000, name: 'core-init', startMs: 120_000 });});});@@ -108,26 +208,26 @@ describe('buildBootMetricsPayload', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,navResponseStartMs: 80,- snapshot: emptySnapshot,+ snapshot: paintSnapshot(),});- expect(result.spans).toContainEqual({ durMs: 80, name: 'ttfb', startMs: 0 });+ expect(result?.spans).toContainEqual({ durMs: 80, name: 'ttfb', startMs: 0 });});it('omits ttfb when navResponseStartMs is absent', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,- snapshot: emptySnapshot,+ snapshot: paintSnapshot(),});- expect(result.spans.find((s) => s.name === 'ttfb')).toBeUndefined();+ expect(result?.spans.find((s) => s.name === 'ttfb')).toBeUndefined();});it('omits ttfb when durMs is negative', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,navResponseStartMs: -5,- snapshot: emptySnapshot,+ snapshot: paintSnapshot(),});- expect(result.spans.find((s) => s.name === 'ttfb')).toBeUndefined();+ expect(result?.spans.find((s) => s.name === 'ttfb')).toBeUndefined();});});@@ -136,17 +236,17 @@ describe('buildBootMetricsPayload', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,htmlMarkMs: 300,- snapshot: emptySnapshot,+ snapshot: paintSnapshot(),});- expect(result.spans).toContainEqual({ durMs: 300, name: 'doc', startMs: 0 });+ expect(result?.spans).toContainEqual({ durMs: 300, name: 'doc', startMs: 0 });});it('omits doc when htmlMarkMs is absent', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,- snapshot: emptySnapshot,+ snapshot: paintSnapshot(),});- expect(result.spans.find((s) => s.name === 'doc')).toBeUndefined();+ expect(result?.spans.find((s) => s.name === 'doc')).toBeUndefined();});});@@ -155,35 +255,35 @@ describe('buildBootMetricsPayload', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,htmlMarkMs: 200,- snapshot: { marks: { 'bundle-eval': 350 }, spans: [] },+ snapshot: paintSnapshot([], { 'bundle-eval': 350 }),});- expect(result.spans).toContainEqual({ durMs: 150, name: 'bundle', startMs: 200 });+ expect(result?.spans).toContainEqual({ durMs: 150, name: 'bundle', startMs: 200 });});it('omits bundle when htmlMarkMs is absent', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,- snapshot: { marks: { 'bundle-eval': 350 }, spans: [] },+ snapshot: paintSnapshot([], { 'bundle-eval': 350 }),});- expect(result.spans.find((s) => s.name === 'bundle')).toBeUndefined();+ expect(result?.spans.find((s) => s.name === 'bundle')).toBeUndefined();});it('omits bundle when bundle-eval mark is absent', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,htmlMarkMs: 200,- snapshot: emptySnapshot,+ snapshot: paintSnapshot(),});- expect(result.spans.find((s) => s.name === 'bundle')).toBeUndefined();+ expect(result?.spans.find((s) => s.name === 'bundle')).toBeUndefined();});it('omits bundle when duration is negative (htmlMarkMs > bundle-eval)', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,htmlMarkMs: 400,- snapshot: { marks: { 'bundle-eval': 300 }, spans: [] },+ snapshot: paintSnapshot([], { 'bundle-eval': 300 }),});- expect(result.spans.find((s) => s.name === 'bundle')).toBeUndefined();+ expect(result?.spans.find((s) => s.name === 'bundle')).toBeUndefined();});});@@ -193,7 +293,7 @@ describe('buildBootMetricsPayload', () => {dimensions: baseDimensions,snapshot: { marks: { 'app-ready': 500, 'first-paint': 650 }, spans: [] },});- expect(result.spans).toContainEqual({ durMs: 150, name: 'store-gate', startMs: 500 });+ expect(result?.spans).toContainEqual({ durMs: 150, name: 'store-gate', startMs: 500 });});it('omits store-gate when app-ready mark is absent', () => {@@ -201,15 +301,16 @@ describe('buildBootMetricsPayload', () => {dimensions: baseDimensions,snapshot: { marks: { 'first-paint': 650 }, spans: [] },});- expect(result.spans.find((s) => s.name === 'store-gate')).toBeUndefined();+ expect(result?.spans.find((s) => s.name === 'store-gate')).toBeUndefined();});it('omits store-gate when first-paint mark is absent', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,+ fcpMs: 500,snapshot: { marks: { 'app-ready': 500 }, spans: [] },});- expect(result.spans.find((s) => s.name === 'store-gate')).toBeUndefined();+ expect(result?.spans.find((s) => s.name === 'store-gate')).toBeUndefined();});it('omits store-gate when duration is negative', () => {@@ -217,7 +318,7 @@ describe('buildBootMetricsPayload', () => {dimensions: baseDimensions,snapshot: { marks: { 'app-ready': 700, 'first-paint': 600 }, spans: [] },});- expect(result.spans.find((s) => s.name === 'store-gate')).toBeUndefined();+ expect(result?.spans.find((s) => s.name === 'store-gate')).toBeUndefined();});});@@ -228,57 +329,54 @@ describe('buildBootMetricsPayload', () => {fcpMs: 550,snapshot: emptySnapshot,});- expect(result.spans).toContainEqual({ durMs: 550, name: 'fcp', startMs: 0 });+ expect(result?.spans).toContainEqual({ durMs: 550, name: 'fcp', startMs: 0 });});it('omits fcp when fcpMs is absent', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,- snapshot: emptySnapshot,+ snapshot: paintSnapshot(),});- expect(result.spans.find((s) => s.name === 'fcp')).toBeUndefined();+ expect(result?.spans.find((s) => s.name === 'fcp')).toBeUndefined();});it('omits fcp when fcpMs is negative', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,fcpMs: -1,- snapshot: emptySnapshot,+ snapshot: paintSnapshot(),});- expect(result.spans.find((s) => s.name === 'fcp')).toBeUndefined();+ expect(result?.spans.find((s) => s.name === 'fcp')).toBeUndefined();});});describe('resourceTimings', () => {- it('appends resource timings verbatim', () => {- const rt = { durMs: 120, name: 'fetch:server-config', startMs: 10 };+ it('appends allowlisted resource timings verbatim', () => {+ const rt = { durMs: 120, name: 'cache-hydration', startMs: 10 };const result = buildBootMetricsPayload({dimensions: baseDimensions,resourceTimings: [rt],- snapshot: emptySnapshot,+ snapshot: paintSnapshot(),});- expect(result.spans).toContainEqual(rt);+ expect(result?.spans).toContainEqual(rt);});it('drops resource timing with negative duration', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,- resourceTimings: [{ durMs: -5, name: 'fetch:user-state', startMs: 10 }],- snapshot: emptySnapshot,+ resourceTimings: [{ durMs: -5, name: 'cache-hydration', startMs: 10 }],+ snapshot: paintSnapshot(),});- expect(result.spans.find((s) => s.name === 'fetch:user-state')).toBeUndefined();+ expect(result?.spans.find((s) => s.name === 'cache-hydration')).toBeUndefined();});it('does not duplicate a span name already in snapshot', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,resourceTimings: [{ durMs: 50, name: 'cache-hydration', startMs: 0 }],- snapshot: {- marks: {},- spans: [{ durMs: 30, name: 'cache-hydration', startMs: 5 }],- },+ snapshot: paintSnapshot([{ durMs: 30, name: 'cache-hydration', startMs: 5 }]),});- expect(result.spans.filter((s) => s.name === 'cache-hydration')).toHaveLength(1);+ expect(result?.spans.filter((s) => s.name === 'cache-hydration')).toHaveLength(1);});});@@ -287,12 +385,9 @@ describe('buildBootMetricsPayload', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,navResponseStartMs: 80,- snapshot: {- marks: {},- spans: [{ durMs: 60, name: 'ttfb', startMs: 0 }],- },+ snapshot: paintSnapshot([{ durMs: 60, name: 'ttfb', startMs: 0 }]),});- expect(result.spans.filter((s) => s.name === 'ttfb')).toHaveLength(1);+ expect(result?.spans.filter((s) => s.name === 'ttfb')).toHaveLength(1);});});@@ -300,27 +395,27 @@ describe('buildBootMetricsPayload', () => {it('truncates spans to 64 when input would produce more', () => {const manySpans = Array.from({ length: 70 }, (_, i) => ({durMs: 1,- name: `span-${i}`,+ name: 'core-init',startMs: i,}));const result = buildBootMetricsPayload({dimensions: baseDimensions,- snapshot: { marks: {}, spans: manySpans },+ snapshot: paintSnapshot(manySpans),});- expect(result.spans).toHaveLength(64);+ expect(result?.spans).toHaveLength(64);});it('does not truncate spans when count is exactly 64', () => {const spans = Array.from({ length: 64 }, (_, i) => ({durMs: 1,- name: `span-${i}`,+ name: 'core-init',startMs: i,}));const result = buildBootMetricsPayload({dimensions: baseDimensions,- snapshot: { marks: {}, spans },+ snapshot: paintSnapshot(spans),});- expect(result.spans).toHaveLength(64);+ expect(result?.spans).toHaveLength(64);});});@@ -329,18 +424,18 @@ describe('buildBootMetricsPayload', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,navResponseStartMs: Number.NaN,- snapshot: emptySnapshot,+ snapshot: paintSnapshot(),});- expect(result.spans.find((s) => s.name === 'ttfb')).toBeUndefined();+ expect(result?.spans.find((s) => s.name === 'ttfb')).toBeUndefined();});it('omits span with Infinity duration', () => {const result = buildBootMetricsPayload({dimensions: baseDimensions,navResponseStartMs: Number.POSITIVE_INFINITY,- snapshot: emptySnapshot,+ snapshot: paintSnapshot(),});- expect(result.spans.find((s) => s.name === 'ttfb')).toBeUndefined();+ expect(result?.spans.find((s) => s.name === 'ttfb')).toBeUndefined();});});});diff --git a/src/libs/bootMetrics/buildPayload.ts b/src/libs/bootMetrics/buildPayload.tsindex 8a118e4f6bb..8e791990221 100644--- a/src/libs/bootMetrics/buildPayload.ts+++ b/src/libs/bootMetrics/buildPayload.ts@@ -31,21 +31,40 @@ interface BuildPayloadInput {snapshot: { marks: Record<string, number>; spans: BootMetricSpan[] };}+const SPAN_TIME_CAP_MS = 120_000;++export const BOOT_SPAN_NAMES: ReadonlySet<string> = new Set([+ 'import-settings',+ 'tool-surfaces',+ 'core-init',+ 'cache-hydration',+ 'ttfb',+ 'doc',+ 'bundle',+ 'store-gate',+ 'fcp',+]);+const isFinitePositive = (n: number) => Number.isFinite(n) && n >= 0;-export const buildBootMetricsPayload = (input: BuildPayloadInput): BootMetricPayload => {+const isAllowedSpan = (s: BootMetricSpan) =>+ BOOT_SPAN_NAMES.has(s.name) && s.durMs <= SPAN_TIME_CAP_MS && s.startMs <= SPAN_TIME_CAP_MS;++export const buildBootMetricsPayload = (input: BuildPayloadInput): BootMetricPayload | null => {const { snapshot, htmlMarkMs, navResponseStartMs, fcpMs, resourceTimings, dimensions } = input;const { marks, spans: snapshotSpans } = snapshot;- const existingNames = new Set(snapshotSpans.map((s) => s.name));-const totalMs = (() => {const fp = marks['first-paint'];if (typeof fp === 'number' && Number.isFinite(fp)) return fp;- if (snapshotSpans.length === 0) return 0;- return Math.max(...snapshotSpans.map((s) => s.startMs + s.durMs));+ if (typeof fcpMs === 'number' && isFinitePositive(fcpMs)) return fcpMs;+ return null;})();+ if (totalMs === null || totalMs > SPAN_TIME_CAP_MS) return null;++ const existingNames = new Set(snapshotSpans.map((s) => s.name));+const derived: BootMetricSpan[] = [];const tryAdd = (name: string, startMs: number, durMs: number) => {@@ -87,6 +106,7 @@ export const buildBootMetricsPayload = (input: BuildPayloadInput): BootMetricPay// performance.now() yields sub-millisecond floats; the metrics columns are integer, so round.const spans = [...snapshotSpans, ...derived]+ .filter(isAllowedSpan).slice(0, 64).map((s) => ({ durMs: Math.round(s.durMs), name: s.name, startMs: Math.round(s.startMs) }));diff --git a/src/libs/bootMetrics/finalize.test.ts b/src/libs/bootMetrics/finalize.test.tsindex 081967ddbb2..e78149cb70a 100644--- a/src/libs/bootMetrics/finalize.test.ts+++ b/src/libs/bootMetrics/finalize.test.ts@@ -4,7 +4,12 @@import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest';const mocks = vi.hoisted(() => ({- bootTimingSnapshot: vi.fn(() => ({ marks: {}, spans: [] })),+ bootTimingSnapshot: vi.fn<+ () => {+ marks: Record<string, number>;+ spans: { durMs: number; name: string; startMs: number }[];+ }+ >(() => ({ marks: { 'first-paint': 1000 }, spans: [] })),getServerConfigStoreState: vi.fn(() => ({ serverConfig: { bootstrapMetricsSampleRate: 1 } })),getUserStoreState: vi.fn(() => ({ user: null })),isLogin: vi.fn(() => false),@@ -52,6 +57,13 @@ describe('startBootMetricsFinalize', () => {vi.clearAllMocks();vi.useFakeTimers();+ localStorage.clear();++ Object.defineProperty(document, 'visibilityState', {+ configurable: true,+ get: () => 'visible',+ });+sendBeaconSpy = vi.spyOn(navigator, 'sendBeacon').mockReturnValue(true);Object.defineProperty(window, 'requestAnimationFrame', {@@ -81,7 +93,7 @@ describe('startBootMetricsFinalize', () => {vi.spyOn(performance, 'getEntriesByType').mockReturnValue([]);vi.spyOn(performance, 'getEntriesByName').mockReturnValue([]);- mocks.bootTimingSnapshot.mockReturnValue({ marks: {}, spans: [] });+ mocks.bootTimingSnapshot.mockReturnValue({ marks: { 'first-paint': 1000 }, spans: [] });mocks.getServerConfigStoreState.mockReturnValue({serverConfig: { bootstrapMetricsSampleRate: 1 },});@@ -169,4 +181,107 @@ describe('startBootMetricsFinalize', () => {expect(sendBeaconSpy).toHaveBeenCalledTimes(1);});++ it('skips sending entirely when the page was hidden at module evaluation', async () => {+ Object.defineProperty(document, 'visibilityState', {+ configurable: true,+ get: () => 'hidden',+ });++ const { startBootMetricsFinalize } = await import('./finalize');+ startBootMetricsFinalize();+ await vi.runAllTimersAsync();++ window.dispatchEvent(new Event('pagehide'));+ await vi.runAllTimersAsync();++ expect(sendBeaconSpy).not.toHaveBeenCalled();+ });++ it('skips sending after a visibilitychange to hidden', async () => {+ Object.defineProperty(window, 'requestIdleCallback', {+ configurable: true,+ value: undefined,+ writable: true,+ });+ Object.defineProperty(window, 'requestAnimationFrame', {+ configurable: true,+ value: undefined,+ writable: true,+ });++ const { startBootMetricsFinalize } = await import('./finalize');+ startBootMetricsFinalize();++ Object.defineProperty(document, 'visibilityState', {+ configurable: true,+ get: () => 'hidden',+ });+ document.dispatchEvent(new Event('visibilitychange'));++ window.dispatchEvent(new Event('pagehide'));+ await vi.runAllTimersAsync();++ expect(sendBeaconSpy).not.toHaveBeenCalled();+ });++ it('marks the device as seen before the sampling gate, even when sampled out', async () => {+ mocks.getServerConfigStoreState.mockReturnValue({+ serverConfig: { bootstrapMetricsSampleRate: 0 },+ });+ vi.spyOn(Math, 'random').mockReturnValue(0.5);++ expect(localStorage.getItem('lobe:boot:seen')).toBeNull();++ const { startBootMetricsFinalize } = await import('./finalize');+ startBootMetricsFinalize();+ await vi.runAllTimersAsync();++ expect(sendBeaconSpy).not.toHaveBeenCalled();+ expect(localStorage.getItem('lobe:boot:seen')).toBe('1');+ });++ it('reports cold=true on first boot and cold=false on the next boot', async () => {+ const { startBootMetricsFinalize: first } = await import('./finalize');+ first();+ await vi.runAllTimersAsync();++ const firstPayload = JSON.parse(await (sendBeaconSpy.mock.calls[0][1] as Blob).text());+ expect(firstPayload.cold).toBe(true);++ vi.resetModules();+ sendBeaconSpy.mockClear();++ const { startBootMetricsFinalize: second } = await import('./finalize');+ second();+ await vi.runAllTimersAsync();++ const secondPayload = JSON.parse(await (sendBeaconSpy.mock.calls[0][1] as Blob).text());+ expect(secondPayload.cold).toBe(false);+ });++ it('leaves sent false when sendBeacon returns false, so pagehide retries', async () => {+ sendBeaconSpy.mockReturnValue(false);++ const { startBootMetricsFinalize } = await import('./finalize');+ startBootMetricsFinalize();+ await vi.runAllTimersAsync();++ expect(sendBeaconSpy).toHaveBeenCalledTimes(1);++ window.dispatchEvent(new Event('pagehide'));+ await vi.runAllTimersAsync();++ expect(sendBeaconSpy).toHaveBeenCalledTimes(2);+ });++ it('does not send when payload build returns null (no first-paint and no fcp)', async () => {+ mocks.bootTimingSnapshot.mockReturnValue({ marks: {}, spans: [] });++ const { startBootMetricsFinalize } = await import('./finalize');+ startBootMetricsFinalize();+ await vi.runAllTimersAsync();++ expect(sendBeaconSpy).not.toHaveBeenCalled();+ });});diff --git a/src/libs/bootMetrics/finalize.ts b/src/libs/bootMetrics/finalize.tsindex e8dbb55fb84..e7317a5587f 100644--- a/src/libs/bootMetrics/finalize.ts+++ b/src/libs/bootMetrics/finalize.ts@@ -13,15 +13,20 @@ const SEEN_KEY = 'lobe:boot:seen';let sent = false;-const readCold = (): boolean => {- try {- const cold = !localStorage.getItem(SEEN_KEY);- localStorage.setItem(SEEN_KEY, '1');- return cold;- } catch {- return false;+let wasHidden = false;+try {+ if (typeof document !== 'undefined') {+ wasHidden =+ document.visibilityState === 'hidden' ||+ (document as Document & { prerendering?: boolean }).prerendering === true;++ document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'hidden') wasHidden = true;+ });}-};+} catch {+ void 0;+}const getPlatform = (): 'desktop' | 'mobile' | 'web' => {if (isDesktop) return 'desktop';@@ -61,8 +66,9 @@ const scheduleAfterFirstPaint = (task: () => void): void => {runWhenIdle();};-const sendPayload = (ingestUrl: string): void => {+const sendPayload = (ingestUrl: string, cold: boolean): void => {if (sent) return;+ if (wasHidden) return;try {const snapshot = bootTiming.snapshot();@@ -88,7 +94,7 @@ const sendPayload = (ingestUrl: string): void => {dimensions: {anonId: nanoid(),appVersion: CURRENT_VERSION,- cold: readCold(),+ cold,isLogin,platform: getPlatform(),userId,@@ -99,9 +105,14 @@ const sendPayload = (ingestUrl: string): void => {snapshot,});+ if (!payload) return;+if (typeof navigator.sendBeacon === 'function') {- navigator.sendBeacon(ingestUrl, new Blob([JSON.stringify(payload)], { type: 'text/plain' }));- sent = true;+ const queued = navigator.sendBeacon(+ ingestUrl,+ new Blob([JSON.stringify(payload)], { type: 'text/plain' }),+ );+ if (queued) sent = true;}} catch {void 0;@@ -115,6 +126,14 @@ export const startBootMetricsFinalize = (): void => {if (!isProductUsageEventEnabled()) return;+ let cold = false;+ try {+ cold = !localStorage.getItem(SEEN_KEY);+ localStorage.setItem(SEEN_KEY, '1');+ } catch {+ cold = false;+ }+try {const state = getServerConfigStoreState();const sampleRate =@@ -128,10 +147,10 @@ export const startBootMetricsFinalize = (): void => {void 0;}- scheduleAfterFirstPaint(() => sendPayload(ingestUrl));+ scheduleAfterFirstPaint(() => sendPayload(ingestUrl, cold));const pagehideHandler = () => {- if (!sent) sendPayload(ingestUrl);+ if (!sent) sendPayload(ingestUrl, cold);window.removeEventListener('pagehide', pagehideHandler);};