Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(cli): delete the PTY session when the terminal WebSocket never opens
Maohao1760f43a3598
diff --git a/cli/src/opensandbox_cli/commands/terminal.py b/cli/src/opensandbox_cli/commands/terminal.pyindex 2d7fbf0e3..76260f3ee 100644--- a/cli/src/opensandbox_cli/commands/terminal.py+++ b/cli/src/opensandbox_cli/commands/terminal.py@@ -259,9 +259,12 @@ async def _connect_and_stream(stdout_write: WriteFn,get_size: SizeFn,error_write: WriteFn | None = None,+ on_connected: Callable[[], None] | None = None,) -> tuple[int | None, list[str]]:"""Connect to the PTY WebSocket, drive the relay loop, handle resize."""async with websockets.connect(ws_url, additional_headers=headers or None) as ws:+ if on_connected is not None:+ on_connected()# websockets forbids concurrent sends: stdin frames and SIGWINCH# resize frames share one lock, and fire-and-forget resize tasks get# their results consumed so failures never surface as task warnings.@@ -364,6 +367,12 @@ def terminal(exit_code: int | None = Noneerrors: list[str] = []teardown = False+ connected = False++ def mark_connected() -> None:+ nonlocal connected+ connected = True+try:with _raw_mode(stdin_fd):exit_code, errors = asyncio.run(@@ -374,6 +383,7 @@ def terminal(stdout_write=stdout_write,get_size=get_size,error_write=report_error,+ on_connected=mark_connected,))teardown = exit_code is not None or bool(errors)@@ -385,9 +395,10 @@ def terminal(raise click.ClickException(f"Terminal connection failed: {exc}") from excfinally:# Clean exit tears the session down, as does a reported failure (e.g.- # START_FAILED: the shell never ran, so there is nothing to preserve).- # A lost connection on a live shell is the one case worth keeping.- if teardown:+ # START_FAILED: the shell never ran, so there is nothing to preserve)+ # or a WebSocket that never opened (the shell starts on the first+ # one). A lost connection on a live shell is the one case worth keeping.+ if teardown or not connected:_delete_pty_session(http_base, headers, session_id, timeout=timeout)if exit_code is None:diff --git a/cli/tests/test_commands.py b/cli/tests/test_commands.pyindex 39f11309c..bc05d7a52 100644--- a/cli/tests/test_commands.py+++ b/cli/tests/test_commands.py@@ -50,6 +50,8 @@ from opensandbox.models.templates import (TemplateInfo,TemplateStatus,)+from websockets.datastructures import Headers+from websockets.http11 import Responsefrom opensandbox_cli.commands.terminal import _make_stdin_reader, stream_ptyfrom opensandbox_cli.config import load_config_file@@ -2601,6 +2603,7 @@ def _invoke_terminal(*,incoming: list,stdin_chunks: list[bytes] | None = None,+ connect_error: Exception | None = None,):"""Run `osb terminal` with the execd PTY boundary fully mocked.@@ -2630,6 +2633,8 @@ def _invoke_terminal(def fake_connect(url: str, additional_headers: dict | None = None):connect_calls.append((url, additional_headers))+ if connect_error is not None:+ raise connect_errorreturn wswith patch("opensandbox_cli.main.resolve_config") as mock_resolve, \@@ -2733,6 +2738,26 @@ class TestTerminal:assert "no such dir" in result.stderrassert delete.call_args.args[2] == "sess-1"+ @pytest.mark.parametrize(+ "error",+ [+ OSError("connection refused"),+ websockets.InvalidStatus(Response(403, "Forbidden", Headers())),+ ],+ )+ def test_failed_connect_deletes_session(+ self, runner: CliRunner, error: Exception+ ) -> None:+ result, _, _, delete, _, _ = _invoke_terminal(+ runner,+ ["terminal", "sbx-1"],+ incoming=[],+ connect_error=error,+ )++ assert result.exit_code == 1+ assert delete.call_args.args[2] == "sess-1"+def test_server_error_frames_are_reported_on_stderr(self, runner: CliRunner) -> None: