diff --git a/backend/open_webui/routers/automations.py b/backend/open_webui/routers/automations.py index 28536218d7..f1800519fe 100644 --- a/backend/open_webui/routers/automations.py +++ b/backend/open_webui/routers/automations.py @@ -21,6 +21,7 @@ from open_webui.models.config import Config from open_webui.models.folders import Folders from open_webui.utils.access_control import has_permission from open_webui.utils.auth import get_admin_user, get_verified_user +from open_webui.utils.agents.discovery import get_models as get_agent_models from open_webui.utils.automations import ( execute_automation, next_n_runs_ns, @@ -207,14 +208,14 @@ async def get_automation_models( db: AsyncSession = Depends(get_async_session), ): await check_automations_permission(request, user) + automation = None if automation_id: automation = await Automations.get_by_id(automation_id, db=db) check_automation_access(automation, user) - from open_webui.utils.agents.discovery import get_models as get_agent_models - - return await get_agent_models( - request, user, {'terminal_id': terminal_id, 'automation_id': automation_id or f'preview:{user.id}'}, cwd=cwd - ) + metadata = {'terminal_id': terminal_id} + if automation: + metadata.update(model_id=automation.data.get('model_id'), automation_id=automation.id) + return await get_agent_models(request, user, metadata, cwd=cwd) # Create New Automation diff --git a/backend/open_webui/routers/configs.py b/backend/open_webui/routers/configs.py index cf0ebdeb82..7e5244ab37 100644 --- a/backend/open_webui/routers/configs.py +++ b/backend/open_webui/routers/configs.py @@ -329,8 +329,6 @@ class TerminalServerConnection(BaseModel): config: dict | None = None server_type: str | None = None - policy_id: str | None = None - model_config = ConfigDict(extra='allow') @@ -374,7 +372,7 @@ async def verify_terminal_server_connection( """ Verify the connection to a terminal server by detecting its type. - Tries GET {url}/api/v1/policies (orchestrator) then GET {url}/api/config + Tries GET {url}/api/v1/terminals/templates (orchestrator) then GET {url}/api/config (plain terminal). Returns ``{status: true, type: "orchestrator"|"terminal"}``. """ if not ENABLE_TOOL_SERVERS: @@ -393,10 +391,10 @@ async def verify_terminal_server_connection( trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT), ) as session: - # Orchestrators expose a policies API; plain terminals don't. + # Orchestrators expose a templates API; plain terminals don't. try: async with session.get( - f'{base_url}/api/v1/policies', headers=headers, ssl=AIOHTTP_CLIENT_SESSION_SSL + f'{base_url}/api/v1/terminals/templates', headers=headers, ssl=AIOHTTP_CLIENT_SESSION_SSL ) as resp: if resp.ok: return {'status': True, 'type': 'orchestrator'} @@ -419,162 +417,6 @@ async def verify_terminal_server_connection( raise HTTPException(status_code=400, detail='Failed to connect to the terminal server') -class TerminalServerPolicyForm(BaseModel): - url: str - key: str | None = '' - auth_type: str | None = 'bearer' - policy_id: str - policy_data: dict | None = None - - -class TerminalServerLifecycleForm(BaseModel): - url: str - key: str | None = '' - auth_type: str | None = 'bearer' - policy_id: str - lifecycle_data: dict | None = None - - -class TerminalServerRefreshForm(BaseModel): - url: str - key: str | None = '' - auth_type: str | None = 'bearer' - user_id: str | None = None - policy_id: str | None = None - only_idle: bool = True - reset: bool = False - - -@router.post('/terminal_servers/policy') -async def put_terminal_server_policy( - request: Request, form_data: TerminalServerPolicyForm, user=Depends(get_admin_user) -): - """Proxy a policy read or update to an orchestrator terminal server.""" - if not ENABLE_TOOL_SERVERS: - raise HTTPException(status_code=403, detail='Tool servers are disabled') - - base_url = (form_data.url or '').rstrip('/') - if not base_url: - raise HTTPException(status_code=400, detail='Terminal server URL is required') - - headers = {'Content-Type': 'application/json'} - if form_data.auth_type in ('bearer', 'session') and form_data.key: - headers.update(bearer_auth_header(form_data.key)) - - try: - async with aiohttp.ClientSession( - trust_env=True, - timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT), - ) as session: - policy_url = f'{base_url}/api/v1/policies/{form_data.policy_id}' - async with session.request( - 'GET' if form_data.policy_data is None else 'PUT', - policy_url, - headers=headers, - json=form_data.policy_data, - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) as resp: - if resp.ok: - return await resp.json() - detail = await resp.text() - raise HTTPException(status_code=resp.status, detail=detail) - except HTTPException: - raise - except Exception as e: - log.debug('Failed to access policy on terminal server: %s', e) - raise HTTPException(status_code=400, detail='Failed to access policy on terminal server') - - -@router.post('/terminal_servers/lifecycle') -async def put_terminal_server_lifecycle( - request: Request, form_data: TerminalServerLifecycleForm, user=Depends(get_admin_user) -): - """Proxy a lifecycle read or update to an orchestrator terminal server.""" - if not ENABLE_TOOL_SERVERS: - raise HTTPException(status_code=403, detail='Tool servers are disabled') - - base_url = (form_data.url or '').rstrip('/') - if not base_url: - raise HTTPException(status_code=400, detail='Terminal server URL is required') - - headers = {'Content-Type': 'application/json'} - if form_data.auth_type in ('bearer', 'session') and form_data.key: - headers.update(bearer_auth_header(form_data.key)) - - try: - async with aiohttp.ClientSession( - trust_env=True, - timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT), - ) as session: - lifecycle_url = f'{base_url}/api/v1/policies/{form_data.policy_id}/lifecycle' - async with session.request( - 'GET' if form_data.lifecycle_data is None else 'PUT', - lifecycle_url, - headers=headers, - json=form_data.lifecycle_data, - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) as resp: - if resp.ok: - return await resp.json() - detail = await resp.text() - raise HTTPException(status_code=resp.status, detail=detail) - except HTTPException: - raise - except Exception as e: - log.debug('Failed to access lifecycle on terminal server: %s', e) - raise HTTPException(status_code=400, detail='Failed to access lifecycle on terminal server') - - -@router.post('/terminal_servers/refresh') -async def refresh_terminal_server_terminals( - request: Request, form_data: TerminalServerRefreshForm, user=Depends(get_admin_user) -): - """ - Proxy a terminal refresh request to an orchestrator terminal server. - """ - if not ENABLE_TOOL_SERVERS: - raise HTTPException(status_code=403, detail='Tool servers are disabled') - - base_url = (form_data.url or '').rstrip('/') - if not base_url: - raise HTTPException(status_code=400, detail='Terminal server URL is required') - - headers = {'Content-Type': 'application/json'} - if form_data.auth_type in ('bearer', 'session') and form_data.key: - headers.update(bearer_auth_header(form_data.key)) - - body = { - 'only_idle': form_data.only_idle, - 'reset': form_data.reset, - } - if form_data.user_id: - body['user_id'] = form_data.user_id - if form_data.policy_id: - body['policy_id'] = form_data.policy_id - - try: - async with aiohttp.ClientSession( - trust_env=True, - timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT), - ) as session: - refresh_url = f'{base_url}/api/v1/terminals/refresh' - async with session.post( - refresh_url, - headers=headers, - json=body, - ssl=AIOHTTP_CLIENT_SESSION_SSL, - ) as resp: - if resp.ok: - return await resp.json() - detail = await resp.text() - raise HTTPException(status_code=resp.status, detail=detail) - except HTTPException: - raise - except Exception as e: - log.debug('Failed to refresh terminals: %s', e) - raise HTTPException(status_code=400, detail='Failed to refresh terminals') - - @router.post('/tool_servers/verify') async def verify_tool_servers_config(request: Request, form_data: ToolServerConnection, user=Depends(get_admin_user)): """ diff --git a/backend/open_webui/routers/templates.py b/backend/open_webui/routers/templates.py new file mode 100644 index 0000000000..a0eb108e6f --- /dev/null +++ b/backend/open_webui/routers/templates.py @@ -0,0 +1,164 @@ +"""Template management and context-authorized terminal lifecycle operations.""" +from urllib.parse import quote +from uuid import UUID + +from fastapi import APIRouter, Depends, HTTPException, Request +from pydantic import BaseModel, Field +from open_webui.models.access_grants import AccessGrants +from open_webui.models.config import Config +from open_webui.utils.access_control import validate_access_grants +from open_webui.utils.auth import get_verified_user +from open_webui.utils.terminals import ( + has_connection_write_access, get_connection, server_request, template_terminal_id, template_connection, + get_terminal_context, find_terminal_connection, +) + +router = APIRouter() + + +class CreateForm(BaseModel): + id: UUID + connection_id: str + data: dict = Field(default_factory=dict) + + +class ShareForm(BaseModel): + access_grants: list[dict] + + +class InstanceForm(BaseModel): + user_id: str | None = Field(default=None, min_length=1) + chat_id: str | None = None + model_id: str | None = None + + +def path(template_id, suffix=''): + return f'api/v1/terminals/templates/{quote(template_id, safe="")}{suffix}' + + +async def changed(user_id, terminal_id, previous=()): + from open_webui.socket.main import emit_to_users + current = await AccessGrants.get_grants_by_resource('terminal', terminal_id) + recipients = {user_id} + recipients.update(await AccessGrants.get_user_ids_by_access_grants([*previous, *current], 'read')) + await emit_to_users('events', {'data': {'type': 'terminals:changed'}}, list(recipients)) + + +@router.get('/connections') +async def management_connections(user=Depends(get_verified_user)): + result = [] + for connection in await Config.get('terminal_server.connections', []) or []: + if connection.get('server_type') != 'orchestrator' or not connection.get('enabled', True): + continue + try: + await get_connection(user, connection['id']) + except HTTPException: + continue + if await has_connection_write_access(user, connection): + result.append({'id': connection['id'], 'name': connection.get('name', connection['id'])}) + return result + + +@router.post('', status_code=201) +async def create_template(body: CreateForm, user=Depends(get_verified_user)): + connection = await get_connection(user, body.connection_id) + if not await has_connection_write_access(user, connection): + raise HTTPException(403, 'Creation is not allowed') + row = await server_request(connection, 'api/v1/terminals/templates', method='POST', + body={'id': str(body.id), 'data': body.data}) + selector = template_terminal_id(connection['id'], row['id']) + try: + await AccessGrants.set_access_grants('terminal', selector, [ + {'principal_type': 'user', 'principal_id': user.id, 'permission': 'read'} + ]) + except Exception: + await server_request(connection, path(row['id']), method='DELETE') + raise + await changed(user.id, selector) + return {**row, 'terminal_id': selector} + + +@router.get('/{terminal_id}') +async def get_template(terminal_id: str, user=Depends(get_verified_user)): + _, template = await template_connection(user, terminal_id, 'write') + return template + + +@router.patch('/{terminal_id}') +async def update_template(terminal_id: str, body: dict, user=Depends(get_verified_user)): + connection, template = await template_connection(user, terminal_id, 'write') + result = await server_request(connection, path(template['id']), method='PATCH', body=body) + await changed(user.id, terminal_id) + return result + + +@router.delete('/{terminal_id}') +async def delete_template(terminal_id: str, user=Depends(get_verified_user)): + connection, template = await template_connection(user, terminal_id, 'write') + previous = await AccessGrants.get_grants_by_resource('terminal', terminal_id) + result = await server_request(connection, path(template['id']), method='DELETE') + await AccessGrants.set_access_grants('terminal', terminal_id, []) + await changed(user.id, terminal_id, previous) + return result + + +@router.get('/{terminal_id}/access') +async def get_shares(terminal_id: str, user=Depends(get_verified_user)): + await template_connection(user, terminal_id, 'write') + return [grant for grant in await AccessGrants.get_grants_by_resource('terminal', terminal_id) + if grant.get('permission') == 'read'] + + +@router.post('/{terminal_id}/access') +async def set_shares(terminal_id: str, body: ShareForm, user=Depends(get_verified_user)): + await template_connection(user, terminal_id, 'write') + if any(g.get('principal_type') not in ('user', 'group') or g.get('principal_id') in (None, '', '*') + for g in body.access_grants): + raise HTTPException(400, 'Public terminal sharing is not allowed') + grants = await validate_access_grants(await Config.get('user.permissions'), user.id, user.role, + body.access_grants, resource_type='terminal') + previous = await AccessGrants.get_grants_by_resource('terminal', terminal_id) + await AccessGrants.set_access_grants('terminal', terminal_id, grants) + await changed(user.id, terminal_id, previous) + return {'ok': True} + + +@router.get('/{terminal_id}/instance') +async def current_instance(terminal_id: str, request: Request, chat_id: str | None = None, + model_id: str | None = None, user=Depends(get_verified_user)): + connection = await find_terminal_connection(user, terminal_id, {'chat_id': chat_id, 'model_id': model_id}, request=request) + if not connection or not connection.get('template_id'): + raise HTTPException(404, 'Template not found') + result = await server_request(connection, path(connection['template_id'], '/instance'), + params={k: v for k, v in connection['terminal_context'].items() if v is not None}) + return result + + +@router.get('/{terminal_id}/instances') +async def list_instances(terminal_id: str, user=Depends(get_verified_user)): + connection, template = await template_connection(user, terminal_id, 'write') + return await server_request(connection, path(template['id'], '/instances')) + + +async def instance_action(terminal_id, action, body, user): + connection, template = await template_connection(user, terminal_id, 'write') + context = get_terminal_context(template, body.user_id or user.id, body.model_dump(exclude_none=True)) + result = await server_request(connection, path(template['id'], '/instance' if action == 'delete' else '/' + action), + method='DELETE' if action == 'delete' else 'POST', body=context) + await changed(user.id, terminal_id) + return result + + +@router.post('/{terminal_id}/restart') +async def restart(terminal_id: str, body: InstanceForm, user=Depends(get_verified_user)): + return await instance_action(terminal_id, 'restart', body, user) + + +@router.post('/{terminal_id}/reset') +async def reset(terminal_id: str, body: InstanceForm, user=Depends(get_verified_user)): + return await instance_action(terminal_id, 'reset', body, user) + + +@router.delete('/{terminal_id}/instance') +async def delete_instance(terminal_id: str, body: InstanceForm, user=Depends(get_verified_user)): + return await instance_action(terminal_id, 'delete', body, user) diff --git a/backend/open_webui/routers/terminals.py b/backend/open_webui/routers/terminals.py index c4a0a73f86..1a85ff61d7 100644 --- a/backend/open_webui/routers/terminals.py +++ b/backend/open_webui/routers/terminals.py @@ -21,21 +21,18 @@ from open_webui.config import TERMINAL_PROXY_HEADERS from open_webui.env import AIOHTTP_CLIENT_SESSION_SSL, ENABLE_TOOL_SERVERS from open_webui.events import EVENTS, publish_event from open_webui.models.groups import Groups +from open_webui.routers.templates import router as templates_router from open_webui.utils.access_control import has_connection_access from open_webui.utils.auth import get_verified_user, get_verified_user_by_token -from open_webui.utils.browser import browser_access, browser_ticket +from open_webui.utils.browser import browser_access, create_browser_token from open_webui.utils.tether import RelayInterrupted, get_terminal_connections, get_terminal_client from open_webui.utils.headers import bearer_auth_header, normalize_bearer_token from open_webui.utils.json_codec import JSONCodec from open_webui.utils.terminals import ( - TERMINAL_CONTEXT_HEADER, + find_terminal_connection, + terminal_headers, get_terminal_server_url, - is_terminal_orchestrator, terminal_chat_uploads, - terminal_context_available, - terminal_context_config, - terminal_context_id, - terminal_contexts, ) from starlette.background import BackgroundTask from starlette.requests import ClientDisconnect @@ -44,6 +41,7 @@ from yarl import URL log = logging.getLogger(__name__) router = APIRouter() +router.include_router(templates_router, prefix='/templates') STREAMING_CONTENT_TYPES = ('application/octet-stream', 'image/', 'application/pdf', 'text/event-stream') ADMIN_API_PATHS = ('api/v1/policies', 'api/v1/status', 'api/v1/terminals') @@ -160,14 +158,24 @@ def _sanitize_proxy_path(path: str) -> str | None: @router.api_route( - '/{server_id}/browser/view/{sid}/{ticket}/{path:path}', + '/{server_id}/browser/view/{sid}/{browser_token}/{path:path}', methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'], ) -async def browser_http(request: Request, server_id: str, sid: str, ticket: str, path: str): - user, data = await browser_access(server_id, sid, ticket) - request.state.browser_auth = data['relay'] - request.scope['path_params']['chat_id'] = data.get('chat', '') - return await proxy_terminal(server_id, f'browser/view/{sid}/{data["capability"]}/{path}', request, user) +async def browser_http(request: Request, server_id: str, sid: str, browser_token: str, path: str): + user, data = await browser_access(server_id, sid, browser_token) + if data.get('resource') == 'files': + if request.method not in ('GET', 'HEAD', 'OPTIONS'): + raise HTTPException(405, 'File preview tokens are read-only') + file_path = _sanitize_proxy_path(path) + if file_path is None: + raise HTTPException(400, 'Invalid file path') + path = f'files/serve/{file_path}' + else: + path = f'browser/view/{sid}/{data["capability"]}/{path}' + return await _proxy_terminal( + server_id, path, request, user, + context=browser_context(data), browser_auth=data['relay'], + ) async def relay_from_browser(ws, upstream): @@ -191,56 +199,41 @@ async def relay_to_browser(ws, upstream): return -async def watch_access(server_id, sid, ticket): +async def watch_access(server_id, sid, browser_token, request): while True: await asyncio.sleep(10) - current_user, _ = await browser_access(server_id, sid, ticket) - latest = await get_terminal_connections(current_user) - current = next((c for c in latest if c.get('id') == server_id), None) - if ( - not current - or not current.get('enabled', True) - or not ENABLE_TOOL_SERVERS - or not await has_connection_access(current_user, current) - or not terminal_context_available(current, 'chat') - ): + current_user, data = await browser_access(server_id, sid, browser_token) + current = await find_terminal_connection(current_user, server_id, browser_context(data), request=request) + if not current: return -@router.websocket('/{server_id}/browser/view/{sid}/{ticket}/{kind}') -async def browser_ws(ws: WebSocket, server_id: str, sid: str, ticket: str, kind: str): +@router.websocket('/{server_id}/browser/view/{sid}/{browser_token}/{kind}') +async def browser_ws(ws: WebSocket, server_id: str, sid: str, browser_token: str, kind: str): try: - user, data = await browser_access(server_id, sid, ticket) - connections = await get_terminal_connections(user) - connection = next((c for c in connections if c.get('id') == server_id), None) + user, data = await browser_access(server_id, sid, browser_token) + connection = await find_terminal_connection(user, server_id, browser_context(data), request=ws) if ( kind not in ('ws', 'stream', 'vnc') + or data.get('resource') == 'files' or not ENABLE_TOOL_SERVERS or not connection - or not connection.get('enabled', True) - or not await has_connection_access(user, connection) - or not terminal_context_available(connection, 'chat') ): raise HTTPException(403, 'Browser access denied') chat = data.get('chat', '') - context = terminal_context_id(connection, {'chat_id': chat}, 'chat') - if terminal_context_config(connection, 'chat').get('context_id') == 'chat_id' and not context: - raise HTTPException(403, 'Saved chat required') except HTTPException: await ws.close(code=4001) return await ws.accept() base = get_terminal_server_url(connection).replace('https://', 'wss://').replace('http://', 'ws://') url = f'{base}/browser/view/{sid}/{quote(data["capability"], safe="")}/{kind}' - headers = {'X-User-Id': user.id, 'X-Session-Id': chat} - if context: - headers[TERMINAL_CONTEXT_HEADER] = context + headers = {'X-User-Id': user.id, 'X-Session-Id': chat, **terminal_headers(connection)} if data['relay'].get('authorization'): headers['Authorization'] = data['relay']['authorization'] tasks = [] try: async with get_terminal_client( - base, user.id, cookies=data['relay'].get('cookies', {}), trust_env=True + base, connection.get('instance_user_id', user.id), cookies=data['relay'].get('cookies', {}), trust_env=True ) as client: async with client.ws_connect( url, @@ -251,7 +244,7 @@ async def browser_ws(ws: WebSocket, server_id: str, sid: str, ticket: str, kind: tasks = [ asyncio.create_task(relay_from_browser(ws, upstream)), asyncio.create_task(relay_to_browser(ws, upstream)), - asyncio.create_task(watch_access(server_id, sid, ticket)), + asyncio.create_task(watch_access(server_id, sid, browser_token, ws)), ] await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) except aiohttp.WSServerHandshakeError as exc: @@ -280,11 +273,12 @@ async def list_terminal_servers(request: Request, user=Depends(get_verified_user 'id': connection.get('id', ''), 'url': '' if connection.get('owner_id') else connection.get('url', ''), 'name': connection.get('name', ''), - 'contexts': terminal_contexts(connection), + 'template_id': connection.get('template_id'), + 'scope': connection.get('scope'), 'config': {'chat_uploads': terminal_chat_uploads(connection)}, } for connection in connections - if connection.get('enabled', True) and await has_connection_access(user, connection, user_group_ids) + if connection.get('enabled', True) and (connection.get('template_id') or await has_connection_access(user, connection, user_group_ids)) ] @@ -300,23 +294,24 @@ async def proxy_terminal( request: Request, user=Depends(get_verified_user), ): - """Proxy a request to the admin terminal server identified by *server_id*.""" + return await _proxy_terminal( + server_id, path, request, user, + context={ + 'chat_id': request.path_params.get('chat_id') or request.headers.get('x-session-id'), + 'model_id': request.headers.get('x-terminal-model-id'), + }, + ) + + +async def _proxy_terminal(server_id, path, request, user, *, context, browser_auth=None): if not ENABLE_TOOL_SERVERS: return JSONResponse({'error': 'Tool servers are disabled'}, status_code=403) - connections = await get_terminal_connections(user) - connection = next((c for c in connections if c.get('id') == server_id), None) + connection = await find_terminal_connection(user, server_id, context, request=request) if connection is None: return JSONResponse({'error': f"Terminal server '{server_id}' not found"}, status_code=404) - if not connection.get('enabled', True): - return JSONResponse({'error': 'Terminal server disabled'}, status_code=403) - - user_group_ids = {group.id for group in await Groups.get_groups_by_member_id(user.id, include_inherited=True)} - if not await has_connection_access(user, connection, user_group_ids): - return JSONResponse({'error': 'Access denied'}, status_code=403) - base_url = get_terminal_server_url(connection) if not base_url: return JSONResponse({'error': 'Terminal server URL not configured'}, status_code=503) @@ -341,26 +336,12 @@ async def proxy_terminal( headers = {'X-User-Id': user.id} # Forward per-session cwd tracking header - session_id = request.path_params.get('chat_id') or request.headers.get('x-session-id') - if ( - safe_path.rstrip('/') == 'system/info' - and (terminal_context_config(connection, 'chat') or {}).get('context_id') == 'chat_id' - and not terminal_context_id(connection, {'chat_id': session_id}, 'chat') - ): - return JSONResponse({'error': 'A saved chat is required for this terminal'}, status_code=409) + session_id = context.get('chat_id') if session_id: headers['X-Session-Id'] = session_id - if not terminal_context_available(connection, 'chat'): - return JSONResponse({'error': 'Terminal server is not available in chats'}, status_code=403) - context_id = terminal_context_id(connection, {'chat_id': session_id}, 'chat') - if terminal_context_config(connection, 'chat').get('context_id') == 'chat_id' and not context_id: - return JSONResponse({'error': 'A saved chat is required for this terminal'}, status_code=409) - if context_id: - headers[TERMINAL_CONTEXT_HEADER] = context_id cookies = getattr(request, 'cookies', {}) if connection.get('forward_cookies', False) else {} auth_type = connection.get('auth_type', 'bearer') - browser_auth = getattr(request.state, 'browser_auth', None) if browser_auth is not None: cookies = browser_auth.get('cookies', {}) if browser_auth.get('authorization'): @@ -396,13 +377,22 @@ async def proxy_terminal( if value := request.headers.get(name): headers[name] = value + headers.update(terminal_headers(connection)) content_type = request.headers.get('content-type') if content_type: headers['Content-Type'] = content_type + if connection.get('template_id') and safe_path == 'files/preview' and request.method == 'POST': + browser_token = create_browser_token( + server_id, user.id, session_id or '', {'id': 'files', 'token': ''}, + headers, cookies, resource='files', + ) + base = request.url.path.removesuffix('/files/preview') + return {'url': f'{base}/browser/view/files/{quote(browser_token, safe="")}/'} + session = get_terminal_client( base_url, - user.id, + connection.get('instance_user_id', user.id), timeout=aiohttp.ClientTimeout(total=300, connect=10), trust_env=True, ) @@ -471,7 +461,7 @@ async def proxy_terminal( ): browser_session = json.loads(response_body) if isinstance(browser_session, dict) and browser_session.get('id') and browser_session.get('token'): - browser_session['token'] = browser_ticket( + browser_session['token'] = create_browser_token( server_id, user.id, session_id or '', browser_session, headers, cookies ) response_body = json.dumps(browser_session).encode() @@ -528,11 +518,11 @@ async def _resolve_authenticated_connection(ws: WebSocket, server_id: str): await ws.close(code=4001, reason='Invalid token') return None + ws.state.auth = payload result = await _resolve_terminal_access(ws, server_id, token) if result is None: return None user, connection = result - ws.state.auth = payload chat_id = payload.get('chat_id', '') return user, connection, chat_id if isinstance(chat_id, str) else '', token @@ -553,8 +543,11 @@ async def _resolve_terminal_access(ws: WebSocket, server_id: str, token: str): return None # Resolve terminal server - connections = await get_terminal_connections(user) - connection = next((c for c in connections if c.get('id') == server_id), None) + try: + connection = await find_terminal_connection(user, server_id, socket_metadata(ws), request=ws) + except HTTPException as exc: + await ws.close(code=4003, reason=str(exc.detail)) + return None if connection is None: if server_id.startswith('tether:'): @@ -563,17 +556,6 @@ async def _resolve_terminal_access(ws: WebSocket, server_id: str, token: str): await ws.close(code=4004, reason='Terminal server not found') return None - if not connection.get('enabled', True): - await ws.close(code=4003, reason='Terminal server disabled') - return None - - if not await has_connection_access(user, connection): - await ws.close(code=4003, reason='Access denied') - return None - - if not terminal_context_available(connection, 'chat'): - await ws.close(code=4003, reason='Terminal server is not available in chats') - return None return user, connection @@ -638,19 +620,12 @@ async def _proxy_terminal_websocket( upstream_params = {} # For orchestrator-backed servers, pass user_id - upstream_params['user_id'] = user.id + upstream_params['user_id'] = connection.get('instance_user_id', user.id) if stream_path.startswith('execute/'): for key in ('offset', 'tail'): if key in ws.query_params: upstream_params[key] = ws.query_params[key] - context_id = terminal_context_id(connection, {'chat_id': chat_id}, 'chat') - upstream_headers = {'X-User-Id': user.id, 'X-Session-Id': chat_id} - if terminal_context_config(connection, 'chat').get('context_id') == 'chat_id' and not context_id: - await ws.close(code=4003, reason='A saved chat is required for this terminal') - return - if context_id: - upstream_headers[TERMINAL_CONTEXT_HEADER] = context_id - + upstream_headers = {'X-User-Id': user.id, 'X-Session-Id': chat_id, **terminal_headers(connection)} import urllib.parse # Encode session_id as an opaque path segment so it cannot smuggle '?'/'#'/'&' (at any @@ -664,7 +639,7 @@ async def _proxy_terminal_websocket( request = Request({**ws.scope, 'type': 'http', 'method': 'GET'}) opened = False - session = get_terminal_client(base_url, user.id) + session = get_terminal_client(base_url, connection.get('instance_user_id', user.id)) try: async with session.ws_connect( upstream_url, @@ -678,8 +653,6 @@ async def _proxy_terminal_websocket( if auth_type == 'bearer': key = normalize_bearer_token(connection.get('key', '')) await upstream.send_str(_json.dumps({**ws.state.auth, 'token': key})) - elif auth_type == 'session' and is_terminal_orchestrator(connection): - await upstream.send_str(_json.dumps({**ws.state.auth, 'token': token})) else: await upstream.send_str(_json.dumps({**ws.state.auth, 'token': ''})) @@ -775,3 +748,12 @@ async def _proxy_terminal_websocket( await ws.close() except Exception: pass + + +def browser_context(data): + return {'chat_id': data.get('chat'), 'model_id': data.get('model')} + + +def socket_metadata(ws): + auth = getattr(ws.state, 'auth', {}) + return {'chat_id': auth.get('chat_id'), 'model_id': auth.get('model_id')} diff --git a/backend/open_webui/utils/access_control/__init__.py b/backend/open_webui/utils/access_control/__init__.py index c9a9d2c69d..cc57a76101 100644 --- a/backend/open_webui/utils/access_control/__init__.py +++ b/backend/open_webui/utils/access_control/__init__.py @@ -227,6 +227,7 @@ _SHARING_PERMISSION_KEYS = { 'channel': (None, 'sharing.public_channels', None), 'calendar': (None, 'sharing.public_calendars', None), 'shared_chat': (None, 'sharing.public_chats', 'sharing.open_chats'), + 'terminal': (None, None, None), } @@ -296,6 +297,8 @@ async def validate_access_grants( ) -> list: """Reject unauthorized sharing changes before replacing any stored grants.""" grants = normalize_access_grants(access_grants) + if resource_type == 'terminal' and any(grant['permission'] != 'read' for grant in grants): + raise HTTPException(400, 'Template access grants must be read-only') allowed = await filter_allowed_access_grants(default_permissions, user_id, user_role, grants, resource_type, db=db) if len(allowed) != len(grants): raise HTTPException(403, 'You do not have permission to share with the requested audience') diff --git a/backend/open_webui/utils/agents/discovery.py b/backend/open_webui/utils/agents/discovery.py index 58c7823f61..49dc2c3bfa 100644 --- a/backend/open_webui/utils/agents/discovery.py +++ b/backend/open_webui/utils/agents/discovery.py @@ -2,7 +2,7 @@ from urllib.parse import quote, urlencode -from open_webui.utils.terminals import get_terminal_json +from open_webui.utils.terminals import MissingTerminalContext, get_terminal_json def model_controls(model): @@ -36,14 +36,17 @@ async def get_models(request, user, metadata, *, provider=None, cwd=None): terminal_id = metadata.get('terminal_id') if not terminal_id: return [] - if not cwd: - directory = await get_terminal_json(request, user, metadata, '/files/cwd') - cwd = (directory or {}).get('cwd') - params = {'provider': provider} if provider else {} - if cwd: - params['cwd'] = cwd - path = '/agents' + ('?' + urlencode(params) if params else '') - catalog = await get_terminal_json(request, user, metadata, path) + try: + if not cwd: + directory = await get_terminal_json(request, user, metadata, '/files/cwd') + cwd = (directory or {}).get('cwd') + params = {'provider': provider} if provider else {} + if cwd: + params['cwd'] = cwd + path = '/agents' + ('?' + urlencode(params) if params else '') + catalog = await get_terminal_json(request, user, metadata, path) + except MissingTerminalContext: + return [] if not catalog or catalog.get('protocol_version') != 1: return [] models = [ diff --git a/backend/open_webui/utils/agents/transport.py b/backend/open_webui/utils/agents/transport.py index 155f24686d..5a189f7fca 100644 --- a/backend/open_webui/utils/agents/transport.py +++ b/backend/open_webui/utils/agents/transport.py @@ -34,7 +34,7 @@ class TerminalTransport: resolved = await resolve_terminal_connection(request, user, metadata) if not resolved: raise ValueError('Select an accessible server or Tether terminal to use agents') - return cls(*resolved, user.id) + return cls(*resolved, resolved[0].get('instance_user_id', user.id)) async def request(self, method, path, body=None): async with get_terminal_client( diff --git a/backend/open_webui/utils/automations.py b/backend/open_webui/utils/automations.py index b65c096aad..942ef6399a 100644 --- a/backend/open_webui/utils/automations.py +++ b/backend/open_webui/utils/automations.py @@ -205,10 +205,18 @@ async def validate_automation_terminal(request, user, data: dict, automation_id: if is_agent: raise HTTPException(400, 'Select a terminal for the agent.') return - metadata = { - 'terminal_id': terminal['server_id'], - 'automation_id': automation_id or f'preview:{user.id}', - } + if terminal['server_id'].startswith('template:'): + from open_webui.utils.terminals import template_connection, require_model_access + _, template = await template_connection(user, terminal['server_id']) + scope = (template.get('data') or {}).get('scope') + if (data.get('target') or {}).get('type') == 'channel' and (is_agent or scope == 'chat'): + raise HTTPException(400, 'This terminal requires a chat destination.') + if scope == 'model': + await require_model_access(user, model_id, terminal['server_id'], request) + return + metadata = {'terminal_id': terminal['server_id'], 'model_id': model_id} + if automation_id: + metadata['automation_id'] = automation_id if not await resolve_terminal_connection(request, user, metadata): raise HTTPException(400, 'The configured terminal is unavailable for this automation.') if is_agent: @@ -301,7 +309,7 @@ async def _execute_channel_automation( await initialize_terminal_directory( request, user, - {'chat_id': form_data['chat_id'], 'automation_id': automation.id}, + {'chat_id': form_data['chat_id'], 'automation_id': automation.id, 'model_id': model_id}, terminal['server_id'], terminal.get('cwd'), ) @@ -491,7 +499,7 @@ async def execute_automation(app, automation: AutomationModel) -> None: await initialize_terminal_directory( request, user, - {'chat_id': chat.id, 'automation_id': automation.id}, + {'chat_id': chat.id, 'automation_id': automation.id, 'model_id': model_id}, terminal['server_id'], terminal.get('cwd'), ) diff --git a/backend/open_webui/utils/browser.py b/backend/open_webui/utils/browser.py index 2bc3ebf3d7..19041c21b6 100644 --- a/backend/open_webui/utils/browser.py +++ b/backend/open_webui/utils/browser.py @@ -2,7 +2,7 @@ from fastapi import HTTPException from open_webui.utils.auth import create_token, decode_token, get_verified_user_by_id -def browser_ticket(server_id, user_id, chat_id, session, headers=None, cookies=None): +def create_browser_token(server_id, user_id, chat_id, session, headers=None, cookies=None, *, resource='browser'): from open_webui.utils.oauth import encrypt_data relay = encrypt_data( @@ -18,14 +18,16 @@ def browser_ticket(server_id, user_id, chat_id, session, headers=None, cookies=N 'user': user_id, 'chat': chat_id, 'session': session['id'], + 'resource': resource, + 'model': (headers or {}).get('X-Terminal-Model-Id'), 'capability': session['token'], 'relay': relay, }, ) -async def browser_access(server_id, sid, ticket): - data = decode_token(ticket) +async def browser_access(server_id, sid, browser_token): + data = decode_token(browser_token) if ( not data or data.get('purpose') != 'terminal-browser' diff --git a/backend/open_webui/utils/terminals.py b/backend/open_webui/utils/terminals.py index dd212431bc..2542bca79c 100644 --- a/backend/open_webui/utils/terminals.py +++ b/backend/open_webui/utils/terminals.py @@ -6,9 +6,14 @@ import logging import ntpath import posixpath from pathlib import Path -from urllib.parse import quote +from urllib.parse import quote, unquote -from open_webui.env import AIOHTTP_CLIENT_TIMEOUT_TERMINAL, ENABLE_TOOL_SERVERS +import aiohttp + +from fastapi import HTTPException + +from open_webui.env import AIOHTTP_CLIENT_SESSION_SSL, AIOHTTP_CLIENT_TIMEOUT_TERMINAL, ENABLE_TOOL_SERVERS +from open_webui.utils.headers import bearer_auth_header from open_webui.utils.chat_id import is_saved_chat_id from open_webui.utils.skill_files import ( SKILL_CONTENT_MAX_CHARS, @@ -18,10 +23,6 @@ from open_webui.utils.skill_files import ( skill_overview, ) -TERMINAL_CONTEXT_HEADER = 'X-Terminal-Context-Id' -TERMINAL_CONTEXT_DEFAULT = 'default' -TERMINAL_CONTEXT_TYPES = {'chat', 'automation'} -TERMINAL_CONTEXT_ID_SOURCES = {'chat': 'chat_id', 'automation': 'automation_id'} TERMINAL_CHAT_UPLOAD_MODES = {'default', 'filesystem'} MAX_AGENTS_MD_BYTES = 32 * 1024 @@ -29,99 +30,11 @@ log = logging.getLogger(__name__) def is_terminal_orchestrator(connection: dict) -> bool: - """Return whether this connection points at Terminals, not raw Open Terminal.""" - return connection.get('server_type') == 'orchestrator' or bool(connection.get('policy_id')) + return connection.get('server_type') == 'orchestrator' def get_terminal_server_url(connection: dict) -> str: - """Return the upstream base URL for a terminal connection. - - An explicit policy uses the named-policy route. Connections without one - keep their existing root route. - """ - base_url = str(connection.get('url') or '').rstrip('/') - policy_id = str(connection.get('policy_id') or '').strip() - if policy_id: - return f'{base_url}/p/{quote(policy_id, safe="")}' - return base_url - - -def terminal_context_config(connection: dict, context: str) -> dict | bool: - """Return config for an OpenWebUI terminal context. - - Missing config is legacy behavior: available, shared default terminal. - """ - if not is_terminal_orchestrator(connection): - return {} - - contexts = (connection.get('config') or {}).get('contexts') - if not isinstance(contexts, dict): - return {} - - value = contexts.get(context, {}) - if value is False: - return False - return value if isinstance(value, dict) else {} - - -def terminal_context_available(connection: dict, context: str) -> bool: - """Return whether this terminal is exposed in an OpenWebUI context.""" - if context not in TERMINAL_CONTEXT_TYPES: - return False - return terminal_context_config(connection, context) is not False - - -def terminal_context_id( - connection: dict, - metadata: dict | None = None, - context: str = 'chat', -) -> str | None: - """Return the terminal runtime context for trusted request metadata.""" - if not is_terminal_orchestrator(connection) or not terminal_context_available(connection, context): - return None - - config = terminal_context_config(connection, context) - context_id_source = config.get('context_id') if isinstance(config, dict) else None - if not context_id_source or context_id_source == TERMINAL_CONTEXT_DEFAULT: - return None - - if context_id_source != TERMINAL_CONTEXT_ID_SOURCES.get(context): - return None - - metadata = metadata or {} - - if context == 'automation': - automation_id = metadata.get('automation_id') - return f'automation:{automation_id}' if automation_id else None - - chat_id = metadata.get('chat_id') - if context == 'chat' and chat_id and is_saved_chat_id(chat_id): - return f'chat:{chat_id}' - return None - - -def terminal_contexts(connection: dict) -> dict: - """Return normalized sparse context config for clients.""" - if not is_terminal_orchestrator(connection): - return {} - - contexts = (connection.get('config') or {}).get('contexts') - if not isinstance(contexts, dict): - return {} - - result = {} - for context, value in contexts.items(): - if context not in TERMINAL_CONTEXT_TYPES: - continue - if value is False: - result[context] = False - elif isinstance(value, dict): - context_id_source = value.get('context_id') - if context_id_source in {TERMINAL_CONTEXT_DEFAULT, TERMINAL_CONTEXT_ID_SOURCES[context]}: - result[context] = {'context_id': context_id_source} - else: - result[context] = {} - return result + return str(connection.get('url') or '').rstrip('/') def terminal_chat_uploads(connection: dict) -> str: @@ -130,49 +43,311 @@ def terminal_chat_uploads(connection: dict) -> str: return value if value in TERMINAL_CHAT_UPLOAD_MODES else 'default' -async def resolve_terminal_connection(request, user, metadata): - """Resolve an authorized backend connection and trusted runtime headers.""" - terminal_id = metadata.get('terminal_id') - if not ENABLE_TOOL_SERVERS or not terminal_id: - return None - from open_webui.utils.tether import get_terminal_connections +async def server_request(connection, path, *, method='GET', body=None, params=None): + if not connection.get('key'): + raise HTTPException(503, 'A Terminals server key is required') + url = connection['url'].rstrip('/') + '/' + path.lstrip('/') + try: + async with aiohttp.ClientSession(trust_env=True, timeout=aiohttp.ClientTimeout(total=180)) as session: + async with session.request( + method, + url, + headers=bearer_auth_header(connection['key']), + json=body, + params=params, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + allow_redirects=False, + ) as response: + if response.status >= 300: + try: + detail = (await response.json()).get('detail', 'Terminals request failed') + except Exception: + detail = 'Terminals request failed' + raise HTTPException(response.status if response.status >= 400 else 502, detail) + return await response.json() + except (aiohttp.ClientError, asyncio.TimeoutError): + raise HTTPException(503, 'Terminals is unavailable') + + +async def get_connection(user, connection_id): + from open_webui.models.config import Config + from open_webui.utils.access_control import has_connection_access + + if not ENABLE_TOOL_SERVERS: + raise HTTPException(403, 'Tool servers are disabled') + connections = await Config.get('terminal_server.connections', []) or [] + connection = next((c for c in connections if c.get('id') == connection_id), None) + if not connection or not connection.get('enabled', True) or connection.get('server_type') != 'orchestrator': + raise HTTPException(404, 'Managed terminal connection not found') + if not await has_connection_access(user, connection) and not await has_connection_write_access(user, connection): + raise HTTPException(403, 'Terminal connection access denied') + return connection + + +async def has_connection_write_access(user, connection, user_group_ids=None): + from open_webui.models.groups import Groups + from open_webui.utils.access_control import has_access + + from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL + + if user.role == 'admin' and ( + BYPASS_ADMIN_ACCESS_CONTROL or not (connection.get('config') or {}).get('access_grants') + ): + return True + if user_group_ids is None: + user_group_ids = {g.id for g in await Groups.get_groups_by_member_id(user.id, include_inherited=True)} + return await has_access(user.id, 'write', (connection.get('config') or {}).get('access_grants', []), user_group_ids) + + +def template_terminal_id(connection_id, template_id): + return f'template:{connection_id}:{quote(template_id, safe="")}' + + +def split_template_id(terminal_id): + if not terminal_id.startswith('template:'): + raise HTTPException(400, 'Invalid template terminal ID') + connection_id, separator, encoded = terminal_id.removeprefix('template:').rpartition(':') + template_id = unquote(encoded) + if not separator or not connection_id or not template_id or template_terminal_id(connection_id, template_id) != terminal_id: + raise HTTPException(400, 'Invalid template terminal ID') + return connection_id, template_id + + +async def require_terminal_access(user, terminal_id): + from open_webui.models.access_grants import AccessGrants + from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL + + if user.role == 'admin' and BYPASS_ADMIN_ACCESS_CONTROL: + return + if await AccessGrants.has_access(user.id, 'terminal', terminal_id, 'read'): + return + raise HTTPException(403, 'Terminal access denied') + + +async def template_connection(user, terminal_id, permission='read'): + connection_id, template_id = split_template_id(terminal_id) + connection = await get_connection(user, connection_id) + if not await has_connection_write_access(user, connection): + if permission == 'write': + raise HTTPException(403, 'Terminal connection write access required') + await require_terminal_access(user, terminal_id) + template = await server_request(connection, f'api/v1/terminals/templates/{quote(template_id, safe="")}') + return connection, template + + +async def list_template_connections(user, connections): + from open_webui.models.access_grants import AccessGrants from open_webui.models.groups import Groups from open_webui.models.users import UserModel from open_webui.utils.access_control import has_connection_access + + if not isinstance(user, UserModel): + user = UserModel(**user) + group_ids = { + group.id for group in await Groups.get_groups_by_member_id(user.id, include_inherited=True) + } + result = [] + for connection in connections: + if connection.get('server_type') != 'orchestrator' or not connection.get('enabled', True): + continue + writable = await has_connection_write_access(user, connection, group_ids) + if not writable and not await has_connection_access(user, connection, group_ids): + continue + try: + templates = await server_request(connection, 'api/v1/terminals/templates') + except HTTPException as exc: + log.warning('Cannot list templates for connection %s: HTTP %s', connection['id'], exc.status_code) + continue + selectors = [template_terminal_id(connection['id'], template['id']) for template in templates] + readable = set(selectors) if writable else await AccessGrants.get_accessible_resource_ids( + user_id=user.id, resource_type='terminal', resource_ids=selectors, + permission='read', user_group_ids=group_ids, + ) + for template, selector in zip(templates, selectors): + if selector not in readable: + continue + data = template.get('data') or {} + result.append({ + **connection, 'id': selector, + 'name': data.get('name') or template['id'], + 'template_id': template['id'], 'scope': data.get('scope'), + 'auth_type': 'bearer', + }) + return result + + +class MissingTerminalContext(HTTPException): + def __init__(self, scope): + detail = 'This terminal requires a saved chat' if scope == 'chat' else f'This terminal requires a {scope}' + super().__init__(409, detail) + + +def get_terminal_context(template, user_id, metadata=None): + """Validate a template's scope and return context for its environment.""" + metadata = metadata or {} + scope = (template.get('data') or {}).get('scope') + if scope not in (None, 'user', 'chat', 'model'): + raise HTTPException(422, 'Invalid template scope') + chat_id = metadata.get('chat_id') + model_id = metadata.get('model_id') or metadata.get('model') + if scope == 'chat' and not is_saved_chat_id(chat_id): + raise MissingTerminalContext(scope) + if scope == 'model' and not model_id: + raise MissingTerminalContext(scope) + return { + 'user_id': user_id, + 'chat_id': chat_id if is_saved_chat_id(chat_id) else None, + 'model_id': model_id if scope == 'model' else None, + } + + +async def require_model_access(user, model_id, terminal_id, request=None): + if not model_id: + raise MissingTerminalContext('model') + if model_id.startswith('agent:'): + parts = model_id.split(':', 3) + if len(parts) != 4 or unquote(parts[1]) != terminal_id or not all(parts[1:]): + raise HTTPException(403, 'Agent model does not belong to this terminal') + # Agent access follows its terminal. Execution still validates the live agent catalog. + return + from open_webui.models.models import Models + from open_webui.utils.models import check_model_access, get_all_models, get_filtered_models + if request is not None: + models = await get_all_models(request, user=user) + permitted = await get_filtered_models(models, user) + if not any(model['id'] == model_id for model in permitted): + raise HTTPException(403, 'Model access denied') + else: + row = await Models.get_model_by_id(model_id) + if row is None: + raise HTTPException(403, 'Model not found') + try: + await check_model_access(user, {'id': model_id}, row) + except Exception as exc: + raise HTTPException(403, 'Model access denied') from exc + + +def terminal_headers(connection): + """Only consumes context produced by find_terminal_connection, never browser headers.""" + if not connection.get('template_id'): + return {'X-User-Id': connection['instance_user_id']} if connection.get('instance_user_id') else {} + context = connection['terminal_context'] + headers = { + 'X-Terminal-Template-Id': connection['template_id'], + 'X-User-Id': context['user_id'], + } + if context.get('chat_id'): + headers['X-Terminal-Chat-Id'] = context['chat_id'] + if context.get('model_id'): + headers['X-Terminal-Model-Id'] = context['model_id'] + return headers + + +async def find_terminal_connection(user, terminal_id, metadata=None, request=None): + from open_webui.models.chats import Chats + from open_webui.models.users import UserModel, Users + from open_webui.utils.access_control import has_connection_access + from open_webui.utils.tether import get_terminal_connections + + if not ENABLE_TOOL_SERVERS: + raise HTTPException(403, 'Tool servers are disabled') + if not isinstance(user, UserModel): + user = UserModel(**user) + metadata = dict(metadata or {}) + chat = None + shared_session = None + instance_user = user + chat_id = metadata.get('chat_id') + if chat_id and is_saved_chat_id(chat_id): + chat = await Chats.get_accessible_chat_by_id(chat_id, user, permission='write') + if chat is None: + raise HTTPException(403, 'Chat access denied') + from open_webui.utils.agents.session import get_session, model_id + shared_session = await get_session(chat) + if shared_session and shared_session['terminal_id'] != terminal_id: + shared_session = None + if shared_session: + metadata['model_id'] = model_id(shared_session) + instance_user_id = shared_session.get('terminal_user_id') or shared_session['user'] + instance_user = user if instance_user_id == user.id else await Users.get_user_by_id(instance_user_id) + if instance_user is None: + raise HTTPException(403, 'Agent terminal owner is unavailable') + + def authorized_connection(connection): + if shared_session: + connection = {**connection, 'instance_user_id': instance_user.id} + return connection + + if not terminal_id.startswith('template:'): + connections = await get_terminal_connections(instance_user, include_templates=False) + connection = next((c for c in connections if c.get('id') == terminal_id), None) + if not connection or not connection.get('enabled', True) or not await has_connection_access(instance_user, connection): + return None + if is_terminal_orchestrator(connection): + raise HTTPException(409, 'Select a terminal template') + return authorized_connection(connection) + + connection_id, template_id = split_template_id(terminal_id) + connection = await get_connection(instance_user, connection_id) + template = await server_request(connection, f'api/v1/terminals/templates/{quote(template_id, safe="")}') + scope = (template.get('data') or {}).get('scope') + + if chat and not shared_session: + stored = (chat.chat or {}).get('terminal_id') + if chat.user_id != user.id and stored != terminal_id: + raise HTTPException(403, 'Use the terminal selected by the chat owner') + if stored and stored != terminal_id: + raise HTTPException(409, 'Chat terminal selection changed; refresh the chat') + + principal = instance_user + if not shared_session and scope == 'chat' and chat: + owner = user if chat.user_id == user.id else await Users.get_user_by_id(chat.user_id) + if owner is None: + raise HTTPException(403, 'Chat owner is unavailable') + if owner.id != instance_user.id and not await has_connection_access(owner, connection) and not await has_connection_write_access(owner, connection): + raise HTTPException(403, 'Terminal connection access denied') + principal = owner + if not await has_connection_write_access(principal, connection): + await require_terminal_access(principal, terminal_id) + + context = get_terminal_context(template, instance_user.id, metadata) + if scope == 'model': + await require_model_access(instance_user, context['model_id'], terminal_id, request) + if metadata.get('automation_id'): + from open_webui.models.automations import Automations + automation = await Automations.get_by_id(metadata['automation_id']) + if not automation or automation.user_id != user.id: + raise HTTPException(403, 'Automation terminal access denied') + return authorized_connection({ + **connection, 'id': terminal_id, + 'template_id': template_id, 'scope': scope, 'auth_type': 'bearer', + 'terminal_context': context, + }) + + +async def resolve_terminal_connection(request, user, metadata): + """Resolve an authorized backend connection and trusted instance headers.""" + terminal_id = metadata.get('terminal_id') + if not ENABLE_TOOL_SERVERS or not terminal_id: + return None + from open_webui.models.users import UserModel from open_webui.utils.tools import build_tool_server_headers user_model = user if isinstance(user, UserModel) else UserModel(**user) - connections = await get_terminal_connections(user_model) - connection = next((item for item in connections if item.get('id') == terminal_id), None) + connection = await find_terminal_connection(user_model, terminal_id, metadata, request=request) if connection: - terminal_context = 'automation' if metadata.get('automation_id') else 'chat' - context_id = terminal_context_id(connection, metadata, terminal_context) - config = terminal_context_config(connection, terminal_context) - if ( - not connection.get('enabled', True) - or not terminal_context_available(connection, terminal_context) - or (config.get('context_id') in {'chat_id', 'automation_id'} and not context_id) - ): - return None - user_group_ids = { - group.id for group in await Groups.get_groups_by_member_id(user_model.id, include_inherited=True) - } - if not await has_connection_access(user_model, connection, user_group_ids): - return None - headers, cookies = await build_tool_server_headers( connection, request, user_model, metadata=metadata, ) + headers.update(terminal_headers(connection)) headers['Accept'] = 'application/json' - headers['X-User-Id'] = user_model.id + headers['X-User-Id'] = connection.get('instance_user_id', user_model.id) if metadata.get('chat_id'): headers['X-Session-Id'] = metadata['chat_id'] - if context_id: - headers[TERMINAL_CONTEXT_HEADER] = context_id return connection, headers, cookies return None @@ -208,7 +383,7 @@ async def get_terminal_json( from open_webui.storage.provider import Storage source = await Files.get_file_by_id(file['id']) - if not source or source.user_id != headers['X-User-Id'] or not source.path: + if not source or source.user_id != (user.id if hasattr(user, 'id') else user['id']) or not source.path: return None local_path = await asyncio.to_thread(Storage.get_file, source.path) body = aiohttp.FormData() @@ -223,7 +398,7 @@ async def get_terminal_json( try: async with get_terminal_client( get_terminal_server_url(connection), - user.id if hasattr(user, 'id') else user['id'], + connection.get('instance_user_id') or (user.id if hasattr(user, 'id') else user['id']), timeout=timeout, trust_env=True, ) as session: @@ -400,7 +575,7 @@ async def get_terminal_file(request, user, metadata: dict, path: str, *, max_byt base_url = get_terminal_server_url(connection) async with get_terminal_client( base_url, - user.id if hasattr(user, 'id') else user['id'], + connection.get('instance_user_id') or (user.id if hasattr(user, 'id') else user['id']), timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_TERMINAL), trust_env=True, ) as session: diff --git a/backend/open_webui/utils/tether.py b/backend/open_webui/utils/tether.py index 1ffe9bedc1..80c782be95 100644 --- a/backend/open_webui/utils/tether.py +++ b/backend/open_webui/utils/tether.py @@ -388,7 +388,7 @@ async def notify(user_id, notification_id, title, body, path): ) -async def get_terminal_connections(user): +async def get_terminal_connections(user, include_templates=True): """Resolve personal targets alongside existing configured servers.""" user_id = user['id'] if isinstance(user, dict) else user.id connections = list(await Config.get('terminal_server.connections', []) or []) @@ -413,6 +413,11 @@ async def get_terminal_connections(user): }, } ) + if include_templates: + from open_webui.utils.terminals import list_template_connections + managed = [c for c in connections if c.get('server_type') == 'orchestrator'] + connections = [c for c in connections if c.get('server_type') != 'orchestrator'] + connections.extend(await list_template_connections(user, managed)) return connections diff --git a/backend/open_webui/utils/tools.py b/backend/open_webui/utils/tools.py index e42f673c69..37c4aefa1e 100644 --- a/backend/open_webui/utils/tools.py +++ b/backend/open_webui/utils/tools.py @@ -125,13 +125,9 @@ from open_webui.utils.plugin import ( load_tool_module_by_id, set_tool_module_in_cache, ) -from open_webui.utils.tether import RelayInterrupted, get_terminal_connections, get_terminal_client +from open_webui.utils.tether import RelayInterrupted, get_terminal_client from open_webui.utils.terminals import ( - TERMINAL_CONTEXT_HEADER, get_terminal_server_url, - terminal_context_available, - terminal_context_config, - terminal_context_id, ) from open_webui.utils.voice_avatar import avatar_animation_tools from pydantic import BaseModel, Field, create_model @@ -1447,7 +1443,7 @@ async def set_terminal_servers(request: Request): # Terminal connections store id/name at top level; translate to info dict server_configs = [] for connection in connections: - if not connection.get('url'): + if not connection.get('url') or connection.get('server_type') == 'orchestrator': continue enabled = connection.get('enabled', True) @@ -1487,8 +1483,6 @@ async def set_terminal_servers(request: Request): headers = {} if connection.get('auth_type', 'bearer') == 'bearer': headers.update(bearer_auth_header(connection.get('key', ''))) - if connection.get('policy_id'): - headers['X-User-Id'] = 'system' prompt = await get_terminal_system_prompt(server['url'], headers) if prompt: server['system_prompt'] = prompt @@ -1549,11 +1543,8 @@ async def get_terminal_tools( if not ENABLE_TOOL_SERVERS: return {} - connections = await get_terminal_connections(user) - connection = next( - (terminal_connection for terminal_connection in connections if terminal_connection.get('id') == terminal_id), - None, - ) + from open_webui.utils.terminals import find_terminal_connection, terminal_headers + connection = await find_terminal_connection(user, terminal_id, extra_params.get('__metadata__', {}), request=request) if connection is None: raise RuntimeError(f"Terminal server '{terminal_id}' not found") if not connection.get('enabled', True): @@ -1564,7 +1555,12 @@ async def get_terminal_tools( raise RuntimeError(f'Access denied to terminal {terminal_id}') # Find the cached spec data for this terminal - if connection.get('owner_id') == user.id: + if connection.get('template_id'): + url = get_terminal_server_url(connection) + discovery_headers = {**bearer_auth_header(connection['key']), **terminal_headers(connection)} + openapi = await get_tool_server_data(url + '/openapi.json', discovery_headers) + server_data = {'id': terminal_id, 'url': url, 'openapi': openapi, 'specs': convert_openapi_to_tool_payload(openapi)} + elif connection.get('owner_id') == user.id: url = connection['url'] openapi = await get_tool_server_data(url + '/openapi.json', {'X-User-Id': user.id}) server_data = { @@ -1600,20 +1596,11 @@ async def get_terminal_tools( # Use chat_id as the per-session key for cwd tracking metadata = extra_params.get('__metadata__', {}) - terminal_context = 'automation' if metadata.get('automation_id') else 'chat' - if not terminal_context_available(connection, terminal_context): - raise RuntimeError(f"Terminal server '{terminal_id}' is not available for {terminal_context}") - session_id = metadata.get('chat_id') if session_id: headers['X-Session-Id'] = session_id - context_id = terminal_context_id(connection, metadata, terminal_context) - config = terminal_context_config(connection, terminal_context) - if isinstance(config, dict) and config.get('context_id') in {'chat_id', 'automation_id'} and not context_id: - raise RuntimeError(f"Terminal server '{terminal_id}' requires a saved {terminal_context} context") - if context_id: - headers[TERMINAL_CONTEXT_HEADER] = context_id + headers.update(terminal_headers(connection)) # Fetch live with the user's credentials so prompt changes apply without a restart connection_config = connection.get('config') or {} @@ -1642,12 +1629,19 @@ async def get_terminal_tools( async def make_tool_function(fn_name, srv_data, hdrs, cks): async def tool_function(**kwargs): + call_headers = dict(hdrs) + if connection.get('template_id'): + current = await find_terminal_connection(user, terminal_id, + {**metadata, 'scope': connection.get('scope')}, request=request) + if current is None: + raise HTTPException(403, 'Terminal access revoked') + call_headers.update(terminal_headers(current)) params = dict(kwargs) if fn_name == 'display_file': params.pop('page', None) return await execute_tool_server( url=srv_data['url'], - headers=hdrs, + headers=call_headers, cookies=cks, name=fn_name, params=params, diff --git a/src/lib/apis/configs/index.ts b/src/lib/apis/configs/index.ts index b50d547fde..bcc76dbb70 100644 --- a/src/lib/apis/configs/index.ts +++ b/src/lib/apis/configs/index.ts @@ -248,9 +248,9 @@ export const setTerminalServerConnections = async (token: string, connections: o /** * Detect whether a terminal server URL points to an Orchestrator or a direct - * Open Terminal instance. + * Open Terminal server. * - * - GET {url}/api/v1/policies → 200 → "orchestrator" + * - GET {url}/api/v1/terminals/templates → 200 → "orchestrator" * - GET {url}/api/config → 200 → "terminal" * - Neither → null */ @@ -264,9 +264,9 @@ export const detectTerminalServerType = async ( headers['Authorization'] = `Bearer ${key}`; } - // Orchestrators expose a policies API; plain terminals don't. + // Orchestrators expose a templates API; plain terminals don't. try { - const res = await fetch(`${baseUrl}/api/v1/policies`, { headers }); + const res = await fetch(`${baseUrl}/api/v1/terminals/templates`, { headers }); if (res.ok) return 'orchestrator'; } catch { // ignore @@ -283,192 +283,6 @@ export const detectTerminalServerType = async ( return null; }; -/** - * Create or update a policy on the orchestrator. - * Proxied through the Open WebUI backend to keep API keys server-side. - */ -export const putOrchestratorPolicy = async ( - token: string, - url: string, - key: string, - policyId: string, - policyData: object, - authType: string = 'bearer' -): Promise => { - let error = null; - - const res = await fetch(`${WEBUI_API_BASE_URL}/configs/terminal_servers/policy`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${token}` - }, - body: JSON.stringify({ - url: url.replace(/\/$/, ''), - key, - auth_type: authType, - policy_id: policyId, - policy_data: policyData - }) - }) - .then(async (res) => { - if (!res.ok) throw await res.json(); - return res.json(); - }) - .catch((err) => { - console.error(err); - error = err.detail; - return null; - }); - - if (error) { - throw error; - } - - return res; -}; - -export const getOrchestratorPolicy = async ( - token: string, - url: string, - key: string, - policyId: string, - authType: string = 'bearer' -): Promise => { - const res = await fetch(`${WEBUI_API_BASE_URL}/configs/terminal_servers/policy`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${token}` - }, - body: JSON.stringify({ - url: url.replace(/\/$/, ''), - key, - auth_type: authType, - policy_id: policyId - }) - }); - if (!res.ok) { - const body = await res.json(); - throw Object.assign(new Error(body.detail || 'Failed to read policy'), { status: res.status }); - } - return res.json(); -}; - -export const putOrchestratorLifecycle = async ( - token: string, - url: string, - key: string, - policyId: string, - lifecycleData: object, - authType: string = 'bearer' -): Promise => { - let error = null; - - const res = await fetch(`${WEBUI_API_BASE_URL}/configs/terminal_servers/lifecycle`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${token}` - }, - body: JSON.stringify({ - url: url.replace(/\/$/, ''), - key, - auth_type: authType, - policy_id: policyId, - lifecycle_data: lifecycleData - }) - }) - .then(async (res) => { - if (!res.ok) throw await res.json(); - return res.json(); - }) - .catch((err) => { - console.error(err); - error = err.detail; - return null; - }); - - if (error) { - throw error; - } - - return res; -}; - -export const getOrchestratorLifecycle = async ( - token: string, - url: string, - key: string, - policyId: string, - authType: string = 'bearer' -): Promise => { - const res = await fetch(`${WEBUI_API_BASE_URL}/configs/terminal_servers/lifecycle`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${token}` - }, - body: JSON.stringify({ - url: url.replace(/\/$/, ''), - key, - auth_type: authType, - policy_id: policyId - }) - }); - if (!res.ok) { - const body = await res.json(); - throw Object.assign(new Error(body.detail || 'Failed to read lifecycle'), { - status: res.status - }); - } - return res.json(); -}; - -export const refreshOrchestratorTerminals = async ( - token: string, - url: string, - key: string, - body: { - user_id?: string; - policy_id?: string; - only_idle?: boolean; - reset?: boolean; - }, - authType: string = 'bearer' -): Promise => { - let error = null; - - const res = await fetch(`${WEBUI_API_BASE_URL}/configs/terminal_servers/refresh`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${token}` - }, - body: JSON.stringify({ - url: url.replace(/\/$/, ''), - key, - auth_type: authType, - ...body - }) - }) - .then(async (res) => { - if (!res.ok) throw await res.json(); - return res.json(); - }) - .catch((err) => { - console.error(err); - error = err.detail; - return null; - }); - - if (error) { - throw error; - } - - return res; -}; - /** * Verify a terminal server connection via the backend proxy. * Used for system/admin connections to avoid CORS issues and API key exposure. diff --git a/src/lib/apis/terminal/browser.ts b/src/lib/apis/terminal/browser.ts index fcf8627970..9e2a67428d 100644 --- a/src/lib/apis/terminal/browser.ts +++ b/src/lib/apis/terminal/browser.ts @@ -1,4 +1,4 @@ -import { terminalRequest, type TerminalConnection } from './index'; +import { terminalRequest, type TerminalTarget } from './index'; export type BrowserSession = { id: string; @@ -9,68 +9,46 @@ export type BrowserSession = { chrome_available: boolean; }; -export const getBrowserSession = ( - connection: TerminalConnection, - chatId: string | null, - id: string -) => - terminalRequest( - connection, - chatId, - `/browser/sessions/${encodeURIComponent(id)}` - ); +export const getBrowserSession = (target: TerminalTarget, id: string) => + terminalRequest(target, `/browser/sessions/${encodeURIComponent(id)}`); -export const createBrowserSession = async ( - connection: TerminalConnection, - chatId: string | null, - url = '' -) => { - const session = await terminalRequest(connection, chatId, '/browser/sessions', { +export const createBrowserSession = async (target: TerminalTarget, url = '') => { + const session = await terminalRequest(target, '/browser/sessions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url }) }); if (!session.chrome_available || session.mode === 'chrome') return session; try { - return await updateBrowserSession(connection, chatId, session.id, { mode: 'chrome' }); + return await updateBrowserSession(target, session.id, { mode: 'chrome' }); } catch { // Reset the server too: Chrome startup may have failed after changing the mode. - return updateBrowserSession(connection, chatId, session.id, { mode: 'proxy' }); + return updateBrowserSession(target, session.id, { mode: 'proxy' }); } }; export const updateBrowserSession = ( - connection: TerminalConnection, - chatId: string | null, + target: TerminalTarget, id: string, fields: Partial> & { active?: boolean; chat_id?: string; } ) => - terminalRequest( - connection, - chatId, - `/browser/sessions/${encodeURIComponent(id)}`, - { - method: 'PATCH', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(fields) - } - ); + terminalRequest(target, `/browser/sessions/${encodeURIComponent(id)}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(fields) + }); -export const closeBrowserSession = ( - connection: TerminalConnection, - chatId: string | null, - id: string -) => - terminalRequest(connection, chatId, `/browser/sessions/${encodeURIComponent(id)}`, { +export const closeBrowserSession = (target: TerminalTarget, id: string) => + terminalRequest(target, `/browser/sessions/${encodeURIComponent(id)}`, { method: 'DELETE', keepalive: true }); -export const browserViewUrl = (connection: TerminalConnection, session: BrowserSession) => - `${connection.baseUrl.replace(/\/$/, '')}/browser/view/${encodeURIComponent(session.id)}/${encodeURIComponent(session.token)}`; +export const browserViewUrl = (target: TerminalTarget, session: BrowserSession) => + `${target.baseUrl.replace(/\/$/, '')}/browser/view/${encodeURIComponent(session.id)}/${encodeURIComponent(session.token)}`; export function browserFrameUrl(prefix: string, value: string) { const url = new URL(value); diff --git a/src/lib/apis/terminal/events.ts b/src/lib/apis/terminal/events.ts index c7969c6e68..b287f55c06 100644 --- a/src/lib/apis/terminal/events.ts +++ b/src/lib/apis/terminal/events.ts @@ -1,9 +1,8 @@ -import type { ListeningPort, TerminalConnection } from './index'; +import type { ListeningPort, TerminalTarget } from './index'; import { openTerminalSocket } from './socket'; function watchTerminalEvents( - connection: TerminalConnection, - chatId: string | null, + target: TerminalTarget, subscription: { path?: string; ports?: boolean }, onMessage: (message: any) => void, onError: (message: string) => void @@ -13,7 +12,7 @@ function watchTerminalEvents( let retry: ReturnType; let retryDelay = 1000; const connect = () => { - socket = openTerminalSocket(connection, chatId, '/events', (socket) => { + socket = openTerminalSocket(target, '/events', (socket) => { socket.send(JSON.stringify({ type: 'subscribe', ...subscription })); }); socket.onmessage = (event) => { @@ -45,15 +44,13 @@ function watchTerminalEvents( } export function watchTerminalFiles( - connection: TerminalConnection, - chatId: string | null, + target: TerminalTarget, directory: string, onChange: () => void, onError: (message: string) => void ) { return watchTerminalEvents( - connection, - chatId, + target, { path: directory }, (message) => { if (message.type === 'fs:ready' || message.type === 'fs:change') onChange(); @@ -63,14 +60,12 @@ export function watchTerminalFiles( } export function watchTerminalPorts( - connection: TerminalConnection, - chatId: string | null, + target: TerminalTarget, onPorts: (ports: ListeningPort[]) => void, onError: (message: string) => void ) { return watchTerminalEvents( - connection, - chatId, + target, { ports: true }, (message) => { if (message.type === 'ports:change') onPorts(message.ports); diff --git a/src/lib/apis/terminal/git.ts b/src/lib/apis/terminal/git.ts index f83f31a6dd..8ba6b6d65e 100644 --- a/src/lib/apis/terminal/git.ts +++ b/src/lib/apis/terminal/git.ts @@ -3,7 +3,8 @@ import { config } from '$lib/stores'; import { joinTerminalPath, terminalRequest, - type TerminalConnection, + terminalHeaders, + type TerminalTarget, type TerminalProcessOutput } from './index'; @@ -54,8 +55,7 @@ export function gitRemoteWebUrl(remote = ''): string { } export async function gitRequest( - connection: TerminalConnection, - chatId: string | null, + target: TerminalTarget, directory: string, operation: string, params: Record = {}, @@ -64,11 +64,10 @@ export async function gitRequest( ): Promise { if (!get(config)?.features?.enable_tool_servers) throw new Error('Tool servers are disabled'); const query = new URLSearchParams({ root: directory, ...params }); - const response = await fetch(`${connection.baseUrl}/git/${operation}?${query}`, { + const response = await fetch(`${target.baseUrl}/git/${operation}?${query}`, { method, headers: { - Authorization: `Bearer ${connection.key.trim()}`, - ...(chatId ? { 'X-Session-Id': chatId } : {}), + ...terminalHeaders(target), ...(body ? { 'Content-Type': 'application/json' } : {}) }, ...(body ? { body: JSON.stringify({ root: directory, ...body }) } : {}) @@ -92,8 +91,7 @@ export async function gitRequest( } export function gitAction( - connection: TerminalConnection, - chatId: string | null, + target: TerminalTarget, directory: string, action: string, fields: Record @@ -121,7 +119,7 @@ export function gitAction( method = 'DELETE'; body = { name: fields.branch }; } - return gitRequest(connection, chatId, directory, operation, {}, body, method); + return gitRequest(target, directory, operation, {}, body, method); } const repositoryFolderName = (url: string) => @@ -133,8 +131,7 @@ const repositoryFolderName = (url: string) => ?.replace(/\.git$/, '') ?? ''; export async function cloneRepository( - connection: Pick, - chatId: string | null, + target: Pick, directory: string, url: string, signal?: AbortSignal @@ -151,28 +148,22 @@ export async function cloneRepository( if (!directory) throw new Error('Choose a destination directory'); const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`; - let result = await terminalRequest( - connection, - chatId, - '/execute?wait=1&tail=20', - { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - command: `git clone -- ${quote(url)} ${quote(`./${name}`)}`, - cwd: directory, - env: { - GIT_TERMINAL_PROMPT: '0', - GIT_SSH_COMMAND: 'ssh -oBatchMode=yes -oStrictHostKeyChecking=yes -oConnectTimeout=15' - } - }), - signal - } - ); + let result = await terminalRequest(target, '/execute?wait=1&tail=20', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + command: `git clone -- ${quote(url)} ${quote(`./${name}`)}`, + cwd: directory, + env: { + GIT_TERMINAL_PROMPT: '0', + GIT_SSH_COMMAND: 'ssh -oBatchMode=yes -oStrictHostKeyChecking=yes -oConnectTimeout=15' + } + }), + signal + }); while (result.status === 'running') { result = await terminalRequest( - connection, - chatId, + target, `/execute/${encodeURIComponent(result.id)}/status?wait=1&tail=20`, { signal } ); diff --git a/src/lib/apis/terminal/index.ts b/src/lib/apis/terminal/index.ts index e1332c483d..a9dc73e734 100644 --- a/src/lib/apis/terminal/index.ts +++ b/src/lib/apis/terminal/index.ts @@ -113,14 +113,12 @@ export type TerminalFeatures = { // Missing flags mean unsupported; never probe a new endpoint on an older server. export async function getTerminalFeatures( - connection: Pick, - chatId: string | null, + target: Pick, signal?: AbortSignal ): Promise { try { const result = await terminalRequest<{ features?: TerminalFeatures }>( - connection, - chatId, + target, '/api/config', { signal } ); @@ -148,18 +146,18 @@ export type TerminalSkill = { is_active: boolean; source: 'terminal'; terminal_path: string; - terminal_scope: 'global'; terminal_selector: string; terminal_name?: string; }; import { WEBUI_API_BASE_URL } from '$lib/constants'; -export type TerminalConnection = { +export type TerminalTarget = { selector: string; baseUrl: string; key: string; system: boolean; + context: { chatId: string | null; modelId: string | null }; }; export type TerminalProcess = { id: string; @@ -173,17 +171,24 @@ export type TerminalProcessOutput = TerminalProcess & { truncated: boolean; }; -export const resolveTerminalConnection = ( +export const resolveTerminalTarget = ( selector: string | null, servers: any[], directServers: any[], - token: string -): TerminalConnection | null => { + token: string, + context: Partial = {} +): TerminalTarget | null => { if (!get(config)?.features?.enable_tool_servers || !selector) return null; - if (servers.some((server) => server.id === selector)) { + const server = servers.find((server) => server.id === selector); + if (server) { + if (server.scope === 'model' && !context.modelId) return null; return { selector, baseUrl: `${WEBUI_API_BASE_URL}/terminals/${encodeURIComponent(selector)}`, + context: { + chatId: context.chatId ?? null, + modelId: server.scope === 'model' ? (context.modelId ?? null) : null + }, // Panels outlive Tether's token rotations; read the current session at request time. get key() { return typeof localStorage === 'undefined' ? token : (localStorage.getItem('token') ?? ''); @@ -193,7 +198,13 @@ export const resolveTerminalConnection = ( } const direct = directServers.find((server) => server.url === selector); return direct - ? { selector, baseUrl: direct.url.replace(/\/$/, ''), key: direct.key ?? '', system: false } + ? { + selector, + baseUrl: direct.url.replace(/\/$/, ''), + key: direct.key ?? '', + system: false, + context: { chatId: context.chatId ?? null, modelId: null } + } : null; }; @@ -208,18 +219,16 @@ export class TerminalRequestError extends Error { } export const terminalRequest = async ( - connection: Pick, - chatId: string | null, + target: Pick, path: string, options: RequestInit = {} ): Promise => { if (!get(config)?.features?.enable_tool_servers) throw new TerminalRequestError('Tool servers are disabled', 403); - const response = await fetch(`${connection.baseUrl}${path}`, { + const response = await fetch(`${target.baseUrl}${path}`, { ...options, headers: { - Authorization: `Bearer ${connection.key.trim()}`, - ...(chatId ? { 'X-Session-Id': chatId } : {}), + ...terminalHeaders(target), ...options.headers } }); @@ -237,9 +246,15 @@ export const terminalRequest = async ( return response.json(); }; -const bearerHeaders = (apiKey: string): Record => { +export const terminalHeaders = ( + target: Pick +): Record => { if (!get(config)?.features?.enable_tool_servers) throw new Error('Tool servers are disabled'); - return { Authorization: `Bearer ${apiKey.trim()}` }; + return { + Authorization: `Bearer ${target.key.trim()}`, + ...(target.context.chatId ? { 'X-Session-Id': target.context.chatId } : {}), + ...(target.context.modelId ? { 'X-Terminal-Model-Id': target.context.modelId } : {}) + }; }; export const joinTerminalPath = (base: string, child: string) => { @@ -258,10 +273,11 @@ const hasHiddenPathPart = (path: string) => .some((part) => part.startsWith('.')); export type TerminalServer = { + template_id?: string; + scope?: 'user' | 'chat' | 'model' | null; id: string; url: string; name: string; - contexts?: Record; config?: { chat_uploads?: 'default' | 'filesystem'; [key: string]: unknown; @@ -279,26 +295,10 @@ export const getTerminalServers = async (token: string): Promise []); }; -export const getTerminalConfig = async ( - baseUrl: string, - apiKey: string -): Promise<{ features: TerminalFeatures } | null> => { - const url = `${baseUrl.replace(/\/$/, '')}/api/config`; - const res = await fetch(url, { - headers: bearerHeaders(apiKey) - }).catch(() => null); - if (!res || !res.ok) return null; - return res.json().catch(() => null); -}; +export const getCwd = async (target: TerminalTarget): Promise => { + const url = `${target.baseUrl.replace(/\/$/, '')}/files/cwd`; + const headers: Record = terminalHeaders(target); -export const getCwd = async ( - baseUrl: string, - apiKey: string, - sessionId?: string -): Promise => { - const url = `${baseUrl.replace(/\/$/, '')}/files/cwd`; - const headers: Record = bearerHeaders(apiKey); - if (sessionId) headers['X-Session-Id'] = sessionId; const res = await fetch(url, { headers }).catch(() => null); if (!res || !res.ok) return null; const json = await res.json().catch(() => null); @@ -311,15 +311,13 @@ export const getCwd = async ( }; export const listFiles = async ( - baseUrl: string, - apiKey: string, - path: string = '/', - sessionId?: string + target: TerminalTarget, + path: string = '/' ): Promise => { // The endpoint uses `directory` as the query param name - const url = `${baseUrl.replace(/\/$/, '')}/files/list?directory=${encodeURIComponent(path)}`; - const headers: Record = bearerHeaders(apiKey); - if (sessionId) headers['X-Session-Id'] = sessionId; + const url = `${target.baseUrl.replace(/\/$/, '')}/files/list?directory=${encodeURIComponent(path)}`; + const headers: Record = terminalHeaders(target); + const res = await fetch(url, { headers }) .then(async (res) => { if (!res.ok) throw await res.json(); @@ -333,18 +331,15 @@ export const listFiles = async ( }; export const searchFiles = async ( - baseUrl: string, - apiKey: string, + target: TerminalTarget, query: string, path: string = '.', limit: number = 20, type: 'file' | 'directory' | 'any' = 'any', - sessionId?: string, showHidden: boolean = false, signal?: AbortSignal ): Promise => { - const headers: Record = bearerHeaders(apiKey); - if (sessionId) headers['X-Session-Id'] = sessionId; + const headers: Record = terminalHeaders(target); const searchParams = new URLSearchParams({ query, @@ -353,7 +348,7 @@ export const searchFiles = async ( type, show_hidden: String(showHidden) }); - const base = baseUrl.replace(/\/$/, ''); + const base = target.baseUrl.replace(/\/$/, ''); const searchRes = await fetch(`${base}/files/search?${searchParams.toString()}`, { headers, signal @@ -397,17 +392,14 @@ export const searchFiles = async ( }; export const getFileMatches = async ( - baseUrl: string, - apiKey: string, + target: TerminalTarget, query: string, path: string = '.', showHidden: boolean = false, offset: number = 0, - sessionId?: string, signal?: AbortSignal ): Promise => { - const headers: Record = bearerHeaders(apiKey); - if (sessionId) headers['X-Session-Id'] = sessionId; + const headers: Record = terminalHeaders(target); const params = new URLSearchParams({ query, @@ -415,10 +407,13 @@ export const getFileMatches = async ( show_hidden: String(showHidden), offset: String(offset) }); - const res = await fetch(`${baseUrl.replace(/\/$/, '')}/files/matches?${params.toString()}`, { - headers, - signal - }).catch((err) => { + const res = await fetch( + `${target.baseUrl.replace(/\/$/, '')}/files/matches?${params.toString()}`, + { + headers, + signal + } + ).catch((err) => { if (err?.name !== 'AbortError') console.error('open-terminal getFileMatches error:', err); return null; }); @@ -428,18 +423,16 @@ export const getFileMatches = async ( }; export const readComparisonSource = async ( - baseUrl: string, - apiKey: string, + target: TerminalTarget, path: string, signal: AbortSignal, - sessionId?: string, size?: number ): Promise => { checkSourceSize(size); - const headers = bearerHeaders(apiKey); - if (sessionId) headers['X-Session-Id'] = sessionId; + const headers = terminalHeaders(target); + const response = await fetch( - `${baseUrl.replace(/\/$/, '')}/files/view?path=${encodeURIComponent(path)}`, + `${target.baseUrl.replace(/\/$/, '')}/files/view?path=${encodeURIComponent(path)}`, { headers, signal } ).catch(() => { signal.throwIfAborted(); @@ -449,14 +442,12 @@ export const readComparisonSource = async ( }; export const readFile = async ( - baseUrl: string, - apiKey: string, - path: string, - sessionId?: string + target: TerminalTarget, + path: string ): Promise => { - const url = `${baseUrl.replace(/\/$/, '')}/files/read?path=${encodeURIComponent(path)}`; - const headers: Record = bearerHeaders(apiKey); - if (sessionId) headers['X-Session-Id'] = sessionId; + const url = `${target.baseUrl.replace(/\/$/, '')}/files/read?path=${encodeURIComponent(path)}`; + const headers: Record = terminalHeaders(target); + const res = await fetch(url, { headers }).catch((err) => { console.error('open-terminal readFile error:', err); return null; @@ -477,38 +468,30 @@ export const readFile = async ( }; export const listTerminalSkills = async ( - connection: TerminalConnection | null, - chatId?: string | null + target: TerminalTarget | null ): Promise => { - if (!connection) return []; + if (!target) return []; - const skills = await terminalRequest( - connection, - chatId ?? null, - '/skills' - ).catch(() => []); + const skills = await terminalRequest(target, '/skills').catch(() => []); return (Array.isArray(skills) ? skills : []).map((skill) => ({ ...skill, is_active: true, source: 'terminal', terminal_path: skill.terminal_path ?? (skill as any).location ?? '', - terminal_scope: skill.terminal_scope ?? (skill as any).scope ?? 'global', - terminal_selector: connection.selector, - terminal_name: connection.selector + terminal_selector: target.selector, + terminal_name: target.selector })); }; export const downloadFileBlob = async ( - baseUrl: string, - apiKey: string, + target: TerminalTarget, path: string, - sessionId?: string, signal?: AbortSignal ): Promise<{ blob: Blob; filename: string } | null> => { - const url = `${baseUrl.replace(/\/$/, '')}/files/view?path=${encodeURIComponent(path)}`; - const headers: Record = bearerHeaders(apiKey); - if (sessionId) headers['X-Session-Id'] = sessionId; + const url = `${target.baseUrl.replace(/\/$/, '')}/files/view?path=${encodeURIComponent(path)}`; + const headers: Record = terminalHeaders(target); + const res = await fetch(url, { headers, signal }).catch(() => null); if (!res || !res.ok) return null; @@ -520,15 +503,13 @@ export const downloadFileBlob = async ( }; export const downloadFilePreview = async ( - baseUrl: string, - apiKey: string, + target: TerminalTarget, path: string, - sessionId?: string, signal?: AbortSignal ): Promise<{ blob: Blob; filename: string } | null> => { - const url = `${baseUrl.replace(/\/$/, '')}/files/view?path=${encodeURIComponent(path)}&preview=true`; - const headers: Record = bearerHeaders(apiKey); - if (sessionId) headers['X-Session-Id'] = sessionId; + const url = `${target.baseUrl.replace(/\/$/, '')}/files/view?path=${encodeURIComponent(path)}&preview=true`; + const headers: Record = terminalHeaders(target); + const res = await fetch(url, { headers, signal }).catch(() => null); if (!res) return null; @@ -544,17 +525,15 @@ export const downloadFilePreview = async ( }; export const archiveFromTerminal = async ( - baseUrl: string, - apiKey: string, - paths: string[], - sessionId?: string + target: TerminalTarget, + paths: string[] ): Promise<{ blob: Blob; filename: string } | null> => { - const url = `${baseUrl.replace(/\/$/, '')}/files/archive`; + const url = `${target.baseUrl.replace(/\/$/, '')}/files/archive`; const headers: Record = { - ...bearerHeaders(apiKey), + ...terminalHeaders(target), 'Content-Type': 'application/json' }; - if (sessionId) headers['X-Session-Id'] = sessionId; + const res = await fetch(url, { method: 'POST', headers, @@ -572,17 +551,15 @@ export const archiveFromTerminal = async ( }; export const uploadToTerminal = async ( - baseUrl: string, - apiKey: string, + target: TerminalTarget, directory: string, - file: File, - sessionId?: string + file: File ): Promise<{ path: string; size: number } | null> => { - const url = `${baseUrl.replace(/\/$/, '')}/files/upload?directory=${encodeURIComponent(directory)}`; + const url = `${target.baseUrl.replace(/\/$/, '')}/files/upload?directory=${encodeURIComponent(directory)}`; const body = new FormData(); body.append('file', file); - const headers: Record = bearerHeaders(apiKey); - if (sessionId) headers['X-Session-Id'] = sessionId; + const headers: Record = terminalHeaders(target); + const res = await fetch(url, { method: 'POST', headers, @@ -603,14 +580,12 @@ export const uploadToTerminal = async ( let newFileUploadQueue: Promise = Promise.resolve(); export const uploadNewFileToTerminal = async ( - baseUrl: string, - apiKey: string, + target: TerminalTarget, directory: string, - file: File, - sessionId?: string + file: File ): Promise<{ path: string; size: number } | null> => { const upload = newFileUploadQueue.then(async () => { - const listing = await listFiles(baseUrl, apiKey, directory, sessionId); + const listing = await listFiles(target, directory); if (!listing) return null; const names = new Set(listing.entries.map((entry) => entry.name)); @@ -626,7 +601,7 @@ export const uploadNewFileToTerminal = async ( name === file.name ? file : new File([file], name, { type: file.type, lastModified: file.lastModified }); - return uploadToTerminal(baseUrl, apiKey, directory, uploadFile, sessionId); + return uploadToTerminal(target, directory, uploadFile); }); newFileUploadQueue = upload.then( () => undefined, @@ -636,17 +611,15 @@ export const uploadNewFileToTerminal = async ( }; export const createDirectory = async ( - baseUrl: string, - apiKey: string, - path: string, - sessionId?: string + target: TerminalTarget, + path: string ): Promise<{ path: string } | null> => { - const url = `${baseUrl.replace(/\/$/, '')}/files/mkdir`; + const url = `${target.baseUrl.replace(/\/$/, '')}/files/mkdir`; const headers: Record = { - ...bearerHeaders(apiKey), + ...terminalHeaders(target), 'Content-Type': 'application/json' }; - if (sessionId) headers['X-Session-Id'] = sessionId; + const res = await fetch(url, { method: 'POST', headers, @@ -664,14 +637,12 @@ export const createDirectory = async ( }; export const deleteEntry = async ( - baseUrl: string, - apiKey: string, - path: string, - sessionId?: string + target: TerminalTarget, + path: string ): Promise<{ path: string; type: string } | null> => { - const url = `${baseUrl.replace(/\/$/, '')}/files/delete?path=${encodeURIComponent(path)}`; - const headers: Record = bearerHeaders(apiKey); - if (sessionId) headers['X-Session-Id'] = sessionId; + const url = `${target.baseUrl.replace(/\/$/, '')}/files/delete?path=${encodeURIComponent(path)}`; + const headers: Record = terminalHeaders(target); + const res = await fetch(url, { method: 'DELETE', headers @@ -688,17 +659,15 @@ export const deleteEntry = async ( }; export const setCwd = async ( - baseUrl: string, - apiKey: string, - path: string, - sessionId?: string + target: TerminalTarget, + path: string ): Promise<{ cwd: string } | null> => { - const url = `${baseUrl.replace(/\/$/, '')}/files/cwd`; + const url = `${target.baseUrl.replace(/\/$/, '')}/files/cwd`; const headers: Record = { - ...bearerHeaders(apiKey), + ...terminalHeaders(target), 'Content-Type': 'application/json' }; - if (sessionId) headers['X-Session-Id'] = sessionId; + const res = await fetch(url, { method: 'POST', headers, @@ -716,18 +685,16 @@ export const setCwd = async ( }; export const moveEntry = async ( - baseUrl: string, - apiKey: string, + target: TerminalTarget, source: string, - destination: string, - sessionId?: string + destination: string ): Promise<{ source: string; destination: string } | { error: string }> => { - const url = `${baseUrl.replace(/\/$/, '')}/files/move`; + const url = `${target.baseUrl.replace(/\/$/, '')}/files/move`; const headers: Record = { - ...bearerHeaders(apiKey), + ...terminalHeaders(target), 'Content-Type': 'application/json' }; - if (sessionId) headers['X-Session-Id'] = sessionId; + const res = await fetch(url, { method: 'POST', headers, @@ -745,15 +712,12 @@ export const moveEntry = async ( }; export const getListeningPorts = async ( - baseUrl: string, - apiKey: string, - sessionId?: string | null + target: TerminalTarget ): Promise => { - const url = `${baseUrl.replace(/\/$/, '')}/ports`; + const url = `${target.baseUrl.replace(/\/$/, '')}/ports`; const res = await fetch(url, { headers: { - ...bearerHeaders(apiKey), - ...(sessionId ? { 'X-Session-Id': sessionId } : {}) + ...terminalHeaders(target) } }).catch(() => null); if (!res || !res.ok) return []; @@ -769,15 +733,14 @@ export const getPortProxyUrl = (baseUrl: string, port: number, path: string = '' // Notebook execution export const createNotebookSession = async ( - baseUrl: string, - apiKey: string, + target: TerminalTarget, path: string ): Promise<{ id: string; kernel: string; status: string } | { error: string }> => { - const url = `${baseUrl.replace(/\/$/, '')}/notebooks`; + const url = `${target.baseUrl.replace(/\/$/, '')}/notebooks`; const res = await fetch(url, { method: 'POST', headers: { - ...bearerHeaders(apiKey), + ...terminalHeaders(target), 'Content-Type': 'application/json' }, body: JSON.stringify({ path }) @@ -797,20 +760,19 @@ export const createNotebookSession = async ( }; export const executeNotebookCell = async ( - baseUrl: string, - apiKey: string, + target: TerminalTarget, sessionId: string, cellIndex: number, source?: string ): Promise<{ status: string; execution_count?: number; outputs: any[] } | { error: string }> => { - const url = `${baseUrl.replace(/\/$/, '')}/notebooks/${sessionId}/execute`; + const url = `${target.baseUrl.replace(/\/$/, '')}/notebooks/${sessionId}/execute`; const body: Record = { cell_index: cellIndex }; if (source !== undefined) body.source = source; const res = await fetch(url, { method: 'POST', headers: { - ...bearerHeaders(apiKey), + ...terminalHeaders(target), 'Content-Type': 'application/json' }, body: JSON.stringify(body) @@ -830,14 +792,13 @@ export const executeNotebookCell = async ( }; export const stopNotebookSession = async ( - baseUrl: string, - apiKey: string, + target: TerminalTarget, sessionId: string ): Promise => { - const url = `${baseUrl.replace(/\/$/, '')}/notebooks/${sessionId}`; + const url = `${target.baseUrl.replace(/\/$/, '')}/notebooks/${sessionId}`; const res = await fetch(url, { method: 'DELETE', - headers: bearerHeaders(apiKey) + headers: { ...terminalHeaders(target) } }).catch(() => null); return res?.ok ?? false; }; @@ -864,19 +825,16 @@ export type TerminalComparison = { }; export const compareFiles = async ( - baseUrl: string, - apiKey: string, + target: TerminalTarget, request: TerminalComparisonRequest, - sessionId?: string, signal?: AbortSignal ): Promise => { - const response = await fetch(`${baseUrl.replace(/\/$/, '')}/files/compare`, { + const response = await fetch(`${target.baseUrl.replace(/\/$/, '')}/files/compare`, { method: 'POST', signal, headers: { - ...bearerHeaders(apiKey), - 'Content-Type': 'application/json', - ...(sessionId ? { 'X-Session-Id': sessionId } : {}) + ...terminalHeaders(target), + 'Content-Type': 'application/json' }, body: JSON.stringify(request) }); @@ -897,3 +855,18 @@ export const compareFiles = async ( ); return body; }; + +export async function templatesApi(path = '', method = 'GET', body?: unknown) { + const response = await fetch(`${WEBUI_API_BASE_URL}/terminals/templates${path}`, { + method, + headers: { + Authorization: `Bearer ${localStorage.token}`, + ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}) + }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}) + }); + const data = await response.json().catch(() => null); + if (!response.ok) + throw new Error(typeof data?.detail === 'string' ? data.detail : 'Terminal request failed'); + return data; +} diff --git a/src/lib/apis/terminal/recentFolders.ts b/src/lib/apis/terminal/recentFolders.ts index c41ce8250a..09e8a088a1 100644 --- a/src/lib/apis/terminal/recentFolders.ts +++ b/src/lib/apis/terminal/recentFolders.ts @@ -2,7 +2,7 @@ import { joinTerminalPath, terminalRequest, TerminalRequestError, - type TerminalConnection, + type TerminalTarget, type TerminalFileList } from './index'; import { computeFileHash } from '$lib/utils/hash'; @@ -14,8 +14,7 @@ const historyDirectory = (home: string, userId: string) => { }; export async function loadRecentFolders( - connection: TerminalConnection, - chatId: string | null, + target: TerminalTarget, home: string, userId: string ): Promise { @@ -23,8 +22,7 @@ export async function loadRecentFolders( let listing: TerminalFileList; try { listing = await terminalRequest( - connection, - chatId, + target, `/files/list?directory=${encodeURIComponent(directory)}` ); } catch (error) { @@ -39,8 +37,7 @@ export async function loadRecentFolders( entries.map(async (entry) => { try { const result = await terminalRequest<{ content: string }>( - connection, - chatId, + target, `/files/read?path=${encodeURIComponent(joinTerminalPath(directory, entry.name))}` ); const record = JSON.parse(result.content); @@ -60,8 +57,7 @@ export async function loadRecentFolders( } export async function rememberRecentFolder( - connection: TerminalConnection, - chatId: string | null, + target: TerminalTarget, home: string, userId: string, path: string @@ -70,7 +66,7 @@ export async function rememberRecentFolder( const normalized = path.replace(/\/+$/, '') || '/'; const hash = await computeFileHash(new File([normalized], 'folder')); // Separate records preserve simultaneous selections in different browsers. - await terminalRequest(connection, chatId, '/files/write', { + await terminalRequest(target, '/files/write', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ diff --git a/src/lib/apis/terminal/socket.ts b/src/lib/apis/terminal/socket.ts index c699339bf3..56b554ef63 100644 --- a/src/lib/apis/terminal/socket.ts +++ b/src/lib/apis/terminal/socket.ts @@ -1,4 +1,4 @@ -import type { TerminalConnection } from './index'; +import type { TerminalTarget } from './index'; export function assignTerminalChat(socket: WebSocket, chatId: string): Promise { return new Promise((resolve, reject) => { @@ -36,13 +36,12 @@ export function assignTerminalChat(socket: WebSocket, chatId: string): Promise void, resume?: { resume: true; cursor: number; flow_control?: true } ) { - const url = new URL(`${connection.baseUrl.replace(/\/$/, '')}${path}`, location.href); + const url = new URL(`${target.baseUrl.replace(/\/$/, '')}${path}`, location.href); url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'; const socket = new WebSocket(url); socket.binaryType = 'arraybuffer'; @@ -51,8 +50,9 @@ export function openTerminalSocket( JSON.stringify({ ...resume, type: 'auth', - token: connection.key.trim(), - chat_id: chatId ?? '' + ...(target.context.modelId ? { model_id: target.context.modelId } : {}), + token: target.key.trim(), + chat_id: target.context.chatId ?? '' }) ); onOpen?.(socket); @@ -62,8 +62,7 @@ export function openTerminalSocket( // Streams use the same response bodies as their HTTP endpoints. export function readTerminalStream( - connection: TerminalConnection, - chatId: string | null, + target: TerminalTarget, path: () => string, onData: (data: T) => void | Promise, onError: (message: string) => void, @@ -79,7 +78,7 @@ export function readTerminalStream( // Apply all received output before constructing the reconnect cursor. await pending; if (stopped) return; - socket = openTerminalSocket(connection, chatId, path()); + socket = openTerminalSocket(target, path()); socket.onmessage = (event) => { pending = pending .then(async () => { diff --git a/src/lib/components/AddTerminalServerModal.svelte b/src/lib/components/AddTerminalServerModal.svelte index a578e1e99c..8bf9053e96 100644 --- a/src/lib/components/AddTerminalServerModal.svelte +++ b/src/lib/components/AddTerminalServerModal.svelte @@ -1,1136 +1,237 @@ -
-
-

- {#if edit} - {$i18n.t('Edit Terminal Connection')} - {:else} - {$i18n.t('Add Terminal Connection')} - {/if} -

- +
+
+

+ {$i18n.t(edit ? 'Edit Terminal Connection' : 'Add Terminal Connection')} +

- -
- -
-
- -
-
-
-
- -
- -
- -
-
- {#if !direct} -
-
- -
-
- -
-
- {/if} -
- -
-
-
- -
- -
- -
-
- - - - -
- -
-
-
- -
-
- -
-
-
- - - {#if serverType === 'orchestrator' && !direct} - - - {#if showOrchestratorAdvanced} -
-
-
-
- {$i18n.t('Terminal Contexts')} -
-
-
- - - - -
-
-
- -
-
-
- -
-
- -
-
-
- {#if loadingPolicy} -
{$i18n.t('Loading policy...')}
- {:else if policyLoadError} -
- {$i18n.t('Failed to load policy: {{error}}', { error: policyLoadError })} -
- {/if} - -
-
-
- -
-
- -
-
-
- -
-
-
- -
-
- -
-
-
-
- -
-
- -
-
-
- -
-
-
- -
-
-
- -
- {#if policyStorage === 'persistent'} -
- -
- {/if} -
-
- -
-
- -
-
- -
-
-
- - -
-
-
-
- {$i18n.t('Environment Variables')} -
- -
- {#each policyEnvPairs as pair, idx} -
- - - -
- {/each} -
-
- -
-
-
- -
- -
-
- -
-
- - -
-
- {$i18n.t( - 'Policy changes apply to newly provisioned terminals. Refresh matching terminals to apply them to existing terminals.' - )} -
- -
- {/if} - {/if} - -
- - - {#if !direct} - { - showAccessControlModal = true; - }} - /> - {/if} -
- - {#if showAdvanced} - {#if !direct} -
-
- -

- {$i18n.t('Include the current directory in tool instructions.')} -

-
- -
- {/if} -
-
- -

- {#if userShellTools === 'auto'} - {$i18n.t('Include tools only while your shell is connected.')} - {:else} - {$i18n.t('Keep tools listed even while your shell is closed.')} - {/if} -

-
- -
- {#if !direct} -
-
- -

- {$i18n.t('Forward cookies from your Open WebUI request to this server.')} -

-
- -
- {/if} - -
-
-
-
-
- {$i18n.t('OpenAPI Spec')} -
-
-
- -
-
-
- - -
-
-
- -
- {$i18n.t(`WebUI will make requests to "{{url}}"`, { - url: path.includes('://') - ? path - : `${url}${path.startsWith('/') ? '' : '/'}${path}` - })} -
-
-
- {/if} - -
-
-
-
- -
-
- -
-
- -
- -
- {#if auth_type === 'bearer' || auth_type === 'session'} -
- - {#if auth_type === 'session'} -
- {$i18n.t('Forwards system user session credentials to authenticate')} -
- {/if} -
- {:else if auth_type === 'none'} -
- {$i18n.t('No authentication')} -
- {:else if auth_type === 'system_oauth'} -
- {$i18n.t('Forwards system user OAuth access token to authenticate')} -
- {/if} -
-
-
-
- -
-
- {#if edit} - - {/if} -
- - -
-
- -
+ {#if error}{/if} + + + + +
+ {#if serverType}{serverType === 'orchestrator' ? 'Terminals' : 'Open Terminal'}{/if}
-
+ {#if serverType === 'orchestrator'}

+ {$i18n.t('Create and configure terminals from the terminal selector.')} +

{/if} + {#if !direct}
+ {}} /> +
{/if} +
+ + + {#if !direct}{/if} + + + +
+
+ {#if edit}{:else}{/if} +
+ - - - { onDelete(); diff --git a/src/lib/components/AutomationModal.svelte b/src/lib/components/AutomationModal.svelte index 4fb25693ef..4be3ed649e 100644 --- a/src/lib/components/AutomationModal.svelte +++ b/src/lib/components/AutomationModal.svelte @@ -155,9 +155,7 @@ const init = async () => { initialized = false; await tick(); - terminalServers = (await getTerminalServers(localStorage.token)).filter( - (server) => server.contexts?.automation !== false - ); + terminalServers = await getTerminalServers(localStorage.token); if (!foldersLoaded && ($folders ?? []).length === 0) { const res = await getFolders(localStorage.token).catch(() => null); if (res) folders.set(res); diff --git a/src/lib/components/admin/Settings/Integrations.svelte b/src/lib/components/admin/Settings/Integrations.svelte index 898f59d9a2..e0c4f888f2 100644 --- a/src/lib/components/admin/Settings/Integrations.svelte +++ b/src/lib/components/admin/Settings/Integrations.svelte @@ -106,11 +106,10 @@ ); const systemTerminals = await getTerminalServers(localStorage.token); const systemEntries = systemTerminals.map((t) => ({ - id: t.id, + ...t, url: `${WEBUI_API_BASE_URL}/terminals/${t.id}`, name: t.name, key: localStorage.token, - contexts: t.contexts ?? {}, config: t.config ?? {} })); terminalServers.set([...existingDirectTerminals, ...systemEntries] as any); @@ -332,7 +331,7 @@
{$i18n.t( - 'Connect to Open Terminal instances. Admins and users granted access can use file browsing and terminal tools through these servers.' + 'Connect to Open Terminal servers. Admins and users granted access can use file browsing and terminal tools through these servers.' )}
{ return ( $config?.features?.enable_tool_servers === true && - (($terminalServers ?? []).some((t) => t.id && t.id === tid) || + (($terminalServers ?? []).some((t) => (!!tid && t.id === tid)) || ($settings?.terminalServers ?? []).some((s) => s.url === tid)) ); }; - $: if ( - $terminalServers !== null && - $selectedTerminalId && - !isTerminalAvailable($selectedTerminalId) - ) { - selectedTerminalId.set(null); - } $: if ( $temporaryChatEnabled && ($terminalServers ?? []).some( - (t) => t.id && t.id === $selectedTerminalId && t.contexts?.chat?.context_id === 'chat_id' + (t) => (!!$selectedTerminalId && t.id === $selectedTerminalId) && t.scope === 'chat' ) ) { selectedTerminalId.set(null); @@ -1133,12 +1126,10 @@ } const applyFolderTerminal = (folder: any) => { - if (!folder) return; - const terminalId = folder.data?.terminal_id || null; + const terminalId = folder?.data?.terminal_id; + if (!terminalId) return; selectedTerminalId.set(terminalId); - terminalContext = terminalId - ? { terminalId, currentDirectory: folder.data?.working_directory ?? '' } - : null; + terminalContext = { terminalId, currentDirectory: folder.data?.working_directory ?? '' }; }; let defaultsModelIds: string[] = []; @@ -2835,7 +2826,7 @@ ); } else { if ($selectedFolder) { - // Folder defaults are explicit; never inherit a previous chat's selection. + // A configured folder terminal overrides the previous selection. applyFolderTerminal($selectedFolder); if ($selectedFolder.data?.terminal_id) { await refreshAgentModels(); @@ -4027,14 +4018,13 @@ if (initializedTerminalChatId === id) return; if (!$config?.features?.enable_tool_servers || !context?.currentDirectory) return; const userSettings: any = $settings; - const connection = resolveTerminalConnection( + const target = resolveTerminalTarget( context.terminalId, $terminalServers ?? [], $config?.features?.enable_direct_integrations ? (userSettings?.terminalServers ?? []) : [], - localStorage.token - ); - if (!connection) throw new Error($i18n.t('Terminal Not Found')); - const result = await setCwd(connection.baseUrl, connection.key, context.currentDirectory, id); + localStorage.token, { chatId: id, modelId: selectedModels[0] ?? null }); + if (!target) throw new Error($i18n.t('Terminal Not Found')); + const result = await setCwd(target, context.currentDirectory); if (!result?.cwd) throw new Error( $i18n.t('Working directory is unavailable. Check the terminal connection and path.') diff --git a/src/lib/components/chat/FileNav.svelte b/src/lib/components/chat/FileNav.svelte index 3c4421fcc4..07412c8e4f 100644 --- a/src/lib/components/chat/FileNav.svelte +++ b/src/lib/components/chat/FileNav.svelte @@ -1,6 +1,9 @@ + + +
+
+
+ {#if editing || sharing} + + {/if} +

+ {editing + ? $i18n.t(editing.id ? 'Configure terminal' : 'New terminal') + : sharing + ? `${$i18n.t('Share')} ${sharing.name}` + : $i18n.t('Terminals')} +

+
+ +
+
+ {#if error}{/if} + {#if editing} +
+
+ + +
+
+ {#if !editing.id} +
+ + {#each connections as c}{/each} +
+ {/if} +
+
+ + +
+

+ {$i18n.t( + scope === 'none' + ? 'Everyone with access shares this terminal.' + : scope === 'user' + ? 'Each user gets their own terminal.' + : scope === 'chat' + ? 'Each chat gets a terminal shared by its participants.' + : 'Each model gets a terminal shared across authorized users and chats.' + )} +

+
+
+
+
+ +
+
+
+ +
+
+ +
+
+
+
+ +
+

+ {$i18n.t('Environment variables, storage, networking, and security settings.')} +

+