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: agent builder

Shinji-Lie3c945423f33
diff --git a/packages/const/src/user.ts b/packages/const/src/user.ts
index a6e41017e57..f40a2057f37 100644
--- a/packages/const/src/user.ts
+++ b/packages/const/src/user.ts
@@ -1,15 +1,20 @@
import { TopicDisplayMode, UserPreference } from '@lobechat/types';
+/**
+ * Current onboarding flow version.
+ * Increment this value when the onboarding flow changes significantly,
+ * which will trigger existing users to go through onboarding again.
+ */
+export const CURRENT_ONBOARDING_VERSION = 1;
+
export const DEFAULT_PREFERENCE: UserPreference = {
guide: {
moveSettingsToAvatar: true,
topic: true,
},
lab: {
- enableGroupChat: false,
enableInputMarkdown: true,
},
- telemetry: null,
topicDisplayMode: TopicDisplayMode.ByTime,
useCmdEnterToSend: false,
};
diff --git a/src/app/[variants]/(main)/chat/profile/features/EditorCanvas/TypoBar.tsx b/src/app/[variants]/(main)/chat/profile/features/EditorCanvas/TypoBar.tsx
new file mode 100644
index 00000000000..1c41ddb9972
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/EditorCanvas/TypoBar.tsx
@@ -0,0 +1,139 @@
+import { HotkeyEnum, getHotkeyById } from '@lobehub/editor';
+import { FloatActions } from '@lobehub/editor/react';
+import { type ChatInputActionsProps, CodeLanguageSelect } from '@lobehub/editor/react';
+import {
+ BoldIcon,
+ CodeXmlIcon,
+ ItalicIcon,
+ ListIcon,
+ ListOrderedIcon,
+ ListTodoIcon,
+ MessageSquareQuote,
+ SigmaIcon,
+ SquareDashedBottomCodeIcon,
+ StrikethroughIcon,
+ UnderlineIcon,
+} from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useProfileStore } from '../store';
+
+const TypoBar = memo(() => {
+ const { t } = useTranslation('editor');
+ const editorState = useProfileStore((s) => s.editorState);
+
+ const items: ChatInputActionsProps['items'] = useMemo(() => {
+ if (!editorState) return [];
+
+ return [
+ {
+ active: editorState.isBold,
+ icon: BoldIcon,
+ key: 'bold',
+ label: t('typobar.bold'),
+ onClick: editorState.bold,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Bold).keys },
+ },
+ {
+ active: editorState.isItalic,
+ icon: ItalicIcon,
+ key: 'italic',
+ label: t('typobar.italic'),
+ onClick: editorState.italic,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Italic).keys },
+ },
+ {
+ active: editorState.isUnderline,
+ icon: UnderlineIcon,
+ key: 'underline',
+ label: t('typobar.underline'),
+ onClick: editorState.underline,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Underline).keys },
+ },
+ {
+ active: editorState.isStrikethrough,
+ icon: StrikethroughIcon,
+ key: 'strikethrough',
+ label: t('typobar.strikethrough'),
+ onClick: editorState.strikethrough,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Strikethrough).keys },
+ },
+ {
+ type: 'divider',
+ },
+
+ {
+ icon: ListIcon,
+ key: 'bulletList',
+ label: t('typobar.bulletList'),
+ onClick: editorState.bulletList,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.BulletList).keys },
+ },
+ {
+ icon: ListOrderedIcon,
+ key: 'numberlist',
+ label: t('typobar.numberList'),
+ onClick: editorState.numberList,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.NumberList).keys },
+ },
+ {
+ icon: ListTodoIcon,
+ key: 'tasklist',
+ label: t('typobar.taskList'),
+ onClick: editorState.checkList,
+ },
+ {
+ type: 'divider',
+ },
+ {
+ active: editorState.isBlockquote,
+ icon: MessageSquareQuote,
+ key: 'blockquote',
+ label: t('typobar.blockquote'),
+ onClick: editorState.blockquote,
+ },
+ {
+ type: 'divider',
+ },
+ {
+ icon: SigmaIcon,
+ key: 'math',
+ label: t('typobar.tex'),
+ onClick: editorState.insertMath,
+ },
+ {
+ active: editorState.isCode,
+ icon: CodeXmlIcon,
+ key: 'code',
+ label: t('typobar.code'),
+ onClick: editorState.code,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.CodeInline).keys },
+ },
+ {
+ icon: SquareDashedBottomCodeIcon,
+ key: 'codeblock',
+ label: t('typobar.codeblock'),
+ onClick: editorState.codeblock,
+ },
+ editorState.isCodeblock && {
+ children: (
+ <CodeLanguageSelect
+ onSelect={(value) => editorState.updateCodeblockLang(value)}
+ value={editorState.codeblockLang}
+ />
+ ),
+ disabled: !editorState.isCodeblock,
+ key: 'codeblockLang',
+ },
+ ].filter(Boolean) as ChatInputActionsProps['items'];
+ }, [editorState, t]);
+
+ if (!editorState) return null;
+
+ return <FloatActions items={items} />;
+});
+
+TypoBar.displayName = 'TypoBar';
+
+export default TypoBar;
diff --git a/src/app/[variants]/(main)/chat/profile/features/EditorCanvas/index.tsx b/src/app/[variants]/(main)/chat/profile/features/EditorCanvas/index.tsx
new file mode 100644
index 00000000000..07de552d2e9
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/EditorCanvas/index.tsx
@@ -0,0 +1,144 @@
+'use client';
+
+import {
+ ReactCodePlugin,
+ ReactCodeblockPlugin,
+ ReactHRPlugin,
+ ReactLinkHighlightPlugin,
+ ReactListPlugin,
+ ReactMathPlugin,
+ ReactMentionPlugin,
+ ReactTablePlugin,
+ ReactToolbarPlugin,
+} from '@lobehub/editor';
+import { Editor } from '@lobehub/editor/react';
+import isEqual from 'fast-deep-equal';
+import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+
+import { useMentionOptions } from '../ProfileEditor/MentionList';
+import PROMPT_TEMPLATE from '../ProfileEditor/promptTemplate.json';
+import { useProfileStore } from '../store';
+import TypoBar from './TypoBar';
+import { useSlashItems } from './useSlashItems';
+
+const EditorCanvas = memo(() => {
+ const { t } = useTranslation('setting');
+ const [editorInit, setEditorInit] = useState(false);
+ const [contentInit, setContentInit] = useState(false);
+ const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);
+ const editorData = config?.editorData;
+ const systemRole = config?.systemRole;
+ const updateConfig = useAgentStore((s) => s.updateAgentConfig);
+ const [initialLoad] = useState(editorData || PROMPT_TEMPLATE);
+ const mentionOptions = useMentionOptions();
+ const editor = useProfileStore((s) => s.editor);
+ const handleContentChange = useProfileStore((s) => s.handleContentChange);
+ const slashItems = useSlashItems();
+
+ // Streaming state from AgentStore
+ const streamingSystemRole = useAgentStore((s) => s.streamingSystemRole);
+ const streamingInProgress = useAgentStore((s) => s.streamingSystemRoleInProgress);
+ const prevStreamingRef = useRef<string | undefined>(undefined);
+ const wasStreamingRef = useRef(false);
+
+ // Wrap handleContentChange with updateConfig
+ const handleChange = useCallback(() => {
+ // Don't trigger save during streaming
+ if (streamingInProgress) return;
+ handleContentChange(updateConfig);
+ }, [handleContentChange, updateConfig, streamingInProgress]);
+
+ // Handle streaming updates - update editor with streaming content
+ useEffect(() => {
+ if (!editor || !editorInit) return;
+ if (!streamingInProgress) {
+ prevStreamingRef.current = undefined;
+ return;
+ }
+
+ // Only update if content has changed
+ if (streamingSystemRole !== prevStreamingRef.current) {
+ prevStreamingRef.current = streamingSystemRole;
+ try {
+ editor.setDocument('markdown', streamingSystemRole || '');
+ } catch {
+ // Ignore errors during streaming updates
+ }
+ }
+ }, [editor, editorInit, streamingSystemRole, streamingInProgress]);
+
+ // Trigger save when streaming ends
+ useEffect(() => {
+ if (wasStreamingRef.current && !streamingInProgress && editor && editorInit) {
+ // Streaming just ended, wait for editor to update its internal state then save
+ // This ensures editorData (json) is properly updated from the markdown content
+ const timer = setTimeout(() => {
+ handleContentChange(updateConfig);
+ }, 100);
+ return () => clearTimeout(timer);
+ }
+ wasStreamingRef.current = !!streamingInProgress;
+ }, [streamingInProgress, editor, editorInit, handleContentChange, updateConfig]);
+
+ useEffect(() => {
+ if (!editorInit || !editor || contentInit) return;
+ // Don't init if streaming is in progress
+ if (streamingInProgress) return;
+ try {
+ if (editorData) {
+ editor.setDocument('json', editorData || PROMPT_TEMPLATE);
+ } else if (systemRole) {
+ editor.setDocument('markdown', systemRole);
+ } else {
+ editor.setDocument('json', PROMPT_TEMPLATE);
+ }
+ setContentInit(true);
+ } catch (error) {
+ console.error('[EditorCanvas] Failed to init editor content:', error);
+ }
+ }, [editorInit, contentInit, editor, editorData, systemRole, streamingInProgress]);
+
+ return (
+ <div
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ }}
+ >
+ <Editor
+ content={initialLoad}
+ editor={editor!}
+ lineEmptyPlaceholder={t('settingAgent.prompt.placeholder')}
+ mentionOption={mentionOptions}
+ onInit={() => setEditorInit(true)}
+ onTextChange={handleChange}
+ placeholder={t('settingAgent.prompt.placeholder')}
+ plugins={[
+ ReactListPlugin,
+ ReactCodePlugin,
+ ReactCodeblockPlugin,
+ ReactHRPlugin,
+ ReactLinkHighlightPlugin,
+ ReactTablePlugin,
+ ReactMathPlugin,
+ ReactMentionPlugin,
+ Editor.withProps(ReactToolbarPlugin, {
+ children: <TypoBar />,
+ }),
+ ]}
+ slashOption={{
+ items: slashItems,
+ }}
+ style={{
+ paddingBottom: 64,
+ }}
+ />
+ </div>
+ );
+});
+
+export default EditorCanvas;
diff --git a/src/app/[variants]/(main)/chat/profile/features/EditorCanvas/useSlashItems.tsx b/src/app/[variants]/(main)/chat/profile/features/EditorCanvas/useSlashItems.tsx
new file mode 100644
index 00000000000..ec0e15d4a3a
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/EditorCanvas/useSlashItems.tsx
@@ -0,0 +1,139 @@
+import {
+ INSERT_CHECK_LIST_COMMAND,
+ INSERT_HEADING_COMMAND,
+ INSERT_HORIZONTAL_RULE_COMMAND,
+ INSERT_MATH_COMMAND,
+ INSERT_ORDERED_LIST_COMMAND,
+ INSERT_TABLE_COMMAND,
+ INSERT_UNORDERED_LIST_COMMAND,
+ SlashOptions,
+} from '@lobehub/editor';
+import { Text } from '@lobehub/ui';
+import {
+ Heading1Icon,
+ Heading2Icon,
+ Heading3Icon,
+ ListIcon,
+ ListOrderedIcon,
+ ListTodoIcon,
+ MinusIcon,
+ SigmaIcon,
+ SquareDashedBottomCodeIcon,
+ Table2Icon,
+} from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useProfileStore } from '../store';
+
+export const useSlashItems = (): SlashOptions['items'] => {
+ const { t } = useTranslation('editor');
+ const editorState = useProfileStore((s) => s.editorState);
+ return useMemo(() => {
+ const data: SlashOptions['items'] = [
+ {
+ icon: Heading1Icon,
+ key: 'h1',
+ label: t('slash.h1'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h1' });
+ },
+ },
+ {
+ icon: Heading2Icon,
+ key: 'h2',
+ label: t('slash.h2'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h2' });
+ },
+ },
+ {
+ icon: Heading3Icon,
+ key: 'h3',
+ label: t('slash.h3'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h3' });
+ },
+ },
+ {
+ type: 'divider',
+ },
+ {
+ icon: ListTodoIcon,
+ key: 'tl',
+ label: t('typobar.taskList'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_CHECK_LIST_COMMAND, undefined);
+ },
+ },
+ {
+ icon: ListIcon,
+ key: 'ul',
+ label: t('typobar.bulletList'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, undefined);
+ },
+ },
+ {
+ icon: ListOrderedIcon,
+ key: 'ol',
+ label: t('typobar.numberList'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined);
+ },
+ },
+ {
+ type: 'divider',
+ },
+ {
+ icon: MinusIcon,
+ key: 'hr',
+ label: t('slash.hr'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_HORIZONTAL_RULE_COMMAND, {});
+ },
+ },
+ {
+ icon: Table2Icon,
+ key: 'table',
+ label: t('slash.table'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_TABLE_COMMAND, { columns: '3', rows: '3' });
+ },
+ },
+ {
+ icon: SquareDashedBottomCodeIcon,
+ key: 'codeblock',
+ label: t('typobar.codeblock'),
+ onSelect: () => {
+ editorState?.codeblock();
+ },
+ },
+ {
+ icon: SigmaIcon,
+ key: 'tex',
+ label: t('slash.tex'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_MATH_COMMAND, { code: 'x^2 + y^2 = z^2' });
+ queueMicrotask(() => {
+ editor.focus();
+ });
+ },
+ },
+ ];
+ return data.map((item) => {
+ if (item.type === 'divider') return item;
+ return {
+ ...item,
+ extra: (
+ <Text code fontSize={12} type={'secondary'}>
+ {item.key}
+ </Text>
+ ),
+ style: {
+ minWidth: 200,
+ },
+ };
+ });
+ }, [t]);
+};
diff --git a/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/PublishButton.tsx b/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/PublishButton.tsx
new file mode 100644
index 00000000000..8bf25ae2427
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/PublishButton.tsx
@@ -0,0 +1,138 @@
+import { ActionIcon } from '@lobehub/ui';
+import { ShapesUploadIcon } from '@lobehub/ui/icons';
+import { memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { message } from '@/components/AntdStaticMethods';
+import { HEADER_ICON_SIZE } from '@/const/layoutTokens';
+import { checkOwnership } from '@/hooks/useAgentOwnershipCheck';
+import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
+import { resolveMarketAuthError } from '@/layout/AuthProvider/MarketAuth/errors';
+import { useServerConfigStore } from '@/store/serverConfig';
+
+import type { MarketPublishAction } from './types';
+import { useMarketPublish } from './useMarketPublish';
+
+interface MarketPublishButtonProps {
+ action: MarketPublishAction;
+ marketIdentifier?: string;
+ onPublishSuccess?: (identifier: string) => void;
+}
+
+const PublishButton = memo<MarketPublishButtonProps>(
+ ({ action, marketIdentifier, onPublishSuccess }) => {
+ const { t } = useTranslation(['setting', 'marketAuth']);
+
+ const mobile = useServerConfigStore((s) => s.isMobile);
+
+ const { isAuthenticated, isLoading, session, signIn } = useMarketAuth();
+ const { isPublishing, publish } = useMarketPublish({
+ action,
+ onSuccess: onPublishSuccess,
+ });
+
+ const buttonConfig = useMemo(() => {
+ if (action === 'upload') {
+ return {
+ authSuccessMessage: t('messages.success.upload', { ns: 'marketAuth' }),
+ authenticated: t('marketPublish.upload.tooltip'),
+ unauthenticated: t('marketPublish.upload.tooltip'),
+ } as const;
+ }
+
+ const submitText = t('submitAgentModal.tooltips');
+
+ return {
+ authSuccessMessage: t('messages.success.submit', { ns: 'marketAuth' }),
+ authenticated: submitText,
+ unauthenticated: t('marketPublish.submit.tooltip'),
+ } as const;
+ }, [action, t]);
+
+ const handleButtonClick = useCallback(async () => {
+ if (!isAuthenticated) {
+ try {
+ const accountId = await signIn();
+ // Check ownership after authentication if marketIdentifier exists
+ if (marketIdentifier && accountId !== null) {
+ let accessToken = session?.accessToken;
+
+ if (!accessToken && typeof window !== 'undefined') {
+ const storedSession = sessionStorage.getItem('market_auth_session');
+ if (storedSession) {
+ try {
+ const parsed = JSON.parse(storedSession) as { accessToken?: string };
+ accessToken = parsed.accessToken;
+ } catch (parseError) {
+ console.error(
+ '[MarketPublishButton] Failed to parse stored session:',
+ parseError,
+ );
+ }
+ }
+ }
+
+ if (accessToken) {
+ try {
+ const isOwner = await checkOwnership({
+ accessToken,
+ accountId,
+ marketIdentifier,
+ skipCache: true,
+ });
+
+ // If user is not the owner and trying to upload, just return
+ // The parent component should handle the action switch
+ if (!isOwner && action === 'upload') {
+ return;
+ }
+ } catch (ownershipError) {
+ console.error('[MarketPublishButton] Failed to confirm ownership:', ownershipError);
+ }
+ }
+ }
+
+ // After authentication, proceed with publish
+ await publish();
+ } catch (error) {
+ console.error(`[MarketPublishButton][${action}] Authorization failed:`, error);
+ const normalizedError = resolveMarketAuthError(error);
+ message.error({
+ content: t(`errors.${normalizedError.code}`, { ns: 'marketAuth' }),
+ key: 'market-auth',
+ });
+ }
+ return;
+ }
+
+ // User is authenticated, directly publish
+ await publish();
+ }, [
+ action,
+ buttonConfig.authSuccessMessage,
+ isAuthenticated,
+ marketIdentifier,
+ publish,
+ session?.accessToken,
+ signIn,
+ t,
+ ]);
+
+ const buttonTitle = isAuthenticated ? buttonConfig.authenticated : buttonConfig.unauthenticated;
+ const loading = isLoading || isPublishing;
+
+ return (
+ <ActionIcon
+ icon={ShapesUploadIcon}
+ loading={loading}
+ onClick={handleButtonClick}
+ size={HEADER_ICON_SIZE(mobile)}
+ title={buttonTitle}
+ />
+ );
+ },
+);
+
+PublishButton.displayName = 'MarketPublishButton';
+
+export default PublishButton;
diff --git a/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/PublishResultModal.tsx b/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/PublishResultModal.tsx
new file mode 100644
index 00000000000..14989bfdcb1
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/PublishResultModal.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import { FluentEmoji, Modal, Text } from '@lobehub/ui';
+import { Result } from 'antd';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+
+interface PublishResultModalProps {
+ identifier?: string;
+ onCancel: () => void;
+ open: boolean;
+}
+
+const PublishResultModal = memo<PublishResultModalProps>(({ identifier, onCancel, open }) => {
+ const navigate = useNavigate();
+ const { t } = useTranslation('setting');
+ const { t: tCommon } = useTranslation('common');
+
+ const handleGoToMarket = () => {
+ if (identifier) {
+ navigate(`/community/assistant/${identifier}`);
+ }
+ onCancel();
+ };
+
+ return (
+ <Modal
+ cancelText={tCommon('cancel')}
+ centered
+ okText={t('marketPublish.resultModal.view')}
+ onCancel={onCancel}
+ onOk={handleGoToMarket}
+ open={open}
+ title={null}
+ width={440}
+ >
+ <Result
+ icon={<FluentEmoji emoji={'🎉'} size={96} type={'anim'} />}
+ style={{
+ paddingBottom: 32,
+ paddingTop: 48,
+ width: '100%',
+ }}
+ subTitle={
+ <Text fontSize={14} type={'secondary'}>
+ {t('marketPublish.resultModal.message')}
+ </Text>
+ }
+ title={
+ <Text fontSize={28} weight={'bold'}>
+ {t('marketPublish.resultModal.title')}
+ </Text>
+ }
+ />
+ </Modal>
+ );
+});
+
+export default PublishResultModal;
diff --git a/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/index.tsx b/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/index.tsx
new file mode 100644
index 00000000000..e11a691d207
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/index.tsx
@@ -0,0 +1,80 @@
+import { ActionIcon } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import { Loader2 } from 'lucide-react';
+import { memo, useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentOwnershipCheck } from '@/hooks/useAgentOwnershipCheck';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+
+import PublishButton from './PublishButton';
+import PublishResultModal from './PublishResultModal';
+
+const AgentPublishButton = memo(() => {
+ const { t } = useTranslation('setting');
+ const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
+ const { isOwnAgent } = useAgentOwnershipCheck(meta?.marketIdentifier);
+
+ const [showResultModal, setShowResultModal] = useState(false);
+ const [publishedIdentifier, setPublishedIdentifier] = useState<string>();
+
+ const handlePublishSuccess = useCallback((identifier: string) => {
+ setPublishedIdentifier(identifier);
+ setShowResultModal(true);
+ }, []);
+
+ const buttonType = useMemo(() => {
+ if (!meta?.marketIdentifier) {
+ return 'submit';
+ }
+ if (isOwnAgent === null) {
+ return 'loading';
+ }
+ if (isOwnAgent === true) {
+ return 'upload';
+ }
+ return 'submit';
+ }, [meta?.marketIdentifier, isOwnAgent]);
+
+ const content = useMemo(() => {
+ switch (buttonType) {
+ case 'upload': {
+ return (
+ <PublishButton
+ action="upload"
+ marketIdentifier={meta?.marketIdentifier}
+ onPublishSuccess={handlePublishSuccess}
+ />
+ );
+ }
+
+ case 'submit': {
+ return (
+ <PublishButton
+ action="submit"
+ marketIdentifier={meta?.marketIdentifier}
+ onPublishSuccess={handlePublishSuccess}
+ />
+ );
+ }
+
+ default: {
+ return <ActionIcon disabled icon={Loader2} loading title={t('checkingPermissions')} />;
+ }
+ }
+ }, [buttonType, meta?.marketIdentifier]);
+
+ return (
+ <>
+ {content}
+ <PublishResultModal
+ identifier={publishedIdentifier}
+ onCancel={() => setShowResultModal(false)}
+ open={showResultModal}
+ />
+ </>
+ );
+});
+
+export default AgentPublishButton;
diff --git a/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/types.ts b/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/types.ts
new file mode 100644
index 00000000000..f1378b670cf
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/types.ts
@@ -0,0 +1 @@
+export type MarketPublishAction = 'submit' | 'upload';
diff --git a/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/useMarketPublish.ts b/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/useMarketPublish.ts
new file mode 100644
index 00000000000..3617c82c9bc
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/useMarketPublish.ts
@@ -0,0 +1,185 @@
+import isEqual from 'fast-deep-equal';
+import { useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { message } from '@/components/AntdStaticMethods';
+import { useTokenCount } from '@/hooks/useTokenCount';
+import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
+import { marketApiService } from '@/services/marketApi';
+import { useAgentStore } from '@/store/agent';
+import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
+import { useGlobalStore } from '@/store/global';
+import { globalGeneralSelectors } from '@/store/global/selectors';
+
+import type { MarketPublishAction } from './types';
+import { generateDefaultChangelog, generateMarketIdentifier } from './utils';
+
+interface UseMarketPublishOptions {
+ action: MarketPublishAction;
+ onSuccess?: (identifier: string) => void;
+}
+
+export const useMarketPublish = ({ action, onSuccess }: UseMarketPublishOptions) => {
+ const { t } = useTranslation('setting');
+ const [isPublishing, setIsPublishing] = useState(false);
+ const { isAuthenticated, session } = useMarketAuth();
+
+ // Agent data from store
+ const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
+ const updateAgentMeta = useAgentStore((s) => s.updateAgentMeta);
+ const systemRole = useAgentStore(agentSelectors.currentAgentSystemRole);
+ const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);
+ const editorData = config?.editorData;
+ const language = useGlobalStore(globalGeneralSelectors.currentLanguage);
+ const agentConfig = useAgentStore(agentSelectors.currentAgentConfig);
+ const chatConfig = useAgentStore(agentChatConfigSelectors.currentChatConfig);
+ const plugins = useAgentStore(agentSelectors.currentAgentPlugins);
+ const model = useAgentStore(agentSelectors.currentAgentModel);
+ const provider = useAgentStore(agentSelectors.currentAgentModelProvider);
+ const tokenUsage = useTokenCount(systemRole);
+
+ const isSubmit = action === 'submit';
+
+ const publish = useCallback(async () => {
+ if (!isAuthenticated || !session?.accessToken) {
+ return { success: false };
+ }
+
+ const messageKey = isSubmit ? 'submit' : 'upload-version';
+ const loadingMessage = isSubmit
+ ? t('marketPublish.modal.loading.submit')
+ : t('marketPublish.modal.loading.upload');
+
+ let identifier = meta?.marketIdentifier;
+
+ const changelog = generateDefaultChangelog();
+
+ try {
+ setIsPublishing(true);
+ message.loading({ content: loadingMessage, key: messageKey });
+ marketApiService.setAccessToken(session.accessToken);
+
+ if (isSubmit) {
+ identifier = generateMarketIdentifier();
+
+ try {
+ await marketApiService.getAgentDetail(identifier);
+ } catch {
+ const createPayload: Record<string, unknown> = {
+ identifier,
+ name: meta?.title || '',
+ };
+ await marketApiService.createAgent(createPayload as any);
+ }
+ } else if (!identifier) {
+ message.error({
+ content: t('marketPublish.modal.messages.missingIdentifier'),
+ key: messageKey,
+ });
+ return { success: false };
+ }
+
+ const versionPayload = {
+ avatar: meta?.avatar,
+ changelog,
+ config: {
+ chatConfig: {
+ enableHistoryCount: chatConfig?.enableHistoryCount,
+ historyCount: chatConfig?.historyCount,
+ maxTokens: agentConfig?.params?.max_tokens,
+ searchMode: chatConfig?.searchMode,
+ temperature: agentConfig?.params?.temperature,
+ topP: agentConfig?.params?.top_p,
+ },
+ description: meta?.description,
+ locale: language,
+ model: {
+ model,
+ parameters: agentConfig?.params,
+ provider,
+ },
+ plugins:
+ plugins?.map((plugin) => {
+ if (typeof plugin === 'string') {
+ return plugin;
+ } else {
+ return null;
+ }
+ }) || [],
+ systemRole: systemRole,
+ },
+ description: meta?.description || '',
+ editorData: editorData,
+ identifier: identifier,
+ name: meta?.title || '',
+ tags: meta?.tags,
+ tokenUsage: tokenUsage,
+ };
+
+ try {
+ await marketApiService.createAgentVersion(versionPayload);
+ } catch (versionError) {
+ const errorMessage = versionError instanceof Error ? versionError.message : '未知错误';
+ message.error({
+ content: t('marketPublish.modal.messages.createVersionFailed', {
+ message: errorMessage,
+ }),
+ key: messageKey,
+ });
+ return { success: false };
+ }
+
+ if (isSubmit) {
+ updateAgentMeta({ marketIdentifier: identifier });
+ }
+
+ message.success({
+ content: t('submitAgentModal.success'),
+ key: messageKey,
+ });
+
+ onSuccess?.(identifier!);
+ return { identifier, success: true };
+ } catch (error) {
+ console.error('Market publish failed:', error);
+ const errorMessage = error instanceof Error ? error.message : '发布失败';
+ message.error({
+ content: t('marketPublish.modal.messages.publishFailed', {
+ message: errorMessage,
+ }),
+ key: messageKey,
+ });
+ return { success: false };
+ } finally {
+ setIsPublishing(false);
+ }
+ }, [
+ agentConfig?.params,
+ chatConfig?.enableHistoryCount,
+ chatConfig?.historyCount,
+ chatConfig?.searchMode,
+ editorData,
+ isAuthenticated,
+ isSubmit,
+ language,
+ meta?.avatar,
+ meta?.description,
+ meta?.marketIdentifier,
+ meta?.tags,
+ meta?.title,
+ model,
+ onSuccess,
+ plugins,
+ provider,
+ session?.accessToken,
+ systemRole,
+ tokenUsage,
+ t,
+ updateAgentMeta,
+ ]);
+
+ return {
+ isPublishing,
+ publish,
+ };
+};
diff --git a/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/utils.ts b/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/utils.ts
new file mode 100644
index 00000000000..877a3a75479
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/Header/AgentPublishButton/utils.ts
@@ -0,0 +1,22 @@
+import { customAlphabet } from 'nanoid/non-secure';
+
+/**
+ * Generate a market identifier (8-character lowercase alphanumeric string)
+ * Format: [a-z0-9]{8}
+ * @returns A unique 8-character market identifier
+ */
+export const generateMarketIdentifier = () => {
+ const alphabet = '0123456789abcdefghijklmnopqrstuvwxyz';
+ const generate = customAlphabet(alphabet, 8);
+ return generate();
+};
+
+/**
+ * Generate a default changelog based on current timestamp
+ * @returns A timestamp-based changelog string
+ */
+export const generateDefaultChangelog = () => {
+ const now = new Date();
+ const formattedDate = now.toISOString().split('T')[0];
+ return `Release ${formattedDate}`;
+};
diff --git a/src/app/[variants]/(main)/chat/profile/features/Header/AutoSaveHint.tsx b/src/app/[variants]/(main)/chat/profile/features/Header/AutoSaveHint.tsx
new file mode 100644
index 00000000000..69676c1f509
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/Header/AutoSaveHint.tsx
@@ -0,0 +1,18 @@
+'use client';
+
+import { memo } from 'react';
+
+import AutoSaveHintBase from '@/components/Editor/AutoSaveHint';
+import { useAgentStore } from '@/store/agent';
+
+/**
+ * AutoSaveHint - Save status indicator for agent settings
+ */
+const AutoSaveHint = memo(() => {
+ const saveStatus = useAgentStore((s) => s.saveStatus);
+ const lastUpdatedTime = useAgentStore((s) => s.lastUpdatedTime);
+
+ return <AutoSaveHintBase lastUpdatedTime={lastUpdatedTime} saveStatus={saveStatus || 'idle'} />;
+});
+
+export default AutoSaveHint;
diff --git a/src/app/[variants]/(main)/chat/profile/features/Header/index.tsx b/src/app/[variants]/(main)/chat/profile/features/Header/index.tsx
new file mode 100644
index 00000000000..b589958af1b
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/Header/index.tsx
@@ -0,0 +1,26 @@
+import { BotMessageSquareIcon } from 'lucide-react';
+import { memo } from 'react';
+
+import NavHeader from '@/features/NavHeader';
+import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';
+import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
+
+import AgentPublishButton from './AgentPublishButton';
+import AutoSaveHint from './AutoSaveHint';
+
+const Header = memo(() => {
+ return (
+ <NavHeader
+ left={<AutoSaveHint />}
+ right={
+ <>
+ <WideScreenButton />
+ <ToggleRightPanelButton icon={BotMessageSquareIcon} showActive={true} />
+ <AgentPublishButton />
+ </>
+ }
+ />
+ );
+});
+
+export default Header;
diff --git a/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/AgentHeader.tsx b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/AgentHeader.tsx
new file mode 100644
index 00000000000..73d1e4f28ca
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/AgentHeader.tsx
@@ -0,0 +1,171 @@
+'use client';
+
+import { EDITOR_DEBOUNCE_TIME } from '@lobechat/const';
+import { Icon, Input, Skeleton, Tooltip } from '@lobehub/ui';
+import { useDebounceFn } from 'ahooks';
+import { message } from 'antd';
+import isEqual from 'fast-deep-equal';
+import { PaletteIcon } from 'lucide-react';
+import { Suspense, memo, useCallback, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import EmojiPicker from '@/components/EmojiPicker';
+import BackgroundSwatches from '@/features/AgentSetting/AgentMeta/BackgroundSwatches';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useFileStore } from '@/store/file';
+import { useGlobalStore } from '@/store/global';
+import { globalGeneralSelectors } from '@/store/global/selectors';
+
+const MAX_AVATAR_SIZE = 1024 * 1024; // 1MB limit for server actions
+
+const AgentHeader = memo(() => {
+ const { t } = useTranslation(['setting', 'common']);
+ const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
+
+ // Get current meta from store
+ const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
+ const updateMeta = useAgentStore((s) => s.updateAgentMeta);
+
+ // File upload
+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
+ const [uploading, setUploading] = useState(false);
+
+ // Local state for inputs (to avoid stuttering during typing)
+ const [localTitle, setLocalTitle] = useState(meta.title || '');
+
+ // Sync local state when meta changes from external source
+ useEffect(() => {
+ setLocalTitle(meta.title || '');
+ }, [meta.title]);
+
+ // Debounced save for title
+ const { run: debouncedSaveTitle } = useDebounceFn(
+ (value: string) => {
+ updateMeta({ title: value });
+ },
+ { wait: EDITOR_DEBOUNCE_TIME },
+ );
+
+ // Handle avatar change (immediate save)
+ const handleAvatarChange = (emoji: string) => {
+ updateMeta({ avatar: emoji });
+ };
+
+ // Handle avatar upload
+ const handleAvatarUpload = useCallback(
+ async (file: File) => {
+ if (file.size > MAX_AVATAR_SIZE) {
+ message.error(t('settingAgent.avatar.sizeExceeded', { ns: 'setting' }));
+ return;
+ }
+
+ setUploading(true);
+ try {
+ const result = await uploadWithProgress({ file });
+ console.log('result', result);
+ if (result?.url) {
+ updateMeta({ avatar: result.url });
+ }
+ } finally {
+ setUploading(false);
+ }
+ },
+ [uploadWithProgress, updateMeta, t],
+ );
+
+ // Handle avatar delete
+ const handleAvatarDelete = useCallback(() => {
+ updateMeta({ avatar: undefined });
+ }, [updateMeta]);
+
+ // Handle background color change (immediate save)
+ const handleBackgroundColorChange = (color?: string) => {
+ if (color !== undefined) {
+ updateMeta({ backgroundColor: color });
+ }
+ };
+
+ return (
+ <Flexbox
+ gap={16}
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ }}
+ paddingBlock={16}
+ style={{
+ cursor: 'default',
+ }}
+ >
+ <EmojiPicker
+ allowDelete={!!meta.avatar}
+ allowUpload
+ background={
+ meta.backgroundColor && meta.backgroundColor !== 'rgba(0,0,0,0)'
+ ? meta.backgroundColor
+ : undefined
+ }
+ customTabs={[
+ {
+ label: (
+ <Tooltip title={t('settingAgent.backgroundColor.title', { ns: 'setting' })}>
+ <Icon icon={PaletteIcon} size={{ size: 20, strokeWidth: 2.5 }} />
+ </Tooltip>
+ ),
+ render: () => (
+ <Flexbox padding={8} width={332}>
+ <Suspense
+ fallback={
+ <Flexbox gap={8}>
+ <Skeleton.Button block style={{ height: 38 }} />
+ <Skeleton.Button block style={{ height: 38 }} />
+ </Flexbox>
+ }
+ >
+ <BackgroundSwatches
+ gap={8}
+ onChange={handleBackgroundColorChange}
+ shape={'square'}
+ size={38}
+ value={meta.backgroundColor}
+ />
+ </Suspense>
+ </Flexbox>
+ ),
+ value: 'background',
+ },
+ ]}
+ loading={uploading}
+ locale={locale}
+ onChange={handleAvatarChange}
+ onDelete={handleAvatarDelete}
+ onUpload={handleAvatarUpload}
+ popupProps={{
+ placement: 'bottomLeft',
+ }}
+ shape={'square'}
+ size={72}
+ value={meta.avatar}
+ />
+ <Input
+ onChange={(e) => {
+ setLocalTitle(e.target.value);
+ debouncedSaveTitle(e.target.value);
+ }}
+ placeholder={t('settingAgent.name.placeholder', { ns: 'setting' })}
+ style={{
+ fontSize: 36,
+ fontWeight: 600,
+ padding: 0,
+ width: '100%',
+ }}
+ value={localTitle}
+ variant={'borderless'}
+ />
+ </Flexbox>
+ );
+});
+
+export default AgentHeader;
diff --git a/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/AgentTool.tsx b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/AgentTool.tsx
new file mode 100644
index 00000000000..a77af5604ea
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/AgentTool.tsx
@@ -0,0 +1,400 @@
+'use client';
+
+import { KLAVIS_SERVER_TYPES, KlavisServerType } from '@lobechat/const';
+import { Avatar, Button, Icon, ItemType, Segmented } from '@lobehub/ui';
+import { useTheme } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { ArrowRight, PlusIcon, Store, ToyBrick } from 'lucide-react';
+import Image from 'next/image';
+import React, { Suspense, memo, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import PluginAvatar from '@/components/Plugins/PluginAvatar';
+import KlavisServerItem from '@/features/ChatInput/ActionBar/Tools/KlavisServerItem';
+import ToolItem from '@/features/ChatInput/ActionBar/Tools/ToolItem';
+import ActionDropdown from '@/features/ChatInput/ActionBar/components/ActionDropdown';
+import PluginStore from '@/features/PluginStore';
+import { useCheckPluginsIsInstalled } from '@/hooks/useCheckPluginsIsInstalled';
+import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+import { useToolStore } from '@/store/tool';
+import {
+ builtinToolSelectors,
+ klavisStoreSelectors,
+ pluginSelectors,
+} from '@/store/tool/selectors';
+
+import PluginTag from './PluginTag';
+
+type TabType = 'all' | 'installed';
+
+/**
+ * Klavis 服务器图标组件
+ * 对于 string 类型的 icon,使用 Image 组件渲染
+ * 对于 IconType 类型的 icon,使用 Icon 组件渲染,并根据主题设置填充色
+ */
+const KlavisIcon = memo<Pick<KlavisServerType, 'icon' | 'label'>>(({ icon, label }) => {
+ const theme = useTheme();
+
+ if (typeof icon === 'string') {
+ return (
+ <Image alt={label} height={18} src={icon} style={{ flex: 'none' }} unoptimized width={18} />
+ );
+ }
+
+ // 使用主题色填充,在深色模式下自动适应
+ return <Icon fill={theme.colorText} icon={icon} size={18} />;
+});
+
+const AgentTool = memo(() => {
+ const { t } = useTranslation('setting');
+ const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);
+
+ const theme = useTheme();
+
+ // Plugin state management
+ const plugins = config?.plugins || [];
+
+ const toggleAgentPlugin = useAgentStore((s) => s.toggleAgentPlugin);
+ const installedPluginList = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);
+ const builtinList = useToolStore(builtinToolSelectors.metaList, isEqual);
+
+ // Klavis 相关状态
+ const allKlavisServers = useToolStore(klavisStoreSelectors.getServers, isEqual);
+ const isKlavisEnabledInEnv = useServerConfigStore(serverConfigSelectors.enableKlavis);
+
+ // Plugin store modal state
+ const [modalOpen, setModalOpen] = useState(false);
+ const [updating, setUpdating] = useState(false);
+
+ // Tab state for dual-column layout
+ const [activeTab, setActiveTab] = useState<TabType | null>(null);
+ const isInitializedRef = useRef(false);
+
+ // Fetch plugins
+ const [useFetchPluginStore, useFetchUserKlavisServers] = useToolStore((s) => [
+ s.useFetchPluginStore,
+ s.useFetchUserKlavisServers,
+ ]);
+ useFetchPluginStore();
+ useFetchInstalledPlugins();
+ useCheckPluginsIsInstalled(plugins);
+
+ // 使用 SWR 加载用户的 Klavis 集成(从数据库)
+ useFetchUserKlavisServers(isKlavisEnabledInEnv);
+
+ // Set default tab based on installed plugins (only on first load)
+ useEffect(() => {
+ if (!isInitializedRef.current && plugins.length >= 0) {
+ isInitializedRef.current = true;
+ setActiveTab(plugins.length > 0 ? 'installed' : 'all');
+ }
+ }, [plugins.length]);
+
+ // 根据 identifier 获取已连接的服务器
+ const getServerByName = (identifier: string) => {
+ return allKlavisServers.find((server) => server.identifier === identifier);
+ };
+
+ // 获取所有 Klavis 服务器类型的 identifier 集合(用于过滤 builtinList)
+ const allKlavisTypeIdentifiers = useMemo(
+ () => new Set(KLAVIS_SERVER_TYPES.map((type) => type.identifier)),
+ [],
+ );
+
+ // 过滤掉 builtinList 中的 klavis 工具(它们会单独显示在 Klavis 区域)
+ const filteredBuiltinList = useMemo(
+ () =>
+ isKlavisEnabledInEnv
+ ? builtinList.filter((item) => !allKlavisTypeIdentifiers.has(item.identifier))
+ : builtinList,
+ [builtinList, allKlavisTypeIdentifiers, isKlavisEnabledInEnv],
+ );
+
+ // Klavis 服务器列表项
+ const klavisServerItems = useMemo(
+ () =>
+ isKlavisEnabledInEnv
+ ? KLAVIS_SERVER_TYPES.map((type) => ({
+ icon: <KlavisIcon icon={type.icon} label={type.label} />,
+ key: type.identifier,
+ label: (
+ <KlavisServerItem
+ identifier={type.identifier}
+ label={type.label}
+ server={getServerByName(type.identifier)}
+ serverName={type.serverName}
+ />
+ ),
+ }))
+ : [],
+ [isKlavisEnabledInEnv, allKlavisServers],
+ );
+
+ // Handle plugin remove via Tag close
+ const handleRemovePlugin =
+ (pluginId: string | { enabled: boolean; identifier: string; settings: Record<string, any> }) =>
+ (e: React.MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const identifier = typeof pluginId === 'string' ? pluginId : pluginId?.identifier;
+ toggleAgentPlugin(identifier, false);
+ };
+
+ // Build dropdown menu items (adapted from useControls)
+ const enablePluginCount = plugins.filter(
+ (id) => !builtinList.some((b) => b.identifier === id),
+ ).length;
+
+ // 合并 builtin 工具和 Klavis 服务器
+ const builtinItems = useMemo(
+ () => [
+ // 原有的 builtin 工具
+ ...filteredBuiltinList.map((item) => ({
+ icon: <Avatar avatar={item.meta.avatar} size={20} style={{ flex: 'none' }} />,
+ key: item.identifier,
+ label: (
+ <ToolItem
+ checked={plugins.includes(item.identifier)}
+ id={item.identifier}
+ label={item.meta?.title}
+ onUpdate={async () => {
+ setUpdating(true);
+ await toggleAgentPlugin(item.identifier);
+ setUpdating(false);
+ }}
+ />
+ ),
+ })),
+ // Klavis 服务器
+ ...klavisServerItems,
+ ],
+ [filteredBuiltinList, klavisServerItems, plugins, toggleAgentPlugin],
+ );
+
+ // Plugin items for dropdown
+ const pluginItems = useMemo(
+ () =>
+ installedPluginList.map((item) => ({
+ icon: item?.avatar ? (
+ <PluginAvatar avatar={item.avatar} size={20} />
+ ) : (
+ <Icon icon={ToyBrick} size={20} />
+ ),
+ key: item.identifier,
+ label: (
+ <ToolItem
+ checked={plugins.includes(item.identifier)}
+ id={item.identifier}
+ label={item.title}
+ onUpdate={async () => {
+ setUpdating(true);
+ await toggleAgentPlugin(item.identifier);
+ setUpdating(false);
+ }}
+ />
+ ),
+ })),
+ [installedPluginList, plugins, toggleAgentPlugin],
+ );
+
+ // All tab items (市场 tab)
+ const allTabItems: ItemType[] = useMemo(
+ () => [
+ {
+ children: builtinItems,
+ key: 'builtins',
+ label: t('tools.builtins.groupName'),
+ type: 'group',
+ },
+ {
+ children: pluginItems,
+ key: 'plugins',
+ label: (
+ <Flexbox align={'center'} gap={40} horizontal justify={'space-between'}>
+ {t('tools.plugins.groupName')}
+ {enablePluginCount === 0 ? null : (
+ <div style={{ fontSize: 12, marginInlineEnd: 4 }}>
+ {t('tools.plugins.enabled', { num: enablePluginCount })}
+ </div>
+ )}
+ </Flexbox>
+ ),
+ type: 'group',
+ },
+ {
+ type: 'divider',
+ },
+ {
+ extra: <Icon icon={ArrowRight} />,
+ icon: Store,
+ key: 'plugin-store',
+ label: t('tools.plugins.store'),
+ onClick: () => {
+ setModalOpen(true);
+ },
+ },
+ ],
+ [builtinItems, pluginItems, enablePluginCount, t],
+ );
+
+ // Installed tab items - 只显示已启用的
+ const installedTabItems: ItemType[] = useMemo(() => {
+ const items: ItemType[] = [];
+
+ // 已启用的 builtin 工具
+ const enabledBuiltinItems = filteredBuiltinList
+ .filter((item) => plugins.includes(item.identifier))
+ .map((item) => ({
+ icon: <Avatar avatar={item.meta.avatar} size={20} style={{ flex: 'none' }} />,
+ key: item.identifier,
+ label: (
+ <ToolItem
+ checked={true}
+ id={item.identifier}
+ label={item.meta?.title}
+ onUpdate={async () => {
+ setUpdating(true);
+ await toggleAgentPlugin(item.identifier);
+ setUpdating(false);
+ }}
+ />
+ ),
+ }));
+
+ // 已连接且已启用的 Klavis 服务器
+ const connectedKlavisItems = klavisServerItems.filter((item) =>
+ plugins.includes(item.key as string),
+ );
+
+ // 合并 builtin 和 Klavis
+ const allBuiltinItems = [...enabledBuiltinItems, ...connectedKlavisItems];
+
+ if (allBuiltinItems.length > 0) {
+ items.push({
+ children: allBuiltinItems,
+ key: 'installed-builtins',
+ label: t('tools.builtins.groupName'),
+ type: 'group',
+ });
+ }
+
+ // 已启用的插件
+ const installedPlugins = installedPluginList
+ .filter((item) => plugins.includes(item.identifier))
+ .map((item) => ({
+ icon: item?.avatar ? (
+ <PluginAvatar avatar={item.avatar} size={20} />
+ ) : (
+ <Icon icon={ToyBrick} size={20} />
+ ),
+ key: item.identifier,
+ label: (
+ <ToolItem
+ checked={true}
+ id={item.identifier}
+ label={item.title}
+ onUpdate={async () => {
+ setUpdating(true);
+ await toggleAgentPlugin(item.identifier);
+ setUpdating(false);
+ }}
+ />
+ ),
+ }));
+
+ if (installedPlugins.length > 0) {
+ items.push({
+ children: installedPlugins,
+ key: 'installed-plugins',
+ label: t('tools.plugins.groupName'),
+ type: 'group',
+ });
+ }
+
+ return items;
+ }, [filteredBuiltinList, klavisServerItems, installedPluginList, plugins, toggleAgentPlugin, t]);
+
+ // Use effective tab for display (default to all while initializing)
+ const effectiveTab = activeTab ?? 'all';
+ const currentItems = effectiveTab === 'all' ? allTabItems : installedTabItems;
+
+ // Final menu items with tab segmented control
+ const menuItems: ItemType[] = useMemo(
+ () => [
+ {
+ key: 'tabs',
+ label: (
+ <Segmented
+ block
+ onChange={(v) => setActiveTab(v as TabType)}
+ options={[
+ {
+ label: t('tools.tabs.all', { defaultValue: 'All' }),
+ value: 'all',
+ },
+ {
+ label: t('tools.tabs.installed', { defaultValue: 'Installed' }),
+ value: 'installed',
+ },
+ ]}
+ size="small"
+ value={effectiveTab}
+ />
+ ),
+ type: 'group',
+ },
+ ...currentItems,
+ ],
+ [currentItems, effectiveTab, t],
+ );
+
+ const button = (
+ <Button
+ icon={PlusIcon}
+ loading={updating}
+ size={'small'}
+ style={{ color: theme.colorTextSecondary }}
+ type={'text'}
+ >
+ {t('tools.add', { defaultValue: 'Add' })}
+ </Button>
+ );
+
+ return (
+ <>
+ {/* Plugin Selector and Tags */}
+ <Flexbox align="center" gap={8} horizontal wrap={'wrap'}>
+ {/* Second Row: Selected Plugins as Tags */}
+ {plugins?.map((pluginId) => {
+ return (
+ <PluginTag key={pluginId} onRemove={handleRemovePlugin(pluginId)} pluginId={pluginId} />
+ );
+ })}
+ {/* Plugin Selector Dropdown - Using Action component pattern */}
+
+ <Suspense fallback={button}>
+ <ActionDropdown
+ maxHeight={500}
+ maxWidth={480}
+ menu={{ items: menuItems }}
+ minHeight={isKlavisEnabledInEnv ? 500 : undefined}
+ minWidth={320}
+ placement={'bottomLeft'}
+ trigger={['click']}
+ >
+ {button}
+ </ActionDropdown>
+ </Suspense>
+ </Flexbox>
+
+ {/* PluginStore Modal */}
+ <PluginStore open={modalOpen} setOpen={setModalOpen} />
+ </>
+ );
+});
+
+export default AgentTool;
diff --git a/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/MentionList/MentionDropdown.tsx b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/MentionList/MentionDropdown.tsx
new file mode 100644
index 00000000000..0db220fd68d
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/MentionList/MentionDropdown.tsx
@@ -0,0 +1,122 @@
+import { MenuRenderProps } from '@lobehub/editor/es/plugins/slash/react/type';
+import { useTheme } from 'antd-style';
+import { ReactNode, memo, useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { MentionListOption } from './types';
+
+/**
+ * Get cursor position from browser selection API
+ */
+const getCursorPosition = (): { x: number; y: number } | null => {
+ const selection = window.getSelection();
+ if (!selection || selection.rangeCount === 0) return null;
+
+ const range = selection.getRangeAt(0);
+ const rect = range.getBoundingClientRect();
+
+ return {
+ x: rect.left,
+ y: rect.bottom,
+ };
+};
+
+const MentionDropdown = memo<MenuRenderProps>(
+ ({ activeKey, onSelect, open, options, setActiveKey }) => {
+ const theme = useTheme();
+ const activeItemRef = useRef<HTMLDivElement>(null);
+ const [position, setPosition] = useState<{ x: number; y: number } | null>(null);
+
+ // Capture cursor position when menu opens
+ useLayoutEffect(() => {
+ if (open) {
+ const pos = getCursorPosition();
+ if (pos) {
+ setPosition(pos);
+ }
+ }
+ }, [open]);
+
+ useEffect(() => {
+ if (activeItemRef.current) {
+ activeItemRef.current.scrollIntoView({
+ behavior: 'smooth',
+ block: 'nearest',
+ });
+ }
+ }, [activeKey]);
+
+ if (!open || !options.length || !position) return null;
+
+ return (
+ <Flexbox
+ style={{
+ background: theme.colorBgElevated,
+ border: `1px solid ${theme.colorBorderSecondary}`,
+ borderRadius: 12,
+ boxShadow: theme.boxShadowSecondary,
+ left: position.x,
+ maxHeight: 260,
+ maxWidth: 400,
+ minWidth: 150,
+ overflow: 'hidden auto',
+ position: 'fixed',
+ top: position.y,
+ zIndex: 9999,
+ }}
+ >
+ {options.map((option) => {
+ if ((option as any)?.type === 'divider') {
+ return (
+ <div
+ key={`divider-${(option as any)?.key ?? 'divider'}`}
+ style={{ borderTop: `1px solid ${theme.colorBorderSecondary}` }}
+ />
+ );
+ }
+
+ const item = option as MentionListOption;
+ const isActive = activeKey === item.key;
+
+ return (
+ <Flexbox
+ align="center"
+ direction="horizontal"
+ gap={8}
+ key={String(item.key)}
+ onMouseDown={(e) => {
+ e.preventDefault();
+ onSelect?.(item);
+ }}
+ onMouseEnter={() => setActiveKey?.(String(item.key))}
+ paddingBlock={8}
+ paddingInline={12}
+ ref={isActive ? activeItemRef : null}
+ style={{
+ background: isActive ? theme.colorFillSecondary : undefined,
+ cursor: 'pointer',
+ }}
+ >
+ {item.icon && <Flexbox style={{ flex: 'none' }}>{item?.icon as ReactNode}</Flexbox>}
+ <div
+ style={{
+ color: theme.colorText,
+ fontSize: 14,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ }}
+ >
+ {item.label}
+ </div>
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ );
+ },
+);
+
+MentionDropdown.displayName = 'MentionDropdown';
+
+export default MentionDropdown;
diff --git a/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/MentionList/index.tsx b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/MentionList/index.tsx
new file mode 100644
index 00000000000..2749d93ebb1
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/MentionList/index.tsx
@@ -0,0 +1 @@
+export { default as useMentionOptions } from './useMentionItems';
diff --git a/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/MentionList/types.ts b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/MentionList/types.ts
new file mode 100644
index 00000000000..9fff5c2a430
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/MentionList/types.ts
@@ -0,0 +1,20 @@
+import type { API } from '@lobechat/prompts';
+import type { DropdownMenuItemType } from '@lobehub/ui';
+
+export type MentionEntityType = 'collection' | 'api';
+
+export interface MentionMetadata {
+ apis?: API[];
+ description?: string;
+ identifier: string;
+ instructions?: string;
+ label?: string;
+ pluginIdentifier?: string;
+ pluginType?: string;
+ type?: MentionEntityType;
+}
+
+export type MentionListOption = DropdownMenuItemType & {
+ description?: string;
+ metadata?: MentionMetadata;
+};
diff --git a/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/MentionList/useMentionItems.tsx b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/MentionList/useMentionItems.tsx
new file mode 100644
index 00000000000..425b40d6c56
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/MentionList/useMentionItems.tsx
@@ -0,0 +1,229 @@
+import { KLAVIS_SERVER_TYPES, KlavisServerType } from '@lobechat/const';
+import { ToolNameResolver } from '@lobechat/context-engine';
+import { type API, apiPrompt, toolPrompt } from '@lobechat/prompts';
+import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';
+import { IEditor, INSERT_MENTION_COMMAND } from '@lobehub/editor';
+import { Icon, Image } from '@lobehub/ui';
+import { useTheme } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { memo, useCallback, useMemo } from 'react';
+
+import PluginAvatar from '@/components/Plugins/PluginAvatar';
+import { useAgentStore } from '@/store/agent';
+import { pluginHelpers, useToolStore } from '@/store/tool';
+import { toolSelectors } from '@/store/tool/selectors';
+import { globalAgentContextManager } from '@/utils/client/GlobalAgentContextManager';
+import { hydrationPrompt } from '@/utils/promptTemplate';
+
+import MentionDropdown from './MentionDropdown';
+import { MentionListOption, MentionMetadata } from './types';
+
+// 根据 identifier 获取 Klavis 服务器类型配置
+const getKlavisServerType = (identifier: string) =>
+ KLAVIS_SERVER_TYPES.find((type) => type.identifier === identifier);
+
+/**
+ * Klavis 服务器图标组件
+ * 对于 string 类型的 icon,使用 Image 组件渲染
+ * 对于 IconType 类型的 icon,使用 Icon 组件渲染,并根据主题设置填充色
+ */
+const KlavisIcon = memo<Pick<KlavisServerType, 'icon' | 'label'>>(({ icon, label }) => {
+ const theme = useTheme();
+
+ if (typeof icon === 'string') {
+ return <Image alt={label} height={20} src={icon} style={{ flex: 'none' }} width={20} />;
+ }
+
+ // 使用主题色填充,在深色模式下自动适应
+ return <Icon fill={theme.colorText} icon={icon} size={20} />;
+});
+
+const toolNameResolver = new ToolNameResolver();
+
+const buildApiList = (identifier: string, manifest?: LobeChatPluginManifest): API[] => {
+ if (!manifest?.api) return [];
+
+ return manifest.api.map((api) => ({
+ desc: api.description || '',
+ name: toolNameResolver.generate(identifier, api.name, manifest.type),
+ }));
+};
+
+const hydrateSystemRole = (systemRole?: string) => {
+ if (!systemRole) return '';
+
+ return hydrationPrompt(systemRole, globalAgentContextManager.getContext());
+};
+
+const resolveInstructions = (
+ metadata: MentionMetadata,
+ manifest?: LobeChatPluginManifest,
+ fallbackDesc?: string,
+) => {
+ if (metadata.instructions) return metadata.instructions;
+
+ if (manifest?.systemRole) return hydrateSystemRole(manifest.systemRole);
+
+ return metadata.description || fallbackDesc || pluginHelpers.getPluginDesc(manifest?.meta) || '';
+};
+
+const resolveApiName = (
+ metadata: MentionMetadata,
+ manifest: LobeChatPluginManifest | undefined,
+ pluginId?: string,
+ fallbackLabel?: string,
+) => {
+ if (metadata.identifier) return metadata.identifier;
+
+ const sourceId = pluginId || manifest?.identifier || '';
+
+ if (metadata.label) {
+ return toolNameResolver.generate(sourceId, metadata.label, manifest?.type);
+ }
+
+ const firstApi = manifest?.api?.[0]?.name;
+
+ if (firstApi) {
+ return toolNameResolver.generate(sourceId, firstApi, manifest?.type);
+ }
+
+ return fallbackLabel;
+};
+
+const resolveApiDescription = (
+ metadata: MentionMetadata,
+ manifest: LobeChatPluginManifest | undefined,
+ pluginId: string | undefined,
+ apiName?: string,
+) => {
+ if (metadata.description) return metadata.description;
+
+ if (!manifest?.api?.length || !apiName) return '';
+
+ const sourceId = pluginId || manifest.identifier;
+ const matched = manifest.api.find((api) => {
+ const fullName = toolNameResolver.generate(sourceId, api.name, manifest.type);
+
+ return fullName === apiName || api.name === apiName;
+ });
+
+ return matched?.description || '';
+};
+
+const useMentionOptions = () => {
+ const installedTools = useToolStore(toolSelectors.metaList, isEqual);
+ const toggleAgentPlugin = useAgentStore((s) => s.toggleAgentPlugin);
+
+ const baseItems = useMemo<MentionListOption[]>(() => {
+ const state = useToolStore.getState();
+
+ return installedTools.map((tool) => {
+ const manifest = toolSelectors.getManifestById(tool.identifier)(state);
+ const label = pluginHelpers.getPluginTitle(tool.meta) || tool.identifier;
+ const description = pluginHelpers.getPluginDesc(tool.meta);
+ const apis = buildApiList(manifest?.identifier || tool.identifier, manifest);
+
+ const createMetadata = (): MentionMetadata => ({
+ apis: apis.map((api) => ({ ...api })),
+ description,
+ identifier: tool.identifier,
+ label,
+ pluginType: manifest?.type,
+ type: 'collection',
+ });
+
+ // 优先使用 Klavis 图标,否则使用 PluginAvatar
+ const klavisServerType = getKlavisServerType(tool.identifier);
+ const icon = klavisServerType ? (
+ <KlavisIcon icon={klavisServerType.icon} label={klavisServerType.label} />
+ ) : (
+ <PluginAvatar alt={label} avatar={pluginHelpers.getPluginAvatar(tool.meta)} size={20} />
+ );
+
+ return {
+ description,
+ icon,
+ key: tool.identifier,
+ label,
+ metadata: createMetadata(),
+ onSelect: (editor: IEditor) => {
+ toggleAgentPlugin(tool.identifier, true);
+ editor.dispatchCommand(INSERT_MENTION_COMMAND, {
+ label,
+ metadata: createMetadata() as unknown as Record<string, unknown>,
+ });
+ },
+ };
+ });
+ }, [installedTools, toggleAgentPlugin]);
+
+ const loadItems = useCallback(
+ async (
+ search: { leadOffset: number; matchingString: string; replaceableString: string } | null,
+ ) => {
+ const query = search?.matchingString?.toLowerCase() || '';
+
+ if (!query) return baseItems;
+
+ return baseItems.filter((item) => {
+ const label = typeof item.label === 'string' ? item.label.toLowerCase() : '';
+ const desc = item.description?.toLowerCase() || '';
+ const key = typeof item.key === 'string' ? item.key.toLowerCase() : '';
+
+ return label.includes(query) || desc.includes(query) || key.includes(query);
+ });
+ },
+ [baseItems],
+ );
+
+ const mentionMarkdownWriter = useCallback((mention: any) => {
+ const metadata = (mention?.metadata || {}) as MentionMetadata;
+ const pluginId = metadata.pluginIdentifier || metadata.identifier;
+ const state = useToolStore.getState();
+ const manifest = pluginId ? toolSelectors.getManifestById(pluginId)(state) : undefined;
+
+ if (metadata.type === 'api') {
+ const apiName = resolveApiName(metadata, manifest, pluginId, mention?.label);
+ const apiDescription = resolveApiDescription(metadata, manifest, pluginId, apiName);
+
+ if (!apiName) return mention?.getTextContent?.() || '';
+
+ return `\n${apiPrompt({ desc: apiDescription, name: apiName })}\n`;
+ }
+
+ const apis =
+ metadata.apis?.length && metadata.apis.length > 0
+ ? metadata.apis
+ : buildApiList(pluginId || manifest?.identifier || '', manifest);
+
+ const name =
+ metadata.label ||
+ pluginHelpers.getPluginTitle(manifest?.meta) ||
+ pluginId ||
+ mention?.label ||
+ '';
+
+ const instructions = resolveInstructions(metadata, manifest, metadata.description);
+
+ const prompt = toolPrompt({
+ apis: apis || [],
+ identifier: pluginId || '',
+ name,
+ systemRole: instructions,
+ });
+
+ return `\n${prompt}\n`;
+ }, []);
+
+ return useMemo(
+ () => ({
+ fuseOptions: { keys: ['key', 'label', 'description'], threshold: 0.4 },
+ items: loadItems,
+ markdownWriter: mentionMarkdownWriter,
+ renderComp: MentionDropdown,
+ }),
+ [loadItems, mentionMarkdownWriter],
+ );
+};
+
+export default useMentionOptions;
diff --git a/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/PluginTag.tsx b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/PluginTag.tsx
new file mode 100644
index 00000000000..b3bae8b3731
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/PluginTag.tsx
@@ -0,0 +1,181 @@
+'use client';
+
+import { KLAVIS_SERVER_TYPES, KlavisServerType } from '@lobechat/const';
+import { Avatar, Icon, Tag } from '@lobehub/ui';
+import { createStyles, useTheme } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { AlertCircle, X } from 'lucide-react';
+import Image from 'next/image';
+import React, { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import PluginAvatar from '@/components/Plugins/PluginAvatar';
+import { useDiscoverStore } from '@/store/discover';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+import { useToolStore } from '@/store/tool';
+import {
+ builtinToolSelectors,
+ klavisStoreSelectors,
+ pluginSelectors,
+} from '@/store/tool/selectors';
+
+/**
+ * Klavis 服务器图标组件
+ */
+const KlavisIcon = memo<Pick<KlavisServerType, 'icon' | 'label'>>(({ icon, label }) => {
+ const theme = useTheme();
+
+ if (typeof icon === 'string') {
+ return (
+ <Image alt={label} height={16} src={icon} style={{ flexShrink: 0 }} unoptimized width={16} />
+ );
+ }
+
+ return <Icon fill={theme.colorText} icon={icon} size={16} />;
+});
+
+const useStyles = createStyles(({ css, token }) => ({
+ notInstalledTag: css`
+ border-color: ${token.colorWarningBorder};
+ background: ${token.colorWarningBg};
+ `,
+ tag: css`
+ height: 28px !important;
+ border-radius: ${token.borderRadiusSM}px !important;
+ `,
+ warningIcon: css`
+ flex-shrink: 0;
+ color: ${token.colorWarning};
+ `,
+}));
+
+interface PluginTagProps {
+ onRemove: (e: React.MouseEvent) => void;
+ pluginId: string | { enabled: boolean; identifier: string; settings: Record<string, any> };
+}
+
+const PluginTag = memo<PluginTagProps>(({ pluginId, onRemove }) => {
+ const { styles, theme } = useStyles();
+ const { t } = useTranslation('setting');
+
+ // Extract identifier
+ const identifier = typeof pluginId === 'string' ? pluginId : pluginId?.identifier;
+
+ // Get local plugin lists
+ const builtinList = useToolStore(builtinToolSelectors.metaList, isEqual);
+ const installedPluginList = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);
+
+ // Klavis 相关状态
+ const allKlavisServers = useToolStore(klavisStoreSelectors.getServers, isEqual);
+ const isKlavisEnabledInEnv = useServerConfigStore(serverConfigSelectors.enableKlavis);
+
+ // Check if plugin is installed
+ const isInstalled = useToolStore(pluginSelectors.isPluginInstalled(identifier));
+
+ // Try to find in local lists first (including Klavis)
+ const localMeta = useMemo(() => {
+ // Check if it's a Klavis server type
+ if (isKlavisEnabledInEnv) {
+ const klavisType = KLAVIS_SERVER_TYPES.find((type) => type.identifier === identifier);
+ if (klavisType) {
+ // Check if this Klavis server is connected
+ const connectedServer = allKlavisServers.find((s) => s.identifier === identifier);
+ return {
+ icon: klavisType.icon,
+ isInstalled: !!connectedServer,
+ label: klavisType.label,
+ title: klavisType.label,
+ type: 'klavis' as const,
+ };
+ }
+ }
+
+ const builtinMeta = builtinList.find((p) => p.identifier === identifier);
+ if (builtinMeta) {
+ return {
+ avatar: builtinMeta.meta.avatar,
+ isInstalled: true,
+ title: builtinMeta.meta.title,
+ type: 'builtin' as const,
+ };
+ }
+
+ const installedMeta = installedPluginList.find((p) => p.identifier === identifier);
+ if (installedMeta) {
+ return {
+ avatar: installedMeta.avatar,
+ isInstalled: true,
+ title: installedMeta.title,
+ type: 'plugin' as const,
+ };
+ }
+
+ return null;
+ }, [identifier, builtinList, installedPluginList, isKlavisEnabledInEnv, allKlavisServers]);
+
+ // Fetch from remote if not found locally
+ const usePluginDetail = useDiscoverStore((s) => s.usePluginDetail);
+ const { data: remoteData, isLoading } = usePluginDetail({
+ identifier: !localMeta && !isInstalled ? identifier : undefined,
+ withManifest: false,
+ });
+
+ // Determine final metadata
+ const meta = localMeta || {
+ avatar: remoteData?.avatar,
+ isInstalled: false,
+ title: remoteData?.title || identifier,
+ type: 'plugin' as const,
+ };
+
+ const displayTitle = isLoading ? 'Loading...' : meta.title;
+
+ // Render icon based on type
+ const renderIcon = () => {
+ if (!meta.isInstalled) {
+ return <AlertCircle className={styles.warningIcon} size={14} />;
+ }
+
+ // Klavis type has icon property
+ if (meta.type === 'klavis' && 'icon' in meta && 'label' in meta) {
+ return <KlavisIcon icon={meta.icon} label={meta.label} />;
+ }
+
+ // Builtin type has avatar
+ if (meta.type === 'builtin' && 'avatar' in meta && meta.avatar) {
+ return <Avatar avatar={meta.avatar} shape={'square'} size={16} style={{ flexShrink: 0 }} />;
+ }
+
+ // Plugin type
+ if ('avatar' in meta) {
+ return <PluginAvatar avatar={meta.avatar} size={16} />;
+ }
+
+ return null;
+ };
+
+ return (
+ <Tag
+ className={styles.tag}
+ closable
+ closeIcon={<X size={12} />}
+ color={meta.isInstalled ? undefined : 'error'}
+ icon={renderIcon()}
+ onClose={onRemove}
+ title={
+ meta.isInstalled
+ ? undefined
+ : t('tools.notInstalledWarning', { defaultValue: 'This tool is not installed' })
+ }
+ variant={theme.isDarkMode ? 'filled' : 'outlined'}
+ >
+ {!meta.isInstalled
+ ? `${displayTitle} (${t('tools.notInstalled', { defaultValue: 'Not Installed' })})`
+ : displayTitle}
+ </Tag>
+ );
+});
+
+PluginTag.displayName = 'PluginTag';
+
+export default PluginTag;
diff --git a/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/index.tsx b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/index.tsx
new file mode 100644
index 00000000000..dc1414bf8fd
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/index.tsx
@@ -0,0 +1,82 @@
+'use client';
+
+import { Button } from '@lobehub/ui';
+import { Divider } from 'antd';
+import isEqual from 'fast-deep-equal';
+import { PlayIcon } from 'lucide-react';
+import React, { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+import urlJoin from 'url-join';
+
+import ModelSelect from '@/features/ModelSelect';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+
+import EditorCanvas from '../EditorCanvas';
+import AgentHeader from './AgentHeader';
+import AgentTool from './AgentTool';
+
+const ProfileEditor = memo(() => {
+ const { t } = useTranslation('setting');
+ const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);
+ const updateConfig = useAgentStore((s) => s.updateAgentConfig);
+ const agentId = useAgentStore((s) => s.activeAgentId);
+ const router = useQueryRoute();
+
+ return (
+ <>
+ <Flexbox
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ }}
+ style={{ cursor: 'default', marginBottom: 12 }}
+ >
+ {/* Header: Avatar + Name + Description */}
+ <AgentHeader />
+ {/* Config Bar: Model Selector */}
+ <Flexbox
+ align={'center'}
+ gap={8}
+ horizontal
+ justify={'flex-start'}
+ style={{ marginBottom: 12 }}
+ >
+ <ModelSelect
+ onChange={updateConfig}
+ value={{
+ model: config.model,
+ provider: config.provider,
+ }}
+ />
+ </Flexbox>
+ <AgentTool />
+ <Flexbox
+ align={'center'}
+ gap={8}
+ horizontal
+ justify={'flex-start'}
+ style={{ marginTop: 16 }}
+ >
+ <Button
+ icon={PlayIcon}
+ onClick={() => {
+ if (!agentId) return;
+ router.push(urlJoin('/agent', agentId));
+ }}
+ type={'primary'}
+ >
+ {t('startConversation')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ <Divider />
+ {/* Main Content: Prompt Editor */}
+ <EditorCanvas />
+ </>
+ );
+});
+
+export default ProfileEditor;
diff --git a/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/promptTemplate.json b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/promptTemplate.json
new file mode 100644
index 00000000000..36e841189f1
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/promptTemplate.json
@@ -0,0 +1,277 @@
+{
+ "root": {
+ "children": [
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Goal",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": null,
+ "format": "",
+ "indent": 0,
+ "type": "heading",
+ "version": 1,
+ "tag": "h4"
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Describe the main purpose and objective of this agent.",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "paragraph",
+ "version": 1,
+ "textFormat": 0,
+ "textStyle": ""
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Skills",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": null,
+ "format": "",
+ "indent": 0,
+ "type": "heading",
+ "version": 1,
+ "tag": "h4"
+ },
+ {
+ "children": [
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "List the key capabilities",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "listitem",
+ "version": 1,
+ "value": 1
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "And specialized knowledge areas",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "listitem",
+ "version": 1,
+ "value": 2
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "list",
+ "version": 1,
+ "listType": "bullet",
+ "start": 1,
+ "tag": "ul"
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Workflow",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": null,
+ "format": "",
+ "indent": 0,
+ "type": "heading",
+ "version": 1,
+ "tag": "h4"
+ },
+ {
+ "children": [
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Step-by-step process",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "listitem",
+ "version": 1,
+ "value": 1
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "How the agent should approach tasks",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "listitem",
+ "version": 1,
+ "value": 2
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Expected interactions with users",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "listitem",
+ "version": 1,
+ "value": 3
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "list",
+ "version": 1,
+ "listType": "number",
+ "start": 1,
+ "tag": "ol"
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Constraints",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": null,
+ "format": "",
+ "indent": 0,
+ "type": "heading",
+ "version": 1,
+ "tag": "h4"
+ },
+ {
+ "children": [
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Important limitations to follow",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "listitem",
+ "version": 1,
+ "value": 1
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Guidelines for behavior",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "listitem",
+ "version": 1,
+ "value": 2
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "list",
+ "version": 1,
+ "listType": "bullet",
+ "start": 1,
+ "tag": "ul"
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "root",
+ "version": 1,
+ "textStyle": "--shiki-dark:var(--color-info);--shiki-light:var(--color-info)"
+ }
+}
diff --git a/src/app/[variants]/(main)/chat/profile/features/ProfileHydration.tsx b/src/app/[variants]/(main)/chat/profile/features/ProfileHydration.tsx
new file mode 100644
index 00000000000..6c03fc32e6e
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/ProfileHydration.tsx
@@ -0,0 +1,15 @@
+import { memo } from 'react';
+
+import { useRegisterFilesHotkeys, useSaveDocumentHotkey } from '@/hooks/useHotkeys';
+
+import { useProfileStore } from './store';
+
+const ProfileHydration = memo(() => {
+ const flushSave = useProfileStore((s) => s.flushSave);
+ useRegisterFilesHotkeys();
+ useSaveDocumentHotkey(flushSave);
+
+ return null;
+});
+
+export default ProfileHydration;
diff --git a/src/app/[variants]/(main)/chat/profile/features/ProfileProvider.tsx b/src/app/[variants]/(main)/chat/profile/features/ProfileProvider.tsx
new file mode 100644
index 00000000000..b25465bb0e5
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/ProfileProvider.tsx
@@ -0,0 +1,20 @@
+'use client';
+
+import { useEditor } from '@lobehub/editor/react';
+import { PropsWithChildren, memo } from 'react';
+
+import StoreUpdater from './StoreUpdater';
+import { Provider, createStore } from './store';
+
+const ProfileProvider = memo<PropsWithChildren>(({ children }) => {
+ const editor = useEditor();
+
+ return (
+ <Provider createStore={() => createStore({ editor })}>
+ <StoreUpdater />
+ {children}
+ </Provider>
+ );
+});
+
+export default ProfileProvider;
diff --git a/src/app/[variants]/(main)/chat/profile/features/StoreUpdater.tsx b/src/app/[variants]/(main)/chat/profile/features/StoreUpdater.tsx
new file mode 100644
index 00000000000..c9019f543be
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/StoreUpdater.tsx
@@ -0,0 +1,24 @@
+'use client';
+
+import { useEditorState } from '@lobehub/editor/react';
+import { memo, useEffect } from 'react';
+
+import { PublicState, useProfileStore, useStoreApi } from './store';
+
+export type StoreUpdaterProps = Partial<PublicState>;
+
+const StoreUpdater = memo<StoreUpdaterProps>(() => {
+ const storeApi = useStoreApi();
+
+ const editor = useProfileStore((s) => s.editor);
+ const editorState = useEditorState(editor);
+
+ // Update editorState in store
+ useEffect(() => {
+ storeApi.setState({ editorState });
+ }, [editorState, storeApi]);
+
+ return null;
+});
+
+export default StoreUpdater;
diff --git a/src/app/[variants]/(main)/chat/profile/features/store/action.ts b/src/app/[variants]/(main)/chat/profile/features/store/action.ts
new file mode 100644
index 00000000000..de377a93f2f
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/store/action.ts
@@ -0,0 +1,153 @@
+import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@lobechat/const';
+import { debounce } from 'es-toolkit/compat';
+import { StateCreator } from 'zustand';
+
+import { State, initialState } from './initialState';
+
+type SaveConfigPayload = {
+ editorData: Record<string, any>;
+ systemRole: string;
+};
+
+export interface Action {
+ /**
+ * Append content to streaming buffer (called during streaming)
+ */
+ appendStreamingContent: (chunk: string) => void;
+ /**
+ * Finalize streaming and save to config
+ */
+ finishStreaming: (updateConfig: (payload: SaveConfigPayload) => Promise<void>) => Promise<void>;
+ flushSave: () => void;
+ handleContentChange: (updateConfig: (payload: SaveConfigPayload) => Promise<void>) => void;
+ /**
+ * Start streaming mode - clears editor and prepares for streaming content
+ */
+ startStreaming: () => void;
+}
+
+export type Store = State & Action;
+
+// Create debounced save function outside of store for reuse
+const createDebouncedSave = (
+ get: () => Store,
+ updateConfig: (payload: SaveConfigPayload) => Promise<void>,
+) =>
+ debounce(
+ async (payload: SaveConfigPayload) => {
+ try {
+ await updateConfig(payload);
+ } catch (error) {
+ console.error('[ProfileEditor] Failed to save:', error);
+ }
+ },
+ EDITOR_DEBOUNCE_TIME,
+ { leading: false, maxWait: EDITOR_MAX_WAIT, trailing: true },
+ );
+
+export const store: (initState?: Partial<State>) => StateCreator<Store> =
+ (initState) => (set, get) => {
+ let debouncedSave: ReturnType<typeof createDebouncedSave> | null = null;
+
+ return {
+ ...initialState,
+ ...initState,
+
+ appendStreamingContent: (chunk) => {
+ const currentContent = get().streamingContent || '';
+ const newContent = currentContent + chunk;
+ set({ streamingContent: newContent });
+
+ // Update editor with streaming content
+ const { editor } = get();
+ if (editor) {
+ try {
+ editor.setDocument('markdown', newContent);
+ } catch {
+ // Ignore errors during streaming updates
+ }
+ }
+ },
+
+ finishStreaming: async (updateConfig) => {
+ const { editor, streamingContent } = get();
+ if (!streamingContent) {
+ set({ streamingInProgress: false });
+ return;
+ }
+
+ // Get the final content from editor
+ let finalContent = streamingContent;
+ let editorData = {};
+
+ if (editor) {
+ try {
+ finalContent =
+ (editor.getDocument('markdown') as unknown as string) || streamingContent;
+ editorData = editor.getDocument('json') as unknown as Record<string, any>;
+ } catch {
+ // Use streaming content if editor read fails
+ }
+ }
+
+ // Save to config
+ try {
+ await updateConfig({
+ editorData: structuredClone(editorData || {}),
+ systemRole: finalContent,
+ });
+ } catch (error) {
+ console.error('[ProfileEditor] Failed to save streaming content:', error);
+ }
+
+ // Reset streaming state
+ set({
+ streamingContent: undefined,
+ streamingInProgress: false,
+ });
+ },
+
+ flushSave: () => {
+ debouncedSave?.flush();
+ },
+
+ handleContentChange: (updateConfig) => {
+ const { editor } = get();
+ if (!editor) return;
+
+ // Create debounced save on first use
+ if (!debouncedSave) {
+ debouncedSave = createDebouncedSave(get, updateConfig);
+ }
+
+ try {
+ const markdownContent = (editor.getDocument('markdown') as unknown as string) || '';
+ const jsonContent = editor.getDocument('json') as unknown as Record<string, any>;
+
+ debouncedSave({
+ editorData: structuredClone(jsonContent || {}),
+ systemRole: markdownContent || '',
+ });
+ } catch (error) {
+ console.error('[ProfileEditor] Failed to read editor content:', error);
+ }
+ },
+ startStreaming: () => {
+ const { editor } = get();
+
+ // Clear editor content and prepare for streaming
+ if (editor) {
+ try {
+ editor.setDocument('markdown', '');
+ } catch {
+ // Ignore errors
+ }
+ }
+
+ set({
+ streamingContent: '',
+ streamingInProgress: true,
+ });
+ },
+ };
+ };
diff --git a/src/app/[variants]/(main)/chat/profile/features/store/index.ts b/src/app/[variants]/(main)/chat/profile/features/store/index.ts
new file mode 100644
index 00000000000..de5b6ed3513
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/store/index.ts
@@ -0,0 +1,23 @@
+'use client';
+
+import { StoreApiWithSelector } from '@lobechat/types';
+import { createContext } from 'zustand-utils';
+import { subscribeWithSelector } from 'zustand/middleware';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import { Store, store } from './action';
+import { State } from './initialState';
+
+export type { PublicState, State } from './initialState';
+
+export const createStore = (initState?: Partial<State>) =>
+ createWithEqualityFn(subscribeWithSelector(store(initState)), shallow);
+
+export const {
+ useStore: useProfileStore,
+ useStoreApi,
+ Provider,
+} = createContext<StoreApiWithSelector<Store>>();
+
+export { selectors } from './selectors';
diff --git a/src/app/[variants]/(main)/chat/profile/features/store/initialState.ts b/src/app/[variants]/(main)/chat/profile/features/store/initialState.ts
new file mode 100644
index 00000000000..746e57c59c8
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/store/initialState.ts
@@ -0,0 +1,23 @@
+import { IEditor } from '@lobehub/editor';
+import { EditorState } from '@lobehub/editor/react';
+
+// eslint-disable-next-line @typescript-eslint/no-empty-interface
+export interface PublicState {}
+
+export interface State extends PublicState {
+ editor?: IEditor;
+ editorState?: EditorState; // EditorState from useEditorState hook
+ /**
+ * Content being streamed from AI
+ */
+ streamingContent?: string;
+ /**
+ * Whether streaming is in progress
+ */
+ streamingInProgress?: boolean;
+}
+
+export const initialState: State = {
+ streamingContent: undefined,
+ streamingInProgress: false,
+};
diff --git a/src/app/[variants]/(main)/chat/profile/features/store/selectors.ts b/src/app/[variants]/(main)/chat/profile/features/store/selectors.ts
new file mode 100644
index 00000000000..4f792ee9462
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/features/store/selectors.ts
@@ -0,0 +1,6 @@
+import { Store } from './action';
+
+export const selectors = {
+ editor: (s: Store) => s.editor,
+ editorState: (s: Store) => s.editorState,
+};
diff --git a/src/app/[variants]/(main)/chat/profile/index.tsx b/src/app/[variants]/(main)/chat/profile/index.tsx
new file mode 100644
index 00000000000..2f5fb992688
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/profile/index.tsx
@@ -0,0 +1,66 @@
+'use client';
+
+import { Suspense, memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import AgentBuilder from '@/features/AgentBuilder';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+
+import Header from './features/Header';
+import ProfileEditor from './features/ProfileEditor';
+import ProfileHydration from './features/ProfileHydration';
+import ProfileProvider from './features/ProfileProvider';
+import { useProfileStore } from './features/store';
+
+const ProfileArea = memo(() => {
+ const editor = useProfileStore((s) => s.editor);
+ const isAgentConfigLoading = useAgentStore(agentSelectors.isAgentConfigLoading);
+
+ return (
+ <>
+ <Flexbox flex={1} height={'100%'}>
+ {isAgentConfigLoading ? (
+ <Loading debugId="ProfileArea" />
+ ) : (
+ <>
+ <Header />
+ <Flexbox
+ height={'100%'}
+ horizontal
+ onClick={() => {
+ editor?.focus();
+ }}
+ style={{ cursor: 'text', display: 'flex', overflowY: 'auto', position: 'relative' }}
+ width={'100%'}
+ >
+ <WideScreenContainer>
+ <ProfileEditor />
+ </WideScreenContainer>
+ </Flexbox>
+ </>
+ )}
+ </Flexbox>
+ <Suspense fallback={null}>
+ <ProfileHydration />
+ </Suspense>
+ </>
+ );
+});
+
+const AgentProfile = memo(() => {
+ return (
+ <Suspense fallback={<Loading debugId="AgentProfile" />}>
+ <ProfileProvider>
+ <Flexbox height={'100%'} horizontal width={'100%'}>
+ <ProfileArea />
+ <AgentBuilder />
+ </Flexbox>
+ </ProfileProvider>
+ </Suspense>
+ );
+});
+
+export default AgentProfile;
diff --git a/src/app/[variants]/(main)/group/profile/features/AgentBuilder/AgentBuilderConversation.tsx b/src/app/[variants]/(main)/group/profile/features/AgentBuilder/AgentBuilderConversation.tsx
new file mode 100644
index 00000000000..d65213f86d2
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/AgentBuilder/AgentBuilderConversation.tsx
@@ -0,0 +1,31 @@
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import AgentBuilderWelcome from '@/features/AgentBuilder/AgentBuilderWelcome';
+import type { ActionKeys } from '@/features/ChatInput';
+import { ChatInput, ChatList } from '@/features/Conversation';
+
+import TopicSelector from './TopicSelector';
+
+interface AgentBuilderConversationProps {
+ agentId: string;
+}
+const actions: ActionKeys[] = ['model'];
+
+/**
+ * Agent Builder Conversation Component
+ * Displays the chat interface for configuring the agent via conversation
+ */
+const AgentBuilderConversation = memo<AgentBuilderConversationProps>(({ agentId }) => {
+ return (
+ <Flexbox flex={1} height={'100%'}>
+ <TopicSelector agentId={agentId} />
+ <Flexbox flex={1} style={{ overflow: 'hidden' }}>
+ <ChatList welcome={<AgentBuilderWelcome />} />
+ </Flexbox>
+ <ChatInput leftActions={actions} />
+ </Flexbox>
+ );
+});
+
+export default AgentBuilderConversation;
diff --git a/src/app/[variants]/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx b/src/app/[variants]/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx
new file mode 100644
index 00000000000..7d20a28b301
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx
@@ -0,0 +1,59 @@
+import { ReactNode, memo, useMemo } from 'react';
+
+import { ConversationProvider } from '@/features/Conversation';
+import { useOperationState } from '@/hooks/useOperationState';
+import { useChatStore } from '@/store/chat';
+import { MessageMapKeyInput, messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+interface AgentBuilderProviderProps {
+ agentId: string;
+ children: ReactNode;
+}
+
+/**
+ * Group Agent Builder Conversation Provider
+ * Provides context for the Group Agent Builder chat panel
+ * Uses 'group_agent_builder' scope with groupId to isolate messages per group
+ */
+const AgentBuilderProvider = memo<AgentBuilderProviderProps>(({ agentId, children }) => {
+ const activeTopicId = useChatStore((s) => s.activeTopicId);
+
+ // Build conversation context for group agent builder
+ // Using group_agent_builder scope with groupId for per-group message isolation
+ const context = useMemo<MessageMapKeyInput>(
+ () => ({
+ agentId,
+ scope: 'group_agent_builder',
+ topicId: activeTopicId,
+ }),
+ [agentId, activeTopicId],
+ );
+
+ // Get messages from ChatStore based on context
+ const chatKey = useMemo(
+ () => (context ? messageMapKey(context) : null),
+ [context?.agentId, context?.groupId, context?.topicId],
+ );
+
+ const replaceMessages = useChatStore((s) => s.replaceMessages);
+ const messages = useChatStore((s) => (chatKey ? s.dbMessagesMap[chatKey] : undefined));
+
+ // Get operation state for reactive updates
+ const operationState = useOperationState(context);
+
+ return (
+ <ConversationProvider
+ context={context}
+ hasInitMessages={!!messages}
+ messages={messages}
+ onMessagesChange={(msgs) => {
+ replaceMessages(msgs, { context });
+ }}
+ operationState={operationState}
+ >
+ {children}
+ </ConversationProvider>
+ );
+});
+
+export default AgentBuilderProvider;
diff --git a/src/app/[variants]/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx b/src/app/[variants]/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx
new file mode 100644
index 00000000000..9c6ddaecb5e
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx
@@ -0,0 +1,81 @@
+import { ActionIcon, Tag } from '@lobehub/ui';
+import { Dropdown } from 'antd';
+import type { ItemType } from 'antd/es/menu/interface';
+import { Clock3Icon, PlusIcon } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
+import NavHeader from '@/features/NavHeader';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/slices/topic/selectors';
+
+interface TopicSelectorProps {
+ agentId: string;
+}
+
+const TopicSelector = memo<TopicSelectorProps>(({ agentId }) => {
+ const { t } = useTranslation('topic');
+
+ // Fetch topics for the group agent builder
+ useChatStore((s) => s.useFetchTopics)(true, { agentId });
+
+ const [activeTopicId, switchTopic, topics] = useChatStore((s) => [
+ s.activeTopicId,
+ s.switchTopic,
+ topicSelectors.getTopicsByAgentId(agentId)(s),
+ ]);
+
+ // Find active topic from the agent's topics list directly
+ const activeTopic = useMemo(
+ () => topics?.find((topic) => topic.id === activeTopicId),
+ [topics, activeTopicId],
+ );
+
+ const items = useMemo<ItemType[]>(
+ () =>
+ (topics || []).map((topic) => ({
+ key: topic.id,
+ label: topic.title,
+ onClick: () => switchTopic(topic.id),
+ })),
+ [topics, t, switchTopic],
+ );
+
+ return (
+ <NavHeader
+ left={activeTopic?.title ? <Tag>{activeTopic.title}</Tag> : undefined}
+ right={
+ <>
+ <ActionIcon
+ icon={PlusIcon}
+ onClick={() => switchTopic()}
+ size={DESKTOP_HEADER_ICON_SIZE}
+ title={t('actions.addNewTopic')}
+ />
+ <Dropdown
+ disabled={!topics || topics.length === 0}
+ menu={{
+ items,
+ selectedKeys: activeTopicId ? [activeTopicId] : [],
+ }}
+ overlayStyle={{
+ maxHeight: 600,
+ minWidth: 200,
+ overflowY: 'auto',
+ }}
+ placement="bottomRight"
+ trigger={['click']}
+ >
+ <ActionIcon disabled={!topics || topics.length === 0} icon={Clock3Icon} />
+ </Dropdown>
+ </>
+ }
+ showTogglePanelButton={false}
+ />
+ );
+});
+
+TopicSelector.displayName = 'TopicSelector';
+
+export default TopicSelector;
diff --git a/src/app/[variants]/(main)/group/profile/features/AgentBuilder/index.tsx b/src/app/[variants]/(main)/group/profile/features/AgentBuilder/index.tsx
new file mode 100644
index 00000000000..87c1c3a95e3
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/AgentBuilder/index.tsx
@@ -0,0 +1,58 @@
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { DraggablePanel } from '@lobehub/ui';
+import { useTheme } from 'antd-style';
+import { memo, useState } from 'react';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+
+import { useProfileStore } from '../store';
+import AgentBuilderConversation from './AgentBuilderConversation';
+import AgentBuilderProvider from './AgentBuilderProvider';
+
+const AgentBuilder = memo(() => {
+ const theme = useTheme();
+ const chatPanelExpanded = useProfileStore((s) => s.chatPanelExpanded);
+ const setChatPanelExpanded = useProfileStore((s) => s.setChatPanelExpanded);
+ const agentId = useAgentStore((s) => s.activeAgentId);
+ const groupAgentBuilderId = useAgentStore(builtinAgentSelectors.groupAgentBuilderId);
+
+ console.log('groupAgentBuilderId', groupAgentBuilderId);
+ console.log('agentId', agentId);
+ const [width, setWidth] = useState<string | number>(360);
+
+ const useInitBuiltinAgent = useAgentStore((s) => s.useInitBuiltinAgent);
+ useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.groupAgentBuilder);
+
+ return (
+ <DraggablePanel
+ backgroundColor={theme.colorBgContainer}
+ expand={chatPanelExpanded}
+ expandable={false}
+ maxWidth={600}
+ minWidth={360}
+ onExpandChange={setChatPanelExpanded}
+ onSizeChange={(_, size) => {
+ if (size?.width) {
+ setWidth(size.width);
+ }
+ }}
+ placement="right"
+ size={{
+ height: '100%',
+ width,
+ }}
+ >
+ {agentId && groupAgentBuilderId ? (
+ <AgentBuilderProvider agentId={groupAgentBuilderId}>
+ <AgentBuilderConversation agentId={groupAgentBuilderId} />
+ </AgentBuilderProvider>
+ ) : (
+ <Loading debugId="GroupAgentBuilder > Init" />
+ )}
+ </DraggablePanel>
+ );
+});
+
+export default AgentBuilder;
diff --git a/src/app/[variants]/(main)/group/profile/features/EditorCanvas/TypoBar.tsx b/src/app/[variants]/(main)/group/profile/features/EditorCanvas/TypoBar.tsx
new file mode 100644
index 00000000000..1c41ddb9972
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/EditorCanvas/TypoBar.tsx
@@ -0,0 +1,139 @@
+import { HotkeyEnum, getHotkeyById } from '@lobehub/editor';
+import { FloatActions } from '@lobehub/editor/react';
+import { type ChatInputActionsProps, CodeLanguageSelect } from '@lobehub/editor/react';
+import {
+ BoldIcon,
+ CodeXmlIcon,
+ ItalicIcon,
+ ListIcon,
+ ListOrderedIcon,
+ ListTodoIcon,
+ MessageSquareQuote,
+ SigmaIcon,
+ SquareDashedBottomCodeIcon,
+ StrikethroughIcon,
+ UnderlineIcon,
+} from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useProfileStore } from '../store';
+
+const TypoBar = memo(() => {
+ const { t } = useTranslation('editor');
+ const editorState = useProfileStore((s) => s.editorState);
+
+ const items: ChatInputActionsProps['items'] = useMemo(() => {
+ if (!editorState) return [];
+
+ return [
+ {
+ active: editorState.isBold,
+ icon: BoldIcon,
+ key: 'bold',
+ label: t('typobar.bold'),
+ onClick: editorState.bold,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Bold).keys },
+ },
+ {
+ active: editorState.isItalic,
+ icon: ItalicIcon,
+ key: 'italic',
+ label: t('typobar.italic'),
+ onClick: editorState.italic,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Italic).keys },
+ },
+ {
+ active: editorState.isUnderline,
+ icon: UnderlineIcon,
+ key: 'underline',
+ label: t('typobar.underline'),
+ onClick: editorState.underline,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Underline).keys },
+ },
+ {
+ active: editorState.isStrikethrough,
+ icon: StrikethroughIcon,
+ key: 'strikethrough',
+ label: t('typobar.strikethrough'),
+ onClick: editorState.strikethrough,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Strikethrough).keys },
+ },
+ {
+ type: 'divider',
+ },
+
+ {
+ icon: ListIcon,
+ key: 'bulletList',
+ label: t('typobar.bulletList'),
+ onClick: editorState.bulletList,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.BulletList).keys },
+ },
+ {
+ icon: ListOrderedIcon,
+ key: 'numberlist',
+ label: t('typobar.numberList'),
+ onClick: editorState.numberList,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.NumberList).keys },
+ },
+ {
+ icon: ListTodoIcon,
+ key: 'tasklist',
+ label: t('typobar.taskList'),
+ onClick: editorState.checkList,
+ },
+ {
+ type: 'divider',
+ },
+ {
+ active: editorState.isBlockquote,
+ icon: MessageSquareQuote,
+ key: 'blockquote',
+ label: t('typobar.blockquote'),
+ onClick: editorState.blockquote,
+ },
+ {
+ type: 'divider',
+ },
+ {
+ icon: SigmaIcon,
+ key: 'math',
+ label: t('typobar.tex'),
+ onClick: editorState.insertMath,
+ },
+ {
+ active: editorState.isCode,
+ icon: CodeXmlIcon,
+ key: 'code',
+ label: t('typobar.code'),
+ onClick: editorState.code,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.CodeInline).keys },
+ },
+ {
+ icon: SquareDashedBottomCodeIcon,
+ key: 'codeblock',
+ label: t('typobar.codeblock'),
+ onClick: editorState.codeblock,
+ },
+ editorState.isCodeblock && {
+ children: (
+ <CodeLanguageSelect
+ onSelect={(value) => editorState.updateCodeblockLang(value)}
+ value={editorState.codeblockLang}
+ />
+ ),
+ disabled: !editorState.isCodeblock,
+ key: 'codeblockLang',
+ },
+ ].filter(Boolean) as ChatInputActionsProps['items'];
+ }, [editorState, t]);
+
+ if (!editorState) return null;
+
+ return <FloatActions items={items} />;
+});
+
+TypoBar.displayName = 'TypoBar';
+
+export default TypoBar;
diff --git a/src/app/[variants]/(main)/group/profile/features/EditorCanvas/index.tsx b/src/app/[variants]/(main)/group/profile/features/EditorCanvas/index.tsx
new file mode 100644
index 00000000000..6d7b26f07e0
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/EditorCanvas/index.tsx
@@ -0,0 +1,140 @@
+'use client';
+
+import {
+ ReactCodePlugin,
+ ReactCodeblockPlugin,
+ ReactHRPlugin,
+ ReactLinkHighlightPlugin,
+ ReactListPlugin,
+ ReactMathPlugin,
+ ReactMentionPlugin,
+ ReactTablePlugin,
+ ReactToolbarPlugin,
+} from '@lobehub/editor';
+import { Editor } from '@lobehub/editor/react';
+import isEqual from 'fast-deep-equal';
+import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+import { useMentionOptions } from '../ProfileEditor/MentionList';
+import PROMPT_TEMPLATE from '../ProfileEditor/promptTemplate.json';
+import { useProfileStore } from '../store';
+import TypoBar from './TypoBar';
+import { useSlashItems } from './useSlashItems';
+
+const EditorCanvas = memo(() => {
+ const { t } = useTranslation('setting');
+ const [editorInit, setEditorInit] = useState(false);
+ const [contentInit, setContentInit] = useState(false);
+
+ // Get systemPrompt from agentGroup store (groupMap.config.systemPrompt)
+ const groupConfig = useAgentGroupStore(agentGroupSelectors.currentGroupConfig, isEqual);
+ const systemRole = groupConfig?.systemPrompt;
+ const updateGroupConfig = useAgentGroupStore((s) => s.updateGroupConfig);
+
+ // Get streaming state from agentGroup store
+ const streamingInProgress = useAgentGroupStore((s) => s.streamingSystemPromptInProgress);
+ const streamingSystemRole = useAgentGroupStore((s) => s.streamingSystemPrompt);
+
+ // For group profile, we don't use editorData - just systemPrompt
+ const editorData = undefined;
+ const [initialLoad] = useState(PROMPT_TEMPLATE);
+ const mentionOptions = useMentionOptions();
+ const editor = useProfileStore((s) => s.editor);
+ const handleContentChange = useProfileStore((s) => s.handleContentChange);
+ const slashItems = useSlashItems();
+
+ const prevStreamingRef = useRef<string | undefined>(undefined);
+
+ // Wrap handleContentChange with updateGroupConfig
+ const handleChange = useCallback(() => {
+ // Don't trigger save during streaming
+ if (streamingInProgress) return;
+ handleContentChange(async (config) => {
+ // Only update systemPrompt in group config
+ if (config.systemRole !== undefined) {
+ await updateGroupConfig({ systemPrompt: config.systemRole });
+ }
+ });
+ }, [handleContentChange, updateGroupConfig, streamingInProgress]);
+
+ // Handle streaming updates - update editor with streaming content
+ useEffect(() => {
+ if (!editor || !editorInit) return;
+ if (!streamingInProgress) {
+ prevStreamingRef.current = undefined;
+ return;
+ }
+
+ // Only update if content has changed
+ if (streamingSystemRole !== prevStreamingRef.current) {
+ prevStreamingRef.current = streamingSystemRole;
+ try {
+ editor.setDocument('markdown', streamingSystemRole || '');
+ } catch {
+ // Ignore errors during streaming updates
+ }
+ }
+ }, [editor, editorInit, streamingSystemRole, streamingInProgress]);
+
+ useEffect(() => {
+ if (!editorInit || !editor || contentInit) return;
+ // Don't init if streaming is in progress
+ if (streamingInProgress) return;
+ try {
+ if (editorData) {
+ editor.setDocument('json', editorData || PROMPT_TEMPLATE);
+ } else if (systemRole) {
+ editor.setDocument('markdown', systemRole);
+ } else {
+ editor.setDocument('json', PROMPT_TEMPLATE);
+ }
+ setContentInit(true);
+ } catch (error) {
+ console.error('[EditorCanvas] Failed to init editor content:', error);
+ }
+ }, [editorInit, contentInit, editor, editorData, systemRole, streamingInProgress]);
+
+ return (
+ <div
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ }}
+ >
+ <Editor
+ content={initialLoad}
+ editor={editor!}
+ lineEmptyPlaceholder={t('settingAgent.prompt.placeholder')}
+ mentionOption={mentionOptions}
+ onInit={() => setEditorInit(true)}
+ onTextChange={handleChange}
+ placeholder={t('settingAgent.prompt.placeholder')}
+ plugins={[
+ ReactListPlugin,
+ ReactCodePlugin,
+ ReactCodeblockPlugin,
+ ReactHRPlugin,
+ ReactLinkHighlightPlugin,
+ ReactTablePlugin,
+ ReactMathPlugin,
+ ReactMentionPlugin,
+ Editor.withProps(ReactToolbarPlugin, {
+ children: <TypoBar />,
+ }),
+ ]}
+ slashOption={{
+ items: slashItems,
+ }}
+ style={{
+ paddingBottom: 64,
+ }}
+ />
+ </div>
+ );
+});
+
+export default EditorCanvas;
diff --git a/src/app/[variants]/(main)/group/profile/features/EditorCanvas/useSlashItems.tsx b/src/app/[variants]/(main)/group/profile/features/EditorCanvas/useSlashItems.tsx
new file mode 100644
index 00000000000..17c94aee717
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/EditorCanvas/useSlashItems.tsx
@@ -0,0 +1,139 @@
+import {
+ INSERT_CHECK_LIST_COMMAND,
+ INSERT_HEADING_COMMAND,
+ INSERT_HORIZONTAL_RULE_COMMAND,
+ INSERT_MATH_COMMAND,
+ INSERT_ORDERED_LIST_COMMAND,
+ INSERT_TABLE_COMMAND,
+ INSERT_UNORDERED_LIST_COMMAND,
+ SlashOptions,
+} from '@lobehub/editor';
+import { Text } from '@lobehub/ui';
+import {
+ Heading1Icon,
+ Heading2Icon,
+ Heading3Icon,
+ ListIcon,
+ ListOrderedIcon,
+ ListTodoIcon,
+ MinusIcon,
+ SigmaIcon,
+ SquareDashedBottomCodeIcon,
+ Table2Icon,
+} from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useProfileStore } from '../store';
+
+export const useSlashItems = (): SlashOptions['items'] => {
+ const { t } = useTranslation('editor');
+ const editorState = useProfileStore((s) => s.editorState);
+ return useMemo(() => {
+ const data: SlashOptions['items'] = [
+ {
+ icon: Heading1Icon,
+ key: 'h1',
+ label: t('slash.h1'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h1' });
+ },
+ },
+ {
+ icon: Heading2Icon,
+ key: 'h2',
+ label: t('slash.h2'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h2' });
+ },
+ },
+ {
+ icon: Heading3Icon,
+ key: 'h3',
+ label: t('slash.h3'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h3' });
+ },
+ },
+ {
+ type: 'divider',
+ },
+ {
+ icon: ListTodoIcon,
+ key: 'tl',
+ label: t('typobar.taskList'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_CHECK_LIST_COMMAND, undefined);
+ },
+ },
+ {
+ icon: ListIcon,
+ key: 'ul',
+ label: t('typobar.bulletList'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, undefined);
+ },
+ },
+ {
+ icon: ListOrderedIcon,
+ key: 'ol',
+ label: t('typobar.numberList'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined);
+ },
+ },
+ {
+ type: 'divider',
+ },
+ {
+ icon: MinusIcon,
+ key: 'hr',
+ label: t('slash.hr'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_HORIZONTAL_RULE_COMMAND, {});
+ },
+ },
+ {
+ icon: Table2Icon,
+ key: 'table',
+ label: t('slash.table'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_TABLE_COMMAND, { columns: '3', rows: '3' });
+ },
+ },
+ {
+ icon: SquareDashedBottomCodeIcon,
+ key: 'codeblock',
+ label: t('typobar.codeblock'),
+ onSelect: () => {
+ editorState.codeblock();
+ },
+ },
+ {
+ icon: SigmaIcon,
+ key: 'tex',
+ label: t('slash.tex'),
+ onSelect: (editor) => {
+ editor.dispatchCommand(INSERT_MATH_COMMAND, { code: 'x^2 + y^2 = z^2' });
+ queueMicrotask(() => {
+ editor.focus();
+ });
+ },
+ },
+ ];
+ return data.map((item) => {
+ if (item.type === 'divider') return item;
+ return {
+ ...item,
+ extra: (
+ <Text code fontSize={12} type={'secondary'}>
+ {item.key}
+ </Text>
+ ),
+ style: {
+ minWidth: 200,
+ },
+ };
+ });
+ }, [t]);
+};
diff --git a/src/app/[variants]/(main)/group/profile/features/Header/AgentBuilderToggle.tsx b/src/app/[variants]/(main)/group/profile/features/Header/AgentBuilderToggle.tsx
new file mode 100644
index 00000000000..b01238bd05e
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/Header/AgentBuilderToggle.tsx
@@ -0,0 +1,25 @@
+import { ActionIcon } from '@lobehub/ui';
+import { BotMessageSquareIcon } from 'lucide-react';
+import { memo } from 'react';
+
+import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
+
+import { useProfileStore } from '../store';
+
+const AgentBuilderToggle = memo(() => {
+ const chatPanelExpanded = useProfileStore((s) => s.chatPanelExpanded);
+ const setChatPanelExpanded = useProfileStore((s) => s.setChatPanelExpanded);
+
+ return (
+ <ActionIcon
+ active={chatPanelExpanded}
+ aria-label="Agent Builder"
+ icon={BotMessageSquareIcon}
+ onClick={() => setChatPanelExpanded((prev) => !prev)}
+ size={DESKTOP_HEADER_ICON_SIZE}
+ title="Agent Builder"
+ />
+ );
+});
+
+export default AgentBuilderToggle;
diff --git a/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/PublishButton.tsx b/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/PublishButton.tsx
new file mode 100644
index 00000000000..10f80b89e55
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/PublishButton.tsx
@@ -0,0 +1,144 @@
+import { ActionIcon } from '@lobehub/ui';
+import { ShapesUploadIcon } from '@lobehub/ui/icons';
+import { memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { message } from '@/components/AntdStaticMethods';
+import { HEADER_ICON_SIZE } from '@/const/layoutTokens';
+import { checkOwnership } from '@/hooks/useAgentOwnershipCheck';
+import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
+import { resolveMarketAuthError } from '@/layout/AuthProvider/MarketAuth/errors';
+import { useServerConfigStore } from '@/store/serverConfig';
+
+import type { MarketPublishAction } from './types';
+import { useMarketPublish } from './useMarketPublish';
+
+interface MarketPublishButtonProps {
+ action: MarketPublishAction;
+ marketIdentifier?: string;
+ onPublishSuccess?: (identifier: string) => void;
+}
+
+const PublishButton = memo<MarketPublishButtonProps>(
+ ({ action, marketIdentifier, onPublishSuccess }) => {
+ const { t } = useTranslation(['setting', 'marketAuth']);
+
+ const mobile = useServerConfigStore((s) => s.isMobile);
+
+ const { isAuthenticated, isLoading, session, signIn } = useMarketAuth();
+ const { isPublishing, publish } = useMarketPublish({
+ action,
+ onSuccess: onPublishSuccess,
+ });
+
+ const buttonConfig = useMemo(() => {
+ if (action === 'upload') {
+ return {
+ authSuccessMessage: t('messages.success.upload', { ns: 'marketAuth' }),
+ authenticated: t('marketPublish.upload.tooltip'),
+ unauthenticated: t('marketPublish.upload.tooltip'),
+ } as const;
+ }
+
+ const submitText = t('submitAgentModal.tooltips');
+
+ return {
+ authSuccessMessage: t('messages.success.submit', { ns: 'marketAuth' }),
+ authenticated: submitText,
+ unauthenticated: t('marketPublish.submit.tooltip'),
+ } as const;
+ }, [action, t]);
+
+ const handleButtonClick = useCallback(async () => {
+ if (!isAuthenticated) {
+ try {
+ message.loading({
+ content: t('messages.loading', { ns: 'marketAuth' }),
+ key: 'market-auth',
+ });
+ const accountId = await signIn();
+ message.success({ content: buttonConfig.authSuccessMessage, key: 'market-auth' });
+
+ // Check ownership after authentication if marketIdentifier exists
+ if (marketIdentifier && accountId !== null) {
+ let accessToken = session?.accessToken;
+
+ if (!accessToken && typeof window !== 'undefined') {
+ const storedSession = sessionStorage.getItem('market_auth_session');
+ if (storedSession) {
+ try {
+ const parsed = JSON.parse(storedSession) as { accessToken?: string };
+ accessToken = parsed.accessToken;
+ } catch (parseError) {
+ console.error(
+ '[MarketPublishButton] Failed to parse stored session:',
+ parseError,
+ );
+ }
+ }
+ }
+
+ if (accessToken) {
+ try {
+ const isOwner = await checkOwnership({
+ accessToken,
+ accountId,
+ marketIdentifier,
+ skipCache: true,
+ });
+
+ // If user is not the owner and trying to upload, just return
+ // The parent component should handle the action switch
+ if (!isOwner && action === 'upload') {
+ return;
+ }
+ } catch (ownershipError) {
+ console.error('[MarketPublishButton] Failed to confirm ownership:', ownershipError);
+ }
+ }
+ }
+
+ // After authentication, proceed with publish
+ await publish();
+ } catch (error) {
+ console.error(`[MarketPublishButton][${action}] Authorization failed:`, error);
+ const normalizedError = resolveMarketAuthError(error);
+ message.error({
+ content: t(`errors.${normalizedError.code}`, { ns: 'marketAuth' }),
+ key: 'market-auth',
+ });
+ }
+ return;
+ }
+
+ // User is authenticated, directly publish
+ await publish();
+ }, [
+ action,
+ buttonConfig.authSuccessMessage,
+ isAuthenticated,
+ marketIdentifier,
+ publish,
+ session?.accessToken,
+ signIn,
+ t,
+ ]);
+
+ const buttonTitle = isAuthenticated ? buttonConfig.authenticated : buttonConfig.unauthenticated;
+ const loading = isLoading || isPublishing;
+
+ return (
+ <ActionIcon
+ icon={ShapesUploadIcon}
+ loading={loading}
+ onClick={handleButtonClick}
+ size={HEADER_ICON_SIZE(mobile)}
+ title={buttonTitle}
+ />
+ );
+ },
+);
+
+PublishButton.displayName = 'MarketPublishButton';
+
+export default PublishButton;
diff --git a/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/PublishResultModal.tsx b/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/PublishResultModal.tsx
new file mode 100644
index 00000000000..14989bfdcb1
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/PublishResultModal.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import { FluentEmoji, Modal, Text } from '@lobehub/ui';
+import { Result } from 'antd';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+
+interface PublishResultModalProps {
+ identifier?: string;
+ onCancel: () => void;
+ open: boolean;
+}
+
+const PublishResultModal = memo<PublishResultModalProps>(({ identifier, onCancel, open }) => {
+ const navigate = useNavigate();
+ const { t } = useTranslation('setting');
+ const { t: tCommon } = useTranslation('common');
+
+ const handleGoToMarket = () => {
+ if (identifier) {
+ navigate(`/community/assistant/${identifier}`);
+ }
+ onCancel();
+ };
+
+ return (
+ <Modal
+ cancelText={tCommon('cancel')}
+ centered
+ okText={t('marketPublish.resultModal.view')}
+ onCancel={onCancel}
+ onOk={handleGoToMarket}
+ open={open}
+ title={null}
+ width={440}
+ >
+ <Result
+ icon={<FluentEmoji emoji={'🎉'} size={96} type={'anim'} />}
+ style={{
+ paddingBottom: 32,
+ paddingTop: 48,
+ width: '100%',
+ }}
+ subTitle={
+ <Text fontSize={14} type={'secondary'}>
+ {t('marketPublish.resultModal.message')}
+ </Text>
+ }
+ title={
+ <Text fontSize={28} weight={'bold'}>
+ {t('marketPublish.resultModal.title')}
+ </Text>
+ }
+ />
+ </Modal>
+ );
+});
+
+export default PublishResultModal;
diff --git a/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/index.tsx b/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/index.tsx
new file mode 100644
index 00000000000..e11a691d207
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/index.tsx
@@ -0,0 +1,80 @@
+import { ActionIcon } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import { Loader2 } from 'lucide-react';
+import { memo, useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentOwnershipCheck } from '@/hooks/useAgentOwnershipCheck';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+
+import PublishButton from './PublishButton';
+import PublishResultModal from './PublishResultModal';
+
+const AgentPublishButton = memo(() => {
+ const { t } = useTranslation('setting');
+ const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
+ const { isOwnAgent } = useAgentOwnershipCheck(meta?.marketIdentifier);
+
+ const [showResultModal, setShowResultModal] = useState(false);
+ const [publishedIdentifier, setPublishedIdentifier] = useState<string>();
+
+ const handlePublishSuccess = useCallback((identifier: string) => {
+ setPublishedIdentifier(identifier);
+ setShowResultModal(true);
+ }, []);
+
+ const buttonType = useMemo(() => {
+ if (!meta?.marketIdentifier) {
+ return 'submit';
+ }
+ if (isOwnAgent === null) {
+ return 'loading';
+ }
+ if (isOwnAgent === true) {
+ return 'upload';
+ }
+ return 'submit';
+ }, [meta?.marketIdentifier, isOwnAgent]);
+
+ const content = useMemo(() => {
+ switch (buttonType) {
+ case 'upload': {
+ return (
+ <PublishButton
+ action="upload"
+ marketIdentifier={meta?.marketIdentifier}
+ onPublishSuccess={handlePublishSuccess}
+ />
+ );
+ }
+
+ case 'submit': {
+ return (
+ <PublishButton
+ action="submit"
+ marketIdentifier={meta?.marketIdentifier}
+ onPublishSuccess={handlePublishSuccess}
+ />
+ );
+ }
+
+ default: {
+ return <ActionIcon disabled icon={Loader2} loading title={t('checkingPermissions')} />;
+ }
+ }
+ }, [buttonType, meta?.marketIdentifier]);
+
+ return (
+ <>
+ {content}
+ <PublishResultModal
+ identifier={publishedIdentifier}
+ onCancel={() => setShowResultModal(false)}
+ open={showResultModal}
+ />
+ </>
+ );
+});
+
+export default AgentPublishButton;
diff --git a/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/types.ts b/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/types.ts
new file mode 100644
index 00000000000..f1378b670cf
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/types.ts
@@ -0,0 +1 @@
+export type MarketPublishAction = 'submit' | 'upload';
diff --git a/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/useMarketPublish.ts b/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/useMarketPublish.ts
new file mode 100644
index 00000000000..bba04646693
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/useMarketPublish.ts
@@ -0,0 +1,184 @@
+import isEqual from 'fast-deep-equal';
+import { useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { message } from '@/components/AntdStaticMethods';
+import { useTokenCount } from '@/hooks/useTokenCount';
+import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
+import { marketApiService } from '@/services/marketApi';
+import { useAgentStore } from '@/store/agent';
+import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
+import { useGlobalStore } from '@/store/global';
+import { globalGeneralSelectors } from '@/store/global/selectors';
+
+import type { MarketPublishAction } from './types';
+import { generateDefaultChangelog, generateMarketIdentifier } from './utils';
+
+interface UseMarketPublishOptions {
+ action: MarketPublishAction;
+ onSuccess?: (identifier: string) => void;
+}
+
+export const useMarketPublish = ({ action, onSuccess }: UseMarketPublishOptions) => {
+ const { t } = useTranslation('setting');
+ const [isPublishing, setIsPublishing] = useState(false);
+ const { isAuthenticated, session } = useMarketAuth();
+
+ // Agent data from store
+ const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
+ const updateAgentMeta = useAgentStore((s) => s.updateAgentMeta);
+ const systemRole = useAgentStore(agentSelectors.currentAgentSystemRole);
+ const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);
+ const editorData = config?.editorData;
+ const language = useGlobalStore(globalGeneralSelectors.currentLanguage);
+ const agentConfig = useAgentStore(agentSelectors.currentAgentConfig);
+ const chatConfig = useAgentStore(agentChatConfigSelectors.currentChatConfig);
+ const plugins = useAgentStore(agentSelectors.currentAgentPlugins);
+ const model = useAgentStore(agentSelectors.currentAgentModel);
+ const provider = useAgentStore(agentSelectors.currentAgentModelProvider);
+ const tokenUsage = useTokenCount(systemRole);
+
+ const isSubmit = action === 'submit';
+
+ const publish = useCallback(async () => {
+ if (!isAuthenticated || !session?.accessToken) {
+ return { success: false };
+ }
+
+ const messageKey = isSubmit ? 'submit' : 'upload-version';
+ const loadingMessage = isSubmit
+ ? t('marketPublish.modal.loading.submit')
+ : t('marketPublish.modal.loading.upload');
+
+ let identifier = meta?.marketIdentifier;
+ const changelog = generateDefaultChangelog();
+
+ try {
+ setIsPublishing(true);
+ message.loading({ content: loadingMessage, key: messageKey });
+ marketApiService.setAccessToken(session.accessToken);
+
+ if (isSubmit) {
+ identifier = generateMarketIdentifier();
+
+ try {
+ await marketApiService.getAgentDetail(identifier);
+ } catch {
+ const createPayload: Record<string, unknown> = {
+ identifier,
+ name: meta?.title || '',
+ };
+ await marketApiService.createAgent(createPayload as any);
+ }
+ } else if (!identifier) {
+ message.error({
+ content: t('marketPublish.modal.messages.missingIdentifier'),
+ key: messageKey,
+ });
+ return { success: false };
+ }
+
+ const versionPayload = {
+ avatar: meta?.avatar,
+ changelog,
+ config: {
+ chatConfig: {
+ enableHistoryCount: chatConfig?.enableHistoryCount,
+ historyCount: chatConfig?.historyCount,
+ maxTokens: agentConfig?.params?.max_tokens,
+ searchMode: chatConfig?.searchMode,
+ temperature: agentConfig?.params?.temperature,
+ topP: agentConfig?.params?.top_p,
+ },
+ description: meta?.description,
+ locale: language,
+ model: {
+ model,
+ parameters: agentConfig?.params,
+ provider,
+ },
+ plugins:
+ plugins?.map((plugin) => {
+ if (typeof plugin === 'string') {
+ return plugin;
+ } else {
+ return null;
+ }
+ }) || [],
+ systemRole: systemRole,
+ },
+ description: meta?.description || '',
+ editorData: editorData,
+ identifier: identifier,
+ name: meta?.title || '',
+ tags: meta?.tags,
+ tokenUsage: tokenUsage,
+ };
+
+ try {
+ await marketApiService.createAgentVersion(versionPayload);
+ } catch (versionError) {
+ const errorMessage = versionError instanceof Error ? versionError.message : '未知错误';
+ message.error({
+ content: t('marketPublish.modal.messages.createVersionFailed', {
+ message: errorMessage,
+ }),
+ key: messageKey,
+ });
+ return { success: false };
+ }
+
+ if (isSubmit) {
+ updateAgentMeta({ marketIdentifier: identifier });
+ }
+
+ message.success({
+ content: t('submitAgentModal.success'),
+ key: messageKey,
+ });
+
+ onSuccess?.(identifier!);
+ return { identifier, success: true };
+ } catch (error) {
+ console.error('Market publish failed:', error);
+ const errorMessage = error instanceof Error ? error.message : '发布失败';
+ message.error({
+ content: t('marketPublish.modal.messages.publishFailed', {
+ message: errorMessage,
+ }),
+ key: messageKey,
+ });
+ return { success: false };
+ } finally {
+ setIsPublishing(false);
+ }
+ }, [
+ agentConfig?.params,
+ chatConfig?.enableHistoryCount,
+ chatConfig?.historyCount,
+ chatConfig?.searchMode,
+ editorData,
+ isAuthenticated,
+ isSubmit,
+ language,
+ meta?.avatar,
+ meta?.description,
+ meta?.marketIdentifier,
+ meta?.tags,
+ meta?.title,
+ model,
+ onSuccess,
+ plugins,
+ provider,
+ session?.accessToken,
+ systemRole,
+ tokenUsage,
+ t,
+ updateAgentMeta,
+ ]);
+
+ return {
+ isPublishing,
+ publish,
+ };
+};
diff --git a/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/utils.ts b/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/utils.ts
new file mode 100644
index 00000000000..877a3a75479
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/Header/AgentPublishButton/utils.ts
@@ -0,0 +1,22 @@
+import { customAlphabet } from 'nanoid/non-secure';
+
+/**
+ * Generate a market identifier (8-character lowercase alphanumeric string)
+ * Format: [a-z0-9]{8}
+ * @returns A unique 8-character market identifier
+ */
+export const generateMarketIdentifier = () => {
+ const alphabet = '0123456789abcdefghijklmnopqrstuvwxyz';
+ const generate = customAlphabet(alphabet, 8);
+ return generate();
+};
+
+/**
+ * Generate a default changelog based on current timestamp
+ * @returns A timestamp-based changelog string
+ */
+export const generateDefaultChangelog = () => {
+ const now = new Date();
+ const formattedDate = now.toISOString().split('T')[0];
+ return `Release ${formattedDate}`;
+};
diff --git a/src/app/[variants]/(main)/group/profile/features/Header/AutoSaveHint.tsx b/src/app/[variants]/(main)/group/profile/features/Header/AutoSaveHint.tsx
new file mode 100644
index 00000000000..63d991ee14d
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/Header/AutoSaveHint.tsx
@@ -0,0 +1,17 @@
+'use client';
+
+import { memo } from 'react';
+
+import AutoSaveHintBase from '@/components/Editor/AutoSaveHint';
+
+/**
+ * AutoSaveHint - Save status indicator for group settings
+ * TODO: Add saveStatus and lastUpdatedTime to agentGroupStore when needed
+ */
+const AutoSaveHint = memo(() => {
+ // Group profile currently doesn't track save status
+ // Return idle state for now
+ return <AutoSaveHintBase lastUpdatedTime={null} saveStatus={'idle'} />;
+});
+
+export default AutoSaveHint;
diff --git a/src/app/[variants]/(main)/group/profile/features/Header/index.tsx b/src/app/[variants]/(main)/group/profile/features/Header/index.tsx
new file mode 100644
index 00000000000..adbd075baed
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/Header/index.tsx
@@ -0,0 +1,24 @@
+import { memo } from 'react';
+
+import NavHeader from '@/features/NavHeader';
+import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
+
+import AgentBuilderToggle from './AgentBuilderToggle';
+import AutoSaveHint from './AutoSaveHint';
+
+const Header = memo(() => {
+ return (
+ <NavHeader
+ left={<AutoSaveHint />}
+ right={
+ <>
+ <WideScreenButton />
+ <AgentBuilderToggle />
+ {/* TODO: Add GroupPublishButton when group publishing is supported */}
+ </>
+ }
+ />
+ );
+});
+
+export default Header;
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/AgentHeader.tsx b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/AgentHeader.tsx
new file mode 100644
index 00000000000..ed7965fd2b9
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/AgentHeader.tsx
@@ -0,0 +1,189 @@
+'use client';
+
+import { DEFAULT_AVATAR, EDITOR_DEBOUNCE_TIME } from '@lobechat/const';
+import { Block, Icon, Input, Skeleton, Tooltip } from '@lobehub/ui';
+import { useDebounceFn } from 'ahooks';
+import { message } from 'antd';
+import isEqual from 'fast-deep-equal';
+import { PaletteIcon } from 'lucide-react';
+import { Suspense, memo, useCallback, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import SupervisorAvatar from '@/app/[variants]/(main)/group/features/GroupAvatar';
+import EmojiPicker from '@/components/EmojiPicker';
+import BackgroundSwatches from '@/features/AgentSetting/AgentMeta/BackgroundSwatches';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+import { useFileStore } from '@/store/file';
+import { useGlobalStore } from '@/store/global';
+import { globalGeneralSelectors } from '@/store/global/selectors';
+
+const MAX_AVATAR_SIZE = 1024 * 1024; // 1MB limit for server actions
+
+const AgentHeader = memo(() => {
+ const { t } = useTranslation(['setting', 'common']);
+ const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
+
+ // Get title from agentGroup store (groupMap.title)
+ const groupMeta = useAgentGroupStore(agentGroupSelectors.currentGroupMeta, isEqual);
+ const updateGroupMeta = useAgentGroupStore((s) => s.updateGroupMeta);
+
+ // Get avatar/backgroundColor from supervisor agent (useAgentStore)
+ const agentMeta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
+ const updateAgentMeta = useAgentStore((s) => s.updateAgentMeta);
+
+ // File upload
+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
+ const [uploading, setUploading] = useState(false);
+
+ // Local state for inputs (to avoid stuttering during typing)
+ const [localTitle, setLocalTitle] = useState(groupMeta.title || '');
+
+ // Sync local state when meta changes from external source
+ useEffect(() => {
+ setLocalTitle(groupMeta.title || '');
+ }, [groupMeta.title]);
+
+ // Debounced save for title - save to group store
+ const { run: debouncedSaveTitle } = useDebounceFn(
+ (value: string) => {
+ updateGroupMeta({ title: value });
+ },
+ { wait: EDITOR_DEBOUNCE_TIME },
+ );
+
+ // Handle avatar change (immediate save) - save to agent store (supervisor agent)
+ const handleAvatarChange = (emoji: string) => {
+ updateAgentMeta({ avatar: emoji });
+ };
+
+ // Handle avatar upload
+ const handleAvatarUpload = useCallback(
+ async (file: File) => {
+ if (file.size > MAX_AVATAR_SIZE) {
+ message.error(t('settingAgent.avatar.sizeExceeded', { ns: 'setting' }));
+ return;
+ }
+
+ setUploading(true);
+ try {
+ const result = await uploadWithProgress({ file });
+ console.log('result', result);
+ if (result?.url) {
+ updateAgentMeta({ avatar: result.url });
+ }
+ } finally {
+ setUploading(false);
+ }
+ },
+ [uploadWithProgress, updateAgentMeta, t],
+ );
+
+ // Handle avatar delete
+ const handleAvatarDelete = useCallback(() => {
+ updateAgentMeta({ avatar: undefined });
+ }, [updateAgentMeta]);
+
+ // Handle background color change (immediate save) - save to agent store (supervisor agent)
+ const handleBackgroundColorChange = (color?: string) => {
+ if (color !== undefined) {
+ updateAgentMeta({ backgroundColor: color });
+ }
+ };
+
+ return (
+ <Flexbox
+ gap={16}
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ }}
+ paddingBlock={16}
+ style={{
+ cursor: 'default',
+ }}
+ >
+ <EmojiPicker
+ allowDelete={!!agentMeta.avatar}
+ allowUpload
+ background={
+ agentMeta.backgroundColor && agentMeta.backgroundColor !== 'rgba(0,0,0,0)'
+ ? agentMeta.backgroundColor
+ : undefined
+ }
+ customRender={
+ agentMeta.avatar && agentMeta.avatar !== DEFAULT_AVATAR
+ ? undefined
+ : () => {
+ return (
+ <Block clickable height={72} width={72}>
+ <SupervisorAvatar size={72} />
+ </Block>
+ );
+ }
+ }
+ customTabs={[
+ {
+ label: (
+ <Tooltip title={t('settingAgent.backgroundColor.title', { ns: 'setting' })}>
+ <Icon icon={PaletteIcon} size={{ size: 20, strokeWidth: 2.5 }} />
+ </Tooltip>
+ ),
+ render: () => (
+ <Flexbox padding={8} width={332}>
+ <Suspense
+ fallback={
+ <Flexbox gap={8}>
+ <Skeleton.Button block style={{ height: 38 }} />
+ <Skeleton.Button block style={{ height: 38 }} />
+ </Flexbox>
+ }
+ >
+ <BackgroundSwatches
+ gap={8}
+ onChange={handleBackgroundColorChange}
+ shape={'square'}
+ size={38}
+ value={agentMeta.backgroundColor}
+ />
+ </Suspense>
+ </Flexbox>
+ ),
+ value: 'background',
+ },
+ ]}
+ loading={uploading}
+ locale={locale}
+ onChange={handleAvatarChange}
+ onDelete={handleAvatarDelete}
+ onUpload={handleAvatarUpload}
+ popupProps={{
+ placement: 'bottomLeft',
+ }}
+ shape={'square'}
+ size={72}
+ value={agentMeta.avatar}
+ />
+ <Input
+ onChange={(e) => {
+ setLocalTitle(e.target.value);
+ debouncedSaveTitle(e.target.value);
+ }}
+ placeholder={t('settingAgent.name.placeholder', { ns: 'setting' })}
+ style={{
+ fontSize: 36,
+ fontWeight: 600,
+ padding: 0,
+ width: '100%',
+ }}
+ value={localTitle}
+ variant={'borderless'}
+ />
+ </Flexbox>
+ );
+});
+
+export default AgentHeader;
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/AgentTool.tsx b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/AgentTool.tsx
new file mode 100644
index 00000000000..e6584405518
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/AgentTool.tsx
@@ -0,0 +1,399 @@
+'use client';
+
+import { KLAVIS_SERVER_TYPES, KlavisServerType } from '@lobechat/const';
+import { Avatar, Button, Icon, ItemType, Segmented } from '@lobehub/ui';
+import { useTheme } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { ArrowRight, PlusIcon, Store, ToyBrick } from 'lucide-react';
+import Image from 'next/image';
+import React, { Suspense, memo, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import PluginAvatar from '@/components/Plugins/PluginAvatar';
+import KlavisServerItem from '@/features/ChatInput/ActionBar/Tools/KlavisServerItem';
+import ToolItem from '@/features/ChatInput/ActionBar/Tools/ToolItem';
+import ActionDropdown from '@/features/ChatInput/ActionBar/components/ActionDropdown';
+import PluginStore from '@/features/PluginStore';
+import { useCheckPluginsIsInstalled } from '@/hooks/useCheckPluginsIsInstalled';
+import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+import { useToolStore } from '@/store/tool';
+import {
+ builtinToolSelectors,
+ klavisStoreSelectors,
+ pluginSelectors,
+} from '@/store/tool/selectors';
+
+import PluginTag from './PluginTag';
+
+type TabType = 'all' | 'installed';
+
+/**
+ * Klavis 服务器图标组件
+ * 对于 string 类型的 icon,使用 Image 组件渲染
+ * 对于 IconType 类型的 icon,使用 Icon 组件渲染,并根据主题设置填充色
+ */
+const KlavisIcon = memo<Pick<KlavisServerType, 'icon' | 'label'>>(({ icon, label }) => {
+ const theme = useTheme();
+
+ if (typeof icon === 'string') {
+ return (
+ <Image alt={label} height={18} src={icon} style={{ flex: 'none' }} unoptimized width={18} />
+ );
+ }
+
+ // 使用主题色填充,在深色模式下自动适应
+ return <Icon fill={theme.colorText} icon={icon} size={18} />;
+});
+
+const AgentTool = memo(() => {
+ const { t } = useTranslation('setting');
+ const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);
+ const theme = useTheme();
+
+ // Plugin state management
+ const plugins = config?.plugins || [];
+
+ const toggleAgentPlugin = useAgentStore((s) => s.toggleAgentPlugin);
+ const installedPluginList = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);
+ const builtinList = useToolStore(builtinToolSelectors.metaList, isEqual);
+
+ // Klavis 相关状态
+ const allKlavisServers = useToolStore(klavisStoreSelectors.getServers, isEqual);
+ const isKlavisEnabledInEnv = useServerConfigStore(serverConfigSelectors.enableKlavis);
+
+ // Plugin store modal state
+ const [modalOpen, setModalOpen] = useState(false);
+ const [updating, setUpdating] = useState(false);
+
+ // Tab state for dual-column layout
+ const [activeTab, setActiveTab] = useState<TabType | null>(null);
+ const isInitializedRef = useRef(false);
+
+ // Fetch plugins
+ const [useFetchPluginStore, useFetchUserKlavisServers] = useToolStore((s) => [
+ s.useFetchPluginStore,
+ s.useFetchUserKlavisServers,
+ ]);
+ useFetchPluginStore();
+ useFetchInstalledPlugins();
+ useCheckPluginsIsInstalled(plugins);
+
+ // 使用 SWR 加载用户的 Klavis 集成(从数据库)
+ useFetchUserKlavisServers(isKlavisEnabledInEnv);
+
+ // Set default tab based on installed plugins (only on first load)
+ useEffect(() => {
+ if (!isInitializedRef.current && plugins.length >= 0) {
+ isInitializedRef.current = true;
+ setActiveTab(plugins.length > 0 ? 'installed' : 'all');
+ }
+ }, [plugins.length]);
+
+ // 根据 identifier 获取已连接的服务器
+ const getServerByName = (identifier: string) => {
+ return allKlavisServers.find((server) => server.identifier === identifier);
+ };
+
+ // 获取所有 Klavis 服务器类型的 identifier 集合(用于过滤 builtinList)
+ const allKlavisTypeIdentifiers = useMemo(
+ () => new Set(KLAVIS_SERVER_TYPES.map((type) => type.identifier)),
+ [],
+ );
+
+ // 过滤掉 builtinList 中的 klavis 工具(它们会单独显示在 Klavis 区域)
+ const filteredBuiltinList = useMemo(
+ () =>
+ isKlavisEnabledInEnv
+ ? builtinList.filter((item) => !allKlavisTypeIdentifiers.has(item.identifier))
+ : builtinList,
+ [builtinList, allKlavisTypeIdentifiers, isKlavisEnabledInEnv],
+ );
+
+ // Klavis 服务器列表项
+ const klavisServerItems = useMemo(
+ () =>
+ isKlavisEnabledInEnv
+ ? KLAVIS_SERVER_TYPES.map((type) => ({
+ icon: <KlavisIcon icon={type.icon} label={type.label} />,
+ key: type.identifier,
+ label: (
+ <KlavisServerItem
+ identifier={type.identifier}
+ label={type.label}
+ server={getServerByName(type.identifier)}
+ serverName={type.serverName}
+ />
+ ),
+ }))
+ : [],
+ [isKlavisEnabledInEnv, allKlavisServers],
+ );
+
+ // Handle plugin remove via Tag close
+ const handleRemovePlugin =
+ (pluginId: string | { enabled: boolean; identifier: string; settings: Record<string, any> }) =>
+ (e: React.MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const identifier = typeof pluginId === 'string' ? pluginId : pluginId?.identifier;
+ toggleAgentPlugin(identifier, false);
+ };
+
+ // Build dropdown menu items (adapted from useControls)
+ const enablePluginCount = plugins.filter(
+ (id) => !builtinList.some((b) => b.identifier === id),
+ ).length;
+
+ // 合并 builtin 工具和 Klavis 服务器
+ const builtinItems = useMemo(
+ () => [
+ // 原有的 builtin 工具
+ ...filteredBuiltinList.map((item) => ({
+ icon: <Avatar avatar={item.meta.avatar} size={20} style={{ flex: 'none' }} />,
+ key: item.identifier,
+ label: (
+ <ToolItem
+ checked={plugins.includes(item.identifier)}
+ id={item.identifier}
+ label={item.meta?.title}
+ onUpdate={async () => {
+ setUpdating(true);
+ await toggleAgentPlugin(item.identifier);
+ setUpdating(false);
+ }}
+ />
+ ),
+ })),
+ // Klavis 服务器
+ ...klavisServerItems,
+ ],
+ [filteredBuiltinList, klavisServerItems, plugins, toggleAgentPlugin],
+ );
+
+ // Plugin items for dropdown
+ const pluginItems = useMemo(
+ () =>
+ installedPluginList.map((item) => ({
+ icon: item?.avatar ? (
+ <PluginAvatar avatar={item.avatar} size={20} />
+ ) : (
+ <Icon icon={ToyBrick} size={20} />
+ ),
+ key: item.identifier,
+ label: (
+ <ToolItem
+ checked={plugins.includes(item.identifier)}
+ id={item.identifier}
+ label={item.title}
+ onUpdate={async () => {
+ setUpdating(true);
+ await toggleAgentPlugin(item.identifier);
+ setUpdating(false);
+ }}
+ />
+ ),
+ })),
+ [installedPluginList, plugins, toggleAgentPlugin],
+ );
+
+ // All tab items (市场 tab)
+ const allTabItems: ItemType[] = useMemo(
+ () => [
+ {
+ children: builtinItems,
+ key: 'builtins',
+ label: t('tools.builtins.groupName'),
+ type: 'group',
+ },
+ {
+ children: pluginItems,
+ key: 'plugins',
+ label: (
+ <Flexbox align={'center'} gap={40} horizontal justify={'space-between'}>
+ {t('tools.plugins.groupName')}
+ {enablePluginCount === 0 ? null : (
+ <div style={{ fontSize: 12, marginInlineEnd: 4 }}>
+ {t('tools.plugins.enabled', { num: enablePluginCount })}
+ </div>
+ )}
+ </Flexbox>
+ ),
+ type: 'group',
+ },
+ {
+ type: 'divider',
+ },
+ {
+ extra: <Icon icon={ArrowRight} />,
+ icon: Store,
+ key: 'plugin-store',
+ label: t('tools.plugins.store'),
+ onClick: () => {
+ setModalOpen(true);
+ },
+ },
+ ],
+ [builtinItems, pluginItems, enablePluginCount, t],
+ );
+
+ // Installed tab items - 只显示已启用的
+ const installedTabItems: ItemType[] = useMemo(() => {
+ const items: ItemType[] = [];
+
+ // 已启用的 builtin 工具
+ const enabledBuiltinItems = filteredBuiltinList
+ .filter((item) => plugins.includes(item.identifier))
+ .map((item) => ({
+ icon: <Avatar avatar={item.meta.avatar} size={20} style={{ flex: 'none' }} />,
+ key: item.identifier,
+ label: (
+ <ToolItem
+ checked={true}
+ id={item.identifier}
+ label={item.meta?.title}
+ onUpdate={async () => {
+ setUpdating(true);
+ await toggleAgentPlugin(item.identifier);
+ setUpdating(false);
+ }}
+ />
+ ),
+ }));
+
+ // 已连接且已启用的 Klavis 服务器
+ const connectedKlavisItems = klavisServerItems.filter((item) =>
+ plugins.includes(item.key as string),
+ );
+
+ // 合并 builtin 和 Klavis
+ const allBuiltinItems = [...enabledBuiltinItems, ...connectedKlavisItems];
+
+ if (allBuiltinItems.length > 0) {
+ items.push({
+ children: allBuiltinItems,
+ key: 'installed-builtins',
+ label: t('tools.builtins.groupName'),
+ type: 'group',
+ });
+ }
+
+ // 已启用的插件
+ const installedPlugins = installedPluginList
+ .filter((item) => plugins.includes(item.identifier))
+ .map((item) => ({
+ icon: item?.avatar ? (
+ <PluginAvatar avatar={item.avatar} size={20} />
+ ) : (
+ <Icon icon={ToyBrick} size={20} />
+ ),
+ key: item.identifier,
+ label: (
+ <ToolItem
+ checked={true}
+ id={item.identifier}
+ label={item.title}
+ onUpdate={async () => {
+ setUpdating(true);
+ await toggleAgentPlugin(item.identifier);
+ setUpdating(false);
+ }}
+ />
+ ),
+ }));
+
+ if (installedPlugins.length > 0) {
+ items.push({
+ children: installedPlugins,
+ key: 'installed-plugins',
+ label: t('tools.plugins.groupName'),
+ type: 'group',
+ });
+ }
+
+ return items;
+ }, [filteredBuiltinList, klavisServerItems, installedPluginList, plugins, toggleAgentPlugin, t]);
+
+ // Use effective tab for display (default to all while initializing)
+ const effectiveTab = activeTab ?? 'all';
+ const currentItems = effectiveTab === 'all' ? allTabItems : installedTabItems;
+
+ // Final menu items with tab segmented control
+ const menuItems: ItemType[] = useMemo(
+ () => [
+ {
+ key: 'tabs',
+ label: (
+ <Segmented
+ block
+ onChange={(v) => setActiveTab(v as TabType)}
+ options={[
+ {
+ label: t('tools.tabs.all', { defaultValue: 'All' }),
+ value: 'all',
+ },
+ {
+ label: t('tools.tabs.installed', { defaultValue: 'Installed' }),
+ value: 'installed',
+ },
+ ]}
+ size="small"
+ value={effectiveTab}
+ />
+ ),
+ type: 'group',
+ },
+ ...currentItems,
+ ],
+ [currentItems, effectiveTab, t],
+ );
+
+ const button = (
+ <Button
+ icon={PlusIcon}
+ loading={updating}
+ size={'small'}
+ style={{ color: theme.colorTextSecondary }}
+ type={'text'}
+ >
+ {t('tools.add', { defaultValue: 'Add' })}
+ </Button>
+ );
+
+ return (
+ <>
+ {/* Plugin Selector and Tags */}
+ <Flexbox align="center" gap={8} horizontal wrap={'wrap'}>
+ {/* Second Row: Selected Plugins as Tags */}
+ {plugins?.map((pluginId) => {
+ return (
+ <PluginTag key={pluginId} onRemove={handleRemovePlugin(pluginId)} pluginId={pluginId} />
+ );
+ })}
+ {/* Plugin Selector Dropdown - Using Action component pattern */}
+
+ <Suspense fallback={button}>
+ <ActionDropdown
+ maxHeight={500}
+ maxWidth={480}
+ menu={{ items: menuItems }}
+ minHeight={isKlavisEnabledInEnv ? 500 : undefined}
+ minWidth={320}
+ placement={'bottomLeft'}
+ trigger={['click']}
+ >
+ {button}
+ </ActionDropdown>
+ </Suspense>
+ </Flexbox>
+
+ {/* PluginStore Modal */}
+ <PluginStore open={modalOpen} setOpen={setModalOpen} />
+ </>
+ );
+});
+
+export default AgentTool;
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/MentionDropdown.tsx b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/MentionDropdown.tsx
new file mode 100644
index 00000000000..0db220fd68d
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/MentionDropdown.tsx
@@ -0,0 +1,122 @@
+import { MenuRenderProps } from '@lobehub/editor/es/plugins/slash/react/type';
+import { useTheme } from 'antd-style';
+import { ReactNode, memo, useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { MentionListOption } from './types';
+
+/**
+ * Get cursor position from browser selection API
+ */
+const getCursorPosition = (): { x: number; y: number } | null => {
+ const selection = window.getSelection();
+ if (!selection || selection.rangeCount === 0) return null;
+
+ const range = selection.getRangeAt(0);
+ const rect = range.getBoundingClientRect();
+
+ return {
+ x: rect.left,
+ y: rect.bottom,
+ };
+};
+
+const MentionDropdown = memo<MenuRenderProps>(
+ ({ activeKey, onSelect, open, options, setActiveKey }) => {
+ const theme = useTheme();
+ const activeItemRef = useRef<HTMLDivElement>(null);
+ const [position, setPosition] = useState<{ x: number; y: number } | null>(null);
+
+ // Capture cursor position when menu opens
+ useLayoutEffect(() => {
+ if (open) {
+ const pos = getCursorPosition();
+ if (pos) {
+ setPosition(pos);
+ }
+ }
+ }, [open]);
+
+ useEffect(() => {
+ if (activeItemRef.current) {
+ activeItemRef.current.scrollIntoView({
+ behavior: 'smooth',
+ block: 'nearest',
+ });
+ }
+ }, [activeKey]);
+
+ if (!open || !options.length || !position) return null;
+
+ return (
+ <Flexbox
+ style={{
+ background: theme.colorBgElevated,
+ border: `1px solid ${theme.colorBorderSecondary}`,
+ borderRadius: 12,
+ boxShadow: theme.boxShadowSecondary,
+ left: position.x,
+ maxHeight: 260,
+ maxWidth: 400,
+ minWidth: 150,
+ overflow: 'hidden auto',
+ position: 'fixed',
+ top: position.y,
+ zIndex: 9999,
+ }}
+ >
+ {options.map((option) => {
+ if ((option as any)?.type === 'divider') {
+ return (
+ <div
+ key={`divider-${(option as any)?.key ?? 'divider'}`}
+ style={{ borderTop: `1px solid ${theme.colorBorderSecondary}` }}
+ />
+ );
+ }
+
+ const item = option as MentionListOption;
+ const isActive = activeKey === item.key;
+
+ return (
+ <Flexbox
+ align="center"
+ direction="horizontal"
+ gap={8}
+ key={String(item.key)}
+ onMouseDown={(e) => {
+ e.preventDefault();
+ onSelect?.(item);
+ }}
+ onMouseEnter={() => setActiveKey?.(String(item.key))}
+ paddingBlock={8}
+ paddingInline={12}
+ ref={isActive ? activeItemRef : null}
+ style={{
+ background: isActive ? theme.colorFillSecondary : undefined,
+ cursor: 'pointer',
+ }}
+ >
+ {item.icon && <Flexbox style={{ flex: 'none' }}>{item?.icon as ReactNode}</Flexbox>}
+ <div
+ style={{
+ color: theme.colorText,
+ fontSize: 14,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ }}
+ >
+ {item.label}
+ </div>
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ );
+ },
+);
+
+MentionDropdown.displayName = 'MentionDropdown';
+
+export default MentionDropdown;
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/index.tsx b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/index.tsx
new file mode 100644
index 00000000000..2749d93ebb1
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/index.tsx
@@ -0,0 +1 @@
+export { default as useMentionOptions } from './useMentionItems';
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/types.ts b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/types.ts
new file mode 100644
index 00000000000..9fff5c2a430
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/types.ts
@@ -0,0 +1,20 @@
+import type { API } from '@lobechat/prompts';
+import type { DropdownMenuItemType } from '@lobehub/ui';
+
+export type MentionEntityType = 'collection' | 'api';
+
+export interface MentionMetadata {
+ apis?: API[];
+ description?: string;
+ identifier: string;
+ instructions?: string;
+ label?: string;
+ pluginIdentifier?: string;
+ pluginType?: string;
+ type?: MentionEntityType;
+}
+
+export type MentionListOption = DropdownMenuItemType & {
+ description?: string;
+ metadata?: MentionMetadata;
+};
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/useMentionItems.tsx b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/useMentionItems.tsx
new file mode 100644
index 00000000000..425b40d6c56
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/useMentionItems.tsx
@@ -0,0 +1,229 @@
+import { KLAVIS_SERVER_TYPES, KlavisServerType } from '@lobechat/const';
+import { ToolNameResolver } from '@lobechat/context-engine';
+import { type API, apiPrompt, toolPrompt } from '@lobechat/prompts';
+import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';
+import { IEditor, INSERT_MENTION_COMMAND } from '@lobehub/editor';
+import { Icon, Image } from '@lobehub/ui';
+import { useTheme } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { memo, useCallback, useMemo } from 'react';
+
+import PluginAvatar from '@/components/Plugins/PluginAvatar';
+import { useAgentStore } from '@/store/agent';
+import { pluginHelpers, useToolStore } from '@/store/tool';
+import { toolSelectors } from '@/store/tool/selectors';
+import { globalAgentContextManager } from '@/utils/client/GlobalAgentContextManager';
+import { hydrationPrompt } from '@/utils/promptTemplate';
+
+import MentionDropdown from './MentionDropdown';
+import { MentionListOption, MentionMetadata } from './types';
+
+// 根据 identifier 获取 Klavis 服务器类型配置
+const getKlavisServerType = (identifier: string) =>
+ KLAVIS_SERVER_TYPES.find((type) => type.identifier === identifier);
+
+/**
+ * Klavis 服务器图标组件
+ * 对于 string 类型的 icon,使用 Image 组件渲染
+ * 对于 IconType 类型的 icon,使用 Icon 组件渲染,并根据主题设置填充色
+ */
+const KlavisIcon = memo<Pick<KlavisServerType, 'icon' | 'label'>>(({ icon, label }) => {
+ const theme = useTheme();
+
+ if (typeof icon === 'string') {
+ return <Image alt={label} height={20} src={icon} style={{ flex: 'none' }} width={20} />;
+ }
+
+ // 使用主题色填充,在深色模式下自动适应
+ return <Icon fill={theme.colorText} icon={icon} size={20} />;
+});
+
+const toolNameResolver = new ToolNameResolver();
+
+const buildApiList = (identifier: string, manifest?: LobeChatPluginManifest): API[] => {
+ if (!manifest?.api) return [];
+
+ return manifest.api.map((api) => ({
+ desc: api.description || '',
+ name: toolNameResolver.generate(identifier, api.name, manifest.type),
+ }));
+};
+
+const hydrateSystemRole = (systemRole?: string) => {
+ if (!systemRole) return '';
+
+ return hydrationPrompt(systemRole, globalAgentContextManager.getContext());
+};
+
+const resolveInstructions = (
+ metadata: MentionMetadata,
+ manifest?: LobeChatPluginManifest,
+ fallbackDesc?: string,
+) => {
+ if (metadata.instructions) return metadata.instructions;
+
+ if (manifest?.systemRole) return hydrateSystemRole(manifest.systemRole);
+
+ return metadata.description || fallbackDesc || pluginHelpers.getPluginDesc(manifest?.meta) || '';
+};
+
+const resolveApiName = (
+ metadata: MentionMetadata,
+ manifest: LobeChatPluginManifest | undefined,
+ pluginId?: string,
+ fallbackLabel?: string,
+) => {
+ if (metadata.identifier) return metadata.identifier;
+
+ const sourceId = pluginId || manifest?.identifier || '';
+
+ if (metadata.label) {
+ return toolNameResolver.generate(sourceId, metadata.label, manifest?.type);
+ }
+
+ const firstApi = manifest?.api?.[0]?.name;
+
+ if (firstApi) {
+ return toolNameResolver.generate(sourceId, firstApi, manifest?.type);
+ }
+
+ return fallbackLabel;
+};
+
+const resolveApiDescription = (
+ metadata: MentionMetadata,
+ manifest: LobeChatPluginManifest | undefined,
+ pluginId: string | undefined,
+ apiName?: string,
+) => {
+ if (metadata.description) return metadata.description;
+
+ if (!manifest?.api?.length || !apiName) return '';
+
+ const sourceId = pluginId || manifest.identifier;
+ const matched = manifest.api.find((api) => {
+ const fullName = toolNameResolver.generate(sourceId, api.name, manifest.type);
+
+ return fullName === apiName || api.name === apiName;
+ });
+
+ return matched?.description || '';
+};
+
+const useMentionOptions = () => {
+ const installedTools = useToolStore(toolSelectors.metaList, isEqual);
+ const toggleAgentPlugin = useAgentStore((s) => s.toggleAgentPlugin);
+
+ const baseItems = useMemo<MentionListOption[]>(() => {
+ const state = useToolStore.getState();
+
+ return installedTools.map((tool) => {
+ const manifest = toolSelectors.getManifestById(tool.identifier)(state);
+ const label = pluginHelpers.getPluginTitle(tool.meta) || tool.identifier;
+ const description = pluginHelpers.getPluginDesc(tool.meta);
+ const apis = buildApiList(manifest?.identifier || tool.identifier, manifest);
+
+ const createMetadata = (): MentionMetadata => ({
+ apis: apis.map((api) => ({ ...api })),
+ description,
+ identifier: tool.identifier,
+ label,
+ pluginType: manifest?.type,
+ type: 'collection',
+ });
+
+ // 优先使用 Klavis 图标,否则使用 PluginAvatar
+ const klavisServerType = getKlavisServerType(tool.identifier);
+ const icon = klavisServerType ? (
+ <KlavisIcon icon={klavisServerType.icon} label={klavisServerType.label} />
+ ) : (
+ <PluginAvatar alt={label} avatar={pluginHelpers.getPluginAvatar(tool.meta)} size={20} />
+ );
+
+ return {
+ description,
+ icon,
+ key: tool.identifier,
+ label,
+ metadata: createMetadata(),
+ onSelect: (editor: IEditor) => {
+ toggleAgentPlugin(tool.identifier, true);
+ editor.dispatchCommand(INSERT_MENTION_COMMAND, {
+ label,
+ metadata: createMetadata() as unknown as Record<string, unknown>,
+ });
+ },
+ };
+ });
+ }, [installedTools, toggleAgentPlugin]);
+
+ const loadItems = useCallback(
+ async (
+ search: { leadOffset: number; matchingString: string; replaceableString: string } | null,
+ ) => {
+ const query = search?.matchingString?.toLowerCase() || '';
+
+ if (!query) return baseItems;
+
+ return baseItems.filter((item) => {
+ const label = typeof item.label === 'string' ? item.label.toLowerCase() : '';
+ const desc = item.description?.toLowerCase() || '';
+ const key = typeof item.key === 'string' ? item.key.toLowerCase() : '';
+
+ return label.includes(query) || desc.includes(query) || key.includes(query);
+ });
+ },
+ [baseItems],
+ );
+
+ const mentionMarkdownWriter = useCallback((mention: any) => {
+ const metadata = (mention?.metadata || {}) as MentionMetadata;
+ const pluginId = metadata.pluginIdentifier || metadata.identifier;
+ const state = useToolStore.getState();
+ const manifest = pluginId ? toolSelectors.getManifestById(pluginId)(state) : undefined;
+
+ if (metadata.type === 'api') {
+ const apiName = resolveApiName(metadata, manifest, pluginId, mention?.label);
+ const apiDescription = resolveApiDescription(metadata, manifest, pluginId, apiName);
+
+ if (!apiName) return mention?.getTextContent?.() || '';
+
+ return `\n${apiPrompt({ desc: apiDescription, name: apiName })}\n`;
+ }
+
+ const apis =
+ metadata.apis?.length && metadata.apis.length > 0
+ ? metadata.apis
+ : buildApiList(pluginId || manifest?.identifier || '', manifest);
+
+ const name =
+ metadata.label ||
+ pluginHelpers.getPluginTitle(manifest?.meta) ||
+ pluginId ||
+ mention?.label ||
+ '';
+
+ const instructions = resolveInstructions(metadata, manifest, metadata.description);
+
+ const prompt = toolPrompt({
+ apis: apis || [],
+ identifier: pluginId || '',
+ name,
+ systemRole: instructions,
+ });
+
+ return `\n${prompt}\n`;
+ }, []);
+
+ return useMemo(
+ () => ({
+ fuseOptions: { keys: ['key', 'label', 'description'], threshold: 0.4 },
+ items: loadItems,
+ markdownWriter: mentionMarkdownWriter,
+ renderComp: MentionDropdown,
+ }),
+ [loadItems, mentionMarkdownWriter],
+ );
+};
+
+export default useMentionOptions;
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/PluginTag.tsx b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/PluginTag.tsx
new file mode 100644
index 00000000000..b3bae8b3731
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/PluginTag.tsx
@@ -0,0 +1,181 @@
+'use client';
+
+import { KLAVIS_SERVER_TYPES, KlavisServerType } from '@lobechat/const';
+import { Avatar, Icon, Tag } from '@lobehub/ui';
+import { createStyles, useTheme } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { AlertCircle, X } from 'lucide-react';
+import Image from 'next/image';
+import React, { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import PluginAvatar from '@/components/Plugins/PluginAvatar';
+import { useDiscoverStore } from '@/store/discover';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+import { useToolStore } from '@/store/tool';
+import {
+ builtinToolSelectors,
+ klavisStoreSelectors,
+ pluginSelectors,
+} from '@/store/tool/selectors';
+
+/**
+ * Klavis 服务器图标组件
+ */
+const KlavisIcon = memo<Pick<KlavisServerType, 'icon' | 'label'>>(({ icon, label }) => {
+ const theme = useTheme();
+
+ if (typeof icon === 'string') {
+ return (
+ <Image alt={label} height={16} src={icon} style={{ flexShrink: 0 }} unoptimized width={16} />
+ );
+ }
+
+ return <Icon fill={theme.colorText} icon={icon} size={16} />;
+});
+
+const useStyles = createStyles(({ css, token }) => ({
+ notInstalledTag: css`
+ border-color: ${token.colorWarningBorder};
+ background: ${token.colorWarningBg};
+ `,
+ tag: css`
+ height: 28px !important;
+ border-radius: ${token.borderRadiusSM}px !important;
+ `,
+ warningIcon: css`
+ flex-shrink: 0;
+ color: ${token.colorWarning};
+ `,
+}));
+
+interface PluginTagProps {
+ onRemove: (e: React.MouseEvent) => void;
+ pluginId: string | { enabled: boolean; identifier: string; settings: Record<string, any> };
+}
+
+const PluginTag = memo<PluginTagProps>(({ pluginId, onRemove }) => {
+ const { styles, theme } = useStyles();
+ const { t } = useTranslation('setting');
+
+ // Extract identifier
+ const identifier = typeof pluginId === 'string' ? pluginId : pluginId?.identifier;
+
+ // Get local plugin lists
+ const builtinList = useToolStore(builtinToolSelectors.metaList, isEqual);
+ const installedPluginList = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);
+
+ // Klavis 相关状态
+ const allKlavisServers = useToolStore(klavisStoreSelectors.getServers, isEqual);
+ const isKlavisEnabledInEnv = useServerConfigStore(serverConfigSelectors.enableKlavis);
+
+ // Check if plugin is installed
+ const isInstalled = useToolStore(pluginSelectors.isPluginInstalled(identifier));
+
+ // Try to find in local lists first (including Klavis)
+ const localMeta = useMemo(() => {
+ // Check if it's a Klavis server type
+ if (isKlavisEnabledInEnv) {
+ const klavisType = KLAVIS_SERVER_TYPES.find((type) => type.identifier === identifier);
+ if (klavisType) {
+ // Check if this Klavis server is connected
+ const connectedServer = allKlavisServers.find((s) => s.identifier === identifier);
+ return {
+ icon: klavisType.icon,
+ isInstalled: !!connectedServer,
+ label: klavisType.label,
+ title: klavisType.label,
+ type: 'klavis' as const,
+ };
+ }
+ }
+
+ const builtinMeta = builtinList.find((p) => p.identifier === identifier);
+ if (builtinMeta) {
+ return {
+ avatar: builtinMeta.meta.avatar,
+ isInstalled: true,
+ title: builtinMeta.meta.title,
+ type: 'builtin' as const,
+ };
+ }
+
+ const installedMeta = installedPluginList.find((p) => p.identifier === identifier);
+ if (installedMeta) {
+ return {
+ avatar: installedMeta.avatar,
+ isInstalled: true,
+ title: installedMeta.title,
+ type: 'plugin' as const,
+ };
+ }
+
+ return null;
+ }, [identifier, builtinList, installedPluginList, isKlavisEnabledInEnv, allKlavisServers]);
+
+ // Fetch from remote if not found locally
+ const usePluginDetail = useDiscoverStore((s) => s.usePluginDetail);
+ const { data: remoteData, isLoading } = usePluginDetail({
+ identifier: !localMeta && !isInstalled ? identifier : undefined,
+ withManifest: false,
+ });
+
+ // Determine final metadata
+ const meta = localMeta || {
+ avatar: remoteData?.avatar,
+ isInstalled: false,
+ title: remoteData?.title || identifier,
+ type: 'plugin' as const,
+ };
+
+ const displayTitle = isLoading ? 'Loading...' : meta.title;
+
+ // Render icon based on type
+ const renderIcon = () => {
+ if (!meta.isInstalled) {
+ return <AlertCircle className={styles.warningIcon} size={14} />;
+ }
+
+ // Klavis type has icon property
+ if (meta.type === 'klavis' && 'icon' in meta && 'label' in meta) {
+ return <KlavisIcon icon={meta.icon} label={meta.label} />;
+ }
+
+ // Builtin type has avatar
+ if (meta.type === 'builtin' && 'avatar' in meta && meta.avatar) {
+ return <Avatar avatar={meta.avatar} shape={'square'} size={16} style={{ flexShrink: 0 }} />;
+ }
+
+ // Plugin type
+ if ('avatar' in meta) {
+ return <PluginAvatar avatar={meta.avatar} size={16} />;
+ }
+
+ return null;
+ };
+
+ return (
+ <Tag
+ className={styles.tag}
+ closable
+ closeIcon={<X size={12} />}
+ color={meta.isInstalled ? undefined : 'error'}
+ icon={renderIcon()}
+ onClose={onRemove}
+ title={
+ meta.isInstalled
+ ? undefined
+ : t('tools.notInstalledWarning', { defaultValue: 'This tool is not installed' })
+ }
+ variant={theme.isDarkMode ? 'filled' : 'outlined'}
+ >
+ {!meta.isInstalled
+ ? `${displayTitle} (${t('tools.notInstalled', { defaultValue: 'Not Installed' })})`
+ : displayTitle}
+ </Tag>
+ );
+});
+
+PluginTag.displayName = 'PluginTag';
+
+export default PluginTag;
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/index.tsx b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/index.tsx
new file mode 100644
index 00000000000..ecd8147853c
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/index.tsx
@@ -0,0 +1,84 @@
+'use client';
+
+import { Button } from '@lobehub/ui';
+import { Divider } from 'antd';
+import isEqual from 'fast-deep-equal';
+import { PlayIcon } from 'lucide-react';
+import React, { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+import urlJoin from 'url-join';
+
+import ModelSelect from '@/features/ModelSelect';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+import EditorCanvas from '../EditorCanvas';
+import AgentHeader from './AgentHeader';
+import AgentTool from './AgentTool';
+
+const ProfileEditor = memo(() => {
+ const { t } = useTranslation('setting');
+ const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);
+ const updateConfig = useAgentStore((s) => s.updateAgentConfig);
+ const groupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
+ const router = useQueryRoute();
+
+ return (
+ <>
+ <Flexbox
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ }}
+ style={{ cursor: 'default', marginBottom: 12 }}
+ >
+ {/* Header: Avatar + Name + Description */}
+ <AgentHeader />
+ {/* Config Bar: Model Selector */}
+ <Flexbox
+ align={'center'}
+ gap={8}
+ horizontal
+ justify={'flex-start'}
+ style={{ marginBottom: 12 }}
+ >
+ <ModelSelect
+ onChange={updateConfig}
+ value={{
+ model: config.model,
+ provider: config.provider,
+ }}
+ />
+ </Flexbox>
+ <AgentTool />
+ <Flexbox
+ align={'center'}
+ gap={8}
+ horizontal
+ justify={'flex-start'}
+ style={{ marginTop: 16 }}
+ >
+ <Button
+ icon={PlayIcon}
+ onClick={() => {
+ if (!groupId) return;
+ router.push(urlJoin('/group', groupId));
+ }}
+ type={'primary'}
+ >
+ {t('startConversation')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ <Divider />
+ {/* Main Content: Prompt Editor */}
+ <EditorCanvas />
+ </>
+ );
+});
+
+export default ProfileEditor;
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/promptTemplate.json b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/promptTemplate.json
new file mode 100644
index 00000000000..36e841189f1
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/promptTemplate.json
@@ -0,0 +1,277 @@
+{
+ "root": {
+ "children": [
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Goal",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": null,
+ "format": "",
+ "indent": 0,
+ "type": "heading",
+ "version": 1,
+ "tag": "h4"
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Describe the main purpose and objective of this agent.",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "paragraph",
+ "version": 1,
+ "textFormat": 0,
+ "textStyle": ""
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Skills",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": null,
+ "format": "",
+ "indent": 0,
+ "type": "heading",
+ "version": 1,
+ "tag": "h4"
+ },
+ {
+ "children": [
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "List the key capabilities",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "listitem",
+ "version": 1,
+ "value": 1
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "And specialized knowledge areas",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "listitem",
+ "version": 1,
+ "value": 2
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "list",
+ "version": 1,
+ "listType": "bullet",
+ "start": 1,
+ "tag": "ul"
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Workflow",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": null,
+ "format": "",
+ "indent": 0,
+ "type": "heading",
+ "version": 1,
+ "tag": "h4"
+ },
+ {
+ "children": [
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Step-by-step process",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "listitem",
+ "version": 1,
+ "value": 1
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "How the agent should approach tasks",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "listitem",
+ "version": 1,
+ "value": 2
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Expected interactions with users",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "listitem",
+ "version": 1,
+ "value": 3
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "list",
+ "version": 1,
+ "listType": "number",
+ "start": 1,
+ "tag": "ol"
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Constraints",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": null,
+ "format": "",
+ "indent": 0,
+ "type": "heading",
+ "version": 1,
+ "tag": "h4"
+ },
+ {
+ "children": [
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Important limitations to follow",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "listitem",
+ "version": 1,
+ "value": 1
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Guidelines for behavior",
+ "type": "text",
+ "version": 1
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "listitem",
+ "version": 1,
+ "value": 2
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "list",
+ "version": 1,
+ "listType": "bullet",
+ "start": 1,
+ "tag": "ul"
+ }
+ ],
+ "direction": "ltr",
+ "format": "",
+ "indent": 0,
+ "type": "root",
+ "version": 1,
+ "textStyle": "--shiki-dark:var(--color-info);--shiki-light:var(--color-info)"
+ }
+}
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileHydration.tsx b/src/app/[variants]/(main)/group/profile/features/ProfileHydration.tsx
new file mode 100644
index 00000000000..4376bcd2fac
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/ProfileHydration.tsx
@@ -0,0 +1,16 @@
+import { memo } from 'react';
+
+import { useRegisterFilesHotkeys, useSaveDocumentHotkey } from '@/hooks/useHotkeys';
+
+import { useProfileStore } from './store';
+
+const ProfileHydration = memo(() => {
+ // Initialize agent builder builtin agent
+ const flushSave = useProfileStore((s) => s.flushSave);
+ useRegisterFilesHotkeys();
+ useSaveDocumentHotkey(flushSave);
+
+ return null;
+});
+
+export default ProfileHydration;
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileProvider.tsx b/src/app/[variants]/(main)/group/profile/features/ProfileProvider.tsx
new file mode 100644
index 00000000000..b25465bb0e5
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/ProfileProvider.tsx
@@ -0,0 +1,20 @@
+'use client';
+
+import { useEditor } from '@lobehub/editor/react';
+import { PropsWithChildren, memo } from 'react';
+
+import StoreUpdater from './StoreUpdater';
+import { Provider, createStore } from './store';
+
+const ProfileProvider = memo<PropsWithChildren>(({ children }) => {
+ const editor = useEditor();
+
+ return (
+ <Provider createStore={() => createStore({ editor })}>
+ <StoreUpdater />
+ {children}
+ </Provider>
+ );
+});
+
+export default ProfileProvider;
diff --git a/src/app/[variants]/(main)/group/profile/features/StoreUpdater.tsx b/src/app/[variants]/(main)/group/profile/features/StoreUpdater.tsx
new file mode 100644
index 00000000000..c9019f543be
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/StoreUpdater.tsx
@@ -0,0 +1,24 @@
+'use client';
+
+import { useEditorState } from '@lobehub/editor/react';
+import { memo, useEffect } from 'react';
+
+import { PublicState, useProfileStore, useStoreApi } from './store';
+
+export type StoreUpdaterProps = Partial<PublicState>;
+
+const StoreUpdater = memo<StoreUpdaterProps>(() => {
+ const storeApi = useStoreApi();
+
+ const editor = useProfileStore((s) => s.editor);
+ const editorState = useEditorState(editor);
+
+ // Update editorState in store
+ useEffect(() => {
+ storeApi.setState({ editorState });
+ }, [editorState, storeApi]);
+
+ return null;
+});
+
+export default StoreUpdater;
diff --git a/src/app/[variants]/(main)/group/profile/features/store/action.ts b/src/app/[variants]/(main)/group/profile/features/store/action.ts
new file mode 100644
index 00000000000..49180cc2cc8
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/store/action.ts
@@ -0,0 +1,163 @@
+import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@lobechat/const';
+import { debounce } from 'es-toolkit/compat';
+import { StateCreator } from 'zustand';
+
+import { State, initialState } from './initialState';
+
+type SaveConfigPayload = {
+ editorData: Record<string, any>;
+ systemRole: string;
+};
+
+export interface Action {
+ /**
+ * Append content to streaming buffer (called during streaming)
+ */
+ appendStreamingContent: (chunk: string) => void;
+ /**
+ * Finalize streaming and save to config
+ */
+ finishStreaming: (updateConfig: (payload: SaveConfigPayload) => Promise<void>) => Promise<void>;
+ flushSave: () => void;
+ handleContentChange: (updateConfig: (payload: SaveConfigPayload) => Promise<void>) => void;
+ setChatPanelExpanded: (expanded: boolean | ((prev: boolean) => boolean)) => void;
+ /**
+ * Start streaming mode - clears editor and prepares for streaming content
+ */
+ startStreaming: () => void;
+}
+
+export type Store = State & Action;
+
+// Create debounced save function outside of store for reuse
+const createDebouncedSave = (
+ get: () => Store,
+ updateConfig: (payload: SaveConfigPayload) => Promise<void>,
+) =>
+ debounce(
+ async (payload: SaveConfigPayload) => {
+ try {
+ await updateConfig(payload);
+ } catch (error) {
+ console.error('[ProfileEditor] Failed to save:', error);
+ }
+ },
+ EDITOR_DEBOUNCE_TIME,
+ { leading: false, maxWait: EDITOR_MAX_WAIT, trailing: true },
+ );
+
+export const store: (initState?: Partial<State>) => StateCreator<Store> =
+ (initState) => (set, get) => {
+ let debouncedSave: ReturnType<typeof createDebouncedSave> | null = null;
+
+ return {
+ ...initialState,
+ ...initState,
+
+ appendStreamingContent: (chunk) => {
+ const currentContent = get().streamingContent || '';
+ const newContent = currentContent + chunk;
+ set({ streamingContent: newContent });
+
+ // Update editor with streaming content
+ const { editor } = get();
+ if (editor) {
+ try {
+ editor.setDocument('markdown', newContent);
+ } catch {
+ // Ignore errors during streaming updates
+ }
+ }
+ },
+
+ finishStreaming: async (updateConfig) => {
+ const { editor, streamingContent } = get();
+ if (!streamingContent) {
+ set({ streamingInProgress: false });
+ return;
+ }
+
+ // Get the final content from editor
+ let finalContent = streamingContent;
+ let editorData = {};
+
+ if (editor) {
+ try {
+ finalContent =
+ (editor.getDocument('markdown') as unknown as string) || streamingContent;
+ editorData = editor.getDocument('json') as unknown as Record<string, any>;
+ } catch {
+ // Use streaming content if editor read fails
+ }
+ }
+
+ // Save to config
+ try {
+ await updateConfig({
+ editorData: structuredClone(editorData || {}),
+ systemRole: finalContent,
+ });
+ } catch (error) {
+ console.error('[ProfileEditor] Failed to save streaming content:', error);
+ }
+
+ // Reset streaming state
+ set({
+ streamingContent: undefined,
+ streamingInProgress: false,
+ });
+ },
+
+ flushSave: () => {
+ debouncedSave?.flush();
+ },
+
+ handleContentChange: (updateConfig) => {
+ const { editor } = get();
+ if (!editor) return;
+
+ // Create debounced save on first use
+ if (!debouncedSave) {
+ debouncedSave = createDebouncedSave(get, updateConfig);
+ }
+
+ try {
+ const markdownContent = (editor.getDocument('markdown') as unknown as string) || '';
+ const jsonContent = editor.getDocument('json') as unknown as Record<string, any>;
+
+ debouncedSave({
+ editorData: structuredClone(jsonContent || {}),
+ systemRole: markdownContent || '',
+ });
+ } catch (error) {
+ console.error('[ProfileEditor] Failed to read editor content:', error);
+ }
+ },
+
+ setChatPanelExpanded: (expanded) => {
+ if (typeof expanded === 'function') {
+ set((state) => ({ chatPanelExpanded: expanded(state.chatPanelExpanded) }));
+ } else {
+ set({ chatPanelExpanded: expanded });
+ }
+ },
+
+ startStreaming: () => {
+ const { editor } = get();
+
+ // Clear editor content and prepare for streaming
+ if (editor) {
+ try {
+ editor.setDocument('markdown', '');
+ } catch {
+ // Ignore errors
+ }
+ }
+
+ set({
+ streamingContent: '',
+ streamingInProgress: true,
+ });
+ },
+ };
+ };
diff --git a/src/app/[variants]/(main)/group/profile/features/store/index.ts b/src/app/[variants]/(main)/group/profile/features/store/index.ts
new file mode 100644
index 00000000000..de5b6ed3513
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/store/index.ts
@@ -0,0 +1,23 @@
+'use client';
+
+import { StoreApiWithSelector } from '@lobechat/types';
+import { createContext } from 'zustand-utils';
+import { subscribeWithSelector } from 'zustand/middleware';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import { Store, store } from './action';
+import { State } from './initialState';
+
+export type { PublicState, State } from './initialState';
+
+export const createStore = (initState?: Partial<State>) =>
+ createWithEqualityFn(subscribeWithSelector(store(initState)), shallow);
+
+export const {
+ useStore: useProfileStore,
+ useStoreApi,
+ Provider,
+} = createContext<StoreApiWithSelector<Store>>();
+
+export { selectors } from './selectors';
diff --git a/src/app/[variants]/(main)/group/profile/features/store/initialState.ts b/src/app/[variants]/(main)/group/profile/features/store/initialState.ts
new file mode 100644
index 00000000000..ab6a56af08a
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/store/initialState.ts
@@ -0,0 +1,24 @@
+import { IEditor } from '@lobehub/editor';
+
+// eslint-disable-next-line @typescript-eslint/no-empty-interface
+export interface PublicState {}
+
+export interface State extends PublicState {
+ chatPanelExpanded: boolean;
+ editor?: IEditor;
+ editorState?: any; // EditorState from useEditorState hook
+ /**
+ * Content being streamed from AI
+ */
+ streamingContent?: string;
+ /**
+ * Whether streaming is in progress
+ */
+ streamingInProgress?: boolean;
+}
+
+export const initialState: State = {
+ chatPanelExpanded: true,
+ streamingContent: undefined,
+ streamingInProgress: false,
+};
diff --git a/src/app/[variants]/(main)/group/profile/features/store/selectors.ts b/src/app/[variants]/(main)/group/profile/features/store/selectors.ts
new file mode 100644
index 00000000000..23ce47726c7
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/store/selectors.ts
@@ -0,0 +1,7 @@
+import { Store } from './action';
+
+export const selectors = {
+ chatPanelExpanded: (s: Store) => s.chatPanelExpanded,
+ editor: (s: Store) => s.editor,
+ editorState: (s: Store) => s.editorState,
+};
diff --git a/src/app/[variants]/(main)/group/profile/index.tsx b/src/app/[variants]/(main)/group/profile/index.tsx
new file mode 100644
index 00000000000..40d29f42593
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/index.tsx
@@ -0,0 +1,66 @@
+'use client';
+
+import { Suspense, memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+import AgentBuilder from './features/AgentBuilder';
+import Header from './features/Header';
+import ProfileEditor from './features/ProfileEditor';
+import ProfileHydration from './features/ProfileHydration';
+import ProfileProvider from './features/ProfileProvider';
+import { useProfileStore } from './features/store';
+
+const ProfileArea = memo(() => {
+ const editor = useProfileStore((s) => s.editor);
+ const isGroupsLoading = useAgentGroupStore(agentGroupSelectors.isGroupsInit);
+
+ return (
+ <>
+ <Flexbox flex={1} height={'100%'}>
+ {isGroupsLoading ? (
+ <Loading debugId="ProfileArea" />
+ ) : (
+ <>
+ <Header />
+ <Flexbox
+ height={'100%'}
+ horizontal
+ onClick={() => {
+ editor?.focus();
+ }}
+ style={{ cursor: 'text', display: 'flex', overflowY: 'auto', position: 'relative' }}
+ width={'100%'}
+ >
+ <WideScreenContainer>
+ <ProfileEditor />
+ </WideScreenContainer>
+ </Flexbox>
+ </>
+ )}
+ </Flexbox>
+ <Suspense fallback={null}>
+ <ProfileHydration />
+ </Suspense>
+ </>
+ );
+});
+
+const GroupProfile = memo(() => {
+ return (
+ <Suspense fallback={<Loading debugId="GroupProfile" />}>
+ <ProfileProvider>
+ <Flexbox height={'100%'} horizontal width={'100%'}>
+ <ProfileArea />
+ <AgentBuilder />
+ </Flexbox>
+ </ProfileProvider>
+ </Suspense>
+ );
+});
+
+export default GroupProfile;
diff --git a/src/server/globalConfig/parseDefaultAgent.ts b/src/server/globalConfig/parseDefaultAgent.ts
index af8124f4875..63af163d7d3 100644
--- a/src/server/globalConfig/parseDefaultAgent.ts
+++ b/src/server/globalConfig/parseDefaultAgent.ts
@@ -1,4 +1,4 @@
-import { set } from 'lodash-es';
+import { set } from 'es-toolkit/compat';
/**
* Improved parsing function that handles numbers, booleans, semicolons, and equals signs in values.
diff --git a/src/server/routers/async/file.ts b/src/server/routers/async/file.ts
index 88ea37110e4..4ada862bd80 100644
--- a/src/server/routers/async/file.ts
+++ b/src/server/routers/async/file.ts
@@ -1,5 +1,5 @@
import { TRPCError } from '@trpc/server';
-import { chunk } from 'lodash-es';
+import { chunk } from 'es-toolkit/compat';
import pMap from 'p-map';
import { z } from 'zod';
diff --git a/src/server/routers/lambda/config/index.ts b/src/server/routers/lambda/config/index.ts
index cb68cf83e4c..8b73a13b68b 100644
--- a/src/server/routers/lambda/config/index.ts
+++ b/src/server/routers/lambda/config/index.ts
@@ -15,12 +15,12 @@ export const configRouter = router({
getGlobalConfig: publicProcedure.query(async ({ ctx }): Promise<GlobalRuntimeConfig> => {
log('[GlobalConfig] Starting global config retrieval for user:', ctx.userId || 'anonymous');
- const serverConfig = await getServerGlobalConfig();
- log('[GlobalConfig] Server config retrieved');
+ const [serverConfig, serverFeatureFlags] = await Promise.all([
+ getServerGlobalConfig(),
+ getServerFeatureFlagsStateFromEdgeConfig(ctx.userId || undefined),
+ ]);
- const serverFeatureFlags = await getServerFeatureFlagsStateFromEdgeConfig(
- ctx.userId || undefined,
- );
+ log('[GlobalConfig] Server config retrieved');
log(
'[GlobalConfig] Final feature flags to return (evaluated booleans only):',
serverFeatureFlags,
diff --git a/src/server/routers/lambda/upload.ts b/src/server/routers/lambda/upload.ts
index aa1731f397c..dcb644c7a99 100644
--- a/src/server/routers/lambda/upload.ts
+++ b/src/server/routers/lambda/upload.ts
@@ -1,13 +1,13 @@
import { z } from 'zod';
import { authedProcedure, router } from '@/libs/trpc/lambda';
-import { S3 } from '@/server/modules/S3';
+import { FileS3 } from '@/server/modules/S3';
export const uploadRouter = router({
createS3PreSignedUrl: authedProcedure
.input(z.object({ pathname: z.string() }))
.mutation(async ({ input }) => {
- const s3 = new S3();
+ const s3 = new FileS3();
return await s3.createPreSignedUrl(input.pathname);
}),
diff --git a/src/server/routers/lambda/user.ts b/src/server/routers/lambda/user.ts
index ac01e8ed5ba..79462ca792a 100644
--- a/src/server/routers/lambda/user.ts
+++ b/src/server/routers/lambda/user.ts
@@ -4,6 +4,7 @@ import {
NextAuthAccountSchame,
UserGuideSchema,
UserInitializationState,
+ UserOnboardingSchema,
UserPreference,
UserPreferenceSchema,
UserSettings,
@@ -22,7 +23,7 @@ import { pino } from '@/libs/logger';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
-import { S3 } from '@/server/modules/S3';
+import { FileS3 } from '@/server/modules/S3';
import { FileService } from '@/server/services/file';
import { NextAuthUserService } from '@/server/services/nextAuthUser';
import { UserService } from '@/server/services/user';
@@ -68,78 +69,89 @@ export const userRouter = router({
// `after` may fail outside request scope (e.g., in tests), ignore silently
}
- let state: Awaited<ReturnType<UserModel['getUserState']>> | undefined;
+ // Helper function to get or create user state
+ const getOrCreateUserState = async () => {
+ let state: Awaited<ReturnType<UserModel['getUserState']>> | undefined;
- // get or create first-time user
- while (!state) {
- try {
- state = await ctx.userModel.getUserState(KeyVaultsGateKeeper.getUserKeyVaults);
- } catch (error) {
- // user not create yet
- if (error instanceof UserNotFoundError) {
- // if in clerk auth mode
- if (enableClerk) {
- const user = await ctx.clerkAuth.getCurrentUser();
- if (user) {
- const userService = new UserService(ctx.serverDB);
-
- await userService.createUser(user.id, {
- created_at: user.createdAt,
- email_addresses: user.emailAddresses.map((e) => ({
- email_address: e.emailAddress,
- id: e.id,
- })),
- first_name: user.firstName,
- id: user.id,
- image_url: user.imageUrl,
- last_name: user.lastName,
- phone_numbers: user.phoneNumbers.map((e) => ({
- id: e.id,
- phone_number: e.phoneNumber,
- })),
- primary_email_address_id: user.primaryEmailAddressId,
- primary_phone_number_id: user.primaryPhoneNumberId,
- username: user.username,
- } as UserJSON);
+ // get or create first-time user
+ while (!state) {
+ try {
+ state = await ctx.userModel.getUserState(KeyVaultsGateKeeper.getUserKeyVaults);
+ } catch (error) {
+ // user not create yet
+ if (error instanceof UserNotFoundError) {
+ // if in clerk auth mode
+ if (enableClerk) {
+ const user = await ctx.clerkAuth.getCurrentUser();
+ if (user) {
+ const userService = new UserService(ctx.serverDB);
+
+ await userService.createUser(user.id, {
+ created_at: user.createdAt,
+ email_addresses: user.emailAddresses.map((e) => ({
+ email_address: e.emailAddress,
+ id: e.id,
+ })),
+ first_name: user.firstName,
+ id: user.id,
+ image_url: user.imageUrl,
+ last_name: user.lastName,
+ phone_numbers: user.phoneNumbers.map((e) => ({
+ id: e.id,
+ phone_number: e.phoneNumber,
+ })),
+ primary_email_address_id: user.primaryEmailAddressId,
+ primary_phone_number_id: user.primaryPhoneNumberId,
+ username: user.username,
+ } as UserJSON);
+
+ continue;
+ }
+ }
+ // if in desktop mode, make sure desktop user exist
+ else if (isDesktop) {
+ await UserModel.makeSureUserExist(ctx.serverDB, ctx.userId);
+ pino.info('create desktop user');
continue;
}
}
- // if in desktop mode, make sure desktop user exist
- else if (isDesktop) {
- await UserModel.makeSureUserExist(ctx.serverDB, ctx.userId);
- pino.info('create desktop user');
- continue;
- }
+ console.error('getUserState:', error);
+ throw error;
}
-
- console.error('getUserState:', error);
- throw error;
}
- }
- // Run all count queries in parallel
- const [hasMoreThan4Messages, hasAnyMessages, hasExtraSession] = await Promise.all([
- ctx.messageModel.hasMoreThanN(4),
- ctx.messageModel.hasMoreThanN(0),
+ return state;
+ };
+
+ // Run user state fetch and count queries in parallel
+ const [state, messageCount, hasExtraSession] = await Promise.all([
+ getOrCreateUserState(),
+ ctx.messageModel.countUpTo(5),
ctx.sessionModel.hasMoreThanN(1),
]);
+ const hasMoreThan4Messages = messageCount > 4;
+ const hasAnyMessages = messageCount > 0;
+
return {
avatar: state.avatar,
canEnablePWAGuide: hasMoreThan4Messages,
canEnableTrace: hasMoreThan4Messages,
email: state.email,
firstName: state.firstName,
-
fullName: state.fullName,
// 有消息,或者创建过助手,则认为有 conversation
hasConversation: hasAnyMessages || hasExtraSession,
+
+ interests: state.interests,
+
// always return true for community version
- isOnboard: state.isOnboarded || true,
+ isOnboard: state.isOnboarded ?? true,
lastName: state.lastName,
+ onboarding: state.onboarding,
preference: state.preference as UserPreference,
settings: state.settings,
userId: ctx.userId,
@@ -163,7 +175,6 @@ export const userRouter = router({
await ctx.nextAuthUserService.unlinkAccount({ provider, providerAccountId });
}),
- // 服务端上传头像
updateAvatar: userProcedure.input(z.string()).mutation(async ({ ctx, input }) => {
// 如果是 Base64 数据,需要上传到 S3
if (input.startsWith('data:image')) {
@@ -183,7 +194,7 @@ export const userRouter = router({
const base64Data = input.slice(commaIndex + 1);
// 创建 S3 客户端
- const s3 = new S3();
+ const s3 = new FileS3();
// 使用 UUID 生成唯一文件名,防止缓存问题
// 获取旧头像 URL, 后面删除该头像
@@ -226,6 +237,14 @@ export const userRouter = router({
return ctx.userModel.updateGuide(input);
}),
+ updateInterests: userProcedure.input(z.array(z.string())).mutation(async ({ ctx, input }) => {
+ return ctx.userModel.updateUser({ interests: input });
+ }),
+
+ updateOnboarding: userProcedure.input(UserOnboardingSchema).mutation(async ({ ctx, input }) => {
+ return ctx.userModel.updateUser({ onboarding: input });
+ }),
+
updatePreference: userProcedure.input(UserPreferenceSchema).mutation(async ({ ctx, input }) => {
return ctx.userModel.updatePreference(input);
}),
diff --git a/src/server/routers/mobile/index.ts b/src/server/routers/mobile/index.ts
index 083736e6845..556fc569243 100644
--- a/src/server/routers/mobile/index.ts
+++ b/src/server/routers/mobile/index.ts
@@ -17,9 +17,9 @@ import { marketRouter } from '../lambda/market';
import { messageRouter } from '../lambda/message';
import { sessionRouter } from '../lambda/session';
import { sessionGroupRouter } from '../lambda/sessionGroup';
-import { topicRouter } from '../lambda/topic';
import { uploadRouter } from '../lambda/upload';
import { userRouter } from '../lambda/user';
+import { topicRouter } from './topic';
export const mobileRouter = router({
agent: agentRouter,
diff --git a/src/server/routers/mobile/topic.ts b/src/server/routers/mobile/topic.ts
new file mode 100644
index 00000000000..990de60d2a0
--- /dev/null
+++ b/src/server/routers/mobile/topic.ts
@@ -0,0 +1,166 @@
+import { z } from 'zod';
+
+import { TopicModel } from '@/database/models/topic';
+import { getServerDB } from '@/database/server';
+import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { BatchTaskResult } from '@/types/service';
+
+const topicProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+
+ return opts.next({
+ ctx: { topicModel: new TopicModel(ctx.serverDB, ctx.userId) },
+ });
+});
+
+export const topicRouter = router({
+ batchCreateTopics: topicProcedure
+ .input(
+ z.array(
+ z.object({
+ favorite: z.boolean().optional(),
+ id: z.string().optional(),
+ messages: z.array(z.string()).optional(),
+ sessionId: z.string().optional(),
+ title: z.string(),
+ }),
+ ),
+ )
+ .mutation(async ({ input, ctx }): Promise<BatchTaskResult> => {
+ const data = await ctx.topicModel.batchCreate(
+ input.map((item) => ({
+ ...item,
+ })) as any,
+ );
+
+ return { added: data.length, ids: [], skips: [], success: true };
+ }),
+
+ batchDelete: topicProcedure
+ .input(z.object({ ids: z.array(z.string()) }))
+ .mutation(async ({ input, ctx }) => {
+ return ctx.topicModel.batchDelete(input.ids);
+ }),
+
+ batchDeleteBySessionId: topicProcedure
+ .input(z.object({ id: z.string().nullable().optional() }))
+ .mutation(async ({ input, ctx }) => {
+ return ctx.topicModel.batchDeleteBySessionId(input.id);
+ }),
+
+ cloneTopic: topicProcedure
+ .input(z.object({ id: z.string(), newTitle: z.string().optional() }))
+ .mutation(async ({ input, ctx }) => {
+ const data = await ctx.topicModel.duplicate(input.id, input.newTitle);
+
+ return data.topic.id;
+ }),
+
+ countTopics: topicProcedure
+ .input(
+ z
+ .object({
+ endDate: z.string().optional(),
+ range: z.tuple([z.string(), z.string()]).optional(),
+ startDate: z.string().optional(),
+ })
+ .optional(),
+ )
+ .query(async ({ ctx, input }) => {
+ return ctx.topicModel.count(input);
+ }),
+
+ createTopic: topicProcedure
+ .input(
+ z.object({
+ favorite: z.boolean().optional(),
+ groupId: z.string().nullable().optional(),
+ messages: z.array(z.string()).optional(),
+ sessionId: z.string().nullable().optional(),
+ title: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const data = await ctx.topicModel.create(input);
+
+ return data.id;
+ }),
+
+ getAllTopics: topicProcedure.query(async ({ ctx }) => {
+ return ctx.topicModel.queryAll();
+ }),
+
+ // TODO: this procedure should be used with authedProcedure
+ getTopics: publicProcedure
+ .input(
+ z.object({
+ containerId: z.string().nullable().optional(),
+ current: z.number().optional(),
+ pageSize: z.number().optional(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ if (!ctx.userId) return [];
+
+ const serverDB = await getServerDB();
+ const topicModel = new TopicModel(serverDB, ctx.userId);
+
+ return topicModel.query(input);
+ }),
+
+ hasTopics: topicProcedure.query(async ({ ctx }) => {
+ return (await ctx.topicModel.count()) === 0;
+ }),
+
+ rankTopics: topicProcedure.input(z.number().optional()).query(async ({ ctx, input }) => {
+ return ctx.topicModel.rank(input);
+ }),
+
+ removeAllTopics: topicProcedure.mutation(async ({ ctx }) => {
+ return ctx.topicModel.deleteAll();
+ }),
+
+ removeTopic: topicProcedure
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ return ctx.topicModel.delete(input.id);
+ }),
+
+ searchTopics: topicProcedure
+ .input(
+ z.object({
+ groupId: z.string().nullable().optional(),
+ keywords: z.string(),
+ sessionId: z.string().nullable().optional(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.topicModel.queryByKeyword(input.keywords, input.sessionId);
+ }),
+
+ updateTopic: topicProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ value: z.object({
+ favorite: z.boolean().optional(),
+ historySummary: z.string().optional(),
+ messages: z.array(z.string()).optional(),
+ metadata: z
+ .object({
+ model: z.string().optional(),
+ provider: z.string().optional(),
+ })
+ .optional(),
+ sessionId: z.string().optional(),
+ title: z.string().optional(),
+ }),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ return ctx.topicModel.update(input.id, input.value);
+ }),
+});
+
+export type TopicRouter = typeof topicRouter;
diff --git a/src/server/services/user/index.test.ts b/src/server/services/user/index.test.ts
index 3dafc49a344..916388ef70a 100644
--- a/src/server/services/user/index.test.ts
+++ b/src/server/services/user/index.test.ts
@@ -4,8 +4,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { UserModel } from '@/database/models/user';
import { UserItem } from '@/database/schemas';
+import { initializeServerAnalytics } from '@/libs/analytics';
import { pino } from '@/libs/logger';
-import { AgentService } from '@/server/services/agent';
import { UserService } from './index';
@@ -39,11 +39,6 @@ vi.mock('@/libs/logger', () => ({
},
}));
-vi.mock('@/server/services/agent', () => ({
- AgentService: vi.fn().mockImplementation(() => ({
- createInbox: vi.fn().mockResolvedValue(undefined),
- })),
-}));
let service: UserService;
const mockUserId = 'test-user-id';
@@ -90,8 +85,8 @@ describe('UserService', () => {
clerkCreatedAt: new Date('2023-01-01T00:00:00Z'),
}),
);
- expect(AgentService).toHaveBeenCalledWith(expect.anything(), mockUserId);
- expect(vi.mocked(AgentService).mock.results[0].value.createInbox).toHaveBeenCalled();
+ // Verify initUser was called (which calls analytics)
+ expect(initializeServerAnalytics).toHaveBeenCalled();
expect(result).toEqual({
message: 'user created',
success: true,
@@ -106,7 +101,6 @@ describe('UserService', () => {
expect(UserModel.findById).toHaveBeenCalledWith(expect.anything(), mockUserId);
expect(UserModel.createUser).not.toHaveBeenCalled();
- expect(AgentService).not.toHaveBeenCalled();
expect(result).toEqual({
message: 'user not created due to user already existing in the database',
success: false,
@@ -130,8 +124,8 @@ describe('UserService', () => {
phone: '+1234567890', // Should use first phone number
}),
);
- expect(AgentService).toHaveBeenCalledWith(expect.anything(), mockUserId);
- expect(vi.mocked(AgentService).mock.results[0].value.createInbox).toHaveBeenCalled();
+ // Verify initUser was called (which calls analytics)
+ expect(initializeServerAnalytics).toHaveBeenCalled();
});
});
diff --git a/src/server/services/user/index.ts b/src/server/services/user/index.ts
index 1fca0f0113b..b49afd8bca5 100644
--- a/src/server/services/user/index.ts
+++ b/src/server/services/user/index.ts
@@ -5,8 +5,7 @@ import { UserModel } from '@/database/models/user';
import { initializeServerAnalytics } from '@/libs/analytics';
import { pino } from '@/libs/logger';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
-import { S3 } from '@/server/modules/S3';
-import { AgentService } from '@/server/services/agent';
+import { FileS3 } from '@/server/modules/S3';
type CreatedUser = {
email?: string | null;
@@ -25,9 +24,6 @@ export class UserService {
}
async initUser(user: CreatedUser) {
- const agentService = new AgentService(this.db, user.id);
- await agentService.createInbox();
-
/* ↓ cloud slot ↓ */
/* ↑ cloud slot ↑ */
@@ -134,7 +130,7 @@ export class UserService {
};
getUserAvatar = async (id: string, image: string) => {
- const s3 = new S3();
+ const s3 = new FileS3();
const s3FileUrl = `user/avatar/${id}/${image}`;
try {
diff --git a/src/store/aiInfra/slices/aiProvider/action.ts b/src/store/aiInfra/slices/aiProvider/action.ts
index 871b5035f88..b8117cac43c 100644
--- a/src/store/aiInfra/slices/aiProvider/action.ts
+++ b/src/store/aiInfra/slices/aiProvider/action.ts
@@ -1,6 +1,6 @@
import { DESKTOP_USER_ID, isDesktop } from '@lobechat/const';
import { getModelPropertyWithFallback, resolveImageSinglePrice } from '@lobechat/model-runtime';
-import { uniqBy } from 'lodash-es';
+import { uniqBy } from 'es-toolkit/compat';
import {
AIImageModelCard,
EnabledAiModel,