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(pty): Zellij as an optional local session backend (+ herdr measurement)
review851c77b2b142
diff --git a/CLAUDE.md b/CLAUDE.mdindex a81a8d718..6d898ccf0 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1112,6 +1112,57 @@ conversation, the other two stop the burst that strands it:Wall time is the price and it is the right trade: ungated, five to eleven panes never painted atall inside a 20 s budget — the same shape `remote-session-index.ts` reports for its own burst.+### Zellij as an optional local backend (`settings.sessionBackend`)++Local POSIX terminals can live in **Zellij** instead of tmux (`src/core/zellij-backend.ts`; the+measurement table, the herdr comparison and the device checklist are in+**`docs/session-backends.md`** — Zellij 0.45.1 and herdr 0.9.3 release binaries, Linux, sandboxed+HOME/XDG/socket dir). Default stays tmux; `normalizeSessionBackend` reads anything unknown as tmux;+SSH projects keep the remote tmux and Windows keeps the session host. herdr was measured and not+implemented: its unit is a server of workspaces, a plain pane cannot be attached on its own+(`agent attach` refuses a non-agent pane), per-pane env is argv, and `pane send-text` ignores the+app's paste mode (measured: unframed after `?2004h`).++Rules a refactor must not undo:+- **The backend follows the session that exists** (`decideZellij`). A warm tmux session wins and+ never reaches the Zellij probe; a LIVE Zellij session is reattached in Zellij whatever the setting+ now says; only a node with no session anywhere is created in the selected backend. Otherwise+ flipping the setting cold-restores (`--resume`) an agent into the other multiplexer while the+ original keeps running in the first.+- **Env rides the client, never argv.** Each Zellij session is its own server forked by the client+ that created it, so the painter's `env` (hook env, account scope, gateway/project/custom-agent+ values, all merged in `spawnSession`) IS the session env — measured. There is no `-e` list to+ maintain and nothing to leak; do not add one.+- **Only an answer is absence.** `list-sessions -n` exits 1 both for "No active zellij sessions+ found" (absence) and for real failures; only the sentence counts, everything else is `unknown`,+ folded to "exists" like tmux's `probeSaysAbsent`.+- **A zombie needs confirming before it is killed.** A shell that exits with no client attached+ leaves the session listed with only the hidden plugin pane, and `attach --create` to it exits at+ once, so `decideZellij` kills it first. But a session a moment old ALSO has no terminal pane yet+ (measured, and it made the first version of this code kill its own fresh sessions): five pane-less+ reads 300 ms apart, and one pane at any read is `live`.+- **Every action names a pane** (`pickZellijPane`): without `--pane-id` an action silently did+ nothing headless. `action paste` is the `paste-buffer -p` contract (framed only when the app asked+ — measured both ways); Enter is a second `write 13`; a paste over 120,000 bytes is refused, never+ split (one argv element; 140,000 failed with exit 126).+- **Keybindings are session-wide**, so our `zellij.kdl` decides what everyone attached to a canvas+ session can press: locked mode (Ctrl-g/p/t/o reach the app — Claude Code uses Ctrl-g), unlock on+ Ctrl-Alt-g so an outside client can still detach, `session_serialization false` so a killed+ session is not resurrected by the next `attach --create`.+- **`tmuxBacked` is also true for a Zellij session** (it means "releasing the client destroys+ nothing"); every path that would talk to the tmux socket asks `isZellij` first. A delete kills+ `nt-<id>` in Zellij whenever a binary exists (exact-name match, a no-op for a tmux node), because a+ node deleted after a restart has no live session and no record.+- **Explicit degrades, named in Settings** (`ZELLIJ_BACKEND_GAPS`, pinned to the doc by+ `zellij-backend.test.ts`): messaging/triggers refused (`paneOwner` null), model switch refused+ (`terminateForeground` false), no session-memory panel / reaper, no pane cwd / stale-cwd banner,+ mobile direct-SSH sees only tmux. The pane foreground command IS provided, from one `ps` read+ (server → shell → the shell's `tpgid`); ambiguous (two pane shells) answers null.+Surfaces: Desktop full; Server Edition the same core (row shown when its host reports Zellij);+Mobile via relay joins the Zellij session (`listNodetermSessions` includes and remembers them),+the phone's direct SSH path does not — iOS follow-up. Real-binary suites: `*.realzellij.test.ts`+(`NODETERM_TEST_ZELLIJ` or `zellij` on PATH; skipped in CI, which has none).+### We have our own VT emulator — check it before asking tmuxxterm.js is not just a renderer. It parses the pane's output stream, so it **tracks DECSET modesdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex aab67070c..9f29ee808 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1110,6 +1110,16 @@ tmux without carrying `TMUX_TMPDIR` into it, which is the one way left to escape`src/core/tmux-socket-isolation.guard.test.ts` holds the short allowlist of suites that name aproduction socket on purpose; adding a third is a review conversation, not a checkbox.+**Session code has two local backends on POSIX: tmux and Zellij.** `settings.sessionBackend` picks+where a NEW local terminal's session is created (default tmux); an existing session is always+reattached in the backend that holds it. If you add a `PtyManager` method that talks to tmux about a+node, ask `isZellij(persistKey, live)` first and either implement the Zellij leg in+`src/core/zellij-backend.ts` or answer the explicit "unknown/refused" value and add the gap to+`ZELLIJ_BACKEND_GAPS` (the Settings row prints that list; `docs/session-backends.md` must state it).+Asking the tmux socket about a Zellij node is a guess, and `has-session` exit 1 there reads as+"cold". The `*.realzellij.test.ts` suites need a binary: set `NODETERM_TEST_ZELLIJ=/abs/path/zellij`+or put `zellij` on PATH; they sandbox HOME, XDG and `ZELLIJ_SOCKET_DIR`, and skip otherwise.+**A test's temp directory must go away when the run does.** `fakePlatform()`'s `userDataDir` is madeon first read under one per-run root (`test/setup/fake-platform-root.ts`), and that root is removedafter the last test file finishes. It used to be one `mkdtemp` in the system temp dir per call, neverdiff --git a/docs/session-backends.md b/docs/session-backends.mdnew file mode 100644index 000000000..10532e9f4--- /dev/null+++ b/docs/session-backends.md@@ -0,0 +1,112 @@+# Session backends: Zellij and herdr beside tmux++nodeterm keeps a local terminal alive across app restarts by running it inside a multiplexer+session named `nt-<node id>`: tmux on macOS/Linux, the session host on Windows. Some people live+in **Zellij** or **herdr** and want their canvas terminals to *be* sessions of that tool, so they+can attach to them from anywhere else. This document is the measurement behind v1: what+`PtyManager` needs from its backend, what each tool offers, which one v1 implements and why, and+what that backend does not do.++## How it was measured++- **Zellij 0.45.1** (`zellij-x86_64-unknown-linux-musl`, the latest GitHub release on 2026-09-30).+- **herdr 0.9.3** (`herdr-linux-x86_64`, latest release on 2026-09-30; source at 0.9.1 read for+ paste framing and config paths).+- Both run from `/var/tmp` with a throwaway `HOME`, `XDG_CONFIG_HOME`, `XDG_DATA_HOME`,+ `XDG_CACHE_HOME`, `XDG_RUNTIME_DIR`, plus `ZELLIJ_SOCKET_DIR` (Zellij) / `HERDR_HOME` (herdr). The+ user's tmux servers were never touched; every server started was killed afterwards.+- A painter was a real client in a real pty (a 60-line Python `pty.fork` harness that writes+ scripted input, resizes, and sends SIGHUP). Linux, x86_64. **Nothing was measured on macOS.**++## What PtyManager needs, and what each tool answers++| Need (tmux today) | Zellij 0.45.1 | herdr 0.9.3 |+|---|---|---|+| **Create-or-attach by stable name** (`new-session -A -s nt-<id>`) | `zellij --config <kdl> --layout-string 'layout { pane; }' attach --create --close-on-exit nt-<id> -- <shell> [args]`. Atomic. The initial command is ignored on a reattach. `options --default-layout <file>` and a `default_layout` line both still produced the tab bar and status bar; `--layout-string` did not, and a reattach with it adds no tab. `options --default-shell` was ignored on a created session, hence the explicit initial command. | A *session* is a whole server holding workspaces/tabs/panes (`herdr --session <name> server`). A node would be a pane made with `workspace create --cwd … --env K=V` — and the only way to attach a pty to ONE pane is `agent attach <pane>`, which answered `agent_not_found` for a plain shell pane. A full `herdr --session X` attach draws herdr's own workspace UI. |+| **Detach, leave running** (client exit) | SIGHUP to the client: "Bye from Zellij!", session stays. | Server-side; clients detach. |+| **Strict exists** (`has-session -t =name`) | `list-sessions -n` lines `name [Created …]` (`(EXITED - attach to resurrect)` for serialized ones). No sessions = exit **1** plus "No active zellij sessions found" — exit status alone cannot tell absence from failure. Exact names only. | `session list --json` (`running: true/false`). |+| **Shell exit ends the session** | With a client attached: yes (client prints "Bye", session gone). **With no client attached: the session stays listed with no terminal pane** ("zombie"); an `attach --create` to it connects and exits at once. Right after creation a session also has no terminal pane *for a moment*. | Pane closes inside a still-running server. |+| **Capture screen + history** (`capture-pane -p [-e] -S`) | `action dump-screen --pane-id <p> --full [--ansi]` (viewport, or viewport + scrollback; `--ansi` keeps SGR). ~16 ms per call. | `pane read <pane> --source visible\|recent [--ansi] [--lines N]`. |+| **Send text as ONE paste honouring the app's paste mode, then Enter** (`paste-buffer -p`) | `action paste --pane-id <p> <text>`: **plain** when the app never asked, **framed** `ESC[200~…ESC[201~` after `printf '\e[?2004h'` (both measured against `cat -v`); `\n` stays `\n`. Enter = `action write --pane-id <p> 13`. Text rides ONE argv element: 131,000 bytes delivered, 140,000 failed (exit 126, Linux `MAX_ARG_STRLEN`). No stdin form. | `pane send-text` is **never framed** — measured: text arrived raw after `?2004h`. The mode-aware paste (`paste_payload` in `src/pane.rs`) is only behind `agent prompt`, which requires herdr's own agent detection. |+| **Targeting with no client** | An action without `--pane-id` silently did nothing headless (no focused pane without a client). `action list-panes --all --json` gives ids; the target is the focused live terminal pane, else the lowest id. | Pane ids (`w1:p1`) from `pane list`. |+| **Kill** (`kill-session -t =name`) | `kill-session <name>`, exact match (`nt-e` did not touch `nt-e1`). With `session_serialization false` the session is gone, not resurrectable. | `session stop` / `pane close`. |+| **List sessions + attached-client counts** (reaper, session memory) | Names: `list-sessions -n`. Clients: `--session <s> action list-clients` (one row per client). Not wired in v1 (see gaps). | `session list`; client counts not measured. |+| **Per-session environment at creation, no secrets on argv** (`-e` + `update-environment`) | Each session is its **own server process**, forked by the client that created it, so the session env IS the creating client's env. Measured: a variable exported only to the creating client was visible in the pane; nothing on argv. `ZELLIJ_SESSION_NAME` is set in the pane. | Per-pane `--env KEY=VALUE` is **argv** (visible in `/proc/<pid>/cmdline` while the CLI runs). A server started with a variable does pass it to its panes, but then one server per node. |+| **Pane foreground command** (`#{pane_current_command}`, restart/Eco gates) | No headless CLI: `list-clients` shows a running command only with a client attached (`N/A` for a shell); `list-panes` gives the launch command. The process table does: `zellij --server <socketdir>/contract_version_1/<name>` → its child shell → the shell's `tpgid` → that process. Measured `server → bash (tpgid = sleep) → sleep`. | `pane process-info --pane <id>` returns `foreground_processes` with argv and cwd — the best answer of the three. |+| **Resize / size ownership** | Pty resize → client SIGWINCH. Two clients: the session takes the **smallest** (100×30 + 80×20 → 80×20). | Not measured. |+| **Mouse / scroll / copy** | Client enters the alternate screen (`?1049h`) and enables `?1000h ?1002h ?1003h ?1006h`; wheel scrolls Zellij's own scrollback; a mouse drag emitted **OSC 52** (`ESC]52;c;<base64>`) to the client — the same model as tmux in nodeterm. | Own UI; not measured. |+| **Key passthrough** | Keybindings are **session-wide** (a session created with cleared keybinds ignored a second client's own config). In `default_mode "locked"` Ctrl-g, Ctrl-p, Ctrl-t, Ctrl-o all reached `cat -v`; with the unlock moved to Ctrl-Alt-g, Ctrl-Alt-g then Ctrl-o d detached. | Not measured. |++## Decision: Zellij for v1++Zellij maps onto the tmux contract nearly one to one: an atomic create-or-attach by name, a real+client as the painter (alternate screen, mouse, OSC 52 — the renderer needs nothing new), a paste+that applies the application's own bracketed-paste mode, and environment delivery with nothing on+argv. herdr is a workspace manager whose unit is a server of many panes: a node would have to be+one pane, which cannot be attached to on its own (`agent attach` refuses a non-agent pane), per-pane+environment is argv, and its text send does not honour paste mode.++**herdr gaps, for whoever picks it up:** single-pane attach for a non-agent pane; mode-aware paste+from the CLI (`pane send-text` framing like `paste_payload`); a per-pane environment that is not+argv (stdin or a file). herdr's `pane process-info` is better than anything Zellij offers for the+foreground-process question and would be the model for that leg.++## v1 design (what shipped)++- **Setting:** `settings.sessionBackend` = `tmux` (default) | `zellij`, Settings → Session+ protection → *Session backend*. Read through `normalizeSessionBackend`: anything else is tmux.+ The row is shown only by a core that reports Zellij discovery (POSIX), and says when Zellij is+ selected but not installed (new terminals then use tmux).+- **The backend follows the session that exists.** A warm tmux session is reattached in tmux; a+ live Zellij session is reattached in Zellij, whatever the setting says now; only a node with no+ session anywhere is created in the selected backend. Switching the setting therefore never+ strands a running agent in one multiplexer while cold restore relaunches it in the other.+- **Local projects only.** SSH projects keep the remote tmux; Windows keeps the session host.+- **Our config** (`<userData>/zellij.kdl`, rewritten when it changes): locked mode with the lock+ toggle on Ctrl-Alt-g, no pane frames, no startup tips, `session_serialization false`, mouse on;+ plus the bare one-pane layout. When nodeterm starts the default shell, it passes `-l` for+ bash/zsh/fish, as tmux runs its default shell as a login shell.+- **Zombies:** a session listed with no terminal pane is only believed after five pane-less reads+ 300 ms apart (a just-created session looks the same for a moment); a confirmed zombie is killed+ before the node is created again. Zellij that cannot be asked folds to "exists", the same+ fail-safe direction as tmux.+- **Delete** kills `nt-<id>` in Zellij (exact name) whenever a Zellij binary exists, so a node+ deleted after a restart, never mounted since, does not leave its session running.+- **Paste:** refused (not split) above 120,000 UTF-8 bytes.++### Not available with Zellij (named in the Settings row)++- Agent-to-agent messaging and triggers into Zellij sessions are refused (no pane-owner or paste-mode probe).+- Model switch refuses: it cannot stop the foreground process of a Zellij pane.+- The session-memory panel and the idle-session reaper do not see Zellij sessions.+- The stale-folder banner and the live pane folder for file links are unavailable.+- SSH projects and Windows keep tmux / the session host.+- nodeterm mobile’s direct SSH attach only finds tmux sessions.++Also true and not in that list: control-mode shadow clients do not exist for Zellij (a released+Zellij node is re-attached by a painter, not a zero-pty control client); the late cold-start check+is SSH-only anyway; `paneCursor` is unknown, so a resync paint leaves the cursor where it lands.++## Surfaces++- **Desktop:** full, macOS and Linux.+- **Server Edition:** the same core. The Settings row appears whenever the server host reports+ Zellij discovery; sessions are created on the server host.+- **Mobile:** over the relay, the phone's `pty.attach` goes through the same core and joins the+ Zellij session (`listNodetermSessions` includes Zellij sessions and remembers them for the attach).+ The phone's **direct SSH** path runs `tmux` on the host and cannot see Zellij sessions — an iOS+ follow-up.++## Device checklist (not run here)++1. macOS: `ps -A -o pid=,ppid=,tpgid=,comm=,args=` shape and `tpgid` for the pane shell+ (Restart agent / Eco read the pane command from it).+2. macOS: Zellij from Homebrew is found from a Finder-launched app (`/opt/homebrew/bin`).+3. A canvas node in Zellij: typing, resize, wheel scroll, drag-copy (OSC 52 pill), Shift+Enter in+ an agent CLI, Ctrl-g reaching Claude Code.+4. Attach from an outside terminal with `zellij attach nt-<id>`; both clients see the same pane;+ the smaller one sizes it.+5. App restart with a Zellij node: warm reattach, no cold restore, agent still running.+6. Machine reboot: cold restore replays the scrollback snapshot and resumes the agent in a new+ Zellij session.+7. Server Edition on a Linux host with Zellij installed: create, reattach from a second tab.diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 8e8876451..ffdb864e9 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -79,6 +79,22 @@ import {runPasteDelivery} from './tmux-naming'import { encodeSendKeysHex } from './tmux-control'+import {+ ZELLIJ_NESTING_ENV,+ zellijAttachArgs,+ zellijCapture,+ zellijConf,+ zellijForegroundCommand,+ zellijKillSession,+ zellijSendText,+ zellijSessionState,+ zellijWriteChars,+ loginShellArgs,+ parseZellijSessionList,+ type ZellijRun,+ type ZellijSessionState+} from './zellij-backend'+import { normalizeSessionBackend } from '../shared/session-backend'import { releasePty, type ReleasablePty } from './pty-release'import { terminateWindowsProcessTree } from '../session-host/windows-process-tree'import { effectiveSize, type PtySize } from './pty-size'@@ -737,6 +753,10 @@ interface Session {* `captureForResync`, the final kill in `destroySession`) branches on this the same way it* already branches on `sshRemote`.*/+ /** Held by a Zellij session (zellij-backend.ts) rather than tmux. `tmuxBacked` is ALSO true for it —+ * that field answers "does releasing this client destroy anything", and for Zellij it does not —+ * so every path that would talk to the tmux socket asks this first. */+ zellij?: booleansessionHost?: boolean}@@ -967,6 +987,18 @@ export class PtyManager {private counter = 0private tmuxPath: string | null = nullprivate confPath = ''+ /** The optional Zellij backend (zellij-backend.ts). `undefined` = not looked up yet. */+ private zellijPathMemo: string | null | undefined+ private zellijConfPath = ''+ private zellijConfWritten = ''+ /**+ * Node ids whose session this process knows to live in ZELLIJ — recorded when a create picked+ * Zellij, or a probe (`sessionExists`, `listNodetermSessions`) found one. It is how the paths that+ * start from a node id alone (capture, paste, the relay host's detached attach, a delete with no+ * live client) route to the right backend. Never persisted: after a restart it refills from the+ * renderer's creates and the probes, and a node absent from it is asked of tmux exactly as before.+ */+ private zellijKeys = new Set<string>()private getSettings: () => Settings = () => DEFAULT_SETTINGS/**@@ -1068,8 +1100,11 @@ export class PtyManager {controlSpawn?: ControlSpawnconfirmedProcessRun?: ConfirmedProcessRunruntimePlatform?: NodeJS.Platform+ /** The Zellij binary (tests point this at a sandboxed release binary); absent = look it up. */+ zellijBin?: string | null} = {}) {+ if (deps.zellijBin !== undefined) this.zellijPathMemo = deps.zellijBinthis.controlSpawn = deps.controlSpawnthis.confirmedProcessRun = deps.confirmedProcessRun ?? runAsyncthis.runtimePlatform = deps.runtimePlatform ?? os.platform()@@ -1238,6 +1273,8 @@ export class PtyManager {// about, so a node that is never wanted again costs nothing.if (live) this.shadows.delete(persistKey)if (this.sessionByPersistKey(persistKey)) return null+ // A control-mode client is a tmux client; a Zellij session has nothing of the kind to hold.+ if (this.zellijKeys.has(persistKey)) return nullconst known = this.released.get(persistKey)// A remote (SSH-project) node's tmux server is on the FAR host, reached over that project's// ControlMaster on the `nodeterm-rmt` socket. A local `-C attach -t nt-<id>` here would find@@ -1445,6 +1482,10 @@ export class PtyManager {return true}const settings = this.getSettings()+ if (this.zellijKeys.has(persistKey)) {+ const run = settings.tmuxEnabled ? this.zellijRun() : null+ return run ? zellijWriteChars(run, sessionName(persistKey), data) : false+ }if (!this.tmuxPath || !settings.tmuxEnabled) return false// The kill switch, and the reason it sits BELOW tier 1: the painter is the session's own pty,// which exists with or without this feature — gating it would turn "no control clients" into@@ -1883,6 +1924,8 @@ export class PtyManager {// Re-probe when unavailable: the banner polls this while its install command runs, and a// successful probe here is what makes new sessions tmux-backed without a restart.if (!this.tmuxPath) this.ensureTmux()+ // Same re-probe promise for Zellij: installed while the app runs ⇒ picked up here.+ if (this.zellijPathMemo === null) this.zellijPathMemo = undefinedconst available = !!this.tmuxPathconst hint = available? null@@ -1895,10 +1938,21 @@ export class PtyManager {persistence: {enabled: this.getSettings().tmuxEnabled,backend:- this.runtimePlatform !== 'win32' && available- ? 'tmux'- : sessionHostSupported() ? 'session-host' : null- }+ // Zellij when it is selected AND found: that is where a new local terminal goes.+ this.zellijSelected() && this.zellijBin()+ ? 'zellij'+ : this.runtimePlatform !== 'win32' && available+ ? 'tmux'+ : sessionHostSupported() ? 'session-host' : null+ },+ ...(this.runtimePlatform !== 'win32'+ ? {+ zellij: {+ available: !!this.zellijBin(),+ selected: normalizeSessionBackend(this.getSettings().sessionBackend) === 'zellij'+ }+ }+ : {})}}@@ -2038,6 +2092,8 @@ export class PtyManager {*/persistentSpawnAvailable(): boolean {if (this.tmuxPath && this.getSettings().tmuxEnabled) return true+ // A machine with no tmux whose setting picks Zellij still creates a persistent session.+ if (this.zellijSelected() && this.zellijBin()) return truereturn this.hostBackendEligible()}@@ -2401,7 +2457,24 @@ export class PtyManager {// IS its probe, see above), so it is refused there too rather than sent a round trip that could// create. Fails closed: a viewer never starts anything. One refusal value for both reasons —// the renderer's sentence claims only that no running terminal was found.- if (options.joinOnly && (fresh || freshUnverified || joinOnlyLocalVerdict === 'unknown'))+ // The optional Zellij backend — see `decideZellij` for the rule ("the backend follows the+ // session that exists"). Asked only for a LOCAL persistent node whose tmux session is not there:+ // a warm tmux session is reattached exactly as before, and SSH projects keep the remote tmux.+ const zellijChoice =+ !options.sshRemote &&+ options.persistKey &&+ !warmWindowsBackend &&+ this.runtimePlatform !== 'win32' &&+ this.getSettings().tmuxEnabled &&+ !(tmuxBacked && !fresh)+ ? await this.decideZellij(options.persistKey)+ : undefined+ if (zellijChoice?.use) fresh = zellijChoice.fresh+ // A join-only create on Zellij needs a session we SAW live; anything else could create one.+ const joinRefused = zellijChoice?.use+ ? zellijChoice.state !== 'live'+ : fresh || freshUnverified || joinOnlyLocalVerdict === 'unknown'+ if (options.joinOnly && joinRefused)return { sessionId: '', fresh: false, unavailable: 'join-only' }// Ensure the login-shell PATH is resolved (prewarmed in init(); usually already settled)// so the session env below picks it up — awaiting keeps the event loop free either way.@@ -2459,7 +2532,14 @@ export class PtyManager {: nulllet sessionId: stringtry {- sessionId = this.spawnSession(options, clientId, undefined, warmWindowsBackend, projectOverrides)+ sessionId = this.spawnSession(+ options,+ clientId,+ undefined,+ warmWindowsBackend,+ projectOverrides,+ zellijChoice?.use === true+ )} catch (err) {// A spawn that never happened must not hold a slot until the settle deadline — the next node// in the queue is waiting on it.@@ -2535,7 +2615,12 @@ export class PtyManager {// cwd lives on the host (its probe would need a remote round trip — deliberately out of v1).// Failure/unknowable ⇒ absent ⇒ no banner: the flag is only ever raised on tmux's own answer.const staleCwd =- !fresh && tmuxBacked && !options.sshRemote && !spawned?.sessionHost && options.persistKey+ !fresh &&+ tmuxBacked &&+ !options.sshRemote &&+ !spawned?.sessionHost &&+ !spawned?.zellij &&+ options.persistKey? await this.paneCwdStale(options.persistKey): falsereturn {@@ -2750,9 +2835,148 @@ export class PtyManager {)}+ /**+ * The `zellij` binary, POSIX only (there is no Zellij backend on Windows: the session host owns+ * persistence there). Same lookup shape as `findSsh`: the login-shell PATH, then the usual install+ * locations a GUI app's minimal PATH misses (Homebrew, a cargo install). A miss is memoized only+ * once the async PATH probe has settled, and `tmuxStatus` re-asks, so installing Zellij while the+ * app runs reaches NEW terminals without a restart — the same promise the tmux probe makes.+ */+ private zellijBin(): string | null {+ if (this.runtimePlatform === 'win32') return null+ if (this.zellijPathMemo !== undefined) return this.zellijPathMemo+ let home = ''+ try {+ home = os.homedir()+ } catch {+ // no home: the fixed paths are still checked+ }+ const found = findExecutableSync('zellij', [+ '/opt/homebrew/bin/zellij',+ '/usr/local/bin/zellij',+ '/usr/bin/zellij',+ ...(home ? [path.join(home, '.cargo', 'bin', 'zellij'), path.join(home, '.local', 'bin', 'zellij')] : [])+ ])+ if (found || shellPathNow() !== undefined) this.zellijPathMemo = found+ return found+ }++ /** A bound, bounded runner for the Zellij CLI, or null when there is no binary. The nesting+ * variables are stripped so an app launched from inside Zellij never aims an action at the+ * session it was launched from. */+ private zellijRun(): ZellijRun | null {+ const bin = this.zellijBin()+ if (!bin) return null+ const env = { ...process.env } as Record<string, string>+ for (const k of ZELLIJ_NESTING_ENV) delete env[k]+ return async (args) => {+ const { stdout, stderr } = await runAsync(bin, args, {+ env,+ encoding: 'utf-8',+ maxBuffer: 50 * 1024 * 1024,+ timeout: PROBE_TIMEOUT_MS+ })+ return { stdout: String(stdout), stderr: String(stderr) }+ }+ }++ /** `#{pane_current_command}` for a Zellij session, from one `ps` read (zellijForegroundCommand+ * has the measurement). `ps -A -o pid=,ppid=,tpgid=,comm=,args=` is POSIX-shaped on Linux and+ * macOS alike. null on any failure — "not a shell yet", the refusing answer. */+ private async zellijPaneCommand(name: string): Promise<string | null> {+ if (!this.zellijBin()) return null+ try {+ const { stdout } = await runAsync('ps', ['-A', '-o', 'pid=,ppid=,tpgid=,comm=,args='], {+ encoding: 'utf-8',+ maxBuffer: 16 * 1024 * 1024,+ timeout: PROBE_TIMEOUT_MS+ })+ return zellijForegroundCommand(String(stdout), name)+ } catch {+ return null+ }+ }++ /** Whether this machine's setting asks for Zellij for NEW local sessions (persistence on, POSIX). */+ private zellijSelected(): boolean {+ const s = this.getSettings()+ return (+ this.runtimePlatform !== 'win32' &&+ s.tmuxEnabled &&+ normalizeSessionBackend(s.sessionBackend) === 'zellij'+ )+ }++ /** Is this node's session a Zellij one? A LIVE session answers for itself; with none, the ids a+ * create or probe recorded (`zellijKeys`). */+ private isZellij(persistKey: string, live?: Session): boolean {+ return live ? live.zellij === true : this.zellijKeys.has(persistKey)+ }++ /** Write `<userData>/zellij.kdl` when its content changed (it is generated, like tmux.conf). */+ private ensureZellijConf(): string {+ if (!this.zellijConfPath) this.zellijConfPath = path.join(platform().userDataDir, 'zellij.kdl')+ const conf = zellijConf()+ if (this.zellijConfWritten !== conf) {+ try {+ fs.writeFileSync(this.zellijConfPath, conf)+ this.zellijConfWritten = conf+ } catch (error) {+ console.warn('[pty] could not write zellij.kdl', error instanceof Error ? error.message : error)+ }+ }+ return this.zellijConfPath+ }++ /**+ * THE BACKEND FOLLOWS THE SESSION THAT EXISTS. Called for a local persistent node whose tmux+ * session is NOT there (a warm tmux session always wins and never reaches here). A live Zellij+ * session is reattached whatever the setting now says — switching the setting must not strand a+ * running agent in one multiplexer while cold-restore relaunches it in the other — and only a+ * node with NO session anywhere is created in the backend the setting picks.+ *+ * - `live` → Zellij, warm (`fresh: false`).+ * - `zombie` → killed first (see `zellijSessionState`), then treated as absent.+ * - `unknown` → Zellij only if selected, and then WARM: Zellij could not be asked, and the+ * fail-safe direction is never to cold-restore into a pane that may be live.+ * - `absent` → Zellij only if selected, cold.+ */+ private async decideZellij(+ persistKey: string+ ): Promise<{ use: boolean; fresh: boolean; state: ZellijSessionState }> {+ const run = this.zellijRun()+ if (!run) {+ this.zellijKeys.delete(persistKey)+ return { use: false, fresh: true, state: 'absent' }+ }+ const name = sessionName(persistKey)+ let state = await zellijSessionState(run, name)+ if (state === 'zombie') {+ await zellijKillSession(run, name)+ state = 'absent'+ }+ const selected = this.zellijSelected()+ const use = state === 'live' || (selected && (state === 'absent' || state === 'unknown'))+ if (use) this.zellijKeys.add(persistKey)+ else this.zellijKeys.delete(persistKey)+ return { use, fresh: state === 'absent', state }+ }+async sessionExists(persistKey: string): Promise<boolean> {if (this.liveSessionForPersistKey(persistKey)) return trueconst probes: Promise<boolean>[] = []+ // A Zellij session is a session: the relay host asks this before attaching a phone to a node,+ // and a "no" there would CREATE a tmux session beside the running Zellij one. `unknown` folds+ // to "exists" like tmux's probe; a live answer records the id so the attach routes to Zellij.+ const zellij = this.getSettings().tmuxEnabled ? this.zellijRun() : null+ if (zellij) {+ probes.push(+ zellijSessionState(zellij, sessionName(persistKey)).then((state) => {+ if (state === 'live') this.zellijKeys.add(persistKey)+ return state === 'live' || state === 'unknown'+ })+ )+ }if (this.tmuxPath) probes.push(this.tmuxSessionExists(persistKey))// Same "would this machine ever choose the host backend" predicate the spawn path uses, and it// has to be here rather than only there: `hasSession` goes through `request()`, which@@ -2869,6 +3093,13 @@ export class PtyManager {*/async captureSnapshot(persistKey: string): Promise<string> {const live = this.liveSessionForPersistKey(persistKey)+ if (this.isZellij(persistKey, live)) {+ // The visible screen with its SGR, like `capture-pane -e` without `-S`.+ const run = this.zellijRun()+ return run+ ? zellijCapture(run, sessionName(persistKey), { ansi: true, viewport: true })+ : ''+ }if (live?.sessionHost) {try {return await sessionHostCapture(sessionName(persistKey), false)@@ -2944,7 +3175,11 @@ export class PtyManager {warmWindowsBackend?: 'session-host' | 'tmux',/** What the OWNING project contributes (see `projectSpawnOverrides`) — already resolved,* because this function is synchronous. Null on every path with no proven project owner. */- overrides?: ProjectSpawnOverrides | null+ overrides?: ProjectSpawnOverrides | null,+ /** `create()`'s Zellij decision. Absent on the detached (relay host) paths, which fall back to+ * what this process knows about the node (`zellijKeys`) — a phone attaching to a Zellij node+ * must join that session, never create a tmux one beside it. */+ zellijBackend?: boolean): string {// PRE-FLIGHT — refuse before node-pty is touched, not after it fails.//@@ -3271,6 +3506,16 @@ export class PtyManager {// Unlike the installed-binary probe, this records the backend selected for THIS generation.// A Windows profile may coexist with an MSYS/Cygwin tmux on PATH and must not inherit it.let useLocalTmux = false+ // Set by the Zellij branch below; see zellij-backend.ts.+ let useLocalZellij = false+ const zellijBin =+ !options.sshRemote &&+ options.persistKey &&+ warmWindowsBackend === undefined &&+ settings.tmuxEnabled &&+ (zellijBackend ?? this.zellijKeys.has(options.persistKey))+ ? this.zellijBin()+ : null// Resolve the session program. A bare 'ssh' is resolved to an absolute path because GUI// apps don't inherit the shell PATH; its args come from options.shellArgs.@@ -3438,6 +3683,24 @@ export class PtyManager {attachExistingHost = truefile = ''args = []+ } else if (zellijBin && options.persistKey) {+ // Zellij: the painter is a Zellij CLIENT that creates-or-attaches `nt-<id>`. No `-e` list:+ // a Zellij session is its own server process forked by this client, so `env` — hook env,+ // account scope, gateway, project and custom-agent values, all merged above — IS the+ // session's environment, and no value ever sits on an argv (measured in zellij-backend.ts).+ // The nesting variables go so an app launched from inside Zellij is not refused.+ for (const k of ZELLIJ_NESTING_ENV) delete env[k]+ file = zellijBin+ args = zellijAttachArgs(+ this.ensureZellijConf(),+ sessionName(options.persistKey),+ localSessionShell,+ // tmux starts its own default shell as a LOGIN shell when neither the node nor the setting+ // names a program; mirror that so the same rc files run under either backend.+ program || settings.defaultShell ? localSessionArgs : loginShellArgs(localSessionShell)+ )+ useLocalZellij = true+ this.zellijKeys.add(options.persistKey)} else if (this.tmuxPath && settings.tmuxEnabled && options.persistKey) {// attach-or-create the persistent session for this node.// `-A` = attach-or-create. `-D` = detach OTHER clients on attach. We use `-D` ONLY for the@@ -3611,7 +3874,7 @@ export class PtyManager {// marked remote — otherwise destroy/capture would target a remote tmux that was never spawned// and silently leak the local session.const remote = options.sshRemote && options.persistKey && remoteSsh ? options.sshRemote : undefined- const tmuxBacked = useLocalTmux+ const tmuxBacked = useLocalTmux || useLocalZellij// `useSessionHost` is exactly "did the branch selection above pick the session-host backend",// so it needs no re-derivation here — session-host-backed sessions survive losing their// client exactly like tmux-backed ones do, for the same reason: the underlying pty lives in a@@ -3668,7 +3931,8 @@ export class PtyManager {unwatchedSince: null,pausedBy: new Set<string>(),accountFallback,- sessionHost: useSessionHost+ sessionHost: useSessionHost,+ ...(useLocalZellij ? { zellij: true } : {})}// Both shared timers are armed by the first session that needs them: the scrollback snapshots// and the idle reap are both about tmux-backed sessions and nothing else.@@ -4339,6 +4603,10 @@ export class PtyManager {async captureSession(persistKey: string, full = false): Promise<string> {const live = this.liveSessionForPersistKey(persistKey)if (live?.nativeWindowsPane) return live.nativeWindowsPane.capture(full)+ if (this.isZellij(persistKey, live)) {+ const run = this.zellijRun()+ return run ? zellijCapture(run, sessionName(persistKey), { full, tailLines: 200 }) : ''+ }// Remote (ssh-project) node: there is no local tmux session — capture from the REMOTE tmux// over the project's ControlMaster (mirrors snapshotScrollback / destroySession).const sshRemote = live?.sshRemote@@ -4434,7 +4702,7 @@ export class PtyManager {)return parsePaneCursor(stdout)}- if (session.sessionHost) return undefined+ if (session.sessionHost || session.zellij) return undefinedif (!this.tmuxPath) return undefinedconst { stdout } = await runAsync(this.tmuxPath, ['-L',@@ -4479,6 +4747,13 @@ export class PtyManager {sshRemote?: NonNullable<PtyCreateOptions['sshRemote']>,sessionHost = false): Promise<boolean> {+ if (!sshRemote && this.zellijKeys.has(persistKey)) {+ const run = this.zellijRun()+ if (!run) return false+ const text = await zellijCapture(run, sessionName(persistKey), { ansi: true, tailLines: 1500 })+ // '' is "no capture" (session gone, Zellij unreachable): keep the last good snapshot.+ return text ? await this.writeScrollbackIfChanged(persistKey, text) : false+ }if (sshRemote) {// Remote (ssh-project) node: capture from the REMOTE tmux over the project's ControlMaster.const ssh = findSsh()@@ -4568,6 +4843,12 @@ export class PtyManager {// A direct (non-persistent) Windows PTY has no session-host entry and no tmux: it is typed// into through the pane itself. Routing it to the session host below failed every time.if (live?.nativeWindowsPane) return live.nativeWindowsPane.sendText(text, enter)+ if (this.isZellij(persistKey, live)) {+ // `action paste` applies the pane's own bracketed-paste state — the `paste-buffer -p`+ // contract — then Enter as a second write. See zellijSendText.+ const run = this.zellijRun()+ return run ? zellijSendText(run, target, text, enter) : false+ }const sshRemote = live?.sshRemotetry {if (sshRemote) {@@ -4610,6 +4891,7 @@ export class PtyManager {async paneCommand(persistKey: string): Promise<string | null> {const target = sessionName(persistKey)const live = this.liveSessionForPersistKey(persistKey)+ if (this.isZellij(persistKey, live)) return this.zellijPaneCommand(target)const sshRemote = live?.sshRemoteif (sshRemote) {const ssh = findSsh()@@ -4660,6 +4942,9 @@ export class PtyManager {async paneCwd(persistKey: string): Promise<string | null> {const target = sessionName(persistKey)const live = this.liveSessionForPersistKey(persistKey)+ // No Zellij equivalent of `#{pane_current_path}` is used: unknown, and file links fall back to+ // the launch cwd (ZELLIJ_BACKEND_GAPS). Never asked of the tmux socket, which would be a guess.+ if (this.isZellij(persistKey, live)) return nullconst sshRemote = live?.sshRemoteif (sshRemote) {const ssh = findSsh()@@ -4712,6 +4997,7 @@ export class PtyManager {async sessionAgeSeconds(persistKey: string): Promise<number | null> {const target = sessionName(persistKey)const live = this.liveSessionForPersistKey(persistKey)+ if (this.isZellij(persistKey, live)) return nullconst sshRemote = live?.sshRemoteif (sshRemote) {const ssh = findSsh()@@ -4758,6 +5044,9 @@ export class PtyManager {*/async terminateForeground(persistKey: string, expectedAgentId?: string): Promise<boolean> {if (typeof persistKey !== 'string' || !persistKey || persistKey.length > REF_MAX_LEN) return false+ // Refused on Zellij (ZELLIJ_BACKEND_GAPS): a signal aimed at a process group read off `ps`+ // without the pane-owner proof the tmux leg has would be a guess at which process to kill.+ if (this.isZellij(persistKey, this.liveSessionForPersistKey(persistKey))) return false// Identity gate: prove the expected harness owns the foreground group before signalling it.// `paneOwner` reads the full argv (local or over the project's ControlMaster) and is null on// any uncertainty, which `isAgentPane` maps to `unknown` → refuse.@@ -4849,6 +5138,9 @@ export class PtyManager {async paneOwner(persistKey: string): Promise<PaneOwner | null> {const target = sessionName(persistKey)const live = this.liveSessionForPersistKey(persistKey)+ // Agent messaging is refused into a Zellij pane (ZELLIJ_BACKEND_GAPS): null = "could not+ // prove the owner", which every messaging gate already reads as a refusal.+ if (this.isZellij(persistKey, live)) return nullif (live?.nativeWindowsPane) return live.nativeWindowsPane.owner()const sshRemote = live?.sshRemotetry {@@ -4925,6 +5217,7 @@ export class PtyManager {async sendEnvelope(persistKey: string, envelope: string, expected?: PaneOwner): Promise<boolean> {if (envelope.length === 0) return falseconst live = this.liveSessionForPersistKey(persistKey)+ if (this.isZellij(persistKey, live)) return falseif (live?.nativeWindowsPane) return live.nativeWindowsPane.sendEnvelope(envelope, expected)const target = sessionName(persistKey)if (this.sessionHostOwns(persistKey, live)) {@@ -4962,6 +5255,7 @@ export class PtyManager {async envelopePasteReady(persistKey: string): Promise<boolean> {const live = this.liveSessionForPersistKey(persistKey)+ if (this.isZellij(persistKey, live)) return falseif (live?.nativeWindowsPane) return live.nativeWindowsPane.pasteAware()if (this.sessionHostOwns(persistKey, live)) return sessionHostMessagePasteReady(sessionName(persistKey))// Existing tmux path frames in paste-buffer -p.@@ -5000,8 +5294,22 @@ export class PtyManager {const hostSessions = this.hostBackendEligible()? sessionHostListSessions().catch(() => [] as string[]): Promise.resolve([] as string[])- const [tmux, host] = await Promise.all([tmuxSessions, hostSessions])- return [...new Set([...tmux, ...host])]+ const zellijRun = this.getSettings().tmuxEnabled ? this.zellijRun() : null+ const zellijSessions = zellijRun+ ? zellijRun(['list-sessions', '-n'])+ .then(({ stdout }) => {+ const listing = parseZellijSessionList(stdout)+ if (!listing.ok) return [] as string[]+ const ours = [...listing.live].filter((name) => isSessionName(name))+ // Remembered so the relay host's attach for one of these joins the Zellij session+ // instead of creating a tmux one beside it.+ for (const name of ours) this.zellijKeys.add(name.slice('nt-'.length))+ return ours+ })+ .catch(() => [] as string[])+ : Promise.resolve([] as string[])+ const [tmux, host, zellij] = await Promise.all([tmuxSessions, hostSessions, zellijSessions])+ return [...new Set([...tmux, ...host, ...zellij])]}/**@@ -5174,8 +5482,9 @@ export class PtyManager {// let the renderer apply the new profile. Legacy fire-and-forget recycle keeps its historical// cleanup-first behavior through endSession's default parameter.const sourceSessionHost = !!live?.sessionHost || confirmedSessionHost+ const sourceZellij = !!live?.zellij || (!live && this.zellijKeys.has(persistKey))const sourceTmux =- confirmedTmux || (!!live?.tmuxBacked && !live.sessionHost && !live.sshRemote)+ confirmedTmux || (!!live?.tmuxBacked && !live.sessionHost && !live.zellij && !live.sshRemote)// These flags describe independent old backends, not one preferred winner. In particular, a// discovered hidden host/tmux generation must not make an indexed direct PTY stop being plain:// dropping that local mapping without taskkill/onExit proof leaks the silent process.@@ -5280,6 +5589,18 @@ export class PtyManager {}}+ // Zellij, independently, with the same proof rule as tmux: the kill's acknowledgement or a+ // re-probe that no longer finds a LIVE session. `unknown` is not proof and abandons.+ if (sourceZellij) {+ const run = this.zellijRun()+ if (!run) abandonConfirmedRecycle(new Error('Zellij is not available to end this session.'))+ else if (!(await zellijKillSession(run, hostName))) {+ const state = await zellijSessionState(run, hostName)+ if (state === 'live' || state === 'unknown')+ abandonConfirmedRecycle(new Error('Could not end the Zellij session before restarting it.'))+ }+ }+// Plain LAST and independently from hidden persistent backends. A natural exact exit recorded// during the earlier probes is already proof, so never taskkill its stale pid. On Windows a// successful process-tree termination is stronger than node-pty's sometimes-missed callback;@@ -5654,7 +5975,17 @@ export class PtyManager {}}}+ // Zellij too, by exact name, whenever a binary exists — not only for a node this process+ // knows to be Zellij-backed: a delete after an app restart, for a node never mounted since,+ // holds no live session and no record, and skipping it would leave the session running with+ // nothing on screen. `kill-session` matches exactly and answers "no such session" for a tmux+ // node, so the extra call ends nothing it should not. Remote nodes never have one.+ if (remoteEnd.kind === 'none' && this.getSettings().tmuxEnabled) {+ const run = this.zellijRun()+ if (run) await zellijKillSession(run, sessionName(persistKey))+ }}+ this.zellijKeys.delete(persistKey)for (const listener of this.sessionEndedListeners) {try {listener(persistKey)diff --git a/src/core/pty-zellij.realzellij.test.ts b/src/core/pty-zellij.realzellij.test.tsnew file mode 100644index 000000000..82062f6b7--- /dev/null+++ b/src/core/pty-zellij.realzellij.test.ts@@ -0,0 +1,143 @@+// PtyManager's Zellij wiring, against a REAL Zellij binary (skipped when none is found — see+// zellij-test-env.ts). node-pty is mocked (suite convention: it is built for Electron's ABI), and+// the mock RUNS the painter argv the manager built — headless, `--create` → `--create-background`+// — with the env and cwd the manager chose. So what reaches the session is exactly what the+// painter would have given it, and every later op (exists, paste, capture, pane command, kill) is+// the manager's own code talking to a real Zellij.+import fs from 'fs'+import { execFileSync } from 'child_process'+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'+import { DEFAULT_SETTINGS, type Settings } from '../shared/types'+import { sessionName } from './tmux-naming'+import { zellijSessionState } from './zellij-backend'+import { TEST_ZELLIJ, disposeZellijSandbox, eventually, makeZellijSandbox, type ZellijSandbox } from './zellij-test-env'+import { testTmpDir } from './test-tmp'++const h = vi.hoisted(() => ({+ spawns: [] as Array<{ file: string; args: string[]; env: Record<string, string>; cwd: string }>,+ zellij: null as string | null+}))++vi.mock('./session-host-backend', async () =>+ (await import('./__fixtures__/no-session-host')).noSessionHost()+)+vi.mock('./pty-devices', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./pty-devices')>()),+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })+}))+vi.mock('node-pty', () => ({+ spawn: (file: string, args: string[], opts: { env: Record<string, string>; cwd: string }) => {+ h.spawns.push({ file, args, env: opts.env, cwd: opts.cwd })+ if (file === h.zellij) {+ // `--create-background` REFUSES a session that exists, where the painter's `--create` would+ // simply attach — so a failure here on a warm reattach is the harness, not the code. Every+ // test asserts the session state it expects afterwards, so a real create failure still fails.+ try {+ execFileSync(+ file,+ args.map((a) => (a === '--create' ? '--create-background' : a)),+ { env: opts.env, cwd: opts.cwd, timeout: 10_000, stdio: 'ignore' }+ )+ } catch {+ /* see above */+ }+ }+ return {+ onData: () => ({ dispose() {} }),+ onExit: () => ({ dispose() {} }),+ write: () => {},+ resize: () => {},+ pause: () => {},+ resume: () => {},+ kill: () => {},+ pid: 4321+ }+ }+}))++describe.skipIf(!TEST_ZELLIJ)('PtyManager on the Zellij backend (real binary)', () => {+ let sb: ZellijSandbox+ let settings: Settings+ const saved: Record<string, string | undefined> = {}+ const node = `zw-${Date.now().toString(36)}`++ beforeAll(() => {+ h.zellij = TEST_ZELLIJ+ sb = makeZellijSandbox()+ // The manager builds its env from process.env; point it at the sandbox for this file.+ for (const k of ['ZELLIJ_SOCKET_DIR', 'XDG_RUNTIME_DIR', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME', 'COLORTERM']) {+ saved[k] = process.env[k]+ if (k === 'COLORTERM') delete process.env[k]+ else process.env[k] = sb.env[k]+ }+ initPlatform(fakePlatform({ userDataDir: testTmpDir('zw-ud-') }))+ settings = { ...DEFAULT_SETTINGS, sessionBackend: 'zellij', defaultShell: '/bin/sh' }+ })+ afterAll(async () => {+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k]+ else process.env[k] = v+ }+ resetPlatformForTests()+ if (sb) await disposeZellijSandbox(sb)+ })++ async function manager(): Promise<import('./pty-manager').PtyManager> {+ const { PtyManager } = await import('./pty-manager')+ const m = new PtyManager({ zellijBin: TEST_ZELLIJ })+ m.init(() => settings)+ return m+ }++ it('a new local terminal is created in Zellij, cold, with its env and nothing on argv', async () => {+ const m = await manager()+ const r = await m.createHeadless({ cols: 100, rows: 30, persistKey: node, cwd: sb.root })+ expect(r.fresh).toBe(true)+ expect(r.persistent).toBe(true)+ const spawn = h.spawns.at(-1)!+ expect(spawn.file).toBe(TEST_ZELLIJ)+ expect(spawn.args).toEqual(expect.arrayContaining(['attach', '--create', '--close-on-exit', sessionName(node)]))+ expect(spawn.args).not.toContain('-e')+ expect(spawn.env.ZELLIJ).toBeUndefined()+ expect(fs.existsSync(spawn.args[spawn.args.indexOf('--config') + 1])).toBe(true)+ expect(await eventually(async () => (await zellijSessionState(sb.run, sessionName(node))) === 'live')).toBe(true)++ // The manager's own env (COLORTERM is set by spawnSession, not inherited — deleted above).+ expect(await m.sendText(node, 'echo "CT=$COLORTERM PWD=$PWD"')).toBe(true)+ expect(+ await eventually(async () => (await m.captureSession(node)).includes(`CT=truecolor PWD=${sb.root}`))+ ).toBe(true)+ expect(await eventually(async () => (await m.paneCommand(node)) === 'sh')).toBe(true)+ // The co-attach seed is the visible screen, colour kept.+ expect(await m.captureSnapshot(node)).toContain('CT=truecolor')+ // Degrades named in ZELLIJ_BACKEND_GAPS answer "unknown/refused", never a tmux guess.+ expect(await m.paneOwner(node)).toBeNull()+ expect(await m.paneCwd(node)).toBeNull()+ expect(await m.terminateForeground(node)).toBe(false)+ }, 30_000)++ it('after a restart the node reattaches its Zellij session warm — even with the setting back on tmux', async () => {+ settings = { ...settings, sessionBackend: 'tmux' }+ const m = await manager() // a fresh manager = a fresh app run: no memory of the node+ expect(await m.sessionExists(node)).toBe(true)+ const r = await m.createHeadless({ cols: 100, rows: 30, persistKey: node, cwd: sb.root })+ expect(r.fresh).toBe(false)+ expect(h.spawns.at(-1)!.file).toBe(TEST_ZELLIJ)+ }, 30_000)++ it('with tmux selected and no Zellij session, the default path is untouched', async () => {+ const m = await manager()+ const other = `${node}-t`+ await m.createHeadless({ cols: 80, rows: 24, persistKey: other, cwd: sb.root })+ expect(h.spawns.at(-1)!.file).not.toBe(TEST_ZELLIJ)+ expect(await zellijSessionState(sb.run, sessionName(other))).toBe('absent')+ }, 30_000)++ it('deleting the node ends its Zellij session, even from a manager that never held it', async () => {+ const m = await manager()+ await m.destroySession(null, node)+ expect(await eventually(async () => (await zellijSessionState(sb.run, sessionName(node))) === 'absent')).toBe(true)+ }, 30_000)+})diff --git a/src/core/zellij-backend.realzellij.test.ts b/src/core/zellij-backend.realzellij.test.tsnew file mode 100644index 000000000..72f92f855--- /dev/null+++ b/src/core/zellij-backend.realzellij.test.ts@@ -0,0 +1,102 @@+// The Zellij backend against a REAL Zellij binary (skipped when none is found — see+// zellij-test-env.ts). Same discipline as the *.realtmux suites: the claims in zellij-backend.ts are+// about another program's behaviour, so they are proven on that program, not on a fake.+//+// Sessions are created headless (`attach --create-background`) with the SAME config and layout+// the painter uses; the painter's `--create` differs only in attaching a client, which vitest has no+// pty for (node-pty is built for Electron's ABI here).+import fs from 'fs'+import path from 'path'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import {+ ZELLIJ_LAYOUT,+ zellijCapture,+ zellijConf,+ zellijForegroundCommand,+ zellijKillSession,+ zellijSendText,+ zellijSessionState,+ zellijWriteChars+} from './zellij-backend'+import { TEST_ZELLIJ, disposeZellijSandbox, eventually, makeZellijSandbox, type ZellijSandbox } from './zellij-test-env'+import { execFile } from 'child_process'+import { promisify } from 'util'++const exec = promisify(execFile)++describe.skipIf(!TEST_ZELLIJ)('Zellij backend against the real binary', () => {+ let sb: ZellijSandbox+ let conf: string+ const created: string[] = []++ beforeAll(() => {+ sb = makeZellijSandbox()+ conf = path.join(sb.root, 'zellij.kdl')+ fs.writeFileSync(conf, zellijConf())+ })+ afterAll(async () => {+ if (sb) await disposeZellijSandbox(sb)+ })++ async function create(name: string, extraEnv: Record<string, string> = {}): Promise<void> {+ created.push(name)+ await exec(+ TEST_ZELLIJ as string,+ ['--config', conf, '--layout-string', ZELLIJ_LAYOUT, 'attach', '--create-background', '--close-on-exit', name, '--', '/bin/sh'],+ { env: { ...sb.env, ...extraEnv }, cwd: sb.root, timeout: 10_000 }+ )+ expect(await eventually(async () => (await zellijSessionState(sb.run, name)) === 'live')).toBe(true)+ }+ const screen = (name: string): Promise<string> => zellijCapture(sb.run, name, { full: true })++ it('the creating client’s environment IS the session’s — nothing rides an argv', async () => {+ await create('nt-env1', { NT_PROBE_SECRET: 'from-client-env' })+ expect(await zellijWriteChars(sb.run, 'nt-env1', 'echo "V=$NT_PROBE_SECRET"\r')).toBe(true)+ expect(await eventually(async () => (await screen('nt-env1')).includes('V=from-client-env'))).toBe(true)+ })++ it('existence is exact-name and tri-state; kill ends it', async () => {+ await create('nt-ex1')+ expect(await zellijSessionState(sb.run, 'nt-ex')).toBe('absent')+ expect(await zellijSessionState(sb.run, 'nt-ex1')).toBe('live')+ expect(await zellijKillSession(sb.run, 'nt-ex')).toBe(false)+ expect(await zellijSessionState(sb.run, 'nt-ex1')).toBe('live')+ expect(await zellijKillSession(sb.run, 'nt-ex1')).toBe(true)+ expect(await eventually(async () => (await zellijSessionState(sb.run, 'nt-ex1')) === 'absent')).toBe(true)+ })++ it('paste honours the app’s bracketed-paste request — the paste-buffer -p contract', async () => {+ await create('nt-paste1')+ await zellijWriteChars(sb.run, 'nt-paste1', 'stty -echo; cat -v\r')+ expect(await zellijSendText(sb.run, 'nt-paste1', 'U1\nU2', true)).toBe(true)+ expect(await eventually(async () => /U1\n\s*U2/.test(await screen('nt-paste1')))).toBe(true)+ expect(await screen('nt-paste1')).not.toContain('^[[200~U1')+ await zellijWriteChars(sb.run, 'nt-paste1', '\u0004')+ await zellijWriteChars(sb.run, 'nt-paste1', "printf '\\033[?2004h'; cat -v\r")+ await new Promise((r) => setTimeout(r, 300))+ expect(await zellijSendText(sb.run, 'nt-paste1', 'F1\nF2', true)).toBe(true)+ expect(await eventually(async () => (await screen('nt-paste1')).includes('^[[200~F1'))).toBe(true)+ })++ it('the foreground command is read off the process table', async () => {+ await create('nt-fg1')+ await zellijWriteChars(sb.run, 'nt-fg1', 'sleep 30\r')+ const fg = async (): Promise<string | null> => {+ const { stdout } = await exec('ps', ['-A', '-o', 'pid=,ppid=,tpgid=,comm=,args='], { encoding: 'utf-8' })+ return zellijForegroundCommand(stdout, 'nt-fg1')+ }+ expect(await eventually(async () => (await fg()) === 'sleep')).toBe(true)+ await zellijWriteChars(sb.run, 'nt-fg1', '\u0003')+ expect(await eventually(async () => (await fg()) === 'sh')).toBe(true)+ })++ it('a shell that exits with no client attached never reads as a live session', async () => {+ await create('nt-z1')+ await zellijWriteChars(sb.run, 'nt-z1', 'exit\r')+ expect(await eventually(async () => (await zellijSessionState(sb.run, 'nt-z1')) !== 'live')).toBe(true)+ })++ afterAll(async () => {+ for (const name of created) await zellijKillSession(sb.run, name)+ })+})diff --git a/src/core/zellij-backend.test.ts b/src/core/zellij-backend.test.tsnew file mode 100644index 000000000..8f9b10065--- /dev/null+++ b/src/core/zellij-backend.test.ts@@ -0,0 +1,236 @@+// Pure halves of the Zellij backend (zellij-backend.ts). The real-binary half is+// zellij-backend.realzellij.test.ts; these pin the decisions against the exact shapes Zellij 0.45.1+// printed when measured (docs/session-backends.md).+import { describe, it, expect } from 'vitest'+import {+ ZELLIJ_LAYOUT,+ ZELLIJ_PASTE_MAX_BYTES,+ loginShellArgs,+ parseZellijSessionList,+ pickZellijPane,+ tailLines,+ zellijAttachArgs,+ zellijConf,+ zellijForegroundCommand,+ zellijSendText,+ zellijSessionState,+ type ZellijRun+} from './zellij-backend'+import fs from 'fs'+import path from 'path'+import { normalizeSessionBackend, ZELLIJ_BACKEND_GAPS } from '../shared/session-backend'++/** A fake runner answering per first-matching arg, failing like promisified execFile. */+function fakeRun(+ answers: Array<{ when: (args: readonly string[]) => boolean; stdout?: string; fail?: { stdout?: string; stderr?: string } }>+): ZellijRun & { calls: string[][] } {+ const calls: string[][] = []+ const run = (async (args: readonly string[]) => {+ calls.push([...args])+ const a = answers.find((x) => x.when(args))+ if (!a) throw Object.assign(new Error('unexpected call'), { stdout: '', stderr: '' })+ if (a.fail) throw Object.assign(new Error('Command failed'), a.fail)+ return { stdout: a.stdout ?? '', stderr: '' }+ }) as ZellijRun & { calls: string[][] }+ run.calls = calls+ return run+}++const LIVE_PANES = JSON.stringify([+ { id: 0, is_plugin: true, is_focused: false, exited: false },+ { id: 0, is_plugin: false, is_focused: true, exited: false }+])+const ZOMBIE_PANES = JSON.stringify([{ id: 0, is_plugin: true, is_focused: false, exited: false }])+const isList = (a: readonly string[]): boolean => a[0] === 'list-sessions'+const isPanes = (a: readonly string[]): boolean => a.includes('list-panes')++describe('normalizeSessionBackend — unknown is tmux', () => {+ it('reads only the literal zellij as zellij', () => {+ expect(normalizeSessionBackend('zellij')).toBe('zellij')+ for (const v of ['tmux', 'Zellij', 'screen', '', undefined, null, 1, {}]) {+ expect(normalizeSessionBackend(v)).toBe('tmux')+ }+ })+})++describe('parseZellijSessionList', () => {+ it('separates live from serialized EXITED sessions (measured line shapes)', () => {+ const l = parseZellijSessionList(+ 'nt-a3 [Created 3m 59s ago] \nnt-b1 [Created 2s ago] (EXITED - attach to resurrect)\n'+ )+ expect(l.ok).toBe(true)+ if (!l.ok) return+ expect([...l.live]).toEqual(['nt-a3'])+ expect([...l.exited]).toEqual(['nt-b1'])+ })+ it('an unparseable line makes the whole listing unknown — never a silent drop', () => {+ expect(parseZellijSessionList('nt-a3 [Created 1s ago]\n\u001b[32;1mnt-b\u001b[m [Created').ok).toBe(false)+ })+})++describe('pickZellijPane', () => {+ it('targets the focused live terminal pane and never the hidden plugin pane', () => {+ expect(pickZellijPane(LIVE_PANES)).toBe('terminal_0')+ expect(+ pickZellijPane(+ JSON.stringify([+ { id: 3, is_plugin: false, is_focused: false, exited: false },+ { id: 1, is_plugin: false, is_focused: false, exited: false }+ ])+ )+ ).toBe('terminal_1')+ })+ it('a session with no live terminal pane (a zombie) and garbage both answer null', () => {+ expect(pickZellijPane(ZOMBIE_PANES)).toBeNull()+ expect(pickZellijPane(JSON.stringify([{ id: 0, is_plugin: false, exited: true }]))).toBeNull()+ expect(pickZellijPane('not json')).toBeNull()+ expect(pickZellijPane('{}')).toBeNull()+ })+})++describe('zellijSessionState — only an answer is evidence of absence', () => {+ it('"No active zellij sessions found" with exit 1 is ABSENT', async () => {+ const run = fakeRun([{ when: isList, fail: { stdout: 'No active zellij sessions found.\n' } }])+ expect(await zellijSessionState(run, 'nt-x')).toBe('absent')+ })+ it('any other failure is UNKNOWN (the caller folds it to "exists")', async () => {+ const run = fakeRun([{ when: isList, fail: { stderr: 'spawn EAGAIN' } }])+ expect(await zellijSessionState(run, 'nt-x')).toBe('unknown')+ })+ it('listed with a live terminal pane is LIVE; exact names only', async () => {+ const run = fakeRun([+ { when: isList, stdout: 'nt-x1 [Created 1s ago]\nnt-x [Created 2s ago]\n' },+ { when: isPanes, stdout: LIVE_PANES }+ ])+ expect(await zellijSessionState(run, 'nt-x')).toBe('live')+ const prefixOnly = fakeRun([{ when: isList, stdout: 'nt-x1 [Created 1s ago]\n' }])+ expect(await zellijSessionState(prefixOnly, 'nt-x')).toBe('absent')+ })+ it('listed with no terminal pane is a ZOMBIE (the shell exited while detached)', async () => {+ const run = fakeRun([+ { when: isList, stdout: 'nt-x [Created 2s ago]\n' },+ { when: isPanes, stdout: ZOMBIE_PANES }+ ])+ expect(await zellijSessionState(run, 'nt-x')).toBe('zombie')+ })+ it('a session whose terminal pane is not listed YET is live, not a zombie (the caller kills zombies)', async () => {+ let reads = 0+ const run = (async (args: readonly string[]) => {+ if (isList(args)) return { stdout: 'nt-x [Created 0s ago]\n', stderr: '' }+ reads+++ return { stdout: reads < 3 ? ZOMBIE_PANES : LIVE_PANES, stderr: '' }+ }) as ZellijRun+ expect(await zellijSessionState(run, 'nt-x')).toBe('live')+ expect(reads).toBe(3)+ })+ it('a serialized EXITED entry is not a session to attach to', async () => {+ const run = fakeRun([{ when: isList, stdout: 'nt-x [Created 2s ago] (EXITED - attach to resurrect)\n' }])+ expect(await zellijSessionState(run, 'nt-x')).toBe('absent')+ })+})++describe('zellijSendText — one paste, then Enter, never a split', () => {+ const live = (): ReturnType<typeof fakeRun> =>+ fakeRun([+ { when: isPanes, stdout: LIVE_PANES },+ { when: (a) => a.includes('paste') },+ { when: (a) => a.includes('write') }+ ])+ it('pastes to the resolved pane and sends Enter as a SECOND call', async () => {+ const run = live()+ expect(await zellijSendText(run, 'nt-x', 'a\nb', true)).toBe(true)+ expect(run.calls.slice(1)).toEqual([+ ['--session', 'nt-x', 'action', 'paste', '--pane-id', 'terminal_0', 'a\nb'],+ ['--session', 'nt-x', 'action', 'write', '--pane-id', 'terminal_0', '13']+ ])+ })+ it('refuses a paste over the argv ceiling instead of splitting it', async () => {+ const run = live()+ expect(await zellijSendText(run, 'nt-x', 'x'.repeat(ZELLIJ_PASTE_MAX_BYTES + 1), true)).toBe(false)+ expect(run.calls).toEqual([])+ })+ it('a paste that landed with an Enter that did not is pasted-not-submitted (no retry)', async () => {+ const run = fakeRun([+ { when: isPanes, stdout: LIVE_PANES },+ { when: (a) => a.includes('paste') },+ { when: (a) => a.includes('write'), fail: { stderr: 'boom' } }+ ])+ expect(await zellijSendText(run, 'nt-x', 'hi', true)).toBe('pasted-not-submitted')+ expect(run.calls.filter((c) => c.includes('paste'))).toHaveLength(1)+ })+ it('no live pane ⇒ nothing is delivered', async () => {+ const run = fakeRun([{ when: isPanes, stdout: ZOMBIE_PANES }])+ expect(await zellijSendText(run, 'nt-x', 'hi', true)).toBe(false)+ })+})++describe('zellijForegroundCommand — the pane_current_command twin, from ps', () => {+ const PS = [+ ' 3034805 1 -1 zellij /opt/bin/zellij --server /run/zellij/contract_version_1/nt-e1',+ ' 3034912 1 -1 zellij /opt/bin/zellij --server /run/zellij/contract_version_1/nt-e12',+ ' 3034917 3034805 3035808 bash -bash',+ ' 3035808 3034917 3035808 sleep sleep 20',+ ' 3040000 3034912 3040000 -zsh -zsh'+ ].join('\n')+ it('server → shell → the shell tty foreground group (measured chain)', () => {+ expect(zellijForegroundCommand(PS, 'nt-e1')).toBe('sleep')+ })+ it('exact session name, and a login shell reads without its dash', () => {+ expect(zellijForegroundCommand(PS, 'nt-e12')).toBe('zsh')+ expect(zellijForegroundCommand(PS, 'nt-e')).toBeNull()+ })+ it('a session with two pane shells is ambiguous ⇒ null (refuse, never guess)', () => {+ const two = `${PS}\n 3050000 3034805 3050000 bash bash`+ expect(zellijForegroundCommand(two, 'nt-e1')).toBeNull()+ })+ it('the CLIENT command line (no --server) is never mistaken for the server', () => {+ const client = ' 99 1 99 zellij /opt/bin/zellij --config c.kdl attach --create nt-e1'+ expect(zellijForegroundCommand(client, 'nt-e1')).toBeNull()+ })+})++describe('argv and config builders', () => {+ it('create-or-attach carries no environment on argv and closes on exit', () => {+ const args = zellijAttachArgs('/u/zellij.kdl', 'nt-n1', '/bin/zsh', ['-l'])+ expect(args).toEqual([+ '--config',+ '/u/zellij.kdl',+ '--layout-string',+ ZELLIJ_LAYOUT,+ 'attach',+ '--create',+ '--close-on-exit',+ 'nt-n1',+ '--',+ '/bin/zsh',+ '-l'+ ])+ expect(args.some((a) => a === '-e' || /^[A-Z_]+=/.test(a))).toBe(false)+ })+ it('the config locks keys through, keeps an unlock that is not Ctrl-g, and never resurrects', () => {+ const c = zellijConf()+ expect(c).toContain('default_mode "locked"')+ expect(c).toContain('unbind "Ctrl g"')+ expect(c).toContain('bind "Ctrl Alt g"')+ expect(c).toContain('session_serialization false')+ expect(c).toContain('pane_frames false')+ })+ it('login flag only for shells known to take it', () => {+ expect(loginShellArgs('/bin/zsh')).toEqual(['-l'])+ expect(loginShellArgs('/usr/bin/bash')).toEqual(['-l'])+ expect(loginShellArgs('/usr/local/bin/nu')).toEqual([])+ })+ it('tailLines keeps the last n lines and the trailing newline', () => {+ expect(tailLines('a\nb\nc\n', 2)).toBe('b\nc\n')+ expect(tailLines('a\nb', 5)).toBe('a\nb')+ })+})++describe('the gap list the Settings row prints is the list the docs state', () => {+ it('every ZELLIJ_BACKEND_GAPS line appears verbatim in docs/session-backends.md', () => {+ const doc = fs+ .readFileSync(path.join(__dirname, '../../docs/session-backends.md'), 'utf8')+ .replace(/\r\n/g, '\n')+ for (const gap of ZELLIJ_BACKEND_GAPS) expect(doc).toContain(`- ${gap}`)+ })+})diff --git a/src/core/zellij-backend.ts b/src/core/zellij-backend.tsnew file mode 100644index 000000000..e9f323a14--- /dev/null+++ b/src/core/zellij-backend.ts@@ -0,0 +1,398 @@+/**+ * 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'++/** `(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). An unparseable line makes+ * the whole listing unknown rather than silently dropping a session we might be asked about.+ */+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 = /^(\S+) \[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++const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))++/** 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 {+ 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')+}diff --git a/src/core/zellij-test-env.ts b/src/core/zellij-test-env.tsnew file mode 100644index 000000000..ac997b6f6--- /dev/null+++ b/src/core/zellij-test-env.ts@@ -0,0 +1,81 @@+// TEST-ONLY — a sandboxed Zellij for the real-binary suites (`*.realzellij.test.ts`).+//+// Zellij is not a dependency and CI does not install it, so those suites skip unless a binary is+// found: `NODETERM_TEST_ZELLIJ` (an absolute path — e.g. a release binary unpacked somewhere+// scratch) or `zellij` on PATH. Everything the binary touches is redirected into one directory the+// suite removes: HOME, the XDG dirs, and `ZELLIJ_SOCKET_DIR`, so a developer's own sessions,+// config and resurrection cache are never read or written. Zellij also writes its log under the+// process temp dir (`zellij-<uid>/`); `disposeZellijSandbox` removes that too, or the run's temp+// hygiene guard reports it.+//+// Lives in src/core (like tmux-test-socket.ts) because the suites import it.+import fs from 'fs'+import os from 'os'+import path from 'path'+import { execFile } from 'child_process'+import { promisify } from 'util'+import { findInPathString } from './exec-path'+import { testTmpDir } from './test-tmp'+import type { ZellijRun } from './zellij-backend'++const run = promisify(execFile)++export const TEST_ZELLIJ: string | null =+ process.platform === 'win32'+ ? null+ : process.env.NODETERM_TEST_ZELLIJ || findInPathString('zellij', process.env.PATH) || null++export interface ZellijSandbox {+ root: string+ env: Record<string, string>+ run: ZellijRun+}++export function makeZellijSandbox(): ZellijSandbox {+ const root = testTmpDir('zj-')+ const dirs = {+ HOME: path.join(root, 'h'),+ XDG_CONFIG_HOME: path.join(root, 'c'),+ XDG_DATA_HOME: path.join(root, 'd'),+ XDG_CACHE_HOME: path.join(root, 'k'),+ XDG_RUNTIME_DIR: path.join(root, 'r'),+ ZELLIJ_SOCKET_DIR: path.join(root, 's')+ }+ for (const d of Object.values(dirs)) fs.mkdirSync(d, { recursive: true })+ const env: Record<string, string> = { ...(process.env as Record<string, string>), ...dirs, SHELL: '/bin/sh' }+ for (const k of ['ZELLIJ', 'ZELLIJ_SESSION_NAME', 'ZELLIJ_PANE_ID', 'TMUX', 'TMUX_PANE']) delete env[k]+ const bound: ZellijRun = async (args) => {+ const { stdout, stderr } = await run(TEST_ZELLIJ as string, args as string[], {+ env,+ encoding: 'utf-8',+ timeout: 10_000+ })+ return { stdout, stderr }+ }+ return { root, env, run: bound }+}++/** Kill every session in the sandbox and remove Zellij's temp-dir log. Never throws. */+export async function disposeZellijSandbox(sb: ZellijSandbox): Promise<void> {+ try {+ await sb.run(['kill-all-sessions', '--yes'])+ } catch {+ // none left — the normal case+ }+ const uid = process.getuid?.() ?? 0+ try {+ fs.rmSync(path.join(os.tmpdir(), `zellij-${uid}`), { recursive: true, force: true })+ } catch {+ // best effort+ }+}++/** Poll `probe` until it returns true (Zellij applies actions asynchronously). */+export async function eventually(probe: () => Promise<boolean>, ms = 5_000): Promise<boolean> {+ const deadline = Date.now() + ms+ while (Date.now() < deadline) {+ if (await probe()) return true+ await new Promise((r) => setTimeout(r, 100))+ }+ return probe()+}diff --git a/src/renderer/components/sessionBackendNote.test.ts b/src/renderer/components/sessionBackendNote.test.tsnew file mode 100644index 000000000..44afb9a23--- /dev/null+++ b/src/renderer/components/sessionBackendNote.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it, vi } from 'vitest'+import type { TmuxStatus } from '@shared/types'+vi.mock('../session/localSession', () => ({ localSession: { api: { pty: {} } } }))+vi.mock('../state/settings', () => ({ useSettings: () => undefined }))+import { persistenceDescription, sessionBackendNote } from './usePersistenceStatus'++describe('Session backend row — the sentence says what a NEW terminal gets', () => {+ it('selected but not installed must not read as applied', () => {+ expect(sessionBackendNote({ selected: true, available: false })).toMatch(/not found.*use tmux/)+ })+ it('selected and installed names Zellij and how to attach', () => {+ expect(sessionBackendNote({ selected: true, available: true })).toMatch(/Zellij session.*zellij attach nt-/)+ })+ it('tmux selected says tmux, and whether Zellij could be chosen', () => {+ expect(sessionBackendNote({ selected: false, available: true })).toMatch(/open in tmux\. Zellij is also available/)+ expect(sessionBackendNote({ selected: false, available: false })).toMatch(/Install Zellij/)+ })+ it('persistence names Zellij when the core reports it as the backend (no tmux-install nag)', () => {+ const status: TmuxStatus = {+ available: false,+ platform: 'darwin',+ installCommand: 'brew install tmux',+ installLabel: null,+ persistence: { enabled: true, backend: 'zellij' },+ zellij: { available: true, selected: true }+ }+ expect(persistenceDescription(status)).toMatch(/^Zellij is available/)+ })+})diff --git a/src/renderer/components/settings/sections/TmuxSection.tsx b/src/renderer/components/settings/sections/TmuxSection.tsxindex 2c5569149..5e361e538 100644--- a/src/renderer/components/settings/sections/TmuxSection.tsx+++ b/src/renderer/components/settings/sections/TmuxSection.tsx@@ -1,10 +1,16 @@-import { persistenceDescription, usePersistenceStatus } from '../../usePersistenceStatus'+import {+ persistenceDescription,+ sessionBackendNote,+ usePersistenceStatus+} from '../../usePersistenceStatus'import { useSettings } from '../../../state/settings'import { SettingsSection } from '../SettingsSection'import { SearchableRow } from '../SearchableRow'import { FieldRow } from '../FieldRow'import { Switch } from '@renderer/ui/Switch'import { NumberField } from '@renderer/ui/NumberField'+import { Select } from '@renderer/ui/Select'+import { normalizeSessionBackend, ZELLIJ_BACKEND_GAPS } from '@shared/session-backend'import {LEAD_PANE_WIDTH_DEFAULT,LEAD_PANE_WIDTH_MAX,@@ -22,6 +28,10 @@ const ROWS = {title: 'Persistent sessions',keywords: ['tmux', 'persistent', 'session', 'continuity', 'protection', 'host']},+ backend: {+ title: 'Session backend',+ keywords: ['tmux', 'zellij', 'backend', 'multiplexer', 'session', 'persistent']+ },scrollback: { title: 'Scrollback lines', keywords: ['tmux', 'scrollback', 'history', 'lines'] },leadPane: {title: 'Keep lead pane wide (agent teams)',@@ -67,6 +77,29 @@ export function TmuxSection({ isActive }: { isActive: boolean }): React.JSX.Elem}/></SearchableRow>+ {status?.zellij ? (+ <SearchableRow {...ROWS.backend}>+ <FieldRow+ label="Session backend"+ description={sessionBackendNote(status.zellij)}+ note={+ normalizeSessionBackend(settings.sessionBackend) === 'zellij'+ ? `Not available with Zellij: ${ZELLIJ_BACKEND_GAPS.join(' ')}`+ : undefined+ }+ control={+ <Select+ aria-label="Session backend"+ value={normalizeSessionBackend(settings.sessionBackend)}+ onChange={(e) => update({ sessionBackend: normalizeSessionBackend(e.target.value) })}+ >+ <option value="tmux">tmux</option>+ <option value="zellij">Zellij</option>+ </Select>+ }+ />+ </SearchableRow>+ ) : null}<SearchableRow {...ROWS.scrollback}><FieldRowlabel="Scrollback lines"diff --git a/src/renderer/components/usePersistenceStatus.ts b/src/renderer/components/usePersistenceStatus.tsindex be3874cf4..df719e87d 100644--- a/src/renderer/components/usePersistenceStatus.ts+++ b/src/renderer/components/usePersistenceStatus.ts@@ -36,5 +36,21 @@ export function persistenceDescription(status: TmuxStatus | null | undefined): sif (!p) return 'Session protection could not be checked. Continuity is not confirmed.'if (!p.enabled) return 'Session protection is off for new local terminals. They will not survive an app or server restart.'if (!p.backend) return 'No session protection backend was found. New local terminals will not survive an app or server restart.'- return `${p.backend === 'tmux' ? 'tmux' : 'Session host'} is available for new local terminals. Existing plain-shell terminals are not upgraded; runtime startup can still fail.`+ const name = p.backend === 'tmux' ? 'tmux' : p.backend === 'zellij' ? 'Zellij' : 'Session host'+ return `${name} is available for new local terminals. Existing plain-shell terminals are not upgraded; runtime startup can still fail.`+}++/**+ * The Session backend row's sentence. The setting only decides where a NEW local terminal is+ * created, so each branch says what actually happens next — including the fallback when Zellij is+ * selected but no binary was found, which must not read as applied.+ */+export function sessionBackendNote(z: { available: boolean; selected: boolean }): string {+ if (z.selected && !z.available)+ return 'Zellij is selected but was not found on this machine — new local terminals use tmux until it is installed.'+ if (z.selected)+ return 'New local terminals open in a Zellij session (attach from any terminal with `zellij attach nt-<node id>`). Terminals already running keep their current backend.'+ return z.available+ ? 'New local terminals open in tmux. Zellij is also available here. Terminals already running keep their current backend.'+ : 'New local terminals open in tmux. Install Zellij to choose it instead.'}diff --git a/src/shared/session-backend.ts b/src/shared/session-backend.tsnew file mode 100644index 000000000..f49b23def--- /dev/null+++ b/src/shared/session-backend.ts@@ -0,0 +1,37 @@+/**+ * Which multiplexer holds a LOCAL terminal's persistent session on POSIX (issue: Zellij as a+ * session backend). tmux is the default and stays the default; `zellij` is opt-in per machine.+ *+ * settings.json is hand-editable, so every reader goes through `normalizeSessionBackend`: an+ * unknown value — a typo, a future backend this build does not know, a non-string — reads as+ * `tmux`, never as "no persistence". The setting only decides where a NEW session is created: a+ * node whose session already lives in one backend keeps reattaching there (see pty-manager.ts,+ * "the backend follows the session that exists").+ *+ * Windows keeps the session host whatever this says; SSH projects keep the remote tmux.+ */+export type SessionBackend = 'tmux' | 'zellij'++export const SESSION_BACKENDS: readonly SessionBackend[] = ['tmux', 'zellij']++export const DEFAULT_SESSION_BACKEND: SessionBackend = 'tmux'++export function normalizeSessionBackend(value: unknown): SessionBackend {+ return value === 'zellij' ? 'zellij' : 'tmux'+}++/**+ * What a Zellij-backed terminal does NOT get, named so the Settings row can say it out loud.+ * Every entry is a capability whose tmux leg has no Zellij equivalent this build uses; each one+ * degrades to "unknown" / "refused" rather than to a guess (docs/session-backends.md has the+ * measurement behind every line). Kept in @shared so the list the UI prints is the list the+ * docs test pins.+ */+export const ZELLIJ_BACKEND_GAPS: readonly string[] = [+ 'Agent-to-agent messaging and triggers into Zellij sessions are refused (no pane-owner or paste-mode probe).',+ 'Model switch refuses: it cannot stop the foreground process of a Zellij pane.',+ 'The session-memory panel and the idle-session reaper do not see Zellij sessions.',+ 'The stale-folder banner and the live pane folder for file links are unavailable.',+ 'SSH projects and Windows keep tmux / the session host.',+ 'nodeterm mobile’s direct SSH attach only finds tmux sessions.'+]diff --git a/src/shared/types.ts b/src/shared/types.tsindex 2e32a6b2e..b5533e708 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1,6 +1,7 @@import type { TextDeliveryResult } from './text-delivery'import type { IdentitySeedEntry } from './agent-identity-seed'import type { PrWaitHold } from './pr-wait'+import type { SessionBackend } from './session-backend'// Types shared across the main, preload, and renderer processes.import { TABBAR_HEIGHT_PX } from './window-chrome-metrics'@@ -1172,7 +1173,14 @@ export interface TmuxStatus {/** tmux discovery only; retained for older callers and install polling. */available: boolean/** Absent on older peers; null when discovery could not be read. */- persistence?: { enabled: boolean; backend: 'tmux' | 'session-host' | null } | null+ persistence?: { enabled: boolean; backend: 'tmux' | 'zellij' | 'session-host' | null } | null+ /**+ * The optional Zellij backend (@shared/session-backend): whether a `zellij` binary was found and+ * whether this machine's setting selects it for NEW local terminals. Absent on older peers and on+ * Windows (no Zellij backend there). `selected && !available` means new terminals fall back to+ * tmux — the Settings row says so rather than letting the choice look applied.+ */+ zellij?: { available: boolean; selected: boolean }/** One-shot install command for a terminal node; null = no known installer (text-only banner). */installCommand: string | null/** Button caption for installCommand (e.g. "Install Homebrew + tmux" when brew must come first). */@@ -1871,6 +1879,13 @@ export interface Settings {browserMemorySaver: booleanaccent: stringtmuxEnabled: boolean+ /**+ * Which multiplexer creates a NEW local terminal's persistent session on POSIX: `tmux` (default)+ * or `zellij`. Hand-editable, so every reader goes through `normalizeSessionBackend`+ * (@shared/session-backend) — anything unknown reads as tmux. A node whose session already+ * lives in one backend keeps reattaching there; Windows and SSH projects ignore it.+ */+ sessionBackend: SessionBackend/*** Reach a released tmux session with a control-mode (`tmux -C`) client instead of respawning its* terminal — the shadow clients in pty-manager.ts (`shadowAttach`) and the shared background-write@@ -2210,6 +2225,7 @@ export const DEFAULT_SETTINGS: Settings = {browserMemorySaver: true,accent: '#0a84ff',tmuxEnabled: true,+ sessionBackend: 'tmux',ptyShadowClients: true,terminalGpuRendering: 'auto',tmuxScrollback: 50000,