🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(agent-builder): accept nested config.meta and replace stale profiles (#17872)
AmAzing-242e3f511535
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.tsindex 2cbcbc1ce22..f6debb07e8a 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts@@ -173,6 +173,34 @@ describe('agentBuilderRuntime', () => {success: true,});});++ it('applies metadata nested under config instead of reporting a successful no-op', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });++ const runtime = createRuntime();+ const params = {+ config: {+ meta: {+ avatar: '🤖',+ title: 'GitHub PR/Issue Manager',+ },+ },+ } as unknown as Parameters<typeof runtime.updateConfig>[0];+ const result = await runtime.updateConfig(params, {+ editingAgentId: 'agent-1',+ toolManifestMap: {},+ });++ expect(result).toMatchObject({+ state: { agentId: 'agent-1', success: true },+ success: true,+ });+ expect(mockUpdateAgent).toHaveBeenCalledWith('agent-1', {+ avatar: '🤖',+ title: 'GitHub PR/Issue Manager',+ });+ expect(mockUpdateConfig).not.toHaveBeenCalled();+ });});describe('updatePrompt', () => {diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.tsindex 1a2858dc0a0..f81aaf41104 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts@@ -2,6 +2,7 @@ import {AgentBuilderIdentifier,type GetAvailableModelsParams,type InstallPluginParams,+ normalizeUpdateConfigParams,type SearchMarketToolsParams,type UpdateAgentConfigParams,type UpdatePromptParams,@@ -185,22 +186,7 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {return { content: `Agent "${agentId}" not found.`, success: false };}- let rawConfig: any = params.config;- if (typeof rawConfig === 'string') {- try {- rawConfig = JSON.parse(rawConfig);- } catch {- rawConfig = undefined;- }- }- let rawMeta: any = params.meta;- if (typeof rawMeta === 'string') {- try {- rawMeta = JSON.parse(rawMeta);- } catch {- rawMeta = undefined;- }- }+ const { config: rawConfig, meta: rawMeta } = normalizeUpdateConfigParams(params);let finalConfig = rawConfig ? { ...rawConfig } : {};const updatedParts: string[] = [];@@ -228,7 +214,12 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {}if (Object.keys(finalConfig).length > 0) {- await agentModel.updateConfig(agentId, finalConfig);+ // Domain tool plugins support structured entries, while the DB+ // model's JSONB column still carries its legacy string[] annotation.+ await agentModel.updateConfig(+ agentId,+ finalConfig as unknown as Parameters<typeof agentModel.updateConfig>[1],+ );const nonPluginFields = Object.keys(finalConfig).filter((f) => f !== 'plugins');if (nonPluginFields.length > 0) {updatedParts.push(`config fields: ${nonPluginFields.join(', ')}`);diff --git a/packages/builtin-tool-agent-builder/src/executor.test.ts b/packages/builtin-tool-agent-builder/src/executor.test.tsindex 7e87f304bd7..2a553f49d59 100644--- a/packages/builtin-tool-agent-builder/src/executor.test.ts+++ b/packages/builtin-tool-agent-builder/src/executor.test.ts@@ -9,15 +9,17 @@ const {mockFinishStreamingSystemRole,mockRefreshAgentConfig,mockStartStreamingSystemRole,+ mockUpdateAgentConfig,} = vi.hoisted(() => ({mockAppendStreamingSystemRole: vi.fn(),mockFinishStreamingSystemRole: vi.fn(),mockRefreshAgentConfig: vi.fn().mockResolvedValue(undefined),mockStartStreamingSystemRole: vi.fn(),+ mockUpdateAgentConfig: vi.fn(),}));vi.mock('@lobechat/agent-manager-runtime', () => ({- AgentManagerRuntime: vi.fn(() => ({})),+ AgentManagerRuntime: vi.fn(() => ({ updateAgentConfig: mockUpdateAgentConfig })),}));vi.mock('@/services/agent', () => ({ agentService: {} }));@@ -45,6 +47,32 @@ const createContext = (},});+describe('AgentBuilderExecutor.updateConfig', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockUpdateAgentConfig.mockResolvedValue({ content: 'updated', success: true });+ });++ it('normalizes metadata nested under config for client-side execution', async () => {+ const params = {+ config: {+ meta: { avatar: '🤖', title: 'GitHub PR/Issue Manager' },+ model: 'gpt-4o',+ },+ } as unknown as Parameters<typeof agentBuilderExecutor.updateConfig>[0];++ await agentBuilderExecutor.updateConfig(params, {+ agentId: 'target-agent',+ messageId: 'message-1',+ });++ expect(mockUpdateAgentConfig).toHaveBeenCalledWith('target-agent', {+ config: { model: 'gpt-4o' },+ meta: { avatar: '🤖', title: 'GitHub PR/Issue Manager' },+ });+ });+});+describe('AgentBuilderExecutor.onAfterCall', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/packages/builtin-tool-agent-builder/src/executor.ts b/packages/builtin-tool-agent-builder/src/executor.tsindex 15ce96c3f3c..55627393e8b 100644--- a/packages/builtin-tool-agent-builder/src/executor.ts+++ b/packages/builtin-tool-agent-builder/src/executor.ts@@ -13,6 +13,7 @@ import { agentService } from '@/services/agent';import { discoverService } from '@/services/discover';import { getAgentStoreState } from '@/store/agent';+import { normalizeUpdateConfigParams } from './normalizeUpdateConfigParams';import type {GetAvailableModelsParams,InstallPluginParams,@@ -67,7 +68,7 @@ class AgentBuilderExecutor extends BaseExecutor<typeof AgentBuilderApiName> {};}- return runtime.updateAgentConfig(agentId, params);+ return runtime.updateAgentConfig(agentId, normalizeUpdateConfigParams(params));};updatePrompt = async (diff --git a/packages/builtin-tool-agent-builder/src/index.ts b/packages/builtin-tool-agent-builder/src/index.tsindex 9bd9b9313b0..f370b4f11f8 100644--- a/packages/builtin-tool-agent-builder/src/index.ts+++ b/packages/builtin-tool-agent-builder/src/index.ts@@ -1,4 +1,5 @@export { AgentBuilderManifest } from './manifest';+export { normalizeUpdateConfigParams } from './normalizeUpdateConfigParams';export { systemPrompt } from './systemRole';export {AgentBuilderApiName,diff --git a/packages/builtin-tool-agent-builder/src/normalizeUpdateConfigParams.ts b/packages/builtin-tool-agent-builder/src/normalizeUpdateConfigParams.tsnew file mode 100644index 00000000000..8056f2d74f2--- /dev/null+++ b/packages/builtin-tool-agent-builder/src/normalizeUpdateConfigParams.ts@@ -0,0 +1,40 @@+import { toRecord } from '@lobechat/utils/object';+import { safeParseJSON } from '@lobechat/utils/safeParseJSON';++import type { UpdateAgentConfigParams } from './types';++const parseRecord = (value: unknown) =>+ toRecord(typeof value === 'string' ? safeParseJSON<unknown>(value) : value);++/**+ * Normalize model-generated updateConfig arguments at the tool boundary.+ *+ * Some models mirror the injected agent context and emit metadata as+ * `{ config: { meta: ... } }`, while the tool contract expects top-level+ * `{ meta: ... }`. Keep accepting that legacy shape, but never forward the+ * unknown `config.meta` field as an agent config update.+ */+export const normalizeUpdateConfigParams = (+ params: UpdateAgentConfigParams,+): UpdateAgentConfigParams => {+ const rawConfig = parseRecord(params.config);+ const nestedMeta = parseRecord(rawConfig?.meta);+ const explicitMeta = parseRecord(params.meta);++ const config = { ...rawConfig };+ delete config.meta;++ const meta = { ...nestedMeta, ...explicitMeta };++ return {+ ...params,+ config:+ Object.keys(config).length > 0+ ? (config as NonNullable<UpdateAgentConfigParams['config']>)+ : undefined,+ meta:+ Object.keys(meta).length > 0+ ? (meta as NonNullable<UpdateAgentConfigParams['meta']>)+ : undefined,+ };+};diff --git a/packages/builtin-tool-agent-builder/src/systemRole.ts b/packages/builtin-tool-agent-builder/src/systemRole.tsindex de0001a64f5..489989fe069 100644--- a/packages/builtin-tool-agent-builder/src/systemRole.ts+++ b/packages/builtin-tool-agent-builder/src/systemRole.ts@@ -49,33 +49,29 @@ You have access to tools that can modify agent configurations:Note: Official tools (built-in tools, Composio MCP servers, and LobehubSkill providers) are automatically available in the \`<current_agent_context>\` - no need to search for them.**Write Operations:**-- **updateConfig**: Update agent configuration fields (model, provider, plugins, and advanced settings). Use this for all config changes.-- **updateMeta**: Update agent metadata (title, description, avatar, tags, backgroundColor)+- **updateConfig**: Update agent configuration and metadata. Put model/provider/settings under \`config\`, and put title/description/avatar/tags/backgroundColor in the top-level \`meta\` argument.- **updatePrompt**: Update the agent's system prompt (the core instruction that defines agent behavior)-- **togglePlugin**: Enable or disable a specific plugin+- **updateConfig.togglePlugin**: Enable or disable a specific plugin- **installPlugin**: Install and enable a plugin from marketplace or official tools</capabilities><workflow>1. **Understand the request**: Listen carefully to what the user wants to configure2. **Reference injected context**: Use the \`<current_agent_context>\` to understand current configuration - no need to call read APIs-3. **Make targeted changes**: Use updateConfig for config changes, updateMeta for metadata, updatePrompt for system prompt, togglePlugin for plugin toggles+3. **Make targeted changes**: Use updateConfig for config, metadata, and plugin toggles; use updatePrompt for the system prompt4. **Confirm changes**: Report what was changed and the new values</workflow><modification_sequence>When creating or modifying an agent, follow this order:-**Step 1: Metadata & Identity**-Set avatar, name, title, description, tags, and backgroundColor first - establish who the agent is+**Step 1: Identity, Model & Tools**+Determine the metadata (including name and title), model, provider, and required tools together. Apply metadata and configuration in ONE updateConfig call with top-level \`meta\` and \`config\`; include \`togglePlugin\` in that call when applicable. Install marketplace plugins separately when needed.-**Step 2: Model & Tools**-Configure the AI model, provider, and enable necessary plugins/tools - define what capabilities the agent has--**Step 3: System Prompt**+**Step 2: System Prompt**Write or refine the system prompt last - this step benefits from knowing the agent's identity and available tools-This sequence ensures the system prompt can reference the agent's established identity and capabilities.+This sequence avoids separate updateConfig calls for metadata and configuration while ensuring the system prompt can reference the agent's established identity and capabilities.</modification_sequence><naming>@@ -129,8 +125,10 @@ Always adapt to user's language. Use natural descriptions, not raw field names.1. **Use injected context**: The current agent's config and meta are already available in the conversation context. Reference them directly instead of calling read APIs.2. **Explain your changes**: When modifying configurations, explain what you're changing and why it might benefit the user.3. **Use updateConfig for config changes**: For model, provider, or other config changes, use the updateConfig API.-4. **Batch config updates together**: When multiple config fields need to be updated, ALWAYS merge them into a single updateConfig call instead of making multiple sequential calls. This prevents race conditions and provides a better user experience.- - ✅ Good: Use updateConfig with { config: { model: "claude-sonnet-4-5-20250929", temperature: 0.7, openingMessage: "Hello!" } }+4. **Batch agent updates together**: When metadata and configuration need to be updated together, ALWAYS include top-level \`meta\` and \`config\` in a single updateConfig call instead of making multiple sequential calls. This prevents race conditions and provides a better user experience.+ - ✅ Good: Use updateConfig with { config: { model: "claude-sonnet-4-5-20250929", params: { temperature: 0.7 }, openingMessage: "Hello!" } }+ - ✅ Metadata: Use updateConfig with { meta: { title: "Research Assistant", avatar: "🔬" } }+ - ❌ Never nest metadata under config, such as { config: { meta: { title: "Research Assistant" } } }- ❌ Bad: Multiple sequential updateConfig calls for different fields- Exception: If you must make multiple updateConfig calls (e.g., due to complex logic or different update contexts), ALWAYS report the changes after each update before proceeding to the next one.5. **Validate user intent**: For significant changes (like changing the model or disabling important plugins), confirm with the user before proceeding.@@ -193,16 +191,14 @@ Always adapt to user's language. Use natural descriptions, not raw field names.<examples>User: "健康助手,咨询健康问题" (short phrase — agent name + purpose)Action: Treat as a configuration request, NOT a health consultation. Follow the modification sequence:-1. Use updateMeta to set identity: { avatar: "🏥", title: "健康助手", description: "专注于健康咨询的 AI 助手" }-2. Use updateConfig to set a suitable model-3. Use updatePrompt to write a system prompt for a health consultant+1. Choose a suitable model and provider from the injected context, then make ONE updateConfig call containing both { meta: { avatar: "🏥", title: "健康助手", description: "专注于健康咨询的 AI 助手" } } and a config object with the chosen model and provider+2. Use updatePrompt to write a system prompt for a health consultantDo NOT respond as a health assistant or provide health advice. You are configuring the agent on the left panel to become a health assistant.User: "帮我创建一个代码助手" / "Help me create a coding assistant"Action: Follow the modification sequence:-1. First, use updateMeta to set identity: { avatar: "👨💻", title: "Code Assistant", description: "A helpful coding assistant for debugging and writing code" }-2. Then, use updateConfig to set model and tools: { config: { model: "claude-sonnet-4-5-20250929", provider: "anthropic" } } and enable relevant plugins-3. Finally, use updatePrompt to write the system prompt that references the established identity and tools+1. First, make ONE updateConfig call containing both { meta: { avatar: "👨💻", title: "Code Assistant", description: "A helpful coding assistant for debugging and writing code" }, config: { model: "claude-sonnet-4-5-20250929", provider: "anthropic" } }, and enable relevant plugins in that same call when applicable+2. Finally, use updatePrompt to write the system prompt that references the established identity and toolsUser: "帮我把模型改成 Claude"Action: Reference the current model from injected context, then use updateConfig with { config: { model: "claude-sonnet-4-5-20250929", provider: "anthropic" } }@@ -219,7 +215,7 @@ Then report all changes made in a single summary.This creates unnecessary multiple operations and poor user experience.User: "Enable web browsing for this agent"-Action: Use togglePlugin with pluginId "lobe-web-browsing" and enabled: true+Action: Use updateConfig with { togglePlugin: { pluginId: "lobe-web-browsing", enabled: true } }User: "What's my current configuration?" / "告诉我现在的配置"Action: Reference the \`<current_agent_context>\` and display all settings using semantic names (e.g., "开场白" instead of "openingMessage", "创意度" instead of "temperature"). Present information in a clear, organized manner.diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsindex 376fd46f675..3176ad8d9c2 100644--- a/src/store/agent/slices/agent/action.test.ts+++ b/src/store/agent/slices/agent/action.test.ts@@ -320,6 +320,35 @@ describe('AgentSlice Actions', () => {// The background fetch only populates agentMap; it must not steal the active agent.expect(result.current.activeAgentId).toBe('routed-agent');});++ it('replaces a stale profile snapshot so omitted editorData is cleared', async () => {+ useAgentStore.setState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ editorData: { root: { children: [{ text: 'Old prompt' }] } },+ id: 'agent-1',+ systemRole: 'Old prompt',+ } as any,+ },+ });+ vi.mocked(agentService.getAgentConfigById).mockResolvedValue({+ id: 'agent-1',+ systemRole: 'New prompt from Agent Builder',+ } as any);++ renderHook(() => useAgentStore().useFetchAgentConfig(true, 'agent-1'), {+ wrapper: withSWR,+ });++ await waitFor(() => {+ expect(useAgentStore.getState().agentMap['agent-1']).toEqual({+ id: 'agent-1',+ systemRole: 'New prompt from Agent Builder',+ });+ });+ expect(useAgentStore.getState().agentMap['agent-1']).not.toHaveProperty('editorData');+ });});describe('invalidateAvailableAgents', () => {diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsindex 165787c2555..aea8a843fe2 100644--- a/src/store/agent/slices/agent/action.ts+++ b/src/store/agent/slices/agent/action.ts@@ -409,7 +409,17 @@ export class AgentSliceActionImpl {return;}this.#clearAgentNotFound(agentId);- this.#get().internal_dispatchAgentMap(agentId, data);+ // This endpoint returns a complete, authoritative profile snapshot.+ // Replace the cached entry instead of applying patch semantics: fields+ // cleared on the server (for example editorData: null) may be omitted+ // from the response and must not survive from an older local profile.+ if (!isEqual(this.#get().agentMap[agentId], data)) {+ this.#set(+ (state) => ({ agentMap: { ...state.agentMap, [agentId]: data } }),+ false,+ 'fetchAgentConfig',+ );+ }// Only adopt the fetched agent as the active one when nothing is// active yet. The active agent is owned by the route-level sync// (AgentIdSync on desktop/mobile, the popup pages' own setState).