🤯 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
✨ feat(analytics): track create agent modal source (#15028)
AmAzing-2b2abca0ae0d
diff --git a/src/libs/analytics/productUsageEvent.test.ts b/src/libs/analytics/productUsageEvent.test.tsnew file mode 100644index 00000000000..70619db57d9--- /dev/null+++ b/src/libs/analytics/productUsageEvent.test.ts@@ -0,0 +1,90 @@+import type { AnalyticsManager } from '@lobehub/analytics';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { isProductUsageEventEnabled, trackProductUsageEvent } from './productUsageEvent';++const telemetryState = vi.hoisted(() => ({ enabled: true }));++vi.mock('@/store/user', () => ({+ getUserStoreState: () => ({ telemetry: telemetryState.enabled }),+}));++vi.mock('@/store/user/selectors', () => ({+ userGeneralSettingsSelectors: {+ telemetry: (state: { telemetry: boolean }) => state.telemetry,+ },+}));++describe('product usage event analytics', () => {+ beforeEach(() => {+ telemetryState.enabled = true;+ vi.clearAllMocks();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('checks settings.general.telemetry', () => {+ expect(isProductUsageEventEnabled()).toBe(true);++ telemetryState.enabled = false;++ expect(isProductUsageEventEnabled()).toBe(false);+ });++ it('tracks when telemetry is enabled', async () => {+ const track = vi.fn().mockResolvedValue(undefined);+ const analytics = {+ getStatus: () => ({ initialized: true, providersCount: 1 }),+ track,+ } as unknown as AnalyticsManager;++ const tracked = await trackProductUsageEvent(+ { name: 'test_event', properties: { source: 'test' } },+ { analytics },+ );++ expect(tracked).toBe(true);+ expect(track).toHaveBeenCalledWith({ name: 'test_event', properties: { source: 'test' } });+ });++ it('does not track when telemetry is disabled', async () => {+ telemetryState.enabled = false;+ const track = vi.fn().mockResolvedValue(undefined);+ const analytics = { track } as unknown as AnalyticsManager;++ const tracked = await trackProductUsageEvent({ name: 'test_event' }, { analytics });++ expect(tracked).toBe(false);+ expect(track).not.toHaveBeenCalled();+ });++ it('does not track before analytics is initialized', async () => {+ const track = vi.fn().mockResolvedValue(undefined);+ const analytics = {+ getStatus: () => ({ initialized: false, providersCount: 1 }),+ track,+ } as unknown as AnalyticsManager;++ const tracked = await trackProductUsageEvent({ name: 'test_event' }, { analytics });++ expect(tracked).toBe(false);+ expect(track).not.toHaveBeenCalled();+ });++ it('logs and returns false when tracking fails', async () => {+ const error = new Error('track failed');+ const track = vi.fn().mockRejectedValue(error);+ const analytics = {+ getStatus: () => ({ initialized: true, providersCount: 1 }),+ track,+ } as unknown as AnalyticsManager;+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ const tracked = await trackProductUsageEvent({ name: 'test_event' }, { analytics });++ expect(tracked).toBe(false);+ expect(consoleError).toHaveBeenCalledWith('Failed to track product usage event:', error);+ });+});diff --git a/src/libs/analytics/productUsageEvent.ts b/src/libs/analytics/productUsageEvent.tsnew file mode 100644index 00000000000..37108ea3fbd--- /dev/null+++ b/src/libs/analytics/productUsageEvent.ts@@ -0,0 +1,33 @@+import type { AnalyticsEvent, AnalyticsManager } from '@lobehub/analytics';+import { getSingletonAnalyticsOptional } from '@lobehub/analytics';++import { getUserStoreState } from '@/store/user';+import { userGeneralSettingsSelectors } from '@/store/user/selectors';++interface TrackProductUsageEventOptions {+ analytics?: AnalyticsManager | null;+}++export const isProductUsageEventEnabled = () =>+ Boolean(userGeneralSettingsSelectors.telemetry(getUserStoreState()));++export const trackProductUsageEvent = async (+ event: AnalyticsEvent,+ options: TrackProductUsageEventOptions = {},+) => {+ 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);+ return true;+ } catch (error) {+ console.error('Failed to track product usage event:', error);+ return false;+ }+};diff --git a/src/routes/(main)/home/_layout/hooks/createAgentModalAnalytics.test.ts b/src/routes/(main)/home/_layout/hooks/createAgentModalAnalytics.test.tsnew file mode 100644index 00000000000..dc792116677--- /dev/null+++ b/src/routes/(main)/home/_layout/hooks/createAgentModalAnalytics.test.ts@@ -0,0 +1,47 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { trackCreateAgentModalCreationSucceeded } from './createAgentModalAnalytics';++const trackProductUsageEvent = vi.hoisted(() => vi.fn());++vi.mock('@/libs/analytics/productUsageEvent', () => ({+ trackProductUsageEvent,+}));++describe('create agent modal analytics', () => {+ beforeEach(() => {+ trackProductUsageEvent.mockReset();+ });++ it('tracks agent submit source', async () => {+ trackProductUsageEvent.mockResolvedValue(true);++ const tracked = await trackCreateAgentModalCreationSucceeded({+ source: 'manual',+ type: 'agent',+ });++ expect(tracked).toBe(true);+ expect(trackProductUsageEvent).toHaveBeenCalledWith(+ {+ name: 'create_agent_modal_creation_succeeded',+ properties: {+ source: 'manual',+ spm: 'home.create_agent_modal.submit',+ type: 'agent',+ },+ },+ { analytics: undefined },+ );+ });++ it('does not track group submits with the agent event name', async () => {+ const tracked = await trackCreateAgentModalCreationSucceeded({+ source: 'manual',+ type: 'group',+ });++ expect(tracked).toBe(false);+ expect(trackProductUsageEvent).not.toHaveBeenCalled();+ });+});diff --git a/src/routes/(main)/home/_layout/hooks/createAgentModalAnalytics.ts b/src/routes/(main)/home/_layout/hooks/createAgentModalAnalytics.tsnew file mode 100644index 00000000000..75dc8242e5e--- /dev/null+++ b/src/routes/(main)/home/_layout/hooks/createAgentModalAnalytics.ts@@ -0,0 +1,31 @@+import type { AnalyticsManager } from '@lobehub/analytics';++import { trackProductUsageEvent } from '@/libs/analytics/productUsageEvent';++export type CreateAgentModalSubmitSource = 'blank' | 'manual' | 'example' | 'example_edited';++interface TrackCreateAgentModalCreationSucceededParams {+ analytics?: AnalyticsManager | null;+ source: CreateAgentModalSubmitSource;+ type: 'agent' | 'group';+}++export const trackCreateAgentModalCreationSucceeded = ({+ analytics,+ source,+ type,+}: TrackCreateAgentModalCreationSucceededParams) => {+ if (type !== 'agent') return Promise.resolve(false);++ return trackProductUsageEvent(+ {+ name: 'create_agent_modal_creation_succeeded',+ properties: {+ source,+ spm: 'home.create_agent_modal.submit',+ type,+ },+ },+ { analytics },+ );+};diff --git a/src/routes/(main)/home/_layout/hooks/useCreateModal.test.tsx b/src/routes/(main)/home/_layout/hooks/useCreateModal.test.tsxnew file mode 100644index 00000000000..049a3e7cb14--- /dev/null+++ b/src/routes/(main)/home/_layout/hooks/useCreateModal.test.tsx@@ -0,0 +1,297 @@+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { CreateAgentModal } from './useCreateModal';++const analyticsTrack = vi.hoisted(() => vi.fn());+const telemetryState = vi.hoisted(() => ({ enabled: true }));+const chatInputState = vi.hoisted(() => {+ interface Editor {+ focus: () => void;+ instance: {+ setDocument: (format: string, content: string) => void;+ };+ }++ interface State {+ editor: Editor;+ onMarkdownContentChange?: (content: string) => void;+ onSend?: () => void;+ }++ const state: State = {+ editor: {+ focus: vi.fn(),+ instance: {+ setDocument: vi.fn((_format: string, content: string) => {+ state.onMarkdownContentChange?.(content);+ }),+ },+ },+ };++ return state;+});++vi.mock('@lobehub/analytics', () => ({+ getSingletonAnalyticsOptional: () => ({+ getStatus: () => ({ initialized: true, providersCount: 1 }),+ track: analyticsTrack,+ }),+}));++vi.mock('@lobehub/ui', () => ({+ ActionIcon: ({ onClick }: { onClick?: () => void }) => (+ <button aria-label="icon action" type="button" onClick={onClick} />+ ),+ Block: ({ children, onClick }: { children?: ReactNode; onClick?: () => void }) => (+ <button type="button" onClick={onClick}>+ {children}+ </button>+ ),+ Button: ({ children, onClick }: { children?: ReactNode; onClick?: () => void }) => (+ <button type="button" onClick={onClick}>+ {children}+ </button>+ ),+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,+}));++vi.mock('@lobehub/ui/base-ui', () => ({+ Modal: ({ children, open }: { children?: ReactNode; open?: boolean }) =>+ open ? <div role="dialog">{children}</div> : null,+}));++vi.mock('antd-style', () => ({+ cssVar: {+ borderRadiusLG: 8,+ colorTextDescription: '#666',+ colorTextSecondary: '#666',+ colorTextTertiary: '#999',+ },+}));++vi.mock('react-i18next', () => ({+ useTranslation: (namespace: string) => ({+ t: (key: string) =>+ (+ ({+ 'chat:createModal.createBlank': 'Create Blank',+ 'chat:createModal.groupPlaceholder': 'Describe what this group should do...',+ 'chat:createModal.groupTitle': 'What should your group do?',+ 'chat:createModal.placeholder': 'Describe what your agent should do...',+ 'chat:createModal.title': 'What should your agent do?',+ 'common:home.suggestQuestions': 'Try these examples',+ 'common:switch': 'Switch',+ 'suggestQuestions:example.prompt': 'Use this example prompt',+ 'suggestQuestions:example.title': 'Example title',+ }) as Record<string, string>+ )[`${namespace}:${key}`] ?? key,+ }),+}));++vi.mock('@/features/ChatInput', () => ({+ ChatInputProvider: ({+ children,+ chatInputEditorRef,+ onMarkdownContentChange,+ onSend,+ }: {+ children?: ReactNode;+ chatInputEditorRef?: (editor: typeof chatInputState.editor) => void;+ onMarkdownContentChange?: (content: string) => void;+ onSend?: () => void;+ }) => {+ chatInputState.onMarkdownContentChange = onMarkdownContentChange;+ chatInputState.onSend = onSend;+ chatInputEditorRef?.(chatInputState.editor);++ return <div>{children}</div>;+ },+ DesktopChatInput: ({ placeholder }: { placeholder?: string }) => (+ <div>+ <textarea+ aria-label="chat input"+ placeholder={placeholder}+ onChange={(event) => {+ chatInputState.onMarkdownContentChange?.(event.currentTarget.value);+ }}+ />+ <button+ type="button"+ onClick={() => {+ chatInputState.onSend?.();+ }}+ >+ Send+ </button>+ </div>+ ),+}));++vi.mock('@/routes/(main)/home/features/SuggestQuestions/useRandomQuestions', () => ({+ useRandomQuestions: () => ({+ questions: [+ {+ id: 'example-1',+ promptKey: 'example.prompt',+ titleKey: 'example.title',+ },+ ],+ refresh: vi.fn(),+ }),+}));++vi.mock('@/store/user', () => ({+ getUserStoreState: () => ({ telemetry: telemetryState.enabled }),+}));++vi.mock('@/store/user/selectors', () => ({+ userGeneralSettingsSelectors: {+ telemetry: (state: { telemetry: boolean }) => state.telemetry,+ },+}));++const renderModal = (type: 'agent' | 'group' = 'agent') => {+ const onClose = vi.fn();+ const onCreateBlank = vi.fn().mockResolvedValue(undefined);+ const onSubmit = vi.fn().mockResolvedValue(undefined);++ render(+ <CreateAgentModal+ open+ agentId="inbox-agent"+ type={type}+ onClose={onClose}+ onCreateBlank={onCreateBlank}+ onSubmit={onSubmit}+ />,+ );++ return { onClose, onCreateBlank, onSubmit };+};++describe('CreateAgentModal analytics', () => {+ beforeEach(() => {+ analyticsTrack.mockReset();+ telemetryState.enabled = true;+ chatInputState.onMarkdownContentChange = undefined;+ chatInputState.onSend = undefined;+ vi.mocked(chatInputState.editor.focus).mockClear();+ vi.mocked(chatInputState.editor.instance.setDocument).mockClear();+ });++ afterEach(() => {+ cleanup();+ });++ it('tracks manual submit source after successful agent creation submit', async () => {+ const { onSubmit } = renderModal();++ fireEvent.change(screen.getByLabelText('chat input'), {+ target: { value: 'Create a research assistant' },+ });+ fireEvent.click(screen.getByText('Send'));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith('Create a research assistant');+ });+ await waitFor(() => {+ expect(analyticsTrack).toHaveBeenCalledWith({+ name: 'create_agent_modal_creation_succeeded',+ properties: {+ source: 'manual',+ spm: 'home.create_agent_modal.submit',+ type: 'agent',+ },+ });+ });+ });++ it('tracks example submit source when the user submits an example unchanged', async () => {+ const { onSubmit } = renderModal();++ fireEvent.click(screen.getByText('Example title'));+ fireEvent.click(screen.getByText('Send'));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith('Use this example prompt');+ });+ await waitFor(() => {+ expect(analyticsTrack).toHaveBeenCalledWith(+ expect.objectContaining({+ properties: expect.objectContaining({ source: 'example' }),+ }),+ );+ });+ });++ it('tracks example_edited when an example is changed before submit', async () => {+ renderModal();++ fireEvent.click(screen.getByText('Example title'));+ fireEvent.change(screen.getByLabelText('chat input'), {+ target: { value: 'Edited example prompt' },+ });+ fireEvent.click(screen.getByText('Send'));++ await waitFor(() => {+ expect(analyticsTrack).toHaveBeenCalledWith(+ expect.objectContaining({+ properties: expect.objectContaining({ source: 'example_edited' }),+ }),+ );+ });+ });++ it('tracks blank source when Create Blank succeeds', async () => {+ const { onCreateBlank } = renderModal();++ fireEvent.click(screen.getByText('Create Blank'));++ await waitFor(() => {+ expect(onCreateBlank).toHaveBeenCalled();+ });+ await waitFor(() => {+ expect(analyticsTrack).toHaveBeenCalledWith({+ name: 'create_agent_modal_creation_succeeded',+ properties: {+ source: 'blank',+ spm: 'home.create_agent_modal.submit',+ type: 'agent',+ },+ });+ });+ });++ it('does not track when telemetry is disabled', async () => {+ telemetryState.enabled = false;+ const { onSubmit } = renderModal();++ fireEvent.change(screen.getByLabelText('chat input'), {+ target: { value: 'Create a research assistant' },+ });+ fireEvent.click(screen.getByText('Send'));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalled();+ });+ expect(analyticsTrack).not.toHaveBeenCalled();+ });++ it('does not track group submits through the create agent event', async () => {+ const { onSubmit } = renderModal('group');++ fireEvent.change(screen.getByLabelText('chat input'), {+ target: { value: 'Create a research group' },+ });+ fireEvent.click(screen.getByText('Send'));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalled();+ });+ expect(analyticsTrack).not.toHaveBeenCalled();+ });+});diff --git a/src/routes/(main)/home/_layout/hooks/useCreateModal.tsx b/src/routes/(main)/home/_layout/hooks/useCreateModal.tsxindex 490af7d69f7..183248a1174 100644--- a/src/routes/(main)/home/_layout/hooks/useCreateModal.tsx+++ b/src/routes/(main)/home/_layout/hooks/useCreateModal.tsx@@ -2,7 +2,7 @@ import { ActionIcon, Block, Button, Flexbox, Text } from '@lobehub/ui';import { Modal } from '@lobehub/ui/base-ui';import { cssVar } from 'antd-style';import { Lightbulb, PencilLineIcon, RefreshCw, X } from 'lucide-react';-import { memo, useCallback, useMemo, useRef, useState } from 'react';+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import {@@ -13,6 +13,9 @@ import {} from '@/features/ChatInput';import { useRandomQuestions } from '@/routes/(main)/home/features/SuggestQuestions/useRandomQuestions';+import type { CreateAgentModalSubmitSource } from './createAgentModalAnalytics';+import { trackCreateAgentModalCreationSucceeded } from './createAgentModalAnalytics';+const LEFT_ACTIONS: ActionKeys[] = ['model'];interface ExampleItemProps {@@ -98,8 +101,8 @@ const Examples = memo<ExamplesProps>(({ suggestMode, onExampleClick }) => {export interface CreateAgentModalProps {agentId?: string;onClose: () => void;- onCreateBlank: () => void;- onSubmit: (prompt: string) => void;+ onCreateBlank: () => Promise<void> | void;+ onSubmit: (prompt: string) => Promise<void> | void;open: boolean;type: 'agent' | 'group';}@@ -109,34 +112,73 @@ export const CreateAgentModal = memo<CreateAgentModalProps>(const { t } = useTranslation('chat');const editorRef = useRef<ChatInputEditor | null>(null);const contentRef = useRef('');+ const examplePromptRef = useRef('');+ const submitSourceRef = useRef<CreateAgentModalSubmitSource>('manual');const [loading, setLoading] = useState(false);const isAgent = type === 'agent';const modalTitle = isAgent ? t('createModal.title') : t('createModal.groupTitle');+ const resetInputTracking = useCallback(() => {+ contentRef.current = '';+ examplePromptRef.current = '';+ submitSourceRef.current = 'manual';+ }, []);++ useEffect(() => {+ if (open) resetInputTracking();+ }, [open, resetInputTracking]);++ const handleClose = useCallback(() => {+ resetInputTracking();+ onClose();+ }, [onClose, resetInputTracking]);++ const getSubmitSource = useCallback((text: string): CreateAgentModalSubmitSource => {+ if (examplePromptRef.current && submitSourceRef.current !== 'manual') {+ return text.trim() === examplePromptRef.current ? 'example' : 'example_edited';+ }++ return submitSourceRef.current;+ }, []);+const handleSubmit = useCallback(async (prompt?: string) => {const text = prompt || contentRef.current.trim();if (!text || loading) return;setLoading(true);- contentRef.current = '';- await onSubmit(text);- setLoading(false);- onClose();+ try {+ await onSubmit(text);+ void trackCreateAgentModalCreationSucceeded({+ source: getSubmitSource(text),+ type,+ });+ handleClose();+ } finally {+ setLoading(false);+ }},- [onClose, onSubmit, loading],+ [getSubmitSource, handleClose, loading, onSubmit, type],);const handleCreateBlank = useCallback(async () => {if (loading) return;setLoading(true);- contentRef.current = '';- await onCreateBlank();- setLoading(false);- onClose();- }, [onClose, onCreateBlank, loading]);+ try {+ await onCreateBlank();+ void trackCreateAgentModalCreationSucceeded({+ source: 'blank',+ type,+ });+ handleClose();+ } finally {+ setLoading(false);+ }+ }, [handleClose, loading, onCreateBlank, type]);const handleExampleClick = useCallback((prompt: string) => {+ examplePromptRef.current = prompt.trim();+ submitSourceRef.current = 'example';editorRef.current?.instance?.setDocument('markdown', prompt);editorRef.current?.focus();contentRef.current = prompt;@@ -176,7 +218,7 @@ export const CreateAgentModal = memo<CreateAgentModalProps>(styles={{body: { padding: 0 },}}- onCancel={onClose}+ onCancel={handleClose}><Flexbox gap={24} paddingBlock={'16px 24px'} paddingInline={24}>{/* Header: Create Blank + Close */}@@ -184,7 +226,7 @@ export const CreateAgentModal = memo<CreateAgentModalProps>(<Button icon={<PencilLineIcon size={14} />} type="text" onClick={handleCreateBlank}>{t('createModal.createBlank')}</Button>- <ActionIcon icon={X} onClick={onClose} />+ <ActionIcon icon={X} onClick={handleClose} /></Flexbox>{/* Title */}<Flexbox align="center">@@ -204,14 +246,23 @@ export const CreateAgentModal = memo<CreateAgentModalProps>(onSend={handleSend}onMarkdownContentChange={(content) => {contentRef.current = content;+ const trimmedContent = content.trim();+ if (+ examplePromptRef.current &&+ (submitSourceRef.current === 'example' ||+ submitSourceRef.current === 'example_edited')+ ) {+ submitSourceRef.current =+ trimmedContent === examplePromptRef.current ? 'example' : 'example_edited';+ }}}><DesktopChatInputinputContainerProps={inputContainerProps}+ showRuntimeConfig={false}placeholder={isAgent ? t('createModal.placeholder') : t('createModal.groupPlaceholder')}- showRuntimeConfig={false}/></ChatInputProvider>)}