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-Liede0ed6d37c6
diff --git a/src/app/(backend)/market/agent/[[...segments]]/route.ts b/src/app/(backend)/market/agent/[[...segments]]/route.ts
index 4770a6cc483..0e91992fab3 100644
--- a/src/app/(backend)/market/agent/[[...segments]]/route.ts
+++ b/src/app/(backend)/market/agent/[[...segments]]/route.ts
@@ -85,6 +85,46 @@ const handleAgent = async (req: NextRequest, segments: string[]) => {
}
}
+ // Get own agents (requires authentication)
+ if (action === 'own') {
+ if (req.method !== 'GET') return methodNotAllowed(['GET']);
+
+ if (!accessToken) {
+ return NextResponse.json(
+ {
+ error: 'unauthorized',
+ message: 'Authentication required to get own agents',
+ status: 'error',
+ },
+ { status: 401 },
+ );
+ }
+
+ try {
+ // Parse query parameters from the request URL
+ const url = new URL(req.url);
+ const page = url.searchParams.get('page');
+ const pageSize = url.searchParams.get('pageSize');
+
+ const response = await market.agents.getOwnAgents({
+ page: page ? parseInt(page, 10) : undefined,
+ pageSize: pageSize ? parseInt(pageSize, 10) : undefined,
+ });
+
+ return NextResponse.json(response);
+ } catch (error) {
+ console.error('[Market] Failed to get own agents:', error);
+ return NextResponse.json(
+ {
+ error: 'get_own_agents_failed',
+ message: error instanceof Error ? error.message : 'Unknown error',
+ status: 'error',
+ },
+ { status: 500 },
+ );
+ }
+ }
+
if (action === 'versions') {
if (rest.length !== 1 || rest[0] !== 'create') {
return notFound('Requested agent version endpoint is not available.');
@@ -118,6 +158,47 @@ const handleAgent = async (req: NextRequest, segments: string[]) => {
}
}
+ // Handle agent status actions: /agent/{identifier}/{action}
+ // Actions: publish, unpublish, deprecate
+ if (segments.length === 2) {
+ const [identifier, statusAction] = segments;
+
+ if (!['publish', 'unpublish', 'deprecate'].includes(statusAction)) {
+ return notFound(`Unknown agent action: ${statusAction}`);
+ }
+
+ if (req.method !== 'POST') return methodNotAllowed(['POST']);
+
+ try {
+ let response;
+ switch (statusAction) {
+ case 'publish': {
+ response = await market.agents.publish(identifier);
+ break;
+ }
+ case 'unpublish': {
+ response = await market.agents.unpublish(identifier);
+ break;
+ }
+ case 'deprecate': {
+ response = await market.agents.deprecate(identifier);
+ break;
+ }
+ }
+ return NextResponse.json(response ?? { success: true });
+ } catch (error) {
+ console.error(`[Market] Failed to ${statusAction} agent:`, error);
+ return NextResponse.json(
+ {
+ error: `${statusAction}_agent_failed`,
+ message: error instanceof Error ? error.message : 'Unknown error',
+ status: 'error',
+ },
+ { status: 500 },
+ );
+ }
+ }
+
if (segments.length === 1) {
if (req.method !== 'GET') return methodNotAllowed(['GET']);
diff --git a/src/app/(backend)/market/user/[username]/route.ts b/src/app/(backend)/market/user/[username]/route.ts
new file mode 100644
index 00000000000..b9445950593
--- /dev/null
+++ b/src/app/(backend)/market/user/[username]/route.ts
@@ -0,0 +1,68 @@
+import { MarketSDK } from '@lobehub/market-sdk';
+import { NextRequest, NextResponse } from 'next/server';
+
+type RouteContext = {
+ params: Promise<{
+ username: string;
+ }>;
+};
+
+const MARKET_BASE_URL = process.env.NEXT_PUBLIC_MARKET_BASE_URL || 'https://market.lobehub.com';
+
+/**
+ * GET /market/user/[username]
+ *
+ * Fetches user profile information from Market SDK.
+ * Returns only user basic info (no agents list).
+ */
+export const GET = async (req: NextRequest, context: RouteContext) => {
+ const { username } = await context.params;
+ const decodedUsername = decodeURIComponent(username);
+
+ const market = new MarketSDK({
+ baseURL: MARKET_BASE_URL,
+ });
+
+ try {
+ const response = await market.user.getUserInfo(decodedUsername);
+
+ if (!response?.user) {
+ return NextResponse.json(
+ {
+ error: 'user_not_found',
+ message: `User not found: ${decodedUsername}`,
+ status: 'error',
+ },
+ { status: 404 },
+ );
+ }
+
+ // Return only user profile info (without agents)
+ const { user } = response;
+
+ return NextResponse.json({
+ avatarUrl: user.avatarUrl || null,
+ bannerUrl: user.meta?.bannerUrl || null,
+ createdAt: user.createdAt,
+ description: user.meta?.description || null,
+ displayName: user.displayName || null,
+ id: user.id,
+ namespace: user.namespace,
+ socialLinks: user.meta?.socialLinks || null,
+ type: user.type || null,
+ userName: user.userName || null,
+ });
+ } catch (error) {
+ console.error('[Market] Failed to get user profile:', error);
+ return NextResponse.json(
+ {
+ error: 'get_user_profile_failed',
+ message: error instanceof Error ? error.message : 'Unknown error',
+ status: 'error',
+ },
+ { status: 500 },
+ );
+ }
+};
+
+export const dynamic = 'force-dynamic';
diff --git a/src/app/(backend)/market/user/me/route.ts b/src/app/(backend)/market/user/me/route.ts
new file mode 100644
index 00000000000..ee9bb7effbf
--- /dev/null
+++ b/src/app/(backend)/market/user/me/route.ts
@@ -0,0 +1,83 @@
+import { MarketSDK } from '@lobehub/market-sdk';
+import { NextRequest, NextResponse } from 'next/server';
+
+const MARKET_BASE_URL = process.env.NEXT_PUBLIC_MARKET_BASE_URL || 'https://market.lobehub.com';
+
+const extractAccessToken = (req: NextRequest) => {
+ const authorization = req.headers.get('authorization');
+ if (!authorization) return undefined;
+
+ const [scheme, token] = authorization.split(' ');
+ if (scheme?.toLowerCase() !== 'bearer' || !token) return undefined;
+
+ return token;
+};
+
+/**
+ * PUT /market/user/me
+ *
+ * Updates the authenticated user's profile information.
+ * Requires authentication via Bearer token.
+ *
+ * Request body:
+ * - userName?: string - User's unique username
+ * - displayName?: string - User's display name
+ * - avatarUrl?: string - User's avatar URL
+ * - meta?: { description?: string; socialLinks?: { github?: string; twitter?: string; website?: string } }
+ */
+export const PUT = async (req: NextRequest) => {
+ const accessToken = extractAccessToken(req);
+
+ if (!accessToken) {
+ return NextResponse.json(
+ {
+ error: 'unauthorized',
+ message: 'Authentication required to update user profile',
+ status: 'error',
+ },
+ { status: 401 },
+ );
+ }
+
+ const market = new MarketSDK({
+ accessToken,
+ baseURL: MARKET_BASE_URL,
+ });
+
+ try {
+ const payload = await req.json();
+
+ // Validate payload
+ if (typeof payload !== 'object' || payload === null) {
+ return NextResponse.json(
+ {
+ error: 'invalid_payload',
+ message: 'Request body must be a JSON object',
+ status: 'error',
+ },
+ { status: 400 },
+ );
+ }
+
+ const response = await market.user.updateUserInfo(payload);
+
+ return NextResponse.json(response);
+ } catch (error) {
+ console.error('[Market] Failed to update user profile:', error);
+
+ // Check for specific error types
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+ const isUserNameTaken = errorMessage.toLowerCase().includes('already taken');
+
+ return NextResponse.json(
+ {
+ error: isUserNameTaken ? 'username_taken' : 'update_user_profile_failed',
+ message: errorMessage,
+ status: 'error',
+ },
+ { status: isUserNameTaken ? 409 : 500 },
+ );
+ }
+};
+
+export const dynamic = 'force-dynamic';
diff --git a/src/features/AgentBuilder/AgentBuilderConversation.tsx b/src/features/AgentBuilder/AgentBuilderConversation.tsx
new file mode 100644
index 00000000000..9bdba48fd3f
--- /dev/null
+++ b/src/features/AgentBuilder/AgentBuilderConversation.tsx
@@ -0,0 +1,31 @@
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import type { ActionKeys } from '@/features/ChatInput';
+import { ChatInput, ChatList } from '@/features/Conversation';
+
+import AgentBuilderWelcome from './AgentBuilderWelcome';
+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/features/AgentBuilder/AgentBuilderProvider.tsx b/src/features/AgentBuilder/AgentBuilderProvider.tsx
new file mode 100644
index 00000000000..6353cddb3c6
--- /dev/null
+++ b/src/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;
+}
+
+/**
+ * Agent Builder Conversation Provider
+ * Provides context for the Agent Builder chat panel
+ * Uses 'agent_builder' scope to isolate messages from main conversation
+ */
+const AgentBuilderProvider = memo<AgentBuilderProviderProps>(({ agentId, children }) => {
+ const activeTopicId = useChatStore((s) => s.activeTopicId);
+
+ // Build conversation context for agent builder
+ // Using agent_builder scope for message management
+ const context = useMemo<MessageMapKeyInput>(
+ () => ({
+ agentId,
+ scope: 'agent_builder',
+ topicId: activeTopicId,
+ }),
+ [agentId, activeTopicId],
+ );
+
+ // Get messages from ChatStore based on context
+ const chatKey = useMemo(
+ () => (context ? messageMapKey(context) : null),
+ [context?.agentId, 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/features/AgentBuilder/AgentBuilderWelcome.tsx b/src/features/AgentBuilder/AgentBuilderWelcome.tsx
new file mode 100644
index 00000000000..21666759fea
--- /dev/null
+++ b/src/features/AgentBuilder/AgentBuilderWelcome.tsx
@@ -0,0 +1,40 @@
+'use client';
+
+import { Avatar, Markdown, Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { DEFAULT_INBOX_AVATAR } from '@/const/index';
+import { conversationSelectors, useConversationStore } from '@/features/Conversation';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+
+const AgentBuilderWelcome = memo(() => {
+ const { t } = useTranslation('chat');
+ const agentId = useConversationStore(conversationSelectors.agentId);
+ const agent = useAgentStore(agentByIdSelectors.getAgentConfigById(agentId));
+
+ return (
+ <>
+ <Flexbox flex={1} />
+ <Flexbox
+ gap={12}
+ style={{
+ paddingBottom: 'max(10vh, 32px)',
+ }}
+ width={'100%'}
+ >
+ <Avatar avatar={agent.avatar || DEFAULT_INBOX_AVATAR} shape={'square'} size={78} />
+ <Text fontSize={24} weight={'bold'}>
+ {t('agentBuilder.title')}
+ </Text>
+ <Markdown fontSize={14} variant={'chat'}>
+ {t('agentBuilder.welcome')}
+ </Markdown>
+ </Flexbox>
+ </>
+ );
+});
+
+export default AgentBuilderWelcome;
diff --git a/src/features/AgentBuilder/TopicSelector.tsx b/src/features/AgentBuilder/TopicSelector.tsx
new file mode 100644
index 00000000000..2559fc36499
--- /dev/null
+++ b/src/features/AgentBuilder/TopicSelector.tsx
@@ -0,0 +1,109 @@
+import { ActionIcon, Tag } from '@lobehub/ui';
+import { Dropdown } from 'antd';
+import { createStyles } from 'antd-style';
+import type { ItemType } from 'antd/es/menu/interface';
+import dayjs from 'dayjs';
+import relativeTime from 'dayjs/plugin/relativeTime';
+import { Clock3Icon, PlusIcon } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+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';
+
+dayjs.extend(relativeTime);
+
+const useStyles = createStyles(({ css, token }) => ({
+ time: css`
+ font-size: 12px;
+ color: ${token.colorTextTertiary};
+ `,
+ title: css`
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+interface TopicSelectorProps {
+ agentId: string;
+}
+
+const TopicSelector = memo<TopicSelectorProps>(({ agentId }) => {
+ const { t } = useTranslation('topic');
+ const { styles } = useStyles();
+
+ // Fetch topics for the 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) => {
+ const displayTime =
+ dayjs().diff(dayjs(topic.updatedAt), 'd') < 7
+ ? dayjs(topic.updatedAt).fromNow()
+ : dayjs(topic.updatedAt).format('YYYY-MM-DD');
+
+ return {
+ key: topic.id,
+ label: (
+ <Flexbox gap={4} horizontal justify="space-between" width="100%">
+ <span className={styles.title}>{topic.title}</span>
+ <span className={styles.time}>{displayTime}</span>
+ </Flexbox>
+ ),
+ onClick: () => switchTopic(topic.id),
+ };
+ }),
+ [topics, switchTopic, styles],
+ );
+
+ 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] : [],
+ style: { maxHeight: 400, overflowY: 'auto' },
+ }}
+ overlayStyle={{ minWidth: 280 }}
+ 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/features/AgentBuilder/index.tsx b/src/features/AgentBuilder/index.tsx
new file mode 100644
index 00000000000..e69e441aa04
--- /dev/null
+++ b/src/features/AgentBuilder/index.tsx
@@ -0,0 +1,32 @@
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { memo } from 'react';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import RightPanel from '@/features/RightPanel';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+
+import AgentBuilderConversation from './AgentBuilderConversation';
+import AgentBuilderProvider from './AgentBuilderProvider';
+
+const AgentBuilder = memo(() => {
+ const agentId = useAgentStore((s) => s.activeAgentId);
+ const agentBuilderId = useAgentStore(builtinAgentSelectors.agentBuilderId);
+
+ const useInitBuiltinAgent = useAgentStore((s) => s.useInitBuiltinAgent);
+ useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.agentBuilder);
+
+ return (
+ <RightPanel>
+ {agentId && agentBuilderId ? (
+ <AgentBuilderProvider agentId={agentBuilderId}>
+ <AgentBuilderConversation agentId={agentBuilderId} />
+ </AgentBuilderProvider>
+ ) : (
+ <Loading debugId="AgentBuilder > Init" />
+ )}
+ </RightPanel>
+ );
+});
+
+export default AgentBuilder;
diff --git a/src/features/AgentSetting/AgentCategory/useCategory.tsx b/src/features/AgentSetting/AgentCategory/useCategory.tsx
index 2e61322d785..d9947dba0cb 100644
--- a/src/features/AgentSetting/AgentCategory/useCategory.tsx
+++ b/src/features/AgentSetting/AgentCategory/useCategory.tsx
@@ -1,14 +1,13 @@
import { Icon } from '@lobehub/ui';
import { MenuItemType } from 'antd/es/menu/interface';
-import { Blocks, Bot, BrainCog, Handshake, MessagesSquare, Mic2, UserCircle } from 'lucide-react';
+import { Bot, BrainCog, Handshake, MessagesSquare, Mic2, UserCircle } from 'lucide-react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import type { MenuProps } from '@/components/Menu';
-import { INBOX_SESSION_ID } from '@/const/session';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
import { ChatSettingsTabs } from '@/store/global/initialState';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-import { useSessionStore } from '@/store/session';
interface UseCategoryOptions {
mobile?: boolean;
@@ -17,9 +16,7 @@ interface UseCategoryOptions {
export const useCategory = ({ mobile }: UseCategoryOptions = {}) => {
const { t } = useTranslation('setting');
const iconSize = mobile ? 20 : undefined;
- const id = useSessionStore((s) => s.activeId);
- const isInbox = id === INBOX_SESSION_ID;
- const { enablePlugins } = useServerConfigStore(featureFlagsSelectors);
+ const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
const cateItems: MenuProps['items'] = useMemo(
() =>
@@ -54,13 +51,8 @@ export const useCategory = ({ mobile }: UseCategoryOptions = {}) => {
key: ChatSettingsTabs.TTS,
label: t('agentTab.tts'),
},
- enablePlugins && {
- icon: <Icon icon={Blocks} size={iconSize} />,
- key: ChatSettingsTabs.Plugin,
- label: t('agentTab.plugin'),
- },
].filter(Boolean) as MenuProps['items'],
- [t, isInbox, enablePlugins],
+ [t, isInbox],
);
return cateItems;
diff --git a/src/features/AgentSetting/AgentChat/index.tsx b/src/features/AgentSetting/AgentChat/index.tsx
index 383234ba773..92797eb8cea 100644
--- a/src/features/AgentSetting/AgentChat/index.tsx
+++ b/src/features/AgentSetting/AgentChat/index.tsx
@@ -1,62 +1,23 @@
'use client';
-import { Form, type FormGroupItemType, ImageSelect, SliderWithInput, TextArea } from '@lobehub/ui';
+import { Form, type FormGroupItemType, SliderWithInput } from '@lobehub/ui';
import { Switch } from 'antd';
-import { useThemeMode } from 'antd-style';
import isEqual from 'fast-deep-equal';
-import { LayoutList, MessagesSquare } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { FORM_STYLE } from '@/const/layoutTokens';
-import { imageUrl } from '@/const/url';
import { selectors, useStore } from '../store';
const AgentChat = memo(() => {
const { t } = useTranslation('setting');
const [form] = Form.useForm();
- const { isDarkMode } = useThemeMode();
const updateConfig = useStore((s) => s.setChatConfig);
const config = useStore(selectors.currentChatConfig, isEqual);
const chat: FormGroupItemType = {
children: [
- {
- children: (
- <ImageSelect
- height={86}
- options={[
- {
- icon: MessagesSquare,
- img: imageUrl(`chatmode_chat_${isDarkMode ? 'dark' : 'light'}.webp`),
- label: t('settingChat.chatStyleType.type.chat'),
- value: 'chat',
- },
- {
- icon: LayoutList,
- img: imageUrl(`chatmode_docs_${isDarkMode ? 'dark' : 'light'}.webp`),
- label: t('settingChat.chatStyleType.type.docs'),
- value: 'docs',
- },
- ]}
- style={{
- marginRight: 2,
- }}
- unoptimized={false}
- width={144}
- />
- ),
- label: t('settingChat.chatStyleType.title'),
- minWidth: undefined,
- name: 'displayMode',
- },
- {
- children: <TextArea placeholder={t('settingChat.inputTemplate.placeholder')} />,
- desc: t('settingChat.inputTemplate.desc'),
- label: t('settingChat.inputTemplate.title'),
- name: 'inputTemplate',
- },
{
children: <Switch />,
desc: t('settingChat.enableAutoCreateTopic.desc'),
diff --git a/src/features/AgentSetting/AgentMeta/AutoGenerateAvatar.tsx b/src/features/AgentSetting/AgentMeta/AutoGenerateAvatar.tsx
index 1c2c6d45585..d83d5798cdc 100644
--- a/src/features/AgentSetting/AgentMeta/AutoGenerateAvatar.tsx
+++ b/src/features/AgentSetting/AgentMeta/AutoGenerateAvatar.tsx
@@ -1,16 +1,14 @@
import { ActionIcon } from '@lobehub/ui';
import { useTheme } from 'antd-style';
import { Wand2 } from 'lucide-react';
-import dynamic from 'next/dynamic';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
+import EmojiPicker from '@/components/EmojiPicker';
import { useGlobalStore } from '@/store/global';
import { globalGeneralSelectors } from '@/store/global/selectors';
-const EmojiPicker = dynamic(() => import('@lobehub/ui/es/EmojiPicker'), { ssr: false });
-
export interface AutoGenerateAvatarProps {
background?: string;
canAutoGenerate?: boolean;
diff --git a/src/features/AgentSetting/AgentMeta/AutoGenerateSelect.tsx b/src/features/AgentSetting/AgentMeta/AutoGenerateSelect.tsx
index 949de8f2b09..e49c83aa84c 100644
--- a/src/features/AgentSetting/AgentMeta/AutoGenerateSelect.tsx
+++ b/src/features/AgentSetting/AgentMeta/AutoGenerateSelect.tsx
@@ -1,5 +1,5 @@
import { ActionIcon, Select, type SelectProps } from '@lobehub/ui';
-import { isString } from 'lodash-es';
+import { isString } from 'es-toolkit/compat';
import { Wand2 } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/src/features/AgentSetting/AgentMeta/BackgroundSwatches.tsx b/src/features/AgentSetting/AgentMeta/BackgroundSwatches.tsx
index f599ef43aea..d9173912aad 100644
--- a/src/features/AgentSetting/AgentMeta/BackgroundSwatches.tsx
+++ b/src/features/AgentSetting/AgentMeta/BackgroundSwatches.tsx
@@ -1,73 +1,78 @@
import { ColorSwatches, ColorSwatchesProps, primaryColors } from '@lobehub/ui';
-import { memo } from 'react';
+import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { DEFAULT_BACKGROUND_COLOR } from '@/const/meta';
-interface BackgroundSwatchesProps
- extends Pick<ColorSwatchesProps, 'defaultValue' | 'value' | 'onChange'> {
+interface BackgroundSwatchesProps extends Omit<ColorSwatchesProps, 'colors'> {
onValuesChange?: ColorSwatchesProps['onChange'];
}
const BackgroundSwatches = memo<BackgroundSwatchesProps>(
- ({ defaultValue = DEFAULT_BACKGROUND_COLOR, value, onChange, onValuesChange }) => {
+ ({ defaultValue = DEFAULT_BACKGROUND_COLOR, value, onChange, onValuesChange, ...rest }) => {
const { t } = useTranslation('color');
+
+ const colors = useMemo(
+ () => [
+ {
+ color: 'rgba(0, 0, 0, 0)',
+ title: t('default'),
+ },
+ {
+ color: primaryColors.red,
+ title: t('red'),
+ },
+ {
+ color: primaryColors.orange,
+ title: t('orange'),
+ },
+ {
+ color: primaryColors.gold,
+ title: t('gold'),
+ },
+ {
+ color: primaryColors.yellow,
+ title: t('yellow'),
+ },
+ {
+ color: primaryColors.lime,
+ title: t('lime'),
+ },
+ {
+ color: primaryColors.green,
+ title: t('green'),
+ },
+ {
+ color: primaryColors.cyan,
+ title: t('cyan'),
+ },
+ {
+ color: primaryColors.blue,
+ title: t('blue'),
+ },
+ {
+ color: primaryColors.geekblue,
+ title: t('geekblue'),
+ },
+ {
+ color: primaryColors.purple,
+ title: t('purple'),
+ },
+ {
+ color: primaryColors.magenta,
+ title: t('magenta'),
+ },
+ {
+ color: primaryColors.volcano,
+ title: t('volcano'),
+ },
+ ],
+ [t],
+ );
+
return (
<ColorSwatches
- colors={[
- {
- color: 'rgba(0, 0, 0, 0)',
- title: t('default'),
- },
- {
- color: primaryColors.red,
- title: t('red'),
- },
- {
- color: primaryColors.orange,
- title: t('orange'),
- },
- {
- color: primaryColors.gold,
- title: t('gold'),
- },
- {
- color: primaryColors.yellow,
- title: t('yellow'),
- },
- {
- color: primaryColors.lime,
- title: t('lime'),
- },
- {
- color: primaryColors.green,
- title: t('green'),
- },
- {
- color: primaryColors.cyan,
- title: t('cyan'),
- },
- {
- color: primaryColors.blue,
- title: t('blue'),
- },
- {
- color: primaryColors.geekblue,
- title: t('geekblue'),
- },
- {
- color: primaryColors.purple,
- title: t('purple'),
- },
- {
- color: primaryColors.magenta,
- title: t('magenta'),
- },
- {
- color: primaryColors.volcano,
- title: t('volcano'),
- },
- ]}
+ colors={colors}
defaultValue={defaultValue}
enableColorPicker
onChange={(v) => {
@@ -79,6 +84,7 @@ const BackgroundSwatches = memo<BackgroundSwatchesProps>(
presets: t('presets'),
}}
value={value}
+ {...rest}
/>
);
},
diff --git a/src/features/AgentSetting/AgentModal/index.tsx b/src/features/AgentSetting/AgentModal/index.tsx
index 0327579b45b..ebaf9c6745f 100644
--- a/src/features/AgentSetting/AgentModal/index.tsx
+++ b/src/features/AgentSetting/AgentModal/index.tsx
@@ -7,7 +7,7 @@ import {
Select,
SliderWithInput,
} from '@lobehub/ui';
-import { Form as AntdForm, Checkbox, Switch } from 'antd';
+import { Form as AntdForm, Switch } from 'antd';
import { createStyles } from 'antd-style';
import isEqual from 'fast-deep-equal';
import { memo, useCallback, useEffect, useRef } from 'react';
@@ -16,32 +16,15 @@ import { Flexbox } from 'react-layout-kit';
import InfoTooltip from '@/components/InfoTooltip';
import { FORM_STYLE } from '@/const/layoutTokens';
-import ModelSelect from '@/features/ModelSelect';
-import { useProviderName } from '@/hooks/useProviderName';
import { selectors, useStore } from '../store';
type ParamKey = 'temperature' | 'top_p' | 'presence_penalty' | 'frequency_penalty';
-const useStyles = createStyles(({ css, token }) => ({
- checkbox: css`
- .ant-checkbox-inner {
- border-radius: 4px;
- }
-
- &:hover .ant-checkbox-inner {
- border-color: ${token.colorPrimary};
- }
- `,
+const useStyles = createStyles(({ css }) => ({
label: css`
user-select: none;
`,
- sliderWrapper: css`
- display: flex;
- gap: 16px;
- align-items: center;
- width: 100%;
- `,
}));
// Wrapper component for slider with checkbox
@@ -58,28 +41,29 @@ interface SliderWithCheckboxProps {
}
const SliderWithCheckbox = memo<SliderWithCheckboxProps>(
- ({ value, onChange, disabled, checked, onToggle, styles, min, max, step }) => {
+ ({ value, onChange, disabled, checked, onToggle, min, max, step }) => {
return (
- <div className={styles.sliderWrapper}>
- <Checkbox
+ <Flexbox align="center" gap={12} horizontal justify={'flex-end'} width={300}>
+ {!disabled && (
+ <div style={{ flex: 1 }}>
+ <SliderWithInput
+ disabled={disabled}
+ max={max}
+ min={min}
+ onChange={onChange}
+ step={step}
+ value={value}
+ />
+ </div>
+ )}
+ <Switch
checked={checked}
- className={styles.checkbox}
- onChange={(e) => {
- e.stopPropagation();
- onToggle(e.target.checked);
+ onChange={(v) => {
+ onToggle(v);
}}
+ size={checked ? 'small' : 'default'}
/>
- <div style={{ flex: 1 }}>
- <SliderWithInput
- disabled={disabled}
- max={max}
- min={min}
- onChange={onChange}
- step={step}
- value={value}
- />
- </div>
- </div>
+ </Flexbox>
);
},
);
@@ -143,8 +127,6 @@ const AgentModal = memo(() => {
const enableReasoningEffort = AntdForm.useWatch(['chatConfig', 'enableReasoningEffort'], form);
const updateConfig = useStore((s) => s.setAgentConfig);
- const provider = useStore((s) => s.config.provider);
- const providerName = useProviderName(provider as string);
const { temperature, top_p, presence_penalty, frequency_penalty } = config.params ?? {};
@@ -156,13 +138,7 @@ const AgentModal = memo(() => {
});
useEffect(() => {
- form.setFieldsValue({
- ...config,
- _modalConfig: {
- model: config.model,
- provider: config.provider,
- },
- });
+ form.setFieldsValue(config);
if (typeof temperature === 'number') lastValuesRef.current.temperature = temperature;
if (typeof top_p === 'number') lastValuesRef.current.top_p = top_p;
@@ -250,6 +226,7 @@ const AgentModal = memo(() => {
<InfoTooltip title={t(meta.descKey as any)} />
</Flexbox>
),
+ minWidth: undefined,
name: PARAM_NAME_MAP[key],
tag: meta.tag,
} satisfies FormItemProps;
@@ -257,13 +234,6 @@ const AgentModal = memo(() => {
const model: FormGroupItemType = {
children: [
- {
- children: <ModelSelect />,
- desc: t('settingModel.model.desc', { provider: providerName }),
- label: t('settingModel.model.title'),
- name: '_modalConfig',
- tag: 'model',
- },
{
children: <Switch />,
desc: t('settingChat.enableStreaming.desc'),
@@ -341,34 +311,24 @@ const AgentModal = memo(() => {
/>
}
form={form}
- initialValues={{
- ...config,
- _modalConfig: {
- model: config.model,
- provider: config.provider,
- },
- }}
+ initialValues={config}
items={[model]}
itemsType={'group'}
- onFinish={({ _modalConfig, ...rest }) => {
+ onFinish={(values) => {
// 清理 params 中的 undefined 和 null 值,确保禁用的参数被正确移除
- const cleanedRest = { ...rest };
- if (cleanedRest.params) {
- const cleanedParams = { ...cleanedRest.params };
+ const cleanedValues = { ...values };
+ if (cleanedValues.params) {
+ const cleanedParams = { ...cleanedValues.params };
(Object.keys(cleanedParams) as Array<keyof typeof cleanedParams>).forEach((key) => {
// 使用 null 作为禁用标记(JSON 可以序列化 null,而 undefined 会被忽略)
if (cleanedParams[key] === undefined) {
cleanedParams[key] = null as any;
}
});
- cleanedRest.params = cleanedParams as any;
+ cleanedValues.params = cleanedParams as any;
}
- updateConfig({
- model: _modalConfig?.model,
- provider: _modalConfig?.provider,
- ...cleanedRest,
- });
+ updateConfig(cleanedValues);
}}
variant={'borderless'}
{...FORM_STYLE}
diff --git a/src/features/AgentSetting/AgentOpening/OpeningQuestions.tsx b/src/features/AgentSetting/AgentOpening/OpeningQuestions.tsx
index c851ddbd1be..60cc6375b6d 100644
--- a/src/features/AgentSetting/AgentOpening/OpeningQuestions.tsx
+++ b/src/features/AgentSetting/AgentOpening/OpeningQuestions.tsx
@@ -1,9 +1,9 @@
'use client';
-import { ActionIcon, Button, Input, SortableList } from '@lobehub/ui';
-import { Empty, Space } from 'antd';
+import { ActionIcon, Button, Empty, Input, SortableList } from '@lobehub/ui';
+import { Space } from 'antd';
import { createStyles } from 'antd-style';
-import { PlusIcon, Trash } from 'lucide-react';
+import { MessageCircle, PlusIcon, Trash } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
@@ -135,7 +135,9 @@ const OpeningQuestions = memo(() => {
<Empty
className={styles.empty}
description={t('settingOpening.openingQuestions.empty')}
- image={Empty.PRESENTED_IMAGE_SIMPLE}
+ descriptionProps={{ fontSize: 14 }}
+ icon={MessageCircle}
+ style={{ maxWidth: 400 }}
/>
)}
</div>
diff --git a/src/features/AgentSetting/AgentPlugin/AddPluginButton.tsx b/src/features/AgentSetting/AgentPlugin/AddPluginButton.tsx
index 1b447797d85..026a8605d1d 100644
--- a/src/features/AgentSetting/AgentPlugin/AddPluginButton.tsx
+++ b/src/features/AgentSetting/AgentPlugin/AddPluginButton.tsx
@@ -3,14 +3,14 @@ import { PackagePlus } from 'lucide-react';
import { forwardRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useStore } from '@/features/AgentSetting/store';
import DevModal from '@/features/PluginDevModal';
+import { useAgentStore } from '@/store/agent';
import { useToolStore } from '@/store/tool';
const AddPluginButton = forwardRef<HTMLButtonElement>((props, ref) => {
const { t } = useTranslation('setting');
const [showModal, setModal] = useState(false);
- const [toggleAgentPlugin] = useStore((s) => [s.toggleAgentPlugin]);
+ const toggleAgentPlugin = useAgentStore((s) => s.toggleAgentPlugin);
const [installCustomPlugin, updateNewDevPlugin] = useToolStore((s) => [
s.installCustomPlugin,
s.updateNewCustomPlugin,
diff --git a/src/features/AgentSetting/AgentPlugin/LoadingList.tsx b/src/features/AgentSetting/AgentPlugin/LoadingList.tsx
index 9ee7af28a3b..a688731c414 100644
--- a/src/features/AgentSetting/AgentPlugin/LoadingList.tsx
+++ b/src/features/AgentSetting/AgentPlugin/LoadingList.tsx
@@ -1,44 +1,28 @@
-import { Skeleton } from 'antd';
-import { createStyles } from 'antd-style';
-
-const useStyles = createStyles(({ css, prefixCls }) => ({
- avatar: css`
- .${prefixCls}-skeleton-header {
- padding-inline-end: 0;
- }
- `,
- label: css`
- li {
- height: 14px !important;
- }
-
- li + li {
- margin-block-start: 12px !important;
- }
- `,
-}));
+import { Skeleton } from '@lobehub/ui';
+import { Flexbox } from 'react-layout-kit';
const LoadingList = () => {
- const { styles } = useStyles();
-
const loadingItem = {
- avatar: (
- <Skeleton
- active
- avatar={{ size: 40 }}
- className={styles.avatar}
- paragraph={false}
- title={false}
- />
- ),
+ avatar: <Skeleton.Avatar active shape="square" size={40} style={{ flex: 'none' }} />,
label: (
- <Skeleton
- active
- avatar={false}
- paragraph={{ className: styles.label, style: { marginBottom: 0 } }}
- style={{ width: 300 }}
- title={false}
- />
+ <Flexbox flex={1} gap={6} style={{ overflow: 'hidden' }}>
+ <Skeleton.Button
+ active
+ size={'small'}
+ style={{
+ height: 16,
+ width: '70%',
+ }}
+ />
+ <Skeleton.Button
+ active
+ size={'small'}
+ style={{
+ height: 12,
+ width: '50%',
+ }}
+ />
+ </Flexbox>
),
};
diff --git a/src/features/AgentSetting/AgentPlugin/index.tsx b/src/features/AgentSetting/AgentPlugin/index.tsx
index 98406f6e5a9..64988a791d4 100644
--- a/src/features/AgentSetting/AgentPlugin/index.tsx
+++ b/src/features/AgentSetting/AgentPlugin/index.tsx
@@ -1,13 +1,13 @@
'use client';
-import { Avatar, Button, Form, type FormGroupItemType, Tag, Tooltip } from '@lobehub/ui';
-import { Empty, Space, Switch } from 'antd';
+import { Avatar, Button, Empty, Form, type FormGroupItemType, Tag, Tooltip } from '@lobehub/ui';
+import { Space, Switch } from 'antd';
import isEqual from 'fast-deep-equal';
-import { LucideTrash2, Store } from 'lucide-react';
-import { Link, useNavigate } from 'react-router-dom';
+import { LucideTrash2, Plug2, Store } from 'lucide-react';
import { memo, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { Center, Flexbox } from 'react-layout-kit';
+import { Link, useNavigate } from 'react-router-dom';
import PluginAvatar from '@/components/Plugins/PluginAvatar';
import PluginTag from '@/components/Plugins/PluginTag';
@@ -73,7 +73,7 @@ const AgentPlugin = memo(() => {
const deprecatedList = userEnabledPlugins
.filter((pluginId) => !installedPlugins.some((p) => p.identifier === pluginId))
.map((id) => ({
- avatar: <Avatar avatar={'♻️'} size={40} />,
+ avatar: <Avatar avatar={'♻️'} shape={'square'} size={40} />,
children: (
<Switch
checked={true}
@@ -140,16 +140,18 @@ const AgentPlugin = memo(() => {
e.stopPropagation();
e.preventDefault();
setShowStore(true);
- navigate('/discover/mcp');
+ navigate('/community/mcp');
}}
- to={'/discover/mcp'}
+ to={'/community/mcp'}
>
前往插件市场
</Link>
安装
</Trans>
}
- image={Empty.PRESENTED_IMAGE_SIMPLE}
+ descriptionProps={{ fontSize: 14 }}
+ icon={Plug2}
+ style={{ maxWidth: 400 }}
/>
</Center>
);
diff --git a/src/features/AgentSetting/AgentSettings.tsx b/src/features/AgentSetting/AgentSettings.tsx
index 300039f97cf..3b093014ccd 100644
--- a/src/features/AgentSetting/AgentSettings.tsx
+++ b/src/features/AgentSetting/AgentSettings.tsx
@@ -1,4 +1,4 @@
-import { Skeleton } from 'antd';
+import { Skeleton } from '@lobehub/ui';
import { Suspense, memo } from 'react';
import { ChatSettingsTabs } from '@/store/global/initialState';
diff --git a/src/features/AgentSetting/AgentSettingsContent.tsx b/src/features/AgentSetting/AgentSettingsContent.tsx
index 4e4e09d37b5..be22b28b40f 100644
--- a/src/features/AgentSetting/AgentSettingsContent.tsx
+++ b/src/features/AgentSetting/AgentSettingsContent.tsx
@@ -1,16 +1,12 @@
import { ReactNode, memo } from 'react';
-import { useStore } from '@/features/AgentSetting/store';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
import { ChatSettingsTabs } from '@/store/global/initialState';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import AgentChat from './AgentChat';
-import AgentMeta from './AgentMeta';
import AgentModal from './AgentModal';
import AgentOpening from './AgentOpening';
-import AgentPlugin from './AgentPlugin';
-import AgentPrompt from './AgentPrompt';
-import AgentTTS from './AgentTTS';
export interface AgentSettingsContentProps {
loadingSkeleton: ReactNode;
@@ -18,20 +14,15 @@ export interface AgentSettingsContentProps {
}
const AgentSettingsContent = memo<AgentSettingsContentProps>(({ tab, loadingSkeleton }) => {
- const loading = useStore((s) => s.loading);
- const { enablePlugins } = useServerConfigStore(featureFlagsSelectors);
+ const loading = useAgentStore(agentSelectors.isAgentConfigLoading);
if (loading) return loadingSkeleton;
return (
<>
- {tab === ChatSettingsTabs.Meta && <AgentMeta />}
- {tab === ChatSettingsTabs.Prompt && <AgentPrompt />}
{tab === ChatSettingsTabs.Opening && <AgentOpening />}
{tab === ChatSettingsTabs.Chat && <AgentChat />}
{tab === ChatSettingsTabs.Modal && <AgentModal />}
- {tab === ChatSettingsTabs.TTS && <AgentTTS />}
- {enablePlugins && tab === ChatSettingsTabs.Plugin && <AgentPlugin />}
</>
);
});
diff --git a/src/features/AgentSetting/store/action.ts b/src/features/AgentSetting/store/action.ts
index 64267a62bb3..75bdee45ee7 100644
--- a/src/features/AgentSetting/store/action.ts
+++ b/src/features/AgentSetting/store/action.ts
@@ -20,7 +20,7 @@ import { SystemAgentItem } from '@/types/user/settings';
import { merge } from '@/utils/merge';
import { setNamespace } from '@/utils/storeDebug';
-import { LoadingState } from '../store/initialState';
+import { LoadingState, SaveStatus } from '../store/initialState';
import { State, initialState } from './initialState';
import { ConfigDispatch, configReducer } from './reducers/config';
import { MetaDataDispatch, metaDataReducer } from './reducers/meta';
@@ -74,6 +74,11 @@ export interface Action extends PublicAction {
* @param value - 加载状态的值
*/
updateLoadingState: (key: keyof LoadingState, value: boolean) => void;
+ /**
+ * 更新保存状态
+ * @param status - 保存状态
+ */
+ updateSaveStatus: (status: SaveStatus) => void;
}
export type Store = Action & State;
@@ -243,14 +248,40 @@ export const store: StateCreator<Store, [['zustand/devtools', never]]> = (set, g
set({ config: nextConfig }, false, payload);
- await get().onConfigChange?.(nextConfig);
+ if (get().onConfigChange) {
+ get().updateSaveStatus('saving');
+ try {
+ await get().onConfigChange?.(nextConfig);
+ get().updateSaveStatus('saved');
+ } catch (error: any) {
+ if (error?.name === 'AbortError' || error?.message?.includes('aborted')) {
+ get().updateSaveStatus('idle');
+ } else {
+ console.error('[AgentSettings] Failed to save config:', error);
+ get().updateSaveStatus('idle');
+ }
+ }
+ }
},
dispatchMeta: async (payload) => {
const nextValue = metaDataReducer(get().meta, payload);
set({ meta: nextValue }, false, payload);
- await get().onMetaChange?.(nextValue);
+ if (get().onMetaChange) {
+ get().updateSaveStatus('saving');
+ try {
+ await get().onMetaChange?.(nextValue);
+ get().updateSaveStatus('saved');
+ } catch (error: any) {
+ if (error?.name === 'AbortError' || error?.message?.includes('aborted')) {
+ get().updateSaveStatus('idle');
+ } else {
+ console.error('[AgentSettings] Failed to save meta:', error);
+ get().updateSaveStatus('idle');
+ }
+ }
+ }
},
getCurrentTracePayload: (data) => ({
sessionId: get().id,
@@ -339,4 +370,15 @@ export const store: StateCreator<Store, [['zustand/devtools', never]]> = (set, g
t('updateLoadingState', { key, value }),
);
},
+
+ updateSaveStatus: (status) => {
+ set(
+ {
+ lastUpdatedTime: status === 'saved' ? new Date() : get().lastUpdatedTime,
+ saveStatus: status,
+ },
+ false,
+ t('updateSaveStatus', { status }),
+ );
+ },
});
diff --git a/src/features/AgentSetting/store/initialState.ts b/src/features/AgentSetting/store/initialState.ts
index 7e73c6da5d8..9c9b98b38a4 100644
--- a/src/features/AgentSetting/store/initialState.ts
+++ b/src/features/AgentSetting/store/initialState.ts
@@ -4,19 +4,23 @@ import { LobeAgentConfig } from '@/types/agent';
import { MetaData } from '@/types/meta';
export type LoadingState = Record<Partial<keyof MetaData> | string, boolean>;
+export type SaveStatus = 'idle' | 'saving' | 'saved';
export interface State {
config: LobeAgentConfig;
id?: string;
+ lastUpdatedTime?: Date | null;
loading?: boolean;
loadingState?: LoadingState;
meta: MetaData;
onConfigChange?: (config: LobeAgentConfig) => void;
onMetaChange?: (meta: MetaData) => void;
+ saveStatus?: SaveStatus;
}
export const initialState: State = {
config: DEFAULT_AGENT_CONFIG,
+ lastUpdatedTime: null,
loading: true,
loadingState: {
avatar: false,
@@ -26,4 +30,5 @@ export const initialState: State = {
title: false,
},
meta: DEFAULT_AGENT_META,
+ saveStatus: 'idle',
};
diff --git a/src/features/AgentSetting/store/reducers/config.ts b/src/features/AgentSetting/store/reducers/config.ts
index 46411e72a78..508eb61ffb1 100644
--- a/src/features/AgentSetting/store/reducers/config.ts
+++ b/src/features/AgentSetting/store/reducers/config.ts
@@ -25,20 +25,25 @@ export const configReducer = (state: LobeAgentConfig, payload: ConfigDispatch):
}
if (typeof state === 'undefined') {
+ // @ts-ignore
if (config.plugins.includes(id)) {
+ // @ts-ignore
config.plugins.splice(config.plugins.indexOf(id), 1);
return;
}
-
+ // @ts-ignore
config.plugins.push(id);
return;
}
if (!state) {
- config.plugins = config.plugins.filter((pluginId) => pluginId !== id);
- } else {
- config.plugins.push(id);
+ // @ts-ignore
+ config.plugins = config?.plugins?.filter?.((pluginId) => pluginId !== id);
+ // @ts-ignore
+ } else if (!config?.plugins?.includes?.(id)) {
+ // @ts-ignore
+ config?.plugins?.push(id);
}
});
}
diff --git a/src/server/routers/lambda/market/index.ts b/src/server/routers/lambda/market/index.ts
index f9bcc692562..f189f44d570 100644
--- a/src/server/routers/lambda/market/index.ts
+++ b/src/server/routers/lambda/market/index.ts
@@ -573,6 +573,28 @@ export const marketRouter = router({
}
}),
+ // ============================== User Profile ==============================
+ getUserInfo: marketProcedure
+ .input(
+ z.object({
+ locale: z.string().optional(),
+ username: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ log('getUserInfo input: %O', input);
+
+ try {
+ return await ctx.discoverService.getUserInfo(input);
+ } catch (error) {
+ log('Error fetching user info: %O', error);
+ throw new TRPCError({
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'Failed to fetch user info',
+ });
+ }
+ }),
+
registerClientInMarketplace: marketProcedure.input(z.object({})).mutation(async ({ ctx }) => {
return ctx.discoverService.registerClient({
userAgent: ctx.userAgent,
@@ -644,6 +666,23 @@ export const marketRouter = router({
}
}),
+ reportAgentInstall: marketProcedure
+ .input(
+ z.object({
+ identifier: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ log('reportAgentInstall input: %O', input);
+ try {
+ await ctx.discoverService.increaseAgentInstallCount(input.identifier);
+ return { success: true };
+ } catch (error) {
+ log('Error reporting agent installation: %O', error);
+ return { success: false };
+ }
+ }),
+
// ============================== Analytics ==============================
reportCall: marketProcedure
.input(
diff --git a/src/server/services/discover/index.ts b/src/server/services/discover/index.ts
index 3e35b1135c6..346b0f403d7 100644
--- a/src/server/services/discover/index.ts
+++ b/src/server/services/discover/index.ts
@@ -3,9 +3,11 @@ import {
DEFAULT_DISCOVER_ASSISTANT_ITEM,
DEFAULT_DISCOVER_PLUGIN_ITEM,
DEFAULT_DISCOVER_PROVIDER_ITEM,
+ KLAVIS_SERVER_TYPES,
isDesktop,
} from '@lobechat/const';
import {
+ AgentStatus,
AssistantListResponse,
AssistantMarketSource,
AssistantQueryParams,
@@ -21,6 +23,7 @@ import {
DiscoverPluginItem,
DiscoverProviderDetail,
DiscoverProviderItem,
+ DiscoverUserProfile,
IdentifiersResponse,
McpListResponse,
McpQueryParams,
@@ -39,12 +42,12 @@ import {
getTextInputUnitRate,
getTextOutputUnitRate,
} from '@lobechat/utils';
-import { CategoryItem, CategoryListQuery, MarketSDK } from '@lobehub/market-sdk';
+import { CategoryItem, CategoryListQuery, MarketSDK, UserInfoResponse } from '@lobehub/market-sdk';
import { CallReportRequest, InstallReportRequest } from '@lobehub/market-types';
import dayjs from 'dayjs';
import debug from 'debug';
+import { cloneDeep, countBy, isString, merge, uniq, uniqBy } from 'es-toolkit/compat';
import matter from 'gray-matter';
-import { cloneDeep, countBy, isString, merge, uniq, uniqBy } from 'lodash-es';
import urlJoin from 'url-join';
import { normalizeLocale } from '@/locales/resources';
@@ -250,24 +253,32 @@ export class DiscoverService {
return result;
};
- private normalizeAuthorField = (author: unknown): string => {
- if (!author) return '';
+ private normalizeAuthorField = (author: unknown): { name: string; userName?: string } => {
+ if (!author) return { name: '' };
- if (typeof author === 'string') return author;
+ if (typeof author === 'string') return { name: author };
if (typeof author === 'object') {
- const { avatar, url, name } = author as {
+ const { avatar, url, name, userName } = author as {
avatar?: unknown;
name?: unknown;
url?: unknown;
+ userName?: unknown;
};
- if (typeof name === 'string' && name.length > 0) return name;
- if (typeof avatar === 'string' && avatar.length > 0) return avatar;
- if (typeof url === 'string' && url.length > 0) return url;
+ const authorName =
+ (typeof name === 'string' && name.length > 0 && name) ||
+ (typeof avatar === 'string' && avatar.length > 0 && avatar) ||
+ (typeof url === 'string' && url.length > 0 && url) ||
+ '';
+
+ return {
+ name: authorName,
+ userName: typeof userName === 'string' ? userName : undefined,
+ };
}
- return '';
+ return { name: '' };
};
private isLegacySource = (source?: AssistantMarketSource) => source === 'legacy';
@@ -568,13 +579,17 @@ export class DiscoverService {
const normalizedAuthor = this.normalizeAuthorField(data.author);
const assistant = {
- author: normalizedAuthor || (data.ownerId !== null ? `User${data.ownerId}` : 'Unknown'),
- avatar: data.avatar || normalizedAuthor || '',
+ author:
+ normalizedAuthor.name || (data.ownerId !== null ? `User${data.ownerId}` : 'Unknown'),
+ avatar: data.avatar || normalizedAuthor.name || '',
category: (data as any).category || 'general',
config: data.config || {},
createdAt: (data as any).createdAt,
currentVersion: data.version,
description: (data as any).description || data.summary,
+ // @ts-ignore
+ editorData: data.editorData || {},
+
examples: Array.isArray((data as any).examples)
? (data as any).examples.map((example: any) => ({
content: typeof example === 'string' ? example : example.content || '',
@@ -590,12 +605,13 @@ export class DiscoverService {
pluginCount: (data.config as any)?.plugins?.length || (data as any).pluginCount || 0,
readme: data.documentationUrl || '',
schemaVersion: 1,
- status: data.status,
+ status: (data.status as AgentStatus) || undefined,
summary: data.summary || '',
systemRole: (data.config as any)?.systemRole || '',
tags: data.tags || [],
title: (data as any).name || (data as any).identifier,
tokenUsage: data.tokenUsage || 0,
+ userName: normalizedAuthor.userName,
versions:
// @ts-ignore
data.versions?.map((item) => ({
@@ -708,20 +724,23 @@ export class DiscoverService {
const transformedItems: DiscoverAssistantItem[] = (data.items || []).map((item: any) => {
const normalizedAuthor = this.normalizeAuthorField(item.author);
return {
- author: normalizedAuthor || (item.ownerId !== null ? `User${item.ownerId}` : 'Unknown'),
- avatar: item.avatar || normalizedAuthor || '',
+ author:
+ normalizedAuthor.name || (item.ownerId !== null ? `User${item.ownerId}` : 'Unknown'),
+ avatar: item.avatar || normalizedAuthor.name || '',
category: item.category || 'general',
config: item.config || {},
createdAt: item.createdAt || item.updatedAt || new Date().toISOString(),
description: item.description || item.summary || '',
homepage: item.homepage || `https://lobehub.com/discover/assistant/${item.identifier}`,
identifier: item.identifier,
+ installCount: item.installCount,
knowledgeCount: item.knowledgeCount ?? item.config?.knowledgeBases?.length ?? 0,
pluginCount: item.pluginCount ?? item.config?.plugins?.length ?? 0,
schemaVersion: item.schemaVersion ?? 1,
tags: item.tags || [],
title: item.name || item.identifier,
tokenUsage: item.tokenUsage || 0,
+ userName: normalizedAuthor.userName,
};
});
@@ -859,6 +878,15 @@ export class DiscoverService {
await this.market.plugins.reportCall(params);
};
+ // ============================== Agent Analytics ==============================
+
+ /**
+ * Increase agent install count in marketplace
+ */
+ increaseAgentInstallCount = async (identifier: string) => {
+ await this.market.agents.increaseInstallCount(identifier);
+ };
+
// ============================== Plugin Market ==============================
private _getPluginList = async (locale?: string): Promise<DiscoverPluginItem[]> => {
@@ -1023,6 +1051,32 @@ export class DiscoverService {
return plugin;
}
+ // Step 4: Try to find in Klavis server types (builtin tools that require env config)
+ const klavisTool = KLAVIS_SERVER_TYPES.find((tool) => tool.identifier === identifier);
+ if (klavisTool) {
+ log('getPluginDetail: found Klavis tool for identifier=%s', identifier);
+
+ // Avatar is empty here because frontend will render Klavis icons using KlavisIcon component
+ // which handles both string URLs and React component icons
+ const plugin: DiscoverPluginDetail = {
+ author: 'Klavis',
+ avatar: typeof klavisTool.icon === 'string' ? klavisTool.icon : '',
+ category: undefined,
+ createdAt: '',
+ description: `LobeHub Mcp Server: ${klavisTool.label}`,
+ homepage: 'https://klavis.ai',
+ identifier: klavisTool.identifier,
+ manifest: undefined,
+ related: [],
+ schemaVersion: 1,
+ source: 'builtin',
+ tags: ['klavis', 'mcp'],
+ title: klavisTool.label,
+ };
+ log('getPluginDetail: returning Klavis tool plugin');
+ return plugin;
+ }
+
log('getPluginDetail: plugin not found anywhere for identifier=%s', identifier);
return;
};
@@ -1614,4 +1668,70 @@ export class DiscoverService {
);
return result;
};
+
+ // ============================== User Profile ==============================
+
+ /**
+ * Get user profile and their published agents by username
+ */
+ getUserInfo = async (params: {
+ locale?: string;
+ username: string;
+ }): Promise<DiscoverUserProfile | undefined> => {
+ log('getUserInfo: params=%O', params);
+ const { username, locale } = params;
+
+ try {
+ // Call Market SDK to get user info
+ const response: UserInfoResponse = await this.market.user.getUserInfo(username, { locale });
+
+ if (!response?.user) {
+ log('getUserInfo: user not found for username=%s', username);
+ return undefined;
+ }
+
+ const { user, agents } = response;
+
+ // Transform agents to DiscoverAssistantItem format
+ const transformedAgents: DiscoverAssistantItem[] = (agents || []).map((agent: any) => ({
+ author: user.displayName || user.userName || user.namespace || '',
+ avatar: agent.avatar || '',
+ category: agent.category as any,
+ config: {} as any,
+ createdAt: agent.createdAt,
+ description: agent.description || '',
+ homepage: `https://lobehub.com/discover/assistant/${agent.identifier}`,
+ identifier: agent.identifier,
+ installCount: agent.installCount,
+ knowledgeCount: agent.knowledgeCount || 0,
+ pluginCount: agent.pluginCount || 0,
+ schemaVersion: 1,
+ tags: agent.tags || [],
+ title: agent.name || agent.identifier,
+ tokenUsage: agent.tokenUsage || 0,
+ }));
+
+ const result: DiscoverUserProfile = {
+ agents: transformedAgents,
+ user: {
+ avatarUrl: user.avatarUrl || null,
+ bannerUrl: user.meta?.bannerUrl || null,
+ createdAt: user.createdAt,
+ description: user.meta?.description || null,
+ displayName: user.displayName || null,
+ id: user.id,
+ namespace: user.namespace,
+ socialLinks: user.meta?.socialLinks || null,
+ type: user.type || null,
+ userName: user.userName || null,
+ },
+ };
+
+ log('getUserInfo: returning user profile with %d agents', result.agents.length);
+ return result;
+ } catch (error) {
+ log('getUserInfo: error fetching user info: %O', error);
+ return undefined;
+ }
+ };
}
diff --git a/src/services/marketApi.ts b/src/services/marketApi.ts
index eda1f9cf100..6b7f1304a81 100644
--- a/src/services/marketApi.ts
+++ b/src/services/marketApi.ts
@@ -1,7 +1,12 @@
-import { AgentItemDetail } from '@lobehub/market-sdk';
+import { AgentItemDetail, AgentListResponse } from '@lobehub/market-sdk';
import { MARKET_ENDPOINTS } from '@/services/_url';
+interface GetOwnAgentsParams {
+ page?: number;
+ pageSize?: number;
+}
+
export class MarketApiService {
private accessToken?: string;
@@ -119,6 +124,43 @@ export class MarketApiService {
method: 'POST',
});
}
+
+ // Publish agent (make it visible in marketplace)
+ async publishAgent(identifier: string): Promise<void> {
+ return this.request(MARKET_ENDPOINTS.publishAgent(identifier), {
+ method: 'POST',
+ });
+ }
+
+ // Unpublish agent (hide from marketplace, can be republished)
+ async unpublishAgent(identifier: string): Promise<void> {
+ return this.request(MARKET_ENDPOINTS.unpublishAgent(identifier), {
+ method: 'POST',
+ });
+ }
+
+ // Deprecate agent (permanently hide, cannot be republished)
+ async deprecateAgent(identifier: string): Promise<void> {
+ return this.request(MARKET_ENDPOINTS.deprecateAgent(identifier), {
+ method: 'POST',
+ });
+ }
+
+ // Get own agents (requires authentication)
+ async getOwnAgents(params?: GetOwnAgentsParams): Promise<AgentListResponse> {
+ const searchParams = new URLSearchParams();
+ if (params?.page) searchParams.set('page', String(params.page));
+ if (params?.pageSize) searchParams.set('pageSize', String(params.pageSize));
+
+ const queryString = searchParams.toString();
+ const url = queryString
+ ? `${MARKET_ENDPOINTS.getOwnAgents}?${queryString}`
+ : MARKET_ENDPOINTS.getOwnAgents;
+
+ return this.request(url, {
+ method: 'GET',
+ });
+ }
}
export const marketApiService = new MarketApiService();
diff --git a/src/store/discover/slices/user/action.ts b/src/store/discover/slices/user/action.ts
new file mode 100644
index 00000000000..5cb685955ea
--- /dev/null
+++ b/src/store/discover/slices/user/action.ts
@@ -0,0 +1,29 @@
+import useSWR, { type SWRResponse } from 'swr';
+import type { StateCreator } from 'zustand/vanilla';
+
+import { discoverService } from '@/services/discover';
+import { DiscoverStore } from '@/store/discover';
+import { globalHelpers } from '@/store/global/helpers';
+import { DiscoverUserProfile } from '@/types/discover';
+
+export interface UserAction {
+ useUserProfile: (params: { username: string }) => SWRResponse<DiscoverUserProfile | undefined>;
+}
+
+export const createUserSlice: StateCreator<
+ DiscoverStore,
+ [['zustand/devtools', never]],
+ [],
+ UserAction
+> = () => ({
+ useUserProfile: (params) => {
+ const locale = globalHelpers.getCurrentLanguage();
+ return useSWR(
+ params.username ? ['user-profile', locale, params.username].join('-') : null,
+ async () => discoverService.getUserInfo({ username: params.username }),
+ {
+ revalidateOnFocus: false,
+ },
+ );
+ },
+});
diff --git a/src/store/discover/slices/user/index.ts b/src/store/discover/slices/user/index.ts
new file mode 100644
index 00000000000..2c0622fbb9c
--- /dev/null
+++ b/src/store/discover/slices/user/index.ts
@@ -0,0 +1 @@
+export * from './action';
diff --git a/src/store/discover/store.ts b/src/store/discover/store.ts
index baeea9b76c7..d8d85f6220b 100644
--- a/src/store/discover/store.ts
+++ b/src/store/discover/store.ts
@@ -8,6 +8,7 @@ import { MCPAction, createMCPSlice } from './slices/mcp';
import { ModelAction, createModelSlice } from './slices/model/action';
import { PluginAction, createPluginSlice } from './slices/plugin/action';
import { ProviderAction, createProviderSlice } from './slices/provider/action';
+import { UserAction, createUserSlice } from './slices/user';
// =============== Aggregate createStoreFn ============ //
@@ -15,7 +16,8 @@ export type DiscoverStore = MCPAction &
AssistantAction &
ProviderAction &
ModelAction &
- PluginAction;
+ PluginAction &
+ UserAction;
const createStore: StateCreator<DiscoverStore, [['zustand/devtools', never]]> = (
...parameters
@@ -25,6 +27,7 @@ const createStore: StateCreator<DiscoverStore, [['zustand/devtools', never]]> =
...createProviderSlice(...parameters),
...createModelSlice(...parameters),
...createPluginSlice(...parameters),
+ ...createUserSlice(...parameters),
});
// =============== Implement useStore ============ //