π€― 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(chat): delegate multi-@agent mentions on the gateway in gateway mode (#16749)
Arvin Xu53c0bf3364f9
diff --git a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts b/apps/server/src/modules/AgentRuntime/executors/callLlm.tsindex 27604f55e68..d6c03cb1905 100644--- a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts+++ b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts@@ -752,6 +752,18 @@ export const callLlm =// into op metadata, mirroring agentConfig/botContext β no per-step DB// lookup here.agentGroup: state.metadata?.agentGroup as AgentGroupConfig | undefined,+ // Bridge the @-mentioned agents (persisted into the runtime+ // initialContext by AiAgentService.execAgent) into the agent-management+ // context so AgentManagementContextInjector injects the delegation+ // block, prompting the supervisor to `callAgent` the mentioned agents.+ // Mirrors the client's contextEngineering bridge; scoped to mention+ // runs only (undefined otherwise) so ordinary runs are unaffected.+ agentManagementContext: (state as any).initialContext?.initialContext?.mentionedAgents+ ?.length+ ? {+ mentionedAgents: (state as any).initialContext.initialContext.mentionedAgents,+ }+ : undefined,additionalVariables: {...state.metadata?.deviceSystemInfo,...lobehubSkillVariables,diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex cb2c64ee9c6..ffd48360b7e 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -202,6 +202,14 @@ const ExecAgentSchema = z* by the user-scoped lookups downstream, so it can't enable others' tools.*/selectedToolIds: z.array(z.string()).optional(),+ /**+ * Agents the user @-mentioned in this message (multi-mention). When present+ * (and non-group), the run enables the callAgent tool and injects the+ * mentioned-agents delegation context so the supervisor delegates to them+ * instead of answering itself. Mirrors the client runtime's+ * `initialContext.mentionedAgents` + injected callAgent manifest.+ */+ mentionedAgents: z.array(z.object({ id: z.string(), name: z.string() })).optional(),/** The agent slug to run (either agentId or slug is required) */slug: z.string().optional(),/**@@ -689,6 +697,7 @@ export const aiAgentRouter = router({deviceId,existingMessageIds = [],fileIds,+ mentionedAgents,parentMessageId,resumeApproval,selectedToolIds,@@ -706,6 +715,7 @@ export const aiAgentRouter = router({deviceId,existingMessageIds,fileIds,+ mentionedAgents,parentMessageId,prompt,// When parentMessageId is provided, this is a regeneration/continue or adiff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex e3c64bdc3c2..48a69f4a992 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -41,6 +41,7 @@ import type {ExecVirtualSubAgentParams,LobeAgentAgencyConfig,MessagePluginItem,+ RuntimeMentionedAgent,UserInterventionConfig,WorkspaceInitResult,} from '@lobechat/types';@@ -308,6 +309,14 @@ interface InternalExecAgentParams extends ExecAgentParams {initialStepCount?: number;/** Maximum steps for the agent operation */maxSteps?: number;+ /**+ * Agents the user @-mentioned in this message (multi-mention). When present+ * (and non-group), the run enables the callAgent tool and persists the mentioned+ * agents into the runtime `initialContext` so the context engine injects the+ * delegation context at step time β making the supervisor delegate to them+ * instead of answering itself. Mirrors the client runtime's mention wiring.+ */+ mentionedAgents?: RuntimeMentionedAgent[];/** Parent message ID to continue from. Only takes effect when resume is true */parentMessageId?: string;queueRetries?: number;@@ -945,6 +954,7 @@ export class AiAgentService {resume,resumeApproval,selectedToolIds,+ mentionedAgents,suppressUserMessage,ephemeralUserMessage,} = params;@@ -2048,6 +2058,14 @@ export class AiAgentService {let lobehubSkillManifests: LobeToolManifest[] = [];let composioManifests: LobeToolManifest[] = [];let connectorManifests: ReturnType<typeof buildConnectorManifests> = [];+ // When the user @-mentions agents (multi-mention, non-group), enable the+ // agent-management tool for this run so the supervisor can `callAgent` to+ // delegate. Mirrors the client runtime, which injects a callAgent manifest.+ // Single-mention takes a client-only deterministic-router path and never+ // reaches here. The delegation *context* (which agents were mentioned) is+ // injected separately via `initialContext.mentionedAgents` below.+ const hasMentionedAgents = !appContext?.groupId && !!mentionedAgents?.length;+// `selectedToolIds` are the user's @-mention picks for this turn; merged in// (deduped) alongside the agent's pinned plugins and any internal// `additionalPluginIds` so a mentioned-but-not-pinned tool (e.g. a custom MCP@@ -2057,6 +2075,7 @@ export class AiAgentService {...(agentConfig?.plugins ?? []),...(additionalPluginIds || []),...(selectedToolIds || []),+ ...(hasMentionedAgents ? ['lobe-agent-management'] : []),]),];@@ -3047,6 +3066,20 @@ export class AiAgentService {};}+ // Persist the @-mentioned agents into the runtime initialContext so the+ // context engine injects the delegation context on every step (survives the+ // queue-mode dispatch). `callLlm` bridges this into `agentManagementContext`+ // for the AgentManagementContextInjector β mirrors the client runtime.+ if (hasMentionedAgents) {+ initialContext = {+ ...initialContext,+ initialContext: {+ ...initialContext.initialContext,+ mentionedAgents,+ },+ };+ }+// 16b. Human-approval resume β override initialContext based on the// user's decision. The DB write above has already persisted the// intervention status, so `allMessages` reflects the decision for thediff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex c6196b9a4bd..c94ca733ac3 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -1,4 +1,9 @@-import type { ExecAgentAppContext, ExecAgentResult, UserInterventionConfig } from '@lobechat/types';+import type {+ ExecAgentAppContext,+ ExecAgentResult,+ RuntimeMentionedAgent,+ UserInterventionConfig,+} from '@lobechat/types';import { lambdaClient } from '@/libs/trpc/client';@@ -32,6 +37,12 @@ export interface ExecAgentTaskParams {existingMessageIds?: string[];/** File IDs of already-uploaded attachments to attach to the new user message */fileIds?: string[];+ /**+ * Agents the user @-mentioned in this message (multi-mention). The server+ * enables the callAgent tool and injects the mentioned-agents delegation+ * context so the supervisor run delegates to them instead of answering itself.+ */+ mentionedAgents?: RuntimeMentionedAgent[];/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */parentMessageId?: string;prompt: string;diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 437fdfe2ddb..5e3e7d1c9bd 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -2060,6 +2060,77 @@ describe('ConversationLifecycle actions', () => {);});+ it('should forward mentionedAgents to the gateway for multi-mention when gateway mode is enabled', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ messages: [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),+ ],+ topics: [],+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ const executeGatewayAgentSpy = vi.fn().mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ operationId: 'op-gw-supervisor',+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ });++ act(() => {+ useChatStore.setState({+ executeGatewayAgent: executeGatewayAgentSpy,+ isGatewayModeEnabled: () => true,+ });+ });++ await act(async () => {+ await result.current.sendMessage({+ message: '@Agent A @Agent B compare',+ editorData: {+ root: {+ children: [+ {+ children: [+ {+ label: 'Agent A',+ metadata: { id: 'agent-a', type: 'agent' },+ type: 'mention',+ },+ { text: ' ', type: 'text' },+ {+ label: 'Agent B',+ metadata: { id: 'agent-b', type: 'agent' },+ type: 'mention',+ },+ { text: ' compare', type: 'text' },+ ],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ } as any,+ context: createTestContext(),+ });+ });++ // Multi-mention keeps the supervisor on the gateway (unlike single-mention,+ // which falls through to the client path). The mentioned agents are+ // forwarded so the server enables callAgent + injects the delegation context.+ expect(result.current.executeClientAgent).not.toHaveBeenCalled();+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ mentionedAgents: [+ { id: 'agent-a', name: 'Agent A' },+ { id: 'agent-b', name: 'Agent B' },+ ],+ }),+ );+ });+it('should NOT inject mentionedAgents into initialContext when in group chat', async () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex d7e0702da35..038e5d2ccd4 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -961,6 +961,14 @@ export class ConversationLifecycleActionImpl {// selection (only the client runtime did). Omit when empty.selectedToolIds:selectedTools.length > 0 ? selectedTools.map((tool) => tool.identifier) : undefined,+ // Forward @-mentioned agents so the server supervisor can delegate to+ // them (multi-mention). Mirrors the client runtime's `initialContext`+ // injection: the server enables the callAgent tool and injects the+ // mentioned-agents delegation context so the supervisor calls them.+ // Omit when empty (single-mention takes the client path above and never+ // reaches here). Non-group only β group @member mentions are handled by+ // the group orchestration path, not agent-management delegation.+ mentionedAgents: hasMentionedAgents ? mentionedAgents : undefined,// Pass temp message IDs so the UI doesn't show a blank loading// state while waiting for the first step_start event to replace// messages with the server's real IDs.diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 1bfa7f09c7c..735cafd2d87 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -9,6 +9,7 @@ import type {ConversationContext,ExecAgentResult,MessageMetadata,+ RuntimeMentionedAgent,} from '@lobechat/types';import { isDesktop } from '@/const/version';@@ -399,6 +400,15 @@ export class GatewayActionImpl {* connector picked from the @ list).*/selectedToolIds?: string[];+ /**+ * Agents the user @-mentioned in this message (multi-mention). Forwarded to+ * the server so the supervisor run enables the callAgent tool and injects the+ * mentioned-agents delegation context β mirrors the client runtime's+ * `initialContext.mentionedAgents` + injected callAgent manifest. Without+ * this the gateway supervisor never sees the mention and answers itself+ * instead of delegating.+ */+ mentionedAgents?: RuntimeMentionedAgent[];/*** Temporary message IDs created during the initial sendMessage phase.* These are associated with the new gateway operation so the UI doesn't@@ -418,6 +428,7 @@ export class GatewayActionImpl {parentOperationId,resumeApproval,selectedToolIds,+ mentionedAgents,tempMessageIds,} = params;@@ -487,6 +498,7 @@ export class GatewayActionImpl {},deviceId: localDeviceId,fileIds,+ mentionedAgents,parentMessageId,prompt: message,resumeApproval,