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(core): the SSH sweep must tell a broken tmux from an idle host
enes2def591984e0
diff --git a/docs/session-memory.md b/docs/session-memory.mdindex 8e16b6556..3949ea6f1 100644--- a/docs/session-memory.md+++ b/docs/session-memory.md@@ -90,8 +90,16 @@ This is the rule the whole feature exists to honour, and every layer preserves i`err.message` and a bare `no such file or directory` also matches a tmux client missing a sharedlibrary (exit 127 on *every* socket) and a dead ssh ControlMaster. Laundering either into "nosessions here" prints an empty panel over 20 live ones.-- `parseRemoteSessionMemory` returns `ok:false` on a missing **or out-of-order** section marker, and- on an empty process table (a host always has processes).+- `parseRemoteSessionMemory` returns `ok:false` on a missing **or out-of-order** section marker, on+ an empty process table (a host always has processes), and — the remote counterpart of the rule+ above — when **no socket answered**. Each socket is fenced in the reply (`##SOCK <name>` … its+ tmux exit status as `##SOCKRC <n>`) with tmux's stderr folded in (`2>&1`), and the SAME+ `isNoServerError` classifies it: exit 0 answers with panes, "no server running" / "error+ connecting to … (no such file or directory)" answers "nothing here", **anything else did not+ answer** (nor did a fence the stream cut off mid-socket). Before this the sweep was+ `{ tmux …; tmux …; } || true` with stderr discarded, so a host whose tmux client could not start+ — exit 127 on *every* socket, live sessions untouched — produced a stream byte-identical to an+ idle host's and the panel said "No sessions are running here." over thirty of them.- The store carries `ok:false` through untouched, and treats a *rejected* call as the same fact.- The panel renders four distinct sentences: "Could not measure sessions on this machine.","Measuring…", "No sessions are running here.", and the list. The grand total and the@@ -133,10 +141,13 @@ under `/bin/sh`** against a fake host tree — the same discipline as `remote-clcomment), and would have made **every healthy host report `ok:false`**. The markers are quoted forthat reason.-Two more properties of that script are load-bearing: every section header is printed-**unconditionally** (a missing one means the stream was cut short, not that the host had nothing),-and the socket names + `-F` format come from the shared constants, so the remote sweep can never-look at a different socket or ask for different fields than the local one. A non-Linux host has no+Three more properties of that script are load-bearing: every section header is printed+**unconditionally** (a missing one means the stream was cut short, not that the host had nothing);+the socket names + `-F` format come from the shared constants, so the remote sweep can never+look at a different socket or ask for different fields than the local one; and **each socket is+fenced with its own tmux exit status and its stderr** (§4) — an exit status alone cannot tell an+unused socket from a broken tmux, and dropping both is what let a failed sweep render as an empty+host. A non-Linux host has no`/proc/meminfo`, so its `mem` is legitimately `null` — the pill must pulse there, never show 0.## 7. Which machine answersdiff --git a/src/core/session-memory-remote.test.ts b/src/core/session-memory-remote.test.tsindex 7f7ce0ca4..62febfe7c 100644--- a/src/core/session-memory-remote.test.ts+++ b/src/core/session-memory-remote.test.ts@@ -12,11 +12,23 @@ import {const run = promisify(execFile)+/** One socket's fence inside the `##PANES` section: what the generated command prints per socket.+ * Every fixture below goes through this, so a change to the fence breaks the tests loudly rather+ * than leaving them asserting a shape the command no longer emits. */+const sock = (name: string, rc: number, body = ''): string =>+ `##SOCK ${name}\n${body}##SOCKRC ${rc}\n`++/** The two sockets answering "no server running" — the normal state of an idle host, and the+ * baseline every "the panes are what matters" fixture wants. */+const bothIdle = (panes = ''): string =>+ sock('node-terminal', 0, panes) + sock('nodeterm-rmt', 1, 'no server running on /tmp/x\n')+describe('parseRemoteSessionMemory', () => {it('parses all three sections into a report', () => {const r = parseRemoteSessionMemory('##MEM\nMemAvailable: 13500000 kB\nMemTotal: 65700000 kB\n' +- '##PANES\nnt-term-a|100|claude\n' ++ '##PANES\n' ++ bothIdle('nt-term-a|100|claude\n') +'##PROCS\n100 1 1024\n200 100 358400\n')expect(r.ok).toBe(true)@@ -26,17 +38,89 @@ describe('parseRemoteSessionMemory', () => {})it('reports ok:false when the PROCS section is missing (the read was cut short)', () => {- const r = parseRemoteSessionMemory('##MEM\n##PANES\nnt-term-a|100|claude\n')+ const r = parseRemoteSessionMemory('##MEM\n##PANES\n' + bothIdle('nt-term-a|100|claude\n'))expect(r.ok).toBe(false)expect(r.rows).toEqual([])})it('reports ok:true with no rows when the host has no nt- sessions', () => {- const r = parseRemoteSessionMemory('##MEM\n##PANES\n##PROCS\n100 1 1024\n')+ const r = parseRemoteSessionMemory('##MEM\n##PANES\n' + bothIdle() + '##PROCS\n100 1 1024\n')expect(r.ok).toBe(true)expect(r.rows).toEqual([])})+ // The whole point of the per-socket fence. `{ tmux …; tmux …; } || true` with stderr discarded+ // produced a byte-identical stream for "this host has no tmux server" and "every tmux call on+ // this host failed", and the panel rendered the second as "No sessions are running here.".+ describe('a socket that FAILED is not a socket that answered "nothing"', () => {+ const procs = '##PROCS\n100 1 1024\n'++ it('accepts tmux saying there is no server (an ANSWER: the socket is simply unused)', () => {+ const r = parseRemoteSessionMemory(+ '##MEM\n##PANES\n' ++ sock('node-terminal', 1, 'no server running on /tmp/tmux-0/node-terminal\n') ++ sock('nodeterm-rmt', 1, 'error connecting to /tmp/tmux-0/nodeterm-rmt (No such file or directory)\n') ++ procs+ )+ expect(r.ok).toBe(true)+ expect(r.rows).toEqual([])+ })++ it('reports ok:false when EVERY socket failed for some other reason', () => {+ // A tmux client missing a shared library exits 127 on every socket — the same binary, so the+ // host's live sessions are untouched and very much still there.+ const linker =+ 'tmux: error while loading shared libraries: libevent-2.1.so.7: cannot open shared object file: No such file or directory\n'+ const r = parseRemoteSessionMemory(+ '##MEM\n##PANES\n' ++ sock('node-terminal', 127, linker) ++ sock('nodeterm-rmt', 127, linker) ++ procs+ )+ expect(r.ok).toBe(false)+ expect(r.rows).toEqual([])+ })++ it('reports ok:true when only SOME sockets failed — one answer is enough', () => {+ const r = parseRemoteSessionMemory(+ '##MEM\n##PANES\n' ++ sock('node-terminal', 0, 'nt-term-a|100|claude\n') ++ sock('nodeterm-rmt', 13, 'error connecting to /tmp/tmux-1/nodeterm-rmt (Permission denied)\n') ++ '##PROCS\n100 1 1024\n'+ )+ expect(r.ok).toBe(true)+ expect(r.rows.map((x) => x.nodeId)).toEqual(['term-a'])+ })++ it('reports ok:false when a socket fence was never closed (the stream was cut mid-socket)', () => {+ const r = parseRemoteSessionMemory(+ '##MEM\n##PANES\n##SOCK node-terminal\nnt-term-a|100|claude\n' + procs+ )+ expect(r.ok).toBe(false)+ expect(r.rows).toEqual([])+ })++ // The fence is matched against the sockets we asked for and a numeric status, so a session+ // whose NAME or foreground command looks like a marker cannot open or close a block.+ it('cannot be fenced by pane data that looks like a marker', () => {+ // The fake opener sits AFTER a real pane and the fake closer INSIDE a real pane line, so a+ // loosened match (`startsWith('##SOCK ')`, or an unanchored `##SOCKRC`) drops one of the two+ // rows instead of merely renaming a command.+ const r = parseRemoteSessionMemory(+ '##MEM\n##PANES\n' ++ sock(+ 'node-terminal',+ 0,+ 'nt-term-a|100|claude\n##SOCK not-a-socket\nnt-term-b|200|##SOCKRC 0\n'+ ) ++ sock('nodeterm-rmt', 1, 'no server running\n') ++ '##PROCS\n100 1 1024\n200 1 2048\n'+ )+ expect(r.ok).toBe(true)+ expect(r.rows.map((x) => x.nodeId).sort()).toEqual(['term-a', 'term-b'])+ })+ })+// An ssh exec channel is not a clean pipe — a login shell's rc file can write to stdout ahead of// our first marker. Out-of-order markers must fail closed, not produce a confident empty report.// The stream below is a COMPLETE, healthy sweep with one stray `##PROCS` echoed ahead of it by a@@ -47,7 +131,8 @@ describe('parseRemoteSessionMemory', () => {const r = parseRemoteSessionMemory('##PROCS\n' +'##MEM\nMemAvailable: 1024 kB\nMemTotal: 2048 kB\n' +- '##PANES\nnt-term-a|100|claude\n' ++ '##PANES\n' ++ bothIdle('nt-term-a|100|claude\n') +'##PROCS\n100 1 1024\n200 100 358400\n')expect(r.ok).toBe(false)@@ -58,7 +143,8 @@ describe('parseRemoteSessionMemory', () => {it('is not confused by a marker appearing inside pane or process data', () => {const r = parseRemoteSessionMemory('##MEM\nMemAvailable: 1024 kB\nMemTotal: 2048 kB\n' +- '##PANES\nnt-term-b|300|##PROCS\n' ++ '##PANES\n' ++ bothIdle('nt-term-b|300|##PROCS\n') +'##PROCS\n300 1 1024\n##PANES\n400 1 2048\n')expect(r.ok).toBe(true)@@ -72,9 +158,13 @@ describe('parseRemoteSessionMemory', () => {// `bySession` map makes the same promise).it('collapses a session reported by several panes into one row', () => {const r = parseRemoteSessionMemory(- '##MEM\n##PANES\nnt-term-a|100|claude\nnt-term-a|300|bash\n##PROCS\n100 1 1024\n300 1 2048\n'+ '##MEM\n##PANES\n' ++ sock('node-terminal', 0, 'nt-term-a|100|claude\n') ++ sock('nodeterm-rmt', 0, 'nt-term-a|300|bash\n') ++ '##PROCS\n100 1 1024\n300 1 2048\n')expect(r.ok).toBe(true)+ // First socket in sweep order wins, exactly as the local leg's first-wins `bySession` does.expect(r.rows.map((x) => x.panePid)).toEqual([100])})})@@ -170,8 +260,13 @@ describe('remoteSessionMemoryCommand under /bin/sh', () => {expect(r.rows.map((x) => x.nodeId)).toEqual(['term-a'])})- it('exits 0 and reports no rows when no tmux server is running', async () => {- const empty = fakeHost('sessmem-notmux-', { tmux: '#!/bin/sh\nexit 1\n' })+ // tmux's OWN words for "there is no server on this socket", on stderr with a non-zero status.+ // A blanket `exit 1` would pass this test while proving nothing: it cannot tell "no server" from+ // "tmux is broken", which are the two cases the fence exists to separate.+ it('exits 0 and reports no rows when tmux says no server is running', async () => {+ const empty = fakeHost('sessmem-notmux-', {+ tmux: '#!/bin/sh\necho "no server running on /tmp/tmux-0/default" >&2\nexit 1\n'+ })const { stdout } = await run('/bin/sh', ['-c', remoteSessionMemoryCommand()], {env: { ...process.env, PATH: `${empty}:${process.env.PATH ?? ''}` }})@@ -180,4 +275,27 @@ describe('remoteSessionMemoryCommand under /bin/sh', () => {expect(r.ok).toBe(true)expect(r.rows).toEqual([])})++ // The failure this whole fence was added for, end to end through the real shell: a tmux client+ // that cannot start exits 127 on EVERY socket while the host's sessions keep running. Under the+ // old command (stderr to /dev/null, status dropped) this stream was byte-identical to the one+ // above and the panel said "No sessions are running here." over thirty live sessions.+ it('reports ok:false when the tmux client itself is broken on every socket', async () => {+ const broken = fakeHost('sessmem-brokentmux-', {+ tmux:+ '#!/bin/sh\necho "tmux: error while loading shared libraries: libevent-2.1.so.7: ' ++ 'cannot open shared object file: No such file or directory" >&2\nexit 127\n'+ })+ const { stdout } = await run('/bin/sh', ['-c', remoteSessionMemoryCommand()], {+ env: { ...process.env, PATH: `${broken}:${process.env.PATH ?? ''}` }+ })+ // The shell still exits 0 and still prints all three markers plus a real process table — which+ // is exactly why the panes section had to carry a per-socket STATUS to tell the two apart.+ expect(stdout).toContain('##MEM')+ expect(stdout).toContain('##PANES')+ expect(stdout).toContain('##PROCS')+ const r = parseRemoteSessionMemory(stdout)+ expect(r.ok).toBe(false)+ expect(r.rows).toEqual([])+ })})diff --git a/src/core/session-memory-remote.ts b/src/core/session-memory-remote.tsindex 69cdf69f8..774aefc7c 100644--- a/src/core/session-memory-remote.ts+++ b/src/core/session-memory-remote.ts@@ -8,6 +8,7 @@import {buildReport,+ isNoServerError,parsePaneList,parseProcessTable,PANE_FMT,@@ -21,6 +22,14 @@ import { RMT_TMUX_SOCKET } from './remote-ssh/control-master'const MEM = '##MEM'const PANES = '##PANES'const PROCS = '##PROCS'+/** Per-socket fence inside the `##PANES` section: `##SOCK <name>` opens it, `##SOCKRC <n>` closes+ * it with that socket's tmux exit status. See `parsePanesSection` for why it exists. */+const SOCK = '##SOCK'+const SOCKRC = '##SOCKRC'++/** The sockets the remote sweep lists, in the order it lists them (the local leg's default order —+ * `bySession` is first-wins, so the order decides which socket a duplicate name is attributed to). */+const SWEEP_SOCKETS: readonly string[] = [TMUX_SOCKET, RMT_TMUX_SOCKET]/*** The generated command. Notes that are load-bearing:@@ -28,8 +37,18 @@ const PROCS = '##PROCS'* short (dead master, killed mid-stream) rather than "the host had nothing".* - The headers are QUOTED. `echo ##MEM` prints an EMPTY LINE: an unquoted `#` at the start of a* word begins a comment in POSIX sh, so the marker is eaten by the shell and every report comes- * back `ok:false`. Measured under dash. Do not drop the quotes.- * - `tmux ... || true` — a host with no tmux server must exit 0. "No sessions" is an answer.+ * back `ok:false`. Measured under dash. Do not drop the quotes. (`"${SOCKRC} $?"` is+ * double-quoted for the same reason AND so `$?` still expands.)+ * - Each socket gets its OWN fence, and its tmux stderr is folded into the fence (`2>&1`) rather+ * than thrown away. This is the remote counterpart of the local leg's `isNoServerError`: the+ * exit status alone cannot tell "there is no tmux server on this socket" (an ANSWER, and the+ * normal state of a socket nobody has used) from "the tmux client is broken / the socket dir+ * belongs to another uid / the server hung" (NOT an answer). The previous form —+ * `{ tmux …; tmux …; } || true` with stderr discarded — collapsed both into an empty section,+ * so a host running thirty sessions with a broken tmux reported `{ok:true, rows:[]}` and the+ * panel said "No sessions are running here."+ * - Nothing after a socket's own line can fail the script: `$?` is consumed by the very next+ * `echo`, so the command still exits 0 for the shell's exit-code gate.* - The socket names and the `-F` format come from the shared constants, so the remote sweep can* never look at a different socket, or ask for different fields, than the local one.* - `ps -eo pid,ppid,rss` is used even on Linux hosts: it is one process instead of thousands of@@ -37,12 +56,16 @@ const PROCS = '##PROCS'*/export function remoteSessionMemoryCommand(): string {const listPanes = (socket: string): string =>- `tmux -L ${socket} list-panes -a -F '${PANE_FMT}' 2>/dev/null`+ [+ `echo '${SOCK} ${socket}'`,+ `tmux -L ${socket} list-panes -a -F '${PANE_FMT}' 2>&1`,+ `echo "${SOCKRC} $?"`+ ].join('\n')return [`echo '${MEM}'`,`cat /proc/meminfo 2>/dev/null | grep -E '^(MemAvailable|MemTotal):' 2>/dev/null || true`,`echo '${PANES}'`,- `{ ${listPanes(TMUX_SOCKET)}; ${listPanes(RMT_TMUX_SOCKET)}; } || true`,+ ...SWEEP_SOCKETS.map(listPanes),`echo '${PROCS}'`,`ps -eo pid,ppid,rss 2>/dev/null || true`].join('\n')@@ -60,6 +83,52 @@ function parseMem(lines: string[]): MemInfo | null {return availableMb !== null && totalMb !== null ? { availableMb, totalMb } : null}+/**+ * The `##PANES` section, one fenced block per socket. Returns how many sockets ANSWERED and the+ * panes they reported.+ *+ * "Answered" is the same distinction the local leg draws with `isNoServerError`, applied to the+ * SAME classifier (a second copy would drift — this branch's ledger records three such drifts):+ * - exit 0 → the socket answered, and its lines are panes;+ * - non-zero with tmux's own "no server running" / "error connecting to … (no such file or+ * directory)" → the socket answered "there is nothing here", which is the normal state of a+ * socket nobody has used;+ * - any other failure (a tmux client missing a shared library exits 127 on EVERY socket, a+ * socket dir owned by another uid, a hung server timing out) → NOT an answer.+ * - a block with no `##SOCKRC` line at all → the stream was cut mid-socket; NOT an answer.+ *+ * The block header is matched against the sockets we actually asked for, and the closer against+ * `##SOCKRC <digits>`, so neither can be forged by a pane whose session name or foreground command+ * happens to start with the marker text.+ */+function parsePanesSection(lines: readonly string[]): { answered: number; panes: PaneRef[] } {+ const headers = new Map(SWEEP_SOCKETS.map((s) => [`${SOCK} ${s}`, s]))+ let answered = 0+ const panes: PaneRef[] = []+ let buf: string[] | null = null+ for (const line of lines) {+ if (headers.has(line)) {+ // A new fence with the previous one still open means the previous socket's status never+ // arrived. It did not answer, and its buffered lines are not trustworthy panes.+ buf = []+ continue+ }+ const rc = /^##SOCKRC (\d+)$/.exec(line)+ if (rc && buf !== null) {+ if (rc[1] === '0') {+ answered+++ panes.push(...parsePaneList(buf.join('\n')))+ } else if (isNoServerError(buf.join('\n'))) {+ answered+++ }+ buf = null+ continue+ }+ if (buf !== null) buf.push(line)+ }+ return { answered, panes }+}+/** Split the fenced sections and reuse the LOCAL assembly, so both legs cannot drift. */export function parseRemoteSessionMemory(stdout: string): SessionMemoryReport {// Tolerant of a CR-terminated stream (an ssh channel that ended up on a pty): the section@@ -82,14 +151,20 @@ export function parseRemoteSessionMemory(stdout: string): SessionMemoryReport {if (!(iMem < iPanes && iPanes < iProcs)) return { ok: false, rows: [], mem: null }const mem = parseMem(lines.slice(iMem + 1, iPanes))- const panes = parsePaneList(lines.slice(iPanes + 1, iProcs).join('\n'))+ const { answered, panes } = parsePanesSection(lines.slice(iPanes + 1, iProcs))const table = parseProcessTable(lines.slice(iProcs + 1).join('\n'))// A host always has processes, so an empty table means `ps` never ran (or its output was lost).if (table.length === 0) return { ok: false, rows: [], mem }+ // Nobody answered: a broken tmux client, a socket dir owned by another uid, a hung server. We did+ // not look, so we cannot claim the host has nothing — that would print "No sessions are running+ // here." over thirty live ones. Exactly the local leg's rule (`collectSessionMemory`), and the+ // reason a blunt "any error ⇒ ok:false" is wrong: on a host with no tmux server at all EVERY+ // socket fails, and there the honest answer is "there are no sessions".+ if (answered === 0) return { ok: false, rows: [], mem }- // Both sockets print into ONE section and `list-panes -a` emits a line per PANE, so a session- // can appear several times. First pane of a session wins — one session is one row, exactly as- // the local leg's `bySession` map guarantees.+ // Both sockets print into the SAME section (each behind its own fence) and `list-panes -a` emits+ // a line per PANE, so a session can appear several times. First pane of a session wins — one+ // session is one row, exactly as the local leg's `bySession` map guarantees.const bySession = new Map<string, PaneRef>()for (const p of panes) if (!bySession.has(p.session)) bySession.set(p.session, p)return buildReport([...bySession.values()], table, mem)