Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🛑 fix: Forward Run Abort Signal to Foreground Tool Calls (#15517)
Danny Avila021951311515
diff --git a/api/server/middleware/abortMiddleware.js b/api/server/middleware/abortMiddleware.jsindex 96db0b60d4..9add302e37 100644--- a/api/server/middleware/abortMiddleware.js+++ b/api/server/middleware/abortMiddleware.js@@ -4,6 +4,7 @@ const {isEnabled,sendEvent,countTokens,+ isAbortError,GenerationJobManager,recordCollectedUsage,getTransactionsConfig,@@ -16,36 +17,6 @@ const { sendError } = require('~/server/middleware/error');const { abortRun } = require('./abortRun');const db = require('~/models');-/**- * @param {Error | unknown} error- * @returns {boolean}- */-const isAbortError = (error) => {- const visited = new Set();- let current = error;-- while (current && typeof current === 'object' && !visited.has(current)) {- visited.add(current);-- const errorName = current.name;- const errorCode = current.code;- const errorMessage = typeof current.message === 'string' ? current.message : '';-- if (- errorName === 'AbortError' ||- errorCode === 'ABORT_ERR' ||- errorMessage.includes('AbortError') ||- /(?:operation|request|stream) was aborted/i.test(errorMessage)- ) {- return true;- }-- current = current.cause;- }-- return false;-};-/*** Spend tokens for all models from collected usage.* This handles both sequential and parallel agent execution.diff --git a/api/server/middleware/abortMiddleware.spec.js b/api/server/middleware/abortMiddleware.spec.jsindex 20c4700421..276760162b 100644--- a/api/server/middleware/abortMiddleware.spec.js+++ b/api/server/middleware/abortMiddleware.spec.js@@ -31,6 +31,9 @@ jest.mock('@librechat/data-schemas', () => ({}));jest.mock('@librechat/api', () => ({+ /** Real implementation: these tests exist to verify abort classification+ * itself, so mocking it would assert the mock rather than the behavior. */+ isAbortError: jest.requireActual('@librechat/api').isAbortError,countTokens: jest.fn().mockResolvedValue(100),isEnabled: jest.fn().mockReturnValue(false),sendEvent: jest.fn(),@@ -44,6 +47,9 @@ jest.mock('@librechat/api', () => ({}));jest.mock('librechat-data-provider', () => ({+ /** Keep the module real: `@librechat/api` is partially un-mocked above and+ * reads constants (`CacheKeys`, ...) from it at import time. */+ ...jest.requireActual('librechat-data-provider'),isAssistantsEndpoint: jest.fn().mockReturnValue(false),ErrorTypes: { INVALID_REQUEST: 'INVALID_REQUEST', NO_SYSTEM_MESSAGES: 'NO_SYSTEM_MESSAGES' },}));diff --git a/api/server/services/ActionService.js b/api/server/services/ActionService.jsindex 85b3d45cdc..7caa89064e 100644--- a/api/server/services/ActionService.js+++ b/api/server/services/ActionService.js@@ -5,7 +5,9 @@ const { tool } = require('@librechat/agents/langchain/tools');const { logger, decryptV2 } = require('@librechat/data-schemas');const {sendEvent,+ isAbortError,logAxiosError,+ detachOnAbort,getTokenExpiresAt,refreshAccessToken,GenerationJobManager,@@ -267,10 +269,17 @@ async function createActionTool({config?.signal,);logger.debug('Waiting for OAuth Authorization response', { action_id, identifier });- const result = await flowManager.createFlow(- identifier,- 'oauth',- {+ /** Detached rather than signalled. This key is `userId:action_id`,+ * so a second run for the same action joins this very flow and+ * the browser's OAuth callback reads its metadata to exchange+ * the code; `monitorFlow` deletes the key when a waiter's signal+ * aborts, which would strand the other run and discard an+ * authorization the user already granted. Stopping only this+ * waiter leaves the flow to finish for whoever else needs it,+ * while keeping a late authorization from resuming this call+ * into the API request below. */+ const result = await detachOnAbort(+ flowManager.createFlow(identifier, 'oauth', {state: stateToken,userId: userId,client_url: metadata.auth.client_url,@@ -280,7 +289,7 @@ async function createActionTool({/** Encrypted values */encrypted_oauth_client_id: encrypted.oauth_client_id,encrypted_oauth_client_secret: encrypted.oauth_client_secret,- },+ }),config?.signal,);logger.debug('Received OAuth Authorization response', { action_id, identifier });@@ -300,6 +309,12 @@ async function createActionTool({const expiresAt = getTokenExpiresAt(result.expires_in);metadata.oauth_token_expires_at = expiresAt?.toISOString();} catch (error) {+ /** A stopped run is not an authentication failure. Relabelling it+ * loses the abort identity every downstream boundary keys on and+ * reports a fault the user caused deliberately. */+ if (isAbortError(error)) {+ throw error;+ }const errorMessage = 'Failed to authenticate OAuth tool';logger.error(errorMessage, error);throw new Error(errorMessage);@@ -351,10 +366,15 @@ async function createActionTool({);const flowsCache = getLogStores(CacheKeys.FLOWS);const flowManager = getActionFlowStateManager(flowsCache);- const refreshData = await flowManager.createFlowWithHandler(- `${identifier}:refresh`,- 'oauth_refresh',- refreshTokens,+ /** Also shared across this user's runs for the action; see the+ * authorization flow above for why it is detached, not+ * signalled. */+ const refreshData = await detachOnAbort(+ flowManager.createFlowWithHandler(+ `${identifier}:refresh`,+ 'oauth_refresh',+ refreshTokens,+ ),config?.signal,);metadata.oauth_access_token = refreshData.access_token;@@ -364,6 +384,12 @@ async function createActionTool({const expiresAt = getTokenExpiresAt(refreshData.expires_in);metadata.oauth_token_expires_at = expiresAt?.toISOString();} catch (error) {+ /** The refresh did not fail — this run stopped waiting on it.+ * Falling through to `requestLogin` would emit an OAuth prompt+ * and open pending authorization state for a turn that is over. */+ if (isAbortError(error)) {+ throw error;+ }logger.error('Failed to refresh token, requesting new login:', error);await requestLogin();}@@ -375,6 +401,7 @@ async function createActionTool({await preparedExecutor.setAuth(metadata);} catch (error) {if (+ isAbortError(error) ||error.message.includes('No access token found') ||error.message.includes('Access token is expired')) {@@ -391,6 +418,13 @@ async function createActionTool({}return response.data;} catch (error) {+ /** Surface the cancellation as a cancellation: `logAxiosError` would log it+ * at error level and return its text as the tool's result, presenting a+ * stopped turn as a failed API call. */+ if (isAbortError(error)) {+ logger.debug(`Action call to ${action.metadata.domain} cancelled by user abort`);+ throw error;+ }const message = `API call to ${action.metadata.domain} failed:`;return logAxiosError({ message, error });}diff --git a/api/server/services/ActionService.spec.js b/api/server/services/ActionService.spec.jsindex 73c4cf6a5a..cd6b8935af 100644--- a/api/server/services/ActionService.spec.js+++ b/api/server/services/ActionService.spec.js@@ -1,3 +1,5 @@+const dataSchemas = require('@librechat/data-schemas');+const { logger } = dataSchemas;const { Constants, actionDelimiter, actionDomainSeparator } = require('librechat-data-provider');const mockEmitChunk = jest.fn();@@ -315,6 +317,285 @@ describe('createActionTool OAuth events', () => {});});+describe('createActionTool OAuth flow cancellation', () => {+ /**+ * `monitorFlow` deletes the flow key when a waiter's signal aborts. The+ * authorization and refresh flows are keyed `userId:action_id`, so a second+ * run for the same action joins the very same record and the browser's OAuth+ * callback reads its metadata to exchange the code — one Stop must not strand+ * either of them. Only the run-scoped login flow may carry the run signal.+ */+ it('withholds the run signal from flows shared beyond this run', async () => {+ const preparedExecutor = {+ setAuth: jest.fn().mockResolvedValue(undefined),+ execute: jest.fn().mockResolvedValue({ data: { ok: true } }),+ };+ const requestBuilder = {+ createExecutor: jest.fn(() => ({+ setParams: jest.fn(() => preparedExecutor),+ })),+ };+ mockFindToken.mockResolvedValue(null);+ mockActionFlowManager.createFlowWithHandler.mockImplementation(+ async (_flowId, _type, handler) => handler(),+ );+ mockActionFlowManager.createFlow.mockResolvedValue({+ access_token: 'access-token',+ refresh_token: 'refresh-token',+ expires_in: 3600,+ });++ const actionTool = await createActionTool({+ userId: 'action-user',+ res: {},+ action: {+ action_id: 'action-1',+ metadata: {+ domain: 'https://api.example.com',+ oauth_client_id: 'client-id',+ auth: {+ type: 'oauth',+ authorization_url: 'https://auth.example.com/authorize',+ client_url: 'https://auth.example.com/token',+ scope: 'read',+ },+ },+ },+ requestBuilder,+ encrypted: {+ oauth_client_id: 'encrypted-client-id',+ oauth_client_secret: 'encrypted-client-secret',+ },+ streamId: 'action-oauth-stream',+ jobCreatedAt: 1234,+ });++ const signal = new AbortController().signal;+ await actionTool._call(+ {},+ {+ signal,+ metadata: { thread_id: 'thread-1', run_id: 'run-1' },+ toolCall: {+ id: 'tool-call-1',+ stepId: 'step-1',+ name: 'action-tool',+ type: 'tool_call',+ },+ },+ );++ const [sharedFlowId, sharedType, , sharedSignal] =+ mockActionFlowManager.createFlow.mock.calls[0];+ expect(sharedFlowId).toBe('action-user:action-1');+ expect(sharedType).toBe('oauth');+ expect(sharedSignal).toBeUndefined();++ const loginCall = mockActionFlowManager.createFlowWithHandler.mock.calls.find(+ ([, type]) => type === 'oauth_login',+ );+ expect(loginCall[0]).toBe('action-user:action-1:oauth_login:thread-1:run-1');+ expect(loginCall[3]).toBe(signal);+ });+});++describe('createActionTool OAuth stop behavior', () => {+ /**+ * Detaching is not the same as ignoring the Stop: the shared flow survives for+ * other waiters and the browser callback, but a late authorization must not+ * resume this call into the API request it was gating.+ */+ it('does not run the API request when the run is stopped mid-OAuth', async () => {+ const preparedExecutor = {+ setAuth: jest.fn().mockResolvedValue(undefined),+ execute: jest.fn().mockResolvedValue({ data: { ok: true } }),+ };+ const requestBuilder = {+ createExecutor: jest.fn(() => ({+ setParams: jest.fn(() => preparedExecutor),+ })),+ };+ mockFindToken.mockResolvedValue(null);+ mockActionFlowManager.createFlowWithHandler.mockImplementation(+ async (_flowId, _type, handler) => handler(),+ );++ /** The shared flow completes only after the user has pressed Stop, exactly+ * as it would when the browser callback lands late. */+ let completeFlow;+ mockActionFlowManager.createFlow.mockImplementation(+ () =>+ new Promise((resolve) => {+ completeFlow = resolve;+ }),+ );++ const actionTool = await createActionTool({+ userId: 'action-user',+ res: {},+ action: {+ action_id: 'action-1',+ metadata: {+ domain: 'https://api.example.com',+ oauth_client_id: 'client-id',+ auth: {+ type: 'oauth',+ authorization_url: 'https://auth.example.com/authorize',+ client_url: 'https://auth.example.com/token',+ scope: 'read',+ },+ },+ },+ requestBuilder,+ encrypted: {+ oauth_client_id: 'encrypted-client-id',+ oauth_client_secret: 'encrypted-client-secret',+ },+ streamId: 'action-oauth-stream',+ jobCreatedAt: 1234,+ });++ const controller = new AbortController();+ const call = actionTool._call(+ {},+ {+ signal: controller.signal,+ metadata: { thread_id: 'thread-1', run_id: 'run-1' },+ toolCall: {+ id: 'tool-call-1',+ stepId: 'step-1',+ name: 'action-tool',+ type: 'tool_call',+ },+ },+ );++ await new Promise((resolve) => setImmediate(resolve));+ controller.abort();++ await expect(call).rejects.toThrow();++ completeFlow({+ access_token: 'access-token',+ refresh_token: 'refresh-token',+ expires_in: 3600,+ });+ await new Promise((resolve) => setImmediate(resolve));++ expect(preparedExecutor.execute).not.toHaveBeenCalled();+ });+});++describe('createActionTool OAuth abort identity', () => {+ const oauthAction = {+ action_id: 'action-1',+ metadata: {+ domain: 'https://api.example.com',+ oauth_client_id: 'client-id',+ auth: {+ type: 'oauth',+ authorization_url: 'https://auth.example.com/authorize',+ client_url: 'https://auth.example.com/token',+ scope: 'read',+ },+ },+ };++ function oauthToolFixture() {+ const preparedExecutor = {+ setAuth: jest.fn().mockResolvedValue(undefined),+ execute: jest.fn().mockResolvedValue({ data: { ok: true } }),+ };+ return {+ preparedExecutor,+ requestBuilder: {+ createExecutor: jest.fn(() => ({+ setParams: jest.fn(() => preparedExecutor),+ })),+ },+ };+ }++ function callConfig(signal) {+ return {+ signal,+ metadata: { thread_id: 'thread-1', run_id: 'run-1' },+ toolCall: { id: 'tool-call-1', stepId: 'step-1', name: 'action-tool', type: 'tool_call' },+ };+ }++ it('does not request a fresh login when a stopped run detaches from a refresh', async () => {+ const { requestBuilder, preparedExecutor } = oauthToolFixture();+ /** No access token but a live refresh token: the branch that waits on the+ * shared refresh flow rather than opening a login. */+ mockFindToken.mockImplementation(async ({ type }) =>+ type === 'oauth_refresh' ? { token: 'encrypted-refresh-token' } : null,+ );+ jest.spyOn(dataSchemas, 'decryptV2').mockResolvedValue('refresh-token');++ /** The refresh never settles; the run stops while it is pending. */+ mockActionFlowManager.createFlowWithHandler.mockImplementation(() => new Promise(() => {}));+ mockActionFlowManager.createFlow.mockImplementation(() => new Promise(() => {}));++ const actionTool = await createActionTool({+ userId: 'action-user',+ res: {},+ action: oauthAction,+ requestBuilder,+ encrypted: {+ oauth_client_id: 'encrypted-client-id',+ oauth_client_secret: 'encrypted-client-secret',+ },+ });++ const controller = new AbortController();+ const call = actionTool._call({}, callConfig(controller.signal));+ await new Promise((resolve) => setImmediate(resolve));+ controller.abort();+ await expect(call).rejects.toThrow();++ const loginFlows = mockActionFlowManager.createFlowWithHandler.mock.calls.filter(+ ([, type]) => type === 'oauth_login',+ );+ expect(loginFlows).toHaveLength(0);+ expect(mockEmitChunk).not.toHaveBeenCalled();+ expect(preparedExecutor.execute).not.toHaveBeenCalled();+ });++ it('propagates the abort instead of reporting a failed API call', async () => {+ const { requestBuilder } = oauthToolFixture();+ mockFindToken.mockResolvedValue(null);+ mockActionFlowManager.createFlowWithHandler.mockImplementation(+ async (_flowId, _type, handler) => handler(),+ );+ mockActionFlowManager.createFlow.mockImplementation(() => new Promise(() => {}));++ const actionTool = await createActionTool({+ userId: 'action-user',+ res: {},+ action: oauthAction,+ requestBuilder,+ encrypted: {+ oauth_client_id: 'encrypted-client-id',+ oauth_client_secret: 'encrypted-client-secret',+ },+ streamId: 'action-oauth-stream',+ jobCreatedAt: 1234,+ });++ const controller = new AbortController();+ const call = actionTool._call({}, callConfig(controller.signal));+ await new Promise((resolve) => setImmediate(resolve));+ controller.abort();++ await expect(call).rejects.toBe(controller.signal.reason);+ expect(logger.error).not.toHaveBeenCalledWith(+ 'Failed to authenticate OAuth tool',+ expect.anything(),+ );+ });+});+describe('validateAndUpdateTool', () => {const mockReq = { user: { id: 'user123' } };diff --git a/api/server/services/MCP.js b/api/server/services/MCP.jsindex 1e8820b487..4635b4a703 100644--- a/api/server/services/MCP.js+++ b/api/server/services/MCP.js@@ -40,6 +40,7 @@ const {containsGraphTokenPlaceholder,createAuthIdentityContext,isOAuthServer,+ isAbortError,OpenIDReauthRequiredError,} = require('@librechat/api');const {@@ -1308,10 +1309,21 @@ function createToolInstance({}return result;} catch (error) {- logger.error(- `[MCP][${serverName}][${toolName}][User: ${userId}] Error calling MCP tool:`,- error,- );+ /** A user Stop aborts every in-flight call at once, and that rejection is+ * the cancellation working, so it must not reach error-level operational+ * alerts; the wrapping below still reports it to the turn. The error has+ * to look like an abort as well: a permission, OAuth, or upstream failure+ * can reject in the same tick as the Stop and must stay visible. */+ if (config?.signal?.aborted === true && isAbortError(error)) {+ logger.debug(+ `[MCP][${serverName}][${toolName}][User: ${userId}] Tool call cancelled by user abort`,+ );+ } else {+ logger.error(+ `[MCP][${serverName}][${toolName}][User: ${userId}] Error calling MCP tool:`,+ error,+ );+ }/** Carries the actionable re-auth message; the substring heuristic below would misreport it as an OAuth configuration problem */if (error instanceof OpenIDReauthRequiredError) {diff --git a/api/server/services/MCP.spec.js b/api/server/services/MCP.spec.jsindex 86a0681c28..bd30fce319 100644--- a/api/server/services/MCP.spec.js+++ b/api/server/services/MCP.spec.js@@ -1610,6 +1610,132 @@ describe('User parameter passing tests', () => {expect(callTool).toHaveBeenCalledTimes(2);});+ it('logs a user-aborted tool call as debug, not as an MCP error', async () => {+ const mockUser = { id: 'cancel-user', role: 'USER' };+ const mockRes = { write: jest.fn(), flush: jest.fn() };+ const abortController = new AbortController();+ const { getRoleByName } = require('~/models');+ getRoleByName.mockResolvedValue({+ permissions: {+ [PermissionTypes.MCP_SERVERS]: {+ [Permissions.USE]: true,+ },+ },+ });+ mockGetMCPManager.mockReturnValue({+ callTool: jest.fn(+ ({ options }) =>+ new Promise((_resolve, reject) => {+ const signal = options?.signal;+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });+ }),+ ),+ });++ const mcpTool = await createMCPTool({+ res: mockRes,+ user: mockUser,+ config: { url: 'https://cancel.example.com/mcp' },+ toolKey: `test-tool${D}test-server`,+ provider: 'openai',+ userMCPAuthMap: {},+ availableTools: {+ [`test-tool${D}test-server`]: {+ function: {+ description: 'Cached tool',+ parameters: { type: 'object', properties: {} },+ },+ },+ },+ });++ const call = mcpTool.invoke(+ {},+ {+ signal: abortController.signal,+ configurable: { user: mockUser },+ metadata: { provider: 'openai', thread_id: 'thread-1', run_id: 'run-1' },+ toolCall: {},+ },+ );+ await new Promise((resolve) => setImmediate(resolve));+ abortController.abort();+ await expect(call).rejects.toThrow();+ /** The wrapper rejects on abort while `_call` is still unwinding; let its+ * catch run before asserting on what it logged. */+ await new Promise((resolve) => setImmediate(resolve));++ expect(logger.error).not.toHaveBeenCalledWith(+ expect.stringContaining('Error calling MCP tool'),+ expect.anything(),+ );+ expect(logger.debug).toHaveBeenCalledWith(+ expect.stringContaining('Tool call cancelled by user abort'),+ );+ });++ it('keeps a real failure racing the Stop at error level', async () => {+ const mockUser = { id: 'race-user', role: 'USER' };+ const mockRes = { write: jest.fn(), flush: jest.fn() };+ const abortController = new AbortController();+ const { getRoleByName } = require('~/models');+ getRoleByName.mockResolvedValue({+ permissions: {+ [PermissionTypes.MCP_SERVERS]: {+ [Permissions.USE]: true,+ },+ },+ });+ mockGetMCPManager.mockReturnValue({+ callTool: jest.fn(+ ({ options }) =>+ new Promise((_resolve, reject) => {+ options?.signal?.addEventListener(+ 'abort',+ () => reject(new Error('upstream 503 from the MCP server')),+ { once: true },+ );+ }),+ ),+ });++ const mcpTool = await createMCPTool({+ res: mockRes,+ user: mockUser,+ config: { url: 'https://race.example.com/mcp' },+ toolKey: `test-tool${D}test-server`,+ provider: 'openai',+ userMCPAuthMap: {},+ availableTools: {+ [`test-tool${D}test-server`]: {+ function: {+ description: 'Cached tool',+ parameters: { type: 'object', properties: {} },+ },+ },+ },+ });++ const call = mcpTool.invoke(+ {},+ {+ signal: abortController.signal,+ configurable: { user: mockUser },+ metadata: { provider: 'openai', thread_id: 'thread-1', run_id: 'run-1' },+ toolCall: {},+ },+ );+ await new Promise((resolve) => setImmediate(resolve));+ abortController.abort();+ await expect(call).rejects.toThrow();+ await new Promise((resolve) => setImmediate(resolve));++ expect(logger.error).toHaveBeenCalledWith(+ expect.stringContaining('Error calling MCP tool'),+ expect.anything(),+ );+ });+it.each(['OAuth flow initiated - return early', 'Pending OAuth flow reused - return early'])('preserves runtime-detected OAuth for the internal signal: %s',async (oauthSignal) => {diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.tsindex d39e6b261b..1c17b12d59 100644--- a/packages/api/src/agents/handlers.spec.ts+++ b/packages/api/src/agents/handlers.spec.ts@@ -309,6 +309,134 @@ describe('createToolExecuteHandler', () => {});});+ describe('run cancellation', () => {+ /** Production aborts with no reason, yielding a DOMException named+ * `AbortError` — the shape every cancellation check downstream keys on. */+ function abortingTool(name = 'slow_tool') {+ return {+ name,+ invoke: jest.fn(+ (_args: unknown, config: Record<string, unknown>) =>+ new Promise((_resolve, reject) => {+ const signal = config.signal as AbortSignal | undefined;+ if (signal == null) {+ setTimeout(() => reject(new Error('never aborted')), 50);+ return;+ }+ signal.addEventListener('abort', () => reject(signal.reason), { once: true });+ }),+ ),+ };+ }++ function runBatch(+ tool: { name: string; invoke: jest.Mock },+ request: Partial<ToolExecuteBatchRequest>,+ controller: AbortController,+ ): Promise<ToolExecuteResult[]> {+ const loadTools: ToolExecuteOptions['loadTools'] = jest.fn(async () => ({+ loadedTools: [tool] as never[],+ }));+ const handler = createToolExecuteHandler({ loadTools });+ return new Promise<ToolExecuteResult[]>((resolve, reject) => {+ handler.handle('on_tool_execute', {+ toolCalls: [{ id: 'call-1', name: tool.name, args: {} }] as ToolCallRequest[],+ signal: controller.signal,+ ...request,+ resolve,+ reject,+ } as ToolExecuteBatchRequest);+ setTimeout(() => controller.abort(), 10);+ });+ }++ it('forwards the batch abort signal into foreground tool invocations', async () => {+ const controller = new AbortController();+ const tool = abortingTool();++ const results = await runBatch(tool, {}, controller);++ expect(tool.invoke.mock.calls[0][1].signal).toBe(controller.signal);+ expect(results).toHaveLength(1);+ expect(results[0].status).toBe('error');+ });++ it('logs a cancelled tool call as debug rather than a tool error', async () => {+ const errorSpy = jest.spyOn(logger, 'error').mockReturnValue(logger);+ const controller = new AbortController();++ await runBatch(abortingTool(), {}, controller);++ expect(+ errorSpy.mock.calls.filter(([message]) =>+ String(message).includes('[ON_TOOL_EXECUTE] Tool slow_tool error'),+ ),+ ).toHaveLength(0);+ });++ /**+ * An aborted run says the turn is over, not that this rejection was the+ * cancellation. A genuine failure that lands in the same tick as the Stop+ * must stay visible to operational logging.+ */+ it('keeps an unrelated failure racing the Stop at error level', async () => {+ const errorSpy = jest.spyOn(logger, 'error').mockReturnValue(logger);+ const controller = new AbortController();+ const tool = {+ name: 'slow_tool',+ invoke: jest.fn(+ (_args: unknown, config: Record<string, unknown>) =>+ new Promise((_resolve, reject) => {+ const signal = config.signal as AbortSignal;+ signal.addEventListener(+ 'abort',+ () => reject(new Error('upstream 503 from the tool backend')),+ { once: true },+ );+ }),+ ),+ };++ await runBatch(tool, {}, controller);++ expect(+ errorSpy.mock.calls.filter(([message]) =>+ String(message).includes('[ON_TOOL_EXECUTE] Tool slow_tool error'),+ ),+ ).toHaveLength(1);+ });++ /**+ * The quiet-log branch must never double as a way around output filtering.+ */+ it('still filters a tool failure that rejects after the run was aborted', async () => {+ const protectedValue = 'PROTECTED-CANCELLED-TOOL-OUTPUT';+ const controller = new AbortController();+ const tool = {+ name: 'slow_tool',+ invoke: jest.fn(+ (_args: unknown, config: Record<string, unknown>) =>+ new Promise((_resolve, reject) => {+ const signal = config.signal as AbortSignal;+ signal.addEventListener('abort', () => reject(new Error(protectedValue)), {+ once: true,+ });+ }),+ ),+ };++ const [result] = await runBatch(+ tool,+ { configurable: { req: protectedToolOutputRequest() } },+ controller,+ );++ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('content_filter_block');+ expect(result.errorMessage).not.toContain(protectedValue);+ });+ });+describe('tool argument normalization', () => {it('parses JSON-string args for object-schema tools before invocation', async () => {const capturedArgs: unknown[] = [];diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.tsindex c06620124d..2287d15d28 100644--- a/packages/api/src/agents/handlers.ts+++ b/packages/api/src/agents/handlers.ts@@ -72,13 +72,19 @@ import {BACKGROUND_TASK_ABORT_GRACE_MS,BACKGROUND_TOOL_PRODUCER_HEARTBEAT_MS,} from './backgroundCompletion';+import {+ isAbortError,+ logAxiosError,+ truncateMiddle,+ runOutsideTracing,+ getSafeErrorMetadata,+} from '~/utils';import {hasIntentArg,stripIntentArg,stripIntentLabelsFromToolDefinitions,INTENT_ARG,} from './intent';-import { getSafeErrorMetadata, logAxiosError, runOutsideTracing, truncateMiddle } from '~/utils';import { buildSkillPrimeMessage, isSkillFilePath, SKILL_FILE_PREFIX } from './skills';import { resolveCallerCapabilityProjectionSnapshot } from './callerCapabilities';import { createSkillContentDigest } from './compatibility';@@ -4411,7 +4417,15 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandreturn {handle: async (_event: string, data: ToolExecuteBatchRequest) => {- const { toolCalls, agentId, configurable, metadata, resolve, reject } = data;+ const {+ toolCalls,+ agentId,+ configurable,+ metadata,+ signal: runSignal,+ resolve,+ reject,+ } = data;const callerCapabilityProjection = resolveCallerCapabilityProjectionSnapshot((data as ToolExecuteBatchRequest & {@@ -5884,6 +5898,13 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandtoolCall: toolCallConfig,configurable: mergedConfigurable,metadata,+ /** The run's cancellation signal. Without it a foreground+ * tool call keeps running after Stop: an MCP call never+ * sends `notifications/cancelled`, and every other+ * signal-aware tool keeps burning quota on a turn the+ * user already abandoned. Detached background calls+ * intentionally use their own controller instead. */+ ...(runSignal != null && { signal: runSignal }),} as Record<string, unknown>);/* Only sandbox-bound calls carry a runtime session hint, so@@ -5981,18 +6002,35 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandreturn errorResult(tc, modelBoundContentFilterErrorMessage(toolError.body));}const { message, logContext } = getSafeToolError(toolError);+ /** A user Stop rejects every in-flight call at once. That is+ * the abort working, not a fault, so it is logged at debug.+ * An aborted run says the turn is over, not that THIS+ * rejection was the cancellation, so the error must look+ * like one too; an unrelated failure racing the Stop stays+ * at error level. Either way the level is all that changes+ * — filtering and the result shape are identical. */+ const logToolFailure = (context: Record<string, unknown>): void => {+ if (runSignal?.aborted === true && isAbortError(toolError)) {+ logger.debug(+ `[ON_TOOL_EXECUTE] Tool ${tc.name} cancelled by run abort`,+ context,+ );+ return;+ }+ logger.error(`[ON_TOOL_EXECUTE] Tool ${tc.name} error`, context);+ };const req = mergedConfigurable?.req as ServerRequest | undefined;const filteredError = filteredToolOutputResult(tc, req, {errorMessage: message,});if (filteredError != null) {- logger.error(`[ON_TOOL_EXECUTE] Tool ${tc.name} error`, {+ logToolFailure({name: logContext.name,contentFiltered: true,});return filteredError;}- logger.error(`[ON_TOOL_EXECUTE] Tool ${tc.name} error`, {+ logToolFailure({...logContext,toolCallArgsShape: getValueShape(tc.args),toolInputSchemaKind: getToolInputSchemaKind(tool),diff --git a/packages/api/src/mcp/MCPManager.ts b/packages/api/src/mcp/MCPManager.tsindex 425aeda004..f3f703faa1 100644--- a/packages/api/src/mcp/MCPManager.ts+++ b/packages/api/src/mcp/MCPManager.ts@@ -33,6 +33,7 @@ import { MCPConnectionFactory } from './MCPConnectionFactory';import { processMCPEnv, isPluginSourced } from '~/utils/env';import { OAuthLifecycleRelay } from './oauth/pending';import { preProcessGraphTokens } from '~/utils/graph';+import { isAbortError } from '~/utils/errors';import { formatToolContent } from './parsers';import { MCPConnection } from './connection';import { mcpConfig } from './mcpConfig';@@ -1197,6 +1198,14 @@ Please follow these instructions when using tools from the respective MCP serverrecoveryTakeoverConsumed = true;continue;}+ /** A user Stop aborts the in-flight request; that rejection is the+ * cancellation working, not a fault, so it stays out of the error log.+ * The error must look like an abort too — a real failure can reject in+ * the same tick as the Stop and has to stay visible. */+ if (options?.signal?.aborted === true && isAbortError(error)) {+ logger.debug(`${logPrefix}[${toolName}] Tool call cancelled by user abort`);+ throw error;+ }// Log with context and re-throw or handle as neededlogger.error(`${logPrefix}[${toolName}] Tool call failed`, error);// Rethrowing allows the caller (createMCPTool) to handle the final user messagediff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.tsindex b7a785d0f1..df42a7bdb1 100644--- a/packages/api/src/mcp/__tests__/MCPManager.test.ts+++ b/packages/api/src/mcp/__tests__/MCPManager.test.ts@@ -819,6 +819,99 @@ describe('MCPManager', () => {});});+ describe('callTool - cancellation logging', () => {+ const mockUser = { id: 'cancel-user' } as IUser;+ const mockFlowManager = {} as Parameters<MCPManager['callTool']>[0]['flowManager'];+ const serverConfig: t.SSEOptions = {+ type: 'sse',+ url: 'https://api.example.com',+ };++ /** Rejects the way the MCP SDK does once a request's signal aborts. */+ function createAbortingConnection(): MCPConnection {+ return {+ isConnected: jest.fn().mockResolvedValue(true),+ setRequestHeaders: jest.fn(),+ timeout: 30000,+ client: {+ request: jest.fn(+ (_request: unknown, _schema: unknown, options: { signal?: AbortSignal }) =>+ new Promise((_resolve, reject) => {+ options.signal?.addEventListener('abort', () => reject(options.signal?.reason), {+ once: true,+ });+ }),+ ),+ },+ } as unknown as MCPConnection;+ }++ beforeEach(() => {+ (graphUtils.preProcessGraphTokens as jest.Mock).mockImplementation(+ async (options) => options,+ );+ (logger.error as jest.Mock).mockClear();+ (logger.debug as jest.Mock).mockClear();+ });++ async function callAndAbort(connection: MCPConnection): Promise<unknown> {+ const manager = new MCPManager();+ jest.spyOn(manager, 'getConnection').mockResolvedValue(connection);+ const controller = new AbortController();+ const call = manager.callTool({+ user: mockUser,+ serverName,+ serverConfig,+ toolName: 'test_tool',+ provider: 'openai',+ flowManager: mockFlowManager,+ options: { signal: controller.signal },+ });+ await new Promise((resolve) => setImmediate(resolve));+ controller.abort();+ return call.catch((error) => error);+ }++ it('logs a user-aborted tool call at debug rather than as a failure', async () => {+ await callAndAbort(createAbortingConnection());++ expect(logger.error).not.toHaveBeenCalledWith(+ expect.stringContaining('Tool call failed'),+ expect.anything(),+ );+ expect(logger.debug).toHaveBeenCalledWith(+ expect.stringContaining('Tool call cancelled by user abort'),+ );+ });++ it('keeps a real failure racing the Stop at error level', async () => {+ const connection = {+ isConnected: jest.fn().mockResolvedValue(true),+ setRequestHeaders: jest.fn(),+ timeout: 30000,+ client: {+ request: jest.fn(+ (_request: unknown, _schema: unknown, options: { signal?: AbortSignal }) =>+ new Promise((_resolve, reject) => {+ options.signal?.addEventListener(+ 'abort',+ () => reject(new Error('upstream 503 from the MCP server')),+ { once: true },+ );+ }),+ ),+ },+ } as unknown as MCPConnection;++ await callAndAbort(connection);++ expect(logger.error).toHaveBeenCalledWith(+ expect.stringContaining('Tool call failed'),+ expect.anything(),+ );+ });+ });+describe('callTool - Graph Token Integration', () => {const mockUser: Partial<IUser> = {id: 'user-123',diff --git a/packages/api/src/utils/errors.spec.ts b/packages/api/src/utils/errors.spec.tsindex cbee85089d..63acde6738 100644--- a/packages/api/src/utils/errors.spec.ts+++ b/packages/api/src/utils/errors.spec.ts@@ -1,4 +1,4 @@-import { getSafeErrorMetadata } from './errors';+import { getSafeErrorMetadata, isAbortError } from './errors';describe('getSafeErrorMetadata', () => {it('keeps bounded diagnostic fields without serializing raw provider data', () => {@@ -51,3 +51,44 @@ describe('getSafeErrorMetadata', () => {).toEqual({ type: 'UnknownError' });});});++describe('isAbortError', () => {+ it('recognizes the DOMException a bare abort() produces', () => {+ const controller = new AbortController();+ controller.abort();+ expect(isAbortError(controller.signal.reason)).toBe(true);+ });++ it('recognizes an abort rewrapped by an intermediate layer', () => {+ const controller = new AbortController();+ controller.abort();+ const wrapped = new Error('[MCP][server][tool] tool call failed', {+ cause: controller.signal.reason,+ });+ expect(isAbortError(wrapped)).toBe(true);+ });++ it('recognizes the SDK message shape that only stringifies the reason', () => {+ expect(+ isAbortError(new Error('MCP error -32001: AbortError: This operation was aborted')),+ ).toBe(true);+ });++ it('does not treat an unrelated failure as a cancellation', () => {+ expect(isAbortError(new Error('upstream 503 from the tool backend'))).toBe(false);+ expect(isAbortError(Object.assign(new Error('forbidden'), { code: 'EPERM' }))).toBe(false);+ });++ it('terminates on a cyclic cause chain', () => {+ const first = new Error('first') as Error & { cause?: unknown };+ const second = new Error('second') as Error & { cause?: unknown };+ first.cause = second;+ second.cause = first;+ expect(isAbortError(first)).toBe(false);+ });++ it('tolerates non-error values', () => {+ expect(isAbortError(undefined)).toBe(false);+ expect(isAbortError('aborted')).toBe(false);+ });+});diff --git a/packages/api/src/utils/errors.ts b/packages/api/src/utils/errors.tsindex 38073c97eb..f43e0354e1 100644--- a/packages/api/src/utils/errors.ts+++ b/packages/api/src/utils/errors.ts@@ -38,3 +38,39 @@ export function getSafeErrorMetadata(error: unknown): SafeErrorMetadata {...(status !== undefined && { status }),};}++/**+ * Whether a caught error is a cancellation rather than a genuine failure.+ *+ * An aborted signal on its own proves only that the run is over: a permission,+ * OAuth, or upstream error can reject in the same tick a user presses Stop, and+ * treating those as cancellations hides real faults from operational alerts.+ * Callers that want to quiet a cancellation should require this as well as the+ * signal state. Walks `cause` because intermediate layers rewrap the rejection.+ */+export function isAbortError(error: unknown): boolean {+ const visited = new Set<unknown>();+ let current: unknown = error;++ while (current != null && typeof current === 'object' && !visited.has(current)) {+ visited.add(current);++ const name = readProperty(current, 'name');+ const code = readProperty(current, 'code');+ const messageValue = readProperty(current, 'message');+ const message = typeof messageValue === 'string' ? messageValue : '';++ if (+ name === 'AbortError' ||+ code === 'ABORT_ERR' ||+ message.includes('AbortError') ||+ /(?:operation|request|stream) was aborted/i.test(message)+ ) {+ return true;+ }++ current = readProperty(current, 'cause');+ }++ return false;+}diff --git a/packages/api/src/utils/index.ts b/packages/api/src/utils/index.tsindex 06e63a62eb..8a12471b3f 100644--- a/packages/api/src/utils/index.ts+++ b/packages/api/src/utils/index.ts@@ -6,6 +6,7 @@ export * from './content';export * from './email';export * from './env';export * from './errors';+export * from './promises';export * from './events';export * from './files';export * from './import';diff --git a/packages/api/src/utils/promises.spec.ts b/packages/api/src/utils/promises.spec.tsnew file mode 100644index 0000000000..cc3ddf2481--- /dev/null+++ b/packages/api/src/utils/promises.spec.ts@@ -0,0 +1,70 @@+import { detachOnAbort } from './promises';++describe('detachOnAbort', () => {+ it('passes the promise through when no signal is given', async () => {+ await expect(detachOnAbort(Promise.resolve('value'))).resolves.toBe('value');+ });++ it('resolves normally when the signal never aborts', async () => {+ const controller = new AbortController();+ await expect(detachOnAbort(Promise.resolve('value'), controller.signal)).resolves.toBe('value');+ });++ it('propagates the underlying rejection when the signal never aborts', async () => {+ const controller = new AbortController();+ await expect(+ detachOnAbort(Promise.reject(new Error('upstream failed')), controller.signal),+ ).rejects.toThrow('upstream failed');+ });++ it('rejects with the abort reason and leaves the work running', async () => {+ const controller = new AbortController();+ let settle!: (value: string) => void;+ const shared = new Promise<string>((resolve) => (settle = resolve));+ let sharedSettled = false;+ shared.then(() => (sharedSettled = true));++ const detached = detachOnAbort(shared, controller.signal);+ controller.abort();++ await expect(detached).rejects.toBe(controller.signal.reason);+ expect(sharedSettled).toBe(false);++ /** The shared work still completes for whoever else is waiting on it. */+ settle('completed after the abort');+ await shared;+ expect(sharedSettled).toBe(true);+ });++ it('rejects immediately when the signal is already aborted', async () => {+ const controller = new AbortController();+ controller.abort();+ await expect(detachOnAbort(Promise.resolve('value'), controller.signal)).rejects.toBe(+ controller.signal.reason,+ );+ });++ it('does not surface a late rejection of detached work', async () => {+ const unhandled: unknown[] = [];+ const onUnhandled = (reason: unknown): void => {+ unhandled.push(reason);+ };+ process.on('unhandledRejection', onUnhandled);+ try {+ const controller = new AbortController();+ let fail!: (error: Error) => void;+ const shared = new Promise<string>((_resolve, reject) => (fail = reject));++ const detached = detachOnAbort(shared, controller.signal);+ controller.abort();+ await expect(detached).rejects.toBe(controller.signal.reason);++ fail(new Error('shared work failed later'));+ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(unhandled).toHaveLength(0);+ } finally {+ process.off('unhandledRejection', onUnhandled);+ }+ });+});diff --git a/packages/api/src/utils/promises.ts b/packages/api/src/utils/promises.tsnew file mode 100644index 0000000000..b51a8a9d24--- /dev/null+++ b/packages/api/src/utils/promises.ts@@ -0,0 +1,39 @@+/**+ * Resolves with `promise`, but rejects as soon as `signal` aborts.+ *+ * Unlike handing the signal to the work itself, the underlying promise keeps+ * running. Use it for shared work whose lifetime outlives this caller — an OAuth+ * flow keyed by user and action that a concurrent run may also be awaiting and+ * that a browser callback will complete. Cancelling such work on one waiter's+ * abort strands the others and discards an authorization the user has already+ * granted; leaving the caller attached is equally wrong, because the value+ * arrives after the user pressed Stop and the caller acts on it.+ *+ * The detached promise's later settlement is swallowed rather than surfacing as+ * an unhandled rejection.+ */+export function detachOnAbort<T>(promise: Promise<T>, signal?: AbortSignal | null): Promise<T> {+ if (signal == null) {+ return promise;+ }++ if (signal.aborted) {+ promise.catch(() => undefined);+ return Promise.reject(signal.reason);+ }++ return new Promise<T>((resolve, reject) => {+ const onAbort = (): void => reject(signal.reason);+ signal.addEventListener('abort', onAbort, { once: true });+ promise.then(+ (value) => {+ signal.removeEventListener('abort', onAbort);+ resolve(value);+ },+ (error) => {+ signal.removeEventListener('abort', onAbort);+ reject(error);+ },+ );+ });+}