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): resolve a parallel tool batch in one approval (#17838)

Arvin Xuc599cac24259
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index f38a057cea9..f00621ba3cd 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -2218,31 +2218,31 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
expect(mockFindPlanDocuments).not.toHaveBeenCalled();
});
- it.each([
- { items: [], updatedAt: 'canonical-clear' },
- [],
- ])('treats canonical and legacy empty message states as clear tombstones', async (todos) => {
- mockFindPlanDocuments.mockResolvedValue([
- {
- metadata: {
- todos: { items: [{ status: 'todo', text: 'Stale metadata task' }] },
+ it.each([{ items: [], updatedAt: 'canonical-clear' }, []])(
+ 'treats canonical and legacy empty message states as clear tombstones',
+ async (todos) => {
+ mockFindPlanDocuments.mockResolvedValue([
+ {
+ metadata: {
+ todos: { items: [{ status: 'todo', text: 'Stale metadata task' }] },
+ },
+ updatedAt: new Date(),
},
- updatedAt: new Date(),
- },
- ]);
+ ]);
- const content = await callWithMessages(
- [
- { content: 'cleared', pluginState: { todos }, role: 'tool' },
- { content: 'Continue', role: 'user' },
- ],
- stateWithLobeAgent(),
- );
+ const content = await callWithMessages(
+ [
+ { content: 'cleared', pluginState: { todos }, role: 'tool' },
+ { content: 'Continue', role: 'user' },
+ ],
+ stateWithLobeAgent(),
+ );
- expect(content).not.toContain('<todo_context>');
- expect(content).not.toContain('Stale metadata task');
- expect(mockFindPlanDocuments).not.toHaveBeenCalled();
- });
+ expect(content).not.toContain('<todo_context>');
+ expect(content).not.toContain('Stale metadata task');
+ expect(mockFindPlanDocuments).not.toHaveBeenCalled();
+ },
+ );
it.each([
{
@@ -4149,7 +4149,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
expect(result.newState.messages[2].id).toBe('tool-msg-1');
});
- it('should return last tool message ID as parentMessageId in nextContext', async () => {
+ it('anchors the next turn on the calling assistant, not the last tool message', async () => {
let callCount = 0;
mockMessageModel.create.mockImplementation(() => {
callCount++;
@@ -4184,9 +4184,12 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const result = await executors.call_tools_batch!(instruction, state);
- // parentMessageId should be the last created tool message ID
+ // A step is one LLM call, and the batch's tool rows are inline data of
+ // that call — so the continuation anchors on the assistant that emitted
+ // the batch. Anchoring on a tool row made the spine depend on which tool
+ // `Promise.all` settled last.
const payload = result.nextContext!.payload as { parentMessageId?: string };
- expect(payload.parentMessageId).toBe('created-tool-msg-2');
+ expect(payload.parentMessageId).toBe('assistant-msg-123');
expect(result.nextContext!.phase).toBe('tools_batch_result');
});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
index 561da953a51..966ef64aaf3 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
@@ -124,6 +124,10 @@ export class ServerMessageTransport implements MessageTransport {
await this.messageModel.updatePluginState(id, state);
}
+ async updateToolIntervention(id: string, intervention: Record<string, any>): Promise<void> {
+ await this.messageModel.updateMessagePlugin(id, { intervention } as any);
+ }
+
async updateToolMessage(id: string, params: UpdateToolMessageInput): Promise<void> {
await this.messageModel.updateToolMessage(id, params);
}
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 33c9ae933e9..caad2aa96e4 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -252,6 +252,31 @@ const ExecAgentSchema = z
toolCallId: z.string(),
})
.optional(),
+ /**
+ * Batch form of `resumeApproval` — one entry per pending tool the user
+ * resolved in a single action ("approve all" on a parallel tool batch).
+ * The op applies every decision, then runs all approved tools in ONE
+ * `call_tools_batch` and continues the LLM once with the full result set.
+ *
+ * Prefer this over firing N `resumeApproval` ops for a parallel batch: each
+ * of those continues the LLM while the not-yet-approved tools are still
+ * empty rows, which forks the parent chain and shows the model blank
+ * results. Mutually exclusive with `resumeApproval`.
+ */
+ resumeApprovals: z
+ .array(
+ z.object({
+ decision: z.enum(['approved', 'rejected', 'rejected_continue']),
+ /** ID of the pending `role='tool'` message this decision targets. */
+ parentMessageId: z.string(),
+ /** Optional user-supplied rejection reason (only meaningful for rejected variants). */
+ rejectionReason: z.string().optional(),
+ /** tool_call_id of the pending tool call being approved/rejected. */
+ toolCallId: z.string(),
+ }),
+ )
+ .min(1)
+ .optional(),
/**
* Resume a previous op paused on a `humanIntervention: 'always'` tool (e.g.
* lobe-agent `askUserQuestion`). When set, the new op writes the
@@ -846,6 +871,7 @@ export const aiAgentRouter = router({
mentionedAgents,
parentMessageId,
resumeApproval,
+ resumeApprovals,
resumeToolResult,
selectedToolIds,
trigger,
@@ -869,6 +895,9 @@ export const aiAgentRouter = router({
...existingMessageIds,
parentMessageId,
resumeApproval?.parentMessageId,
+ // Every batch target is authorized too — a caller must not be able to
+ // slip a message it doesn't own into the list behind an owned anchor.
+ ...(resumeApprovals ?? []).map((decision) => decision.parentMessageId),
resumeToolResult?.parentMessageId,
],
topicId: appContext?.topicId,
@@ -894,6 +923,7 @@ export const aiAgentRouter = router({
// human-approval resume — either way, skip user message creation.
resume: !!parentMessageId,
resumeApproval,
+ resumeApprovals,
resumeToolResult,
selectedToolIds,
slug,
@@ -1491,6 +1521,39 @@ export const aiAgentRouter = router({
* This endpoint interrupts a SubAgent task by threadId or operationId.
* It updates both operation status and Thread status to cancelled state.
*/
+ /**
+ * Stop a run parked on tool approval: settle the pending tool rows and end
+ * the operation without executing anything or continuing the model.
+ *
+ * Distinct from `interruptTask`, which only flips runtime state and assumes
+ * a live loop will persist the outcome — a parked run has no loop, so its
+ * tool rows and DB row would both be left behind.
+ */
+ stopPendingApproval: aiAgentWriteProcedure
+ .input(
+ z.object({
+ /** Pending `role='tool'` message ids to settle — the active batch. */
+ toolMessageIds: z.array(z.string()).min(1),
+ topicId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ // Same ownership gate the approval resume uses: every target must belong
+ // to the caller before anything is written.
+ await assertCanUseAgentRunConversation({
+ db: ctx.serverDB,
+ messageIds: input.toolMessageIds,
+ topicId: input.topicId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
+ return ctx.aiAgentService.stopPendingApproval({
+ toolMessageIds: input.toolMessageIds,
+ topicId: input.topicId,
+ });
+ }),
+
interruptTask: aiAgentWriteProcedure
.input(InterruptTaskSchema)
.mutation(async ({ input, ctx }) => {
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts
index 6f1da731e1d..df585f7dd4f 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts
@@ -12,7 +12,13 @@ const {
mockMessageQuery,
mockUpdateMessagePlugin,
mockUpdateToolMessage,
+ mockFindLatestParkedOperationId,
+ mockRecordCompletion,
+ mockInterruptOperation,
} = vi.hoisted(() => ({
+ mockFindLatestParkedOperationId: vi.fn(),
+ mockRecordCompletion: vi.fn(),
+ mockInterruptOperation: vi.fn(),
mockCreateOperation: vi.fn(),
mockFindById: vi.fn(),
mockFindMessagePlugin: vi.fn(),
@@ -95,6 +101,14 @@ vi.mock('@/database/models/userMemory/persona', () => ({
vi.mock('@/server/services/agentRuntime', () => ({
AgentRuntimeService: vi.fn().mockImplementation(() => ({
createOperation: mockCreateOperation,
+ interruptOperation: mockInterruptOperation,
+ })),
+}));
+
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: vi.fn().mockImplementation(() => ({
+ findLatestParkedOperationId: mockFindLatestParkedOperationId,
+ recordCompletion: mockRecordCompletion,
})),
}));
@@ -149,6 +163,8 @@ describe('AiAgentService.execAgent - resumeApproval', () => {
// `messages` row — `findById` returns this. Note plugin metadata (apiName,
// identifier, etc.) lives in a separate `message_plugins` table.
const pendingToolMessage = {
+ // Non-null in the schema; the batch resume sorts approved rows by it.
+ createdAt: new Date('2026-08-02T00:00:00.000Z'),
id: 'tool-msg-1',
role: 'tool',
sessionId: 'session-1',
@@ -333,5 +349,143 @@ describe('AiAgentService.execAgent - resumeApproval', () => {
}),
).rejects.toThrow(/no plugin row/);
});
+
+ it('rejects a batch whose targets belong to different assistant turns', async () => {
+ // A batch resume runs every approved tool as ONE `call_tools_batch` under
+ // ONE assistant anchor and continues the model once. Mixing an abandoned
+ // approval from an earlier turn would execute an unrelated tool and fold
+ // its result into this turn. Anchoring on whichever entry came first is
+ // silent corruption, so refuse instead.
+ mockFindById.mockImplementation(async (id: string) =>
+ id === 'tool-msg-old'
+ ? { ...pendingToolMessage, id: 'tool-msg-old', parentId: 'assistant-old' }
+ : { ...pendingToolMessage, parentId: 'assistant-new' },
+ );
+
+ await expect(
+ service.execAgent({
+ ...baseParams,
+ resumeApprovals: [
+ { decision: 'approved', parentMessageId: 'tool-msg-1', toolCallId: 'call_xyz' },
+ { decision: 'approved', parentMessageId: 'tool-msg-old', toolCallId: 'call_xyz' },
+ ],
+ }),
+ ).rejects.toThrow(/must resolve one assistant turn/);
+
+ // Nothing may be persisted: validation runs before any write, so a
+ // refused batch cannot leave half its tools marked approved with no run
+ // to execute them.
+ expect(mockUpdateMessagePlugin).not.toHaveBeenCalled();
+ expect(mockCreateOperation).not.toHaveBeenCalled();
+ });
+
+ it('accepts a batch whose targets share one assistant turn', async () => {
+ mockFindById.mockImplementation(async (id: string) => ({
+ ...pendingToolMessage,
+ id,
+ parentId: 'assistant-new',
+ }));
+
+ await service.execAgent({
+ ...baseParams,
+ resumeApprovals: [
+ { decision: 'approved', parentMessageId: 'tool-msg-1', toolCallId: 'call_xyz' },
+ { decision: 'approved', parentMessageId: 'tool-msg-2', toolCallId: 'call_xyz' },
+ ],
+ });
+
+ expect(mockUpdateMessagePlugin).toHaveBeenCalledWith('tool-msg-1', {
+ intervention: { status: 'approved' },
+ });
+ expect(mockUpdateMessagePlugin).toHaveBeenCalledWith('tool-msg-2', {
+ intervention: { status: 'approved' },
+ });
+ expect(mockCreateOperation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ initialContext: expect.objectContaining({
+ payload: expect.objectContaining({ parentMessageId: 'assistant-new' }),
+ phase: 'human_approved_tool',
+ }),
+ }),
+ );
+ });
+ });
+});
+
+describe('AiAgentService.stopPendingApproval', () => {
+ let service: AiAgentService;
+
+ const pendingToolMessage = {
+ createdAt: new Date('2026-08-03T00:00:00.000Z'),
+ id: 'tool-msg-1',
+ role: 'tool',
+ topicId: 'topic-1',
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockFindById.mockImplementation(async (id: string) => ({ ...pendingToolMessage, id }));
+ mockUpdateMessagePlugin.mockResolvedValue(undefined);
+ mockUpdateToolMessage.mockResolvedValue(undefined);
+ mockFindLatestParkedOperationId.mockResolvedValue('op-parked-1');
+ mockRecordCompletion.mockResolvedValue(undefined);
+ mockInterruptOperation.mockResolvedValue(true);
+ service = new AiAgentService({} as unknown as LobeChatDatabase, 'user-1');
+ });
+
+ it('settles every pending row in place and retires the parked operation', async () => {
+ const result = await service.stopPendingApproval({
+ toolMessageIds: ['tool-msg-1', 'tool-msg-2'],
+ topicId: 'topic-1',
+ });
+
+ // In place: the approval pause already wrote these rows. Inserting fresh
+ // aborted rows would duplicate every tool AND leave the originals pending,
+ // which is what keeps the approval cards on screen after a stop.
+ for (const id of ['tool-msg-1', 'tool-msg-2']) {
+ expect(mockUpdateToolMessage).toHaveBeenCalledWith(id, {
+ content: 'Tool execution was aborted by user.',
+ });
+ expect(mockUpdateMessagePlugin).toHaveBeenCalledWith(id, {
+ intervention: { status: 'aborted' },
+ });
+ }
+
+ // The parked op is resolved from the topic — the client has lost its id by
+ // the time the user decides to stop.
+ expect(mockInterruptOperation).toHaveBeenCalledWith('op-parked-1');
+ expect(mockRecordCompletion).toHaveBeenCalledWith(
+ 'op-parked-1',
+ expect.objectContaining({ completionReason: 'interrupted', status: 'interrupted' }),
+ );
+ expect(result.settledToolMessageIds).toEqual(['tool-msg-1', 'tool-msg-2']);
+ });
+
+ it('nothing runs and the model is not continued', async () => {
+ await service.stopPendingApproval({ toolMessageIds: ['tool-msg-1'], topicId: 'topic-1' });
+
+ // A stop is not a rejection: a rejection resumes the model so it can
+ // respond, a stop ends the turn outright.
+ expect(mockCreateOperation).not.toHaveBeenCalled();
+ });
+
+ it('rejects a target from another topic before writing anything', async () => {
+ mockFindById.mockImplementation(async (id: string) => ({
+ ...pendingToolMessage,
+ id,
+ topicId: id === 'tool-msg-2' ? 'other-topic' : 'topic-1',
+ }));
+
+ await expect(
+ service.stopPendingApproval({
+ toolMessageIds: ['tool-msg-1', 'tool-msg-2'],
+ topicId: 'topic-1',
+ }),
+ ).rejects.toThrow(/topicId does not match/);
+
+ // Validation runs before any write, so a refused stop cannot half-clear the
+ // batch and strand the rest against a run that is already gone.
+ expect(mockUpdateMessagePlugin).not.toHaveBeenCalled();
+ expect(mockInterruptOperation).not.toHaveBeenCalled();
});
});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 05cf8e1041e..5621fba6e2f 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -183,6 +183,13 @@ import { isWorkspaceCacheFresh, upsertWorkspaceScan } from './workspaceInitCache
const log = debug('lobe-server:ai-agent-service');
+/**
+ * Content written onto a tool row that the user stopped before it ran. Mirrors
+ * the runtime's aborted-tool wording so a stopped call reads the same whether
+ * it was settled here or by `resolve_aborted_tools`.
+ */
+const STOPPED_TOOL_CONTENT = 'Tool execution was aborted by user.';
+
const createGraphAwareAgentFactory =
(
upstreamFactory?: AgentRuntimeServiceOptions['agentFactory'],
@@ -404,6 +411,24 @@ interface InternalExecAgentParams extends ExecAgentParams {
rejectionReason?: string;
toolCallId: string;
};
+ /**
+ * Batch form of `resumeApproval` — every decision the user made in ONE
+ * action ("approve all" on a parallel tool batch). The service applies each
+ * decision to its tool message and resumes with a single `call_tools_batch`
+ * covering all approved tools, so the LLM is continued exactly once with the
+ * complete result set.
+ *
+ * Resolving a parallel batch as N sequential `resumeApproval` calls instead
+ * produces N operations, and each one continues the LLM while the tools not
+ * yet approved are still empty rows. Mutually exclusive with
+ * `resumeApproval`; when both are absent nothing approval-related runs.
+ */
+ resumeApprovals?: {
+ decision: 'approved' | 'rejected' | 'rejected_continue';
+ parentMessageId: string;
+ rejectionReason?: string;
+ toolCallId: string;
+ }[];
/**
* When present, this execAgent call resumes a previous op that paused on a
* `humanIntervention: 'always'` tool (e.g. lobe-agent `askUserQuestion`). The
@@ -1180,6 +1205,7 @@ export class AiAgentService {
parentOperationId,
resume,
resumeApproval,
+ resumeApprovals,
resumeToolResult,
selectedToolIds,
mentionedAgents,
@@ -1462,7 +1488,16 @@ export class AiAgentService {
// tRPC router get `resume: true` via the router, but the service-level
// API allows resumeApproval alone — fold both into a single effective
// flag so downstream resume branches don't need to know about approval.
- const effectiveResume = resume || !!resumeApproval || !!resumeToolResult;
+ // Normalize the single and batch approval forms into one list so every
+ // branch below (validation, DB writes, resume context) has a single shape
+ // to reason about. `resumeApproval` stays the wire format for one decision.
+ const approvalDecisions = resumeApprovals?.length
+ ? resumeApprovals
+ : resumeApproval
+ ? [resumeApproval]
+ : [];
+
+ const effectiveResume = resume || approvalDecisions.length > 0 || !!resumeToolResult;
// Both resume and suppressUserMessage run the turn off existing history
// instead of appending a new user message — share the message-construction
@@ -1516,40 +1551,97 @@ export class AiAgentService {
// tool_call_id / apiName / identifier / arguments / type fields live on
// the plugin row and must be fetched separately.
let resumeApprovalPlugin: MessagePluginItem | undefined;
-
- if (resumeApproval) {
- if (!resumeParentMessage) {
- throw new Error('resumeApproval requires parentMessageId to point at a tool message');
+ /**
+ * Approved decisions paired with their plugin row, in the order the caller
+ * listed them. Drives the batch resume context at 16b; the tool message id
+ * doubles as the row `call_tools_batch` fills in place.
+ */
+ const approvedToolEntries: {
+ createdAt: Date;
+ plugin: MessagePluginItem;
+ toolMessageId: string;
+ }[] = [];
+ /** Assistant that emitted this batch — the pending tool rows' shared parent. */
+ let approvalOwnerAssistantId: string | undefined;
+
+ // Load and validate EVERY decision before applying any of them. The apply
+ // step writes per entry, so validating inline would leave a rejected batch
+ // half-persisted — some tools already marked approved with no run to
+ // execute them.
+ const validatedDecisions: {
+ entry: (typeof approvalDecisions)[number];
+ plugin: MessagePluginItem;
+ targetMessage: NonNullable<typeof resumeParentMessage>;
+ }[] = [];
+
+ for (const decisionEntry of approvalDecisions) {
+ // The single-decision form validated `parentMessageId` (the op-level
+ // resume anchor) as the target tool message. In the batch form each
+ // decision names its own tool message, so load and validate per entry —
+ // the op-level anchor is only one of them.
+ const targetMessage =
+ decisionEntry.parentMessageId === parentMessageId
+ ? resumeParentMessage
+ : await this.messageModel.findById(decisionEntry.parentMessageId);
+
+ if (!targetMessage) {
+ throw new Error(`resumeApproval: tool message not found: ${decisionEntry.parentMessageId}`);
}
- if (resumeParentMessage.role !== 'tool') {
+ if (targetMessage.role !== 'tool') {
throw new Error(
- `resumeApproval.parentMessageId must point at a role='tool' message, got role='${resumeParentMessage.role}'`,
+ `resumeApproval.parentMessageId must point at a role='tool' message, got role='${targetMessage.role}'`,
);
}
+ if (targetMessage.topicId !== appContext?.topicId) {
+ throw new Error('appContext.topicId does not match approval target message');
+ }
- resumeApprovalPlugin = await this.messageModel.findMessagePlugin(
- resumeApproval.parentMessageId,
- );
- if (!resumeApprovalPlugin) {
+ const plugin = await this.messageModel.findMessagePlugin(decisionEntry.parentMessageId);
+ if (!plugin) {
throw new Error(
- `resumeApproval: no plugin row for tool message ${resumeApproval.parentMessageId}`,
+ `resumeApproval: no plugin row for tool message ${decisionEntry.parentMessageId}`,
);
}
- if (
- resumeApprovalPlugin.toolCallId &&
- resumeApprovalPlugin.toolCallId !== resumeApproval.toolCallId
- ) {
+ if (plugin.toolCallId && plugin.toolCallId !== decisionEntry.toolCallId) {
throw new Error(
- `resumeApproval.toolCallId mismatch for message ${resumeApproval.parentMessageId}: ` +
- `stored=${resumeApprovalPlugin.toolCallId}, requested=${resumeApproval.toolCallId}`,
+ `resumeApproval.toolCallId mismatch for message ${decisionEntry.parentMessageId}: ` +
+ `stored=${plugin.toolCallId}, requested=${decisionEntry.toolCallId}`,
);
}
- const { decision, rejectionReason } = resumeApproval;
+ validatedDecisions.push({ entry: decisionEntry, plugin, targetMessage });
+ }
+
+ // A batch resume executes every approved tool as ONE `call_tools_batch`
+ // under ONE assistant anchor and continues the LLM once. That is only
+ // meaningful when the calls actually came from the same assistant turn.
+ // The client scopes its selection, but a stale or hand-built request could
+ // mix an abandoned approval from an earlier turn into this one — which
+ // would run an unrelated tool and fold its result into a turn it does not
+ // belong to. Reject rather than silently anchoring on whichever entry came
+ // first.
+ const approvalOwnerIds = new Set(
+ validatedDecisions.map(({ targetMessage }) => targetMessage.parentId ?? '(none)'),
+ );
+ if (approvalOwnerIds.size > 1) {
+ throw new Error(
+ `resumeApprovals must resolve one assistant turn, got ${approvalOwnerIds.size} owners: ` +
+ [...approvalOwnerIds].join(', '),
+ );
+ }
+
+ for (const { entry: decisionEntry, plugin, targetMessage } of validatedDecisions) {
+ const { decision, rejectionReason } = decisionEntry;
if (decision === 'approved') {
- await this.messageModel.updateMessagePlugin(resumeApproval.parentMessageId, {
+ await this.messageModel.updateMessagePlugin(decisionEntry.parentMessageId, {
intervention: { status: 'approved' },
});
+ approvedToolEntries.push({
+ createdAt: targetMessage.createdAt,
+ plugin,
+ toolMessageId: decisionEntry.parentMessageId,
+ });
+ approvalOwnerAssistantId ??= targetMessage.parentId ?? undefined;
} else {
// rejected / rejected_continue both write the same rejection content
// + intervention state. The difference surfaces later in how the new
@@ -1557,22 +1649,43 @@ export class AiAgentService {
const rejectionContent = rejectionReason
? `User reject this tool calling with reason: ${rejectionReason}`
: 'User reject this tool calling without reason';
- await this.messageModel.updateToolMessage(resumeApproval.parentMessageId, {
+ await this.messageModel.updateToolMessage(decisionEntry.parentMessageId, {
content: rejectionContent,
});
- await this.messageModel.updateMessagePlugin(resumeApproval.parentMessageId, {
+ await this.messageModel.updateMessagePlugin(decisionEntry.parentMessageId, {
intervention: { rejectedReason: rejectionReason, status: 'rejected' },
});
}
+ // Kept for the single-decision resume context at 16b, which reads the
+ // plugin of the op-level anchor message.
+ if (decisionEntry.parentMessageId === parentMessageId) resumeApprovalPlugin = plugin;
+
log(
'execAgent: resumeApproval decision=%s applied to tool message %s (toolCallId=%s)',
decision,
- resumeApproval.parentMessageId,
- resumeApproval.toolCallId,
+ decisionEntry.parentMessageId,
+ decisionEntry.toolCallId,
);
}
+ // The approval pause creates one row per pending tool sequentially, in the
+ // order the model emitted the calls — so row creation order IS declaration
+ // order, and sorting by it makes the resume independent of how the client
+ // happened to order its request array.
+ approvedToolEntries.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
+
+ /**
+ * Spine anchor for a batch approval: the ASSISTANT that emitted the batch —
+ * i.e. the previous LLM call. A step is one LLM call, and tool rows are
+ * inline data of the call that produced them, never spine nodes. So the
+ * continuation assistant created below chains directly onto that assistant
+ * (`user → asst → asst …`, tools hanging off their caller) rather than onto
+ * one of the batch's tool rows, which would make the spine depend on which
+ * tool row you happened to pick and on the order they were written in.
+ */
+ const batchApprovalAnchorId = resumeApprovals?.length ? approvalOwnerAssistantId : undefined;
+
// 2.7. Human-answer resume: a `humanIntervention: 'always'` tool (e.g.
// lobe-agent `askUserQuestion`) paused this run. Write the human-provided
// answer as the target tool message's result and mark the intervention
@@ -1865,8 +1978,11 @@ export class AiAgentService {
metadata: orchestrationMetadata,
model: isHeteroAgent ? undefined : model,
// Chain onto the user turn we just persisted; `parentMessageId` is the
- // anchor only on a resume, where no user message is created.
- parentId: userMessageRecord?.id ?? parentMessageId,
+ // anchor only on a resume, where no user message is created. A batch
+ // approval overrides it with the assistant that emitted the batch — the
+ // previous LLM call — so the spine stays one node per call and never
+ // depends on which of the batch's tool rows the client sent as anchor.
+ parentId: userMessageRecord?.id ?? batchApprovalAnchorId ?? parentMessageId,
provider: isHeteroAgent ? heteroType : provider,
role: 'assistant',
threadId: appContext?.threadId ?? undefined,
@@ -3821,7 +3937,42 @@ export class AiAgentService {
// decision is persisted, there's nothing meaningful to do differently
// server-side, and letting the LLM produce a brief acknowledgement keeps
// the conversation cleanly terminated either way.
- if (resumeApproval && resumeApprovalPlugin) {
+ // Batch approval: hand the runtime every approved tool at once so it runs a
+ // single `call_tools_batch` against the existing pending rows and continues
+ // the LLM exactly once, with the complete result set. Taken whenever the
+ // caller used the batch wire form; the single `resumeApproval` form keeps
+ // the established `call_tool` + `skipCreateToolMessage` path below.
+ if (resumeApprovals?.length && approvedToolEntries.length > 0) {
+ initialContext = {
+ initialContext: initialContext.initialContext,
+ payload: {
+ approvedToolCalls: approvedToolEntries.map(({ plugin }) => ({
+ apiName: plugin.apiName,
+ arguments: plugin.arguments,
+ id: plugin.toolCallId,
+ identifier: plugin.identifier,
+ type: plugin.type ?? 'default',
+ })),
+ assistantMessageId: assistantMessageRecord.id,
+ // The tool rows already exist and are parented to the assistant that
+ // emitted the calls; the batch executor addresses them through
+ // `toolMessageIds` and never inserts, so this only anchors the spine.
+ parentMessageId: approvalOwnerAssistantId ?? assistantMessageRecord.id,
+ toolMessageIds: Object.fromEntries(
+ approvedToolEntries
+ .filter(({ plugin }) => !!plugin.toolCallId)
+ .map(({ plugin, toolMessageId }) => [plugin.toolCallId!, toolMessageId]),
+ ),
+ } as any,
+ phase: 'human_approved_tool' as const,
+ session: {
+ messageCount: allMessages.length,
+ sessionId: operationId,
+ status: 'idle' as const,
+ stepCount: 0,
+ },
+ };
+ } else if (resumeApproval && resumeApprovalPlugin) {
if (resumeApproval.decision === 'approved') {
// Ask the runtime to execute the approved tool directly. Matches the
// `phase: 'human_approved_tool'` contract used by the in-place
@@ -5249,4 +5400,86 @@ export class AiAgentService {
threadId: thread?.id,
};
}
+
+ /**
+ * Stop a run that is parked waiting for tool approval: settle the pending
+ * tool rows and terminate the operation, WITHOUT executing anything and
+ * without continuing the model.
+ *
+ * This is the "from this step on, don't go any further" action. It is not the
+ * same as rejecting a tool — a rejection resumes the model so it can respond
+ * to the refusal, whereas stopping ends the turn outright.
+ *
+ * Why it can't reuse the ordinary cancel path: when the runtime parks it
+ * emits a stream-terminal `waiting_for_human`, so the client marks its own
+ * operation `completed` and prunes it ~30s later, and the topic's
+ * `runningOperation` pointer is cleared. By the time the user decides to
+ * stop, the client no longer knows the parked operation id — so we resolve it
+ * here from the topic instead of trusting the caller.
+ *
+ * The tool rows are settled IN PLACE (the approval pause already created one
+ * row per pending call). Inserting fresh aborted rows would duplicate every
+ * tool in the turn and leave the originals `pending`, which is exactly what
+ * keeps the approval cards on screen after a stop.
+ */
+ async stopPendingApproval(params: { toolMessageIds: string[]; topicId: string }): Promise<{
+ operationId?: string;
+ settledToolMessageIds: string[];
+ success: boolean;
+ }> {
+ const { toolMessageIds, topicId } = params;
+
+ // Validate every target before writing any of them: a half-settled batch
+ // would clear some cards while leaving the rest pointing at a run that is
+ // already gone.
+ const targets: { id: string }[] = [];
+ for (const toolMessageId of toolMessageIds) {
+ const message = await this.messageModel.findById(toolMessageId);
+ if (!message)
+ throw new Error(`stopPendingApproval: tool message not found: ${toolMessageId}`);
+ if (message.role !== 'tool') {
+ throw new Error(
+ `stopPendingApproval.toolMessageIds must point at role='tool' messages, got role='${message.role}'`,
+ );
+ }
+ if (message.topicId !== topicId) {
+ throw new Error('stopPendingApproval: topicId does not match the target tool message');
+ }
+ targets.push({ id: toolMessageId });
+ }
+
+ for (const target of targets) {
+ await this.messageModel.updateToolMessage(target.id, {
+ content: STOPPED_TOOL_CONTENT,
+ });
+ await this.messageModel.updateMessagePlugin(target.id, {
+ intervention: { status: 'aborted' },
+ } as any);
+ }
+
+ // Retire the parked operation so the topic does not keep a run that can
+ // never be resumed. Resolved from the topic because the client has lost the
+ // id by now (see the doc comment above).
+ const parkedOperationId = await this.agentOperationModel.findLatestParkedOperationId(topicId);
+ if (parkedOperationId) {
+ await this.agentRuntimeService.interruptOperation(parkedOperationId);
+ await this.agentOperationModel.recordCompletion(parkedOperationId, {
+ completedAt: new Date(),
+ completionReason: 'interrupted',
+ status: 'interrupted',
+ });
+ }
+
+ log(
+ 'stopPendingApproval: settled %d tool message(s), retired operation %s',
+ targets.length,
+ parkedOperationId ?? '(none)',
+ );
+
+ return {
+ operationId: parkedOperationId,
+ settledToolMessageIds: targets.map((t) => t.id),
+ success: true,
+ };
+ }
}
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 7ed9010a70b..0e61100d620 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1293,6 +1293,8 @@
"tokenTag.used": "Used",
"tool.intervention.approvalMode": "Approval Mode",
"tool.intervention.approve": "Approve",
+ "tool.intervention.approveAll": "Approve all {{count}}",
+ "tool.intervention.approveAllTooltip": "Run all {{count}} pending tool calls together, then continue",
"tool.intervention.mode.allowList": "Allow List",
"tool.intervention.mode.allowListDesc": "Only automatically execute approved tools",
"tool.intervention.mode.autoRun": "Auto Approve",
@@ -1324,6 +1326,8 @@
"tool.intervention.scrollToIntervention": "View",
"tool.intervention.skipMessage": "I'll skip this.",
"tool.intervention.skipMessageWithReason": "I'll skip this. {{reason}}",
+ "tool.intervention.stop": "Stop",
+ "tool.intervention.stopTooltip": "Stop here — nothing pending runs and the agent does not continue",
"tool.intervention.submit": "Submit",
"tool.intervention.toolAbort": "You canceled this Skill call",
"tool.intervention.toolRejected": "This Skill call was rejected",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 58f848b1b82..49d2697a9be 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1293,6 +1293,8 @@
"tokenTag.used": "已使用",
"tool.intervention.approvalMode": "审批模式",
"tool.intervention.approve": "批准",
+ "tool.intervention.approveAll": "全部通过({{count}})",
+ "tool.intervention.approveAllTooltip": "一次性执行全部 {{count}} 个待确认工具调用,然后继续",
"tool.intervention.mode.allowList": "白名单",
"tool.intervention.mode.allowListDesc": "仅自动执行已批准的技能",
"tool.intervention.mode.autoRun": "自动批准",
@@ -1324,6 +1326,8 @@
"tool.intervention.scrollToIntervention": "查看",
"tool.intervention.skipMessage": "先跳过这个问题。",
"tool.intervention.skipMessageWithReason": "先跳过这个问题。{{reason}}",
+ "tool.intervention.stop": "停止",
+ "tool.intervention.stopTooltip": "就停在这一步——待审批的工具都不会执行,Agent 也不会继续",
"tool.intervention.submit": "提交",
"tool.intervention.toolAbort": "你已取消本次技能调用",
"tool.intervention.toolRejected": "本次技能调用已被拒绝",
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
index da85d737bfe..883d920ae31 100644
--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts
+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
@@ -308,6 +308,12 @@ export class GeneralChatAgent implements Agent {
let hasToolsCalling = false;
let toolsCalling: ChatToolPayload[] = [];
let parentMessageId = '';
+ /**
+ * `tool_call_id → existing tool message id` for pending rows the approval
+ * pause already wrote. Carried to `resolve_aborted_tools` so it settles
+ * those rows instead of inserting duplicates beside them.
+ */
+ let existingToolMessageIds: Record<string, string> | undefined;
// Extract abort info based on current phase
switch (context.phase) {
@@ -331,19 +337,25 @@ export class GeneralChatAgent implements Agent {
case 'tools_batch_result': {
const payload = context.payload as GeneralAgentCallToolResultPayload;
parentMessageId = payload.parentMessageId;
- // Check if there are pending tool messages
- const pendingToolMessages = state.messages.filter(
- (m: any) => m.role === 'tool' && m.pluginIntervention?.status === 'pending',
- );
+ // Check if there are pending tool messages. Deliberately UN-scoped
+ // (unlike the loop guard): an abort must cancel every pending row it
+ // can see, including one whose owning assistant isn't in this state
+ // snapshot — leaving it pending strands it forever.
+ const pendingToolMessages = this.collectPendingToolMessages(state);
if (pendingToolMessages.length > 0) {
hasToolsCalling = true;
toolsCalling = pendingToolMessages.map((m: any) => m.plugin).filter(Boolean);
+ existingToolMessageIds = Object.fromEntries(
+ pendingToolMessages
+ .filter((m: any) => m.plugin?.id && m.id)
+ .map((m: any) => [m.plugin.id, m.id]),
+ );
}
break;
}
}
- return { hasToolsCalling, parentMessageId, toolsCalling };
+ return { existingToolMessageIds, hasToolsCalling, parentMessageId, toolsCalling };
}
/**
@@ -361,27 +373,104 @@ export class GeneralChatAgent implements Agent {
* stored as either model-native `tool_calls` or persisted `tools`. All pending
* tool messages legitimately belonging to this turn have
* `parentId === currentAssistantId`.
+ *
+ * Two message shapes reach this method and BOTH must be handled:
+ *
+ * 1. **Raw shape** (client runtime, and any step that never round-tripped
+ * through the DB): a `role: 'assistant'` row carrying `tools` /
+ * `tool_calls`, followed by sibling `role: 'tool'` rows whose
+ * `pluginIntervention.status` is the approval state.
+ * 2. **Parsed shape** (server runtime): `AgentRuntimeService` rebuilds
+ * `state.messages` from the DB through `conversation-flow`'s `parse()` on
+ * every step entry, and `FlatListBuilder` folds an assistant plus its tool
+ * rows into ONE `role: 'assistantGroup'` virtual message. In that shape
+ * there is no `role: 'assistant'` row carrying tools and no top-level
+ * `role: 'tool'` row at all — the tool calls live in
+ * `children[].tools[]`, each carrying `intervention` and `result_msg_id`.
+ *
+ * Matching only shape 1 made this guard a no-op on the entire server runtime:
+ * approving one tool of a parallel batch resumed the LLM immediately while the
+ * other N-1 tool rows were still `pending` with empty content, so the model
+ * saw blank tool results and (visibly, in reproduction) re-issued the whole
+ * batch. Every parallel-approval defect downstream of that — forked parent
+ * chains, duplicate batches — starts here.
*/
private getCurrentTurnPendingToolMessages(state: AgentState): any[] {
- let currentAssistantId: string | undefined;
- for (let i = state.messages.length - 1; i >= 0; i--) {
- const m = state.messages[i] as any;
+ const messages = (state.messages ?? []) as any[];
+
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const m = messages[i];
+
+ // Shape 2 — parsed `assistantGroup`. Read the folded tool entries; their
+ // `result_msg_id` is the tool message id the approval flow addresses.
+ if (this.isFoldedAssistantGroup(m)) {
+ return this.pendingToolMessagesFromGroup(m);
+ }
+
+ // Shape 1 — raw assistant + sibling tool rows.
if (m.role === 'assistant' && (m.tool_calls?.length > 0 || m.tools?.length > 0)) {
- currentAssistantId = m.id;
- break;
+ return messages.filter(
+ (t: any) =>
+ t.role === 'tool' && t.pluginIntervention?.status === 'pending' && t.parentId === m.id,
+ );
}
}
- if (!currentAssistantId) return [];
+ return [];
+ }
- return state.messages.filter(
- (m: any) =>
- m.role === 'tool' &&
- m.pluginIntervention?.status === 'pending' &&
- m.parentId === currentAssistantId,
+ /**
+ * Every pending tool message visible in `state.messages`, across BOTH shapes
+ * and WITHOUT turn scoping.
+ *
+ * Used by the abort path, whose contract is the inverse of the loop guard's:
+ * the guard must ignore stale rows so they can't park the loop forever, while
+ * an abort must resolve every pending row it can reach — including one whose
+ * owning assistant is absent from this snapshot — or that row stays `pending`
+ * with no runtime left to settle it.
+ */
+ private collectPendingToolMessages(state: AgentState): any[] {
+ const messages = (state.messages ?? []) as any[];
+
+ return messages.flatMap((m: any) => {
+ if (this.isFoldedAssistantGroup(m)) return this.pendingToolMessagesFromGroup(m);
+ if (m.role === 'tool' && m.pluginIntervention?.status === 'pending') return [m];
+ return [];
+ });
+ }
+
+ private isFoldedAssistantGroup(message: any): boolean {
+ return (
+ (message?.role === 'assistantGroup' || message?.role === 'supervisor') &&
+ (message.children ?? []).some((child: any) => child.tools?.length > 0)
);
}
+ /**
+ * Normalize an `assistantGroup`'s folded tool entries back into the tool-row
+ * shape the rest of the runner expects (`plugin`, `pluginIntervention`,
+ * `parentId`), keeping only the pending ones.
+ */
+ private pendingToolMessagesFromGroup(group: any): any[] {
+ return (group.children ?? [])
+ .flatMap((child: any) => child.tools ?? [])
+ .filter((tool: any) => tool.intervention?.status === 'pending')
+ .map((tool: any) => {
+ // Drop the display-only fields FlatListBuilder merges onto the entry so
+ // `plugin` is a plain ChatToolPayload — the same shape the raw path
+ // produces, and what `request_human_approve` / `call_tool` expect.
+ const { intervention, result: _result, result_msg_id, ...plugin } = tool;
+ return {
+ id: result_msg_id,
+ parentId: group.id,
+ plugin: plugin as ChatToolPayload,
+ pluginIntervention: intervention,
+ role: 'tool',
+ tool_call_id: tool.id,
+ };
+ });
+ }
+
/**
* Find existing compression summary from messages
* Looks for MessageGroup with type 'compression' and extracts its content
@@ -458,15 +547,13 @@ export class GeneralChatAgent implements Agent {
context: AgentRuntimeContext,
state: AgentState,
): AgentInstruction | AgentInstruction[] {
- const { hasToolsCalling, parentMessageId, toolsCalling } = this.extractAbortInfo(
- context,
- state,
- );
+ const { existingToolMessageIds, hasToolsCalling, parentMessageId, toolsCalling } =
+ this.extractAbortInfo(context, state);
// If there are pending tool calls, resolve them
if (hasToolsCalling && toolsCalling.length > 0) {
return {
- payload: { parentMessageId, toolsCalling },
+ payload: { existingToolMessageIds, parentMessageId, toolsCalling },
type: 'resolve_aborted_tools',
};
}
@@ -840,7 +927,10 @@ export class GeneralChatAgent implements Agent {
const { hasToolsCalling, parentMessageId, toolsCalling, reason } =
context.payload as HumanAbortPayload;
- // If there are pending tool calls, resolve them
+ // If there are pending tool calls, resolve them. No
+ // `existingToolMessageIds` here on purpose: this phase is an abort
+ // DURING llm streaming, where the calls came off the stream and no tool
+ // row has been written yet — the executor must insert.
if (hasToolsCalling && toolsCalling && toolsCalling.length > 0) {
return {
payload: { parentMessageId, toolsCalling },
diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
index 5240af06d02..1fa5198d1b0 100644
--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
@@ -1524,10 +1524,13 @@ describe('GeneralChatAgent', () => {
const result = await agent.runner(context, state);
- // Should handle abort and resolve pending tools
+ // Should handle abort and resolve pending tools, carrying the id of the
+ // row that already exists so the executor settles it instead of inserting
+ // a duplicate beside it.
expect(result).toEqual({
type: 'resolve_aborted_tools',
payload: {
+ existingToolMessageIds: { 'call-1': 'tool-msg-1' },
parentMessageId: 'msg-456',
toolsCalling: [
{
@@ -1542,6 +1545,66 @@ describe('GeneralChatAgent', () => {
});
});
+ it('carries existing tool message ids when aborting a FOLDED (server-shape) pending batch', async () => {
+ // The server runtime rebuilds `state.messages` through conversation-flow,
+ // which folds an assistant plus its tool rows into one `assistantGroup`.
+ // Without the ids, `resolve_aborted_tools` would insert a second row per
+ // call and leave the originals `pending` — the approval cards would
+ // survive the Stop.
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState({
+ status: 'interrupted',
+ messages: [
+ {
+ id: 'assistant-group-1',
+ role: 'assistantGroup',
+ children: [
+ {
+ tools: [
+ {
+ apiName: 'createPlan',
+ arguments: '{}',
+ id: 'call-alpha',
+ identifier: 'lobe-agent',
+ intervention: { status: 'pending' },
+ result_msg_id: 'pending-msg-alpha',
+ type: 'builtin',
+ },
+ {
+ apiName: 'createPlan',
+ arguments: '{}',
+ id: 'call-beta',
+ identifier: 'lobe-agent',
+ intervention: { status: 'pending' },
+ result_msg_id: 'pending-msg-beta',
+ type: 'builtin',
+ },
+ ],
+ },
+ ],
+ } as any,
+ ],
+ });
+
+ const context = createMockContext('tools_batch_result', {
+ parentMessageId: 'assistant-group-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect((result as any).type).toBe('resolve_aborted_tools');
+ expect((result as any).payload.existingToolMessageIds).toEqual({
+ 'call-alpha': 'pending-msg-alpha',
+ 'call-beta': 'pending-msg-beta',
+ });
+ expect((result as any).payload.toolsCalling).toHaveLength(2);
+ });
+
it('should return finish when state is interrupted with no tools', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
@@ -3611,4 +3674,172 @@ describe('GeneralChatAgent', () => {
]);
});
});
+ describe('pending approval guard across message shapes', () => {
+ // `AgentRuntimeService` rebuilds `state.messages` from the DB through
+ // conversation-flow's `parse()` on every server-runtime step, and
+ // `FlatListBuilder` folds an assistant plus its tool rows into ONE
+ // `role: 'assistantGroup'` message. Matching only the raw shape made this
+ // guard a permanent no-op there: approving one tool of a parallel batch
+ // resumed the LLM while the siblings were still pending empty rows.
+ const groupedToolEntry = (id: string, status: 'pending' | 'approved') => ({
+ apiName: 'calculate',
+ arguments: `{"expression":"${id}"}`,
+ id,
+ identifier: 'lobe-calculator',
+ intervention: { status },
+ result: { content: '', id: `tool-msg-${id}` },
+ result_msg_id: `tool-msg-${id}`,
+ type: 'builtin',
+ });
+
+ const parsedStateWith = (entries: any[]) =>
+ createMockState({
+ messages: [
+ { id: 'msg-user', role: 'user', content: 'calc' },
+ {
+ children: [{ content: '', id: 'msg-assistant', tools: entries }],
+ content: '',
+ id: 'msg-assistant',
+ role: 'assistantGroup',
+ },
+ ] as any,
+ });
+
+ it('re-parks on the parsed assistantGroup shape while siblings are still pending', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = parsedStateWith([
+ groupedToolEntry('call-a', 'approved'),
+ groupedToolEntry('call-b', 'pending'),
+ groupedToolEntry('call-c', 'pending'),
+ ]);
+
+ const result = await agent.runner(
+ createMockContext('tools_batch_result', { parentMessageId: 'tool-msg-call-a' }),
+ state,
+ );
+
+ expect(result).toMatchObject({
+ skipCreateToolMessage: true,
+ type: 'request_human_approve',
+ });
+ // The payload must be plain ChatToolPayloads — the display-only fields
+ // FlatListBuilder merges on (intervention/result/result_msg_id) would
+ // otherwise ride into `pendingToolsCalling` and back out to the client.
+ expect((result as any).pendingToolsCalling).toEqual([
+ {
+ apiName: 'calculate',
+ arguments: '{"expression":"call-b"}',
+ id: 'call-b',
+ identifier: 'lobe-calculator',
+ type: 'builtin',
+ },
+ {
+ apiName: 'calculate',
+ arguments: '{"expression":"call-c"}',
+ id: 'call-c',
+ identifier: 'lobe-calculator',
+ type: 'builtin',
+ },
+ ]);
+ });
+
+ it('continues to the LLM once every tool in the parsed group is resolved', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = parsedStateWith([
+ groupedToolEntry('call-a', 'approved'),
+ groupedToolEntry('call-b', 'approved'),
+ ]);
+
+ const result = await agent.runner(
+ createMockContext('tools_batch_result', { parentMessageId: 'tool-msg-call-b' }),
+ state,
+ );
+
+ expect((result as any).type).toBe('call_llm');
+ });
+
+ it('still re-parks on the raw assistant + tool-row shape', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const plugin = {
+ apiName: 'calculate',
+ arguments: '{"expression":"1+1"}',
+ id: 'call-b',
+ identifier: 'lobe-calculator',
+ type: 'builtin',
+ };
+
+ const state = createMockState({
+ messages: [
+ { id: 'msg-assistant', role: 'assistant', content: '', tools: [plugin] },
+ {
+ content: '',
+ id: 'tool-msg-b',
+ parentId: 'msg-assistant',
+ plugin,
+ pluginIntervention: { status: 'pending' },
+ role: 'tool',
+ },
+ ] as any,
+ });
+
+ const result = await agent.runner(
+ createMockContext('tools_batch_result', { parentMessageId: 'tool-msg-b' }),
+ state,
+ );
+
+ expect(result).toMatchObject({ type: 'request_human_approve' });
+ expect((result as any).pendingToolsCalling).toEqual([plugin]);
+ });
+
+ it('ignores a stale pending row from an earlier turn', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState({
+ messages: [
+ {
+ children: [
+ { content: '', id: 'msg-old', tools: [groupedToolEntry('stale', 'pending')] },
+ ],
+ content: '',
+ id: 'msg-old',
+ role: 'assistantGroup',
+ },
+ {
+ children: [
+ { content: '', id: 'msg-new', tools: [groupedToolEntry('call-new', 'approved')] },
+ ],
+ content: '',
+ id: 'msg-new',
+ role: 'assistantGroup',
+ },
+ ] as any,
+ });
+
+ const result = await agent.runner(
+ createMockContext('tools_batch_result', { parentMessageId: 'tool-msg-call-new' }),
+ state,
+ );
+
+ expect((result as any).type).toBe('call_llm');
+ });
+ });
});
diff --git a/packages/agent-runtime/src/core/__tests__/runtime.test.ts b/packages/agent-runtime/src/core/__tests__/runtime.test.ts
index 57bafcd69bc..9fc8bbc9c58 100644
--- a/packages/agent-runtime/src/core/__tests__/runtime.test.ts
+++ b/packages/agent-runtime/src/core/__tests__/runtime.test.ts
@@ -377,6 +377,58 @@ describe('AgentRuntime', () => {
expect(result.newState.pendingAssistantMessageId).toBe('msg_seeded_placeholder');
});
+ // "Approve all" on a parallel batch resolves every pending tool in one
+ // action. The resume must run them as ONE call_tools_batch against the
+ // rows the approval pause already created — approving them one at a time
+ // instead continues the LLM once per tool, each seeing its not-yet-
+ // approved siblings as empty results.
+ it('should dispatch a single call_tools_batch when a batch of approvals resumes', async () => {
+ const agent = new MockAgent();
+ const batchExecutor = vi.fn().mockResolvedValue({
+ events: [],
+ newState: AgentRuntime.createInitialState({ operationId: 'test-session' }),
+ });
+ agent.executors = { call_tools_batch: batchExecutor } as any;
+
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
+
+ const approvedToolCalls = ['call_a', 'call_b'].map((id) => ({
+ apiName: 'calculate',
+ arguments: '{"expression": "2+2"}',
+ id,
+ identifier: 'lobe-calculator',
+ type: 'default' as const,
+ }));
+
+ await runtime.step(state, {
+ operationId: 'test-session',
+ phase: 'human_approved_tool',
+ payload: {
+ approvedToolCalls,
+ assistantMessageId: 'msg_seeded_placeholder',
+ parentMessageId: 'msg_assistant',
+ toolMessageIds: { call_a: 'tool-msg-a', call_b: 'tool-msg-b' },
+ },
+ session: {
+ sessionId: 'test-session',
+ messageCount: 0,
+ status: 'idle',
+ stepCount: 0,
+ },
+ } as any);
+
+ expect(batchExecutor).toHaveBeenCalledTimes(1);
+ expect(batchExecutor.mock.calls[0][0]).toEqual({
+ payload: {
+ existingToolMessageIds: { call_a: 'tool-msg-a', call_b: 'tool-msg-b' },
+ parentMessageId: 'msg_assistant',
+ toolsCalling: approvedToolCalls,
+ },
+ type: 'call_tools_batch',
+ });
+ });
+
it('should stash a tool_result-seeded assistantMessageId as pendingAssistantMessageId', async () => {
const agent = new MockAgent();
agent.runner = vi.fn(async (_context: AgentRuntimeContext, state: AgentState) => {
diff --git a/packages/agent-runtime/src/core/runtime.ts b/packages/agent-runtime/src/core/runtime.ts
index dfee448c090..02256a6b359 100644
--- a/packages/agent-runtime/src/core/runtime.ts
+++ b/packages/agent-runtime/src/core/runtime.ts
@@ -110,12 +110,19 @@ export class AgentRuntime {
// Handle human approved tool calls
if (runtimeContext.phase === 'human_approved_tool') {
const approvedPayload = runtimeContext.payload as {
- approvedToolCall: ChatToolPayload;
+ approvedToolCall?: ChatToolPayload;
+ /**
+ * Batch approval — every tool the user approved in ONE action.
+ * Present instead of `approvedToolCall` when the client resolved the
+ * whole pending batch at once.
+ */
+ approvedToolCalls?: ChatToolPayload[];
assistantMessageId?: string;
parentMessageId: string;
- skipCreateToolMessage: boolean;
+ skipCreateToolMessage?: boolean;
+ /** `tool_call_id → pending tool message id`, batch path only. */
+ toolMessageIds?: Record<string, string>;
};
- const toolCalling = approvedPayload.approvedToolCall;
// The resume seeded an assistant placeholder (assistantMessageId) for
// this operation, but the first instruction here is a tool execution —
@@ -128,14 +135,31 @@ export class AgentRuntime {
newState.pendingAssistantMessageId = approvedPayload.assistantMessageId;
}
- rawInstructions = {
- payload: {
- parentMessageId: approvedPayload.parentMessageId,
- skipCreateToolMessage: approvedPayload.skipCreateToolMessage,
- toolCalling,
- },
- type: 'call_tool',
- };
+ const approvedBatch = approvedPayload.approvedToolCalls ?? [];
+
+ if (approvedBatch.length > 0) {
+ // Run every approved tool in ONE batch, exactly as the original
+ // (pre-approval) `call_tools_batch` would have. Approving them one at
+ // a time instead means one LLM continuation per tool, each seeing the
+ // not-yet-approved siblings as empty results.
+ rawInstructions = {
+ payload: {
+ existingToolMessageIds: approvedPayload.toolMessageIds ?? {},
+ parentMessageId: approvedPayload.parentMessageId,
+ toolsCalling: approvedBatch,
+ },
+ type: 'call_tools_batch',
+ };
+ } else {
+ rawInstructions = {
+ payload: {
+ parentMessageId: approvedPayload.parentMessageId,
+ skipCreateToolMessage: approvedPayload.skipCreateToolMessage,
+ toolCalling: approvedPayload.approvedToolCall,
+ },
+ type: 'call_tool',
+ };
+ }
} else {
if (runtimeContext.phase === 'tool_result') {
const toolResultPayload = runtimeContext.payload as
diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.ts
index 20ecf07c6c0..3a741085b2b 100644
--- a/packages/agent-runtime/src/executors/callLlm.test.ts
+++ b/packages/agent-runtime/src/executors/callLlm.test.ts
@@ -73,6 +73,7 @@ const createMessageTransport = (): MessageTransport => ({
query: vi.fn(),
update: vi.fn(),
updatePluginState: vi.fn(),
+ updateToolIntervention: vi.fn(),
updateToolMessage: vi.fn(),
});
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
index b48138dab16..2b397ba630f 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
@@ -21,6 +21,7 @@ const createMessageTransport = (): MessageTransport => ({
query: vi.fn(),
update: vi.fn().mockResolvedValue(undefined),
updatePluginState: vi.fn(),
+ updateToolIntervention: vi.fn(),
updateToolMessage: vi.fn(),
});
diff --git a/packages/agent-runtime/src/executors/humanApprove.test.ts b/packages/agent-runtime/src/executors/humanApprove.test.ts
index abed8cbaf39..1ca35459cdc 100644
--- a/packages/agent-runtime/src/executors/humanApprove.test.ts
+++ b/packages/agent-runtime/src/executors/humanApprove.test.ts
@@ -48,11 +48,13 @@ const pendingTool = {
describe('requestHumanApprove', () => {
let createToolMessage: ReturnType<typeof vi.fn>;
+ let deleteMessage: ReturnType<typeof vi.fn>;
let query: ReturnType<typeof vi.fn>;
let host: AgentRuntimeHost;
beforeEach(() => {
createToolMessage = vi.fn().mockResolvedValue({ id: 'tool-msg-1' });
+ deleteMessage = vi.fn().mockResolvedValue(undefined);
query = vi.fn().mockResolvedValue([]);
host = {
@@ -64,7 +66,7 @@ describe('requestHumanApprove', () => {
topicId: 'topic-1',
},
transports: {
- messages: { createToolMessage, query },
+ messages: { createToolMessage, deleteMessage, query },
stream: { publishChunk: vi.fn(), publishEvent: vi.fn() },
},
} as unknown as AgentRuntimeHost;
@@ -159,4 +161,49 @@ describe('requestHumanApprove', () => {
(host.transports.stream.publishChunk as ReturnType<typeof vi.fn>).mock.calls[0][0],
).toMatchObject({ toolMessageIds: { call_ask_1: 'tool-msg-existing' } });
});
+ describe('unconsumed assistant placeholder', () => {
+ // A resume op (approve / answer) seeds an assistant placeholder so the UI
+ // shows a spinner, and the first `call_llm` claims it. Parking here means no
+ // `call_llm` ran — the approved tool executed and the batch still has
+ // unresolved siblings — so the placeholder would linger as an empty "…"
+ // assistant hanging off the tool that was just settled.
+ const instruction = {
+ parentMessageId: 'assistant-msg-1',
+ pendingToolsCalling: [pendingTool],
+ skipCreateToolMessage: true,
+ type: 'request_human_approve',
+ } as unknown as AgentInstruction;
+
+ it('retires the seeded placeholder when the run parks without calling the LLM', async () => {
+ const result = await requestHumanApprove(host)(
+ instruction,
+ createState({ pendingAssistantMessageId: 'assistant-placeholder-1' }),
+ undefined as any,
+ );
+
+ expect(deleteMessage).toHaveBeenCalledWith('assistant-placeholder-1');
+ expect(result.newState.pendingAssistantMessageId).toBeUndefined();
+ expect(result.newState.status).toBe('waiting_for_human');
+ });
+
+ it('parks normally when no placeholder was seeded', async () => {
+ const result = await requestHumanApprove(host)(instruction, createState(), undefined as any);
+
+ expect(deleteMessage).not.toHaveBeenCalled();
+ expect(result.newState.status).toBe('waiting_for_human');
+ });
+
+ it('still parks when retiring the placeholder fails', async () => {
+ deleteMessage.mockRejectedValue(new Error('db down'));
+
+ const result = await requestHumanApprove(host)(
+ instruction,
+ createState({ pendingAssistantMessageId: 'assistant-placeholder-1' }),
+ undefined as any,
+ );
+
+ expect(result.newState.status).toBe('waiting_for_human');
+ expect(result.newState.pendingToolsCalling).toEqual([pendingTool]);
+ });
+ });
});
diff --git a/packages/agent-runtime/src/executors/humanApprove.ts b/packages/agent-runtime/src/executors/humanApprove.ts
index 9924df91985..87d415f6cfe 100644
--- a/packages/agent-runtime/src/executors/humanApprove.ts
+++ b/packages/agent-runtime/src/executors/humanApprove.ts
@@ -58,6 +58,23 @@ export const requestHumanApprove =
newState.status = 'waiting_for_human';
newState.pendingToolsCalling = pendingToolsCalling;
+ // A resume op (approve / answer) seeds an assistant placeholder up front so
+ // the UI has a spinner row, and the first `call_llm` claims it. Parking here
+ // means no `call_llm` ever ran — the tool executed, and the batch still has
+ // unresolved siblings — so that placeholder would be left behind as an empty
+ // "…" assistant hanging off the tool we just settled. Retire it: the next
+ // resume seeds its own, and the run has produced no assistant content to
+ // keep. Best-effort — a failed delete must not strand the approval pause.
+ if (newState.pendingAssistantMessageId) {
+ const orphanId = newState.pendingAssistantMessageId;
+ newState.pendingAssistantMessageId = undefined;
+ try {
+ await transports.messages.deleteMessage(orphanId);
+ } catch {
+ // leaving the placeholder is cosmetic; parking correctly is not
+ }
+ }
+
// Map of toolCallId -> toolMessageId, populated either by creating fresh
// pending tool messages or (in resumption mode) by looking up existing ones.
const toolMessageIds: Record<string, string> = {};
diff --git a/packages/agent-runtime/src/executors/resolveTools.test.ts b/packages/agent-runtime/src/executors/resolveTools.test.ts
index 90bf0c12e52..1abb51eb1fd 100644
--- a/packages/agent-runtime/src/executors/resolveTools.test.ts
+++ b/packages/agent-runtime/src/executors/resolveTools.test.ts
@@ -207,6 +207,41 @@ describe('resolveTools executors', () => {
);
});
+ it('settles an already-persisted pending row in place instead of inserting a duplicate', async () => {
+ // Aborting a parked approval: the pause already wrote one tool row per
+ // pending call. Inserting fresh aborted rows here would duplicate every
+ // tool in the turn AND leave the originals `pending`, so the approval cards
+ // survive the Stop that was supposed to clear them.
+ const updateToolMessage = vi.fn().mockResolvedValue(undefined);
+ const updateToolIntervention = vi.fn().mockResolvedValue(undefined);
+ host.transports.messages.updateToolMessage = updateToolMessage;
+ host.transports.messages.updateToolIntervention = updateToolIntervention;
+
+ const instruction: Extract<AgentInstruction, { type: 'resolve_aborted_tools' }> = {
+ payload: {
+ existingToolMessageIds: { 'tool-call-1': 'pending-msg-1' },
+ parentMessageId: 'assistant-msg-1',
+ toolsCalling: [createToolCall('tool-call-1'), createToolCall('tool-call-2')],
+ },
+ type: 'resolve_aborted_tools',
+ };
+
+ const result = await resolveAbortedTools(host)(instruction, createState());
+
+ expect(updateToolMessage).toHaveBeenCalledWith('pending-msg-1', {
+ content: 'Tool execution was aborted by user.',
+ });
+ expect(updateToolIntervention).toHaveBeenCalledWith('pending-msg-1', { status: 'aborted' });
+
+ // The call with no existing row still gets one created — mixed batches are
+ // resolved per call, not all-or-nothing.
+ expect(createToolMessage).toHaveBeenCalledTimes(1);
+ expect(createToolMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ tool_call_id: 'tool-call-2' }),
+ );
+ expect(result.newState.status).toBe('done');
+ });
+
it('publishes and rethrows persist errors', async () => {
const error = new Error('database went away');
createToolMessage.mockRejectedValueOnce(error);
diff --git a/packages/agent-runtime/src/executors/resolveTools.ts b/packages/agent-runtime/src/executors/resolveTools.ts
index 02c3a6e029c..658c846ac64 100644
--- a/packages/agent-runtime/src/executors/resolveTools.ts
+++ b/packages/agent-runtime/src/executors/resolveTools.ts
@@ -210,20 +210,36 @@ export const resolveAbortedTools =
const newState = structuredClone(state);
+ const existingToolMessageIds = payload.existingToolMessageIds ?? {};
+
for (const toolPayload of payload.toolsCalling) {
+ const existingMessageId = existingToolMessageIds[toolPayload.id];
try {
- await transports.messages.createToolMessage({
- agentId,
- content: ABORTED_TOOL_CONTENT,
- groupId,
- parentId: payload.parentMessageId,
- plugin: toolPayload as any,
- pluginIntervention: { status: 'aborted' },
- role: 'tool',
- threadId,
- tool_call_id: toolPayload.id,
- topicId,
- });
+ if (existingMessageId) {
+ // The approval pause already wrote a row for this call. Settle THAT
+ // row: inserting a second one would duplicate the tool in the turn
+ // and leave the original `pending`, so the approval card survives the
+ // Stop that was supposed to clear it.
+ await transports.messages.updateToolMessage(existingMessageId, {
+ content: ABORTED_TOOL_CONTENT,
+ });
+ await transports.messages.updateToolIntervention(existingMessageId, {
+ status: 'aborted',
+ });
+ } else {
+ await transports.messages.createToolMessage({
+ agentId,
+ content: ABORTED_TOOL_CONTENT,
+ groupId,
+ parentId: payload.parentMessageId,
+ plugin: toolPayload as any,
+ pluginIntervention: { status: 'aborted' },
+ role: 'tool',
+ threadId,
+ tool_call_id: toolPayload.id,
+ topicId,
+ });
+ }
} catch (error) {
await publishPersistError(host, error);
throw error;
diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.ts
index 43ecd80d343..4d4353c3021 100644
--- a/packages/agent-runtime/src/executors/tool.test.ts
+++ b/packages/agent-runtime/src/executors/tool.test.ts
@@ -441,7 +441,9 @@ describe('tool executors', () => {
expect(createToolMessage).not.toHaveBeenCalled();
expect(host.transports.messages.updateToolMessage).not.toHaveBeenCalled();
- expect(result.nextContext?.payload).toMatchObject({ parentMessageId: 'client-tool-msg' });
+ // The transport-persisted row is still just tool output hanging off the
+ // calling assistant; the spine anchor stays that assistant.
+ expect(result.nextContext?.payload).toMatchObject({ parentMessageId: 'assistant-msg-1' });
});
it('publishes and rethrows tool-message persist errors', async () => {
@@ -463,6 +465,141 @@ describe('tool executors', () => {
});
});
+ describe('parallel batch parent chain', () => {
+ // The next assistant turn hangs off `nextContext.parentMessageId`. A step is
+ // ONE LLM call, and a batch's tool rows are inline data of the call that
+ // emitted them — so the anchor is that assistant, never a tool row. Picking
+ // a tool row made the spine depend on which promise settled last: the parent
+ // chain forked, and a DFS over the parentId forest (how a topic is ordered
+ // for reading) emitted the losing tools after the rest of the conversation.
+ const batchOf = (ids: string[]): Extract<AgentInstruction, { type: 'call_tools_batch' }> => ({
+ payload: {
+ parentMessageId: 'assistant-msg-1',
+ toolsCalling: ids.map((id) => createToolCall(id)),
+ },
+ type: 'call_tools_batch',
+ });
+
+ it('anchors the next turn on the assistant that emitted the batch, not a tool row', async () => {
+ // Finish order is deliberately the reverse of declaration order.
+ const delays: Record<string, number> = { 'call-a': 30, 'call-b': 20, 'call-c': 0 };
+ runTool = vi.fn().mockImplementation(async (tool: { id: string }) => {
+ await new Promise((resolve) => setTimeout(resolve, delays[tool.id] ?? 0));
+ return {
+ attempts: 1,
+ result: { content: `result ${tool.id}`, executionTime: 1, state: {}, success: true },
+ };
+ });
+ createToolMessage = vi
+ .fn()
+ .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({
+ id: `tool-msg-${tool_call_id}`,
+ }));
+ host.transports.tools!.run = runTool;
+ host.transports.messages.createToolMessage = createToolMessage;
+
+ const result = await callToolsBatch(host)(
+ batchOf(['call-a', 'call-b', 'call-c']),
+ createState(),
+ );
+
+ expect(result.nextContext?.phase).toBe('tools_batch_result');
+ expect(result.nextContext?.payload).toMatchObject({
+ parentMessageId: 'assistant-msg-1',
+ });
+ });
+
+ it('is stable across runs regardless of which tool resolves first', async () => {
+ const parents: string[] = [];
+
+ for (const delays of [
+ { 'call-a': 0, 'call-b': 10, 'call-c': 20 },
+ { 'call-a': 20, 'call-b': 0, 'call-c': 10 },
+ { 'call-a': 10, 'call-b': 20, 'call-c': 0 },
+ ]) {
+ host.transports.tools!.run = vi.fn().mockImplementation(async (tool: { id: string }) => {
+ await new Promise((resolve) => setTimeout(resolve, (delays as any)[tool.id] ?? 0));
+ return {
+ attempts: 1,
+ result: { content: 'ok', executionTime: 1, state: {}, success: true },
+ };
+ });
+ host.transports.messages.createToolMessage = vi
+ .fn()
+ .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({
+ id: `tool-msg-${tool_call_id}`,
+ }));
+
+ const result = await callToolsBatch(host)(
+ batchOf(['call-a', 'call-b', 'call-c']),
+ createState(),
+ );
+ parents.push((result.nextContext?.payload as any).parentMessageId);
+ }
+
+ expect(parents).toEqual(['assistant-msg-1', 'assistant-msg-1', 'assistant-msg-1']);
+ });
+
+ it('keeps the assistant anchor when a tool in the batch fails', async () => {
+ host.transports.tools!.run = vi.fn().mockImplementation(async (tool: { id: string }) => {
+ if (tool.id === 'call-c') throw new Error('tool blew up');
+ if (tool.id === 'call-a') await new Promise((resolve) => setTimeout(resolve, 20));
+ return {
+ attempts: 1,
+ result: { content: 'ok', executionTime: 1, state: {}, success: true },
+ };
+ });
+ host.transports.messages.createToolMessage = vi
+ .fn()
+ .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({
+ id: `tool-msg-${tool_call_id}`,
+ }));
+
+ const result = await callToolsBatch(host)(
+ batchOf(['call-a', 'call-b', 'call-c']),
+ createState(),
+ );
+
+ // A tool row was never the anchor, so a tool that produced no message
+ // can't leave the spine empty either.
+ expect(result.nextContext?.payload).toMatchObject({
+ parentMessageId: 'assistant-msg-1',
+ });
+ });
+
+ it('fills existing pending rows in place when resuming an approved batch', async () => {
+ const updateToolMessage = vi.fn().mockResolvedValue(undefined);
+ host.transports.messages.updateToolMessage = updateToolMessage;
+ host.transports.messages.createToolMessage = createToolMessage;
+
+ const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {
+ payload: {
+ existingToolMessageIds: { 'call-a': 'pending-msg-a', 'call-b': 'pending-msg-b' },
+ parentMessageId: 'assistant-msg-1',
+ toolsCalling: [createToolCall('call-a'), createToolCall('call-b')],
+ },
+ type: 'call_tools_batch',
+ };
+
+ const result = await callToolsBatch(host)(instruction, createState());
+
+ // Creating fresh rows here would strand the approved-but-empty originals
+ // under the same assistant.
+ expect(createToolMessage).not.toHaveBeenCalled();
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'pending-msg-a',
+ expect.objectContaining({ content: 'Tool result' }),
+ );
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'pending-msg-b',
+ expect.objectContaining({ content: 'Tool result' }),
+ );
+ // Resuming an approved batch continues from the assistant that emitted
+ // it, exactly like a batch that never paused.
+ expect(result.nextContext?.payload).toMatchObject({ parentMessageId: 'assistant-msg-1' });
+ });
+ });
+
describe('work registration redaction', () => {
// A skill intent carries the UNTRUNCATED tool payload (`data`/`args`) solely
// for server-side Work registration. It must NOT ride the published stream
diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.ts
index 5abd200e51b..ca46869cc4e 100644
--- a/packages/agent-runtime/src/executors/tool.ts
+++ b/packages/agent-runtime/src/executors/tool.ts
@@ -591,6 +591,8 @@ export const callToolsBatch =
const { payload } = instruction as Extract<AgentInstruction, { type: 'call_tools_batch' }>;
const parentMessageId = payload.parentMessageId as string;
const toolsCalling = payload.toolsCalling as ChatToolPayload[];
+ // Batch human approval resumes onto rows the approval pause already created.
+ const existingToolMessageIds = (payload.existingToolMessageIds ?? {}) as Record<string, string>;
const tools = requireToolTransport(host);
const events: AgentEvent[] = [];
const clientTools: ChatToolPayload[] = [];
@@ -611,7 +613,6 @@ export const callToolsBatch =
});
}
- const toolMessageIds: string[] = [];
const toolResults: ToolResultEntry[] = [];
const deferredTools: ChatToolPayload[] = [];
// `tool_call_id → placeholder message id` for the deferred tools in this batch.
@@ -620,13 +621,16 @@ export const callToolsBatch =
await Promise.all(
toolsToExecute.map(async (tool) => {
+ const existingMessageId = existingToolMessageIds[tool.id];
const runContext = createRunContext({
host,
mode: 'batch',
parentMessageId,
+ reuseExistingMessage: !!existingMessageId,
state,
stepContext: runtimeContext?.stepContext,
tool,
+ toolMessageId: existingMessageId,
});
await host.transports.stream.publishEvent({
@@ -669,6 +673,12 @@ export const callToolsBatch =
if (!execution.resultPersisted) {
await updateExistingToolMessage({ host, result: executionResult, toolMessageId });
}
+ } else if (existingMessageId) {
+ // Batch approval resume: fill the pending placeholder in place.
+ // Creating a fresh row here would leave the approved-but-empty
+ // original stranded under the same assistant.
+ toolMessageId = existingMessageId;
+ await updateExistingToolMessage({ host, result: executionResult, toolMessageId });
} else {
const toolMessage = await createToolMessage({
host,
@@ -679,7 +689,6 @@ export const callToolsBatch =
});
toolMessageId = toolMessage.id;
}
- toolMessageIds.push(toolMessageId);
// `sourceMessageId` + `workRegistration` are carried so the
// post-batch accumulate loop can persist the Work version ONCE with
@@ -795,7 +804,15 @@ export const callToolsBatch =
newState,
nextContext: {
payload: {
- parentMessageId: toolMessageIds.at(-1) ?? parentMessageId,
+ // The assistant that emitted this batch — i.e. the previous LLM call.
+ // A step is one LLM call, and the batch's tool rows are inline data of
+ // that call, so the continuation assistant chains onto the caller and
+ // the tools stay its children. Anchoring on a tool row instead makes
+ // the spine depend on which tool `Promise.all` happened to settle
+ // last, which forks the parent chain and (via the reader's DFS over
+ // the parentId forest) strands the other tools after the whole rest of
+ // the conversation.
+ parentMessageId,
toolCount: toolsCalling.length,
toolResults,
},
diff --git a/packages/agent-runtime/src/transport/message.ts b/packages/agent-runtime/src/transport/message.ts
index e4902959cd2..8691ad3eb22 100644
--- a/packages/agent-runtime/src/transport/message.ts
+++ b/packages/agent-runtime/src/transport/message.ts
@@ -73,5 +73,15 @@ export interface MessageTransport {
query: (params?: QueryMessagesInput, options?: QueryMessagesOptions) => Promise<UIChatMessage[]>;
update: (id: string, params: Partial<UpdateMessageParams>) => Promise<void>;
updatePluginState: (id: string, state: Record<string, any>) => Promise<void>;
+ /**
+ * Move an existing tool row out of its `pending` approval state.
+ *
+ * Separate from {@link updateToolMessage} because intervention lives on the
+ * plugin row, not the message row. The abort path needs it: a parked approval
+ * already has one tool row per pending call, and Stop must settle THOSE rows —
+ * inserting fresh aborted rows instead leaves the originals `pending`, so the
+ * approval cards never clear.
+ */
+ updateToolIntervention: (id: string, intervention: Record<string, any>) => Promise<void>;
updateToolMessage: (id: string, params: UpdateToolMessageInput) => Promise<void>;
}
diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.ts
index a7bfa4cbc9a..7319f52da84 100644
--- a/packages/agent-runtime/src/types/instruction.ts
+++ b/packages/agent-runtime/src/types/instruction.ts
@@ -258,6 +258,14 @@ export interface AgentInstructionCallTool extends AgentInstructionBase {
export interface AgentInstructionCallToolsBatch extends AgentInstructionBase {
payload: {
+ /**
+ * `tool_call_id → existing tool message id`, for tools whose row already
+ * exists as a pending placeholder (batch human approval: the approval pause
+ * created one row per pending tool). The executor UPDATES those rows instead
+ * of inserting new ones — without this, resuming an approved batch would
+ * duplicate every tool message and orphan the pending originals.
+ */
+ existingToolMessageIds?: Record<string, string>;
parentMessageId: string;
toolsCalling: ChatToolPayload[];
} & any;
@@ -266,6 +274,15 @@ export interface AgentInstructionCallToolsBatch extends AgentInstructionBase {
export interface AgentInstructionResolveAbortedTools extends AgentInstructionBase {
payload: {
+ /**
+ * `tool_call_id → existing tool message id`, for calls whose row is already
+ * on disk as a pending placeholder (an approval pause creates one row per
+ * pending tool). The executor UPDATES those rows to the aborted state
+ * instead of inserting new ones — without this, aborting a parked approval
+ * duplicates every tool row and leaves the originals `pending`, so the
+ * approval cards stay on screen after Stop.
+ */
+ existingToolMessageIds?: Record<string, string>;
/** Parent message ID (assistant message) */
parentMessageId: string;
/** Reason for the abort */
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
index af04cc1681f..226ef30c9f3 100644
--- a/packages/database/src/models/agentOperation.ts
+++ b/packages/database/src/models/agentOperation.ts
@@ -130,6 +130,31 @@ export class AgentOperationModel {
await this.db.insert(agentOperations).values(values).onConflictDoNothing();
}
+ /**
+ * Newest operation in this topic that is parked waiting for tool approval.
+ *
+ * A parked run is stream-terminal, so the client marks its own operation
+ * completed and prunes it — by the time the user decides to stop, only the
+ * DB still knows which operation is holding the turn. Scoped by `userId` so
+ * one user can never resolve (and then terminate) another's run.
+ */
+ async findLatestParkedOperationId(topicId: string): Promise<string | undefined> {
+ const [row] = await this.db
+ .select({ id: agentOperations.id })
+ .from(agentOperations)
+ .where(
+ and(
+ eq(agentOperations.topicId, topicId),
+ eq(agentOperations.userId, this.userId),
+ eq(agentOperations.status, 'waiting_for_human'),
+ ),
+ )
+ .orderBy(sql`${agentOperations.createdAt} desc`)
+ .limit(1);
+
+ return row?.id;
+ }
+
/**
* Update the row when the operation reaches a terminal state. Scoped by
* `userId` so a leaked operationId can't be used to flip another user's
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 0bced053843..6cb5f6661bf 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1476,9 +1476,15 @@ export default {
'tokenTag.used': 'Used',
'tool.intervention.approvalMode': 'Approval Mode',
'tool.intervention.approve': 'Approve',
+ 'tool.intervention.approveAll': 'Approve all {{count}}',
+ 'tool.intervention.approveAllTooltip':
+ 'Run all {{count}} pending tool calls together, then continue',
'tool.intervention.optionApprove': 'Approve',
'tool.intervention.optionApproveRemember': "Approve, and don't ask again for similar actions",
'tool.intervention.rememberSimilar': "Don't ask again for similar actions",
+ 'tool.intervention.stop': 'Stop',
+ 'tool.intervention.stopTooltip':
+ 'Stop here — nothing pending runs and the agent does not continue',
'tool.intervention.renderFallback.description':
'This display was downgraded to raw JSON because the current model was not capable enough to generate a stable interactive payload. Switch to a stronger model and try again.',
'tool.intervention.renderFallback.rawJson': 'Raw JSON',
diff --git a/src/features/Conversation/InterventionBar/InterventionTabBar.tsx b/src/features/Conversation/InterventionBar/InterventionTabBar.tsx
index d511bf3a0f0..4ff43cf360f 100644
--- a/src/features/Conversation/InterventionBar/InterventionTabBar.tsx
+++ b/src/features/Conversation/InterventionBar/InterventionTabBar.tsx
@@ -1,17 +1,33 @@
+import { Tooltip } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
import { cx } from 'antd-style';
+import { CheckCheck } from 'lucide-react';
import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
import { type PendingIntervention } from '../store/slices/data/pendingInterventions';
import { styles } from './style';
interface InterventionTabBarProps {
activeIndex: number;
+ /**
+ * Batch-approval affordance. Omitted entirely by hosts that don't offer one.
+ *
+ * `count` is the active card's OWN parallel batch, which can be smaller than
+ * the tab list: the tab list spans the whole conversation, so it may also
+ * hold an abandoned approval from an earlier turn. Bundling count with the
+ * handler makes "a button whose label counts calls it won't resolve"
+ * unrepresentable.
+ */
+ approveAll?: { count: number; loading?: boolean; onApprove: () => void };
interventions: PendingIntervention[];
onTabChange: (index: number) => void;
}
const InterventionTabBar = memo<InterventionTabBarProps>(
- ({ interventions, activeIndex, onTabChange }) => {
+ ({ interventions, activeIndex, approveAll, onTabChange }) => {
+ const { t } = useTranslation('chat');
+
return (
<div className={styles.tabBar}>
{interventions.map((item, index) => (
@@ -23,8 +39,27 @@ const InterventionTabBar = memo<InterventionTabBarProps>(
🔧 {item.apiName}
</div>
))}
- <div className={styles.tabCounter}>
- {activeIndex + 1} / {interventions.length}
+ <div className={styles.tabTrailing}>
+ <span className={styles.tabCounter}>
+ {activeIndex + 1} / {interventions.length}
+ </span>
+ {/* Only shown for a real batch: with one pending call in the active
+ turn the per-card Submit already IS "approve all", and a second
+ button beside it would just add a decision the user doesn't have
+ to make. */}
+ {approveAll && (
+ <Tooltip title={t('tool.intervention.approveAllTooltip', { count: approveAll.count })}>
+ <Button
+ icon={CheckCheck}
+ loading={approveAll.loading}
+ size={'small'}
+ type={'fill'}
+ onClick={approveAll.onApprove}
+ >
+ {t('tool.intervention.approveAll', { count: approveAll.count })}
+ </Button>
+ </Tooltip>
+ )}
</div>
</div>
);
diff --git a/src/features/Conversation/InterventionBar/index.tsx b/src/features/Conversation/InterventionBar/index.tsx
index 32101a05288..d1aa6bb629a 100644
--- a/src/features/Conversation/InterventionBar/index.tsx
+++ b/src/features/Conversation/InterventionBar/index.tsx
@@ -1,7 +1,12 @@
import { ChatInput } from '@lobehub/editor/react';
import { memo, useCallback, useMemo, useState } from 'react';
-import { type PendingIntervention } from '../store/slices/data/pendingInterventions';
+import { useConversationResourceAccess } from '../hooks/useConversationResourceAccess';
+import { useConversationStore } from '../store';
+import {
+ getInterventionBatch,
+ type PendingIntervention,
+} from '../store/slices/data/pendingInterventions';
import InterventionContent from './InterventionContent';
import InterventionTabBar from './InterventionTabBar';
import { styles } from './style';
@@ -13,6 +18,13 @@ interface InterventionBarProps {
const InterventionBar = memo<InterventionBarProps>(({ interventions }) => {
const [activeId, setActiveId] = useState<string | null>(null);
const [actionsPortalTarget, setActionsPortalTarget] = useState<HTMLDivElement | null>(null);
+ const [approveAllLoading, setApproveAllLoading] = useState(false);
+
+ const approveAllToolCalls = useConversationStore((s) => s.approveAllToolCalls);
+ // Workspace topics are shared: a view-only member can be looking at a
+ // teammate's run and must not drive its approvals — same gate the per-card
+ // actions apply.
+ const { canUseResource } = useConversationResourceAccess();
// Derive the active index from the stored toolCallId.
// Falls back to the first intervention when the previously active one is resolved.
@@ -32,20 +44,50 @@ const InterventionBar = memo<InterventionBarProps>(({ interventions }) => {
);
const activeIntervention = interventions[activeIndex];
+
+ // The active card's own parallel batch. `interventions` spans the whole
+ // conversation, so approve-all must never act on the raw list.
+ const batch = useMemo(
+ () => getInterventionBatch(interventions, activeIntervention),
+ [interventions, activeIntervention],
+ );
+
+ const handleApproveAll = useCallback(async () => {
+ if (approveAllLoading) return;
+ setApproveAllLoading(true);
+ try {
+ await approveAllToolCalls(batch.map((i) => i.toolMessageId));
+ } finally {
+ setApproveAllLoading(false);
+ }
+ }, [approveAllLoading, approveAllToolCalls, batch]);
+
if (!activeIntervention) return null;
+ // Tabs still list every pending call so nothing is hidden; only the batch
+ // action is scoped to the active turn.
+ const hasMultipleCards = interventions.length > 1;
+ const canApproveBatch = batch.length > 1;
+
return (
<ChatInput
data-pending-hotkey-scope
className={styles.container}
footer={<div className={styles.actions} ref={setActionsPortalTarget} />}
- maxHeight={'50vh' as any}
resize={false}
+ // The card's action row — Stop sits beside Submit inside `ApprovalActions`
+ // and the whole row portals in here.
+ maxHeight={'50vh' as any}
>
- {interventions.length > 1 && (
+ {hasMultipleCards && (
<InterventionTabBar
activeIndex={activeIndex}
interventions={interventions}
+ approveAll={
+ canUseResource && canApproveBatch
+ ? { count: batch.length, loading: approveAllLoading, onApprove: handleApproveAll }
+ : undefined
+ }
onTabChange={handleTabChange}
/>
)}
diff --git a/src/features/Conversation/InterventionBar/style.ts b/src/features/Conversation/InterventionBar/style.ts
index 276fc8b2436..feee640a00d 100644
--- a/src/features/Conversation/InterventionBar/style.ts
+++ b/src/features/Conversation/InterventionBar/style.ts
@@ -52,12 +52,18 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
border-block-end: 1px solid ${cssVar.colorBorderSecondary};
`,
tabCounter: css`
- margin-inline-start: auto;
- padding-block: 5px;
- padding-inline: 10px;
-
font-size: 11px;
color: ${cssVar.colorTextTertiary};
white-space: nowrap;
`,
+ tabTrailing: css`
+ display: flex;
+ flex-shrink: 0;
+ gap: 8px;
+ align-items: center;
+
+ margin-inline-start: auto;
+ padding-block: 4px;
+ padding-inline: 10px;
+ `,
}));
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx
index 9ae8d5faac4..3c6396500f1 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx
@@ -2,7 +2,7 @@ import { registerPendingHotkeyCard } from '@lobechat/shared-tool-ui/pending-hotk
import { Flexbox } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
import { createStaticStyles, cx } from 'antd-style';
-import { CornerDownLeft } from 'lucide-react';
+import { CircleStop, CornerDownLeft } from 'lucide-react';
import type { KeyboardEvent as ReactKeyboardEvent } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -35,7 +35,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
footer: css`
display: flex;
+ gap: 8px;
+ align-items: center;
justify-content: flex-end;
+
margin-block-start: 8px;
`,
number: css`
@@ -148,9 +151,37 @@ const ApprovalActions = memo<ApprovalActionsProps>(
[isAllowListMode],
);
- const [approveToolCall, rejectAndContinueToolCall] = useConversationStore((s) => [
- s.approveToolCall,
- s.rejectAndContinueToolCall,
+ const [approveToolCall, rejectAndContinueToolCall, stopPendingApprovalForCard] =
+ useConversationStore((s) => [
+ s.approveToolCall,
+ s.rejectAndContinueToolCall,
+ s.stopPendingApprovalForCard,
+ ]);
+ const [stopping, setStopping] = useState(false);
+
+ /**
+ * "Stop here — don't continue." Sits beside Submit because it answers the
+ * same question the card is asking; splitting the two across the bar makes
+ * the user hunt for the one they want.
+ *
+ * Not a rejection: rejecting writes a reason and lets the model respond,
+ * stopping ends the turn outright and executes nothing.
+ */
+ const handleStop = useCallback(async () => {
+ if (stopping || loading || isMessageCreating || !canUseResource) return;
+ setStopping(true);
+ try {
+ await stopPendingApprovalForCard(messageId);
+ } finally {
+ setStopping(false);
+ }
+ }, [
+ stopping,
+ loading,
+ isMessageCreating,
+ canUseResource,
+ stopPendingApprovalForCard,
+ messageId,
]);
const addToolToAllowList = useUserStore((s) => s.addToolToAllowList);
@@ -339,6 +370,16 @@ const ApprovalActions = memo<ApprovalActionsProps>(
</div>
<div className={styles.footer}>
+ <Button
+ disabled={loading || isMessageCreating}
+ icon={CircleStop}
+ loading={stopping}
+ size={'middle'}
+ type={'text'}
+ onClick={handleStop}
+ >
+ {t('tool.intervention.stop')}
+ </Button>
<Button
className={styles.submitButton}
disabled={isMessageCreating}
diff --git a/src/features/Conversation/store/slices/data/pendingInterventions.test.ts b/src/features/Conversation/store/slices/data/pendingInterventions.test.ts
new file mode 100644
index 00000000000..cdb3c7b3280
--- /dev/null
+++ b/src/features/Conversation/store/slices/data/pendingInterventions.test.ts
@@ -0,0 +1,97 @@
+import type { UIChatMessage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { getInterventionBatch, getPendingInterventions } from './pendingInterventions';
+
+const toolMessage = (id: string, toolCallId: string, parentId?: string): UIChatMessage =>
+ ({
+ id,
+ parentId,
+ plugin: {
+ apiName: 'createPlan',
+ arguments: '{}',
+ id: toolCallId,
+ identifier: 'lobe-agent',
+ type: 'builtin',
+ },
+ pluginIntervention: { status: 'pending' },
+ role: 'tool',
+ tool_call_id: toolCallId,
+ }) as any;
+
+const assistantGroup = (id: string, toolCallIds: string[]): UIChatMessage =>
+ ({
+ children: [
+ {
+ tools: toolCallIds.map((toolCallId) => ({
+ apiName: 'createPlan',
+ arguments: '{}',
+ id: toolCallId,
+ identifier: 'lobe-agent',
+ intervention: { status: 'pending' },
+ result_msg_id: `msg-${toolCallId}`,
+ type: 'builtin',
+ })),
+ },
+ ],
+ id,
+ role: 'assistantGroup',
+ }) as any;
+
+describe('getPendingInterventions', () => {
+ it('records the owning assistant for a standalone tool row', () => {
+ const [pending] = getPendingInterventions([toolMessage('msg-1', 'call-1', 'assistant-1')]);
+
+ // Without an owner, a bulk action cannot tell this call apart from one that
+ // belongs to a different turn.
+ expect(pending.assistantGroupId).toBe('assistant-1');
+ });
+
+ it('records the owning assistant for a folded assistantGroup', () => {
+ const pending = getPendingInterventions([assistantGroup('assistant-1', ['call-1', 'call-2'])]);
+
+ expect(pending.map((p) => p.assistantGroupId)).toEqual(['assistant-1', 'assistant-1']);
+ });
+
+ it('spans the whole conversation, including an abandoned approval from an earlier turn', () => {
+ const pending = getPendingInterventions([
+ toolMessage('msg-stale', 'call-stale', 'assistant-old'),
+ assistantGroup('assistant-new', ['call-1', 'call-2']),
+ ]);
+
+ // This is exactly why length alone must never gate a bulk approval.
+ expect(pending).toHaveLength(3);
+ });
+});
+
+describe('getInterventionBatch', () => {
+ it('keeps only the calls emitted by the active card’s own assistant turn', () => {
+ const pending = getPendingInterventions([
+ toolMessage('msg-stale', 'call-stale', 'assistant-old'),
+ assistantGroup('assistant-new', ['call-1', 'call-2']),
+ ]);
+ const active = pending.find((p) => p.toolCallId === 'call-1')!;
+
+ const batch = getInterventionBatch(pending, active);
+
+ // Approving across turns would resolve `call-stale` under this turn's
+ // assistant anchor and continue the model once with unrelated results.
+ expect(batch.map((b) => b.toolCallId)).toEqual(['call-1', 'call-2']);
+ });
+
+ it('treats an entry with no resolvable owner as its own batch', () => {
+ const pending = getPendingInterventions([
+ toolMessage('msg-1', 'call-1'),
+ toolMessage('msg-2', 'call-2'),
+ ]);
+ const active = pending.find((p) => p.toolCallId === 'call-1')!;
+
+ // Both have `assistantGroupId === undefined`; grouping by that value would
+ // fold two unrelated calls into one pseudo-batch.
+ expect(getInterventionBatch(pending, active).map((b) => b.toolCallId)).toEqual(['call-1']);
+ });
+
+ it('returns nothing when there is no active card', () => {
+ expect(getInterventionBatch([], undefined)).toEqual([]);
+ });
+});
diff --git a/src/features/Conversation/store/slices/data/pendingInterventions.ts b/src/features/Conversation/store/slices/data/pendingInterventions.ts
index f13bdda3ba9..408cf19cf15 100644
--- a/src/features/Conversation/store/slices/data/pendingInterventions.ts
+++ b/src/features/Conversation/store/slices/data/pendingInterventions.ts
@@ -2,6 +2,16 @@ import type { ChatToolPayloadWithResult, ToolIntervention, UIChatMessage } from
export interface PendingIntervention {
apiName: string;
+ /**
+ * Id of the assistant turn that emitted this tool call.
+ *
+ * The list itself spans the WHOLE conversation, so any consumer that wants to
+ * act on "this parallel batch" (e.g. approve-all) must group by this field
+ * first — two pending calls can belong to different turns, and resolving them
+ * together would execute them under one anchor with unrelated results.
+ * `undefined` means the owner could not be determined; treat such an entry as
+ * its own group rather than folding it in with the others.
+ */
assistantGroupId?: string;
identifier: string;
intervention: ToolIntervention & { status: 'pending' };
@@ -25,6 +35,8 @@ export const getPendingInterventions = (
) {
pending.push({
apiName: msg.plugin.apiName,
+ // A standalone tool row parents directly to its calling assistant.
+ assistantGroupId: msg.parentId,
identifier: msg.plugin.identifier,
intervention: msg.pluginIntervention as ToolIntervention & { status: 'pending' },
requestArgs: msg.plugin.arguments || '',
@@ -45,6 +57,30 @@ export const getPendingInterventions = (
return pending;
};
+/**
+ * Narrow a whole-conversation pending list down to ONE parallel batch — the
+ * calls emitted by the same assistant turn as `active`.
+ *
+ * `getPendingInterventions` walks every message, so its length says nothing
+ * about batch membership: an abandoned approval from an earlier turn sits in
+ * the same list as this turn's calls. Any bulk action must group first —
+ * resolving across turns hands the server a set it executes under one assistant
+ * anchor and continues the model once with unrelated results, running a tool the
+ * user never meant to release into this turn.
+ *
+ * An entry whose owner cannot be resolved is its own batch: unknown owners must
+ * not collapse into one pseudo-group.
+ */
+export const getInterventionBatch = (
+ interventions: PendingIntervention[],
+ active: PendingIntervention | undefined,
+): PendingIntervention[] => {
+ if (!active) return [];
+ const owner = active.assistantGroupId;
+ if (!owner) return [active];
+ return interventions.filter((i) => i.assistantGroupId === owner);
+};
+
const collectPendingTools = (
tools: ChatToolPayloadWithResult[],
pending: PendingIntervention[],
diff --git a/src/features/Conversation/store/slices/tool/action.ts b/src/features/Conversation/store/slices/tool/action.ts
index 6497cbcb94d..6745a3d46f8 100644
--- a/src/features/Conversation/store/slices/tool/action.ts
+++ b/src/features/Conversation/store/slices/tool/action.ts
@@ -2,6 +2,8 @@ import { useChatStore } from '@/store/chat';
import { type StoreSetter } from '@/store/types';
import { type Store as ConversationStore } from '../../action';
+import { getInterventionBatch } from '../data/pendingInterventions';
+import { dataSelectors } from '../data/selectors';
/**
* Tool Interaction Actions
@@ -44,6 +46,72 @@ export class ToolActionImpl {
}
};
+ /**
+ * Approve every pending tool of a parallel batch in one action.
+ *
+ * Args edits are flushed for all cards first: the intervention UI debounces
+ * `updatePluginArguments`, so approving without waiting would ship the
+ * pre-edit arguments for any card the user had just typed in.
+ */
+ /**
+ * Stop a run parked on tool approval — nothing in the batch executes and the
+ * model is not continued.
+ *
+ * No `waitForPendingArgsUpdate` here, unlike approval: the arguments are
+ * about to be discarded, so flushing a debounced edit into a call that will
+ * never run is pure latency.
+ */
+ stopPendingApproval = async (toolMessageIds: string[]): Promise<void> => {
+ const { context } = this.#get();
+ await useChatStore.getState().stopPendingApproval(toolMessageIds, context);
+ };
+
+ /**
+ * Stop from a single card: resolve that card's own parallel batch and stop
+ * the whole thing.
+ *
+ * Scoped the same way approve-all is — the pending list spans the entire
+ * conversation, so stopping the raw list would also discard an unrelated
+ * turn's approval.
+ */
+ stopPendingApprovalForCard = async (toolMessageId: string): Promise<void> => {
+ const state = this.#get();
+ const pending = dataSelectors.pendingInterventions(state);
+ const active = pending.find((item) => item.toolMessageId === toolMessageId);
+ const batch = getInterventionBatch(pending, active);
+ const ids = batch.length > 0 ? batch.map((item) => item.toolMessageId) : [toolMessageId];
+
+ await useChatStore.getState().stopPendingApproval(ids, state.context);
+ };
+
+ approveAllToolCalls = async (toolMessageIds: string[]): Promise<void> => {
+ const { hooks, context, waitForPendingArgsUpdate } = this.#get();
+
+ await Promise.all(toolMessageIds.map((id) => waitForPendingArgsUpdate(id)));
+
+ // ===== Hook: onToolApproved =====
+ // Per tool, so a host that vetoes one card drops only that card from the
+ // batch rather than cancelling the whole approval.
+ const approved: string[] = [];
+ for (const toolMessageId of toolMessageIds) {
+ if (hooks.onToolApproved) {
+ const shouldProceed = await hooks.onToolApproved(toolMessageId);
+ if (shouldProceed === false) continue;
+ }
+ approved.push(toolMessageId);
+ }
+
+ if (approved.length === 0) return;
+
+ const chatStore = useChatStore.getState();
+ await chatStore.approveAllToolCalls(approved, context);
+
+ // ===== Hook: onToolCallComplete =====
+ if (hooks.onToolCallComplete) {
+ for (const toolMessageId of approved) hooks.onToolCallComplete(toolMessageId, undefined);
+ }
+ };
+
cancelToolInteraction = async (toolMessageId: string): Promise<void> => {
const { context } = this.#get();
const chatStore = useChatStore.getState();
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 8a2ecd47107..8c5620b4faa 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -72,6 +72,12 @@ export interface ExecAgentTaskParams {
prompt: string;
/** Resume a previous op paused on `human_approve_required` instead of starting from a fresh user prompt. */
resumeApproval?: ResumeApprovalParam;
+ /**
+ * Batch form of `resumeApproval` — one entry per pending tool resolved in a
+ * single "approve all" action. The server applies every decision, runs all
+ * approved tools as ONE `call_tools_batch`, and continues the LLM once.
+ */
+ resumeApprovals?: ResumeApprovalParam[];
/** Resume a previous op paused on a human-intervention tool by carrying the human answer as the tool result. */
resumeToolResult?: ResumeToolResultParam;
/** Tool identifiers the user @-mentioned in this message; the server enables them for this run. */
@@ -214,6 +220,17 @@ class AiAgentService {
return await lambdaClient.aiAgent.interruptTask.mutate(params);
}
+ /**
+ * Stop a run parked on tool approval: settle the pending tool rows and end
+ * the operation without running anything or continuing the model.
+ *
+ * Not `interruptTask` — that one assumes a live loop will persist the
+ * outcome, which a parked run does not have.
+ */
+ async stopPendingApproval(params: { toolMessageIds: string[]; topicId: string }) {
+ return await lambdaClient.aiAgent.stopPendingApproval.mutate(params);
+ }
+
/**
* Create Thread for client-side task execution (desktop only, single agent mode)
*
diff --git a/src/store/chat/agents/transports/ClientMessageTransport.ts b/src/store/chat/agents/transports/ClientMessageTransport.ts
index 311fcd11a57..17d3a282bf6 100644
--- a/src/store/chat/agents/transports/ClientMessageTransport.ts
+++ b/src/store/chat/agents/transports/ClientMessageTransport.ts
@@ -102,6 +102,16 @@ export class ClientMessageTransport implements MessageTransport {
await this.persist([{ id, type: 'updateToolMessage', value: { pluginState: state } }]);
}
+ async updateToolIntervention(id: string, intervention: Record<string, any>): Promise<void> {
+ // `optimisticUpdateMessagePlugin` also mirrors the change onto the calling
+ // assistant's `tools[]` entry, which is what the intervention card reads
+ // once the conversation has been folded — updating only the tool row would
+ // clear the state in the store while the card kept rendering.
+ await this.get().optimisticUpdateMessagePlugin(id, { intervention } as any, {
+ operationId: this.operationId,
+ });
+ }
+
async updateToolMessage(id: string, params: UpdateToolMessageInput): Promise<void> {
const store = this.get();
const optimisticContext = { operationId: this.operationId };
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 5ab36f9716a..7264c51ecdf 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
@@ -2590,4 +2590,177 @@ describe('ConversationControl actions', () => {
);
});
});
+ describe('approveAllToolCalls', () => {
+ const agentId = 'server-agent';
+ const topicId = 'server-topic';
+ const chatKey = messageMapKey({ agentId, topicId, threadId: undefined });
+
+ const seedPendingBatch = (result: any) => {
+ const assistantMessage = createMockMessage({ id: 'assistant-msg-1', role: 'assistant' });
+ const toolMessages = ['a', 'b', 'c'].map((suffix, index) =>
+ createMockMessage({
+ id: `tool-msg-${suffix}`,
+ parentId: assistantMessage.id,
+ plugin: {
+ apiName: 'calculate',
+ arguments: `{"expression":"${index}"}`,
+ identifier: 'lobe-calculator',
+ type: 'default',
+ },
+ role: 'tool',
+ tool_call_id: `call_${suffix}`,
+ } as any),
+ );
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: topicId,
+ dbMessagesMap: { [chatKey]: [assistantMessage, ...toolMessages] },
+ messagesMap: { [chatKey]: [assistantMessage, ...toolMessages] },
+ });
+ });
+
+ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);
+ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);
+ };
+
+ // The whole point of the batch path: ONE gateway op carrying every decision.
+ // Looping single approvals starts one op per tool, and each continues the
+ // LLM while its siblings are still empty pending rows.
+ it('resolves the whole batch through a single gateway op', async () => {
+ const { result } = renderHook(() => useChatStore());
+ seedPendingBatch(result);
+
+ const executeGatewayAgentSpy = vi
+ .spyOn(result.current, 'executeGatewayAgent')
+ .mockResolvedValue({} as any);
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
+ .mockResolvedValue(undefined);
+
+ await act(async () => {
+ await result.current.approveAllToolCalls(['tool-msg-a', 'tool-msg-b', 'tool-msg-c']);
+ });
+
+ expect(executeGatewayAgentSpy).toHaveBeenCalledTimes(1);
+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: '',
+ parentMessageId: 'tool-msg-c',
+ resumeApprovals: [
+ { decision: 'approved', parentMessageId: 'tool-msg-a', toolCallId: 'call_a' },
+ { decision: 'approved', parentMessageId: 'tool-msg-b', toolCallId: 'call_b' },
+ { decision: 'approved', parentMessageId: 'tool-msg-c', toolCallId: 'call_c' },
+ ],
+ }),
+ );
+ expect(executeClientAgentSpy).not.toHaveBeenCalled();
+
+ executeGatewayAgentSpy.mockRestore();
+ });
+
+ it('marks every card approved so the bar settles in one paint', async () => {
+ const { result } = renderHook(() => useChatStore());
+ seedPendingBatch(result);
+
+ const optimisticSpy = vi.mocked(result.current.optimisticUpdateMessagePlugin);
+ optimisticSpy.mockClear();
+ const executeGatewayAgentSpy = vi
+ .spyOn(result.current, 'executeGatewayAgent')
+ .mockResolvedValue({} as any);
+
+ await act(async () => {
+ await result.current.approveAllToolCalls(['tool-msg-a', 'tool-msg-b', 'tool-msg-c']);
+ });
+
+ for (const id of ['tool-msg-a', 'tool-msg-b', 'tool-msg-c']) {
+ expect(optimisticSpy).toHaveBeenCalledWith(
+ id,
+ { intervention: { status: 'approved' } },
+ expect.anything(),
+ );
+ }
+
+ executeGatewayAgentSpy.mockRestore();
+ });
+
+ // An optimistic row has no server identity yet, so the server can't address
+ // it; sending it would fail the whole batch instead of just that card.
+ it('drops rows the server cannot address', async () => {
+ const { result } = renderHook(() => useChatStore());
+ seedPendingBatch(result);
+
+ const executeGatewayAgentSpy = vi
+ .spyOn(result.current, 'executeGatewayAgent')
+ .mockResolvedValue({} as any);
+
+ await act(async () => {
+ await result.current.approveAllToolCalls(['tool-msg-a', 'tmp_pending', 'tool-msg-c']);
+ });
+
+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ resumeApprovals: [
+ { decision: 'approved', parentMessageId: 'tool-msg-a', toolCallId: 'call_a' },
+ { decision: 'approved', parentMessageId: 'tool-msg-c', toolCallId: 'call_c' },
+ ],
+ }),
+ );
+
+ executeGatewayAgentSpy.mockRestore();
+ });
+
+ // Client mode has no batch resume; its local runtime re-parks on the
+ // remaining pending tools after each approval, so sequential is correct.
+ it('falls back to sequential approvals in client mode', async () => {
+ const { result } = renderHook(() => useChatStore());
+ seedPendingBatch(result);
+ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(false);
+
+ vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue({
+ agentConfig: createMockResolvedAgentConfig(),
+ context: { phase: 'init' } as any,
+ state: {} as any,
+ });
+ const executeGatewayAgentSpy = vi
+ .spyOn(result.current, 'executeGatewayAgent')
+ .mockResolvedValue({} as any);
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
+ .mockResolvedValue(undefined);
+
+ await act(async () => {
+ await result.current.approveAllToolCalls(['tool-msg-a', 'tool-msg-b']);
+ });
+
+ expect(executeGatewayAgentSpy).not.toHaveBeenCalled();
+ // One local resume per tool, in order — the runtime re-parks on the
+ // remaining pending tools between them.
+ expect(executeClientAgentSpy).toHaveBeenCalledTimes(2);
+ expect(
+ executeClientAgentSpy.mock.calls.map((call) => (call[0] as any).parentMessageId),
+ ).toEqual(['tool-msg-a', 'tool-msg-b']);
+
+ executeClientAgentSpy.mockRestore();
+ executeGatewayAgentSpy.mockRestore();
+ });
+
+ it('is a no-op for an empty batch', async () => {
+ const { result } = renderHook(() => useChatStore());
+ seedPendingBatch(result);
+
+ const executeGatewayAgentSpy = vi
+ .spyOn(result.current, 'executeGatewayAgent')
+ .mockResolvedValue({} as any);
+
+ await act(async () => {
+ await result.current.approveAllToolCalls([]);
+ });
+
+ expect(executeGatewayAgentSpy).not.toHaveBeenCalled();
+
+ executeGatewayAgentSpy.mockRestore();
+ });
+ });
});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
index 0b95165fca0..30ec4245155 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
@@ -11,6 +11,7 @@ import { t } from 'i18next';
import { type ChatInputEditor } from '@/features/ChatInput';
import { lambdaClient } from '@/libs/trpc/client';
+import { aiAgentService } from '@/services/aiAgent';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { displayMessageSelectors } from '@/store/chat/selectors';
@@ -530,6 +531,171 @@ export class ConversationControlActionImpl {
}
};
+ /**
+ * Approve every pending tool of a parallel batch in ONE action.
+ *
+ * Server mode resolves the whole batch through a single Gateway op carrying
+ * `resumeApprovals`, so the run executes all approved tools as one
+ * `call_tools_batch` and continues the LLM exactly once with the complete
+ * result set. Looping `approveToolCalling` instead would start one op per
+ * tool, and each op continues the run while its siblings are still empty
+ * pending rows — which is what forks the parent chain and shows the model
+ * blank tool results.
+ *
+ * Client mode has no batch resume: the local runtime re-parks on the
+ * remaining pending tools after each approval, so sequential approvals are
+ * already correct there. Approvals are issued in order and awaited so the
+ * runtime never sees two resumes racing on the same assistant turn.
+ */
+ /**
+ * Stop a run parked on tool approval — "from this step on, don't continue".
+ *
+ * Distinct from rejecting a tool: a rejection resumes the model so it can
+ * respond to the refusal, whereas stopping ends the turn outright. Nothing
+ * in the batch executes.
+ *
+ * This cannot go through the ordinary cancel actions: they all filter on
+ * `status === 'running'`, and a parked run's client operation is `completed`
+ * (the server's park is stream-terminal) and pruned ~30s later, so the client
+ * no longer holds the parked operation id. The server resolves it from the
+ * topic instead.
+ */
+ stopPendingApproval = async (
+ toolMessageIds: string[],
+ context?: ConversationContext,
+ ): Promise<void> => {
+ if (toolMessageIds.length === 0) return;
+
+ const effectiveContext: ConversationContext = context ?? {
+ agentId: this.#get().activeAgentId,
+ topicId: this.#get().activeTopicId,
+ threadId: this.#get().activeThreadId,
+ };
+
+ const topicId = effectiveContext.topicId;
+ if (!topicId) {
+ console.warn('[stopPendingApproval] no active topic; skipping');
+ return;
+ }
+
+ // Only rows the server can address — an optimistic `tmp_` row has no server
+ // identity yet.
+ const addressable = toolMessageIds.filter((id) => !id.startsWith('tmp_'));
+ if (addressable.length === 0) return;
+
+ // Clear the cards in one paint rather than letting them wink out one by one
+ // as the server catches up.
+ await Promise.all(
+ addressable.map((toolMessageId) =>
+ this.#get().optimisticUpdateMessagePlugin(toolMessageId, {
+ intervention: { status: 'aborted' },
+ }),
+ ),
+ );
+
+ const pausedOpIds = this.#getRunningServerOps(effectiveContext).map((op) => op.id);
+
+ try {
+ await aiAgentService.stopPendingApproval({ toolMessageIds: addressable, topicId });
+ this.#completeOpsById(pausedOpIds);
+ } catch (error) {
+ console.error('[stopPendingApproval] failed:', error);
+ throw error;
+ }
+ };
+
+ approveAllToolCalls = async (
+ toolMessageIds: string[],
+ context?: ConversationContext,
+ ): Promise<void> => {
+ if (toolMessageIds.length === 0) return;
+
+ const effectiveContext: ConversationContext = context ?? {
+ agentId: this.#get().activeAgentId,
+ topicId: this.#get().activeTopicId,
+ threadId: this.#get().activeThreadId,
+ };
+
+ if (!this.#shouldUseGatewayResume(effectiveContext)) {
+ for (const toolMessageId of toolMessageIds) {
+ await this.approveToolCalling(toolMessageId, '', effectiveContext);
+ }
+ return;
+ }
+
+ const { completeOperation, startOperation } = this.#get();
+
+ // Drop anything that can't be addressed: an optimistic row (`tmp_`) has no
+ // server identity yet, and a tool message without `tool_call_id` can't be
+ // matched to its pending call.
+ const decisions = toolMessageIds
+ .map((toolMessageId) => {
+ const toolMessage = dbMessageSelectors.getDbMessageById(toolMessageId)(this.#get());
+ const toolCallId = toolMessage?.tool_call_id;
+ return toolCallId && !toolMessageId.startsWith('tmp_')
+ ? { decision: 'approved' as const, parentMessageId: toolMessageId, toolCallId }
+ : undefined;
+ })
+ .filter((decision) => !!decision);
+
+ if (decisions.length === 0) {
+ console.warn('[approveAllToolCalls][server] no addressable pending tools; skipping resume');
+ return;
+ }
+
+ // The op-level anchor. The server re-derives the spine anchor from the
+ // batch itself, so this only has to be one of the batch's own rows.
+ const anchorMessageId = decisions.at(-1)!.parentMessageId;
+
+ const { operationId } = startOperation({
+ type: 'approveToolCalling',
+ context: { ...effectiveContext, messageId: anchorMessageId },
+ });
+
+ const optimisticContext = { operationId };
+
+ this.#emitRunResumed(effectiveContext, {
+ operationId,
+ parentMessageId: anchorMessageId,
+ runtimeType: 'gateway',
+ });
+
+ // Mark every card approved up front so the whole intervention bar settles in
+ // one paint instead of clearing card-by-card as the server catches up.
+ await Promise.all(
+ decisions.map((decision) =>
+ this.#get().optimisticUpdateMessagePlugin(
+ decision.parentMessageId,
+ { intervention: { status: 'approved' } },
+ optimisticContext,
+ ),
+ ),
+ );
+
+ const requestMetadata = this.#getRequestMetadataFromMessageChain(anchorMessageId);
+ const pausedOpIds = this.#getRunningServerOps(effectiveContext).map((op) => op.id);
+
+ try {
+ await this.#get().executeGatewayAgent({
+ context: effectiveContext,
+ message: '',
+ metadata: requestMetadata,
+ parentMessageId: anchorMessageId,
+ resumeApprovals: decisions,
+ });
+ this.#writeTopicStatus(effectiveContext, 'active');
+ this.#completeOpsById(pausedOpIds);
+ completeOperation(operationId);
+ } catch (error) {
+ const err = error as Error;
+ console.error('[approveAllToolCalls][server] Gateway resume failed:', err);
+ this.#get().failOperation(operationId, {
+ type: 'approveToolCalling',
+ message: err.message || 'Unknown error',
+ });
+ }
+ };
+
submitToolInteraction = async (
toolMessageId: string,
response: Record<string, unknown>,
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 423702944d9..0c859a83039 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -405,6 +405,12 @@ export class GatewayActionImpl {
* a fresh user prompt.
*/
resumeApproval?: ResumeApprovalParam;
+ /**
+ * Batch form of `resumeApproval` — every decision made in one "approve all"
+ * action. Forwarded so the server resolves the whole pending batch in a
+ * single op instead of one op (and one LLM continuation) per tool.
+ */
+ resumeApprovals?: ResumeApprovalParam[];
/**
* Resume a paused op waiting on a human-intervention tool (e.g. lobe-agent
* `askUserQuestion`). Forwarded to `aiAgentService.execAgentTask` so the new
@@ -448,6 +454,7 @@ export class GatewayActionImpl {
parentMessageId,
parentOperationId,
resumeApproval,
+ resumeApprovals,
resumeToolResult,
selectedToolIds,
mentionedAgents,
@@ -541,6 +548,7 @@ export class GatewayActionImpl {
parentMessageId,
prompt: message,
resumeApproval,
+ resumeApprovals,
resumeToolResult,
selectedToolIds,
trigger: metadata?.trigger,