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): a joiner's cursor lands where the PANE has it, not at the end of the paint

enes77fc485ad112
diff --git a/src/core/pane-cursor.test.ts b/src/core/pane-cursor.test.ts
new file mode 100644
index 000000000..0a1a16a3c
--- /dev/null
+++ b/src/core/pane-cursor.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from 'vitest'
+import { parsePaneCursor } from './pane-cursor'
+
+/**
+ * The interesting cases here are the REFUSALS.
+ *
+ * The caller's fallback for `undefined` is "leave the cursor where the paint left it" — the
+ * behaviour this whole path replaces, so a refusal costs nothing that was not already lost. A
+ * half-parsed reply is the opposite: it would place the cursor at a position the pane never had,
+ * which is worse than the bug being fixed.
+ */
+describe('parsePaneCursor', () => {
+ it('reads the three fields tmux reports', () => {
+ expect(parsePaneCursor('6 1 1')).toEqual({ x: 6, y: 1, visible: true })
+ expect(parsePaneCursor('0 0 0')).toEqual({ x: 0, y: 0, visible: false })
+ })
+
+ it('tolerates the whitespace a shell round trip adds', () => {
+ // The remote path runs through `ssh` and a login shell, so a trailing newline is the norm.
+ expect(parsePaneCursor('12 3 1\n')).toEqual({ x: 12, y: 3, visible: true })
+ expect(parsePaneCursor(' 12 3 1 ')).toEqual({ x: 12, y: 3, visible: true })
+ })
+
+ it('refuses a reply that is not three fields', () => {
+ expect(parsePaneCursor('')).toBeUndefined() // dead ControlMaster, session just died
+ expect(parsePaneCursor('6 1')).toBeUndefined()
+ expect(parsePaneCursor('6 1 1 1')).toBeUndefined()
+ })
+
+ it("refuses tmux's own error text, which arrives on stdout", () => {
+ expect(parsePaneCursor("can't find pane: nt-abc")).toBeUndefined()
+ })
+
+ it('refuses a format string echoed back by a tmux that does not know the fields', () => {
+ expect(parsePaneCursor('#{cursor_x} #{cursor_y} #{cursor_flag}')).toBeUndefined()
+ })
+
+ it('refuses non-integer or negative coordinates', () => {
+ expect(parsePaneCursor('6.5 1 1')).toBeUndefined()
+ expect(parsePaneCursor('-1 1 1')).toBeUndefined()
+ expect(parsePaneCursor('6 -1 1')).toBeUndefined()
+ })
+
+ it('reads the visibility flag strictly rather than guessing', () => {
+ // Guessing wrong either hides a cursor the user is looking for, or paints one over a
+ // full-screen TUI that deliberately hid it.
+ expect(parsePaneCursor('6 1 2')).toBeUndefined()
+ expect(parsePaneCursor('6 1 yes')).toBeUndefined()
+ expect(parsePaneCursor('6 1 ')).toBeUndefined()
+ })
+})
diff --git a/src/core/pane-cursor.ts b/src/core/pane-cursor.ts
new file mode 100644
index 000000000..cf399debf
--- /dev/null
+++ b/src/core/pane-cursor.ts
@@ -0,0 +1,30 @@
+import type { PaneCursor } from '@shared/types'
+
+/**
+ * Parse tmux's `display-message -p '#{cursor_x} #{cursor_y} #{cursor_flag}'` reply.
+ *
+ * Its own module, and pure, because it is the one part of the cursor-restore path that can be
+ * tested without a tmux: the rest is a subprocess call. What it has to get right is not the happy
+ * case but the REFUSALS — a reply that is not three numbers must produce `undefined`, because the
+ * caller's fallback (leave the cursor where the paint left it) is merely the old behaviour, while a
+ * half-parsed answer would place the cursor somewhere the pane never had it.
+ *
+ * Things that legitimately arrive here and are not a cursor: the empty string (a dead
+ * ControlMaster, a session that just died), tmux's own error text on stdout ("can't find pane"),
+ * and a format string echoed back verbatim by a tmux too old to know a field. All refused.
+ *
+ * `cursor_flag` is tmux's "does the application want the cursor shown" bit — 1 or 0. It is read
+ * strictly: anything else refuses the whole reply rather than guessing a visibility, since guessing
+ * wrong either hides a cursor the user needs or paints one over a full-screen TUI that hid it.
+ */
+export function parsePaneCursor(reply: string): PaneCursor | undefined {
+ const parts = reply.trim().split(/\s+/)
+ if (parts.length !== 3) return undefined
+ const x = Number(parts[0])
+ const y = Number(parts[1])
+ // `Number('')` is 0 and `Number('1x')` is NaN — the integer check covers both, and the
+ // non-negative check covers a tmux that reports -1 for "no cursor here".
+ if (!Number.isInteger(x) || !Number.isInteger(y) || x < 0 || y < 0) return undefined
+ if (parts[2] !== '0' && parts[2] !== '1') return undefined
+ return { x, y, visible: parts[2] === '1' }
+}
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index d2ea10c89..5a01fc735 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -10,6 +10,7 @@ import { safeSessionProgram } from '../shared/node-exec'
import { REF_MAX_LEN } from '../shared/presence'
import {
DEFAULT_SETTINGS,
+ type PaneCursor,
type PtyCreateOptions,
type PtyCreateResult,
type Settings,
@@ -25,8 +26,10 @@ import {
remoteTmuxPtyArgs,
remoteTmuxSendKeysArgs,
remoteCapturePaneArgs,
- remotePaneCommandArgs
+ remotePaneCommandArgs,
+ remotePaneCursorArgs
} from './remote-ssh/control-master'
+import { parsePaneCursor } from './pane-cursor'
import { TMUX_SOCKET, sessionName } from './tmux-naming'
import { bracketedInjection } from './paste-injection'
import { releasePty, type ReleasablePty } from './pty-release'
@@ -866,9 +869,17 @@ export class PtyManager {
// as '': the renderer must not reset a terminal for nothing. A plain-shell joiner therefore
// still lands on a blank-but-live screen — there is no source of truth for its past output,
// which is exactly what "no tmux = no continuity" already means everywhere else here.
- return this.captureForResync(existingId)
- .catch(() => '')
- .then((screen) => (screen ? { ...base, screen } : base))
+ // The cursor rides ALONGSIDE the screen, never appended to it: the renderer strips exactly one
+ // trailing newline off the capture before painting (`stripTrailingNewline`, which stops that
+ // last LF scrolling the top row into scrollback), and a control sequence tacked on the end
+ // would leave that regex nothing to match. Asked for in PARALLEL — it is a second tmux round
+ // trip on the create path, and serialising it would add its latency to every join.
+ return Promise.all([
+ this.captureForResync(existingId).catch(() => ''),
+ this.paneCursor(existingId).catch(() => undefined)
+ ]).then(([screen, cursor]) =>
+ screen ? { ...base, screen, ...(cursor ? { cursor } : {}) } : base
+ )
}
/** Spawn a brand-new session for this client (the non-co-attach path). */
@@ -1787,6 +1798,49 @@ export class PtyManager {
return this.captureSnapshot(key)
}
+ /**
+ * Where the pane's cursor is, for a client about to PAINT a captured screen.
+ *
+ * `capture-pane` returns the pane's text and nothing else, so a client painted from it ends up
+ * with its cursor after the last character written rather than where the application put it —
+ * the 2026-08-05 report (refresh an agent CLI, and the block sits at the end of the status line
+ * until the first keystroke repaints). This is the missing half, asked of tmux directly.
+ *
+ * `undefined` on every failure — no tmux, no session, an unparseable reply, a dead ControlMaster.
+ * The renderer's answer to that is to leave the cursor alone, which is exactly the behaviour this
+ * fix replaces, so a failure here costs nothing that was not already lost.
+ */
+ async paneCursor(sessionId: string): Promise<PaneCursor | undefined> {
+ const session = this.sessions.get(sessionId)
+ const key = session?.persistKey ?? session?.indexKey
+ if (!session || !key) return undefined
+ const target = sessionName(key)
+ try {
+ if (session.sshRemote) {
+ const ssh = findSsh()
+ if (!ssh) return undefined
+ const { stdout } = await runAsync(
+ ssh,
+ remotePaneCursorArgs(session.sshRemote.conn, session.sshRemote.controlPath, target)
+ )
+ return parsePaneCursor(stdout)
+ }
+ if (!this.tmuxPath) return undefined
+ const { stdout } = await runAsync(this.tmuxPath, [
+ '-L',
+ TMUX_SOCKET,
+ 'display-message',
+ '-p',
+ '-t',
+ target,
+ '#{cursor_x} #{cursor_y} #{cursor_flag}'
+ ])
+ return parsePaneCursor(stdout)
+ } catch {
+ return undefined
+ }
+ }
+
/**
* 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.ts b/src/core/remote-ssh/control-master.ts
index b0990613c..1ae7c2385 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -249,6 +249,23 @@ export function remotePaneCommandArgs(conn: SshConnection, controlPath: string,
`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${sessionId} '#{pane_current_command}'`
)
}
+/**
+ * Ask the REMOTE tmux where a pane's cursor is — the remote counterpart of `PtyManager.paneCursor`,
+ * and the thing that makes a refreshed SSH terminal land its cursor in the right place. Same
+ * single-quoting rule as `remotePaneCommandArgs`: the `#{…}` fields have to reach the remote tmux
+ * verbatim rather than being eaten by the remote shell. Space-separated so one `split` parses it.
+ */
+export function remotePaneCursorArgs(
+ conn: SshConnection,
+ controlPath: string,
+ sessionId: string
+): string[] {
+ return childArgs(
+ conn,
+ controlPath,
+ `tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${sessionId} '#{cursor_x} #{cursor_y} #{cursor_flag}'`
+ )
+}
export function tmuxProbeArgs(conn: SshConnection, controlPath: string): string[] {
return childArgs(conn, controlPath, 'command -v tmux')
}
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index 0e3a15070..82d91616a 100644
--- a/src/renderer/components/kanban/ModalTerminal.tsx
+++ b/src/renderer/components/kanban/ModalTerminal.tsx
@@ -15,6 +15,7 @@ import { parseOsc52 } from '../../terminal/osc52'
import { activateUnicode11 } from '../../terminal/unicode-width'
import {
attachReplay,
+ cursorPlacementSeq,
seedPaint,
stripTrailingNewline,
terminalKeyAction,
@@ -240,6 +241,10 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Moda
} else if (paint === 'create-screen' && res.screen) {
// Start from a known-clean SGR state, then convert the capture's LFs to CRLFs.
term.write('\x1b[0m' + toXtermText(stripTrailingNewline(res.screen)))
+ // The capture is TEXT, so the paint above left the cursor after its last character rather
+ // than where the pane has it. The modal is a co-attach joiner by definition — it is the
+ // path this affects most, not an edge case (see `cursorPlacementSeq`).
+ term.write(cursorPlacementSeq(res.cursor))
}
// Co-attach joiners miss the mouse-tracking mode tmux only sends at its own attach, so the
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 49502ef7f..ba442db6a 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -34,6 +34,7 @@ import {
attachReplay,
closedByLabel,
createDataGate,
+ cursorPlacementSeq,
disposalAction,
forgetNodeTermState,
letterboxFor,
@@ -1700,7 +1701,16 @@ export function TerminalNode({
accountId: data.accountId,
sshRemote
})
- .then(async ({ sessionId: sid, fresh, accountFallback: fellBack, closed, screen, coAttachMouse }) => {
+ .then(
+ async ({
+ sessionId: sid,
+ fresh,
+ accountFallback: fellBack,
+ closed,
+ screen,
+ cursor,
+ coAttachMouse
+ }) => {
// REFUSED: core's tombstone says another client deleted this node while we weren't
// subscribed (our project was closed/inactive, so no `pty:closed` could reach us). Nothing
// was spawned — land in the same "closed by <name>" state a subscribed co-viewer gets.
@@ -1906,6 +1916,9 @@ export function TerminalNode({
// 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)))
+ // …and put the cursor back where the PANE has it. The capture is text, so the paint
+ // above left the cursor after its last character — see `cursorPlacementSeq`.
+ term.write(cursorPlacementSeq(cursor))
}
}
// A CO-ATTACH JOINER (a second window on this node — rare on the canvas, but possible)
diff --git a/src/renderer/terminal/terminal-config.test.ts b/src/renderer/terminal/terminal-config.test.ts
index a357156bc..92cc7ccfe 100644
--- a/src/renderer/terminal/terminal-config.test.ts
+++ b/src/renderer/terminal/terminal-config.test.ts
@@ -4,6 +4,7 @@ import {
closedByLabel,
copyKeyAction,
createDataGate,
+ cursorPlacementSeq,
disposalAction,
forgetNodeTermState,
isCopyShortcut,
@@ -263,6 +264,34 @@ describe('stripTrailingNewline', () => {
})
})
+/**
+ * …and the row the seed leaves the cursor on is the LAST CAPTURED one, not the one the pane has it
+ * on. That was the 2026-08-05 report: refresh a terminal running an agent CLI and the block cursor
+ * sits at the end of the status line instead of in the input prompt, until the first keystroke
+ * makes the app repaint. `capture-pane` carries text and nothing else, so the position has to be
+ * asked of tmux separately and written after the paint.
+ */
+describe('cursorPlacementSeq', () => {
+ it('moves the cursor to the pane position, converting 0-based to CUP 1-based', () => {
+ // tmux says column 6, row 1 (0-based). CUP is `ESC [ row ; col H`, 1-based, ROW FIRST — getting
+ // that order backwards is the classic way to land the cursor on a transposed cell.
+ expect(cursorPlacementSeq({ x: 6, y: 1, visible: true })).toBe('\x1b[2;7H\x1b[?25h')
+ expect(cursorPlacementSeq({ x: 0, y: 0, visible: true })).toBe('\x1b[1;1H\x1b[?25h')
+ })
+
+ it('carries the visibility the capture also drops', () => {
+ // A full-screen TUI that hid its cursor would otherwise have one painted back over it — the
+ // same class of gap as the mouse modes (`CO_ATTACH_MOUSE_SEQ`).
+ expect(cursorPlacementSeq({ x: 3, y: 4, visible: false })).toBe('\x1b[5;4H\x1b[?25l')
+ })
+
+ it('writes NOTHING when tmux could not be asked', () => {
+ // The pre-fix behaviour: leave the cursor where the paint left it. A poor place, but a known
+ // one — better than a guessed coordinate the pane never had.
+ expect(cursorPlacementSeq(undefined)).toBe('')
+ })
+})
+
describe('disposalAction', () => {
it('proceeds while the node is still mounted', () => {
expect(disposalAction({ disposed: false, handedOff: null })).toBe('proceed')
diff --git a/src/renderer/terminal/terminal-config.ts b/src/renderer/terminal/terminal-config.ts
index 7d061268c..dfc97831a 100644
--- a/src/renderer/terminal/terminal-config.ts
+++ b/src/renderer/terminal/terminal-config.ts
@@ -1,6 +1,11 @@
import type { FontWeight, ITheme } from '@xterm/xterm'
import type { ClientId } from '@shared/presence'
-import type { Settings, TerminalCursorInactiveStyle, TerminalCursorStyle } from '@shared/types'
+import type {
+ PaneCursor,
+ Settings,
+ TerminalCursorInactiveStyle,
+ TerminalCursorStyle
+} from '@shared/types'
import { resolveTerminalTheme } from './themes'
/**
@@ -500,6 +505,29 @@ export function repaintResync(term: ResyncTarget, screen: string, alive?: () =>
})
}
+/**
+ * Put the cursor where the PANE has it, after a screen captured from tmux has been painted.
+ *
+ * `capture-pane` returns text, so painting it leaves the emulator's cursor after the last character
+ * written — the end of the last non-blank row. On an agent CLI that reads as the block cursor
+ * sitting in the status line instead of the input prompt, until the first keystroke makes the app
+ * repaint and move it (reported 2026-08-05, after a terminal Refresh).
+ *
+ * The visibility half matters as much as the position: a full-screen TUI that hid its cursor
+ * (`\x1b[?25l`) would otherwise have one painted back over it by the joiner, because the capture
+ * carries no private modes either — the same gap `CO_ATTACH_MOUSE_SEQ` covers for mouse tracking.
+ *
+ * `undefined` means tmux could not be asked, and the answer to that is the EMPTY string: leave the
+ * cursor exactly where the paint left it. That is the pre-fix behaviour, which is a poor place to
+ * be but a known one — far better than a guessed coordinate, which would move the cursor somewhere
+ * the pane never had it.
+ */
+export function cursorPlacementSeq(cursor: PaneCursor | undefined): string {
+ if (!cursor) return ''
+ // tmux reports 0-based pane coordinates; CUP is 1-based, row first.
+ 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
diff --git a/src/shared/types.ts b/src/shared/types.ts
index cffde05d8..3cad58a56 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -41,6 +41,14 @@ export interface PtyCreateOptions {
sshRemote?: { controlPath: string; conn: import('./ssh').SshConnection; remoteCwd: string; hookEndpointPath?: string; tmuxConfPath?: string; remoteHome?: string }
}
+/** A tmux pane's cursor, as tmux reports it: 0-based column/row within the pane, plus whether the
+ * application currently wants it shown (`#{cursor_flag}`). */
+export interface PaneCursor {
+ x: number
+ y: number
+ visible: boolean
+}
+
/**
* Result of creating a PTY session. `fresh` distinguishes a tmux session that had to be
* created anew (cold start — e.g. after a machine reboot killed the tmux server) from a
@@ -70,6 +78,25 @@ export interface PtyCreateResult {
* — a plain-shell session has no tmux to capture and simply gets nothing).
*/
screen?: string
+ /**
+ * Where the CURSOR sits in the session that `screen` was captured from, in 0-based pane
+ * coordinates, with tmux's cursor-visibility flag.
+ *
+ * The THIRD thing `capture-pane` does not carry, after the mouse modes below. Its output is the
+ * pane's TEXT, so painting it leaves the emulator's cursor wherever the last character landed —
+ * the end of the last non-blank row. That was visible as: refresh a terminal running an agent
+ * CLI, and the block cursor sits at the end of the status line instead of in the input prompt,
+ * until the first keystroke makes the app repaint and place it (reported 2026-08-05).
+ *
+ * Absent when tmux could not be asked, which the renderer treats as "leave the cursor alone" —
+ * the pre-fix behaviour, and better than guessing a position.
+ *
+ * The coordinates are absolute in the pane, and the paint preserves that frame: the capture
+ * starts at pane row 0, the renderer writes it into a terminal that is at least as tall (a
+ * SMALLER joiner resizes the pty, and a resizing join gets no `screen` at all), and tmux trims
+ * trailing blank rows — so nothing scrolls and pane row N is emulator row N.
+ */
+ cursor?: PaneCursor
/**
* This create JOINED a live TMUX-backed session (co-attach), so the fresh xterm must be told
* tmux's mouse-tracking is on. tmux emits the mouse-enable DECSET sequences (`?1000h ?1002h