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): inject editing-agent context in gateway mode & restore editor sync (#16326)

LiJian8ac6a1b4825a
diff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
index 12ad6ba6ffe..163312c0592 100644
--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
@@ -20,15 +20,18 @@ import {
generateCredsList,
} from '@lobechat/builtin-tool-creds';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
+import { builtinTools } from '@lobechat/builtin-tools';
import { BRANDING_PROVIDER } from '@lobechat/business-const';
import { COMPOSIO_APP_TYPES } from '@lobechat/const';
import {
+ type AgentBuilderContext,
type AgentContextDocument,
type AgentGroupConfig,
type BotPlatformContext,
buildStepSkillDelta,
buildStepToolDelta,
type LobeToolManifest,
+ type OfficialToolItem,
type OnboardingContext,
type OperationToolSet,
type ResolvedToolSet,
@@ -78,6 +81,7 @@ import debug from 'debug';
import { type ExtendParamsType, ModelProvider } from 'model-bank';
import { composioEnv } from '@/config/composio';
+import { AgentModel } from '@/database/models/agent';
import { FileModel } from '@/database/models/file';
import { type MessageModel, MessageModel as MessageModelClass } from '@/database/models/message';
import { PluginModel } from '@/database/models/plugin';
@@ -1273,8 +1277,113 @@ export const createRuntimeExecutors = (
}
}
+ // Agent Builder (gateway / server mode): the `<current_agent_context>`
+ // that tells the builder LLM WHICH agent it is editing is built
+ // CLIENT-side in chat mode (services/chat/index.ts). In gateway mode that
+ // client code never runs, so without this the context is never injected
+ // and the builder answers with its OWN config instead of the edited
+ // agent's. `state.metadata.editingAgentId` is the agent being configured
+ // (the builder builtin is `state.metadata.agentId`).
+ let agentBuilderContext: AgentBuilderContext | undefined;
+ const editingAgentId = state.metadata?.editingAgentId;
+ if (editingAgentId && ctx.serverDB && ctx.userId) {
+ try {
+ const editingAgentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
+ const editingConfig = (await editingAgentModel.getAgentConfigById(
+ editingAgentId,
+ )) as Record<string, any> | null;
+ if (editingConfig) {
+ // Build the `<available_official_tools>` list the same way the
+ // client does (services/chat/index.ts). Without it the builder
+ // prompt β€” which now relies on injected official tools instead of a
+ // search API β€” can't see installable builtin/Composio tools or their
+ // enabled/connected status, so the model may pick invalid ids or
+ // claim a supported tool is unavailable.
+ const enabledPlugins: string[] = Array.isArray(editingConfig.plugins)
+ ? (editingConfig.plugins as string[])
+ : [];
+ const composioIdentifiers = new Set(COMPOSIO_APP_TYPES.map((t) => t.identifier));
+ const officialTools: OfficialToolItem[] = [];
+
+ // Builtin tools β€” exclude hidden/infra tools (mirrors the client's
+ // `metaList`) and Composio entries (listed separately below).
+ for (const tool of builtinTools) {
+ if (tool.hidden) continue;
+ if (composioIdentifiers.has(tool.identifier)) continue;
+ officialTools.push({
+ description: tool.manifest?.meta?.description,
+ enabled: enabledPlugins.includes(tool.identifier),
+ identifier: tool.identifier,
+ installed: true,
+ name: tool.manifest?.meta?.title || tool.identifier,
+ type: 'builtin',
+ });
+ }
+
+ // Composio MCP servers β€” only when Composio is configured for this
+ // deployment. Connection status mirrors the existing
+ // {{COMPOSIO_SERVICES_LIST}} logic (ACTIVE composio plugin rows).
+ if (composioEnv.COMPOSIO_API_KEY) {
+ try {
+ const pluginModel = new PluginModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
+ const allPlugins = await pluginModel.query();
+ const connectedComposioIds = new Set(
+ allPlugins
+ .filter(
+ (p) =>
+ composioIdentifiers.has(p.identifier) &&
+ (p.customParams as any)?.composio?.status === 'ACTIVE',
+ )
+ .map((p) => p.identifier),
+ );
+ for (const t of COMPOSIO_APP_TYPES) {
+ officialTools.push({
+ description: `LobeHub Mcp Server: ${t.label}`,
+ enabled: enabledPlugins.includes(t.identifier),
+ identifier: t.identifier,
+ installed: connectedComposioIds.has(t.identifier),
+ name: t.label,
+ type: 'composio',
+ });
+ }
+ } catch (composioError) {
+ log('Failed to load Composio status for agentBuilderContext: %O', composioError);
+ }
+ }
+
+ agentBuilderContext = {
+ config: {
+ chatConfig: editingConfig.chatConfig ?? undefined,
+ model: editingConfig.model ?? undefined,
+ openingMessage: editingConfig.openingMessage ?? undefined,
+ openingQuestions: editingConfig.openingQuestions ?? undefined,
+ params: editingConfig.params ?? undefined,
+ plugins: editingConfig.plugins ?? undefined,
+ provider: editingConfig.provider ?? undefined,
+ systemRole: editingConfig.systemRole ?? undefined,
+ },
+ meta: {
+ avatar: editingConfig.avatar ?? undefined,
+ backgroundColor: editingConfig.backgroundColor ?? undefined,
+ description: editingConfig.description ?? undefined,
+ tags: editingConfig.tags ?? undefined,
+ title: editingConfig.title ?? undefined,
+ },
+ ...(officialTools.length > 0 && { officialTools }),
+ };
+ }
+ } catch (error) {
+ log(
+ 'Failed to build agentBuilderContext for editing agent %s: %O',
+ editingAgentId,
+ error,
+ );
+ }
+ }
+
const contextEngineInput = {
agentDocuments,
+ ...(agentBuilderContext && { agentBuilderContext }),
agentGroup: buildBotAgentGroupContext({
agentConfig,
agentId: state.metadata?.agentId,
diff --git a/packages/builtin-tool-agent-builder/src/executor.ts b/packages/builtin-tool-agent-builder/src/executor.ts
index fec348a628f..a63329d5e06 100644
--- a/packages/builtin-tool-agent-builder/src/executor.ts
+++ b/packages/builtin-tool-agent-builder/src/executor.ts
@@ -8,10 +8,10 @@ import { AgentManagerRuntime } from '@lobechat/agent-manager-runtime';
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';
+import { getAgentStoreState } from '@/store/agent';
+import { getChatStoreState } from '@/store/chat';
import type {
GetAvailableModelsParams,
@@ -34,6 +34,16 @@ const runtime = new AgentManagerRuntime({
discoverService,
});
+// Generation token for the gateway updatePrompt typewriter animation. The
+// streamingSystemRole buffer in the agent store is a singleton, and gateway
+// `tool_end` events fan out (gatewayEventHandler dispatches onAfterCall without
+// serializing across invocations). A newer updatePrompt therefore bumps this
+// counter so any in-flight animation stops appending and does NOT finalize β€”
+// only the latest run persists, preventing interleaved / partial prompt text.
+// (The client runtime awaits its stream during tool execution and is naturally
+// serialized, so this guard is gateway-only.)
+let updatePromptStreamGeneration = 0;
+
class AgentBuilderExecutor extends BaseExecutor<typeof AgentBuilderApiName> {
readonly identifier = AgentBuilderIdentifier;
protected readonly apiEnum = AgentBuilderApiName;
@@ -107,16 +117,61 @@ class AgentBuilderExecutor extends BaseExecutor<typeof AgentBuilderApiName> {
// ==================== 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 (!result.success || !WRITE_APIS.has(apiName)) return;
if (!editingAgentId) return;
- await getAgentStoreState().internal_refreshAgentConfig(editingAgentId);
+ const agentStore = getAgentStoreState();
+
+ // updatePrompt streaming fill:
+ // In CLIENT mode the AgentManagerRuntime streams the new prompt into the
+ // left profile editor via the agent store's streamingSystemRole (typewriter
+ // effect). In GATEWAY mode the prompt is written server-side, so no client
+ // streaming happens. `onAfterCall` ONLY fires for gateway tools, so we
+ // reproduce the same typewriter fill here using the SAME mechanism the
+ // editor already listens to β€” no double-stream risk in client mode. The
+ // animation persists the final systemRole; we still refresh afterwards to
+ // pull the server-cleared editorData and any other fields.
+ if (apiName === AgentBuilderApiName.updatePrompt) {
+ const newPrompt = (result.state as { newPrompt?: string } | undefined)?.newPrompt ?? '';
+ // Claim this animation; a later updatePrompt bumps the counter to supersede it.
+ const generation = ++updatePromptStreamGeneration;
+ agentStore.startStreamingSystemRole();
+ // Fire-and-forget so the gateway event handler isn't blocked for the whole
+ // animation; the editor reacts to streamingSystemRole reactively. The
+ // generation guard keeps concurrent animations from corrupting the shared
+ // buffer (see updatePromptStreamGeneration above).
+ void (async () => {
+ try {
+ const chunkSize = 5;
+ const delay = 10;
+ for (let i = 0; i < newPrompt.length; i += chunkSize) {
+ // A newer updatePrompt has taken over the shared buffer β€” stop here
+ // and let the latest run own the stream.
+ if (updatePromptStreamGeneration !== generation) return;
+ agentStore.appendStreamingSystemRole(newPrompt.slice(i, i + chunkSize));
+ if (i + chunkSize < newPrompt.length) {
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ }
+ }
+ } finally {
+ // Only the latest animation finalizes/persists, so a superseded run
+ // never writes interleaved or partial prompt text.
+ if (updatePromptStreamGeneration === generation) {
+ await agentStore.finishStreamingSystemRole(editingAgentId);
+ await agentStore.internal_refreshAgentConfig(editingAgentId);
+ }
+ }
+ })();
+ return;
+ }
+
+ await agentStore.internal_refreshAgentConfig(editingAgentId);
};
}
diff --git a/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx b/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx
index fdc13db222d..b22ee8756dc 100644
--- a/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx
+++ b/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx
@@ -71,6 +71,13 @@ const EditorCanvas = memo(() => {
const streamingInProgress = useAgentStore((s) => s.streamingSystemRoleInProgress);
const prevStreamingRef = useRef<string | undefined>(undefined);
const wasStreamingRef = useRef(false);
+ // Guards programmatic editor writes (external Agent Builder updates) so they
+ // are not mistaken for user edits β€” avoids latching edit-intent / acquiring
+ // the lock and echoing a redundant save.
+ const programmaticSyncRef = useRef(false);
+ // Last systemRole pushed into the editor on the external-update (editorData
+ // empty) path, so we don't re-push the same value on every render.
+ const lastSyncedRoleRef = useRef<string | undefined>(undefined);
// Collaborative edit-lock state, peeked-on-open and driven by the always-mounted
// EditLockDriver (see ../EditLockDriver) so it's resolved before this editor
@@ -88,6 +95,10 @@ const EditorCanvas = memo(() => {
if (!editable) return;
// Don't trigger save during streaming
if (streamingInProgress) return;
+ // Skip programmatic external re-sync (Agent Builder updated systemRole) β€”
+ // it's not a user edit, so don't latch edit-intent / acquire the lock or
+ // echo a redundant save.
+ if (programmaticSyncRef.current) return;
// Latch edit-intent so the lock driver acquires the lock on the first real
// edit. Streaming systemRole writes are programmatic and skipped above.
setHasEdited(true);
@@ -137,6 +148,9 @@ const EditorCanvas = memo(() => {
editor.setDocument('json', editorData);
} else if (systemRole) {
editor.setDocument('markdown', systemRole);
+ // Record the displayed role so the external-update re-sync below doesn't
+ // redundantly re-push the same value right after init.
+ lastSyncedRoleRef.current = systemRole;
}
// If no editorData and no systemRole, leave editor empty to show placeholder
setContentInit(true);
@@ -145,6 +159,46 @@ const EditorCanvas = memo(() => {
}
}, [editorInit, contentInit, editor, editorData, systemRole, streamingInProgress]);
+ // Re-sync the editor when the agent's systemRole is updated EXTERNALLY β€” the
+ // Agent Builder's updatePrompt / updateConfig clears editorData and sets a new
+ // systemRole. The content-init effect above only runs ONCE, so without this an
+ // external update with empty editorData leaves the editor blank even though a
+ // systemRole exists. A real user edit keeps editorData populated, so gating on
+ // "editorData empty" restores the original "fall back to systemRole" behavior
+ // without clobbering local edits. Skipped during streaming (the streaming
+ // effect owns the editor then).
+ useEffect(() => {
+ if (!editor || !editorInit || !contentInit) return;
+ if (streamingInProgress) return;
+
+ const hasEditorData = !!editorData && editorData?.root !== undefined;
+ if (hasEditorData) {
+ // Editor-backed content is the source of truth; allow a later clear to
+ // re-sync from systemRole again.
+ lastSyncedRoleRef.current = undefined;
+ return;
+ }
+
+ const role = systemRole ?? '';
+ if (lastSyncedRoleRef.current === role) return;
+ lastSyncedRoleRef.current = role;
+
+ programmaticSyncRef.current = true;
+ try {
+ editor.setDocument('markdown', role);
+ } catch {
+ // ignore
+ }
+ // Release the guard after the editor's onTextChange has had a chance to fire.
+ const timer = setTimeout(() => {
+ programmaticSyncRef.current = false;
+ }, 0);
+ return () => {
+ clearTimeout(timer);
+ programmaticSyncRef.current = false;
+ };
+ }, [editor, editorInit, contentInit, editorData, systemRole, streamingInProgress]);
+
return (
<Flexbox className={styles.root} gap={16}>
<Flexbox className={styles.header} gap={4}>
diff --git a/src/store/home/slices/homeInput/action.test.ts b/src/store/home/slices/homeInput/action.test.ts
index a7fb85451a1..d3e6914efe8 100644
--- a/src/store/home/slices/homeInput/action.test.ts
+++ b/src/store/home/slices/homeInput/action.test.ts
@@ -88,6 +88,7 @@ vi.mock('@/store/chat', () => ({
getState: () => ({
sendMessage: sendMessageMock,
}),
+ setState: vi.fn(),
},
}));
diff --git a/src/store/home/slices/homeInput/action.ts b/src/store/home/slices/homeInput/action.ts
index 4c0da7e7471..afa830f3179 100644
--- a/src/store/home/slices/homeInput/action.ts
+++ b/src/store/home/slices/homeInput/action.ts
@@ -90,6 +90,21 @@ export class HomeInputActionImpl {
groupId,
});
+ // Sync the editing target into the chat store BEFORE the builder message
+ // is sent. Gateway mode reads `chatStore.activeAgentId` at send time to
+ // forward `editingAgentId` (see gateway.ts executeGatewayAgent), and the
+ // AgentBuilder tool `onAfterCall` reads it to refresh the correct agent's
+ // config. Setting it here β€” instead of waiting for AgentBuilderProvider's
+ // mount effect β€” removes the create-time race where the first tool call
+ // could target / refresh the wrong agent (left profile not refreshed).
+ if (result.agentId) {
+ useChatStore.setState(
+ { activeAgentId: result.agentId },
+ false,
+ 'sendAsAgent/syncEditingAgentId',
+ );
+ }
+
if (message.trim()) {
useGlobalStore.getState().toggleAgentBuilderPanel(true);
}