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): preserve intervention message ancestry (#17628)

YuTengjing91878a5d135c
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
index fc48a62beeb..9a2ef9de106 100644
--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts
+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
@@ -558,6 +558,13 @@ export class GeneralChatAgent implements Agent {
} satisfies AgentInstruction);
} else {
instructions.push({
+ // Same `parentMessageId` the sibling call_tool / call_tools_batch
+ // instructions carry: the assistant message this llm_result just
+ // produced. Naming the owner explicitly keeps it resolvable
+ // across a step boundary β€” after rehydration that assistant
+ // comes back as an `assistantGroup`, which the executor's
+ // role-only fallback scan skips (see `executors/humanApprove.ts`).
+ parentMessageId,
pendingToolsCalling: toolsNeedingIntervention,
reason: 'human_intervention_required',
type: 'request_human_approve',
diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
index 515aed3aadf..17a1443a8d9 100644
--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
@@ -500,9 +500,13 @@ describe('GeneralChatAgent', () => {
const result = await agent.runner(context, state);
+ // `parentMessageId` must be carried: the executor persists the pending
+ // tool row under it, and without it the row lands on the previous turn's
+ // assistant and renders as an orphaned tool call.
expect(result).toEqual([
{
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [toolCall],
reason: 'human_intervention_required',
},
@@ -562,7 +566,10 @@ describe('GeneralChatAgent', () => {
},
},
{
+ // Same parent as the sibling call_tool above β€” both halves of a mixed
+ // step belong to the assistant this llm_result produced.
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [dangerousTool],
reason: 'human_intervention_required',
},
@@ -2041,6 +2048,7 @@ describe('GeneralChatAgent', () => {
expect(result).toEqual([
{
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [toolCall],
reason: 'human_intervention_required',
},
@@ -2233,6 +2241,7 @@ describe('GeneralChatAgent', () => {
expect(result).toEqual([
{
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [toolCall],
reason: 'human_intervention_required',
},
@@ -2287,6 +2296,7 @@ describe('GeneralChatAgent', () => {
expect(result).toEqual([
{
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [toolCall],
reason: 'human_intervention_required',
},
@@ -2396,6 +2406,7 @@ describe('GeneralChatAgent', () => {
},
{
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [blockedTool],
reason: 'human_intervention_required',
},
@@ -2460,6 +2471,7 @@ describe('GeneralChatAgent', () => {
},
{
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [dangerousTool],
reason: 'human_intervention_required',
},
@@ -2511,6 +2523,7 @@ describe('GeneralChatAgent', () => {
expect(result).toEqual([
{
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [alwaysTool],
reason: 'human_intervention_required',
},
@@ -2557,6 +2570,7 @@ describe('GeneralChatAgent', () => {
expect(result).toEqual([
{
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [alwaysTool],
reason: 'human_intervention_required',
},
@@ -2627,6 +2641,7 @@ describe('GeneralChatAgent', () => {
},
{
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [alwaysTool],
reason: 'human_intervention_required',
},
@@ -2679,6 +2694,7 @@ describe('GeneralChatAgent', () => {
expect(result).toEqual([
{
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [toolCall],
reason: 'human_intervention_required',
},
@@ -2726,6 +2742,7 @@ describe('GeneralChatAgent', () => {
expect(result).toEqual([
{
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [toolCall],
reason: 'human_intervention_required',
},
@@ -2911,6 +2928,7 @@ describe('GeneralChatAgent', () => {
expect(result).toEqual([
{
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [toolCall],
reason: 'human_intervention_required',
},
@@ -3053,6 +3071,7 @@ describe('GeneralChatAgent', () => {
expect(result).toEqual([
{
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [blacklistedTool],
reason: 'human_intervention_required',
},
@@ -3092,6 +3111,7 @@ describe('GeneralChatAgent', () => {
expect(result).toEqual([
{
type: 'request_human_approve',
+ parentMessageId: 'msg-1',
pendingToolsCalling: [alwaysTool],
reason: 'human_intervention_required',
},
diff --git a/packages/agent-runtime/src/executors/humanApprove.test.ts b/packages/agent-runtime/src/executors/humanApprove.test.ts
new file mode 100644
index 00000000000..abed8cbaf39
--- /dev/null
+++ b/packages/agent-runtime/src/executors/humanApprove.test.ts
@@ -0,0 +1,162 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { AgentRuntimeHost } from '../transport';
+import type { AgentInstruction, AgentState } from '../types';
+import { requestHumanApprove } from './humanApprove';
+
+const createState = (overrides?: Partial<AgentState>): AgentState => ({
+ cost: {
+ calculatedAt: '2026-07-26T00:00:00.000Z',
+ currency: 'USD',
+ llm: { byModel: [], currency: 'USD', total: 0 },
+ tools: { byTool: [], currency: 'USD', total: 0 },
+ total: 0,
+ },
+ createdAt: '2026-07-26T00:00:00.000Z',
+ lastModified: '2026-07-26T00:00:00.000Z',
+ maxSteps: 100,
+ messages: [],
+ metadata: {
+ agentId: 'agent-1',
+ threadId: undefined,
+ topicId: 'topic-1',
+ },
+ operationId: 'op-1',
+ status: 'running',
+ stepCount: 0,
+ toolManifestMap: {},
+ usage: {
+ humanInteraction: {
+ approvalRequests: 0,
+ promptRequests: 0,
+ selectRequests: 0,
+ totalWaitingTimeMs: 0,
+ },
+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },
+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },
+ },
+ ...overrides,
+});
+
+const pendingTool = {
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ id: 'call_ask_1',
+ identifier: 'lobe-agent',
+ type: 'builtin' as const,
+};
+
+describe('requestHumanApprove', () => {
+ let createToolMessage: ReturnType<typeof vi.fn>;
+ let query: ReturnType<typeof vi.fn>;
+ let host: AgentRuntimeHost;
+
+ beforeEach(() => {
+ createToolMessage = vi.fn().mockResolvedValue({ id: 'tool-msg-1' });
+ query = vi.fn().mockResolvedValue([]);
+
+ host = {
+ lifecycle: { dispatch: vi.fn().mockResolvedValue(undefined) },
+ operation: {
+ agentId: 'agent-1',
+ operationId: 'op-1',
+ stepIndex: 1,
+ topicId: 'topic-1',
+ },
+ transports: {
+ messages: { createToolMessage, query },
+ stream: { publishChunk: vi.fn(), publishEvent: vi.fn() },
+ },
+ } as unknown as AgentRuntimeHost;
+ });
+
+ /**
+ * The shape `state.messages` has after an op crosses a step boundary:
+ * `AgentStateManager` strips `messages` before persisting, and the reload runs
+ * them through `parse()`, which folds the assistant that carries tool calls
+ * into an `assistantGroup` (same id, different role). The previous turn stays
+ * a plain `assistant`.
+ */
+ const rehydratedMessages = [
+ { content: 'previous answer', id: 'assistant-previous', role: 'assistant' },
+ {
+ children: [],
+ content: '',
+ groupId: 'group-1',
+ id: 'assistant-current',
+ role: 'assistantGroup',
+ },
+ ] as unknown as AgentState['messages'];
+
+ /**
+ * Regression: scanning `state.messages` for the last `role: 'assistant'` skips
+ * the rehydrated `assistantGroup` that actually owns these tool calls and
+ * lands on the previous turn, so the pending tool row was persisted under the
+ * wrong assistant and the UI flagged it as an orphaned tool call.
+ */
+ it('parents pending tool messages on the instruction parentMessageId, not the last plain assistant in state', async () => {
+ const instruction: Extract<AgentInstruction, { type: 'request_human_approve' }> = {
+ parentMessageId: 'assistant-current',
+ pendingToolsCalling: [pendingTool],
+ type: 'request_human_approve',
+ };
+
+ await requestHumanApprove(host)(instruction, createState({ messages: rehydratedMessages }));
+
+ expect(createToolMessage).toHaveBeenCalledTimes(1);
+ expect(createToolMessage.mock.calls[0][0]).toMatchObject({
+ // The assistantGroup, NOT `assistant-previous`.
+ parentId: 'assistant-current',
+ tool_call_id: 'call_ask_1',
+ });
+ });
+
+ it('reads groupId off the rehydrated assistantGroup when the operation carries none', async () => {
+ const instruction: Extract<AgentInstruction, { type: 'request_human_approve' }> = {
+ parentMessageId: 'assistant-current',
+ pendingToolsCalling: [pendingTool],
+ type: 'request_human_approve',
+ };
+
+ await requestHumanApprove(host)(instruction, createState({ messages: rehydratedMessages }));
+
+ expect(createToolMessage.mock.calls[0][0]).toMatchObject({ groupId: 'group-1' });
+ });
+
+ it('falls back to the last assistant in state when no parentMessageId is carried', async () => {
+ const instruction: Extract<AgentInstruction, { type: 'request_human_approve' }> = {
+ pendingToolsCalling: [pendingTool],
+ type: 'request_human_approve',
+ };
+
+ const state = createState({
+ messages: [
+ { content: 'previous answer', id: 'assistant-previous', role: 'assistant' },
+ ] as AgentState['messages'],
+ });
+
+ await requestHumanApprove(host)(instruction, state);
+
+ expect(createToolMessage.mock.calls[0][0]).toMatchObject({ parentId: 'assistant-previous' });
+ });
+
+ it('does not create tool messages on the resume path', async () => {
+ const instruction: Extract<AgentInstruction, { type: 'request_human_approve' }> = {
+ parentMessageId: 'assistant-current',
+ pendingToolsCalling: [pendingTool],
+ skipCreateToolMessage: true,
+ type: 'request_human_approve',
+ };
+
+ query.mockResolvedValue([
+ { id: 'tool-msg-existing', role: 'tool', tool_call_id: 'call_ask_1' },
+ ]);
+
+ await requestHumanApprove(host)(instruction, createState());
+
+ expect(createToolMessage).not.toHaveBeenCalled();
+ expect(
+ (host.transports.stream.publishChunk as ReturnType<typeof vi.fn>).mock.calls[0][0],
+ ).toMatchObject({ toolMessageIds: { call_ask_1: 'tool-msg-existing' } });
+ });
+});
diff --git a/packages/agent-runtime/src/executors/humanApprove.ts b/packages/agent-runtime/src/executors/humanApprove.ts
index 1157ef79cb9..9924df91985 100644
--- a/packages/agent-runtime/src/executors/humanApprove.ts
+++ b/packages/agent-runtime/src/executors/humanApprove.ts
@@ -14,7 +14,7 @@ import type { AgentEvent, AgentInstruction, AnyHookEvent, InstructionExecutor }
export const requestHumanApprove =
(host: AgentRuntimeHost): InstructionExecutor =>
async (instruction, state) => {
- const { pendingToolsCalling, skipCreateToolMessage } = instruction as Extract<
+ const { parentMessageId, pendingToolsCalling, skipCreateToolMessage } = instruction as Extract<
AgentInstruction,
{ type: 'request_human_approve' }
>;
@@ -86,10 +86,42 @@ export const requestHumanApprove =
// best-effort lookup β€” a miss just omits the mapping
}
} else {
- // Find parent assistant message. Prefer state.messages (already in
- // memory from call_llm); fall back to a query if the runtime has been
- // rehydrated without recent messages.
- let parentAssistant = (state.messages ?? [])
+ // Resolve the assistant message that owns these tool calls.
+ //
+ // `parentMessageId` names it explicitly and is authoritative. Scanning
+ // `state.messages` for the last `role: 'assistant'` β€” the original
+ // approach, kept below only as a legacy fallback β€” silently picks the
+ // WRONG turn once an op crosses a step boundary:
+ //
+ // 1. `callLlmFinalizer` pushes this turn's assistant onto `state.messages`
+ // as a plain `role: 'assistant'`, so in-process the scan is correct.
+ // 2. `AgentStateManager.serializeStateForPersist` strips `messages` before
+ // persisting (Upstash 10MB cap), so the next step starts without them.
+ // 3. `AgentRuntimeService.rehydrateStateMessagesFromDB` reloads them via
+ // `parse()`, which folds an assistant carrying tool calls into an
+ // `assistantGroup` virtual message β€” same `id`, different `role`.
+ //
+ // The scan skips that `assistantGroup` and lands on the previous turn's
+ // plain assistant. The tool row then persists under a parent whose
+ // `tools[]` doesn't list it, and `MessageCollector.collectToolMessages`
+ // (which pairs a tool to its assistant on `parentId` + `tool_call_id`)
+ // can't match it from either side β€” the UI renders it as a top-level
+ // `inspector.orphanedToolCall`. Only interventions hit this: plain tool
+ // calls carry the parent through `call_tool` and were never affected.
+ let parentAssistant: { groupId?: string | null; id: string } | undefined = parentMessageId
+ ? {
+ // Post-rehydration the owner is present as an `assistantGroup`,
+ // which keeps the source assistant's fields (incl. groupId), so
+ // this lookup still resolves. `groupId` from the operation takes
+ // precedence anyway; this only backfills legacy callers.
+ groupId: (state.messages ?? []).find((m: any) => m.id === parentMessageId)?.groupId,
+ id: parentMessageId,
+ }
+ : undefined;
+
+ // Legacy fallback for instructions emitted without `parentMessageId`.
+ // Accurate only within a single step β€” see the step-boundary case above.
+ parentAssistant ??= (state.messages ?? [])
.slice()
.reverse()
.find((m: any) => m.role === 'assistant' && m.id) as
diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.ts
index 5e80295b349..44b7156a0af 100644
--- a/packages/agent-runtime/src/types/instruction.ts
+++ b/packages/agent-runtime/src/types/instruction.ts
@@ -328,6 +328,17 @@ export interface AgentInstructionRequestHumanSelect extends AgentInstructionBase
}
export interface AgentInstructionRequestHumanApprove extends AgentInstructionBase {
+ /**
+ * The assistant message that emitted `pendingToolsCalling`. Any producer that
+ * creates pending tool rows should set it, so those rows land under their real
+ * owner β€” see the parent resolution comment in `executors/humanApprove.ts`.
+ *
+ * Optional for the `skipCreateToolMessage` (resume) paths, which create no
+ * rows, and for backwards compatibility with producers that omit it: the
+ * executor still falls back to scanning `state.messages`, which is accurate
+ * only within a single step.
+ */
+ parentMessageId?: string;
pendingToolsCalling: ChatToolPayload[];
reason?: string;
skipCreateToolMessage?: boolean;
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
index 26e0cda49e5..8847e2722f4 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
@@ -1276,6 +1276,9 @@ describe('ConversationControl actions', () => {
content: 'Writing documents, Professional',
groupId: 'group-1',
metadata: { trigger: RequestTrigger.Onboarding },
+ // Anchored on the assistant that asked, not left null β€” a null parent
+ // would make this turn a second root of the topic (`segment-split`).
+ parentId: onboardingAssistantMessage.id,
role: 'user',
}),
expect.objectContaining({ operationId: expect.any(String) }),
@@ -1831,6 +1834,9 @@ describe('ConversationControl actions', () => {
content: `I'll skip this. ${reason}`,
groupId: 'group-1',
metadata: { trigger: RequestTrigger.Onboarding },
+ // Anchored on the assistant that asked, not left null β€” a null parent
+ // would make this turn a second root of the topic (`segment-split`).
+ parentId: onboardingAssistantMessage.id,
role: 'user',
}),
expect.objectContaining({ operationId: expect.any(String) }),
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
index 1421ef62280..99bf83055b3 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
@@ -169,6 +169,24 @@ export class ConversationControlActionImpl {
}
};
+ /**
+ * Parent for the synthetic user turn that answers / skips a tool interaction.
+ *
+ * Anchor it on the assistant that requested the interaction β€” the tool
+ * message's own parent β€” rather than leaving it null. A null parent makes the
+ * turn a SECOND root of the topic, which `conversation-flow`'s doctor reports
+ * as `segment-split`: the reader still shows it (roots are flattened in
+ * order), but it starts a fresh parent chain, so anything walking the tree
+ * (branch resolution, chain-based context assembly) loses the history before
+ * it.
+ *
+ * Deliberately not the tool message itself: `canAnchor` in the doctor's
+ * repair rule never treats a tool row as a spine tail, and this mirrors it so
+ * the write side and the repair side agree on the same shape.
+ */
+ #interactionTurnParentId = (toolMessage: UIChatMessage): string | undefined =>
+ toolMessage.parentId ?? undefined;
+
/**
* Client-side fallback guard that retires paused server ops once a Gateway
* resume op has started successfully. The server emits `agent_runtime_end`
@@ -699,6 +717,7 @@ export class ConversationControlActionImpl {
content: userMessageContent,
groupId: groupId ?? undefined,
...(requestMetadata && { metadata: requestMetadata }),
+ parentId: this.#interactionTurnParentId(toolMessage),
role: 'user',
threadId: threadId ?? undefined,
topicId: topicId ?? undefined,
@@ -825,6 +844,7 @@ export class ConversationControlActionImpl {
content: userMessageContent,
groupId: groupId ?? undefined,
...(requestMetadata && { metadata: requestMetadata }),
+ parentId: this.#interactionTurnParentId(toolMessage),
role: 'user',
threadId: threadId ?? undefined,
topicId: topicId ?? undefined,