diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 3640dfc5..4cf4b5b7 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -801,7 +801,7 @@ Further detail: with many sessions the horizontal strip stops being scannable, w ### Split-pane sessions -**Split-pane sessions** (`showSplitButton`, header button, default OFF, per-device like `showFileViewerButton` — not in `SettingsUpdateSchema`, `displayKeys` in settings-ui.js): shows two live sessions side-by-side in one Codeman window. Pane A is the untouched, existing singleton terminal (`this.terminal`/`this._ws` in terminal-ui.js); Pane B is an independent `TerminalTile` (terminal-tile.js, constructed by the orchestration in terminal-split.js) with its own xterm instance and its own `/ws/sessions/:id/terminal` WebSocket, whose `cid` is the tab's identity with a `:tile` suffix, so it can never supersede the primary pane's socket (the registry supersedes by cid per session). ⚠️ **Pane B is deliberately plainer than Pane A** — no local-echo overlay, no CJK IME, no touch/mobile handlers, no keyboard accessory bar (it does carry the primary pane's hollow-buffer wheel paging and desktop click report, through terminal-ui.js's own gates aimed at the tile, and its own keyCode-229 soft-keyboard controller from terminal-keycode229-recovery.js, the #441 next-keydown drain and #541's edit-based diff for Android autocorrect, since the 1180px width gate is reachable by a wide Android tablet; see terminal-tile.js's fileoverview) — since this is a desktop-only feature (a split view needs a wide viewport) and those features exist for mobile/touch input; `.btn-split` is hard-hidden below 1180px regardless of the setting by the `@media (max-width: 1179px)` rule in styles.css (mobile.css only carries a comment pointing at it: that file loads up to 1023px, so it cannot cover the 1024-1179px tablet range the feature also needs to stay off), and the per-device setting means turning it on at a desk can never sync it onto a phone in the first place. No persistence: closing the browser tab or reloading always returns to the normal single-pane view; there is no localStorage key for split state. ⚠️ Splitting a session against itself is disallowed (the picker excludes the active session), **as is splitting against a popped-out (detached) session** — `buildSplitPickerSessions()` excludes `detachedSessions` because a detached session's own window is already claiming its PTY size, and `MAX_WS_PER_SESSION` needs no change since Pane A/B are always two different sessions. ⚠️ Either pane's session ending (deleted locally or from another client) auto-collapses the split — Pane A's session ending promotes Pane B to the new single pane via `selectSession(id, { auto: true })` (an app-driven selection, so it must not spend the session's idle alert — see the Approvals Inbox note above), never by trying to hot-swap the lightweight `TerminalTile` object into the primary singleton state. ⚠️ Pane B refits on every window/sidebar/tab-rail resize via the SAME trailing-edge `ResizeObserver` callback that resizes Pane A (`throttledResize` in terminal-ui.js) — it only ever measured Pane A's own container, so without the explicit `this._forEachTile?.((tile) => tile.fit(), { grid: false })` call there (grid tiles are left out: the grid's own observer refits them on the same resize) Pane B silently kept its stale PTY size through every resize that did not happen to be a divider drag. ⚠️ A dropped WebSocket writes a `[disconnected, reconnecting…]` marker into Pane B and reconnects on the primary pane's backoff ladder (`CodemanWsReconnect` plus jitter; the attempt count resets only on a successful open), then refreshes the buffer to close the output gap. ⚠️ The open handler clears `_wsClosed`/`_markerOwed` BEFORE that refresh, or the refresh re-owes the marker and stamps it under a healthy pane. ⚠️ 4003/4004/4009/4010 stop the pane for good, report once through `onExit(code)` and write a marker saying why (`CodemanWsReconnect` alone would retry 4003). ⚠️ A replacement socket detaches the old one first and every handler ignores a socket that is no longer `this.ws`, so a late 4010 from a superseded socket cannot stop its successor; `destroy()` cancels a pending reconnect. Related but distinct: `detachSession()` already opens one session in a separate OS-level browser window (`isSoloWindow`) — that is prior art for "two sessions visible at once" but not for one window with a draggable in-page divider, which is what this feature adds. ⚠️ Pane B installs its own `attachCustomKeyEventHandler` gating the same app-level chords Pane A's own handler gates (command palette, Alt+1-9/[/] tab nav, Alt+B sidebar toggle, Ctrl+Z suspend, Shift/Ctrl+Enter newline, smart-copy Ctrl+C) — without it the document capture-phase handler's `preventDefault()` (which never stops xterm) let each chord ALSO write its raw byte/escape sequence into Pane B's live PTY on top of whatever the app action did to Pane A (COD-153). Ctrl+Z is swallowed unless Pane B's own session is `mode === 'shell'`, mirroring terminal-ui.js's reasoning: in a plain shell it is the user's own job-control tool, everywhere else it silently suspends an unattended agent loop. Shift/Ctrl+Enter POSTs to `/api/sessions/:id/send-key` (`{key:'S-Enter'|'C-Enter'}`, typed by tmux `send-keys -H`: Ctrl+Enter is always a real 0x0a, Shift+Enter is the CLI's declared `capabilities.newline` chord, also 0x0a unless the CLI declares another; sent on keydown only, with the keypress and keyup swallowed too, see the keypress rule under Command palette and shortcut registry) targeting THIS pane's own `sessionId` rather than the primary pane's `activeSessionId` — without it xterm's plain `\r` would submit an incomplete prompt instead of adding a line to it. Smart-copy Ctrl+C/Ctrl+Shift+C is re-implemented against `this.terminal` (Pane B's own) rather than reusing `app.copyTerminalSelection()`, which reads Pane A's terminal and would copy the wrong pane's selection; Ctrl+Shift+C never falls through even with nothing to copy, mirroring terminal-ui.js's own `ev.shiftKey` branch. ⚠️ **This is a UX-parity fix, not an interrupt-safety one** — verified live in a real browser: xterm's `evaluateKeyboardEvent` routes a shifted ctrl-letter into a branch that assigns `c.key` only for two special cases (`_`→US, `@`→NUL), so it emits no data for Ctrl+Shift+C at all regardless of any application gate; a synthetic keydown with the gate removed produces zero WS frames, proving no accidental interrupt reaches the PTY either way. What gating the whole copy block on `hasSelection()` (an earlier draft) actually cost: with no selection, a selection-less Ctrl+Shift+C fell straight to `return true`, silently ceding the keystroke to the BROWSER's own handling (e.g. Chrome's Inspect-Element binding) with no feedback and no copy attempt — Pane A always intercepts it. Ctrl+V goes through the primary pane's paste trap aimed at Pane B (`_handleImagePaste({ terminal, sessionId })`), so a pasted image uploads to Pane B's session. ⚠️ `buildSplitPickerSessions()` also excludes any session with `pid === null` (an exited CLI, a crash-looped session whose breaker tripped, a restore that never re-attached): Pane B has no equivalent of `selectSession()`'s auto re-attach POST, so a pane opened onto one has nothing reading its tmux pane — no `terminal` events ever arrive, and `Session.write()` silently drops every keystroke with no ack either way, so the loss is invisible behind a socket that reports healthy. Pane B's keystrokes go through the exactly-once queue (`_sendInputAsync`) over its own socket, registered in the app's input-socket map (`_registerInputSocket` / `_inputSocketFor`), so they are seq-tagged, ACKed (`{t:'ia'}` is routed by the RECEIVING socket's session, since the frame names none), redelivered after a drop, and the ACK clears the idle alert. ⚠️ What xterm generates never enters that persisted queue: query replies are dropped (`shouldSuppressTerminalQueryResponse`, as the primary pane drops them) and focus/mouse reports go through `_sendInputEphemeral`, or a reload would replay them as typed text. That includes the click report a tile hand-encodes for a mouse-strip CLI: `TerminalTile._installClickListener` passes `ephemeral: true` in its target, which `_sendSyntheticSgrTap` honours, while the primary pane's own report (no flag) stays on `_sendInputAsync` as before. ⚠️ A SHELL Pane B pulls scrollback itself when the wheel goes up at the top of its buffer (`_maybeLoadMoreHistory`/`_pullHistory`): tmux repaints a burst of output instead of scrolling it, so Pane B's own xterm holds about one screen of scrollback while tmux holds every line, and it loaded history exactly once at connect and never again. It is the same bounded pull as Pane A's (`?full=1&tail=TERMINAL_TAIL_SIZE`, no rewrite when the window holds no more rows than the pane already has or the pane is at its `scrollback + rows` cap, and a 60 s back-off instead of 4 s when that skipped window was truncated or the pane is full, since each ask costs the server a whole-history `capture-pane`), against Pane B's OWN terminal rather than `app.terminal`, so it cannot share `_maybeRefetchFullHistory`. The wheel listener is capture-phase because xterm `stopPropagation()`s the events it consumes; the alternate-screen skip (nano, vim, less) only matters for a direct-PTY shell, since under tmux the browser xterm never enters the alternate buffer; skipped too for a detached session (mirrors `_sendResize()`'s own check and app.js's `_maybeRefetchFullHistory`), since its own window already owns its PTY size and scrollback. Live frames arriving from the response onward are held with their arrival time (`_liveQueue`, opened right after `await fetch(...)` beside `capturedAt`; a frame from before it is replaced by the capture or written unchanged, so the pane keeps painting during the round trip) and replayed in order only if they arrived after the capture (the response's arrival stands in for the capture instant, as in `_finishBufferLoad`, so a frame inside that one round trip can be lost or doubled); the request uses the primary pane's budget (`CodemanFetchDeadline.terminalFetchDeadlineMs({ full: true })`, 45 s, 10 s only if that helper is absent) and the body read gets 10 s once the headers land, because from then on the pull holds the pane's live output. The request phase holds no live output, but it does hold the single-flight flag, so a coalesced `{t:'r'}` refresh and a marker owed by a close (below) wait for the response, at worst for that whole budget (accepted: a Codeman restart resets an in-flight request along with the socket, so that pull fails at once and stamps the marker). ⚠️ The "disconnected" marker must be the LAST thing on screen. A replay's own `\x1bc` would otherwise wipe a marker written before the pull and paint a fresh, current-looking history while `onData` keeps silently dropping every keystroke on the dead socket (a Codeman restart drops the socket while the tmux session, and so the HTTP pull, still succeeds), so `_pullHistory()` re-stamps it after the live-frame flush. A close DURING any load (a pull, a refresh; `connect()` awaits the initial load before it creates the socket, so no close lands in that one) writes nothing: `_onSocketClosed()` sets `_markerOwed` while a load's work runs (`_loadRunning`; a load that only waits in the tile grid's queue writes the marker at once, and its refresh resets the screen only once its own capture is in hand), since written there it would sit above the held frames the pull flushes after a skip, a downgrade, a failed fetch or the deadline, above a refresh's replay, or land mid-way through a chunked replay. Each load settles the marker in its OWN `finally` (`_stampMarkerIfOwed()`), after the queue flush, EXCEPT when a trailing refresh is pending: that refresh settles it itself (its replay's queued `\x1bc` would wipe a marker written now, so it re-owes the marker on a closed socket and writes the one copy below its replay, and a refresh that writes nothing stamps the one still owed). The marker stays owed instead of being written twice; the default fake terminal in `test/terminal-tile-unit.test.ts` writes synchronously, so an async-parse fake there pins what ends up on screen. Anything that wipes the terminal on a closed socket (a pull's or a refresh's `\x1bc`) sets `_markerOwed` too, so the marker is rewritten whether or not the close landed during the load. Tracked via `_wsClosed`/`_markerOwed` rather than routed through `_onLiveOutput()`, since a close landing before the response is stamped before the cutoff and would be dropped with the rest of the pre-capture queue. There is no "Load full history" banner in Pane B, so a shell history past that 1 MiB window stays out of reach there. Non-shell Pane B is unchanged: it already loads `full=1`, and its history is out of scope for this pull (codex and Claude's inline renderer do grow tmux history; this just isn't how they recover it). ⚠️ A server `{t:'c'}` frame is a REFRESH, never a bare `clear()` (`_onLiveClear()` calls `_refreshBuffer()`): its one emitter is a fresh Claude pane's first prompt (`Session.startInteractive`, "refresh after startup"), the primary pane answers it with a refetch and replay (`_onSessionClearTerminal`, which stands aside while the grid is open), and xterm's `clear()` keeps only the cursor's row, so a Claude session Run into the grid or Attached in a tile came up as a near-empty tile that an idle Claude never repainted. As a refresh it coalesces behind a load already running (a pull's held frames included) and waits its turn in the grid's load queue. ⚠️ A refresh (`{t:'r'}`, `{t:'c'}`, a reconnect) runs in the primary pane's order (`_onSessionNeedsRefresh`): fetch FIRST, so the pane keeps its last frame through the round trip and through a grid tile's wait; hold live frames from the response on (`_liveQueue`; the body read of a bounded window, a grid tile's or a shell's, gets the 10 s budget, while Pane B's unbounded `full=1` keeps the request's); then the queued in-stream `\x1bc` immediately before the replay, then the held frames that arrived after the response. Never xterm's `clear()`: it is synchronous while queued bytes are parsed after it (they fused into the snapshot) and it keeps the cursor's row and column, where the capture (raw rows, no home) then started. A failed, aborted or empty fetch writes nothing and resets nothing. ⚠️ App-level terminal actions find their pane through `_focusedPane()`, the terminal focused LAST (not `document.activeElement`, which the mic or a header button takes): Ctrl+L, Ctrl+Shift+R, voice and image paste act on Pane B while it holds the keyboard. Ctrl+W is not an app shortcut at all (Close Session has no default key), so it reaches whichever pane is focused as delete-word. ⚠️ Geometry: `TerminalTile.fit()` sends the size the xterm actually holds, unfloored (the divider's 20% clamp leaves about 28 columns), skips an unchanged size, re-sends on every fresh socket, and adopts the PTY's column count from `{t:'zc'}`; the font, family and weight setters call `tile.fit()`, never a local refit alone (#464). Every capture a pane fetches carries a deadline covering the body (`CodemanFetchDeadline`), so a capture that never answers cannot hold its single-flight flag forever. Design: `docs/split-pane-sessions-plan.md`; the tile class: `docs/tile-grid-plan.md`. +**Split-pane sessions** (`showSplitButton`, header button, default OFF, per-device like `showFileViewerButton` — not in `SettingsUpdateSchema`, `displayKeys` in settings-ui.js): shows two live sessions side-by-side in one Codeman window. Pane A is the untouched, existing singleton terminal (`this.terminal`/`this._ws` in terminal-ui.js); Pane B is an independent `TerminalTile` (terminal-tile.js, constructed by the orchestration in terminal-split.js) with its own xterm instance and its own `/ws/sessions/:id/terminal` WebSocket, whose `cid` is the tab's identity with a `:tile` suffix, so it can never supersede the primary pane's socket (the registry supersedes by cid per session). ⚠️ **Pane B is deliberately plainer than Pane A** — no local-echo overlay, no CJK IME, no touch/mobile handlers, no keyboard accessory bar (it does carry the primary pane's hollow-buffer wheel paging and desktop click report, through terminal-ui.js's own gates aimed at the tile, and its own keyCode-229 soft-keyboard controller from terminal-keycode229-recovery.js, the #441 next-keydown drain and #541's edit-based diff for Android autocorrect, since the 1180px width gate is reachable by a wide Android tablet; see terminal-tile.js's fileoverview) — since this is a desktop-only feature (a split view needs a wide viewport) and those features exist for mobile/touch input; `.btn-split` is hard-hidden below 1180px regardless of the setting by the `@media (max-width: 1179px)` rule in styles.css (mobile.css only carries a comment pointing at it: that file loads up to 1023px, so it cannot cover the 1024-1179px tablet range the feature also needs to stay off), and the per-device setting means turning it on at a desk can never sync it onto a phone in the first place. No persistence: closing the browser tab or reloading always returns to the normal single-pane view; there is no localStorage key for split state. ⚠️ Splitting a session against itself is disallowed (the picker excludes the active session), **as is splitting against a popped-out (detached) session** — `buildSplitPickerSessions()` excludes `detachedSessions` because a detached session's own window is already claiming its PTY size, and `MAX_WS_PER_SESSION` needs no change since Pane A/B are always two different sessions. ⚠️ Either pane's session ending (deleted locally or from another client) auto-collapses the split — Pane A's session ending promotes Pane B to the new single pane via `selectSession(id, { auto: true })` (an app-driven selection, so it must not spend the session's idle alert — see the Approvals Inbox note above), never by trying to hot-swap the lightweight `TerminalTile` object into the primary singleton state. ⚠️ Pane B refits on every window/sidebar/tab-rail resize via the SAME trailing-edge `ResizeObserver` callback that resizes Pane A (`throttledResize` in terminal-ui.js) — it only ever measured Pane A's own container, so without the explicit `this._forEachTile?.((tile) => tile.fit(), { grid: false })` call there (grid tiles are left out: the grid's own observer refits them on the same resize) Pane B silently kept its stale PTY size through every resize that did not happen to be a divider drag. ⚠️ A dropped WebSocket writes a `[disconnected, reconnecting…]` marker into Pane B and reconnects on the primary pane's backoff ladder (`CodemanWsReconnect` plus jitter; the attempt count resets only on a successful open), then refreshes the buffer to close the output gap. ⚠️ The open handler clears `_wsClosed`/`_markerOwed` BEFORE that refresh, or the refresh re-owes the marker and stamps it under a healthy pane. ⚠️ 4003/4004/4009/4010 stop the pane for good, report once through `onExit(code)` and write a marker saying why (`CodemanWsReconnect` alone would retry 4003). ⚠️ A replacement socket detaches the old one first and every handler ignores a socket that is no longer `this.ws`, so a late 4010 from a superseded socket cannot stop its successor; `destroy()` cancels a pending reconnect. Related but distinct: `detachSession()` already opens one session in a separate OS-level browser window (`isSoloWindow`) — that is prior art for "two sessions visible at once" but not for one window with a draggable in-page divider, which is what this feature adds. ⚠️ Pane B installs its own `attachCustomKeyEventHandler` gating the same app-level chords Pane A's own handler gates (command palette, Alt+1-9/[/] tab nav, Alt+B sidebar toggle, Ctrl+Z suspend, Shift/Ctrl+Enter newline, smart-copy Ctrl+C) — without it the document capture-phase handler's `preventDefault()` (which never stops xterm) let each chord ALSO write its raw byte/escape sequence into Pane B's live PTY on top of whatever the app action did to Pane A (COD-153). Ctrl+Z is swallowed unless Pane B's own session is `mode === 'shell'`, mirroring terminal-ui.js's reasoning: in a plain shell it is the user's own job-control tool, everywhere else it silently suspends an unattended agent loop. Shift/Ctrl+Enter POSTs to `/api/sessions/:id/send-key` (`{key:'S-Enter'|'C-Enter'}`, typed by tmux `send-keys -H`: Ctrl+Enter is always a real 0x0a, Shift+Enter is the CLI's declared `capabilities.newline` chord, also 0x0a unless the CLI declares another; sent on keydown only, with the keypress and keyup swallowed too, see the keypress rule under Command palette and shortcut registry) targeting THIS pane's own `sessionId` rather than the primary pane's `activeSessionId` — without it xterm's plain `\r` would submit an incomplete prompt instead of adding a line to it. Smart-copy Ctrl+C/Ctrl+Shift+C is re-implemented against `this.terminal` (Pane B's own) rather than reusing `app.copyTerminalSelection()`, which reads Pane A's terminal and would copy the wrong pane's selection; Ctrl+Shift+C never falls through even with nothing to copy, mirroring terminal-ui.js's own `ev.shiftKey` branch. ⚠️ **This is a UX-parity fix, not an interrupt-safety one** — verified live in a real browser: xterm's `evaluateKeyboardEvent` routes a shifted ctrl-letter into a branch that assigns `c.key` only for two special cases (`_`→US, `@`→NUL), so it emits no data for Ctrl+Shift+C at all regardless of any application gate; a synthetic keydown with the gate removed produces zero WS frames, proving no accidental interrupt reaches the PTY either way. What gating the whole copy block on `hasSelection()` (an earlier draft) actually cost: with no selection, a selection-less Ctrl+Shift+C fell straight to `return true`, silently ceding the keystroke to the BROWSER's own handling (e.g. Chrome's Inspect-Element binding) with no feedback and no copy attempt — Pane A always intercepts it. Ctrl+V goes through the primary pane's paste trap aimed at Pane B (`_handleImagePaste({ terminal, sessionId })`), so a pasted image uploads to Pane B's session. ⚠️ `buildSplitPickerSessions()` also excludes any session with `pid === null` (an exited CLI, a crash-looped session whose breaker tripped, a restore that never re-attached): Pane B has no equivalent of `selectSession()`'s auto re-attach POST, so a pane opened onto one has nothing reading its tmux pane — no `terminal` events ever arrive, and `Session.write()` silently drops every keystroke with no ack either way, so the loss is invisible behind a socket that reports healthy. Pane B's keystrokes go through the exactly-once queue (`_sendInputAsync`) over its own socket, registered in the app's input-socket map (`_registerInputSocket` / `_inputSocketFor`), so they are seq-tagged, ACKed (`{t:'ia'}` is routed by the RECEIVING socket's session, since the frame names none), redelivered after a drop, and the ACK clears the idle alert. ⚠️ What xterm generates never enters that persisted queue: query replies are dropped (`shouldSuppressTerminalQueryResponse`, as the primary pane drops them) and focus/mouse reports go through `_sendInputEphemeral`, or a reload would replay them as typed text. That includes the click report a tile hand-encodes for a mouse-strip CLI: `TerminalTile._installClickListener` passes `ephemeral: true` in its target, which `_sendSyntheticSgrTap` honours, while the primary pane's own report (no flag) stays on `_sendInputAsync` as before. ⚠️ A SHELL Pane B pulls scrollback itself when the wheel goes up at the top of its buffer (`_maybeLoadMoreHistory`/`_pullHistory`): tmux repaints a burst of output instead of scrolling it, so Pane B's own xterm holds about one screen of scrollback while tmux holds every line, and it loaded history exactly once at connect and never again. It is the same bounded pull as Pane A's (`?full=1&tail=TERMINAL_TAIL_SIZE`, no rewrite when the window holds no more rows than the pane already has or the pane is at its `scrollback + rows` cap, and a 60 s back-off instead of 4 s when that skipped window was truncated or the pane is full, since each ask costs the server a whole-history `capture-pane`), against Pane B's OWN terminal rather than `app.terminal`, so it cannot share `_maybeRefetchFullHistory`. The wheel listener is capture-phase because xterm `stopPropagation()`s the events it consumes; the alternate-screen skip (nano, vim, less) only matters for a direct-PTY shell, since under tmux the browser xterm never enters the alternate buffer; skipped too for a detached session (mirrors `_sendResize()`'s own check and app.js's `_maybeRefetchFullHistory`), since its own window already owns its PTY size and scrollback. Live frames arriving from the response onward are held with their arrival time (`_liveQueue`, opened right after `await fetch(...)` beside `capturedAt`; a frame from before it is replaced by the capture or written unchanged, so the pane keeps painting during the round trip) and replayed in order only if they arrived after the capture (the response's arrival stands in for the capture instant, as in `_finishBufferLoad`, so a frame inside that one round trip can be lost or doubled); the request uses the primary pane's budget (`CodemanFetchDeadline.terminalFetchDeadlineMs({ full: true })`, 45 s, 10 s only if that helper is absent) and the body read gets 10 s once the headers land, because from then on the pull holds the pane's live output. The request phase holds no live output, but it does hold the single-flight flag, so a coalesced `{t:'r'}` refresh and a marker owed by a close (below) wait for the response, at worst for that whole budget (accepted: a Codeman restart resets an in-flight request along with the socket, so that pull fails at once and stamps the marker). ⚠️ The "disconnected" marker must be the LAST thing on screen. A replay's own `\x1bc` would otherwise wipe a marker written before the pull and paint a fresh, current-looking history while `onData` keeps silently dropping every keystroke on the dead socket (a Codeman restart drops the socket while the tmux session, and so the HTTP pull, still succeeds), so `_pullHistory()` re-stamps it after the live-frame flush. A close DURING any load (a pull, a refresh; `connect()` awaits the initial load before it creates the socket, so no close lands in that one) writes nothing: `_onSocketClosed()` sets `_markerOwed` while a load's work runs (`_loadRunning`; a load that only waits in the tile grid's queue writes the marker at once, and its refresh resets the screen only once its own capture is in hand), since written there it would sit above the held frames the pull flushes after a skip, a downgrade, a failed fetch or the deadline, above a refresh's replay, or land mid-way through a chunked replay. Each load settles the marker in its OWN `finally` (`_stampMarkerIfOwed()`), after the queue flush, EXCEPT when a trailing refresh is pending: that refresh settles it itself (its replay's queued `\x1bc` would wipe a marker written now, so it re-owes the marker on a closed socket and writes the one copy below its replay, and a refresh that writes nothing stamps the one still owed). The marker stays owed instead of being written twice; the default fake terminal in `test/terminal-tile-unit.test.ts` writes synchronously, so an async-parse fake there pins what ends up on screen. Anything that wipes the terminal on a closed socket (a pull's or a refresh's `\x1bc`) sets `_markerOwed` too, so the marker is rewritten whether or not the close landed during the load. Tracked via `_wsClosed`/`_markerOwed` rather than routed through `_onLiveOutput()`, since a close landing before the response is stamped before the cutoff and would be dropped with the rest of the pre-capture queue. There is no "Load full history" banner in Pane B, so a shell history past that 1 MiB window stays out of reach there. Non-shell Pane B is unchanged: it already loads `full=1`, and its history is out of scope for this pull (codex and Claude's inline renderer do grow tmux history; this just isn't how they recover it). ⚠️ A server `{t:'c'}` frame is a REFRESH, never a bare `clear()` (`_onLiveClear()` calls `_refreshBuffer()`): its one emitter is a fresh Claude pane's first prompt (`Session.startInteractive`, "refresh after startup"), the primary pane answers it with a refetch and replay (`_onSessionClearTerminal`, which stands aside while the grid is open), and xterm's `clear()` keeps only the cursor's row, so a Claude session Run into the grid or Attached in a tile came up as a near-empty tile that an idle Claude never repainted. As a refresh it coalesces behind a load already running (a pull's held frames included) and waits its turn in the grid's load queue. ⚠️ A refresh (`{t:'r'}`, `{t:'c'}`, a reconnect) runs in the primary pane's order (`_onSessionNeedsRefresh`): fetch FIRST, so the pane keeps its last frame through the round trip and through a grid tile's wait; hold live frames from the response on (`_liveQueue`; the body read of a bounded window, a grid tile's or a shell's, gets the 10 s budget, while Pane B's unbounded `full=1` keeps the request's); then the queued in-stream `\x1bc` immediately before the replay, then the held frames that arrived after the response. Never xterm's `clear()`: it is synchronous while queued bytes are parsed after it (they fused into the snapshot) and it keeps the cursor's row and column, where the capture (raw rows, no home) then started. A failed, aborted or empty fetch writes nothing and resets nothing. ⚠️ App-level terminal actions find their pane through `_focusedPane()`, the terminal focused LAST (not `document.activeElement`, which the mic or a header button takes): Ctrl+L, Ctrl+Shift+R, voice and image paste act on Pane B while it holds the keyboard. Ctrl+W is not an app shortcut at all (Close Session has no default key), so it reaches whichever pane is focused as delete-word. ⚠️ Geometry: `TerminalTile.fit()` sends the size the xterm actually holds, unfloored (the divider's 20% clamp leaves about 28 columns), skips an unchanged size, re-sends on every fresh socket, and adopts the PTY's column count from `{t:'zc'}`; a forced fit (Redraw: Ctrl+Shift+R, the header button, through `restoreTerminalSize`) carries the primary pane's `f` flag, without which `Session.resize` skips a size equal to the one it last applied, and `fit()` returns whether a frame went out, so Redraw reports success only for a resize it sent (a detached session or a socket that is down gets a warning instead); the font, family and weight setters call `tile.fit()`, never a local refit alone (#464). Every capture a pane fetches carries a deadline covering the body (`CodemanFetchDeadline`), so a capture that never answers cannot hold its single-flight flag forever. Design: `docs/split-pane-sessions-plan.md`; the tile class: `docs/tile-grid-plan.md`. ### Tile grid diff --git a/src/web/public/terminal-tile.js b/src/web/public/terminal-tile.js index c0841973..54a34968 100644 --- a/src/web/public/terminal-tile.js +++ b/src/web/public/terminal-tile.js @@ -1205,23 +1205,26 @@ // Reflow to the container and tell the PTY, as one step: the xterm and the // PTY must never disagree about size (#464), and a font change is a size // change too, so the font setters call this rather than localFit(). - // `force` resends an unchanged size. + // `force` resends an unchanged size and asks the server to apply it anyway + // (Redraw, restoreTerminalSize). Returns whether a resize went out. fit({ force = false } = {}) { this.localFit(); - this._sendResize({ force }); + return this._sendResize({ force }); } + // Returns true only once a `{t:'z'}` frame was sent, false at every early + // exit, so Redraw can say when nothing reached the PTY. _sendResize({ force = false } = {}) { - if (!this._wsReady || !this.fitAddon || !this.terminal) return; + if (!this._wsReady || !this.fitAddon || !this.terminal) return false; // One PTY cannot hold two sizes (mirrors sendResize's own // detachedElsewhere yield in terminal-ui.js): the session got detached // to its own window AFTER this pane was opened, so its own window now // owns the PTY's size and this pane must stand aside. - if (this.detachedSessions?.has(this.sessionId)) return; + if (this.detachedSessions?.has(this.sessionId)) return false; // A hidden pane (a web tab over it, a zoomed neighbour) measures NaN, and // fit() then leaves the xterm alone: there is no size worth reporting. const dims = this.fitAddon.proposeDimensions(); - if (!dims || !Number.isFinite(dims.cols) || !Number.isFinite(dims.rows)) return; + if (!dims || !Number.isFinite(dims.cols) || !Number.isFinite(dims.rows)) return false; // Report what the xterm actually holds, so the PTY gets exactly the size // the pane renders at. Unclamped, unlike the primary pane's 40x10 floor: // a floor would misreport the split's Pane B at its divider's reachable @@ -1231,9 +1234,20 @@ const cols = this.terminal.cols; const rows = this.terminal.rows; const last = this._lastSentDims; - if (!force && last && last.cols === cols && last.rows === rows) return; + if (!force && last && last.cols === cols && last.rows === rows) return false; + // `f` is the primary pane's forced resize (sendResize, terminal-ui.js): + // Session.resize (session.ts) otherwise skips a size equal to the one it + // last applied, so without it a forced resend reached the server and did + // nothing there (no tmux resize-window, no PTY resize). + const msg = { t: 'z', c: cols, r: rows, v: 'desktop' }; + if (force) msg.f = true; + try { + this.ws.send(JSON.stringify(msg)); + } catch { + return false; // nothing went out, so nothing is recorded as sent + } this._lastSentDims = { cols, rows }; - this.ws.send(JSON.stringify({ t: 'z', c: cols, r: rows, v: 'desktop' })); + return true; } // The session's PTY is new: a tile can connect before its session has a diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 48d134bc..95727d04 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -4664,11 +4664,24 @@ Object.assign(CodemanApp.prototype, { */ async restoreTerminalSize() { // A second pane owns its own geometry: refit it and force its PTY to the - // size it renders at (TerminalTile.fit), whatever another device set. + // size it renders at (TerminalTile.fit sends the same forced `f` resize + // sendResize sends below), whatever another device set. fit() says whether + // the resize went out; when it did not, say why rather than report a size + // that was never sent, as the primary branch does below. const pane = this._focusedPane(); if (!pane.isPrimary) { - pane.tile.fit({ force: true }); - this.showToast(`Terminal restored to ${pane.terminal.cols}x${pane.terminal.rows}`, 'success'); + const sent = pane.tile.fit({ force: true }); + if (sent !== false) { + this.showToast(`Terminal restored to ${pane.terminal.cols}x${pane.terminal.rows}`, 'success'); + } else if (this.detachedSessions?.has(pane.sessionId)) { + // Its own window owns the PTY's size (TerminalTile._sendResize yields). + this.showToast('This session is sized by its own window', 'warning'); + } else if (!pane.tile._wsReady) { + // The tile announces its size again as soon as its socket reopens. + this.showToast('Terminal not connected: its size is sent when it reconnects', 'warning'); + } else { + this.showToast('Could not determine terminal size', 'error'); + } return; } if (!this.activeSessionId) { diff --git a/test/focused-pane-shortcuts.test.ts b/test/focused-pane-shortcuts.test.ts index 25d50042..caccfb9a 100644 --- a/test/focused-pane-shortcuts.test.ts +++ b/test/focused-pane-shortcuts.test.ts @@ -127,6 +127,36 @@ describe('terminal shortcuts follow the focused pane', () => { expect(app.showToast).toHaveBeenCalledWith('Terminal restored to 60x30', 'success'); }); + // TerminalTile.fit() returns whether its resize went out. When it did not, + // Redraw used to report a size that was never sent. + it.each([ + [ + 'popped out to its own window', + { detached: true, wsReady: true }, + 'This session is sized by its own window', + 'warning', + ], + [ + 'whose socket is down', + { detached: false, wsReady: false }, + 'Terminal not connected: its size is sent when it reconnects', + 'warning', + ], + ['that could not measure itself', { detached: false, wsReady: true }, 'Could not determine terminal size', 'error'], + ])('Ctrl+Shift+R on a second pane %s reports no success', async (_label, state, message, level) => { + const app = loadApp(); + app.detachedSessions = new Set(state.detached ? ['session-b'] : []); + const tile = paneB({ fit: vi.fn(() => false), _wsReady: state.wsReady }); + app._noteFocusedTile(tile); + + await app.restoreTerminalSize(); + + expect(tile.fit).toHaveBeenCalledWith({ force: true }); + expect(app.showToast).toHaveBeenCalledTimes(1); + expect(app.showToast).toHaveBeenCalledWith(message, level); + expect(app.sendResize).not.toHaveBeenCalled(); + }); + it('Ctrl+Shift+R keeps restoring the primary when it holds the keyboard', async () => { const app = loadApp(); diff --git a/test/terminal-tile-input.test.ts b/test/terminal-tile-input.test.ts index 496cced1..ec77e81d 100644 --- a/test/terminal-tile-input.test.ts +++ b/test/terminal-tile-input.test.ts @@ -118,7 +118,7 @@ type Tile = { connect(): Promise; destroy(): void; reconnectNow(): void; - fit(opts?: { force?: boolean }): void; + fit(opts?: { force?: boolean }): boolean; detachedSessions?: Set; ws: FakeSocket | null; _reconnectAttempts: number; @@ -514,15 +514,80 @@ describe('TerminalTile geometry (#464: the pane and its PTY never disagree)', () const { tile, ws } = await connectTile(makeApp()); ws.open(); - tile.fit(); + expect(tile.fit()).toBe(false); // unchanged: nothing sent expect(resizeFrames(ws)).toHaveLength(1); FakeFit.proposed = { cols: 100, rows: 30 }; - tile.fit(); + expect(tile.fit()).toBe(true); expect(resizeFrames(ws).at(-1)).toEqual({ t: 'z', c: 100, r: 30, v: 'desktop' }); - tile.fit({ force: true }); + expect(tile.fit({ force: true })).toBe(true); expect(resizeFrames(ws)).toHaveLength(3); + // The primary pane's forced resize flag: without it Session.resize skips a + // size equal to the one it last applied, and the forced resend did nothing. + expect(resizeFrames(ws).at(-1)).toEqual({ t: 'z', c: 100, r: 30, v: 'desktop', f: true }); + }); + + it('force on a closed socket sends nothing and says so', async () => { + const { tile, ws } = await connectTile(makeApp()); + ws.open(); + ws.drop(1006); + + expect(tile.fit({ force: true })).toBe(false); + expect(resizeFrames(ws)).toHaveLength(1); // only the open's own announcement + }); + + describe('Redraw (Ctrl+Shift+R, the header button) on a focused tile', () => { + type RedrawApp = App & { + restoreTerminalSize(): Promise; + _noteFocusedTile(tile: unknown): void; + detachedSessions?: Set; + }; + + it('forces the resize through to the server and reports the size it sent', async () => { + const app = makeApp() as RedrawApp; + const { tile, ws } = await connectTile(app); + ws.open(); + app._noteFocusedTile(tile); + + await app.restoreTerminalSize(); + + expect(resizeFrames(ws).at(-1)).toEqual({ t: 'z', c: 80, r: 24, v: 'desktop', f: true }); + expect(app.showToast).toHaveBeenCalledWith('Terminal restored to 80x24', 'success'); + }); + + it('with the socket down, sends nothing and does not report a success', async () => { + const app = makeApp() as RedrawApp; + const { tile, ws } = await connectTile(app); + ws.open(); + app._noteFocusedTile(tile); + ws.drop(1006); + + await app.restoreTerminalSize(); + + expect(resizeFrames(ws)).toHaveLength(1); + expect(app.showToast).not.toHaveBeenCalledWith(expect.stringContaining('restored'), 'success'); + expect(app.showToast).toHaveBeenCalledWith( + 'Terminal not connected: its size is sent when it reconnects', + 'warning' + ); + }); + + it('for a session popped out to its own window, says that window sizes it', async () => { + const app = makeApp() as RedrawApp; + const detached = new Set(); + app.detachedSessions = detached; + const { tile, ws } = await connectTile(app, { detachedSessions: detached }); + ws.open(); + app._noteFocusedTile(tile); + detached.add('s-tile'); // popped out after the tile opened + + await app.restoreTerminalSize(); + + expect(resizeFrames(ws)).toHaveLength(1); + expect(app.showToast).not.toHaveBeenCalledWith(expect.stringContaining('restored'), 'success'); + expect(app.showToast).toHaveBeenCalledWith('This session is sized by its own window', 'warning'); + }); }); it('re-announces an unchanged size on a reconnected socket', async () => { @@ -598,7 +663,7 @@ describe('TerminalTile geometry (#464: the pane and its PTY never disagree)', () ws.open(); FakeFit.proposed = { cols: 120, rows: 40 }; - tile.fit(); + expect(tile.fit()).toBe(false); expect(resizeFrames(ws)).toEqual([]); });