Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: initialize terminal dimensions before shell startup (#10830)

Myles Scolnick8521d669c597
diff --git a/frontend/src/components/terminal/terminal.tsx b/frontend/src/components/terminal/terminal.tsx
index 5dc811b6d5..230b4d7799 100644
--- a/frontend/src/components/terminal/terminal.tsx
+++ b/frontend/src/components/terminal/terminal.tsx
@@ -254,7 +254,9 @@ const TerminalComponent: React.FC<TerminalComponentProps> = ({
try {
await waitForConnectionOpen();
- const socket = new WebSocket(runtimeManager.getTerminalWsURL());
+ // Size the PTY before the shell draws its first prompt.
+ fitAddon.fit();
+ const socket = new WebSocket(runtimeManager.getTerminalWsURL(terminal));
const attachAddon = new AttachAddon(socket);
terminal.loadAddon(attachAddon);
wsRef.current = socket;
@@ -270,9 +272,7 @@ const TerminalComponent: React.FC<TerminalComponentProps> = ({
const handleOpen = () => {
updateReadyState();
- // Send initial dimensions: the mount-time fit() may have fired
- // before the WS was OPEN, dropping the resize message and leaving
- // the PTY at its default 0x0 winsize.
+ // The container may have resized while the connection was opening.
fitAddon.fit();
if (terminal.cols > 0 && terminal.rows > 0) {
socket.send(
diff --git a/frontend/src/core/runtime/__tests__/runtime.test.ts b/frontend/src/core/runtime/__tests__/runtime.test.ts
index f2b2eb09c2..b98d08acee 100644
--- a/frontend/src/core/runtime/__tests__/runtime.test.ts
+++ b/frontend/src/core/runtime/__tests__/runtime.test.ts
@@ -276,6 +276,17 @@ describe("RuntimeManager", () => {
});
describe("getTerminalWsURL", () => {
+ it("should include dimensions in the terminal handshake", () => {
+ const runtime = new RuntimeManager(mockConfig);
+ const url = runtime.getTerminalWsURL({ rows: 30, cols: 140 });
+
+ expect(Object.fromEntries(url.searchParams)).toEqual({
+ access_token: "test-token",
+ rows: "30",
+ cols: "140",
+ });
+ });
+
it("should return terminal WebSocket URL", () => {
const runtime = new RuntimeManager(mockConfig);
const url = runtime.getTerminalWsURL();
diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.ts
index 1db04cc6fd..b49d4bfc00 100644
--- a/frontend/src/core/runtime/runtime.ts
+++ b/frontend/src/core/runtime/runtime.ts
@@ -183,8 +183,13 @@ export class RuntimeManager {
/**
* The WebSocket URL of the terminal.
*/
- getTerminalWsURL(): URL {
- return this.formatWsURL("/terminal/ws");
+ getTerminalWsURL(size?: { rows: number; cols: number }): URL {
+ const url = this.formatWsURL("/terminal/ws");
+ if (size) {
+ url.searchParams.set("rows", String(size.rows));
+ url.searchParams.set("cols", String(size.cols));
+ }
+ return url;
}
/**
diff --git a/marimo/_server/api/endpoints/terminal.py b/marimo/_server/api/endpoints/terminal.py
index 9d7f5245f3..ca9e0b925f 100644
--- a/marimo/_server/api/endpoints/terminal.py
+++ b/marimo/_server/api/endpoints/terminal.py
@@ -40,7 +40,19 @@ READ_TIMEOUT = 0.05
IDLE_SLEEP = 0.01
-def _resize_pty(fd: int, rows: int, cols: int) -> None:
+def _get_initial_terminal_size(websocket: WebSocket) -> tuple[int, int]:
+ try:
+ rows = int(websocket.query_params.get("rows", "24"))
+ cols = int(websocket.query_params.get("cols", "80"))
+ # The PTY window size uses unsigned shorts.
+ if 0 < rows <= 65535 and 0 < cols <= 65535:
+ return rows, cols
+ except ValueError:
+ pass
+ return 24, 80
+
+
+def _resize_pty(fd: int, rows: int, cols: int, *, log: bool = True) -> None:
"""Resize the PTY to the specified dimensions."""
try:
# Use TIOCSWINSZ ioctl to set window size
@@ -50,9 +62,11 @@ def _resize_pty(fd: int, rows: int, cols: int) -> None:
# Format: struct winsize { unsigned short ws_row, ws_col, ws_xpixel, ws_ypixel }
winsize = struct.pack("HHHH", rows, cols, 0, 0)
fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
- LOGGER.debug(f"PTY resized to {cols}x{rows}")
+ if log:
+ LOGGER.debug(f"PTY resized to {cols}x{rows}")
except Exception as e:
- LOGGER.warning(f"Failed to resize PTY: {e}")
+ if log:
+ LOGGER.warning(f"Failed to resize PTY: {e}")
def _send_sigwinch(pid: int) -> None:
@@ -390,6 +404,8 @@ async def websocket_endpoint(websocket: WebSocket) -> None:
try:
import pty
+ rows, cols = _get_initial_terminal_size(websocket)
+
# TODO(akshayka): Someone should clean this up to make it safe on
# macOS.
#
@@ -399,6 +415,9 @@ async def websocket_endpoint(websocket: WebSocket) -> None:
# See https://docs.python.org/3/library/pty.html
child_pid, fd = pty.fork()
if child_pid == 0:
+ # Resize stdin (the PTY slave) before exec so shell startup cannot
+ # race the browser's first resize. Child logs would enter the PTY.
+ _resize_pty(0, rows, cols, log=False)
# Child process - set up the shell environment
shell, env = _create_shell_environment()
cwd = env.get("PWD", os.getcwd())
diff --git a/tests/_server/api/endpoints/test_terminal.py b/tests/_server/api/endpoints/test_terminal.py
index dfc32da669..10d7ce9d7b 100644
--- a/tests/_server/api/endpoints/test_terminal.py
+++ b/tests/_server/api/endpoints/test_terminal.py
@@ -1,22 +1,26 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import json
+import logging
import os
import signal
import sys
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING
-from unittest.mock import Mock, patch
+from unittest.mock import Mock, call, patch
import pytest
from starlette.websockets import WebSocketDisconnect
from marimo._server.api.endpoints.terminal import (
+ LOGGER,
_create_process_cleanup_handler,
_create_shell_environment,
_decode_pty_data,
_manage_command_buffer,
+ _resize_pty,
_setup_child_process,
_should_close_on_command,
)
@@ -50,6 +54,97 @@ def test_terminal_ws(client: TestClient) -> None:
assert "echo hello" in data
+ is_windows or is_mac, reason="PTY integration requires Linux"
+)
+ ("query", "expected_size"),
+ [
+ ("&rows=30&cols=140", (30, 140)),
+ ("", (24, 80)),
+ ("&rows=0&cols=140", (24, 80)),
+ ("&rows=30&cols=-1", (24, 80)),
+ ("&rows=invalid&cols=140", (24, 80)),
+ ("&rows=30&cols=65536", (24, 80)),
+ ],
+)
+def test_terminal_ws_initial_size(
+ client: TestClient,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ query: str,
+ expected_size: tuple[int, int],
+) -> None:
+ shell = tmp_path / "shell"
+ shell.write_text(
+ "#!/bin/sh\nstty size\nwhile read -r line; do stty size; done\n"
+ )
+ shell.chmod(0o755)
+ monkeypatch.setenv("SHELL", str(shell))
+
+ with client.websocket_connect(TERMINAL_WS_URL + query) as websocket:
+ # No resize message is sent until the shell has reported its size.
+ data = ""
+ while "\n" not in data:
+ data += websocket.receive_text()
+ assert tuple(map(int, data.split())) == expected_size
+
+ websocket.send_text(
+ json.dumps({"type": "resize", "rows": 40, "cols": 160})
+ )
+ websocket.send_text("\n")
+ data = ""
+ while "40 160" not in data:
+ data += websocket.receive_text()
+ assert data.strip() == "40 160"
+
+
+ is_windows or is_mac, reason="PTY integration requires Linux"
+)
[email protected]("log_level", [logging.WARNING, logging.DEBUG])
+def test_terminal_ws_long_prompt(
+ client: TestClient,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+ log_level: int,
+) -> None:
+ caplog.set_level(log_level, logger=LOGGER.name)
+ # Use the real stderr so the inherited handler writes to the PTY slave.
+ monkeypatch.setattr(
+ LOGGER, "handlers", [logging.StreamHandler(sys.__stderr__)]
+ )
+ shell = tmp_path / "shell"
+ shell.write_text("#!/bin/sh\nexec /bin/bash --noprofile --norc -i\n")
+ shell.chmod(0o755)
+ monkeypatch.setenv("SHELL", str(shell))
+ prompt = (
+ "henkan@session-gbm-henkan-notebook-m-6b3c03b8238e-56ddd64d76-5p27b"
+ ":~/notebooks$ "
+ )
+ monkeypatch.setenv("PS1", prompt)
+ monkeypatch.setenv("LC_ALL", "C")
+ monkeypatch.delenv("PROMPT_COMMAND", raising=False)
+
+ with client.websocket_connect(
+ TERMINAL_WS_URL + "&rows=30&cols=140"
+ ) as websocket:
+ data = ""
+ while "$ " not in data:
+ data += websocket.receive_text()
+ # Type before sending any resize message, as on a slow connection.
+ websocket.send_text("ls")
+ while not data.endswith("ls"):
+ data += websocket.receive_text()
+
+ # A wrong initial width makes Bash emit a carriage return after the
+ # prompt, placing typed characters over its first letters.
+ assert data.replace("\x1b[?2004h", "") == prompt + "ls"
+
+
def test_terminal_ws_not_allowed_in_run(client: TestClient) -> None:
session_manager: SessionManager = get_session_manager(client)
session_manager.mode = SessionMode.RUN
@@ -78,6 +173,39 @@ def test_terminal_ws_wrong_token(client: TestClient) -> None:
# Unit tests for terminal utility functions
[email protected](is_windows, reason="Skip on Windows")
[email protected]("log", [True, False])
+def test_resize_pty_logging(log: bool) -> None:
+ import pty
+
+ master, slave = pty.openpty()
+ try:
+ with patch("marimo._server.api.endpoints.terminal.LOGGER") as logger:
+ _resize_pty(slave, 30, 140, log=log)
+ assert os.get_terminal_size(slave) == (140, 30)
+ assert logger.mock_calls == (
+ [call.debug("PTY resized to 140x30")] if log else []
+ )
+ finally:
+ os.close(master)
+ os.close(slave)
+
+
[email protected](is_windows, reason="Skip on Windows")
[email protected]("log", [True, False])
+def test_resize_pty_failure_logging(log: bool) -> None:
+ with (
+ patch("fcntl.ioctl", side_effect=OSError("resize failed")),
+ patch("marimo._server.api.endpoints.terminal.LOGGER") as logger,
+ ):
+ _resize_pty(0, 30, 140, log=log)
+ assert logger.mock_calls == (
+ [call.warning("Failed to resize PTY: resize failed")]
+ if log
+ else []
+ )
+
+
class TestCreateShellEnvironment:
def test_create_shell_environment_default_cwd(
self, monkeypatch: pytest.MonkeyPatch