Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(terminal): resize the PTY to fill the window (SIGWINCH + send size on connect) (#710)

Call White268a35da235e
diff --git a/core/terminal_service.py b/core/terminal_service.py
index cfb2b42be..82e31930f 100644
--- a/core/terminal_service.py
+++ b/core/terminal_service.py
@@ -444,6 +444,16 @@ class TerminalService:
cols = max(1, min(int(cols), 1000))
payload = struct.pack("HHHH", rows, cols, 0, 0)
await asyncio.to_thread(fcntl.ioctl, connection.master_fd, termios.TIOCSWINSZ, payload)
+ # TIOCSWINSZ updates the PTY winsize, but the kernel only raises SIGWINCH on the
+ # slave's foreground process group — and our child has none. open() spawns it with
+ # start_new_session=True and the slave dup'd onto its std fds (never opened by the
+ # session leader), so the slave is not the child's controlling terminal. Without
+ # SIGWINCH the tmux client (and any SIGWINCH-driven TUI) never re-reads the new size,
+ # so the pane stays pinned at tmux's 80x24 default no matter how large the browser
+ # window grows — the "output only fills the top of the window" bug. Deliver the signal
+ # to the child's process group ourselves. (A controlling terminal would make this
+ # native, but that needs a preexec_fn we deliberately avoid; see open() for why.)
+ _signal_winch(connection.process.pid)
connection.touch()
async def _write_all(self, fd: int, data: bytes) -> None:
@@ -756,3 +766,17 @@ def _close_fd(fd: int) -> None:
os.close(fd)
except OSError:
pass
+
+
+def _signal_winch(pid: int) -> None:
+ """Send SIGWINCH to a terminal child's process group so it re-reads the PTY size.
+
+ The child is its own session/group leader (start_new_session=True), so its pgid equals
+ its pid and the group holds the tmux client (or fallback shell and, with job control
+ disabled for want of a controlling terminal, its foreground job). A child that has
+ already exited is a no-op, not an error.
+ """
+ try:
+ os.killpg(os.getpgid(pid), signal.SIGWINCH)
+ except (ProcessLookupError, PermissionError, OSError):
+ pass
diff --git a/tests/test_terminal_backend.py b/tests/test_terminal_backend.py
index 30675f631..bc31d9bc6 100644
--- a/tests/test_terminal_backend.py
+++ b/tests/test_terminal_backend.py
@@ -346,6 +346,39 @@ async def _terminal_resize_applies_winsize(monkeypatch, tmp_path):
await service.shutdown()
+def test_terminal_resize_signals_winch_to_child_group(monkeypatch, tmp_path):
+ asyncio.run(_terminal_resize_signals_winch(monkeypatch, tmp_path))
+
+
+async def _terminal_resize_signals_winch(monkeypatch, tmp_path):
+ # The PTY child has no controlling terminal (start_new_session + dup'd slave), so the
+ # kernel never raises SIGWINCH on a winsize change. resize() must deliver it to the
+ # child's process group itself, or the tmux client never re-reads the new size.
+ (tmp_path / "home").mkdir()
+ monkeypatch.setenv("SHELL", "/bin/sh")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(terminal_service, "resolve_tmux_binary", lambda: None)
+ calls: list[tuple[int, int]] = []
+ real_killpg = terminal_service.os.killpg
+ monkeypatch.setattr(terminal_service.os, "killpg", lambda pgid, sig: calls.append((pgid, sig)))
+ service = TerminalService(idle_timeout_seconds=60, max_sessions=2)
+ connection = await service.open("winch")
+ try:
+ expected_pgid = os.getpgid(connection.process.pid)
+ await service.resize(connection, cols=120, rows=40)
+ assert calls == [(expected_pgid, signal.SIGWINCH)]
+ finally:
+ monkeypatch.setattr(terminal_service.os, "killpg", real_killpg)
+ await service.close(connection)
+ await service.shutdown()
+
+
+def test_signal_winch_ignores_missing_process():
+ # A resize that races a just-exited child must be a no-op, not an error: getpgid on an
+ # unknown pid raises ProcessLookupError, which _signal_winch is expected to swallow.
+ terminal_service._signal_winch(2**31 - 1)
+
+
def test_terminal_tmux_launch_command_uses_safe_session():
cmd = _tmux_launch_command("/tmp/tmux", sanitize_session_id("../bad session!"))
diff --git a/ui/src/components/workbench/TerminalView.tsx b/ui/src/components/workbench/TerminalView.tsx
index 8e8253cc3..55e12f10b 100644
--- a/ui/src/components/workbench/TerminalView.tsx
+++ b/ui/src/components/workbench/TerminalView.tsx
@@ -90,6 +90,24 @@ export const TerminalView: React.FC<{
term.loadAddon(fit);
termRef.current = term;
const settleTimers: number[] = [];
+ let resizeSendTimer: number | null = null;
+ // Push the CURRENT terminal size to the PTY. The backend only learns the size from these
+ // messages, and xterm's onResize fires ONLY on a change — so a no-op fit (the size already
+ // settled before connect/reconnect) would otherwise never tell the PTY, leaving it at the
+ // default 24x80. A maximized window then shows the shell using only the top ~24 rows with a
+ // big blank area below (and the cursor stuck partway up).
+ const sendSize = () => {
+ const term = termRef.current;
+ const ws = wsRef.current;
+ if (term && ws && ws.readyState === WebSocket.OPEN) {
+ ws.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }));
+ }
+ };
+ // Debounced so a maximize/restore animation's flurry of fits sends just the final size.
+ const queueSendSize = () => {
+ if (resizeSendTimer != null) window.clearTimeout(resizeSendTimer);
+ resizeSendTimer = window.setTimeout(sendSize, 80);
+ };
const refit = () => {
const el = containerRef.current;
// Skip when the container is hidden (a background tab uses display:none → 0×0): fitting to
@@ -102,6 +120,8 @@ export const TerminalView: React.FC<{
} catch {
/* container not measured yet */
}
+ // Always (re)send the fitted size — covers the no-op fit at connect/reconnect that onResize misses.
+ queueSendSize();
};
// A single fit can land before BOTH the layout and xterm's own character-cell metrics have
// settled. On some browsers (notably Safari) the cell size finalises a frame or two after
@@ -133,11 +153,6 @@ export const TerminalView: React.FC<{
}
ws.send(ENC.encode(out));
});
- const onResize = term.onResize(({ cols, rows }: { cols: number; rows: number }) => {
- const ws = wsRef.current;
- if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'resize', cols, rows }));
- });
-
setStatus('connecting');
setExitCode(null);
const ws = new WebSocket(buildWsUrl(sessionId));
@@ -195,10 +210,10 @@ export const TerminalView: React.FC<{
return () => {
if (retryTimerRef.current != null) window.clearTimeout(retryTimerRef.current);
+ if (resizeSendTimer != null) window.clearTimeout(resizeSendTimer);
for (const id of settleTimers) window.clearTimeout(id);
ro.disconnect();
onData.dispose();
- onResize.dispose();
// Detach handlers before closing. A closing socket's onclose can fire asynchronously
// *after* its replacement has already reported 'ready' (reconnect / effect remount);
// left attached, the stale onclose would mark the live terminal 'closed' or schedule a