This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-02 12:09:54 +09:00
1 parent 042ac65628
commit 47a9e7d48d
8 files changed
+154 -93

No files matched your search

+2 -56
View File
@@ -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
+52
View File
@@ -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:
+35
View File
@@ -1,5 +1,40 @@
import type { TerminalConnection } from './index';
export function assignTerminalChat(socket: WebSocket, chatId: string): Promise<void> {
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,
+10 -2
View File
@@ -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]}
+11
View File
@@ -103,6 +103,16 @@
let viewportWidth = 0;
let tabs = emptyTabs();
let terminalViews: Record<string, XTerminal> = {};
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}
<XTerminal
bind:this={terminalViews[tab.id]}
connection={tab.connection}
{chatId}
active={!!$showTabs && tabs.activeId === tab.id}
+44 -16
View File
@@ -5,8 +5,7 @@
import { WebLinksAddon } from '@xterm/addon-web-links';
import '@xterm/xterm/css/xterm.css';
import { terminalRequest, type TerminalConnection } from '$lib/apis/terminal';
import { openTerminalSocket } from '$lib/apis/terminal/socket';
import { connectedUserTerminals } from '$lib/stores';
import { assignTerminalChat, openTerminalSocket } from '$lib/apis/terminal/socket';
export let connection: TerminalConnection;
export let chatId: string | null = null;
@@ -25,9 +24,29 @@
let pingInterval: ReturnType<typeof setInterval>;
let destroyed = false;
let sessionId = '';
const terminalOwner = Symbol();
let sessionChatId = chatId;
let bindingChat: Promise<void> | null = null;
let finishConnection: (ready: boolean) => void;
const connectionReady = new Promise<boolean>((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);
-3
View File
@@ -190,9 +190,6 @@ export type FileNavOpenRequest = string | { path: string; page?: number | null }
export const showFileNavPath: Writable<FileNavOpenRequest | null> = writable(null);
export const showFileNavDir: Writable<string | null> = writable(null);
export const selectedTerminalId: Writable<string | null> = writable(null);
export const connectedUserTerminals = writable(
new Map<symbol, { terminalId: string; chatId: string }>()
);
export const artifactCode = writable(null);
export const artifactContents = writable(null);
-16
View File
@@ -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.