Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(chat): stop MCP tool-approval popup from hanging; move transient approval state off disk (#8391)
Akarshan Biswas96ad8d39075e
diff --git a/web-app/src/components/ai-elements/tool.tsx b/web-app/src/components/ai-elements/tool.tsxindex 2aab7e597..fd80d5be3 100644--- a/web-app/src/components/ai-elements/tool.tsx+++ b/web-app/src/components/ai-elements/tool.tsx@@ -20,7 +20,7 @@ import {useState,} from 'react'import { CodeBlock } from './code-block'-import { useToolApproval } from '@/hooks/useToolApproval'+import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'import { useTranslation } from '@/i18n/react-i18next-compat'import { Button } from '@/components/ui/button'import { ShieldAlertIcon } from 'lucide-react'@@ -67,7 +67,7 @@ export const Tool = memo(children,...props}: ToolProps) => {- const isPending = useToolApproval((s) =>+ const isPending = useToolApprovalRequests((s) =>toolCallId ? Boolean(s.pending[toolCallId]) : false)const [isOpen, setIsOpen] = useControllableState({@@ -137,7 +137,7 @@ const getStatusText = (export const ToolHeader = memo(({ className, title, state, type }: ToolHeaderProps) => {const { isOpen, toolCallId } = useTool()- const awaitingApproval = useToolApproval((s) =>+ const awaitingApproval = useToolApprovalRequests((s) =>toolCallId ? Boolean(s.pending[toolCallId]) : false)const toolName = title ?? type.split('-').slice(1).join('-')@@ -225,10 +225,10 @@ export const ToolInput = memo(export const ToolApprovalActions = memo(() => {const { t } = useTranslation()const { toolCallId } = useTool()- const pending = useToolApproval((s) =>+ const pending = useToolApprovalRequests((s) =>toolCallId ? s.pending[toolCallId] : undefined)- const resolveApproval = useToolApproval((s) => s.resolveApproval)+ const resolveApproval = useToolApprovalRequests((s) => s.resolveApproval)if (!pending || !toolCallId) return nulldiff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsxindex 662498ae0..8e5f90efa 100644--- a/web-app/src/containers/MessageItem.tsx+++ b/web-app/src/containers/MessageItem.tsx@@ -38,7 +38,7 @@ import { useMemo } from 'react'import { Button } from '@/components/ui/button'import { PromptProgress } from '@/components/PromptProgress'import { useServiceHub } from '@/hooks/useServiceHub'-import { useToolApproval } from '@/hooks/useToolApproval'+import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'import { parseCitationsFromToolOutput } from '@/lib/citation-parser'import type { RagCitation } from '@/components/Citations'import { useGroundingStore } from '@/stores/grounding-store'@@ -151,7 +151,7 @@ export const MessageItem = memo(})}, [isLastMessage, message.role, message.parts])- const pendingApprovals = useToolApproval((s) => s.pending)+ const pendingApprovals = useToolApprovalRequests((s) => s.pending)const awaitingApproval = useMemo(() => {if (!hasPendingToolCall) return falsereturn message.parts.some((part) => {@@ -490,9 +490,17 @@ export const MessageItem = memo(return part.type.startsWith('tool-') && 'state' in part}const meaningful = entries.filter(isMeaningfulEntry)+ // While streaming, show only the latest step — but never truncate away a+ // tool part that is awaiting the user's approval, or its approve/deny+ // controls would never mount and the run would hang (multi-tool turns).+ const lastMeaningful = meaningful[meaningful.length - 1]const visibleEntries =groupIsStreaming && meaningful.length > 0- ? [meaningful[meaningful.length - 1]]+ ? meaningful.filter((e) => {+ if (e === lastMeaningful) return true+ const toolCallId = (e.part as { toolCallId?: string }).toolCallId+ return Boolean(toolCallId && pendingApprovals[toolCallId])+ }): entries// Streaming label reflects the current step, not whether the whole tracediff --git a/web-app/src/containers/__tests__/MessageItem.test.tsx b/web-app/src/containers/__tests__/MessageItem.test.tsxindex fe80f5201..baec86464 100644--- a/web-app/src/containers/__tests__/MessageItem.test.tsx+++ b/web-app/src/containers/__tests__/MessageItem.test.tsx@@ -105,8 +105,8 @@ vi.mock('@/components/PromptProgress', () => ({}))const pendingApprovalsRef = vi.hoisted(() => ({ current: {} as any }))-vi.mock('@/hooks/useToolApproval', () => ({- useToolApproval: (selector: any) =>+vi.mock('@/hooks/useToolApprovalRequests', () => ({+ useToolApprovalRequests: (selector: any) =>selector({ pending: pendingApprovalsRef.current }),}))@@ -473,6 +473,54 @@ describe('MessageItem', () => {expect(screen.queryByTestId('prompt-progress')).not.toBeInTheDocument()})+ it('keeps an earlier tool part visible while it awaits approval (multi-tool turn)', () => {+ // Two tool calls in one streaming turn; the first is awaiting approval.+ // Streaming truncation must not hide it, or its approve/deny controls+ // never mount and the run hangs.+ pendingApprovalsRef.current = { 'tc-alpha': {} }+ render(+ <MessageItem+ message={+ makeMsg({+ parts: [+ { type: 'tool-alpha', state: 'input-available', toolCallId: 'tc-alpha', input: {} },+ { type: 'tool-beta', state: 'input-available', toolCallId: 'tc-beta', input: {} },+ ],+ }) as any+ }+ isFirstMessage+ isLastMessage+ status={'streaming' as any}+ />+ )+ const headers = screen.getAllByTestId('tool-header').map((h) => h.textContent)+ expect(headers).toContain('alpha')+ expect(headers).toContain('beta')+ })++ it('still truncates a non-pending earlier tool step while streaming', () => {+ // No pending approval: streaming truncation keeps only the latest step.+ pendingApprovalsRef.current = {}+ render(+ <MessageItem+ message={+ makeMsg({+ parts: [+ { type: 'tool-alpha', state: 'input-available', toolCallId: 'tc-alpha', input: {} },+ { type: 'tool-beta', state: 'input-available', toolCallId: 'tc-beta', input: {} },+ ],+ }) as any+ }+ isFirstMessage+ isLastMessage+ status={'streaming' as any}+ />+ )+ const headers = screen.getAllByTestId('tool-header').map((h) => h.textContent)+ expect(headers).not.toContain('alpha')+ expect(headers).toContain('beta')+ })+it('passes full text to copy button', () => {render(<MessageItemdiff --git a/web-app/src/hooks/__tests__/useToolApprovalRequests.test.ts b/web-app/src/hooks/__tests__/useToolApprovalRequests.test.tsnew file mode 100644index 000000000..eca41c3c7--- /dev/null+++ b/web-app/src/hooks/__tests__/useToolApprovalRequests.test.ts@@ -0,0 +1,154 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { renderHook, act } from '@testing-library/react'+import { useToolApprovalRequests } from '../useToolApprovalRequests'+import { useToolApproval } from '../useToolApproval'++// useToolApproval persists via backendStorage; stub the persist layer so the+// import is inert and no disk I/O happens in tests.+vi.mock('@/constants/localStorage', () => ({+ localStorageKey: { toolApproval: 'tool-approval-settings' },+}))+vi.mock('zustand/middleware', () => ({+ persist: (fn: any) => fn,+ createJSONStorage: () => ({+ getItem: vi.fn(),+ setItem: vi.fn(),+ removeItem: vi.fn(),+ }),+}))++describe('useToolApprovalRequests', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ useToolApprovalRequests.setState({ pending: {} })+ useToolApproval.setState({+ approvedTools: {},+ allowAllMCPPermissions: false,+ })+ })++ it('stores a pending approval keyed by toolCallId', () => {+ const { result } = renderHook(() => useToolApprovalRequests())++ act(() => {+ result.current.requestApproval('tc1', 'tool-a', 'thread-1')+ })++ expect(result.current.pending['tc1']).toMatchObject({+ toolCallId: 'tc1',+ toolName: 'tool-a',+ threadId: 'thread-1',+ })+ })++ it('auto-resolves true (no pending) when allowAllMCPPermissions is set', async () => {+ useToolApproval.setState({ allowAllMCPPermissions: true })+ const { result } = renderHook(() => useToolApprovalRequests())++ let p: Promise<boolean>+ act(() => {+ p = result.current.requestApproval('tc1', 'tool-a', 'thread-1')+ })++ await expect(p!).resolves.toBe(true)+ expect(result.current.pending['tc1']).toBeUndefined()+ })++ it('auto-resolves true (no pending) when the tool is already approved for the thread', async () => {+ act(() => {+ useToolApproval.getState().approveToolForThread('thread-1', 'tool-a')+ })+ const { result } = renderHook(() => useToolApprovalRequests())++ let p: Promise<boolean>+ act(() => {+ p = result.current.requestApproval('tc1', 'tool-a', 'thread-1')+ })++ await expect(p!).resolves.toBe(true)+ expect(result.current.pending['tc1']).toBeUndefined()+ })++ it('resolveApproval allow-once resolves true without persisting the tool', async () => {+ const { result } = renderHook(() => useToolApprovalRequests())++ let p: Promise<boolean>+ act(() => {+ p = result.current.requestApproval('tc1', 'tool-a', 'thread-1')+ })+ act(() => {+ result.current.resolveApproval('tc1', 'allow-once')+ })++ await expect(p!).resolves.toBe(true)+ expect(useToolApproval.getState().isToolApproved('thread-1', 'tool-a')).toBe(false)+ expect(result.current.pending['tc1']).toBeUndefined()+ })++ it('resolveApproval allow-always resolves true and persists the tool for the thread', async () => {+ const { result } = renderHook(() => useToolApprovalRequests())++ let p: Promise<boolean>+ act(() => {+ p = result.current.requestApproval('tc1', 'tool-a', 'thread-1')+ })+ act(() => {+ result.current.resolveApproval('tc1', 'allow-always')+ })++ await expect(p!).resolves.toBe(true)+ expect(useToolApproval.getState().isToolApproved('thread-1', 'tool-a')).toBe(true)+ })++ it('resolveApproval deny resolves false', async () => {+ const { result } = renderHook(() => useToolApprovalRequests())++ let p: Promise<boolean>+ act(() => {+ p = result.current.requestApproval('tc1', 'tool-a', 'thread-1')+ })+ act(() => {+ result.current.resolveApproval('tc1', 'deny')+ })++ await expect(p!).resolves.toBe(false)+ expect(useToolApproval.getState().isToolApproved('thread-1', 'tool-a')).toBe(false)+ })++ it('clearPendingForThread resolves matching promises false and removes only that thread', async () => {+ const { result } = renderHook(() => useToolApprovalRequests())++ let pA: Promise<boolean>+ let pB: Promise<boolean>+ act(() => {+ pA = result.current.requestApproval('tcA', 'tool-a', 'thread-A')+ pB = result.current.requestApproval('tcB', 'tool-b', 'thread-B')+ })++ act(() => {+ result.current.clearPendingForThread('thread-A')+ })++ await expect(pA!).resolves.toBe(false)+ expect(result.current.pending['tcA']).toBeUndefined()+ expect(result.current.pending['tcB']).toMatchObject({ threadId: 'thread-B' })++ act(() => {+ result.current.resolveApproval('tcB', 'allow-once')+ })+ await expect(pB!).resolves.toBe(true)+ })++ it('clearPendingForThread is a no-op when nothing matches', () => {+ const { result } = renderHook(() => useToolApprovalRequests())++ act(() => {+ result.current.requestApproval('tcA', 'tool-a', 'thread-A')+ })+ act(() => {+ result.current.clearPendingForThread('thread-Z')+ })++ expect(result.current.pending['tcA']).toMatchObject({ threadId: 'thread-A' })+ })+})diff --git a/web-app/src/hooks/useToolApproval.ts b/web-app/src/hooks/useToolApproval.tsindex 6222bb4aa..998241d0b 100644--- a/web-app/src/hooks/useToolApproval.ts+++ b/web-app/src/hooks/useToolApproval.ts@@ -11,28 +11,15 @@ export type ToolApprovalModalProps = {onDeny: () => void}-export type PendingApproval = {- toolCallId: string- toolName: string- threadId: string- resolve: (approved: boolean) => void-}--export type ApprovalDecision = 'allow-once' | 'allow-always' | 'deny'-type ToolApprovalState = {approvedTools: Record<string, string[]>allowAllMCPPermissions: booleanisModalOpen: booleanmodalProps: ToolApprovalModalProps | null- pending: Record<string, PendingApproval>approveToolForThread: (threadId: string, toolName: string) => voidisToolApproved: (threadId: string, toolName: string) => booleanshowApprovalModal: (toolName: string, threadId: string, toolParameters?: object) => Promise<boolean>- requestApproval: (toolCallId: string, toolName: string, threadId: string) => Promise<boolean>- resolveApproval: (toolCallId: string, decision: ApprovalDecision) => void- isApprovalPending: (toolCallId: string) => booleancloseModal: () => voidsetModalOpen: (open: boolean) => voidsetAllowAllMCPPermissions: (allow: boolean) => void@@ -45,7 +32,6 @@ export const useToolApproval = create<ToolApprovalState>()(allowAllMCPPermissions: false,isModalOpen: false,modalProps: null,- pending: {},approveToolForThread: (threadId: string, toolName: string) => {set((state) => ({@@ -103,44 +89,6 @@ export const useToolApproval = create<ToolApprovalState>()(})},- requestApproval: (toolCallId, toolName, threadId) => {- return new Promise<boolean>((resolve) => {- const state = get()- if (state.allowAllMCPPermissions) {- resolve(true)- return- }- if (state.isToolApproved(threadId, toolName)) {- resolve(true)- return- }- set((s) => ({- pending: {- ...s.pending,- [toolCallId]: { toolCallId, toolName, threadId, resolve },- },- }))- })- },-- resolveApproval: (toolCallId, decision) => {- const entry = get().pending[toolCallId]- if (!entry) return- if (decision === 'allow-always') {- get().approveToolForThread(entry.threadId, entry.toolName)- }- set((s) => {- const next = { ...s.pending }- delete next[toolCallId]- return { pending: next }- })- entry.resolve(decision !== 'deny')- },-- isApprovalPending: (toolCallId) => {- return Boolean(get().pending[toolCallId])- },-closeModal: () => {set({isModalOpen: false,diff --git a/web-app/src/hooks/useToolApprovalRequests.ts b/web-app/src/hooks/useToolApprovalRequests.tsnew file mode 100644index 000000000..a9a1d45b3--- /dev/null+++ b/web-app/src/hooks/useToolApprovalRequests.ts@@ -0,0 +1,81 @@+import { create } from 'zustand'+import { useToolApproval } from './useToolApproval'++export type PendingApproval = {+ toolCallId: string+ toolName: string+ threadId: string+ resolve: (approved: boolean) => void+}++export type ApprovalDecision = 'allow-once' | 'allow-always' | 'deny'++type ToolApprovalRequestsState = {+ // In-flight per-tool-call approval prompts. Kept out of the persisted+ // useToolApproval store so approval churn never flushes to disk (the+ // resolve callbacks are non-serializable anyway).+ pending: Record<string, PendingApproval>++ requestApproval: (+ toolCallId: string,+ toolName: string,+ threadId: string+ ) => Promise<boolean>+ resolveApproval: (toolCallId: string, decision: ApprovalDecision) => void+ clearPendingForThread: (threadId: string) => void+}++export const useToolApprovalRequests = create<ToolApprovalRequestsState>()(+ (set, get) => ({+ pending: {},++ requestApproval: (toolCallId, toolName, threadId) => {+ return new Promise<boolean>((resolve) => {+ const settings = useToolApproval.getState()+ if (settings.allowAllMCPPermissions) {+ resolve(true)+ return+ }+ if (settings.isToolApproved(threadId, toolName)) {+ resolve(true)+ return+ }+ set((s) => ({+ pending: {+ ...s.pending,+ [toolCallId]: { toolCallId, toolName, threadId, resolve },+ },+ }))+ })+ },++ resolveApproval: (toolCallId, decision) => {+ const entry = get().pending[toolCallId]+ if (!entry) return+ if (decision === 'allow-always') {+ useToolApproval.getState().approveToolForThread(entry.threadId, entry.toolName)+ }+ set((s) => {+ const next = { ...s.pending }+ delete next[toolCallId]+ return { pending: next }+ })+ entry.resolve(decision !== 'deny')+ },++ clearPendingForThread: (threadId) => {+ const { pending } = get()+ const stranded = Object.values(pending).filter(+ (entry) => entry.threadId === threadId+ )+ if (stranded.length === 0) return+ set((s) => {+ const next = { ...s.pending }+ for (const entry of stranded) delete next[entry.toolCallId]+ return { pending: next }+ })+ // Resolve as denied so any awaiting tool loop unblocks instead of hanging.+ for (const entry of stranded) entry.resolve(false)+ },+ })+)diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex 8331e4052..ab5cadacb 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -71,6 +71,7 @@ import { useTranslation } from '@/i18n/react-i18next-compat'import { Button } from '@/components/ui/button'import { IconAlertCircle, IconRefresh, IconLoader2 } from '@tabler/icons-react'import { useToolApproval } from '@/hooks/useToolApproval'+import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'import DropdownModelProvider from '@/containers/DropdownModelProvider'import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'import { ExtensionManager } from '@/lib/extension'@@ -153,6 +154,12 @@ function ThreadDetail() {// AbortController for cancelling tool callsconst 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)@@ -387,11 +394,14 @@ function ThreadDetail() {}}- // Create a new AbortController for tool calls+ // 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- // Get cached tool names from store (initialized in useTools hook)const ragToolNames = useAppState.getState().ragToolNamesconst mcpToolNames = useAppState.getState().mcpToolNames@@ -399,10 +409,8 @@ function ThreadDetail() {// since streaming has already ended and isSessionBusy's tools-array read isn't reactive.useAppState.getState().setThreadBusy(threadId, true)- // Process tool calls sequentially, requesting approval for each if needed;(async () => {for (const toolCall of sessionData.tools) {- // Check if already aborted before startingif (signal.aborted) {break}@@ -413,12 +421,13 @@ function ThreadDetail() {// Built-in RAG tools are internal and should not require approval.const approved = ragToolNames.has(toolName)? true- : await useToolApproval- .getState()- .requestApproval(toolCall.toolCallId, toolName, threadId)+ : await (toolApprovalPromises.current.get(toolCall.toolCallId) ??+ useToolApprovalRequests+ .getState()+ .requestApproval(toolCall.toolCallId, toolName, threadId))+ toolApprovalPromises.current.delete(toolCall.toolCallId)if (!approved) {- // User denied the tool calladdToolOutput({state: 'output-error',tool: toolCall.toolName,@@ -430,7 +439,6 @@ function ThreadDetail() {let result- // Route to the appropriate service based on tool nameif (ragToolNames.has(toolName)) {result = await serviceHub.rag().callTool({toolName,@@ -445,7 +453,6 @@ function ThreadDetail() {arguments: toolCall.input,})} else {- // Tool not found in either serviceresult = {error: `Tool '${toolName}' not found in any service`,}@@ -466,7 +473,6 @@ function ThreadDetail() {})}} catch (error) {- // Ignore abort errorsif ((error as Error).name !== 'AbortError') {console.error('Tool call error:', error)addToolOutput({@@ -479,16 +485,16 @@ function ThreadDetail() {}}- // Clear tools after processing allsessionData.tools = []+ toolApprovalPromises.current.clear()toolCallAbortController.current = nulluseAppState.getState().setThreadBusy(threadId, false)})().catch((error) => {- // Ignore abort errorsif (error.name !== 'AbortError') {console.error('Tool call error:', error)}sessionData.tools = []+ toolApprovalPromises.current.clear()toolCallAbortController.current = nulluseAppState.getState().setThreadBusy(threadId, false)})@@ -557,7 +563,25 @@ function ThreadDetail() {}},onToolCall: ({ toolCall }) => {+ // Collect the tool for the onFinish execution loop, and request approval+ // right now so the popup appears immediately instead of waiting for the+ // stream's terminal finish chunk (a stalled stream would otherwise leave+ // the tool at "Running..." with no popup). Execution itself stays in+ // onFinish so the tool result lands on a completed message. RAG tools are+ // internal and never prompt.sessionData.tools.push(toolCall)+ const ragToolNames = useAppState.getState().ragToolNames+ if (+ !ragToolNames.has(toolCall.toolName) &&+ !toolApprovalPromises.current.has(toolCall.toolCallId)+ ) {+ toolApprovalPromises.current.set(+ toolCall.toolCallId,+ useToolApprovalRequests+ .getState()+ .requestApproval(toolCall.toolCallId, toolCall.toolName, threadId)+ )+ }},sendAutomaticallyWhen: followUpMessage,})@@ -749,6 +773,21 @@ function ThreadDetail() {// eslint-disable-next-line react-hooks/exhaustive-deps}, [])+ // The route component is reused across thread switches (no remount), so tear+ // down the in-flight tool loop and release approvals waiting on the thread we+ // 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.current+ return () => {+ toolCallAbortController.current?.abort()+ toolCallAbortController.current = null+ approvalPromises.clear()+ useToolApprovalRequests.getState().clearPendingForThread(threadId)+ }+ }, [threadId])+// Resync the OOM/backend banner from message metadata on every thread switch.// Persisted by LlamacppOomListener at error time; unset state when this// thread carries no such metadata so the banner doesn't leak across threads.diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsxindex cd5e668d8..f2a885af5 100644--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx@@ -114,9 +114,16 @@ const h = vi.hoisted(() => {const toolApprovalState: any = {showApprovalModal: vi.fn().mockResolvedValue(true),approveToolForThread: vi.fn(),+ clearPendingForThread: vi.fn(),+ requestApproval: vi.fn().mockResolvedValue(true),}const useToolApprovalMock: any = (selector: any) => selector(toolApprovalState)useToolApprovalMock.getState = () => toolApprovalState+ // Transient approval store shares the same backing object so existing+ // toolApprovalState.requestApproval / clearPendingForThread refs keep working.+ const useToolApprovalRequestsMock: any = (selector: any) =>+ selector(toolApprovalState)+ useToolApprovalRequestsMock.getState = () => toolApprovalStateconst agentModeState: any = { agentThreads: {} }const useAgentModeMock: any = (selector: any) => selector(agentModeState)@@ -156,6 +163,7 @@ const h = vi.hoisted(() => {useToolAvailableMock,toolApprovalState,useToolApprovalMock,+ useToolApprovalRequestsMock,agentModeState,useAgentModeMock,messageQueueState,@@ -338,6 +346,7 @@ vi.mock('zustand/react/shallow', () => ({vi.mock('@/hooks/use-chat', () => ({useChat: (_args: any) => {;(h as any).capturedOnFinish = _args?.onFinish+ ;(h as any).capturedOnToolCall = _args?.onToolCallreturn {messages: h.chatState.messages,status: h.chatState.status,@@ -366,6 +375,9 @@ vi.mock('@/hooks/useChatAttachments', () => ({vi.mock('@/hooks/useAttachments', () => ({ useAttachments: h.useAttachmentsMock }))vi.mock('@/hooks/useToolAvailable', () => ({ useToolAvailable: h.useToolAvailableMock }))vi.mock('@/hooks/useToolApproval', () => ({ useToolApproval: h.useToolApprovalMock }))+vi.mock('@/hooks/useToolApprovalRequests', () => ({+ useToolApprovalRequests: h.useToolApprovalRequestsMock,+}))vi.mock('@/hooks/useAgentMode', () => ({ useAgentMode: h.useAgentModeMock }))vi.mock('@/stores/message-queue-store', () => ({ useMessageQueue: h.useMessageQueueMock }))@@ -443,6 +455,9 @@ describe('ThreadDetail route', () => {h.agentModeState.agentThreads = {}h.modelProviderState.selectedProvider = 'openai'h.appStateState.oomError = undefined+ h.appStateState.ragToolNames = new Set<string>()+ h.appStateState.mcpToolNames = new Set<string>()+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)sessionStorage.clear()})@@ -472,6 +487,12 @@ describe('ThreadDetail route', () => {expect(h.threadsState.setCurrentThreadId).toHaveBeenLastCalledWith(undefined)})+ it('clears this thread pending tool approvals on unmount', () => {+ const { unmount } = renderComponent()+ unmount()+ expect(h.toolApprovalState.clearPendingForThread).toHaveBeenCalledWith('thread-1')+ })+it('renders messages passed through useChat', () => {h.chatState.messages = [{ id: 'm-a', role: 'user', parts: [{ type: 'text', text: 'hi' }] },@@ -683,6 +704,104 @@ describe('ThreadDetail route', () => {expect(persisted.metadata.parentId).not.toBeNull()})+ describe('tool-call approval requested early, execution stays in onFinish', () => {+ const toolCall = (id: string) => ({+ toolCall: { toolCallId: id, toolName: 'fetch', input: { url: 'x' } },+ })+ const finishWithToolCalls = () =>+ (h as any).capturedOnFinish({+ message: {+ id: 'a-tc',+ role: 'assistant',+ parts: [{ type: 'text', text: '' }],+ metadata: { finishReason: 'tool-calls' },+ },+ isAbort: false,+ })++ it('requests approval as soon as a tool call arrives, before onFinish', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)+ renderComponent()++ expect((h as any).capturedOnToolCall).toBeTypeOf('function')++ await act(async () => {+ await (h as any).capturedOnToolCall(toolCall('tc1'))+ })++ // Popup is requested purely from the tool-call arrival, decoupled from onFinish.+ expect(h.toolApprovalState.requestApproval).toHaveBeenCalledWith(+ 'tc1',+ 'fetch',+ 'thread-1'+ )+ })++ it('does NOT execute the tool from onToolCall (execution deferred to onFinish)', async () => {+ // Executing during streaming lands addToolResult on an incomplete message,+ // which suppresses auto-resubmit and makes the model appear to "stop".+ h.appStateState.mcpToolNames = new Set(['fetch'])+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)+ renderComponent()++ await act(async () => {+ await (h as any).capturedOnToolCall(toolCall('tc1'))+ })++ expect(h.mockAddToolOutput).not.toHaveBeenCalled()+ })++ it('executes approved tools in onFinish so the completed message can auto-resubmit', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)+ renderComponent()++ await act(async () => {+ await (h as any).capturedOnToolCall(toolCall('tc2'))+ })+ await act(async () => {+ await finishWithToolCalls()+ })++ // Global setup mock resolves callTool to { error: '', content: [] }.+ expect(h.mockAddToolOutput).toHaveBeenCalledWith(+ expect.objectContaining({ toolCallId: 'tc2', tool: 'fetch' })+ )+ })++ it('reuses the early approval instead of prompting twice', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)+ renderComponent()++ await act(async () => {+ await (h as any).capturedOnToolCall(toolCall('tc4'))+ })+ await act(async () => {+ await finishWithToolCalls()+ })++ expect(h.toolApprovalState.requestApproval).toHaveBeenCalledTimes(1)+ })++ it('marks the thread busy during onFinish execution and clears it when tools drain', async () => {+ h.appStateState.mcpToolNames = new Set(['fetch'])+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)+ renderComponent()++ await act(async () => {+ await (h as any).capturedOnToolCall(toolCall('tc5'))+ })+ await act(async () => {+ await finishWithToolCalls()+ })++ expect(h.appStateState.setThreadBusy).toHaveBeenCalledWith('thread-1', true)+ expect(h.appStateState.setThreadBusy).toHaveBeenLastCalledWith('thread-1', false)+ })+ })+it('delete removes message from store and chat list', () => {h.chatState.messages = [{ id: 'u1', role: 'user', parts: [{ type: 'text', text: 'hi' }] },