Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(terminal): flag a warm-reattached session whose cwd was deleted, with an explicit restart
eneseb3e520f3eea
diff --git a/src/core/pane-cwd.realtmux.test.ts b/src/core/pane-cwd.realtmux.test.tsnew file mode 100644index 000000000..8b2adf373--- /dev/null+++ b/src/core/pane-cwd.realtmux.test.ts@@ -0,0 +1,116 @@+// THE STALE-CWD SIGNAL, PROVEN AGAINST A REAL TMUX (issue #464).+//+// Unit tests pin what `classifyPaneCwd` does with an answer; whether tmux actually gives that+// answer for a session whose start directory was deleted — and keeps giving it after a same-named+// directory is re-created (a DIFFERENT inode, the whole point of the issue) — is a property of+// tmux and the kernel, so it is measured here on a private socket, exactly like the other+// realtmux suites.+//+// Also proven, because the issue asks it explicitly: a NEW session created after the re-creation+// starts in the re-created directory — the spawn path was never the broken half.+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { execFileSync } from 'child_process'+import fs from 'fs'+import path from 'path'+import { classifyPaneCwd } from './pane-cwd'+import { makeTmuxTmpdir } from './tmux-test-socket'++const SOCKET = `nt-cwd-${process.pid}`++let tmp: string+let tmuxOk = false++function tmux(args: string[], opts?: { cwd?: string }): string {+ return execFileSync('tmux', ['-L', SOCKET, ...args], {+ env: { ...process.env, TMUX_TMPDIR: tmp },+ cwd: opts?.cwd,+ stdio: ['ignore', 'pipe', 'pipe']+ }).toString()+}++/** The exact probe `PtyManager.paneCwdStale` runs: exact-match target, one format. The trailing+ * colon is load-bearing and MEASURED here (tmux 3.4): a bare `=name` target-pane resolves+ * NOTHING silently — exit 0, every format empty — while `=name:` is "exactly this session, its+ * active pane". The first assertion below (`'ok'`, not `'unknown'`) is what pins it. */+function panePath(session: string): string {+ return tmux(['display-message', '-p', '-t', `=${session}:`, '#{pane_current_path}']).replace(+ /\r?\n$/,+ ''+ )+}++const dirExists = (p: string): boolean => {+ try {+ return fs.statSync(p).isDirectory()+ } catch {+ return false+ }+}++beforeAll(() => {+ if (process.platform === 'win32') return // no tmux on Windows — the session host owns that world+ try {+ execFileSync('tmux', ['-V'], { stdio: 'ignore' })+ tmuxOk = true+ } catch {+ return // no tmux on this host — every test below self-skips+ }+ tmp = makeTmuxTmpdir('ntcwd-', SOCKET)+})++afterAll(() => {+ if (!tmuxOk) return+ try {+ tmux(['kill-server'])+ } catch {+ /* already gone */+ }+ fs.rmSync(tmp, { recursive: true, force: true })+})++describe('pane_current_path across delete → recreate (real tmux)', () => {+ it('a deleted-then-recreated start dir stays STALE for the live session, and a healthy one is ok', () => {+ if (!tmuxOk) return+ const dir = path.join(tmp, 'proj')+ fs.mkdirSync(dir)+ // `sleep` rather than an interactive shell: the pane's process-group leader holds the cwd and+ // sits still, so the measurement has no prompt/rc-file noise in it.+ // `-f /dev/null` on the server-starting call: a contributor's ~/.tmux.conf must not join the+ // measurement (the private socket makes this call the one that boots the server).+ tmux(['-f', '/dev/null', 'new-session', '-d', '-s', 'victim', '-c', dir, 'sleep 60'])++ // Healthy: tmux names the directory and it exists.+ expect(classifyPaneCwd(panePath('victim'), dirExists)).toBe('ok')++ // Deleted: the shell keeps the inode; the classifier must call it stale.+ fs.rmSync(dir, { recursive: true, force: true })+ const afterDelete = panePath('victim')+ expect(classifyPaneCwd(afterDelete, dirExists)).toBe('stale')++ // Recreated at the same path — a different inode, so nothing self-heals. This is the exact+ // reported state: the folder EXISTS again, and the verdict must still be stale.+ fs.mkdirSync(dir)+ const afterRecreate = panePath('victim')+ expect(dirExists(dir)).toBe(true)+ expect(classifyPaneCwd(afterRecreate, dirExists)).toBe('stale')+ if (process.platform === 'linux') {+ // The measured Linux signal, pinned so a kernel/tmux change that stops emitting it turns+ // this suite red instead of silently disabling the banner: /proc's readlink names the dead+ // inode with the " (deleted)" suffix, before AND after the same-named mkdir.+ expect(afterDelete.endsWith(' (deleted)')).toBe(true)+ expect(afterRecreate.endsWith(' (deleted)')).toBe(true)+ }+ })++ it('a NEW session created after the recreation starts in the recreated directory', () => {+ if (!tmuxOk) return+ const dir = path.join(tmp, 'proj2')+ fs.mkdirSync(dir)+ fs.rmSync(dir, { recursive: true, force: true })+ fs.mkdirSync(dir)+ tmux(['new-session', '-d', '-s', 'fresh', '-c', dir, 'sleep 60'])+ const reported = panePath('fresh')+ expect(classifyPaneCwd(reported, dirExists)).toBe('ok')+ expect(fs.realpathSync(reported)).toBe(fs.realpathSync(dir))+ })+})diff --git a/src/core/pane-cwd.test.ts b/src/core/pane-cwd.test.tsnew file mode 100644index 000000000..f93f620d9--- /dev/null+++ b/src/core/pane-cwd.test.ts@@ -0,0 +1,59 @@+import { describe, it, expect } from 'vitest'+import { classifyPaneCwd } from './pane-cwd'++const exists = (): boolean => true+const missing = (): boolean => false++describe('classifyPaneCwd (issue #464 — stale cwd after delete/recreate)', () => {+ it('a live directory is ok', () => {+ expect(classifyPaneCwd('/home/user/project', exists, 'linux')).toBe('ok')+ expect(classifyPaneCwd('/home/user/project', exists, 'darwin')).toBe('ok')+ })++ it('the Linux "(deleted)" readlink suffix is stale — even when a same-named dir exists again', () => {+ // MEASURED (tmux 3.4, Linux): after `rm -rf dir && mkdir dir`, `#{pane_current_path}` still+ // reports `dir (deleted)` — the readlink names the inode the shell holds, not the path. The+ // recreated directory existing must NOT launder the verdict, so `exists` answers true here.+ expect(classifyPaneCwd('/home/user/project (deleted)', exists, 'linux')).toBe('stale')+ })++ it('a reported path that is gone from disk is stale (deleted, not yet recreated)', () => {+ expect(classifyPaneCwd('/home/user/project', missing, 'linux')).toBe('stale')+ expect(classifyPaneCwd('/home/user/project', missing, 'darwin')).toBe('stale')+ })++ it('an empty answer is stale ONLY on darwin', () => {+ // darwin: proc_pidinfo cannot name an unlinked cwd vnode, so tmux answers empty (inferred+ // from tmux's osdep-darwin.c — the PR's device checklist owes the on-device measurement).+ expect(classifyPaneCwd('', exists, 'darwin')).toBe('stale')+ // Elsewhere, empty means "tmux could not say" (an osdep with no cwd reader, a transient+ // tcgetpgrp failure). Flagging every terminal on such a platform would be a wrong fact on+ // screen, so the verdict degrades to nothing.+ expect(classifyPaneCwd('', exists, 'linux')).toBe('unknown')+ expect(classifyPaneCwd('', exists, 'freebsd')).toBe('unknown')+ })++ it('a non-absolute answer is unknown, never judged', () => {+ expect(classifyPaneCwd('not a path', missing, 'linux')).toBe('unknown')+ })++ it('a path ending in spaces is judged as-is (no trimming)', () => {+ let asked = ''+ const record = (p: string): boolean => {+ asked = p+ return true+ }+ expect(classifyPaneCwd('/tmp/dir with trailing ', record, 'linux')).toBe('ok')+ expect(asked).toBe('/tmp/dir with trailing ')+ })++ it('a throwing-free contract: dirExists is only consulted for plain absolute paths', () => {+ // The "(deleted)" branch never stats — the suffix IS the verdict, and statting the suffixed+ // string would be statting a name that never existed.+ const boom = (): boolean => {+ throw new Error('must not be called')+ }+ expect(classifyPaneCwd('/x (deleted)', boom, 'linux')).toBe('stale')+ expect(classifyPaneCwd('', boom, 'darwin')).toBe('stale')+ })+})diff --git a/src/core/pane-cwd.ts b/src/core/pane-cwd.tsnew file mode 100644index 000000000..5d26a9c57--- /dev/null+++ b/src/core/pane-cwd.ts@@ -0,0 +1,62 @@+/**+ * Stale working-directory detection for a WARM tmux reattach (issue #464).+ *+ * The failure this classifies: a project folder is deleted and re-created at the same path while+ * the node's tmux session keeps running. The shell inside still holds the DELETED directory's+ * inode — a fresh directory with the same name is a different inode, so nothing self-heals — and+ * every prompt prints `getcwd: cannot access parent directories`. `tmux new-session -A` reattaches+ * without looking at the cwd we pass, so the warm-attach path is the one that needs to notice.+ *+ * The signal is tmux's own `#{pane_current_path}` (present since tmux 1.7, so no version hazard —+ * see the bracket_paste_flag tombstone in pty-manager.ts for why that check matters):+ *+ * - **Linux (MEASURED, tmux 3.4):** tmux reads `/proc/<pid>/cwd`, and for an unlinked directory+ * the kernel reports `<path> (deleted)` — including AFTER a same-named directory is re-created,+ * because the readlink names the inode the process holds, not the path. This is the definite+ * signal on Linux.+ * - **macOS (inferred from tmux source, NOT device-measured — see the PR's device checklist):**+ * `osdep-darwin.c` resolves the cwd via `proc_pidinfo(PROC_PIDVNODEPATHINFO)`, which cannot+ * produce a path for an UNLINKED directory vnode; tmux then answers NULL and the format expands+ * to an EMPTY string. So on darwin an empty answer for a live pane is read as stale. Kept+ * darwin-only on purpose: on other platforms an empty answer more likely means "this platform's+ * osdep has no cwd reader at all", and flagging every terminal there would be a wrong fact on+ * screen (the house rule: degrade to nothing, never to something wrong).+ * - **Both platforms:** a non-empty path that no longer exists on disk is stale (deleted and not+ * yet re-created).+ *+ * The verdict only ever raises a dismissible banner with an explicit user action (recycle ++ * respawn) — nothing is typed into the pane and nothing is killed without a click.+ */++export type PaneCwdVerdict = 'ok' | 'stale' | 'unknown'++/** The `/proc` readlink convention tmux passes through verbatim on Linux. */+const DELETED_SUFFIX = ' (deleted)'++/**+ * Classify a pane's live working directory from tmux's `#{pane_current_path}` answer.+ *+ * `reported` is the raw single-line answer (caller strips the trailing newline). `dirExists` is+ * injected so the pure rules are testable without a filesystem; it must answer "is this an+ * existing directory" and never throw.+ */+export function classifyPaneCwd(+ reported: string,+ dirExists: (path: string) => boolean,+ platform: NodeJS.Platform = process.platform+): PaneCwdVerdict {+ // Deliberately NOT trimmed: a path may legally end in spaces, and the one suffix we match is+ // exact. Only a trailing newline is the transport's, and the caller already removed it.+ if (reported === '') {+ // darwin: proc_pidinfo cannot name an unlinked cwd vnode → tmux answers empty (see module+ // docblock). Elsewhere empty is "tmux could not say", which is not evidence of anything.+ return platform === 'darwin' ? 'stale' : 'unknown'+ }+ if (reported.endsWith(DELETED_SUFFIX)) return 'stale'+ // Only judge an absolute path: anything else is not a directory answer at all.+ if (!reported.startsWith('/')) return 'unknown'+ // A path tmux still resolves cleanly but that is gone from disk: deleted, not yet re-created.+ // (The recreated-same-path case never lands here — on Linux it keeps the " (deleted)" suffix+ // above, and on darwin it comes in empty.)+ return dirExists(reported) ? 'ok' : 'stale'+}diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex fcbe0e77c..822d48285 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -39,6 +39,7 @@ import {} from './remote-ssh/control-master'import { probeAgentSockToPin } from './remote-ssh/agent-probe'import { parsePaneCursor } from './pane-cursor'+import { classifyPaneCwd } from './pane-cwd'import {recordFreshSpawnOwner,forgetPaneOwner,@@ -2239,15 +2240,67 @@ export class PtyManager {// (`persisted` in spawnSession) — i.e. exactly "this session survives losing its client",// which is what the renderer's cache-dispose levers must not assume. See PtyCreateResult.const persistent = !!spawned?.persistKey- return accountFallback- ? {- sessionId,- fresh,- accountFallback,- persistent,- ...(screen ? { screen } : {})+ // Stale-cwd probe (issue #464), WARM local-tmux reattach only: `new-session -A` reattached a+ // session whose shell may sit on a DELETED directory inode (a re-created same-named folder is+ // a different inode, so the getcwd errors never self-heal). A fresh spawn already validated+ // its cwd above; a plain shell has no session that outlived anything; an SSH-remote session's+ // 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+ ? await this.paneCwdStale(options.persistKey)+ : false+ return {+ sessionId,+ fresh,+ persistent,+ ...(accountFallback ? { accountFallback } : {}),+ ...(staleCwd ? { staleCwd: true as const } : {}),+ ...(screen ? { screen } : {})+ }+ }++ /**+ * Is the live tmux session's working directory GONE (deleted, or deleted and re-created at the+ * same path — issue #464)? Asks tmux for `#{pane_current_path}` — a format present since 1.7,+ * so no version hazard — and classifies through the pure `classifyPaneCwd` (see pane-cwd.ts for+ * the per-platform signals, one measured and one inferred). Exact-match target: `=name:` —+ * the trailing colon matters, and is MEASURED (tmux 3.4): for a target-PANE a bare `=name`+ * resolves NOTHING silently (exit 0, every format empty), while `=name:` is "exactly this+ * session, its active pane". Without `=`, tmux falls back to fnmatch-then-prefix matching and+ * could answer about a DIFFERENT node whose id extends this one (the same trap the kill path+ * documents). Any failure answers `false` — no banner on a guess.+ */+ private async paneCwdStale(persistKey: string): Promise<boolean> {+ if (!this.tmuxPath) return false+ try {+ const { stdout } = await runAsync(+ this.tmuxPath,+ [+ '-L',+ TMUX_SOCKET,+ 'display-message',+ '-p',+ '-t',+ `=${sessionName(persistKey)}:`,+ '#{pane_current_path}'+ ],+ { timeout: PROBE_TIMEOUT_MS }+ )+ // Strip ONLY the transport's trailing newline — a path may legally end in spaces, and the+ // Linux " (deleted)" suffix must survive untouched for the classifier to see it.+ const reported = stdout.replace(/\r?\n$/, '')+ const dirExists = (p: string): boolean => {+ try {+ return fs.statSync(p).isDirectory()+ } catch {+ return false}- : { sessionId, fresh, persistent, ...(screen ? { screen } : {}) }+ }+ return classifyPaneCwd(reported, dirExists) === 'stale'+ } catch {+ return false+ }}/** Does the node's remote tmux session exist (over the project's ControlMaster)? Async so thediff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 901c6677d..4318c8a5d 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -791,13 +791,24 @@ interface CoState {* nobody.*/spawnError: string | null+ /**+ * A WARM reattach found the session's live working directory GONE (`PtyCreateResult.staleCwd`,+ * issue #464): the folder was deleted — or deleted and re-created, which is a different inode,+ * so the shell keeps printing `getcwd` errors forever. NOT an overlay state: the terminal is+ * alive and possibly mid-work, so this only raises a slim banner offering an EXPLICIT+ * recycle-and-respawn ("Restart in folder") plus a dismiss. Nothing is typed into the pane and+ * nothing restarts on its own. Overwritten by every create result for this node, so a clean+ * respawn clears it.+ */+ staleCwd: boolean}const NO_CO: CoState = {letterbox: false,closed: null,ended: false,offline: false,- spawnError: null+ spawnError: null,+ staleCwd: false}const coStates = new Map<string, CoState>()const coSubs = new Map<string, (s: CoState) => void>()@@ -928,11 +939,18 @@ function setCo(key: string, patch: Partial<CoState>): void {const next = { ...prev, ...patch }// A no-op write must stay a no-op: applyFit clears the letterbox on every fit, and handing the// node a fresh object each time would re-render it for nothing (and, solo, on every resize tick).+ //+ // EVERY field must be compared, not a hand-kept subset. The list used to stop at `offline`, so a+ // patch that changed ONLY `spawnError` was swallowed here — the "terminal could not be started"+ // overlay silently never rendered from a bare `{ spawnError }` write, and the new `staleCwd`+ // banner would have been born with the same fault. If you add a CoState field, add it here.if (next.letterbox === prev.letterbox &&next.closed === prev.closed &&next.ended === prev.ended &&- next.offline === prev.offline+ next.offline === prev.offline &&+ next.spawnError === prev.spawnError &&+ next.staleCwd === prev.staleCwd)returncoStates.set(key, next)@@ -1603,6 +1621,22 @@ export function TerminalNode({}))}+ // "Restart in folder" (CoState.staleCwd, issue #464): the warm-reattached shell sits on a+ // DELETED directory inode, which no `cd` we could inject would be allowed to fix (text into a+ // pane is injection) and which re-creating the folder can never heal. The recovery is the same+ // recycle-then-respawn the model switch and "restart shell" use: core ends the tmux session+ // (reserving the replacement for this client), the respawn re-validates `data.cwd` and starts a+ // fresh shell in the re-created folder. Explicit user action only — the session may hold live+ // work, which is exactly why nothing here runs on its own.+ const restartInFolder = (): void => {+ setCo(termKey, { staleCwd: false })+ transport.recycle(id)+ updateNodeData(id, (n) => ({+ respawnNonce: ((n.data.respawnNonce as number | undefined) ?? 0) + 1+ }))+ }+ const dismissStaleCwd = (): void => setCo(termKey, { staleCwd: false })+// "Not connected" (CoState.offline): the host was unreachable, so this node has no session// anywhere. Ask the coordinator to re-establish the project's master NOW — it flushes the// pending nodes (this one included) on success, which is what respawns them. We do NOT bump@@ -2696,6 +2730,7 @@ export function TerminalNode({sessionId: sid,fresh,accountFallback: fellBack,+ staleCwd,closed,screen,cursor,@@ -2744,6 +2779,9 @@ export function TerminalNode({// Published for the mount-stable observer effect, which cannot see this closure.sessionPersistentRef.current = sessionPersistentif (fellBack) setAccountFallback(true)+ // Truthful on EVERY result, not only when set: a clean respawn ("Restart in folder", or+ // any refresh that landed on a healthy session) must take the banner down with it.+ setCo(termKey, { staleCwd: !!staleCwd })// Catch up a size change that landed while the spawn was in flight (applyFit skips the// IPC until sessionId is set, and the observer won't re-fire without another change).applyFit()@@ -4856,6 +4894,33 @@ export function TerminalNode({</button></div>)}+ {/* Stale working directory (issue #464): a slim TOP banner, never an overlay — the+ terminal underneath is alive and may be mid-work. Top edge on purpose: every shell+ and agent CLI writes its input line at the BOTTOM, and covering the prompt would be+ worse than covering the oldest visible output row. */}+ {!co.closed && !co.ended && !co.spawnError && !co.offline && co.staleCwd && !offscreenDown && (+ <div className="term-node__stalecwd nodrag">+ <span className="term-node__stalecwd-text">+ This terminal's folder was deleted (or replaced) — the shell's working+ directory no longer exists.+ </span>+ <button+ className="term-node__stalecwd-restart"+ onClick={restartInFolder}+ title={`End this shell and start a fresh one in ${(data.cwd as string) || 'the project folder'}. Anything still running in this terminal will end.`}+ >+ Restart in folder+ </button>+ <button+ className="term-node__stalecwd-dismiss"+ onClick={dismissStaleCwd}+ title="Dismiss"+ aria-label="Dismiss"+ >+ ×+ </button>+ </div>+ )}{armed && !mdMode && (<divclassName="term-hover-guard"diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex ad696e3e8..7859f558e 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -2206,6 +2206,57 @@ body,background: rgba(var(--tint-rgb), 0.12);}+/* Stale working directory (issue #464): the project folder was deleted (or replaced) while this+ node's tmux session kept running, so the shell sits on a dead inode. A slim TOP banner — never+ a covering overlay, the terminal underneath is alive — offering the explicit recycle-respawn+ ("Restart in folder") plus a dismiss. Top edge: shells and agent CLIs write their input line at+ the bottom, and covering the prompt would be worse than covering the oldest output row. */+.term-node__stalecwd {+ position: absolute;+ top: 0;+ left: 0;+ right: 0;+ z-index: 4;+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 5px 8px;+ font-size: 11px;+ color: #ffd9a8;+ background: rgba(120, 70, 10, 0.92);+ border-bottom: 1px solid rgba(255, 180, 80, 0.35);+}+.term-node__stalecwd-text {+ flex: 1;+ min-width: 0;+}+.term-node__stalecwd-restart {+ padding: 2px 10px;+ border: 1px solid rgba(255, 200, 120, 0.45);+ border-radius: 6px;+ background: rgba(255, 255, 255, 0.1);+ color: inherit;+ font-size: 11px;+ cursor: pointer;+ white-space: nowrap;+}+.term-node__stalecwd-restart:hover {+ background: rgba(255, 255, 255, 0.2);+}+.term-node__stalecwd-dismiss {+ padding: 0 4px;+ border: none;+ background: none;+ color: inherit;+ font-size: 14px;+ line-height: 1;+ cursor: pointer;+ opacity: 0.7;+}+.term-node__stalecwd-dismiss:hover {+ opacity: 1;+}+/* "Reconnect" in the SSH connection banner. The banner paints its own dark-red background, so thissits on a light translucent fill rather than the card tint the node buttons use. */.ssh-banner__retry {diff --git a/src/shared/types.ts b/src/shared/types.tsindex c3f6dac5b..100bc9b60 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -156,6 +156,19 @@ export interface PtyCreateResult {/** Set when the node's `accountId` had no config dir at spawn, so the session fell back to the* system account. The renderer flags the account chip (folder-missing warning) when true. */accountFallback?: boolean+ /**+ * WARM reattach only (local tmux): the reattached session's live working directory no longer+ * exists — the folder was deleted (or deleted and re-created, which is a DIFFERENT inode, so the+ * shell inside keeps printing `getcwd: cannot access parent directories`; issue #464). `tmux+ * new-session -A` ignores the cwd we pass on a reattach, so this is the only moment the fact is+ * knowable cheaply. The renderer shows a dismissible banner with an explicit+ * recycle-and-respawn action — NOTHING is typed into the pane and nothing restarts on its own+ * (the pane may be mid-work, and text into a pane is injection).+ *+ * Absent = fine or unknowable (fresh spawn, plain shell, SSH-remote session, probe failed, or a+ * core older than this field over the relay) — the banner never shows on a guess.+ */+ staleCwd?: boolean/*** The CURRENT SCREEN of a session this create JOINED (co-attach), captured from tmux — write it* into the fresh xterm before the live stream starts.