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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(pty): let only one DA answer per query reach a shared tmux client (#1223)
eneskirca995e7f65f816
diff --git a/CLAUDE.md b/CLAUDE.mdindex 28b6bacda..0d4c5ab98 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -642,6 +642,22 @@ addon's `select()` must never touch the clipboard. Canvas node and kanban modalsettings preview; attached once per xterm (it survives park/adopt) and written via the bridge's`{ quiet: true }` path so a failed write raises no toast per drag.+**Every viewer answers the tmux client's handshake; only one answer may reach it** (issue #1172).+A new tmux client queries the terminal it is drawn in (DA1 `ESC[c`, DA2 `ESC[>c`, XTVERSION, OSC+10/11 — measured on 3.4). With N viewers on one pty (two Server Edition tabs, a canvas node plus its+kanban card modal, a relay peer) all N xterms answer; tmux consumes ONE DA answer inside its ~5 s+query timeout and passes the rest — and a lone late one — to the pane as typed input, so+`1;2c0;276;0c` landed in front of agent launch lines (the echo check passes: the line itself is+intact) and in live prompts on every reattach. OSC replies are always consumed by tmux. The gate is+`core/da-reply-gate.ts`, per Session, fed from `proc.onData` and applied in `PtyManager.write`: a write+made ONLY of DA1/DA2 replies spends one open query of its kind per reply, and a reply with no open+query (a duplicate, an unsolicited one, or one past `DA_REPLY_TTL_TMUX_MS` = 4 s for a real tmux+client) is dropped. Rules: match only `CSI ? … c` / `CSI > … c` — no key produces them, while a+broader report match eats keystrokes (`ESC[1;2R` is CPR AND Shift+F3); touch only whole reply-only+writes (xterm.js emits each reply as its own data event, so a mixed write is a person); never close+the gate for the session's life (a pane app's DCS-passthrough query shows up as the same `ESC[c` and+gets exactly one answer).+**A tmux client is not necessarily a watcher.** `SessionInfo.clients` is a COUNT(`#{session_attached}`), never a boolean, because one session can hold several: the app's painter,the user's own `tmux -L node-terminal attach`, a second nodeterm on the same socket, and our owndiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex fa1c379ae..aeee66dd9 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -264,6 +264,14 @@ anything else. Board-level fields survive every transform — `pullLinks` is onefrom a background header: only the active SSH project is git-routable. SSH headers observeSource refreshes instead.+- **Pty input is filtered for exactly one thing: duplicate Device Attributes answers.** Every viewer+ of a session (browser tabs, a kanban card modal, a relay peer) answers the tmux client's DA+ handshake, and tmux types every answer after the first into the pane. `core/da-reply-gate.ts`, in+ `PtyManager.write`, lets one DA1/DA2 reply through per query seen on the output and drops the rest.+ Do not widen it to "anything that looks like a terminal report": `ESC[1;2R` is both a CPR and+ Shift+F3, and a filter that eats a keystroke is worse than the bug (see CLAUDE.md → Terminal+ session continuity).+- **A port is a node's only if its listener is in that node's process tree.** Dev-serverdiscovery (`core/dev-ports.ts`) attributes ports by socket ownership and never connects toanything. A new consumer reads the scan, it does not add a probe. A forwarddiff --git a/src/core/da-reply-gate.test.ts b/src/core/da-reply-gate.test.tsnew file mode 100644index 000000000..7ea6d75cd--- /dev/null+++ b/src/core/da-reply-gate.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from 'vitest'+import { DaReplyGate, DA_REPLY_TTL_TMUX_MS } from './da-reply-gate'++const DA1_Q = '\x1b[c'+const DA2_Q = '\x1b[>c'+const DA1_R = '\x1b[?1;2c' // xterm.js+const DA2_R = '\x1b[>0;276;0c' // xterm.js++/** tmux 3.4's client handshake as it reaches the viewer (DA1, DA2, XTVERSION, OSC 10/11). */+const HANDSHAKE = `${DA1_Q}${DA2_Q}\x1b[>q\x1b]10;?\x1b\\\x1b]11;?\x1b\\`++describe('DaReplyGate', () => {+ it('two viewers answer one handshake: the first answer of each kind passes, the copies are dropped', () => {+ const g = new DaReplyGate(DA_REPLY_TTL_TMUX_MS)+ g.noteOutput(HANDSHAKE, 0)+ // Viewer A, then viewer B — each emits DA1 and DA2 as separate writes (xterm.js does).+ expect(g.filterInput(DA1_R, 50)).toBe(DA1_R)+ expect(g.filterInput(DA2_R, 50)).toBe(DA2_R)+ expect(g.filterInput(DA1_R, 60)).toBe('')+ expect(g.filterInput(DA2_R, 60)).toBe('')+ })++ it('a lone answer that arrives after tmux stopped waiting is dropped instead of typed into the pane', () => {+ const g = new DaReplyGate(DA_REPLY_TTL_TMUX_MS)+ g.noteOutput(HANDSHAKE, 0)+ expect(g.filterInput(DA1_R, DA_REPLY_TTL_TMUX_MS + 1)).toBe('')+ expect(g.filterInput(DA2_R, DA_REPLY_TTL_TMUX_MS + 1)).toBe('')+ })++ it('an answer nobody asked for is dropped', () => {+ const g = new DaReplyGate(DA_REPLY_TTL_TMUX_MS)+ expect(g.filterInput(DA1_R, 0)).toBe('')+ expect(g.filterInput(DA2_R, 0)).toBe('')+ })++ it('every reattach (a new handshake) gets its answer again — the gate never closes for good', () => {+ const g = new DaReplyGate(DA_REPLY_TTL_TMUX_MS)+ g.noteOutput(HANDSHAKE, 0)+ expect(g.filterInput(DA1_R, 10)).toBe(DA1_R)+ g.noteOutput(`hello\r\n${DA1_Q}`, 60_000) // e.g. a pane app querying through DCS passthrough+ expect(g.filterInput(DA1_R, 60_010)).toBe(DA1_R)+ expect(g.filterInput(DA1_R, 60_020)).toBe('')+ })++ it('a query split across output chunks still counts, once', () => {+ const g = new DaReplyGate(DA_REPLY_TTL_TMUX_MS)+ g.noteOutput('text\x1b[', 0)+ g.noteOutput('>', 1)+ g.noteOutput('0c more', 2)+ expect(g.filterInput(DA2_R, 3)).toBe(DA2_R)+ expect(g.filterInput(DA2_R, 4)).toBe('')+ })++ it('a reply in the output stream is not a query', () => {+ const g = new DaReplyGate(DA_REPLY_TTL_TMUX_MS)+ g.noteOutput(`${DA1_R}${DA2_R}\x1b[0m\x1b[2J`, 0)+ expect(g.filterInput(DA1_R, 1)).toBe('')+ })++ it('a write that is not purely DA replies is never touched — keystrokes, Shift+F3, CPR, pastes', () => {+ const g = new DaReplyGate(DA_REPLY_TTL_TMUX_MS)+ for (const input of [+ 'claude --resume x\r',+ 'c',+ '\x1b[1;2R', // Shift+F3 == a cursor-position report+ '\x1b[12;40R',+ '\x1b]11;rgb:0000/0000/0000\x1b\\',+ `\x1b[200~${DA1_R}\x1b[201~`, // a bracketed paste that happens to contain the bytes+ `${DA1_R}x`,+ '\x1b[A'+ ]) {+ expect(g.filterInput(input, 0)).toBe(input)+ }+ })++ it('a batched write of several replies keeps only the answered ones', () => {+ const g = new DaReplyGate(DA_REPLY_TTL_TMUX_MS)+ g.noteOutput(DA1_Q, 0)+ expect(g.filterInput(`${DA1_R}${DA2_R}${DA1_R}`, 1)).toBe(DA1_R)+ })++ it('DA1 (CSI 0 c) and DA2 (CSI > 0 c) explicit-parameter queries count too', () => {+ const g = new DaReplyGate(DA_REPLY_TTL_TMUX_MS)+ g.noteOutput('\x1b[0c\x1b[>0c', 0)+ expect(g.filterInput(DA1_R, 1)).toBe(DA1_R)+ expect(g.filterInput(DA2_R, 1)).toBe(DA2_R)+ })+})diff --git a/src/core/da-reply-gate.ts b/src/core/da-reply-gate.tsnew file mode 100644index 000000000..083575b3e--- /dev/null+++ b/src/core/da-reply-gate.ts@@ -0,0 +1,98 @@+/**+ * One Device Attributes answer per question (issue #1172).+ *+ * A new tmux client opens with a handshake to the terminal it is drawn in: DA1 (`ESC[c`) and DA2+ * (`ESC[>c`), among others. When a session has N viewers (two browser tabs on the Server Edition,+ * a canvas node plus its kanban card modal, a relay peer), the client's output reaches N xterms and+ * EVERY one of them answers. tmux takes one answer inside its query timeout (~5 s, measured on 3.4+ * by the reporter) and passes everything else through to the pane as typed input — so N-1 copies of+ * `ESC[?1;2c ESC[>0;276;0c` land in front of an agent's launch line (`1;2c0;276;0c: command not+ * found`), or in a live agent's prompt on every reattach. One viewer whose answer arrives late (a+ * throttled background tab) leaks the same way.+ *+ * The gate sits in `PtyManager.write`, where every viewer's input converges, and answers only what+ * was asked, once:+ * - the pty's OUTPUT is watched for DA1 / DA2 queries (`noteOutput`); each one opens a slot;+ * - an INPUT write that consists of nothing but DA1/DA2 replies (`filterInput`) spends one open+ * slot of its kind per reply; a reply with no open slot is dropped;+ * - a slot expires after `ttlMs` — for a real tmux client just under tmux's own timeout, so an+ * answer tmux would no longer consume is dropped here instead of leaking into the pane.+ *+ * Why only DA1/DA2 replies, and only whole writes (the traps the reporter named):+ * - no key produces `CSI ? … c` or `CSI > … c`, so matching them can never eat a keystroke. A+ * broader "looks like a terminal report" match would: `CSI 1;2R` is a cursor-position report AND+ * Shift+F3. Colour (OSC) replies need no gate — tmux consumes those however many arrive.+ * - xterm.js emits every reply as its OWN data event, so a write that mixes a reply with anything+ * else is not an emulator answer and is passed through untouched (a paste, a keystroke).+ * - the gate never closes for the session's life: a pane app querying the outer terminal through+ * DCS passthrough produces the same `ESC[c` on the client's output, opens a slot, and gets+ * exactly one answer — which is also what that app wants.+ */++/** A real tmux client: just under tmux's ~5 s query timeout, with room for an SSH round trip. */+export const DA_REPLY_TTL_TMUX_MS = 4_000+/** Anything else (a plain shell, the session host): the app's own wait is unknown, so be generous. */+export const DA_REPLY_TTL_OTHER_MS = 30_000++type Kind = 'da1' | 'da2'++// Queries the app/tmux writes to the terminal: CSI c, CSI 0 c (DA1); CSI > c, CSI > 0 c (DA2).+const QUERY = /\x1b\[(>?)0?c/g+// A whole write made only of DA1/DA2 replies.+const REPLIES_ONLY = /^(?:\x1b\[[?>][0-9;]*c)+$/+const REPLY = /\x1b\[([?>])[0-9;]*c/g+// The longest query is 5 bytes (`ESC [ > 0 c`); a chunk ending inside one carries at most 4.+const MAX_CARRY = 4+// A slot list cannot grow without bound when a viewer never answers (a burst of queries).+const MAX_OPEN = 32++export class DaReplyGate {+ private readonly open: Record<Kind, number[]> = { da1: [], da2: [] }+ private carry = ''++ constructor(private readonly ttlMs: number) {}++ /** Watch the pty's output for DA queries. */+ noteOutput(chunk: string, now: number): void {+ if (!chunk) return+ const text = this.carry + chunk+ this.carry = ''+ if (text.indexOf('\x1b') === -1) return+ QUERY.lastIndex = 0+ let m: RegExpExecArray | null+ while ((m = QUERY.exec(text))) this.push(m[1] === '>' ? 'da2' : 'da1', now)+ // Keep a trailing fragment that could still become a query with the next chunk.+ const esc = text.lastIndexOf('\x1b')+ if (esc !== -1 && text.length - esc <= MAX_CARRY && /^\x1b(?:\[(?:>?0?)?)?$/.test(text.slice(esc)))+ this.carry = text.slice(esc)+ }++ /**+ * Input from a viewer. Returns what may reach the pty: the write unchanged unless it is made only+ * of DA1/DA2 replies, in which case only the replies that answer an open query survive ('' = drop).+ */+ filterInput(data: string, now: number): string {+ if (!data || data.charCodeAt(0) !== 0x1b || !REPLIES_ONLY.test(data)) return data+ let kept = ''+ REPLY.lastIndex = 0+ let m: RegExpExecArray | null+ while ((m = REPLY.exec(data))) {+ if (this.take(m[1] === '>' ? 'da2' : 'da1', now)) kept += m[0]+ }+ return kept+ }++ private push(kind: Kind, now: number): void {+ const slots = this.open[kind]+ slots.push(now)+ if (slots.length > MAX_OPEN) slots.shift()+ }++ private take(kind: Kind, now: number): boolean {+ const slots = this.open[kind]+ while (slots.length > 0 && now - slots[0] > this.ttlMs) slots.shift()+ if (slots.length === 0) return false+ slots.shift()+ return true+ }+}diff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.tsindex 323cb3eed..dc8e6b1d9 100644--- a/src/core/pty-coattach.test.ts+++ b/src/core/pty-coattach.test.ts@@ -194,6 +194,33 @@ describe('terminal co-attach: one PTY, N subscribers', () => {expect(spawned[0].writes).toEqual(['a', 'b'])})+ // Issue #1172: tmux's client handshake (DA1 `ESC[c`, DA2 `ESC[>c`) reaches EVERY subscriber's+ // xterm and every one answers. tmux consumes one answer; the rest used to be typed into the pane+ // (`1;2c0;276;0c` in front of an agent's launch line).+ it('only ONE viewer\'s answer to the client\'s DA handshake reaches the pty; keystrokes are untouched', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ await create(BOB)+ spawned[0].onDataCb?.('\x1b[c\x1b[>c\x1b[>q\x1b]11;?\x1b\\')+ write(ALICE, sessionId, '\x1b[?1;2c')+ write(ALICE, sessionId, '\x1b[>0;276;0c')+ write(BOB, sessionId, '\x1b[?1;2c')+ write(BOB, sessionId, '\x1b[>0;276;0c')+ write(BOB, sessionId, '\x1b[1;2R') // Shift+F3, the same bytes as a cursor-position report+ write(ALICE, sessionId, 'claude\r')+ expect(spawned[0].writes).toEqual(['\x1b[?1;2c', '\x1b[>0;276;0c', '\x1b[1;2R', 'claude\r'])+ })++ it('a DA answer nobody asked for (or that arrives after the query expired) never reaches the pty', async () => {+ await manager()+ const { sessionId } = await create(ALICE)+ write(ALICE, sessionId, '\x1b[?1;2c')+ spawned[0].onDataCb?.('\x1b[>c')+ vi.advanceTimersByTime(60_000)+ write(ALICE, sessionId, '\x1b[>0;276;0c')+ expect(spawned[0].writes).toEqual([])+ })+it('a destroyed node is never co-attached to, and never respawned (the × path un-indexes + tombstones it)', async () => {const m = await manager()await create(ALICE)diff --git a/src/core/pty-manager.control-input.test.ts b/src/core/pty-manager.control-input.test.tsindex 9f9a3428f..4182ffb92 100644--- a/src/core/pty-manager.control-input.test.ts+++ b/src/core/pty-manager.control-input.test.ts@@ -13,6 +13,7 @@ import { TMUX_SOCKET, sessionName } from './tmux-naming'import { PANE_INPUT_DEADLINE_MS, keysCommandText, remoteKeysArgs } from './watch-link/pane-input'import { INPUT_DELIVERY_TIMEOUT_MS } from './watch-link/link-host'import { DEFAULT_SETTINGS } from '../shared/types'+import { DaReplyGate } from './da-reply-gate'type Call = { file: string; args: string[]; input: string | undefined }const calls = vi.hoisted(() => [] as Array<{ file: string; args: string[]; input: string | undefined }>)@@ -94,7 +95,7 @@ async function manager(session: Record<string, unknown> | null, tmux: string | nmgr.tmuxPath = tmuxconst write = vi.fn()if (session) {- mgr.sessions.set('sess-1', { persistKey: NODE, indexKey: NODE, nodeId: NODE, tmuxBacked: true, proc: { write }, ...session })+ mgr.sessions.set('sess-1', { persistKey: NODE, indexKey: NODE, nodeId: NODE, tmuxBacked: true, daReplies: new DaReplyGate(4_000), proc: { write }, ...session })mgr.byPersistKey.set(NODE, 'sess-1')}return { mgr, write }diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex fbc59572c..ead6d6d1b 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -148,6 +148,7 @@ import { releasePty, type ReleasablePty } from './pty-release'import { terminateWindowsProcessTree } from '../session-host/windows-process-tree'import { NESTED_AGENT_ENV_STRIP } from './nested-agent-env'import { effectiveSize, type PtySize } from './pty-size'+import { DaReplyGate, DA_REPLY_TTL_OTHER_MS, DA_REPLY_TTL_TMUX_MS } from './da-reply-gate'import { machOArch, archMismatch } from './macho-arch'import { writeScrollback, readScrollback, deleteScrollback } from './scrollback-store'import { snapshotDue } from './scrollback-cadence'@@ -863,6 +864,8 @@ interface Session {* create re-attaches with `new-session -A`. It is the precondition for the idle reap — see* pty-reap.ts — and it is exactly the condition `persisted` is computed from at spawn. */tmuxBacked: boolean+ /** One DA1/DA2 answer per query from however many viewers answer it (issue #1172, da-reply-gate.ts). */+ daReplies: DaReplyGate/** When the reap sweep first saw this session with nobody attached (no live subscriber, no relay* sink); `null` while somebody is. See `reapTick`. */unwatchedSince: number | null@@ -4958,6 +4961,11 @@ export class PtyManager {// asks a different question of it: not "is it worth snapshotting" but "would releasing this// pty client destroy anything" (pty-reap.ts).tmuxBacked: persisted,+ // A real tmux client (local or the SSH project's remote one) gives up on its handshake after+ // ~5 s; anything else has no known deadline. Zellij is not measured, so it gets the generous one.+ daReplies: new DaReplyGate(+ persisted && !useSessionHost && !useLocalZellij ? DA_REPLY_TTL_TMUX_MS : DA_REPLY_TTL_OTHER_MS+ ),unwatchedSince: null,pausedBy: new Set<string>(),accountFallback,@@ -5007,6 +5015,7 @@ export class PtyManager {// rollback removes this exact generation, late callbacks must not recreate its flush timer// or leak bytes into a replacement that happens to reuse the same node id.if (this.sessions.get(sessionId) !== session) return+ session.daReplies.noteOutput(data, Date.now())session.nativeWindowsPane?.recordOutput(data)this.queueData(sessionId, session, data)})@@ -5451,6 +5460,10 @@ export class PtyManager {write(clientId: ClientId | null, sessionId: string, data: string): void {const session = this.sessions.get(sessionId)if (!session) return this.backgroundWriteBySessionId(sessionId, data)+ // Every viewer's xterm answers the tmux client's DA handshake; only one answer per question may+ // reach tmux, or the rest are typed into the pane (issue #1172, da-reply-gate.ts).+ data = session.daReplies.filterInput(data, Date.now())+ if (!data) returnif (clientId !== null && session.nodeId && presenceHub.peerCount() > 1)presenceHub.noteTyping(clientId, session.nodeId)session.proc.write(data)