diff --git a/cptr/routers/terminal.py b/cptr/routers/terminal.py index 3a70179..dc3c8b1 100644 --- a/cptr/routers/terminal.py +++ b/cptr/routers/terminal.py @@ -10,7 +10,7 @@ from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect from pydantic import BaseModel from cptr.utils.config import check_access -from cptr.utils.terminal import manager, IS_WINDOWS +from cptr.utils.terminal import TerminalUnavailable, manager, IS_WINDOWS from cptr.utils.tools import ( command_session_bytes_since, drain_command_session_input, @@ -57,7 +57,10 @@ class CommandSessionInfo(BaseModel): async def create_session(req: CreateSessionRequest): """Create a new terminal session.""" logger.info(f"Creating terminal session: cwd={req.cwd}, rows={req.rows}, cols={req.cols}") - session = manager.create(rows=req.rows, cols=req.cols, cwd=req.cwd) + try: + session = manager.create(rows=req.rows, cols=req.cols, cwd=req.cwd) + except TerminalUnavailable as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc logger.info( f"Created session {session.session_id} at {session.cwd}, fd={session._fd}, alive={session.is_alive()}" ) diff --git a/cptr/utils/terminal.py b/cptr/utils/terminal.py index 2c14bfd..a36a97f 100644 --- a/cptr/utils/terminal.py +++ b/cptr/utils/terminal.py @@ -18,6 +18,10 @@ SCROLLBACK_SIZE = 64 * 1024 # 64 KB IS_WINDOWS = platform.system() == "Windows" +class TerminalUnavailable(RuntimeError): + """Raised when the platform terminal backend cannot be loaded.""" + + @dataclass class TerminalSession: """Platform-agnostic terminal session with scrollback buffer.""" @@ -194,7 +198,14 @@ def _create_windows( session_id: str, shell: str, work_dir: str, env: dict, rows: int, cols: int ) -> TerminalSession: """Create a terminal session on Windows using pywinpty.""" - from winpty import PtyProcess # type: ignore + try: + from winpty import PtyProcess # type: ignore + except (ImportError, OSError) as exc: + raise TerminalUnavailable( + "Windows terminal support requires pywinpty and the Microsoft Visual C++ " + "Redistributable. Install the latest supported Visual C++ Redistributable " + "from Microsoft, then restart cptr." + ) from exc proc = PtyProcess.spawn( [shell],