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.

19.3 KB
Raw Blame
/**
 * Zellij as a persistent-session backend for LOCAL terminals (POSIX only), beside tmux.
 *
 * Everything here was measured against the Zellij 0.45.1 release binary in a throwaway HOME with
 * its own socket dir (docs/session-backends.md has the table and the exact invocations). The
 * functions are pure builders/parsers plus thin runners over an injected `ZellijRun`, so the
 * decisions are testable without a binary and the real-binary suite can drive the same code.
 *
 * The one-paragraph model, so the rest reads:
 *  - One Zellij SESSION per node, named exactly like the tmux one (`nt-<nodeId>`). Every Zellij
 *    session is its own server process, forked by the client that created it — so the session's
 *    environment IS the creating client's environment. That is how the hook env, the account scope
 *    and the gateway/custom-agent env reach the pane with nothing on an argv (measured: a variable
 *    exported only to the creating client is visible in the pane; `-e KEY=VALUE` never exists).
 *  - The PAINTER is a real Zellij client in our pty (`zellij … attach -c <name>`), exactly as the
 *    tmux painter is a tmux client. It enters the alternate screen and enables mouse tracking at
 *    attach, owns the wheel (its own scrollback) and copies a mouse selection with OSC 52 — the
 *    same division of labour the tmux section of CLAUDE.md describes, so the renderer needs no
 *    new mode.
 *  - Everything else (exists / capture / paste / kill) is a short-lived `zellij` CLI call against
 *    the session by name, the way the tmux paths use `has-session` / `capture-pane`.
 */
import type { TextDeliveryResult } from '../shared/text-delivery'
import { sleep } from '../shared/sleep'

/** `(args) → stdout/stderr`, rejecting on a non-zero exit with `stdout`/`stderr` on the error —
 *  i.e. promisified `execFile`'s contract, already bound to the zellij binary and its env. */
export type ZellijRun = (args: readonly string[]) => Promise<{ stdout: string; stderr: string }>

/**
 * Our Zellij config, written to `<userData>/zellij.kdl` and passed with `--config` on every
 * client we start. KEYBINDINGS ARE SESSION-WIDE (measured: a session created with a config
 * whose keybinds were cleared ignored a second client's own config — Ctrl-o d did not detach), so
 * this file decides what everyone attached to a canvas-created session can press.
 *
 * - `default_mode "locked"`: every key reaches the pane. Measured: Ctrl-g, Ctrl-p, Ctrl-t, Ctrl-o
 *   arrived at `cat -v` untouched. Agent CLIs use several of those (Claude Code's Ctrl-g opens the
 *   editor), so the stock NORMAL mode would steal them.
 * - The lock toggle moves from Ctrl-g to Ctrl-Alt-g for the same reason; that keeps a way out for
 *   someone who attaches from their own terminal (Ctrl-Alt-g, then Ctrl-o d detaches — measured).
 * - `session_serialization false`: a killed session is gone, not an "EXITED — attach to resurrect"
 *   entry that `attach -c` would resurrect by re-running its last command.
 * - `pane_frames false` + the bare layout (`ZELLIJ_LAYOUT`): no tab bar, no status bar, no frame —
 *   the node is the terminal, as with tmux's `status off`.
 */
export function zellijConf(): string {
  return [
    '// Generated by nodeterm for canvas terminals. Rewritten on launch; edits are lost.',
    'default_mode "locked"',
    'keybinds {',
    '    locked {',
    '        unbind "Ctrl g"',
    '        bind "Ctrl Alt g" { SwitchToMode "Normal"; }',
    '    }',
    '    shared_except "locked" {',
    '        unbind "Ctrl g"',
    '        bind "Ctrl Alt g" { SwitchToMode "Locked"; }',
    '    }',
    '}',
    'pane_frames false',
    'show_startup_tips false',
    'show_release_notes false',
    'session_serialization false',
    'mouse_mode true',
    ''
  ].join('\n')
}

/**
 * One borderless pane, no plugins. Passed as `--layout-string`, because `options
 * --default-layout <file>` and a `default_layout` config line were both measured to still produce
 * the tab bar and status bar on 0.45.1; `--layout-string` did not. A REATTACH with the same flag
 * was measured to leave the session's single tab alone (no extra tab).
 */
export const ZELLIJ_LAYOUT = 'layout { pane; }'

/**
 * The painter's argv: create-or-attach `name`, the Zellij twin of `tmux new-session -A -s name`.
 * `--close-on-exit` + an explicit initial command make the pane's program deterministic (without
 * one Zellij runs `$SHELL`, and `options --default-shell` was measured NOT to take effect on a
 * created session) and make a shell exit end the session instead of leaving a "held" pane. The
 * initial command is ignored on a reattach, like tmux's `new-session -A` program.
 */
export function zellijAttachArgs(confPath: string, name: string, program: string, programArgs: readonly string[]): string[] {
  return [
    '--config',
    confPath,
    '--layout-string',
    ZELLIJ_LAYOUT,
    'attach',
    '--create',
    '--close-on-exit',
    name,
    '--',
    program,
    ...programArgs
  ]
}

/**
 * `-l` for the shells known to take it, when WE picked the shell (no node program, no configured
 * default): tmux runs its default shell as a login shell, so without this a Zellij node would skip
 * `.zprofile` / `.bash_profile` where a tmux node reads them. Any other shell gets no flag rather
 * than a guess at its grammar.
 */
export function loginShellArgs(shell: string): string[] {
  const base = shell.slice(shell.lastIndexOf('/') + 1)
  return base === 'bash' || base === 'zsh' || base === 'fish' ? ['-l'] : []
}

/** Environment names that make a Zellij CLI act on, or refuse to nest inside, the session the APP
 *  itself happens to run in. Stripped from every Zellij child we start (the TMUX/TMUX_PANE twin). */
export const ZELLIJ_NESTING_ENV = ['ZELLIJ', 'ZELLIJ_SESSION_NAME', 'ZELLIJ_PANE_ID'] as const

/** What `zellij list-sessions -n` prints when there are none — with exit status 1, which is why
 *  the exit status alone cannot tell "no sessions" from "zellij could not answer". */
const NO_SESSIONS = 'No active zellij sessions found'

export type ZellijListing = { ok: true; live: Set<string>; exited: Set<string> } | { ok: false }

/**
 * Parse `zellij list-sessions -n`. A line is `<name> [Created <age> ago]`, plus
 * ` (EXITED - attach to resurrect)` for a serialized dead session (possible for a session a USER
 * created under our name with their own config — ours never serialize). Session names may contain
 * SPACES (measured: `zellij attach -b 'my work'` lists as `my work [Created 0s ago]`), so the name
 * is everything before the LAST ` [Created `. A line that still does not parse makes the whole
 * listing unknown rather than silently dropping a session we might be asked about — which is why a
 * space-intolerant pattern was a blocker: ONE personal session named "my work" turned every answer
 * into `unknown`, forever.
 */
export function parseZellijSessionList(stdout: string): ZellijListing {
  const live = new Set<string>()
  const exited = new Set<string>()
  for (const raw of stdout.split('\n')) {
    const line = raw.trimEnd()
    if (!line) continue
    if (line.startsWith(NO_SESSIONS)) continue
    const m = /^(.+) \[Created [^\]]*\]( \(EXITED\b.*\))?$/.exec(line)
    if (!m) return { ok: false }
    ;(m[2] ? exited : live).add(m[1])
  }
  return { ok: true, live, exited }
}

/** A terminal pane as `list-panes -a -j` reports it (only the fields we read). */
interface ZellijPaneJson {
  id?: unknown
  is_plugin?: unknown
  is_focused?: unknown
  exited?: unknown
}

/**
 * The pane a CLI action should target. Zellij has no "the session's active pane" target for a
 * session with no client attached — an action without `-p` was measured to silently do nothing
 * headless — so every write/dump names a pane: the focused live terminal pane, else the lowest id.
 * Plugin panes (the suppressed `zellij:link`) are never a target. `null` = no live terminal pane
 * (a zombie session, see `zellijSessionState`) or an unreadable reply.
 */
export function pickZellijPane(json: string): string | null {
  let panes: ZellijPaneJson[]
  try {
    const parsed = JSON.parse(json) as unknown
    if (!Array.isArray(parsed)) return null
    panes = parsed as ZellijPaneJson[]
  } catch {
    return null
  }
  const terminals = panes.filter(
    (p) => p && p.is_plugin === false && p.exited !== true && Number.isSafeInteger(p.id) && (p.id as number) >= 0
  )
  if (terminals.length === 0) return null
  const chosen =
    terminals.find((p) => p.is_focused === true) ??
    terminals.reduce((a, b) => ((a.id as number) <= (b.id as number) ? a : b))
  return `terminal_${chosen.id as number}`
}

export type ZellijSessionState = 'live' | 'zombie' | 'absent' | 'unknown'

/**
 * Tri-state existence (plus one), for the warm/cold decision.
 *
 *  - `absent`  — Zellij answered and the name is not listed (or only as a serialized EXITED one).
 *  - `live`    — listed and holding at least one live terminal pane.
 *  - `zombie`  — listed with NO live terminal pane. Measured: when the pane's shell exits while no
 *    client is attached, the session stays listed with only the hidden plugin pane, and an
 *    `attach --create` to it connects and exits at once ("Bye from Zellij!"), taking the session
 *    with it. tmux simply ends the session when its last shell exits, so a zombie IS absence for
 *    our purposes; the caller kills it before creating.
 *  - `unknown` — Zellij could not be asked. Folded to "exists" by the caller, the same fail-safe
 *    direction as tmux (`probeSaysAbsent`): never cold-restore into a session that may be live.
 */
export async function zellijSessionState(run: ZellijRun, name: string): Promise<ZellijSessionState> {
  let listing: ZellijListing
  try {
    listing = parseZellijSessionList((await run(['list-sessions', '-n'])).stdout)
  } catch (error) {
    // Exit 1 with the "none found" sentence is an ANSWER; every other failure is not.
    const out = errorText(error)
    if (out.includes(NO_SESSIONS)) return 'absent'
    return 'unknown'
  }
  if (!listing.ok) return 'unknown'
  if (!listing.live.has(name)) return 'absent'
  // A session a moment old has no terminal pane listed YET (measured: a probe right after
  // `attach --create-background` saw only the plugin pane), which is indistinguishable from a
  // zombie in one read — and the caller KILLS a zombie. So "no terminal pane" must hold across a
  // short window before it is believed; a pane appearing at any point is `live`.
  for (let attempt = 0; ; attempt++) {
    let pane: string | null
    try {
      const { stdout } = await run(['--session', name, 'action', 'list-panes', '--all', '--json'])
      pane = pickZellijPane(stdout)
    } catch {
      return 'unknown'
    }
    if (pane) return 'live'
    if (attempt >= ZOMBIE_CONFIRM_READS - 1) return 'zombie'
    await sleep(ZOMBIE_CONFIRM_GAP_MS)
  }
}

/** A zombie verdict needs this many consecutive pane-less reads, this far apart (~1.2 s total). */
export const ZOMBIE_CONFIRM_READS = 5
export const ZOMBIE_CONFIRM_GAP_MS = 300

/** Resolve the target pane, or null. */
async function paneOf(run: ZellijRun, name: string): Promise<string | null> {
  try {
    const { stdout } = await run(['--session', name, 'action', 'list-panes', '--all', '--json'])
    return pickZellijPane(stdout)
  } catch {
    return null
  }
}

/**
 * The pane's text: viewport + scrollback when `full`, the viewport alone when `viewport`, else the
 * last `tailLines` lines of viewport + scrollback (the shape `tmux capture-pane -S -N` returns).
 * `ansi` keeps SGR (the scrollback snapshot replays colour; the ⌘M view and search read plain
 * text). `''` on any failure — the same "no capture"
 * every caller already handles for tmux.
 */
export async function zellijCapture(
  run: ZellijRun,
  name: string,
  opts: { full?: boolean; ansi?: boolean; tailLines?: number; viewport?: boolean } = {}
): Promise<string> {
  const pane = await paneOf(run, name)
  if (!pane) return ''
  try {
    const { stdout } = await run([
      '--session',
      name,
      'action',
      'dump-screen',
      '--pane-id',
      pane,
      // `viewport`: exactly what is on screen (the co-attach seed, `capture-pane -e` without -S).
      ...(opts.viewport ? [] : ['--full']),
      ...(opts.ansi ? ['--ansi'] : [])
    ])
    if (opts.viewport || opts.full || !opts.tailLines) return stdout
    return tailLines(stdout, opts.tailLines)
  } catch {
    return ''
  }
}

export function tailLines(text: string, n: number): string {
  const lines = text.split('\n')
  const trailing = lines.length > 0 && lines[lines.length - 1] === '' ? lines.pop() : undefined
  const kept = lines.slice(-n)
  return kept.join('\n') + (trailing !== undefined ? '\n' : '')
}

/**
 * Largest paste handed to `zellij action paste`, in UTF-8 bytes. The text rides ONE argv element
 * (the CLI has no stdin form), and Linux caps a single argument at MAX_ARG_STRLEN = 128 KiB —
 * measured: 131,000 bytes delivered, 140,000 failed with exit 126. The margin covers the
 * other argv. A longer paste is REFUSED (false), never split: two bracketed pastes are two
 * submissions to an agent's composer, which is the "one turn per line" class of bug.
 */
export const ZELLIJ_PASTE_MAX_BYTES = 120_000

/**
 * The `paste-buffer -p` contract on Zellij: `action paste` frames with ESC[200~ … ESC[201~ ONLY
 * when the pane's app has requested bracketed paste (measured both ways against `cat -v`: plain
 * after no request, framed after `printf '\e[?2004h'`), and keeps `\n` as `\n`. Enter is a SECOND
 * call (`action write 13`), which is the separate-write shape settled-submit already relies on.
 *
 * Returns true when both landed, `'pasted-not-submitted'` when the paste landed and the Enter did
 * not (never retried — a retry would duplicate the paste), false when nothing was delivered.
 */
export async function zellijSendText(
  run: ZellijRun,
  name: string,
  text: string,
  enter: boolean
): Promise<TextDeliveryResult> {
  if (Buffer.byteLength(text, 'utf8') > ZELLIJ_PASTE_MAX_BYTES) return false
  const pane = await paneOf(run, name)
  if (!pane) return false
  if (text) {
    try {
      // `--` before the text: without it clap reads a leading `-` as a flag — measured, a markdown
      // bullet list was refused and `-h` printed help with exit 0, delivering NOTHING.
      await run(['--session', name, 'action', 'paste', '--pane-id', pane, '--', text])
    } catch {
      return false
    }
  }
  if (!enter) return true
  try {
    await run(['--session', name, 'action', 'write', '--pane-id', pane, '13'])
    return true
  } catch {
    return text ? 'pasted-not-submitted' : false
  }
}

/** Raw bytes into the pane (a keystroke, a control character) — the background-write twin of
 *  `tmux send-keys -l`. Same argv ceiling as the paste. */
export async function zellijWriteChars(run: ZellijRun, name: string, data: string): Promise<boolean> {
  if (!data || Buffer.byteLength(data, 'utf8') > ZELLIJ_PASTE_MAX_BYTES) return false
  const pane = await paneOf(run, name)
  if (!pane) return false
  try {
    await run(['--session', name, 'action', 'write-chars', '--pane-id', pane, '--', data])
    return true
  } catch {
    return false
  }
}

/**
 * End the session. Measured: `kill-session` matches the name EXACTLY (`nt-e` did not touch
 * `nt-e1`: "No session named "nt-e" found. Did you mean nt-e1?", exit 1) — unlike a bare tmux
 * target, there is no prefix fallback to guard against. A session that is not there is an answer
 * (false), not an error.
 */
export async function zellijKillSession(run: ZellijRun, name: string): Promise<boolean> {
  try {
    await run(['kill-session', name])
    return true
  } catch {
    return false
  }
}

/**
 * The pane's foreground command, from ONE `ps -A -o pid=,ppid=,tpgid=,comm=,args=` read.
 *
 * Zellij has no headless equivalent of `#{pane_current_command}`: `action list-clients` names a
 * running command only while a client is attached, and `list-panes` reports the LAUNCH command.
 * The process table does know: each session is a server process `zellij --server
 * <socket dir>/<contract>/<name>`, the pane's shell is its child, and the shell's controlling-tty
 * foreground process group (`tpgid`) is the foreground program — measured: server → bash
 * (tpgid = the `sleep 20` it was running) → `sleep`.
 *
 * `null` = could not tell: no server, a session with more than one pane shell (a user split it
 * from their own client — which pane would we be judging?), a row that does not parse. Every
 * caller already reads null as "not a shell yet" and refuses, the fail-closed direction.
 */
export function zellijForegroundCommand(psOutput: string, name: string): string | null {
  interface Row {
    pid: number
    ppid: number
    tpgid: number
    comm: string
    args: string
  }
  const rows: Row[] = []
  for (const line of psOutput.split('\n')) {
    const m = /^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+(.*)$/.exec(line)
    if (!m) continue
    rows.push({ pid: +m[1], ppid: +m[2], tpgid: +m[3], comm: m[4], args: m[5] })
  }
  const servers = rows.filter((r) => {
    const argv = r.args.trimEnd().split(/\s+/)
    const at = argv.indexOf('--server')
    return at >= 0 && at === argv.length - 2 && argv[at + 1].endsWith(`/${name}`)
  })
  if (servers.length !== 1) return null
  const shells = rows.filter((r) => r.ppid === servers[0].pid)
  if (shells.length !== 1) return null
  const shell = shells[0]
  const fg = shell.tpgid > 0 ? rows.find((r) => r.pid === shell.tpgid) ?? shell : shell
  return commandName(fg.comm)
}

function commandName(comm: string): string {
  const base = comm.slice(comm.lastIndexOf('/') + 1)
  // A login shell's argv[0] is `-zsh`; tmux reports `zsh`.
  return base.startsWith('-') ? base.slice(1) : base
}

function errorText(error: unknown): string {
  if (!error || typeof error !== 'object') return String(error ?? '')
  const e = error as { stdout?: unknown; stderr?: unknown; message?: unknown }
  return [e.stdout, e.stderr, e.message].filter((v) => typeof v === 'string').join('\n')
}

/**
 * Where Zellij will put a session's IPC socket, mirroring its own rule: `$ZELLIJ_SOCKET_DIR`, else
 * `$XDG_RUNTIME_DIR/zellij`, else `<temp dir>/zellij-<uid>`; then `contract_version_1/<name>`.
 * Zellij REFUSES a path over the platform's `sun_path` limit ("IPC socket path is too long (108
 * bytes, max 107)", exit 1) — and on a stock Mac (no XDG_RUNTIME_DIR, a 49-character
 * `/var/folders/…/T/`) a real node id lands at ~104 bytes against macOS's 103. Calculated, not run
 * on a Mac: see the device checklist in docs/session-backends.md.
 */
export function zellijSocketPath(
  env: Record<string, string | undefined>,
  tmpDir: string,
  uid: number,
  name: string
): string {
  const trim = (d: string): string => d.replace(/\/+$/, '')
  const dir = env.ZELLIJ_SOCKET_DIR
    ? trim(env.ZELLIJ_SOCKET_DIR)
    : env.XDG_RUNTIME_DIR
      ? `${trim(env.XDG_RUNTIME_DIR)}/zellij`
      : `${trim(tmpDir)}/zellij-${uid}`
  return `${dir}/contract_version_1/${name}`
}

/** Largest usable unix-socket path in bytes: `sun_path` is 104 bytes on macOS/BSD, 108 on Linux,
 *  one of which is the terminating NUL. */
export function socketPathMax(platform: NodeJS.Platform): number {
  return platform === 'linux' ? 107 : 103
}

/** A node id as the app mints them (`term-<base36 ms>-<8 hex>`), for "would a typical node fit". */
export const TYPICAL_SESSION_NAME = 'nt-term-mucjey8s-ca76ca3d'

export function zellijSocketFits(path: string, platform: NodeJS.Platform): boolean {
  return Buffer.byteLength(path, 'utf8') <= socketPathMax(platform)
}