Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(chat): a switch to turn the shell tool off (#9222) (#9235)

Thinh Le16ad13968930
diff --git a/web-app/src/constants/localStorage.ts b/web-app/src/constants/localStorage.ts
index 6f75f74a0..6f573618a 100644
--- a/web-app/src/constants/localStorage.ts
+++ b/web-app/src/constants/localStorage.ts
@@ -13,6 +13,7 @@ export const localStorageKey = {
settingWebSearch: 'setting-web-search',
settingCowork: 'setting-cowork',
settingImageAttachments: 'setting-image-attachments',
+ settingChatShell: 'setting-chat-shell',
settingHardware: 'setting-hardware',
settingVulkan: 'setting-vulkan',
productAnalyticPrompt: 'productAnalyticPrompt',
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index 334bf2fd1..f0d2feba6 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -34,6 +34,7 @@ import {
IconPaperclip,
IconLoader2,
IconWorldSearch,
+ IconTerminal2,
IconBrandChrome,
IconDots,
} from '@tabler/icons-react'
@@ -66,7 +67,8 @@ import {
SESSION_STORAGE_PREFIX,
} from '@/constants/chat'
import { defaultModel } from '@/lib/models'
-import { cancelAgentThreadBash } from '@/lib/agentTools'
+import { cancelAgentThreadBash, getSandboxStatus } from '@/lib/agentTools'
+import { useChatShell } from '@/hooks/useChatShell'
import { useAssistant } from '@/hooks/useAssistant'
import { AssistantSwitcher } from '@/containers/AssistantSwitcher'
import DropdownToolsAvailable from '@/containers/DropdownToolsAvailable'
@@ -322,6 +324,20 @@ const ChatInput = memo(function ChatInput({
const showToolControls = ownsToolSet && !effectiveAgentMode
const webSearchEnabled = useWebSearchConfig((s) => s.webSearchEnabled)
const setWebSearchEnabled = useWebSearchConfig((s) => s.setWebSearchEnabled)
+ const shellEnabled = useChatShell((s) => s.shellEnabled)
+ const setShellEnabled = useChatShell((s) => s.setShellEnabled)
+ // The shell is only ever offered where a sandbox can confine it, so the
+ // switch is only shown there: with no backend there is nothing to turn off.
+ const [sandboxEnforcesShell, setSandboxEnforcesShell] = useState(false)
+ useEffect(() => {
+ let live = true
+ void getSandboxStatus().then((s) => {
+ if (live) setSandboxEnforcesShell(s.enforces)
+ })
+ return () => {
+ live = false
+ }
+ }, [])
const [filePickerOpen, setFilePickerOpen] = useState(false)
const [filePickerQuery, setFilePickerQuery] = useState('')
@@ -2564,6 +2580,38 @@ const ChatInput = memo(function ChatInput({
</Tooltip>
)}
+ {showToolControls &&
+ sandboxEnforcesShell &&
+ selectedModel?.capabilities?.includes('tools') && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-pressed={shellEnabled}
+ aria-label={t('common:shell')}
+ className={cn(shellEnabled && 'text-primary')}
+ onClick={() => setShellEnabled(!shellEnabled)}
+ >
+ <IconTerminal2
+ size={18}
+ className={cn(
+ 'text-muted-foreground',
+ shellEnabled && 'text-primary'
+ )}
+ />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>
+ {shellEnabled
+ ? t('common:shell') + t('common:activeSuffix')
+ : t('common:shell')}
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ )}
+
{!effectiveAgentMode &&
(selectedProvider === 'llamacpp' ||
selectedProvider === 'google' ||
diff --git a/web-app/src/hooks/__tests__/useChatShell.test.ts b/web-app/src/hooks/__tests__/useChatShell.test.ts
new file mode 100644
index 000000000..db957a9b9
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useChatShell.test.ts
@@ -0,0 +1,49 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// Real zustand persist, fake disk, as in useCoworkConfig.test.ts.
+const disk = vi.hoisted(() => new Map<string, string>())
+vi.mock('@/lib/backendStorage', () => ({
+ backendStorage: {
+ getItem: async (name: string) => disk.get(name) ?? null,
+ setItem: async (name: string, value: string) => {
+ disk.set(name, value)
+ },
+ removeItem: async (name: string) => {
+ disk.delete(name)
+ },
+ },
+}))
+
+import { useChatShell } from '../useChatShell'
+
+describe('useChatShell', () => {
+ beforeEach(() => {
+ disk.clear()
+ useChatShell.setState({ shellEnabled: true })
+ })
+
+ // Existing users must keep the shell they have today until they say no.
+ it('is on by default', () => {
+ expect(useChatShell.getState().shellEnabled).toBe(true)
+ })
+
+ it('flushes an off switch to the backend store', async () => {
+ useChatShell.getState().setShellEnabled(false)
+ await vi.waitFor(() => {
+ expect(JSON.parse(disk.get('setting-chat-shell') ?? '{}').state).toEqual({
+ shellEnabled: false,
+ })
+ })
+ })
+
+ // A record already on disk wins over the default: how an off switch survives
+ // an app restart.
+ it('hydrates an off switch from disk', async () => {
+ disk.set(
+ 'setting-chat-shell',
+ JSON.stringify({ state: { shellEnabled: false }, version: 0 })
+ )
+ await useChatShell.persist.rehydrate()
+ expect(useChatShell.getState().shellEnabled).toBe(false)
+ })
+})
diff --git a/web-app/src/hooks/useChatShell.ts b/web-app/src/hooks/useChatShell.ts
new file mode 100644
index 000000000..6168be11b
--- /dev/null
+++ b/web-app/src/hooks/useChatShell.ts
@@ -0,0 +1,29 @@
+import { create } from 'zustand'
+import { persist, createJSONStorage } from 'zustand/middleware'
+import { localStorageKey } from '@/constants/localStorage'
+import { backendStorage } from '@/lib/backendStorage'
+
+type ChatShellState = {
+ /**
+ * Whether the main chat offers the model its sandboxed shell. On by default,
+ * since the sandbox confines it; but a command runner is something a user must
+ * be able to refuse outright (#9222), so it is a switch and not a given.
+ * Cowork owns its own tool set and does not read this.
+ */
+ shellEnabled: boolean
+ setShellEnabled: (value: boolean) => void
+}
+
+export const useChatShell = create<ChatShellState>()(
+ persist(
+ (set) => ({
+ shellEnabled: true,
+ setShellEnabled: (shellEnabled) => set({ shellEnabled }),
+ }),
+ {
+ name: localStorageKey.settingChatShell,
+ storage: createJSONStorage(() => backendStorage),
+ skipHydration: true,
+ }
+ )
+)
diff --git a/web-app/src/lib/__tests__/custom-chat-transport-shell-switch.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-shell-switch.test.ts
new file mode 100644
index 000000000..5d6c9d05b
--- /dev/null
+++ b/web-app/src/lib/__tests__/custom-chat-transport-shell-switch.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest'
+
+// #9222: a user who turns the chat shell off must get neither the tool nor the
+// prompt paragraph that describes it.
+const h = vi.hoisted(() => ({
+ shellEnabled: true,
+ sandbox: true,
+ schemas: vi.fn(),
+}))
+
+vi.mock('@/hooks/useChatShell', () => ({
+ useChatShell: { getState: () => ({ shellEnabled: h.shellEnabled }) },
+}))
+vi.mock('@/lib/agentTools', () => ({
+ CHAT_AGENT_TOOL_NAMES: new Set(['shell']),
+ getAgentToolSchemas: h.schemas,
+ sandboxEnforces: () => h.sandbox,
+ memoryDigestNow: () => '',
+ refreshMemoryDigest: async () => '',
+}))
+vi.mock('@/hooks/useServiceHub', () => ({
+ useServiceStore: {
+ getState: () => ({
+ serviceHub: {
+ mcp: () => ({ getTools: async () => [] }),
+ rag: () => ({ getTools: async () => [] }),
+ },
+ }),
+ },
+}))
+vi.mock('@/hooks/useToolAvailable', () => ({
+ useToolAvailable: { getState: () => ({ getDisabledTools: () => [] }) },
+}))
+vi.mock('@/hooks/useModelProvider', () => ({
+ useModelProvider: {
+ getState: () => ({
+ selectedModel: { capabilities: ['tools'] },
+ selectedProvider: '',
+ getProviderByName: () => null,
+ }),
+ },
+}))
+vi.mock('@/hooks/useAssistant', () => ({
+ useAssistant: { getState: () => ({ currentAssistant: null }) },
+}))
+vi.mock('@/hooks/useThreads', () => ({
+ useThreads: { getState: () => ({ threads: {} }) },
+}))
+vi.mock('@/hooks/useAttachments', () => ({
+ useAttachments: { getState: () => ({ enabled: false }) },
+}))
+vi.mock('@/hooks/useMCPServers', () => ({
+ useMCPServers: {
+ getState: () => ({ settings: { enableSmartToolRouting: false } }),
+ },
+}))
+vi.mock('@/hooks/useWebSearchConfig', () => ({
+ useWebSearchConfig: { getState: () => ({ webSearchEnabled: false }) },
+}))
+vi.mock('@/lib/extension', () => ({
+ ExtensionManager: { getInstance: () => ({ get: () => null }) },
+}))
+vi.mock('@/lib/mcp-orchestrator', () => ({
+ mcpOrchestrator: { getRelevantTools: vi.fn() },
+}))
+vi.mock('@/lib/mcp-router-model-filter', () => ({
+ isRouterModelSelectable: () => false,
+}))
+vi.mock('../model-factory', () => ({
+ ModelFactory: { createModel: vi.fn() },
+}))
+
+import { CustomChatTransport } from '../custom-chat-transport'
+
+describe('chat shell switch (#9222)', () => {
+ let transport: CustomChatTransport
+
+ beforeEach(() => {
+ h.shellEnabled = true
+ h.sandbox = true
+ h.schemas.mockReset()
+ h.schemas.mockResolvedValue([
+ {
+ type: 'function',
+ function: {
+ name: 'shell',
+ description: 'run',
+ parameters: { type: 'object' },
+ },
+ },
+ ])
+ transport = new CustomChatTransport('sys', 'thread-1')
+ })
+
+ it('offers the shell and describes it while the switch is on', async () => {
+ await transport.refreshTools()
+ expect(Object.keys(transport.getTools())).toContain('shell')
+ expect(transport.buildAgentToolsSystemInstruction()).toContain('# Shell')
+ })
+
+ it('withholds the shell and its prompt text once the switch is off', async () => {
+ h.shellEnabled = false
+ await transport.refreshTools()
+ expect(Object.keys(transport.getTools())).not.toContain('shell')
+ expect(transport.buildAgentToolsSystemInstruction()).toBe('')
+ })
+
+ it('does not even ask the sandbox for schemas when the switch is off', async () => {
+ h.shellEnabled = false
+ await transport.refreshTools()
+ expect(h.schemas).not.toHaveBeenCalled()
+ })
+
+ it('takes effect on the very next send without a new transport', async () => {
+ await transport.refreshTools()
+ expect(Object.keys(transport.getTools())).toContain('shell')
+ h.shellEnabled = false
+ await transport.refreshTools()
+ expect(Object.keys(transport.getTools())).not.toContain('shell')
+ })
+})
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index f1316b4aa..823a740f9 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -28,6 +28,7 @@ import { useThreads } from '@/hooks/useThreads'
import { useAttachments } from '@/hooks/useAttachments'
import { useMCPServers } from '@/hooks/useMCPServers'
import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'
+import { useChatShell } from '@/hooks/useChatShell'
import {
WEB_SEARCH_DESCRIPTION,
WEB_SEARCH_INPUT_SCHEMA,
@@ -1179,9 +1180,11 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
// The main chat offers exactly one built-in agent tool: the sandboxed
// shell, with no network. The full toolset lives in Cowork. Schemas come
// from Rust so they are never re-typed here, and `getAgentToolSchemas`
- // already withholds shell when no sandbox backend can confine it.
+ // already withholds shell when no sandbox backend can confine it. A user
+ // who switched it off (#9222) gets none of it.
try {
- for (const schema of await getAgentToolSchemas()) {
+ const shellOn = useChatShell.getState().shellEnabled
+ for (const schema of shellOn ? await getAgentToolSchemas() : []) {
if (!CHAT_AGENT_TOOL_NAMES.has(schema.function.name)) continue
toolsRecord[schema.function.name] = {
description: schema.function.description,
@@ -1810,12 +1813,6 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
].join(' ')
}
- /**
- * Static instruction for the one built-in tool chat offers: the sandboxed
- * shell. Empty when no sandbox backend enforces, because shell is then
- * withheld too — stating limits for a tool that is not offered would only
- * confuse the model, and an empty string keeps the prompt prefix stable.
- */
/**
* A self-contained digest of the newest memory notes. Chat advertises no
* memory tools, so a catalog it cannot dereference would be useless; whole
@@ -1834,8 +1831,16 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
].join('\n')
}
+ /**
+ * Static instruction for the one built-in tool chat offers: the sandboxed
+ * shell. Empty when no sandbox backend enforces or when the user has turned
+ * the shell off, because shell is then withheld too — stating limits for a
+ * tool that is not offered would only confuse the model, and an empty string
+ * keeps the prompt prefix stable.
+ */
buildAgentToolsSystemInstruction(): string {
- if (!sandboxEnforces()) return ''
+ // Describing a tool the model was not given only invites it to ask for it.
+ if (!useChatShell.getState().shellEnabled || !sandboxEnforces()) return ''
// Stating the limits up front is cheaper than letting the model discover
// them by having a command refused.
return [
diff --git a/web-app/src/lib/hydrateStores.ts b/web-app/src/lib/hydrateStores.ts
index 3b4178c38..0fa3f017c 100644
--- a/web-app/src/lib/hydrateStores.ts
+++ b/web-app/src/lib/hydrateStores.ts
@@ -22,6 +22,7 @@ import { useAgentMode } from '@/hooks/useAgentMode'
import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'
import { useCoworkSessions } from '@/hooks/useCoworkSessions'
import { useCoworkConfig } from '@/hooks/useCoworkConfig'
+import { useChatShell } from '@/hooks/useChatShell'
import { useCoTDuration } from '@/hooks/useCoTDuration'
import { useImageAttachmentConfig } from '@/hooks/useImageAttachmentConfig'
@@ -57,6 +58,7 @@ const secondaryStores = [
useWebSearchConfig,
useCoworkSessions,
useCoworkConfig,
+ useChatShell,
useCoTDuration,
useImageAttachmentConfig,
] as const
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index dd9672933..15f05f554 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -16,6 +16,7 @@
"claude_code": "Claude Code",
"https_proxy": "HTTPS Proxy",
"web_search": "Web Search",
+ "shell": "Shell",
"browse": "Browse",
"moreControls": "More controls",
"starting": "Starting...",
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 1818483f4..72d6231f6 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -82,6 +82,7 @@ import { usePrompt } from '@/hooks/usePrompt'
import { useAttachments } from '@/hooks/useAttachments'
import { PromptProgress } from '@/components/PromptProgress'
import { useToolAvailable } from '@/hooks/useToolAvailable'
+import { useChatShell } from '@/hooks/useChatShell'
import {
OUT_OF_CONTEXT_SIZE,
isContextOverflowMessage,
@@ -168,6 +169,13 @@ const forgetApprovals = (threadId: string) => {
const CHAT_CLOSED_TOOL_ERROR =
'Tool call cancelled: the chat was closed before it ran.'
+// Recorded for a call to the built-in shell while the user has the shell switch
+// off. The model reads it on its next turn, so it says why the call did not run
+// and that calling it again cannot succeed.
+const SHELL_DISABLED_TOOL_ERROR =
+ 'Shell is turned off: the user disabled it, so this command was not run. ' +
+ 'Do not call the shell again in this chat; use another approach or tell the user it is needed.'
+
// 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
@@ -200,6 +208,23 @@ function serverForTool(toolName: string): string | undefined {
?.server
}
+// How a call to a chat agent tool name is served. The switch is enforced where
+// the command would run, not only where the tool is offered: a call can still
+// arrive from replayed history or from a turn in flight when it flips. Such a
+// call is refused outright, before any approval prompt, because a prompt for a
+// tool the user turned off could save a permission for it. With the switch off
+// the built-in is not offered, so an MCP tool of the same name is the user's
+// own: it is served as an MCP tool and prompts like any other.
+function chatShellRoute(toolName: string): 'builtin' | 'disabled' | 'other' {
+ if (!CHAT_AGENT_TOOL_NAMES.has(toolName)) return 'other'
+ if (useChatShell.getState().shellEnabled) return 'builtin'
+ return useAppState.getState().mcpToolNames.has(toolName) ? 'other' : 'disabled'
+}
+
+function isDisabledChatAgentTool(toolName: string): boolean {
+ return chatShellRoute(toolName) === 'disabled'
+}
+
// Internal tools never prompt: RAG and the native web tools are Jan's own, and
// the built-in shell is gated in Rust (execute_tool refuses anything needing
// approval), so only workspace-confined calls ever reach here.
@@ -207,7 +232,7 @@ function isAutoAllowedTool(toolName: string): boolean {
return (
useAppState.getState().ragToolNames.has(toolName) ||
WEB_TOOL_NAMES.has(toolName) ||
- CHAT_AGENT_TOOL_NAMES.has(toolName)
+ chatShellRoute(toolName) === 'builtin'
)
}
@@ -679,6 +704,16 @@ function ThreadDetail() {
try {
const toolName = toolCall.toolName
+ if (isDisabledChatAgentTool(toolName)) {
+ record({
+ state: 'output-error',
+ tool: toolCall.toolName,
+ toolCallId: toolCall.toolCallId,
+ errorText: SHELL_DISABLED_TOOL_ERROR,
+ })
+ continue
+ }
+
const approved = isAutoAllowedTool(toolName)
? true
: await (approvalsOf(threadId).get(toolCall.toolCallId) ??
@@ -732,7 +767,7 @@ function ThreadDetail() {
return await executeWebTool(toolName, toolCall.input, {
maxOutputChars,
})
- } else if (CHAT_AGENT_TOOL_NAMES.has(toolName)) {
+ } else if (chatShellRoute(toolName) === 'builtin') {
// Chat's shell runs with the sandbox network closed: the
// default `allowNetwork = false` is the contract here, not an
// accident.
@@ -931,6 +966,7 @@ function ThreadDetail() {
sessionData.tools.push(toolCall)
if (
!isAutoAllowedTool(toolCall.toolName) &&
+ !isDisabledChatAgentTool(toolCall.toolName) &&
!approvalsOf(threadId).has(toolCall.toolCallId)
) {
approvalsOf(threadId).set(
diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
index 7efa8c295..2143cba46 100644
--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx
+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
@@ -418,6 +418,17 @@ vi.mock('@/hooks/useChatAttachments', () => ({
}))
vi.mock('@/hooks/useAttachments', () => ({ useAttachments: h.useAttachmentsMock }))
vi.mock('@/hooks/useToolAvailable', () => ({ useToolAvailable: h.useToolAvailableMock }))
+const shell = vi.hoisted(() => ({
+ enabled: true,
+ execute: vi.fn(async () => ({ output: 'ok' })),
+}))
+vi.mock('@/hooks/useChatShell', () => ({
+ useChatShell: { getState: () => ({ shellEnabled: shell.enabled }) },
+}))
+vi.mock('@/lib/agentTools', () => ({
+ CHAT_AGENT_TOOL_NAMES: new Set(['shell']),
+ executeAgentTool: shell.execute,
+}))
vi.mock('@/hooks/useToolApproval', () => ({ useToolApproval: h.useToolApprovalMock }))
vi.mock('@/hooks/useToolApprovalRequests', () => ({
useToolApprovalRequests: h.useToolApprovalRequestsMock,
@@ -1118,6 +1129,114 @@ describe('ThreadDetail route', () => {
})
})
+ // #9222: the shell switch is enforced where the command would run, so a call
+ // that still arrives while it is off (replayed history, a turn in flight when
+ // the switch flipped) is refused rather than auto-approved.
+ describe('the chat shell switch at execution time', () => {
+ const shellCall = (id: string) => ({
+ toolCall: { toolCallId: id, toolName: 'shell', input: { command: 'ls' } },
+ })
+ const finish = () =>
+ (h as any).capturedOnFinish({
+ message: {
+ id: 'a-sh',
+ role: 'assistant',
+ parts: [{ type: 'text', text: '' }],
+ metadata: { finishReason: 'tool-calls' },
+ },
+ isAbort: false,
+ })
+
+ beforeEach(() => {
+ shell.enabled = true
+ shell.execute.mockClear()
+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(false)
+ })
+
+ it('runs the shell without a prompt while the switch is on', async () => {
+ renderComponent()
+ await act(async () => {
+ await (h as any).capturedOnToolCall(shellCall('sh1'))
+ })
+ await act(async () => {
+ await finish()
+ })
+ expect(h.toolApprovalState.requestApproval).not.toHaveBeenCalled()
+ expect(shell.execute).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not run the shell, and says why, once the switch is off', async () => {
+ shell.enabled = false
+ renderComponent()
+ await act(async () => {
+ await (h as any).capturedOnToolCall(shellCall('sh2'))
+ })
+ await act(async () => {
+ await finish()
+ })
+ expect(shell.execute).not.toHaveBeenCalled()
+ expect(h.mockAddToolOutput).toHaveBeenCalledWith(
+ expect.objectContaining({
+ toolCallId: 'sh2',
+ tool: 'shell',
+ state: 'output-error',
+ // What the model reads on its next turn: why the call did not run, and
+ // that calling it again cannot succeed.
+ errorText: expect.stringMatching(/turned off.*Do not call the shell again/s),
+ })
+ )
+ })
+
+ // A prompt for a tool the user turned off is itself wrong: an "always allow"
+ // answer could save a permission for it. It is refused before any prompt,
+ // on both paths that can open one.
+ it('never prompts for a shell call while the switch is off', async () => {
+ shell.enabled = false
+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)
+ renderComponent()
+ await act(async () => {
+ await (h as any).capturedOnToolCall(shellCall('sh3'))
+ })
+ expect(h.toolApprovalState.requestApproval).not.toHaveBeenCalled()
+ await act(async () => {
+ await finish()
+ })
+ expect(h.toolApprovalState.requestApproval).not.toHaveBeenCalled()
+ expect(shell.execute).not.toHaveBeenCalled()
+ })
+
+ // Turning the built-in off must not break a user's own MCP tool that happens
+ // to be called `shell`: it is not offered by the built-in any more, so the
+ // call is served by the MCP server and prompts like any MCP call.
+ it('serves an MCP tool named shell while the switch is off', async () => {
+ shell.enabled = false
+ h.appStateState.mcpToolNames = new Set(['shell'])
+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)
+ const callTool = vi.fn().mockResolvedValue({ error: '', content: [] })
+ hub.mcp = () =>
+ ({
+ callToolWithCancellation: (args: unknown) => ({
+ promise: callTool(args),
+ cancel: vi.fn().mockResolvedValue(undefined),
+ token: 't',
+ }),
+ }) as never
+ renderComponent()
+ await act(async () => {
+ await (h as any).capturedOnToolCall(shellCall('sh4'))
+ })
+ await act(async () => {
+ await finish()
+ })
+ expect(h.toolApprovalState.requestApproval).toHaveBeenCalledTimes(1)
+ expect(callTool).toHaveBeenCalledTimes(1)
+ expect(shell.execute).not.toHaveBeenCalled()
+ expect(h.mockAddToolOutput).not.toHaveBeenCalledWith(
+ expect.objectContaining({ toolCallId: 'sh4', state: 'output-error' })
+ )
+ })
+ })
+
describe('tool-call approval requested early, execution stays in onFinish', () => {
const toolCall = (id: string) => ({
toolCall: { toolCallId: id, toolName: 'fetch', input: { url: 'x' } },