Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(agent-runtime): settle tool calls that were still running at an interrupt (#18506)

Arvin Xuaa92ba239e82
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index a5249ede84e..64c009f1707 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -222,6 +222,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
// call_llm does a parent existence preflight; return a truthy row by
// default so existing tests don't have to stub it.
findById: vi.fn().mockResolvedValue({ id: 'msg-existing' }),
+ // The abort settle asks whether a row already holds the call. Null by
+ // default: these tests exercise calls that never got one.
+ findToolMessageIdByToolCallId: vi.fn().mockResolvedValue(null),
query: vi.fn().mockResolvedValue([]),
update: vi.fn().mockResolvedValue({}),
updateToolMessage: vi.fn().mockResolvedValue({ success: true }),
@@ -5740,6 +5743,71 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
);
});
+ it('should not launch the tool when Stop lands during the preflight hook', async () => {
+ // Every await between entering `run` and the actual launch reopens the
+ // cancellation window. The executor's race settles the call the moment
+ // the signal fires, so anything launched after that is side-effecting
+ // work for an operation that is already over.
+ const controller = new AbortController();
+ const mockDispatcher = {
+ dispatch: vi.fn().mockResolvedValue(undefined),
+ dispatchBeforeToolCall: vi.fn().mockImplementation(async () => {
+ controller.abort();
+ return null;
+ }),
+ };
+
+ const ctxWithHooks = {
+ ...ctx,
+ abortSignal: controller.signal,
+ hookDispatcher: mockDispatcher as any,
+ };
+ const executors = createRuntimeExecutors(ctxWithHooks);
+
+ await executors.call_tool!(createToolInstruction(), createToolState()).catch(
+ () => undefined,
+ );
+
+ expect(mockDispatcher.dispatchBeforeToolCall).toHaveBeenCalled();
+ expect(mockToolExecutionService.executeTool).not.toHaveBeenCalled();
+ });
+
+ it('should not dispatch afterToolCall for a tool that outlived an abort', async () => {
+ // The tool keeps running after the abort β€” work already handed to a
+ // process cannot be recalled. Its hook must still be suppressed: by the
+ // time it lands, `executeStep` has emitted the terminal hooks and the
+ // operation is unregistered, so a local consumer drops it silently and a
+ // webhook consumer would see `afterToolCall` after `onComplete`.
+ const mockDispatcher = {
+ dispatch: vi.fn().mockResolvedValue(undefined),
+ dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
+ };
+
+ const controller = new AbortController();
+ mockToolExecutionService.executeTool.mockImplementationOnce(async () => {
+ controller.abort();
+ return { content: 'late result', success: true };
+ });
+
+ const ctxWithHooks = {
+ ...ctx,
+ abortSignal: controller.signal,
+ hookDispatcher: mockDispatcher as any,
+ };
+ const executors = createRuntimeExecutors(ctxWithHooks);
+
+ await executors.call_tool!(createToolInstruction(), createToolState()).catch(
+ () => undefined,
+ );
+
+ expect(mockDispatcher.dispatch).not.toHaveBeenCalledWith(
+ expect.anything(),
+ 'afterToolCall',
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
it('should skip real execution when beforeToolCall returns mock', async () => {
const mockDispatcher = {
dispatch: vi.fn().mockResolvedValue(undefined),
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
index 966ef64aaf3..68a260e3525 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
@@ -85,6 +85,16 @@ export class ServerMessageTransport implements MessageTransport {
await this.messageModel.deleteMessage(id);
}
+ async findToolMessageIdByToolCallId(
+ toolCallId: string,
+ parentMessageId: string,
+ ): Promise<string | undefined> {
+ // Indexed on `message_plugins_tool_call_id_idx`; the model already uses this
+ // lookup for card updates, so the abort path adds no new access pattern.
+ const id = await this.messageModel.findToolMessageIdByToolCallId(toolCallId, parentMessageId);
+ return id ?? undefined;
+ }
+
async findById(id: string): Promise<RuntimeMessageRef | undefined> {
const message = await this.messageModel.findById(id);
return message
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index 41ff1e5885c..7f0e3b2fb27 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -154,6 +154,12 @@ export class ServerToolTransport implements ToolTransport {
args: context.parsedArgs,
manifest: context.effectiveManifestMap[chatToolPayload.identifier],
});
+ // The preflight above (`dispatchBeforeToolCall`, policy checks) is async,
+ // so Stop can land between entering `run` and reaching this line. The
+ // executor's race has already settled the call by then β€” launching now
+ // would start side-effecting work for a cancelled operation.
+ if (context.abortSignal?.aborted) return this.abortedBeforeLaunch();
+
const dispatchResult = await dispatchClientTool(chatToolPayload, {
agentId: context.state.metadata?.agentId,
assistantMessageId: context.parentMessageId,
@@ -182,6 +188,10 @@ export class ServerToolTransport implements ToolTransport {
});
const agentVisibility = await this.resolveAgentVisibility(context);
+ // Re-checked after the visibility await for the same reason as above:
+ // every await between entry and launch reopens the cancellation window.
+ if (context.abortSignal?.aborted) return this.abortedBeforeLaunch();
+
log(`[${operationLogId}] Executing tool ${context.toolName} ...`);
execution = await executeToolWithRetry(
() =>
@@ -314,6 +324,21 @@ export class ServerToolTransport implements ToolTransport {
}
}
+ /**
+ * Result for a call the abort caught before anything was launched.
+ *
+ * Returned rather than thrown: by this point the executor's race has already
+ * rejected and moved on, so this promise is detached β€” throwing would only
+ * surface as an unhandled rejection.
+ */
+ private abortedBeforeLaunch(): ToolRunExecution {
+ return {
+ attempts: 0,
+ interrupted: true,
+ result: { content: '', success: false },
+ };
+ }
+
private async dispatchBeforeToolCall(chatToolPayload: ChatToolPayload, context: ToolRunContext) {
const { hookDispatcher, operationId, stepIndex, userId } = this.ctx;
if (!hookDispatcher) return null;
@@ -353,6 +378,14 @@ export class ServerToolTransport implements ToolTransport {
const { hookDispatcher, operationId, stepIndex, userId } = this.ctx;
if (!hookDispatcher) return;
+ // A tool that outlives an abort still finishes in the background β€” we cannot
+ // recall work already handed to a process. Its hook must not be dispatched
+ // though: by now `executeStep` has emitted the terminal hooks and
+ // `CompletionLifecycle` has unregistered this operation, so a local consumer
+ // would silently drop it and a webhook consumer would receive `afterToolCall`
+ // AFTER `onComplete`.
+ if (context.abortSignal?.aborted) return;
+
hookDispatcher
.dispatch(
operationId,
diff --git a/apps/server/src/modules/AgentRuntime/buildHost.ts b/apps/server/src/modules/AgentRuntime/buildHost.ts
index 4f8c848548c..310317d4085 100644
--- a/apps/server/src/modules/AgentRuntime/buildHost.ts
+++ b/apps/server/src/modules/AgentRuntime/buildHost.ts
@@ -35,6 +35,7 @@ export const buildHost = (ctx: RuntimeExecutorContext): AgentRuntimeHost => {
? new ServerLifecycleSink(ctx.hookDispatcher, ctx.operationId)
: undefined,
operation: {
+ abortSignal: ctx.abortSignal,
allowEarlyFinalAnswerVisibleOutputEnd: ctx.allowEarlyFinalAnswerVisibleOutputEnd,
operationId: ctx.operationId,
stepIndex: ctx.stepIndex,
diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.ts
index ef9050fa00d..13d369484ed 100644
--- a/apps/server/src/modules/AgentRuntime/context.ts
+++ b/apps/server/src/modules/AgentRuntime/context.ts
@@ -20,6 +20,12 @@ import { type ToolExecutionService } from '@/server/services/toolExecution';
import { type IStreamEventManager } from './types';
export interface RuntimeExecutorContext {
+ /**
+ * Cancels tool work that is still in flight for this step. Driven by the
+ * persisted interruption flag (the step runs in its own invocation, so there
+ * is no in-process controller to share with whoever requested the stop).
+ */
+ abortSignal?: AbortSignal;
agentConfig?: any;
/**
* Allows call_llm to publish visible_output_end immediately after a no-tool
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index d1fb63a36ea..a049be3f4d8 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -1044,6 +1044,94 @@ describe('AgentRuntimeService', () => {
}),
);
});
+
+ it('should resolve pending client tools when interruption races the parked result', async () => {
+ const completedTool = {
+ apiName: 'calculate',
+ arguments: '{}',
+ id: 'completed-server-tool-call',
+ identifier: 'server-tool',
+ type: 'default' as const,
+ };
+ const pendingTool = {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'client-tool-call',
+ identifier: 'client-tool',
+ type: 'default' as const,
+ };
+ const parkedResult = {
+ events: [{ type: 'interrupted' as const }],
+ newState: {
+ ...mockState,
+ messages: [
+ {
+ content: 'Completed server result',
+ role: 'tool' as const,
+ tool_call_id: completedTool.id,
+ },
+ ],
+ pendingToolsCalling: [pendingTool],
+ status: 'waiting_for_async_tool' as const,
+ stepCount: 2,
+ },
+ nextContext: undefined,
+ };
+ const resolvedResult = {
+ events: [{ type: 'done' as const }],
+ newState: {
+ ...parkedResult.newState,
+ messages: [
+ ...parkedResult.newState.messages,
+ {
+ content: 'Tool execution was aborted by user.',
+ role: 'tool' as const,
+ tool_call_id: pendingTool.id,
+ },
+ ],
+ status: 'done' as const,
+ },
+ };
+ const mockRuntime = {
+ step: vi.fn().mockResolvedValueOnce(parkedResult).mockResolvedValueOnce(resolvedResult),
+ };
+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });
+ mockCoordinator.loadAgentState
+ .mockResolvedValueOnce(mockState)
+ .mockResolvedValueOnce({ ...mockState, status: 'interrupted' });
+
+ const mixedBatchContext = {
+ ...mockParams.context!,
+ payload: {
+ ...(mockParams.context!.payload as Record<string, unknown>),
+ hasToolsCalling: true,
+ toolsCalling: [completedTool, pendingTool],
+ },
+ phase: 'llm_result' as const,
+ };
+ const result = await service.executeStep({ ...mockParams, context: mixedBatchContext });
+
+ expect(result.state).toEqual(
+ expect.objectContaining({
+ messages: expect.arrayContaining([
+ expect.objectContaining({
+ content: 'Completed server result',
+ tool_call_id: completedTool.id,
+ }),
+ expect.objectContaining({ tool_call_id: pendingTool.id }),
+ ]),
+ status: 'interrupted',
+ }),
+ );
+ expect(mockRuntime.step).toHaveBeenCalledTimes(2);
+ expect(mockRuntime.step).toHaveBeenLastCalledWith(
+ expect.objectContaining({ status: 'interrupted' }),
+ expect.objectContaining({
+ payload: expect.objectContaining({ toolsCalling: [pendingTool] }),
+ phase: 'llm_result',
+ }),
+ );
+ });
});
describe('executeStep - tool result extraction', () => {
@@ -1634,6 +1722,14 @@ describe('AgentRuntimeService', () => {
expect(shouldContinue).toBe(false);
});
+ it('should return false for a plain interrupt with nothing left to settle', () => {
+ const shouldContinue = (service as any).shouldContinueExecution(
+ { status: 'interrupted' },
+ { phase: 'tool_result' },
+ );
+ expect(shouldContinue).toBe(false);
+ });
+
it('should return false when waiting for human input', () => {
const shouldContinue = (service as any).shouldContinueExecution(
{ status: 'waiting_for_human' },
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 2feaf333bd7..a20c35012b0 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -133,6 +133,14 @@ const ASYNC_TOOL_VERIFY_MAX_ATTEMPTS = 5;
const ASYNC_TOOL_VERIFY_MAX_DELAY_MS = 240_000;
const STEP_LOCK_TTL_SECONDS = 120;
+/**
+ * How often a live step re-reads its own operation state to notice an
+ * interrupt. Interrupts are persisted by a different invocation, so this poll
+ * is the only way a running tool learns it should stop.
+ */
+const STEP_ABORT_POLL_INTERVAL_MS = 2_000;
+/** Cap on the exponential backoff multiplier after consecutive poll failures. */
+const STEP_ABORT_POLL_MAX_BACKOFF = 8;
const STEP_LOCK_HEARTBEAT_MS = 30_000;
const EVAL_TOOL_FORWARDING_HOOK_ID = 'eval-tool-forwarding';
@@ -1010,6 +1018,14 @@ export class AgentRuntimeService {
stepLockOwner,
);
+ // Hoisted so the shared `finally` can stop it on every exit path β€” an
+ // orphaned interval would keep polling Redis for a step that is long gone.
+ let stepAbortPoll: ReturnType<typeof setTimeout> | undefined;
+ // Clearing the timeout is not enough: a poll already awaiting the state read
+ // would schedule the next one after the step is gone, leaking a loop that
+ // re-reads the store forever for a finished operation.
+ let stepAbortPollStopped = false;
+
// Hoisted so the error-path snapshot finalize can record an
// approximate startedAt for the failing step. The inner `startAt` at the
// runtime.step() call site stays as the authoritative start for the
@@ -1189,7 +1205,43 @@ export class AgentRuntimeService {
// Create Agent and Runtime instances
// Use agentState.metadata which contains the full app context (topicId, agentId, etc.)
// operationMetadata only contains basic fields (agentConfig, modelRuntimeConfig, userId)
+ // Interrupts arrive as a flag on the persisted state β€” the request that
+ // asked for the stop runs in a different invocation, so there is no
+ // in-process controller to share. Poll for it while the step is alive
+ // and cancel locally, otherwise a multi-minute tool would keep running
+ // long after the user asked it to stop.
+ const stepAbortController = new AbortController();
+ // Serialized on purpose: `setInterval` would fire a new read without
+ // waiting for the last one, so a slow or failing state store turns every
+ // concurrent run into a growing pile of overlapping requests β€” the load
+ // spikes exactly when the store is already struggling. Each read is
+ // scheduled only after the previous one settles, and failures back off.
+ let abortPollFailures = 0;
+ const pollForAbort = async () => {
+ try {
+ const latest = await this.coordinator.loadAgentState(operationId);
+ abortPollFailures = 0;
+ if (latest?.status === 'interrupted') {
+ stepAbortController.abort();
+ return;
+ }
+ } catch (error) {
+ abortPollFailures += 1;
+ log('[%s][%d] Abort poll failed: %O', operationId, stepIndex, error);
+ }
+
+ if (stepAbortPollStopped || stepAbortController.signal.aborted) return;
+
+ stepAbortPoll = setTimeout(
+ pollForAbort,
+ STEP_ABORT_POLL_INTERVAL_MS *
+ Math.min(2 ** abortPollFailures, STEP_ABORT_POLL_MAX_BACKOFF),
+ );
+ };
+ stepAbortPoll = setTimeout(pollForAbort, STEP_ABORT_POLL_INTERVAL_MS);
+
const { runtime } = await this.createAgentRuntime({
+ abortSignal: stepAbortController.signal,
agentState,
metadata: agentState?.metadata,
operationId,
@@ -1291,7 +1343,7 @@ export class AgentRuntimeService {
forcedFinish: Boolean(forcedFinishState),
stateStatus: currentState.status,
}));
- const stepResult = forcedFinishState
+ let stepResult = forcedFinishState
? { events: [], newState: forcedFinishState, nextContext: undefined }
: await runtime.step(currentState, currentContext);
@@ -1317,6 +1369,34 @@ export class AgentRuntimeService {
interrupted: latestState?.status === 'interrupted',
}));
if (latestState?.status === 'interrupted') {
+ // Stop can be persisted after a client-tool executor's last local
+ // signal check but before this reconciliation read. If that executor
+ // just returned a parked state, run the agent's existing abort path
+ // once so every pending tool call gets a terminal row before the
+ // interrupted state is saved.
+ if (
+ stepResult.newState.status === 'waiting_for_async_tool' &&
+ stepResult.newState.pendingToolsCalling?.length &&
+ currentContext
+ ) {
+ const interruptedState = structuredClone(stepResult.newState);
+ interruptedState.status = 'interrupted';
+ const abortContext: AgentRuntimeContext = {
+ ...currentContext,
+ payload: {
+ ...(currentContext.payload as Record<string, unknown>),
+ hasToolsCalling: true,
+ toolsCalling: interruptedState.pendingToolsCalling,
+ },
+ phase: 'llm_result',
+ };
+ const abortResult = await runtime.step(interruptedState, abortContext);
+ stepResult = {
+ ...abortResult,
+ events: [...stepResult.events, ...abortResult.events],
+ };
+ }
+
stepResult.newState.status = 'interrupted';
stepResult.newState.lastModified = new Date().toISOString();
log('[%s][%d] Operation was interrupted during step execution', operationId, stepIndex);
@@ -1745,6 +1825,8 @@ export class AgentRuntimeService {
throw error;
} finally {
invokeAgentSpan.end();
+ stepAbortPollStopped = true;
+ if (stepAbortPoll) clearTimeout(stepAbortPoll);
stopStepLockHeartbeat();
await this.coordinator.releaseStepLock(operationId, stepIndex, stepLockOwner);
}
@@ -2906,12 +2988,15 @@ export class AgentRuntimeService {
* Create Agent Runtime instance
*/
private async createAgentRuntime({
+ abortSignal,
agentState,
metadata,
operationId,
stepIndex,
tracingContextEngine,
}: {
+ /** Cancels in-flight tool work when this step's operation is interrupted. */
+ abortSignal?: AbortSignal;
/**
* Current runtime state, when the caller has it. Only consulted to decide
* whether the early final-answer `visible_output_end` must be suppressed
@@ -2965,6 +3050,7 @@ export class AgentRuntimeService {
// Create streaming executor context
const executorContext: RuntimeExecutorContext = {
+ abortSignal,
agentConfig: metadata?.agentConfig,
// The factory may be a Graph-aware dispatcher that still returns the
// default agent for ordinary conversations. Keep the early visible
diff --git a/packages/agent-runtime/src/executors/abortedToolRows.ts b/packages/agent-runtime/src/executors/abortedToolRows.ts
new file mode 100644
index 00000000000..a84499b35ec
--- /dev/null
+++ b/packages/agent-runtime/src/executors/abortedToolRows.ts
@@ -0,0 +1,151 @@
+import type { ChatToolPayload } from '@lobechat/types';
+
+import type { AgentRuntimeHost } from '../transport';
+import type { AgentState } from '../types';
+
+export const ABORTED_TOOL_CONTENT = 'Tool execution was aborted by user.';
+
+const TOOL_MESSAGE_PERSIST_PHASE = 'tool_message_persist';
+
+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';
+};
+
+export const publishPersistError = async (host: AgentRuntimeHost, error: unknown) => {
+ const { stepIndex } = host.operation;
+
+ if (host.transports.stream.publishError) {
+ await host.transports.stream.publishError({
+ error,
+ phase: TOOL_MESSAGE_PERSIST_PHASE,
+ stepIndex,
+ });
+ return;
+ }
+
+ await host.transports.stream.publishEvent({
+ data: {
+ error: getErrorMessage(error),
+ errorType: getErrorType(error),
+ phase: TOOL_MESSAGE_PERSIST_PHASE,
+ },
+ stepIndex,
+ type: 'error',
+ });
+};
+
+/**
+ * Close out tool calls that will never produce a result.
+ *
+ * Every `tool_call_id` the assistant asked for must end up with exactly one
+ * tool row. The assistant message is already persisted, so a call left without
+ * one puts the conversation in a shape no provider accepts on the next
+ * `call_llm` β€” and, before that, leaves an approval card that outlives the Stop
+ * meant to clear it.
+ *
+ * Shared by the two moments that produce such calls: `resolve_aborted_tools`
+ * (calls that never started β€” fresh off the LLM stream, or parked pending
+ * approval) and the tool executors themselves (calls that were mid-flight when
+ * an abort landed, which settle inline rather than deferring to another step).
+ */
+export const settleAbortedToolRows = async ({
+ existingToolMessageIds,
+ host,
+ parentMessageId,
+ state,
+ toolsCalling,
+}: {
+ existingToolMessageIds?: Record<string, string>;
+ host: AgentRuntimeHost;
+ parentMessageId: string;
+ state: AgentState;
+ toolsCalling: ChatToolPayload[];
+}): Promise<{
+ /** `tool_call_id β†’ the row that now holds its aborted result`. */
+ messageIds: Record<string, string>;
+ /** Tool messages to append to `state.messages`, in call order. */
+ messages: Array<{ content: string; role: 'tool'; tool_call_id: string }>;
+}> => {
+ const { operation, transports } = host;
+ const agentId = operation.agentId ?? state.metadata?.agentId;
+ const groupId = operation.groupId ?? state.metadata?.groupId;
+ const threadId = operation.threadId ?? state.metadata?.threadId;
+ const topicId = operation.topicId ?? state.metadata?.topicId;
+
+ if (!agentId) {
+ throw new Error(
+ `[settleAbortedToolRows] Missing agentId for tool messages (op=${operation.operationId})`,
+ );
+ }
+
+ const messageIds: Record<string, string> = {};
+ const messages: Array<{ content: string; role: 'tool'; tool_call_id: string }> = [];
+
+ for (const toolPayload of toolsCalling) {
+ // Prefer an ID carried by the approval resume: its `parentMessageId` is the
+ // tool row itself, so using it as lookup scope would miss the row's real
+ // assistant parent. Other paths cannot reliably know whether a row exists,
+ // so the scoped indexed read keeps the invariant for them.
+ const existingMessageId =
+ existingToolMessageIds?.[toolPayload.id] ??
+ (await transports.messages.findToolMessageIdByToolCallId(toolPayload.id, parentMessageId));
+ try {
+ if (existingMessageId) {
+ // Settle THAT row: inserting a second one would duplicate the tool in
+ // the turn and leave the original `pending`, so the approval card
+ // outlives the Stop that was supposed to clear it.
+ await transports.messages.updateToolMessage(existingMessageId, {
+ content: ABORTED_TOOL_CONTENT,
+ });
+ await transports.messages.updateToolIntervention(existingMessageId, {
+ status: 'aborted',
+ });
+ messageIds[toolPayload.id] = existingMessageId;
+ } else {
+ const created = await transports.messages.createToolMessage({
+ agentId,
+ content: ABORTED_TOOL_CONTENT,
+ groupId,
+ parentId: parentMessageId,
+ plugin: toolPayload as any,
+ pluginIntervention: { status: 'aborted' },
+ role: 'tool',
+ threadId,
+ tool_call_id: toolPayload.id,
+ topicId,
+ });
+ messageIds[toolPayload.id] = created.id;
+ }
+ } catch (error) {
+ await publishPersistError(host, error);
+ throw error;
+ }
+
+ messages.push({
+ content: ABORTED_TOOL_CONTENT,
+ role: 'tool',
+ tool_call_id: toolPayload.id,
+ });
+ }
+
+ return { messageIds, messages };
+};
diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.ts
index 3a741085b2b..4fff8ca945a 100644
--- a/packages/agent-runtime/src/executors/callLlm.test.ts
+++ b/packages/agent-runtime/src/executors/callLlm.test.ts
@@ -70,6 +70,7 @@ const createMessageTransport = (): MessageTransport => ({
createToolMessage: vi.fn(),
deleteMessage: vi.fn(),
findById: vi.fn().mockResolvedValue({ id: 'parent-1' }),
+ findToolMessageIdByToolCallId: 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.ts
index 2b397ba630f..39ab3bb016c 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
@@ -18,6 +18,7 @@ const createMessageTransport = (): MessageTransport => ({
createToolMessage: vi.fn(),
deleteMessage: vi.fn(),
findById: vi.fn(),
+ findToolMessageIdByToolCallId: vi.fn(),
query: vi.fn(),
update: vi.fn().mockResolvedValue(undefined),
updatePluginState: vi.fn(),
diff --git a/packages/agent-runtime/src/executors/resolveTools.test.ts b/packages/agent-runtime/src/executors/resolveTools.test.ts
index 1abb51eb1fd..27d3f1128bb 100644
--- a/packages/agent-runtime/src/executors/resolveTools.test.ts
+++ b/packages/agent-runtime/src/executors/resolveTools.test.ts
@@ -48,12 +48,27 @@ const createToolCall = (id = 'tool-call-1') => ({
describe('resolveTools executors', () => {
let createToolMessage: ReturnType<typeof vi.fn>;
+ let findToolMessageIdByToolCallId: ReturnType<typeof vi.fn>;
+ /** `tool_call_id β†’ row id` the store already holds. */
+ let toolRows: Map<string, { id: string; parentId: string }>;
let publishError: ReturnType<typeof vi.fn>;
let publishEvent: ReturnType<typeof vi.fn>;
let host: AgentRuntimeHost;
beforeEach(() => {
- createToolMessage = vi.fn().mockResolvedValue({ id: 'tool-msg-1' });
+ 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;
+ });
publishError = vi.fn().mockResolvedValue(undefined);
publishEvent = vi.fn().mockResolvedValue(undefined);
@@ -68,6 +83,7 @@ describe('resolveTools executors', () => {
createToolMessage,
deleteMessage: vi.fn(),
findById: vi.fn(),
+ findToolMessageIdByToolCallId,
query: vi.fn(),
update: vi.fn(),
updatePluginState: vi.fn(),
@@ -216,11 +232,14 @@ describe('resolveTools executors', () => {
const updateToolIntervention = vi.fn().mockResolvedValue(undefined);
host.transports.messages.updateToolMessage = updateToolMessage;
host.transports.messages.updateToolIntervention = updateToolIntervention;
+ // A single approval resume uses the pending row itself as parentMessageId,
+ // while the row's real parent remains the assistant that requested it.
+ toolRows.set('tool-call-1', { id: 'pending-msg-1', parentId: 'assistant-msg-1' });
const instruction: Extract<AgentInstruction, { type: 'resolve_aborted_tools' }> = {
payload: {
existingToolMessageIds: { 'tool-call-1': 'pending-msg-1' },
- parentMessageId: 'assistant-msg-1',
+ parentMessageId: 'pending-msg-1',
toolsCalling: [createToolCall('tool-call-1'), createToolCall('tool-call-2')],
},
type: 'resolve_aborted_tools',
@@ -232,6 +251,8 @@ describe('resolveTools executors', () => {
content: 'Tool execution was aborted by user.',
});
expect(updateToolIntervention).toHaveBeenCalledWith('pending-msg-1', { status: 'aborted' });
+ expect(findToolMessageIdByToolCallId).toHaveBeenCalledTimes(1);
+ expect(findToolMessageIdByToolCallId).toHaveBeenCalledWith('tool-call-2', 'pending-msg-1');
// The call with no existing row still gets one created β€” mixed batches are
// resolved per call, not all-or-nothing.
diff --git a/packages/agent-runtime/src/executors/resolveTools.ts b/packages/agent-runtime/src/executors/resolveTools.ts
index 658c846ac64..9f6664a6359 100644
--- a/packages/agent-runtime/src/executors/resolveTools.ts
+++ b/packages/agent-runtime/src/executors/resolveTools.ts
@@ -6,64 +6,17 @@ import type {
AgentState,
InstructionExecutor,
} from '../types';
+import { publishPersistError, settleAbortedToolRows } from './abortedToolRows';
const BLOCKED_TOOL_CONTENT = 'Blocked by security/privacy.';
const BLOCKED_TOOL_ERROR = 'blocked_by_security_privacy';
-const ABORTED_TOOL_CONTENT = 'Tool execution was aborted by user.';
const USER_ABORTED_REASON = 'user_aborted';
const USER_ABORTED_REASON_DETAIL = 'User aborted operation with pending tool calls';
-const TOOL_MESSAGE_PERSIST_PHASE = 'tool_message_persist';
type RuntimeSessionWithEventCount = NonNullable<AgentRuntimeContext['session']> & {
eventCount?: number;
};
-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 publishPersistError = async (host: AgentRuntimeHost, error: unknown) => {
- const { stepIndex } = host.operation;
-
- if (host.transports.stream.publishError) {
- await host.transports.stream.publishError({
- error,
- phase: TOOL_MESSAGE_PERSIST_PHASE,
- stepIndex,
- });
- return;
- }
-
- await host.transports.stream.publishEvent({
- data: {
- error: getErrorMessage(error),
- errorType: getErrorType(error),
- phase: TOOL_MESSAGE_PERSIST_PHASE,
- },
- stepIndex,
- type: 'error',
- });
-};
-
const createSession = (state: AgentState, operationId: string): RuntimeSessionWithEventCount => ({
messageCount: state.messages.length,
sessionId: operationId,
@@ -186,18 +139,10 @@ export const resolveAbortedTools =
async (instruction, state) => {
const { payload } = instruction as Extract<AgentInstruction, { type: 'resolve_aborted_tools' }>;
const { operation, transports } = host;
- const agentId = operation.agentId ?? state.metadata?.agentId;
- const groupId = operation.groupId ?? state.metadata?.groupId;
- const threadId = operation.threadId ?? state.metadata?.threadId;
- const topicId = operation.topicId ?? state.metadata?.topicId;
+ // Message ownership (agentId / groupId / threadId / topicId) is resolved by
+ // `settleAbortedToolRows`, which owns the row writes for every abort source.
const events: AgentEvent[] = [];
- if (!agentId) {
- throw new Error(
- `[resolve_aborted_tools] Missing agentId for tool messages (op=${operation.operationId})`,
- );
- }
-
await transports.stream.publishEvent({
data: {
parentMessageId: payload.parentMessageId,
@@ -210,47 +155,14 @@ export const resolveAbortedTools =
const newState = structuredClone(state);
- const existingToolMessageIds = payload.existingToolMessageIds ?? {};
-
- for (const toolPayload of payload.toolsCalling) {
- const existingMessageId = existingToolMessageIds[toolPayload.id];
- try {
- if (existingMessageId) {
- // The approval pause already wrote a row for this call. Settle THAT
- // row: inserting a second one would duplicate the tool in the turn
- // and leave the original `pending`, so the approval card survives the
- // Stop that was supposed to clear it.
- await transports.messages.updateToolMessage(existingMessageId, {
- content: ABORTED_TOOL_CONTENT,
- });
- await transports.messages.updateToolIntervention(existingMessageId, {
- status: 'aborted',
- });
- } else {
- await transports.messages.createToolMessage({
- agentId,
- content: ABORTED_TOOL_CONTENT,
- groupId,
- parentId: payload.parentMessageId,
- plugin: toolPayload as any,
- pluginIntervention: { status: 'aborted' },
- role: 'tool',
- threadId,
- tool_call_id: toolPayload.id,
- topicId,
- });
- }
- } catch (error) {
- await publishPersistError(host, error);
- throw error;
- }
-
- newState.messages.push({
- content: ABORTED_TOOL_CONTENT,
- role: 'tool',
- tool_call_id: toolPayload.id,
- });
- }
+ const { messages } = await settleAbortedToolRows({
+ existingToolMessageIds: payload.existingToolMessageIds,
+ host,
+ parentMessageId: payload.parentMessageId,
+ state,
+ toolsCalling: payload.toolsCalling,
+ });
+ newState.messages.push(...messages);
newState.lastModified = new Date().toISOString();
newState.status = 'done';
diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.ts
index 4d4353c3021..5a1fc06390f 100644
--- a/packages/agent-runtime/src/executors/tool.test.ts
+++ b/packages/agent-runtime/src/executors/tool.test.ts
@@ -52,6 +52,15 @@ const createToolCall = (id = 'tool-call-1', identifier = 'web-search') => ({
describe('tool executors', () => {
let createToolMessage: ReturnType<typeof vi.fn>;
+ let findToolMessageIdByToolCallId: ReturnType<typeof vi.fn>;
+ 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>;
@@ -60,7 +69,21 @@ describe('tool executors', () => {
let host: AgentRuntimeHost;
beforeEach(() => {
- createToolMessage = vi.fn().mockResolvedValue({ id: 'tool-msg-1' });
+ 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);
@@ -86,10 +109,12 @@ describe('tool executors', () => {
createToolMessage,
deleteMessage: vi.fn(),
findById: vi.fn(),
+ findToolMessageIdByToolCallId,
query,
update: vi.fn(),
updatePluginState: vi.fn(),
- updateToolMessage: vi.fn(),
+ updateToolIntervention,
+ updateToolMessage,
},
stream: {
publishChunk,
@@ -218,7 +243,7 @@ describe('tool executors', () => {
expect(result.nextContext?.payload).toMatchObject({ parentMessageId: 'client-tool-msg' });
});
- it('does not advance after the transport reports cancellation', async () => {
+ it('settles the existing row when the transport reports cancellation', async () => {
runTool.mockResolvedValueOnce({
attempts: 0,
interrupted: true,
@@ -226,16 +251,300 @@ describe('tool executors', () => {
resultPersisted: true,
toolMessageId: 'cancelled-tool-msg',
});
+ const toolCall = createToolCall();
+ toolRows.set(toolCall.id, { id: 'cancelled-tool-msg', parentId: 'assistant-msg-1' });
const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
- payload: { parentMessageId: 'assistant-msg-1', toolCalling: createToolCall() },
+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: toolCall },
+ type: 'call_tool',
+ };
+
+ const result = await callTool(host)(instruction, createState());
+
+ // The transport already made a row for this call β€” settle THAT one rather
+ // than inserting a second one beside it.
+ expect(createToolMessage).not.toHaveBeenCalled();
+ expect(updateToolMessage).toHaveBeenCalledWith('cancelled-tool-msg', {
+ content: 'Tool execution was aborted by user.',
+ });
+ expect(updateToolIntervention).toHaveBeenCalledWith('cancelled-tool-msg', {
+ status: 'aborted',
+ });
+ expect(result.newState.messages).toContainEqual(
+ expect.objectContaining({ role: 'tool', tool_call_id: toolCall.id }),
+ );
+ });
+
+ it('writes an aborted row when the operation aborts mid-run', async () => {
+ const controller = new AbortController();
+ const abortingHost = {
+ ...host,
+ operation: { ...host.operation, abortSignal: controller.signal },
+ } as typeof host;
+
+ runTool.mockImplementationOnce(
+ () =>
+ new Promise(() => {
+ // never settles β€” the abort is what ends the wait
+ }),
+ );
+
+ const toolCall = createToolCall();
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: toolCall },
+ type: 'call_tool',
+ };
+
+ const pending = callTool(abortingHost)(instruction, createState());
+ controller.abort();
+ const result = await pending;
+
+ // Every tool_call_id gets exactly one row, even one that never returned.
+ expect(createToolMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: 'Tool execution was aborted by user.',
+ parentId: 'assistant-msg-1',
+ pluginIntervention: { status: 'aborted' },
+ role: 'tool',
+ tool_call_id: toolCall.id,
+ }),
+ );
+ expect(result.newState.messages).toContainEqual(
+ expect.objectContaining({ role: 'tool', tool_call_id: toolCall.id }),
+ );
+ // An abort is not a tool failure: no error event, no handleError bookkeeping.
+ expect(result.events).toEqual([]);
+ expect(host.transports.tools!.handleError).not.toHaveBeenCalled();
+ // Whether the run ends is the caller's call β€” a user Stop persists
+ // `interrupted` on its own; this executor must not decide it.
+ expect(result.newState.status).toBe('running');
+ });
+
+ it('observes a late transport rejection after a synchronous abort', async () => {
+ const controller = new AbortController();
+ const abortingHost = {
+ ...host,
+ operation: { ...host.operation, abortSignal: controller.signal },
+ } as typeof host;
+ let rejectTransport: ((error: Error) => void) | undefined;
+ runTool.mockImplementationOnce(() => {
+ controller.abort();
+ return new Promise((_, reject) => {
+ rejectTransport = reject;
+ });
+ });
+
+ const toolCall = createToolCall();
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: toolCall },
+ type: 'call_tool',
+ };
+
+ const result = await callTool(abortingHost)(instruction, createState());
+ rejectTransport!(new Error('transport failed after abort'));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(result.newState.messages).toContainEqual(
+ expect.objectContaining({ role: 'tool', tool_call_id: toolCall.id }),
+ );
+ expect(host.transports.tools!.handleError).not.toHaveBeenCalled();
+ });
+
+ it('never starts a tool when the signal is already aborted', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ const abortingHost = {
+ ...host,
+ operation: { ...host.operation, abortSignal: controller.signal },
+ } as typeof host;
+
+ const toolCall = createToolCall();
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: toolCall },
+ type: 'call_tool',
+ };
+
+ const result = await callTool(abortingHost)(instruction, createState());
+
+ // No transport ever inspects `context.abortSignal` before doing its work, so
+ // launching it here would spawn the process Stop was meant to prevent.
+ expect(runTool).not.toHaveBeenCalled();
+ expect(createToolMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: 'Tool execution was aborted by user.',
+ tool_call_id: toolCall.id,
+ }),
+ );
+ expect(result.newState.messages).toContainEqual(
+ expect.objectContaining({ role: 'tool', tool_call_id: toolCall.id }),
+ );
+ });
+
+ it('settles the pending approval row when an approved tool is aborted', async () => {
+ const controller = new AbortController();
+ const abortingHost = {
+ ...host,
+ operation: { ...host.operation, abortSignal: controller.signal },
+ } as typeof host;
+
+ runTool.mockImplementationOnce(
+ () =>
+ new Promise(() => {
+ // never settles β€” the abort is what ends the wait
+ }),
+ );
+
+ const toolCall = createToolCall();
+ // The approval pause wrote this row before parking.
+ toolRows.set(toolCall.id, { id: 'pending-tool-row', parentId: 'assistant-msg-1' });
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: {
+ // On an approval resume this IS the pending tool row, not an assistant.
+ parentMessageId: 'pending-tool-row',
+ skipCreateToolMessage: true,
+ toolCalling: toolCall,
+ },
+ type: 'call_tool',
+ };
+
+ const pending = callTool(abortingHost)(instruction, createState());
+ controller.abort();
+ await pending;
+
+ // Creating a row here would duplicate the tool_call_id, strand the approval
+ // card as `pending`, and parent a tool row to another tool row.
+ expect(createToolMessage).not.toHaveBeenCalled();
+ expect(updateToolMessage).toHaveBeenCalledWith('pending-tool-row', {
+ content: 'Tool execution was aborted by user.',
+ });
+ expect(updateToolIntervention).toHaveBeenCalledWith('pending-tool-row', {
+ status: 'aborted',
+ });
+ expect(findToolMessageIdByToolCallId).not.toHaveBeenCalled();
+ });
+
+ it('settles a client-only call 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 toolCall = createToolCall('client-call', 'client-tool');
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: toolCall },
+ type: 'call_tool',
+ };
+
+ const result = await callTool(abortingHost)(
+ instruction,
+ createState({ toolSourceMap: { 'client-tool': 'client' as any } }),
+ );
+
+ // Nothing will come back to collect a parked call in an aborted run.
+ expect(publishChunk).not.toHaveBeenCalled();
+ expect(createToolMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: 'Tool execution was aborted by user.',
+ tool_call_id: toolCall.id,
+ }),
+ );
+ expect(result.newState.messages).toContainEqual(
+ expect.objectContaining({ role: 'tool', tool_call_id: toolCall.id }),
+ );
+ });
+
+ it('settles a client-only call 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 toolCall = createToolCall('client-call', 'client-tool');
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: toolCall },
+ type: 'call_tool',
+ };
+
+ const pending = callTool(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).toContainEqual(
+ expect.objectContaining({ role: 'tool', tool_call_id: toolCall.id }),
+ );
+ expect(createToolMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('treats an unrelated AbortError as a tool failure, not a user stop', async () => {
+ // The operation signal is live β€” this rejection is the transport's own
+ // timeout, so it must keep normal error handling and must NOT persist a row
+ // claiming the user aborted it.
+ const foreign = new Error('fetch timed out');
+ foreign.name = 'AbortError';
+ runTool.mockRejectedValueOnce(foreign);
+
+ const toolCall = createToolCall();
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: toolCall },
+ type: 'call_tool',
+ };
+
+ const result = await callTool(host)(instruction, createState());
+
+ expect(host.transports.tools!.handleError).toHaveBeenCalled();
+ expect(publishError).toHaveBeenCalled();
+ expect(result.events).toContainEqual(expect.objectContaining({ type: 'error' }));
+ expect(createToolMessage).not.toHaveBeenCalledWith(
+ expect.objectContaining({ content: 'Tool execution was aborted by user.' }),
+ );
+ });
+
+ it('settles the row the transport already created when a client tool is aborted', async () => {
+ const controller = new AbortController();
+ const abortingHost = {
+ ...host,
+ operation: { ...host.operation, abortSignal: controller.signal },
+ } as typeof host;
+
+ // The client transport persists its row before executing, and only surfaces
+ // the id through a settled run β€” which an abort never gives us.
+ const toolCall = createToolCall();
+ runTool.mockImplementationOnce(
+ () =>
+ new Promise(() => {
+ // The client transport persists its row before executing, so by the
+ // time the abort lands the store already knows about it.
+ toolRows.set(toolCall.id, { id: 'optimistic-row', parentId: 'assistant-msg-1' });
+ controller.abort();
+ }),
+ );
+
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: toolCall },
type: 'call_tool',
};
- const state = createState();
- const result = await callTool(host)(instruction, state);
+ await callTool(abortingHost)(instruction, createState());
- expect(result).toEqual({ events: [], newState: state });
expect(createToolMessage).not.toHaveBeenCalled();
+ expect(updateToolMessage).toHaveBeenCalledWith('optimistic-row', {
+ content: 'Tool execution was aborted by user.',
+ });
});
it('terminates removed client sub-agent stop states like other stop results', async () => {
@@ -465,6 +774,234 @@ describe('tool executors', () => {
});
});
+ 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
diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.ts
index ca46869cc4e..d194e373cdc 100644
--- a/packages/agent-runtime/src/executors/tool.ts
+++ b/packages/agent-runtime/src/executors/tool.ts
@@ -15,6 +15,7 @@ import type {
InstructionExecutor,
} from '../types';
import { extractActivatedSkillsFromMessages, extractTodosFromMessages } from '../utils';
+import { settleAbortedToolRows } from './abortedToolRows';
const TOOL_EXECUTION_PHASE = 'tool_execution';
const TOOL_MESSAGE_PERSIST_PHASE = 'tool_message_persist';
@@ -158,6 +159,7 @@ const createRunContext = ({
{ chatConfig?: { toolResultMaxLength?: number } } | undefined;
return {
+ abortSignal: host.operation.abortSignal,
activatedSkills: extractActivatedSkillsFromMessages(state.messages),
agentId: host.operation.agentId ?? state.metadata?.agentId,
assistantMessageId: parentMessageId,
@@ -188,6 +190,123 @@ const createRunContext = ({
};
};
+class ToolAbortedError extends Error {
+ constructor() {
+ super('Tool execution aborted');
+ this.name = 'AbortError';
+ }
+}
+
+/**
+ * Did this rejection come from the operation being aborted?
+ *
+ * Name-matching alone is wrong: a transport's own fetch timeout or an internal
+ * cancellation also rejects with `AbortError`, and treating that as "the user
+ * pressed Stop" would swallow `handleError`, drop the error telemetry, and
+ * persist a row claiming the user aborted a tool that actually failed.
+ *
+ * Our sentinel is definitive. A foreign `AbortError` only counts when the
+ * operation signal is genuinely aborted β€” that is a transport honouring the
+ * signal we handed it, which is the same event by another route.
+ */
+const isOperationAbort = (error: unknown, signal?: AbortSignal): boolean => {
+ if (error instanceof ToolAbortedError) return true;
+
+ return !!signal?.aborted && error instanceof Error && error.name === 'AbortError';
+};
+
+/**
+ * Run a tool, but stop waiting the moment the operation is aborted.
+ *
+ * The transport may keep running in the background β€” work already handed to a
+ * device or a remote process cannot be recalled. What this buys is the step
+ * boundary arriving at once instead of after a multi-minute tool, and the
+ * caller settling the call's row rather than leaving it open forever.
+ */
+const raceToolAbort = async <T>(run: () => Promise<T>, signal?: AbortSignal): Promise<T> => {
+ if (!signal) return run();
+ // Checked BEFORE `run()` β€” taking a thunk rather than a promise is the whole
+ // point. With an already-aborted signal (the poll fired as this executor was
+ // entered) an eagerly-evaluated argument would have launched the tool, and no
+ // transport inspects `context.abortSignal` before starting its own work, so
+ // Stop would still spawn the process and only record an aborted row after.
+ if (signal.aborted) throw new ToolAbortedError();
+
+ const started = run();
+
+ return new Promise<T>((resolve, reject) => {
+ const onAbort = () => reject(new ToolAbortedError());
+ signal.addEventListener('abort', onAbort, { once: true });
+ // Observe the transport before the synchronous-abort recheck below. The
+ // outer race may already be settled, but a started transport can still
+ // reject later and must not surface as an unhandled rejection.
+ started.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));
+ // The signal can fire between `run()` starting and the listener attaching β€”
+ // a transport that aborts from inside its own synchronous setup does exactly
+ // that. Without this re-check the listener is registered too late, nothing
+ // rejects, and a run that never settles hangs the step forever.
+ if (signal.aborted) {
+ reject(new ToolAbortedError());
+ return;
+ }
+ });
+};
+
+/**
+ * Close out one call that an abort caught mid-flight.
+ *
+ * Settled inline, in the same invocation that noticed the abort, rather than
+ * handed to a later step: everything needed is already here, and a follow-up
+ * step is exactly what cannot be relied on once a run is being torn down.
+ * `status` deliberately stays as-is β€” whether the run ends is the caller's
+ * decision (a user Stop persists `interrupted` independently), not this
+ * executor's.
+ */
+const settleAbortedCall = async ({
+ events,
+ existingToolMessageId,
+ host,
+ parentMessageId,
+ state,
+ tool,
+}: {
+ events: AgentEvent[];
+ existingToolMessageId?: string;
+ host: AgentRuntimeHost;
+ parentMessageId: string;
+ state: AgentState;
+ tool: ChatToolPayload;
+}) => {
+ const settled = await settleAbortedToolRows({
+ existingToolMessageIds: existingToolMessageId
+ ? { [tool.id]: existingToolMessageId }
+ : undefined,
+ host,
+ parentMessageId,
+ state,
+ toolsCalling: [tool],
+ });
+
+ const newState = structuredClone(state);
+ newState.messages.push(...settled.messages);
+ newState.lastModified = nowIso();
+
+ return {
+ events,
+ newState,
+ nextContext: {
+ payload: { parentMessageId: settled.messageIds[tool.id] ?? parentMessageId },
+ phase: 'tool_result' as const,
+ session: {
+ messageCount: newState.messages.length,
+ sessionId: host.operation.operationId,
+ status: newState.status,
+ stepCount: state.stepCount + 1,
+ },
+ },
+ };
+};
+
const publishError = async (host: AgentRuntimeHost, error: unknown, phase: string) => {
const { stepIndex } = host.operation;
@@ -395,20 +514,69 @@ export const callTool =
});
if (runContext.toolSource === 'client' && !tools.canRunClientTools) {
- return pauseForTools({
+ // Parking is only meaningful if something will come back for it. Once the
+ // operation is aborted nothing resumes this run, so the pause would leave
+ // the call with no row at all β€” settle it instead.
+ if (host.operation.abortSignal?.aborted) {
+ return settleAbortedCall({
+ events,
+ existingToolMessageId: payload.skipCreateToolMessage
+ ? payload.parentMessageId
+ : undefined,
+ host,
+ parentMessageId: payload.parentMessageId,
+ state,
+ tool,
+ });
+ }
+
+ const paused = await pauseForTools({
host,
instruction,
reason: 'client_tool_execution',
state,
toolsCalling: [tool],
});
+
+ // Stop can arrive while the chunk is being published. Do not return a
+ // parked state after that asynchronous gap: no client result will ever
+ // resume an operation that has already been interrupted.
+ if (host.operation.abortSignal?.aborted) {
+ return settleAbortedCall({
+ events,
+ existingToolMessageId: payload.skipCreateToolMessage
+ ? payload.parentMessageId
+ : undefined,
+ host,
+ parentMessageId: payload.parentMessageId,
+ state,
+ tool,
+ });
+ }
+
+ return paused;
}
try {
- const execution = await tools.run(tool, runContext);
+ const execution = await raceToolAbort(
+ () => tools.run(tool, runContext),
+ host.operation.abortSignal,
+ );
if (execution.interrupted) {
- return { events, newState: state };
+ // The transport bailed after creating its optimistic row but before a
+ // result existed. Close the call out here β€” returning `state` untouched
+ // used to strand the tool_call_id with no row at all.
+ return settleAbortedCall({
+ events,
+ existingToolMessageId: payload.skipCreateToolMessage
+ ? payload.parentMessageId
+ : undefined,
+ host,
+ parentMessageId: payload.parentMessageId,
+ state,
+ tool,
+ });
}
if (execution.result.deferred) {
@@ -573,6 +741,21 @@ export const callTool =
} catch (error) {
if (isPersistFatal(error)) throw error;
+ // An abort is not a tool failure: no error row, no retry bookkeeping,
+ // no `handleError`. Just close the call out with an aborted row.
+ if (isOperationAbort(error, host.operation.abortSignal)) {
+ return settleAbortedCall({
+ events,
+ existingToolMessageId: payload.skipCreateToolMessage
+ ? payload.parentMessageId
+ : undefined,
+ host,
+ parentMessageId: payload.parentMessageId,
+ state,
+ tool,
+ });
+ }
+
await tools.handleError?.(tool, error, runContext);
await publishError(host, error, TOOL_EXECUTION_PHASE);
@@ -605,15 +788,55 @@ export const callToolsBatch =
}
if (clientTools.length > 0 && serverTools.length === 0) {
- return pauseForTools({
+ // Same reasoning as the single-call path: an aborted run never comes back
+ // to collect these, so parking them strands every tool_call_id in the batch.
+ if (host.operation.abortSignal?.aborted) {
+ const { messages } = await settleAbortedToolRows({
+ existingToolMessageIds,
+ host,
+ parentMessageId,
+ state,
+ toolsCalling: clientTools,
+ });
+ const abortedState = structuredClone(state);
+ abortedState.messages.push(...messages);
+ abortedState.lastModified = nowIso();
+
+ return { events, newState: abortedState };
+ }
+
+ const paused = await pauseForTools({
host,
reason: 'client_tool_execution',
state,
toolsCalling: clientTools,
});
+
+ if (host.operation.abortSignal?.aborted) {
+ const { messages } = await settleAbortedToolRows({
+ existingToolMessageIds,
+ host,
+ parentMessageId,
+ state,
+ toolsCalling: clientTools,
+ });
+ const abortedState = structuredClone(state);
+ abortedState.messages.push(...messages);
+ abortedState.lastModified = nowIso();
+
+ return { events, newState: abortedState };
+ }
+
+ return paused;
}
const toolResults: ToolResultEntry[] = [];
+ /**
+ * Calls this batch could not settle because the operation was aborted
+ * mid-flight. Tracked separately from `deferredTools` (which are alive and
+ * will call back) β€” these need `aborted` rows before the next `call_llm`.
+ */
+ const abortedTools: ChatToolPayload[] = [];
const deferredTools: ChatToolPayload[] = [];
// `tool_call_id β†’ placeholder message id` for the deferred tools in this batch.
const deferredToolMessageIds: Record<string, string> = {};
@@ -640,7 +863,15 @@ export const callToolsBatch =
});
try {
- const execution = await tools.run(tool, runContext);
+ const execution = await raceToolAbort(
+ () => tools.run(tool, runContext),
+ host.operation.abortSignal,
+ );
+
+ if (execution.interrupted) {
+ abortedTools.push(tool);
+ return;
+ }
if (execution.result.deferred) {
deferredTools.push(tool);
@@ -720,6 +951,14 @@ export const callToolsBatch =
} catch (error) {
if (isPersistFatal(error)) throw error;
+ // Abort is not a tool failure β€” see `callTool`. Siblings that already
+ // finished keep their real results; this one is collected for the
+ // aborted-row settle after the batch.
+ if (isOperationAbort(error, host.operation.abortSignal)) {
+ abortedTools.push(tool);
+ return;
+ }
+
await tools.handleError?.(tool, error, runContext);
await publishError(host, error, TOOL_EXECUTION_PHASE);
@@ -728,6 +967,27 @@ export const callToolsBatch =
}),
);
+ // Client tools in a mixed batch never entered `toolsToExecute` β€” they were
+ // waiting for the pause below to hand them to the client. Once the operation
+ // is aborted that pause parks calls into a run nothing will resume, so their
+ // tool_call_ids would keep no rows at all. Settle them alongside the ones
+ // caught mid-flight, and skip the pause entirely.
+ const aborted = host.operation.abortSignal?.aborted ?? false;
+ const unstartedOnAbort = aborted ? clientTools : [];
+ const toSettle = [...abortedTools, ...unstartedOnAbort];
+
+ // Close out everything the abort left unsettled BEFORE the message refresh
+ // below, so the rows are part of the state this step returns.
+ if (toSettle.length > 0) {
+ await settleAbortedToolRows({
+ existingToolMessageIds,
+ host,
+ parentMessageId,
+ state,
+ toolsCalling: toSettle,
+ });
+ }
+
const newState = structuredClone(state);
// Work-registration intents produced by the tool executions, paired with
// the cumulative cost as of their tool call so the version is inserted ONCE.
@@ -781,7 +1041,10 @@ export const callToolsBatch =
);
newState.lastModified = nowIso();
- const pendingTools = [...deferredTools, ...clientTools];
+ // Deferred tools stay out of this: they are alive elsewhere (device /
+ // sub-agent) with placeholder rows already written, and cancelling them is
+ // a separate concern from settling calls that will never run.
+ const pendingTools = aborted ? deferredTools : [...deferredTools, ...clientTools];
if (pendingTools.length > 0) {
const pauseReason = deferredTools.length > 0 ? 'async_tool' : 'client_tool_execution';
diff --git a/packages/agent-runtime/src/transport/message.ts b/packages/agent-runtime/src/transport/message.ts
index 8691ad3eb22..c48d1e8f82e 100644
--- a/packages/agent-runtime/src/transport/message.ts
+++ b/packages/agent-runtime/src/transport/message.ts
@@ -70,6 +70,26 @@ export interface MessageTransport {
deleteMessage: (id: string) => Promise<void>;
/** Existence / parent preflight; returns the id when present. */
findById: (id: string) => Promise<RuntimeMessageRef | undefined>;
+ /**
+ * The tool row already holding this call, if one exists.
+ *
+ * A call's row can be created by several parties β€” an approval pause, a
+ * transport that pre-creates it so the UI has something to render, an earlier
+ * step. Asking the store is what makes "exactly one row per `tool_call_id`"
+ * hold no matter which of them got there first; the alternative is every
+ * caller having to know the whole history, which is how duplicate rows and
+ * stranded approval cards happen.
+ */
+ findToolMessageIdByToolCallId: (
+ toolCallId: string,
+ /**
+ * The assistant message that made the call. Required scope, not a hint:
+ * `tool_call_id` is provider-supplied and merely indexed, so an unscoped
+ * match can resolve to a reused id from an unrelated turn β€” and this lookup
+ * feeds a write.
+ */
+ parentMessageId: string,
+ ) => Promise<string | 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/transport/operation.ts b/packages/agent-runtime/src/transport/operation.ts
index 5f7d760963e..aecf169fc54 100644
--- a/packages/agent-runtime/src/transport/operation.ts
+++ b/packages/agent-runtime/src/transport/operation.ts
@@ -7,6 +7,15 @@ import type { AgentState } from '../types';
* request; `stepIndex` advances per step.
*/
export interface RuntimeOperationContext {
+ /**
+ * Cancels work that is still in flight for this operation. Executors that
+ * `await` something long (tool runs today) must race it so an interrupt does
+ * not have to wait for the call to finish on its own.
+ *
+ * Client adapter: the operation's own `AbortController`. Server adapter: a
+ * per-step controller driven by the persisted interruption flag.
+ */
+ abortSignal?: AbortSignal;
/** Effective message owner for this operation (group member when applicable). */
agentId?: string;
allowEarlyFinalAnswerVisibleOutputEnd?: boolean;
diff --git a/packages/agent-runtime/src/transport/tool.ts b/packages/agent-runtime/src/transport/tool.ts
index 7eab456a395..af62f0006f9 100644
--- a/packages/agent-runtime/src/transport/tool.ts
+++ b/packages/agent-runtime/src/transport/tool.ts
@@ -82,6 +82,12 @@ export interface ToolRunExecution {
* adapter is constructed β€” NOT passed here β€” so this stays transport-neutral.
*/
export interface ToolRunContext {
+ /**
+ * Forwarded from `RuntimeOperationContext.abortSignal`. Transports that reach
+ * the network (or a device) should thread it into their request so an
+ * interrupt actually stops the work, not just stops waiting for it.
+ */
+ abortSignal?: AbortSignal;
activatedSkills?: unknown[];
activeDeviceId?: string;
agentId?: string;
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index cf150a89141..71581505250 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -3005,13 +3005,38 @@ export class MessageModel {
* time (e.g. the goal loop updating the `createGoal` card via
* `task.context.origin.toolCallId`).
*/
- findToolMessageIdByToolCallId = async (toolCallId: string): Promise<string | null> => {
- const [row] = await this.db
- .select({ id: messagePlugins.id })
- .from(messagePlugins)
- .where(and(eq(messagePlugins.toolCallId, toolCallId), this.pluginsOwnership()))
- .limit(1);
- return row?.id ?? null;
+ findToolMessageIdByToolCallId = async (
+ toolCallId: string,
+ /**
+ * Restrict the match to calls made by one assistant message.
+ *
+ * `tool_call_id` is provider-supplied and only unique in practice β€” the
+ * column carries a plain index, not a unique constraint. Callers that act
+ * on the row (rather than just reading it) should scope the match, or a
+ * reused id from another turn resolves to an unrelated historical result.
+ */
+ parentId?: string,
+ ): Promise<string | null> => {
+ const rows = parentId
+ ? await this.db
+ .select({ id: messagePlugins.id })
+ .from(messagePlugins)
+ .innerJoin(messages, eq(messages.id, messagePlugins.id))
+ .where(
+ and(
+ eq(messagePlugins.toolCallId, toolCallId),
+ eq(messages.parentId, parentId),
+ this.pluginsOwnership(),
+ ),
+ )
+ .limit(1)
+ : await this.db
+ .select({ id: messagePlugins.id })
+ .from(messagePlugins)
+ .where(and(eq(messagePlugins.toolCallId, toolCallId), this.pluginsOwnership()))
+ .limit(1);
+
+ return rows[0]?.id ?? null;
};
/**
diff --git a/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-tool.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-tool.test.ts
index 933286ccfd4..4bdcf0fa441 100644
--- a/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-tool.test.ts
+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-tool.test.ts
@@ -888,7 +888,12 @@ describe('call_tool executor', () => {
// Then - tool execution should be skipped
expect(mockStore.internal_invokeDifferentTypePlugin).not.toHaveBeenCalled();
expect(result.events).toHaveLength(0);
- expect(result.newState).toEqual(state);
+ // ...but the call still has to be closed out. Returning the state
+ // untouched used to leave this tool_call_id with no row at all, which the
+ // assistant that requested it makes invalid for the next LLM call.
+ expect(result.newState.messages).toContainEqual(
+ expect.objectContaining({ content: 'Tool execution was aborted by user.', role: 'tool' }),
+ );
});
it('should check parent abortController signal after message creation', async () => {
@@ -961,8 +966,11 @@ describe('call_tool executor', () => {
// Then
expect(result.events).toHaveLength(0);
- expect(result.newState).toEqual(state);
expect(result.newState.stepCount).toBe(5); // Unchanged
+ // The cancelled call is settled rather than stranded β€” see above.
+ expect(result.newState.messages).toContainEqual(
+ expect.objectContaining({ content: 'Tool execution was aborted by user.', role: 'tool' }),
+ );
});
it('should not create executeToolCall operation if parent cancelled', async () => {
diff --git a/src/store/chat/agents/transports/ClientMessageTransport.ts b/src/store/chat/agents/transports/ClientMessageTransport.ts
index 17d3a282bf6..6c7c0d6b195 100644
--- a/src/store/chat/agents/transports/ClientMessageTransport.ts
+++ b/src/store/chat/agents/transports/ClientMessageTransport.ts
@@ -184,6 +184,23 @@ export class ClientMessageTransport implements MessageTransport {
return message;
}
+ async findToolMessageIdByToolCallId(
+ toolCallId: string,
+ parentMessageId: string,
+ ): Promise<string | undefined> {
+ // Deliberately the store, not the database: client rows are created
+ // optimistically and may not have been persisted yet, so a DB read would
+ // miss exactly the row this lookup exists to find.
+ const match = this.getMessages().find(
+ (message) =>
+ message.role === 'tool' &&
+ message.tool_call_id === toolCallId &&
+ message.parentId === parentMessageId,
+ );
+
+ return match?.id;
+ }
+
private async persist(operations: MessageBatchOperation[]): Promise<void> {
await messageService.batchMutateOrThrow(operations);
}
diff --git a/src/store/chat/agents/transports/buildClientRuntimeHost.ts b/src/store/chat/agents/transports/buildClientRuntimeHost.ts
index 68f0a5d8013..ffcdcb88efa 100644
--- a/src/store/chat/agents/transports/buildClientRuntimeHost.ts
+++ b/src/store/chat/agents/transports/buildClientRuntimeHost.ts
@@ -48,6 +48,10 @@ export const buildClientRuntimeHost = (context: {
return {
operation: {
+ // Same controller Stop already uses for the LLM stream. Threading it here
+ // lets an interrupt end a long-running tool at once instead of waiting
+ // for it to finish on its own.
+ abortSignal: context.get().operations[context.operationId]?.abortController?.signal,
agentId: effectiveAgentId ?? undefined,
groupId: groupId ?? undefined,
operationId: context.operationId,