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): relay nodes hydrate scrollback via the transport; copy chord never SIGINTs

enes03a78225d0ae
diff --git a/docs/SERVER.md b/docs/SERVER.md
index 6241751d8..27c2f21bc 100644
--- a/docs/SERVER.md
+++ b/docs/SERVER.md
@@ -168,6 +168,17 @@ The following affordances change shape in the browser (no native OS is reachable
- **"Reveal in Finder" / "open with default app"** — **inert** in the browser
(there is no desktop file manager to reveal into); these actions are hidden or
no-op rather than erroring.
+- **Clipboard (copy)** — the browser's `navigator.clipboard` only exists in a **secure
+ context** (https or `localhost`). Over plain http on a LAN it is `undefined`, so the
+ bridge falls back to a hidden-textarea `document.execCommand('copy')`. That fallback
+ only works **inside a user gesture**: the copy shortcut and the click-driven copy
+ buttons are fine, but an `OSC 52` write driven by terminal *output* (`vim "+y`, `gh`,
+ `yazi`) is not — it fails and raises a **banner** ("the browser blocks clipboard access
+ over plain http"). Copy never fails silently, but if you want it to work properly,
+ **serve over https (or localhost)** — that is one more reason for the TLS proxy above.
+ Note also that **Ctrl+Shift+C** (advertised as copy on Linux/Windows) additionally opens
+ Chromium's element inspector and a page cannot suppress that; **Ctrl+Insert** is the
+ browser-safe copy chord.
The **backpressure / flow-control** gap noted in the Phase 2 limitations is now
closed: a flooding PTY is automatically paused based on the WebSocket
diff --git a/src/main/remote/client-service.ts b/src/main/remote/client-service.ts
index 2c188d1ce..f6974d3bf 100644
--- a/src/main/remote/client-service.ts
+++ b/src/main/remote/client-service.ts
@@ -12,6 +12,7 @@
// - `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
//
@@ -60,6 +61,13 @@ 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. */
@@ -134,6 +142,16 @@ 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)
@@ -357,6 +375,15 @@ 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/preload/index.ts b/src/preload/index.ts
index a43a9033f..fae4b30ca 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -319,6 +319,8 @@ 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 6e4267877..38a5f1d8e 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -67,7 +67,9 @@ function copyViaExecCommand(text: string): boolean {
// diagnosis differs — plain http has no Clipboard API at all, while in a secure context we got
// here because the API rejected (permission denied / document not focused) AND the fallback
// failed too. Canvas listens for this event and shows a banner.
- const secure = typeof window !== 'undefined' && window.isSecureContext
+ // This module only ever runs in a browser (it IS the browser shim), so `window` is there —
+ // guarded consistently rather than half-guarded.
+ const secure = window.isSecureContext
window.dispatchEvent(
new CustomEvent('nodeterm:toast', {
detail: {
@@ -80,8 +82,15 @@ function copyViaExecCommand(text: string): boolean {
)
return false
} finally {
- ta?.remove()
- prev?.focus?.()
+ // A throw in here would ESCAPE the function and replace the return value (a `finally` outranks
+ // both the `return true` and the `return false` above) — so cleanup can never be allowed to
+ // throw: `prev.focus()` on an exotic element is out of our control.
+ try {
+ ta?.remove()
+ prev?.focus?.()
+ } catch {
+ // Cleanup is best-effort; the copy's outcome is what the caller must see.
+ }
}
}
@@ -224,6 +233,10 @@ export function buildStubApi(): Omit<
write: noop,
resize: noop,
kill: noop,
+ // 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/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 830451240..a9462f9dd 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -3795,7 +3795,7 @@ export function Canvas() {
</div>
)}
{copyError && (
- <div className="announce-banner announce-banner--info">
+ <div className="announce-banner announce-banner--warning">
<span className="announce-banner__dot" />
<div className="announce-banner__content">
<span className="announce-banner__body">{copyError}</span>
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index b88c8035e..28800bed6 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -20,9 +20,9 @@ import { patchTerminalScale } from '../terminal/scale-fix'
import { parseOsc52 } from '../terminal/osc52'
import {
attachReplay,
+ copyKeyAction,
createDataGate,
disposalAction,
- isCopyShortcut,
stripTrailingNewline,
toXtermText,
xtermScrollback,
@@ -420,16 +420,21 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
})
}
- // Cmd+C (mac) / Ctrl+Shift+C (Linux, Windows) copy the terminal selection — xterm renders to a
- // canvas, so the DOM-selection copy used elsewhere can't see it. Plain Ctrl+C is left alone so
- // it still sends SIGINT.
- // Returning false only tells xterm to skip the key — xterm never gets to its own
- // preventDefault(), so the browser default would still run: in the Server Edition (and in
- // `npm run dev` with DevTools attached) Ctrl+Shift+C is Chromium's inspect-element picker.
+ // Cmd+C (mac) / Ctrl+Shift+C (Linux, Windows) / Ctrl+Insert copy the terminal selection — xterm
+ // renders to a canvas, so the DOM-selection copy used elsewhere can't see it. Plain Ctrl+C is
+ // left alone so it still sends SIGINT.
+ // The chord is swallowed whether or not there is a selection (`copyKeyAction`): with no
+ // selection, falling through would let xterm map ctrl+c to \x03 and SIGINT the foreground
+ // process — the exact opposite of the "copy" we advertise.
+ // Returning false only tells xterm to skip the key; the browser default still runs unless we
+ // preventDefault() ourselves. Note that in Chromium (Server Edition, or `npm run dev` with
+ // DevTools attached) Ctrl+Shift+C is ALSO the browser's inspect-element picker and that one is
+ // NOT preventable by a page — hence Ctrl+Insert, which no browser reserves.
term.attachCustomKeyEventHandler((e) => {
- if (!term.hasSelection() || !isCopyShortcut(e)) return true
- window.nodeTerminal.clipboard.writeText(term.getSelection())
+ const action = copyKeyAction(e, term.hasSelection())
+ if (action === 'pass') return true
e.preventDefault()
+ if (action === 'copy') window.nodeTerminal.clipboard.writeText(term.getSelection())
return false
})
@@ -618,7 +623,10 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
// 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 ''.
- const history = await window.nodeTerminal.pty.captureHistory(id).catch(() => '')
+ // 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
if (history) {
// The capture is byte-trimmed at the head, so it can begin mid-escape-sequence —
diff --git a/src/renderer/terminal/local-transport.ts b/src/renderer/terminal/local-transport.ts
index 8f1dfe105..987870a73 100644
--- a/src/renderer/terminal/local-transport.ts
+++ b/src/renderer/terminal/local-transport.ts
@@ -35,6 +35,10 @@ export class LocalTransport implements TerminalTransport {
this.pty.destroy(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
new file mode 100644
index 000000000..cd723d428
--- /dev/null
+++ b/src/renderer/terminal/remote-transport.test.ts
@@ -0,0 +1,52 @@
+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') {
+ return {
+ create: vi.fn(async () => '7'),
+ captureHistory: vi.fn(async () => history),
+ write: vi.fn(),
+ resize: vi.fn(),
+ kill: vi.fn(),
+ onData: vi.fn(() => () => {}),
+ onExit: vi.fn(() => () => {})
+ }
+}
+
+let client: ReturnType<typeof fakeClient>
+
+beforeEach(() => {
+ client = fakeClient()
+ ;(globalThis as { window?: unknown }).window = { nodeTerminal: { remoteClient: client } }
+})
+
+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 () => {
+ const transport = new RemoteTransport('conn-1')
+ await expect(transport.create({ cols: 80, rows: 24, persistKey: 'node-a' })).resolves.toEqual({
+ sessionId: '7',
+ fresh: false
+ })
+ })
+})
diff --git a/src/renderer/terminal/remote-transport.ts b/src/renderer/terminal/remote-transport.ts
index 4087a783d..314decdd6 100644
--- a/src/renderer/terminal/remote-transport.ts
+++ b/src/renderer/terminal/remote-transport.ts
@@ -14,6 +14,9 @@ import type { TerminalTransport } from './transport'
* persistent session.
*/
export class RemoteTransport implements TerminalTransport {
+ /** persistKey (host node id) -> the session (host streamId) this client attached for it. */
+ private readonly sessions = new Map<string, string>()
+
constructor(private readonly connectionId: string) {}
private get client() {
@@ -22,11 +25,22 @@ export class RemoteTransport implements TerminalTransport {
async create(options: PtyCreateOptions): Promise<PtyCreateResult> {
const sessionId = await this.client.create(this.connectionId, options)
+ if (options.persistKey) this.sessions.set(options.persistKey, sessionId)
// Cold-restore (scrollback replay / agent resume) is the host's responsibility; a mirroring
// client must never re-launch or replay, so it always reports a warm (non-fresh) attach.
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 5fbb9b7b4..bdf266829 100644
--- a/src/renderer/terminal/terminal-config.test.ts
+++ b/src/renderer/terminal/terminal-config.test.ts
@@ -2,7 +2,9 @@ import { describe, it, expect } from 'vitest'
import {
xtermScrollback,
XTERM_SCROLLBACK_MAX,
+ XTERM_SCROLLBACK_MIN,
isCopyShortcut,
+ copyKeyAction,
attachReplay,
toXtermText,
stripTrailingNewline,
@@ -163,6 +165,14 @@ describe('xtermScrollback', () => {
expect(xtermScrollback(50000)).toBe(XTERM_SCROLLBACK_MAX)
expect(XTERM_SCROLLBACK_MAX).toBe(10000)
})
+
+ it('floors a tiny setting the same way the tmux conf does (history-limit max(1000, n))', () => {
+ // tmux would still keep 1000 lines of history — an xterm buffer smaller than that would make
+ // them unreachable, since xterm is the buffer the user scrolls.
+ expect(XTERM_SCROLLBACK_MIN).toBe(1000)
+ expect(xtermScrollback(100)).toBe(XTERM_SCROLLBACK_MIN)
+ expect(xtermScrollback(0)).toBe(XTERM_SCROLLBACK_MIN)
+ })
})
describe('isCopyShortcut', () => {
@@ -210,4 +220,37 @@ describe('isCopyShortcut', () => {
expect(isCopyShortcut(ev({ ctrlKey: true, altKey: true, shiftKey: true }))).toBe(false)
expect(isCopyShortcut(ev({ ctrlKey: true, altKey: true }))).toBe(false)
})
+
+ it('copies on Ctrl+Insert (the traditional binding no browser reserves)', () => {
+ expect(isCopyShortcut(ev({ ctrlKey: true, key: 'Insert', code: 'Insert' }))).toBe(true)
+ // Shift+Insert is PASTE, not ours; bare Insert is a plain key.
+ expect(isCopyShortcut(ev({ shiftKey: true, key: 'Insert', code: 'Insert' }))).toBe(false)
+ expect(isCopyShortcut(ev({ key: 'Insert', code: 'Insert' }))).toBe(false)
+ expect(
+ isCopyShortcut(ev({ ctrlKey: true, altKey: true, key: 'Insert', code: 'Insert' }))
+ ).toBe(false)
+ })
+})
+
+describe('copyKeyAction', () => {
+ it('copies a copy chord when there is a selection', () => {
+ expect(copyKeyAction(ev({ metaKey: true }), true)).toBe('copy')
+ expect(copyKeyAction(ev({ ctrlKey: true, shiftKey: true }), true)).toBe('copy')
+ })
+
+ it('SWALLOWS Ctrl+Shift+C with no selection — it must never reach the pty as SIGINT', () => {
+ // Regression: falling through to xterm here maps ctrl+c to \x03 and kills the foreground
+ // process, right after the user's selection was cleared by a click. We advertise the chord as
+ // copy, so it can only ever copy or do nothing.
+ expect(copyKeyAction(ev({ ctrlKey: true, shiftKey: true }), false)).toBe('swallow')
+ expect(copyKeyAction(ev({ metaKey: true }), false)).toBe('swallow')
+ expect(copyKeyAction(ev({ ctrlKey: true, key: 'Insert', code: 'Insert' }), false)).toBe(
+ 'swallow'
+ )
+ })
+
+ it('passes plain Ctrl+C through to the pty (SIGINT), selection or not', () => {
+ expect(copyKeyAction(ev({ ctrlKey: true }), true)).toBe('pass')
+ expect(copyKeyAction(ev({ ctrlKey: true }), false)).toBe('pass')
+ })
})
diff --git a/src/renderer/terminal/terminal-config.ts b/src/renderer/terminal/terminal-config.ts
index 652956ee4..02baf5d9a 100644
--- a/src/renderer/terminal/terminal-config.ts
+++ b/src/renderer/terminal/terminal-config.ts
@@ -6,13 +6,22 @@
/** Hard cap on xterm's in-memory scrollback: the cost is per node and one canvas holds many. */
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.
+ */
+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 capped.
+ * `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).
*/
export function xtermScrollback(tmuxScrollback: number): number {
- return Math.min(tmuxScrollback, XTERM_SCROLLBACK_MAX)
+ return Math.min(Math.max(XTERM_SCROLLBACK_MIN, tmuxScrollback), XTERM_SCROLLBACK_MAX)
}
/**
@@ -145,11 +154,12 @@ export interface CopyShortcutEvent {
}
/**
- * True for the keydowns that should copy the terminal selection: Cmd+C (mac) and
- * Ctrl+Shift+C (Linux, Windows). Plain Ctrl+C is deliberately NOT one of them — it must keep
- * reaching the pty as SIGINT.
+ * True for the keydowns that should copy the terminal selection: Cmd+C (mac), Ctrl+Shift+C
+ * (Linux, Windows) and Ctrl+Insert (the traditional terminal binding — the only one of the three
+ * that no browser reserves). Plain Ctrl+C is deliberately NOT one of them — it must keep reaching
+ * the pty as SIGINT.
*
- * The key is matched on the printed letter (`e.key`, so Dvorak/AZERTY follow the letter the user
+ * The letter is matched on the printed key (`e.key`, so Dvorak/AZERTY follow the letter the user
* actually presses) OR on the physical `KeyC` position (`e.code`) — on a non-Latin layout
* (Cyrillic 'с', Greek 'ψ') `e.key` is never 'c', and without the fallback an xterm selection
* would have no keyboard copy at all (the OS Edit menu only copies the DOM selection, not
@@ -160,8 +170,30 @@ export interface CopyShortcutEvent {
*/
export function isCopyShortcut(e: CopyShortcutEvent): boolean {
if (e.type !== 'keydown') return false
- if (e.key.toLowerCase() !== 'c' && e.code !== 'KeyC') return false
+ const insert = e.key === 'Insert' || e.code === 'Insert'
+ const letterC = e.key.toLowerCase() === 'c' || e.code === 'KeyC'
+ if (!insert && !letterC) return false
+ if (insert) {
+ // Ctrl+Insert = copy (Shift+Insert is paste — not ours). No meta/alt.
+ return e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey
+ }
const cmdC = e.metaKey && !e.ctrlKey && !e.altKey
const ctrlShiftC = e.ctrlKey && e.shiftKey && !e.metaKey && !e.altKey
return cmdC || ctrlShiftC
}
+
+/**
+ * What a terminal keydown that MIGHT be a copy chord should do:
+ * - `copy` — it is a copy chord and there is a selection: copy it, swallow the key.
+ * - `swallow` — it is a copy chord with NO selection: still swallow it. Critical for Ctrl+Shift+C:
+ * letting it through means xterm maps ctrl+c to `\x03` and SIGINTs the foreground process. We
+ * advertise the chord as "copy", so pressing it right after a click cleared the selection must
+ * never kill the user's process.
+ * - `pass` — not a copy chord: xterm handles it as usual.
+ */
+export type CopyKeyAction = 'copy' | 'swallow' | 'pass'
+
+export function copyKeyAction(e: CopyShortcutEvent, hasSelection: boolean): CopyKeyAction {
+ if (!isCopyShortcut(e)) return 'pass'
+ return hasSelection ? 'copy' : 'swallow'
+}
diff --git a/src/renderer/terminal/transport.ts b/src/renderer/terminal/transport.ts
index e3409f0a5..5f8cd5791 100644
--- a/src/renderer/terminal/transport.ts
+++ b/src/renderer/terminal/transport.ts
@@ -18,6 +18,13 @@ export interface TerminalTransport {
kill(sessionId: string): void
/** Permanently ends a node's persistent session. */
destroy(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 8d0834f14..eb4ceb4a7 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -167,6 +167,8 @@ 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/types.ts b/src/shared/types.ts
index 706554cfe..34ec4c0a3 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -959,6 +959,13 @@ 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 3e1799e65..8973f2fb9 100644
--- a/test/remote/client-handlers.test.ts
+++ b/test/remote/client-handlers.test.ts
@@ -164,3 +164,73 @@ 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('')
+ })
+})