From 47a9e7d48d7b8e42e8b3095f00773d5334f0a7b5 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Mon, 2 Nov 2026 12:09:54 +0900 Subject: [PATCH] refac --- backend/open_webui/utils/middleware.py | 58 +---------------------- backend/open_webui/utils/terminals.py | 52 ++++++++++++++++++++ src/lib/apis/terminal/socket.ts | 35 ++++++++++++++ src/lib/components/chat/Chat.svelte | 12 ++++- src/lib/components/chat/ChatTabs.svelte | 11 +++++ src/lib/components/chat/XTerminal.svelte | 60 +++++++++++++++++------- src/lib/stores/index.ts | 3 -- src/routes/+layout.svelte | 16 ------- 8 files changed, 154 insertions(+), 93 deletions(-) diff --git a/backend/open_webui/utils/middleware.py b/backend/open_webui/utils/middleware.py index 0ee6ae5a1b..6458fdd8e6 100644 --- a/backend/open_webui/utils/middleware.py +++ b/backend/open_webui/utils/middleware.py @@ -151,7 +151,7 @@ from open_webui.utils.task import ( rag_template, tools_function_calling_generation_template, ) -from open_webui.utils.terminals import upload_files_to_terminal +from open_webui.utils.terminals import filter_user_terminal_tools, upload_files_to_terminal from open_webui.utils.tool_approval import complete_tool_call, pending_tool_calls from open_webui.utils.tool_search import apply_tool_search, resolve_tool_call from open_webui.utils.tools import ( @@ -2871,61 +2871,7 @@ async def process_chat_payload(request, form_data, user, metadata, model): ): tools_dict[name] = {**tools_dict[name], 'file_tool': tool_dict} - # Connections can keep shell tools advertised across browser disconnects for prompt caching. - shell_tools = { - name: tool - for name, tool in tools_dict.items() - if name in {'read_user_terminal', 'send_user_terminal_input'} - and (tool.get('type') == 'terminal' or tool.get('server', {}).get('is_terminal') is True) - } - selected = { - name: tool - for name, tool in shell_tools.items() - if terminal_id - and ( - tool.get('tool_id') == f'terminal:{terminal_id}' - or (tool.get('direct') and tool.get('server', {}).get('url') == terminal_id) - ) - } - connected = ( - any( - tool.get('user_shell_tools') == 'always' - or ( - tool.get('direct') - and (tool.get('server', {}).get('config') or {}).get('user_shell_tools') == 'always' - ) - for tool in selected.values() - ) - and not metadata.get('automation_id') - and not metadata.get('internal') - ) - if ( - selected - and not connected - and event_caller - and metadata.get('session_id') - and metadata.get('chat_id') - and not metadata.get('automation_id') - and not metadata.get('internal') - ): - try: - state = await asyncio.wait_for( - event_caller( - { - 'type': 'request:terminal:state', - 'data': {'terminal_id': terminal_id, 'session_id': metadata['session_id']}, - } - ), - timeout=2, - ) - connected = isinstance(state, dict) and state.get('connected') is True - except Exception: - # Old/disconnected browsers cannot confirm availability; other tools still work. - pass - - for name in shell_tools: - if not connected or name not in selected: - tools_dict.pop(name) + await filter_user_terminal_tools(request, user, tools_dict, metadata, extra_params) if tools_dict: # Always store resolved tools in metadata so downstream consumers diff --git a/backend/open_webui/utils/terminals.py b/backend/open_webui/utils/terminals.py index fad06c388a..ec9fff01de 100644 --- a/backend/open_webui/utils/terminals.py +++ b/backend/open_webui/utils/terminals.py @@ -232,6 +232,58 @@ async def get_terminal_json( return None +async def filter_user_terminal_tools(request, user, tools: dict, metadata: dict, extra_params: dict): + """Let Open Terminal, which owns the shells, confirm availability for this user and chat.""" + terminal_id = metadata.get('terminal_id') + shell_tools = { + name: tool + for name, tool in tools.items() + if name in {'read_user_terminal', 'send_user_terminal_input'} + and (tool.get('type') == 'terminal' or tool.get('server', {}).get('is_terminal') is True) + } + selected = { + name: tool + for name, tool in shell_tools.items() + if terminal_id + and ( + tool.get('tool_id') == f'terminal:{terminal_id}' + or (tool.get('direct') and tool.get('server', {}).get('url') == terminal_id) + ) + } + available = False + if selected and not metadata.get('automation_id') and not metadata.get('internal'): + available = any( + tool.get('user_shell_tools') == 'always' + or (tool.get('direct') and (tool.get('server', {}).get('config') or {}).get('user_shell_tools') == 'always') + for tool in selected.values() + ) + if not available and metadata.get('chat_id'): + try: + # This endpoint checks ownership, a live process, and a connected shell. + # Its output is discarded; the model must explicitly read the terminal. + async with asyncio.timeout(5): + state = await get_terminal_json(request, user, metadata, '/api/terminals/user/output', extra_params) + available = isinstance(state, dict) and isinstance(state.get('output'), str) + except Exception as error: + log.debug('User terminal availability check failed (%s)', type(error).__name__) + + for name in shell_tools: + if not available or name not in selected: + tools.pop(name) + + if available and 'read_user_terminal' in selected: + tool = selected['read_user_terminal'] + tools['read_user_terminal'] = { + **tool, + 'spec': { + **tool['spec'], + 'description': tool['spec'].get('description', '') + + "\nReads the user's Open WebUI Terminal tab, separate from the Desktop. " + 'Use this tool when the user refers to an open terminal tab.', + }, + } + + async def upload_files_to_terminal(request, user, files: list[dict], metadata: dict, extra_params: dict): """Copy Open WebUI files to the selected terminal, adding terminal_path or terminal_error to each entry.""" if not metadata.get('terminal_id') or not files: diff --git a/src/lib/apis/terminal/socket.ts b/src/lib/apis/terminal/socket.ts index ae68f4f74e..9b0a7ae9cf 100644 --- a/src/lib/apis/terminal/socket.ts +++ b/src/lib/apis/terminal/socket.ts @@ -1,5 +1,40 @@ import type { TerminalConnection } from './index'; +export function assignTerminalChat(socket: WebSocket, chatId: string): Promise { + return new Promise((resolve, reject) => { + const finish = (error?: Error) => { + clearTimeout(timeout); + socket.removeEventListener('message', onMessage); + socket.removeEventListener('close', onClose); + if (error) reject(error); + else resolve(); + }; + const onMessage = (event: MessageEvent) => { + if (typeof event.data !== 'string') return; + try { + const data = JSON.parse(event.data); + if (data.type !== 'chat') return; + if (data.error) finish(new Error(String(data.error))); + else if (data.chat_id === chatId) finish(); + } catch { + // Terminal output is not a control message. + } + }; + const onClose = () => finish(new Error('Terminal disconnected before joining the chat')); + const timeout = setTimeout( + () => finish(new Error('Terminal did not confirm the chat update')), + 10000 + ); + socket.addEventListener('message', onMessage); + socket.addEventListener('close', onClose); + try { + socket.send(JSON.stringify({ type: 'chat', chat_id: chatId })); + } catch (error) { + finish(error instanceof Error ? error : new Error(String(error))); + } + }); +} + export function openTerminalSocket( connection: TerminalConnection, chatId: string | null, diff --git a/src/lib/components/chat/Chat.svelte b/src/lib/components/chat/Chat.svelte index 4fcdd35d15..c2247d19f3 100644 --- a/src/lib/components/chat/Chat.svelte +++ b/src/lib/components/chat/Chat.svelte @@ -3430,7 +3430,7 @@ scrollToBottom(); } - if (messages.length === 0) { + if (!$chatId) { await initChatHandler(history); } else { await saveChatHandler($chatId, history); @@ -3494,7 +3494,7 @@ scrollToBottom(); } - if (messages.length === 0) { + if (!$chatId) { await initChatHandler(history); } else { await saveChatHandler($chatId, history); @@ -3861,6 +3861,8 @@ prompt = ''; }; + let terminalTabs: ChatTabs; + const getChatId = async (_history: typeof history) => { let _chatId = $chatId; // Empty embedded drafts create their backing chat only when the first message is sent. @@ -3887,8 +3889,13 @@ _chatId = createTemporaryChatId($socket?.id); await chatId.set(_chatId); } + if (!_chatId && terminalTabs?.hasTerminals()) { + _chatId = await initChatHandler(_history); + } await tick(); } + if (history !== _history) return null; + if (_chatId) await terminalTabs?.bindTerminalChat(_chatId); return _chatId; }; @@ -5683,6 +5690,7 @@ bind:history bind:files chatId={$chatId} + bind:this={terminalTabs} chatUser={chatOwner} modelId={selectedModelIds?.at(0) ?? null} canSideChat={sideChatAllowed && selectedModels.length === 1 && !!selectedModelIds[0]} diff --git a/src/lib/components/chat/ChatTabs.svelte b/src/lib/components/chat/ChatTabs.svelte index 4ce5799969..c2962552a0 100644 --- a/src/lib/components/chat/ChatTabs.svelte +++ b/src/lib/components/chat/ChatTabs.svelte @@ -103,6 +103,16 @@ let viewportWidth = 0; let tabs = emptyTabs(); + let terminalViews: Record = {}; + export const hasTerminals = () => tabs.tabs.some((tab) => tab.kind === 'terminal'); + export async function bindTerminalChat(id: string) { + await tick(); + await Promise.all( + tabs.tabs + .filter((tab) => tab.kind === 'terminal') + .map((tab) => terminalViews[tab.id]?.bindChat(id)) + ); + } let fileViews: Record< string, { @@ -919,6 +929,7 @@ /> {:else if tab.kind === 'terminal' && tab.connection} ; let destroyed = false; let sessionId = ''; - const terminalOwner = Symbol(); + let sessionChatId = chatId; + let bindingChat: Promise | null = null; + let finishConnection: (ready: boolean) => void; + const connectionReady = new Promise((resolve) => (finishConnection = resolve)); let reportedActive: boolean | null = null; + export async function bindChat(id: string) { + if (readOnly || destroyed || sessionChatId === id) return; + if (sessionChatId) throw new Error('Terminal already belongs to another chat'); + if (!(await connectionReady) || !ws) throw new Error('Terminal is not connected'); + if (!bindingChat) { + bindingChat = assignTerminalChat(ws, id) + .then(() => { + sessionChatId = id; + }) + .finally(() => { + bindingChat = null; + }); + } + await bindingChat; + if (sessionChatId !== id) throw new Error('Terminal already belongs to another chat'); + } + function reportActivity(visible: boolean) { if (readOnly || !connected || ws?.readyState !== WebSocket.OPEN) return; const isActive = visible && !document.hidden; @@ -38,10 +57,7 @@ const reportVisibility = () => reportActivity(active); function disconnect() { - connectedUserTerminals.update((entries) => { - entries.delete(terminalOwner); - return entries; - }); + finishConnection(false); connected = false; connecting = false; reportedActive = null; @@ -82,14 +98,19 @@ async function connect() { connecting = true; try { - const session = await terminalRequest<{ id: string }>(connection, chatId, '/api/terminals', { - method: 'POST' - }); + const session = await terminalRequest<{ id: string }>( + connection, + sessionChatId, + '/api/terminals', + { + method: 'POST' + } + ); sessionId = session.id; if (destroyed) { await terminalRequest( connection, - chatId, + sessionChatId, `/api/terminals/${encodeURIComponent(sessionId)}`, { method: 'DELETE' } ); @@ -97,15 +118,12 @@ } ws = openTerminalSocket( connection, - chatId, + sessionChatId, `/api/terminals/${encodeURIComponent(sessionId)}`, () => { if (destroyed) return; - if (connection.selector && chatId) { - const shell = { terminalId: connection.selector, chatId }; - connectedUserTerminals.update((entries) => entries.set(terminalOwner, shell)); - } connected = true; + finishConnection(true); connecting = false; reportActivity(active); fit(); @@ -118,6 +136,13 @@ ); ws.onmessage = (event) => { if (destroyed) return; + if (typeof event.data === 'string') { + try { + if (JSON.parse(event.data).type === 'chat') return; + } catch { + /* Render non-JSON terminal output below. */ + } + } if (event.data instanceof ArrayBuffer) term?.write(new Uint8Array(event.data)); else write(event.data); }; @@ -140,6 +165,9 @@ $: if (active && term) requestAnimationFrame(fit); $: if (connected) reportActivity(active); + $: if (connected && chatId && !sessionChatId) { + void bindChat(chatId).catch((error) => write(`\r\n[${error}]\r\n`)); + } onMount(() => { document.addEventListener('visibilitychange', reportVisibility); diff --git a/src/lib/stores/index.ts b/src/lib/stores/index.ts index f423980624..8e7aff71ea 100644 --- a/src/lib/stores/index.ts +++ b/src/lib/stores/index.ts @@ -190,9 +190,6 @@ export type FileNavOpenRequest = string | { path: string; page?: number | null } export const showFileNavPath: Writable = writable(null); export const showFileNavDir: Writable = writable(null); export const selectedTerminalId: Writable = writable(null); -export const connectedUserTerminals = writable( - new Map() -); export const artifactCode = writable(null); export const artifactContents = writable(null); diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index a885d23510..9df5cd8d05 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -35,7 +35,6 @@ channelId, channelRequestQueues, terminalServers, - connectedUserTerminals, showTabs, showFileNavPath, showFileNavDir, @@ -581,21 +580,6 @@ const chatEventHandler = async (event, cb) => { if (event.shared) return; - // Answer this session's availability check even when another chat is active. - if ( - event?.data?.type === 'request:terminal:state' && - event.data.data?.session_id === $socket?.id - ) { - cb?.({ - connected: - $config?.features?.enable_tool_servers && - [...$connectedUserTerminals.values()].some( - (shell) => - shell.terminalId === event.data.data?.terminal_id && shell.chatId === event.chat_id - ) - }); - return; - } const chat = $page.url.pathname.includes(`/c/${event.chat_id}`); // Skip events from temporary chats that are not the current chat.