π€― 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): fetch tool plugin from message_plugins for resumeApproval (#13852)
Arvin Xu986bd2f7eceb
diff --git a/packages/database/src/models/__tests__/messages/message.update.test.ts b/packages/database/src/models/__tests__/messages/message.update.test.tsindex 6e8895932a0..48b2cb8d041 100644--- a/packages/database/src/models/__tests__/messages/message.update.test.ts+++ b/packages/database/src/models/__tests__/messages/message.update.test.ts@@ -495,6 +495,42 @@ describe('MessageModel Update Tests', () => {});});+ describe('findMessagePlugin', () => {+ it('should return the plugin row (identifier / apiName / toolCallId / ...) for a tool message', async () => {+ await serverDB.insert(messages).values({ id: '1', role: 'tool', content: '', userId });+ await serverDB.insert(messagePlugins).values([+ {+ id: '1',+ apiName: 'runCommand',+ arguments: '{"command":"echo"}',+ identifier: 'lobe-local-system',+ toolCallId: 'call_abc',+ type: 'builtin',+ userId,+ },+ ]);++ const plugin = await messageModel.findMessagePlugin('1');++ expect(plugin).toEqual(+ expect.objectContaining({+ apiName: 'runCommand',+ arguments: '{"command":"echo"}',+ id: '1',+ identifier: 'lobe-local-system',+ toolCallId: 'call_abc',+ type: 'builtin',+ }),+ );+ });++ it('should return undefined when no plugin row exists for the given id', async () => {+ const plugin = await messageModel.findMessagePlugin('non-existent-id');++ expect(plugin).toBeUndefined();+ });+ });+describe('updateToolMessage', () => {it('should update content only', async () => {await serverDB.insert(messages).values({diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex f91e6bc2398..12c1bf805f4 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -1425,6 +1425,37 @@ export class MessageModel {return this.db.update(messagePlugins).set(value).where(eq(messagePlugins.id, id));};+ /**+ * Fetch the `message_plugins` row associated with a tool message. Tool-call+ * metadata (identifier / apiName / arguments / type / toolCallId /+ * intervention) lives on this row, not on the `messages` row returned by+ * {@link findById}.+ *+ * Returns `undefined` when the message has no plugin row. Normalizes the+ * DB row (nullable columns) into the optional-field shape of+ * {@link MessagePluginItem} so callers don't need to juggle `null` vs+ * `undefined`.+ */+ findMessagePlugin = async (messageId: string): Promise<MessagePluginItem | undefined> => {+ const row = await this.db.query.messagePlugins.findFirst({+ where: eq(messagePlugins.id, messageId),+ });+ if (!row) return undefined;+ return {+ apiName: row.apiName ?? undefined,+ arguments: row.arguments ?? undefined,+ clientId: row.clientId ?? undefined,+ error: row.error ?? undefined,+ id: row.id,+ identifier: row.identifier ?? undefined,+ intervention: row.intervention ?? undefined,+ state: row.state ?? undefined,+ toolCallId: row.toolCallId ?? undefined,+ type: row.type ?? 'default',+ userId: row.userId,+ };+ };+/*** Update tool message with content, metadata, pluginState, and pluginError in a single transaction* This prevents race conditions when updating multiple fieldsdiff --git a/src/server/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/src/server/services/aiAgent/__tests__/execAgent.resumeApproval.test.tsindex a5e8978fa50..abca4e2db39 100644--- a/src/server/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts@@ -1,3 +1,4 @@+import type { LobeChatDatabase } from '@lobechat/database';import type * as ModelBankModule from 'model-bank';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -6,6 +7,7 @@ import { AiAgentService } from '../index';const {mockCreateOperation,mockFindById,+ mockFindMessagePlugin,mockMessageCreate,mockMessageQuery,mockUpdateMessagePlugin,@@ -13,6 +15,7 @@ const {} = vi.hoisted(() => ({mockCreateOperation: vi.fn(),mockFindById: vi.fn(),+ mockFindMessagePlugin: vi.fn(),mockMessageCreate: vi.fn(),mockMessageQuery: vi.fn(),mockUpdateMessagePlugin: vi.fn(),@@ -29,6 +32,7 @@ vi.mock('@/database/models/message', () => ({MessageModel: vi.fn().mockImplementation(() => ({create: mockMessageCreate,findById: mockFindById,+ findMessagePlugin: mockFindMessagePlugin,query: mockMessageQuery,update: vi.fn().mockResolvedValue({}),updateMessagePlugin: mockUpdateMessagePlugin,@@ -135,20 +139,23 @@ vi.mock('model-bank', async (importOriginal) => {describe('AiAgentService.execAgent - resumeApproval', () => {let service: AiAgentService;+ // `messages` row β `findById` returns this. Note plugin metadata (apiName,+ // identifier, etc.) lives in a separate `message_plugins` table.const pendingToolMessage = {id: 'tool-msg-1',- plugin: {- apiName: 'runCommand',- arguments: '{"command":"echo"}',- identifier: 'lobe-local-system',- type: 'builtin',- },role: 'tool',sessionId: 'session-1',threadId: 'thread-1',- tool_call_id: 'call_xyz',topicId: 'topic-1',};+ // `message_plugins` row β fetched via `db.query.messagePlugins.findFirst`.+ const pendingToolPlugin = {+ apiName: 'runCommand',+ arguments: '{"command":"echo"}',+ identifier: 'lobe-local-system',+ toolCallId: 'call_xyz',+ type: 'builtin',+ };beforeEach(() => {vi.clearAllMocks();@@ -159,11 +166,15 @@ describe('AiAgentService.execAgent - resumeApproval', () => {success: true,});mockFindById.mockResolvedValue(pendingToolMessage);+ mockFindMessagePlugin.mockResolvedValue(pendingToolPlugin);mockMessageQuery.mockResolvedValue([{ content: 'hi', id: 'history-1', role: 'user' }]);mockMessageCreate.mockResolvedValue({ id: 'assistant-msg-new' });mockUpdateMessagePlugin.mockResolvedValue(undefined);mockUpdateToolMessage.mockResolvedValue(undefined);- service = new AiAgentService({} as any, 'user-1');+ // `MessageModel` is fully mocked above, so the service never touches the+ // raw `db` arg β cast an empty stub through `unknown` to satisfy the+ // `LobeChatDatabase` parameter type without dragging the real schema.+ service = new AiAgentService({} as unknown as LobeChatDatabase, 'user-1');});const baseParams = {@@ -284,7 +295,10 @@ describe('AiAgentService.execAgent - resumeApproval', () => {});it('throws when the stored tool_call_id does not match the resume request', async () => {- mockFindById.mockResolvedValue({ ...pendingToolMessage, tool_call_id: 'call_other' });+ // toolCallId lives on the plugin row β mutate the plugin mock, not the+ // message. This is exactly the class of bug that the separate-table+ // fetch guards against.+ mockFindMessagePlugin.mockResolvedValue({ ...pendingToolPlugin, toolCallId: 'call_other' });await expect(service.execAgent({@@ -297,5 +311,20 @@ describe('AiAgentService.execAgent - resumeApproval', () => {}),).rejects.toThrow(/toolCallId mismatch/);});++ it('throws when no plugin row exists for the target message', async () => {+ mockFindMessagePlugin.mockResolvedValue(undefined);++ await expect(+ service.execAgent({+ ...baseParams,+ resumeApproval: {+ decision: 'approved',+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_xyz',+ },+ }),+ ).rejects.toThrow(/no plugin row/);+ });});});diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 01f8807d2de..e25a4254935 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -28,6 +28,7 @@ import type {ExecGroupAgentResult,ExecSubAgentTaskParams,ExecSubAgentTaskResult,+ MessagePluginItem,UserInterventionConfig,} from '@lobechat/types';import { ThreadStatus, ThreadType } from '@lobechat/types';@@ -413,6 +414,13 @@ export class AiAgentService {// state both reflect the decision before the first step runs. Validates// the parent is actually a pending tool message tied to the tool call we// were asked about β guards against stale / double-clicks.+ //+ // Note: `messages` and `message_plugins` live in separate tables. The+ // `messageModel.findById` query returns the `messages` row only β the+ // tool_call_id / apiName / identifier / arguments / type fields live on+ // the plugin row and must be fetched separately.+ let resumeApprovalPlugin: MessagePluginItem | undefined;+if (resumeApproval) {if (!resumeParentMessage) {throw new Error('resumeApproval requires parentMessageId to point at a tool message');@@ -422,11 +430,22 @@ export class AiAgentService {`resumeApproval.parentMessageId must point at a role='tool' message, got role='${resumeParentMessage.role}'`,);}- const existingToolCallId = (resumeParentMessage as any).tool_call_id;- if (existingToolCallId && existingToolCallId !== resumeApproval.toolCallId) {++ resumeApprovalPlugin = await this.messageModel.findMessagePlugin(+ resumeApproval.parentMessageId,+ );+ if (!resumeApprovalPlugin) {+ throw new Error(+ `resumeApproval: no plugin row for tool message ${resumeApproval.parentMessageId}`,+ );+ }+ if (+ resumeApprovalPlugin.toolCallId &&+ resumeApprovalPlugin.toolCallId !== resumeApproval.toolCallId+ ) {throw new Error(`resumeApproval.toolCallId mismatch for message ${resumeApproval.parentMessageId}: ` +- `stored=${existingToolCallId}, requested=${resumeApproval.toolCallId}`,+ `stored=${resumeApprovalPlugin.toolCallId}, requested=${resumeApproval.toolCallId}`,);}@@ -1311,23 +1330,22 @@ export class AiAgentService {// decision is persisted, there's nothing meaningful to do differently// server-side, and letting the LLM produce a brief acknowledgement keeps// the conversation cleanly terminated either way.- if (resumeApproval && resumeParentMessage) {+ if (resumeApproval && resumeApprovalPlugin) {if (resumeApproval.decision === 'approved') {// Ask the runtime to execute the approved tool directly. Matches the// `phase: 'human_approved_tool'` contract used by the in-place// handleHumanIntervention flow β the runner generates a `call_tool`- // instruction keyed on this payload.- const toolPlugin = (resumeParentMessage as any).plugin as- | { apiName?: string; arguments?: string; identifier?: string; type?: string }- | undefined;+ // instruction keyed on this payload. All tool metadata comes from+ // the plugin row fetched above; missing any of identifier/apiName+ // breaks the server-side tool executor dispatch.initialContext = {payload: {approvedToolCall: {- apiName: toolPlugin?.apiName,- arguments: toolPlugin?.arguments,+ apiName: resumeApprovalPlugin.apiName,+ arguments: resumeApprovalPlugin.arguments,id: resumeApproval.toolCallId,- identifier: toolPlugin?.identifier,- type: toolPlugin?.type ?? 'default',+ identifier: resumeApprovalPlugin.identifier,+ type: resumeApprovalPlugin.type ?? 'default',},assistantMessageId: assistantMessageRecord.id,parentMessageId: resumeApproval.parentMessageId,