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: export agent profiles as Markdown (#15312)

YuTengjing2657b667bea7
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 779f3cc3be6..1902e84f8d6 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -513,6 +513,16 @@
"settingAgent.description.desc": "A brief introduction to your agent, not for character setting",
"settingAgent.description.placeholder": "Enter agent description",
"settingAgent.description.title": "Agent Description",
+ "settingAgent.export.dialogTitle": "Export Agent Profile",
+ "settingAgent.export.enabledPlugins": "Enabled Skills",
+ "settingAgent.export.error": "Failed to export the agent profile",
+ "settingAgent.export.metadata": "Metadata",
+ "settingAgent.export.model": "Model",
+ "settingAgent.export.provider": "Provider",
+ "settingAgent.export.success": "Agent profile exported successfully",
+ "settingAgent.export.tags": "Tags",
+ "settingAgent.export.untitled": "Untitled Agent",
+ "settingAgent.export.untitledFileName": "agent-profile",
"settingAgent.name.placeholder": "Enter agent name",
"settingAgent.name.title": "Name",
"settingAgent.prompt.placeholder": "Enter agent settings, press / to open the command menu",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 76f8834d27f..f6eb03fbf62 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -513,6 +513,16 @@
"settingAgent.description.desc": "简单介绍你的助理,不作为角色设定",
"settingAgent.description.placeholder": "请输入助理描述",
"settingAgent.description.title": "助理描述",
+ "settingAgent.export.dialogTitle": "导出助理档案",
+ "settingAgent.export.enabledPlugins": "已启用技能",
+ "settingAgent.export.error": "助理档案导出失败",
+ "settingAgent.export.metadata": "元信息",
+ "settingAgent.export.model": "模型",
+ "settingAgent.export.provider": "服务商",
+ "settingAgent.export.success": "助理档案导出成功",
+ "settingAgent.export.tags": "标签",
+ "settingAgent.export.untitled": "未命名助理",
+ "settingAgent.export.untitledFileName": "助理档案",
"settingAgent.name.placeholder": "请输入助理名称",
"settingAgent.name.title": "名称",
"settingAgent.prompt.placeholder": "输入助理设定,按 / 打开命令菜单",
diff --git a/packages/builtin-tool-agent-builder/src/systemRole.ts b/packages/builtin-tool-agent-builder/src/systemRole.ts
index f50b44fbd47..bc25d4f8e0d 100644
--- a/packages/builtin-tool-agent-builder/src/systemRole.ts
+++ b/packages/builtin-tool-agent-builder/src/systemRole.ts
@@ -11,7 +11,7 @@ export const systemPrompt = `You are an Agent Configuration Assistant integrated
The injected context includes:
- **agent_meta**: title, description, avatar, backgroundColor, tags
-- **agent_config**: model, provider, plugins, systemRole (preview), and other advanced settings
+- **agent_config**: model, provider, plugins, systemRole (truncated only when over 10000 characters), and other advanced settings
- **official_tools**: List of available official tools including built-in tools, Klavis MCP servers, and LobehubSkill providers (Linear, Outlook Calendar, Twitter, etc.) with their enabled/installed status
You should use this context to understand the current state of the agent and available tools before making any modifications.
@@ -175,7 +175,7 @@ User: "I want to use a model with vision capabilities"
Action: Use getAvailableModels to find models with vision capability, then recommend suitable options and use updateConfig to change if user confirms
User: "Show me the current prompt"
-Action: Reference the systemRole from the injected \`<current_agent_context>\` and display it
+Action: Reference the systemRole from the injected \`<current_agent_context>\` and display it. If it ends with "...", mention that the injected context was truncated.
User: "Change the prompt to make the agent act as a coding assistant"
Action: Reference the current systemRole from context, then use updatePrompt with a new prompt like "You are a helpful coding assistant. Help users write, debug, and explain code in any programming language."
diff --git a/packages/context-engine/src/providers/AgentBuilderContextInjector.ts b/packages/context-engine/src/providers/AgentBuilderContextInjector.ts
index 050eef15b2a..5f19906c8ce 100644
--- a/packages/context-engine/src/providers/AgentBuilderContextInjector.ts
+++ b/packages/context-engine/src/providers/AgentBuilderContextInjector.ts
@@ -12,6 +12,8 @@ declare module '../types' {
const log = debug('context-engine:provider:AgentBuilderContextInjector');
+const SYSTEM_ROLE_CONTEXT_PREVIEW_LENGTH = 10_000;
+
/**
* Official tool item for Agent Builder context
*/
@@ -112,13 +114,13 @@ const defaultFormatAgentContext = (context: AgentBuilderContext): string => {
configFields.push(` <openingQuestions>\n${questions}\n </openingQuestions>`);
}
if (context.config.systemRole) {
- // For system role, show preview (first 500 chars) to avoid too long context
- const preview =
- context.config.systemRole.length > 500
- ? context.config.systemRole.slice(0, 500) + '...'
+ const systemRole =
+ context.config.systemRole.length > SYSTEM_ROLE_CONTEXT_PREVIEW_LENGTH
+ ? `${context.config.systemRole.slice(0, SYSTEM_ROLE_CONTEXT_PREVIEW_LENGTH)}...`
: context.config.systemRole;
+
configFields.push(
- ` <systemRole length="${context.config.systemRole.length}">${escapeXml(preview)}</systemRole>`,
+ ` <systemRole length="${context.config.systemRole.length}">${escapeXml(systemRole)}</systemRole>`,
);
}
diff --git a/packages/context-engine/src/providers/__tests__/AgentBuilderContextInjector.test.ts b/packages/context-engine/src/providers/__tests__/AgentBuilderContextInjector.test.ts
new file mode 100644
index 00000000000..992c7c2bca3
--- /dev/null
+++ b/packages/context-engine/src/providers/__tests__/AgentBuilderContextInjector.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { AgentBuilderContextInjector } from '../AgentBuilderContextInjector';
+
+describe('AgentBuilderContextInjector', () => {
+ const createContext = (): PipelineContext => ({
+ initialState: { messages: [] },
+ isAborted: false,
+ messages: [
+ { role: 'system', content: 'sys' },
+ { role: 'user', content: 'hi' },
+ ],
+ metadata: {},
+ });
+
+ it('should include the full systemRole when it is under the preview limit', async () => {
+ const head = 'A'.repeat(1622);
+ const tail = '\n## Tail section\nKeep this content visible.';
+ const systemRole = `${head}${tail}`;
+ const injector = new AgentBuilderContextInjector({
+ agentContext: {
+ config: { systemRole },
+ },
+ enabled: true,
+ });
+
+ const result = await injector.process(createContext());
+ const injected = result.messages[1].content;
+
+ expect(injected).toContain(`<systemRole length="${systemRole.length}">`);
+ expect(injected).toContain(tail);
+ expect(injected).not.toContain(`${head}...`);
+ });
+
+ it('should truncate the systemRole only after 10000 characters', async () => {
+ const head = 'A'.repeat(10_000);
+ const tail = '\n## Hidden tail\nThis should not be injected.';
+ const systemRole = `${head}${tail}`;
+ const injector = new AgentBuilderContextInjector({
+ agentContext: {
+ config: { systemRole },
+ },
+ enabled: true,
+ });
+
+ const result = await injector.process(createContext());
+ const injected = result.messages[1].content;
+
+ expect(injected).toContain(`<systemRole length="${systemRole.length}">`);
+ expect(injected).toContain(`${head}...`);
+ expect(injected).not.toContain(tail);
+ });
+});
diff --git a/src/locales/default/setting.ts b/src/locales/default/setting.ts
index acb4865605d..250d760d829 100644
--- a/src/locales/default/setting.ts
+++ b/src/locales/default/setting.ts
@@ -565,6 +565,16 @@ export default {
'settingAgent.description.desc': 'A brief introduction to your agent, not for character setting',
'settingAgent.description.placeholder': 'Enter agent description',
'settingAgent.description.title': 'Agent Description',
+ 'settingAgent.export.dialogTitle': 'Export Agent Profile',
+ 'settingAgent.export.enabledPlugins': 'Enabled Skills',
+ 'settingAgent.export.error': 'Failed to export the agent profile',
+ 'settingAgent.export.metadata': 'Metadata',
+ 'settingAgent.export.model': 'Model',
+ 'settingAgent.export.provider': 'Provider',
+ 'settingAgent.export.success': 'Agent profile exported successfully',
+ 'settingAgent.export.tags': 'Tags',
+ 'settingAgent.export.untitled': 'Untitled Agent',
+ 'settingAgent.export.untitledFileName': 'agent-profile',
'settingAgent.name.placeholder': 'Enter agent name',
'settingAgent.name.title': 'Name',
'settingAgent.prompt.placeholder': 'Enter agent settings, press / to open the command menu',
diff --git a/src/routes/(main)/agent/profile/features/Header/index.test.tsx b/src/routes/(main)/agent/profile/features/Header/index.test.tsx
index 4f8d8b4002c..4519fa4f53a 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.test.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.test.tsx
@@ -1,4 +1,4 @@
-import { render, screen } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { PropsWithChildren, ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -8,8 +8,15 @@ const mocks = vi.hoisted(() => ({
agentState: {
activeAgentId: 'agent-1',
canCurrentAgentPublishToCommunity: true,
+ config: {
+ model: 'gpt-4o',
+ plugins: ['lobe-web-browsing'],
+ provider: 'openai',
+ },
isCurrentAgentHeterogeneous: false,
meta: {
+ description: 'Test description',
+ tags: ['test'],
title: 'Test Agent',
},
systemRole: 'You are helpful.',
@@ -38,25 +45,41 @@ const mocks = vi.hoisted(() => ({
},
}));
+vi.mock('@lobechat/const', () => ({
+ isDesktop: false,
+}));
+
+interface MockDropdownItem {
+ children?: MockDropdownItem[];
+ key?: string;
+ label?: ReactNode;
+ onClick?: () => void;
+ type?: string;
+}
+
+const renderMenuItems = (items: MockDropdownItem[]) =>
+ items
+ .filter((item) => item.type !== 'divider')
+ .map((item) => (
+ <div key={item.key}>
+ <button type="button" onClick={item.onClick}>
+ {item.label}
+ </button>
+ {item.children && <div>{renderMenuItems(item.children)}</div>}
+ </div>
+ ));
+
vi.mock('@lobehub/ui', () => ({
ActionIcon: () => <button aria-label="more" type="button" />,
DropdownMenu: ({
children,
items = [],
}: PropsWithChildren<{
- items?: Array<{ key?: string; label?: ReactNode; type?: string }>;
+ items?: MockDropdownItem[];
}>) => (
<div>
{children}
- <div data-testid="agent-profile-menu">
- {items
- .filter((item) => item.type !== 'divider')
- .map((item) => (
- <button key={item.key} type="button">
- {item.label}
- </button>
- ))}
- </div>
+ <div data-testid="agent-profile-menu">{renderMenuItems(items)}</div>
</div>
),
Flexbox: ({ children }: PropsWithChildren) => <div>{children}</div>,
@@ -86,6 +109,7 @@ vi.mock('antd', () => ({
vi.mock('lucide-react', () => ({
BotMessageSquareIcon: () => null,
+ Download: () => null,
MoreHorizontal: () => null,
Settings2Icon: () => null,
Trash: () => null,
@@ -143,6 +167,7 @@ vi.mock('@/store/agent/selectors', () => ({
agentSelectors: {
canCurrentAgentPublishToCommunity: (state: typeof mocks.agentState) =>
state.canCurrentAgentPublishToCommunity,
+ currentAgentConfig: (state: typeof mocks.agentState) => state.config,
currentAgentMeta: (state: typeof mocks.agentState) => state.meta,
currentAgentSystemRole: (state: typeof mocks.agentState) => state.systemRole,
isCurrentAgentHeterogeneous: (state: typeof mocks.agentState) =>
@@ -166,6 +191,11 @@ vi.mock('@/store/home', () => ({
useHomeStore: (selector: (state: typeof mocks.homeState) => unknown) => selector(mocks.homeState),
}));
+vi.mock('../store', () => ({
+ useProfileStore: (selector: (state: { editor: undefined }) => unknown) =>
+ selector({ editor: undefined }),
+}));
+
vi.mock('./AgentForkTag', () => ({
default: () => null,
}));
@@ -197,6 +227,9 @@ vi.mock('./AgentVersionReviewTag', () => ({
describe('Agent profile Header', () => {
beforeEach(() => {
+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
+ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:agent-profile');
+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
mocks.agentState.canCurrentAgentPublishToCommunity = true;
mocks.agentState.isCurrentAgentHeterogeneous = false;
});
@@ -207,6 +240,29 @@ describe('Agent profile Header', () => {
expect(screen.getByRole('button', { name: 'publishToCommunity' })).toBeInTheDocument();
});
+ it('should show the markdown export action', () => {
+ render(<Header />);
+
+ expect(screen.getByRole('button', { name: 'pageEditor.menu.export' })).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', { name: 'pageEditor.menu.export.markdown' }),
+ ).toBeInTheDocument();
+ });
+
+ it('should export the current agent profile as markdown', async () => {
+ render(<Header />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'pageEditor.menu.export.markdown' }));
+
+ await waitFor(() => expect(URL.createObjectURL).toHaveBeenCalled());
+
+ const exportedBlob = vi.mocked(URL.createObjectURL).mock.calls[0][0] as Blob;
+ await expect(exportedBlob.text()).resolves.toContain('# Test Agent');
+ await expect(exportedBlob.text()).resolves.toContain('You are helpful.');
+ expect(HTMLAnchorElement.prototype.click).toHaveBeenCalled();
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:agent-profile');
+ });
+
it('should hide the community publish action for heterogeneous and platform agents', () => {
mocks.agentState.canCurrentAgentPublishToCommunity = false;
mocks.agentState.isCurrentAgentHeterogeneous = true;
diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsx
index d0ed3cc87a7..38f0dbdea9c 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx
@@ -1,8 +1,10 @@
+import { isDesktop } from '@lobechat/const';
import { ActionIcon, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { ShapesUploadIcon } from '@lobehub/ui/icons';
import isEqual from 'fast-deep-equal';
-import { BotMessageSquareIcon, MoreHorizontal, Settings2Icon, Trash } from 'lucide-react';
+import type { TFunction } from 'i18next';
+import { BotMessageSquareIcon, Download, MoreHorizontal, Settings2Icon, Trash } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -18,7 +20,9 @@ import { agentSelectors } from '@/store/agent/selectors';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useHomeStore } from '@/store/home';
+import { sanitizeFileName } from '@/utils/sanitizeFileName';
+import { useProfileStore } from '../store';
import AgentForkTag from './AgentForkTag';
import ForkConfirmModal from './AgentPublishButton/ForkConfirmModal';
import PublishResultModal from './AgentPublishButton/PublishResultModal';
@@ -27,11 +31,66 @@ import AgentStatusTag from './AgentStatusTag';
import AgentVersionReviewTag, { useVersionReviewStatus } from './AgentVersionReviewTag';
import AutoSaveHint from './AutoSaveHint';
+type HeaderTranslation = TFunction<
+ readonly ['setting', 'marketAuth', 'chat', 'file', 'common'],
+ undefined
+>;
+
+const buildAgentProfileMarkdown = (params: {
+ description?: string;
+ model?: string;
+ plugins?: string[];
+ provider?: string;
+ systemRole?: string;
+ t: HeaderTranslation;
+ tags?: string[];
+ title?: string;
+}) => {
+ const { description, model, plugins = [], provider, systemRole, t, tags = [], title } = params;
+ const sections: string[] = [];
+ const agentTitle = title?.trim() || t('settingAgent.export.untitled', { ns: 'setting' });
+
+ sections.push(`# ${agentTitle}`);
+
+ if (description?.trim()) sections.push(description.trim());
+
+ const metadata = [
+ provider ? `- ${t('settingAgent.export.provider', { ns: 'setting' })}: ${provider}` : undefined,
+ model ? `- ${t('settingAgent.export.model', { ns: 'setting' })}: ${model}` : undefined,
+ tags.length > 0
+ ? `- ${t('settingAgent.export.tags', { ns: 'setting' })}: ${tags.join(', ')}`
+ : undefined,
+ ].filter(Boolean);
+
+ if (metadata.length > 0) {
+ sections.push(
+ `## ${t('settingAgent.export.metadata', { ns: 'setting' })}\n\n${metadata.join('\n')}`,
+ );
+ }
+
+ if (plugins.length > 0) {
+ sections.push(
+ `## ${t('settingAgent.export.enabledPlugins', { ns: 'setting' })}\n\n${plugins
+ .map((plugin) => `- ${plugin}`)
+ .join('\n')}`,
+ );
+ }
+
+ if (systemRole?.trim()) {
+ sections.push(
+ `## ${t('settingAgent.prompt.title', { ns: 'setting' })}\n\n${systemRole.trim()}`,
+ );
+ }
+
+ return `${sections.join('\n\n')}\n`;
+};
+
const Header = memo(() => {
- const { t } = useTranslation(['setting', 'marketAuth', 'chat']);
+ const { t } = useTranslation(['setting', 'marketAuth', 'chat', 'file', 'common']);
const navigate = useNavigate();
const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
+ const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);
const systemRole = useAgentStore(agentSelectors.currentAgentSystemRole);
const activeAgentId = useAgentStore((s) => s.activeAgentId);
const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
@@ -42,6 +101,7 @@ const Header = memo(() => {
systemStatusSelectors.isStatusInit(s),
]);
const removeAgent = useHomeStore((s) => s.removeAgent);
+ const editor = useProfileStore((s) => s.editor);
const { isAuthenticated, isLoading: isAuthLoading, signIn } = useMarketAuth();
const { isUnderReview } = useVersionReviewStatus();
@@ -137,6 +197,51 @@ const Header = memo(() => {
});
}, [activeAgentId, navigate, removeAgent, t]);
+ const handleExportMarkdown = useCallback(async () => {
+ try {
+ const editorMarkdown = editor?.getDocument('markdown') as string | undefined;
+ const profileMarkdown = buildAgentProfileMarkdown({
+ description: meta?.description,
+ model: config.model,
+ plugins: config.plugins,
+ provider: config.provider,
+ systemRole: editorMarkdown || systemRole,
+ t,
+ tags: meta?.tags,
+ title: meta?.title,
+ });
+ const baseFileName = sanitizeFileName(
+ meta?.title || '',
+ t('settingAgent.export.untitledFileName', { ns: 'setting' }),
+ );
+ const fileName = `${baseFileName}.md`;
+
+ if (isDesktop) {
+ const { desktopExportService } = await import('@/services/electron/desktopExportService');
+ await desktopExportService.exportMarkdown({
+ content: profileMarkdown,
+ dialogTitle: t('settingAgent.export.dialogTitle', { ns: 'setting' }),
+ fileName,
+ successTitle: t('settingAgent.export.success', { ns: 'setting' }),
+ });
+ } else {
+ const blob = new Blob([profileMarkdown], { type: 'text/markdown' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = fileName;
+ document.body.append(a);
+ a.click();
+ a.remove();
+ URL.revokeObjectURL(url);
+ message.success(t('settingAgent.export.success', { ns: 'setting' }));
+ }
+ } catch (error) {
+ console.error('Failed to export agent profile markdown:', error);
+ message.error(t('settingAgent.export.error', { ns: 'setting' }));
+ }
+ }, [config.model, config.plugins, config.provider, editor, meta, systemRole, t]);
+
const menuItems = useMemo(
() => [
{
@@ -157,6 +262,19 @@ const Header = memo(() => {
{ type: 'divider' as const },
]
: []),
+ {
+ children: [
+ {
+ key: 'export-markdown',
+ label: t('pageEditor.menu.export.markdown', { ns: 'file' }),
+ onClick: handleExportMarkdown,
+ },
+ ],
+ icon: <Icon icon={Download} />,
+ key: 'export',
+ label: t('pageEditor.menu.export', { ns: 'file' }),
+ },
+ { type: 'divider' as const },
{
danger: true,
icon: <Icon icon={Trash} />,
@@ -165,7 +283,7 @@ const Header = memo(() => {
onClick: handleDelete,
},
],
- [canPublishToCommunity, handlePublishClick, handleDelete, t],
+ [canPublishToCommunity, handlePublishClick, handleExportMarkdown, handleDelete, t],
);
return (
diff --git a/src/services/electron/desktopExportService.tsx b/src/services/electron/desktopExportService.tsx
index 2d0e7cb9a00..8b4137201ad 100644
--- a/src/services/electron/desktopExportService.tsx
+++ b/src/services/electron/desktopExportService.tsx
@@ -5,7 +5,9 @@ import { localFileService } from './localFileService';
export interface DesktopExportOptions {
content: string;
+ dialogTitle?: string;
fileName: string;
+ successTitle?: string;
}
export interface DesktopExportResult {
@@ -15,12 +17,12 @@ export interface DesktopExportResult {
class DesktopExportService {
async exportMarkdown(options: DesktopExportOptions): Promise<DesktopExportResult> {
- const { content, fileName } = options;
+ const { content, dialogTitle, fileName, successTitle } = options;
const result = await localFileService.showSaveDialog({
defaultPath: fileName,
filters: [{ extensions: ['md'], name: 'Markdown' }],
- title: i18next.t('pageEditor.exportDialogTitle', { ns: 'file' }),
+ title: dialogTitle || i18next.t('pageEditor.exportDialogTitle', { ns: 'file' }),
});
if (result.canceled || !result.filePath) {
@@ -32,12 +34,12 @@ class DesktopExportService {
path: result.filePath,
});
- this.showExportSuccessToast(result.filePath);
+ this.showExportSuccessToast(result.filePath, successTitle);
return { canceled: false, filePath: result.filePath };
}
- private showExportSuccessToast(filePath: string) {
+ private showExportSuccessToast(filePath: string, successTitle?: string) {
const t = i18next.t.bind(i18next);
toast.success({
@@ -53,7 +55,7 @@ class DesktopExportService {
variant: 'primary',
},
],
- title: t('pageEditor.exportSuccess', { ns: 'file' }),
+ title: successTitle || t('pageEditor.exportSuccess', { ns: 'file' }),
});
}
}