Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(chat): make Stop end the whole turn, including a tool still running or awaiting approval (#9241)
Thinh Le7ae3f5db59e3
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex 98b9729bd..24614034f 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -145,6 +145,13 @@ type ChatInputProps = {) => voidonStop?: () => voidchatStatus?: ChatStatus+ /**+ * The turn's tools are still running or awaiting approval after the stream+ * ended (`chatStatus` is already `ready`). Stop must stay reachable then: a+ * runaway command otherwise leaves a send arrow and no way to end it. Like+ * `chatStatus`, it queues what the user types until the turn ends.+ */+ toolsRunning?: boolean// Overrides the conversation scope this input belongs to — both its message// queue and its pending attachments (default: useThreads' currentThreadId).// Callers outside the general chat (e.g. Cowork, keyed by session id) pass@@ -254,6 +261,7 @@ const ChatInput = memo(function ChatInput({onSubmit,onStop,chatStatus,+ toolsRunning,scopeKey,ownsToolSet = true,surfaceControls,@@ -673,8 +681,10 @@ const ChatInput = memo(function ChatInput({// Use onSubmit prop if available (AI SDK), otherwise create thread and navigateif (onSubmit) {- // When the model is still streaming, queue the message for later- if (isStreaming && queueId) {+ // While the model is still streaming, or the turn's tools are still+ // running, queue the message for later. The queue waits for the tools, so+ // a second turn never starts under a tool loop that Stop still has to end.+ if ((isStreaming || toolsRunning) && queueId) {useMessageQueue.getState().enqueue(queueId, {id: generateId(),text: effectivePrompt,@@ -2932,7 +2942,7 @@ const ChatInput = memo(function ChatInput({</div>)}- {isStreaming ? (+ {isStreaming || toolsRunning ? (<Tooltip><TooltipTrigger asChild><Buttondiff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsxindex 3a33a90d2..e79be83fe 100644--- a/web-app/src/containers/MessageItem.tsx+++ b/web-app/src/containers/MessageItem.tsx@@ -112,6 +112,15 @@ export const MessageItem = memo(}, [onContinue, message.id])const isStopped = metadata?.stopped === true+ // Continue extends partial text; a turn stopped before it wrote any (a tool+ // call was all it had) has nothing to resume, so offering it would do+ // nothing.+ const canContinue =+ isStopped &&+ message.parts.some(+ (p) =>+ (p.type === 'text' || p.type === 'reasoning') && !!p.text?.trim()+ )const handleEdit = useCallback((newText: string) => {@@ -701,7 +710,7 @@ export const MessageItem = memo(onContinue &&!isStreaming &&isLastMessage &&- isStopped && (+ canContinue && (<Buttonvariant="ghost"size="icon-xs"diff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsxindex c9010d270..e74671069 100644--- a/web-app/src/containers/__tests__/ChatInput.test.tsx+++ b/web-app/src/containers/__tests__/ChatInput.test.tsx@@ -495,6 +495,22 @@ describe('ChatInput', () => {expect(setPromptMock).toHaveBeenCalledWith('')})+ // Tools running means the stream is over (`ready`), but the turn is not: a new+ // message must wait for it like one sent mid-stream.+ it('queues the message while the turn\'s tools are still running', async () => {+ promptState = 'queued msg'+ const onSubmit = vi.fn()+ renderInput({ onSubmit, chatStatus: 'ready', toolsRunning: true })+ fireEvent.keyDown(getTextarea(), { key: 'Enter' })+ await waitFor(() =>+ expect(enqueueMock).toHaveBeenCalledWith(+ 'thread-1',+ expect.objectContaining({ text: 'queued msg' })+ )+ )+ expect(onSubmit).not.toHaveBeenCalled()+ })+it('shows "please select a model" inline message when no model selected', () => {// With no selected model, Enter should set the inline error messageselectedModelOverride = nulldiff --git a/web-app/src/containers/__tests__/MessageItem.test.tsx b/web-app/src/containers/__tests__/MessageItem.test.tsxindex 93f157ce7..514c34338 100644--- a/web-app/src/containers/__tests__/MessageItem.test.tsx+++ b/web-app/src/containers/__tests__/MessageItem.test.tsx@@ -252,6 +252,33 @@ describe('MessageItem', () => {expect(onContinue).toHaveBeenCalledWith('msg-1')})+ // Continue extends partial text; with none there is nothing to resume.+ it('hides Continue on a stopped turn that never wrote any text', () => {+ render(+ <MessageItem+ message={+ makeMsg({+ metadata: { createdAt: new Date(), stopped: true },+ parts: [+ {+ type: 'tool-slow_wait',+ toolCallId: 'c1',+ state: 'output-error',+ input: {},+ errorText: 'Stopped before the tool finished.',+ },+ ],+ }) as any+ }+ isFirstMessage+ isLastMessage+ status={'ready' as any}+ onContinue={vi.fn()}+ />+ )+ expect(screen.queryByTitle('chat:actions.continue')).not.toBeInTheDocument()+ })+it('hides Continue button when the turn finished normally', () => {render(<MessageItemdiff --git a/web-app/src/lib/__tests__/stopped-tool-calls.test.ts b/web-app/src/lib/__tests__/stopped-tool-calls.test.tsnew file mode 100644index 000000000..cb9388c43--- /dev/null+++ b/web-app/src/lib/__tests__/stopped-tool-calls.test.ts@@ -0,0 +1,131 @@+import { describe, expect, it } from 'vitest'+import type { UIMessage } from '@ai-sdk/react'+import {+ STOPPED_TOOL_ERROR,+ settleStoppedToolCalls,+ untilAborted,+} from '../stopped-tool-calls'+import {+ convertThreadMessageToUIMessage,+ extractContentPartsFromUIMessage,+ toolErrorsOf,+} from '../messages'++const assistant = (parts: unknown[], metadata?: object): UIMessage =>+ ({ id: 'a1', role: 'assistant', parts, metadata }) as UIMessage++const tool = (state: string, extra: object = {}) => ({+ type: 'tool-slow_wait',+ toolCallId: 'c1',+ input: { seconds: 20 },+ state,+ ...extra,+})++describe('settleStoppedToolCalls', () => {+ it.each(['input-streaming', 'input-available'])(+ 'settles a call left in %s as a stopped error',+ (state) => {+ const [message] = settleStoppedToolCalls([assistant([tool(state)])])+ expect(message.parts[0]).toMatchObject({+ state: 'output-error',+ errorText: STOPPED_TOOL_ERROR,+ input: { seconds: 20 },+ })+ expect(message.metadata).toMatchObject({ stopped: true })+ }+ )++ // Older messages hold calls that failed or were denied before this release+ // saved their error; relabelling them "stopped" would be wrong, and the model+ // reads them on later turns.+ it('settles only the last message, never earlier history', () => {+ const old = { ...assistant([tool('input-available')]), id: 'old' }+ const current = {+ ...assistant([tool('input-streaming', { toolCallId: 'c2' })]),+ id: 'cur',+ }+ const out = settleStoppedToolCalls([old, current])+ expect(out[0]).toBe(old)+ expect(out[1].parts[0]).toMatchObject({ state: 'output-error' })+ })++ it('leaves finished calls and their message alone', () => {+ const done = assistant([+ tool('output-available', { output: 'ok' }),+ { type: 'text', text: 'hi' },+ ])+ const messages = [done]+ expect(settleStoppedToolCalls(messages)).toBe(messages)+ })++ it('settles only the unfinished call of a turn with several', () => {+ const [message] = settleStoppedToolCalls([+ assistant([+ tool('output-available', { toolCallId: 'c0', output: 'ok' }),+ tool('input-available'),+ ]),+ ])+ expect(message.parts[0]).toMatchObject({ state: 'output-available' })+ expect(message.parts[1]).toMatchObject({ state: 'output-error' })+ })++ it('reloads a stopped call as an error, not as running or as a result', () => {+ const [stopped] = settleStoppedToolCalls([+ assistant([tool('input-streaming')]),+ ])+ const reloaded = convertThreadMessageToUIMessage({+ id: 'a1',+ role: 'assistant',+ content: extractContentPartsFromUIMessage(stopped),+ metadata: { toolErrors: toolErrorsOf(stopped) },+ } as Parameters<typeof convertThreadMessageToUIMessage>[0])+ // `input-available` is what renders "Running"; `output-available` would+ // present the stop as a result the tool returned.+ expect(reloaded.parts[0]).toMatchObject({+ state: 'output-error',+ errorText: STOPPED_TOOL_ERROR,+ })+ })++ it('reloads a denied call as an error too', () => {+ const denied = assistant([+ tool('output-error', { errorText: 'Tool execution denied by user' }),+ ])+ expect(toolErrorsOf(denied)).toEqual({+ c1: 'Tool execution denied by user',+ })+ })+})++describe('untilAborted', () => {+ it('passes the result through while not aborted', async () => {+ const controller = new AbortController()+ await expect(+ untilAborted(Promise.resolve(7), controller.signal)+ ).resolves.toBe(7)+ })++ it('rejects as soon as the signal aborts, though the call never returns', async () => {+ const controller = new AbortController()+ const never = new Promise<string>(() => {})+ const raced = untilAborted(never, controller.signal)+ controller.abort()+ await expect(raced).rejects.toMatchObject({ name: 'AbortError' })+ })++ it('rejects at once when already aborted', async () => {+ const controller = new AbortController()+ controller.abort()+ await expect(+ untilAborted(Promise.resolve(1), controller.signal)+ ).rejects.toMatchObject({ name: 'AbortError' })+ })++ it("forwards the call's own failure", async () => {+ const controller = new AbortController()+ await expect(+ untilAborted(Promise.reject(new Error('boom')), controller.signal)+ ).rejects.toThrow('boom')+ })+})diff --git a/web-app/src/lib/messages.ts b/web-app/src/lib/messages.tsindex cacf054b2..7c70e83d8 100644--- a/web-app/src/lib/messages.ts+++ b/web-app/src/lib/messages.ts@@ -293,6 +293,14 @@ export function convertThreadMessageToUIMessage(} else if (content.type === 'tool_call') {// Handle tool call content items - direct conversion from flat structure// Use AI SDK v5 UIToolInvocation format: toolCallId, state: 'output-available'/'input-available'+ // A call that failed, was denied or was stopped has no output; its error+ // is kept beside the content (see `toolErrorsOf`) so it reloads as an+ // error and not as a call that is still running.+ const errorText = (+ threadMessage.metadata as+ | { toolErrors?: Record<string, string> }+ | undefined+ )?.toolErrors?.[content.tool_call_id ?? '']if (content.output != null) {parts.push({type: `tool-${content.tool_name}`,@@ -301,6 +309,14 @@ export function convertThreadMessageToUIMessage(state: 'output-available',output: content.output,})+ } else if (errorText) {+ parts.push({+ type: `tool-${content.tool_name}`,+ toolCallId: content.tool_call_id,+ input: content.input,+ state: 'output-error',+ errorText,+ })} else {parts.push({type: `tool-${content.tool_name}`,@@ -441,6 +457,30 @@ export function convertThreadMessagesToUIMessages(.filter((msg): msg is UIMessage => msg !== null)}+/**+ * The error text of each tool call in `message` that ended in an error (failed,+ * denied, or stopped), by tool call id, for the message's persisted metadata.+ * Such a call has no output to store, so without this it reloads as a call that+ * never finished. Undefined when there is none.+ */+export function toolErrorsOf(+ message: UIMessage+): Record<string, string> | undefined {+ const errors: Record<string, string> = {}+ for (const part of (message.parts ?? []) as any[]) {+ if (+ typeof part?.type === 'string' &&+ part.type.startsWith('tool-') &&+ part.state === 'output-error' &&+ part.toolCallId &&+ part.errorText+ ) {+ errors[part.toolCallId] = part.errorText+ }+ }+ return Object.keys(errors).length > 0 ? errors : undefined+}+/*** Extract content from UIMessage parts as separate ThreadContent items.* This preserves the structure of multiple text/reasoning/tool call parts instead of combining them.diff --git a/web-app/src/lib/stopped-tool-calls.ts b/web-app/src/lib/stopped-tool-calls.tsnew file mode 100644index 000000000..5ba25104c--- /dev/null+++ b/web-app/src/lib/stopped-tool-calls.ts@@ -0,0 +1,94 @@+import type { UIMessage } from '@ai-sdk/react'++/**+ * What a tool card reads when the turn was stopped before its call finished.+ * It is also what the model is told on the next turn: the call was stopped and+ * its result discarded. Neutral on who stopped it, since Stop is also pressed+ * for the user by the error handling (out of memory, backend or context+ * errors). Only MCP calls are cancelled on the backend; a web, RAG or agent+ * call may still finish its side effects, so this does not claim the call never+ * ran.+ */+export const STOPPED_TOOL_ERROR = 'Stopped before the tool finished.'++/** The part of a tool's result the tool loop reads. */+export type ToolRunResult = { error?: string; content?: unknown }++const isUnsettled = (part: unknown): boolean => {+ const p = part as { type?: string; state?: string } | null+ return (+ !!p &&+ typeof p.type === 'string' &&+ (p.type === 'dynamic-tool' || p.type.startsWith('tool-')) &&+ (p.state === 'input-streaming' || p.state === 'input-available')+ )+}++/**+ * After a Stop nothing will ever resolve a tool call that is still streaming+ * its arguments or waiting to run, so its card would keep saying "Running"+ * (live, and after every reload, once persisted). Settles each such call in one+ * message, the turn that was stopped, as an error and marks that message+ * `stopped`. That is the message with `messageId`, or the last one when none is+ * given. Other messages are history and are never touched.+ *+ * Returns the same array when there is nothing to settle, so callers can tell+ * by identity whether to write anything back.+ */+export function settleStoppedToolCalls(+ messages: UIMessage[],+ messageId?: string+): UIMessage[] {+ const index =+ messageId === undefined+ ? messages.length - 1+ : messages.findIndex((m) => m.id === messageId)+ const message = messages[index]+ if (+ !message ||+ message.role !== 'assistant' ||+ !message.parts?.some(isUnsettled)+ ) {+ return messages+ }+ const settled = {+ ...message,+ parts: message.parts.map((part) =>+ isUnsettled(part)+ ? { ...part, state: 'output-error', errorText: STOPPED_TOOL_ERROR }+ : part+ ),+ metadata: {+ ...((message.metadata as Record<string, unknown> | undefined) ?? {}),+ stopped: true,+ },+ } as UIMessage+ return messages.map((m, i) => (i === index ? settled : m))+}++/**+ * Settles with `promise`, or rejects with an AbortError as soon as `signal`+ * aborts. A tool call that never returns (a runaway shell, a hung MCP server)+ * must not keep the tool loop, and with it the thread, busy after a Stop.+ */+export function untilAborted<T>(+ promise: Promise<T>,+ signal: AbortSignal+): Promise<T> {+ const aborted = () => new DOMException('Aborted', 'AbortError')+ if (signal.aborted) return Promise.reject(aborted())+ return new Promise<T>((resolve, reject) => {+ const onAbort = () => reject(aborted())+ signal.addEventListener('abort', onAbort, { once: true })+ promise.then(+ (value) => {+ signal.removeEventListener('abort', onAbort)+ resolve(value)+ },+ (error) => {+ signal.removeEventListener('abort', onAbort)+ reject(error)+ }+ )+ })+}diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex 78d2864f0..16e488915 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -35,10 +35,16 @@ import { useChatSessions } from '@/stores/chat-session-store'import {convertThreadMessagesToUIMessages,extractContentPartsFromUIMessage,+ toolErrorsOf,uiMessageHasMeaningfulContent,threadMessageIsEmpty,} from '@/lib/messages'import { newUserThreadContent } from '@/lib/completion'+import {+ settleStoppedToolCalls,+ untilAborted,+ type ToolRunResult,+} from '@/lib/stopped-tool-calls'import {computeActivePath,backfillParentIds,@@ -114,6 +120,79 @@ const CHAT_STATUS = {const TITLE_REFRESH_EVERY_N_ASSISTANT_MESSAGES = 4+// What an explicit Stop aborts to end a thread's running tool call, by thread.+// Aborted only by Stop: leaving a thread ends its tool loop (see the cleanup in+// ThreadDetail) but must not cancel a call that is running, whose result still+// lands in the retained session. Keyed by thread because the route component is+// reused across thread switches, so a Stop in one thread can never reach+// another's call, and the Stop button still works after coming back.+const toolStopControllers = new Map<string, AbortController>()++// What ends a thread's tool loop: aborted when the thread is left or stopped, it+// stops the loop between calls and the auto follow-up of the turn. Keyed by+// thread for the same reason as the Stop controllers; a ref on the component+// would be shared by every thread's loop and let one thread's Stop, or one+// thread's loop finishing, end another's.+const toolLoopControllers = new Map<string, AbortController>()+// The message each thread's running tool call belongs to, keyed by its Stop+// controller, so a Stop settles that turn even when the user has sent another+// one since or left and came back.+const toolLoopTurns = new WeakMap<AbortController, string>()+// Which tool loop of a thread is the latest. A loop that was replaced (an edit or+// a regenerate started a newer turn) must not, as it winds down, settle the+// runtime, drop the approvals or clear the busy flag the newer loop now owns.+const toolLoopGeneration = new Map<string, number>()++// Approval promises started in onToolCall (so the popup appears immediately) and+// awaited by the onFinish execution loop, keyed by thread and then toolCallId.+// Executing stays in onFinish so the tool result lands on a completed assistant+// message and the AI SDK's auto-resubmit (sendAutomaticallyWhen) fires. A+// component ref would be shared by every thread (the route is reused across+// thread switches), so one thread finishing or being left would drop another+// thread's pending approvals and prompt the user again.+const toolApprovalPromises = new Map<string, Map<string, Promise<boolean>>>()+const approvalsOf = (threadId: string) => {+ let approvals = toolApprovalPromises.get(threadId)+ if (!approvals) {+ approvals = new Map()+ toolApprovalPromises.set(threadId, approvals)+ }+ return approvals+}+const forgetApprovals = (threadId: string) => {+ toolApprovalPromises.delete(threadId)+}++// Recorded for a call that never ran because its chat was closed (the thread was+// left) rather than because the user refused or stopped it.+const CHAT_CLOSED_TOOL_ERROR =+ 'Tool call cancelled: the chat was closed before it ran.'++// Rewrites a turn that is already stored with what its live copy holds now. A+// turn is stored before its tools run, so a call's outcome (result, error,+// stopped) only reaches storage when a later reply rewrites the turn; when no+// reply follows (Stop, or the thread was left) it has to be written here, or the+// call reloads as "Running" after a restart.+function rewriteStoredTurn(+ threadId: string,+ message: UIMessage,+ stopped: boolean+) {+ const { getMessages, updateMessage } = useMessages.getState()+ const stored = getMessages(threadId).find((m) => m.id === message.id)+ if (!stored) return+ const toolErrors = toolErrorsOf(message)+ updateMessage({+ ...stored,+ content: extractContentPartsFromUIMessage(message),+ metadata: {+ ...stored.metadata,+ ...(stopped ? { stopped: true } : {}),+ ...(toolErrors ? { toolErrors } : {}),+ },+ })+}+// The MCP server a tool belongs to, so an approval prompt can offer to trust// the whole server rather than this one tool.function serverForTool(toolName: string): string | undefined {@@ -201,29 +280,18 @@ function ThreadDetail() {const getSessionData = useChatSessions((state) => state.getSessionData)const sessionData = getSessionData(threadId)- // AbortController for cancelling tool calls- const toolCallAbortController = useRef<AbortController | null>(null)-- // Approval promises started in onToolCall (so the popup appears immediately)- // and awaited by the onFinish execution loop, keyed by toolCallId. Executing- // stays in onFinish so the tool result lands on a completed assistant message- // and the AI SDK's auto-resubmit (sendAutomaticallyWhen) fires.- const toolApprovalPromises = useRef<Map<string, Promise<boolean>>>(new Map())-const titleAbortRef = useRef<AbortController | null>(null)// Check if we should follow up with tool calls (respects abort signal)const followUpMessage = useCallback(({ messages }: { messages: UIMessage[] }) => {- if (- !toolCallAbortController.current ||- toolCallAbortController.current?.signal.aborted- ) {+ const controller = toolLoopControllers.get(threadId)+ if (!controller || controller.signal.aborted) {return false}return lastAssistantMessageIsCompleteWithToolCalls({ messages })},- []+ [threadId])// Subscribe directly to the thread data to ensure updates when model changes@@ -332,7 +400,24 @@ function ThreadDetail() {sessionTitle: thread?.title,systemMessage,experimental_throttle: 50,- onFinish: ({ message, isAbort, isError }) => {+ onFinish: ({ message: finishedMessage, isAbort, isError }) => {+ // A stopped turn can end with a tool call that never got to run; settle+ // it before it is persisted so its card does not read "Running" forever.+ const message = isAbort+ ? settleStoppedToolCalls([finishedMessage])[0]+ : finishedMessage+ // The live copy too, for every aborted turn: one stopped before its tool+ // call had any input has nothing meaningful to persist below, but its+ // card still reads "Running". Only this turn's message: the setter is the+ // open thread's, and a background thread's turn can abort while another+ // thread is in front.+ if (isAbort) {+ setChatMessagesRef.current?.((prev) =>+ prev.map((m) =>+ m.id === finishedMessage.id ? settleStoppedToolCalls([m])[0] : m+ )+ )+ }const msgMeta = message.metadata as Record<string, unknown> | undefinedconst finishReason = msgMeta?.finishReason as string | undefined// Consume once per generation so a skipped persist (error/empty) can't@@ -407,9 +492,11 @@ function ThreadDetail() {uiMessageHasMeaningfulContent(message)) {const contentParts = extractContentPartsFromUIMessage(message)+ const toolErrors = toolErrorsOf(message)const messageMetadata = {...((message.metadata || {}) as Record<string, unknown>),...(isStoppedTurn ? { stopped: true } : {}),+ ...(toolErrors ? { toolErrors } : {}),}if (isStoppedTurn) {@@ -518,30 +605,75 @@ function ThreadDetail() {}}+ // Stopped: none of this turn's tools will run. Left alone, their approval+ // prompts stay up, and a late "Allow" would run the tool and resume the+ // reply the user just stopped.+ if (isAbort) {+ forgetApprovals(threadId)+ sessionData.tools = []+ useToolApprovalRequests.getState().clearPendingForThread(threadId)+ return+ }+// Execute tool calls here, after the assistant message has completed, so// each addToolOutput lands on a finished message and the SDK's// auto-resubmit (sendAutomaticallyWhen) fires. Approval is requested// earlier in onToolCall (popup appears without waiting for this callback);// we await that already-started promise here rather than prompting again.- toolCallAbortController.current = new AbortController()- const signal = toolCallAbortController.current.signal+ // A reply without tool calls has no loop. It must not register+ // controllers, settle the runtime or clear the busy flag, or it would take+ // them from an earlier turn whose call is still running.+ const hasTools = sessionData.tools.length > 0+ const callController = new AbortController()+ const signal = callController.signal+ const stopController = new AbortController()+ const stopSignal = stopController.signal+ const generation = hasTools+ ? (toolLoopGeneration.get(threadId) ?? 0) + 1+ : -1+ if (hasTools) {+ toolLoopGeneration.set(threadId, generation)+ toolLoopControllers.set(threadId, callController)+ toolStopControllers.set(threadId, stopController)+ toolLoopTurns.set(stopController, message.id)+ }const ragToolNames = useAppState.getState().ragToolNamesconst mcpToolNames = useAppState.getState().mcpToolNames// Keep the thread marked busy while awaiting approval and executing tools,// since streaming has already ended and isSessionBusy's tools-array read isn't reactive.- useAppState.getState().setThreadBusy(threadId, true)+ if (hasTools) {+ useAppState.getState().setThreadBusy(threadId, true)- // Tools run one at a time below, so the rest are genuinely queued.- useToolCallRuntime- .getState()- .enqueue(sessionData.tools.map((tc) => tc.toolCallId))+ // Tools run one at a time below, so the rest are genuinely queued.+ useToolCallRuntime+ .getState()+ .enqueue(sessionData.tools.map((tc) => tc.toolCallId))+ }++ // The outcomes handed to the chat, so a loop that ends after the thread was+ // left can wait for them to land before it persists the turn.+ const outputs: Promise<unknown>[] = []+ const record = (output: Parameters<typeof addToolOutput>[0]) => {+ outputs.push(Promise.resolve(addToolOutput(output)))+ };(async () => {for (const toolCall of sessionData.tools) {+ // Stop settles the turn's calls itself (see handleStop).+ if (stopSignal.aborted) break+ // The thread was left before this call's turn came: it will not run,+ // and without an outcome its card would read "Running" on return.if (signal.aborted) {- break+ record({+ state: 'output-error',+ tool: toolCall.toolName,+ toolCallId: toolCall.toolCallId,+ errorText: CHAT_CLOSED_TOOL_ERROR,+ })+ useToolCallRuntime.getState().markSettled(toolCall.toolCallId)+ continue}try {@@ -549,7 +681,7 @@ function ThreadDetail() {const approved = isAutoAllowedTool(toolName)? true- : await (toolApprovalPromises.current.get(toolCall.toolCallId) ??+ : await (approvalsOf(threadId).get(toolCall.toolCallId) ??useToolApprovalRequests.getState().requestApproval(@@ -558,14 +690,22 @@ function ThreadDetail() {threadId,serverForTool(toolName)))- toolApprovalPromises.current.delete(toolCall.toolCallId)+ approvalsOf(threadId).delete(toolCall.toolCallId)+ // Only an explicit Stop skips the result. Leaving the thread also+ // resolves a pending approval as denied; that denial must still be+ // recorded, or the call stays "Running" with nothing running.+ if (stopSignal.aborted) breakif (!approved) {- addToolOutput({+ record({state: 'output-error',tool: toolCall.toolName,toolCallId: toolCall.toolCallId,- errorText: 'Tool execution denied by user',+ // Leaving the thread resolves a pending approval as denied; that+ // was not the user's decision and the model reads this later.+ errorText: signal.aborted+ ? CHAT_CLOSED_TOOL_ERROR+ : 'Tool execution denied by user',})continue}@@ -574,65 +714,81 @@ function ThreadDetail() {// not reported as the tool being slow.useToolCallRuntime.getState().markRunning(toolCall.toolCallId)- let result-- if (WEB_TOOL_NAMES.has(toolName)) {- result = await executeWebTool(toolName, toolCall.input)- } else if (CHAT_AGENT_TOOL_NAMES.has(toolName)) {- // Chat's shell runs with the sandbox network closed: the default- // `allowNetwork = false` is the contract here, not an accident.- const agentResult = await executeAgentTool(- toolName,- toolCall.input,- threadId- )- // The diff is display-only, so it goes to the runtime store rather- // than into `result`: anything in `result` reaches the model, and a- // full diff there would duplicate the file it just wrote.- const { diff, ...rest } = agentResult- if (diff) {- useToolCallRuntime- .getState()- .recordDiff(toolCall.toolCallId, diff)- }- result = rest- } else if (ragToolNames.has(toolName)) {- result = await serviceHub.rag().callTool({- toolName,- arguments: toolCall.input,- threadId,- projectId: projectId,- scope: projectId ? 'project' : 'thread',- })- } else if (mcpToolNames.has(toolName)) {- // An MCP result is injected into conversation history verbatim, so- // a page-sized one can exhaust the context on its own. Give the- // backend a budget scaled to the window this model actually has;- // it narrows that against the user's configured ceiling.- const ctxLen = useModelProvider.getState().selectedModel?.settings- ?.ctx_len?.controller_props?.value- result = await serviceHub.mcp().callTool({- toolName,- arguments: toolCall.input,- maxOutputChars: deriveToolOutputCap(- typeof ctxLen === 'number' ? ctxLen : undefined- ),- })- } else {- result = {- error: `Tool '${toolName}' not found in any service`,- }- }+ // Raced against Stop: a call that never returns (a runaway shell,+ // a hung MCP server) must not hold the loop, and the thread, busy.+ const result = await untilAborted<ToolRunResult>(+ (async () => {+ if (WEB_TOOL_NAMES.has(toolName)) {+ return await executeWebTool(toolName, toolCall.input)+ } else if (CHAT_AGENT_TOOL_NAMES.has(toolName)) {+ // Chat's shell runs with the sandbox network closed: the+ // default `allowNetwork = false` is the contract here, not an+ // accident.+ const agentResult = await executeAgentTool(+ toolName,+ toolCall.input,+ threadId+ )+ // The diff is display-only, so it goes to the runtime store+ // rather than into `result`: anything in `result` reaches the+ // model, and a full diff there would duplicate the file it+ // just wrote.+ const { diff, ...rest } = agentResult+ if (diff) {+ useToolCallRuntime+ .getState()+ .recordDiff(toolCall.toolCallId, diff)+ }+ return rest+ } else if (ragToolNames.has(toolName)) {+ return await serviceHub.rag().callTool({+ toolName,+ arguments: toolCall.input,+ threadId,+ projectId: projectId,+ scope: projectId ? 'project' : 'thread',+ })+ } else if (mcpToolNames.has(toolName)) {+ // An MCP result is injected into conversation history+ // verbatim, so a page-sized one can exhaust the context on its+ // own. Give the backend a budget scaled to the window this+ // model actually has; it narrows that against the user's+ // configured ceiling. Cancellable, so Stop ends the call on+ // the backend as well as in this loop.+ const ctxLen = useModelProvider.getState().selectedModel+ ?.settings?.ctx_len?.controller_props?.value+ const call = serviceHub.mcp().callToolWithCancellation({+ toolName,+ arguments: toolCall.input,+ maxOutputChars: deriveToolOutputCap(+ typeof ctxLen === 'number' ? ctxLen : undefined+ ),+ })+ const cancel = () => void call.cancel().catch(() => {})+ stopSignal.addEventListener('abort', cancel, { once: true })+ try {+ return await call.promise+ } finally {+ stopSignal.removeEventListener('abort', cancel)+ }+ } else {+ return {+ error: `Tool '${toolName}' not found in any service`,+ }+ }+ })(),+ stopSignal+ )if (result.error) {- addToolOutput({+ record({state: 'output-error',tool: toolCall.toolName,toolCallId: toolCall.toolCallId,errorText: `Error: ${result.error}`,})} else {- addToolOutput({+ record({tool: toolCall.toolName,toolCallId: toolCall.toolCallId,output: result.content,@@ -641,7 +797,7 @@ function ThreadDetail() {} catch (error) {if ((error as Error).name !== 'AbortError') {console.error('Tool call error:', error)- addToolOutput({+ record({state: 'output-error',tool: toolCall.toolName,toolCallId: toolCall.toolCallId,@@ -654,19 +810,43 @@ function ThreadDetail() {}}+ // The thread was left: no follow-up reply will run to rewrite the stored+ // turn, so write what the live copy holds (results and errors included).+ // This turn by its id, not the last message: the user may have come back+ // and started another turn before this one's calls returned.+ if (signal.aborted && !stopSignal.aborted) {+ await Promise.allSettled(outputs)+ const turn = useChatSessions+ .getState()+ .sessions[threadId]?.chat.messages.find((m) => m.id === message.id)+ if (turn?.role === 'assistant') rewriteStoredTurn(threadId, turn, false)+ }+ if (!hasTools || toolLoopGeneration.get(threadId) !== generation) returnuseToolCallRuntime.getState().settleRemaining()+ forgetApprovals(threadId)sessionData.tools = []- toolApprovalPromises.current.clear()- toolCallAbortController.current = null+ // Only this loop's own: a later loop of the thread may have replaced it.+ if (toolLoopControllers.get(threadId) === callController) {+ toolLoopControllers.delete(threadId)+ }+ if (toolStopControllers.get(threadId) === stopController) {+ toolStopControllers.delete(threadId)+ }useAppState.getState().setThreadBusy(threadId, false)})().catch((error) => {if (error.name !== 'AbortError') {console.error('Tool call error:', error)}+ if (!hasTools || toolLoopGeneration.get(threadId) !== generation) returnuseToolCallRuntime.getState().settleRemaining()+ forgetApprovals(threadId)sessionData.tools = []- toolApprovalPromises.current.clear()- toolCallAbortController.current = null+ if (toolLoopControllers.get(threadId) === callController) {+ toolLoopControllers.delete(threadId)+ }+ if (toolStopControllers.get(threadId) === stopController) {+ toolStopControllers.delete(threadId)+ }useAppState.getState().setThreadBusy(threadId, false)})@@ -746,9 +926,9 @@ function ThreadDetail() {sessionData.tools.push(toolCall)if (!isAutoAllowedTool(toolCall.toolName) &&- !toolApprovalPromises.current.has(toolCall.toolCallId)+ !approvalsOf(threadId).has(toolCall.toolCallId)) {- toolApprovalPromises.current.set(+ approvalsOf(threadId).set(toolCall.toolCallId,useToolApprovalRequests.getState()@@ -771,6 +951,62 @@ function ThreadDetail() {const hasBannerError = !!(oomError || backendError || contextLimitError)const effectiveStatus = hasBannerError ? 'ready' : status+ // The stream has ended but the turn's tools are still running or waiting on+ // approval. `status` is `ready` then, so without this the composer offers a+ // send arrow and no way to stop a runaway command.+ const toolsBusy = useAppState((s) => !!s.busyThreads[threadId])+ const toolsRunning = toolsBusy && !processingEmbeddings++ // Read at send or stop time without making those callbacks depend on every+ // streamed token.+ const chatMessagesRef = useRef(chatMessages)+ chatMessagesRef.current = chatMessages++ // Stop ends the whole turn, not just the stream: it aborts the tool loop,+ // drops the approval prompts, and settles whatever tool call never got to+ // finish so its card stops saying "Running" (and stays settled on reload).+ const handleStop = useCallback(() => {+ // The Stop controller outlives the thread-switch cleanup, which deletes the+ // loop controller, so it is what says which turn is still running a call.+ // One already aborted was stopped earlier; its loop is only winding down.+ const stopping = toolStopControllers.get(threadId)+ const running = stopping?.signal.aborted ? undefined : stopping+ // The turn whose call this aborts; with none running (the reply is still+ // streaming) it is the last message.+ const turnId = running ? toolLoopTurns.get(running) : undefined+ toolLoopControllers.get(threadId)?.abort()+ running?.abort()+ useToolApprovalRequests.getState().clearPendingForThread(threadId)+ stop()++ // Only the turn being stopped. Taken from the SDK's own chat state, which+ // is current: the rendered snapshot is throttled and can lag the stream, so+ // a call whose result just landed would still look unfinished there and be+ // saved as stopped while the live copy holds its result.+ const live =+ useChatSessions.getState().sessions[threadId]?.chat.messages ??+ chatMessagesRef.current+ const settled = settleStoppedToolCalls(live, turnId)+ if (settled === live) return+ setChatMessages((prev) => settleStoppedToolCalls(prev, turnId))+ // A turn that was still streaming is persisted by onFinish; one that is+ // already stored (its tools were running) has to be rewritten here. It was+ // stored before any tool ran, so the output of a call that did finish is+ // only in the rendered message, and the follow-up reply that would have+ // persisted it never happens.+ const stoppedId = turnId ?? live[live.length - 1].id+ const stoppedTurn = settled.find((m) => m.id === stoppedId)+ if (stoppedTurn) rewriteStoredTurn(threadId, stoppedTurn, true)+ }, [threadId, stop, setChatMessages])++ // A new reply (regenerate, edit) replaces the turn it answers, so a tool call+ // that turn still has running is abandoned: ended like a Stop, before the new+ // turn can register its own loop over it.+ const endRunningTools = useCallback(() => {+ const running = toolStopControllers.get(threadId)+ if (running && !running.signal.aborted) handleStop()+ }, [threadId, handleStop])+// Global disabled-tools set; re-run the effect below when it changes.const disabledTools = useToolAvailable((state) => state.disabledTools)@@ -827,11 +1063,6 @@ function ThreadDetail() {reset: resetReasoningScroll,} = useAutoScroll()- // Read at send time without making the send callbacks depend on every- // streamed token.- const chatMessagesRef = useRef(chatMessages)- chatMessagesRef.current = chatMessages-const lastIsAssistant = useMemo(() => {const last = chatMessages[chatMessages.length - 1]return !!last && last.role === 'assistant'@@ -981,12 +1212,10 @@ function ThreadDetail() {// are leaving. Cleanup captures the previous threadId; without this the// unresolved approval promise keeps that thread marked busy forever.useEffect(() => {- // Stable ref object (never reassigned) — capture for the cleanup closure.- const approvalPromises = toolApprovalPromises.currentreturn () => {- toolCallAbortController.current?.abort()- toolCallAbortController.current = null- approvalPromises.clear()+ toolLoopControllers.get(threadId)?.abort()+ toolLoopControllers.delete(threadId)+ forgetApprovals(threadId)useToolApprovalRequests.getState().clearPendingForThread(threadId)// Drop per-thread timing/progress/diff state from the shared runtime// store. The cards for the thread we leave are unmounting, so a thread a@@ -1493,10 +1722,12 @@ function ThreadDetail() {ensureBranched()pendingAssistantParentId.current = resolveAssistantParent(messageId)+ endRunningTools()regenerate(messageId ? { messageId } : undefined)},[regenerate,+ endRunningTools,stripBannerMetadata,contextLimitError,ensureBranched,@@ -1551,6 +1782,7 @@ function ThreadDetail() {if (target.role === 'user') {pendingAssistantParentId.current = newIdsyncActivePath()+ endRunningTools()regenerate({ messageId: newId })} else {syncActivePath()@@ -1562,6 +1794,7 @@ function ThreadDetail() {setActiveBranch,syncActivePath,regenerate,+ endRunningTools,])@@ -2002,8 +2235,9 @@ function ThreadDetail() {<ChatInputmodel={threadModel}onSubmit={handleSubmit}- onStop={stop}+ onStop={handleStop}chatStatus={effectiveStatus}+ toolsRunning={toolsRunning}/></div></div>diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsxindex d62b9707a..a9c89c03f 100644--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx@@ -138,6 +138,8 @@ const h = vi.hoisted(() => {useMessageQueueMock.getState = () => messageQueueStatereturn {+ // The route's thread id, which the tests move to simulate a thread switch.+ routeParams: { threadId: 'thread-1' },mockSendMessage,mockRegenerate,mockStop,@@ -178,7 +180,7 @@ const h = vi.hoisted(() => {vi.mock('@tanstack/react-router', () => ({createFileRoute: () => (config: any) => ({ ...config, id: '/threads/$threadId' }),- useParams: () => ({ threadId: 'thread-1' }),+ useParams: () => ({ threadId: h.routeParams.threadId }),useSearch: () => ({ threadModel: undefined }),}))@@ -317,13 +319,31 @@ vi.mock('@/lib/messages', () => ({parts: [{ type: 'text', text: m.content?.[0]?.text?.value ?? '' }],})),extractContentPartsFromUIMessage: (msg: any) =>- msg.parts- .filter((p: any) => p.type === 'text')- .map((p: any) => ({ type: 'text', text: { value: p.text, annotations: [] } })),+ msg.parts.flatMap((p: any) =>+ p.type === 'text'+ ? [{ type: 'text', text: { value: p.text, annotations: [] } }]+ : p.type?.startsWith('tool-')+ ? [{ type: 'tool_call', tool_call_id: p.toolCallId, output: p.output }]+ : []+ ),uiMessageHasMeaningfulContent: (msg: any) =>!!msg?.parts?.some((p: any) => p.type === 'text' && p.text?.trim()),+ toolErrorsOf: (msg: any) => {+ const errors: Record<string, string> = {}+ for (const p of msg.parts ?? []) {+ if (p.state === 'output-error') errors[p.toolCallId] = p.errorText+ }+ return Object.keys(errors).length ? errors : undefined+ },}))+// The chat runs MCP tools through the cancellable API so Stop can end the call.+const cancellable = (run: (args: any) => Promise<unknown>) => (args: any) => ({+ promise: run(args),+ cancel: vi.fn().mockResolvedValue(undefined),+ token: 'test-token',+})+vi.mock('@/lib/completion', () => ({newUserThreadContent: (threadId: string, text: string, _a: any, id: string) => ({id,@@ -359,7 +379,7 @@ vi.mock('@/types/attachment', () => ({vi.mock('ai', () => ({generateId: () => 'gen-id',- lastAssistantMessageIsCompleteWithToolCalls: () => false,+ lastAssistantMessageIsCompleteWithToolCalls: () => true,}))vi.mock('zustand/react/shallow', () => ({@@ -370,6 +390,7 @@ vi.mock('@/hooks/use-chat', () => ({useChat: (_args: any) => {;(h as any).capturedOnFinish = _args?.onFinish;(h as any).capturedOnToolCall = _args?.onToolCall+ ;(h as any).capturedSendAutomaticallyWhen = _args?.sendAutomaticallyWhenreturn {messages: h.chatState.messages,status: h.chatState.status,@@ -957,6 +978,47 @@ describe('ThreadDetail route', () => {})expect(useMessageErrors.getState().errors['a-empty']).toBeUndefined()})++ // Stopped right after the tool call started, before any input arrived: the+ // turn has nothing worth persisting, but its live card must not stay+ // "Running".+ it('settles a live tool call stopped before it had any input', () => {+ renderComponent()+ h.mockSetChatMessages.mockClear()+ act(() => {+ ;(h as any).capturedOnFinish({+ message: {+ id: 'a-early',+ role: 'assistant',+ parts: [{ type: 'tool-fetch', toolCallId: 'tcE', state: 'input-streaming' }],+ metadata: {},+ },+ isAbort: true,+ isError: false,+ })+ })+ const updater = h.mockSetChatMessages.mock.calls+ .map((c: any[]) => c[0])+ .find((a: unknown) => typeof a === 'function')+ // The open thread's own last message is still mid-call; it is not the+ // aborted turn, so it must be left alone.+ const other = {+ id: 'a-other',+ role: 'assistant',+ parts: [{ type: 'tool-fetch', toolCallId: 'tcO', state: 'input-available' }],+ }+ const live = [+ {+ id: 'a-early',+ role: 'assistant',+ parts: [{ type: 'tool-fetch', toolCallId: 'tcE', state: 'input-streaming' }],+ },+ other,+ ]+ const out = updater(live)+ expect(out[0].parts[0]).toMatchObject({ state: 'output-error' })+ expect(out[1]).toBe(other)+ })})describe('context overflow banner (#9228)', () => {@@ -1102,7 +1164,8 @@ describe('ThreadDetail route', () => {h.appStateState.mcpToolNames = new Set(['fetch'])h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)const callTool = vi.fn().mockResolvedValue({ error: '', content: [] })- hub.mcp = () => ({ callTool }) as never+ hub.mcp = () =>+ ({ callToolWithCancellation: cancellable(callTool) }) as neverrenderComponent()const onToolCall = (@@ -1129,7 +1192,8 @@ describe('ThreadDetail route', () => {const previousSettings = h.modelProviderState.selectedModel.settingsh.modelProviderState.selectedModel.settings = {}const callTool = vi.fn().mockResolvedValue({ error: '', content: [] })- hub.mcp = () => ({ callTool }) as never+ hub.mcp = () =>+ ({ callToolWithCancellation: cancellable(callTool) }) as nevertry {renderComponent()@@ -1187,7 +1251,8 @@ describe('ThreadDetail route', () => {}return Promise.resolve({ error: '', content: [] })})- hub.mcp = () => ({ callTool }) as never+ hub.mcp = () =>+ ({ callToolWithCancellation: cancellable(callTool) }) as neverrenderComponent()await act(async () => {@@ -1218,6 +1283,527 @@ describe('ThreadDetail route', () => {expect(started).toEqual(['tcA', 'tcB'])})+ // A call that never returns must not hold the loop, the thread, or the+ // backend: Stop ends all three, and the stopped call's output is dropped.+ it('Stop cancels a running MCP call and frees the thread', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ const cancel = vi.fn().mockResolvedValue(undefined)+ const never = new Promise(() => {})+ hub.mcp = () =>+ ({+ callToolWithCancellation: () => ({+ promise: never,+ cancel,+ token: 't',+ }),+ }) as never+ h.appStateState.setThreadBusy.mockClear()+ h.mockAddToolOutput.mockClear()++ renderComponent()+ await arrive('tcA')+ await act(async () => {+ await finishWithToolCalls()+ })+ expect(h.appStateState.setThreadBusy).toHaveBeenLastCalledWith(+ 'thread-1',+ true+ )++ await act(async () => {+ screen.getByTestId('chat-stop').click()+ })++ expect(cancel).toHaveBeenCalledTimes(1)+ expect(h.appStateState.setThreadBusy).toHaveBeenLastCalledWith(+ 'thread-1',+ false+ )+ expect(h.mockAddToolOutput).not.toHaveBeenCalled()+ })++ // Edit and regenerate stay available while tools run (the status is+ // `ready`). The new reply replaces the turn it answers, so the call that+ // turn still has running must be ended first, or the new turn's loop would+ // take over the controllers and Stop could no longer reach it.+ it.each([+ ['editing a message', 'edit-u1'],+ ['regenerating a reply', 'regen-a-tc'],+ ])('%s ends the tool call the replaced turn still has running', async (_name, button) => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ const cancel = vi.fn().mockResolvedValue(undefined)+ hub.mcp = () =>+ ({+ callToolWithCancellation: () => ({+ promise: new Promise(() => {}),+ cancel,+ token: 't',+ }),+ }) as never+ h.chatState.messages = [+ { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'go' }] },+ { id: 'a-tc', role: 'assistant', parts: [{ type: 'text', text: 'ok' }] },+ ]++ renderComponent()+ await arrive('tcA')+ await act(async () => {+ await finishWithToolCalls()+ })+ await act(async () => {+ screen.getByTestId(button).click()+ })++ expect(cancel).toHaveBeenCalledTimes(1)+ expect(h.mockRegenerate).toHaveBeenCalled()+ })++ // A reply with no tool calls has no loop. If it registered one anyway it+ // would take the controllers of an earlier turn whose call is still+ // running, and its empty loop would delete them: Stop could no longer end+ // that call.+ it('a reply without tool calls leaves an earlier running call stoppable', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ const cancel = vi.fn().mockResolvedValue(undefined)+ hub.mcp = () =>+ ({+ callToolWithCancellation: () => ({+ promise: new Promise(() => {}),+ cancel,+ token: 't',+ }),+ }) as never+ const Component = Route.component as React.ComponentType++ const { rerender } = renderComponent()+ await arrive('tcA')+ await act(async () => {+ await finishWithToolCalls()+ })++ // A newer reply with no tool calls finishes (a fresh render, so a fresh+ // tool list).+ rerender(<Component />)+ await act(async () => {+ await finishWithToolCalls()+ })++ await act(async () => {+ screen.getByTestId('chat-stop').click()+ })+ expect(cancel).toHaveBeenCalledTimes(1)+ })++ // Leaving the thread ends the loop but is not a Stop: a call already+ // running keeps going and its result still lands in the retained session.+ it('leaving the thread does not cancel a running MCP call', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ const cancel = vi.fn().mockResolvedValue(undefined)+ hub.mcp = () =>+ ({+ callToolWithCancellation: () => ({+ promise: new Promise(() => {}),+ cancel,+ token: 't',+ }),+ }) as never++ const { unmount } = renderComponent()+ await arrive('tcA')+ await act(async () => {+ await finishWithToolCalls()+ })+ unmount()++ expect(cancel).not.toHaveBeenCalled()+ })++ // A turn of a thread that was left can finish in the background, after+ // another thread is shown. A Stop there is that thread's, and must not end+ // the background thread's loop: its queued calls still run.+ it('Stop in the thread in front does not end another thread\'s loop', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)+ const started: string[] = []+ const finish: Array<(r: unknown) => void> = []+ hub.mcp = () =>+ ({+ callToolWithCancellation: (args: any) => {+ started.push(args.arguments.id)+ return {+ promise: new Promise((resolve) => finish.push(resolve)),+ cancel: vi.fn().mockResolvedValue(undefined),+ token: 't',+ }+ },+ }) as never+ h.mockAddToolOutput.mockClear()+ const Component = Route.component as React.ComponentType+ const call = (id: string) => ({+ toolCall: { toolCallId: id, toolName: 'fetch', input: { id } },+ })++ try {+ const { rerender } = renderComponent()+ const onToolCallA = (h as any).capturedOnToolCall+ const onFinishA = (h as any).capturedOnFinish+ await act(async () => {+ await onToolCallA(call('tcA'))+ await onToolCallA(call('tcB'))+ })++ h.routeParams.threadId = 'thread-2'+ rerender(<Component />)+ await act(async () => {+ await onFinishA({+ message: {+ id: 'a-tc',+ role: 'assistant',+ parts: [{ type: 'text', text: '' }],+ metadata: { finishReason: 'tool-calls' },+ },+ isAbort: false,+ })+ })+ expect(started).toEqual(['tcA'])++ await act(async () => {+ screen.getByTestId('chat-stop').click()+ })+ await act(async () => {+ finish[0]({ error: '', content: [] })+ })++ expect(started).toEqual(['tcA', 'tcB'])+ } finally {+ h.routeParams.threadId = 'thread-1'+ }+ })++ // A loop left behind by a thread switch finishes later. It must not take+ // the controller of the thread now in front with it, or that thread's reply+ // would never continue after its tool result.+ it('a left thread\'s loop ending does not stop the current thread continuing', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ const results: Array<(r: unknown) => void> = []+ hub.mcp = () =>+ ({+ callToolWithCancellation: () => ({+ promise: new Promise((resolve) => results.push(resolve)),+ cancel: vi.fn().mockResolvedValue(undefined),+ token: 't',+ }),+ }) as never+ const Component = Route.component as React.ComponentType++ try {+ const { rerender } = renderComponent()+ await arrive('tcA')+ await act(async () => {+ await finishWithToolCalls()+ })++ h.routeParams.threadId = 'thread-2'+ rerender(<Component />)+ await arrive('tcB')+ await act(async () => {+ await finishWithToolCalls()+ })++ // Thread 1's call, left running, now completes.+ await act(async () => {+ results[0]({ error: '', content: [] })+ })++ const followUp = (h as any).capturedSendAutomaticallyWhen+ expect(followUp({ messages: [] })).toBe(true)+ } finally {+ h.routeParams.threadId = 'thread-1'+ }+ })++ // The route component is reused across thread switches, so a Stop must+ // reach only the thread it is pressed in, and still work after returning.+ it('Stop reaches only its own thread\'s running call, also after returning', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ const cancel = vi.fn().mockResolvedValue(undefined)+ hub.mcp = () =>+ ({+ callToolWithCancellation: () => ({+ promise: new Promise(() => {}),+ cancel,+ token: 't',+ }),+ }) as never+ const Component = Route.component as React.ComponentType++ try {+ const { rerender } = renderComponent()+ await arrive('tcA')+ await act(async () => {+ await finishWithToolCalls()+ })++ h.routeParams.threadId = 'thread-2'+ rerender(<Component />)+ await act(async () => {+ screen.getByTestId('chat-stop').click()+ })+ expect(cancel).not.toHaveBeenCalled()++ h.routeParams.threadId = 'thread-1'+ rerender(<Component />)+ await act(async () => {+ screen.getByTestId('chat-stop').click()+ })+ expect(cancel).toHaveBeenCalledTimes(1)+ } finally {+ h.routeParams.threadId = 'thread-1'+ }+ })++ // The turn was stored before any tool ran, so a call that finished while+ // another was still running has its output only in the rendered message.+ it('Stop keeps a finished call\'s output and settles only the running one', async () => {+ const part = (id: string, state: string, extra: object = {}) => ({+ type: 'tool-fetch',+ toolCallId: id,+ input: {},+ state,+ ...extra,+ })+ const stored = {+ id: 'a-tools',+ role: 'assistant',+ content: [],+ metadata: { parentId: 'u1' },+ }+ h.messagesState.getMessages = vi.fn(() => [stored])+ h.chatState.messages = [+ { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'go' }] },+ {+ id: 'a-tools',+ role: 'assistant',+ parts: [+ part('tcA', 'output-available', { output: 'result A' }),+ part('tcB', 'input-available'),+ ],+ },+ ]+ renderComponent()++ await act(async () => {+ screen.getByTestId('chat-stop').click()+ })++ const rewritten = h.messagesState.updateMessage.mock.calls+ .map((c: any[]) => c[0])+ .find((m: any) => m.id === 'a-tools')+ expect(rewritten.content).toEqual([+ { type: 'tool_call', tool_call_id: 'tcA', output: 'result A' },+ { type: 'tool_call', tool_call_id: 'tcB', output: undefined },+ ])+ expect(rewritten.metadata).toMatchObject({+ parentId: 'u1',+ stopped: true,+ toolErrors: { tcB: expect.stringContaining('Stopped') },+ })+ expect(rewritten.metadata.toolErrors).not.toHaveProperty('tcA')+ })++ // Leaving the thread deletes the loop controller but leaves the call+ // running. A Stop after coming back, with a newer turn sent since, must+ // still settle the turn that owns the call.+ it('Stop after returning to the thread still settles the turn that owns the call', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)+ hub.mcp = () =>+ ({+ callToolWithCancellation: () => ({+ promise: new Promise(() => {}),+ cancel: vi.fn().mockResolvedValue(undefined),+ token: 't',+ }),+ }) as never+ h.messagesState.getMessages = vi.fn(() => [+ { id: 'a-tc', role: 'assistant', content: [], metadata: {} },+ ])+ h.chatSessionsState.sessions = {+ 'thread-1': {+ chat: {+ messages: [+ {+ id: 'a-tc',+ role: 'assistant',+ parts: [+ {+ type: 'tool-fetch',+ toolCallId: 'tcA',+ input: {},+ state: 'input-available',+ },+ ],+ },+ { id: 'u2', role: 'user', parts: [{ type: 'text', text: 'again' }] },+ {+ id: 'a-newer',+ role: 'assistant',+ parts: [{ type: 'text', text: 'a newer turn' }],+ },+ ],+ },+ },+ }+ h.messagesState.updateMessage.mockClear()+ const Component = Route.component as React.ComponentType++ try {+ const { rerender } = renderComponent()+ await arrive('tcA')+ await act(async () => {+ await finishWithToolCalls()+ })++ h.routeParams.threadId = 'thread-2'+ rerender(<Component />)+ h.routeParams.threadId = 'thread-1'+ rerender(<Component />)++ await act(async () => {+ screen.getByTestId('chat-stop').click()+ })+ } finally {+ h.routeParams.threadId = 'thread-1'+ h.chatSessionsState.sessions = {}+ }++ const stored = h.messagesState.updateMessage.mock.calls+ .map((c: any[]) => c[0])+ .find((m: any) => m.id === 'a-tc')+ expect(stored.metadata.toolErrors).toEqual({+ tcA: expect.stringContaining('Stopped'),+ })+ })++ // The composer still sends while tools run, so the last message can be a+ // newer turn. Stop ends the older turn's loop, and that is the turn whose+ // call must be settled.+ it('Stop settles the turn whose loop it aborts, not just the last message', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ h.toolApprovalState.requestApproval = vi.fn(+ () => new Promise<boolean>(() => {})+ )+ h.messagesState.getMessages = vi.fn(() => [+ { id: 'a-tc', role: 'assistant', content: [], metadata: {} },+ ])+ h.chatSessionsState.sessions = {+ 'thread-1': {+ chat: {+ messages: [+ {+ id: 'a-tc',+ role: 'assistant',+ parts: [+ {+ type: 'tool-fetch',+ toolCallId: 'tcA',+ input: {},+ state: 'input-available',+ },+ ],+ },+ { id: 'u2', role: 'user', parts: [{ type: 'text', text: 'again' }] },+ {+ id: 'a-newer',+ role: 'assistant',+ parts: [{ type: 'text', text: 'a newer turn' }],+ },+ ],+ },+ },+ }+ h.messagesState.updateMessage.mockClear()++ try {+ renderComponent()+ await arrive('tcA')+ await act(async () => {+ await finishWithToolCalls()+ })+ await act(async () => {+ screen.getByTestId('chat-stop').click()+ })+ } finally {+ h.chatSessionsState.sessions = {}+ }++ const stored = h.messagesState.updateMessage.mock.calls+ .map((c: any[]) => c[0])+ .find((m: any) => m.id === 'a-tc')+ expect(stored.metadata.toolErrors).toEqual({+ tcA: expect.stringContaining('Stopped'),+ })+ })++ // The rendered messages are throttled; the SDK's chat state is current.+ // A result that landed inside the throttle window must not be saved as a+ // stopped call while the live copy holds it.+ it('Stop saves from the live chat state, not the throttled snapshot', async () => {+ const part = (state: string, extra: object = {}) => ({+ type: 'tool-fetch',+ toolCallId: 'tcA',+ input: {},+ state,+ ...extra,+ })+ h.messagesState.getMessages = vi.fn(() => [+ { id: 'a-tools', role: 'assistant', content: [], metadata: {} },+ ])+ // Stale: still waiting on the call.+ h.chatState.messages = [+ { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'go' }] },+ { id: 'a-tools', role: 'assistant', parts: [part('input-available')] },+ ]+ // Live: the result has just landed, and a second call is unfinished.+ h.chatSessionsState.sessions = {+ 'thread-1': {+ chat: {+ messages: [+ { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'go' }] },+ {+ id: 'a-tools',+ role: 'assistant',+ parts: [+ part('output-available', { output: 'result A' }),+ { ...part('input-available'), toolCallId: 'tcB' },+ ],+ },+ ],+ },+ },+ }+ renderComponent()++ try {+ await act(async () => {+ screen.getByTestId('chat-stop').click()+ })+ } finally {+ h.chatSessionsState.sessions = {}+ }++ const rewritten = h.messagesState.updateMessage.mock.calls+ .map((c: any[]) => c[0])+ .find((m: any) => m.id === 'a-tools')+ expect(rewritten.content[0]).toMatchObject({+ tool_call_id: 'tcA',+ output: 'result A',+ })+ expect(rewritten.metadata.toolErrors).toEqual({+ tcB: expect.stringContaining('Stopped'),+ })+ })+it('drains the runtime queue and times every call', async () => {h.appStateState.mcpToolNames = new Set(['fetch'])renderComponent()@@ -1234,6 +1820,169 @@ describe('ThreadDetail route', () => {}})+ // Leaving the thread resolves a pending approval as denied. It must be+ // recorded, or the call stays "Running" with nothing running, but not as a+ // refusal by the user: the model reads this on the next turn.+ it('records a cut-short approval as the chat closing, not a user denial', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ let decide: (approved: boolean) => void = () => {}+ h.toolApprovalState.requestApproval = vi.fn(+ () => new Promise<boolean>((resolve) => (decide = resolve))+ )+ h.mockAddToolOutput.mockClear()++ const { unmount } = renderComponent()+ await arrive('tcA')+ await act(async () => {+ await finishWithToolCalls()+ })+ unmount()+ await act(async () => {+ decide(false)+ })++ expect(h.mockAddToolOutput).toHaveBeenCalledWith(+ expect.objectContaining({+ toolCallId: 'tcA',+ state: 'output-error',+ errorText: expect.stringContaining('chat was closed'),+ })+ )+ })++ // No reply follows once the thread is left, and a reply is what rewrites a+ // stored turn. Without a rewrite here the call reloads as "Running".+ it('stores the outcome of a call cut short by leaving the thread', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ let decide: (approved: boolean) => void = () => {}+ h.toolApprovalState.requestApproval = vi.fn(+ () => new Promise<boolean>((resolve) => (decide = resolve))+ )+ h.messagesState.getMessages = vi.fn(() => [+ { id: 'a-tc', role: 'assistant', content: [], metadata: {} },+ ])+ h.chatSessionsState.sessions = {+ 'thread-1': {+ chat: {+ messages: [+ {+ id: 'a-tc',+ role: 'assistant',+ parts: [+ {+ type: 'tool-fetch',+ toolCallId: 'tcA',+ input: {},+ state: 'output-error',+ errorText: 'Tool call cancelled: the chat was closed before it ran.',+ },+ ],+ },+ // The user came back and started another turn meanwhile.+ {+ id: 'a-new',+ role: 'assistant',+ parts: [{ type: 'text', text: 'a newer turn' }],+ },+ ],+ },+ },+ }+ h.messagesState.updateMessage.mockClear()++ try {+ const { unmount } = renderComponent()+ await arrive('tcA')+ await act(async () => {+ await finishWithToolCalls()+ })+ unmount()+ await act(async () => {+ decide(false)+ })+ } finally {+ h.chatSessionsState.sessions = {}+ }++ const stored = h.messagesState.updateMessage.mock.calls+ .map((c: any[]) => c[0])+ .find((m: any) => m.id === 'a-tc')+ expect(stored.metadata.toolErrors).toEqual({+ tcA: expect.stringContaining('chat was closed'),+ })+ expect(stored.metadata.stopped).toBeUndefined()+ })++ // The approval promises are shared by every thread's loop. A thread whose+ // turn is cut off must forget only its own, or the thread in front would+ // be asked again about a call the user may already have allowed.+ it('another thread ending does not drop the approval in flight here', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ h.toolApprovalState.requestApproval = vi.fn(+ () => new Promise<boolean>(() => {})+ )+ const Component = Route.component as React.ComponentType++ try {+ const { rerender } = renderComponent()+ const onFinishA = (h as any).capturedOnFinish++ h.routeParams.threadId = 'thread-2'+ rerender(<Component />)+ await arrive('tcB')+ expect(h.toolApprovalState.requestApproval).toHaveBeenCalledTimes(1)++ // Thread 1's turn is cut off in the background.+ await act(async () => {+ await onFinishA({+ message: {+ id: 'a-bg',+ role: 'assistant',+ parts: [{ type: 'text', text: '' }],+ metadata: {},+ },+ isAbort: true,+ })+ })+ await act(async () => {+ await finishWithToolCalls()+ })++ expect(h.toolApprovalState.requestApproval).toHaveBeenCalledTimes(1)+ } finally {+ h.routeParams.threadId = 'thread-1'+ }+ })++ // The calls queued behind the one awaiting approval are cut short too.+ it('settles the calls queued behind one whose approval was cut short', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ const decide: Record<string, (approved: boolean) => void> = {}+ h.toolApprovalState.requestApproval = vi.fn(+ (id: string) =>+ new Promise<boolean>((resolve) => (decide[id] = resolve))+ )+ h.mockAddToolOutput.mockClear()++ const { unmount } = renderComponent()+ await arrive('tcA', 'tcB')+ await act(async () => {+ await finishWithToolCalls()+ })+ unmount()+ await act(async () => {+ decide.tcA(false)+ })++ const settled = h.mockAddToolOutput.mock.calls.map(+ (c: any[]) => c[0].toolCallId+ )+ expect(settled).toEqual(['tcA', 'tcB'])+ expect(h.mockAddToolOutput).toHaveBeenLastCalledWith(+ expect.objectContaining({ toolCallId: 'tcB', state: 'output-error' })+ )+ })+it('keeps going when one call is denied', async () => {h.appStateState.mcpToolNames = new Set(['fetch'])h.toolApprovalState.requestApproval = vi.fn((id: string) =>diff --git a/web-app/src/services/mcp/tauri.ts b/web-app/src/services/mcp/tauri.tsindex 640115fe4..db8c59f7f 100644--- a/web-app/src/services/mcp/tauri.ts+++ b/web-app/src/services/mcp/tauri.ts@@ -93,6 +93,7 @@ export class TauriMCPService extends DefaultMCPService {serverName?: stringarguments: objectcancellationToken?: string+ maxOutputChars?: number}): {promise: Promise<{ error: string; content: { text: string }[] }>cancel: () => Promise<void>diff --git a/web-app/src/services/mcp/types.ts b/web-app/src/services/mcp/types.tsindex 8945540f6..695fbccf5 100644--- a/web-app/src/services/mcp/types.ts+++ b/web-app/src/services/mcp/types.ts@@ -76,6 +76,7 @@ export interface MCPService {serverName?: stringarguments: objectcancellationToken?: string+ maxOutputChars?: number}): ToolCallWithCancellationResultcancelToolCall(cancellationToken: string): Promise<void>