🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(agent-runtime): 步骤恢复时不再重复执行已完成的工具调用 (#22058)
Mochac0e4591793ac
diff --git a/apps/cli/src/runtime/CliMessageTransport.ts b/apps/cli/src/runtime/CliMessageTransport.tsindex d0f13977b25..5c365484427 100644--- a/apps/cli/src/runtime/CliMessageTransport.ts+++ b/apps/cli/src/runtime/CliMessageTransport.ts@@ -4,6 +4,7 @@ import type {QueryMessagesInput,QueryMessagesOptions,RuntimeMessageRef,+ RuntimeToolMessage,UpdateToolMessageInput,} from '@lobechat/agent-runtime';import type { CreateMessageParams, UIChatMessage, UpdateMessageParams } from '@lobechat/types';@@ -98,6 +99,11 @@ export class CliMessageTransport implements MessageTransport {return message ? toRef(message) : undefined;}+ async getToolMessage(id: string): Promise<RuntimeToolMessage | undefined> {+ const message = this.store.get(id);+ return message?.role === 'tool' ? message : undefined;+ }+async findToolMessageIdByToolCallId(toolCallId: string,parentMessageId: string,diff --git a/apps/cli/src/runtime/runtimeIntegration.test.ts b/apps/cli/src/runtime/runtimeIntegration.test.tsindex ad39b083663..a15f5c762c5 100644--- a/apps/cli/src/runtime/runtimeIntegration.test.ts+++ b/apps/cli/src/runtime/runtimeIntegration.test.ts@@ -127,6 +127,35 @@ describe('CliMessageTransport driving the real runtime executors', () => {expect(result.nextContext?.phase).toBe('tool_result');});+ it.each(['single', 'batch'])(+ 'replays a committed %s tool step against the local store',+ async (mode) => {+ const assistant = await transport.createAssistantMessage({+ content: 'call',+ role: 'assistant',+ topicId: 'topic-1',+ });+ const instruction =+ mode === 'single'+ ? {+ type: 'call_tool',+ payload: { parentMessageId: assistant.id, toolCalling: createToolCall() },+ }+ : {+ type: 'call_tools_batch',+ payload: { parentMessageId: assistant.id, toolsCalling: [createToolCall()] },+ };+ const execute = mode === 'single' ? callTool(host) : callToolsBatch(host);+ await execute(instruction as never, createState());+ const replay = await execute(instruction as never, createState());+ expect(host.transports.tools!.run).toHaveBeenCalledTimes(1);+ expect(replay.newState.messages.filter((row) => row.role === 'tool')).toHaveLength(1);+ expect(replay.newState.messages).toContainEqual(+ expect.objectContaining({ content: 'Tool result' }),+ );+ },+ );+it('answers the runtime read-back without waiting on the sink', async () => {// A sink that never settles stands in for an unreachable network.const stalled = new MessageWriteQueue({ sink: { flush: () => new Promise<void>(() => {}) } });diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 2cc5ad18f87..180785dcf3c 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -3460,9 +3460,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {expect(mockMessageModel.create).toHaveBeenCalledWith(expect.objectContaining({- metadata: {- toolExecutionTimeMs: 100,- },+ metadata: { toolExecutionTimeMs: 100, toolResultStop: false, toolResultSuccess: true },}),);});@@ -3794,10 +3792,19 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {});describe('skipCreateToolMessage (resumption after human approval)', () => {+ beforeEach(() => {+ mockMessageModel.findById.mockImplementation(async (id: string) => ({+ id,+ role: 'tool',+ content: '',+ }));+ mockMessageModel.findMessagePlugin.mockImplementation(async (id: string) => ({+ toolCallId: id.replace('pending-tool-msg-', 'tool-call-'),+ }));+ });it('should update existing tool message instead of creating a new one', async () => {const executors = createRuntimeExecutors(ctx);const state = createMockState();-const instruction = {payload: {parentMessageId: 'pending-tool-msg-1',@@ -3812,23 +3819,19 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {},type: 'call_tool' as const,};-await executors.call_tool!(instruction, state);-expect(mockMessageModel.create).not.toHaveBeenCalled();expect(mockMessageModel.updateToolMessage).toHaveBeenCalledWith('pending-tool-msg-1',expect.objectContaining({content: 'Tool result',- metadata: { toolExecutionTimeMs: 100 },+ metadata: { toolExecutionTimeMs: 100, toolResultStop: false, toolResultSuccess: true },}),);});-it('should return the existing toolMessageId as parentMessageId for the next LLM step', async () => {const executors = createRuntimeExecutors(ctx);const state = createMockState();-const instruction = {payload: {parentMessageId: 'pending-tool-msg-42',@@ -3843,17 +3846,13 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {},type: 'call_tool' as const,};-const result = await executors.call_tool!(instruction, state);-const nextPayload = result.nextContext?.payload as { parentMessageId?: string } | undefined;expect(nextPayload?.parentMessageId).toBe('pending-tool-msg-42');});-it('should fall back to creating a new tool message when skipCreateToolMessage is false', async () => {const executors = createRuntimeExecutors(ctx);const state = createMockState();-const instruction = {payload: {parentMessageId: 'assistant-msg-7',@@ -3868,15 +3867,12 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {},type: 'call_tool' as const,};-await executors.call_tool!(instruction, state);-expect(mockMessageModel.create).toHaveBeenCalledTimes(1);expect(mockMessageModel.updateToolMessage).not.toHaveBeenCalled();});});});-describe('request_human_approve executor', () => {const createMockState = (overrides?: Partial<AgentState>): AgentState => ({cost: createMockCost(),@@ -4997,17 +4993,13 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {expect(mockMessageModel.create).toHaveBeenNthCalledWith(1,expect.objectContaining({- metadata: {- toolExecutionTimeMs: 150,- },+ metadata: { toolExecutionTimeMs: 150, toolResultStop: false, toolResultSuccess: true },}),);expect(mockMessageModel.create).toHaveBeenNthCalledWith(2,expect.objectContaining({- metadata: {- toolExecutionTimeMs: 250,- },+ metadata: { toolExecutionTimeMs: 250, toolResultStop: false, toolResultSuccess: true },}),);});diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.test.tsindex 884491150fe..8a82a17f48e 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.test.ts@@ -25,6 +25,54 @@ const createUniqueViolation = (constraint: string) => {};describe('ServerMessageTransport', () => {+ it('keeps the complete Work intent readable while excluding it from runtime message queries', async () => {+ const intent = {+ type: 'skill' as const,+ provider: 'example',+ toolName: 'create',+ data: { body: 'raw payload' },+ };+ const row = {+ id: 'tool-1',+ role: 'tool',+ content: 'truncated',+ metadata: { operationId: 'op', toolWorkRegistration: intent },+ };+ const model = {+ query: vi.fn().mockResolvedValue([row]),+ findById: vi.fn().mockResolvedValue(row),+ findMessagePlugin: vi.fn().mockResolvedValue({ toolCallId: 'call-1' }),+ } as unknown as MessageModel;+ const transport = new ServerMessageTransport(model);+ expect((await transport.getToolMessage('tool-1'))?.metadata?.toolWorkRegistration).toEqual(+ intent,+ );+ expect((await transport.query())[0].metadata).toEqual({ operationId: 'op' });+ expect(row.metadata.toolWorkRegistration).toEqual(intent);+ });++ it('reads both halves of a durable tool result instead of only its message row', async () => {+ const messageModel = {+ findById: vi.fn().mockResolvedValue({+ content: 'Created document',+ id: 'tool-1',+ parentId: 'assistant-1',+ role: 'tool',+ }),+ findMessagePlugin: vi.fn().mockResolvedValue({+ state: { documentId: 'docs-1' },+ toolCallId: 'call-1',+ }),+ } as unknown as MessageModel;+ expect(await new ServerMessageTransport(messageModel).getToolMessage('tool-1')).toMatchObject({+ content: 'Created document',+ id: 'tool-1',+ parentId: 'assistant-1',+ pluginState: { documentId: 'docs-1' },+ tool_call_id: 'call-1',+ });+ });+it('returns the first assistant message when the same idempotency key is delivered twice', async () => {const existingMessage = {agentId: 'agent-1',diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.tsindex b39c892a97b..ef573c2a1b5 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts@@ -4,8 +4,10 @@ import type {QueryMessagesInput,QueryMessagesOptions,RuntimeMessageRef,+ RuntimeToolMessage,UpdateToolMessageInput,} from '@lobechat/agent-runtime';+import { omitToolWorkRegistration } from '@lobechat/agent-runtime';import { parse } from '@lobechat/conversation-flow';import type { CreateMessageParams, UIChatMessage, UpdateMessageParams } from '@lobechat/types';@@ -115,19 +117,40 @@ export class ServerMessageTransport implements MessageTransport {: undefined;}+ async getToolMessage(id: string): Promise<RuntimeToolMessage | undefined> {+ const [message, plugin] = await Promise.all([+ this.messageModel.findById(id),+ this.messageModel.findMessagePlugin(id),+ ]);+ if (!message || message.role !== 'tool' || !plugin) return undefined;+ return {+ content: message.content ?? '',+ id: message.id,+ metadata: message.metadata ?? undefined,+ parentId: message.parentId,+ pluginError: plugin.error,+ pluginIntervention: plugin.intervention,+ pluginState: plugin.state,+ role: 'tool',+ tool_call_id: plugin.toolCallId,+ };+ }+async query(params?: QueryMessagesInput,options?: QueryMessagesOptions,): Promise<UIChatMessage[]> {- const messages = await this.messageModel.query(params, {- // Executors only ever read the operation's own, already-authorized topic.- // An agent-share visitor run executes under the CREATOR's identity, so- // without this opt-in `query()`'s creator-facing agent-share exclusion- // would blank the visitor's conversation mid-run (see `tool.ts`, which- // re-reads `state.messages` from the DB after every tool call).- allowShareVisitor: true,- postProcessUrl: options?.resolveAssetUrls ? this.options.postProcessUrl : undefined,- });+ const messages = (+ await this.messageModel.query(params, {+ // Executors only ever read the operation's own, already-authorized topic.+ // An agent-share visitor run executes under the CREATOR's identity, so+ // without this opt-in `query()`'s creator-facing agent-share exclusion+ // would blank the visitor's conversation mid-run (see `tool.ts`, which+ // re-reads `state.messages` from the DB after every tool call).+ allowShareVisitor: true,+ postProcessUrl: options?.resolveAssetUrls ? this.options.postProcessUrl : undefined,+ })+ ).map(omitToolWorkRegistration);if (!options?.flatten) return messages;diff --git a/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts b/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.tsindex 2075d74d4a2..8f8638bc26f 100644--- a/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts@@ -132,6 +132,7 @@ function setup(hooks: AgentHook[], signal?: AbortSignal, restore = false) {return persisted;}),query: vi.fn(async () => rows),+ getToolMessage: vi.fn(async (id: string) => rows.find((row) => row.id === id)),updateToolMessage: vi.fn(async (id, update) => {const row = rows.find((row) => row.id === id);if (row) Object.assign(row, update);@@ -484,7 +485,7 @@ describe('afterToolCall control pipeline', () => {role: 'tool',tool_call_id: 'native-1',content: secret,- pluginState: { images: [{ url: secret }] },+ pluginState: { status: 'pending', images: [{ url: secret }] },});fixture.execute.mockResolvedValue(raw());fetchHook.mockImplementation(async () => response('deny'));diff --git a/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts b/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.tsindex f5ef8a45f94..91c21a510ff 100644--- a/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts@@ -112,6 +112,7 @@ function setup(hooks: AgentHook[], signal?: AbortSignal, restore = false) {return { ...row, id: `row-${rows.length}` };}),query: vi.fn(async () => rows),+ getToolMessage: vi.fn(),updateToolMessage: vi.fn(),updateToolIntervention: vi.fn(),update: vi.fn(),@@ -307,6 +308,13 @@ describe('beforeToolCall control pipeline', () => {const reason = 'Approval does not override this policy.';fetchHook.mockImplementation(async () => response('deny', reason));const fixture = setup([control()]);+ vi.mocked(fixture.host.transports.messages.getToolMessage).mockResolvedValue({+ id: 'pending-row',+ role: 'tool',+ content: '',+ tool_call_id: call().id,+ pluginIntervention: { status: 'pending' },+ });await fixture.runtime.step(fixture.state, {phase: 'human_approved_tool',payload:@@ -908,6 +916,13 @@ describe('beforeToolCall control pipeline', () => {});it('settles an already-approved row when the refreshed control denies it', async () => {const fixture = setup([control()]);+ vi.mocked(fixture.host.transports.messages.getToolMessage).mockResolvedValue({+ id: 'pending-tool-row',+ role: 'tool',+ content: '',+ tool_call_id: call().id,+ pluginIntervention: { status: 'pending' },+ });fetchHook.mockImplementation(async () => response('deny'));const result = await fixture.runtime.step(fixture.state, {phase: 'human_approved_tool',diff --git a/apps/server/src/routers/lambda/__tests__/message.workIntent.test.ts b/apps/server/src/routers/lambda/__tests__/message.workIntent.test.tsnew file mode 100644index 00000000000..d7c0688d9d7--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/message.workIntent.test.ts@@ -0,0 +1,122 @@+// @vitest-environment node+import type { UIChatMessage } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => ({})) }));+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ cloudWorkspaceAuth: (opts: any) => opts.next({ ctx: opts.ctx }),+}));+vi.mock('../_helpers/conversationResourceGuard', () => ({+ assertCanUseConversationTargets: vi.fn(),+ assertCanUseCreateMessageTargets: vi.fn(),+ assertCanUseMessageTargets: vi.fn(),+ assertCanUseTopicTargets: vi.fn(),+ assertCanViewMessageTargets: vi.fn(),+ assertCanViewTopicTargets: vi.fn(),+}));+vi.mock('../_helpers/resolveContext', () => ({ resolveContext: vi.fn(async (input) => input) }));++const { query, queryByCursor, findShare } = vi.hoisted(() => ({+ query: vi.fn(),+ queryByCursor: vi.fn(),+ findShare: vi.fn(),+}));+vi.mock('@/database/models/message', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ MessageModel: vi.fn(function () {+ return { query, queryTopicMessagesByCursor: queryByCursor };+ }),+}));+vi.mock('@/database/models/topicShare', () => ({+ TopicShareModel: { findByShareIdWithAccessCheck: findShare },+}));+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function () {+ return {};+ }),+}));++const { messageRouter } = await import('../message');+const intent = {+ type: 'skill' as const,+ provider: 'test',+ toolName: 'skill',+ args: { raw: 'arguments' },+ data: 'untruncated skill data',+};+const message = {+ id: 'tool-result',+ role: 'tool',+ content: 'truncated result',+ metadata: { toolWorkRegistration: intent, toolResultSuccess: true },+} as UIChatMessage;++beforeEach(() => {+ vi.clearAllMocks();+ query.mockResolvedValue([+ message,+ {+ id: 'group',+ role: 'compressedGroup',+ content: '',+ compressedMessages: [message],+ members: [message],+ columns: [[message]],+ },+ ]);+ queryByCursor.mockResolvedValue({+ messages: [+ message,+ {+ id: 'group',+ role: 'compressedGroup',+ content: '',+ compressedMessages: [message],+ members: [message],+ columns: [[message]],+ },+ ],+ hasMore: false,+ nextCursor: null,+ });+ findShare.mockResolvedValue({ ownerId: 'owner', topicId: 'topic' });+});++describe('message lists omit durable replay-only Work intents', () => {+ it.each([+ [false, false],+ [false, true],+ [true, false],+ [true, true],+ ])('ordinary list (share=%s, projected=%s)', async (shared, projected) => {+ const caller = messageRouter.createCaller({ userId: 'owner', serverDB: {} } as any);+ const result = await caller.getMessages({+ topicId: 'topic',+ projectToolPayloads: projected,+ ...(shared && { topicShareId: 'share' }),+ });+ expect(result[0].metadata).toEqual({ toolResultSuccess: true });+ expect(JSON.stringify(result)).not.toContain('untruncated skill data');+ expect(message.metadata?.toolWorkRegistration).toEqual(intent);+ if (!projected || shared) expect(result[0].content).toBe('truncated result');+ });++ it.each([+ [false, false],+ [false, true],+ [true, false],+ [true, true],+ ])('cursor page (share=%s, projected=%s)', async (shared, projected) => {+ const caller = messageRouter.createCaller({ userId: 'owner', serverDB: {} } as any);+ const result = await caller.getMessagesByCursor({+ topicId: 'topic',+ projectToolPayloads: projected,+ ...(shared && { topicShareId: 'share' }),+ });+ expect(result.messages[0].metadata).toEqual({ toolResultSuccess: true });+ expect(JSON.stringify(result.messages)).not.toContain('untruncated skill data');+ expect(result.hasMore).toBe(false);+ expect(message.metadata?.toolWorkRegistration).toEqual(intent);+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/messagesByCursor.ts b/apps/server/src/routers/lambda/_helpers/messagesByCursor.tsindex 51ac7d947b3..a8a4fc94282 100644--- a/apps/server/src/routers/lambda/_helpers/messagesByCursor.ts+++ b/apps/server/src/routers/lambda/_helpers/messagesByCursor.ts@@ -1,3 +1,4 @@+import { omitToolWorkRegistration } from '@lobechat/agent-runtime';import { projectToolViewModels } from '@lobechat/tool-view-model';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -144,7 +145,10 @@ export const readMessagesByCursor = async (// Same rule as `getMessages`: only the caller knows whether this page is// rendered or fed to a model, so projection is opt-in per read.- return projectToolPayloads- ? { ...page, direction, messages: projectToolViewModels(page.messages) }- : { ...page, direction };+ const messages = page.messages.map(omitToolWorkRegistration);+ return {+ ...page,+ direction,+ messages: projectToolPayloads ? projectToolViewModels(messages) : messages,+ };};diff --git a/apps/server/src/routers/lambda/_helpers/projectSharedTopicMessages.ts b/apps/server/src/routers/lambda/_helpers/projectSharedTopicMessages.tsindex ec3e5795d5f..2331aa3deb0 100644--- a/apps/server/src/routers/lambda/_helpers/projectSharedTopicMessages.ts+++ b/apps/server/src/routers/lambda/_helpers/projectSharedTopicMessages.ts@@ -1,3 +1,4 @@+import { omitToolWorkRegistration } from '@lobechat/agent-runtime';import {type AssistantContentBlock,ChatErrorType,@@ -29,7 +30,7 @@ const projectAssistantContentBlock = (block: AssistantContentBlock): AssistantCo});const projectMessage = (message: UIChatMessage): UIChatMessage => ({- ...message,+ ...omitToolWorkRegistration(message),children: message.children?.map(projectAssistantContentBlock),...(message.columns && { columns: message.columns.map((column) => column.map(projectMessage)) }),compressedMessages: message.compressedMessages?.map(projectMessage),diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.tsindex fff924a0a40..0d7a2574c6a 100644--- a/apps/server/src/routers/lambda/message.ts+++ b/apps/server/src/routers/lambda/message.ts@@ -1,3 +1,4 @@+import { omitToolWorkRegistration } from '@lobechat/agent-runtime';import { projectToolViewModels } from '@lobechat/tool-view-model';import {AgentSenderMetadataSchema,@@ -576,7 +577,8 @@ export const messageRouter = router({// from the very list this read returns, and a projected tool result would// silently disappear from it. Absent ⇒ whole payloads, which is never the// answer that loses data.- return input.projectToolPayloads ? projectToolViewModels(messages) : messages;+ const visibleMessages = messages.map(omitToolWorkRegistration);+ return input.projectToolPayloads ? projectToolViewModels(visibleMessages) : visibleMessages;}),/**diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.test.tsindex a72c940862e..f51e6920d51 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.test.ts@@ -422,6 +422,35 @@ describe('AgentRuntimeService', () => {expect(query).toHaveBeenCalledTimes(1);});+ it.each(['queryMessagesFromDB', 'queryStepEntryMessages'])(+ 'keeps durable Work payloads outside %s runtime hydration',+ async (method) => {+ const state = {+ ...mockState,+ messages: [],+ origin: { agentId: 'agent', topicId: 'topic' },+ };+ const messages = buildPersistedToolChain('stored answer');+ const tool = messages.find((message) => message.role === 'tool')!;+ const intent = {+ type: 'skill' as const,+ provider: 'example',+ toolName: 'create',+ data: { body: 'untruncated Work payload' },+ };+ tool.metadata = { ...tool.metadata, toolWorkRegistration: intent };+ (service as any).messageModel.query.mockResolvedValue(messages);+ vi.spyOn((service as any).messageService, 'prepareUiMessages').mockImplementation(+ async (rows) => rows,+ );+ const result = await (service as any)[method](state);+ expect(JSON.stringify(result)).not.toContain('untruncated Work payload');+ expect(JSON.stringify(state.messages)).not.toContain('untruncated Work payload');+ expect(JSON.stringify(result)).toContain('stored answer');+ expect(tool.metadata.toolWorkRegistration).toEqual(intent);+ },+ );+it('keeps ephemeral input while preparing the persisted UI snapshot', async () => {const messages = [{ role: 'user', content: 'transient prompt' }];const state = { ...mockState, messages, origin: { agentId: 'agent', topicId: 'topic' } };diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.tsindex 31862dacf2a..4b98ad666f1 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.ts@@ -1,4 +1,4 @@-import type { AgentState } from '@lobechat/agent-runtime';+import { type AgentState, omitToolWorkRegistration } from '@lobechat/agent-runtime';import { parse } from '@lobechat/conversation-flow';import { type ChatToolPayload, type UIChatMessage } from '@lobechat/types';@@ -73,7 +73,7 @@ export async function queryUiMessages(const includeFileWorks = isShareVisitorRun || agentState?.host?.acceptsFileWorks === true;try {- return await deps.messageService.queryMessages(+ const messages = await deps.messageService.queryMessages({agentId,groupId,@@ -91,6 +91,7 @@ export async function queryUiMessages(// `GatewayStreamNotifier`.{ allowShareVisitor: true, ...(workAccessScope && { workAccessScope }) },);+ return messages.map(omitToolWorkRegistration);} catch (error) {// Stream events must never fail the step. If the DB hiccups, fall back// to letting the client refresh as before.@@ -131,7 +132,7 @@ export async function queryMessagesFromDB(deps: MessagesDeps, state: AgentState)// reduce tool payloads to render-facing view models (see// `@lobechat/tool-view-model`), which would silently strip the results the// model is supposed to remember.- return deps.messageModel.query(+ const messages = await deps.messageModel.query({agentId: state.origin?.agentId,// Group runs must pass groupId, else the query filters `groupId IS NULL`@@ -146,6 +147,7 @@ export async function queryMessagesFromDB(deps: MessagesDeps, state: AgentState)// of `query()`'s creator-facing agent-share exclusion.{ allowShareVisitor: true, postProcessUrl },);+ return messages.map(omitToolWorkRegistration);}/**@@ -252,6 +254,7 @@ export async function queryStepEntryMessages(},{ allowShareVisitor: true },);+ messages = messages.map(omitToolWorkRegistration);} catch (error) {console.error('[queryStepEntryMessages] Failed to load messages: %O', error);return {};diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.tsindex b3afbe5d119..73f2c3ca085 100644--- a/packages/agent-runtime/src/executors/callLlm.test.ts+++ b/packages/agent-runtime/src/executors/callLlm.test.ts@@ -71,6 +71,7 @@ const createMessageTransport = (): MessageTransport => ({deleteMessage: vi.fn(),findById: vi.fn().mockResolvedValue({ id: 'parent-1' }),findToolMessageIdByToolCallId: vi.fn(),+ getToolMessage: vi.fn(),query: vi.fn(),update: vi.fn(),updatePluginState: vi.fn(),diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.tsindex 8729feaf301..ea611ffe6f6 100644--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts@@ -20,6 +20,7 @@ const createMessageTransport = (): MessageTransport => ({deleteMessage: vi.fn(),findById: vi.fn(),findToolMessageIdByToolCallId: vi.fn(),+ getToolMessage: vi.fn(),query: vi.fn(),update: vi.fn().mockResolvedValue(undefined),updatePluginState: vi.fn(),diff --git a/packages/agent-runtime/src/executors/tool.batch.test.ts b/packages/agent-runtime/src/executors/tool.batch.test.tsnew file mode 100644index 00000000000..0b0390a5351--- /dev/null+++ b/packages/agent-runtime/src/executors/tool.batch.test.ts@@ -0,0 +1,1004 @@+import type { Mock } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { AgentRuntimeHost } from '../transport';+import type { AgentInstruction, AgentRuntimeContext } from '../types';+import { callTool, callToolsBatch } from './tool';+import { createState, createToolCall, createToolExecutorFixture } from './tool.testUtils';++describe('batch tool executors', () => {+ let createToolMessage: Mock;+ let updateToolIntervention: ReturnType<typeof vi.fn>;+ let updateToolMessage: ReturnType<typeof vi.fn>;+ /**+ * `tool_call_id → row id`, the store's view of which calls already have a row.+ * Writes register here so a later lookup finds them — the same reason the real+ * settle can ask instead of being told.+ */+ let toolRows: Map<string, { id: string; parentId: string }>;+ let publishChunk: ReturnType<typeof vi.fn>;+ let publishError: ReturnType<typeof vi.fn>;+ let publishEvent: ReturnType<typeof vi.fn>;+ let query: ReturnType<typeof vi.fn>;+ let runTool: Mock;+ let host: AgentRuntimeHost;++ beforeEach(() => {+ ({+ createToolMessage,+ updateToolIntervention,+ updateToolMessage,+ toolRows,+ publishChunk,+ publishError,+ publishEvent,+ query,+ runTool,+ host,+ } = createToolExecutorFixture());+ });++ it('collects placeholder ids for every deferred tool in a batch', async () => {+ runTool.mockImplementation(async (tool: { id: string }) => ({+ attempts: 1,+ result: {+ content: '',+ deferred: true,+ state: { status: 'pending', toolMessageId: `msg-for-${tool.id}` },+ success: true,+ },+ }));++ await callToolsBatch(host)(+ {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [+ createToolCall('sub-a', 'lobe-agent'),+ createToolCall('sub-b', 'lobe-agent'),+ ],+ },+ type: 'call_tools_batch',+ },+ createState(),+ );++ expect(publishChunk).toHaveBeenCalledWith(+ expect.objectContaining({+ toolMessageIds: { 'sub-a': 'msg-for-sub-a', 'sub-b': 'msg-for-sub-b' },+ }),+ );+ });++ it('passes the current step context to every tool in a batch', async () => {+ const stepContext = {+ activatedToolIds: ['page-editor'],+ hasQueuedMessages: true,+ };+ const runtimeContext = {+ phase: 'llm_result',+ stepContext,+ } satisfies AgentRuntimeContext;++ await callToolsBatch(host)(+ {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [createToolCall('tool-a'), createToolCall('tool-b')],+ },+ type: 'call_tools_batch',+ },+ createState(),+ runtimeContext,+ );++ expect(runTool).toHaveBeenCalledTimes(2);+ expect(runTool.mock.calls.map(([, runContext]) => runContext.stepContext)).toEqual([+ stepContext,+ stepContext,+ ]);+ });++ it('executes server tools in a mixed batch then parks for client tools', async () => {+ const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [createToolCall('server-call'), createToolCall('client-call', 'client-tool')],+ },+ type: 'call_tools_batch',+ };++ const result = await callToolsBatch(host)(+ instruction,+ createState({ toolSourceMap: { 'client-tool': 'client' as any } }),+ );++ expect(runTool).toHaveBeenCalledTimes(1);+ expect(createToolMessage).toHaveBeenCalledTimes(1);+ expect(query).toHaveBeenCalledWith(+ {+ agentId: 'agent-1',+ groupId: undefined,+ threadId: 'thread-1',+ topicId: 'topic-1',+ },+ { flatten: true, resolveAssetUrls: true },+ );+ expect(result.newState.status).toBe('waiting_for_async_tool');+ expect(result.newState.pendingToolsCalling).toEqual([+ expect.objectContaining({ id: 'client-call' }),+ ]);+ expect(result.events).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ id: 'server-call', type: 'tool_result' }),+ expect.objectContaining({ reason: 'client_tool_execution', type: 'interrupted' }),+ ]),+ );+ });++ it('uses tool messages already persisted by the transport in a batch', async () => {+ host.transports.tools!.canRunClientTools = true;+ runTool.mockResolvedValueOnce({+ attempts: 1,+ result: { content: 'Client result', executionTime: 10, success: true },+ resultPersisted: true,+ toolMessageId: 'client-tool-msg',+ });+ const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [createToolCall('client-call', 'client-tool')],+ },+ type: 'call_tools_batch',+ };++ const result = await callToolsBatch(host)(+ instruction,+ createState({ toolSourceMap: { 'client-tool': 'client' as any } }),+ );++ expect(createToolMessage).not.toHaveBeenCalled();+ expect(host.transports.messages.updateToolMessage).toHaveBeenCalledWith('client-tool-msg', {+ metadata: expect.objectContaining({ toolResultSuccess: true }),+ });+ // 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 () => {+ const error = new Error('database failed');+ createToolMessage.mockRejectedValueOnce(error);+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolCalling: createToolCall(),+ },+ type: 'call_tool',+ };++ await expect(callTool(host)(instruction, createState())).rejects.toThrow('database failed');+ expect(publishError).toHaveBeenCalledWith({+ error,+ phase: 'tool_message_persist',+ stepIndex: 2,+ });+ });++ it('keeps finished batch results and writes aborted rows only for the rest', async () => {+ const controller = new AbortController();+ const abortingHost = {+ ...host,+ operation: { ...host.operation, abortSignal: controller.signal },+ } as typeof host;++ const settled = createToolCall('settled-call');+ const stuck = createToolCall('stuck-call');++ runTool.mockImplementation((tool: any) =>+ tool.id === settled.id+ ? Promise.resolve({+ attempts: 1,+ result: { content: 'done', executionTime: 1, success: true },+ })+ : new Promise(() => {+ // never settles — abort is what ends the wait+ }),+ );++ const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {+ payload: { parentMessageId: 'assistant-msg-1', toolsCalling: [settled, stuck] },+ type: 'call_tools_batch',+ };++ const pending = callToolsBatch(abortingHost)(instruction, createState());+ // Let the settled tool resolve and persist its row before the abort lands.+ await new Promise((resolve) => setTimeout(resolve, 0));+ controller.abort();+ const result = await pending;++ // The finished tool keeps its real result...+ expect(result.events).toContainEqual(+ expect.objectContaining({ id: settled.id, type: 'tool_result' }),+ );+ // ...and only the in-flight one gets an aborted row. Two rows total, one+ // per tool_call_id — a partially settled batch must not lose either half.+ expect(createToolMessage).toHaveBeenCalledTimes(2);+ expect(createToolMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ content: 'Tool execution was aborted by user.',+ tool_call_id: stuck.id,+ }),+ );+ });++ it('settles unstarted client tools instead of parking them when a mixed batch aborts', async () => {+ const controller = new AbortController();+ const abortingHost = {+ ...host,+ operation: { ...host.operation, abortSignal: controller.signal },+ } as typeof host;++ const serverCall = createToolCall('server-call');+ const clientCall = createToolCall('client-call', 'client-tool');++ runTool.mockImplementation(+ () =>+ new Promise(() => {+ // never settles — the abort is what ends the wait+ }),+ );++ const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {+ payload: { parentMessageId: 'assistant-msg-1', toolsCalling: [serverCall, clientCall] },+ type: 'call_tools_batch',+ };++ const pending = callToolsBatch(abortingHost)(+ instruction,+ createState({ toolSourceMap: { 'client-tool': 'client' as any } }),+ );+ controller.abort();+ await pending;++ // The client call never started, and the pause it was waiting for would park+ // it into a run nothing resumes — leaving its tool_call_id with no row ever.+ const settledIds = createToolMessage.mock.calls.map((call: any) => call[0].tool_call_id);+ expect(settledIds).toContain(serverCall.id);+ expect(settledIds).toContain(clientCall.id);+ expect(publishChunk).not.toHaveBeenCalledWith(+ expect.objectContaining({ chunkType: 'tools_calling' }),+ );+ });++ it('writes one row per tool_call_id even if a call reaches the settle twice', async () => {+ const controller = new AbortController();+ controller.abort();+ const abortingHost = {+ ...host,+ operation: { ...host.operation, abortSignal: controller.signal },+ } as typeof host;++ const dupe = createToolCall('dupe-call');+ const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {+ payload: { parentMessageId: 'assistant-msg-1', toolsCalling: [dupe, dupe] },+ type: 'call_tools_batch',+ };++ await callToolsBatch(abortingHost)(instruction, createState());++ // Callers merge several abort sources into one list; "exactly one row per+ // tool_call_id" has to survive that.+ expect(createToolMessage).toHaveBeenCalledTimes(1);+ });++ it('settles a client-only batch instead of parking it when already aborted', async () => {+ const controller = new AbortController();+ controller.abort();+ const abortingHost = {+ ...host,+ operation: { ...host.operation, abortSignal: controller.signal },+ } as typeof host;++ const a = createToolCall('client-a', 'client-tool');+ const b = createToolCall('client-b', 'client-tool');+ const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {+ payload: { parentMessageId: 'assistant-msg-1', toolsCalling: [a, b] },+ type: 'call_tools_batch',+ };++ const result = await callToolsBatch(abortingHost)(+ instruction,+ createState({ toolSourceMap: { 'client-tool': 'client' as any } }),+ );++ expect(publishChunk).not.toHaveBeenCalled();+ const settledIds = createToolMessage.mock.calls.map((call: any) => call[0].tool_call_id);+ expect(settledIds).toEqual([a.id, b.id]);+ expect(result.newState.messages).toHaveLength(2);+ });++ it('settles a client-only batch when aborted while publishing the pause chunk', async () => {+ const controller = new AbortController();+ const abortingHost = {+ ...host,+ operation: { ...host.operation, abortSignal: controller.signal },+ } as typeof host;+ let finishPublishing: (() => void) | undefined;+ publishChunk.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finishPublishing = resolve;+ }),+ );++ const a = createToolCall('client-a', 'client-tool');+ const b = createToolCall('client-b', 'client-tool');+ const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {+ payload: { parentMessageId: 'assistant-msg-1', toolsCalling: [a, b] },+ type: 'call_tools_batch',+ };++ const pending = callToolsBatch(abortingHost)(+ instruction,+ createState({ toolSourceMap: { 'client-tool': 'client' as any } }),+ );+ await vi.waitFor(() => expect(finishPublishing).toBeTypeOf('function'));+ controller.abort();+ finishPublishing!();+ const result = await pending;++ expect(result.newState.status).toBe('running');+ expect(result.newState.messages).toHaveLength(2);+ expect(createToolMessage).toHaveBeenCalledTimes(2);+ });++ it('settles approved client rows in a mixed batch rather than duplicating them', async () => {+ const controller = new AbortController();+ controller.abort();+ const abortingHost = {+ ...host,+ operation: { ...host.operation, abortSignal: controller.signal },+ } as typeof host;++ const serverCall = createToolCall('server-call');+ const clientCall = createToolCall('client-call', 'client-tool');++ // An approved batch resume left a pending row for EVERY call, including the+ // client ones that never enter `toolsToExecute`.+ toolRows.set(serverCall.id, { id: 'server-row', parentId: 'assistant-msg-1' });+ toolRows.set(clientCall.id, { id: 'client-row', parentId: 'assistant-msg-1' });+ const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [serverCall, clientCall],+ },+ type: 'call_tools_batch',+ };++ await callToolsBatch(abortingHost)(+ instruction,+ createState({ toolSourceMap: { 'client-tool': 'client' as any } }),+ );++ expect(createToolMessage).not.toHaveBeenCalled();+ expect(updateToolIntervention).toHaveBeenCalledWith('client-row', { status: 'aborted' });+ expect(updateToolIntervention).toHaveBeenCalledWith('server-row', { status: 'aborted' });+ });++ it('ignores a reused tool_call_id that belongs to another turn', async () => {+ const controller = new AbortController();+ controller.abort();+ const abortingHost = {+ ...host,+ operation: { ...host.operation, abortSignal: controller.signal },+ } as typeof host;++ const toolCall = createToolCall();+ // Same id, different assistant — `tool_call_id` is provider-supplied and+ // only indexed, so a reuse across turns is possible. Settling that row would+ // overwrite a real historical result AND leave this call without one.+ toolRows.set(toolCall.id, { id: 'older-turn-row', parentId: 'assistant-msg-OLD' });++ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: toolCall },+ type: 'call_tool',+ };++ await callTool(abortingHost)(instruction, createState());++ expect(updateToolMessage).not.toHaveBeenCalledWith('older-turn-row', expect.anything());+ expect(createToolMessage).toHaveBeenCalledWith(+ expect.objectContaining({ parentId: 'assistant-msg-1', tool_call_id: toolCall.id }),+ );+ });++ 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',+ };++ toolRows.set('call-a', { id: 'pending-msg-a', parentId: 'assistant-msg-1' });+ toolRows.set('call-b', { id: 'pending-msg-b', parentId: 'assistant-msg-1' });+ 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('serialized batch calls', () => {+ // Several editFile calls to one path in a batch reached the device at once;+ // each read the same snapshot and the last write dropped the others while+ // every call reported success. Calls naming the same resource through+ // `serializeBy` queue in emission order; other paths stay concurrent.+ const manifestMap = {+ 'lobe-local-system': {+ api: [+ { name: 'editFile', serializeBy: 'file_path' },+ { name: 'writeFile', serializeBy: 'path' },+ { name: 'readFile' },+ ],+ identifier: 'lobe-local-system',+ },+ };++ const fileCall = (id: string, apiName: string, args: Record<string, unknown>) => ({+ apiName,+ arguments: JSON.stringify(args),+ id,+ identifier: 'lobe-local-system',+ type: 'builtin' as const,+ });++ const trackingRunner = (delays: Record<string, number>, timeline: string[]) =>+ vi.fn().mockImplementation(async (tool: { id: string }) => {+ timeline.push(`start:${tool.id}`);+ await new Promise((resolve) => setTimeout(resolve, delays[tool.id] ?? 0));+ timeline.push(`end:${tool.id}`);+ return {+ attempts: 1,+ result: { content: `done ${tool.id}`, executionTime: 1, state: {}, success: true },+ };+ });++ beforeEach(() => {+ host.transports.messages.createToolMessage = vi+ .fn()+ .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({+ id: `tool-msg-${tool_call_id}`,+ }));+ });++ it('runs edits and writes to one path one after another, in emission order', async () => {+ const timeline: string[] = [];+ host.transports.tools!.run = trackingRunner(+ { 'edit-1': 30, 'edit-2': 10, 'write-1': 0 },+ timeline,+ );++ const result = await callToolsBatch(host)(+ {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [+ fileCall('edit-1', 'editFile', { file_path: '/repo/a.ts', old_string: 'x' }),+ fileCall('edit-2', 'editFile', { file_path: '/repo/a.ts', old_string: 'y' }),+ fileCall('write-1', 'writeFile', { content: 'z', path: '/repo/a.ts' }),+ ],+ },+ type: 'call_tools_batch',+ },+ createState({ toolManifestMap: manifestMap }),+ );++ expect(timeline).toEqual([+ 'start:edit-1',+ 'end:edit-1',+ 'start:edit-2',+ 'end:edit-2',+ 'start:write-1',+ 'end:write-1',+ ]);+ expect((result.nextContext?.payload as any).toolResults).toHaveLength(3);+ });++ it('keeps edits to different paths and unmarked reads concurrent', async () => {+ const timeline: string[] = [];+ host.transports.tools!.run = trackingRunner(+ { 'edit-a': 30, 'edit-b': 0, 'read-a': 0 },+ timeline,+ );++ await callToolsBatch(host)(+ {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [+ fileCall('edit-a', 'editFile', { file_path: '/repo/a.ts', old_string: 'x' }),+ fileCall('edit-b', 'editFile', { file_path: '/repo/b.ts', old_string: 'x' }),+ fileCall('read-a', 'readFile', { path: '/repo/a.ts' }),+ ],+ },+ type: 'call_tools_batch',+ },+ createState({ toolManifestMap: manifestMap }),+ );++ // All three start before the slow edit to a.ts finishes.+ expect(timeline.slice(0, 3).sort()).toEqual(['start:edit-a', 'start:edit-b', 'start:read-a']);+ });+ });++ describe('ordered batch calls', () => {+ // A model that posts a long report as several `sendMessage` calls emits+ // them in reading order, but `Promise.all` handed every call to the+ // platform at once and the channel kept whichever arrived first. An API+ // marked `ordered` runs its calls one after another in emission order;+ // everything else in the batch stays concurrent.+ const manifestMap = {+ 'lobe-message': {+ api: [+ { name: 'sendMessage', ordered: true },+ { name: 'replyToThread', ordered: true },+ { name: 'readMessages' },+ ],+ identifier: 'lobe-message',+ },+ };++ const messageCall = (id: string, apiName: string) => ({+ apiName,+ arguments: '{}',+ id,+ identifier: 'lobe-message',+ type: 'builtin' as const,+ });++ const batchOf = (+ toolsCalling: ReturnType<typeof messageCall>[],+ ): Extract<AgentInstruction, { type: 'call_tools_batch' }> => ({+ payload: { parentMessageId: 'assistant-msg-1', toolsCalling },+ type: 'call_tools_batch',+ });++ /** Records `start:<id>` / `end:<id>` so the interleaving is observable. */+ const trackingRunner = (delays: Record<string, number>, timeline: string[]) =>+ vi.fn().mockImplementation(async (tool: { id: string }) => {+ timeline.push(`start:${tool.id}`);+ await new Promise((resolve) => setTimeout(resolve, delays[tool.id] ?? 0));+ timeline.push(`end:${tool.id}`);+ return {+ attempts: 1,+ result: { content: `sent ${tool.id}`, executionTime: 1, state: {}, success: true },+ };+ });++ it('runs ordered calls one after another in emission order, even when the first is slowest', async () => {+ const timeline: string[] = [];+ // Slowest first: concurrent dispatch would finish send-3 before send-1.+ host.transports.tools!.run = trackingRunner(+ { 'send-1': 30, 'send-2': 10, 'send-3': 0 },+ timeline,+ );+ 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([+ messageCall('send-1', 'sendMessage'),+ messageCall('send-2', 'sendMessage'),+ messageCall('send-3', 'replyToThread'),+ ]),+ createState({ toolManifestMap: manifestMap }),+ );++ expect(timeline).toEqual([+ 'start:send-1',+ 'end:send-1',+ 'start:send-2',+ 'end:send-2',+ 'start:send-3',+ 'end:send-3',+ ]);+ // Every call still lands in the batch result.+ expect((result.nextContext?.payload as any).toolResults).toHaveLength(3);+ expect(result.nextContext?.payload).toMatchObject({ parentMessageId: 'assistant-msg-1' });+ });++ it('does not hold up unordered siblings behind the ordered chain', async () => {+ const timeline: string[] = [];+ host.transports.tools!.run = trackingRunner(+ { 'read-1': 0, 'send-1': 30, 'send-2': 10 },+ timeline,+ );+ host.transports.messages.createToolMessage = vi+ .fn()+ .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({+ id: `tool-msg-${tool_call_id}`,+ }));++ await callToolsBatch(host)(+ batchOf([+ messageCall('send-1', 'sendMessage'),+ messageCall('read-1', 'readMessages'),+ messageCall('send-2', 'sendMessage'),+ ]),+ createState({ toolManifestMap: manifestMap }),+ );++ // The read finished while send-1 was still in flight …+ expect(timeline.indexOf('end:read-1')).toBeLessThan(timeline.indexOf('end:send-1'));+ // … and send-2 still waited for send-1.+ expect(timeline.indexOf('start:send-2')).toBeGreaterThan(timeline.indexOf('end:send-1'));+ });++ it('reads the flag from a step-activated manifest as well', async () => {+ const timeline: string[] = [];+ host.transports.tools!.run = trackingRunner({ 'send-1': 20, 'send-2': 0 }, timeline);+ host.transports.messages.createToolMessage = vi+ .fn()+ .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({+ id: `tool-msg-${tool_call_id}`,+ }));++ await callToolsBatch(host)(+ batchOf([messageCall('send-1', 'sendMessage'), messageCall('send-2', 'sendMessage')]),+ createState({+ activatedStepTools: [+ {+ activatedAtStep: 0,+ id: 'lobe-message',+ manifest: manifestMap['lobe-message'] as any,+ source: 'activator' as any,+ },+ ],+ toolManifestMap: {},+ }),+ );++ expect(timeline).toEqual(['start:send-1', 'end:send-1', 'start:send-2', 'end:send-2']);+ });++ it('keeps unmarked calls concurrent', async () => {+ const timeline: string[] = [];+ host.transports.tools!.run = trackingRunner({ 'read-1': 20, 'read-2': 0 }, timeline);+ host.transports.messages.createToolMessage = vi+ .fn()+ .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({+ id: `tool-msg-${tool_call_id}`,+ }));++ await callToolsBatch(host)(+ batchOf([messageCall('read-1', 'readMessages'), messageCall('read-2', 'readMessages')]),+ createState({ toolManifestMap: manifestMap }),+ );++ expect(timeline.indexOf('start:read-2')).toBeLessThan(timeline.indexOf('end:read-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+ // event nor the returned `events` array (which get serialized into the+ // capped Redis step blob) — clients only read `workRegistration` as a+ // presence flag.+ const createSkillIntent = () => ({+ args: { number: 42, repo: 'lobehub/lobehub' },+ data: { body: 'x'.repeat(500), issues: Array.from({ length: 30 }, (_, i) => ({ id: i })) },+ provider: 'github',+ toolName: 'github.searchIssues',+ type: 'skill' as const,+ });++ const findEvent = (calls: unknown[][], type: string) =>+ calls.map((call) => call[0] as any).find((event) => event?.type === type);++ it('redacts a skill intent on the stream event and returned events, but registers the full intent (single path)', async () => {+ const skillIntent = createSkillIntent();+ const registerWork = vi.fn().mockResolvedValue(undefined);+ host.transports.tools!.registerWork = registerWork;+ runTool.mockResolvedValueOnce({+ attempts: 1,+ result: {+ content: 'issue found',+ executionTime: 100,+ state: {},+ success: true,+ workRegistration: skillIntent,+ },+ });+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: createToolCall() },+ type: 'call_tool',+ };++ const result = await callTool(host)(instruction, createState());++ // 1) Published `tool_end` stream event: presence flag preserved, payload stripped.+ const toolEnd = findEvent(publishEvent.mock.calls, 'tool_end');+ expect(toolEnd.data.result.workRegistration).toEqual({+ args: undefined,+ data: null,+ provider: 'github',+ toolName: 'github.searchIssues',+ type: 'skill',+ });++ // 2) Returned step `events` array (serialized into the Redis step blob).+ const toolResultEvent = result.events.find(+ (event: any) => event.type === 'tool_result',+ ) as any;+ expect(toolResultEvent.result.workRegistration.data).toBeNull();+ expect(toolResultEvent.result.workRegistration.args).toBeUndefined();++ // 3) `registerWork` still receives the FULL intent (data + args intact).+ expect(registerWork).toHaveBeenCalledTimes(1);+ const registeredIntent = registerWork.mock.calls[0][0].intent;+ expect(registeredIntent.data).toEqual(skillIntent.data);+ expect(registeredIntent.args).toEqual(skillIntent.args);+ });++ it('passes a non-skill (task) intent through unredacted (single path)', async () => {+ const taskIntent = {+ action: 'create',+ targets: [{ taskId: 'task-9' }],+ type: 'task' as const,+ };+ host.transports.tools!.registerWork = vi.fn().mockResolvedValue(undefined);+ runTool.mockResolvedValueOnce({+ attempts: 1,+ result: {+ content: 'task created',+ executionTime: 100,+ state: {},+ success: true,+ workRegistration: taskIntent,+ },+ });+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: createToolCall() },+ type: 'call_tool',+ };++ const result = await callTool(host)(instruction, createState());++ const toolEnd = findEvent(publishEvent.mock.calls, 'tool_end');+ expect(toolEnd.data.result.workRegistration).toEqual(taskIntent);+ const toolResultEvent = result.events.find(+ (event: any) => event.type === 'tool_result',+ ) as any;+ expect(toolResultEvent.result.workRegistration).toEqual(taskIntent);+ });++ it('redacts a skill intent on the returned events but registers the full intent (batch path)', async () => {+ const skillIntent = createSkillIntent();+ const registerWork = vi.fn().mockResolvedValue(undefined);+ host.transports.tools!.registerWork = registerWork;+ runTool.mockResolvedValue({+ attempts: 1,+ result: {+ content: 'issue found',+ executionTime: 100,+ state: {},+ success: true,+ workRegistration: skillIntent,+ },+ });+ const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [createToolCall('server-call')],+ },+ type: 'call_tools_batch',+ };++ const result = await callToolsBatch(host)(instruction, createState());++ const toolResultEvent = result.events.find(+ (event: any) => event.type === 'tool_result',+ ) as any;+ expect(toolResultEvent.result.workRegistration.data).toBeNull();+ expect(toolResultEvent.result.workRegistration.args).toBeUndefined();++ const toolEnd = findEvent(publishEvent.mock.calls, 'tool_end');+ expect(toolEnd.data.result.workRegistration.data).toBeNull();++ expect(registerWork).toHaveBeenCalledTimes(1);+ const registeredIntent = registerWork.mock.calls[0][0].intent;+ expect(registeredIntent.data).toEqual(skillIntent.data);+ expect(registeredIntent.args).toEqual(skillIntent.args);+ });+ });++ describe('todo state forwarding', () => {+ // Todo-mutating tools (lobe-agent createTodos/updateTodos) persist their own+ // copy into a plan document that only exists after `createPlan`. Message+ // history is the store that always exists, so the run context must carry it+ // — otherwise `updateTodos` reloads an empty list and silently drops every+ // index-based operation.+ const stateWithTodos = () =>+ createState({+ messages: [+ {+ content: 'todo tool result',+ id: 'tool-msg-0',+ plugin: { apiName: 'createTodos', identifier: 'lobe-agent', type: 'builtin' },+ pluginState: {+ todos: {+ items: [+ { status: 'completed', text: 'env setup' },+ { status: 'todo', text: 'run case 1' },+ ],+ updatedAt: '2026-07-09T00:00:00.000Z',+ },+ },+ role: 'tool',+ },+ ] as unknown as AgentState['messages'],+ });++ it('forwards todos rebuilt from message history to the tool transport', async () => {+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolCalling: createToolCall('tool-call-1', 'lobe-agent'),+ },+ type: 'call_tool',+ };++ await callTool(host)(instruction, stateWithTodos());++ expect(runTool).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ currentTodos: [+ { status: 'completed', text: 'env setup' },+ { status: 'todo', text: 'run case 1' },+ ],+ }),+ );+ });++ it('leaves currentTodos undefined when no todo state exists yet', async () => {+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolCalling: createToolCall(),+ },+ type: 'call_tool',+ };++ await callTool(host)(instruction, createState());++ expect(runTool.mock.calls[0][1].currentTodos).toBeUndefined();+ });+ });+});diff --git a/packages/agent-runtime/src/executors/tool.replay.test.ts b/packages/agent-runtime/src/executors/tool.replay.test.tsnew file mode 100644index 00000000000..13ee669ebc7--- /dev/null+++ b/packages/agent-runtime/src/executors/tool.replay.test.ts@@ -0,0 +1,362 @@+import type {+ ChatToolPayload,+ CreateMessageParams,+ UIChatMessage,+ WorkRegistrationIntent,+} from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import type { AgentRuntimeHost, ToolRunExecution } from '../transport';+import type { AgentInstruction, AgentState } from '../types';+import { omitToolWorkRegistration } from '../utils/redactResultForEvents';+import { callTool, callToolsBatch } from './tool';++const call: ChatToolPayload = {+ apiName: 'createDocument',+ arguments: '{"title":"one document"}',+ id: 'call-document',+ identifier: 'documents',+ type: 'builtin',+};++const fixture = (rows: Partial<UIChatMessage>[] = []) => {+ const stored = rows.map((row) => ({+ content: '',+ id: 'tool-existing',+ parentId: 'assistant-1',+ role: 'tool',+ tool_call_id: call.id,+ ...row,+ })) as UIChatMessage[];+ const messages = {+ createToolMessage: vi.fn(async (params: CreateMessageParams) => {+ const message = { ...params, id: `tool-${stored.length + 1}` } as UIChatMessage;+ stored.push(message);+ return message;+ }),+ deleteMessage: vi.fn(),+ findToolMessageIdByToolCallId: vi.fn(+ async (id: string, parentId: string) =>+ stored.find((row) => row.tool_call_id === id && row.parentId === parentId)?.id,+ ),+ getToolMessage: vi.fn(async (id: string) => stored.find((row) => row.id === id)),+ query: vi.fn(async () => structuredClone(stored).map(omitToolWorkRegistration)),+ updateToolIntervention: vi.fn(),+ updateToolMessage: vi.fn(async (id: string, value: Partial<UIChatMessage>) => {+ const row = stored.find((row) => row.id === id)!;+ Object.assign(row, value);+ }),+ };+ let documents = 0;+ const tools = {+ beforeToolCall: vi.fn(),+ getCost: vi.fn(() => 0),+ run: vi.fn(async (): Promise<ToolRunExecution> => {+ documents++;+ return {+ attempts: 1,+ result: {+ content: 'Created document docs-one',+ executionTime: 20,+ state: { documentId: 'docs-one' },+ success: true,+ },+ };+ }),+ };+ const host = {+ operation: { operationId: 'operation-1', stepIndex: 1 },+ transports: {+ messages,+ stream: { publishChunk: vi.fn(), publishEvent: vi.fn() },+ tools,+ },+ } as unknown as AgentRuntimeHost;+ const state = {+ cost: {+ currency: 'USD',+ llm: { byModel: [], total: 0 },+ tools: { byTool: [], total: 0 },+ total: 0,+ },+ messages: [],+ operationId: 'operation-1',+ origin: { agentId: 'agent-1', topicId: 'topic-1' },+ status: 'running',+ stepCount: 1,+ usage: { tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 } },+ } as unknown as AgentState;+ return { documents: () => documents, host, messages, state, stored, tools };+};++describe.each(['single', 'batch'] as const)('%s tool step redelivery', (mode) => {+ const execute = (f: ReturnType<typeof fixture>, extra = {}) => {+ const instruction =+ mode === 'single'+ ? {+ payload: { parentMessageId: 'assistant-1', toolCalling: call, ...extra },+ type: 'call_tool',+ }+ : {+ payload: { parentMessageId: 'assistant-1', toolsCalling: [call], ...extra },+ type: 'call_tools_batch',+ };+ return (mode === 'single' ? callTool : callToolsBatch)(f.host)(+ instruction as AgentInstruction,+ f.state,+ );+ };++ it('reuses a complete durable result without running hooks, side effects, or writing another row', async () => {+ const f = fixture([+ { content: 'Created original document', pluginState: { documentId: 'original' } },+ ]);+ const result = await execute(f);+ expect(f.tools.run).not.toHaveBeenCalled();+ expect(f.tools.beforeToolCall).not.toHaveBeenCalled();+ expect(f.messages.createToolMessage).not.toHaveBeenCalled();+ expect(f.messages.updateToolMessage).not.toHaveBeenCalled();+ expect(result.newState.messages).toContainEqual(+ expect.objectContaining({+ content: 'Created original document',+ id: 'tool-existing',+ pluginState: { documentId: 'original' },+ }),+ );+ expect(result.nextContext?.phase).toBe(+ mode === 'single' ? 'tool_result' : 'tools_batch_result',+ );+ });++ it.each([+ { content: '', pluginState: { status: 'pending' } },+ { content: '', pluginIntervention: { status: 'approved' } },+ { content: '...', pluginState: {} },+ { content: 'preview', pluginState: { status: 'pending' } },+ ])('fills an incomplete placeholder in place: %j', async (placeholder) => {+ const f = fixture([placeholder as Partial<UIChatMessage>]);+ await execute(f);+ expect(f.documents()).toBe(1);+ expect(f.messages.createToolMessage).not.toHaveBeenCalled();+ expect(f.stored).toHaveLength(1);+ await execute(f);+ expect(f.documents()).toBe(1);+ expect(f.stored[0]).toMatchObject({+ id: 'tool-existing',+ content: 'Created document docs-one',+ });+ expect(f.tools.run).toHaveBeenCalledWith(+ call,+ expect.objectContaining({+ reuseExistingMessage: true,+ toolMessageId: 'tool-existing',+ }),+ );+ });++ it('replaces a placeholder already present in the restored model context', async () => {+ const f = fixture([{ content: '', pluginState: { status: 'pending' } }]);+ f.state.messages = structuredClone(f.stored);+ const result = await execute(f);+ const rows = result.newState.messages.filter((row) => row.tool_call_id === call.id);+ expect(rows).toHaveLength(1);+ expect(rows[0].content).toBe('Created document docs-one');+ });++ it('executes a fresh call once and reuses the committed result when its step is replayed', async () => {+ const f = fixture();+ await execute(f);+ await execute(f); // Deliberately replay the pre-step checkpoint, not the returned state.+ expect(f.documents()).toBe(1);+ expect(f.stored).toHaveLength(1);+ expect(f.tools.run).toHaveBeenCalledTimes(1);+ });++ it.each([+ {+ action: 'register',+ document: { documentId: 'docs-one', changeType: 'created', toolName: 'createDocument' },+ type: 'document',+ },+ {+ args: { title: 'original title' },+ data: { url: 'https://example.com/items/42', body: 'untruncated result' },+ provider: 'example',+ toolName: 'createItem',+ type: 'skill',+ },+ ] satisfies WorkRegistrationIntent[])(+ 'replays a durable %s Work intent after registration is interrupted',+ async (intent) => {+ const f = fixture();+ const registerWork = vi+ .fn()+ .mockRejectedValueOnce(new Error('worker stopped'))+ .mockResolvedValue(undefined);+ f.host.transports.tools!.registerWork = registerWork;+ f.tools.run.mockResolvedValue({+ attempts: 1,+ result: {+ content: 'truncated result',+ executionTime: 20,+ success: true,+ workRegistration: intent,+ },+ });+ if (mode === 'batch') await expect(execute(f)).rejects.toThrow('worker stopped');+ else await execute(f);+ expect(f.stored).toHaveLength(1);+ const persisted = structuredClone(f.stored);+ // A new host has only the committed message, not the first execution's intent.+ const resumed = fixture(persisted);+ resumed.host.transports.tools!.registerWork = registerWork;+ const result = await execute(resumed);+ expect(resumed.tools.run).not.toHaveBeenCalled();+ expect(registerWork).toHaveBeenCalledTimes(2);+ expect(registerWork.mock.calls[1][0]).toMatchObject({+ intent,+ sourceMessageId: persisted[0].id,+ sourceToolCallId: call.id,+ state: registerWork.mock.calls[0][0].state,+ });+ if (intent.type === 'skill') {+ expect(result.events).not.toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ result: expect.objectContaining({ workRegistration: intent }),+ }),+ ]),+ );+ expect(JSON.stringify(result.newState.messages)).not.toContain('untruncated result');+ }+ },+ );++ it.each(['constructor', '__proto__'])(+ 'executes provider call id %s as an own key',+ async (id) => {+ const f = fixture();+ const originalId = call.id;+ call.id = id;+ try {+ await execute(f);+ expect(f.tools.run).toHaveBeenCalledOnce();+ } finally {+ call.id = originalId;+ }+ },+ );++ it('reuses a completed empty result with persisted execution metadata', async () => {+ const f = fixture([+ { content: '', metadata: { toolExecutionTimeMs: 20, toolResultSuccess: true } },+ ]);+ await execute(f);+ expect(f.tools.run).not.toHaveBeenCalled();+ expect(f.stored).toHaveLength(1);+ });++ it('does not reuse a provider call id from another assistant', async () => {+ const f = fixture([{ content: 'unrelated result', parentId: 'other-assistant' }]);+ await execute(f);+ expect(f.documents()).toBe(1);+ expect(f.stored).toHaveLength(2);+ });++ it('reuses a persisted error instead of repeating the failed side effect', async () => {+ const f = fixture([+ { content: 'Tool failed', pluginError: { message: 'failed', type: 'ToolError' } },+ ]);+ const result = await execute(f);+ expect(f.tools.run).not.toHaveBeenCalled();+ expect(result.events).toContainEqual(+ expect.objectContaining({+ id: call.id,+ result: expect.objectContaining({ content: 'Tool failed', success: false }),+ type: 'tool_result',+ }),+ );+ });++ it('reuses completed client results without parking the operation again', async () => {+ const f = fixture([{ content: 'client result' }]);+ f.state.toolSourceMap = { documents: 'client' as never };+ f.host.transports.tools!.beforeToolCall = undefined;+ const result = await execute(f);+ expect(f.tools.run).not.toHaveBeenCalled();+ expect(result.newState.status).toBe('running');+ expect(f.host.transports.stream.publishChunk).not.toHaveBeenCalled();+ });++ it('reuses a complete result from an explicit approval-resume row', async () => {+ const f = fixture([{ content: 'approved call already completed' }]);+ const result = await execute(+ f,+ mode === 'single'+ ? { parentMessageId: 'tool-existing', skipCreateToolMessage: true }+ : { existingToolMessageIds: { [call.id]: 'tool-existing' } },+ );+ expect(f.tools.run).not.toHaveBeenCalled();+ expect(result.newState.messages).toContainEqual(+ expect.objectContaining({ content: 'approved call already completed' }),+ );+ });++ it('propagates a failed replay lookup without executing any side effect', async () => {+ const f = fixture();+ f.messages.findToolMessageIdByToolCallId.mockRejectedValue(new Error('database unavailable'));+ await expect(execute(f)).rejects.toThrow('database unavailable');+ expect(f.tools.run).not.toHaveBeenCalled();+ });++ it('preserves a committed result if Stop was observed before the replay', async () => {+ const f = fixture([{ content: 'committed result' }]);+ f.host.operation.abortSignal = AbortSignal.abort();+ const result = await execute(f);+ expect(f.tools.run).not.toHaveBeenCalled();+ expect(f.messages.updateToolMessage).not.toHaveBeenCalled();+ expect(result.newState.messages).toContainEqual(+ expect.objectContaining({ content: 'committed result' }),+ );+ });++ it('preserves an unsuccessful result without an error on replay', async () => {+ const f = fixture();+ f.tools.run.mockResolvedValue({+ attempts: 1,+ result: {+ content: 'Handled failure',+ executionTime: 20,+ state: {},+ success: false,+ },+ });+ await execute(f);+ const replayed = await execute(f);+ expect(replayed.events).toContainEqual(+ expect.objectContaining({+ result: expect.objectContaining({ success: false }),+ type: 'tool_result',+ }),+ );+ expect(f.tools.run).toHaveBeenCalledTimes(1);+ });++ if (mode === 'single')+ it('preserves a terminal stop result on replay', async () => {+ const f = fixture();+ f.tools.run.mockResolvedValue({+ attempts: 1,+ result: {+ content: 'Finished',+ executionTime: 20,+ state: {},+ success: true,+ stop: true,+ },+ } as never);+ await execute(f);+ expect((await execute(f)).newState.status).toBe('done');+ expect(f.tools.run).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.tsindex 583a7eaa2c2..cfb5c7c4667 100644--- a/packages/agent-runtime/src/executors/tool.test.ts+++ b/packages/agent-runtime/src/executors/tool.test.ts@@ -2,56 +2,11 @@ import type { Mock } from 'vitest';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { AgentRuntimeHost } from '../transport';-import type { AgentInstruction, AgentRuntimeContext, AgentState } from '../types';-import { callTool, callToolsBatch } from './tool';--const createCost = () => ({- calculatedAt: '2026-07-09T00:00:00.000Z',- currency: 'USD',- llm: { byModel: [], currency: 'USD', total: 0 },- tools: { byTool: [], currency: 'USD', total: 0 },- total: 0,-});--const createUsage = () => ({- humanInteraction: {- approvalRequests: 0,- promptRequests: 0,- selectRequests: 0,- totalWaitingTimeMs: 0,- },- llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },- tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },-});--const createState = (overrides?: Partial<AgentState>): AgentState => ({- cost: createCost(),- createdAt: '2026-07-09T00:00:00.000Z',- lastModified: '2026-07-09T00:00:00.000Z',- maxSteps: 100,- messages: [],- origin: {- agentId: 'agent-1',- threadId: 'thread-1',- topicId: 'topic-1',- },- operationId: 'op-1',- status: 'running',- stepCount: 0,- toolManifestMap: {},- usage: createUsage(),- ...overrides,-});--const createToolCall = (id = 'tool-call-1', identifier = 'web-search') => ({- apiName: 'search',- arguments: '{"query":"test"}',- id,- identifier,- type: 'default' as const,-});+import type { AgentInstruction } from '../types';+import { callTool } from './tool';+import { createState, createToolCall, createToolExecutorFixture } from './tool.testUtils';-describe('tool executors', () => {+describe('single tool executors', () => {let createToolMessage: Mock;let findToolMessageIdByToolCallId: ReturnType<typeof vi.fn>;let updateToolIntervention: ReturnType<typeof vi.fn>;@@ -70,66 +25,19 @@ describe('tool executors', () => {let host: AgentRuntimeHost;beforeEach(() => {- toolRows = new Map();- createToolMessage = vi.fn().mockImplementation(async (params: any) => {- if (params?.tool_call_id) {- toolRows.set(params.tool_call_id, { id: 'tool-msg-1', parentId: params.parentId });- }- return { id: 'tool-msg-1' };- });- findToolMessageIdByToolCallId = vi- .fn()- .mockImplementation(async (toolCallId: string, parentMessageId: string) => {- const row = toolRows.get(toolCallId);- return row && row.parentId === parentMessageId ? row.id : undefined;- });- updateToolIntervention = vi.fn().mockResolvedValue(undefined);- updateToolMessage = vi.fn().mockResolvedValue(undefined);- publishChunk = vi.fn().mockResolvedValue(undefined);- publishError = vi.fn().mockResolvedValue(undefined);- publishEvent = vi.fn().mockResolvedValue(undefined);- query = vi.fn().mockResolvedValue([{ content: 'refreshed', id: 'msg-1', role: 'user' }]);- runTool = vi.fn().mockResolvedValue({- attempts: 1,- result: {- content: 'Tool result',- executionTime: 100,- state: {},- success: true,- },- });-- host = {- operation: {- operationId: 'op-1',- stepIndex: 2,- },- transports: {- messages: {- createAssistantMessage: vi.fn(),- createToolMessage,- deleteMessage: vi.fn(),- findById: vi.fn(),- findToolMessageIdByToolCallId,- query,- update: vi.fn(),- updatePluginState: vi.fn(),- updateToolIntervention,- updateToolMessage,- },- stream: {- publishChunk,- publishError,- publishEvent,- },- tools: {- getCost: vi.fn().mockReturnValue(0),- handleError: vi.fn(),- maxRetries: 2,- run: runTool,- },- },- } as unknown as AgentRuntimeHost;+ ({+ createToolMessage,+ findToolMessageIdByToolCallId,+ updateToolIntervention,+ updateToolMessage,+ toolRows,+ publishChunk,+ publishError,+ publishEvent,+ query,+ runTool,+ host,+ } = createToolExecutorFixture());});it('executes a single tool, persists the result, and advances to tool_result', async () => {@@ -155,7 +63,7 @@ describe('tool executors', () => {expect(createToolMessage).toHaveBeenCalledWith(expect.objectContaining({content: 'Tool result',- metadata: { toolExecutionTimeMs: 100 },+ metadata: expect.objectContaining({ toolExecutionTimeMs: 100 }),parentId: 'assistant-msg-1',role: 'tool',tool_call_id: 'tool-call-1',@@ -661,6 +569,7 @@ describe('tool executors', () => {},});+ toolRows.set('task-call', { id: 'approved-tool', parentId: 'assistant-msg-1' });const result = await callTool(host)({payload: {@@ -699,964 +608,4 @@ describe('tool executors', () => {expect.not.objectContaining({ toolMessageIds: expect.anything() }),);});-- it('collects placeholder ids for every deferred tool in a batch', async () => {- runTool.mockImplementation(async (tool: { id: string }) => ({- attempts: 1,- result: {- content: '',- deferred: true,- state: { status: 'pending', toolMessageId: `msg-for-${tool.id}` },- success: true,- },- }));-- await callToolsBatch(host)(- {- payload: {- parentMessageId: 'assistant-msg-1',- toolsCalling: [- createToolCall('sub-a', 'lobe-agent'),- createToolCall('sub-b', 'lobe-agent'),- ],- },- type: 'call_tools_batch',- },- createState(),- );-- expect(publishChunk).toHaveBeenCalledWith(- expect.objectContaining({- toolMessageIds: { 'sub-a': 'msg-for-sub-a', 'sub-b': 'msg-for-sub-b' },- }),- );- });-- it('passes the current step context to every tool in a batch', async () => {- const stepContext = {- activatedToolIds: ['page-editor'],- hasQueuedMessages: true,- };- const runtimeContext = {- phase: 'llm_result',- stepContext,- } satisfies AgentRuntimeContext;-- await callToolsBatch(host)(- {- payload: {- parentMessageId: 'assistant-msg-1',- toolsCalling: [createToolCall('tool-a'), createToolCall('tool-b')],- },- type: 'call_tools_batch',- },- createState(),- runtimeContext,- );-- expect(runTool).toHaveBeenCalledTimes(2);- expect(runTool.mock.calls.map(([, runContext]) => runContext.stepContext)).toEqual([- stepContext,- stepContext,- ]);- });-- it('executes server tools in a mixed batch then parks for client tools', async () => {- const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {- payload: {- parentMessageId: 'assistant-msg-1',- toolsCalling: [createToolCall('server-call'), createToolCall('client-call', 'client-tool')],- },- type: 'call_tools_batch',- };-- const result = await callToolsBatch(host)(- instruction,- createState({ toolSourceMap: { 'client-tool': 'client' as any } }),- );-- expect(runTool).toHaveBeenCalledTimes(1);- expect(createToolMessage).toHaveBeenCalledTimes(1);- expect(query).toHaveBeenCalledWith(- {- agentId: 'agent-1',- groupId: undefined,- threadId: 'thread-1',- topicId: 'topic-1',- },- { flatten: true, resolveAssetUrls: true },- );- expect(result.newState.status).toBe('waiting_for_async_tool');- expect(result.newState.pendingToolsCalling).toEqual([- expect.objectContaining({ id: 'client-call' }),- ]);- expect(result.events).toEqual(- expect.arrayContaining([- expect.objectContaining({ id: 'server-call', type: 'tool_result' }),- expect.objectContaining({ reason: 'client_tool_execution', type: 'interrupted' }),- ]),- );- });-- it('uses tool messages already persisted by the transport in a batch', async () => {- host.transports.tools!.canRunClientTools = true;- runTool.mockResolvedValueOnce({- attempts: 1,- result: { content: 'Client result', executionTime: 10, success: true },- resultPersisted: true,- toolMessageId: 'client-tool-msg',- });- const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {- payload: {- parentMessageId: 'assistant-msg-1',- toolsCalling: [createToolCall('client-call', 'client-tool')],- },- type: 'call_tools_batch',- };-- const result = await callToolsBatch(host)(- instruction,- createState({ toolSourceMap: { 'client-tool': 'client' as any } }),- );-- expect(createToolMessage).not.toHaveBeenCalled();- expect(host.transports.messages.updateToolMessage).not.toHaveBeenCalled();- // 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 () => {- const error = new Error('database failed');- createToolMessage.mockRejectedValueOnce(error);- const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {- payload: {- parentMessageId: 'assistant-msg-1',- toolCalling: createToolCall(),- },- type: 'call_tool',- };-- await expect(callTool(host)(instruction, createState())).rejects.toThrow('database failed');- expect(publishError).toHaveBeenCalledWith({- error,- phase: 'tool_message_persist',- stepIndex: 2,- });- });-- it('keeps finished batch results and writes aborted rows only for the rest', async () => {- const controller = new AbortController();- const abortingHost = {- ...host,- operation: { ...host.operation, abortSignal: controller.signal },- } as typeof host;-- const settled = createToolCall('settled-call');- const stuck = createToolCall('stuck-call');-- runTool.mockImplementation((tool: any) =>- tool.id === settled.id- ? Promise.resolve({- attempts: 1,- result: { content: 'done', executionTime: 1, success: true },- })- : new Promise(() => {- // never settles — abort is what ends the wait- }),- );-- const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {- payload: { parentMessageId: 'assistant-msg-1', toolsCalling: [settled, stuck] },- type: 'call_tools_batch',- };-- const pending = callToolsBatch(abortingHost)(instruction, createState());- // Let the settled tool resolve and persist its row before the abort lands.- await new Promise((resolve) => setTimeout(resolve, 0));- controller.abort();- const result = await pending;-- // The finished tool keeps its real result...- expect(result.events).toContainEqual(- expect.objectContaining({ id: settled.id, type: 'tool_result' }),- );- // ...and only the in-flight one gets an aborted row. Two rows total, one- // per tool_call_id — a partially settled batch must not lose either half.- expect(createToolMessage).toHaveBeenCalledTimes(2);- expect(createToolMessage).toHaveBeenCalledWith(- expect.objectContaining({- content: 'Tool execution was aborted by user.',- tool_call_id: stuck.id,- }),- );- });-- it('settles unstarted client tools instead of parking them when a mixed batch aborts', async () => {- const controller = new AbortController();- const abortingHost = {- ...host,- operation: { ...host.operation, abortSignal: controller.signal },- } as typeof host;-- const serverCall = createToolCall('server-call');- const clientCall = createToolCall('client-call', 'client-tool');-- runTool.mockImplementation(- () =>- new Promise(() => {- // never settles — the abort is what ends the wait- }),- );-- const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {- payload: { parentMessageId: 'assistant-msg-1', toolsCalling: [serverCall, clientCall] },- type: 'call_tools_batch',- };-- const pending = callToolsBatch(abortingHost)(- instruction,- createState({ toolSourceMap: { 'client-tool': 'client' as any } }),- );- controller.abort();- await pending;-- // The client call never started, and the pause it was waiting for would park- // it into a run nothing resumes — leaving its tool_call_id with no row ever.- const settledIds = createToolMessage.mock.calls.map((call: any) => call[0].tool_call_id);- expect(settledIds).toContain(serverCall.id);- expect(settledIds).toContain(clientCall.id);- expect(publishChunk).not.toHaveBeenCalledWith(- expect.objectContaining({ chunkType: 'tools_calling' }),- );- });-- it('writes one row per tool_call_id even if a call reaches the settle twice', async () => {- const controller = new AbortController();- controller.abort();- const abortingHost = {- ...host,- operation: { ...host.operation, abortSignal: controller.signal },- } as typeof host;-- const dupe = createToolCall('dupe-call');- const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {- payload: { parentMessageId: 'assistant-msg-1', toolsCalling: [dupe, dupe] },- type: 'call_tools_batch',- };-- await callToolsBatch(abortingHost)(instruction, createState());-- // Callers merge several abort sources into one list; "exactly one row per- // tool_call_id" has to survive that.- expect(createToolMessage).toHaveBeenCalledTimes(1);- });-- it('settles a client-only batch instead of parking it when already aborted', async () => {- const controller = new AbortController();- controller.abort();- const abortingHost = {- ...host,- operation: { ...host.operation, abortSignal: controller.signal },- } as typeof host;-- const a = createToolCall('client-a', 'client-tool');- const b = createToolCall('client-b', 'client-tool');- const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {- payload: { parentMessageId: 'assistant-msg-1', toolsCalling: [a, b] },- type: 'call_tools_batch',- };-- const result = await callToolsBatch(abortingHost)(- instruction,- createState({ toolSourceMap: { 'client-tool': 'client' as any } }),- );-- expect(publishChunk).not.toHaveBeenCalled();- const settledIds = createToolMessage.mock.calls.map((call: any) => call[0].tool_call_id);- expect(settledIds).toEqual([a.id, b.id]);- expect(result.newState.messages).toHaveLength(2);- });-- it('settles a client-only batch when aborted while publishing the pause chunk', async () => {- const controller = new AbortController();- const abortingHost = {- ...host,- operation: { ...host.operation, abortSignal: controller.signal },- } as typeof host;- let finishPublishing: (() => void) | undefined;- publishChunk.mockImplementationOnce(- () =>- new Promise<void>((resolve) => {- finishPublishing = resolve;- }),- );-- const a = createToolCall('client-a', 'client-tool');- const b = createToolCall('client-b', 'client-tool');- const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {- payload: { parentMessageId: 'assistant-msg-1', toolsCalling: [a, b] },- type: 'call_tools_batch',- };-- const pending = callToolsBatch(abortingHost)(- instruction,- createState({ toolSourceMap: { 'client-tool': 'client' as any } }),- );- await vi.waitFor(() => expect(finishPublishing).toBeTypeOf('function'));- controller.abort();- finishPublishing!();- const result = await pending;-- expect(result.newState.status).toBe('running');- expect(result.newState.messages).toHaveLength(2);- expect(createToolMessage).toHaveBeenCalledTimes(2);- });-- it('settles approved client rows in a mixed batch rather than duplicating them', async () => {- const controller = new AbortController();- controller.abort();- const abortingHost = {- ...host,- operation: { ...host.operation, abortSignal: controller.signal },- } as typeof host;-- const serverCall = createToolCall('server-call');- const clientCall = createToolCall('client-call', 'client-tool');-- // An approved batch resume left a pending row for EVERY call, including the- // client ones that never enter `toolsToExecute`.- toolRows.set(serverCall.id, { id: 'server-row', parentId: 'assistant-msg-1' });- toolRows.set(clientCall.id, { id: 'client-row', parentId: 'assistant-msg-1' });- const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {- payload: {- parentMessageId: 'assistant-msg-1',- toolsCalling: [serverCall, clientCall],- },- type: 'call_tools_batch',- };-- await callToolsBatch(abortingHost)(- instruction,- createState({ toolSourceMap: { 'client-tool': 'client' as any } }),- );-- expect(createToolMessage).not.toHaveBeenCalled();- expect(updateToolIntervention).toHaveBeenCalledWith('client-row', { status: 'aborted' });- expect(updateToolIntervention).toHaveBeenCalledWith('server-row', { status: 'aborted' });- });-- it('ignores a reused tool_call_id that belongs to another turn', async () => {- const controller = new AbortController();- controller.abort();- const abortingHost = {- ...host,- operation: { ...host.operation, abortSignal: controller.signal },- } as typeof host;-- const toolCall = createToolCall();- // Same id, different assistant — `tool_call_id` is provider-supplied and- // only indexed, so a reuse across turns is possible. Settling that row would- // overwrite a real historical result AND leave this call without one.- toolRows.set(toolCall.id, { id: 'older-turn-row', parentId: 'assistant-msg-OLD' });-- const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {- payload: { parentMessageId: 'assistant-msg-1', toolCalling: toolCall },- type: 'call_tool',- };-- await callTool(abortingHost)(instruction, createState());-- expect(updateToolMessage).not.toHaveBeenCalledWith('older-turn-row', expect.anything());- expect(createToolMessage).toHaveBeenCalledWith(- expect.objectContaining({ parentId: 'assistant-msg-1', tool_call_id: toolCall.id }),- );- });-- 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('serialized batch calls', () => {- // Several editFile calls to one path in a batch reached the device at once;- // each read the same snapshot and the last write dropped the others while- // every call reported success. Calls naming the same resource through- // `serializeBy` queue in emission order; other paths stay concurrent.- const manifestMap = {- 'lobe-local-system': {- api: [- { name: 'editFile', serializeBy: 'file_path' },- { name: 'writeFile', serializeBy: 'path' },- { name: 'readFile' },- ],- identifier: 'lobe-local-system',- },- };-- const fileCall = (id: string, apiName: string, args: Record<string, unknown>) => ({- apiName,- arguments: JSON.stringify(args),- id,- identifier: 'lobe-local-system',- type: 'builtin' as const,- });-- const trackingRunner = (delays: Record<string, number>, timeline: string[]) =>- vi.fn().mockImplementation(async (tool: { id: string }) => {- timeline.push(`start:${tool.id}`);- await new Promise((resolve) => setTimeout(resolve, delays[tool.id] ?? 0));- timeline.push(`end:${tool.id}`);- return {- attempts: 1,- result: { content: `done ${tool.id}`, executionTime: 1, state: {}, success: true },- };- });-- beforeEach(() => {- host.transports.messages.createToolMessage = vi- .fn()- .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({- id: `tool-msg-${tool_call_id}`,- }));- });-- it('runs edits and writes to one path one after another, in emission order', async () => {- const timeline: string[] = [];- host.transports.tools!.run = trackingRunner(- { 'edit-1': 30, 'edit-2': 10, 'write-1': 0 },- timeline,- );-- const result = await callToolsBatch(host)(- {- payload: {- parentMessageId: 'assistant-msg-1',- toolsCalling: [- fileCall('edit-1', 'editFile', { file_path: '/repo/a.ts', old_string: 'x' }),- fileCall('edit-2', 'editFile', { file_path: '/repo/a.ts', old_string: 'y' }),- fileCall('write-1', 'writeFile', { content: 'z', path: '/repo/a.ts' }),- ],- },- type: 'call_tools_batch',- },- createState({ toolManifestMap: manifestMap }),- );-- expect(timeline).toEqual([- 'start:edit-1',- 'end:edit-1',- 'start:edit-2',- 'end:edit-2',- 'start:write-1',- 'end:write-1',- ]);- expect((result.nextContext?.payload as any).toolResults).toHaveLength(3);- });-- it('keeps edits to different paths and unmarked reads concurrent', async () => {- const timeline: string[] = [];- host.transports.tools!.run = trackingRunner(- { 'edit-a': 30, 'edit-b': 0, 'read-a': 0 },- timeline,- );-- await callToolsBatch(host)(- {- payload: {- parentMessageId: 'assistant-msg-1',- toolsCalling: [- fileCall('edit-a', 'editFile', { file_path: '/repo/a.ts', old_string: 'x' }),- fileCall('edit-b', 'editFile', { file_path: '/repo/b.ts', old_string: 'x' }),- fileCall('read-a', 'readFile', { path: '/repo/a.ts' }),- ],- },- type: 'call_tools_batch',- },- createState({ toolManifestMap: manifestMap }),- );-- // All three start before the slow edit to a.ts finishes.- expect(timeline.slice(0, 3).sort()).toEqual(['start:edit-a', 'start:edit-b', 'start:read-a']);- });- });-- describe('ordered batch calls', () => {- // A model that posts a long report as several `sendMessage` calls emits- // them in reading order, but `Promise.all` handed every call to the- // platform at once and the channel kept whichever arrived first. An API- // marked `ordered` runs its calls one after another in emission order;- // everything else in the batch stays concurrent.- const manifestMap = {- 'lobe-message': {- api: [- { name: 'sendMessage', ordered: true },- { name: 'replyToThread', ordered: true },- { name: 'readMessages' },- ],- identifier: 'lobe-message',- },- };-- const messageCall = (id: string, apiName: string) => ({- apiName,- arguments: '{}',- id,- identifier: 'lobe-message',- type: 'builtin' as const,- });-- const batchOf = (- toolsCalling: ReturnType<typeof messageCall>[],- ): Extract<AgentInstruction, { type: 'call_tools_batch' }> => ({- payload: { parentMessageId: 'assistant-msg-1', toolsCalling },- type: 'call_tools_batch',- });-- /** Records `start:<id>` / `end:<id>` so the interleaving is observable. */- const trackingRunner = (delays: Record<string, number>, timeline: string[]) =>- vi.fn().mockImplementation(async (tool: { id: string }) => {- timeline.push(`start:${tool.id}`);- await new Promise((resolve) => setTimeout(resolve, delays[tool.id] ?? 0));- timeline.push(`end:${tool.id}`);- return {- attempts: 1,- result: { content: `sent ${tool.id}`, executionTime: 1, state: {}, success: true },- };- });-- it('runs ordered calls one after another in emission order, even when the first is slowest', async () => {- const timeline: string[] = [];- // Slowest first: concurrent dispatch would finish send-3 before send-1.- host.transports.tools!.run = trackingRunner(- { 'send-1': 30, 'send-2': 10, 'send-3': 0 },- timeline,- );- 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([- messageCall('send-1', 'sendMessage'),- messageCall('send-2', 'sendMessage'),- messageCall('send-3', 'replyToThread'),- ]),- createState({ toolManifestMap: manifestMap }),- );-- expect(timeline).toEqual([- 'start:send-1',- 'end:send-1',- 'start:send-2',- 'end:send-2',- 'start:send-3',- 'end:send-3',- ]);- // Every call still lands in the batch result.- expect((result.nextContext?.payload as any).toolResults).toHaveLength(3);- expect(result.nextContext?.payload).toMatchObject({ parentMessageId: 'assistant-msg-1' });- });-- it('does not hold up unordered siblings behind the ordered chain', async () => {- const timeline: string[] = [];- host.transports.tools!.run = trackingRunner(- { 'read-1': 0, 'send-1': 30, 'send-2': 10 },- timeline,- );- host.transports.messages.createToolMessage = vi- .fn()- .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({- id: `tool-msg-${tool_call_id}`,- }));-- await callToolsBatch(host)(- batchOf([- messageCall('send-1', 'sendMessage'),- messageCall('read-1', 'readMessages'),- messageCall('send-2', 'sendMessage'),- ]),- createState({ toolManifestMap: manifestMap }),- );-- // The read finished while send-1 was still in flight …- expect(timeline.indexOf('end:read-1')).toBeLessThan(timeline.indexOf('end:send-1'));- // … and send-2 still waited for send-1.- expect(timeline.indexOf('start:send-2')).toBeGreaterThan(timeline.indexOf('end:send-1'));- });-- it('reads the flag from a step-activated manifest as well', async () => {- const timeline: string[] = [];- host.transports.tools!.run = trackingRunner({ 'send-1': 20, 'send-2': 0 }, timeline);- host.transports.messages.createToolMessage = vi- .fn()- .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({- id: `tool-msg-${tool_call_id}`,- }));-- await callToolsBatch(host)(- batchOf([messageCall('send-1', 'sendMessage'), messageCall('send-2', 'sendMessage')]),- createState({- activatedStepTools: [- {- activatedAtStep: 0,- id: 'lobe-message',- manifest: manifestMap['lobe-message'] as any,- source: 'activator' as any,- },- ],- toolManifestMap: {},- }),- );-- expect(timeline).toEqual(['start:send-1', 'end:send-1', 'start:send-2', 'end:send-2']);- });-- it('keeps unmarked calls concurrent', async () => {- const timeline: string[] = [];- host.transports.tools!.run = trackingRunner({ 'read-1': 20, 'read-2': 0 }, timeline);- host.transports.messages.createToolMessage = vi- .fn()- .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({- id: `tool-msg-${tool_call_id}`,- }));-- await callToolsBatch(host)(- batchOf([messageCall('read-1', 'readMessages'), messageCall('read-2', 'readMessages')]),- createState({ toolManifestMap: manifestMap }),- );-- expect(timeline.indexOf('start:read-2')).toBeLessThan(timeline.indexOf('end:read-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- // event nor the returned `events` array (which get serialized into the- // capped Redis step blob) — clients only read `workRegistration` as a- // presence flag.- const createSkillIntent = () => ({- args: { number: 42, repo: 'lobehub/lobehub' },- data: { body: 'x'.repeat(500), issues: Array.from({ length: 30 }, (_, i) => ({ id: i })) },- provider: 'github',- toolName: 'github.searchIssues',- type: 'skill' as const,- });-- const findEvent = (calls: unknown[][], type: string) =>- calls.map((call) => call[0] as any).find((event) => event?.type === type);-- it('redacts a skill intent on the stream event and returned events, but registers the full intent (single path)', async () => {- const skillIntent = createSkillIntent();- const registerWork = vi.fn().mockResolvedValue(undefined);- host.transports.tools!.registerWork = registerWork;- runTool.mockResolvedValueOnce({- attempts: 1,- result: {- content: 'issue found',- executionTime: 100,- state: {},- success: true,- workRegistration: skillIntent,- },- });- const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {- payload: { parentMessageId: 'assistant-msg-1', toolCalling: createToolCall() },- type: 'call_tool',- };-- const result = await callTool(host)(instruction, createState());-- // 1) Published `tool_end` stream event: presence flag preserved, payload stripped.- const toolEnd = findEvent(publishEvent.mock.calls, 'tool_end');- expect(toolEnd.data.result.workRegistration).toEqual({- args: undefined,- data: null,- provider: 'github',- toolName: 'github.searchIssues',- type: 'skill',- });-- // 2) Returned step `events` array (serialized into the Redis step blob).- const toolResultEvent = result.events.find(- (event: any) => event.type === 'tool_result',- ) as any;- expect(toolResultEvent.result.workRegistration.data).toBeNull();- expect(toolResultEvent.result.workRegistration.args).toBeUndefined();-- // 3) `registerWork` still receives the FULL intent (data + args intact).- expect(registerWork).toHaveBeenCalledTimes(1);- const registeredIntent = registerWork.mock.calls[0][0].intent;- expect(registeredIntent.data).toEqual(skillIntent.data);- expect(registeredIntent.args).toEqual(skillIntent.args);- });-- it('passes a non-skill (task) intent through unredacted (single path)', async () => {- const taskIntent = {- action: 'create',- targets: [{ taskId: 'task-9' }],- type: 'task' as const,- };- host.transports.tools!.registerWork = vi.fn().mockResolvedValue(undefined);- runTool.mockResolvedValueOnce({- attempts: 1,- result: {- content: 'task created',- executionTime: 100,- state: {},- success: true,- workRegistration: taskIntent,- },- });- const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {- payload: { parentMessageId: 'assistant-msg-1', toolCalling: createToolCall() },- type: 'call_tool',- };-- const result = await callTool(host)(instruction, createState());-- const toolEnd = findEvent(publishEvent.mock.calls, 'tool_end');- expect(toolEnd.data.result.workRegistration).toEqual(taskIntent);- const toolResultEvent = result.events.find(- (event: any) => event.type === 'tool_result',- ) as any;- expect(toolResultEvent.result.workRegistration).toEqual(taskIntent);- });-- it('redacts a skill intent on the returned events but registers the full intent (batch path)', async () => {- const skillIntent = createSkillIntent();- const registerWork = vi.fn().mockResolvedValue(undefined);- host.transports.tools!.registerWork = registerWork;- runTool.mockResolvedValue({- attempts: 1,- result: {- content: 'issue found',- executionTime: 100,- state: {},- success: true,- workRegistration: skillIntent,- },- });- const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {- payload: {- parentMessageId: 'assistant-msg-1',- toolsCalling: [createToolCall('server-call')],- },- type: 'call_tools_batch',- };-- const result = await callToolsBatch(host)(instruction, createState());-- const toolResultEvent = result.events.find(- (event: any) => event.type === 'tool_result',- ) as any;- expect(toolResultEvent.result.workRegistration.data).toBeNull();- expect(toolResultEvent.result.workRegistration.args).toBeUndefined();-- const toolEnd = findEvent(publishEvent.mock.calls, 'tool_end');- expect(toolEnd.data.result.workRegistration.data).toBeNull();-- expect(registerWork).toHaveBeenCalledTimes(1);- const registeredIntent = registerWork.mock.calls[0][0].intent;- expect(registeredIntent.data).toEqual(skillIntent.data);- expect(registeredIntent.args).toEqual(skillIntent.args);- });- });-- describe('todo state forwarding', () => {- // Todo-mutating tools (lobe-agent createTodos/updateTodos) persist their own- // copy into a plan document that only exists after `createPlan`. Message- // history is the store that always exists, so the run context must carry it- // — otherwise `updateTodos` reloads an empty list and silently drops every- // index-based operation.- const stateWithTodos = () =>- createState({- messages: [- {- content: 'todo tool result',- id: 'tool-msg-0',- plugin: { apiName: 'createTodos', identifier: 'lobe-agent', type: 'builtin' },- pluginState: {- todos: {- items: [- { status: 'completed', text: 'env setup' },- { status: 'todo', text: 'run case 1' },- ],- updatedAt: '2026-07-09T00:00:00.000Z',- },- },- role: 'tool',- },- ] as unknown as AgentState['messages'],- });-- it('forwards todos rebuilt from message history to the tool transport', async () => {- const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {- payload: {- parentMessageId: 'assistant-msg-1',- toolCalling: createToolCall('tool-call-1', 'lobe-agent'),- },- type: 'call_tool',- };-- await callTool(host)(instruction, stateWithTodos());-- expect(runTool).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({- currentTodos: [- { status: 'completed', text: 'env setup' },- { status: 'todo', text: 'run case 1' },- ],- }),- );- });-- it('leaves currentTodos undefined when no todo state exists yet', async () => {- const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {- payload: {- parentMessageId: 'assistant-msg-1',- toolCalling: createToolCall(),- },- type: 'call_tool',- };-- await callTool(host)(instruction, createState());-- expect(runTool.mock.calls[0][1].currentTodos).toBeUndefined();- });- });});diff --git a/packages/agent-runtime/src/executors/tool.testUtils.ts b/packages/agent-runtime/src/executors/tool.testUtils.tsnew file mode 100644index 00000000000..330506c5c73--- /dev/null+++ b/packages/agent-runtime/src/executors/tool.testUtils.ts@@ -0,0 +1,131 @@+import { vi } from 'vitest';++import type { AgentRuntimeHost } from '../transport';+import type { AgentState } from '../types';++const createCost = () => ({+ calculatedAt: '2026-07-09T00:00:00.000Z',+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ total: 0,+});++const createUsage = () => ({+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+});++export const createState = (overrides?: Partial<AgentState>): AgentState => ({+ cost: createCost(),+ createdAt: '2026-07-09T00:00:00.000Z',+ lastModified: '2026-07-09T00:00:00.000Z',+ maxSteps: 100,+ messages: [],+ origin: {+ agentId: 'agent-1',+ threadId: 'thread-1',+ topicId: 'topic-1',+ },+ operationId: 'op-1',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+ usage: createUsage(),+ ...overrides,+});++export const createToolCall = (id = 'tool-call-1', identifier = 'web-search') => ({+ apiName: 'search',+ arguments: '{"query":"test"}',+ id,+ identifier,+ type: 'default' as const,+});++export const createToolExecutorFixture = () => {+ const toolRows = new Map<string, { id: string; parentId: string }>();+ const createToolMessage = vi.fn().mockImplementation(async (params: any) => {+ if (params?.tool_call_id) {+ toolRows.set(params.tool_call_id, { id: 'tool-msg-1', parentId: params.parentId });+ }+ return { id: 'tool-msg-1' };+ });+ const findToolMessageIdByToolCallId = vi+ .fn()+ .mockImplementation(async (toolCallId: string, parentMessageId: string) => {+ const row = toolRows.get(toolCallId);+ return row && row.parentId === parentMessageId ? row.id : undefined;+ });+ const updateToolIntervention = vi.fn().mockResolvedValue(undefined);+ const updateToolMessage = vi.fn().mockResolvedValue(undefined);+ const publishChunk = vi.fn().mockResolvedValue(undefined);+ const publishError = vi.fn().mockResolvedValue(undefined);+ const publishEvent = vi.fn().mockResolvedValue(undefined);+ const query = vi.fn().mockResolvedValue([{ content: 'refreshed', id: 'msg-1', role: 'user' }]);+ const runTool = vi.fn().mockResolvedValue({+ attempts: 1,+ result: {+ content: 'Tool result',+ executionTime: 100,+ state: {},+ success: true,+ },+ });++ const host = {+ operation: {+ operationId: 'op-1',+ stepIndex: 2,+ },+ transports: {+ messages: {+ createAssistantMessage: vi.fn(),+ createToolMessage,+ deleteMessage: vi.fn(),+ findById: vi.fn(),+ findToolMessageIdByToolCallId,+ getToolMessage: vi.fn(async (id: string) => {+ const entry = [...toolRows].find(([, row]) => row.id === id);+ return entry ? { content: '', id, role: 'tool', tool_call_id: entry[0] } : undefined;+ }),+ query,+ update: vi.fn(),+ updatePluginState: vi.fn(),+ updateToolIntervention,+ updateToolMessage,+ },+ stream: {+ publishChunk,+ publishError,+ publishEvent,+ },+ tools: {+ getCost: vi.fn().mockReturnValue(0),+ handleError: vi.fn(),+ maxRetries: 2,+ run: runTool,+ },+ },+ } as unknown as AgentRuntimeHost;++ return {+ createToolMessage,+ findToolMessageIdByToolCallId,+ updateToolIntervention,+ updateToolMessage,+ toolRows,+ publishChunk,+ publishError,+ publishEvent,+ query,+ runTool,+ host,+ };+};diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.tsindex db216f82a9c..8e576e0d90d 100644--- a/packages/agent-runtime/src/executors/tool.ts+++ b/packages/agent-runtime/src/executors/tool.ts@@ -21,13 +21,19 @@ import {} from '../utils';import { selectEffectiveToolManifestMap, selectToolSourceMap } from '../utils/operationToolSet';import { settleAbortedToolRows } from './abortedToolRows';+import {+ createToolMessage,+ isBlockedBeforeExecution,+ isPersistFatal,+ persistToolResultMetadata,+ publishError,+ updateExistingToolMessage,+} from './toolPersistence';+import { resolveToolReplay } from './toolReplay';const TOOL_EXECUTION_PHASE = 'tool_execution';-const TOOL_MESSAGE_PERSIST_PHASE = 'tool_message_persist';const DEFAULT_TOOL_MAX_RETRIES = 2;-const persistFatalErrors = new WeakSet<object>();-interface ToolResultEntry {data: ToolRunResult;executionTime: number;@@ -48,37 +54,6 @@ interface ToolResultEntry {const nowIso = () => new Date().toISOString();-const markPersistFatal = <T>(error: T): T => {- if (error && typeof error === 'object') persistFatalErrors.add(error);- return error;-};--const isPersistFatal = (error: unknown) =>- !!error && typeof error === 'object' && persistFatalErrors.has(error);--const getErrorType = (error: unknown): string | undefined => {- if (!error || typeof error !== 'object') return;-- const value = (error as { errorType?: unknown; name?: unknown; type?: unknown }).errorType;- if (typeof value === 'string' || typeof value === 'number') return String(value);-- const type = (error as { type?: unknown }).type;- if (typeof type === 'string' || typeof type === 'number') return String(type);-- const name = error instanceof Error ? error.name : undefined;- return name || undefined;-};--const getErrorMessage = (error: unknown): string => {- if (error instanceof Error && error.message) return error.message;- if (typeof error === 'string' && error) return error;- if (error && typeof error === 'object') {- const message = (error as { message?: unknown }).message;- if (typeof message === 'string' && message) return message;- }- return 'Unknown error';-};-const requireToolTransport = (host: AgentRuntimeHost) => {const tools = host.transports.tools;if (!tools) {@@ -89,10 +64,6 @@ const requireToolTransport = (host: AgentRuntimeHost) => {const toolNameOf = (tool: ChatToolPayload) => `${tool.identifier}/${tool.apiName}`;-// Execution-entry denial is free; withholding an already executed result is not.-const isBlockedBeforeExecution = (result: ToolRunResult) =>- result.state?.type === 'blocked' && result.state.phase !== 'afterToolCall';-const resolveToolSource = (state: AgentState, tool: ChatToolPayload): string | undefined =>selectToolSourceMap(state)[tool.identifier];@@ -357,25 +328,6 @@ const settleAbortedCall = async ({};};-const publishError = async (host: AgentRuntimeHost, error: unknown, phase: string) => {- const { stepIndex } = host.operation;-- if (host.transports.stream.publishError) {- await host.transports.stream.publishError({ error, phase, stepIndex });- return;- }-- await host.transports.stream.publishEvent({- data: {- error: getErrorMessage(error),- errorType: getErrorType(error),- phase,- },- stepIndex,- type: 'error',- });-};-/*** A deferred tool's runtime has already created the row its result will be* backfilled into (e.g. `callSubAgent`'s pending placeholder) and hands the id@@ -457,83 +409,6 @@ const pauseForTools = async ({};};-const createToolMessage = async ({- host,- parentMessageId,- result,- resultBlocked,- state,- tool,-}: {- host: AgentRuntimeHost;- parentMessageId: string;- result: ToolRunResult;- resultBlocked?: boolean;- state: AgentState;- tool: ChatToolPayload;-}) => {- try {- const agentId = host.operation.agentId ?? state.origin?.agentId;- if (!agentId) {- throw new Error(- `[call_tool] Missing agentId for tool message (op=${host.operation.operationId})`,- );- }-- return await host.transports.messages.createToolMessage({- agentId,- content: result.content,- groupId: host.operation.groupId ?? state.origin?.groupId ?? undefined,- metadata: { toolExecutionTimeMs: result.executionTime ?? 0 },- parentId: parentMessageId,- plugin: tool as any,- pluginError: result.error ?? null,- ...((isBlockedBeforeExecution(result) || resultBlocked) && {- pluginIntervention: { rejectedReason: result.state?.reason, status: 'rejected' },- }),- pluginState: result.state,- role: 'tool',- threadId: host.operation.threadId ?? state.origin?.threadId,- tool_call_id: tool.id,- topicId: host.operation.topicId ?? state.origin?.topicId,- });- } catch (error) {- await publishError(host, error, TOOL_MESSAGE_PERSIST_PHASE);- throw markPersistFatal(error);- }-};--const updateExistingToolMessage = async ({- host,- result,- resultBlocked,- toolMessageId,-}: {- host: AgentRuntimeHost;- result: ToolRunResult;- resultBlocked?: boolean;- toolMessageId: string;-}) => {- try {- await host.transports.messages.updateToolMessage(toolMessageId, {- content: result.content,- metadata: { toolExecutionTimeMs: result.executionTime ?? 0 },- pluginError: result.error ?? null,- pluginState: result.state,- ...(resultBlocked && { replacePluginState: true }),- });- if (isBlockedBeforeExecution(result) || resultBlocked) {- await host.transports.messages.updateToolIntervention(toolMessageId, {- rejectedReason: result.state?.reason,- status: 'rejected',- });- }- } catch (error) {- await publishError(host, error, TOOL_MESSAGE_PERSIST_PHASE);- throw markPersistFatal(error);- }-};-const persistActivatedTools = ({effectiveManifestMap,newState,@@ -581,15 +456,21 @@ export const callTool =const tools = requireToolTransport(host);const tool = payload.toolCalling;const events: AgentEvent[] = [];+ const replay = await resolveToolReplay({+ existingToolMessageId: payload.skipCreateToolMessage ? payload.parentMessageId : undefined,+ host,+ parentMessageId: payload.parentMessageId,+ tool,+ });const runContext = createRunContext({host,mode: 'single',parentMessageId: payload.parentMessageId,- reuseExistingMessage: payload.skipCreateToolMessage,+ reuseExistingMessage: !!replay.toolMessageId,state,stepContext: runtimeContext?.stepContext,tool,- toolMessageId: payload.skipCreateToolMessage ? payload.parentMessageId : undefined,+ toolMessageId: replay.toolMessageId,});await host.transports.stream.publishEvent({@@ -599,11 +480,13 @@ export const callTool =});try {- const intercepted = await raceToolAbort(- () => tools.beforeToolCall?.(tool, runContext) ?? Promise.resolve(undefined),- host.operation.abortSignal,- );- if (host.operation.abortSignal?.aborted) throw new ToolAbortedError();+ const intercepted =+ replay.execution ??+ (await raceToolAbort(+ () => tools.beforeToolCall?.(tool, runContext) ?? Promise.resolve(undefined),+ host.operation.abortSignal,+ ));+ if (!replay.execution && host.operation.abortSignal?.aborted) throw new ToolAbortedError();if (!intercepted && runContext.toolSource === 'client' && !tools.canRunClientTools) {const paused = await pauseForTools({host,@@ -619,9 +502,7 @@ export const callTool =if (host.operation.abortSignal?.aborted) {return settleAbortedCall({events,- existingToolMessageId: payload.skipCreateToolMessage- ? payload.parentMessageId- : undefined,+ existingToolMessageId: replay.toolMessageId,host,parentMessageId: payload.parentMessageId,state,@@ -642,9 +523,7 @@ export const callTool =// used to strand the tool_call_id with no row at all.return settleAbortedCall({events,- existingToolMessageId: payload.skipCreateToolMessage- ? payload.parentMessageId- : undefined,+ existingToolMessageId: replay.toolMessageId,host,parentMessageId: payload.parentMessageId,state,@@ -694,8 +573,8 @@ export const callTool =resultBlocked: execution.resultBlocked,});}- } else if (payload.skipCreateToolMessage) {- toolMessageId = payload.parentMessageId;+ } else if (replay.toolMessageId) {+ toolMessageId = replay.toolMessageId;await updateExistingToolMessage({host,result: executionResult,@@ -714,6 +593,9 @@ export const callTool =toolMessageId = toolMessage.id;}+ if (execution.resultPersisted && !replay.execution) {+ await persistToolResultMetadata(host, toolMessageId, executionResult);+ }const newState = structuredClone(state);if (execution.resultPersisted) {newState.messages = await host.transports.messages.query({@@ -729,14 +611,19 @@ export const callTool =* and an id-less tool result makes that safety gate keep the stale* snapshot instead.*/- newState.messages.push({+ const toolMessage = {content: executionResult.content,id: toolMessageId,plugin: tool,pluginState: executionResult.state,role: 'tool',tool_call_id: tool.id,- });+ };+ const existingIndex = newState.messages.findIndex(+ (message) => message.id === toolMessageId,+ );+ if (existingIndex >= 0) newState.messages[existingIndex] = toolMessage;+ else newState.messages.push(toolMessage);}newState.lastModified = nowIso();@@ -844,9 +731,7 @@ export const callTool =if (isOperationAbort(error, host.operation.abortSignal)) {return settleAbortedCall({events,- existingToolMessageId: payload.skipCreateToolMessage- ? payload.parentMessageId- : undefined,+ existingToolMessageId: replay.toolMessageId,host,parentMessageId: payload.parentMessageId,state,@@ -873,14 +758,33 @@ export const callToolsBatch =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 existingToolMessageIds: Record<string, string> = Object.assign(+ Object.create(null),+ payload.existingToolMessageIds,+ );const tools = requireToolTransport(host);const events: AgentEvent[] = [];const clientTools: ChatToolPayload[] = [];const serverTools: ChatToolPayload[] = [];+ const replays = new Map(+ await Promise.all(+ toolsCalling.map(async (tool) => {+ const replay = await resolveToolReplay({+ existingToolMessageId: existingToolMessageIds[tool.id],+ host,+ parentMessageId,+ tool,+ });+ if (replay.toolMessageId) existingToolMessageIds[tool.id] = replay.toolMessageId;+ return [tool.id, replay] as const;+ }),+ ),+ );+for (const tool of toolsCalling) {if (+ !replays.get(tool.id)?.execution &&!tools.beforeToolCall &&resolveToolSource(state, tool) === 'client' &&!tools.canRunClientTools@@ -966,11 +870,14 @@ export const callToolsBatch =});try {- const intercepted = await raceToolAbort(- () => tools.beforeToolCall?.(tool, runContext) ?? Promise.resolve(undefined),- host.operation.abortSignal,- );- if (host.operation.abortSignal?.aborted) throw new ToolAbortedError();+ const intercepted =+ replays.get(tool.id)?.execution ??+ (await raceToolAbort(+ () => tools.beforeToolCall?.(tool, runContext) ?? Promise.resolve(undefined),+ host.operation.abortSignal,+ ));+ if (!replays.get(tool.id)?.execution && host.operation.abortSignal?.aborted)+ throw new ToolAbortedError();if (!intercepted && runContext.toolSource === 'client' && !tools.canRunClientTools) {clientTools.push(tool);return;@@ -1045,6 +952,10 @@ export const callToolsBatch =toolMessageId = toolMessage.id;}+ if (execution.resultPersisted && !replays.get(tool.id)?.execution) {+ await persistToolResultMetadata(host, toolMessageId, executionResult);+ }+// `sourceMessageId` + `workRegistration` are carried so the// post-batch accumulate loop can persist the Work version ONCE with// this call's cumulative cost (known only then).diff --git a/packages/agent-runtime/src/executors/toolPersistence.ts b/packages/agent-runtime/src/executors/toolPersistence.tsnew file mode 100644index 00000000000..1eb8802ea99--- /dev/null+++ b/packages/agent-runtime/src/executors/toolPersistence.ts@@ -0,0 +1,161 @@+import type { ChatToolPayload } from '@lobechat/types';++import type { AgentRuntimeHost, ToolRunResult } from '../transport';+import type { AgentState } from '../types';++const TOOL_MESSAGE_PERSIST_PHASE = 'tool_message_persist';++const persistFatalErrors = new WeakSet<object>();++const markPersistFatal = <T>(error: T): T => {+ if (error && typeof error === 'object') persistFatalErrors.add(error);+ return error;+};++export const isPersistFatal = (error: unknown) =>+ !!error && typeof error === 'object' && persistFatalErrors.has(error);++const getErrorType = (error: unknown): string | undefined => {+ if (!error || typeof error !== 'object') return;++ const value = (error as { errorType?: unknown; name?: unknown; type?: unknown }).errorType;+ if (typeof value === 'string' || typeof value === 'number') return String(value);++ const type = (error as { type?: unknown }).type;+ if (typeof type === 'string' || typeof type === 'number') return String(type);++ const name = error instanceof Error ? error.name : undefined;+ return name || undefined;+};++const getErrorMessage = (error: unknown): string => {+ if (error instanceof Error && error.message) return error.message;+ if (typeof error === 'string' && error) return error;+ if (error && typeof error === 'object') {+ const message = (error as { message?: unknown }).message;+ if (typeof message === 'string' && message) return message;+ }+ return 'Unknown error';+};++// Execution-entry denial is free; withholding an already executed result is not.+export const isBlockedBeforeExecution = (result: ToolRunResult) =>+ result.state?.type === 'blocked' && result.state.phase !== 'afterToolCall';++export const toolResultMetadata = (result: ToolRunResult) => ({+ toolExecutionTimeMs: result.executionTime ?? 0,+ toolResultStop: result.stop ?? false,+ toolResultSuccess: result.success,+ ...(result.workRegistration && { toolWorkRegistration: result.workRegistration }),+});++export const persistToolResultMetadata = async (+ host: AgentRuntimeHost,+ toolMessageId: string,+ result: ToolRunResult,+) => {+ try {+ await host.transports.messages.updateToolMessage(toolMessageId, {+ metadata: toolResultMetadata(result),+ });+ } catch (error) {+ await publishError(host, error, TOOL_MESSAGE_PERSIST_PHASE);+ throw markPersistFatal(error);+ }+};++export const publishError = async (host: AgentRuntimeHost, error: unknown, phase: string) => {+ const { stepIndex } = host.operation;++ if (host.transports.stream.publishError) {+ await host.transports.stream.publishError({ error, phase, stepIndex });+ return;+ }++ await host.transports.stream.publishEvent({+ data: {+ error: getErrorMessage(error),+ errorType: getErrorType(error),+ phase,+ },+ stepIndex,+ type: 'error',+ });+};++export const createToolMessage = async ({+ host,+ parentMessageId,+ result,+ resultBlocked,+ state,+ tool,+}: {+ host: AgentRuntimeHost;+ parentMessageId: string;+ result: ToolRunResult;+ resultBlocked?: boolean;+ state: AgentState;+ tool: ChatToolPayload;+}) => {+ try {+ const agentId = host.operation.agentId ?? state.origin?.agentId;+ if (!agentId) {+ throw new Error(+ `[call_tool] Missing agentId for tool message (op=${host.operation.operationId})`,+ );+ }++ return await host.transports.messages.createToolMessage({+ agentId,+ content: result.content,+ groupId: host.operation.groupId ?? state.origin?.groupId ?? undefined,+ metadata: toolResultMetadata(result),+ parentId: parentMessageId,+ plugin: tool as any,+ pluginError: result.error ?? null,+ ...((isBlockedBeforeExecution(result) || resultBlocked) && {+ pluginIntervention: { rejectedReason: result.state?.reason, status: 'rejected' },+ }),+ pluginState: result.state,+ role: 'tool',+ threadId: host.operation.threadId ?? state.origin?.threadId,+ tool_call_id: tool.id,+ topicId: host.operation.topicId ?? state.origin?.topicId,+ });+ } catch (error) {+ await publishError(host, error, TOOL_MESSAGE_PERSIST_PHASE);+ throw markPersistFatal(error);+ }+};++export const updateExistingToolMessage = async ({+ host,+ result,+ resultBlocked,+ toolMessageId,+}: {+ host: AgentRuntimeHost;+ result: ToolRunResult;+ resultBlocked?: boolean;+ toolMessageId: string;+}) => {+ try {+ await host.transports.messages.updateToolMessage(toolMessageId, {+ content: result.content,+ metadata: toolResultMetadata(result),+ pluginError: result.error ?? null,+ pluginState: result.state ?? {},+ replacePluginState: true,+ });+ if (isBlockedBeforeExecution(result) || resultBlocked) {+ await host.transports.messages.updateToolIntervention(toolMessageId, {+ rejectedReason: result.state?.reason,+ status: 'rejected',+ });+ }+ } catch (error) {+ await publishError(host, error, TOOL_MESSAGE_PERSIST_PHASE);+ throw markPersistFatal(error);+ }+};diff --git a/packages/agent-runtime/src/executors/toolReplay.ts b/packages/agent-runtime/src/executors/toolReplay.tsnew file mode 100644index 00000000000..6bd591ccbc1--- /dev/null+++ b/packages/agent-runtime/src/executors/toolReplay.ts@@ -0,0 +1,63 @@+import type { ChatToolPayload } from '@lobechat/types';++import type { AgentRuntimeHost, ToolRunExecution } from '../transport';++/** A redelivered step may lag behind its already committed tool result. */+export const resolveToolReplay = async ({+ existingToolMessageId,+ host,+ parentMessageId,+ tool,+}: {+ existingToolMessageId?: string;+ host: AgentRuntimeHost;+ parentMessageId: string;+ tool: ChatToolPayload;+}): Promise<{ execution?: ToolRunExecution; toolMessageId?: string }> => {+ const messages = host.transports.messages;+ const toolMessageId =+ existingToolMessageId ??+ (await messages.findToolMessageIdByToolCallId(tool.id, parentMessageId));+ if (!toolMessageId) return {};++ const message = await messages.getToolMessage(toolMessageId);+ // Do not turn an unreadable result into permission to repeat a side effect.+ if (!message || message.role !== 'tool' || message.tool_call_id !== tool.id) {+ throw new Error(`Cannot read tool result for ${toolMessageId}`);+ }++ const pending =+ message.pluginState?.status === 'pending' || message.pluginIntervention?.status === 'pending';+ const placeholder = !message.content || message.content === '...';+ if (+ pending ||+ (placeholder &&+ !message.pluginError &&+ typeof message.metadata?.toolExecutionTimeMs !== 'number')+ ) {+ return { toolMessageId };+ }++ return {+ execution: {+ attempts: 0,+ result: {+ content: message.content,+ error: message.pluginError,+ executionTime: message.metadata?.toolExecutionTimeMs ?? 0,+ state: message.pluginState,+ stop: message.metadata?.toolResultStop,+ workRegistration: message.metadata?.toolWorkRegistration,+ success:+ message.metadata?.toolResultSuccess ??+ (!message.pluginError &&+ message.pluginState?.type !== 'blocked' &&+ message.pluginIntervention?.status !== 'aborted' &&+ message.pluginIntervention?.status !== 'rejected'),+ },+ resultPersisted: true,+ toolMessageId,+ },+ toolMessageId,+ };+};diff --git a/packages/agent-runtime/src/transport/message.ts b/packages/agent-runtime/src/transport/message.tsindex a4d4ab83eea..df997f9de2b 100644--- a/packages/agent-runtime/src/transport/message.ts+++ b/packages/agent-runtime/src/transport/message.ts@@ -13,6 +13,20 @@ export interface RuntimeMessageRef {topicId?: string | null;}+/** Durable tool payload, including the fields that distinguish a result from a placeholder. */+export type RuntimeToolMessage = Pick<+ UIChatMessage,+ | 'id'+ | 'content'+ | 'parentId'+ | 'role'+ | 'tool_call_id'+ | 'metadata'+ | 'pluginState'+ | 'pluginError'+ | 'pluginIntervention'+>;+export interface CreateAssistantMessageOptions {/*** Stable key for one logical assistant output. Persistent transports should@@ -92,6 +106,8 @@ export interface MessageTransport {*/parentMessageId: string,) => Promise<string | undefined>;+ /** Read one tool row by primary key, without projecting away its stored result. */+ getToolMessage: (id: string) => Promise<RuntimeToolMessage | undefined>;query: (params?: QueryMessagesInput, options?: QueryMessagesOptions) => Promise<UIChatMessage[]>;update: (id: string, params: Partial<UpdateMessageParams>) => Promise<void>;updatePluginState: (id: string, state: Record<string, any>) => Promise<void>;diff --git a/packages/agent-runtime/src/utils/redactResultForEvents.ts b/packages/agent-runtime/src/utils/redactResultForEvents.tsindex da5d0f56ca8..fec20842926 100644--- a/packages/agent-runtime/src/utils/redactResultForEvents.ts+++ b/packages/agent-runtime/src/utils/redactResultForEvents.ts@@ -1,3 +1,5 @@+import type { UIChatMessage } from '@lobechat/types';+import type { ToolRunResult } from '../transport/tool';/** Trim raw skill payloads from event copies while preserving the result used for Work registration. */@@ -5,3 +7,23 @@ export const redactResultForEvents = (result: ToolRunResult): ToolRunResult =>result.workRegistration?.type === 'skill'? { ...result, workRegistration: { ...result.workRegistration, args: undefined, data: null } }: result;++/** Keep untruncated Work payloads in durable storage, outside runtime and UI message lists. */+export const omitToolWorkRegistration = (message: UIChatMessage): UIChatMessage => {+ let visible = message;+ if (message.metadata?.toolWorkRegistration) {+ const { toolWorkRegistration: _intent, ...metadata } = message.metadata;+ visible = { ...message, metadata };+ }+ if (!visible.columns && !visible.compressedMessages && !visible.members) return visible;+ return {+ ...visible,+ ...(visible.columns && {+ columns: visible.columns.map((column) => column.map(omitToolWorkRegistration)),+ }),+ ...(visible.compressedMessages && {+ compressedMessages: visible.compressedMessages.map(omitToolWorkRegistration),+ }),+ ...(visible.members && { members: visible.members.map(omitToolWorkRegistration) }),+ };+};diff --git a/packages/types/src/message/common/metadata.test.ts b/packages/types/src/message/common/metadata.test.tsindex 5cabb7f15ea..3aba09e0150 100644--- a/packages/types/src/message/common/metadata.test.ts+++ b/packages/types/src/message/common/metadata.test.ts@@ -9,6 +9,55 @@ import {} from './metadata';describe('MessageMetadataSchema', () => {+ it.each([+ { action: 'create', targets: [{ taskId: 'task-1' }], type: 'task' },+ {+ args: { title: 'one' },+ data: { body: 'untruncated' },+ provider: 'example',+ toolName: 'create',+ type: 'skill',+ },+ {+ action: 'register',+ document: { documentId: 'doc-1', changeType: 'created', toolName: 'createDocument' },+ type: 'document',+ },+ { action: 'delete', document: { documentId: 'doc-1' }, type: 'document' },+ {+ action: 'register',+ canvas: {+ canvasId: 'canvas-1',+ title: 'one',+ toolName: 'createCanvas',+ metadata: {+ entry: 'index.html',+ fileCount: 1,+ manifestKey: 'manifest',+ runtimeMajor: 1,+ totalSize: 10,+ },+ },+ type: 'canvas',+ },+ ])('preserves a complete durable $type Work registration intent', (intent) => {+ expect(MessageMetadataSchema.parse({ toolWorkRegistration: intent })).toEqual({+ toolWorkRegistration: intent,+ });+ });++ it('rejects malformed durable Work identities', () => {+ expect(+ MessageMetadataSchema.safeParse({+ toolWorkRegistration: {+ type: 'document',+ action: 'register',+ document: { documentId: 42 },+ },+ }).success,+ ).toBe(false);+ });+it('preserves the native Codex turn separately from message item provenance', () => {const metadata = {codexTurnId: 'turn-7',diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.tsindex c8e8214f092..5f2c4018ea1 100644--- a/packages/types/src/message/common/metadata.ts+++ b/packages/types/src/message/common/metadata.ts@@ -1,11 +1,68 @@import { z } from 'zod';import { RequestTrigger } from '../../agentRuntime';+import type { WorkRegistrationIntent } from '../../work';import type { ContextSelection } from './contextSelection';import { ContextSelectionSchema } from './contextSelection';import type { PageSelection } from './pageSelection';import { PageSelectionSchema } from './pageSelection';+const ToolWorkRegistrationSchema: z.ZodType<WorkRegistrationIntent> = z.union([+ z.object({+ action: z.enum(['create', 'update', 'delete']),+ changeType: z.enum(['created', 'updated']).optional(),+ targets: z.array(+ z.object({ taskId: z.string().optional(), taskIdentifier: z.string().optional() }),+ ),+ type: z.literal('task'),+ }),+ z.object({+ args: z.record(z.string(), z.unknown()).optional(),+ data: z.unknown(),+ provider: z.string(),+ toolName: z.string(),+ type: z.literal('skill'),+ }),+ z.object({+ action: z.literal('register'),+ document: z.object({+ agentDocumentId: z.string().nullish(),+ agentId: z.string().nullish(),+ description: z.string().nullish(),+ documentId: z.string(),+ changeType: z.enum(['created', 'updated']),+ toolName: z.string(),+ }),+ type: z.literal('document'),+ }),+ z.object({+ action: z.literal('delete'),+ document: z.object({+ agentDocumentId: z.string().nullish(),+ agentId: z.string().nullish(),+ documentId: z.string(),+ }),+ type: z.literal('document'),+ }),+ z.object({+ action: z.literal('register'),+ canvas: z.object({+ canvasId: z.string(),+ description: z.string().nullish(),+ title: z.string(),+ toolName: z.string(),+ metadata: z.object({+ entry: z.string(),+ fileCount: z.number(),+ manifestKey: z.string(),+ runtimeMajor: z.number(),+ totalSize: z.number(),+ }),+ }),+ type: z.literal('canvas'),+ }),+]);+const LocalSystemToolSnapshotSchema = z.object({apiName: z.enum(['readFile', 'listFiles', 'readLocalFile', 'listLocalFiles']),arguments: z.record(z.string(), z.unknown()),@@ -386,6 +443,9 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSche// conversation, and the run outcome. The card header + jump link read this.taskCallback: MessageTaskCallbackSchema.optional(),toolExecutionTimeMs: z.number().optional(),+ toolResultSuccess: z.boolean().optional(),+ toolResultStop: z.boolean().optional(),+ toolWorkRegistration: ToolWorkRegistrationSchema.optional(),trigger: z.nativeEnum(RequestTrigger).optional(),// role='verify' card: which Agent Run (agent_operations.id) it renders.verifyOperationId: z.string().optional(),@@ -690,6 +750,11 @@ export interface MessageMetadata {* Tool execution time for tool messages (ms)*/toolExecutionTimeMs?: number;+ toolResultStop?: boolean;+ /** Terminal tool-result flags retained for step redelivery. */+ toolResultSuccess?: boolean;+ /** Durable registration intent; omitted from runtime conversation contexts. */+ toolWorkRegistration?: WorkRegistrationIntent;/** @deprecated use the top-level message `usage` field instead */totalInputTokens?: number;/** @deprecated use the top-level message `usage` field instead */diff --git a/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-tool.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-tool.test.tsindex 4bdcf0fa441..9c350c04d0e 100644--- a/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-tool.test.ts+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-tool.test.ts@@ -510,13 +510,13 @@ describe('call_tool executor', () => {describe('Skip Create Tool Message Mode', () => {it('should reuse existing tool message when skipCreateToolMessage is true', async () => {- // Givenconst mockStore = createMockStore();const context = createTestContext();const assistantMessage = createAssistantMessage();const existingToolMessage = {id: 'msg_existing_tool',+ tool_call_id: 'approval-call',role: 'tool',content: '',pluginIntervention: { status: 'pending' },@@ -526,7 +526,7 @@ describe('call_tool executor', () => {mockStore.dbMessagesMap[context.messageKey] = [assistantMessage, existingToolMessage as any];const instruction = createCallToolInstruction(- {},+ { id: 'approval-call' },{skipCreateToolMessage: true,parentMessageId: 'msg_existing_tool',@@ -553,7 +553,6 @@ describe('call_tool executor', () => {});it('should still execute tool when skipping message creation', async () => {- // Givenconst mockStore = createMockStore({internal_invokeDifferentTypePlugin: vi.fn().mockResolvedValue({data: 'result',@@ -565,6 +564,7 @@ describe('call_tool executor', () => {const assistantMessage = createAssistantMessage();const existingToolMessage = {id: 'msg_tool_reuse',+ tool_call_id: 'tool_resume',role: 'tool',content: '',createdAt: Date.now(),diff --git a/src/store/chat/agents/transports/ClientMessageTransport.test.ts b/src/store/chat/agents/transports/ClientMessageTransport.test.tsindex f6ba604b7e6..a91c1324313 100644--- a/src/store/chat/agents/transports/ClientMessageTransport.test.ts+++ b/src/store/chat/agents/transports/ClientMessageTransport.test.ts@@ -39,6 +39,29 @@ describe('ClientMessageTransport', () => {vi.restoreAllMocks();});+ it('keeps raw Work intents available to replay but outside runtime conversation messages', async () => {+ const store = createStore();+ const intent = {+ type: 'skill' as const,+ provider: 'example',+ toolName: 'create',+ data: { body: 'raw payload' },+ };+ const row = {+ id: 'tool-1',+ role: 'tool',+ content: 'truncated',+ metadata: { operationId: 'op', toolWorkRegistration: intent },+ };+ store.dbMessagesMap['message-key'] = [row as any];+ const transport = new ClientMessageTransport(() => store, 'message-key', 'operation-1');+ expect((await transport.getToolMessage('tool-1'))?.metadata?.toolWorkRegistration).toEqual(+ intent,+ );+ expect((await transport.query())[0].metadata).toEqual({ operationId: 'op' });+ expect(row.metadata.toolWorkRegistration).toEqual(intent);+ });+describe('query', () => {const projectedRow = {content: '',@@ -53,6 +76,18 @@ describe('ClientMessageTransport', () => {return store;};+ it('refuses to treat an unavailable projected result as a pending tool', async () => {+ vi.spyOn(messageService, 'getToolResultPayloads').mockResolvedValue({});+ const transport = new ClientMessageTransport(+ () => storeWith([projectedRow]),+ 'message-key',+ 'operation-1',+ );+ await expect(transport.getToolMessage('tool-1')).rejects.toThrow(+ 'Cannot restore tool result',+ );+ });+it('refills a projected tool payload before the list becomes a context', async () => {const fetchPayloads = vi.spyOn(messageService, 'getToolResultPayloads')diff --git a/src/store/chat/agents/transports/ClientMessageTransport.ts b/src/store/chat/agents/transports/ClientMessageTransport.tsindex a128664e4e2..1fe72237908 100644--- a/src/store/chat/agents/transports/ClientMessageTransport.ts+++ b/src/store/chat/agents/transports/ClientMessageTransport.ts@@ -3,8 +3,10 @@ import type {QueryMessagesInput,QueryMessagesOptions,RuntimeMessageRef,+ RuntimeToolMessage,UpdateToolMessageInput,} from '@lobechat/agent-runtime';+import { omitToolWorkRegistration } from '@lobechat/agent-runtime';import type {ChatMessagePluginError,CreateMessageParams,@@ -82,11 +84,20 @@ export class ClientMessageTransport implements MessageTransport {return undefined;}+ async getToolMessage(id: string): Promise<RuntimeToolMessage | undefined> {+ const messages = await this.withStoredToolPayloads(this.getMessages());+ const message = messages.find((message) => message.id === id && message.role === 'tool');+ if (message?.payloadOmitted && !this.storedToolPayloads.has(id)) {+ throw new Error(`Cannot restore tool result for ${id}`);+ }+ return message;+ }+async query(_params?: QueryMessagesInput,_options?: QueryMessagesOptions,): Promise<UIChatMessage[]> {- return this.withStoredToolPayloads(this.getMessages());+ return (await this.withStoredToolPayloads(this.getMessages())).map(omitToolWorkRegistration);}async update(id: string, params: Partial<UpdateMessageParams>): Promise<void> {diff --git a/src/store/chat/agents/transports/ClientToolTransport.test.ts b/src/store/chat/agents/transports/ClientToolTransport.test.tsindex 4452e820538..f3d8a04dd06 100644--- a/src/store/chat/agents/transports/ClientToolTransport.test.ts+++ b/src/store/chat/agents/transports/ClientToolTransport.test.ts@@ -20,74 +20,84 @@ beforeEach(() => {});describe('ClientToolTransport', () => {- it('preserves an explicit unsuccessful tool result without an error', async () => {- const completeOperation = vi.fn();- const failOperation = vi.fn();- let operationIndex = 0;- const store = {- completeOperation,- dbMessagesMap: {- 'message-key': [{ id: 'assistant-message', parentId: 'user-message', role: 'assistant' }],- },- failOperation,- internal_invokeDifferentTypePlugin: vi.fn().mockResolvedValue({- content: 'Tool reported a handled failure',- success: false,- }),- onOperationCancel: vi.fn(),- operations: {- 'root-operation': {- context: { agentId: 'agent-1', messageId: 'assistant-message' },+ it.each([false, true])(+ 'preserves an unsuccessful result when reusing a placeholder: %s',+ async (reuseExistingMessage) => {+ const completeOperation = vi.fn();+ const failOperation = vi.fn();+ let operationIndex = 0;+ const store = {+ completeOperation,+ dbMessagesMap: {+ 'message-key': [{ id: 'assistant-message', parentId: 'user-message', role: 'assistant' }],},- },- optimisticCreateMessage: vi.fn().mockResolvedValue({ id: 'tool-message' }),- startOperation: vi.fn(() => ({ operationId: `child-operation-${++operationIndex}` })),- updateOperationMetadata: vi.fn(),- } as unknown as ChatStore;- const createToolMessageForOperation = vi.fn().mockResolvedValue({ id: 'tool-message' });- const messages = { createToolMessageForOperation } as unknown as ClientMessageTransport;- const transport = new ClientToolTransport(- () => store,- 'message-key',- 'root-operation',- messages,- );- const call: ChatToolPayload = {- apiName: 'run',- arguments: '{}',- id: 'tool-call',- identifier: 'client-tool',- type: 'default',- };- const context = {- callIndex: 1,- effectiveManifestMap: {},- mode: 'single',- operationId: 'root-operation',- parentMessageId: 'assistant-message',- parsedArgs: {},- state: {},- stepIndex: 0,- toolName: 'client-tool/run',- } as ToolRunContext;+ failOperation,+ internal_invokeDifferentTypePlugin: vi.fn().mockResolvedValue({+ content: 'Tool reported a handled failure',+ success: false,+ }),+ onOperationCancel: vi.fn(),+ operations: {+ 'root-operation': {+ context: { agentId: 'agent-1', messageId: 'assistant-message' },+ },+ },+ optimisticCreateMessage: vi.fn().mockResolvedValue({ id: 'tool-message' }),+ startOperation: vi.fn(() => ({ operationId: `child-operation-${++operationIndex}` })),+ updateOperationMetadata: vi.fn(),+ } as unknown as ChatStore;+ const createToolMessageForOperation = vi.fn().mockResolvedValue({ id: 'tool-message' });+ const messages = { createToolMessageForOperation } as unknown as ClientMessageTransport;+ const transport = new ClientToolTransport(+ () => store,+ 'message-key',+ 'root-operation',+ messages,+ );+ const call: ChatToolPayload = {+ apiName: 'run',+ arguments: '{}',+ id: 'tool-call',+ identifier: 'client-tool',+ type: 'default',+ };+ const context = {+ callIndex: 1,+ effectiveManifestMap: {},+ mode: 'single',+ operationId: 'root-operation',+ parentMessageId: 'assistant-message',+ parsedArgs: {},+ reuseExistingMessage,+ toolMessageId: reuseExistingMessage ? 'tool-message' : undefined,+ state: {},+ stepIndex: 0,+ toolName: 'client-tool/run',+ } as ToolRunContext;- const execution = await transport.run(call, context);+ const execution = await transport.run(call, context);- expect(execution.result).toMatchObject({- content: 'Tool reported a handled failure',- success: false,- });- expect(failOperation).toHaveBeenCalledWith('child-operation-1', {- message: 'Tool execution failed',- type: 'ToolExecutionError',- });- expect(completeOperation).not.toHaveBeenCalledWith('child-operation-1');- expect(createToolMessageForOperation).toHaveBeenCalledWith(- expect.objectContaining({ role: 'tool', tool_call_id: 'tool-call' }),- 'child-operation-2',- );- expect(store.optimisticCreateMessage).not.toHaveBeenCalled();- });+ expect(execution.result).toMatchObject({+ content: 'Tool reported a handled failure',+ success: false,+ });+ expect(failOperation).toHaveBeenCalledWith('child-operation-1', {+ message: 'Tool execution failed',+ type: 'ToolExecutionError',+ });+ expect(completeOperation).not.toHaveBeenCalledWith('child-operation-1');+ if (reuseExistingMessage) {+ expect(createToolMessageForOperation).not.toHaveBeenCalled();+ expect(execution.toolMessageId).toBe('tool-message');+ } else {+ expect(createToolMessageForOperation).toHaveBeenCalledWith(+ expect.objectContaining({ role: 'tool', tool_call_id: 'tool-call' }),+ 'child-operation-2',+ );+ }+ expect(store.optimisticCreateMessage).not.toHaveBeenCalled();+ },+ );it('always drains the stashed Work intent even when the tool invoke throws', async () => {const failOperation = vi.fn();diff --git a/src/store/chat/agents/transports/ClientToolTransport.ts b/src/store/chat/agents/transports/ClientToolTransport.tsindex 364b4cc68f7..fde2605b515 100644--- a/src/store/chat/agents/transports/ClientToolTransport.ts+++ b/src/store/chat/agents/transports/ClientToolTransport.ts@@ -45,7 +45,9 @@ export class ClientToolTransport implements ToolTransport {const opContext = rootOperation.context;const messages = store.dbMessagesMap[this.messageKey] ?? [];const existingToolMessage = context.reuseExistingMessage- ? messages.find((message) => message.id === context.parentMessageId)+ ? messages.find(+ (message) => message.id === (context.toolMessageId ?? context.parentMessageId),+ ): undefined;const assistantMessage =messages.find(@@ -94,7 +96,7 @@ export class ClientToolTransport implements ToolTransport {try {const toolMessageId = context.reuseExistingMessage- ? context.parentMessageId+ ? (context.toolMessageId ?? context.parentMessageId): await this.createToolMessage({assistantGroupId: assistantMessage?.groupId ?? undefined,call,