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.

⚡️ perf(analytics): load @lobehub/analytics after first paint (#19289)

Innei8a3c6c16fd8f
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 5ae33c44656..ebdc274b425 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -236,6 +236,18 @@ export default eslint(
'Boot-path modules must load EmojiPicker with lazy(); it carries the emoji-mart dataset.',
name: '@/components/EmojiPicker',
},
+ {
+ allowTypeImports: true,
+ message:
+ 'Boot-path modules must not import @lobehub/analytics; it bundles posthog-js. Use "@/libs/analytics/client", which loads it after first paint and queues events.',
+ name: '@lobehub/analytics',
+ },
+ {
+ allowTypeImports: true,
+ message:
+ 'Boot-path modules must not import @lobehub/analytics/react; use useAnalytics from "@/libs/analytics/client".',
+ name: '@lobehub/analytics/react',
+ },
],
patterns: [
{
diff --git a/src/components/Analytics/HomePageTracker.tsx b/src/components/Analytics/HomePageTracker.tsx
index a552b727c0e..c288687f2d7 100644
--- a/src/components/Analytics/HomePageTracker.tsx
+++ b/src/components/Analytics/HomePageTracker.tsx
@@ -1,9 +1,10 @@
'use client';
-import { useAnalytics } from '@lobehub/analytics/react';
import { memo, useEffect } from 'react';
import { useLocation } from 'react-router';
+import { useAnalytics } from '@/libs/analytics/client';
+
const HomePageTracker = memo(() => {
const { analytics } = useAnalytics();
const { pathname } = useLocation();
diff --git a/src/components/Analytics/LobeAnalyticsProvider.tsx b/src/components/Analytics/LobeAnalyticsProvider.tsx
index 95766db308b..01722921a05 100644
--- a/src/components/Analytics/LobeAnalyticsProvider.tsx
+++ b/src/components/Analytics/LobeAnalyticsProvider.tsx
@@ -1,17 +1,14 @@
'use client';
-import {
- type GoogleAnalyticsProviderConfig,
- type PostHogProviderAnalyticsConfig,
- type XAdsProviderAnalyticsConfig,
+import type {
+ GoogleAnalyticsProviderConfig,
+ PostHogProviderAnalyticsConfig,
+ XAdsProviderAnalyticsConfig,
} from '@lobehub/analytics';
-import { createSingletonAnalytics } from '@lobehub/analytics';
-import { AnalyticsProvider } from '@lobehub/analytics/react';
import { type ReactNode } from 'react';
-import { memo, useRef } from 'react';
+import { memo, useEffect } from 'react';
-import { BUSINESS_LINE } from '@/const/analytics';
-import { isDesktop } from '@/const/version';
+import { loadAnalytics } from '@/libs/analytics/client';
type Props = {
children: ReactNode;
@@ -20,52 +17,24 @@ type Props = {
xAdsConfig: XAdsProviderAnalyticsConfig;
};
-let analyticsInstance: ReturnType<typeof createSingletonAnalytics> | null = null;
+const scheduleIdle = (task: () => void) => {
+ if (typeof window.requestIdleCallback === 'function') {
+ window.requestIdleCallback(task, { timeout: 3000 });
+ return;
+ }
+
+ window.setTimeout(task, 0);
+};
export const LobeAnalyticsProvider = memo(
({ children, ga4Config, postHogConfig, xAdsConfig }: Props) => {
- const analyticsRef = useRef<ReturnType<typeof createSingletonAnalytics> | null>(null);
-
- if (!analyticsRef.current) {
- analyticsRef.current =
- analyticsInstance ||
- createSingletonAnalytics({
- business: BUSINESS_LINE,
- // Keep the manager-level logs (`[AnalyticsManager] ...`) quiet even in dev
- debug: false,
- providers: {
- ga4: ga4Config,
- posthog: postHogConfig,
- xAds: xAdsConfig,
- },
- });
-
- analyticsInstance = analyticsRef.current;
- }
-
- const analytics = analyticsRef.current;
-
- if (!analytics) return children;
-
- return (
- <AnalyticsProvider
- client={analytics}
- onInitializeSuccess={() => {
- analyticsInstance?.setGlobalContext({
- platform: isDesktop ? 'desktop' : 'web',
- });
+ useEffect(() => {
+ scheduleIdle(() => {
+ void loadAnalytics({ ga4: ga4Config, posthog: postHogConfig, xAds: xAdsConfig });
+ });
+ }, [ga4Config, postHogConfig, xAdsConfig]);
- analyticsInstance
- ?.getProvider('posthog')
- ?.getNativeInstance()
- ?.register({
- platform: isDesktop ? 'desktop' : 'web',
- });
- }}
- >
- {children}
- </AnalyticsProvider>
- );
+ return children;
},
() => true,
);
diff --git a/src/components/Analytics/X.tsx b/src/components/Analytics/X.tsx
index 21e325287ac..3633812a61e 100644
--- a/src/components/Analytics/X.tsx
+++ b/src/components/Analytics/X.tsx
@@ -1,6 +1,6 @@
'use client';
-import { createAnalytics, getSingletonAnalyticsOptional } from '@lobehub/analytics';
+import type { AnalyticsManager } from '@lobehub/analytics';
import { memo, useEffect, useRef } from 'react';
import { BUSINESS_LINE } from '@/const/analytics';
@@ -13,33 +13,38 @@ interface XAdsProps {
}
const XAds = memo<XAdsProps>(({ eventIds, pixelId, purchaseEventId }) => {
- const analyticsRef = useRef<ReturnType<typeof createAnalytics> | null>(null);
+ const analyticsRef = useRef<AnalyticsManager | null>(null);
useEffect(() => {
- const singletonAnalytics = getSingletonAnalyticsOptional();
- if (singletonAnalytics?.getProvider('xAds')) {
- return;
- }
-
- if (!analyticsRef.current) {
- analyticsRef.current = createAnalytics({
- business: BUSINESS_LINE,
- debug: isDev,
- providers: {
- xAds: {
- debug: isDev,
- eventIds,
- enabled: !!pixelId,
- pixelId: pixelId ?? '',
- purchaseEventId,
+ let cancelled = false;
+
+ void import('@lobehub/analytics').then(({ createAnalytics, getSingletonAnalyticsOptional }) => {
+ if (cancelled || getSingletonAnalyticsOptional()?.getProvider('xAds')) return;
+
+ if (!analyticsRef.current) {
+ analyticsRef.current = createAnalytics({
+ business: BUSINESS_LINE,
+ debug: isDev,
+ providers: {
+ xAds: {
+ debug: isDev,
+ eventIds,
+ enabled: !!pixelId,
+ pixelId: pixelId ?? '',
+ purchaseEventId,
+ },
},
- },
- });
- }
+ });
+ }
- analyticsRef.current.initialize().catch((error) => {
- console.error('[X Ads Bootstrap] Initialization failed:', error);
+ analyticsRef.current.initialize().catch((error) => {
+ console.error('[X Ads Bootstrap] Initialization failed:', error);
+ });
});
+
+ return () => {
+ cancelled = true;
+ };
}, [eventIds, pixelId, purchaseEventId]);
return null;
diff --git a/src/features/AgentSetting/store/action.ts b/src/features/AgentSetting/store/action.ts
index 9b09df59cea..b7f962dbb05 100644
--- a/src/features/AgentSetting/store/action.ts
+++ b/src/features/AgentSetting/store/action.ts
@@ -7,10 +7,10 @@ import {
} from '@lobechat/prompts';
import { type TracePayload } from '@lobechat/types';
import { TraceNameMap, TraceTopicType } from '@lobechat/types';
-import { getSingletonAnalyticsOptional } from '@lobehub/analytics';
import { type PartialDeep } from 'type-fest';
import { type StateCreator } from 'zustand/vanilla';
+import { analyticsClient } from '@/libs/analytics/client';
import { chatService } from '@/services/chat';
import { globalHelpers } from '@/store/global/helpers';
import { useUserStore } from '@/store/user';
@@ -311,23 +311,20 @@ export const store: StateCreator<Store, [['zustand/devtools', never]]> = (set, g
const mergedMeta = merge(currentMeta, meta);
try {
- const analytics = getSingletonAnalyticsOptional();
- if (analytics) {
- analytics.track({
- name: 'agent_meta_updated',
- properties: {
- assistant_avatar: mergedMeta.avatar,
- assistant_background_color: mergedMeta.backgroundColor,
- assistant_description: mergedMeta.description,
- assistant_name: mergedMeta.title,
- assistant_tags: mergedMeta.tags,
- is_inbox: id === 'inbox',
- session_id: id || 'unknown',
- timestamp: Date.now(),
- user_id: useUserStore.getState().user?.id || 'anonymous',
- },
- });
- }
+ void analyticsClient.track({
+ name: 'agent_meta_updated',
+ properties: {
+ assistant_avatar: mergedMeta.avatar,
+ assistant_background_color: mergedMeta.backgroundColor,
+ assistant_description: mergedMeta.description,
+ assistant_name: mergedMeta.title,
+ assistant_tags: mergedMeta.tags,
+ is_inbox: id === 'inbox',
+ session_id: id || 'unknown',
+ timestamp: Date.now(),
+ user_id: useUserStore.getState().user?.id || 'anonymous',
+ },
+ });
} catch (error) {
console.warn('Failed to track agent meta update:', error);
}
diff --git a/src/features/Auth/SignIn/useSignIn.test.ts b/src/features/Auth/SignIn/useSignIn.test.ts
index 4559f859cc4..e257609b85b 100644
--- a/src/features/Auth/SignIn/useSignIn.test.ts
+++ b/src/features/Auth/SignIn/useSignIn.test.ts
@@ -55,6 +55,7 @@ vi.mock('@/libs/better-auth/utils/client', () => ({
vi.mock('@lobechat/business-const', () => ({
BRANDING_NAME: 'LobeHub',
+ ORG_NAME: 'LobeHub',
}));
vi.mock('@/business/client/hooks/useBusinessSignin', () => ({
diff --git a/src/features/Auth/SignUp/useSignUp.test.ts b/src/features/Auth/SignUp/useSignUp.test.ts
index bd864e1746c..ca31e79bf75 100644
--- a/src/features/Auth/SignUp/useSignUp.test.ts
+++ b/src/features/Auth/SignUp/useSignUp.test.ts
@@ -26,6 +26,7 @@ vi.mock('@/libs/better-auth/auth-client', () => ({
vi.mock('@lobechat/business-const', () => ({
BRANDING_NAME: 'LobeHub',
+ ORG_NAME: 'LobeHub',
}));
vi.mock('@/business/client/hooks/useBusinessSignup', () => ({
diff --git a/src/features/Billboard/Carousel.tsx b/src/features/Billboard/Carousel.tsx
index d85d02018fb..8428b8338c2 100644
--- a/src/features/Billboard/Carousel.tsx
+++ b/src/features/Billboard/Carousel.tsx
@@ -1,6 +1,5 @@
'use client';
-import { useAnalytics } from '@lobehub/analytics/react';
import { Flexbox, Tooltip } from '@lobehub/ui';
import { ActionIcon, Button } from '@lobehub/ui/base-ui';
import { Carousel as AntCarousel } from 'antd';
@@ -19,6 +18,7 @@ import {
} from 'react';
import { useTranslation } from 'react-i18next';
+import { useAnalytics } from '@/libs/analytics/client';
import type { GlobalBillboard, GlobalBillboardItem } from '@/types/serverConfig';
import { resolveBillboardAction, runBillboardAction } from './actions';
diff --git a/src/features/Billboard/index.tsx b/src/features/Billboard/index.tsx
index 676764a3b1c..16f3ed43b6f 100644
--- a/src/features/Billboard/index.tsx
+++ b/src/features/Billboard/index.tsx
@@ -1,8 +1,8 @@
'use client';
-import { useAnalytics } from '@lobehub/analytics/react';
import { memo, useCallback, useState } from 'react';
+import { useAnalytics } from '@/libs/analytics/client';
import { useGlobalStore } from '@/store/global';
import { useServerConfigStore } from '@/store/serverConfig';
diff --git a/src/features/HomeSidebar/Footer/index.test.tsx b/src/features/HomeSidebar/Footer/index.test.tsx
index cdfb9094321..d73fbbb90f0 100644
--- a/src/features/HomeSidebar/Footer/index.test.tsx
+++ b/src/features/HomeSidebar/Footer/index.test.tsx
@@ -70,7 +70,7 @@ const renderFooter = async ({
analytics: { track: analyticsTrack },
};
}
- vi.doMock('@lobehub/analytics/react', () => ({
+ vi.doMock('@/libs/analytics/client', () => ({
useAnalytics: createAnalyticsApi,
}));
vi.doMock('@/components/ChangelogModal', () => ({
@@ -149,7 +149,7 @@ afterEach(() => {
cleanup();
vi.unstubAllGlobals();
vi.doUnmock('@lobechat/const');
- vi.doUnmock('@lobehub/analytics/react');
+ vi.doUnmock('@/libs/analytics/client');
vi.doUnmock('@/components/ChangelogModal');
vi.doUnmock('@/components/FeedbackModal');
vi.doUnmock('@/features/Billboard');
diff --git a/src/features/HomeSidebar/Footer/index.tsx b/src/features/HomeSidebar/Footer/index.tsx
index 2e9b2657be8..e4eab4d6b84 100644
--- a/src/features/HomeSidebar/Footer/index.tsx
+++ b/src/features/HomeSidebar/Footer/index.tsx
@@ -1,7 +1,6 @@
'use client';
import { SOCIAL_URL } from '@lobechat/business-const';
-import { useAnalytics } from '@lobehub/analytics/react';
import { type MenuProps } from '@lobehub/ui';
import { DropdownMenu, Flexbox, Icon } from '@lobehub/ui';
import { ActionIcon } from '@lobehub/ui/base-ui';
@@ -30,6 +29,7 @@ import { useActiveNavKey } from '@/features/NavPanel/useActiveNavKey';
import ThemeButton from '@/features/User/UserPanel/ThemeButton';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useNavLayout } from '@/hooks/useNavLayout';
+import { useAnalytics } from '@/libs/analytics/client';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/slices/settings/selectors/general';
diff --git a/src/features/HomeSidebar/hooks/useCreateModal.test.tsx b/src/features/HomeSidebar/hooks/useCreateModal.test.tsx
index edb4211607a..c56fb127f01 100644
--- a/src/features/HomeSidebar/hooks/useCreateModal.test.tsx
+++ b/src/features/HomeSidebar/hooks/useCreateModal.test.tsx
@@ -44,11 +44,8 @@ const chatInputState = vi.hoisted(() => {
return state;
});
-vi.mock('@lobehub/analytics', () => ({
- getSingletonAnalyticsOptional: () => ({
- getStatus: () => ({ initialized: true, providersCount: 1 }),
- track: analyticsTrack,
- }),
+vi.mock('@/libs/analytics/client', () => ({
+ analyticsClient: { track: analyticsTrack },
}));
vi.mock('@lobehub/ui', async (importOriginal) => ({
diff --git a/src/features/MobileHome/SessionListContent/List/index.tsx b/src/features/MobileHome/SessionListContent/List/index.tsx
index 4de88f8b04f..a0f38a2cac8 100644
--- a/src/features/MobileHome/SessionListContent/List/index.tsx
+++ b/src/features/MobileHome/SessionListContent/List/index.tsx
@@ -1,4 +1,3 @@
-import { useAnalytics } from '@lobehub/analytics/react';
import { createStaticStyles } from 'antd-style';
import { memo } from 'react';
import LazyLoad from 'react-lazy-load';
@@ -6,6 +5,7 @@ import { Link } from 'react-router';
import { AGENT_CHAT_URL } from '@/const/index';
import { useNavigateToAgent } from '@/hooks/useNavigateToAgent';
+import { useAnalytics } from '@/libs/analytics/client';
import { useServerConfigStore } from '@/store/serverConfig';
import { getSessionStoreState, useSessionStore } from '@/store/session';
import { sessionGroupSelectors, sessionSelectors } from '@/store/session/selectors';
diff --git a/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.test.ts b/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.test.ts
index 9e034da0fb4..ab880ce6117 100644
--- a/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.test.ts
+++ b/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.test.ts
@@ -2,19 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { trackLoginOrSignupClicked } from './trackLoginOrSignupClicked';
-const getSingletonAnalyticsOptional = vi.hoisted(() => vi.fn());
-vi.mock('@lobehub/analytics', () => ({ getSingletonAnalyticsOptional }));
-
-const makeAnalytics = (initialized = true) => {
- const track = vi.fn().mockResolvedValue(undefined);
- const initialize = vi.fn().mockResolvedValue(undefined);
- const analytics = {
- getStatus: () => ({ initialized, providersCount: 1 }),
- initialize,
- track,
- };
- return { analytics, initialize, track };
-};
+const track = vi.hoisted(() => vi.fn());
+vi.mock('@/libs/analytics/client', () => ({ analyticsClient: { track } }));
const resetEnv = () => {
window.sessionStorage.clear();
@@ -24,6 +13,7 @@ const resetEnv = () => {
describe('trackLoginOrSignupClicked', () => {
beforeEach(() => {
vi.clearAllMocks();
+ track.mockResolvedValue(undefined);
resetEnv();
});
@@ -33,8 +23,6 @@ describe('trackLoginOrSignupClicked', () => {
});
it('attaches the lh_cid from the current URL', async () => {
- const { analytics, track } = makeAnalytics();
- getSingletonAnalyticsOptional.mockReturnValue(analytics);
window.history.replaceState({}, '', '/signup?lh_cid=cid-url');
await trackLoginOrSignupClicked({ spm: 'signup.submit.click' });
@@ -46,8 +34,6 @@ describe('trackLoginOrSignupClicked', () => {
});
it('falls back to the lh_cid the shell beacon stored in sessionStorage', async () => {
- const { analytics, track } = makeAnalytics();
- getSingletonAnalyticsOptional.mockReturnValue(analytics);
window.sessionStorage.setItem('lh_cid', 'cid-storage');
await trackLoginOrSignupClicked({ provider: 'google', spm: 'signin.social.click' });
@@ -59,9 +45,6 @@ describe('trackLoginOrSignupClicked', () => {
});
it('omits lh_cid entirely when no landing click id is present', async () => {
- const { analytics, track } = makeAnalytics();
- getSingletonAnalyticsOptional.mockReturnValue(analytics);
-
await trackLoginOrSignupClicked({ spm: 'homepage.login_or_signup.click' });
expect(track).toHaveBeenCalledWith({
@@ -70,41 +53,9 @@ describe('trackLoginOrSignupClicked', () => {
});
});
- it('initializes analytics first when it is not yet initialized', async () => {
- const { analytics, initialize, track } = makeAnalytics(false);
- getSingletonAnalyticsOptional.mockReturnValue(analytics);
-
- await trackLoginOrSignupClicked({ spm: 'signin.email_step.submit' });
-
- expect(initialize).toHaveBeenCalledTimes(1);
- expect(track).toHaveBeenCalledTimes(1);
- });
-
- it('does not initialize again when analytics is already initialized', async () => {
- const { analytics, initialize, track } = makeAnalytics(true);
- getSingletonAnalyticsOptional.mockReturnValue(analytics);
-
- await trackLoginOrSignupClicked({ spm: 'signin.password_step.submit' });
-
- expect(initialize).not.toHaveBeenCalled();
- expect(track).toHaveBeenCalledTimes(1);
- });
-
- it('no-ops without throwing when analytics is unavailable', async () => {
- getSingletonAnalyticsOptional.mockReturnValue(undefined);
-
- await expect(
- trackLoginOrSignupClicked({ spm: 'homepage.login_or_signup.click' }),
- ).resolves.toBeUndefined();
- });
-
it('swallows and logs a tracking failure', async () => {
const error = new Error('boom');
- const track = vi.fn().mockRejectedValue(error);
- getSingletonAnalyticsOptional.mockReturnValue({
- getStatus: () => ({ initialized: true, providersCount: 1 }),
- track,
- });
+ track.mockRejectedValue(error);
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
await trackLoginOrSignupClicked({ spm: 'signup.submit.click' });
diff --git a/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.ts b/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.ts
index 9792fc32b35..364ae63fbec 100644
--- a/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.ts
+++ b/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.ts
@@ -1,4 +1,4 @@
-import { getSingletonAnalyticsOptional } from '@lobehub/analytics';
+import { analyticsClient } from '@/libs/analytics/client';
import { resolveLandingClickId } from './landingClickId';
@@ -8,29 +8,18 @@ interface TrackLoginOrSignupClickedParams {
}
export const trackLoginOrSignupClicked = ({ provider, spm }: TrackLoginOrSignupClickedParams) => {
- const analytics = getSingletonAnalyticsOptional();
- if (!analytics) return Promise.resolve();
+ const lhCid = resolveLandingClickId();
- const sendEvent = async () => {
- const status = analytics.getStatus();
-
- if (!status.initialized) {
- await analytics.initialize();
- }
-
- const lhCid = resolveLandingClickId();
-
- await analytics.track({
+ return analyticsClient
+ .track({
name: 'login_or_signup_clicked',
properties: {
...(lhCid && { lh_cid: lhCid }),
...(provider && { provider }),
spm,
},
+ })
+ .catch((error) => {
+ console.error('Failed to track login_or_signup_clicked:', error);
});
- };
-
- return sendEvent().catch((error) => {
- console.error('Failed to track login_or_signup_clicked:', error);
- });
};
diff --git a/src/libs/analytics/client.test.ts b/src/libs/analytics/client.test.ts
new file mode 100644
index 00000000000..e930314b5c3
--- /dev/null
+++ b/src/libs/analytics/client.test.ts
@@ -0,0 +1,52 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { __testing, analyticsClient, loadAnalytics } from './client';
+
+const fake = vi.hoisted(() => ({
+ getProvider: vi.fn(),
+ identify: vi.fn(),
+ initialize: vi.fn().mockResolvedValue(undefined),
+ setGlobalContext: vi.fn(),
+ track: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('@lobehub/analytics', () => ({ createSingletonAnalytics: () => fake }));
+
+const config = {
+ ga4: { enabled: false, measurementId: '' },
+ posthog: { enabled: false, host: '', key: '' },
+ xAds: { enabled: false, pixelId: '' },
+} as Parameters<typeof loadAnalytics>[0];
+
+describe('analytics client', () => {
+ beforeEach(() => {
+ __testing.reset();
+ vi.clearAllMocks();
+ });
+
+ it('queues events fired before the library loads and flushes them in order', async () => {
+ void analyticsClient.track({ name: 'first' });
+ analyticsClient.identify('u1', { email: '[email protected]' });
+ void analyticsClient.track({ name: 'second' });
+
+ expect(fake.track).not.toHaveBeenCalled();
+
+ await loadAnalytics(config);
+
+ expect(fake.track.mock.calls.map(([event]) => event.name)).toEqual(['first', 'second']);
+ expect(fake.identify).toHaveBeenCalledWith('u1', { email: '[email protected]' });
+ });
+
+ it('forwards directly once loaded', async () => {
+ await loadAnalytics(config);
+ await analyticsClient.track({ name: 'live' });
+
+ expect(fake.track).toHaveBeenCalledWith({ name: 'live' });
+ });
+
+ it('loads the library only once', async () => {
+ await Promise.all([loadAnalytics(config), loadAnalytics(config)]);
+
+ expect(fake.initialize).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/libs/analytics/client.ts b/src/libs/analytics/client.ts
new file mode 100644
index 00000000000..c6ce781a116
--- /dev/null
+++ b/src/libs/analytics/client.ts
@@ -0,0 +1,92 @@
+import type {
+ AnalyticsEvent,
+ AnalyticsManager,
+ GoogleAnalyticsProviderConfig,
+ PostHogProviderAnalyticsConfig,
+ XAdsProviderAnalyticsConfig,
+} from '@lobehub/analytics';
+
+import { BUSINESS_LINE } from '@/const/analytics';
+import { isDesktop } from '@/const/version';
+
+export interface AnalyticsClientConfig {
+ ga4: GoogleAnalyticsProviderConfig;
+ posthog: PostHogProviderAnalyticsConfig;
+ xAds: XAdsProviderAnalyticsConfig;
+}
+
+type Pending =
+ | { event: AnalyticsEvent; type: 'track' }
+ | { traits: Record<string, unknown>; type: 'identify'; userId: string };
+
+let manager: AnalyticsManager | null = null;
+let loading: Promise<AnalyticsManager | null> | null = null;
+const QUEUE_LIMIT = 100;
+const queue: Pending[] = [];
+
+const enqueue = (item: Pending) => {
+ if (queue.length >= QUEUE_LIMIT) queue.shift();
+ queue.push(item);
+};
+
+const apply = (item: Pending) => {
+ if (!manager) return;
+ if (item.type === 'track') void manager.track(item.event);
+ else manager.identify(item.userId, item.traits);
+};
+
+// @lobehub/analytics bundles posthog-js; loading it after first paint keeps it
+// off the first screen, and the queue keeps events fired before then.
+export const loadAnalytics = (config: AnalyticsClientConfig) => {
+ if (loading) return loading;
+
+ loading = import('@lobehub/analytics')
+ .then(async ({ createSingletonAnalytics }) => {
+ const instance = createSingletonAnalytics({
+ business: BUSINESS_LINE,
+ debug: false,
+ providers: config,
+ });
+ await instance.initialize();
+
+ const platform = isDesktop ? 'desktop' : 'web';
+ instance.setGlobalContext({ platform });
+ instance.getProvider('posthog')?.getNativeInstance()?.register({ platform });
+
+ manager = instance;
+ for (const item of queue.splice(0)) apply(item);
+ return instance;
+ })
+ .catch((error) => {
+ console.error('[Analytics] initialization failed:', error);
+ queue.length = 0;
+ return null;
+ });
+
+ return loading;
+};
+
+export const getAnalyticsManager = () => manager;
+
+export const analyticsClient = {
+ identify: (userId: string, traits: Record<string, unknown>) => {
+ if (manager) void manager.identify(userId, traits);
+ else enqueue({ traits, type: 'identify', userId });
+ },
+ track: async (event: AnalyticsEvent) => {
+ if (manager) return manager.track(event);
+ enqueue({ event, type: 'track' });
+ },
+};
+
+export type AnalyticsClient = typeof analyticsClient;
+
+export const useAnalytics = () => ({ analytics: analyticsClient });
+
+export const __testing = {
+ reset: () => {
+ manager = null;
+ loading = null;
+ queue.length = 0;
+ },
+};
diff --git a/src/libs/analytics/productUsageEvent.ts b/src/libs/analytics/productUsageEvent.ts
index 37108ea3fbd..7c9398c59d3 100644
--- a/src/libs/analytics/productUsageEvent.ts
+++ b/src/libs/analytics/productUsageEvent.ts
@@ -1,6 +1,6 @@
import type { AnalyticsEvent, AnalyticsManager } from '@lobehub/analytics';
-import { getSingletonAnalyticsOptional } from '@lobehub/analytics';
+import { analyticsClient } from '@/libs/analytics/client';
import { getUserStoreState } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/selectors';
@@ -17,14 +17,13 @@ export const trackProductUsageEvent = async (
) => {
if (!isProductUsageEventEnabled()) return false;
- const analytics = options.analytics ?? getSingletonAnalyticsOptional();
- if (!analytics) return false;
-
try {
- const status = analytics.getStatus();
- if (!status.initialized) return false;
-
- await analytics.track(event);
+ if (options.analytics) {
+ if (!options.analytics.getStatus().initialized) return false;
+ await options.analytics.track(event);
+ } else {
+ await analyticsClient.track(event);
+ }
return true;
} catch (error) {
console.error('Failed to track product usage event:', error);
diff --git a/src/services/onboardingMetrics/index.test.ts b/src/services/onboardingMetrics/index.test.ts
index 2fb9174f288..0abbefc7f38 100644
--- a/src/services/onboardingMetrics/index.test.ts
+++ b/src/services/onboardingMetrics/index.test.ts
@@ -18,11 +18,11 @@ import {
} from './index';
const analyticsMocks = vi.hoisted(() => ({
- getSingletonAnalyticsOptional: vi.fn(),
+ track: vi.fn(),
}));
-vi.mock('@lobehub/analytics', () => ({
- getSingletonAnalyticsOptional: analyticsMocks.getSingletonAnalyticsOptional,
+vi.mock('@/libs/analytics/client', () => ({
+ analyticsClient: { track: analyticsMocks.track },
}));
describe('onboardingMetrics', () => {
@@ -30,8 +30,7 @@ describe('onboardingMetrics', () => {
beforeEach(() => {
track.mockReset();
- analyticsMocks.getSingletonAnalyticsOptional.mockReset();
- analyticsMocks.getSingletonAnalyticsOptional.mockReturnValue(null);
+ analyticsMocks.track.mockReset();
setOnboardingAnalyticsClient({ track });
});
@@ -216,10 +215,9 @@ describe('onboardingMetrics', () => {
});
});
- it('falls back to the global analytics singleton when no explicit client is configured', () => {
- const singletonTrack = vi.fn();
+ it('falls back to the deferred analytics client when no explicit client is configured', () => {
+ const singletonTrack = analyticsMocks.track;
setOnboardingAnalyticsClient(null);
- analyticsMocks.getSingletonAnalyticsOptional.mockReturnValue({ track: singletonTrack });
trackOnboardingStepViewed({
flow: 'classic',
diff --git a/src/services/onboardingMetrics/index.ts b/src/services/onboardingMetrics/index.ts
index 5b339924832..1191e6f837c 100644
--- a/src/services/onboardingMetrics/index.ts
+++ b/src/services/onboardingMetrics/index.ts
@@ -1,4 +1,4 @@
-import { getSingletonAnalyticsOptional } from '@lobehub/analytics';
+import { analyticsClient } from '@/libs/analytics/client';
export const ONBOARDING_METRICS_EVENTS = {
COMPLETED: 'onboarding_completed',
@@ -32,15 +32,14 @@ interface AnalyticsLike {
track: (event: { name: string; properties?: Record<string, unknown> }) => unknown;
}
-let analyticsClient: AnalyticsLike | null = null;
+let injectedClient: AnalyticsLike | null = null;
export const setOnboardingAnalyticsClient = (client: AnalyticsLike | null): void => {
- analyticsClient = client;
+ injectedClient = client;
};
const emit = (name: string, properties: Record<string, unknown>): void => {
- const client = analyticsClient ?? getSingletonAnalyticsOptional();
- if (!client) return;
+ const client = injectedClient ?? analyticsClient;
try {
client.track({ name, properties });
diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.ts
index 6c85fcf589c..506d8c242d9 100644
--- a/src/store/agent/slices/agent/action.ts
+++ b/src/store/agent/slices/agent/action.ts
@@ -6,7 +6,6 @@ import {
type LobeAgentAgencyConfig,
pruneWorkingDirByDeviceDeletes,
} from '@lobechat/types';
-import { getSingletonAnalyticsOptional } from '@lobehub/analytics';
import { toast } from '@lobehub/ui/base-ui';
import isEqual from 'fast-deep-equal';
import { t } from 'i18next';
@@ -16,6 +15,7 @@ import type { PartialDeep } from 'type-fest';
import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { MESSAGE_CANCEL_FLAT } from '@/const/message';
+import { analyticsClient } from '@/libs/analytics/client';
import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';
import { agentConfigKeys, builtinAgentKeys } from '@/libs/swr/keys';
import { getCacheScope } from '@/libs/swr/useCacheScope';
@@ -183,22 +183,17 @@ export class AgentSliceActionImpl {
const result = await agentService.createAgent({ ...params, config });
this.#get().invalidateAvailableAgents();
- // Track new agent creation analytics
- const analytics = getSingletonAnalyticsOptional();
- if (analytics) {
- const userStore = getUserStoreState();
- const userId = userProfileSelectors.userId(userStore);
-
- analytics.track({
- name: 'new_agent_created',
- properties: {
- agent_id: result.agentId,
- assistant_name: params.config?.title || 'Untitled Agent',
- assistant_tags: params.config?.tags || [],
- user_id: userId || 'anonymous',
- },
- });
- }
+ const userId = userProfileSelectors.userId(getUserStoreState());
+
+ void analyticsClient.track({
+ name: 'new_agent_created',
+ properties: {
+ agent_id: result.agentId,
+ assistant_name: params.config?.title || 'Untitled Agent',
+ assistant_tags: params.config?.tags || [],
+ user_id: userId || 'anonymous',
+ },
+ });
return result;
};
diff --git a/src/store/session/slices/session/action.ts b/src/store/session/slices/session/action.ts
index 75a1bc51f16..222181b9a8c 100644
--- a/src/store/session/slices/session/action.ts
+++ b/src/store/session/slices/session/action.ts
@@ -1,4 +1,3 @@
-import { getSingletonAnalyticsOptional } from '@lobehub/analytics';
import { toast } from '@lobehub/ui/base-ui';
import isEqual from 'fast-deep-equal';
import { t } from 'i18next';
@@ -7,6 +6,7 @@ import useSWR from 'swr';
import { type PartialDeep } from 'type-fest';
import { DEFAULT_AGENT_LOBE_SESSION, INBOX_SESSION_ID } from '@/const/session';
+import { analyticsClient } from '@/libs/analytics/client';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { sessionKeys } from '@/libs/swr/keys';
import { chatGroupService } from '@/services/chatGroup';
@@ -71,22 +71,17 @@ export class SessionActionImpl {
const id = await sessionService.createSession(LobeSessionType.Agent, newSession);
await refreshSessions();
- // Track new agent creation analytics
- const analytics = getSingletonAnalyticsOptional();
- if (analytics) {
- const userStore = getUserStoreState();
- const userId = userProfileSelectors.userId(userStore);
-
- analytics.track({
- name: 'new_agent_created',
- properties: {
- assistant_name: newSession.meta?.title || 'Untitled Agent',
- assistant_tags: newSession.meta?.tags || [],
- session_id: id,
- user_id: userId || 'anonymous',
- },
- });
- }
+ const userId = userProfileSelectors.userId(getUserStoreState());
+
+ void analyticsClient.track({
+ name: 'new_agent_created',
+ properties: {
+ assistant_name: newSession.meta?.title || 'Untitled Agent',
+ assistant_tags: newSession.meta?.tags || [],
+ session_id: id,
+ user_id: userId || 'anonymous',
+ },
+ });
// Whether to goto to the new session after creation, the default is to switch to
if (isSwitchSession) switchSession(id);
diff --git a/src/store/user/slices/common/action.ts b/src/store/user/slices/common/action.ts
index 9d9abf62e2a..9ef3b5adb61 100644
--- a/src/store/user/slices/common/action.ts
+++ b/src/store/user/slices/common/action.ts
@@ -1,11 +1,11 @@
import { isDesktop } from '@lobechat/const';
import type { UserGeneralConfig } from '@lobechat/types';
-import { getSingletonAnalyticsOptional } from '@lobehub/analytics';
import { type SWRResponse } from 'swr';
import useSWR from 'swr';
import { type PartialDeep } from 'type-fest';
import { DEFAULT_PREFERENCE } from '@/const/user';
+import { analyticsClient } from '@/libs/analytics/client';
import { mutate, useOnlyFetchOnceSWR } from '@/libs/swr';
import { taskTemplateKeys, userKeys } from '@/libs/swr/keys';
import { userService } from '@/services/user';
@@ -201,9 +201,7 @@ export class CommonActionImpl {
.catch(() => {});
}
- //analytics
- const analytics = getSingletonAnalyticsOptional();
- analytics?.identify(data.userId || '', {
+ analyticsClient.identify(data.userId || '', {
email: data.email,
firstName: data.firstName,
lastName: data.lastName,