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(relay): clear, home and CRLF the backpressure resume repaint

review7de944977bd6
diff --git a/CLAUDE.md b/CLAUDE.md
index c890e8301..35c36383c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -9399,7 +9399,12 @@ unix-socket forward and dev-server `-L` forward over it. POSIX keeps OpenSSH unt
(audit net-1). A 250 ms sweep, armed only while a stream is paused and cleared in
`dropStream`/`closeAll`, waits for `bufferedAmount() <= 256 KB`, then capture → `OP.Snapshot*` →
`setFlow(resume)`, in that order (the dropped frame desynced the phone; resuming first lets live
- output race the repaint). A refused repaint retries with backoff (250 ms doubling to 10 s: a
+ output race the repaint). The repaint is NOT the attach snapshot's bytes: the phone feeds a
+ snapshot into its emulator with no reset, over the old screen, so the resume payload
+ (`resumeRepaintText`, `@shared/capture-paint`) is SGR reset + home + clear, the screen with CRLF
+ line endings (SwiftTerm runs convertEol off) and one trailing newline dropped, then the pane's
+ cursor when `PtyManager.captureVisible` read it (else the attach's own capture, no cursor). The
+ attach snapshot, painted into an empty emulator, stays the raw capture. A refused repaint retries with backoff (250 ms doubling to 10 s: a
reconnecting relay reads 0 buffered but refuses every send, so no backoff = a tmux capture per
tick). Output still queued after the pause is dropped, not streamed. An empty
capture resumes WITHOUT a repaint — unlike `ui-sink-registry`'s keep-desynced rule, staying here
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index c58224324..6cab02e51 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -58,6 +58,8 @@ import { parseRelayKeys } from '../../core/relay-keys'
import { parseRelayLaunch, type RelayLaunchRequest } from '../../core/relay-launch'
import { browseHostDirectory, isWithinRootsFor, type BrowseFs } from '../../core/remote/host-fs-rpc'
import { stripAnsi } from '../../core/transcript-reader'
+import type { VisibleCapture } from '../../core/watch-link/capture-route'
+import { resumeRepaintText } from '../../shared/capture-paint'
// Default relay endpoint; `NODETERM_RELAY_URL` overrides it (mirrors license.ts's API_BASE /
// CHECKOUT_URL env-override pattern — used both as the dev gate and for local testing).
@@ -106,6 +108,10 @@ export interface HostPtyManager {
/** Where a `pty.scroll` wheel for this stream goes (`PtyManager.scrollRoute`). Optional so a
* pre-feature fake keeps today's tmux-only behaviour. */
scrollRoute?(sessionId: string): Promise<'tmux' | 'app-mouse' | 'local'>
+ /** The stream's VISIBLE screen and cursor in one capture (`PtyManager.captureVisible`), for the
+ * backpressure resume's repaint. Optional: absent, or `unavailable`, the resume repaints from the
+ * attach's own capture with no cursor. */
+ captureVisible?(sessionId: string): Promise<VisibleCapture>
/** The node's recent output as plain text (`PtyManager.captureSession`) — `pty.capture`. */
captureSession?(persistKey: string, full?: boolean): Promise<string>
/** Does a session for this node id exist RIGHT NOW? (The destroy path's outcome check.) */
@@ -262,8 +268,9 @@ interface Stream {
resumeAttempts?: number
resumeNotBefore?: number
/** The current-screen capture for this stream (the attach's own `prep.snapshot`), kept so a
- * resume after backpressure can repaint the phone: the frame that crossed the 8 MB line was
- * dropped, so the phone's emulator is desynced and only a fresh screen can fix it. */
+ * resume after backpressure can repaint the phone when no visible capture is available: the
+ * frame that crossed the 8 MB line was dropped, so the phone's emulator is desynced and only a
+ * fresh screen can fix it. */
snapshot?: () => Promise<string>
}
@@ -389,6 +396,22 @@ export function createHostHandlers(
flowSweep = null
}
+ /**
+ * The repaint a resumed stream gets, '' for none. Unlike the attach snapshot (painted into an
+ * EMPTY emulator), this lands on a phone that still shows the old screen and feeds a snapshot in
+ * with no reset of its own — so it clears and homes first, uses CRLF (SwiftTerm runs with
+ * convertEol off; bare LFs staircase), and puts the cursor back when the capture read it. The
+ * visible capture is preferred (screen + cursor in one tmux call); without one the attach's own
+ * capture is used, with the cursor left where the paint ends.
+ */
+ async function resumeRepaint(stream: Stream): Promise<string> {
+ const visible =
+ stream.sessionId && pty.captureVisible ? await pty.captureVisible(stream.sessionId).catch(() => null) : null
+ if (visible && !visible.unavailable) return visible.screen ? resumeRepaintText(visible.screen, visible.cursor) : ''
+ const screen = stream.snapshot ? await stream.snapshot() : ''
+ return screen ? resumeRepaintText(screen, null) : ''
+ }
+
/** Resume a paused stream IF its socket has drained: capture → snapshot → resume, in that order.
* While paused no `onData` can fire, so nothing interleaves with the repaint; resuming first
* would let live output race ahead of a now-stale snapshot. */
@@ -400,7 +423,7 @@ export function createHostHandlers(
void (async () => {
let screen = ''
try {
- screen = stream.snapshot ? await stream.snapshot() : ''
+ screen = await resumeRepaint(stream)
} catch {
screen = ''
}
diff --git a/src/renderer/terminal/terminal-config.ts b/src/renderer/terminal/terminal-config.ts
index bd34458a2..f8b199841 100644
--- a/src/renderer/terminal/terminal-config.ts
+++ b/src/renderer/terminal/terminal-config.ts
@@ -8,6 +8,7 @@ import type {
} from '@shared/types'
import { isWindowsPlatform } from '@shared/platform-utils'
import { xtermScrollback } from '@shared/scrollback'
+import { toXtermText } from '@shared/capture-paint'
import { isKnownTerminalThemeId, resolveTerminalTheme } from './themes'
/**
@@ -156,6 +157,8 @@ export function shouldApplyResync(screen: string | null | undefined): screen is
* cold-restore snapshot replay needs. It follows `settings.tmuxScrollback`, floored and capped.
*/
export { XTERM_SCROLLBACK_MAX, XTERM_SCROLLBACK_MIN, xtermScrollback } from '@shared/scrollback'
+// The capture → emulator transforms live in @shared so main's relay repaint uses the same rules.
+export { stripTrailingNewline, toXtermText } from '@shared/capture-paint'
/* ------------------------------------------------------------------------------------------- *
* Terminal appearance — ONE source for both xterm call sites.
@@ -632,14 +635,6 @@ export function cursorPlacementSeq(cursor: PaneCursor | undefined): string {
return `\x1b[${cursor.y + 1};${cursor.x + 1}H` + (cursor.visible ? '\x1b[?25h' : '\x1b[?25l')
}
-/**
- * Make text captured from tmux (`capture-pane`, LF-separated lines) safe to `term.write()`.
- * xterm runs with `convertEol: false` — a bare LF moves down but keeps the column, so raw capture
- * output would render as a staircase. Lone LFs become CRLF; existing CRLFs are left alone.
- */
-export function toXtermText(text: string): string {
- return text.replace(/\r?\n/g, '\r\n')
-}
/**
* Who closed this node, for the "closed by …" overlay. `by` is null when the destroy was not
@@ -654,18 +649,6 @@ export function closedByLabel(
return peers[by]?.name || 'another user'
}
-/**
- * Drop exactly ONE trailing newline from a tmux capture.
- * `capture-pane -p -e -S -<n>` emits a trailing LF after its last line. Writing it would leave the
- * cursor one row BELOW the last captured row: xterm scrolls, the topmost row of the captured
- * visible screen is pushed into scrollback, and tmux's attach redraw (`\x1b[H\x1b[2J`) then
- * repaints that same screen — so on every warm reattach the first visible row would appear twice.
- * Strip on the RAW capture (LF-separated), before `toXtermText` turns the LFs into CRLFs.
- */
-export function stripTrailingNewline(text: string): string {
- return text.replace(/\r?\n$/, '')
-}
-
/**
* What a spawn continuation must do when it finds the effect already cleaned up while an async
* seed (scrollback snapshot / tmux history) was in flight.
diff --git a/src/shared/capture-paint.ts b/src/shared/capture-paint.ts
new file mode 100644
index 000000000..d283daab6
--- /dev/null
+++ b/src/shared/capture-paint.ts
@@ -0,0 +1,44 @@
+// Turning a screen captured from tmux (`capture-pane -p -e`, LF-separated rows) into bytes an
+// emulator can be fed. Pure, so the renderer's xterm seeding and main's relay repaint share it.
+
+/**
+ * Make text captured from tmux (`capture-pane`, LF-separated lines) safe to `term.write()`.
+ * xterm runs with `convertEol: false` — a bare LF moves down but keeps the column, so raw capture
+ * output would render as a staircase. Lone LFs become CRLF; existing CRLFs are left alone.
+ */
+export function toXtermText(text: string): string {
+ return text.replace(/\r?\n/g, '\r\n')
+}
+
+/**
+ * Drop exactly ONE trailing newline from a tmux capture.
+ * `capture-pane -p -e -S -<n>` emits a trailing LF after its last line. Writing it would leave the
+ * cursor one row BELOW the last captured row: xterm scrolls, the topmost row of the captured
+ * visible screen is pushed into scrollback, and tmux's attach redraw (`\x1b[H\x1b[2J`) then
+ * repaints that same screen — so on every warm reattach the first visible row would appear twice.
+ * Strip on the RAW capture (LF-separated), before `toXtermText` turns the LFs into CRLFs.
+ */
+export function stripTrailingNewline(text: string): string {
+ return text.replace(/\r?\n$/, '')
+}
+
+/**
+ * What a repaint over a LIVE emulator starts with: SGR reset (so the clear paints the default
+ * background, not whatever colour the stream left set), cursor home, clear the screen. The ESC
+ * that opens it also ends any escape sequence the emulator was halfway through when the stream was
+ * cut.
+ */
+export const RESUME_REPAINT_PREFIX = '\x1b[0m\x1b[H\x1b[2J'
+
+/**
+ * A captured screen as a repaint over an emulator that is already showing something — the relay
+ * stream resumed after backpressure, whose phone emulator has the old screen (and a dropped
+ * frame's worth of missing output) on it and feeds a snapshot in without any reset of its own.
+ * Clear and home first, CRLF line endings with the trailing newline dropped, then the cursor where
+ * the pane has it when the capture read one (0-based, as tmux reports it); unknown leaves it where
+ * the paint ends.
+ */
+export function resumeRepaintText(screen: string, cursor: { x: number; y: number } | null): string {
+ const place = cursor ? `\x1b[${cursor.y + 1};${cursor.x + 1}H` : ''
+ return RESUME_REPAINT_PREFIX + toXtermText(stripTrailingNewline(screen)) + place
+}
diff --git a/test/remote/host-handlers.test.ts b/test/remote/host-handlers.test.ts
index 8e6400932..86e1bc6c3 100644
--- a/test/remote/host-handlers.test.ts
+++ b/test/remote/host-handlers.test.ts
@@ -5,6 +5,7 @@ import {
type HostRelaySocket
} from '../../src/main/remote/host-service'
import { OP } from '../../src/main/remote/framing'
+import { RESUME_REPAINT_PREFIX } from '../../src/shared/capture-paint'
import type { DetachedSinks } from '../../src/main/pty-manager'
import type { PtyCreateOptions } from '../../src/shared/types'
@@ -309,6 +310,75 @@ describe('createHostHandlers', () => {
expect(vi.getTimerCount()).toBe(0) // the sweep disarms once nothing is paused
})
+ const resumePayload = (sock: ReturnType<typeof fakeSocket>, from: number): string => {
+ const start = sock.frames.findIndex((f, i) => i >= from && f.op === OP.SnapshotStart)
+ expect(start).toBeGreaterThanOrEqual(0)
+ const chunks: string[] = []
+ for (let i = start + 1; i < sock.frames.length && sock.frames[i].op === OP.SnapshotChunk; i++) {
+ chunks.push(Buffer.from(sock.frames[i].payload).toString('utf8'))
+ }
+ return chunks.join('')
+ }
+
+ it('the resume repaint clears and homes first and paints with CRLF line endings', async () => {
+ // The phone feeds a snapshot into its emulator as-is, with no reset, and the frame that
+ // crossed the 8 MB line was dropped: written raw, the capture lands at the phone's current
+ // cursor over the old screen, and its bare LFs staircase (SwiftTerm runs convertEol off).
+ const { sock } = await pausedStream('row one\nrow two\n')
+ sock.state.ok = true
+ sock.state.buffered = 0
+ const from = sock.frames.length
+ await vi.advanceTimersByTimeAsync(300)
+ const payload = resumePayload(sock, from)
+ expect(payload.startsWith(RESUME_REPAINT_PREFIX)).toBe(true)
+ expect(RESUME_REPAINT_PREFIX).toContain('\x1b[H\x1b[2J')
+ // One trailing newline dropped (it would scroll the top row away), every LF made CRLF.
+ expect(payload).toBe(RESUME_REPAINT_PREFIX + 'row one\r\nrow two')
+ })
+
+ it('the resume repaint puts the cursor where the pane has it when the capture says', async () => {
+ const pty = fakePty()
+ pty.setSnapshot('ATTACH SCREEN\n')
+ const visible: string[] = []
+ ;(pty.mgr as HostPtyManager).captureVisible = async (sessionId) => {
+ visible.push(sessionId)
+ return { screen: 'prompt $ \nstatus\n', cursor: { x: 9, y: 0 } }
+ }
+ const sock = fakeSocket()
+ const h = createHostHandlers(pty.mgr, sock.socket)
+ await openViaAttach(h)
+ // The attach snapshot is byte-identical to before: the raw capture, no prefix, no cursor.
+ expect(Buffer.from(sock.frames[1].payload).toString('utf8')).toBe('ATTACH SCREEN\n')
+ vi.useFakeTimers()
+ sock.state.ok = false
+ sock.state.buffered = 9_000_000
+ pty.sinks().onData('a')
+ sock.state.ok = true
+ sock.state.buffered = 0
+ const from = sock.frames.length
+ await vi.advanceTimersByTimeAsync(300)
+ expect(visible).toEqual(['pty-1'])
+ expect(resumePayload(sock, from)).toBe(RESUME_REPAINT_PREFIX + 'prompt $ \r\nstatus' + '\x1b[1;10H')
+ })
+
+ it('an unavailable visible capture falls back to the attach capture, with no cursor', async () => {
+ const pty = fakePty()
+ pty.setSnapshot('FALLBACK\n')
+ ;(pty.mgr as HostPtyManager).captureVisible = async () => ({ screen: '', cursor: null, unavailable: true })
+ const sock = fakeSocket()
+ const h = createHostHandlers(pty.mgr, sock.socket)
+ await openViaAttach(h)
+ vi.useFakeTimers()
+ sock.state.ok = false
+ sock.state.buffered = 9_000_000
+ pty.sinks().onData('a')
+ sock.state.ok = true
+ sock.state.buffered = 0
+ const from = sock.frames.length
+ await vi.advanceTimersByTimeAsync(300)
+ expect(resumePayload(sock, from)).toBe(RESUME_REPAINT_PREFIX + 'FALLBACK')
+ })
+
it('stays paused while the socket is above the low-water mark', async () => {
const { pty, sock } = await pausedStream()
sock.state.ok = true