feat: implement web terminal for tool instances

- Add TerminalSession backend service for docker exec subprocess management
- Add TerminalManager for WebSocket session lifecycle management
- Create WebSocket endpoint at /ws/tool-instances/{id}/terminal
- Add session cookie authentication and instance ownership verification
- Install xterm.js with fit and web-links addons
- Create TerminalComponent with xterm.js integration
- Create TerminalPage with full-screen terminal view
- Add terminal route at /instances/:id/terminal
- Add terminal button to InstanceList for running instances
- Add terminal and arrow-left icons to icon registry
- Add comprehensive terminal CSS styles (dark theme, responsive)

Quality gates: typecheck ✓, lint ✓, build ✓, Python syntax ✓
This commit is contained in:
Fusion
2026-05-19 21:11:29 +02:00
parent d6b3e8b804
commit e344e961d6
23 changed files with 1136 additions and 4 deletions
+99
View File
@@ -0,0 +1,99 @@
"""WebSocket terminal endpoint for tool instances."""
import uuid
from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect, status
from sqlalchemy.ext.asyncio import AsyncSession
from src.auth.dependencies import get_current_user_id
from src.database import get_db_session
from src.models.tool_instance import ToolInstance
from src.services.terminal_manager import terminal_manager
router = APIRouter()
@router.websocket("/ws/tool-instances/{instance_id}/terminal")
async def terminal_websocket(
websocket: WebSocket,
instance_id: str,
db_session: AsyncSession = Depends(get_db_session),
) -> None:
"""WebSocket endpoint for terminal access to a tool instance."""
await websocket.accept()
try:
# Parse instance_id
instance_uuid = uuid.UUID(instance_id)
except ValueError:
await websocket.close(code=4001, reason="Invalid instance ID")
return
# Authenticate user from session cookie
user_id = await _get_user_from_websocket(websocket, db_session)
if user_id is None:
await websocket.close(code=4003, reason="Unauthorized")
return
# Get instance and verify ownership
instance = await db_session.get(ToolInstance, instance_uuid)
if instance is None:
await websocket.close(code=4004, reason="Instance not found")
return
if instance.owner_id != user_id:
await websocket.close(code=4003, reason="Forbidden")
return
if instance.status != "running" or not instance.container_id:
await websocket.close(code=4004, reason="Instance not running")
return
# Create terminal session
try:
session = await terminal_manager.create_session(
instance_uuid,
instance.container_id,
websocket,
)
# Send connected status
await websocket.send_json({"type": "status", "status": "connected"})
# Keep connection alive until closed
while True:
try:
message = await websocket.receive()
if message["type"] == "websocket.disconnect":
break
except WebSocketDisconnect:
break
except RuntimeError:
break
except Exception as exc:
await websocket.close(code=4000, reason=f"Error: {exc}")
finally:
# Cleanup will be handled by the session manager
pass
async def _get_user_from_websocket(
websocket: WebSocket,
db_session: AsyncSession,
) -> uuid.UUID | None:
"""Extract and validate user ID from session cookie in WebSocket."""
from src.auth.session import verify_session_token
session_cookie = websocket.cookies.get("session")
if not session_cookie:
return None
user_id = verify_session_token(session_cookie)
if not user_id:
return None
try:
return uuid.UUID(user_id)
except ValueError:
return None
+2
View File
@@ -11,6 +11,7 @@ from src.api.dashboard import router as dashboard_router
from src.api.git_repositories import router as git_repositories_router
from src.api.projects import router as projects_router
from src.api.ssh_keys import router as ssh_keys_router
from src.api.terminal import router as terminal_router
from src.api.tool_instances import router as tool_instances_router
from src.api.tool_instances import sessions_router
from src.api.tool_types import router as tool_types_router
@@ -168,4 +169,5 @@ app.include_router(user_config_router)
app.include_router(tool_types_router)
app.include_router(tool_instances_router)
app.include_router(sessions_router)
app.include_router(terminal_router)
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
+96
View File
@@ -0,0 +1,96 @@
"""Terminal session manager for WebSocket connections."""
import asyncio
import uuid
from typing import Any
from fastapi import WebSocket
from src.services.terminal_session import TerminalSession
class TerminalManager:
"""Manages active terminal sessions."""
def __init__(self) -> None:
self._sessions: dict[str, TerminalSession] = {}
async def create_session(
self,
instance_id: uuid.UUID,
container_id: str,
websocket: WebSocket,
) -> TerminalSession:
"""Create a new terminal session."""
session_id = str(uuid.uuid4())
session = TerminalSession(session_id, instance_id, container_id)
await session.start()
self._sessions[session_id] = session
# Start background tasks for I/O streaming
asyncio.create_task(self._read_loop(session, websocket))
asyncio.create_task(self._write_loop(session, websocket))
return session
async def _read_loop(self, session: TerminalSession, websocket: WebSocket) -> None:
"""Read output from the container and send to WebSocket."""
try:
while session.is_alive() and not session._closed:
data = await session.read_output()
if data:
await websocket.send_bytes(data)
else:
await asyncio.sleep(0.01)
except Exception:
pass
finally:
await self._cleanup_session(session)
async def _write_loop(self, session: TerminalSession, websocket: WebSocket) -> None:
"""Read input from WebSocket and send to container."""
try:
while session.is_alive() and not session._closed:
message = await websocket.receive()
if message["type"] == "websocket.receive":
if "bytes" in message:
await session.write_input(message["bytes"])
elif "text" in message:
text = message["text"]
if text.startswith("{"):
# Control message (JSON)
import json
try:
ctrl = json.loads(text)
if ctrl.get("type") == "resize":
await session.resize(
ctrl.get("cols", 80),
ctrl.get("rows", 24),
)
except json.JSONDecodeError:
pass
else:
await session.write_input(text.encode("utf-8"))
elif message["type"] == "websocket.disconnect":
break
except Exception:
pass
finally:
await self._cleanup_session(session)
async def _cleanup_session(self, session: TerminalSession) -> None:
"""Clean up a session."""
if session.session_id in self._sessions:
del self._sessions[session.session_id]
await session.close()
async def close_all(self) -> None:
"""Close all active sessions."""
sessions = list(self._sessions.values())
self._sessions.clear()
for session in sessions:
await session.close()
# Global terminal manager instance
terminal_manager = TerminalManager()
+90
View File
@@ -0,0 +1,90 @@
"""Terminal session management for tool instances."""
import asyncio
import uuid
from typing import Any
class TerminalSession:
"""Manages a single terminal session connected to a docker container."""
def __init__(self, session_id: str, instance_id: uuid.UUID, container_id: str) -> None:
self.session_id = session_id
self.instance_id = instance_id
self.container_id = container_id
self.process: asyncio.subprocess.Process | None = None
self._closed = False
async def start(self) -> None:
"""Start the docker exec process with a shell."""
self.process = await asyncio.create_subprocess_exec(
"docker",
"exec",
"-i",
self.container_id,
"/bin/sh",
"-c",
"exec bash -l || exec sh -l",
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
)
async def read_output(self) -> bytes:
"""Read output from the process."""
if self.process is None or self.process.stdout is None:
return b""
try:
return await self.process.stdout.read(4096)
except (asyncio.CancelledError, BrokenPipeError):
return b""
async def write_input(self, data: bytes) -> None:
"""Write input to the process."""
if self.process is None or self.process.stdin is None or self._closed:
return
try:
self.process.stdin.write(data)
await self.process.stdin.drain()
except (BrokenPipeError, ConnectionResetError):
pass
async def resize(self, cols: int, rows: int) -> None:
"""Resize the terminal."""
if self._closed:
return
try:
proc = await asyncio.create_subprocess_exec(
"docker",
"exec",
self.container_id,
"stty",
"cols",
str(cols),
"rows",
str(rows),
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
)
await proc.wait()
except Exception:
pass
async def close(self) -> None:
"""Close the session and cleanup."""
if self._closed:
return
self._closed = True
if self.process is not None:
try:
self.process.kill()
await asyncio.wait_for(self.process.wait(), timeout=2.0)
except (asyncio.TimeoutError, ProcessLookupError):
pass
def is_alive(self) -> bool:
"""Check if the session process is still running."""
if self.process is None:
return False
return self.process.returncode is None