Skip to content

🤯 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.

✨ feat(boot-metrics): instrument SPA bootstrap timing beacon (#16305)

Inneiea7c1dcc6f2e
diff --git a/index.html b/index.html
index 9d53c07074b..5c3972c99ed 100644
--- a/index.html
+++ b/index.html
@@ -54,6 +54,9 @@
color: #f0f0f0;
}
</style>
+ <script>
+ window.__LOBE_BOOT_T_HTML__ = performance.now();
+ </script>
<script>
(function () {
function supportsImportMaps() {
diff --git a/index.mobile.html b/index.mobile.html
index c2c14c88bbd..18d4ba16b65 100644
--- a/index.mobile.html
+++ b/index.mobile.html
@@ -14,6 +14,9 @@
background-color: #000;
}
</style>
+ <script>
+ window.__LOBE_BOOT_T_HTML__ = performance.now();
+ </script>
<script>
(function(){
var O=globalThis.Worker;
diff --git a/src/layout/GlobalProvider/CacheHydrationGate.tsx b/src/layout/GlobalProvider/CacheHydrationGate.tsx
index 469bbbfea44..64720b733a6 100644
--- a/src/layout/GlobalProvider/CacheHydrationGate.tsx
+++ b/src/layout/GlobalProvider/CacheHydrationGate.tsx
@@ -3,11 +3,15 @@
import type { PropsWithChildren } from 'react';
import { useEffect, useLayoutEffect, useState, useSyncExternalStore } from 'react';
+import { bootTiming } from '@/libs/bootTiming';
import { cacheHydration, isCacheHydrationBlocked } from '@/libs/swr/cacheHydration';
import { useCacheScope } from '@/libs/swr/useCacheScope';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
+// first-write-wins: keyed by scope remounts must not overwrite the initial mark
+let firstPaintMarked = false;
+
const HYDRATION_TIMEOUT = 1500;
const CacheHydrationGate = ({ children }: PropsWithChildren) => {
@@ -59,6 +63,10 @@ const CacheHydrationGateInner = ({ children, scope }: CacheHydrationGateInnerPro
useLayoutEffect(() => {
if (booting) return;
+ if (!firstPaintMarked) {
+ firstPaintMarked = true;
+ bootTiming.mark('first-paint');
+ }
document.getElementById('loading-screen')?.remove();
}, [booting]);
diff --git a/src/libs/bootMetrics/buildPayload.test.ts b/src/libs/bootMetrics/buildPayload.test.ts
new file mode 100644
index 00000000000..11427ca3abb
--- /dev/null
+++ b/src/libs/bootMetrics/buildPayload.test.ts
@@ -0,0 +1,346 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildBootMetricsPayload } from './buildPayload';
+
+const baseDimensions = {
+ appVersion: '1.0.0',
+ cold: true,
+ isLogin: false,
+ platform: 'web' as const,
+};
+
+const emptySnapshot = { marks: {}, spans: [] };
+
+describe('buildBootMetricsPayload', () => {
+ describe('totalMs', () => {
+ it('uses first-paint mark when present', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ snapshot: { marks: { 'first-paint': 420 }, spans: [] },
+ });
+ expect(result.totalMs).toBe(420);
+ });
+
+ it('falls back to max span end 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 },
+ ],
+ },
+ });
+ expect(result.totalMs).toBe(200);
+ });
+
+ it('returns 0 when no marks and no spans', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ snapshot: emptySnapshot,
+ });
+ expect(result.totalMs).toBe(0);
+ });
+ });
+
+ describe('rounding (integer ms columns)', () => {
+ it('rounds totalMs and span startMs/durMs to integers', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ snapshot: {
+ marks: { 'first-paint': 1746.4000000059605 },
+ 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 });
+ });
+
+ it('rounds derived spans (ttfb/fcp) to integers', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ fcpMs: 900.5,
+ navResponseStartMs: 23.9,
+ snapshot: { marks: { 'first-paint': 1000 }, spans: [] },
+ });
+ const byName = Object.fromEntries(result.spans.map((s) => [s.name, s]));
+ expect(byName.ttfb.durMs).toBe(24);
+ expect(byName.fcp.durMs).toBe(901);
+ });
+ });
+
+ describe('dimensions pass-through', () => {
+ it('propagates all dimension fields', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: {
+ anonId: 'a123',
+ appVersion: '2.0.0',
+ cold: false,
+ isLogin: true,
+ platform: 'desktop',
+ userId: 'u42',
+ },
+ snapshot: emptySnapshot,
+ });
+ 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');
+ });
+ });
+
+ describe('snapshot spans', () => {
+ it('includes existing snapshot spans unchanged', () => {
+ const span = { durMs: 10, name: 'core-init', startMs: 5 };
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ snapshot: { marks: {}, spans: [span] },
+ });
+ expect(result.spans).toContainEqual(span);
+ });
+ });
+
+ describe('ttfb derived span', () => {
+ it('adds ttfb when navResponseStartMs is provided', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ navResponseStartMs: 80,
+ snapshot: emptySnapshot,
+ });
+ expect(result.spans).toContainEqual({ durMs: 80, name: 'ttfb', startMs: 0 });
+ });
+
+ it('omits ttfb when navResponseStartMs is absent', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ snapshot: emptySnapshot,
+ });
+ 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,
+ });
+ expect(result.spans.find((s) => s.name === 'ttfb')).toBeUndefined();
+ });
+ });
+
+ describe('doc derived span', () => {
+ it('adds doc when htmlMarkMs is provided', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ htmlMarkMs: 300,
+ snapshot: emptySnapshot,
+ });
+ expect(result.spans).toContainEqual({ durMs: 300, name: 'doc', startMs: 0 });
+ });
+
+ it('omits doc when htmlMarkMs is absent', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ snapshot: emptySnapshot,
+ });
+ expect(result.spans.find((s) => s.name === 'doc')).toBeUndefined();
+ });
+ });
+
+ describe('bundle derived span', () => {
+ it('adds bundle when both htmlMarkMs and bundle-eval mark are present', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ htmlMarkMs: 200,
+ snapshot: { marks: { 'bundle-eval': 350 }, spans: [] },
+ });
+ 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: [] },
+ });
+ 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,
+ });
+ 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: [] },
+ });
+ expect(result.spans.find((s) => s.name === 'bundle')).toBeUndefined();
+ });
+ });
+
+ describe('store-gate derived span', () => {
+ it('adds store-gate from app-ready to first-paint marks', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ snapshot: { marks: { 'app-ready': 500, 'first-paint': 650 }, spans: [] },
+ });
+ expect(result.spans).toContainEqual({ durMs: 150, name: 'store-gate', startMs: 500 });
+ });
+
+ it('omits store-gate when app-ready mark is absent', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ snapshot: { marks: { 'first-paint': 650 }, spans: [] },
+ });
+ 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,
+ snapshot: { marks: { 'app-ready': 500 }, spans: [] },
+ });
+ expect(result.spans.find((s) => s.name === 'store-gate')).toBeUndefined();
+ });
+
+ it('omits store-gate when duration is negative', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ snapshot: { marks: { 'app-ready': 700, 'first-paint': 600 }, spans: [] },
+ });
+ expect(result.spans.find((s) => s.name === 'store-gate')).toBeUndefined();
+ });
+ });
+
+ describe('fcp derived span', () => {
+ it('adds fcp when fcpMs is provided', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ fcpMs: 550,
+ snapshot: emptySnapshot,
+ });
+ expect(result.spans).toContainEqual({ durMs: 550, name: 'fcp', startMs: 0 });
+ });
+
+ it('omits fcp when fcpMs is absent', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ snapshot: emptySnapshot,
+ });
+ 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,
+ });
+ 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 };
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ resourceTimings: [rt],
+ snapshot: emptySnapshot,
+ });
+ 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,
+ });
+ expect(result.spans.find((s) => s.name === 'fetch:user-state')).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 }],
+ },
+ });
+ expect(result.spans.filter((s) => s.name === 'cache-hydration')).toHaveLength(1);
+ });
+ });
+
+ describe('no-duplicate protection', () => {
+ it('does not emit derived ttfb if name already in snapshot', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ navResponseStartMs: 80,
+ snapshot: {
+ marks: {},
+ spans: [{ durMs: 60, name: 'ttfb', startMs: 0 }],
+ },
+ });
+ expect(result.spans.filter((s) => s.name === 'ttfb')).toHaveLength(1);
+ });
+ });
+
+ describe('spans cap', () => {
+ it('truncates spans to 64 when input would produce more', () => {
+ const manySpans = Array.from({ length: 70 }, (_, i) => ({
+ durMs: 1,
+ name: `span-${i}`,
+ startMs: i,
+ }));
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ snapshot: { marks: {}, spans: manySpans },
+ });
+ 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}`,
+ startMs: i,
+ }));
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ snapshot: { marks: {}, spans },
+ });
+ expect(result.spans).toHaveLength(64);
+ });
+ });
+
+ describe('non-finite duration guard', () => {
+ it('omits span with NaN duration', () => {
+ const result = buildBootMetricsPayload({
+ dimensions: baseDimensions,
+ navResponseStartMs: Number.NaN,
+ snapshot: emptySnapshot,
+ });
+ 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,
+ });
+ expect(result.spans.find((s) => s.name === 'ttfb')).toBeUndefined();
+ });
+ });
+});
diff --git a/src/libs/bootMetrics/buildPayload.ts b/src/libs/bootMetrics/buildPayload.ts
new file mode 100644
index 00000000000..8a118e4f6bb
--- /dev/null
+++ b/src/libs/bootMetrics/buildPayload.ts
@@ -0,0 +1,98 @@
+export interface BootMetricSpan {
+ durMs: number;
+ name: string;
+ startMs: number;
+}
+
+export interface BootMetricPayload {
+ anonId?: string;
+ appVersion: string;
+ cold: boolean;
+ isLogin: boolean;
+ platform: 'desktop' | 'mobile' | 'web';
+ spans: BootMetricSpan[];
+ totalMs: number;
+ userId?: string;
+}
+
+interface BuildPayloadInput {
+ dimensions: {
+ anonId?: string;
+ appVersion: string;
+ cold: boolean;
+ isLogin: boolean;
+ platform: 'desktop' | 'mobile' | 'web';
+ userId?: string;
+ };
+ fcpMs?: number;
+ htmlMarkMs?: number;
+ navResponseStartMs?: number;
+ resourceTimings?: { durMs: number; name: string; startMs: number }[];
+ snapshot: { marks: Record<string, number>; spans: BootMetricSpan[] };
+}
+
+const isFinitePositive = (n: number) => Number.isFinite(n) && n >= 0;
+
+export const buildBootMetricsPayload = (input: BuildPayloadInput): BootMetricPayload => {
+ 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));
+ })();
+
+ const derived: BootMetricSpan[] = [];
+
+ const tryAdd = (name: string, startMs: number, durMs: number) => {
+ if (existingNames.has(name)) return;
+ if (!isFinitePositive(durMs)) return;
+ derived.push({ durMs, name, startMs });
+ };
+
+ if (typeof navResponseStartMs === 'number') {
+ tryAdd('ttfb', 0, navResponseStartMs);
+ }
+
+ if (typeof htmlMarkMs === 'number') {
+ tryAdd('doc', 0, htmlMarkMs);
+ }
+
+ const bundleEval = marks['bundle-eval'];
+ if (typeof htmlMarkMs === 'number' && typeof bundleEval === 'number') {
+ tryAdd('bundle', htmlMarkMs, bundleEval - htmlMarkMs);
+ }
+
+ const appReady = marks['app-ready'];
+ const firstPaint = marks['first-paint'];
+ if (typeof appReady === 'number' && typeof firstPaint === 'number') {
+ tryAdd('store-gate', appReady, firstPaint - appReady);
+ }
+
+ if (typeof fcpMs === 'number') {
+ tryAdd('fcp', 0, fcpMs);
+ }
+
+ if (resourceTimings) {
+ for (const rt of resourceTimings) {
+ if (!existingNames.has(rt.name) && isFinitePositive(rt.durMs)) {
+ derived.push({ durMs: rt.durMs, name: rt.name, startMs: rt.startMs });
+ }
+ }
+ }
+
+ // performance.now() yields sub-millisecond floats; the metrics columns are integer, so round.
+ const spans = [...snapshotSpans, ...derived]
+ .slice(0, 64)
+ .map((s) => ({ durMs: Math.round(s.durMs), name: s.name, startMs: Math.round(s.startMs) }));
+
+ return {
+ ...dimensions,
+ spans,
+ totalMs: Math.round(totalMs),
+ };
+};
diff --git a/src/libs/bootMetrics/finalize.test.ts b/src/libs/bootMetrics/finalize.test.ts
new file mode 100644
index 00000000000..081967ddbb2
--- /dev/null
+++ b/src/libs/bootMetrics/finalize.test.ts
@@ -0,0 +1,172 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ bootTimingSnapshot: vi.fn(() => ({ marks: {}, spans: [] })),
+ getServerConfigStoreState: vi.fn(() => ({ serverConfig: { bootstrapMetricsSampleRate: 1 } })),
+ getUserStoreState: vi.fn(() => ({ user: null })),
+ isLogin: vi.fn(() => false),
+ isProductUsageEventEnabled: vi.fn(() => true),
+}));
+
+vi.mock('@/libs/bootTiming', () => ({
+ bootTiming: { snapshot: mocks.bootTimingSnapshot },
+}));
+
+vi.mock('@/store/serverConfig', () => ({
+ getServerConfigStoreState: mocks.getServerConfigStoreState,
+}));
+
+vi.mock('@/store/user', () => ({
+ getUserStoreState: mocks.getUserStoreState,
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ authSelectors: {
+ isLogin: mocks.isLogin,
+ },
+}));
+
+vi.mock('@/libs/analytics/productUsageEvent', () => ({
+ isProductUsageEventEnabled: mocks.isProductUsageEventEnabled,
+}));
+
+vi.mock('@/const/version', () => ({
+ CURRENT_VERSION: '1.0.0-test',
+ isDesktop: false,
+}));
+
+vi.mock('nanoid', () => ({
+ nanoid: () => 'test-anon-id',
+}));
+
+const INGEST_URL = 'https://ingest.example.com/boot';
+
+describe('startBootMetricsFinalize', () => {
+ let sendBeaconSpy: MockInstance<typeof navigator.sendBeacon>;
+
+ beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+
+ sendBeaconSpy = vi.spyOn(navigator, 'sendBeacon').mockReturnValue(true);
+
+ Object.defineProperty(window, 'requestAnimationFrame', {
+ configurable: true,
+ value: (cb: FrameRequestCallback) => {
+ cb(0);
+ return 0;
+ },
+ writable: true,
+ });
+
+ Object.defineProperty(window, 'requestIdleCallback', {
+ configurable: true,
+ value: (cb: IdleRequestCallback) => {
+ cb({ didTimeout: false, timeRemaining: () => 50 });
+ return 0;
+ },
+ writable: true,
+ });
+
+ Object.defineProperty(window, '__LOBE_BOOT_T_HTML__', {
+ configurable: true,
+ value: undefined,
+ writable: true,
+ });
+
+ vi.spyOn(performance, 'getEntriesByType').mockReturnValue([]);
+ vi.spyOn(performance, 'getEntriesByName').mockReturnValue([]);
+
+ mocks.bootTimingSnapshot.mockReturnValue({ marks: {}, spans: [] });
+ mocks.getServerConfigStoreState.mockReturnValue({
+ serverConfig: { bootstrapMetricsSampleRate: 1 },
+ });
+ mocks.getUserStoreState.mockReturnValue({ user: null });
+ mocks.isLogin.mockReturnValue(false);
+ mocks.isProductUsageEventEnabled.mockReturnValue(true);
+
+ process.env.NEXT_PUBLIC_BOOTSTRAP_METRICS_INGEST_URL = INGEST_URL;
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ delete process.env.NEXT_PUBLIC_BOOTSTRAP_METRICS_INGEST_URL;
+ });
+
+ it('does not call sendBeacon when ingest URL is unset', async () => {
+ delete process.env.NEXT_PUBLIC_BOOTSTRAP_METRICS_INGEST_URL;
+ const { startBootMetricsFinalize } = await import('./finalize');
+ startBootMetricsFinalize();
+ await vi.runAllTimersAsync();
+ expect(sendBeaconSpy).not.toHaveBeenCalled();
+ });
+
+ it('does not call sendBeacon when telemetry is opted out', async () => {
+ mocks.isProductUsageEventEnabled.mockReturnValue(false);
+ const { startBootMetricsFinalize } = await import('./finalize');
+ startBootMetricsFinalize();
+ await vi.runAllTimersAsync();
+ expect(sendBeaconSpy).not.toHaveBeenCalled();
+ });
+
+ it('does not call sendBeacon when sampled out (sampleRate = 0)', async () => {
+ mocks.getServerConfigStoreState.mockReturnValue({
+ serverConfig: { bootstrapMetricsSampleRate: 0 },
+ });
+ vi.spyOn(Math, 'random').mockReturnValue(0.5);
+ const { startBootMetricsFinalize } = await import('./finalize');
+ startBootMetricsFinalize();
+ await vi.runAllTimersAsync();
+ expect(sendBeaconSpy).not.toHaveBeenCalled();
+ });
+
+ it('calls sendBeacon exactly once with text/plain Blob when all gates pass', async () => {
+ const { startBootMetricsFinalize } = await import('./finalize');
+ startBootMetricsFinalize();
+ await vi.runAllTimersAsync();
+
+ expect(sendBeaconSpy).toHaveBeenCalledTimes(1);
+
+ const [url, blob] = sendBeaconSpy.mock.calls[0] as [string, Blob];
+ expect(url).toBe(INGEST_URL);
+ expect(blob).toBeInstanceOf(Blob);
+ expect(blob.type).toBe('text/plain');
+
+ const text = await blob.text();
+ const payload = JSON.parse(text);
+ expect(payload).toMatchObject({
+ appVersion: '1.0.0-test',
+ cold: expect.any(Boolean),
+ isLogin: false,
+ platform: 'web',
+ spans: expect.any(Array),
+ totalMs: expect.any(Number),
+ });
+ });
+
+ it('pagehide fallback sends when idle path has not fired, and sent flag prevents double-send', 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();
+
+ window.dispatchEvent(new Event('pagehide'));
+
+ await vi.runAllTimersAsync();
+
+ expect(sendBeaconSpy).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/libs/bootMetrics/finalize.ts b/src/libs/bootMetrics/finalize.ts
new file mode 100644
index 00000000000..e8dbb55fb84
--- /dev/null
+++ b/src/libs/bootMetrics/finalize.ts
@@ -0,0 +1,142 @@
+import { nanoid } from 'nanoid';
+
+import { CURRENT_VERSION, isDesktop } from '@/const/version';
+import { isProductUsageEventEnabled } from '@/libs/analytics/productUsageEvent';
+import { bootTiming } from '@/libs/bootTiming';
+import { getServerConfigStoreState } from '@/store/serverConfig';
+import { getUserStoreState } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+import { buildBootMetricsPayload } from './buildPayload';
+
+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;
+ }
+};
+
+const getPlatform = (): 'desktop' | 'mobile' | 'web' => {
+ if (isDesktop) return 'desktop';
+ try {
+ if (typeof __MOBILE__ !== 'undefined' && __MOBILE__) return 'mobile';
+ } catch {
+ void 0;
+ }
+ return 'web';
+};
+
+type RequestIdleCallback = (callback: () => void, options?: { timeout?: number }) => number;
+
+const scheduleAfterFirstPaint = (task: () => void): void => {
+ if (typeof window === 'undefined') {
+ task();
+ return;
+ }
+
+ const runWhenIdle = () => {
+ const ric = (window as typeof window & { requestIdleCallback?: RequestIdleCallback })
+ .requestIdleCallback;
+
+ if (typeof ric === 'function') {
+ ric(task, { timeout: 1500 });
+ return;
+ }
+
+ window.setTimeout(task, 0);
+ };
+
+ if (typeof window.requestAnimationFrame === 'function') {
+ window.requestAnimationFrame(runWhenIdle);
+ return;
+ }
+
+ runWhenIdle();
+};
+
+const sendPayload = (ingestUrl: string): void => {
+ if (sent) return;
+
+ try {
+ const snapshot = bootTiming.snapshot();
+ const userState = getUserStoreState();
+
+ const htmlMarkMs =
+ typeof (window as Window & { __LOBE_BOOT_T_HTML__?: number }).__LOBE_BOOT_T_HTML__ ===
+ 'number'
+ ? (window as Window & { __LOBE_BOOT_T_HTML__?: number }).__LOBE_BOOT_T_HTML__
+ : undefined;
+
+ const navEntry = performance.getEntriesByType('navigation')[0] as
+ PerformanceNavigationTiming | undefined;
+ const navResponseStartMs = navEntry?.responseStart;
+
+ const fcpEntry = performance.getEntriesByName('first-contentful-paint')[0];
+ const fcpMs = fcpEntry?.startTime;
+
+ const isLogin = Boolean(authSelectors.isLogin(userState));
+ const userId = userState.user?.id;
+
+ const payload = buildBootMetricsPayload({
+ dimensions: {
+ anonId: nanoid(),
+ appVersion: CURRENT_VERSION,
+ cold: readCold(),
+ isLogin,
+ platform: getPlatform(),
+ userId,
+ },
+ fcpMs,
+ htmlMarkMs,
+ navResponseStartMs,
+ snapshot,
+ });
+
+ if (typeof navigator.sendBeacon === 'function') {
+ navigator.sendBeacon(ingestUrl, new Blob([JSON.stringify(payload)], { type: 'text/plain' }));
+ sent = true;
+ }
+ } catch {
+ void 0;
+ }
+};
+
+export const startBootMetricsFinalize = (): void => {
+ try {
+ const ingestUrl = process.env.NEXT_PUBLIC_BOOTSTRAP_METRICS_INGEST_URL;
+ if (!ingestUrl) return;
+
+ if (!isProductUsageEventEnabled()) return;
+
+ try {
+ const state = getServerConfigStoreState();
+ const sampleRate =
+ (
+ state?.serverConfig as unknown as {
+ bootstrapMetricsSampleRate?: number;
+ }
+ )?.bootstrapMetricsSampleRate ?? 1;
+ if (Math.random() >= sampleRate) return;
+ } catch {
+ void 0;
+ }
+
+ scheduleAfterFirstPaint(() => sendPayload(ingestUrl));
+
+ const pagehideHandler = () => {
+ if (!sent) sendPayload(ingestUrl);
+ window.removeEventListener('pagehide', pagehideHandler);
+ };
+
+ window.addEventListener('pagehide', pagehideHandler, { once: true });
+ } catch {
+ void 0;
+ }
+};
diff --git a/src/libs/bootMetrics/index.ts b/src/libs/bootMetrics/index.ts
new file mode 100644
index 00000000000..cea1fb6b9cf
--- /dev/null
+++ b/src/libs/bootMetrics/index.ts
@@ -0,0 +1 @@
+export { startBootMetricsFinalize } from './finalize';
diff --git a/src/libs/bootTiming/index.test.ts b/src/libs/bootTiming/index.test.ts
new file mode 100644
index 00000000000..6fda39090f7
--- /dev/null
+++ b/src/libs/bootTiming/index.test.ts
@@ -0,0 +1,140 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { bootTiming } from './index';
+
+const resetState = () => {
+ (bootTiming as unknown as { _reset: () => void })._reset();
+};
+
+beforeEach(() => {
+ resetState();
+ vi.spyOn(performance, 'now').mockReturnValue(0);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('bootTiming', () => {
+ it('span records name/startMs/durMs and returns fn value', async () => {
+ const nowMock = vi.spyOn(performance, 'now');
+ nowMock.mockReturnValueOnce(10).mockReturnValueOnce(25);
+
+ const result = await bootTiming.span('init', () => 'ok');
+
+ expect(result).toBe('ok');
+ const { spans } = bootTiming.snapshot();
+ expect(spans).toHaveLength(1);
+ expect(spans[0]).toEqual({ durMs: 15, name: 'init', startMs: 10 });
+ });
+
+ it('span with async fn awaits and times full duration', async () => {
+ const nowMock = vi.spyOn(performance, 'now');
+ nowMock.mockReturnValueOnce(5).mockReturnValueOnce(30);
+
+ const result = await bootTiming.span('fetch', async () => 42);
+
+ expect(result).toBe(42);
+ const { spans } = bootTiming.snapshot();
+ expect(spans[0]).toEqual({ durMs: 25, name: 'fetch', startMs: 5 });
+ });
+
+ it('span records span even when fn throws, and rethrows the error', async () => {
+ const nowMock = vi.spyOn(performance, 'now');
+ nowMock.mockReturnValueOnce(2).mockReturnValueOnce(8);
+
+ const err = new Error('boom');
+ await expect(
+ bootTiming.span('bad', () => {
+ throw err;
+ }),
+ ).rejects.toThrow(err);
+
+ const { spans } = bootTiming.snapshot();
+ expect(spans).toHaveLength(1);
+ expect(spans[0]).toEqual({ durMs: 6, name: 'bad', startMs: 2 });
+ });
+
+ it('mark + measure derive a span with correct startMs/durMs', () => {
+ const nowMock = vi.spyOn(performance, 'now');
+ nowMock.mockReturnValueOnce(100).mockReturnValueOnce(250);
+
+ bootTiming.mark('a');
+ bootTiming.mark('b');
+ bootTiming.measure('a-to-b', 'a', 'b');
+
+ const { spans } = bootTiming.snapshot();
+ expect(spans).toHaveLength(1);
+ expect(spans[0]).toEqual({ durMs: 150, name: 'a-to-b', startMs: 100 });
+ });
+
+ it('measure with a missing mark is a no-op', () => {
+ const nowMock = vi.spyOn(performance, 'now');
+ nowMock.mockReturnValueOnce(10);
+
+ bootTiming.mark('a');
+ expect(() => bootTiming.measure('a-to-b', 'a', 'missing')).not.toThrow();
+
+ const { spans } = bootTiming.snapshot();
+ expect(spans).toHaveLength(0);
+ });
+
+ it('recordSpan appends a span verbatim', () => {
+ bootTiming.recordSpan('resource', 50, 20);
+ const { spans } = bootTiming.snapshot();
+ expect(spans).toHaveLength(1);
+ expect(spans[0]).toEqual({ durMs: 20, name: 'resource', startMs: 50 });
+ });
+
+ it('spanSync records name/startMs/durMs and returns fn value', () => {
+ const nowMock = vi.spyOn(performance, 'now');
+ nowMock.mockReturnValueOnce(10).mockReturnValueOnce(25);
+
+ const result = bootTiming.spanSync('sync-init', () => 'ok');
+
+ expect(result).toBe('ok');
+ const { spans } = bootTiming.snapshot();
+ expect(spans).toHaveLength(1);
+ expect(spans[0]).toEqual({ durMs: 15, name: 'sync-init', startMs: 10 });
+ });
+
+ it('spanSync records span even when fn throws, and rethrows the error', () => {
+ const nowMock = vi.spyOn(performance, 'now');
+ nowMock.mockReturnValueOnce(2).mockReturnValueOnce(8);
+
+ const err = new Error('boom');
+ expect(() =>
+ bootTiming.spanSync('sync-bad', () => {
+ throw err;
+ }),
+ ).toThrow(err);
+
+ const { spans } = bootTiming.snapshot();
+ expect(spans).toHaveLength(1);
+ expect(spans[0]).toEqual({ durMs: 6, name: 'sync-bad', startMs: 2 });
+ });
+
+ it('measure with fromMark absent is a no-op', () => {
+ const nowMock = vi.spyOn(performance, 'now');
+ nowMock.mockReturnValueOnce(10);
+
+ bootTiming.mark('b');
+ expect(() => bootTiming.measure('a-to-b', 'missing', 'b')).not.toThrow();
+
+ const { spans } = bootTiming.snapshot();
+ expect(spans).toHaveLength(0);
+ });
+
+ it('snapshot returns copies — mutating returned data does not affect internal state', () => {
+ bootTiming.recordSpan('x', 1, 2);
+ bootTiming.mark('m');
+
+ const snap1 = bootTiming.snapshot();
+ snap1.spans.push({ durMs: 99, name: 'injected', startMs: 0 });
+ snap1.marks['m'] = 9999;
+
+ const snap2 = bootTiming.snapshot();
+ expect(snap2.spans).toHaveLength(1);
+ expect(snap2.marks['m']).not.toBe(9999);
+ });
+});
diff --git a/src/libs/bootTiming/index.ts b/src/libs/bootTiming/index.ts
new file mode 100644
index 00000000000..92f5a7fda61
--- /dev/null
+++ b/src/libs/bootTiming/index.ts
@@ -0,0 +1,69 @@
+export interface BootSpan {
+ durMs: number;
+ name: string;
+ startMs: number;
+}
+
+const now = (): number => (typeof performance === 'undefined' ? 0 : performance.now());
+
+let spans: BootSpan[] = [];
+let marks: Record<string, number> = {};
+
+export const bootTiming = {
+ mark(name: string): void {
+ try {
+ marks[name] = now();
+ } catch (_) {
+ void _;
+ }
+ },
+
+ measure(name: string, fromMark: string, toMark: string): void {
+ try {
+ if (!(fromMark in marks) || !(toMark in marks)) return;
+ spans.push({ durMs: marks[toMark] - marks[fromMark], name, startMs: marks[fromMark] });
+ } catch (_) {
+ void _;
+ }
+ },
+
+ recordSpan(name: string, startMs: number, durMs: number): void {
+ try {
+ spans.push({ durMs, name, startMs });
+ } catch (_) {
+ void _;
+ }
+ },
+
+ snapshot(): { marks: Record<string, number>; spans: BootSpan[] } {
+ try {
+ return { marks: { ...marks }, spans: [...spans] };
+ } catch (_) {
+ void _;
+ return { marks: {}, spans: [] };
+ }
+ },
+
+ async span<T>(name: string, fn: () => Promise<T> | T): Promise<T> {
+ const start = now();
+ try {
+ return await fn();
+ } finally {
+ spans.push({ durMs: now() - start, name, startMs: start });
+ }
+ },
+
+ spanSync<T>(name: string, fn: () => T): T {
+ const start = now();
+ try {
+ return fn();
+ } finally {
+ spans.push({ durMs: now() - start, name, startMs: start });
+ }
+ },
+
+ _reset(): void {
+ spans = [];
+ marks = {};
+ },
+};
diff --git a/src/libs/swr/localStorageProvider.test.ts b/src/libs/swr/localStorageProvider.test.ts
index 5755dca99be..f95f7acc2e3 100644
--- a/src/libs/swr/localStorageProvider.test.ts
+++ b/src/libs/swr/localStorageProvider.test.ts
@@ -3,6 +3,8 @@
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { bootTiming } from '@/libs/bootTiming';
+
import { taskTemplateKeys } from './keys';
import { buildLocalDataKey, localDataCache } from './localDataCache';
import {
@@ -280,6 +282,61 @@ describe('createCacheProvider — tiering', () => {
});
});
+describe('cache-hydration span', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ (bootTiming as unknown as { _reset: () => void })._reset();
+ });
+
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await localDataCache.clearScope('span-s1');
+ await localDataCache.clearScope('span-s2');
+ });
+
+ it('records exactly one cache-hydration span after initial hydration', async () => {
+ vi.spyOn(performance, 'now').mockReturnValueOnce(100).mockReturnValue(200);
+
+ const scope = { value: 'span-s1' };
+ const { hydrated, provider } = buildProvider(scope);
+ provider();
+ await hydrated;
+
+ const { spans } = bootTiming.snapshot();
+ const hydrationSpans = spans.filter((s) => s.name === 'cache-hydration');
+ expect(hydrationSpans).toHaveLength(1);
+ expect(hydrationSpans[0].startMs).toBe(100);
+ expect(hydrationSpans[0].durMs).toBe(100);
+ });
+
+ it('does not record a second cache-hydration span on scope reload', async () => {
+ vi.spyOn(performance, 'now').mockReturnValue(50);
+
+ const scope = { value: 'span-s1' };
+ const { hydrated, provider } = buildProvider(scope);
+ provider();
+ await hydrated;
+
+ scope.value = 'span-s2';
+ await provider.reloadScope!();
+
+ const { spans } = bootTiming.snapshot();
+ expect(spans.filter((s) => s.name === 'cache-hydration')).toHaveLength(1);
+ });
+
+ it('does not record a span when hydration fails', async () => {
+ vi.spyOn(localDataCache, 'entriesByScope').mockRejectedValueOnce(new Error('idb error'));
+
+ const scope = { value: 'span-s1' };
+ const { hydrated, provider } = buildProvider(scope);
+ provider();
+ await hydrated;
+
+ const { spans } = bootTiming.snapshot();
+ expect(spans.filter((s) => s.name === 'cache-hydration')).toHaveLength(0);
+ });
+});
+
describe('clearSWRCache', () => {
beforeEach(() => localStorage.clear());
diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.ts
index 9aa10b0004d..6679c5e19a7 100644
--- a/src/libs/swr/localStorageProvider.ts
+++ b/src/libs/swr/localStorageProvider.ts
@@ -23,6 +23,8 @@
* </SWRConfig>
* ```
*/
+import { bootTiming } from '@/libs/bootTiming';
+
import { buildLocalDataKey, localDataCache } from './localDataCache';
interface CacheEntry<T = unknown> {
@@ -147,6 +149,7 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS
let hydratedScope: string | null = null;
let hydrationEpoch = 0;
let pendingHydration: { promise: Promise<void>; scope: string } | null = null;
+ let cacheHydrationSpanRecorded = false;
// --- localStorage tier (synchronous snapshot) ----------------------------
let localTimer: ReturnType<typeof setTimeout> | null = null;
@@ -230,7 +233,8 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS
idbTimer = setTimeout(flushIdb, debounceMs);
};
- const loadIdb = async (scope: string, epoch: number) => {
+ const loadIdb = async (scope: string, epoch: number, hydrationStart?: number) => {
+ let succeeded = false;
try {
const entries = await localDataCache.entriesByScope(scope);
// The IndexedDB tier holds read-heavy / write-light business entities
@@ -247,9 +251,18 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS
cacheMapInstance.hydrate(valid.map((e) => [e.key, e.data]));
hydratedScope = scope;
}
+ succeeded = true;
} catch (error) {
onError(error as Error);
} finally {
+ if (hydrationStart !== undefined && succeeded && !cacheHydrationSpanRecorded) {
+ cacheHydrationSpanRecorded = true;
+ bootTiming.recordSpan(
+ 'cache-hydration',
+ hydrationStart,
+ performance.now() - hydrationStart,
+ );
+ }
onScopeHydrated?.(scope);
if (pendingHydration?.scope === scope && hydrationEpoch === epoch) {
pendingHydration = null;
@@ -367,7 +380,8 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS
if (pendingHydration?.scope === scope) return pendingHydration.promise;
const epoch = ++hydrationEpoch;
- const promise = loadIdb(scope, epoch);
+ const start = !cacheHydrationSpanRecorded ? performance.now() : undefined;
+ const promise = loadIdb(scope, epoch, start);
pendingHydration = { promise, scope };
return promise;
};
diff --git a/src/spa/entry.desktop.tsx b/src/spa/entry.desktop.tsx
index f7f385d1b13..a9866215285 100644
--- a/src/spa/entry.desktop.tsx
+++ b/src/spa/entry.desktop.tsx
@@ -4,11 +4,13 @@ import { createRoot } from 'react-dom/client';
import { RouterProvider } from 'react-router/dom';
import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';
+import { bootTiming } from '@/libs/bootTiming';
import { createAppRouter } from '@/utils/router';
import { startAppInitialization } from './initialize/bootstrap';
import { desktopRoutes } from './router/desktopRouter.config';
+bootTiming.mark('bundle-eval');
startAppInitialization();
const router = createAppRouter(desktopRoutes);
diff --git a/src/spa/entry.mobile.tsx b/src/spa/entry.mobile.tsx
index 2e8b5ab90b5..696f28c4ad3 100644
--- a/src/spa/entry.mobile.tsx
+++ b/src/spa/entry.mobile.tsx
@@ -4,11 +4,13 @@ import { createRoot } from 'react-dom/client';
import { RouterProvider } from 'react-router/dom';
import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';
+import { bootTiming } from '@/libs/bootTiming';
import { createAppRouter } from '@/utils/router';
import { startAppInitialization } from './initialize/bootstrap';
import { mobileRoutes } from './router/mobileRouter.config';
+bootTiming.mark('bundle-eval');
startAppInitialization();
const router = createAppRouter(mobileRoutes);
diff --git a/src/spa/entry.popup.tsx b/src/spa/entry.popup.tsx
index e94a5d73f0b..2b04d59d596 100644
--- a/src/spa/entry.popup.tsx
+++ b/src/spa/entry.popup.tsx
@@ -4,11 +4,13 @@ import { createRoot } from 'react-dom/client';
import { RouterProvider } from 'react-router/dom';
import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';
+import { bootTiming } from '@/libs/bootTiming';
import { createAppRouter } from '@/utils/router';
import { startAppInitialization } from './initialize/bootstrap';
import { popupRoutes } from './router/popupRouter.config';
+bootTiming.mark('bundle-eval');
startAppInitialization();
const router = createAppRouter(popupRoutes);
diff --git a/src/spa/entry.web.tsx b/src/spa/entry.web.tsx
index 575fbdb0f2d..5f98440c715 100644
--- a/src/spa/entry.web.tsx
+++ b/src/spa/entry.web.tsx
@@ -5,11 +5,13 @@ import { RouterProvider } from 'react-router/dom';
import BootErrorBoundary from '@/components/BootErrorBoundary';
import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';
+import { bootTiming } from '@/libs/bootTiming';
import { createAppRouter } from '@/utils/router';
import { startAppInitialization } from './initialize/bootstrap';
import { desktopRoutes } from './router/desktopRouter.config';
+bootTiming.mark('bundle-eval');
startAppInitialization();
const debugProxyBase = '/_dangerous_local_dev_proxy';
diff --git a/src/spa/initialize/bootstrap.ts b/src/spa/initialize/bootstrap.ts
index b3bfc7d81d6..3f6546b0a7b 100644
--- a/src/spa/initialize/bootstrap.ts
+++ b/src/spa/initialize/bootstrap.ts
@@ -1,5 +1,8 @@
import { flushSync } from 'react-dom';
+import { startBootMetricsFinalize } from '@/libs/bootMetrics';
+import { bootTiming } from '@/libs/bootTiming';
+
import { setAppReady } from '../atoms/app';
import { initializeApp } from '.';
import { startImportSettingsFromUrl } from './importSettings';
@@ -12,10 +15,12 @@ export const startAppInitialization = () => {
if (started) return;
started = true;
- startImportSettingsFromUrl();
- registerBuiltinToolSurfaces();
+ // must run synchronously before first React render
+ bootTiming.spanSync('import-settings', startImportSettingsFromUrl);
+ bootTiming.spanSync('tool-surfaces', registerBuiltinToolSurfaces);
- void initializeApp()
+ void bootTiming
+ .span('core-init', initializeApp)
.catch((error) => {
console.error('[SPA Initialize] failed', error);
})
@@ -23,6 +28,8 @@ export const startAppInitialization = () => {
flushSync(() => {
setAppReady(true);
});
+ bootTiming.mark('app-ready');
startPostRenderInitialization();
+ startBootMetricsFinalize();
});
};
diff --git a/src/types/global.d.ts b/src/types/global.d.ts
index 21fe524b93b..332c4b9af08 100644
--- a/src/types/global.d.ts
+++ b/src/types/global.d.ts
@@ -20,6 +20,7 @@ declare global {
interface Window {
__DEBUG_PROXY__: boolean | undefined;
__editor?: IEditor;
+ __LOBE_BOOT_T_HTML__?: number;
/** Dev-only: Zustand store snapshots via `getState()` keyed by store name */
__LOBE_STORES?: Record<string, () => unknown>;
__SERVER_CONFIG__: SPAServerConfig | undefined;