Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(web-app): let a chat attach a folder without becoming a Cowork task
thinhlpg229da8752448
diff --git a/web-app/src/containers/CoworkWorkspacePill.tsx b/web-app/src/containers/CoworkWorkspacePill.tsxindex 515e3a1a0..907ddc90d 100644--- a/web-app/src/containers/CoworkWorkspacePill.tsx+++ b/web-app/src/containers/CoworkWorkspacePill.tsx@@ -18,6 +18,9 @@ type Props = {gitBranch?: string | nullonAttach: () => voidonDetach: () => void+ /** Replaces the default access note for an attached folder: chat asks+ * before every change, Cowork does not. */+ footnote?: string}/**@@ -37,6 +40,7 @@ export function CoworkWorkspacePill({gitBranch,onAttach,onDetach,+ footnote,}: Props) {const { t } = useTranslation()const serviceHub = useServiceHub()@@ -162,7 +166,7 @@ export function CoworkWorkspacePill({<p className="text-xs text-muted-foreground">{folder- ? t('common:workspace.footnote')+ ? (footnote ?? t('common:workspace.footnote')): t('common:workspace.footnoteEmpty')}</p>diff --git a/web-app/src/hooks/useChatFolder.ts b/web-app/src/hooks/useChatFolder.tsnew file mode 100644index 000000000..80bc3807d--- /dev/null+++ b/web-app/src/hooks/useChatFolder.ts@@ -0,0 +1,63 @@+import { useCallback, useMemo } from 'react'+import { toast } from 'sonner'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { useModelProvider } from '@/hooks/useModelProvider'+import { useServiceHub } from '@/hooks/useServiceHub'+import { useThreads } from '@/hooks/useThreads'+import { TEMPORARY_CHAT_ID } from '@/constants/chat'+import { supportsCowork } from '@/lib/coworkSync'+import { isCoworkEnabled } from '@/lib/version'++/**+ * The folder attached to an existing chat thread. Unlike a home draft's folder+ * (useFolderDraft), it is saved on the thread and stays until detached; the+ * thread's tools read it from there.+ */+export function useChatFolder(threadId: string) {+ const { t } = useTranslation()+ const serviceHub = useServiceHub()+ const selectedModel = useModelProvider((s) => s.selectedModel)+ const stored = useThreads((s) => s.threads[threadId]?.metadata?.folder)+ const setThreadFolder = useThreads((s) => s.setThreadFolder)+ // Same availability as a draft's folder: the desktop host, on builds that+ // ship the agent tools. A temporary chat keeps no folder.+ const available =+ supportsCowork() && isCoworkEnabled() && threadId !== TEMPORARY_CHAT_ID+ const folder = typeof stored === 'string' && stored.trim() ? stored : null++ const save = useCallback(+ async (next: string | null) => {+ try {+ await setThreadFolder(threadId, next)+ } catch (error) {+ console.warn('[chat] could not save the folder:', error)+ toast.error(t('common:workspace.saveFailed'))+ }+ },+ [setThreadFolder, threadId, t]+ )++ const attach = useCallback(async () => {+ if (!selectedModel) {+ toast.info(t('common:conversationScope.folderSelectModel'))+ return+ }+ if (!selectedModel.capabilities?.includes('tools')) {+ toast.info(t('common:conversationScope.folderUnsupported'))+ return+ }+ const picked = await serviceHub.dialog().open({ directory: true })+ if (typeof picked !== 'string') return+ await save(picked)+ }, [save, selectedModel, serviceHub, t])++ return useMemo(+ () => ({+ available,+ folder: available ? folder : null,+ attach: () => void attach(),+ detach: () => void save(null),+ }),+ [available, folder, attach, save]+ )+}diff --git a/web-app/src/hooks/useThreads.ts b/web-app/src/hooks/useThreads.tsindex 7a47850c2..289a8c0e7 100644--- a/web-app/src/hooks/useThreads.ts+++ b/web-app/src/hooks/useThreads.ts@@ -61,6 +61,12 @@ type ThreadState = {) => Promise<Assistant | undefined>updateThreadTimestamp: (threadId: string) => voidupdateThread: (threadId: string, updates: Partial<Thread>) => void+ /**+ * Attach a folder to a chat thread, or detach it with `null`. Resolves once+ * the record is on disk, because that record is what the tools read when+ * they run: a send right after attaching must find the folder there.+ */+ setThreadFolder: (threadId: string, folder: string | null) => Promise<void>deleteAllThreadsByProject: (projectId: string) => voidsearchIndex: Fzf<Thread[]> | null}@@ -593,4 +599,32 @@ export const useThreads = create<ThreadState>()((set, get) => ({}})},+ setThreadFolder: async (threadId, folder) => {+ const thread = get().threads[threadId]+ if (!thread) return+ const metadata = { ...thread.metadata }+ if (folder) {+ metadata.folder = folder+ metadata.folderAccess = 'write'+ } else {+ delete metadata.folder+ delete metadata.folderAccess+ }+ await getServiceHub()+ .threads()+ .updateThread({ ...thread, metadata, updated: Date.now() / 1000 })+ // Applied onto the thread as it is now: other metadata may have changed+ // while the write was in flight.+ set((state) => {+ const current = state.threads[threadId]+ if (!current) return state+ const next = { ...current.metadata }+ delete next.folder+ delete next.folderAccess+ if (folder) Object.assign(next, { folder, folderAccess: 'write' })+ return {+ threads: { ...state.threads, [threadId]: { ...current, metadata: next } },+ }+ })+ },}))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.tsindex 56e83f435..6fc594a94 100644--- 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@@ -6,6 +6,7 @@ const h = vi.hoisted(() => ({shellEnabled: true,sandbox: true,schemas: vi.fn(),+ threads: {} as Record<string, unknown>,}))vi.mock('@/hooks/useChatShell', () => ({@@ -44,7 +45,7 @@ vi.mock('@/hooks/useAssistant', () => ({useAssistant: { getState: () => ({ currentAssistant: null }) },}))vi.mock('@/hooks/useThreads', () => ({- useThreads: { getState: () => ({ threads: {} }) },+ useThreads: { getState: () => ({ threads: h.threads }) },}))vi.mock('@/hooks/useAttachments', () => ({useAttachments: { getState: () => ({ enabled: false }) },@@ -75,17 +76,14 @@ describe('chat shell switch (#9222)', () => {beforeEach(() => {h.shellEnabled = trueh.sandbox = true+ h.threads = {}h.schemas.mockReset()- h.schemas.mockResolvedValue([- {+ h.schemas.mockResolvedValue(+ ['shell', 'read', 'write', 'memory'].map((name) => ({type: 'function',- function: {- name: 'shell',- description: 'run',- parameters: { type: 'object' },- },- },- ])+ function: { name, description: 'run', parameters: { type: 'object' } },+ }))+ )transport = new CustomChatTransport('sys', 'thread-1')})@@ -115,4 +113,23 @@ describe('chat shell switch (#9222)', () => {await transport.refreshTools()expect(Object.keys(transport.getTools())).not.toContain('shell')})++ // #9649: a folder the user attached to the thread adds the file tools, and+ // the prompt names it; the shell switch still governs the shell alone.+ it('offers the file tools on an attached folder, and only then', async () => {+ await transport.refreshTools()+ expect(Object.keys(transport.getTools()).sort()).toEqual(['shell'])++ h.shellEnabled = false+ h.threads = { 'thread-1': { metadata: { folder: '/Users/me/project' } } }+ await transport.refreshTools()+ expect(Object.keys(transport.getTools()).sort()).toEqual(['read', 'write'])+ const prompt = transport.buildAgentToolsSystemInstruction()+ expect(prompt).toContain('/Users/me/project')+ expect(prompt).not.toContain('# Shell')++ h.threads = {}+ await transport.refreshTools()+ expect(Object.keys(transport.getTools())).toEqual([])+ })})diff --git a/web-app/src/lib/chatFolder.ts b/web-app/src/lib/chatFolder.tsnew file mode 100644index 000000000..960af1c79--- /dev/null+++ b/web-app/src/lib/chatFolder.ts@@ -0,0 +1,40 @@+import { useThreads } from '@/hooks/useThreads'++/**+ * The file tools a chat gets while a folder is attached to it, on top of the+ * shell. Without a folder chat keeps the shell alone (`CHAT_AGENT_TOOL_NAMES`).+ */+export const CHAT_FOLDER_TOOL_NAMES = new Set([+ 'read',+ 'ls',+ 'find',+ 'grep',+ 'write',+ 'edit',+])++/**+ * Calls that change the attached folder or run in it. With a folder attached+ * they are asked for on every call and no answer is saved: the shell can write+ * the folder as well as `write` and `edit` can. Reads run without asking.+ */+const ASKED_WITH_FOLDER = new Set(['write', 'edit', 'shell'])++/**+ * The folder attached to a chat thread, from its record. The record is the+ * authority: Rust reads the same `thread.json` field when the tool runs, so+ * what is offered here and what is reachable there cannot drift apart.+ */+export function chatFolderOf(threadId: string | undefined): string | null {+ if (!threadId) return null+ const folder = useThreads.getState().threads[threadId]?.metadata?.folder+ return typeof folder === 'string' && folder.trim() ? folder : null+}++/** Whether a built-in chat call must be asked for, given the thread's folder. */+export function chatToolNeedsApproval(+ toolName: string,+ threadId: string+): boolean {+ return ASKED_WITH_FOLDER.has(toolName) && chatFolderOf(threadId) !== null+}diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex e08d4536b..9cbeee031 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -29,6 +29,7 @@ import { useThreads } from '@/hooks/useThreads'import { useAttachments } from '@/hooks/useAttachments'import { useMCPServers } from '@/hooks/useMCPServers'import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'+import { CHAT_FOLDER_TOOL_NAMES, chatFolderOf } from '@/lib/chatFolder'import { useChatShell } from '@/hooks/useChatShell'import {WEB_SEARCH_DESCRIPTION,@@ -1254,16 +1255,24 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {} as Tool}- // 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. A user- // who switched it off (#9222) gets none of it.+ // Built-in agent tools. Without a folder chat offers one: the sandboxed+ // shell, with no network. A folder the user attached to this thread adds+ // the file tools, served on that folder (Rust reads it from the thread's+ // record, see chatFolder.ts). Schemas come from Rust so they are never+ // re-typed here, and `getAgentToolSchemas` already withholds shell when+ // no sandbox backend can confine it. A user who switched the shell off+ // (#9222) does not get it, folder or not.try {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] = {+ const hasFolder = chatFolderOf(this.threadId) !== null+ const wanted = shellOn || hasFolder+ for (const schema of wanted ? await getAgentToolSchemas() : []) {+ const name = schema.function.name+ const offered =+ (shellOn && CHAT_AGENT_TOOL_NAMES.has(name)) ||+ (hasFolder && CHAT_FOLDER_TOOL_NAMES.has(name))+ if (!offered) continue+ toolsRecord[name] = {description: schema.function.description,inputSchema: jsonSchema(schema.function.parameters),} as Tool@@ -1794,15 +1803,18 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {? prependContinuationToUIStream(uiStream, continueContent): uiStream- // A call to the built-in shell while the user has it switched off is not in+ // A call to a built-in the thread does not offer right now (the shell+ // switched off, a file tool after the folder was detached) is not in// `this.tools`, so the SDK would reject it and end the turn. Hand it to the- // tool loop instead, which answers it with the "turned off" refusal.+ // tool loop instead, which answers it with a refusal the model can read.return routeRefusedToolCalls(continuedStream,(toolName) =>- CHAT_AGENT_TOOL_NAMES.has(toolName) &&!(toolName in this.tools) &&- !useChatShell.getState().shellEnabled+ ((CHAT_AGENT_TOOL_NAMES.has(toolName) &&+ !useChatShell.getState().shellEnabled) ||+ (CHAT_FOLDER_TOOL_NAMES.has(toolName) &&+ chatFolderOf(this.threadId) === null)))}@@ -1940,26 +1952,51 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {}/**- * 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.+ * Static instruction for the built-in tools chat offers: the sandboxed shell,+ * and the file tools while a folder is attached. Empty when none of them is+ * offered, because stating limits for a tool the model was not given only+ * confuses it, and an empty string keeps the prompt prefix stable.*/buildAgentToolsSystemInstruction(): string {- // 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 [- '# Shell',- 'shell runs commands in an isolated scratch workspace under an OS',- 'sandbox: it starts there, can only write there, and cannot read files',- "in the user's home directory. The workspace belongs to this",- 'conversation alone and is deleted with it, so do not keep anything',- 'there that should last. It has no network access, so commands that',- 'download or upload will fail.',- ].join(' ')+ const folder = chatFolderOf(this.threadId)+ const shell = useChatShell.getState().shellEnabled && sandboxEnforces()+ const sections: string[] = []+ if (folder) {+ sections.push(+ [+ '# Folder',+ `The user attached the folder \`${folder}\` to this conversation.`,+ 'It is your working directory: relative paths resolve against it.',+ 'Read, list and search it with read, ls, find and grep. write and edit',+ 'change its files in place, and the user is asked to approve every',+ 'such call (and every shell command) before it runs; a declined call',+ 'did not happen, so do not retry it unchanged.',+ ].join(' ')+ )+ }+ // Stating the shell's limits up front is cheaper than letting the model+ // discover them by having a command refused.+ if (shell) {+ sections.push(+ folder+ ? [+ '# Shell',+ 'shell runs commands in the attached folder under an OS sandbox:',+ "it cannot read the rest of the user's home directory, and it has",+ 'no network access, so commands that download or upload will fail.',+ ].join(' ')+ : [+ '# Shell',+ 'shell runs commands in an isolated scratch workspace under an OS',+ 'sandbox: it starts there, can only write there, and cannot read files',+ "in the user's home directory. The workspace belongs to this",+ 'conversation alone and is deleted with it, so do not keep anything',+ 'there that should last. It has no network access, so commands that',+ 'download or upload will fail.',+ ].join(' ')+ )+ }+ return sections.join('\n\n')}mapUserInlineAttachments(messages: UIMessage[]): UIMessage[] {diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex ad2d5877b..2b820cb7f 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -729,6 +729,7 @@"readsFrom": "Works in","writable": "read & write","footnote": "The agent reads and edits this folder directly. Review what changed in the diff panel.",+ "chatFootnote": "Jan reads this folder freely and asks you before every edit or command that runs in it.","footnoteEmpty": "Attach a folder to let the agent work on your project. It can read and edit files inside it.","attach": "Attach a folder","change": "Change folder",@@ -739,6 +740,7 @@"missing": "The workspace folder {{folder}} is no longer available. Choose a different folder.","openFailed": "Couldn't open workspace","revealFailed": "Couldn't reveal workspace",+ "saveFailed": "Couldn't save the folder for this chat","a11yWithFolder": "Project folder {{folder}}, attached with read and write access. Change or detach it.","a11yNoFolder": "No project folder attached. Attach one."},diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex 5b5b52377..7678b47a8 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -121,6 +121,14 @@ import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'import { webToolRoute, executeWebTool } from '@/lib/webSearchTool'import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'import { CHAT_AGENT_TOOL_NAMES, executeAgentTool } from '@/lib/agentTools'+import {+ CHAT_FOLDER_TOOL_NAMES,+ chatFolderOf,+ chatToolNeedsApproval,+} from '@/lib/chatFolder'+import { useChatFolder } from '@/hooks/useChatFolder'+import { CoworkComposerMenu } from '@/containers/CoworkComposerMenu'+import { CoworkWorkspacePill } from '@/containers/CoworkWorkspacePill'import { getExtensionHost } from '@/lib/extensions/host'import { extensionAuthorOf } from '@/lib/extensions/authorship'import { ServiceKeys } from '@janhq/core'@@ -272,6 +280,12 @@ 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.'+// Recorded for a call to a file tool (read, write, ...) in a chat with no folder+// attached, e.g. one issued before the user detached it.+const NO_FOLDER_TOOL_ERROR =+ 'No folder is attached to this chat, so this call was not run. ' ++ 'Do not call the file tools again unless the user attaches a folder.'+// Recorded for a call to a built-in web tool while the user has web search off// and no MCP server provides a tool of that name.const WEB_DISABLED_TOOL_ERROR =@@ -357,21 +371,38 @@ function turnModelOf(threadId: string) {)}-// 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'+// How a call to a built-in chat agent tool name is served. The shell switch and+// the attached folder are 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 they change. 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. When the built-in is not offered, 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 chatAgentRoute(+ toolName: string,+ threadId: string+): 'builtin' | 'disabled' | 'other' {+ let offered: boolean+ if (CHAT_FOLDER_TOOL_NAMES.has(toolName)) {+ offered = chatFolderOf(threadId) !== null+ } else if (CHAT_AGENT_TOOL_NAMES.has(toolName)) {+ offered = useChatShell.getState().shellEnabled+ } else {+ return 'other'+ }+ if (offered) return 'builtin'return useAppState.getState().mcpToolNames.has(toolName) ? 'other' : 'disabled'}-function isDisabledChatAgentTool(toolName: string): boolean {- return chatShellRoute(toolName) === 'disabled'+function disabledChatAgentToolError(+ toolName: string,+ threadId: string+): string | null {+ if (chatAgentRoute(toolName, threadId) !== 'disabled') return null+ return CHAT_FOLDER_TOOL_NAMES.has(toolName)+ ? NO_FOLDER_TOOL_ERROR+ : SHELL_DISABLED_TOOL_ERROR}// How a call to a built-in web tool name is served. Same contract as the shell:@@ -389,26 +420,31 @@ function webRoute(toolName: string): 'builtin' | 'disabled' | 'other' {}// 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. The web tools-// do prompt on a turn an extension's provider serves: there the model is the-// extension's, and a free `web_fetch` would reach any host its network grants-// leave out.+// the built-in tools are gated in Rust (execute_tool refuses anything needing+// approval), so only workspace-confined calls ever reach here. Two exceptions+// ask. The web tools on a turn an extension's provider serves: there the model+// is the extension's, and a free `web_fetch` would reach any host its network+// grants leave out. And with a folder attached, every call that can change it+// (write, edit, shell): the folder is the user's own files, not a scratch space.function isAutoAllowedTool(toolName: string, threadId: string): boolean {return (useAppState.getState().ragToolNames.has(toolName) ||(webRoute(toolName) === 'builtin' && !turnOnExtensionProvider(threadId)) ||- chatShellRoute(toolName) === 'builtin'+ (chatAgentRoute(toolName, threadId) === 'builtin' &&+ !chatToolNeedsApproval(toolName, threadId)))}-// Every call the model an extension serves makes is asked for on its own:-// neither "allow all MCP" nor a grant given on another turn covers it.+// Asked for on its own, with neither "allow all MCP" nor a saved grant covering+// it: every call the model an extension serves makes, and a built-in call that+// changes the attached folder (no "allow always" for writing the user's files).function approvalOptions(threadId: string,+ toolName: string,origin: ToolOrigin['origin']): ApprovalOptions {- return turnOnExtensionProvider(threadId)+ const builtin = chatAgentRoute(toolName, threadId) === 'builtin'+ return turnOnExtensionProvider(threadId) || builtin? { strict: true, origin }: { origin }}@@ -545,6 +581,7 @@ function ThreadDetail() {const currentThread = useRef<string | undefined>(undefined)useTools()+ const chatFolder = useChatFolder(threadId)// Get attachments for this threadconst attachmentsKey = threadId ?? NEW_THREAD_ATTACHMENT_KEY@@ -989,12 +1026,13 @@ function ThreadDetail() {continue}- if (isDisabledChatAgentTool(toolName)) {+ const disabledError = disabledChatAgentToolError(toolName, threadId)+ if (disabledError) {record({state: 'output-error',tool: toolCall.toolName,toolCallId: toolCall.toolCallId,- errorText: SHELL_DISABLED_TOOL_ERROR,+ errorText: disabledError,})continue}@@ -1011,7 +1049,7 @@ function ThreadDetail() {toolName,threadId,origin.server,- approvalOptions(threadId, origin.origin)+ approvalOptions(threadId, toolName, origin.origin)))approvalsOf(threadId).delete(toolCall.toolCallId)// Only an explicit Stop skips the result. Deleting the thread also@@ -1070,7 +1108,7 @@ function ThreadDetail() {return await executeWebTool(toolName, toolCall.input, {maxOutputChars,})- } else if (chatShellRoute(toolName) === 'builtin') {+ } else if (chatAgentRoute(toolName, threadId) === 'builtin') {// Chat's shell runs with the sandbox network closed: the// default `allowNetwork = false` is the contract here, not an// accident.@@ -1283,7 +1321,7 @@ function ThreadDetail() {sessionData.tools.push(toolCall)if (!isAutoAllowedTool(toolCall.toolName, threadId) &&- !isDisabledChatAgentTool(toolCall.toolName) &&+ !disabledChatAgentToolError(toolCall.toolName, threadId) &&webRoute(toolCall.toolName) !== 'disabled' &&!approvalsOf(threadId).has(toolCall.toolCallId)) {@@ -1296,7 +1334,7 @@ function ThreadDetail() {toolCall.toolName,threadId,origin.server,- approvalOptions(threadId, origin.origin)+ approvalOptions(threadId, toolCall.toolName, origin.origin)),origin,})@@ -2682,6 +2720,21 @@ function ThreadDetail() {onStop={handleStop}chatStatus={effectiveStatus}toolsRunning={toolsRunning}+ menuWorkspace={+ chatFolder.available && !chatFolder.folder ? (+ <CoworkComposerMenu onAttachFolder={chatFolder.attach} />+ ) : undefined+ }+ surfaceControls={+ chatFolder.folder ? (+ <CoworkWorkspacePill+ folder={chatFolder.folder}+ onAttach={chatFolder.attach}+ onDetach={chatFolder.detach}+ footnote={t('common:workspace.chatFootnote')}+ />+ ) : undefined+ }/></ConversationColumn></div>diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsxindex 6f48437f5..b043253e4 100644--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx@@ -450,6 +450,23 @@ vi.mock('@/lib/agentTools', () => ({CHAT_AGENT_TOOL_NAMES: new Set(['shell']),executeAgentTool: shell.execute,}))+const folder = vi.hoisted(() => ({ path: null as string | null }))+vi.mock('@/lib/chatFolder', () => ({+ CHAT_FOLDER_TOOL_NAMES: new Set(['read', 'ls', 'find', 'grep', 'write', 'edit']),+ chatFolderOf: () => folder.path,+ chatToolNeedsApproval: (name: string) =>+ folder.path !== null && ['write', 'edit', 'shell'].includes(name),+}))+vi.mock('@/hooks/useChatFolder', () => ({+ useChatFolder: () => ({+ available: false,+ folder: null,+ attach: vi.fn(),+ detach: vi.fn(),+ }),+}))+vi.mock('@/containers/CoworkComposerMenu', () => ({ CoworkComposerMenu: () => null }))+vi.mock('@/containers/CoworkWorkspacePill', () => ({ CoworkWorkspacePill: () => null }))vi.mock('@/hooks/useToolApproval', () => ({ useToolApproval: h.useToolApprovalMock }))vi.mock('@/hooks/useToolApprovalRequests', () => ({useToolApprovalRequests: h.useToolApprovalRequestsMock,@@ -1606,6 +1623,90 @@ describe('ThreadDetail route', () => {})})+ // #9649: a folder attached to the chat. Reads run on it without asking; every+ // call that can change it asks on its own, and the answer is never saved.+ describe('a chat with an attached folder', () => {+ const call = (id: string, toolName: string) => ({+ toolCall: { toolCallId: id, toolName, input: { path: 'a.md' } },+ })+ const finish = () =>+ (h as any).capturedOnFinish({+ message: {+ id: 'a-folder',+ role: 'assistant',+ parts: [{ type: 'text', text: '' }],+ metadata: { finishReason: 'tool-calls' },+ },+ isAbort: false,+ })+ const run = async (...calls: ReturnType<typeof call>[]) => {+ renderComponent()+ for (const c of calls) {+ await act(async () => {+ await (h as any).capturedOnToolCall(c)+ })+ }+ await act(async () => {+ await finish()+ })+ }++ beforeEach(() => {+ shell.enabled = true+ shell.execute.mockClear()+ folder.path = '/Users/me/project'+ })+ afterEach(() => {+ folder.path = null+ })++ it('reads the folder without asking', async () => {+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(false)+ await run(call('f1', 'read'))+ expect(h.toolApprovalState.requestApproval).not.toHaveBeenCalled()+ expect(shell.execute).toHaveBeenCalledWith('read', { path: 'a.md' }, expect.anything())+ })++ it('asks before every write, edit or command, with no grant saved', async () => {+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)+ await run(call('f2', 'write'), call('f3', 'shell'))+ for (const [id, name] of [['f2', 'write'], ['f3', 'shell']]) {+ expect(h.toolApprovalState.requestApproval).toHaveBeenCalledWith(+ id,+ name,+ expect.anything(),+ undefined,+ { strict: true, origin: 'mcp' }+ )+ }+ expect(shell.execute).toHaveBeenCalledTimes(2)+ })++ it('does not write when the user declines', async () => {+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(false)+ await run(call('f4', 'edit'))+ expect(shell.execute).not.toHaveBeenCalled()+ expect(h.mockAddToolOutput).toHaveBeenCalledWith(+ expect.objectContaining({ toolCallId: 'f4', state: 'output-error' })+ )+ })++ it('refuses a file tool, without asking, once no folder is attached', async () => {+ folder.path = null+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)+ await run(call('f5', 'write'))+ expect(h.toolApprovalState.requestApproval).not.toHaveBeenCalled()+ expect(shell.execute).not.toHaveBeenCalled()+ expect(h.mockAddToolOutput).toHaveBeenCalledWith(+ expect.objectContaining({+ toolCallId: 'f5',+ state: 'output-error',+ errorText: expect.stringMatching(/No folder is attached/),+ })+ )+ })+ })+// #9458: search servers such as Parallel Search expose tools named// `web_search` / `web_fetch`, the built-ins' own names. Execution used to// route on the name alone, so the built-in provider answered (and failed)