π€― 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): honor per-tool timeout end-to-end for client tool dispatch (#14817)
Arvin Xu43b0b5e854c7
diff --git a/packages/builtin-tool-local-system/src/manifest.ts b/packages/builtin-tool-local-system/src/manifest.tsindex cddc93cbe92..b69ec38e435 100644--- a/packages/builtin-tool-local-system/src/manifest.ts+++ b/packages/builtin-tool-local-system/src/manifest.ts@@ -7,6 +7,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {executors: ['client', 'server'],api: [{+ defaultTimeoutMs: 30_000,description:'List files and folders in a specified directory. Input should be a path. Output is a JSON array of file/folder names.',humanIntervention: {@@ -46,6 +47,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},},{+ defaultTimeoutMs: 30_000,description:'Read the content of a text or document file (txt/md/json/source code/pdf/docx/etc.). Binary files (.bin/.exe/.zip/.b64/encoded blobs) are rejected with a structured error β use runCommand with file/hexdump/strings to inspect those instead. Output is capped at 500K chars total and 8K chars per line; for larger files, use a narrower line range or grepContent.',humanIntervention: {@@ -76,6 +78,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},},{+ defaultTimeoutMs: 60_000,description:'Search for files within the workspace based on a query string and optional filter options. Input should include the search query and any filter options. Output is a JSON array of matching file paths.',humanIntervention: {@@ -160,6 +163,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},},{+ defaultTimeoutMs: 60_000,description:'Moves or renames multiple files/directories. Input is an array of objects, each containing an oldPath and a newPath.',humanIntervention: {@@ -197,6 +201,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},},{+ defaultTimeoutMs: 30_000,description:'Write content to a specific file. Input should be the file path and content. Overwrites existing file or creates a new one.',humanIntervention: {@@ -223,6 +228,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},},{+ defaultTimeoutMs: 30_000,description:'Perform exact string replacements in files. Must read the file first before editing.',humanIntervention: {@@ -257,6 +263,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},},{+ defaultTimeoutMs: 120_000,description:'Execute a shell command and return its output. Supports both synchronous and background execution with timeout control.',humanIntervention: 'required',@@ -283,7 +290,8 @@ export const LocalSystemManifest: BuiltinToolManifest = {type: 'boolean',},timeout: {- description: 'Timeout in milliseconds (default: 120000ms, max: 600000ms)',+ description:+ 'Timeout in milliseconds for this command. Default 120000ms. Server clamps to [1000, 800000]; raise this for long-running tasks (builds, large searches) instead of letting them hit the default and fail.',type: 'number',},},@@ -292,6 +300,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},},{+ defaultTimeoutMs: 30_000,description:'Retrieve output from a running or completed background shell command. Returns only new output since the last check.',name: LocalSystemApiName.getCommandOutput,@@ -312,6 +321,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},},{+ defaultTimeoutMs: 10_000,description: 'Kill a running background shell command by its ID.',name: LocalSystemApiName.killCommand,parameters: {@@ -326,6 +336,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},},{+ defaultTimeoutMs: 60_000,description:'Search for content within files using regex patterns. Supports various output modes and filtering options.',humanIntervention: {@@ -398,6 +409,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},},{+ defaultTimeoutMs: 60_000,description:'Find files matching glob patterns. Supports standard glob syntax like "**/*.js" or "src/**/*.ts".',humanIntervention: {diff --git a/packages/context-engine/src/engine/tools/types.ts b/packages/context-engine/src/engine/tools/types.tsindex 4531843e5be..52407f2cea6 100644--- a/packages/context-engine/src/engine/tools/types.ts+++ b/packages/context-engine/src/engine/tools/types.ts@@ -1,6 +1,12 @@import type { ExtendedHumanInterventionConfig } from '@/types/index';export interface LobeChatPluginApi {+ /**+ * Default execution timeout in milliseconds for this API.+ * Falls back to the global default (120_000 ms) when omitted.+ * The resolver reads this when the LLM does not supply `arguments.timeout`.+ */+ defaultTimeoutMs?: number;description: string;/*** Human intervention configurationdiff --git a/packages/local-file-shell/src/shell/runner.ts b/packages/local-file-shell/src/shell/runner.tsindex 29c24eb52bc..de559fe5222 100644--- a/packages/local-file-shell/src/shell/runner.ts+++ b/packages/local-file-shell/src/shell/runner.ts@@ -32,7 +32,7 @@ export async function runCommand(const logPrefix = `[runCommand: ${description || command.slice(0, 50)}]`;logger?.debug(`${logPrefix} Starting`, { background: run_in_background, cwd, timeout });- const effectiveTimeout = Math.min(Math.max(timeout, 1000), 600_000);+ const effectiveTimeout = Math.min(Math.max(timeout, 1000), 800_000);const shellConfig = getShellConfig(command);const childEnv = extraEnv ? { ...process.env, ...extraEnv } : process.env;diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex 448f49fd654..99e27b2fa78 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -134,6 +134,17 @@ export const ExtendedHumanInterventionConfigSchema = z.union([]);export interface LobeChatPluginApi {+ /**+ * Default execution timeout in milliseconds for this API.+ *+ * Used as the fallback when the LLM does not supply `arguments.timeout`.+ * Falls back to the global default (120_000 ms) if not set.+ *+ * The resolved value (clamped to `[1_000, 800_000]` server-side) drives+ * both `dispatchClientTool` BLPOP deadline and the renderer's race+ * deadline, keeping server and client aligned on a single budget.+ */+ defaultTimeoutMs?: number;description: string;/*** Human intervention configuration@@ -166,6 +177,7 @@ export interface LobeChatPluginApi {}export const LobeChatPluginApiSchema = z.object({+ defaultTimeoutMs: z.number().int().positive().optional(),description: z.string(),humanIntervention: ExtendedHumanInterventionConfigSchema.optional(),name: z.string(),diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex feae2b82df3..23839649ef9 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -65,6 +65,7 @@ import {isPersistFatal,markPersistFatal,} from './messagePersistErrors';+import { resolveToolTimeoutMs } from './resolveToolTimeout';import { type IStreamEventManager } from './types';const log = debug('lobe-server:agent-runtime:streaming-executors');@@ -1633,9 +1634,15 @@ export const createRuntimeExecutors = (};} else if (canDispatchToClient) {log(`[${operationLogId}] Dispatching tool ${toolName} to client via Agent Gateway`);+ const timeoutMs = resolveToolTimeoutMs({+ apiName: chatToolPayload.apiName,+ args: parsedArgs,+ manifest: effectiveManifestMap[chatToolPayload.identifier],+ });const dispatchResult = await dispatchClientTool(chatToolPayload, {operationId,streamManager,+ timeoutMs,});execution = { attempts: 1, result: dispatchResult };} else {@@ -2088,9 +2095,15 @@ export const createRuntimeExecutors = (};} else if (canDispatchToClient) {log(`[${operationLogId}] Dispatching tool ${toolName} to client via Agent Gateway`);+ const timeoutMs = resolveToolTimeoutMs({+ apiName: chatToolPayload.apiName,+ args: batchParsedArgs,+ manifest: batchManifestMap[chatToolPayload.identifier],+ });const dispatchResult = await dispatchClientTool(chatToolPayload, {operationId,streamManager,+ timeoutMs,});execution = { attempts: 1, result: dispatchResult };} else {diff --git a/src/server/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts b/src/server/modules/AgentRuntime/__tests__/dispatchClientTool.test.tsindex 5d4882421d6..0261fffec5b 100644--- a/src/server/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/dispatchClientTool.test.ts@@ -181,4 +181,60 @@ describe('dispatchClientTool', () => {expect(result.error?.message).toBe('gateway down');expect(mockDisconnect).toHaveBeenCalled();});++ it('forwards the caller-provided timeoutMs to both sendToolExecute and waitForResult', async () => {+ const sendToolExecute = vi.fn().mockResolvedValue(undefined);+ const streamManager = makeStreamManager(sendToolExecute);++ mockBlpop.mockResolvedValue([+ 'tool_result:call-1',+ JSON.stringify({ content: 'ok', success: true, toolCallId: 'call-1' }),+ ]);++ await dispatchClientTool(makePayload(), {+ operationId: 'op-1',+ streamManager,+ timeoutMs: 240_000,+ });++ expect(sendToolExecute.mock.calls[0][1]).toMatchObject({ executionTimeoutMs: 240_000 });+ // BLPOP signature: (key1, ..., timeoutSeconds). 240_000ms β 240s.+ const blpopArgs = mockBlpop.mock.calls[0];+ expect(blpopArgs.at(-1)).toBe(240);+ });++ it('clamps caller-supplied timeoutMs above the MAX_TIMEOUT_MS ceiling', async () => {+ const sendToolExecute = vi.fn().mockResolvedValue(undefined);+ const streamManager = makeStreamManager(sendToolExecute);++ mockBlpop.mockResolvedValue([+ 'tool_result:call-1',+ JSON.stringify({ content: 'ok', success: true, toolCallId: 'call-1' }),+ ]);++ await dispatchClientTool(makePayload(), {+ operationId: 'op-1',+ streamManager,+ timeoutMs: 10_000_000,+ });++ expect(sendToolExecute.mock.calls[0][1]).toMatchObject({ executionTimeoutMs: 800_000 });+ });++ it('falls back to the 120s global default when ctx.timeoutMs is omitted', async () => {+ const sendToolExecute = vi.fn().mockResolvedValue(undefined);+ const streamManager = makeStreamManager(sendToolExecute);++ mockBlpop.mockResolvedValue([+ 'tool_result:call-1',+ JSON.stringify({ content: 'ok', success: true, toolCallId: 'call-1' }),+ ]);++ await dispatchClientTool(makePayload(), {+ operationId: 'op-1',+ streamManager,+ });++ expect(sendToolExecute.mock.calls[0][1]).toMatchObject({ executionTimeoutMs: 120_000 });+ });});diff --git a/src/server/modules/AgentRuntime/__tests__/resolveToolTimeout.test.ts b/src/server/modules/AgentRuntime/__tests__/resolveToolTimeout.test.tsnew file mode 100644index 00000000000..ece4a7f3ab2--- /dev/null+++ b/src/server/modules/AgentRuntime/__tests__/resolveToolTimeout.test.ts@@ -0,0 +1,122 @@+import { type LobeToolManifest } from '@lobechat/context-engine';+import { describe, expect, it } from 'vitest';++import {+ GLOBAL_DEFAULT_TIMEOUT_MS,+ MAX_TIMEOUT_MS,+ MIN_TIMEOUT_MS,+ resolveToolTimeoutMs,+} from '../resolveToolTimeout';++const makeManifest = (api: LobeToolManifest['api']): LobeToolManifest => ({+ api,+ identifier: 'lobe-local-system',+ meta: {},+});++describe('resolveToolTimeoutMs', () => {+ it('uses LLM-supplied args.timeout when present (highest priority)', () => {+ const manifest = makeManifest([+ { defaultTimeoutMs: 30_000, description: '', name: 'runCommand', parameters: {} },+ ]);+ expect(+ resolveToolTimeoutMs({ apiName: 'runCommand', args: { timeout: 240_000 }, manifest }),+ ).toBe(240_000);+ });++ it('falls back to manifest defaultTimeoutMs when args.timeout absent', () => {+ const manifest = makeManifest([+ { defaultTimeoutMs: 30_000, description: '', name: 'readFile', parameters: {} },+ ]);+ expect(resolveToolTimeoutMs({ apiName: 'readFile', args: {}, manifest })).toBe(30_000);+ });++ it('falls back to global default when neither args nor manifest specify', () => {+ const manifest = makeManifest([{ description: '', name: 'runCommand', parameters: {} }]);+ expect(resolveToolTimeoutMs({ apiName: 'runCommand', args: {}, manifest })).toBe(+ GLOBAL_DEFAULT_TIMEOUT_MS,+ );+ });++ it('falls back to global default when manifest is missing entirely', () => {+ expect(resolveToolTimeoutMs({ apiName: 'runCommand', args: undefined })).toBe(+ GLOBAL_DEFAULT_TIMEOUT_MS,+ );+ });++ it('clamps values above MAX_TIMEOUT_MS down to the cap', () => {+ expect(resolveToolTimeoutMs({ apiName: 'runCommand', args: { timeout: 10_000_000 } })).toBe(+ MAX_TIMEOUT_MS,+ );+ });++ it('clamps values below MIN_TIMEOUT_MS up to the floor', () => {+ expect(resolveToolTimeoutMs({ apiName: 'runCommand', args: { timeout: 1 } })).toBe(+ MIN_TIMEOUT_MS,+ );+ });++ it('ignores non-numeric args.timeout and falls through to next source', () => {+ const manifest = makeManifest([+ { defaultTimeoutMs: 45_000, description: '', name: 'runCommand', parameters: {} },+ ]);+ expect(+ resolveToolTimeoutMs({+ apiName: 'runCommand',+ // String value at runtime β defensive, the resolver should reject and fall through.+ args: { timeout: '240' } as unknown as Record<string, unknown>,+ manifest,+ }),+ ).toBe(45_000);+ });++ it('ignores zero / negative args.timeout and falls through', () => {+ const manifest = makeManifest([+ { defaultTimeoutMs: 45_000, description: '', name: 'runCommand', parameters: {} },+ ]);+ expect(resolveToolTimeoutMs({ apiName: 'runCommand', args: { timeout: 0 }, manifest })).toBe(+ 45_000,+ );+ expect(resolveToolTimeoutMs({ apiName: 'runCommand', args: { timeout: -1 }, manifest })).toBe(+ 45_000,+ );+ });++ it('ignores NaN/Infinity args.timeout and falls through', () => {+ const manifest = makeManifest([+ { defaultTimeoutMs: 45_000, description: '', name: 'runCommand', parameters: {} },+ ]);+ expect(+ resolveToolTimeoutMs({ apiName: 'runCommand', args: { timeout: Number.NaN }, manifest }),+ ).toBe(45_000);+ expect(+ resolveToolTimeoutMs({+ apiName: 'runCommand',+ args: { timeout: Number.POSITIVE_INFINITY },+ manifest,+ }),+ ).toBe(45_000);+ });++ it('ignores null/undefined args without crashing', () => {+ expect(resolveToolTimeoutMs({ apiName: 'runCommand', args: null })).toBe(+ GLOBAL_DEFAULT_TIMEOUT_MS,+ );+ expect(resolveToolTimeoutMs({ apiName: 'runCommand' })).toBe(GLOBAL_DEFAULT_TIMEOUT_MS);+ });++ it('matches the right API entry by name when manifest has multiple', () => {+ const manifest = makeManifest([+ { defaultTimeoutMs: 30_000, description: '', name: 'readFile', parameters: {} },+ { defaultTimeoutMs: 120_000, description: '', name: 'runCommand', parameters: {} },+ { defaultTimeoutMs: 60_000, description: '', name: 'grepContent', parameters: {} },+ ]);+ expect(resolveToolTimeoutMs({ apiName: 'grepContent', args: {}, manifest })).toBe(60_000);+ });++ it('truncates fractional values before clamping', () => {+ expect(resolveToolTimeoutMs({ apiName: 'runCommand', args: { timeout: 123_456.789 } })).toBe(+ 123_456,+ );+ });+});diff --git a/src/server/modules/AgentRuntime/dispatchClientTool.ts b/src/server/modules/AgentRuntime/dispatchClientTool.tsindex 8602f214986..65724e905f7 100644--- a/src/server/modules/AgentRuntime/dispatchClientTool.ts+++ b/src/server/modules/AgentRuntime/dispatchClientTool.ts@@ -4,31 +4,28 @@ import debug from 'debug';import type { ToolExecutionResultResponse } from '@/server/services/toolExecution/types';import { getAgentRuntimeRedisClient } from './redis';+import { GLOBAL_DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS, MIN_TIMEOUT_MS } from './resolveToolTimeout';import type { ToolResultPayload } from './ToolResultWaiter';import { ToolResultWaiter } from './ToolResultWaiter';import type { IStreamEventManager } from './types';const log = debug('lobe-server:agent-runtime:dispatch-client-tool');-/**- * Default per-tool execution budget when the payload doesn't carry one.- */-const DEFAULT_EXECUTION_TIMEOUT_MS = 60_000;--/**- * Hard cap tied to a single Vercel serverless function window. Phase 6.3c- * relaxes this by persisting pending-tool state and resuming on a fresh- * invocation.- */-const MAX_EXECUTION_TIMEOUT_MS = 270_000;-interface DispatchContext {operationId: string;streamManager: IStreamEventManager;+ /**+ * Per-call execution budget in milliseconds, normally produced by+ * `resolveToolTimeoutMs`. When omitted, falls back to the global default+ * (`GLOBAL_DEFAULT_TIMEOUT_MS`). Always clamped to+ * `[MIN_TIMEOUT_MS, MAX_TIMEOUT_MS]` regardless of source β the client is+ * a suggester, this dispatcher is the arbiter.+ */+ timeoutMs?: number;}const clampTimeout = (value: number): number =>- Math.min(Math.max(value, 1_000), MAX_EXECUTION_TIMEOUT_MS);+ Math.min(Math.max(Math.trunc(value), MIN_TIMEOUT_MS), MAX_TIMEOUT_MS);const buildTimeoutResult = (executionTime: number): ToolExecutionResultResponse => ({content: '',@@ -88,7 +85,7 @@ export async function dispatchClientTool(const blockingClient = redis.duplicate();const waiter = new ToolResultWaiter(blockingClient, redis);- const timeoutMs = clampTimeout(DEFAULT_EXECUTION_TIMEOUT_MS);+ const timeoutMs = clampTimeout(ctx.timeoutMs ?? GLOBAL_DEFAULT_TIMEOUT_MS);try {log(diff --git a/src/server/modules/AgentRuntime/resolveToolTimeout.ts b/src/server/modules/AgentRuntime/resolveToolTimeout.tsnew file mode 100644index 00000000000..3ee9d4bea0e--- /dev/null+++ b/src/server/modules/AgentRuntime/resolveToolTimeout.ts@@ -0,0 +1,66 @@+import { type LobeToolManifest } from '@lobechat/context-engine';++/**+ * Global fallback when neither the LLM nor the tool manifest specifies a+ * timeout. Chosen to fit the common case (most tools complete in seconds)+ * while leaving room for short-running shell commands.+ */+export const GLOBAL_DEFAULT_TIMEOUT_MS = 120_000;++/**+ * Lower bound β anything shorter than this is almost certainly a misconfig.+ */+export const MIN_TIMEOUT_MS = 1_000;++/**+ * Hard ceiling enforced server-side regardless of what the LLM or manifest+ * asks for. Matches the cloud agent function window (800s) so a single+ * client-tool dispatch never outlives its containing run.+ */+export const MAX_TIMEOUT_MS = 800_000;++const clamp = (value: number): number =>+ Math.min(Math.max(Math.trunc(value), MIN_TIMEOUT_MS), MAX_TIMEOUT_MS);++const readPositiveNumber = (value: unknown): number | undefined => {+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return undefined;+ return value;+};++export interface ResolveToolTimeoutInput {+ apiName: string;+ /**+ * Tool arguments parsed from the LLM `tool_call.arguments` JSON. The+ * LLM-supplied `timeout` (in milliseconds, per the manifest contract)+ * takes top priority when present.+ */+ args?: Record<string, unknown> | null;+ /** Manifest for the tool being dispatched, looked up by identifier. */+ manifest?: LobeToolManifest;+}++/**+ * Decide the per-call execution timeout for a client-side tool dispatch.+ *+ * Priority (highest first):+ * 1. `args.timeout` β LLM-supplied per-call value (ms)+ * 2. `manifest.api[apiName].defaultTimeoutMs` β tool-author default (ms)+ * 3. `GLOBAL_DEFAULT_TIMEOUT_MS` (120_000)+ *+ * The result is always clamped to `[MIN_TIMEOUT_MS, MAX_TIMEOUT_MS]`. The+ * client is a *suggester*; this function is the sole *arbiter*.+ */+export const resolveToolTimeoutMs = ({+ apiName,+ args,+ manifest,+}: ResolveToolTimeoutInput): number => {+ const argTimeout = readPositiveNumber(args?.timeout);+ if (argTimeout !== undefined) return clamp(argTimeout);++ const manifestApi = manifest?.api?.find((a) => a.name === apiName);+ const manifestDefault = readPositiveNumber(manifestApi?.defaultTimeoutMs);+ if (manifestDefault !== undefined) return clamp(manifestDefault);++ return clamp(GLOBAL_DEFAULT_TIMEOUT_MS);+};diff --git a/src/store/chat/slices/aiChat/actions/__tests__/clientToolExecution.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/clientToolExecution.test.tsindex ae5f96add98..9604ce9913d 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/clientToolExecution.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/clientToolExecution.test.ts@@ -1,5 +1,5 @@import type { ToolExecuteData } from '@lobechat/agent-gateway-client';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { ClientToolExecutionActionImpl } from '../clientToolExecution';@@ -39,6 +39,7 @@ function setup(options: { hasConnection?: boolean; sendReturns?: boolean } = {})const { hasConnection = true, sendReturns = true } = options;const sendToolResult = vi.fn(() => sendReturns);+ const abort = vi.fn();const state: any = {gatewayConnections: hasConnection@@ -57,7 +58,7 @@ function setup(options: { hasConnection?: boolean; sendReturns?: boolean } = {}): {},operations: {'op-1': {- abortController: { signal: { aborted: false } },+ abortController: { abort, signal: { aborted: false } },context: {agentId: 'agent-1',documentId: 'documents-row-id',@@ -76,7 +77,7 @@ function setup(options: { hasConnection?: boolean; sendReturns?: boolean } = {})const get = vi.fn(() => state);const action = new ClientToolExecutionActionImpl(set, get);- return { action, sendToolResult, state, set, get };+ return { abort, action, sendToolResult, state, set, get };}beforeEach(() => {@@ -284,6 +285,133 @@ describe('internal_executeClientTool', () => {});});+ describe('execution timeout (Bug 2)', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('sends a client_executor_timeout failure when the executor exceeds the deadline', async () => {+ hasExecutorMock.mockReturnValue(true);+ // Executor never resolves β only the race timeout can wake the action.+ invokeExecutorMock.mockReturnValue(new Promise(() => {}));+ const { action, sendToolResult, abort } = setup();++ const promise = action.internal_executeClientTool(makeData({ executionTimeoutMs: 2_000 }), {+ operationId: 'op-1',+ });++ // Fast-forward to the safety-buffered deadline (2_000 - 500 = 1_500ms).+ await vi.advanceTimersByTimeAsync(1_500);+ await promise;++ expect(abort).toHaveBeenCalledTimes(1);+ // Error message surfaces the budget so the LLM can adjust on retry.+ expect(sendToolResult).toHaveBeenCalledWith(+ expect.objectContaining({+ error: expect.objectContaining({+ message: expect.stringContaining('2000ms'),+ type: 'client_executor_timeout',+ }),+ success: false,+ toolCallId: 'call_1',+ }),+ );+ });++ it('does NOT trip the timeout when executor finishes before the deadline', async () => {+ hasExecutorMock.mockReturnValue(true);+ invokeExecutorMock.mockResolvedValue({ content: 'fast', success: true });+ const { action, sendToolResult, abort } = setup();++ await action.internal_executeClientTool(makeData({ executionTimeoutMs: 60_000 }), {+ operationId: 'op-1',+ });++ expect(abort).not.toHaveBeenCalled();+ expect(sendToolResult).toHaveBeenCalledWith(+ expect.objectContaining({ content: 'fast', success: true }),+ );+ });+ });++ describe('live gateway connection lookup (Bug 3)', () => {+ it('uses the connection present at send-time, not at action-entry time', async () => {+ hasExecutorMock.mockReturnValue(true);++ let resolver: (v: any) => void = () => {};+ invokeExecutorMock.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolver = resolve;+ }),+ );++ const { action, state } = setup({ hasConnection: false });++ // Kick off β at this moment gatewayConnections is empty.+ const promise = action.internal_executeClientTool(makeData(), {+ operationId: 'op-1',+ });++ // Simulate a reconnect landing while the executor is still running:+ // a fresh entry appears in gatewayConnections.+ const reconnectedSend = vi.fn(() => true);+ state.gatewayConnections['op-1'] = {+ client: {+ connect: vi.fn(),+ disconnect: vi.fn(),+ on: vi.fn(),+ sendInterrupt: vi.fn(),+ sendToolResult: reconnectedSend,+ },+ status: 'connected',+ };++ resolver({ content: 'late ok', success: true });+ await promise;++ expect(reconnectedSend).toHaveBeenCalledWith(+ expect.objectContaining({ content: 'late ok', success: true }),+ );+ });+ });++ describe('exactly-once send tripwire (Bug 4)', () => {+ it('sends only one tool_result even if the executor resolves *and* the timeout fires', async () => {+ vi.useFakeTimers();+ try {+ hasExecutorMock.mockReturnValue(true);+ let resolver: (v: any) => void = () => {};+ invokeExecutorMock.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolver = resolve;+ }),+ );+ const { action, sendToolResult } = setup();++ const promise = action.internal_executeClientTool(makeData({ executionTimeoutMs: 2_000 }), {+ operationId: 'op-1',+ });++ // Resolve the executor right around the deadline.+ await vi.advanceTimersByTimeAsync(1_400);+ resolver({ content: 'just-in-time', success: true });+ await vi.advanceTimersByTimeAsync(500);+ await promise;++ // No matter which side won the race, we must send exactly once.+ expect(sendToolResult).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });+ });+describe('pending state', () => {it('marks the call pending during execution and clears it afterwards', async () => {hasExecutorMock.mockReturnValue(true);diff --git a/src/store/chat/slices/aiChat/actions/clientToolExecution.ts b/src/store/chat/slices/aiChat/actions/clientToolExecution.tsindex e560a78b16f..473b53561eb 100644--- a/src/store/chat/slices/aiChat/actions/clientToolExecution.ts+++ b/src/store/chat/slices/aiChat/actions/clientToolExecution.ts@@ -13,11 +13,42 @@ const log = debug('lobe-store:client-tool-execution');type Setter = StoreSetter<ChatStore>;+/**+ * Fallback used when the WS payload is missing `executionTimeoutMs` (e.g. an+ * older server). Matches `GLOBAL_DEFAULT_TIMEOUT_MS` on the server side so+ * the renderer's race is never more lax than the server's BLPOP deadline.+ */+const FALLBACK_EXECUTION_TIMEOUT_MS = 120_000;++/**+ * Fire the renderer-side timeout 500ms ahead of the server's BLPOP deadline+ * so the server consistently observes an explicit `client_executor_timeout`+ * failure rather than a naked BLPOP timeout. Small enough to barely matter+ * for normal runs, large enough to absorb event-loop / WS jitter.+ */+const SAFETY_BUFFER_MS = 500;++class ClientExecutorTimeoutError extends Error {+ readonly executionTimeoutMs: number;+ constructor(executionTimeoutMs: number) {+ super(`Tool execution exceeded ${executionTimeoutMs}ms client deadline`);+ this.name = 'ClientExecutorTimeoutError';+ this.executionTimeoutMs = executionTimeoutMs;+ }+}++const resolveDeadlineMs = (executionTimeoutMs: number | undefined): number => {+ const base =+ typeof executionTimeoutMs === 'number' && executionTimeoutMs > 0+ ? executionTimeoutMs+ : FALLBACK_EXECUTION_TIMEOUT_MS;+ return Math.max(base - SAFETY_BUFFER_MS, 100);+};+/*** Executes a Gateway `tool_execute` request locally and always returns a- * `tool_result` β even on parse failure, missing executor, or thrown error.- *- * Never let the server-side BLPOP time out: the contract is that every+ * `tool_result` β even on parse failure, missing executor, thrown error, or+ * a deadline overrun. Never let the server-side BLPOP time out: every* `tool_execute` produces exactly one `tool_result` back over the same WS.*/export class ClientToolExecutionActionImpl {@@ -34,24 +65,33 @@ export class ClientToolExecutionActionImpl {data: ToolExecuteData,context: { operationId: string },): Promise<void> => {- const { toolCallId, identifier, apiName, arguments: argsString } = data;+ const { toolCallId, identifier, apiName, arguments: argsString, executionTimeoutMs } = data;const { operationId } = context;log(- '[internal_executeClientTool] start toolCallId=%s identifier=%s apiName=%s op=%s',+ '[internal_executeClientTool] start toolCallId=%s identifier=%s apiName=%s op=%s timeout=%dms',toolCallId,identifier,apiName,operationId,+ executionTimeoutMs,);this.#setPending(toolCallId, true);- // Captured once; must be the SAME connection that received the execute request.- const conn = this.#get().gatewayConnections[operationId];-+ let sent = false;const send = (payload: Omit<ToolResultMessage, 'type'>): void => {- this.#setPending(toolCallId, false);+ if (sent) {+ log('[internal_executeClientTool] duplicate send ignored for toolCallId=%s', toolCallId);+ return;+ }+ sent = true;++ // Look up the gateway connection at send-time, not at action-entry time.+ // Reconnects between dispatch and result land a new entry in+ // `gatewayConnections`; using a captured reference would silently+ // sendToolResult into a dead socket.+ const conn = this.#get().gatewayConnections[operationId];if (!conn) {log('[internal_executeClientTool] no gateway connection for op=%s toolCallId=%s β server will timeout',@@ -69,29 +109,30 @@ export class ClientToolExecutionActionImpl {}};- // βββ Parse arguments βββ- let params: any = {};- if (argsString) {- const parsed = safeParseJSON(argsString);- if (parsed === undefined) {- send({- content: null,- error: {- message: `Failed to parse tool arguments: ${argsString.slice(0, 200)}`,- type: 'arguments_parse_error',- },- success: false,- toolCallId,- });- return;+ try {+ // βββ Parse arguments βββ+ let params: any = {};+ if (argsString) {+ const parsed = safeParseJSON(argsString);+ if (parsed === undefined) {+ send({+ content: null,+ error: {+ message: `Failed to parse tool arguments: ${argsString.slice(0, 200)}`,+ type: 'arguments_parse_error',+ },+ success: false,+ toolCallId,+ });+ return;+ }+ params = parsed ?? {};}- params = parsed ?? {};- }- try {+ const operation = this.#get().operations[operationId];+// βββ Builtin dispatch (via registry) βββif (hasExecutor(identifier, apiName)) {- const operation = this.#get().operations[operationId];const ctx: BuiltinToolContext = {agentId: operation?.context?.agentId,documentId: operation?.context?.documentId,@@ -117,7 +158,11 @@ export class ClientToolExecutionActionImpl {topicId: ctx.topicId,});- const result = await invokeExecutor(identifier, apiName, params, ctx);+ const result = await this.#raceAgainstDeadline(+ () => invokeExecutor(identifier, apiName, params, ctx),+ executionTimeoutMs,+ () => operation?.abortController?.abort(),+ );log('[ClientToolCall] execute:end', {apiName,@@ -148,30 +193,34 @@ export class ClientToolExecutionActionImpl {}// βββ MCP fallback β unified dispatch, mirrors invokeMCPTypePlugin shape βββ- const operation = this.#get().operations[operationId];- const mcpResult = await mcpService- .invokeMcpToolCall(- {- apiName,- arguments: argsString,- id: toolCallId,- identifier,- type: 'default',- },- {- signal: operation?.abortController?.signal,- topicId: operation?.context?.topicId ?? undefined,- },- )- .catch((err) => {- log(- '[internal_executeClientTool] mcp invoke threw for %s/%s: %O',- identifier,- apiName,- err,- );- return undefined;- });+ const mcpResult = await this.#raceAgainstDeadline(+ () =>+ mcpService+ .invokeMcpToolCall(+ {+ apiName,+ arguments: argsString,+ id: toolCallId,+ identifier,+ type: 'default',+ },+ {+ signal: operation?.abortController?.signal,+ topicId: operation?.context?.topicId ?? undefined,+ },+ )+ .catch((err) => {+ log(+ '[internal_executeClientTool] mcp invoke threw for %s/%s: %O',+ identifier,+ apiName,+ err,+ );+ return undefined;+ }),+ executionTimeoutMs,+ () => operation?.abortController?.abort(),+ );if (!mcpResult) {send({@@ -199,6 +248,23 @@ export class ClientToolExecutionActionImpl {toolCallId,});} catch (error) {+ if (error instanceof ClientExecutorTimeoutError) {+ log(+ '[internal_executeClientTool] timeout toolCallId=%s after %dms',+ toolCallId,+ error.executionTimeoutMs,+ );+ send({+ content: null,+ error: {+ message: `Tool exceeded ${error.executionTimeoutMs}ms deadline. Raise \`timeout\` in the next call's arguments if this is expected.`,+ type: 'client_executor_timeout',+ },+ success: false,+ toolCallId,+ });+ return;+ }const err = error as Error;log('[internal_executeClientTool] unexpected error toolCallId=%s: %O', toolCallId, err);send({@@ -210,6 +276,60 @@ export class ClientToolExecutionActionImpl {success: false,toolCallId,});+ } finally {+ // Last-resort safety net: every `tool_execute` must produce exactly+ // one `tool_result`. If every branch above somehow missed `send()`,+ // emit a default failure here so the server's BLPOP wakes up.+ if (!sent) {+ log(+ '[internal_executeClientTool] no send observed for toolCallId=%s; emitting default failure',+ toolCallId,+ );+ send({+ content: null,+ error: {+ message: 'Client tool execution finished without producing a result',+ type: 'client_executor_no_result',+ },+ success: false,+ toolCallId,+ });+ }+ this.#setPending(toolCallId, false);+ }+ };++ /**+ * Race a task against the server-supplied execution deadline. Trips+ * `SAFETY_BUFFER_MS` ahead of the server's BLPOP so the renderer can emit a+ * structured timeout failure instead of letting the server time out blindly.+ * On timeout, calls `onTimeout` (typically `abortController.abort()`) so the+ * executor / IPC layer can interrupt in-flight work.+ */+ #raceAgainstDeadline = async <T>(+ task: () => Promise<T>,+ executionTimeoutMs: number | undefined,+ onTimeout: () => void,+ ): Promise<T> => {+ const deadlineMs = resolveDeadlineMs(executionTimeoutMs);+ const budgetMs = executionTimeoutMs ?? FALLBACK_EXECUTION_TIMEOUT_MS;+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ return await Promise.race([+ task(),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ try {+ onTimeout();+ } catch (err) {+ log('[raceAgainstDeadline] onTimeout threw: %O', err);+ }+ reject(new ClientExecutorTimeoutError(budgetMs));+ }, deadlineMs);+ }),+ ]);+ } finally {+ if (timer) clearTimeout(timer);}};