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.

🐛 fix(agent-builder): correct target agentId and refresh sidebar in gateway mode (#15888)

LiJiand3fbc194732f
diff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
index 0b0360132d4..f6aafbdce1f 100644
--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
@@ -2661,6 +2661,7 @@ export const createRuntimeExecutors = (
payload.parentMessageId,
),
documentId: state.metadata?.documentId,
+ editingAgentId: state.metadata?.editingAgentId,
execSubAgent: ctx.execSubAgent,
executionTimeoutMs: timeoutMs,
groupId: state.metadata?.groupId,
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 69695eff14a..11408c51c32 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -139,6 +139,8 @@ const ExecAgentSchema = z
.object({
defaultTaskAssigneeAgentId: z.string().optional(),
documentId: z.string().optional().nullable(),
+ /** The agent being edited when scope is 'agent_builder' (not the builder builtin itself). */
+ editingAgentId: z.string().optional(),
groupId: z.string().optional().nullable(),
initialTopicMetadata: z
.object({
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 497b6529a3e..0d564b57cb1 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -2713,6 +2713,13 @@ export class AiAgentService {
// context (state.metadata.agentId) targets the reviewed agent; ordinary
// runs (no marker) fall back to the resolved executing agent.
agentId: appContext?.agentSignal?.agentId ?? resolvedAgentId,
+ // When scope === 'agent_builder', agentId stays as the builder builtin so
+ // message ownership and queryUiMessages remain correct. editingAgentId
+ // carries the actual editing target separately; only the AgentBuilder server
+ // runtime reads it, keeping the rest of the pipeline unaffected.
+ ...(appContext?.scope === 'agent_builder' && appContext?.editingAgentId
+ ? { editingAgentId: appContext.editingAgentId }
+ : {}),
// Run-scoped Agent Signal marker for background self-iteration / memory
// runs — lands in state.metadata.agentSignal so the completion path can
// project receipts/briefs. Undefined for ordinary chat runs.
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts
index 6e0783967b7..6e1ca926830 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts
@@ -152,7 +152,7 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {
params: UpdateAgentConfigParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const agentId = ctx.agentId;
+ const agentId = ctx.editingAgentId ?? ctx.agentId;
if (!agentId) {
return {
@@ -240,7 +240,7 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {
params: UpdatePromptParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const agentId = ctx.agentId;
+ const agentId = ctx.editingAgentId ?? ctx.agentId;
if (!agentId) {
return {
@@ -272,7 +272,7 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {
params: InstallPluginParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const agentId = ctx.agentId;
+ const agentId = ctx.editingAgentId ?? ctx.agentId;
if (!agentId) {
return {
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index 7628804f604..74389b6a4d1 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -121,6 +121,12 @@ export interface ToolExecutionContext {
agentMember?: ServerAgentMemberRunner;
/** Current page document ID for page-scoped conversations */
documentId?: string | null;
+ /**
+ * When scope is 'agent_builder', the ID of the agent being edited. Kept
+ * separate from agentId so message ownership and queryUiMessages remain
+ * bound to the builder builtin; only AgentBuilder tool methods read this.
+ */
+ editingAgentId?: string;
/**
* Legacy agent invocation callback forwarded from RuntimeExecutorContext.
* Kept for tool runtimes that still dispatch through exec_sub_agent style
diff --git a/packages/builtin-tool-agent-builder/src/executor.ts b/packages/builtin-tool-agent-builder/src/executor.ts
index eee5da486fe..fec348a628f 100644
--- a/packages/builtin-tool-agent-builder/src/executor.ts
+++ b/packages/builtin-tool-agent-builder/src/executor.ts
@@ -5,9 +5,11 @@
* Delegates to AgentManagerRuntime for actual implementation.
*/
import { AgentManagerRuntime } from '@lobechat/agent-manager-runtime';
-import type { BuiltinToolContext, BuiltinToolResult } from '@lobechat/types';
+import type { BuiltinToolContext, BuiltinToolResult, ToolAfterCallContext } from '@lobechat/types';
import { BaseExecutor } from '@lobechat/types';
+import { getAgentStoreState } from '@/store/agent';
+import { getChatStoreState } from '@/store/chat';
import { agentService } from '@/services/agent';
import { discoverService } from '@/services/discover';
@@ -20,6 +22,13 @@ import type {
} from './types';
import { AgentBuilderApiName, AgentBuilderIdentifier } from './types';
+// Write APIs that mutate agent state and require a client-side store refresh.
+const WRITE_APIS = new Set<string>([
+ AgentBuilderApiName.updateAgentConfig,
+ AgentBuilderApiName.updatePrompt,
+ AgentBuilderApiName.installPlugin,
+]);
+
const runtime = new AgentManagerRuntime({
agentService,
discoverService,
@@ -94,6 +103,21 @@ class AgentBuilderExecutor extends BaseExecutor<typeof AgentBuilderApiName> {
return runtime.installPlugin(agentId, params);
};
+
+ // ==================== Hooks ====================
+
+ onAfterCall = async ({ apiName, result }: ToolAfterCallContext): Promise<void> => {
+ if (!result.success || !WRITE_APIS.has(apiName)) return;
+
+ // AgentBuilderProvider keeps chatStore.activeAgentId in sync with the agent
+ // being edited. After a successful write the server has already updated the
+ // DB, so we re-fetch the config here to update the Zustand store and
+ // re-render the left-sidebar without requiring a page reload.
+ const editingAgentId = getChatStoreState().activeAgentId;
+ if (!editingAgentId) return;
+
+ await getAgentStoreState().internal_refreshAgentConfig(editingAgentId);
+ };
}
export const agentBuilderExecutor = new AgentBuilderExecutor();
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 6a1c208c46f..7908983e671 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -63,6 +63,14 @@ export interface ExecAgentAppContext {
defaultTaskAssigneeAgentId?: string;
/** Current document ID for page-scoped conversations */
documentId?: string | null;
+ /**
+ * When scope is 'agent_builder', the ID of the agent being edited (i.e. the
+ * left-sidebar agent the user opened AgentBuilder for). The AgentBuilder
+ * builtin runs under its own `agentId`; this field carries the *target* so
+ * server-side tool executors update the correct agent rather than the builder
+ * itself.
+ */
+ editingAgentId?: string;
/** Group ID for group chat */
groupId?: string | null;
/**
diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.ts
index 97155bf9936..15fbc8292a5 100644
--- a/src/store/chat/slices/aiChat/actions/gateway.ts
+++ b/src/store/chat/slices/aiChat/actions/gateway.ts
@@ -381,6 +381,13 @@ export class GatewayActionImpl {
agentDocumentId: context.agentDocumentId,
defaultTaskAssigneeAgentId: context.defaultTaskAssigneeAgentId,
documentId: context.documentId,
+ // When AgentBuilder runs, context.agentId is the builtin builder agent.
+ // The actual editing target is chatStore.activeAgentId (kept in sync by
+ // AgentBuilderProvider). Pass it so the server can route tool calls to
+ // the correct agent rather than the builder itself.
+ ...(context.scope === 'agent_builder' && {
+ editingAgentId: this.#get().activeAgentId ?? undefined,
+ }),
groupId: context.groupId,
...(initialTopicMetadata && { initialTopicMetadata }),
scope: context.scope,