diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 011e0566..7db6054f 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -1083,7 +1083,7 @@ Tests: `test/tab-rail-search.test.ts` (gate) and `test/tab-rail-search.browser.t ### 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. ⚠️ Live output is flow-controlled per pane (`_writeLive`), because the server applies no backpressure and a flood a tile cannot parse as fast (a shell tile running `cat` on a huge log) used to pile up in xterm's own queue until its WriteBuffer threw past 50M code units and onmessage's catch lost the frames silently: unparsed output is counted through each write's callback, and held output by the queue, against `TerminalTile.LIVE_BACKLOG_BUDGET` (4 MiB; deliberately NOT the primary pane's 128 KB, which caps its own rAF-paced queues, while xterm itself paces a tile and a tight cap would blank-and-reload it on ordinary bursts). Past it a frame is dropped, the tile stops writing onto the hole, and one refresh, debounced and bounded by the primary pane's own rule (`CodemanDroppedOutput`: 2 s, at most `DROP_RECOVERY_MAX_ATTEMPTS`, never retried after a deadline abort), recaptures the screen; the flag clears only once a capture taken after the last dropped frame has replayed. A write xterm throws on is the same drop. Past the bound the flag is released (the tile is never left frozen), a reconnect starts the accounting over (an epoch makes callbacks from before it count nothing) and drops a pending recovery, since its own refresh replaces the screen, and `destroy()` cancels it. ⚠️ 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`. +**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 soft-keyboard input owner: the iOS native-input owner (`_iosNativeInput`, terminal-ios-native-input.js, #830) on iOS WebKit touch, otherwise the keyCode-229 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. ⚠️ Live output is flow-controlled per pane (`_writeLive`), because the server applies no backpressure and a flood a tile cannot parse as fast (a shell tile running `cat` on a huge log) used to pile up in xterm's own queue until its WriteBuffer threw past 50M code units and onmessage's catch lost the frames silently: unparsed output is counted through each write's callback, and held output by the queue, against `TerminalTile.LIVE_BACKLOG_BUDGET` (4 MiB; deliberately NOT the primary pane's 128 KB, which caps its own rAF-paced queues, while xterm itself paces a tile and a tight cap would blank-and-reload it on ordinary bursts). Past it a frame is dropped, the tile stops writing onto the hole, and one refresh, debounced and bounded by the primary pane's own rule (`CodemanDroppedOutput`: 2 s, at most `DROP_RECOVERY_MAX_ATTEMPTS`, never retried after a deadline abort), recaptures the screen; the flag clears only once a capture taken after the last dropped frame has replayed. A write xterm throws on is the same drop. Past the bound the flag is released (the tile is never left frozen), a reconnect starts the accounting over (an epoch makes callbacks from before it count nothing) and drops a pending recovery, since its own refresh replaces the screen, and `destroy()` cancels it. ⚠️ 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/input-cjk.js b/src/web/public/input-cjk.js index 4ebf200a..4d2038b0 100644 --- a/src/web/public/input-cjk.js +++ b/src/web/public/input-cjk.js @@ -353,10 +353,17 @@ const CjkInput = (() => { return; } _t('hold ctrl key'); - _textarea.value = PHANTOM + before; - _textarea.setSelectionRange(1 + at, 1 + at); - _heldBase = before; - _send(now[at]); + // The control key goes to the session this field's text was captured for; + // with no draft left, the next answer captures its own destination. + const target = _targetForSend(); + if (!before) { + _resetToPhantom(); + } else { + _textarea.value = PHANTOM + before; + _textarea.setSelectionRange(1 + at, 1 + at); + _heldBase = before; + } + _send(now[at], target); } /** Send-on-Enter input handling: nothing is flushed, the field only settles. @@ -370,7 +377,7 @@ const CjkInput = (() => { const wasEmpty = !_heldBase; _heldBase = _strip(_textarea.value); if (!_heldBase) { - if (wasEmpty) _send('\x7f'); + if (wasEmpty) _send('\x7f', _targetForSend()); _resetToPhantom(); } else if (!_textarea.value.startsWith(PHANTOM)) { // Backspace at the very start of the text deleted the phantom: put it @@ -801,6 +808,10 @@ const CjkInput = (() => { _textarea.value = PHANTOM + draft; _textarea.setSelectionRange(_textarea.value.length, _textarea.value.length); _heldBase = draft; + // The restored text belongs to this session: Enter after a focus move to + // another pane must still send it here (see _targetForSend). + _target = sessionId; + _hasTarget = true; _autoGrow(); }, diff --git a/src/web/public/voice-input.js b/src/web/public/voice-input.js index b0c9d641..13e474ab 100644 --- a/src/web/public/voice-input.js +++ b/src/web/public/voice-input.js @@ -1079,8 +1079,10 @@ const VoiceInput = { app.showToast?.('That session has closed; dictation not sent', 'warning'); return Promise.resolve(); } + // Settle the destination's iOS owner, but leave an unsent local-echo draft + // in the overlay: flushing it would prepend it to the reviewed dictation. const pane = app._paneForSession?.(target); - if (pane) app._prepareExternalInput?.(pane, 'voice-send', { flushEcho: true }); + if (pane) app._prepareExternalInput?.(pane, 'voice-send'); app._sendInputAsync(target, text, { useMux: true }); return Promise.resolve(); }, diff --git a/test/cjk-hold-per-device-setting.test.ts b/test/cjk-hold-per-device-setting.test.ts index cc6804ce..200c3eda 100644 --- a/test/cjk-hold-per-device-setting.test.ts +++ b/test/cjk-hold-per-device-setting.test.ts @@ -158,6 +158,11 @@ describe('a held draft survives a reload of the same session', () => { /if \(this\.activeSessionId === sessionId && forceReload\) \{\s*reloadingSameSession = true;/ ); expect(appJs).toContain('this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });'); + // Nothing in the same-session reload block may clear the field ahead of + // that flag: a CjkInput.clear() there wipes the held draft keepCjkDraft keeps. + const start = appJs.indexOf('if (this.activeSessionId === sessionId && forceReload) {'); + const block = appJs.slice(start, appJs.indexOf('this.activeSessionId = null;', start)); + expect(block).not.toContain('CjkInput.clear'); }); }); @@ -178,13 +183,24 @@ describe('Send on Enter field layout and strings', () => { expect(base).toContain('overflow-y: auto;'); }); - it('the phone toolbar Enter presses Enter in the visible CJK field', () => { + it('the phone toolbar Enter presses Enter in the visible CJK field, not a bare terminal Enter', () => { // onData drops everything while cjkActive, so the xterm path does nothing. - const sessionUi = read('session-ui.js'); - const start = sessionUi.indexOf(' sendEnterKey() {'); - const body = sessionUi.slice(start, sessionUi.indexOf('submitFromToolbar()', start)); - expect(body).toContain("classList.contains('cjk-input-visible')"); - expect(body).toContain('CjkInput.submit?.();'); + // The real sendEnterKey from session-ui.js, run with and without the field. + for (const visible of [true, false]) { + const submit = vi.fn(); + const field = { classList: { contains: (name: string) => visible && name === 'cjk-input-visible' } }; + const context = vm.createContext({ + CodemanApp: function CodemanApp() {}, + CjkInput: { submit }, + document: { getElementById: (id: string) => (id === 'cjkInput' ? field : null) }, + }); + vm.runInContext(`${read('session-ui.js')}\nglobalThis.__mixin = CodemanApp.prototype;`, context); + const mixin = (context as unknown as { __mixin: { sendEnterKey(this: object): void } }).__mixin; + const submitFromToolbar = vi.fn(); + mixin.sendEnterKey.call({ submitFromToolbar }); + expect(submit).toHaveBeenCalledTimes(visible ? 1 : 0); + expect(submitFromToolbar).toHaveBeenCalledTimes(visible ? 0 : 1); + } }); it('has zh-CN strings for both field placeholders', () => { diff --git a/test/image-paste-trap.test.ts b/test/image-paste-trap.test.ts index 0b1961c1..d92742f0 100644 --- a/test/image-paste-trap.test.ts +++ b/test/image-paste-trap.test.ts @@ -206,14 +206,6 @@ function loadPasteHarness(options: PasteHarnessOptions = {}): Harness { }; app._flushedOffsets = new Map(); app._flushedTexts = new Map(); - app._flushLocalEchoPending = function (this: Record) { - const pending = this._localEchoOverlay?.pendingText || ''; - this._localEchoOverlay.clear(); - this._localEchoOverlay.suppressBufferDetection(); - this._flushedOffsets?.delete(this.activeSessionId); - this._flushedTexts?.delete(this.activeSessionId); - if (pending) this._pendingInput += pending; - }; } const toasts: string[] = []; app.showToast = (message: string) => toasts.push(message); diff --git a/test/mobile-shell-keyboard.test.ts b/test/mobile-shell-keyboard.test.ts index 875d0b27..0d3bca9e 100644 --- a/test/mobile-shell-keyboard.test.ts +++ b/test/mobile-shell-keyboard.test.ts @@ -554,27 +554,43 @@ describe('one-shot Ctrl through the CJK input field', () => { }); describe('Send on Enter: a held answer goes out with Enter as its own write', () => { - // _sendCjkPrompt is CjkInput's sendPrompt callback. Anything longer than one - // character goes to the composer's _sendComposedPrompt with the session - // captured at Enter, so the delayed Enter cannot follow a tab switch. + // _sendCjkPrompt is CjkInput's sendPrompt callback, called with the session + // CjkInput captured for the text (_targetForSend). Anything longer than one + // character goes to the composer's _sendComposedPrompt for that session; one + // character, the 120 ms gap and Enter are reserved on that session's FIFO, so + // the delayed Enter cannot follow a tab switch. + type PromptApp = { + activeSessionId: string | null; + sessions: Map; + pendingHooks?: Map>; + _focusedPane(): { sessionId: string | null; terminal: object; isPrimary: boolean } | null; + _paneForSession(id: string): null; + _enqueueReliableInput(id: string, input: string, opts?: { useMux?: boolean }): void; + _sendCjkPrompt(text: string, sessionId?: string): boolean; + }; function promptApp() { const { CodemanApp, bar } = loadTerminalModule(); bar.clearCtrl(); - const app = Object.create(CodemanApp.prototype) as { - activeSessionId: string | null; - _sendCjkPrompt(text: string): boolean; - }; + const app = Object.create(CodemanApp.prototype) as PromptApp; app.activeSessionId = 'session-a'; + app.sessions = new Map([ + ['session-a', { mode: 'claude' }], + ['session-b', { mode: 'claude' }], + ]); + app._focusedPane = () => ({ sessionId: app.activeSessionId, terminal: {}, isPrimary: true }); + app._paneForSession = () => null; + const writes: Array<[string, string, boolean]> = []; + app._enqueueReliableInput = (id, input, opts) => void writes.push([id, input, opts?.useMux === true]); const composed = vi .spyOn(bar as unknown as { _sendComposedPrompt: (s: string, t: string) => boolean }, '_sendComposedPrompt') .mockReturnValue(true); - return { app, bar, composed }; + return { app, bar, composed, writes }; } - it('sends through the composer path, bound to the session active at Enter', () => { + it('sends through the composer path for the captured session, not the active one', () => { const { app, composed } = promptApp(); - expect(app._sendCjkPrompt('line one\nline two')).toBe(true); app.activeSessionId = 'session-b'; + expect(app._sendCjkPrompt('line one\nline two', 'session-a')).toBe(true); expect(composed).toHaveBeenCalledWith('session-a', 'line one\nline two'); composed.mockRestore(); }); @@ -582,28 +598,28 @@ describe('Send on Enter: a held answer goes out with Enter as its own write', () it('spends an armed one-shot Ctrl, like any multi-character chunk', () => { const { app, bar, composed } = promptApp(); bar.toggleCtrl(); - app._sendCjkPrompt('x'.repeat(100)); + app._sendCjkPrompt('x'.repeat(100), 'session-a'); expect(bar.isCtrlArmed()).toBe(false); composed.mockRestore(); }); - it('types a single character, then Enter ~120 ms later to the same session', () => { + it('types a single character, then Enter 120 ms later on the same session FIFO across a switch', () => { // Codex folds an Enter that arrives in the same burst as the text into a // paste, even for `1\r`; a selection dialog ignores a pasted digit. Same // split as TmuxManager.sendInput (submitsAsKeys). vi.useFakeTimers(); try { - const { app, composed } = promptApp(); - const writes: Array<[string, string, unknown]> = []; - (app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (id: string, input: string, opts?: unknown) => - writes.push([id, input, opts]); - expect(app._sendCjkPrompt('1')).toBe(true); - expect(writes).toEqual([['session-a', '1', undefined]]); + const { app, composed, writes } = promptApp(); + expect(app._sendCjkPrompt('1', 'session-a')).toBe(true); + expect(writes).toEqual([['session-a', '1', false]]); app.activeSessionId = 'session-b'; vi.advanceTimersByTime(119); expect(writes).toHaveLength(1); vi.advanceTimersByTime(1); - expect(writes[1]).toEqual(['session-a', '\r', { useMux: true }]); + expect(writes).toEqual([ + ['session-a', '1', false], + ['session-a', '\r', true], + ]); expect(composed).not.toHaveBeenCalled(); composed.mockRestore(); } finally { @@ -618,19 +634,11 @@ describe('Send on Enter: a held answer goes out with Enter as its own write', () vi.useFakeTimers(); try { for (const hook of ['permission_prompt', 'elicitation_dialog']) { - const { app, composed } = promptApp(); - const writes: Array<[string, string, unknown]> = []; - (app as unknown as { _sendInputAsync: unknown })._sendInputAsync = ( - id: string, - input: string, - opts?: unknown - ) => writes.push([id, input, opts]); - (app as unknown as { pendingHooks: Map> }).pendingHooks = new Map([ - ['session-a', new Set([hook])], - ]); - expect(app._sendCjkPrompt('2')).toBe(true); + const { app, composed, writes } = promptApp(); + app.pendingHooks = new Map([['session-a', new Set([hook])]]); + expect(app._sendCjkPrompt('2', 'session-a')).toBe(true); vi.advanceTimersByTime(500); - expect(writes).toEqual([['session-a', '2', undefined]]); + expect(writes).toEqual([['session-a', '2', false]]); composed.mockRestore(); } } finally { @@ -646,21 +654,13 @@ describe('Send on Enter: a held answer goes out with Enter as its own write', () ['permission_prompt', 'y'], ]; for (const [hook, text] of cases) { - const { app, composed } = promptApp(); - const writes: Array<[string, string, unknown]> = []; - (app as unknown as { _sendInputAsync: unknown })._sendInputAsync = ( - id: string, - input: string, - opts?: unknown - ) => writes.push([id, input, opts]); - (app as unknown as { pendingHooks: Map> }).pendingHooks = new Map([ - ['session-a', new Set([hook])], - ]); - expect(app._sendCjkPrompt(text)).toBe(true); + const { app, composed, writes } = promptApp(); + app.pendingHooks = new Map([['session-a', new Set([hook])]]); + expect(app._sendCjkPrompt(text, 'session-a')).toBe(true); vi.advanceTimersByTime(120); expect(writes).toEqual([ - ['session-a', text, undefined], - ['session-a', '\r', { useMux: true }], + ['session-a', text, false], + ['session-a', '\r', true], ]); composed.mockRestore(); } @@ -671,19 +671,22 @@ describe('Send on Enter: a held answer goes out with Enter as its own write', () it('pastes even a short word: only one character is typed', () => { const { app, composed } = promptApp(); - expect(app._sendCjkPrompt('yes')).toBe(true); + expect(app._sendCjkPrompt('yes', 'session-a')).toBe(true); expect(composed).toHaveBeenCalledWith('session-a', 'yes'); composed.mockRestore(); }); it('reports a refusal so the field keeps the text', () => { - const { app, composed } = promptApp(); + const { app, composed, writes } = promptApp(); composed.mockReturnValue(false); - expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false); + expect(app._sendCjkPrompt('x'.repeat(100), 'session-a')).toBe(false); + // A captured session that closed meanwhile, or no session at all, sends nothing. + expect(app._sendCjkPrompt('1', 'session-gone')).toBe(false); app.activeSessionId = null; expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false); expect(app._sendCjkPrompt('1')).toBe(false); expect(composed).toHaveBeenCalledTimes(1); + expect(writes).toEqual([]); composed.mockRestore(); }); }); diff --git a/test/terminal-input-fifo.test.ts b/test/terminal-input-fifo.test.ts index 633cb337..e1322036 100644 --- a/test/terminal-input-fifo.test.ts +++ b/test/terminal-input-fifo.test.ts @@ -86,7 +86,11 @@ function loadProducerModules(app: object, context: vm.Context) { } function attachCjk( - app: { _focusedPane: () => { sessionId: string } | null; _handleCjkInput: (text: string, sessionId: string) => void }, + app: { + _focusedPane: () => { sessionId: string } | null; + _handleCjkInput: (text: string, sessionId: string) => void; + _sendCjkPrompt: (text: string, sessionId: string) => boolean; + }, context: vm.Context ) { const listeners = new Map void>(); @@ -94,6 +98,8 @@ function attachCjk( value: '', selectionStart: 1, selectionEnd: 1, + style: {}, + setAttribute: vi.fn(), setSelectionRange: vi.fn(), addEventListener: (name: string, fn: (event: object) => void) => listeners.set(name, fn), removeEventListener: vi.fn(), @@ -105,6 +111,7 @@ function attachCjk( cjk.init({ captureTarget: () => app._focusedPane()?.sessionId, send: (text: string, sessionId: string) => app._handleCjkInput(text, sessionId), + sendPrompt: (text: string, sessionId: string) => app._sendCjkPrompt(text, sessionId), }); return { cjk, field, fire: (name: string, event = {}) => listeners.get(name)!(event) }; } @@ -491,6 +498,102 @@ describe('native main transactions and boundaries', () => { cjk.destroy(); }); + it('Send on Enter keeps a held answer, its gap and Enter on the session it was typed for', () => { + const { app, wire, context } = harness(); + context.KeyboardAccessoryBar = { clearCtrl: vi.fn(), isCtrlArmed: () => false }; + const { cjk, field, fire } = attachCjk(app, context); + cjk.setHoldUntilEnter(true); + field.value = '\u200By'; + fire('input', { inputType: 'insertText', isComposing: false }); + // Focus moves to Pane B before Enter; the held answer still belongs to A. + const tile = { sessionId: 'new', terminal: {} }; + app._splitPane = tile; + app._noteFocusedTile(tile); + fire('keydown', { key: 'Enter', preventDefault: vi.fn() }); + expect(wire).toEqual([['old', 'y']]); + vi.advanceTimersByTime(120); + expect(wire).toEqual([ + ['old', 'y'], + ['old', '\r'], + ]); + cjk.destroy(); + }); + + it('Send on Enter sends a restored draft to its own session after focus moves, without an edit', () => { + const { app, wire, context } = harness(); + context.KeyboardAccessoryBar = { clearCtrl: vi.fn(), isCtrlArmed: () => false }; + const { cjk, field, fire } = attachCjk(app, context); + cjk.setHoldUntilEnter(true); + // A draft typed for `old` is stashed on a switch and restored on the way back. + field.value = '\u200By'; + fire('input', { inputType: 'insertText', isComposing: false }); + cjk.stashDraft('old'); + cjk.clear(); + cjk.restoreDraft('old'); + expect(field.value).toBe('\u200By'); + // Focus moves to Pane B; Enter is pressed without touching the draft. + const tile = { sessionId: 'new', terminal: {} }; + app._splitPane = tile; + app._noteFocusedTile(tile); + fire('keydown', { key: 'Enter', preventDefault: vi.fn() }); + vi.advanceTimersByTime(120); + expect(wire).toEqual([ + ['old', 'y'], + ['old', '\r'], + ]); + cjk.destroy(); + }); + + it('Send on Enter sends a held-mode Ctrl key to the session it was typed for across a focus move', () => { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + const bar = vm.runInContext('KeyboardAccessoryBar', context); + const { cjk, field, fire } = attachCjk(app, context); + cjk.setHoldUntilEnter(true); + field.value = '\u200Bab'; + fire('input', { inputType: 'insertText', isComposing: false }); + bar.toggleCtrl(); + fire('compositionstart'); + // Focus moves to Pane B before the composition commits `c`. + const tile = { sessionId: 'new', terminal: {} }; + app._splitPane = tile; + app._noteFocusedTile(tile); + field.value = '\u200Babc'; + fire('compositionend'); + vi.advanceTimersByTime(0); + expect(wire).toEqual([['old', '\x03']]); + expect(field.value).toBe('\u200Bab'); + cjk.destroy(); + }); + + it('Send on Enter lets the next answer capture its own session after Ctrl empties the field', () => { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + const bar = vm.runInContext('KeyboardAccessoryBar', context); + const { cjk, field, fire } = attachCjk(app, context); + cjk.setHoldUntilEnter(true); + bar.toggleCtrl(); + fire('keydown', { key: 'c' }); + field.value = '\u200Bc'; + fire('input', { inputType: 'insertText', isComposing: false }); + expect(wire).toEqual([['old', '\x03']]); + // Focus moves to Pane B; a fresh answer typed there belongs to B. + const tile = { sessionId: 'new', terminal: {} }; + app._splitPane = tile; + app._noteFocusedTile(tile); + fire('keydown', { key: 'y' }); + field.value = '\u200By'; + fire('input', { inputType: 'insertText', isComposing: false }); + fire('keydown', { key: 'Enter', preventDefault: vi.fn() }); + vi.advanceTimersByTime(120); + expect(wire).toEqual([ + ['old', '\x03'], + ['new', 'y'], + ['new', '\r'], + ]); + cjk.destroy(); + }); + it('keeps an unfinished CJK composition on B after focus moves to A', () => { const { app, wire, context } = harness(); const { cjk, field, fire } = attachCjk(app, context); @@ -620,7 +723,7 @@ describe('native main transactions and boundaries', () => { } ); - it.each(['upload', 'voice', 'Esc', 'paste'])( + it.each(['upload', 'Esc', 'paste'])( '%s preserves the typed prefix before direct writes with echo on or off', async (producer) => { for (const echo of [true, false]) { @@ -656,12 +759,6 @@ describe('native main transactions and boundaries', () => { ['old', '/p'], ['old', '\r'], ]); - } else if (producer === 'voice') { - await vm.runInContext("VoiceInput._sendToTarget('old', 'world')", context); - expect(wire).toEqual([ - ['old', 'hel'], - ['old', 'world'], - ]); } else if (producer === 'Esc') { vm.runInContext("KeyboardAccessoryBar.sendKey('\\x1b')", context); expect(wire).toEqual([ @@ -694,6 +791,19 @@ describe('native main transactions and boundaries', () => { } }); + it('sends voice dictation without submitting the unsent local-echo draft', async () => { + for (const echo of [true, false]) { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + app._localEchoEnabled = echo; + app._handleTerminalData('hel', 'old'); + await vm.runInContext("VoiceInput._sendToTarget('old', 'world\\r')", context); + // Echo on: `hel` stays in the overlay. Echo off: it was already typed into the PTY. + expect(wire).toEqual([...(echo ? [] : [['old', 'hel']]), ['old', 'world\r']]); + expect(app._localEchoOverlay.pendingText).toBe(echo ? 'hel' : ''); + } + }); + it('keeps the typed prefix in the overlay when a toolbar attachment appends', async () => { const { app, wire, context } = harness(); loadProducerModules(app, context); diff --git a/test/voice-input-target.test.ts b/test/voice-input-target.test.ts index 44de29f2..386877f6 100644 --- a/test/voice-input-target.test.ts +++ b/test/voice-input-target.test.ts @@ -78,6 +78,11 @@ function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string } app._paneForSession = (id: string) => (opts.pane?.sessionId === id ? opts.pane : null); if (opts.tiles) app._tilesOwnTerminal = () => true; + const doc = { + querySelector: (sel: string): unknown => (sel === '.btn-settings' ? gear : null), + createElement: (): unknown => ({}), + body: { appendChild: () => {} }, + }; const context = vm.createContext({ console, setTimeout: (fn: () => void) => fn(), @@ -90,11 +95,7 @@ function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string key === 'codeman-voice-settings' ? JSON.stringify({ insertMode: opts.insertMode || 'direct' }) : null, setItem: () => {}, }, - document: { - querySelector: (sel: string) => (sel === '.btn-settings' ? gear : null), - createElement: () => ({}), - body: { appendChild: () => {} }, - }, + document: doc, window: {}, navigator: {}, }); @@ -103,7 +104,7 @@ function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string // Recording itself is out of scope: start() only has to pick the target. voice._resolveProvider = () => 'webspeech'; voice._startWebSpeech = vi.fn(); - return { voice, app, sendInput, sendInputAsync, appendText, overlayClear, showToast, gear }; + return { voice, app, sendInput, sendInputAsync, appendText, overlayClear, showToast, gear, doc }; } function clickGreenSend(gear: { addEventListener: { mock: { calls: unknown[][] } } }) { @@ -131,9 +132,7 @@ describe('dictation target', () => { expect(sendInput).not.toHaveBeenCalled(); expect(sendInputAsync).toHaveBeenCalledWith('session-a', 'hello', { useMux: true }); - expect(app._prepareExternalInput).toHaveBeenCalledWith({ sessionId: 'session-a', isPrimary: true }, 'voice-send', { - flushEcho: true, - }); + expect(app._prepareExternalInput).toHaveBeenCalledWith({ sessionId: 'session-a', isPrimary: true }, 'voice-send'); }); it('never types another session dictation into the active local-echo overlay', () => { @@ -289,6 +288,42 @@ describe('dictation target', () => { expect(paneB.focus).not.toHaveBeenCalled(); }); + it('compose Send delivers only the reviewed dictation and leaves the typed draft in the overlay', () => { + const { voice, app, appendText, overlayClear, sendInputAsync, doc } = load({ + insertMode: 'compose', + localEcho: true, + pane: { sessionId: 'session-a', isPrimary: true }, + }); + const overlay = app._localEchoOverlay as { pendingText: string }; + overlay.pendingText = 'hel'; + const handlers = new Map void>(); + const textarea = { value: '', focus: vi.fn(), blur: vi.fn(), selectionStart: 0, selectionEnd: 0 }; + doc.createElement = () => ({ + className: '', + innerHTML: '', + remove: vi.fn(), + addEventListener: vi.fn(), + querySelector: (sel: string) => + sel === 'textarea' + ? textarea + : { addEventListener: (_type: string, handler: () => void) => handlers.set(sel, handler) }, + }); + voice.start(); + + voice._insertText('Please fix the bug'); + // The dialog's