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
feat(core): SSH leg for session memory, one sh round trip
enes232ed520e949
diff --git a/src/core/session-memory-remote.test.ts b/src/core/session-memory-remote.test.tsnew file mode 100644index 000000000..ddf959185--- /dev/null+++ b/src/core/session-memory-remote.test.ts@@ -0,0 +1,106 @@+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { execFile } from 'child_process'+import { promisify } from 'util'+import fs from 'fs'+import os from 'os'+import path from 'path'+import {+ remoteSessionMemoryCommand,+ parseRemoteSessionMemory,+ fetchRemoteSessionMemory+} from './session-memory-remote'++const run = promisify(execFile)++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' ++ '##PROCS\n100 1 1024\n200 100 358400\n'+ )+ expect(r.ok).toBe(true)+ expect(r.mem).toEqual({ availableMb: 13184, totalMb: 64160 })+ expect(r.rows).toHaveLength(1)+ expect(r.rows[0]).toMatchObject({ nodeId: 'term-a', selfMb: 1, childrenMb: 350 })+ })++ 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')+ 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')+ expect(r.ok).toBe(true)+ expect(r.rows).toEqual([])+ })++ // Both sockets are swept in ONE stream, and `list-panes -a` prints a line per PANE, so the same+ // session can appear several times. It is still one session, hence one row (the local leg's+ // `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'+ )+ expect(r.ok).toBe(true)+ expect(r.rows.map((x) => x.panePid)).toEqual([100])+ })+})++describe('fetchRemoteSessionMemory', () => {+ it('reports ok:false when the command could not run (a dead master says nothing)', async () => {+ const r = await fetchRemoteSessionMemory('p1', async () => null)+ expect(r.ok).toBe(false)+ })++ it('reports ok:false when the runner throws', async () => {+ const r = await fetchRemoteSessionMemory('p1', async () => {+ throw new Error('master down')+ })+ expect(r.ok).toBe(false)+ })+})++// The command is generated shell that no compiler checks. Run it for real.+describe('remoteSessionMemoryCommand under /bin/sh', () => {+ let dir: string++ beforeAll(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sessmem-'))+ // A fake tmux on PATH that answers list-panes and nothing else.+ fs.writeFileSync(+ path.join(dir, 'tmux'),+ '#!/bin/sh\nfor a in "$@"; do [ "$a" = "list-panes" ] && { echo "nt-term-a|$$|claude"; exit 0; }; done\nexit 1\n'+ )+ fs.chmodSync(path.join(dir, 'tmux'), 0o755)+ })++ afterAll(() => fs.rmSync(dir, { recursive: true, force: true }))++ it('produces a parseable report on a host with a tmux server', async () => {+ const { stdout } = await run('/bin/sh', ['-c', remoteSessionMemoryCommand()], {+ env: { ...process.env, PATH: `${dir}:${process.env.PATH ?? ''}` }+ })+ const r = parseRemoteSessionMemory(stdout)+ expect(r.ok).toBe(true)+ expect(r.rows.map((x) => x.nodeId)).toEqual(['term-a'])+ // The row resolved against the REAL process table, so it has a real size.+ expect(r.rows[0].totalMb).toBeGreaterThanOrEqual(0)+ })++ it('exits 0 and reports no rows when no tmux server is running', async () => {+ const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'sessmem-notmux-'))+ fs.writeFileSync(path.join(empty, 'tmux'), '#!/bin/sh\nexit 1\n')+ fs.chmodSync(path.join(empty, 'tmux'), 0o755)+ const { stdout } = await run('/bin/sh', ['-c', remoteSessionMemoryCommand()], {+ env: { ...process.env, PATH: `${empty}:${process.env.PATH ?? ''}` }+ })+ const r = parseRemoteSessionMemory(stdout)+ // A clean miss is an ANSWER: the sweep ran, the host simply has nothing.+ expect(r.ok).toBe(true)+ expect(r.rows).toEqual([])+ fs.rmSync(empty, { recursive: true, force: true })+ })+})diff --git a/src/core/session-memory-remote.ts b/src/core/session-memory-remote.tsnew file mode 100644index 000000000..94d5513d8--- /dev/null+++ b/src/core/session-memory-remote.ts@@ -0,0 +1,107 @@+// The SSH leg of session memory: an SSH project's sessions live on the HOST, so the sweep must+// happen there. Core generates one POSIX sh line, the shell runs it over the project's+// ControlMaster, and only the printed sections come back — the same division of labour as+// remote-claude-usage.ts (core owns the command AND the parsing; the shell owns the master).+//+// One round trip carries all three facts, because each extra `ssh` exec is a login on someone+// else's machine.++import {+ buildReport,+ parsePaneList,+ parseProcessTable,+ PANE_FMT,+ type MemInfo,+ type PaneRef,+ type SessionMemoryReport+} from './session-memory'+import { TMUX_SOCKET } from './tmux-naming'+import { RMT_TMUX_SOCKET } from './remote-ssh/control-master'++const MEM = '##MEM'+const PANES = '##PANES'+const PROCS = '##PROCS'++/**+ * The generated command. Notes that are load-bearing:+ * - Every section header is printed unconditionally, so a MISSING one means the read was cut+ * 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.+ * - 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+ * /proc reads over a link we do not control, and its output is what we already parse.+ */+export function remoteSessionMemoryCommand(): string {+ const listPanes = (socket: string): string =>+ `tmux -L ${socket} list-panes -a -F '${PANE_FMT}' 2>/dev/null`+ return [+ `echo '${MEM}'`,+ `cat /proc/meminfo 2>/dev/null | grep -E '^(MemAvailable|MemTotal):' || true`,+ `echo '${PANES}'`,+ `{ ${listPanes(TMUX_SOCKET)}; ${listPanes(RMT_TMUX_SOCKET)}; } || true`,+ `echo '${PROCS}'`,+ `ps -eo pid,ppid,rss 2>/dev/null || true`+ ].join('\n')+}++function parseMem(lines: string[]): MemInfo | null {+ let availableMb: number | null = null+ let totalMb: number | null = null+ for (const l of lines) {+ const a = /MemAvailable:\s+(\d+)\s*kB/.exec(l)+ if (a) availableMb = Math.round(Number(a[1]) / 1024)+ const t = /MemTotal:\s+(\d+)\s*kB/.exec(l)+ if (t) totalMb = Math.round(Number(t[1]) / 1024)+ }+ return availableMb !== null && totalMb !== null ? { availableMb, totalMb } : null+}++/** 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+ // markers are matched whole-line, so a stray \r would hide every one of them.+ const lines = stdout.split('\n').map((l) => l.replace(/\r$/, ''))+ const iMem = lines.indexOf(MEM)+ const iPanes = lines.indexOf(PANES)+ const iProcs = lines.indexOf(PROCS)+ // A missing header means the stream was cut short — not evidence that the host has nothing.+ if (iMem < 0 || iPanes < 0 || iProcs < 0) 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 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 }++ // 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.+ 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)+}++/** Runs a POSIX sh command on the project's host; resolves stdout, or null if it could not run. */+export type RemoteSessionMemoryRunner = (+ projectId: string,+ command: string+) => Promise<string | null>++export async function fetchRemoteSessionMemory(+ projectId: string,+ run: RemoteSessionMemoryRunner+): Promise<SessionMemoryReport> {+ let stdout: string | null = null+ try {+ stdout = await run(projectId, remoteSessionMemoryCommand())+ } catch {+ return { ok: false, rows: [], mem: null }+ }+ // A dead master says nothing about what the host is running.+ if (stdout === null) return { ok: false, rows: [], mem: null }+ return parseRemoteSessionMemory(stdout)+}diff --git a/src/core/session-memory.ts b/src/core/session-memory.tsindex 9d21b4a74..3213626db 100644--- a/src/core/session-memory.ts+++ b/src/core/session-memory.ts@@ -136,7 +136,9 @@ export interface PaneRef {command: string}-const PANE_FMT = '#{session_name}|#{pane_pid}|#{pane_current_command}'+/** The `-F` format `parsePaneList` reads. Exported so the SSH leg's generated shell asks for the+ * exact same fields — a second copy of this string would drift from its own parser. */+export const PANE_FMT = '#{session_name}|#{pane_pid}|#{pane_current_command}'/** Parse `list-panes -a -F '<PANE_FMT>'`. Tolerant: malformed lines are skipped. */export function parsePaneList(stdout: string): PaneRef[] {