mirror of
https://github.com/open-webui/open-webui.git
synced 2026-11-22 21:50:42 -05:00
refac
This commit is contained in:
1 parent
b01fe7fae2
commit
6f2fc7bc7a
66 files changed
+2206
-2737
No files matched your search
@@ -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
|
||||
|
||||
@@ -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)):
|
||||
"""
|
||||
|
||||
@@ -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)
|
||||
@@ -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')}
|
||||
@@ -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')
|
||||
|
||||
@@ -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 = [
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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'),
|
||||
)
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<object | null> => {
|
||||
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<any> => {
|
||||
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<object | null> => {
|
||||
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<any> => {
|
||||
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<object | null> => {
|
||||
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.
|
||||
|
||||
@@ -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<BrowserSession>(
|
||||
connection,
|
||||
chatId,
|
||||
`/browser/sessions/${encodeURIComponent(id)}`
|
||||
);
|
||||
export const getBrowserSession = (target: TerminalTarget, id: string) =>
|
||||
terminalRequest<BrowserSession>(target, `/browser/sessions/${encodeURIComponent(id)}`);
|
||||
|
||||
export const createBrowserSession = async (
|
||||
connection: TerminalConnection,
|
||||
chatId: string | null,
|
||||
url = ''
|
||||
) => {
|
||||
const session = await terminalRequest<BrowserSession>(connection, chatId, '/browser/sessions', {
|
||||
export const createBrowserSession = async (target: TerminalTarget, url = '') => {
|
||||
const session = await terminalRequest<BrowserSession>(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<Pick<BrowserSession, 'url' | 'title' | 'mode'>> & {
|
||||
active?: boolean;
|
||||
chat_id?: string;
|
||||
}
|
||||
) =>
|
||||
terminalRequest<BrowserSession>(
|
||||
connection,
|
||||
chatId,
|
||||
`/browser/sessions/${encodeURIComponent(id)}`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(fields)
|
||||
}
|
||||
);
|
||||
terminalRequest<BrowserSession>(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);
|
||||
|
||||
@@ -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<typeof setTimeout>;
|
||||
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);
|
||||
|
||||
@@ -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<T>(
|
||||
connection: TerminalConnection,
|
||||
chatId: string | null,
|
||||
target: TerminalTarget,
|
||||
directory: string,
|
||||
operation: string,
|
||||
params: Record<string, string> = {},
|
||||
@@ -64,11 +64,10 @@ export async function gitRequest<T>(
|
||||
): Promise<T> {
|
||||
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<T>(
|
||||
}
|
||||
|
||||
export function gitAction<T>(
|
||||
connection: TerminalConnection,
|
||||
chatId: string | null,
|
||||
target: TerminalTarget,
|
||||
directory: string,
|
||||
action: string,
|
||||
fields: Record<string, unknown>
|
||||
@@ -121,7 +119,7 @@ export function gitAction<T>(
|
||||
method = 'DELETE';
|
||||
body = { name: fields.branch };
|
||||
}
|
||||
return gitRequest<T>(connection, chatId, directory, operation, {}, body, method);
|
||||
return gitRequest<T>(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<TerminalConnection, 'baseUrl' | 'key'>,
|
||||
chatId: string | null,
|
||||
target: Pick<TerminalTarget, 'baseUrl' | 'key' | 'context'>,
|
||||
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<TerminalProcessOutput>(
|
||||
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<TerminalProcessOutput>(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<TerminalProcessOutput>(
|
||||
connection,
|
||||
chatId,
|
||||
target,
|
||||
`/execute/${encodeURIComponent(result.id)}/status?wait=1&tail=20`,
|
||||
{ signal }
|
||||
);
|
||||
|
||||
+142
-169
@@ -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<TerminalConnection, 'baseUrl' | 'key'>,
|
||||
chatId: string | null,
|
||||
target: Pick<TerminalTarget, 'baseUrl' | 'key' | 'context'>,
|
||||
signal?: AbortSignal
|
||||
): Promise<TerminalFeatures> {
|
||||
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['context']> = {}
|
||||
): 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 <T>(
|
||||
connection: Pick<TerminalConnection, 'baseUrl' | 'key'>,
|
||||
chatId: string | null,
|
||||
target: Pick<TerminalTarget, 'baseUrl' | 'key' | 'context'>,
|
||||
path: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<T> => {
|
||||
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 <T>(
|
||||
return response.json();
|
||||
};
|
||||
|
||||
const bearerHeaders = (apiKey: string): Record<string, string> => {
|
||||
export const terminalHeaders = (
|
||||
target: Pick<TerminalTarget, 'key' | 'context'>
|
||||
): Record<string, string> => {
|
||||
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<string, false | { context_id?: string }>;
|
||||
config?: {
|
||||
chat_uploads?: 'default' | 'filesystem';
|
||||
[key: string]: unknown;
|
||||
@@ -279,26 +295,10 @@ export const getTerminalServers = async (token: string): Promise<TerminalServer[
|
||||
return res.json().catch(() => []);
|
||||
};
|
||||
|
||||
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<TerminalCwd | null> => {
|
||||
const url = `${target.baseUrl.replace(/\/$/, '')}/files/cwd`;
|
||||
const headers: Record<string, string> = terminalHeaders(target);
|
||||
|
||||
export const getCwd = async (
|
||||
baseUrl: string,
|
||||
apiKey: string,
|
||||
sessionId?: string
|
||||
): Promise<TerminalCwd | null> => {
|
||||
const url = `${baseUrl.replace(/\/$/, '')}/files/cwd`;
|
||||
const headers: Record<string, string> = 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<TerminalFileList | null> => {
|
||||
// The endpoint uses `directory` as the query param name
|
||||
const url = `${baseUrl.replace(/\/$/, '')}/files/list?directory=${encodeURIComponent(path)}`;
|
||||
const headers: Record<string, string> = bearerHeaders(apiKey);
|
||||
if (sessionId) headers['X-Session-Id'] = sessionId;
|
||||
const url = `${target.baseUrl.replace(/\/$/, '')}/files/list?directory=${encodeURIComponent(path)}`;
|
||||
const headers: Record<string, string> = 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<TerminalFileSearchResponse | null> => {
|
||||
const headers: Record<string, string> = bearerHeaders(apiKey);
|
||||
if (sessionId) headers['X-Session-Id'] = sessionId;
|
||||
const headers: Record<string, string> = 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<TerminalFileMatchesResponse | null> => {
|
||||
const headers: Record<string, string> = bearerHeaders(apiKey);
|
||||
if (sessionId) headers['X-Session-Id'] = sessionId;
|
||||
const headers: Record<string, string> = 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<string> => {
|
||||
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<string | null> => {
|
||||
const url = `${baseUrl.replace(/\/$/, '')}/files/read?path=${encodeURIComponent(path)}`;
|
||||
const headers: Record<string, string> = bearerHeaders(apiKey);
|
||||
if (sessionId) headers['X-Session-Id'] = sessionId;
|
||||
const url = `${target.baseUrl.replace(/\/$/, '')}/files/read?path=${encodeURIComponent(path)}`;
|
||||
const headers: Record<string, string> = 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<TerminalSkill[]> => {
|
||||
if (!connection) return [];
|
||||
if (!target) return [];
|
||||
|
||||
const skills = await terminalRequest<TerminalSkill[]>(
|
||||
connection,
|
||||
chatId ?? null,
|
||||
'/skills'
|
||||
).catch(() => []);
|
||||
const skills = await terminalRequest<TerminalSkill[]>(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<string, string> = bearerHeaders(apiKey);
|
||||
if (sessionId) headers['X-Session-Id'] = sessionId;
|
||||
const url = `${target.baseUrl.replace(/\/$/, '')}/files/view?path=${encodeURIComponent(path)}`;
|
||||
const headers: Record<string, string> = 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<string, string> = bearerHeaders(apiKey);
|
||||
if (sessionId) headers['X-Session-Id'] = sessionId;
|
||||
const url = `${target.baseUrl.replace(/\/$/, '')}/files/view?path=${encodeURIComponent(path)}&preview=true`;
|
||||
const headers: Record<string, string> = 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<string, string> = {
|
||||
...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<string, string> = bearerHeaders(apiKey);
|
||||
if (sessionId) headers['X-Session-Id'] = sessionId;
|
||||
const headers: Record<string, string> = terminalHeaders(target);
|
||||
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
@@ -603,14 +580,12 @@ export const uploadToTerminal = async (
|
||||
let newFileUploadQueue: Promise<void> = 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<string, string> = {
|
||||
...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<string, string> = bearerHeaders(apiKey);
|
||||
if (sessionId) headers['X-Session-Id'] = sessionId;
|
||||
const url = `${target.baseUrl.replace(/\/$/, '')}/files/delete?path=${encodeURIComponent(path)}`;
|
||||
const headers: Record<string, string> = 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<string, string> = {
|
||||
...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<string, string> = {
|
||||
...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<ListeningPort[]> => {
|
||||
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<string, any> = { 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<boolean> => {
|
||||
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<TerminalComparison> => {
|
||||
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;
|
||||
}
|
||||
@@ -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<string[]> {
|
||||
@@ -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({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { TerminalConnection } from './index';
|
||||
import type { TerminalTarget } from './index';
|
||||
|
||||
export function assignTerminalChat(socket: WebSocket, chatId: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -36,13 +36,12 @@ export function assignTerminalChat(socket: WebSocket, chatId: string): Promise<v
|
||||
}
|
||||
|
||||
export function openTerminalSocket(
|
||||
connection: TerminalConnection,
|
||||
chatId: string | null,
|
||||
target: TerminalTarget,
|
||||
path: string,
|
||||
onOpen?: (socket: WebSocket) => 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<T>(
|
||||
connection: TerminalConnection,
|
||||
chatId: string | null,
|
||||
target: TerminalTarget,
|
||||
path: () => string,
|
||||
onData: (data: T) => void | Promise<void>,
|
||||
onError: (message: string) => void,
|
||||
@@ -79,7 +78,7 @@ export function readTerminalStream<T>(
|
||||
// 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 () => {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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);
|
||||
|
||||
@@ -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 @@
|
||||
|
||||
<div class="mt-1 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{$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.'
|
||||
)}
|
||||
</div>
|
||||
<a
|
||||
|
||||
@@ -109,7 +109,7 @@
|
||||
updateChatParams,
|
||||
updateChatFolderIdById
|
||||
} from '$lib/apis/chats';
|
||||
import { resolveTerminalConnection, setCwd, type FilesystemFile } from '$lib/apis/terminal';
|
||||
import { resolveTerminalTarget, setCwd, type FilesystemFile } from '$lib/apis/terminal';
|
||||
import { generateOpenAIChatCompletion, getErrorMessage } from '$lib/apis/openai';
|
||||
import { processUrl, processWebSearch } from '$lib/apis/retrieval';
|
||||
import {
|
||||
@@ -1071,23 +1071,16 @@
|
||||
const isTerminalAvailable = (tid: string): boolean => {
|
||||
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.')
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<script lang="ts">
|
||||
export let modelId: string | null = null;
|
||||
export let target: TerminalTarget | null | undefined = undefined;
|
||||
import { resolveTerminalTarget } from '$lib/apis/terminal';
|
||||
import type { TerminalContext } from '$lib/types';
|
||||
import type { TerminalConnection } from '$lib/apis/terminal';
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
import { gitRequest, type GitStatus, type GitFile } from '$lib/apis/terminal/git';
|
||||
import { reverseGitDiff } from './Messages/diff';
|
||||
import FileGitDiff from './FileNav/FileGitDiff.svelte';
|
||||
@@ -124,7 +127,7 @@
|
||||
export let overlay = false;
|
||||
export let active = true;
|
||||
export let gitStatus: GitStatus | null = null;
|
||||
export let gitConnection: TerminalConnection | null = null;
|
||||
export let gitTarget: TerminalTarget | null = null;
|
||||
export let gitDiffMode: 'unified' | 'split' = 'unified';
|
||||
export let gitHideWhitespace = false;
|
||||
export let terminalId: string | null = null;
|
||||
@@ -135,7 +138,7 @@
|
||||
let gitAvailable = false;
|
||||
let cloneSupportVersion = 0;
|
||||
async function checkCloneSupport(
|
||||
terminal: { url: string; key: string } | null,
|
||||
terminal: TerminalTarget | null,
|
||||
session: string | null,
|
||||
enabled: boolean
|
||||
) {
|
||||
@@ -143,10 +146,7 @@
|
||||
gitAvailable = false;
|
||||
showCloneRepository = false;
|
||||
if (!terminal || !enabled) return;
|
||||
const features = await getTerminalFeatures(
|
||||
{ baseUrl: terminal.url, key: terminal.key },
|
||||
session
|
||||
);
|
||||
const features = await getTerminalFeatures(terminal);
|
||||
if (!disposed && version === cloneSupportVersion) gitAvailable = features.git === true;
|
||||
}
|
||||
$: void checkCloneSupport(selectedTerminal, chatId, !!onSelectDirectory);
|
||||
@@ -228,8 +228,7 @@
|
||||
export let dirty = false;
|
||||
let diskChanged = false;
|
||||
let overwriteChoice: ((replace: boolean) => void) | null = null;
|
||||
let saveConnection: { url: string; key: string; chatId: string | null; path: string } | null =
|
||||
null;
|
||||
let saveTarget: (TerminalTarget & { path: string }) | null = null;
|
||||
let dirtyChoice: {
|
||||
sending: boolean;
|
||||
resolve: (confirmed: boolean) => void;
|
||||
@@ -348,7 +347,7 @@
|
||||
// Preserve translations for the former save notifications during extraction.
|
||||
// $i18n.t('File saved'); $i18n.t('Failed to save file');
|
||||
const saveFile = async (content: string) => {
|
||||
const target = saveConnection;
|
||||
const target = saveTarget;
|
||||
if (
|
||||
diskChanged &&
|
||||
!(await new Promise<boolean>((resolve) => {
|
||||
@@ -357,19 +356,24 @@
|
||||
)
|
||||
throw new Error('Save cancelled.');
|
||||
const current = getTerminal();
|
||||
if (!target || !current || current.url !== target.url || !selectedFileWritable)
|
||||
if (
|
||||
!target ||
|
||||
!current ||
|
||||
current.baseUrl !== target.baseUrl ||
|
||||
current.context.modelId !== target.context.modelId ||
|
||||
current.context.chatId !== target.context.chatId ||
|
||||
!selectedFileWritable
|
||||
)
|
||||
throw new Error('File is not writable.');
|
||||
const name = target.path.split('/').pop()!;
|
||||
const dir = target.path.slice(0, target.path.lastIndexOf('/') + 1) || '/';
|
||||
const result = await uploadToTerminal(
|
||||
target.url,
|
||||
current.key,
|
||||
current,
|
||||
dir,
|
||||
new File([content], name, { type: 'text/plain' }),
|
||||
target.chatId ?? undefined
|
||||
new File([content], name, { type: 'text/plain' })
|
||||
);
|
||||
if (!result) throw new Error('Failed to save file. Your changes are still in the editor.');
|
||||
if (saveConnection === target) {
|
||||
if (saveTarget === target) {
|
||||
fileContent = content;
|
||||
diskChanged = false;
|
||||
}
|
||||
@@ -387,7 +391,7 @@
|
||||
let pinnedComparison: ComparisonFile | null = null;
|
||||
let comparison: {
|
||||
files: [ComparisonFile, ComparisonFile];
|
||||
terminal: { url: string; key: string };
|
||||
terminal: TerminalTarget;
|
||||
chatId: string | null;
|
||||
opener: HTMLElement | null;
|
||||
} | null = null;
|
||||
@@ -698,7 +702,7 @@
|
||||
let gitBaseGeneration = 0;
|
||||
let gitBaseKey = '';
|
||||
const loadGitBase = async (
|
||||
connection: TerminalConnection | null,
|
||||
target: TerminalTarget | null,
|
||||
session: string | null,
|
||||
status: GitStatus | null,
|
||||
file: GitFile | null,
|
||||
@@ -708,12 +712,12 @@
|
||||
_version: number
|
||||
) => {
|
||||
const generation = ++gitBaseGeneration;
|
||||
const key = JSON.stringify([connection, session, path]);
|
||||
const key = JSON.stringify([target, session, path]);
|
||||
if (key !== gitBaseKey) gitBaseContent = null;
|
||||
gitBaseKey = key;
|
||||
const root = status?.is_repo && status.root ? normalizePath(status.root) : null;
|
||||
if (
|
||||
!connection ||
|
||||
!target ||
|
||||
root === null ||
|
||||
!path ||
|
||||
content === null ||
|
||||
@@ -730,13 +734,13 @@
|
||||
else if (file) {
|
||||
const [unstaged, staged] = await Promise.all([
|
||||
file.unstaged
|
||||
? gitRequest<{ diff: string }>(connection, session, root, 'diff', {
|
||||
? gitRequest<{ diff: string }>(target, root, 'diff', {
|
||||
file: file.path,
|
||||
staged: 'false'
|
||||
})
|
||||
: null,
|
||||
file.staged
|
||||
? gitRequest<{ diff: string }>(connection, session, root, 'diff', {
|
||||
? gitRequest<{ diff: string }>(target, root, 'diff', {
|
||||
file: file.path,
|
||||
staged: 'true'
|
||||
})
|
||||
@@ -752,7 +756,7 @@
|
||||
}
|
||||
};
|
||||
$: void loadGitBase(
|
||||
gitConnection,
|
||||
gitTarget,
|
||||
chatId,
|
||||
gitStatus,
|
||||
currentGitFile,
|
||||
@@ -809,53 +813,45 @@
|
||||
let shiftKey = false;
|
||||
|
||||
// Terminal resolution
|
||||
let selectedTerminal: { url: string; key: string } | null = null;
|
||||
let selectedTerminal: TerminalTarget | null = null;
|
||||
let terminalChatContextPending = false;
|
||||
let terminalChatContextHidden = false;
|
||||
let isPerChatTerminal = false;
|
||||
$: previewBaseUrl =
|
||||
selectedTerminal && isPerChatTerminal && chatId
|
||||
? `${selectedTerminal.url}/chats/${encodeURIComponent(chatId)}`
|
||||
: (selectedTerminal?.url ?? '');
|
||||
|
||||
const chatContext = (terminal: any) => terminal?.contexts?.chat ?? {};
|
||||
|
||||
const getTerminal = (): { url: string; key: string } | null => {
|
||||
const getTerminal = (): TerminalTarget | null => {
|
||||
const systemTerminal = effectiveTerminalId
|
||||
? (($terminalServers ?? []).find((t) => t.id === effectiveTerminalId) ?? null)
|
||||
: ($terminalServers?.[0] ?? null);
|
||||
const chatConfig = chatContext(systemTerminal);
|
||||
isPerChatTerminal = !!systemTerminal && chatConfig?.context_id === 'chat_id';
|
||||
isPerChatTerminal = !!systemTerminal && systemTerminal?.scope === 'chat';
|
||||
terminalChatContextHidden =
|
||||
!!systemTerminal &&
|
||||
(chatConfig === false || (isPerChatTerminal && isTemporaryChatId(chatId)));
|
||||
isPerChatTerminal && isTemporaryChatId(chatId);
|
||||
terminalChatContextPending =
|
||||
isPerChatTerminal && !terminalChatContextHidden && !isSavedChatId(chatId);
|
||||
if (terminalChatContextHidden || terminalChatContextPending) return null;
|
||||
|
||||
const settingsValue: any = $settings;
|
||||
const userTerminal = (settingsValue?.terminalServers ?? []).find(
|
||||
(s: any) => s.url === effectiveTerminalId
|
||||
if (target !== undefined) return target;
|
||||
return resolveTerminalTarget(
|
||||
effectiveTerminalId ?? systemTerminal?.id ?? null,
|
||||
$terminalServers ?? [],
|
||||
($settings as any)?.terminalServers ?? [],
|
||||
localStorage.token,
|
||||
{ chatId: chatId, modelId: modelId }
|
||||
);
|
||||
|
||||
const isSystem = !!systemTerminal;
|
||||
const url = systemTerminal?.url ?? userTerminal?.url ?? '';
|
||||
const key = isSystem ? localStorage.token : (userTerminal?.key ?? '');
|
||||
|
||||
return url ? { url, key } : null;
|
||||
};
|
||||
|
||||
// Detect terminal or chat changes — the explicit store references ensure
|
||||
// Svelte re-runs this block when any of them update.
|
||||
// The `mounted` flag prevents the initial run from racing with onMount.
|
||||
let prevTerminalUrl = '';
|
||||
let prevModelId: string | null | undefined;
|
||||
let prevTerminalId = effectiveTerminalId;
|
||||
let prevChatId = chatId;
|
||||
let prevFolderDirectory: string | null = null;
|
||||
let mounted = false;
|
||||
let disposed = false;
|
||||
$: {
|
||||
(effectiveTerminalId, $terminalServers, $settings);
|
||||
(effectiveTerminalId, target, modelId, $terminalServers, $settings);
|
||||
const terminal = getTerminal();
|
||||
selectedTerminal = terminal;
|
||||
|
||||
@@ -866,9 +862,13 @@
|
||||
prevFolderDirectory = folderDirectory;
|
||||
|
||||
const terminalChanged =
|
||||
terminal && (terminal.url !== prevTerminalUrl || effectiveTerminalId !== prevTerminalId);
|
||||
terminal &&
|
||||
(terminal.baseUrl !== prevTerminalUrl ||
|
||||
terminal.context.modelId !== prevModelId ||
|
||||
effectiveTerminalId !== prevTerminalId);
|
||||
if (terminalChanged) {
|
||||
prevTerminalUrl = terminal.url;
|
||||
prevTerminalUrl = terminal.baseUrl;
|
||||
prevModelId = terminal.context.modelId;
|
||||
prevTerminalId = effectiveTerminalId;
|
||||
}
|
||||
|
||||
@@ -896,7 +896,7 @@
|
||||
entries = [];
|
||||
resetTreeState();
|
||||
(async () => {
|
||||
const cwd = await getCwd(terminal.url, terminal.key, chatId ?? undefined);
|
||||
const cwd = await getCwd(terminal);
|
||||
if (disposed || generation !== loadGeneration) return;
|
||||
const serverPath = applyCwd(cwd);
|
||||
savedPath = folderDirectory || serverPath;
|
||||
@@ -988,7 +988,7 @@
|
||||
|
||||
const queueFileSearch = (
|
||||
query: string,
|
||||
terminal: { url: string; key: string } | null,
|
||||
terminal: TerminalTarget | null,
|
||||
path: string,
|
||||
hiddenVisible: boolean,
|
||||
activeFile: string | null
|
||||
@@ -1015,13 +1015,11 @@
|
||||
matchController = controller;
|
||||
matchTimer = setTimeout(async () => {
|
||||
const data = await getFileMatches(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
terminal,
|
||||
query,
|
||||
path,
|
||||
hiddenVisible,
|
||||
0,
|
||||
chatId ?? undefined,
|
||||
controller.signal
|
||||
);
|
||||
if (requestId !== matchRequestId) return;
|
||||
@@ -1051,13 +1049,11 @@
|
||||
const controller = new AbortController();
|
||||
matchController = controller;
|
||||
const data = await getFileMatches(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
terminal,
|
||||
searchText,
|
||||
currentPath,
|
||||
showHidden,
|
||||
offset,
|
||||
chatId ?? undefined,
|
||||
controller.signal
|
||||
);
|
||||
if (requestId === matchRequestId) {
|
||||
@@ -1201,7 +1197,7 @@
|
||||
}
|
||||
|
||||
openedFile = null;
|
||||
saveConnection = null;
|
||||
saveTarget = null;
|
||||
dirty = false;
|
||||
loading = true;
|
||||
error = null;
|
||||
@@ -1218,7 +1214,7 @@
|
||||
savedPathLoaded = true;
|
||||
pushNavHistory(directory);
|
||||
|
||||
const result = await listFiles(terminal.url, terminal.key, directory, chatId ?? undefined);
|
||||
const result = await listFiles(terminal, directory);
|
||||
if (generation !== loadGeneration || selector !== effectiveTerminalId || session !== chatId)
|
||||
return;
|
||||
loading = false;
|
||||
@@ -1241,7 +1237,7 @@
|
||||
if (!terminal) return null;
|
||||
const directory = asDirectoryPath(path);
|
||||
loadingDirs = new Set(loadingDirs).add(directory);
|
||||
const result = await listFiles(terminal.url, terminal.key, directory, chatId ?? undefined);
|
||||
const result = await listFiles(terminal, directory);
|
||||
const nextLoading = new Set(loadingDirs);
|
||||
nextLoading.delete(directory);
|
||||
loadingDirs = nextLoading;
|
||||
@@ -1340,7 +1336,7 @@
|
||||
if (terminalContext) terminalContext = { ...terminalContext, file: null };
|
||||
dirty = false;
|
||||
diskChanged = false;
|
||||
saveConnection = { ...terminal, path: filePath, chatId: session };
|
||||
saveTarget = { ...terminal, path: filePath };
|
||||
pendingFile = filesystemFile(
|
||||
{ path: filePath, name: entry.name, size: entry.size, modified: entry.modified },
|
||||
selector,
|
||||
@@ -1378,47 +1374,22 @@
|
||||
fileContent: null
|
||||
} as any;
|
||||
if (isImage(filePath)) {
|
||||
const result = await downloadFileBlob(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
filePath,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const result = await downloadFileBlob(terminal, filePath);
|
||||
if (result) next.fileImageUrl = URL.createObjectURL(result.blob);
|
||||
} else if (isVideo(filePath)) {
|
||||
const result = await downloadFileBlob(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
filePath,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const result = await downloadFileBlob(terminal, filePath);
|
||||
if (result) next.fileVideoUrl = URL.createObjectURL(result.blob);
|
||||
} else if (isAudio(filePath)) {
|
||||
const result = await downloadFileBlob(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
filePath,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const result = await downloadFileBlob(terminal, filePath);
|
||||
if (result) next.fileAudioUrl = URL.createObjectURL(result.blob);
|
||||
} else if (isPdf(filePath)) {
|
||||
const result = await downloadFileBlob(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
filePath,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const result = await downloadFileBlob(terminal, filePath);
|
||||
if (result) next.filePdfData = await result.blob.arrayBuffer();
|
||||
} else if (
|
||||
isSqlite(filePath) ||
|
||||
['glb', 'gltf', 'stl', 'obj', 'ply'].includes(getFileExt(filePath))
|
||||
) {
|
||||
const result = await downloadFileBlob(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
filePath,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const result = await downloadFileBlob(terminal, filePath);
|
||||
if (result) {
|
||||
const data = await result.blob.arrayBuffer();
|
||||
if (['glb', 'gltf', 'stl', 'obj', 'ply'].includes(getFileExt(filePath)))
|
||||
@@ -1429,32 +1400,17 @@
|
||||
const ext = getFileExt(filePath);
|
||||
try {
|
||||
if (ext === 'docx') {
|
||||
const preview = await downloadFilePreview(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
filePath,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const preview = await downloadFilePreview(terminal, filePath);
|
||||
if (preview) {
|
||||
next.filePdfData = await preview.blob.arrayBuffer();
|
||||
} else {
|
||||
const result = await downloadFileBlob(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
filePath,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const result = await downloadFileBlob(terminal, filePath);
|
||||
if (!result) throw new Error('Preview failed');
|
||||
const arrayBuffer = await result.blob.arrayBuffer();
|
||||
next.fileDocxData = arrayBuffer;
|
||||
}
|
||||
} else if (ext === 'xlsx') {
|
||||
const result = await downloadFileBlob(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
filePath,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const result = await downloadFileBlob(terminal, filePath);
|
||||
if (result) {
|
||||
const arrayBuffer = await result.blob.arrayBuffer();
|
||||
const { readExcelWorkbook, excelToTable } = await import('$lib/utils/excelToTable');
|
||||
@@ -1469,21 +1425,11 @@
|
||||
}
|
||||
}
|
||||
} else if (ext === 'pptx') {
|
||||
const preview = await downloadFilePreview(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
filePath,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const preview = await downloadFilePreview(terminal, filePath);
|
||||
if (preview) {
|
||||
next.filePdfData = await preview.blob.arrayBuffer();
|
||||
} else {
|
||||
const result = await downloadFileBlob(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
filePath,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const result = await downloadFileBlob(terminal, filePath);
|
||||
if (!result) throw new Error('Preview failed');
|
||||
const arrayBuffer = await result.blob.arrayBuffer();
|
||||
const { pptxToImages } = await import('$lib/utils/pptxToHtml');
|
||||
@@ -1499,7 +1445,7 @@
|
||||
});
|
||||
}
|
||||
} else {
|
||||
next.fileContent = await readFile(terminal.url, terminal.key, filePath, chatId ?? undefined);
|
||||
next.fileContent = await readFile(terminal, filePath);
|
||||
}
|
||||
if (!current()) {
|
||||
[next.fileImageUrl, next.fileVideoUrl, next.fileAudioUrl]
|
||||
@@ -1587,13 +1533,8 @@
|
||||
// Directories end with '/', downloaded as a ZIP archive
|
||||
const isDir = path.endsWith('/');
|
||||
const result = isDir
|
||||
? await archiveFromTerminal(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
[path.replace(/\/$/, '')],
|
||||
chatId ?? undefined
|
||||
)
|
||||
: await downloadFileBlob(terminal.url, terminal.key, path, chatId ?? undefined);
|
||||
? await archiveFromTerminal(terminal, [path.replace(/\/$/, '')])
|
||||
: await downloadFileBlob(terminal, path);
|
||||
if (!result) {
|
||||
toast.error($i18n.t('Download failed'));
|
||||
return;
|
||||
@@ -1610,7 +1551,11 @@
|
||||
}
|
||||
};
|
||||
|
||||
$: dragContext = JSON.stringify([selectedTerminal?.url, chatId ?? null]);
|
||||
$: dragContext = JSON.stringify([
|
||||
selectedTerminal?.baseUrl,
|
||||
selectedTerminal?.context.modelId,
|
||||
chatId ?? null
|
||||
]);
|
||||
|
||||
// Drag-and-drop upload
|
||||
type UploadEntry = { path: string; file?: File };
|
||||
@@ -1699,20 +1644,18 @@
|
||||
const path = `${destination.replace(/\/$/, '')}/${entry.path}`;
|
||||
const result = entry.file
|
||||
? await uploadToTerminal(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
terminal,
|
||||
path.slice(0, path.lastIndexOf('/')) || '/',
|
||||
entry.file,
|
||||
sessionId
|
||||
entry.file
|
||||
)
|
||||
: await createDirectory(terminal.url, terminal.key, path, sessionId);
|
||||
: await createDirectory(terminal, path);
|
||||
if (!result) throw new Error(entry.path);
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(`${$i18n.t('Upload failed')}: ${error instanceof Error ? error.message : error}`);
|
||||
} finally {
|
||||
uploading = false;
|
||||
if (selectedTerminal?.url === terminal.url && (chatId ?? undefined) === sessionId) {
|
||||
if (selectedTerminal?.baseUrl === terminal.baseUrl && (chatId ?? undefined) === sessionId) {
|
||||
invalidateTreeCache(destination);
|
||||
if (currentPath === destination && !selectedFile) await refreshBrowser();
|
||||
}
|
||||
@@ -1751,12 +1694,7 @@
|
||||
const terminal = selectedTerminal;
|
||||
if (!terminal) return;
|
||||
|
||||
const result = await createDirectory(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
`${currentPath}${name}`,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const result = await createDirectory(terminal, `${currentPath}${name}`);
|
||||
toast[result ? 'success' : 'error'](
|
||||
result ? $i18n.t('Folder created') : $i18n.t('Failed to create folder')
|
||||
);
|
||||
@@ -1787,13 +1725,7 @@
|
||||
if (!terminal || !currentWritable) return;
|
||||
|
||||
const emptyFile = new File([''], name, { type: 'application/octet-stream' });
|
||||
const result = await uploadToTerminal(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
currentPath,
|
||||
emptyFile,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const result = await uploadToTerminal(terminal, currentPath, emptyFile);
|
||||
toast[result ? 'success' : 'error'](
|
||||
result ? $i18n.t('File created') : $i18n.t('Failed to create file')
|
||||
);
|
||||
@@ -1806,7 +1738,7 @@
|
||||
const terminal = selectedTerminal;
|
||||
if (!terminal || !currentWritable) return;
|
||||
|
||||
const result = await deleteEntry(terminal.url, terminal.key, path, chatId ?? undefined);
|
||||
const result = await deleteEntry(terminal, path);
|
||||
toast[result ? 'success' : 'error'](
|
||||
result
|
||||
? $i18n.t('{{name}} deleted', { name })
|
||||
@@ -1843,13 +1775,7 @@
|
||||
const sourceDir = asDirectoryPath(cleanSource);
|
||||
if (asDirectoryPath(destFolder).startsWith(sourceDir)) return false;
|
||||
|
||||
const result = await moveEntry(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
cleanSource,
|
||||
destination,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const result = await moveEntry(terminal, cleanSource, destination);
|
||||
if ('error' in result) {
|
||||
toast.error(result.error);
|
||||
return false;
|
||||
@@ -1895,13 +1821,7 @@
|
||||
|
||||
if (oldPath === destination) return;
|
||||
|
||||
const result = await moveEntry(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
oldPath,
|
||||
destination,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const result = await moveEntry(terminal, oldPath, destination);
|
||||
if ('error' in result) {
|
||||
toast.error(result.error);
|
||||
} else {
|
||||
@@ -2177,12 +2097,7 @@
|
||||
const paths = [...selectedEntries];
|
||||
let ok = 0;
|
||||
for (const p of paths) {
|
||||
const result = await deleteEntry(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
p.replace(/\/$/, ''),
|
||||
chatId ?? undefined
|
||||
);
|
||||
const result = await deleteEntry(terminal, p.replace(/\/$/, ''));
|
||||
if (result) ok++;
|
||||
}
|
||||
toast[ok > 0 ? 'success' : 'error'](
|
||||
@@ -2210,12 +2125,7 @@
|
||||
const toastId = toast.loading($i18n.t('Preparing download...'));
|
||||
try {
|
||||
// Archive everything into a single ZIP
|
||||
const result = await archiveFromTerminal(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
paths,
|
||||
chatId ?? undefined
|
||||
);
|
||||
const result = await archiveFromTerminal(terminal, paths);
|
||||
if (!result) {
|
||||
toast.error($i18n.t('Download failed'));
|
||||
return;
|
||||
@@ -2346,7 +2256,7 @@
|
||||
loading = true;
|
||||
|
||||
void (async () => {
|
||||
const serverCwd = await getCwd(terminal.url, terminal.key, chatId ?? undefined);
|
||||
const serverCwd = await getCwd(terminal);
|
||||
if (disposed) return;
|
||||
const serverPath = applyCwd(serverCwd);
|
||||
savedPath =
|
||||
@@ -2508,9 +2418,7 @@
|
||||
{#key comparison}
|
||||
<FileComparisonModal
|
||||
files={comparison.files}
|
||||
baseUrl={comparison.terminal.url}
|
||||
apiKey={comparison.terminal.key}
|
||||
chatId={comparison.chatId}
|
||||
target={comparison.terminal}
|
||||
onClose={closeComparison}
|
||||
/>
|
||||
{/key}
|
||||
@@ -2846,8 +2754,7 @@
|
||||
{#if selectedFile !== null}
|
||||
{#if showGitDiff}
|
||||
<FileGitDiff
|
||||
connection={gitConnection}
|
||||
{chatId}
|
||||
target={gitTarget}
|
||||
root={gitStatus?.root ?? currentPath}
|
||||
file={currentGitFile}
|
||||
active={active && !fileLoading}
|
||||
@@ -2858,7 +2765,7 @@
|
||||
{/if}
|
||||
<div class="h-full" class:hidden={showGitDiff}>
|
||||
{#if supportsComments(selectedFile) && selectedTerminal}
|
||||
{#key `${selectedTerminal.url}|${selectedTerminal.key}|${chatId}|${selectedFile}|${commentGeneration}`}
|
||||
{#key `${selectedTerminal.baseUrl}|${selectedTerminal.context.modelId}|${selectedTerminal.key}|${chatId}|${selectedFile}|${commentGeneration}`}
|
||||
<CommentFilePreview
|
||||
bind:this={commentPreviewRef}
|
||||
bind:dirty
|
||||
@@ -2869,9 +2776,7 @@
|
||||
onViewChange?.({ ...captureView(), preview, dirty: preview?.dirty ?? false });
|
||||
}}
|
||||
path={selectedFile}
|
||||
baseUrl={selectedTerminal.url}
|
||||
apiKey={selectedTerminal.key}
|
||||
{chatId}
|
||||
target={selectedTerminal}
|
||||
targetPage={documentTargetPage}
|
||||
initialSheet={selectedExcelSheet}
|
||||
onReady={() => {
|
||||
@@ -2919,8 +2824,7 @@
|
||||
const DOMPurify = (await import('dompurify')).default;
|
||||
fileOfficeHtml = DOMPurify.sanitize(result.html, { ADD_ATTR: ['target'] });
|
||||
}}
|
||||
baseUrl={previewBaseUrl}
|
||||
apiKey={selectedTerminal?.key ?? ''}
|
||||
target={selectedTerminal}
|
||||
overlay={overlay || isDraggingHandle}
|
||||
onSave={saveFile}
|
||||
/>
|
||||
@@ -3152,8 +3056,7 @@
|
||||
expanded={expandedDirs.has(entry.fullPath)}
|
||||
loadingChildren={loadingDirs.has(entry.fullPath)}
|
||||
folderContentsVersion={loadGeneration}
|
||||
terminalUrl={selectedTerminal.url}
|
||||
terminalKey={selectedTerminal.key}
|
||||
target={selectedTerminal}
|
||||
terminalSessionId={chatId ?? undefined}
|
||||
selected={selectedEntries.has(entry.fullPath)}
|
||||
{selectionMode}
|
||||
@@ -3229,7 +3132,6 @@
|
||||
{#key `${effectiveTerminalId}:${chatId}`}
|
||||
<CloneRepository
|
||||
terminal={selectedTerminal}
|
||||
{chatId}
|
||||
directory={currentPath}
|
||||
disabled={loading || !!error || !savedPathLoaded || !currentWritable}
|
||||
onCancel={() => (showCloneRepository = false)}
|
||||
@@ -3289,8 +3191,9 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#key JSON.stringify([chatId, effectiveTerminalId])}
|
||||
{#key JSON.stringify([chatId, effectiveTerminalId, modelId])}
|
||||
<TerminalDock
|
||||
{modelId}
|
||||
terminalId={effectiveTerminalId}
|
||||
{active}
|
||||
bind:hasSessions
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
<script lang="ts">
|
||||
import { getContext, onDestroy } from 'svelte';
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
import { cloneRepository } from '$lib/apis/terminal/git';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
const i18n = getContext<any>('i18n');
|
||||
export let terminal: { url: string; key: string };
|
||||
export let chatId: string | null;
|
||||
export let terminal: TerminalTarget;
|
||||
|
||||
export let directory: string;
|
||||
export let disabled = false;
|
||||
export let onCloned: (path: string) => void;
|
||||
@@ -24,13 +25,7 @@
|
||||
cloningDirectory = directory;
|
||||
error = '';
|
||||
try {
|
||||
const path = await cloneRepository(
|
||||
{ baseUrl: terminal.url, key: terminal.key },
|
||||
chatId,
|
||||
directory,
|
||||
url,
|
||||
controller.signal
|
||||
);
|
||||
const path = await cloneRepository(terminal, directory, url, controller.signal);
|
||||
if (!controller.signal.aborted) onCloned(path);
|
||||
} catch (err) {
|
||||
if (!controller.signal.aborted)
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script lang="ts">
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
export let target: TerminalTarget;
|
||||
import { getContext, onMount, onDestroy, tick } from 'svelte';
|
||||
import type { WorkBook } from 'xlsx';
|
||||
export let onReady = () => {};
|
||||
@@ -30,9 +32,7 @@
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
const i18n: any = getContext('i18n');
|
||||
export let path: string;
|
||||
export let baseUrl: string;
|
||||
export let apiKey: string;
|
||||
export let chatId: string | null = null;
|
||||
|
||||
export let targetPage: number | null = null;
|
||||
export let readOnly = true;
|
||||
export let dirty = false;
|
||||
@@ -67,7 +67,7 @@
|
||||
saving = true;
|
||||
try {
|
||||
const bytes = await editor.bytes();
|
||||
const current = await downloadFileBlob(baseUrl, apiKey, path, chatId ?? undefined);
|
||||
const current = await downloadFileBlob(target, path);
|
||||
if (!current)
|
||||
throw new Error('Could not check the current file. Your changes are still in the editor.');
|
||||
if (!editor.matches(await current.blob.arrayBuffer()))
|
||||
@@ -76,13 +76,11 @@
|
||||
);
|
||||
// shortcut: the terminal upload API has no conditional write; it cannot prevent a concurrent write after this check.
|
||||
const result = await uploadToTerminal(
|
||||
baseUrl,
|
||||
apiKey,
|
||||
target,
|
||||
path.slice(0, path.lastIndexOf('/') + 1) || '/',
|
||||
new File([bytes], path.split('/').pop()!, {
|
||||
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
}),
|
||||
chatId ?? undefined
|
||||
})
|
||||
);
|
||||
if (!result)
|
||||
throw new Error('Failed to save workbook. Your changes are still in the editor.');
|
||||
@@ -255,7 +253,7 @@
|
||||
};
|
||||
async function load() {
|
||||
const previewPromise = ['docx', 'pptx'].includes(ext)
|
||||
? downloadFilePreview(baseUrl, apiKey, path, chatId ?? undefined, abort.signal)
|
||||
? downloadFilePreview(target, path, abort.signal)
|
||||
.then(async (r) => {
|
||||
if (r) {
|
||||
const bytes = await r.blob.arrayBuffer();
|
||||
@@ -268,7 +266,7 @@
|
||||
.catch(() => undefined)
|
||||
: Promise.resolve();
|
||||
try {
|
||||
const raw = await downloadFileBlob(baseUrl, apiKey, path, chatId ?? undefined, abort.signal);
|
||||
const raw = await downloadFileBlob(target, path, abort.signal);
|
||||
if (!raw) throw new Error('Original file unavailable');
|
||||
const bytes = await raw.blob.arrayBuffer();
|
||||
if (!alive) return;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script lang="ts">
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
export let target: TerminalTarget;
|
||||
import { getContext, onMount, onDestroy } from 'svelte';
|
||||
import type { Readable } from 'svelte/store';
|
||||
import type { i18n as I18n } from 'i18next';
|
||||
@@ -9,9 +11,6 @@
|
||||
import Dropdown from '../../common/Dropdown.svelte';
|
||||
import DropdownMenu from '../../common/DropdownMenu.svelte';
|
||||
|
||||
export let baseUrl: string;
|
||||
export let apiKey: string;
|
||||
export let chatId: string | null = null;
|
||||
export let paths: [string, string];
|
||||
export let onClose: () => void;
|
||||
|
||||
@@ -40,10 +39,8 @@
|
||||
result = null;
|
||||
try {
|
||||
const response = await compareFiles(
|
||||
baseUrl,
|
||||
apiKey,
|
||||
target,
|
||||
{ original, revised, ignore_whitespace: ignoreWhitespace },
|
||||
chatId ?? undefined,
|
||||
request.signal
|
||||
);
|
||||
if (!request.signal.aborted) result = response;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script lang="ts">
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
export let target: TerminalTarget;
|
||||
import { getContext, onDestroy, onMount } from 'svelte';
|
||||
import { readComparisonSource } from '$lib/apis/terminal';
|
||||
import DiffEditorModal from '$lib/components/common/DiffEditorModal.svelte';
|
||||
@@ -12,9 +14,7 @@
|
||||
{ name: string; path: string; size?: number },
|
||||
{ name: string; path: string; size?: number }
|
||||
];
|
||||
export let baseUrl: string;
|
||||
export let apiKey: string;
|
||||
export let chatId: string | null;
|
||||
|
||||
export let onClose: () => void;
|
||||
|
||||
const i18n = getContext<any>('i18n');
|
||||
@@ -24,7 +24,7 @@
|
||||
: null;
|
||||
// The caller keys this controller by its captured comparison session.
|
||||
const sourceFiles = files.map((file) => ({ ...file }));
|
||||
const connection = { baseUrl, apiKey, chatId };
|
||||
const capturedTarget = target;
|
||||
const documentComparison = sourceFiles.some(({ path }) =>
|
||||
/\.(pdf|docx?|xlsx?|pptx?|odt|ods|odp|rtf)$/i.test(path)
|
||||
);
|
||||
@@ -54,11 +54,9 @@
|
||||
sourceFiles.map(async (file) => {
|
||||
try {
|
||||
return await readComparisonSource(
|
||||
connection.baseUrl,
|
||||
connection.apiKey,
|
||||
capturedTarget,
|
||||
file.path,
|
||||
request.signal,
|
||||
connection.chatId ?? undefined,
|
||||
file.size
|
||||
);
|
||||
} catch (cause) {
|
||||
@@ -134,9 +132,7 @@
|
||||
<div class="h-full min-h-0">
|
||||
<FileCompare
|
||||
paths={[sourceFiles[0].path, sourceFiles[1].path]}
|
||||
baseUrl={connection.baseUrl}
|
||||
apiKey={connection.apiKey}
|
||||
chatId={connection.chatId}
|
||||
{target}
|
||||
onClose={close}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
export let target: TerminalTarget | null = null;
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { LinkPreview } from 'bits-ui';
|
||||
import { mobile, settings } from '$lib/stores';
|
||||
@@ -93,8 +95,6 @@
|
||||
export let expanded = false;
|
||||
export let loadingChildren = false;
|
||||
export let folderContentsVersion = 0;
|
||||
export let terminalUrl: string = '';
|
||||
export let terminalKey: string = '';
|
||||
export let terminalSessionId: string | undefined = undefined;
|
||||
|
||||
export let onOpen: (entry: FileEntry) => void = () => {};
|
||||
@@ -191,7 +191,7 @@
|
||||
const closeHoverPreview = () => (openPreview = false);
|
||||
$: hoverDisabled =
|
||||
entry.type !== 'file' ||
|
||||
!terminalUrl ||
|
||||
!target?.baseUrl ||
|
||||
$mobile ||
|
||||
renaming ||
|
||||
menuOpen ||
|
||||
@@ -219,17 +219,15 @@
|
||||
: $i18n.t('{{count}} items', { count: folderItemCount });
|
||||
const observeFolderContents = (node: Element) => {
|
||||
folderItemCount = null;
|
||||
if (!terminalUrl) return;
|
||||
if (!target?.baseUrl) return;
|
||||
let disposed = false;
|
||||
const url = terminalUrl;
|
||||
const key = terminalKey;
|
||||
const session = terminalSessionId;
|
||||
const capturedTarget = target;
|
||||
const path = directoryPath;
|
||||
const observer = new IntersectionObserver((observations) => {
|
||||
if (!observations.some((observation) => observation.isIntersecting)) return;
|
||||
observer.disconnect();
|
||||
// Only inspect visible folders; failed reads leave their contents unknown.
|
||||
void listFiles(url, key, path, session).then((result) => {
|
||||
void listFiles(capturedTarget!, path).then((result) => {
|
||||
if (!disposed && result)
|
||||
folderItemCount = result.entries.filter(
|
||||
(item) => showHidden || !item.name.startsWith('.')
|
||||
@@ -637,13 +635,11 @@
|
||||
{#if viewMode === 'list'}
|
||||
<FileTypeIcon name={entry.name} type={entry.type} size={14} />
|
||||
{:else}
|
||||
{#key JSON.stringify( [terminalUrl, terminalKey, terminalSessionId, entryPath, entry.modified, entry.size] )}
|
||||
{#key JSON.stringify( [target?.baseUrl, target?.key, terminalSessionId, entryPath, entry.modified, entry.size] )}
|
||||
<FileGridIcon
|
||||
{entry}
|
||||
path={entryPath}
|
||||
{terminalUrl}
|
||||
{terminalKey}
|
||||
sessionId={terminalSessionId}
|
||||
{target}
|
||||
itemCount={folderItemCount}
|
||||
/>
|
||||
{/key}
|
||||
@@ -724,7 +720,7 @@
|
||||
>{formatRelativeTime(entryDate)}</span
|
||||
>
|
||||
{/if}
|
||||
{#if terminalUrl}
|
||||
{#if target?.baseUrl}
|
||||
{#key folderContentsVersion}
|
||||
<span use:observeFolderContents class="text-xs text-gray-400 shrink-0"
|
||||
>{folderCountLabel}</span
|
||||
@@ -735,15 +731,14 @@
|
||||
</button>
|
||||
{/snippet}
|
||||
</LinkPreview.Trigger>
|
||||
{#if openPreview}
|
||||
{#key JSON.stringify( [terminalUrl, terminalKey, terminalSessionId, entryPath, entry.modified, entry.size] )}
|
||||
{#if openPreview && target}
|
||||
{#key JSON.stringify( [target?.baseUrl, target?.key, terminalSessionId, entryPath, entry.modified, entry.size] )}
|
||||
{#await import('./FileHoverPreview.svelte') then { default: FileHoverPreview }}
|
||||
<FileHoverPreview
|
||||
{entry}
|
||||
sideOffset={viewMode === 'grid' ? 4 : 12}
|
||||
path={entryPath}
|
||||
{terminalUrl}
|
||||
{terminalKey}
|
||||
{target}
|
||||
sessionId={terminalSessionId}
|
||||
/>
|
||||
{/await}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
<script lang="ts">
|
||||
import { getContext, onDestroy } from 'svelte';
|
||||
import type { TerminalConnection } from '$lib/apis/terminal';
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
import { gitRequest, type GitFile } from '$lib/apis/terminal/git';
|
||||
import GitDiff from '../Tabs/GitDiff.svelte';
|
||||
import Spinner from '../../common/Spinner.svelte';
|
||||
|
||||
export let connection: TerminalConnection | null;
|
||||
export let chatId: string | null;
|
||||
export let target: TerminalTarget | null;
|
||||
|
||||
export let root: string;
|
||||
export let file: GitFile | null;
|
||||
export let active = true;
|
||||
@@ -20,8 +20,7 @@
|
||||
let generation = 0;
|
||||
|
||||
const load = async (
|
||||
server: TerminalConnection | null,
|
||||
session: string | null,
|
||||
server: TerminalTarget | null,
|
||||
directory: string,
|
||||
entry: GitFile | null,
|
||||
enabled: boolean,
|
||||
@@ -38,7 +37,7 @@
|
||||
}
|
||||
loading = true;
|
||||
try {
|
||||
const result = await gitRequest<{ diff: string }>(server, session, directory, 'diff', {
|
||||
const result = await gitRequest<{ diff: string }>(server, directory, 'diff', {
|
||||
file: entry.path,
|
||||
staged: String(entry.staged && !entry.unstaged),
|
||||
untracked: String(entry.status === 'untracked'),
|
||||
@@ -54,7 +53,7 @@
|
||||
if (current === generation) loading = false;
|
||||
}
|
||||
};
|
||||
$: void load(connection, chatId, root, file, active, hideWhitespace, resourceVersion);
|
||||
$: void load(target, root, file, active, hideWhitespace, resourceVersion);
|
||||
onDestroy(() => {
|
||||
++generation;
|
||||
});
|
||||
@@ -73,7 +72,7 @@
|
||||
{error}<button
|
||||
class="underline"
|
||||
on:click={() =>
|
||||
load(connection, chatId, root, file, active, hideWhitespace, resourceVersion)}
|
||||
load(target, root, file, active, hideWhitespace, resourceVersion)}
|
||||
>{$i18n.t('Retry')}</button
|
||||
>
|
||||
</div>
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
<script lang="ts">
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
export let target: TerminalTarget | null = null;
|
||||
import { downloadFileBlob, type FileEntry } from '$lib/apis/terminal';
|
||||
import { fileIconName } from './fileIcon';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
export let entry: FileEntry;
|
||||
export let path = '';
|
||||
export let terminalUrl = '';
|
||||
export let terminalKey = '';
|
||||
export let sessionId: string | undefined = undefined;
|
||||
|
||||
export let itemCount: number | null = null;
|
||||
|
||||
let imageUrl: string | null = null;
|
||||
@@ -19,7 +19,7 @@
|
||||
// shortcut: Bound automatic downloads until the terminal provides resized thumbnails.
|
||||
if (
|
||||
entry.type !== 'file' ||
|
||||
!terminalUrl ||
|
||||
!target?.baseUrl ||
|
||||
entry.size === undefined ||
|
||||
entry.size > 5 * 1024 * 1024 ||
|
||||
!['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'bmp', 'ico'].includes(extension)
|
||||
@@ -32,7 +32,7 @@
|
||||
const observer = new IntersectionObserver((observations) => {
|
||||
if (!observations.some((item) => item.isIntersecting)) return;
|
||||
observer.disconnect();
|
||||
void downloadFileBlob(terminalUrl, terminalKey, path, sessionId, controller.signal)
|
||||
void downloadFileBlob(target, path, controller.signal)
|
||||
.then((result) => {
|
||||
if (disposed || !result) return;
|
||||
objectUrl = URL.createObjectURL(result.blob);
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script lang="ts">
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
export let target: TerminalTarget;
|
||||
import { getContext, onMount, onDestroy } from 'svelte';
|
||||
import { LinkPreview } from 'bits-ui';
|
||||
import { readFile, downloadFileBlob, type FileEntry } from '$lib/apis/terminal';
|
||||
@@ -11,8 +13,6 @@
|
||||
const i18n: any = getContext('i18n');
|
||||
export let entry: FileEntry;
|
||||
export let path: string;
|
||||
export let terminalUrl: string;
|
||||
export let terminalKey: string;
|
||||
export let sessionId: string | undefined = undefined;
|
||||
export let sideOffset = 12;
|
||||
|
||||
@@ -44,13 +44,7 @@
|
||||
const isSqlite = ['db', 'sqlite', 'sqlite3', 'db3'].includes(extension);
|
||||
try {
|
||||
if (isImage || isVideo || isAudio || isSqlite || isModel) {
|
||||
const result = await downloadFileBlob(
|
||||
terminalUrl,
|
||||
terminalKey,
|
||||
path,
|
||||
sessionId,
|
||||
controller.signal
|
||||
);
|
||||
const result = await downloadFileBlob(target, path, controller.signal);
|
||||
if (!result || disposed) return;
|
||||
if (isSqlite || isModel) {
|
||||
const bytes = await result.blob.arrayBuffer();
|
||||
@@ -65,7 +59,7 @@
|
||||
else fileAudioUrl = url;
|
||||
}
|
||||
} else if (entry.size! <= 1024 * 1024) {
|
||||
const text = await readFile(terminalUrl, terminalKey, path, sessionId);
|
||||
const text = await readFile(target, path);
|
||||
if (!disposed && text !== null && !text.startsWith('[Binary file:')) fileContent = text;
|
||||
}
|
||||
} catch {
|
||||
@@ -109,12 +103,7 @@
|
||||
class="h-60 max-h-[calc(100dvh-6rem)] overflow-hidden text-xs [&_.document-markdown]:!p-2 [&_.document-markdown_h1]:!text-sm [&_.document-markdown_h2]:!text-xs [&_.document-markdown_h3]:!text-xs [&_.document-markdown]:!text-[0.8125rem] [&_.cm-editor]:!text-[0.6875rem] [&_pre]:!text-[0.6875rem]"
|
||||
>
|
||||
{#if documentPreview && withinPreviewLimit}
|
||||
<CommentFilePreview
|
||||
{path}
|
||||
baseUrl={terminalUrl}
|
||||
apiKey={terminalKey}
|
||||
chatId={sessionId ?? null}
|
||||
/>
|
||||
<CommentFilePreview {path} {target} />
|
||||
{:else if loading || fileContent !== null || fileImageUrl || fileVideoUrl || fileAudioUrl || fileSqliteData || fileModelData}
|
||||
<FilePreview
|
||||
selectedFile={path}
|
||||
@@ -125,8 +114,7 @@
|
||||
{fileAudioUrl}
|
||||
{fileSqliteData}
|
||||
{fileModelData}
|
||||
baseUrl={terminalUrl}
|
||||
apiKey={terminalKey}
|
||||
{target}
|
||||
chatId={sessionId ?? null}
|
||||
readOnly={true}
|
||||
allowScripts={false}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
<script lang="ts">
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
export let target: TerminalTarget | null = null;
|
||||
import ExcelPreview from '$lib/components/common/ExcelPreview.svelte';
|
||||
import { getContext, tick } from 'svelte';
|
||||
import { downloadFileBlob } from '$lib/apis/terminal';
|
||||
import { getContext, tick, onDestroy } from 'svelte';
|
||||
import { downloadFileBlob, terminalRequest } from '$lib/apis/terminal';
|
||||
import MarkdownFileEditor from './MarkdownFileEditor.svelte';
|
||||
import MarkdownDocument from './MarkdownDocument.svelte';
|
||||
import { settings, config } from '$lib/stores';
|
||||
@@ -36,8 +38,6 @@
|
||||
export let gitBaseContent: string | null = null;
|
||||
|
||||
// Terminal connection for notebook execution
|
||||
export let baseUrl: string = '';
|
||||
export let apiKey: string = '';
|
||||
export let chatId: string | null = null;
|
||||
export let resourceVersion = 0;
|
||||
export let onLocalLink: (path: string) => void = () => {};
|
||||
@@ -137,12 +137,42 @@
|
||||
$: csvDelimiter = getExt(selectedFile) === 'tsv' ? '\t' : ',';
|
||||
$: isPptx = getExt(selectedFile) === 'pptx';
|
||||
|
||||
// For HTML files on system terminals (proxy URL), use path-based serving
|
||||
// so the iframe can resolve relative CSS/JS/image references via cookie auth.
|
||||
$: serveUrl =
|
||||
isHtml && selectedFile && baseUrl && baseUrl.includes('/api/v1/terminals/')
|
||||
? `${baseUrl}/files/serve/${selectedFile.replace(/^\//, '')}`
|
||||
: null;
|
||||
let serveUrl: string | null = null;
|
||||
let previewError = '';
|
||||
let previewPending = false;
|
||||
let previewGeneration = 0;
|
||||
const configurePreview = async (_key: string) => {
|
||||
const generation = ++previewGeneration;
|
||||
serveUrl = null;
|
||||
previewError = '';
|
||||
previewPending = false;
|
||||
if (!isHtml || !selectedFile || !target?.system) return;
|
||||
const path = selectedFile.replace(/^\//, '').split('/').map(encodeURIComponent).join('/');
|
||||
if (!target.selector.startsWith('template:')) {
|
||||
serveUrl = `${target.baseUrl}${target.context.chatId ? `/chats/${encodeURIComponent(target.context.chatId)}` : ''}/files/serve/${path}`;
|
||||
return;
|
||||
}
|
||||
previewPending = true;
|
||||
try {
|
||||
const result = await terminalRequest<{ url: string }>(target, '/files/preview', {
|
||||
method: 'POST'
|
||||
});
|
||||
if (generation === previewGeneration) serveUrl = result.url + path;
|
||||
} catch (error) {
|
||||
if (generation === previewGeneration) previewError = String(error);
|
||||
} finally {
|
||||
if (generation === previewGeneration) previewPending = false;
|
||||
}
|
||||
};
|
||||
$: void configurePreview(
|
||||
JSON.stringify([
|
||||
isHtml,
|
||||
selectedFile,
|
||||
target?.baseUrl,
|
||||
target?.context
|
||||
])
|
||||
);
|
||||
onDestroy(() => previewGeneration++);
|
||||
// Simple CSV parser that handles quoted fields
|
||||
const parseCsv = (text: string, delimiter: string): string[][] => {
|
||||
const rows: string[][] = [];
|
||||
@@ -302,13 +332,11 @@
|
||||
<ModelPreview
|
||||
data={fileModelData}
|
||||
path={selectedFile ?? ''}
|
||||
loadResource={baseUrl
|
||||
loadResource={target?.baseUrl
|
||||
? async (path, signal) => {
|
||||
const result = await downloadFileBlob(
|
||||
baseUrl,
|
||||
apiKey,
|
||||
target,
|
||||
path,
|
||||
chatId ?? undefined,
|
||||
signal
|
||||
);
|
||||
if (!result) throw new Error('Could not load model resource.');
|
||||
@@ -356,6 +384,8 @@
|
||||
{searchTarget}
|
||||
/>
|
||||
</div>
|
||||
{:else if isHtml && !showRaw && (previewPending || previewError)}
|
||||
{#if previewError}<p role="alert">{previewError}</p>{:else}<Spinner />{/if}
|
||||
{:else if isHtml && !showRaw && serveUrl}
|
||||
{#if overlay}
|
||||
<div class="absolute top-0 left-0 right-0 bottom-0 z-10"></div>
|
||||
@@ -394,8 +424,7 @@
|
||||
bind:this={markdownEditorRef}
|
||||
bind:value={codeValue}
|
||||
path={selectedFile ?? ''}
|
||||
{baseUrl}
|
||||
{apiKey}
|
||||
{target}
|
||||
{chatId}
|
||||
{readOnly}
|
||||
onSave={readOnly ? null : saveCodeFile}
|
||||
@@ -407,8 +436,7 @@
|
||||
content={codeValue}
|
||||
id={`file-${selectedFile}`}
|
||||
path={selectedFile ?? ''}
|
||||
{baseUrl}
|
||||
{apiKey}
|
||||
{target}
|
||||
{chatId}
|
||||
{resourceVersion}
|
||||
{onLocalLink}
|
||||
@@ -446,8 +474,7 @@
|
||||
<NotebookView
|
||||
notebook={parsedNotebook}
|
||||
filePath={selectedFile ?? ''}
|
||||
{baseUrl}
|
||||
{apiKey}
|
||||
{target}
|
||||
{readOnly}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -38,6 +38,8 @@
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
export let target: TerminalTarget | null = null;
|
||||
import { getAllContexts, mount, unmount, setContext, onDestroy } from 'svelte';
|
||||
import { writable } from 'svelte/store';
|
||||
import DOMPurify from 'dompurify';
|
||||
@@ -52,8 +54,6 @@
|
||||
export let saving = false;
|
||||
export let id: string;
|
||||
export let path = '';
|
||||
export let baseUrl = '';
|
||||
export let apiKey = '';
|
||||
export let chatId: string | null = null;
|
||||
export let resourceVersion = 0;
|
||||
export let onLocalLink: (path: string) => void = () => {};
|
||||
@@ -70,12 +70,12 @@
|
||||
onDestroy(release);
|
||||
const resolveImage = (reference: string): Promise<string | null> => {
|
||||
const file = resolveDocumentPath(path, reference);
|
||||
if (!file || !baseUrl) return Promise.resolve(null);
|
||||
if (!file || !target?.baseUrl) return Promise.resolve(null);
|
||||
if (!urls.has(file)) {
|
||||
const current = generation;
|
||||
urls.set(
|
||||
file,
|
||||
downloadFileBlob(baseUrl, apiKey, file, chatId ?? undefined).then((result) => {
|
||||
downloadFileBlob(target, file).then((result) => {
|
||||
if (!result || current !== generation) return null;
|
||||
const url = URL.createObjectURL(result.blob);
|
||||
objectUrls.push(url);
|
||||
@@ -87,7 +87,7 @@
|
||||
};
|
||||
const resources = {
|
||||
resolveImage,
|
||||
localPath: (ref: string) => (baseUrl ? resolveDocumentPath(path, ref) : null),
|
||||
localPath: (ref: string) => (target?.baseUrl ? resolveDocumentPath(path, ref) : null),
|
||||
open: (ref: string) => {
|
||||
const file = resolveDocumentPath(path, ref);
|
||||
if (file) onLocalLink(file);
|
||||
@@ -95,7 +95,7 @@
|
||||
};
|
||||
setContext('terminal-document', resources);
|
||||
$: {
|
||||
(resourceVersion, path, baseUrl, chatId);
|
||||
(resourceVersion, path, target?.baseUrl, chatId);
|
||||
release();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script lang="ts">
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
export let target: TerminalTarget | null = null;
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { getAllContexts, getContext, mount, unmount, onDestroy, tick } from 'svelte';
|
||||
import { Node, type Editor } from '@tiptap/core';
|
||||
@@ -19,8 +21,6 @@
|
||||
|
||||
export let value = '';
|
||||
export let path = '';
|
||||
export let baseUrl = '';
|
||||
export let apiKey = '';
|
||||
export let chatId: string | null = null;
|
||||
export let readOnly = false;
|
||||
export let onSave: (() => Promise<void>) | null = null;
|
||||
@@ -157,8 +157,7 @@
|
||||
content: node.attrs.source,
|
||||
id: `editor-${uuidv4()}`,
|
||||
path,
|
||||
baseUrl,
|
||||
apiKey,
|
||||
target,
|
||||
chatId
|
||||
}
|
||||
});
|
||||
@@ -242,7 +241,7 @@
|
||||
export const flushUploads = () => Promise.all(pendingImages);
|
||||
const attachImages = (event: ClipboardEvent | DragEvent) => {
|
||||
const currentEditor = editor;
|
||||
if (readOnly || !currentEditor || !baseUrl || !path) return;
|
||||
if (readOnly || !currentEditor || !target?.baseUrl || !path) return;
|
||||
const transfer = 'clipboardData' in event ? event.clipboardData : event.dataTransfer;
|
||||
const files = Array.from(transfer?.files ?? []).filter((file) =>
|
||||
file.type.startsWith('image/')
|
||||
@@ -263,17 +262,15 @@
|
||||
const current = generation;
|
||||
const documentPath = path.replace(/\\/g, '/');
|
||||
const directory = documentPath.slice(0, documentPath.lastIndexOf('/')) || '/';
|
||||
const connection = { baseUrl, apiKey, chatId };
|
||||
const capturedTarget = target;
|
||||
const upload = (async () => {
|
||||
try {
|
||||
for (const file of files) {
|
||||
if (current !== generation || currentEditor.isDestroyed || readOnly) break;
|
||||
const result = await uploadNewFileToTerminal(
|
||||
connection.baseUrl,
|
||||
connection.apiKey,
|
||||
capturedTarget!,
|
||||
directory,
|
||||
file,
|
||||
connection.chatId ?? undefined
|
||||
file
|
||||
);
|
||||
if (current !== generation || currentEditor.isDestroyed || readOnly) break;
|
||||
if (!result) throw new Error($i18n.t('Failed to upload file.'));
|
||||
@@ -318,9 +315,9 @@
|
||||
Array.from(dom.querySelectorAll('img')).map(async (image) => {
|
||||
const reference = image.getAttribute('src') ?? '';
|
||||
const file = resolveDocumentPath(path, reference);
|
||||
if (!file || !baseUrl) return;
|
||||
if (!file || !target?.baseUrl) return;
|
||||
try {
|
||||
const result = await downloadFileBlob(baseUrl, apiKey, file, chatId ?? undefined);
|
||||
const result = await downloadFileBlob(target, file);
|
||||
if (!result || current !== generation) return;
|
||||
const url = URL.createObjectURL(result.blob);
|
||||
images.set(url, reference);
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
<script lang="ts">
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
export let target: TerminalTarget | null = null;
|
||||
|
||||
import { getContext, onMount, onDestroy } from 'svelte';
|
||||
import { marked } from 'marked';
|
||||
import DOMPurify from 'dompurify';
|
||||
@@ -16,8 +19,6 @@
|
||||
|
||||
export let notebook: Record<string, unknown>;
|
||||
export let filePath: string = '';
|
||||
export let baseUrl: string = '';
|
||||
export let apiKey: string = '';
|
||||
export let readOnly = false;
|
||||
|
||||
interface NotebookCell {
|
||||
@@ -128,14 +129,14 @@
|
||||
let runningCell: number | null = null;
|
||||
let runAllActive = false;
|
||||
|
||||
const canExecute = !readOnly && baseUrl && apiKey && filePath;
|
||||
const canExecute = !readOnly && target?.baseUrl && target?.key && filePath;
|
||||
|
||||
const startSession = async (): Promise<boolean> => {
|
||||
if (!baseUrl || !apiKey || !filePath) return false;
|
||||
if (!target?.baseUrl || !target?.key || !filePath) return false;
|
||||
kernelStarting = true;
|
||||
kernelError = null;
|
||||
|
||||
const result = await createNotebookSession(baseUrl, apiKey, filePath);
|
||||
const result = await createNotebookSession(target, filePath);
|
||||
|
||||
if ('error' in result) {
|
||||
kernelStarting = false;
|
||||
@@ -150,8 +151,8 @@
|
||||
};
|
||||
|
||||
const stopSession = async () => {
|
||||
if (sessionId && baseUrl && apiKey) {
|
||||
await stopNotebookSession(baseUrl, apiKey, sessionId);
|
||||
if (sessionId && target?.baseUrl && target?.key) {
|
||||
await stopNotebookSession(target, sessionId);
|
||||
}
|
||||
sessionId = null;
|
||||
kernelReady = false;
|
||||
@@ -172,7 +173,7 @@
|
||||
editingCell = editingCell;
|
||||
}
|
||||
|
||||
const result = await executeNotebookCell(baseUrl, apiKey, sessionId!, index, source);
|
||||
const result = await executeNotebookCell(target!, sessionId!, index, source);
|
||||
|
||||
if ('error' in result) {
|
||||
cells[index].outputs = [
|
||||
@@ -219,7 +220,7 @@
|
||||
|
||||
<div class="notebook-view">
|
||||
<!-- Toolbar -->
|
||||
{#if !readOnly && baseUrl && apiKey && filePath}
|
||||
{#if !readOnly && target?.baseUrl && target?.key && filePath}
|
||||
<div class="nb-toolbar flex items-center gap-1 px-2 py-0.5">
|
||||
<button
|
||||
class="nb-btn text-[0.6rem]"
|
||||
@@ -315,7 +316,7 @@
|
||||
<div class="nb-cell-gutter">
|
||||
{#if runningCell === i}
|
||||
<div class="nb-cell-label"><Spinner className="size-3" /></div>
|
||||
{:else if !readOnly && baseUrl && apiKey && filePath}
|
||||
{:else if !readOnly && target?.baseUrl && target?.key && filePath}
|
||||
<button
|
||||
class="nb-run-btn"
|
||||
on:click={() => runCell(i)}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script lang="ts">
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
export let target: TerminalTarget;
|
||||
import { onMount, onDestroy, getContext, createEventDispatcher } from 'svelte';
|
||||
import type { ListeningPort } from '$lib/apis/terminal';
|
||||
import { getListeningPorts, getPortProxyUrl, getTerminalFeatures } from '$lib/apis/terminal';
|
||||
@@ -9,11 +11,9 @@
|
||||
const i18n = getContext<any>('i18n');
|
||||
const dispatch = createEventDispatcher<{ previewPort: number }>();
|
||||
|
||||
export let baseUrl: string;
|
||||
export let active = true;
|
||||
export let previewBaseUrl: string | null = null;
|
||||
export let apiKey: string;
|
||||
export let chatId: string | null = null;
|
||||
|
||||
|
||||
let ports: ListeningPort[] = [];
|
||||
let loading = false;
|
||||
@@ -25,7 +25,7 @@
|
||||
const loadPorts = async () => {
|
||||
const current = generation;
|
||||
loading = true;
|
||||
const next = await getListeningPorts(baseUrl, apiKey, chatId);
|
||||
const next = await getListeningPorts(target);
|
||||
if (current !== generation) return;
|
||||
ports = next;
|
||||
loading = false;
|
||||
@@ -38,15 +38,13 @@
|
||||
if (context !== key) ports = [];
|
||||
context = key;
|
||||
loading = false;
|
||||
if (!enabled || !baseUrl) return;
|
||||
const connection = { baseUrl, key: apiKey, selector: '', system: false };
|
||||
const features = await getTerminalFeatures(connection, chatId);
|
||||
if (!enabled || !target.baseUrl) return;
|
||||
const features = await getTerminalFeatures(target);
|
||||
if (current !== generation) return;
|
||||
if (features.events === true) {
|
||||
loading = true;
|
||||
stopWatching = watchTerminalPorts(
|
||||
connection,
|
||||
chatId,
|
||||
target,
|
||||
(next) => {
|
||||
ports = next;
|
||||
loading = false;
|
||||
@@ -65,12 +63,12 @@
|
||||
};
|
||||
|
||||
const openPortExternal = (port: number) => {
|
||||
const url = getPortProxyUrl(previewBaseUrl ?? baseUrl, port);
|
||||
const url = getPortProxyUrl(previewBaseUrl ?? target.baseUrl, port);
|
||||
window.open(url, '_blank', 'noopener,noreferrer');
|
||||
};
|
||||
|
||||
// Only discover ports while the browser start view is visible.
|
||||
$: configure(JSON.stringify([baseUrl, apiKey, chatId]), mounted && active);
|
||||
$: configure(JSON.stringify([target.baseUrl, target.key, target.context]), mounted && active);
|
||||
onMount(() => {
|
||||
mounted = true;
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { resolveTerminalTarget } from '$lib/apis/terminal';
|
||||
import type { TerminalContext } from '$lib/types';
|
||||
import {
|
||||
estimateTokens,
|
||||
@@ -1072,24 +1073,31 @@
|
||||
fileItem.error = '';
|
||||
files = files;
|
||||
try {
|
||||
const terminal = getFilesystemUploadTerminal(fileItem.terminal_id);
|
||||
const server = getFilesystemUploadTerminal(fileItem.terminal_id);
|
||||
const terminal = server
|
||||
? resolveTerminalTarget(
|
||||
fileItem.terminal_id,
|
||||
$terminalServers ?? [],
|
||||
($settings as any)?.terminalServers ?? [],
|
||||
localStorage.token,
|
||||
{ chatId: sessionId, modelId: selectedModels[0] ?? null }
|
||||
)
|
||||
: null;
|
||||
if (!terminal) throw new Error('The attached file’s terminal is unavailable.');
|
||||
if (fileItem.session_id && fileItem.session_id !== sessionId)
|
||||
throw new Error('Attached files must belong to this chat.');
|
||||
if (terminal.contexts?.chat?.context_id === 'chat_id' && !isSavedChatId(sessionId))
|
||||
if (server.scope === 'chat' && !isSavedChatId(sessionId))
|
||||
throw new Error('A saved chat is required for this terminal');
|
||||
|
||||
const cwd =
|
||||
(terminalContext?.terminalId === fileItem.terminal_id
|
||||
? terminalContext?.currentDirectory
|
||||
: null) || (await getCwd(terminal.url, terminal.key, sessionId || undefined))?.cwd;
|
||||
: null) || (await getCwd(terminal))?.cwd;
|
||||
if (!cwd) throw new Error($i18n.t('Could not determine the upload folder.'));
|
||||
const uploadedFile = await uploadNewFileToTerminal(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
terminal,
|
||||
cwd,
|
||||
fileItem.file,
|
||||
sessionId || undefined
|
||||
fileItem.file
|
||||
);
|
||||
if (!uploadedFile) throw new Error($i18n.t('Failed to upload file.'));
|
||||
|
||||
@@ -1171,7 +1179,7 @@
|
||||
fileItem.file = file;
|
||||
fileItem.terminal_id = $selectedTerminalId;
|
||||
fileItem.session_id = chatId || null;
|
||||
if (!chatId && filesystemUploadTerminal.contexts?.chat?.context_id === 'chat_id') {
|
||||
if (!chatId && filesystemUploadTerminal.scope === 'chat') {
|
||||
fileItem.status = 'pending';
|
||||
files = files;
|
||||
return;
|
||||
@@ -1639,6 +1647,7 @@
|
||||
{
|
||||
char: '@',
|
||||
render: getSuggestionRenderer(CommandSuggestionList, {
|
||||
modelId: () => selectedModels[0] ?? null,
|
||||
i18n,
|
||||
fileUploadEnabled: () => fileUploadEnabled,
|
||||
onSelect: (e) => {
|
||||
@@ -1735,6 +1744,7 @@
|
||||
.run();
|
||||
},
|
||||
render: getSuggestionRenderer(CommandSuggestionList, {
|
||||
modelId: () => selectedModels[0] ?? null,
|
||||
i18n,
|
||||
canCompact: () => !!history?.currentId && contextCompactionEnabled,
|
||||
compactDisabled: () => isActive,
|
||||
@@ -1802,6 +1812,7 @@
|
||||
{
|
||||
char: '#',
|
||||
render: getSuggestionRenderer(CommandSuggestionList, {
|
||||
modelId: () => selectedModels[0] ?? null,
|
||||
i18n,
|
||||
fileUploadEnabled: () => fileUploadEnabled,
|
||||
onSelect: (e) => {
|
||||
@@ -1841,6 +1852,7 @@
|
||||
{
|
||||
char: '$',
|
||||
render: getSuggestionRenderer(CommandSuggestionList, {
|
||||
modelId: () => selectedModels[0] ?? null,
|
||||
i18n,
|
||||
onSelect: (e) => {
|
||||
focus({ preventScroll: true });
|
||||
@@ -1863,6 +1875,7 @@
|
||||
editor.chain().focus().deleteRange(range).insertContent(emoji).run();
|
||||
},
|
||||
render: getSuggestionRenderer(CommandSuggestionList, {
|
||||
modelId: () => selectedModels[0] ?? null,
|
||||
i18n,
|
||||
onSelect: (e) => {
|
||||
focus({ preventScroll: true });
|
||||
@@ -2647,7 +2660,13 @@
|
||||
|
||||
<svelte:fragment slot="terminal">
|
||||
{#if showTerminalSelector && terminalControlsInMenu}
|
||||
<TerminalMenu inMenu {chatId} bind:terminalContext disabled={generating} />
|
||||
<TerminalMenu
|
||||
modelId={selectedModels[0] ?? null}
|
||||
inMenu
|
||||
{chatId}
|
||||
bind:terminalContext
|
||||
disabled={generating}
|
||||
/>
|
||||
<div class="h-px mx-1 my-1 bg-gray-100 dark:bg-gray-800"></div>
|
||||
{/if}
|
||||
</svelte:fragment>
|
||||
@@ -2911,6 +2930,7 @@
|
||||
{#if showTerminalSelector}
|
||||
<div data-terminal-controls class="flex items-center gap-1.5 shrink-0">
|
||||
<TerminalMenu
|
||||
modelId={selectedModels[0] ?? null}
|
||||
bind:show={showTerminalMenu}
|
||||
{chatId}
|
||||
bind:terminalContext
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
|
||||
export let char = '';
|
||||
export let query = '';
|
||||
export let modelId: string | null | (() => string | null) = null;
|
||||
$: selectedModelId = typeof modelId === 'function' ? modelId() : modelId;
|
||||
export let command: (payload: {
|
||||
id: string;
|
||||
label: string;
|
||||
@@ -111,6 +113,7 @@
|
||||
<div class="max-h-60 overflow-y-auto overflow-x-hidden scrollbar-thin">
|
||||
{#if char === '/'}
|
||||
<SlashCommands
|
||||
modelId={selectedModelId}
|
||||
bind:this={suggestionElement}
|
||||
{query}
|
||||
canCompare={onCompare !== null}
|
||||
@@ -209,6 +212,7 @@
|
||||
/>
|
||||
{:else if char === '@'}
|
||||
<AtCommands
|
||||
modelId={selectedModelId}
|
||||
bind:this={suggestionElement}
|
||||
{query}
|
||||
fileUploadEnabled={isFileUploadEnabled}
|
||||
@@ -249,6 +253,7 @@
|
||||
/>
|
||||
{:else if char === '$'}
|
||||
<Skills
|
||||
modelId={selectedModelId}
|
||||
bind:this={suggestionElement}
|
||||
{query}
|
||||
bind:filteredItems
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { resolveTerminalTarget, type TerminalTarget } from '$lib/apis/terminal';
|
||||
import Fuse from 'fuse.js';
|
||||
import { getContext, onDestroy, onMount, tick } from 'svelte';
|
||||
|
||||
@@ -34,6 +35,7 @@
|
||||
const i18n = getContext<any>('i18n');
|
||||
|
||||
export let query = '';
|
||||
export let modelId: string | null = null;
|
||||
export let onSelect: (e: any) => void = () => {};
|
||||
export let fileUploadEnabled: boolean = true;
|
||||
|
||||
@@ -121,10 +123,7 @@
|
||||
getKnowledgeFileItems(signal);
|
||||
};
|
||||
|
||||
const getFilesystemItems = async (
|
||||
terminal: { url: string; key: string } | null,
|
||||
signal: AbortSignal
|
||||
) => {
|
||||
const getFilesystemItems = async (terminal: TerminalTarget | null, signal: AbortSignal) => {
|
||||
if (!terminal) {
|
||||
filesystemItems = [];
|
||||
return;
|
||||
@@ -133,13 +132,11 @@
|
||||
const terminalId = $selectedTerminalId;
|
||||
const sessionId = $activeChatId;
|
||||
const res = await searchFiles(
|
||||
terminal.url,
|
||||
terminal.key,
|
||||
terminal,
|
||||
query,
|
||||
'.',
|
||||
20,
|
||||
'any',
|
||||
sessionId || undefined,
|
||||
localStorage.getItem('fileNav:showHidden') === 'true',
|
||||
signal
|
||||
).catch(() => null);
|
||||
@@ -153,31 +150,17 @@
|
||||
}));
|
||||
};
|
||||
|
||||
const chatContext = (terminal: any) => terminal?.contexts?.chat ?? {};
|
||||
|
||||
const getSelectedTerminal = (): { url: string; key: string } | null => {
|
||||
if (!$selectedTerminalId) return null;
|
||||
|
||||
const systemTerminal = ($terminalServers ?? []).find(
|
||||
(t) => t.id && t.id === $selectedTerminalId
|
||||
const getSelectedTerminal = (): TerminalTarget | null => {
|
||||
const target = resolveTerminalTarget(
|
||||
$selectedTerminalId,
|
||||
$terminalServers ?? [],
|
||||
(($settings as any)?.terminalServers ?? []).filter((server: any) => server.enabled),
|
||||
localStorage.token,
|
||||
{ chatId: $activeChatId || null, modelId: modelId }
|
||||
);
|
||||
const systemChatContext = chatContext(systemTerminal);
|
||||
if (systemTerminal) {
|
||||
if (
|
||||
systemChatContext === false ||
|
||||
(($temporaryChatEnabled || isTemporaryChatId($activeChatId)) &&
|
||||
systemChatContext?.context_id === 'chat_id')
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { url: systemTerminal.url, key: localStorage.token };
|
||||
}
|
||||
|
||||
const directTerminal = ($settings?.terminalServers ?? []).find(
|
||||
(t: any) => t.url === $selectedTerminalId && t.enabled
|
||||
);
|
||||
return directTerminal?.url ? { url: directTerminal.url, key: directTerminal.key ?? '' } : null;
|
||||
if (($terminalServers ?? []).find((server) => server.id === $selectedTerminalId)?.scope === 'chat' && ($temporaryChatEnabled || isTemporaryChatId($activeChatId)))
|
||||
return null;
|
||||
return target;
|
||||
};
|
||||
|
||||
$: folderItems = (($folders ?? []) as any[])
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
<script lang="ts">
|
||||
export let modelId: string | null = null;
|
||||
import { resolveLocalizedResource } from '$lib/utils/localizedContent';
|
||||
import { getContext, onDestroy } from 'svelte';
|
||||
import { getSkillItems } from '$lib/apis/skills';
|
||||
import {
|
||||
listTerminalSkills,
|
||||
resolveTerminalConnection,
|
||||
resolveTerminalTarget,
|
||||
type TerminalSkill
|
||||
} from '$lib/apis/terminal';
|
||||
import {
|
||||
@@ -47,13 +48,12 @@
|
||||
};
|
||||
|
||||
const getTerminalItems = async (query = ''): Promise<TerminalSkill[]> => {
|
||||
const connection = resolveTerminalConnection(
|
||||
const target = resolveTerminalTarget(
|
||||
$selectedTerminalId,
|
||||
$terminalServers ?? [],
|
||||
$settings?.terminalServers ?? [],
|
||||
localStorage.token
|
||||
);
|
||||
const items = await listTerminalSkills(connection, $chatId || null).catch(() => []);
|
||||
localStorage.token, { chatId: $chatId || null, modelId: modelId });
|
||||
const items = await listTerminalSkills(target).catch(() => []);
|
||||
terminalSkills.set(items);
|
||||
const q = query.trim().toLowerCase();
|
||||
return q
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
<script lang="ts">
|
||||
export let modelId: string | null = null;
|
||||
import { resolveLocalizedResource } from '$lib/utils/localizedContent';
|
||||
import { getContext, onDestroy } from 'svelte';
|
||||
import { getPrompts } from '$lib/apis/prompts';
|
||||
import { getSkillItems } from '$lib/apis/skills';
|
||||
import {
|
||||
listTerminalSkills,
|
||||
resolveTerminalConnection,
|
||||
resolveTerminalTarget,
|
||||
type TerminalSkill
|
||||
} from '$lib/apis/terminal';
|
||||
import {
|
||||
@@ -122,13 +123,12 @@
|
||||
});
|
||||
|
||||
const getTerminalItems = async (query = ''): Promise<TerminalSkill[]> => {
|
||||
const connection = resolveTerminalConnection(
|
||||
const target = resolveTerminalTarget(
|
||||
$selectedTerminalId,
|
||||
$terminalServers ?? [],
|
||||
$settings?.terminalServers ?? [],
|
||||
localStorage.token
|
||||
);
|
||||
const items = await listTerminalSkills(connection, $chatId || null).catch(() => []);
|
||||
localStorage.token, { chatId: $chatId || null, modelId: modelId });
|
||||
const items = await listTerminalSkills(target).catch(() => []);
|
||||
terminalSkills.set(items);
|
||||
const q = query.trim().toLowerCase();
|
||||
return q
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
import { getSkills } from '$lib/apis/skills';
|
||||
import {
|
||||
listTerminalSkills,
|
||||
resolveTerminalConnection,
|
||||
resolveTerminalTarget,
|
||||
type TerminalSkill
|
||||
} from '$lib/apis/terminal';
|
||||
|
||||
@@ -188,13 +188,12 @@
|
||||
};
|
||||
|
||||
const getTerminalSkillItems = async (): Promise<TerminalSkill[]> => {
|
||||
const connection = resolveTerminalConnection(
|
||||
const target = resolveTerminalTarget(
|
||||
$selectedTerminalId,
|
||||
$terminalServers ?? [],
|
||||
$settings?.terminalServers ?? [],
|
||||
localStorage.token
|
||||
);
|
||||
const items = await listTerminalSkills(connection, $chatId || null).catch(() => []);
|
||||
localStorage.token, { chatId: $chatId || null, modelId: selectedModels[0] ?? null });
|
||||
const items = await listTerminalSkills(target).catch(() => []);
|
||||
terminalSkills.set(items);
|
||||
return items;
|
||||
};
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
<script lang="ts">
|
||||
export let modelId: string | null = null;
|
||||
import { getContext, tick } from 'svelte';
|
||||
import { resolveTerminalConnection, type TerminalConnection } from '$lib/apis/terminal';
|
||||
import { resolveTerminalTarget, type TerminalTarget } from '$lib/apis/terminal';
|
||||
import UserTerminalsModal from '../UserTerminalsModal.svelte';
|
||||
import { updateChatById } from '$lib/apis/chats';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import TerminalSystemInfoModal from '../TerminalSystemInfoModal.svelte';
|
||||
@@ -36,23 +38,21 @@
|
||||
export let chatId: string | null = null;
|
||||
export let terminalContext: TerminalContext | null = null;
|
||||
|
||||
const chatContext = (terminal: any) => terminal?.contexts?.chat ?? {};
|
||||
|
||||
$: systemTerminals = ($terminalServers ?? []).filter(
|
||||
(t) =>
|
||||
t.id &&
|
||||
chatContext(t) !== false &&
|
||||
!(
|
||||
($temporaryChatEnabled || isTemporaryChatId($activeChatId)) &&
|
||||
chatContext(t)?.context_id === 'chat_id'
|
||||
t.scope === 'chat'
|
||||
)
|
||||
);
|
||||
// Tether presences are the user's own paired devices, listed apart from servers.
|
||||
const isDevice = (terminal: any) => terminal.id.startsWith('tether:');
|
||||
$: systemSections = [
|
||||
{ devices: false, terminals: systemTerminals.filter((t) => !isDevice(t)) },
|
||||
{ devices: true, terminals: systemTerminals.filter(isDevice) }
|
||||
].filter((section) => section.terminals.length > 0);
|
||||
{ devices: false, managed: true, terminals: systemTerminals.filter((t) => !isDevice(t)) },
|
||||
{ devices: true, managed: false, terminals: systemTerminals.filter(isDevice) }
|
||||
].filter((section) => !section.devices || section.terminals.length > 0);
|
||||
$: directTerminals = (
|
||||
$config?.features?.enable_direct_integrations &&
|
||||
($user?.role === 'admin' || ($user?.permissions?.features?.direct_tool_servers ?? true))
|
||||
@@ -132,14 +132,13 @@
|
||||
show = false;
|
||||
};
|
||||
|
||||
$: selectedSystemTerminal = systemTerminals.find((t) => t.id === $selectedTerminalId);
|
||||
$: selectedSystemTerminal = systemTerminals.find((t) => (!!$selectedTerminalId && t.id === $selectedTerminalId));
|
||||
$: selectedDirectTerminal = directTerminals.find((t) => t.url === $selectedTerminalId);
|
||||
$: folderConnection = resolveTerminalConnection(
|
||||
$: folderTarget = resolveTerminalTarget(
|
||||
$selectedTerminalId,
|
||||
systemTerminals,
|
||||
directTerminals,
|
||||
''
|
||||
);
|
||||
'', { chatId: $activeChatId || null, modelId: modelId });
|
||||
$: selectedDevice = !!selectedSystemTerminal && isDevice(selectedSystemTerminal);
|
||||
|
||||
$: selectedLabel =
|
||||
@@ -147,9 +146,10 @@
|
||||
selectedSystemTerminal?.id ||
|
||||
selectedDirectTerminal?.name ||
|
||||
selectedDirectTerminal?.url?.replace(/^https?:\/\//, '') ||
|
||||
$i18n.t('Terminal');
|
||||
($selectedTerminalId ? $i18n.t('Unavailable terminal') : $i18n.t('Terminal'));
|
||||
$: if (disabled && show) show = false;
|
||||
|
||||
let showTerminals = false;
|
||||
async function saveSelection(id: string | null) {
|
||||
if (isSavedChatId(chatId)) {
|
||||
try {
|
||||
@@ -164,32 +164,33 @@
|
||||
}
|
||||
return true;
|
||||
}
|
||||
let info: { connection: TerminalConnection; chatId: string | null; label: string } | null = null;
|
||||
async function selectTerminal(id: string) {
|
||||
if (await saveSelection(id)) selectedTerminalId.set(id);
|
||||
}
|
||||
let info: { target: TerminalTarget; label: string } | null = null;
|
||||
const openInfo = async (selector: string, label: string) => {
|
||||
if (
|
||||
chatContext(systemTerminals.find((t) => t.id === selector))?.context_id === 'chat_id' &&
|
||||
systemTerminals.find((t) => (!!selector && t.id === selector))?.scope === 'chat' &&
|
||||
!isSavedChatId($activeChatId)
|
||||
)
|
||||
return;
|
||||
const connection = resolveTerminalConnection(
|
||||
const target = resolveTerminalTarget(
|
||||
selector,
|
||||
systemTerminals,
|
||||
directTerminals,
|
||||
localStorage.token ?? ''
|
||||
);
|
||||
if (!connection) return;
|
||||
const chatId = $activeChatId;
|
||||
localStorage.token ?? '', { chatId: $activeChatId || null, modelId: modelId });
|
||||
if (!target) return;
|
||||
show = false;
|
||||
await tick();
|
||||
info = { connection, chatId, label };
|
||||
info = { target, label };
|
||||
};
|
||||
$: if (
|
||||
!$config?.features?.enable_tool_servers ||
|
||||
(info &&
|
||||
(info.chatId !== $activeChatId ||
|
||||
(info.connection.system
|
||||
? !systemTerminals.some((t) => t.id === info?.connection.selector)
|
||||
: !directTerminals.some((t) => t.url === info?.connection.selector))))
|
||||
(info.target.context.chatId !== $activeChatId ||
|
||||
(info.target.system
|
||||
? !systemTerminals.some((t) => t.id === info?.target.selector)
|
||||
: !directTerminals.some((t) => t.url === info?.target.selector))))
|
||||
)
|
||||
info = null;
|
||||
|
||||
@@ -287,7 +288,7 @@
|
||||
|
||||
{#each directTerminals as terminal}
|
||||
<div
|
||||
class="group/instance relative rounded-xl hover:bg-gray-50/40 dark:hover:bg-gray-800/40"
|
||||
class="group/terminal relative rounded-xl hover:bg-gray-50/40 dark:hover:bg-gray-800/40"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@@ -328,7 +329,7 @@
|
||||
<div
|
||||
class="absolute inset-y-0 {$selectedTerminalId === terminal.url
|
||||
? 'right-6'
|
||||
: 'right-1'} flex items-center opacity-0 pointer-events-none transition-opacity group-hover/instance:opacity-100 group-hover/instance:pointer-events-auto group-focus-within/instance:opacity-100 group-focus-within/instance:pointer-events-auto"
|
||||
: 'right-1'} flex items-center opacity-0 pointer-events-none transition-opacity group-hover/terminal:opacity-100 group-hover/terminal:pointer-events-auto group-focus-within/terminal:opacity-100 group-focus-within/terminal:pointer-events-auto"
|
||||
>
|
||||
<Tooltip content={$i18n.t('System info')} placement="top">
|
||||
<button
|
||||
@@ -355,9 +356,36 @@
|
||||
<span
|
||||
class="text-[0.625rem] font-normal text-gray-400 dark:text-gray-500 uppercase tracking-wider"
|
||||
>
|
||||
{section.devices ? $i18n.t('Your devices') : $i18n.t('System')}
|
||||
{section.devices
|
||||
? $i18n.t('Your devices')
|
||||
: section.managed
|
||||
? $i18n.t('Terminals')
|
||||
: $i18n.t('System')}
|
||||
</span>
|
||||
{#if !section.devices && $user?.role === 'admin'}
|
||||
{#if section.managed}
|
||||
<Tooltip content={$i18n.t('Manage terminals')} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={$i18n.t('Manage terminals')}
|
||||
class="p-0.5 rounded-md text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 transition"
|
||||
on:click|stopPropagation={() => {
|
||||
show = false;
|
||||
showTerminals = true;
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
class="size-3.5"
|
||||
>
|
||||
<path
|
||||
d="M10.75 4.75a.75.75 0 00-1.5 0v4.5h-4.5a.75.75 0 000 1.5h4.5v4.5a.75.75 0 001.5 0v-4.5h4.5a.75.75 0 000-1.5h-4.5v-4.5z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</Tooltip>
|
||||
{:else if !section.devices && $user?.role === 'admin'}
|
||||
<Tooltip content={$i18n.t('Add Terminal')} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
@@ -385,7 +413,7 @@
|
||||
|
||||
{#each section.terminals as terminal}
|
||||
<div
|
||||
class="group/instance relative rounded-xl hover:bg-gray-50/40 dark:hover:bg-gray-800/40"
|
||||
class="group/terminal relative rounded-xl hover:bg-gray-50/40 dark:hover:bg-gray-800/40"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@@ -425,11 +453,11 @@
|
||||
</div>
|
||||
{/if}
|
||||
</button>
|
||||
{#if chatContext(terminal)?.context_id !== 'chat_id' || isSavedChatId($activeChatId)}
|
||||
{#if terminal.scope !== 'chat' || isSavedChatId($activeChatId)}
|
||||
<div
|
||||
class="absolute inset-y-0 {$selectedTerminalId === terminal.id
|
||||
? 'right-6'
|
||||
: 'right-1'} flex items-center opacity-0 pointer-events-none transition-opacity group-hover/instance:opacity-100 group-hover/instance:pointer-events-auto group-focus-within/instance:opacity-100 group-focus-within/instance:pointer-events-auto"
|
||||
: 'right-1'} flex items-center opacity-0 pointer-events-none transition-opacity group-hover/terminal:opacity-100 group-hover/terminal:pointer-events-auto group-focus-within/terminal:opacity-100 group-focus-within/terminal:pointer-events-auto"
|
||||
>
|
||||
<Tooltip content={$i18n.t('System info')} placement="top">
|
||||
<button
|
||||
@@ -446,6 +474,15 @@
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center h-[1.6875rem] px-2 text-[0.8125rem] text-gray-500 rounded-xl hover:bg-gray-50/40 dark:hover:bg-gray-800/40"
|
||||
on:click={() => {
|
||||
show = false;
|
||||
showTerminals = true;
|
||||
}}>{$i18n.t('New terminal')}</button
|
||||
>
|
||||
{/each}
|
||||
{/each}
|
||||
</DropdownMenu>
|
||||
@@ -457,19 +494,18 @@
|
||||
{#if info}
|
||||
{#key info}
|
||||
<TerminalSystemInfoModal
|
||||
connection={info.connection}
|
||||
chatId={info.chatId}
|
||||
target={info.target}
|
||||
label={info.label}
|
||||
onClose={() => (info = null)}
|
||||
/>
|
||||
{/key}
|
||||
{/if}
|
||||
|
||||
{#if folderConnection && (chatContext(selectedSystemTerminal)?.context_id !== 'chat_id' || isSavedChatId(chatId))}
|
||||
{#key `${$user?.id}:${folderConnection.selector}:${chatId ?? ''}`}
|
||||
{#if folderTarget && (selectedSystemTerminal?.scope !== 'chat' || isSavedChatId(chatId))}
|
||||
{#key `${$user?.id}:${folderTarget.selector}:${chatId ?? ''}`}
|
||||
<WorkingDirectoryMenu
|
||||
{inMenu}
|
||||
connection={folderConnection}
|
||||
target={folderTarget}
|
||||
{chatId}
|
||||
userId={$user?.id ?? ''}
|
||||
bind:terminalContext
|
||||
@@ -482,3 +518,12 @@
|
||||
/>
|
||||
{/key}
|
||||
{/if}
|
||||
|
||||
{#if showTerminals}
|
||||
<UserTerminalsModal {modelId}
|
||||
bind:show={showTerminals}
|
||||
{chatId}
|
||||
selected={$selectedTerminalId}
|
||||
onSelect={selectTerminal}
|
||||
/>
|
||||
{/if}
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { getContext, onMount, onDestroy } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { getCwd, setCwd, type TerminalConnection } from '$lib/apis/terminal';
|
||||
import { getCwd, setCwd, type TerminalTarget } from '$lib/apis/terminal';
|
||||
import { loadRecentFolders, rememberRecentFolder } from '$lib/apis/terminal/recentFolders';
|
||||
import { selectedFolder, showFileNav } from '$lib/stores';
|
||||
import type { TerminalContext } from '$lib/types';
|
||||
@@ -18,7 +18,7 @@
|
||||
import FileNav from '../FileNav.svelte';
|
||||
|
||||
const i18n = getContext<any>('i18n');
|
||||
export let connection: TerminalConnection;
|
||||
export let target: TerminalTarget;
|
||||
export let chatId: string | null = null;
|
||||
export let userId: string;
|
||||
export let terminalContext: TerminalContext | null = null;
|
||||
@@ -40,7 +40,7 @@
|
||||
const folderName = (path: string) => path.replace(/\/+$/, '').split('/').pop() || '/';
|
||||
const normalize = (path: string) => path.replace(/\/+$/, '') || '/';
|
||||
|
||||
$: if (terminalContext?.terminalId === connection.selector)
|
||||
$: if (terminalContext?.terminalId === target.selector)
|
||||
cwd = terminalContext.currentDirectory;
|
||||
$: directory = cwd;
|
||||
$: options = [...new Set([directory, ...recent].filter(Boolean).map(normalize))].filter((path) =>
|
||||
@@ -55,12 +55,12 @@
|
||||
await initialization;
|
||||
if (disposed) return;
|
||||
if (!home) {
|
||||
const result = await getCwd(connection.baseUrl, connection.key, chatId ?? undefined);
|
||||
const result = await getCwd(target);
|
||||
if (disposed) return;
|
||||
home = result?.home ?? '';
|
||||
}
|
||||
if (!home) throw new Error('Terminal home is unavailable');
|
||||
const paths = await loadRecentFolders(connection, chatId, home, userId);
|
||||
const paths = await loadRecentFolders(target, home, userId);
|
||||
if (disposed || version !== historyVersion) return;
|
||||
recent = paths;
|
||||
historyError = '';
|
||||
@@ -71,19 +71,19 @@
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
if (!chatId && terminalContext?.terminalId !== connection.selector) {
|
||||
if (!chatId && terminalContext?.terminalId !== target.selector) {
|
||||
terminalContext = {
|
||||
terminalId: connection.selector,
|
||||
terminalId: target.selector,
|
||||
currentDirectory:
|
||||
$selectedFolder?.data?.terminal_id === connection.selector
|
||||
$selectedFolder?.data?.terminal_id === target.selector
|
||||
? ($selectedFolder.data.working_directory ?? '')
|
||||
: ''
|
||||
};
|
||||
}
|
||||
const selectedContext =
|
||||
terminalContext?.terminalId === connection.selector ? terminalContext : null;
|
||||
terminalContext?.terminalId === target.selector ? terminalContext : null;
|
||||
if (selectedContext) cwd = selectedContext.currentDirectory;
|
||||
initialization = getCwd(connection.baseUrl, connection.key, chatId ?? undefined).then(
|
||||
initialization = getCwd(target).then(
|
||||
(result) => {
|
||||
if (disposed) return;
|
||||
home = result?.home ?? '';
|
||||
@@ -100,7 +100,7 @@
|
||||
saving = true;
|
||||
// A draft has no terminal session yet; submission applies this choice after creating the chat.
|
||||
const result = chatId
|
||||
? await setCwd(connection.baseUrl, connection.key, path, chatId)
|
||||
? await setCwd(target, path)
|
||||
: { cwd: path || home };
|
||||
if (disposed) return;
|
||||
if (!result?.cwd) {
|
||||
@@ -110,7 +110,7 @@
|
||||
}
|
||||
// An empty path resets the terminal to its default directory.
|
||||
cwd = path ? result.cwd : '';
|
||||
terminalContext = { terminalId: connection.selector, currentDirectory: cwd };
|
||||
terminalContext = { terminalId: target.selector, currentDirectory: cwd };
|
||||
try {
|
||||
await onSelect(cwd);
|
||||
} catch (error) {
|
||||
@@ -129,7 +129,7 @@
|
||||
try {
|
||||
await initialization;
|
||||
if (disposed) return;
|
||||
await rememberRecentFolder(connection, chatId, home, userId, cwd);
|
||||
await rememberRecentFolder(target, home, userId, cwd);
|
||||
if (disposed) return;
|
||||
historyError = '';
|
||||
} catch {
|
||||
@@ -253,7 +253,7 @@
|
||||
on:click|stopPropagation={() => {
|
||||
show = false;
|
||||
showFileNav.set({
|
||||
terminalId: connection.selector,
|
||||
terminalId: target.selector,
|
||||
directory: path,
|
||||
chatId
|
||||
});
|
||||
@@ -299,7 +299,7 @@
|
||||
</div>
|
||||
<div class="h-[60dvh] min-h-0" aria-busy={saving}>
|
||||
<FileNav
|
||||
terminalId={connection.selector}
|
||||
terminalId={target.selector}
|
||||
{chatId}
|
||||
initialDirectory={directory || null}
|
||||
manageFileRequests={false}
|
||||
|
||||
@@ -203,7 +203,7 @@
|
||||
</ConsecutiveDetailsGroup>
|
||||
{:else if displayItem.type === 'file'}
|
||||
{#if displayItem.item?.displayed || $settings?.terminalFileDisplay === 'inline'}
|
||||
<ToolOutputFile item={displayItem.item} {chatId} />
|
||||
<ToolOutputFile item={displayItem.item} {chatId} modelId={model?.id ?? null} />
|
||||
{/if}
|
||||
{:else if displayItem.type === 'context_compaction'}
|
||||
<ContextCompactionLabel summary={displayItem.summary} {compactPreview} />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { resolveTerminalTarget, type TerminalTarget } from '$lib/apis/terminal';
|
||||
// Keep keys in nested template expressions visible to i18next-parser.
|
||||
// $i18n.t("Terminal unavailable");
|
||||
// $i18n.t("No preview available");
|
||||
@@ -23,6 +24,7 @@
|
||||
|
||||
export let item: any;
|
||||
export let chatId = '';
|
||||
export let modelId: string | null = null;
|
||||
|
||||
const i18n = getContext<Writable<i18nType>>('i18n');
|
||||
|
||||
@@ -64,14 +66,9 @@
|
||||
$: selector = item?.terminal_selector;
|
||||
$: terminal = resolveTerminal();
|
||||
$: unavailable = !terminal && !fileId;
|
||||
$: previewKey = fileId || (terminal ? `${terminal.url}|${terminal.key}|${path}|${chatId}` : '');
|
||||
$: isPerChatTerminal =
|
||||
($terminalServers ?? []).find((server: any) => server.id === selector)?.contexts?.chat
|
||||
?.context_id === 'chat_id';
|
||||
$: previewBaseUrl =
|
||||
terminal && isPerChatTerminal && chatId
|
||||
? `${terminal.url}/chats/${encodeURIComponent(chatId)}`
|
||||
: (terminal?.url ?? '');
|
||||
$: previewKey =
|
||||
fileId || (terminal ? `${terminal.baseUrl}|${terminal.key}|${path}|${chatId}` : '');
|
||||
|
||||
$: previewClass = isImage(path)
|
||||
? 'h-[22rem]'
|
||||
: isPdf(path) ||
|
||||
@@ -96,22 +93,15 @@
|
||||
|
||||
const t = (key: string, vars?: Record<string, unknown>) => $i18n?.t?.(key, vars) ?? key;
|
||||
|
||||
function resolveTerminal(): { url: string; key: string } | null {
|
||||
function resolveTerminal(): TerminalTarget | null {
|
||||
if (!selector || $selectedTerminalId !== selector) return null;
|
||||
|
||||
const systemTerminal = ($terminalServers ?? []).find((server: any) => server.id === selector);
|
||||
if (systemTerminal?.url) {
|
||||
return { url: systemTerminal.url, key: localStorage.token };
|
||||
}
|
||||
|
||||
const directTerminal = (($settings as any)?.terminalServers ?? []).find(
|
||||
(server: any) => server.url === selector && server.enabled
|
||||
return resolveTerminalTarget(
|
||||
selector,
|
||||
$terminalServers ?? [],
|
||||
(($settings as any)?.terminalServers ?? []).filter((server: any) => server.enabled),
|
||||
localStorage.token,
|
||||
{ chatId: chatId, modelId: item?.model_id ?? modelId }
|
||||
);
|
||||
if (directTerminal?.url) {
|
||||
return { url: directTerminal.url, key: directTerminal.key ?? '' };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function clearPreview() {
|
||||
@@ -141,7 +131,7 @@
|
||||
: null;
|
||||
}
|
||||
if (!terminal) return null;
|
||||
return downloadFileBlob(terminal.url, terminal.key, path, chatId || undefined);
|
||||
return downloadFileBlob(terminal, path);
|
||||
}
|
||||
|
||||
async function loadExcelSheet(sheet: string) {
|
||||
@@ -187,7 +177,7 @@
|
||||
fileSqliteData = arrayBuffer;
|
||||
} else if (ext === 'docx') {
|
||||
const preview = terminal
|
||||
? await downloadFilePreview(terminal.url, terminal.key, path, chatId || undefined)
|
||||
? await downloadFilePreview(terminal, path)
|
||||
: null;
|
||||
if (preview) {
|
||||
filePdfData = await preview.blob.arrayBuffer();
|
||||
@@ -208,7 +198,7 @@
|
||||
}
|
||||
} else if (ext === 'pptx') {
|
||||
const preview = terminal
|
||||
? await downloadFilePreview(terminal.url, terminal.key, path, chatId || undefined)
|
||||
? await downloadFilePreview(terminal, path)
|
||||
: null;
|
||||
if (preview) {
|
||||
filePdfData = await preview.blob.arrayBuffer();
|
||||
@@ -226,7 +216,7 @@
|
||||
if (!result) throw new Error(t('Preview failed'));
|
||||
fileContent = await result.blob.text();
|
||||
} else if (terminal) {
|
||||
fileContent = await readFile(terminal.url, terminal.key, path, chatId || undefined);
|
||||
fileContent = await readFile(terminal, path);
|
||||
}
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : t('Preview failed');
|
||||
@@ -326,9 +316,8 @@
|
||||
{fileModelData}
|
||||
{fileDocxData}
|
||||
{fileContent}
|
||||
baseUrl={fileId ? '' : previewBaseUrl}
|
||||
target={fileId ? null : terminal}
|
||||
{chatId}
|
||||
apiKey={terminal?.key ?? ''}
|
||||
{fileOfficeHtml}
|
||||
{fileOfficeSlides}
|
||||
{currentSlide}
|
||||
|
||||
@@ -166,6 +166,11 @@
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
{#if shareMode === 'continue'}
|
||||
<p class="mb-3 text-xs text-gray-500">
|
||||
{$i18n.t('People who can reply can also use this chat’s own terminal.')}
|
||||
</p>
|
||||
{/if}
|
||||
<AccessControl
|
||||
bind:accessGrants
|
||||
accessRoles={['read']}
|
||||
|
||||
+156
-106
@@ -77,10 +77,10 @@
|
||||
type PanelTab
|
||||
} from './Tabs/tabs';
|
||||
import {
|
||||
resolveTerminalConnection,
|
||||
resolveTerminalTarget,
|
||||
terminalRequest,
|
||||
TerminalRequestError,
|
||||
type TerminalConnection
|
||||
type TerminalTarget
|
||||
} from '$lib/apis/terminal';
|
||||
import { formatChord, keybindings, matchKeybinding, Shortcut } from '$lib/shortcuts';
|
||||
import HotkeyHint from '../common/HotkeyHint.svelte';
|
||||
@@ -305,6 +305,7 @@
|
||||
...tab,
|
||||
label: $i18n.t('Files'),
|
||||
terminalId: selector,
|
||||
target: undefined,
|
||||
path: undefined,
|
||||
directory: undefined
|
||||
}
|
||||
@@ -323,7 +324,7 @@
|
||||
tabsChatId = undefined;
|
||||
clearChatViews();
|
||||
}
|
||||
const captureConnections = (..._connections: unknown[]) => {
|
||||
const captureTargets = (..._connections: unknown[]) => {
|
||||
captureView();
|
||||
// A returning component must read disk before restoring its cached draft.
|
||||
for (const tab of tabs.tabs) {
|
||||
@@ -331,21 +332,24 @@
|
||||
}
|
||||
dirtyFiles = { ...dirtyFiles };
|
||||
};
|
||||
$: if (mounted && viewReady) captureConnections($terminalServers, $settings, $config, $user);
|
||||
const tabConnection = (tab: PanelTab) =>
|
||||
tab.terminalId && terminalAccessible(tab.terminalId)
|
||||
? resolveTerminalConnection(
|
||||
tab.terminalId,
|
||||
$terminalServers ?? [],
|
||||
directTerminals,
|
||||
localStorage.token ?? ''
|
||||
)
|
||||
: null;
|
||||
$: if (mounted && viewReady) captureTargets($terminalServers, $settings, $config, $user);
|
||||
const tabTarget = (tab: PanelTab) => {
|
||||
if (!tab.terminalId || !terminalAccessible(tab.terminalId)) return null;
|
||||
const target = resolveTerminalTarget(
|
||||
tab.terminalId,
|
||||
$terminalServers ?? [],
|
||||
directTerminals,
|
||||
localStorage.token ?? '',
|
||||
tab.target?.context ?? { chatId, modelId: modelId ?? null }
|
||||
);
|
||||
if (target) tab.target = target;
|
||||
return target;
|
||||
};
|
||||
const startSession = (owner: NonNullable<typeof viewEntry>, tab: PanelTab) => {
|
||||
const connection = tabConnection(tab);
|
||||
if (connection) {
|
||||
const target = tabTarget(tab);
|
||||
if (target) {
|
||||
delete sessionFailures[tab.id];
|
||||
void createViewSession(owner, tab.id, connection);
|
||||
void createViewSession(owner, tab.id, target);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -367,11 +371,11 @@
|
||||
let hasOpenedTabs = false;
|
||||
let commentTarget: { comment_id?: string } = {};
|
||||
let closing = new Set<string>();
|
||||
let selectedConnection: TerminalConnection | null = null;
|
||||
let selectedTarget: TerminalTarget | null = null;
|
||||
let showQuickOpen = false;
|
||||
let voiceNote: VoiceNote;
|
||||
let voiceNoteTarget: {
|
||||
connection: TerminalConnection;
|
||||
target: TerminalTarget;
|
||||
chatId: string | null;
|
||||
directory?: string;
|
||||
} | null = null;
|
||||
@@ -382,12 +386,12 @@
|
||||
voiceNote?.finishRecording();
|
||||
return;
|
||||
}
|
||||
if (!canVoiceNote || !selectedConnection || !$user) return;
|
||||
if (!canVoiceNote || !selectedTarget || !$user) return;
|
||||
voiceNoteTarget = {
|
||||
connection: selectedConnection,
|
||||
target: selectedTarget,
|
||||
chatId,
|
||||
directory:
|
||||
activeFileContext?.terminalId === selectedConnection.selector
|
||||
activeFileContext?.terminalId === selectedTarget.selector
|
||||
? activeFileContext.currentDirectory
|
||||
: undefined
|
||||
};
|
||||
@@ -503,6 +507,18 @@
|
||||
const openPanel = (tab: PanelTab, inSidePanel = false) => {
|
||||
if (!viewReady || !viewEntry) return;
|
||||
hasOpenedTabs = true;
|
||||
if (tab.terminalId) {
|
||||
const target =
|
||||
tab.target ??
|
||||
resolveTerminalTarget(
|
||||
tab.terminalId,
|
||||
$terminalServers ?? [],
|
||||
directTerminals,
|
||||
localStorage.token,
|
||||
{ chatId: chatId, modelId: modelId ?? null }
|
||||
);
|
||||
tab = { ...tab, target: target ?? undefined };
|
||||
}
|
||||
tabs = inSidePanel ? openTabInSidePanel(tabs, tab) : openTab(tabs, tab);
|
||||
changeChatView(viewEntry, { ...viewEntry.state, panels: tabs });
|
||||
showTabs.set(true);
|
||||
@@ -557,17 +573,36 @@
|
||||
openPageTab(request);
|
||||
}
|
||||
|
||||
const openFiles = (selector = $selectedTerminalId, directory?: string, newTab = false) => {
|
||||
const openFiles = (
|
||||
selector = $selectedTerminalId,
|
||||
directory?: string,
|
||||
newTab = false,
|
||||
sourceModelId = modelId
|
||||
) => {
|
||||
if (selector ? !terminalAccessible(selector) : !showFilesTab) return;
|
||||
const target = resolveTerminalTarget(
|
||||
selector,
|
||||
$terminalServers ?? [],
|
||||
directTerminals,
|
||||
localStorage.token,
|
||||
{ chatId: chatId, modelId: sourceModelId ?? null }
|
||||
);
|
||||
const pinnedModel = target?.context.modelId ?? null;
|
||||
const existing = newTab
|
||||
? undefined
|
||||
: (tabs.tabs.find(
|
||||
(tab) =>
|
||||
tab.id === tabs.activeId &&
|
||||
tab.kind === 'files' &&
|
||||
(tab.terminalId ?? null) === selector
|
||||
(tab.terminalId ?? null) === selector &&
|
||||
(tab.target?.context.modelId ?? null) === pinnedModel
|
||||
) ??
|
||||
tabs.tabs.find((tab) => tab.kind === 'files' && (tab.terminalId ?? null) === selector));
|
||||
tabs.tabs.find(
|
||||
(tab) =>
|
||||
tab.kind === 'files' &&
|
||||
(tab.terminalId ?? null) === selector &&
|
||||
(tab.target?.context.modelId ?? null) === pinnedModel
|
||||
));
|
||||
if (!existing && terminalContext?.terminalId === selector)
|
||||
directory ??= terminalContext.currentDirectory || undefined;
|
||||
const id = existing?.id ?? uuidv4();
|
||||
@@ -576,6 +611,7 @@
|
||||
kind: 'files',
|
||||
label: $i18n.t('Files'),
|
||||
terminalId: selector ?? undefined,
|
||||
target: target ?? undefined,
|
||||
path: directory
|
||||
});
|
||||
const view = fileViews[id];
|
||||
@@ -586,37 +622,55 @@
|
||||
)
|
||||
void view.browseDirectory(directory);
|
||||
};
|
||||
const openFile = (path: string, selector: string, page?: number | null) => {
|
||||
const openFile = (
|
||||
path: string,
|
||||
selector: string,
|
||||
page?: number | null,
|
||||
sourceModelId = modelId
|
||||
) => {
|
||||
if (!terminalAccessible(selector)) return;
|
||||
const target = resolveTerminalTarget(
|
||||
selector,
|
||||
$terminalServers ?? [],
|
||||
directTerminals,
|
||||
localStorage.token,
|
||||
{ chatId: chatId, modelId: sourceModelId ?? null }
|
||||
);
|
||||
const pinnedModel = target?.context.modelId ?? null;
|
||||
path = path.replace(/\\/g, '/').replace(/\/{2,}/g, '/');
|
||||
const id =
|
||||
tabs.tabs.find(
|
||||
(tab) =>
|
||||
tab.kind === 'file' && !tab.untitled && tab.terminalId === selector && tab.path === path
|
||||
)?.id ?? fileTabId(selector, path);
|
||||
tab.kind === 'file' &&
|
||||
!tab.untitled &&
|
||||
tab.terminalId === selector &&
|
||||
(tab.target?.context.modelId ?? null) === pinnedModel &&
|
||||
tab.path === path
|
||||
)?.id ?? fileTabId(JSON.stringify([selector, pinnedModel]), path);
|
||||
openPanel({
|
||||
id,
|
||||
kind: 'file',
|
||||
label: path.split('/').pop() || path,
|
||||
terminalId: selector,
|
||||
target: target ?? undefined,
|
||||
path,
|
||||
page
|
||||
});
|
||||
if (page != null) fileViews[id]?.revealPage?.(page);
|
||||
};
|
||||
const newFile = () => {
|
||||
if (!terminalFilesAvailable || !selectedConnection) return;
|
||||
if (!terminalFilesAvailable || !selectedTarget) return;
|
||||
let number = 1;
|
||||
while (tabs.tabs.some((tab) => tab.untitled && tab.label === `Untitled-${number}`)) number++;
|
||||
openPanel({
|
||||
id: uuidv4(),
|
||||
kind: 'file',
|
||||
label: `Untitled-${number}`,
|
||||
terminalId: selectedConnection.selector,
|
||||
connection: { ...selectedConnection },
|
||||
terminalId: selectedTarget.selector,
|
||||
target: { ...selectedTarget },
|
||||
untitled: true,
|
||||
context:
|
||||
activeFileContext?.terminalId === selectedConnection.selector
|
||||
activeFileContext?.terminalId === selectedTarget.selector
|
||||
? activeFileContext
|
||||
: undefined
|
||||
});
|
||||
@@ -823,7 +877,7 @@
|
||||
dragged = false;
|
||||
};
|
||||
const newTerminal = () => {
|
||||
if (!terminalEnabled || !selectedConnection) return;
|
||||
if (!terminalEnabled || !selectedTarget) return;
|
||||
let terminalNumber = 1;
|
||||
while (
|
||||
tabs.tabs.some((tab) => tab.kind === 'terminal' && tab.terminalNumber === terminalNumber)
|
||||
@@ -836,19 +890,19 @@
|
||||
kind: 'terminal',
|
||||
label: `${$i18n.t('Terminal')} ${terminalNumber}`,
|
||||
terminalNumber,
|
||||
terminalId: selectedConnection.selector,
|
||||
connection: { ...selectedConnection }
|
||||
terminalId: selectedTarget.selector,
|
||||
target: { ...selectedTarget }
|
||||
});
|
||||
if (viewEntry && viewReady) startSession(viewEntry, tabs.tabs.find((tab) => tab.id === id)!);
|
||||
};
|
||||
const openDesktop = () => {
|
||||
if (!desktopEnabled || !selectedConnection) return;
|
||||
if (!desktopEnabled || !selectedTarget) return;
|
||||
openPanel({
|
||||
id: JSON.stringify(['desktop', selectedConnection.selector]),
|
||||
id: JSON.stringify(['desktop', selectedTarget.baseUrl, selectedTarget.context.modelId]),
|
||||
kind: 'desktop',
|
||||
label: $i18n.t('Desktop'),
|
||||
terminalId: selectedConnection.selector,
|
||||
connection: { ...selectedConnection }
|
||||
terminalId: selectedTarget.selector,
|
||||
target: { ...selectedTarget }
|
||||
});
|
||||
};
|
||||
const openBrowser = (
|
||||
@@ -863,27 +917,32 @@
|
||||
const existing =
|
||||
url &&
|
||||
tabs.tabs.find(
|
||||
(tab) => tab.kind === 'browser' && tab.terminalId === selector && tab.path === url
|
||||
(tab) =>
|
||||
tab.kind === 'browser' &&
|
||||
tab.terminalId === selector &&
|
||||
tab.path === url &&
|
||||
(tab.target?.context.modelId ?? null) === (selectedTarget?.context.modelId ?? null)
|
||||
);
|
||||
if (existing) {
|
||||
selectTab(existing.id);
|
||||
return;
|
||||
}
|
||||
const connection = selector
|
||||
? resolveTerminalConnection(
|
||||
const target = selector
|
||||
? resolveTerminalTarget(
|
||||
selector,
|
||||
$terminalServers ?? [],
|
||||
directTerminals,
|
||||
localStorage.token ?? ''
|
||||
localStorage.token ?? '',
|
||||
{ chatId: chatId, modelId: modelId ?? null }
|
||||
)
|
||||
: null;
|
||||
if (!connection) return;
|
||||
if (!target) return;
|
||||
const terminal = ($terminalServers ?? []).find((item) => item.id === selector);
|
||||
const proxyBase =
|
||||
baseUrl ??
|
||||
(connection && chatContextNeedsSavedChat(terminal) && chatId
|
||||
? `${connection.baseUrl}/chats/${encodeURIComponent(chatId)}`
|
||||
: connection?.baseUrl);
|
||||
(target && chatContextNeedsSavedChat(terminal) && chatId
|
||||
? `${target.baseUrl}/chats/${encodeURIComponent(chatId)}`
|
||||
: target?.baseUrl);
|
||||
const id = uuidv4();
|
||||
openPanel({
|
||||
id,
|
||||
@@ -892,7 +951,7 @@
|
||||
path: url,
|
||||
terminalId: selector ?? undefined,
|
||||
browserBaseUrl: proxyBase,
|
||||
connection: connection ?? undefined
|
||||
target: target ?? undefined
|
||||
});
|
||||
if (viewEntry && viewReady) startSession(viewEntry, tabs.tabs.find((tab) => tab.id === id)!);
|
||||
};
|
||||
@@ -907,12 +966,12 @@
|
||||
const tab = owner.state.panels.tabs.find((item) => item.id === id);
|
||||
if (!tab) return;
|
||||
if (tab.kind === 'page' && !(await pageViews[id]?.requestClose() ?? true)) return;
|
||||
const connection =
|
||||
const target =
|
||||
tab.sessionId && (tab.kind === 'terminal' || tab.kind === 'browser')
|
||||
? tabConnection(tab)
|
||||
? tabTarget(tab)
|
||||
: null;
|
||||
if (
|
||||
connection &&
|
||||
target &&
|
||||
tab.kind === 'terminal' &&
|
||||
!(await new Promise<boolean>((resolve) => {
|
||||
stopTerminalChoice = resolve;
|
||||
@@ -942,11 +1001,10 @@
|
||||
await tick();
|
||||
if (owner === viewEntry) document.getElementById(domId(tabs.activeId))?.focus();
|
||||
}
|
||||
if (connection && tab.sessionId) {
|
||||
if (target && tab.sessionId) {
|
||||
try {
|
||||
await terminalRequest(
|
||||
connection,
|
||||
owner.chatId,
|
||||
target,
|
||||
`${tab.kind === 'terminal' ? '/api/terminals' : '/browser/sessions'}/${encodeURIComponent(tab.sessionId)}`,
|
||||
{ method: 'DELETE' }
|
||||
);
|
||||
@@ -1085,16 +1143,12 @@
|
||||
|
||||
$: hasMessages = history?.messages && Object.keys(history.messages).length > 0;
|
||||
|
||||
const chatContext = (terminal: any) => terminal?.contexts?.chat ?? {};
|
||||
const chatContextAvailable = (terminal: any) => chatContext(terminal) !== false;
|
||||
const chatContextNeedsSavedChat = (terminal: any) =>
|
||||
chatContext(terminal)?.context_id === 'chat_id';
|
||||
$: selectedSystemTerminal = ($terminalServers ?? []).find(
|
||||
(t) => t.id && t.id === $selectedTerminalId
|
||||
const chatContextNeedsSavedChat = (terminal: any) => terminal?.scope === 'chat';
|
||||
$: selectedSystemTerminal = ($terminalServers ?? []).find((t) =>
|
||||
(!!$selectedTerminalId && t.id === $selectedTerminalId)
|
||||
);
|
||||
$: selectedSystemTerminalAvailable =
|
||||
selectedSystemTerminal &&
|
||||
chatContextAvailable(selectedSystemTerminal) &&
|
||||
!(chatContextNeedsSavedChat(selectedSystemTerminal) && !isSavedChatId(chatId));
|
||||
$: terminalFilesAvailable = !!(
|
||||
$config?.features?.enable_tool_servers &&
|
||||
@@ -1201,7 +1255,7 @@
|
||||
if (voiceNoteTarget || canVoiceNote) action = openVoiceNote;
|
||||
break;
|
||||
case Shortcut.QUICK_OPEN:
|
||||
if (terminalFilesAvailable && selectedConnection)
|
||||
if (terminalFilesAvailable && selectedTarget)
|
||||
action = () => {
|
||||
showQuickOpen = true;
|
||||
};
|
||||
@@ -1210,7 +1264,7 @@
|
||||
if (showFilesTab) action = () => openFiles();
|
||||
break;
|
||||
case Shortcut.OPEN_DESKTOP:
|
||||
if (desktopEnabled && selectedConnection) action = openDesktop;
|
||||
if (desktopEnabled && selectedTarget) action = openDesktop;
|
||||
break;
|
||||
case Shortcut.NEW_CHAT_TAB:
|
||||
if (canSideChat) action = () => openFeature('side');
|
||||
@@ -1219,13 +1273,13 @@
|
||||
if (showCommentsTab) action = () => openFeature('comments');
|
||||
break;
|
||||
case Shortcut.NEW_FILE:
|
||||
if (terminalFilesAvailable && selectedConnection) action = newFile;
|
||||
if (terminalFilesAvailable && selectedTarget) action = newFile;
|
||||
break;
|
||||
case Shortcut.NEW_TERMINAL:
|
||||
if (terminalEnabled && selectedConnection) action = newTerminal;
|
||||
if (terminalEnabled && selectedTarget) action = newTerminal;
|
||||
break;
|
||||
case Shortcut.NEW_BROWSER:
|
||||
if (browserEnabled && selectedConnection) action = () => openBrowser();
|
||||
if (browserEnabled && selectedTarget) action = () => openBrowser();
|
||||
break;
|
||||
case Shortcut.CLOSE_TAB:
|
||||
if (panelVisible && tabs.activeId)
|
||||
@@ -1261,10 +1315,9 @@
|
||||
($settings as { terminalServers?: { url: string; key?: string }[] })?.terminalServers ?? [];
|
||||
const terminalAccessible = (selector: string) => {
|
||||
if (!$config?.features?.enable_tool_servers) return false;
|
||||
const system = ($terminalServers ?? []).find((terminal) => terminal.id === selector);
|
||||
const system = ($terminalServers ?? []).find((terminal) => (!!selector && terminal.id === selector));
|
||||
if (system)
|
||||
return (
|
||||
chatContextAvailable(system) &&
|
||||
!(chatContextNeedsSavedChat(system) && !isSavedChatId(chatId))
|
||||
);
|
||||
return !!(
|
||||
@@ -1273,13 +1326,14 @@
|
||||
directTerminals.some((terminal) => terminal.url === selector)
|
||||
);
|
||||
};
|
||||
$: selectedConnection =
|
||||
$: selectedTarget =
|
||||
terminalFilesAvailable && mounted
|
||||
? resolveTerminalConnection(
|
||||
? resolveTerminalTarget(
|
||||
$selectedTerminalId,
|
||||
$terminalServers ?? [],
|
||||
directTerminals,
|
||||
localStorage.token ?? ''
|
||||
localStorage.token ?? '',
|
||||
{ chatId: chatId, modelId: modelId ?? null }
|
||||
)
|
||||
: null;
|
||||
const checkTerminal = async () => {
|
||||
@@ -1287,11 +1341,11 @@
|
||||
terminalEnabled = false;
|
||||
desktopEnabled = false;
|
||||
browserEnabled = false;
|
||||
if (!selectedConnection) return;
|
||||
if (!selectedTarget) return;
|
||||
try {
|
||||
const result = await terminalRequest<{
|
||||
features?: { terminal?: boolean; desktop?: boolean; browser?: boolean };
|
||||
}>(selectedConnection, chatId, '/api/config');
|
||||
}>(selectedTarget, '/api/config');
|
||||
if (version === featureVersion) {
|
||||
terminalEnabled = result.features?.terminal !== false;
|
||||
desktopEnabled = result.features?.desktop === true;
|
||||
@@ -1302,7 +1356,7 @@
|
||||
}
|
||||
};
|
||||
$: {
|
||||
selectedConnection;
|
||||
selectedTarget;
|
||||
chatId;
|
||||
void checkTerminal();
|
||||
}
|
||||
@@ -1407,7 +1461,7 @@
|
||||
$: if (
|
||||
$selectedTerminalId &&
|
||||
$terminalServers !== null &&
|
||||
!($terminalServers ?? []).some((t) => t.id && t.id === $selectedTerminalId) &&
|
||||
!($terminalServers ?? []).some((t) => (!!$selectedTerminalId && t.id === $selectedTerminalId)) &&
|
||||
!(
|
||||
$config?.features?.enable_direct_integrations &&
|
||||
($user?.role === 'admin' || ($user?.permissions?.features?.direct_tool_servers ?? true))
|
||||
@@ -1572,19 +1626,19 @@
|
||||
onclose={() => {
|
||||
voiceNoteTarget = null;
|
||||
}}
|
||||
onsaved={(path) => openFile(path, target.connection.selector)}
|
||||
onsaved={(path) => openFile(path, target.target.selector)}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if showQuickOpen && terminalFilesAvailable && selectedConnection}
|
||||
{#key `${selectedConnection.selector}:${chatId}`}
|
||||
{#if showQuickOpen && terminalFilesAvailable && selectedTarget}
|
||||
{#key JSON.stringify([selectedTarget.baseUrl, selectedTarget.context.modelId, chatId])}
|
||||
<QuickOpen
|
||||
connection={selectedConnection}
|
||||
target={selectedTarget}
|
||||
{chatId}
|
||||
onclose={() => {
|
||||
showQuickOpen = false;
|
||||
}}
|
||||
onselect={(path) => openFile(path, selectedConnection!.selector)}
|
||||
onselect={(path) => openFile(path, selectedTarget!.selector)}
|
||||
/>
|
||||
{/key}
|
||||
{/if}
|
||||
@@ -1736,9 +1790,9 @@
|
||||
{/each}
|
||||
{#each (viewReady ? tabs.tabs : []).filter((tab) => tab.kind !== 'chat') as tab (`${viewEntry?.instanceId}:${tab.id}`)}
|
||||
{@const owner = viewEntry!}
|
||||
{@const connection =
|
||||
{@const target =
|
||||
mounted && $config && $user && $settings && $terminalServers !== null
|
||||
? tabConnection(tab)
|
||||
? tabTarget(tab)
|
||||
: null}
|
||||
{@const failure = sessionFailures[tab.id]}
|
||||
<div
|
||||
@@ -1754,7 +1808,7 @@
|
||||
on:focusin={() => focusGroup(tabGroups[tab.id].id)}
|
||||
on:pointerdown={() => focusGroup(tabGroups[tab.id].id)}
|
||||
>
|
||||
{#if tab.terminalId && !connection}
|
||||
{#if tab.terminalId && !target}
|
||||
<div
|
||||
role="status"
|
||||
class="flex h-full items-center justify-center p-4 text-center text-xs text-gray-400 dark:text-gray-500"
|
||||
@@ -1814,9 +1868,9 @@
|
||||
onCountChange={setCommentCount}
|
||||
/>
|
||||
{/key}
|
||||
{:else if tab.kind === 'desktop' && connection}
|
||||
{:else if tab.kind === 'desktop' && target}
|
||||
<Desktop
|
||||
connection={connection!}
|
||||
target={target!}
|
||||
chatId={owner.chatId}
|
||||
active={panelVisible && visibleTabIds.has(tab.id)}
|
||||
overlay={dragged}
|
||||
@@ -1866,8 +1920,7 @@
|
||||
{#if tab.kind === 'terminal'}
|
||||
<XTerminal
|
||||
bind:this={terminalViews[tab.id]}
|
||||
connection={connection!}
|
||||
chatId={owner.chatId}
|
||||
target={target!}
|
||||
sessionId={tab.sessionId}
|
||||
active={panelVisible && visibleTabIds.has(tab.id)}
|
||||
overlay={dragged}
|
||||
@@ -1879,8 +1932,7 @@
|
||||
{:else}
|
||||
<Browser
|
||||
bind:this={browserViews[tab.id]}
|
||||
{connection}
|
||||
chatId={owner.chatId}
|
||||
{target}
|
||||
sessionId={tab.sessionId}
|
||||
active={panelVisible && visibleTabIds.has(tab.id)}
|
||||
overlay={dragged}
|
||||
@@ -1894,14 +1946,13 @@
|
||||
{/if}
|
||||
{/key}
|
||||
{/if}
|
||||
{:else if tab.untitled && connection}
|
||||
{:else if tab.untitled && target}
|
||||
<UntitledFile
|
||||
initialView={owner.drafts.get(tab.id)}
|
||||
bind:this={fileViews[tab.id]}
|
||||
bind:dirty={dirtyFiles[tab.id]}
|
||||
label={tab.label}
|
||||
connection={connection!}
|
||||
chatId={owner.chatId}
|
||||
target={target!}
|
||||
initialDirectory={tab.context?.currentDirectory}
|
||||
isOpen={(path) =>
|
||||
tabs.tabs.some(
|
||||
@@ -1923,17 +1974,12 @@
|
||||
}}
|
||||
/>
|
||||
{:else if (tab.kind === 'files' || tab.kind === 'file') && tab.terminalId}
|
||||
{@const fileConnection = mounted
|
||||
? resolveTerminalConnection(
|
||||
tab.terminalId,
|
||||
$terminalServers ?? [],
|
||||
directTerminals,
|
||||
localStorage.token ?? ''
|
||||
)
|
||||
: null}
|
||||
{@const fileTarget = mounted ? tabTarget(tab) : null}
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<div class="min-h-0 flex-1">
|
||||
<FileNav
|
||||
target={fileTarget}
|
||||
modelId={fileTarget?.context.modelId ?? null}
|
||||
onFileSaved={(content) => {
|
||||
const draft = owner.drafts.get(tab.id);
|
||||
if (draft?.preview) {
|
||||
@@ -1964,7 +2010,7 @@
|
||||
}
|
||||
}}
|
||||
gitStatus={fileGitStatuses[tab.terminalId] ?? null}
|
||||
gitConnection={fileConnection}
|
||||
gitTarget={fileTarget}
|
||||
gitDiffMode={fileGitDiffModes[tab.terminalId] ?? 'unified'}
|
||||
gitHideWhitespace={fileGitHideWhitespace[tab.terminalId] ?? false}
|
||||
bind:this={fileViews[tab.id]}
|
||||
@@ -1975,30 +2021,34 @@
|
||||
active={panelVisible && visibleTabIds.has(tab.id)}
|
||||
manageFileRequests={false}
|
||||
showTerminalDock={tab.kind === 'files'}
|
||||
onOpenFile={(path, page) => openFile(path, tab.terminalId!, page)}
|
||||
onBrowseDirectory={(path) => openFiles(tab.terminalId, path)}
|
||||
onOpenFile={(path, page) =>
|
||||
openFile(path, tab.terminalId!, page, fileTarget?.context.modelId)}
|
||||
onBrowseDirectory={(path) =>
|
||||
openFiles(tab.terminalId, path, false, fileTarget?.context.modelId)}
|
||||
{onAskFile}
|
||||
overlay={dragged}
|
||||
chatId={owner.chatId}
|
||||
bind:terminalContext={fileContexts[tab.id]}
|
||||
/>
|
||||
</div>
|
||||
{#if tab.kind === 'files' && fileConnection}
|
||||
{#if tab.kind === 'files' && fileTarget}
|
||||
<GitBar
|
||||
bind:this={gitViews[tab.id]}
|
||||
initialView={owner.transient[`git:${tab.id}`]}
|
||||
bind:status={fileGitStatuses[tab.terminalId]}
|
||||
bind:diffMode={fileGitDiffModes[tab.terminalId]}
|
||||
bind:hideWhitespace={fileGitHideWhitespace[tab.terminalId]}
|
||||
connection={fileConnection}
|
||||
target={fileTarget}
|
||||
chatId={owner.chatId}
|
||||
directory={fileContexts[tab.id]?.currentDirectory ??
|
||||
tab.directory ??
|
||||
tab.path ??
|
||||
'.'}
|
||||
active={panelVisible && visibleTabIds.has(tab.id)}
|
||||
onOpenFile={(path) => openFile(path, tab.terminalId!)}
|
||||
onOpenDirectory={(path) => openFiles(tab.terminalId, path)}
|
||||
onOpenFile={(path) =>
|
||||
openFile(path, tab.terminalId!, null, fileTarget?.context.modelId)}
|
||||
onOpenDirectory={(path) =>
|
||||
openFiles(tab.terminalId, path, false, fileTarget?.context.modelId)}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
import {
|
||||
getPortProxyUrl,
|
||||
TerminalRequestError,
|
||||
type TerminalConnection
|
||||
type TerminalTarget
|
||||
} from '$lib/apis/terminal';
|
||||
import PortList from '../FileNav/PortList.svelte';
|
||||
import { settings } from '$lib/stores';
|
||||
@@ -23,8 +23,8 @@
|
||||
|
||||
const i18n = getContext<any>('i18n');
|
||||
export let baseUrl = '';
|
||||
export let connection: TerminalConnection | null = null;
|
||||
export let chatId: string | null = null;
|
||||
export let target: TerminalTarget | null = null;
|
||||
|
||||
export let active = true;
|
||||
export let initialUrl = '';
|
||||
export let sessionId = '';
|
||||
@@ -32,19 +32,18 @@
|
||||
let ready: Promise<void> = Promise.resolve();
|
||||
export async function bindChat(id: string) {
|
||||
await ready;
|
||||
if (sessionChatId === id) return;
|
||||
if (sessionChatId || !session || !sessionConnection)
|
||||
if (sessionTarget?.context.chatId === id) return;
|
||||
if (sessionTarget?.context.chatId || !session || !sessionTarget)
|
||||
throw new Error('Browser is not connected');
|
||||
await updateBrowserSession(sessionConnection, sessionChatId, session.id, { chat_id: id });
|
||||
sessionChatId = id;
|
||||
await updateBrowserSession(sessionTarget, session.id, { chat_id: id });
|
||||
sessionTarget.context.chatId = id;
|
||||
}
|
||||
export let overlay = false;
|
||||
export let onNavigate: (url: string, label: string) => void = () => {};
|
||||
export let onOpenBrowser: (url: string) => void = () => {};
|
||||
export let onClose: (() => void) | null = null;
|
||||
let session: BrowserSession | null = null;
|
||||
let sessionChatId = chatId;
|
||||
let sessionConnection = connection;
|
||||
let sessionTarget = target;
|
||||
let chrome: ChromeBrowser;
|
||||
let switching = false;
|
||||
let deviceMode: 'desktop' | 'mobile' = 'desktop';
|
||||
@@ -53,24 +52,24 @@
|
||||
let chromeBack = false;
|
||||
let chromeForward = false;
|
||||
let frameReady = false;
|
||||
$: viewUrl = session && sessionConnection ? browserViewUrl(sessionConnection, session) : '';
|
||||
$: if (session && sessionConnection) {
|
||||
void updateBrowserSession(sessionConnection, sessionChatId, session.id, { active }).catch(
|
||||
$: viewUrl = session && sessionTarget ? browserViewUrl(sessionTarget, session) : '';
|
||||
$: if (session && sessionTarget) {
|
||||
void updateBrowserSession(sessionTarget, session.id, { active }).catch(
|
||||
() => {}
|
||||
);
|
||||
}
|
||||
|
||||
const persist = (url: string, title: string) => {
|
||||
if (session && sessionConnection)
|
||||
void updateBrowserSession(sessionConnection, sessionChatId, session.id, { url, title }).catch(
|
||||
if (session && sessionTarget)
|
||||
void updateBrowserSession(sessionTarget, session.id, { url, title }).catch(
|
||||
() => {}
|
||||
);
|
||||
};
|
||||
const switchMode = async (mode: 'proxy' | 'chrome', force = false) => {
|
||||
if (!session || !sessionConnection || switching || (!force && session.mode === mode)) return;
|
||||
if (!session || !sessionTarget || switching || (!force && session.mode === mode)) return;
|
||||
switching = true;
|
||||
try {
|
||||
session = await updateBrowserSession(sessionConnection, sessionChatId, session.id, {
|
||||
session = await updateBrowserSession(sessionTarget, session.id, {
|
||||
mode,
|
||||
url: currentUrl
|
||||
});
|
||||
@@ -79,7 +78,7 @@
|
||||
history = [];
|
||||
historyIndex = -1;
|
||||
if (currentUrl)
|
||||
frameUrl = browserFrameUrl(browserViewUrl(sessionConnection, session), currentUrl);
|
||||
frameUrl = browserFrameUrl(browserViewUrl(sessionTarget, session), currentUrl);
|
||||
}
|
||||
error = '';
|
||||
return true;
|
||||
@@ -94,7 +93,7 @@
|
||||
}
|
||||
};
|
||||
const fallbackToProxy = async (message: string) => {
|
||||
if (!session || !sessionConnection || switching) return;
|
||||
if (!session || !sessionTarget || switching) return;
|
||||
// The server may already be in Chrome mode even if its startup request failed.
|
||||
const switched = await switchMode('proxy', true);
|
||||
connectionStatus = '';
|
||||
@@ -143,8 +142,8 @@
|
||||
? Number(url.port || (url.protocol === 'https:' ? 443 : 80))
|
||||
: null;
|
||||
const source = (url: URL) => {
|
||||
if (session && sessionConnection)
|
||||
return browserFrameUrl(browserViewUrl(sessionConnection, session), url.href);
|
||||
if (session && sessionTarget)
|
||||
return browserFrameUrl(browserViewUrl(sessionTarget, session), url.href);
|
||||
const port = localPort(url);
|
||||
if (port === null) return url.href;
|
||||
if (!baseUrl) throw new Error($i18n.t('Select a terminal to open localhost URLs.'));
|
||||
@@ -257,27 +256,27 @@
|
||||
onMount(() => {
|
||||
let disposed = false;
|
||||
const release = () => {
|
||||
if (session && sessionConnection)
|
||||
void updateBrowserSession(sessionConnection, sessionChatId, session.id, {
|
||||
if (session && sessionTarget)
|
||||
void updateBrowserSession(sessionTarget, session.id, {
|
||||
active: false
|
||||
}).catch(() => {});
|
||||
};
|
||||
const heartbeat = setInterval(() => {
|
||||
if (session && sessionConnection)
|
||||
void updateBrowserSession(sessionConnection, sessionChatId, session.id, {}).catch(() => {});
|
||||
if (session && sessionTarget)
|
||||
void updateBrowserSession(sessionTarget, session.id, {}).catch(() => {});
|
||||
}, 60_000);
|
||||
window.addEventListener('message', receiveNavigation);
|
||||
window.addEventListener('pagehide', release);
|
||||
ready = (async () => {
|
||||
try {
|
||||
if (!sessionConnection || !sessionId) throw new Error('Session no longer available');
|
||||
const restored = await getBrowserSession(sessionConnection, sessionChatId, sessionId);
|
||||
if (!sessionTarget || !sessionId) throw new Error('Session no longer available');
|
||||
const restored = await getBrowserSession(sessionTarget, sessionId);
|
||||
if (disposed) return;
|
||||
session = restored;
|
||||
currentUrl = restored.url;
|
||||
urlInput = restored.url;
|
||||
if (restored.mode === 'proxy' && restored.url) {
|
||||
frameUrl = browserFrameUrl(browserViewUrl(sessionConnection, restored), restored.url);
|
||||
frameUrl = browserFrameUrl(browserViewUrl(sessionTarget, restored), restored.url);
|
||||
remember(restored.url);
|
||||
}
|
||||
onNavigate(restored.url, restored.title || restored.url || 'Browser');
|
||||
@@ -465,13 +464,11 @@
|
||||
<Icon name="browser" size={18} strokeWidth={1.4} class="text-gray-400" />
|
||||
{$i18n.t('Browser')}
|
||||
</div>
|
||||
{#if connection}
|
||||
{#if target}
|
||||
<div class="mt-3">
|
||||
<PortList
|
||||
baseUrl={connection.baseUrl}
|
||||
{target}
|
||||
previewBaseUrl={baseUrl}
|
||||
apiKey={connection.key}
|
||||
{chatId}
|
||||
{active}
|
||||
on:previewPort={(event) => navigate(`http://localhost:${event.detail}/`)}
|
||||
/>
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
import { toast } from 'svelte-sonner';
|
||||
import type RFB from '@novnc/novnc';
|
||||
import Icon from '../FileNav/Icon.svelte';
|
||||
import { terminalRequest, type TerminalConnection } from '$lib/apis/terminal';
|
||||
import { terminalRequest, type TerminalTarget } from '$lib/apis/terminal';
|
||||
import { openTerminalSocket } from '$lib/apis/terminal/socket';
|
||||
|
||||
const i18n = getContext<any>('i18n');
|
||||
export let connection: TerminalConnection;
|
||||
export let target: TerminalTarget;
|
||||
export let chatId: string | null = null;
|
||||
export let active = true;
|
||||
export let overlay = false;
|
||||
@@ -67,8 +67,7 @@
|
||||
status = $i18n.t('Connecting…');
|
||||
try {
|
||||
const info = await terminalRequest<{ transport?: string; audio?: boolean }>(
|
||||
connection,
|
||||
chatId,
|
||||
target,
|
||||
'/desktop'
|
||||
);
|
||||
if (version !== generation) return;
|
||||
@@ -77,7 +76,7 @@
|
||||
await tick();
|
||||
if (version !== generation) return;
|
||||
if (transport === 'frames') {
|
||||
socket = openTerminalSocket(connection, chatId, '/desktop/stream');
|
||||
socket = openTerminalSocket(target, '/desktop/stream');
|
||||
let framePending = Promise.resolve();
|
||||
socket.onmessage = async (event) => {
|
||||
if (version !== generation) return;
|
||||
@@ -98,7 +97,7 @@
|
||||
} else {
|
||||
const { default: RFB } = await import('@novnc/novnc');
|
||||
if (version !== generation) return;
|
||||
socket = openTerminalSocket(connection, chatId, '/desktop/stream', (channel) => {
|
||||
socket = openTerminalSocket(target, '/desktop/stream', (channel) => {
|
||||
if (version !== generation) return;
|
||||
viewer = new RFB(surface, channel);
|
||||
const cursor = viewer._cursor;
|
||||
@@ -212,7 +211,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
{#if audioAvailable && active && !status && !error}
|
||||
<DesktopAudio {connection} {chatId} {fullscreenEnabled} />
|
||||
<DesktopAudio {target} {fullscreenEnabled} />
|
||||
{/if}
|
||||
{#if fullscreenEnabled}
|
||||
<button
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
<script lang="ts">
|
||||
import { getContext, onDestroy } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import type { TerminalConnection } from '$lib/apis/terminal';
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
import { openTerminalSocket } from '$lib/apis/terminal/socket';
|
||||
import Icon from '../FileNav/Icon.svelte';
|
||||
|
||||
const i18n = getContext<any>('i18n');
|
||||
export let connection: TerminalConnection;
|
||||
export let chatId: string | null;
|
||||
export let target: TerminalTarget;
|
||||
|
||||
export let fullscreenEnabled: boolean;
|
||||
const mime = 'audio/webm; codecs="opus"';
|
||||
let audio: HTMLAudioElement | null = null;
|
||||
@@ -83,7 +83,7 @@
|
||||
buffer = source.addSourceBuffer(mime);
|
||||
buffer.onupdateend = append;
|
||||
buffer.onerror = failed;
|
||||
socket = openTerminalSocket(connection, chatId, '/desktop/audio');
|
||||
socket = openTerminalSocket(target, '/desktop/audio');
|
||||
socket.onmessage = (event) => {
|
||||
if (!(event.data instanceof ArrayBuffer) || !event.data.byteLength) return failed();
|
||||
queuedBytes += event.data.byteLength;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { getContext, onDestroy, onMount } from 'svelte';
|
||||
import { getTerminalFeatures, type TerminalConnection } from '$lib/apis/terminal';
|
||||
import { getTerminalFeatures, type TerminalTarget } from '$lib/apis/terminal';
|
||||
import { watchTerminalFiles } from '$lib/apis/terminal/events';
|
||||
import {
|
||||
gitRequest,
|
||||
@@ -21,7 +21,7 @@
|
||||
import Tooltip from '../../common/Tooltip.svelte';
|
||||
import GitPullRequests from './GitPullRequests.svelte';
|
||||
|
||||
export let connection: TerminalConnection | null = null;
|
||||
export let target: TerminalTarget | null = null;
|
||||
export let directory = '.';
|
||||
export let chatId: string | null = null;
|
||||
export let active = false;
|
||||
@@ -184,13 +184,13 @@
|
||||
operation: string,
|
||||
params: Record<string, string> = {},
|
||||
body?: Record<string, unknown>
|
||||
) => gitRequest<T>(connection!, chatId, status?.root ?? directory, operation, params, body);
|
||||
) => gitRequest<T>(target!, status?.root ?? directory, operation, params, body);
|
||||
const refresh = (force = false): Promise<void> => {
|
||||
if (!connection || !active || !gitEnabled || (!force && document.hidden))
|
||||
if (!target || !active || !gitEnabled || (!force && document.hidden))
|
||||
return Promise.resolve();
|
||||
if (pending) return pending;
|
||||
const current = generation;
|
||||
const task = gitRequest<GitStatus>(connection, chatId, directory, 'status')
|
||||
const task = gitRequest<GitStatus>(target, directory, 'status')
|
||||
.then((next) => {
|
||||
if (current !== generation) return;
|
||||
detectionError = '';
|
||||
@@ -266,8 +266,8 @@
|
||||
view = restoring?.view ?? 'changes';
|
||||
resetSelection();
|
||||
}
|
||||
if (enabled && connection) {
|
||||
const features = await getTerminalFeatures(connection, chatId);
|
||||
if (enabled && target) {
|
||||
const features = await getTerminalFeatures(target);
|
||||
if (version !== configuration || !mounted) return;
|
||||
gitEnabled = features.git === true;
|
||||
if (!gitEnabled) {
|
||||
@@ -278,8 +278,7 @@
|
||||
if (features.events !== true) return;
|
||||
const current = generation;
|
||||
stopWatching = watchTerminalFiles(
|
||||
connection,
|
||||
chatId,
|
||||
target,
|
||||
directory,
|
||||
async () => {
|
||||
// An event arriving during a status request must refresh after that request.
|
||||
@@ -292,7 +291,7 @@
|
||||
);
|
||||
}
|
||||
};
|
||||
$: configure(JSON.stringify([connection, chatId, directory]), mounted && active);
|
||||
$: configure(JSON.stringify([target, chatId, directory]), mounted && active);
|
||||
|
||||
const selectFile = async (file: GitFile, staged: boolean) => {
|
||||
resetSelection();
|
||||
@@ -372,8 +371,7 @@
|
||||
error = '';
|
||||
try {
|
||||
const result = await gitAction<{ path?: string }>(
|
||||
connection!,
|
||||
chatId,
|
||||
target!,
|
||||
status?.root ?? directory,
|
||||
action,
|
||||
fields
|
||||
@@ -808,12 +806,11 @@
|
||||
</div>
|
||||
</Dropdown>
|
||||
</div>
|
||||
{#if view === 'pull requests' && connection && status.root}
|
||||
{#if view === 'pull requests' && target && status.root}
|
||||
{#key status.root}<GitPullRequests
|
||||
mode={diffMode}
|
||||
{hideWhitespace}
|
||||
{connection}
|
||||
{chatId}
|
||||
{target}
|
||||
directory={status.root}
|
||||
branch={status.branch}
|
||||
defaultBranch={prCapabilities?.default_branch ?? 'main'}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
<script lang="ts">
|
||||
import { getContext, onMount, onDestroy } from 'svelte';
|
||||
import { gitRequest } from '$lib/apis/terminal/git';
|
||||
import type { TerminalConnection } from '$lib/apis/terminal';
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
import Icon from '../FileNav/Icon.svelte';
|
||||
import GitDiff from './GitDiff.svelte';
|
||||
import Dropdown from '../../common/Dropdown.svelte';
|
||||
import DropdownMenu from '../../common/DropdownMenu.svelte';
|
||||
import ConfirmDialog from '../../common/ConfirmDialog.svelte';
|
||||
export let connection: TerminalConnection;
|
||||
export let chatId: string | null;
|
||||
export let target: TerminalTarget;
|
||||
|
||||
export let directory: string;
|
||||
export let branch: string;
|
||||
export let defaultBranch = 'main';
|
||||
@@ -66,7 +66,7 @@
|
||||
operation: string,
|
||||
params: Record<string, string> = {},
|
||||
payload?: Record<string, unknown>
|
||||
) => gitRequest<T>(connection, chatId, directory, `pr/${operation}`, params, payload);
|
||||
) => gitRequest<T>(target, directory, `pr/${operation}`, params, payload);
|
||||
const load = async () => {
|
||||
const version = ++generation;
|
||||
loading = true;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { getContext, onDestroy } from 'svelte';
|
||||
import {
|
||||
searchFiles,
|
||||
type TerminalConnection,
|
||||
type TerminalTarget,
|
||||
type TerminalFileSearchResult
|
||||
} from '$lib/apis/terminal';
|
||||
import { settings } from '$lib/stores';
|
||||
@@ -13,7 +13,7 @@
|
||||
import { fileIconName } from '../FileNav/fileIcon';
|
||||
|
||||
const i18n = getContext<any>('i18n');
|
||||
export let connection: TerminalConnection;
|
||||
export let target: TerminalTarget;
|
||||
export let chatId: string | null = null;
|
||||
export let onclose: () => void;
|
||||
export let onselect: (path: string) => void;
|
||||
@@ -26,7 +26,7 @@
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
let requestVersion = 0;
|
||||
|
||||
const queueSearch = (query: string, connection: TerminalConnection, chatId: string | null) => {
|
||||
const queueSearch = (query: string, target: TerminalTarget, chatId: string | null) => {
|
||||
clearTimeout(timer);
|
||||
const version = ++requestVersion;
|
||||
results = [];
|
||||
@@ -37,14 +37,11 @@
|
||||
timer = setTimeout(async () => {
|
||||
const path = query.trim().replace(/\\/g, '/');
|
||||
const slash = path.lastIndexOf('/');
|
||||
const response = await searchFiles(
|
||||
connection.baseUrl,
|
||||
connection.key,
|
||||
const response = await searchFiles(target,
|
||||
path.slice(slash + 1),
|
||||
slash < 0 ? '.' : path.slice(0, slash) || '/',
|
||||
50,
|
||||
'file',
|
||||
chatId ?? undefined,
|
||||
localStorage.getItem('fileNav:showHidden') === 'true'
|
||||
).catch(() => null);
|
||||
if (version !== requestVersion) return;
|
||||
@@ -54,7 +51,7 @@
|
||||
}, 200);
|
||||
};
|
||||
|
||||
$: queueSearch(query, connection, chatId);
|
||||
$: queueSearch(query, target, chatId);
|
||||
onDestroy(() => {
|
||||
clearTimeout(timer);
|
||||
requestVersion++;
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
uploadToTerminal,
|
||||
joinTerminalPath,
|
||||
type FileEntry,
|
||||
type TerminalConnection
|
||||
type TerminalTarget
|
||||
} from '$lib/apis/terminal';
|
||||
import FileCodeEditor from '../FileNav/FileCodeEditor.svelte';
|
||||
import Icon from '../FileNav/Icon.svelte';
|
||||
@@ -18,8 +18,8 @@
|
||||
|
||||
const i18n = getContext<any>('i18n');
|
||||
export let label: string;
|
||||
export let connection: TerminalConnection;
|
||||
export let chatId: string | null = null;
|
||||
export let target: TerminalTarget;
|
||||
|
||||
export let initialDirectory: string | undefined = undefined;
|
||||
export let dirty = false;
|
||||
export let onSaved: (path: string) => void;
|
||||
@@ -57,7 +57,7 @@
|
||||
const browse = async (path: string) => {
|
||||
loading = true;
|
||||
error = '';
|
||||
const listing = await listFiles(connection.baseUrl, connection.key, path, chatId ?? undefined);
|
||||
const listing = await listFiles(target, path);
|
||||
if (disposed) return;
|
||||
loading = false;
|
||||
writable = listing?.writable !== false && !!listing;
|
||||
@@ -82,7 +82,7 @@
|
||||
loading = true;
|
||||
fileName = label;
|
||||
replacePath = '';
|
||||
const cwd = await getCwd(connection.baseUrl, connection.key, chatId ?? undefined);
|
||||
const cwd = await getCwd(target);
|
||||
if (disposed || !showSave) return false;
|
||||
root = (cwd?.root?.path ?? '/').replace(/\/$/, '') || '/';
|
||||
await browse(initialDirectory ?? cwd?.cwd ?? cwd?.home ?? root);
|
||||
@@ -105,11 +105,8 @@
|
||||
saving = true;
|
||||
error = '';
|
||||
try {
|
||||
const listing = await listFiles(
|
||||
connection.baseUrl,
|
||||
connection.key,
|
||||
directory,
|
||||
chatId ?? undefined
|
||||
const listing = await listFiles(target,
|
||||
directory
|
||||
);
|
||||
if (!listing || listing.writable === false) throw new Error($i18n.t('File is not writable.'));
|
||||
const existing = listing.entries.find((entry) => entry.name === name);
|
||||
@@ -120,12 +117,9 @@
|
||||
error = $i18n.t('A file with this name already exists. Replace it?');
|
||||
return;
|
||||
}
|
||||
const result = await uploadToTerminal(
|
||||
connection.baseUrl,
|
||||
connection.key,
|
||||
const result = await uploadToTerminal(target,
|
||||
directory,
|
||||
new File([value], name, { type: 'text/plain' }),
|
||||
chatId ?? undefined
|
||||
new File([value], name, { type: 'text/plain' })
|
||||
);
|
||||
if (!result)
|
||||
throw new Error($i18n.t('Failed to save file. Your changes are still in the editor.'));
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { getContext, onMount, onDestroy, tick } from 'svelte';
|
||||
import { config, settings } from '$lib/stores';
|
||||
import { transcribeAudio } from '$lib/apis/audio';
|
||||
import { getCwd, uploadNewFileToTerminal, type TerminalConnection } from '$lib/apis/terminal';
|
||||
import { getCwd, uploadNewFileToTerminal, type TerminalTarget } from '$lib/apis/terminal';
|
||||
import { matchKeybinding, Shortcut } from '$lib/shortcuts';
|
||||
import Icon from '../FileNav/Icon.svelte';
|
||||
type VoiceNoteDraft = {
|
||||
@@ -36,8 +36,8 @@
|
||||
};
|
||||
|
||||
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
|
||||
export let connection: TerminalConnection;
|
||||
export let chatId: string | null = null;
|
||||
export let target: TerminalTarget;
|
||||
|
||||
export let directory: string | undefined = undefined;
|
||||
export let canTranscribe = false;
|
||||
export let onclose: () => void;
|
||||
@@ -104,7 +104,7 @@
|
||||
initializing = true;
|
||||
try {
|
||||
if (!directory) {
|
||||
const cwd = await getCwd(connection.baseUrl, connection.key, chatId ?? undefined);
|
||||
const cwd = await getCwd(target);
|
||||
if (!cwd) throw new Error($i18n.t('Could not load the recording folder.'));
|
||||
directory = cwd.cwd ?? cwd.home ?? cwd.root?.path;
|
||||
if (!directory) throw new Error($i18n.t('Could not load the recording folder.'));
|
||||
@@ -222,24 +222,18 @@
|
||||
player?.pause();
|
||||
try {
|
||||
if (!draft.audioPath) {
|
||||
const result = await uploadNewFileToTerminal(
|
||||
connection.baseUrl,
|
||||
connection.key,
|
||||
const result = await uploadNewFileToTerminal(target,
|
||||
draft.directory,
|
||||
new File([draft.audio], `${draft.name.trim()}.${voiceNoteExtension(draft.audio.type)}`, {
|
||||
type: draft.audio.type
|
||||
}),
|
||||
chatId ?? undefined
|
||||
})
|
||||
);
|
||||
if (!result?.path) throw new Error();
|
||||
draft.audioPath = result.path;
|
||||
}
|
||||
const note = await uploadNewFileToTerminal(
|
||||
connection.baseUrl,
|
||||
connection.key,
|
||||
const note = await uploadNewFileToTerminal(target,
|
||||
draft.directory,
|
||||
new File([voiceNoteMarkdown(draft)], `${draft.name.trim()}.md`, { type: 'text/markdown' }),
|
||||
chatId ?? undefined
|
||||
new File([voiceNoteMarkdown(draft)], `${draft.name.trim()}.md`, { type: 'text/markdown' })
|
||||
);
|
||||
if (!note?.path) throw new Error();
|
||||
draft = undefined;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import type { TerminalContext } from '$lib/types';
|
||||
import type { TerminalConnection } from '$lib/apis/terminal';
|
||||
import type { TerminalTarget } from '$lib/apis/terminal';
|
||||
|
||||
export type PanelTabKind =
|
||||
| 'chat'
|
||||
@@ -32,7 +32,7 @@ export type PanelTab = {
|
||||
directory?: string;
|
||||
dirty?: boolean;
|
||||
untitled?: boolean;
|
||||
connection?: TerminalConnection;
|
||||
target?: TerminalTarget;
|
||||
browserBaseUrl?: string;
|
||||
context?: TerminalContext | null;
|
||||
};
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
<script lang="ts">
|
||||
export let modelId: string | null = null;
|
||||
import { getContext, onMount, tick } from 'svelte';
|
||||
import type { Readable } from 'svelte/store';
|
||||
import { settings, terminalServers, selectedTerminalId } from '$lib/stores';
|
||||
import {
|
||||
resolveTerminalConnection,
|
||||
resolveTerminalTarget,
|
||||
terminalRequest,
|
||||
type TerminalConnection,
|
||||
type TerminalTarget,
|
||||
type TerminalProcess,
|
||||
type TerminalProcessOutput
|
||||
} from '$lib/apis/terminal';
|
||||
@@ -35,7 +36,7 @@
|
||||
available: boolean;
|
||||
finished: boolean;
|
||||
};
|
||||
let connection: TerminalConnection | null = null;
|
||||
let target: TerminalTarget | null = null;
|
||||
let tabs: Tab[] = [];
|
||||
let activeId = '';
|
||||
let error = '';
|
||||
@@ -61,10 +62,9 @@
|
||||
outputContext = id;
|
||||
stopOutput?.();
|
||||
stopOutput = undefined;
|
||||
if (id && connection) {
|
||||
if (id && target) {
|
||||
stopOutput = readTerminalStream<TerminalProcessOutput>(
|
||||
connection,
|
||||
chatId,
|
||||
target,
|
||||
() =>
|
||||
`/execute/${encodeURIComponent(id)}/status?offset=${tabs.find((tab) => tab.id === id)?.offset ?? 0}&tail=1000`,
|
||||
writeOutput,
|
||||
@@ -120,10 +120,10 @@
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
if (!connection || streaming || !active || polling || disposed || document.hidden) return;
|
||||
if (!target || streaming || !active || polling || disposed || document.hidden) return;
|
||||
polling = true;
|
||||
try {
|
||||
const processes = await terminalRequest<TerminalProcess[]>(connection, chatId, '/execute', {
|
||||
const processes = await terminalRequest<TerminalProcess[]>(target, '/execute', {
|
||||
signal: controller.signal
|
||||
});
|
||||
if (disposed) return;
|
||||
@@ -134,8 +134,7 @@
|
||||
await tick();
|
||||
if (!panes[tab.id]) return;
|
||||
const result = await terminalRequest<TerminalProcessOutput>(
|
||||
connection,
|
||||
chatId,
|
||||
target,
|
||||
`/execute/${encodeURIComponent(tab.id)}/status?wait=0&offset=${tab.offset}&tail=1000`,
|
||||
{ signal: controller.signal }
|
||||
);
|
||||
@@ -180,16 +179,14 @@
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
connection = resolveTerminalConnection(
|
||||
target = resolveTerminalTarget(
|
||||
terminalId ?? $selectedTerminalId,
|
||||
$terminalServers ?? [],
|
||||
($settings as { terminalServers?: { url: string; key?: string }[] })?.terminalServers ?? [],
|
||||
localStorage.getItem('token') ?? ''
|
||||
);
|
||||
if (connection) {
|
||||
localStorage.getItem('token') ?? '', { chatId: chatId, modelId: modelId });
|
||||
if (target) {
|
||||
stopList = readTerminalStream<TerminalProcess[]>(
|
||||
connection,
|
||||
chatId,
|
||||
target,
|
||||
() => '/execute',
|
||||
updateProcesses,
|
||||
(message) => {
|
||||
@@ -297,14 +294,13 @@
|
||||
{error}
|
||||
</div>{/if}
|
||||
<div class="relative min-h-0 flex-1">
|
||||
{#if connection}
|
||||
{#if target}
|
||||
{#each tabs as tab (tab.id)}
|
||||
{#if tab.loaded || activeId === tab.id}
|
||||
<div class="absolute inset-0" class:hidden={activeId !== tab.id}>
|
||||
<XTerminal
|
||||
bind:this={panes[tab.id]}
|
||||
{connection}
|
||||
{chatId}
|
||||
{target}
|
||||
{overlay}
|
||||
readOnly
|
||||
active={active && expanded && activeId === tab.id}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { getContext, onMount, onDestroy } from 'svelte';
|
||||
import {
|
||||
terminalRequest,
|
||||
type TerminalConnection,
|
||||
type TerminalTarget,
|
||||
type TerminalSystemInfo
|
||||
} from '$lib/apis/terminal';
|
||||
import Icon from './FileNav/Icon.svelte';
|
||||
@@ -11,8 +11,8 @@
|
||||
import XMark from '$lib/components/icons/XMark.svelte';
|
||||
import ChevronDown from '$lib/components/icons/ChevronDown.svelte';
|
||||
|
||||
export let connection: TerminalConnection;
|
||||
export let chatId: string | null = null;
|
||||
export let target: TerminalTarget;
|
||||
|
||||
export let label: string;
|
||||
export let onClose: () => void;
|
||||
const i18n = getContext<any>('i18n');
|
||||
@@ -32,7 +32,7 @@
|
||||
controller = request;
|
||||
loading = true;
|
||||
try {
|
||||
const next = await terminalRequest<TerminalSystemInfo>(connection, chatId, '/system/info', {
|
||||
const next = await terminalRequest<TerminalSystemInfo>(target, '/system/info', {
|
||||
signal: request.signal
|
||||
});
|
||||
if (request.signal.aborted || destroyed) return;
|
||||
|
||||
@@ -0,0 +1,495 @@
|
||||
<script lang="ts">
|
||||
import { onMount, getContext } from 'svelte';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import Modal from '$lib/components/common/Modal.svelte';
|
||||
import ConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
|
||||
import Collapsible from '$lib/components/common/Collapsible.svelte';
|
||||
import SettingsSelect from '$lib/components/common/SettingsSelect.svelte';
|
||||
import Dropdown from '$lib/components/common/Dropdown.svelte';
|
||||
import DropdownMenu from '$lib/components/common/DropdownMenu.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import Cloud from '$lib/components/icons/Cloud.svelte';
|
||||
import Check from '$lib/components/icons/Check.svelte';
|
||||
import ChevronLeft from '$lib/components/icons/ChevronLeft.svelte';
|
||||
import EllipsisHorizontal from '$lib/components/icons/EllipsisHorizontal.svelte';
|
||||
import Plus from '$lib/components/icons/Plus.svelte';
|
||||
import XMark from '$lib/components/icons/XMark.svelte';
|
||||
import Pencil from '$lib/components/icons/Pencil.svelte';
|
||||
import Users from '$lib/components/icons/Users.svelte';
|
||||
import ArrowPath from '$lib/components/icons/ArrowPath.svelte';
|
||||
import Trash from '$lib/components/icons/Trash.svelte';
|
||||
import AccessControl from '$lib/components/workspace/common/AccessControl.svelte';
|
||||
import { templatesApi, getTerminalServers } from '$lib/apis/terminal';
|
||||
import { terminalServers } from '$lib/stores';
|
||||
|
||||
export let show = true;
|
||||
export let chatId: string | null = null;
|
||||
export let modelId: string | null = null;
|
||||
export let selected: string | null = null;
|
||||
export let onSelect: (id: string) => Promise<void>;
|
||||
const i18n = getContext<any>('i18n');
|
||||
let rows: any[] = [];
|
||||
let connections: any[] = [];
|
||||
let current: any = null;
|
||||
let editing: any = null;
|
||||
let sharing: any = null;
|
||||
let accessGrants: any[] = [];
|
||||
let connectionId = '';
|
||||
let name = '';
|
||||
let image = '';
|
||||
let scope = 'none';
|
||||
let cpu = '';
|
||||
let memory = '';
|
||||
let advanced = '{}';
|
||||
let showAdvanced = false;
|
||||
let busy = false;
|
||||
let error = '';
|
||||
let confirmation: { title: string; message: string; run: () => Promise<void> } | null = null;
|
||||
let showConfirm = false;
|
||||
const button =
|
||||
'flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2.5 text-xs font-normal text-gray-600 transition hover:bg-gray-100 hover:text-gray-900 disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-850 dark:hover:text-white';
|
||||
const input =
|
||||
'w-full min-w-0 bg-transparent py-1 text-sm outline-hidden placeholder:text-gray-400 dark:placeholder:text-gray-600';
|
||||
const path = (id: string) => `/${encodeURIComponent(id)}`;
|
||||
const context = () => ({ chat_id: chatId, model_id: modelId });
|
||||
|
||||
async function run(work: () => Promise<void>) {
|
||||
busy = true;
|
||||
error = '';
|
||||
try {
|
||||
await work();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : String(e);
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
async function load() {
|
||||
const [servers, allowed] = await Promise.all([
|
||||
getTerminalServers(localStorage.token),
|
||||
templatesApi('/connections')
|
||||
]);
|
||||
terminalServers.set(servers);
|
||||
rows = servers.filter((row) => row.template_id);
|
||||
connections = allowed;
|
||||
if (!connections.some((c) => c.id === connectionId)) connectionId = connections[0]?.id ?? '';
|
||||
current = null;
|
||||
if (selected && rows.some((r) => r.id === selected)) {
|
||||
const query = new URLSearchParams();
|
||||
if (chatId) query.set('chat_id', chatId);
|
||||
if (modelId) query.set('model_id', modelId);
|
||||
try {
|
||||
current = await templatesApi(`${path(selected)}/instance?${query}`);
|
||||
} catch (e) {
|
||||
current = { status: 'unavailable', detail: String(e) };
|
||||
}
|
||||
}
|
||||
}
|
||||
async function edit(row: any = null) {
|
||||
await run(async () => {
|
||||
const data = row ? (await templatesApi(path(row.id))).data : {};
|
||||
editing = row ?? { id: null };
|
||||
sharing = null;
|
||||
name = data.name ?? row?.name ?? '';
|
||||
image = data.image ?? '';
|
||||
scope = data.scope ?? 'none';
|
||||
cpu = data.cpu_limit ?? '';
|
||||
memory = data.memory_limit ?? '';
|
||||
const { name: _name, image: _image, scope: _scope, cpu_limit, memory_limit, ...rest } = data;
|
||||
advanced = JSON.stringify(rest, null, 2);
|
||||
showAdvanced = false;
|
||||
});
|
||||
}
|
||||
async function save() {
|
||||
await run(async () => {
|
||||
const extra = JSON.parse(advanced);
|
||||
if (!extra || Array.isArray(extra) || typeof extra !== 'object')
|
||||
throw new Error('Configuration must be an object');
|
||||
const data = {
|
||||
...extra,
|
||||
name: name.trim(),
|
||||
image: image.trim() || null,
|
||||
scope: scope === 'none' ? null : scope,
|
||||
cpu_limit: cpu || null,
|
||||
memory_limit: memory || null
|
||||
};
|
||||
if (!data.name) throw new Error('Name is required');
|
||||
if (editing.id) await templatesApi(path(editing.id), 'PATCH', data);
|
||||
else {
|
||||
const row = await templatesApi('', 'POST', {
|
||||
id: uuidv4(),
|
||||
connection_id: connectionId,
|
||||
data
|
||||
});
|
||||
await load();
|
||||
await onSelect(row.terminal_id);
|
||||
selected = row.terminal_id;
|
||||
}
|
||||
editing = null;
|
||||
await load();
|
||||
});
|
||||
}
|
||||
async function share(row: any) {
|
||||
await run(async () => {
|
||||
accessGrants = await templatesApi(`${path(row.id)}/access`);
|
||||
sharing = row;
|
||||
editing = null;
|
||||
});
|
||||
}
|
||||
async function saveShares() {
|
||||
await run(async () => {
|
||||
await templatesApi(`${path(sharing.id)}/access`, 'POST', { access_grants: accessGrants });
|
||||
sharing = null;
|
||||
await load();
|
||||
});
|
||||
}
|
||||
async function removeTemplate(row: any) {
|
||||
await run(async () => {
|
||||
const instances = await templatesApi(`${path(row.id)}/instances`);
|
||||
confirmation = {
|
||||
title: `Delete ${row.name}?`,
|
||||
message: `This deletes the terminal and ${instances.length} instances, including their files.`,
|
||||
run: async () => {
|
||||
await templatesApi(path(row.id), 'DELETE');
|
||||
await load();
|
||||
}
|
||||
};
|
||||
showConfirm = true;
|
||||
});
|
||||
}
|
||||
function action(kind: 'restart' | 'reset' | 'delete') {
|
||||
if (!selected) return;
|
||||
const target = selected;
|
||||
const pinned = context();
|
||||
confirmation = {
|
||||
title:
|
||||
kind === 'delete'
|
||||
? 'Delete this instance?'
|
||||
: `${kind === 'restart' ? 'Restart' : 'Reset'} terminal?`,
|
||||
message:
|
||||
kind === 'restart'
|
||||
? 'Running work stops. Files are kept.'
|
||||
: 'Files and running work are removed for everyone using this instance.',
|
||||
run: async () => {
|
||||
await templatesApi(
|
||||
`${path(target)}/${kind === 'delete' ? 'instance' : kind}`,
|
||||
kind === 'delete' ? 'DELETE' : 'POST',
|
||||
pinned
|
||||
);
|
||||
await load();
|
||||
}
|
||||
};
|
||||
showConfirm = true;
|
||||
}
|
||||
onMount(() => run(load));
|
||||
</script>
|
||||
|
||||
<Modal
|
||||
bind:show
|
||||
size="sm"
|
||||
ariaLabel={$i18n.t(
|
||||
editing
|
||||
? editing.id
|
||||
? 'Configure terminal'
|
||||
: 'New terminal'
|
||||
: sharing
|
||||
? 'Share terminal'
|
||||
: 'Terminals'
|
||||
)}
|
||||
>
|
||||
<div class="text-gray-900 dark:text-gray-100">
|
||||
<div class="flex items-center justify-between gap-2 px-4 pt-3 pb-2">
|
||||
<div class="flex min-w-0 items-center gap-1.5">
|
||||
{#if editing || sharing}
|
||||
<button
|
||||
type="button"
|
||||
class="-ml-1 flex size-6 shrink-0 items-center justify-center rounded-lg text-gray-400 transition hover:bg-gray-50 hover:text-gray-700 dark:hover:bg-gray-850 dark:hover:text-gray-200"
|
||||
aria-label={$i18n.t('Back')}
|
||||
disabled={busy}
|
||||
on:click={() => {
|
||||
editing = null;
|
||||
sharing = null;
|
||||
error = '';
|
||||
}}><ChevronLeft className="size-3.5" strokeWidth="2" /></button
|
||||
>
|
||||
{/if}
|
||||
<h2 class="truncate text-sm font-medium">
|
||||
{editing
|
||||
? $i18n.t(editing.id ? 'Configure terminal' : 'New terminal')
|
||||
: sharing
|
||||
? `${$i18n.t('Share')} ${sharing.name}`
|
||||
: $i18n.t('Terminals')}
|
||||
</h2>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-lg py-1 text-gray-500 transition hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
|
||||
on:click={() => (show = false)}
|
||||
aria-label={$i18n.t('Close')}><XMark className="size-4" /></button
|
||||
>
|
||||
</div>
|
||||
<div class="max-h-[min(36rem,75dvh)] overflow-y-auto px-4 pb-4" aria-busy={busy}>
|
||||
{#if error}<p role="alert" class="mb-3 text-xs text-red-500">{error}</p>{/if}
|
||||
{#if editing}
|
||||
<form class="space-y-4 pt-1" on:submit|preventDefault={save}>
|
||||
<div>
|
||||
<label for="terminal-name" class="block text-xs text-gray-500 dark:text-gray-400"
|
||||
>{$i18n.t('Name')}</label
|
||||
>
|
||||
<input
|
||||
id="terminal-name"
|
||||
class={input}
|
||||
bind:value={name}
|
||||
placeholder={$i18n.t('Terminal name')}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-3 border-t border-gray-100/50 pt-3 dark:border-white/[0.04]">
|
||||
{#if !editing.id}
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<label for="terminal-connection" class="text-xs">{$i18n.t('Connection')}</label>
|
||||
<SettingsSelect
|
||||
id="terminal-connection"
|
||||
bind:value={connectionId}
|
||||
className="max-w-[65%]"
|
||||
required
|
||||
disabled={busy}
|
||||
>{#each connections as c}<option value={c.id}>{c.name}</option
|
||||
>{/each}</SettingsSelect
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
<div>
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<label for="terminal-scope" class="text-xs">{$i18n.t('Scope')}</label>
|
||||
<SettingsSelect id="terminal-scope" bind:value={scope} disabled={busy}
|
||||
><option value="none">{$i18n.t('None')}</option><option value="user"
|
||||
>{$i18n.t('User')}</option
|
||||
><option value="chat">{$i18n.t('Chat')}</option><option value="model"
|
||||
>{$i18n.t('Model')}</option
|
||||
></SettingsSelect
|
||||
>
|
||||
</div>
|
||||
<p class="mt-1.5 text-xs leading-relaxed text-gray-500 dark:text-gray-400">
|
||||
{$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.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="space-y-3 border-t border-gray-100/50 pt-3 dark:border-white/[0.04]">
|
||||
<div>
|
||||
<label for="terminal-image" class="block text-xs text-gray-500 dark:text-gray-400"
|
||||
>{$i18n.t('Image')}</label
|
||||
><input
|
||||
id="terminal-image"
|
||||
class={input}
|
||||
bind:value={image}
|
||||
placeholder={$i18n.t('Server default')}
|
||||
/>
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label for="terminal-cpu" class="block text-xs text-gray-500 dark:text-gray-400"
|
||||
>CPU</label
|
||||
><input
|
||||
id="terminal-cpu"
|
||||
class={input}
|
||||
bind:value={cpu}
|
||||
placeholder={$i18n.t('Server default')}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label for="terminal-memory" class="block text-xs text-gray-500 dark:text-gray-400"
|
||||
>{$i18n.t('Memory')}</label
|
||||
><input
|
||||
id="terminal-memory"
|
||||
class={input}
|
||||
bind:value={memory}
|
||||
placeholder={$i18n.t('Server default')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="border-t border-gray-100/50 pt-2 dark:border-white/[0.04]">
|
||||
<Collapsible
|
||||
title={$i18n.t('Advanced configuration')}
|
||||
bind:open={showAdvanced}
|
||||
buttonClassName="flex w-full py-1 text-xs text-gray-500 transition hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
|
||||
chevronClassName="size-3.5"
|
||||
chevronStrokeWidth="2"
|
||||
>
|
||||
<div slot="content" class="pt-2">
|
||||
<p class="mb-2 text-xs leading-relaxed text-gray-500 dark:text-gray-400">
|
||||
{$i18n.t('Environment variables, storage, networking, and security settings.')}
|
||||
</p>
|
||||
<textarea
|
||||
class="w-full resize-y rounded-lg bg-gray-50/60 p-2.5 font-mono text-xs leading-relaxed outline-hidden focus:ring-1 focus:ring-gray-200 dark:bg-gray-850/50 dark:focus:ring-gray-700"
|
||||
rows="7"
|
||||
bind:value={advanced}
|
||||
aria-label={$i18n.t('Template configuration')}
|
||||
spellcheck="false"
|
||||
/>
|
||||
</div>
|
||||
</Collapsible>
|
||||
</div>
|
||||
<div class="flex justify-end gap-1.5 pt-1">
|
||||
<button type="button" class={button} disabled={busy} on:click={() => (editing = null)}
|
||||
>{$i18n.t('Cancel')}</button
|
||||
>
|
||||
<button
|
||||
type="submit"
|
||||
class="flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-lg bg-gray-900 px-2.5 text-xs font-normal text-white transition hover:bg-black disabled:opacity-50 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-white"
|
||||
disabled={busy || (!editing.id && !connectionId)}
|
||||
>{#if busy}<Spinner className="size-3" />{/if}{$i18n.t(
|
||||
editing.id ? 'Save' : 'Create'
|
||||
)}</button
|
||||
>
|
||||
</div>
|
||||
</form>
|
||||
{:else if sharing}
|
||||
<p class="mb-3 pt-1 text-xs leading-relaxed text-gray-500 dark:text-gray-400">
|
||||
{$i18n.t(
|
||||
'Use allows commands and file access. Manage also allows configuration, sharing, and instance management.'
|
||||
)}
|
||||
</p>
|
||||
<AccessControl
|
||||
bind:accessGrants
|
||||
accessRoles={['read']}
|
||||
labels={{ read: $i18n.t('Use') }}
|
||||
sharePublic={false}
|
||||
shareOpen={false}
|
||||
shareUsers={true}
|
||||
allowGroups={true}
|
||||
onChange={() => {}}
|
||||
/>
|
||||
<div class="mt-4 flex justify-end gap-1.5">
|
||||
<button class={button} disabled={busy} on:click={() => (sharing = null)}
|
||||
>{$i18n.t('Cancel')}</button
|
||||
><button
|
||||
class="flex h-7 items-center gap-1.5 rounded-lg bg-gray-900 px-2.5 text-xs text-white transition hover:bg-black disabled:opacity-50 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-white"
|
||||
disabled={busy}
|
||||
on:click={saveShares}
|
||||
>{#if busy}<Spinner className="size-3" />{/if}{$i18n.t('Save')}</button
|
||||
>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="-mx-2 space-y-0.5">
|
||||
{#each rows as row (row.id)}
|
||||
{@const connection = connections.find((c) => c.id === row.id.slice('template:'.length, row.id.lastIndexOf(':')))}
|
||||
<div
|
||||
class="flex items-center gap-1 rounded-xl pr-1 transition {row.id === selected
|
||||
? 'bg-gray-50/60 dark:bg-gray-850/50'
|
||||
: 'hover:bg-gray-50/40 dark:hover:bg-gray-850/30'}"
|
||||
>
|
||||
<button
|
||||
class="flex min-w-0 flex-1 items-center gap-2.5 rounded-xl px-2 py-2 text-left disabled:opacity-50"
|
||||
aria-pressed={row.id === selected}
|
||||
disabled={busy}
|
||||
on:click={() =>
|
||||
run(async () => {
|
||||
await onSelect(row.id);
|
||||
selected = row.id;
|
||||
await load();
|
||||
})}
|
||||
>
|
||||
<Cloud
|
||||
className="size-4 shrink-0 text-gray-400 dark:text-gray-500"
|
||||
strokeWidth="1.5"
|
||||
/>
|
||||
<span class="min-w-0 flex-1"
|
||||
><span class="block truncate text-[0.8125rem]">{row.name}</span><span
|
||||
class="mt-0.5 flex items-center gap-1.5 text-[0.6875rem] text-gray-500 dark:text-gray-400"
|
||||
>{$i18n.t(
|
||||
row.scope ? row.scope[0].toUpperCase() + row.scope.slice(1) : 'None'
|
||||
)}{#if row.id === selected && current}<span aria-hidden="true">·</span><span
|
||||
class="flex items-center gap-1"
|
||||
>{#if current.status === 'running'}<span
|
||||
class="size-1 rounded-full bg-emerald-500"
|
||||
/>{/if}{$i18n.t(
|
||||
current.status === 'not_created'
|
||||
? 'Not started'
|
||||
: current.status[0].toUpperCase() + current.status.slice(1)
|
||||
)}</span
|
||||
>{/if}</span
|
||||
></span
|
||||
>
|
||||
{#if row.id === selected}<Check
|
||||
className="size-3.5 shrink-0 text-emerald-600 dark:text-emerald-400"
|
||||
/>{/if}
|
||||
</button>
|
||||
{#if connection}
|
||||
<Dropdown align="end" closeOnSelect>
|
||||
<button
|
||||
class="flex size-7 items-center justify-center rounded-lg text-gray-400 transition hover:bg-gray-100/60 hover:text-gray-700 disabled:opacity-50 dark:hover:bg-gray-800/60 dark:hover:text-gray-200"
|
||||
aria-label={$i18n.t('Actions for {{name}}', { name: row.name })}
|
||||
disabled={busy}><EllipsisHorizontal className="size-4" /></button
|
||||
>
|
||||
<div slot="content">
|
||||
<DropdownMenu className="w-48">
|
||||
<button disabled={busy} on:click={() => edit(row)}
|
||||
><Pencil />{$i18n.t('Configure')}</button
|
||||
><button disabled={busy} on:click={() => share(row)}
|
||||
><Users />{$i18n.t('Share')}</button
|
||||
>
|
||||
{#if row.id === selected && current && !['not_created', 'unavailable'].includes(current.status)}
|
||||
<hr class="border-gray-100/50 dark:border-white/[0.04]" />
|
||||
<button disabled={busy} on:click={() => action('restart')}
|
||||
><ArrowPath />{$i18n.t('Restart')}</button
|
||||
><button disabled={busy} on:click={() => action('reset')}
|
||||
><ArrowPath />{$i18n.t('Reset')}</button
|
||||
><button
|
||||
class="text-red-500 dark:text-red-400"
|
||||
disabled={busy}
|
||||
on:click={() => action('delete')}
|
||||
><Trash />{$i18n.t('Delete instance')}</button
|
||||
>
|
||||
{/if}
|
||||
<hr class="border-gray-100/50 dark:border-white/[0.04]" />
|
||||
<button
|
||||
class="text-red-500 dark:text-red-400"
|
||||
disabled={busy}
|
||||
on:click={() => removeTemplate(row)}
|
||||
><Trash />{$i18n.t('Delete terminal')}</button
|
||||
>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</Dropdown>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}<div class="flex items-center justify-center gap-2 py-8 text-xs text-gray-500">
|
||||
{#if busy}<Spinner className="size-3.5" />{$i18n.t('Loading...')}{:else}{$i18n.t(
|
||||
'No terminals available'
|
||||
)}{/if}
|
||||
</div>{/each}
|
||||
</div>
|
||||
{#if current?.detail}<p class="mt-2 text-xs text-gray-500" role="status">
|
||||
{current.detail}
|
||||
</p>{/if}
|
||||
{#if connections.length}<div
|
||||
class="mt-2 border-t border-gray-100/50 pt-2 dark:border-white/[0.04]"
|
||||
>
|
||||
<button class={`${button} -ml-2`} disabled={busy} on:click={() => edit()}
|
||||
><Plus className="size-3.5" />{$i18n.t('New terminal')}</button
|
||||
>
|
||||
</div>{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
<ConfirmDialog
|
||||
bind:show={showConfirm}
|
||||
title={confirmation?.title ?? ''}
|
||||
message={confirmation?.message ?? ''}
|
||||
onConfirm={() =>
|
||||
run(async () => {
|
||||
await confirmation?.run();
|
||||
showConfirm = false;
|
||||
})}
|
||||
/>
|
||||
@@ -8,12 +8,12 @@
|
||||
import {
|
||||
terminalRequest,
|
||||
TerminalRequestError,
|
||||
type TerminalConnection
|
||||
type TerminalTarget
|
||||
} from '$lib/apis/terminal';
|
||||
import { assignTerminalChat, openTerminalSocket } from '$lib/apis/terminal/socket';
|
||||
|
||||
export let connection: TerminalConnection;
|
||||
export let chatId: string | null = null;
|
||||
export let target: TerminalTarget;
|
||||
|
||||
export let overlay = false;
|
||||
export let active = true;
|
||||
export let readOnly = false;
|
||||
@@ -30,7 +30,6 @@
|
||||
let destroyed = false;
|
||||
export let sessionId = '';
|
||||
export let onUnavailable: (message: string, status?: number) => void = () => {};
|
||||
let sessionChatId = chatId;
|
||||
let bindingChat: Promise<void> | null = null;
|
||||
let finishConnection: (ready: boolean) => void;
|
||||
const connectionReady = new Promise<boolean>((resolve) => (finishConnection = resolve));
|
||||
@@ -45,20 +44,20 @@
|
||||
let reconnecting = false;
|
||||
|
||||
export async function bindChat(id: string) {
|
||||
if (readOnly || destroyed || sessionChatId === id) return;
|
||||
if (sessionChatId) throw new Error('Terminal already belongs to another chat');
|
||||
if (readOnly || destroyed || target.context.chatId === id) return;
|
||||
if (target.context.chatId) throw new Error('Terminal already belongs to another chat');
|
||||
if (!(await connectionReady) || !ws) throw new Error('Terminal is not connected');
|
||||
if (!bindingChat) {
|
||||
bindingChat = assignTerminalChat(ws, id)
|
||||
.then(() => {
|
||||
sessionChatId = id;
|
||||
target.context.chatId = id;
|
||||
})
|
||||
.finally(() => {
|
||||
bindingChat = null;
|
||||
});
|
||||
}
|
||||
await bindingChat;
|
||||
if (sessionChatId !== id) throw new Error('Terminal already belongs to another chat');
|
||||
if (target.context.chatId !== id) throw new Error('Terminal already belongs to another chat');
|
||||
}
|
||||
|
||||
function reportActivity(visible: boolean) {
|
||||
@@ -114,14 +113,12 @@
|
||||
try {
|
||||
if (!sessionId) throw new Error('Session no longer available');
|
||||
await terminalRequest(
|
||||
connection,
|
||||
sessionChatId,
|
||||
target,
|
||||
`/api/terminals/${encodeURIComponent(sessionId)}`
|
||||
);
|
||||
if (destroyed) return;
|
||||
ws = openTerminalSocket(
|
||||
connection,
|
||||
sessionChatId,
|
||||
target,
|
||||
`/api/terminals/${encodeURIComponent(sessionId)}`,
|
||||
() => {
|
||||
if (destroyed) return;
|
||||
|
||||
@@ -36,7 +36,7 @@
|
||||
let saving = false;
|
||||
|
||||
export let accessRoles = ['read'];
|
||||
export let labels: Partial<Record<'title' | 'public' | 'private' | 'read' | 'empty', string>> =
|
||||
export let labels: Partial<Record<'title' | 'public' | 'private' | 'read' | 'write' | 'empty', string>> =
|
||||
{};
|
||||
export let accessGrants: AccessGrant[] | any = [];
|
||||
export let accessControl: any = undefined;
|
||||
@@ -629,8 +629,8 @@
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="read">{$i18n.t('Read')}</option>
|
||||
<option value="write">{$i18n.t('Write')}</option>
|
||||
<option value="read">{labels.read ?? $i18n.t('Read')}</option>
|
||||
<option value="write">{labels.write ?? $i18n.t('Write')}</option>
|
||||
</select>
|
||||
{:else}
|
||||
<Badge type={'info'} content={labels.read ?? $i18n.t('Read')} />
|
||||
@@ -682,8 +682,8 @@
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="read">{$i18n.t('Read')}</option>
|
||||
<option value="write">{$i18n.t('Write')}</option>
|
||||
<option value="read">{labels.read ?? $i18n.t('Read')}</option>
|
||||
<option value="write">{labels.write ?? $i18n.t('Write')}</option>
|
||||
</select>
|
||||
{:else}
|
||||
<Badge type={'info'} content={labels.read ?? $i18n.t('Read')} />
|
||||
|
||||
@@ -2,7 +2,7 @@ import { browser } from '$app/environment';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { writable } from 'svelte/store';
|
||||
import { getChatView, updateChatView } from '$lib/apis/chats/view';
|
||||
import { terminalRequest, type TerminalConnection } from '$lib/apis/terminal';
|
||||
import { terminalRequest, type TerminalTarget } from '$lib/apis/terminal';
|
||||
import { createBrowserSession } from '$lib/apis/terminal/browser';
|
||||
import { isSavedChatId } from '$lib/utils/chatId';
|
||||
import {
|
||||
@@ -186,7 +186,7 @@ export function updateViewTab(entry: Entry, id: string, values: Partial<PanelTab
|
||||
);
|
||||
}
|
||||
|
||||
export function createViewSession(entry: Entry, id: string, connection: TerminalConnection) {
|
||||
export function createViewSession(entry: Entry, id: string, target: TerminalTarget) {
|
||||
const pending = entry.pending.get(id);
|
||||
if (pending) return pending;
|
||||
const tab = entry.state.panels.tabs.find((tab) => tab.id === id);
|
||||
@@ -196,8 +196,8 @@ export function createViewSession(entry: Entry, id: string, connection: Terminal
|
||||
try {
|
||||
const session =
|
||||
tab.kind === 'browser'
|
||||
? await createBrowserSession(connection, entry.chatId, tab.path ?? '')
|
||||
: await terminalRequest<{ id: string }>(connection, entry.chatId, '/api/terminals', {
|
||||
? await createBrowserSession(target, tab.path ?? '')
|
||||
: await terminalRequest<{ id: string }>(target, '/api/terminals', {
|
||||
method: 'POST'
|
||||
});
|
||||
updateViewTab(entry, id, { sessionId: session.id });
|
||||
@@ -225,6 +225,9 @@ export async function promoteChatView(
|
||||
await bind();
|
||||
entries.delete(key(entry.userId, entry.chatId || entry.instanceId));
|
||||
entry.chatId = chatId;
|
||||
for (const tab of entry.state.panels.tabs) {
|
||||
if (tab.target) tab.target.context.chatId = chatId;
|
||||
}
|
||||
entry.persistent = isSavedChatId(chatId) && !temporary;
|
||||
entries.set(key(entry.userId, chatId), entry);
|
||||
entry.error = '';
|
||||
|
||||
@@ -108,12 +108,9 @@
|
||||
terminalServers.update((servers) => [
|
||||
...(servers ?? []).filter((server) => !server.id),
|
||||
...systemTerminals.map((terminal) => ({
|
||||
id: terminal.id,
|
||||
...terminal,
|
||||
url: `${WEBUI_API_BASE_URL}/terminals/${terminal.id}`,
|
||||
name: terminal.name,
|
||||
key: localStorage.token,
|
||||
contexts: terminal.contexts ?? {},
|
||||
config: terminal.config ?? {}
|
||||
key: localStorage.token
|
||||
}))
|
||||
]);
|
||||
};
|
||||
|
||||
@@ -90,7 +90,7 @@
|
||||
import { getUserSettings } from '$lib/apis/users';
|
||||
import { getChannelById, getChannels } from '$lib/apis/channels';
|
||||
import { shouldNotifyChannelMessage } from '$lib/utils/channelNotifications';
|
||||
import { resolveTerminalConnection, terminalRequest } from '$lib/apis/terminal';
|
||||
import { resolveTerminalTarget, terminalRequest } from '$lib/apis/terminal';
|
||||
|
||||
const unregisterServiceWorkers = async () => {
|
||||
if ('serviceWorker' in navigator) {
|
||||
@@ -685,13 +685,13 @@
|
||||
} else if (type === 'request:terminal') {
|
||||
try {
|
||||
if (!$config?.features?.enable_tool_servers) throw new Error('Tool servers are disabled');
|
||||
const connection = resolveTerminalConnection(
|
||||
const target = resolveTerminalTarget(
|
||||
data.terminal_id,
|
||||
[],
|
||||
$config?.features?.enable_direct_integrations ? ($settings?.terminalServers ?? []) : [],
|
||||
localStorage.token
|
||||
localStorage.token, { chatId: event.chat_id ?? null }
|
||||
);
|
||||
if (!connection) throw new Error('Terminal Not Found');
|
||||
if (!target) throw new Error('Terminal Not Found');
|
||||
let options = {};
|
||||
if (data.file) {
|
||||
const blob = await getFileBlobById(localStorage.token, data.file.id);
|
||||
@@ -699,7 +699,7 @@
|
||||
body.append('file', blob, data.file.name);
|
||||
options = { method: 'POST', body };
|
||||
}
|
||||
const result = await terminalRequest(connection, event.chat_id, data.path, options);
|
||||
const result = await terminalRequest(target, data.path, options);
|
||||
cb?.({ data: result });
|
||||
} catch (error) {
|
||||
cb?.({ error: `${error}` });
|
||||
|
||||
Reference in new issue
Block a user