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-runtime): resume an approved callSubAgent into its own row (#20071)

Arvin Xub1e1b255ddd5
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentApproval.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentApproval.test.ts
new file mode 100644
index 00000000000..0c5c2fff2ce
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentApproval.test.ts
@@ -0,0 +1,83 @@
+import { type AgentState } from '@lobechat/agent-runtime';
+import { type ChatToolPayload } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { type RuntimeExecutorContext } from '../context';
+import { buildServerVirtualSubAgentRunner } from '../executorHelpers';
+
+/**
+ * A `callSubAgent` that went through human approval is executed in place on
+ * its intervention row. The runner used to create a second placeholder anyway,
+ * so the sub-agent reported into that one while the approved row stayed empty:
+ * the parent's barrier never cleared and later turns read the slot as empty.
+ */
+describe('buildServerVirtualSubAgentRunner after tool approval', () => {
+ const buildRunner = (
+ existingToolMessageId: string | undefined,
+ execResult: Record<string, unknown> = { operationId: 'child-op', success: true },
+ ) => {
+ const messageModel = {
+ create: vi.fn().mockResolvedValue({ id: 'new-placeholder' }),
+ deleteMessage: vi.fn(),
+ updatePluginState: vi.fn().mockResolvedValue(undefined),
+ };
+ const execVirtualSubAgent = vi.fn().mockResolvedValue(execResult);
+ const ctx = {
+ execVirtualSubAgent,
+ messageModel,
+ operationId: 'parent-op',
+ topicId: 'topic-1',
+ } as unknown as RuntimeExecutorContext;
+
+ const runner = buildServerVirtualSubAgentRunner(
+ ctx,
+ {
+ operationId: 'parent-op',
+ origin: { agentId: 'agent-1', topicId: 'topic-1' },
+ } as unknown as AgentState,
+ { id: 'tool-call-1' } as ChatToolPayload,
+ existingToolMessageId ?? 'assistant-1',
+ existingToolMessageId,
+ );
+
+ return { execVirtualSubAgent, messageModel, runner: runner! };
+ };
+
+ it('anchors the sub-agent to the approved row instead of creating a second one', async () => {
+ const { execVirtualSubAgent, messageModel, runner } = buildRunner('approved-tool-row');
+
+ const result = await runner.run({ description: 'research', instruction: 'go' });
+
+ expect(messageModel.create).not.toHaveBeenCalled();
+ expect(messageModel.updatePluginState).toHaveBeenCalledWith('approved-tool-row', {
+ status: 'pending',
+ });
+ expect(execVirtualSubAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ parentMessageId: 'approved-tool-row' }),
+ );
+ expect(result).toMatchObject({ started: true, toolMessageId: 'approved-tool-row' });
+ });
+
+ it('keeps the approved row when the sub-agent fails to start', async () => {
+ const { messageModel, runner } = buildRunner('approved-tool-row', {
+ error: 'queue unavailable',
+ success: false,
+ });
+
+ const result = await runner.run({ description: 'research', instruction: 'go' });
+
+ expect(result).toMatchObject({ error: 'queue unavailable', started: false });
+ expect(messageModel.deleteMessage).not.toHaveBeenCalled();
+ });
+
+ it('still creates its own placeholder when the call was not approved in place', async () => {
+ const { messageModel, runner } = buildRunner(undefined);
+
+ const result = await runner.run({ description: 'research', instruction: 'go' });
+
+ expect(messageModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({ parentId: 'assistant-1', pluginState: { status: 'pending' } }),
+ );
+ expect(result).toMatchObject({ started: true, toolMessageId: 'new-placeholder' });
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index 0d07118a0cf..9b62fd646ab 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -269,6 +269,7 @@ export class ServerToolTransport implements ToolTransport {
context.state,
chatToolPayload,
context.parentMessageId,
+ context.toolMessageId,
),
taskId: context.state.origin?.taskId,
threadId: context.state.origin?.threadId,
diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
index f818f52cd10..1d6bb5f3d29 100644
--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts
+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
@@ -222,6 +222,13 @@ export const buildServerVirtualSubAgentRunner = (
state: AgentState,
chatToolPayload: ChatToolPayload,
parentMessageId: string,
+ /**
+ * The row this tool call already owns β€” set when the call went through human
+ * approval, whose intervention row is then executed in place. The sub-agent
+ * must report into that row: a second placeholder left the approved row empty
+ * forever, so the parent's barrier never cleared and it was never resumed.
+ */
+ existingToolMessageId?: string,
): ServerSubAgentRunner | undefined => {
// Share-visitor runs never get a sub-agent runner: the child run spawned
// here does not thread the parent's shareGate, so it would execute with the
@@ -271,25 +278,31 @@ export const buildServerVirtualSubAgentRunner = (
? undefined
: getSubAgentChatConfigOverride(parentAgentConfig?.agencyConfig?.subagent);
- // 1. Create the pending placeholder tool message (mirrors the normal
+ // 1. Create (or, after approval, reuse) the pending placeholder tool message (mirrors the normal
// tool-message shape in call_tool) that anchors the isolation thread
// and renders a loading state until the bridge backfills it.
- const placeholder = await ctx.messageModel.create({
- agentId,
- content: '',
- groupId: state.origin?.groupId ?? undefined,
- parentId: parentMessageId,
- plugin: chatToolPayload as any,
- // A continued sub-agent already has its thread, so the card can link to
- // it while the new turn is still running.
- pluginState: subAgentId
- ? { status: 'pending', threadId: subAgentId }
- : { status: 'pending' },
- role: 'tool',
- threadId: state.origin?.threadId,
- tool_call_id: chatToolPayload.id,
- topicId,
- });
+ const pendingState = subAgentId
+ ? { status: 'pending', threadId: subAgentId }
+ : { status: 'pending' };
+ if (existingToolMessageId) {
+ await ctx.messageModel.updatePluginState(existingToolMessageId, pendingState);
+ }
+ const placeholder = existingToolMessageId
+ ? { id: existingToolMessageId }
+ : await ctx.messageModel.create({
+ agentId,
+ content: '',
+ groupId: state.origin?.groupId ?? undefined,
+ parentId: parentMessageId,
+ plugin: chatToolPayload as any,
+ // A continued sub-agent already has its thread, so the card can link to
+ // it while the new turn is still running.
+ pluginState: pendingState,
+ role: 'tool',
+ threadId: state.origin?.threadId,
+ tool_call_id: chatToolPayload.id,
+ topicId,
+ });
// 2. Fork the virtual child op anchored to the placeholder. The virtual
// entry marks the child as `isSubAgent` and registers the completion
@@ -317,6 +330,16 @@ export const buildServerVirtualSubAgentRunner = (
// `started: false` (with the underlying reason) so callSubAgent surfaces
// an inline tool error instead.
if (!result?.success) {
+ // A reused approval row is the call's own result slot: the runtime writes
+ // this failure into it, so it must not be deleted.
+ if (existingToolMessageId) {
+ return {
+ error: result?.error,
+ started: false,
+ subOperationId: result?.operationId,
+ threadId: '',
+ };
+ }
try {
// Runtime placeholder cleanup β€” also valid inside an agent-share
// visitor topic, hence the explicit opt-in.
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index cf221ece802..a903857bb8c 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -1324,6 +1324,61 @@ describe('AgentRuntimeService', () => {
);
});
+ // Approving a callSubAgent starts a resume op that seeds its assistant
+ // placeholder, runs the tool, then parks on the deferred sub-agent. The
+ // resumed turn must fill that seed; a second assistant left the seed as an
+ // empty "…" branch that hid the real answer.
+ it('fills the seeded assistant placeholder when resuming from an async tool', async () => {
+ const parkedState = {
+ ...mockState,
+ interruption: {
+ canResume: true,
+ interruptedAt: new Date().toISOString(),
+ reason: 'async_tool',
+ },
+ pendingAssistantMessageId: 'seeded-assistant-1',
+ pendingToolsCalling: [
+ {
+ apiName: 'callSubAgent',
+ arguments: '{}',
+ id: 'tool-call-1',
+ identifier: 'lobe-agent',
+ type: 'builtin',
+ },
+ ],
+ status: 'waiting_for_async_tool',
+ };
+ const refreshedMessages = [
+ { content: 'research', id: 'user-msg-1', role: 'user' },
+ {
+ id: 'assistant-msg-1',
+ role: 'assistant',
+ tools: [{ id: 'tool-call-1', result_msg_id: 'tool-msg-1' }],
+ },
+ ];
+ const mockRuntime = {
+ step: vi.fn().mockResolvedValue({
+ events: [],
+ newState: { ...parkedState, pendingToolsCalling: [], status: 'done', stepCount: 2 },
+ nextContext: null,
+ }),
+ };
+
+ mockCoordinator.loadAgentState.mockResolvedValue(parkedState);
+ vi.spyOn(service as any, 'refreshMessagesFromDB').mockResolvedValue(refreshedMessages);
+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });
+
+ await service.executeStep({ ...mockParams, resumeAsyncTool: true });
+
+ expect(mockRuntime.step).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ payload: { assistantMessageId: 'seeded-assistant-1', parentMessageId: 'tool-msg-1' },
+ phase: 'user_input',
+ }),
+ );
+ });
+
it('should handle missing agent state', async () => {
mockCoordinator.loadAgentState.mockResolvedValue(null);
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index cd81499ba76..fef8bd08910 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -2057,8 +2057,17 @@ export class AgentRuntimeService {
// not this one. Drop ours rather than render a list that predates it.
currentState.operationCredentials = undefined;
currentState.lastModified = new Date().toISOString();
+ // A resume op (e.g. approving a callSubAgent) seeds its assistant
+ // placeholder before running the tool; when that tool is deferred the
+ // op parks with the seed unclaimed. Fill it now β€” creating another
+ // assistant leaves the seed as an empty "…" sibling branch that hides
+ // the real answer.
+ const seededAssistantMessageId = currentState.pendingAssistantMessageId;
currentContext = {
- payload: { parentMessageId: resumeParentMessageId },
+ payload: {
+ ...(seededAssistantMessageId && { assistantMessageId: seededAssistantMessageId }),
+ parentMessageId: resumeParentMessageId,
+ },
phase: 'user_input',
} as AgentRuntimeContext;
log(