Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(pty): spawn the local tmux client from a stable dir, not the node's cwd (#1221)

eneskirca75a4f2ce4650
diff --git a/CLAUDE.md b/CLAUDE.md
index d528cd02a..28b6bacda 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1108,6 +1108,19 @@ and the Claude CLI there then turned transcript saving off (no ⌘M view, no con
seeded from such an environment does not hand them back (the #419 mechanism). Explicit names, never a
`CLAUDE*` prefix sweep: `CLAUDE_CONFIG_DIR` and `CODEX_HOME` are how a managed account is selected.
+**The local tmux CLIENT is spawned from `localTmuxClientCwd()` (home, else `/`), never the node's
+cwd — the pane's directory rides `new-session -c` only** (issue #1131). Any client can be the one
+that starts the shared server, the server keeps that client's cwd for life, and from tmux 3.7
+`spawn.c` applies a pane's `-c` only when the server's own `getcwd()` succeeds: once the dir the
+server started in is deleted (a removed worktree), every NEW pane on the server inherits the deleted
+dir whatever `-c` said, and agents launched there hang. MEASURED on a locally built tmux 3.7c
+(private socket): client in the doomed dir → `-c <proj>` pane at `<gone> (deleted)`; client in
+`$HOME` → pane at `<proj>`. tmux 3.4–3.6 honour `-c` either way, which is why CI cannot reproduce it
+and the guard is a spawn-options assertion (`pty-tmux-client-cwd.test.ts`). The plain-shell fallback
+is the pane itself and keeps the project cwd; remote tmux is started from an ssh exec channel, which
+sshd places in the login home. A server started by an earlier build keeps its old cwd until it is
+restarted (`tmux -L node-terminal kill-server`, which ends every session).
+
**A session-host session follows its most recently ACTIVE viewer, like tmux's `window-size
latest`** (issue #914). Under tmux a relay-mirrored phone is its own tmux client, so dismissing its
keyboard gives it its rows back; on the session host the phone and the desktop node share ONE
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c83e01bef..fa1c379ae 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -915,6 +915,12 @@ shipped: managed-account `CLAUDE_CONFIG_DIR` leaked into system-account sessions
env either joins `ACCOUNT_SCOPE_UPDATE_ENV` / the gateway list, or rides `-e` — and gets a
real-tmux test (`account-env.realtmux.test.ts` is the pattern).
+**The same goes for the CWD: a tmux client never runs in the node's directory.** The server keeps
+the cwd of the client that started it, and from tmux 3.7 a new pane's `-c` is silently dropped once
+that directory is deleted — every new terminal then opens in the deleted dir (issue #1131, measured
+on tmux 3.7c). The local tmux client is spawned from `localTmuxClientCwd()` (home, else `/`) and the
+pane's directory rides `-c` only. The plain-shell fallback IS the pane and keeps the project cwd.
+
**A new keyboard chord has to survive the shells, not just the renderer.** The application menu is
ours (`buildAppMenu` in `main/index.ts`), but its command-style accelerators — ⌘Q, ⌘M, ⌘W, ⌘0, ⌘⇧B,
⌘, — are still handled above the page, so your `keydown` branch simply never runs: steal the chord
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 74f3fb195..fbc59572c 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -977,6 +977,36 @@ export interface DetachedSinks {
adaptsToSize?: boolean
}
+/**
+ * The working directory a LOCAL tmux CLIENT is spawned in (issue #1131) — never the node's own
+ * directory, which reaches tmux only through `new-session -c`.
+ *
+ * Any client can be the one that STARTS the shared `-L node-terminal` server, and the server keeps
+ * that client's cwd for the rest of its life. From tmux 3.7, `spawn.c` applies a new pane's `-c`
+ * only when the SERVER's own `getcwd()` succeeds; once the directory the server started in is
+ * deleted (a removed worktree, a cleaned-up station), `getcwd()` fails, the `chdir` is skipped and
+ * every new pane on the server inherits the deleted directory, whatever `-c` said. MEASURED on a
+ * locally built tmux 3.7c (private socket): server started from a dir that was then removed → a
+ * `new-session -c <proj>` pane at `<gone> (deleted)`; the same sequence with the client in $HOME →
+ * the pane at `<proj>`. tmux 3.4–3.6 honour `-c` either way. The home directory is what the issue's
+ * reporter and every terminal emulator use; `/` is the fallback when even that is missing.
+ *
+ * Not for the plain-shell fallback: there the spawned process IS the pane and needs the project
+ * cwd. A server started by an earlier build keeps its old cwd until it is restarted.
+ */
+export function localTmuxClientCwd(
+ home: string = os.homedir(),
+ isDir: (p: string) => boolean = (p) => {
+ try {
+ return fs.statSync(p).isDirectory()
+ } catch {
+ return false
+ }
+ }
+): string {
+ return home && isDir(home) ? home : '/'
+}
+
/**
* tmux attach flags. `-A` = attach-or-create. `-D` = detach OTHER clients on attach.
*
@@ -4825,6 +4855,9 @@ export class PtyManager {
xtermScrollback(settings.tmuxScrollback)
)) as unknown as pty.IPty
} else {
+ // A tmux client must not pin the project dir as the shared server's cwd (#1131): the pane's
+ // directory is the `-c` argument above, never the client's own cwd.
+ const spawnCwd = useLocalTmux ? localTmuxClientCwd() : cwd
try {
proc =
nativeSshArgv && useNativeSsh()
@@ -4841,7 +4874,7 @@ export class PtyManager {
name: 'xterm-256color',
cols: options.cols,
rows: options.rows,
- cwd,
+ cwd: spawnCwd,
env
})
} catch (err) {
@@ -4854,7 +4887,7 @@ export class PtyManager {
// Re-read the devices rather than reusing the pre-flight's reading: this spawn just consumed
// (and, per the leak above, kept) devices of its own, so the number the user is shown should
// be the one that was true when the failure happened.
- throw this.spawnFailureError(reason, file, cwd, spawnHelperArchMismatch(), readPtyDevices())
+ throw this.spawnFailureError(reason, file, spawnCwd, spawnHelperArchMismatch(), readPtyDevices())
}
}
diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.ts
index 189ffb895..2be80ef14 100644
--- a/src/core/pty-single-user.test.ts
+++ b/src/core/pty-single-user.test.ts
@@ -265,8 +265,12 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =
expect(args[args.indexOf('-c') + 1]).toBe(cwd)
expect(args.slice(-2)).toEqual(['-s', sessionName('solo-1')])
// The spawned process env is the pre-co-attach env: forced TERM, no inherited TMUX nesting,
- // and the real login-shell PATH.
- expect(spawnArgs[0].cwd).toBe(cwd)
+ // and the real login-shell PATH. The CLIENT runs from a stable dir, never the node's: the
+ // pane's directory is the `-c` above (issue #1131 — a client in the project dir can start the
+ // shared server there, and tmux 3.7 then drops every later pane's `-c` once that dir is gone).
+ const { localTmuxClientCwd } = await import('./pty-manager')
+ expect(spawnArgs[0].cwd).toBe(localTmuxClientCwd())
+ expect(spawnArgs[0].cwd).not.toBe(cwd)
expect(env.TERM).toBe('xterm-256color')
expect(env.TMUX).toBeUndefined()
expect(env.TMUX_PANE).toBeUndefined()
diff --git a/src/core/pty-tmux-client-cwd.test.ts b/src/core/pty-tmux-client-cwd.test.ts
new file mode 100644
index 000000000..508c9d49c
--- /dev/null
+++ b/src/core/pty-tmux-client-cwd.test.ts
@@ -0,0 +1,105 @@
+/**
+ * Issue #1131 — the LOCAL tmux client must not be spawned in the node's project directory.
+ *
+ * The first client to reach the shared `-L node-terminal` socket STARTS the server, and the server
+ * keeps that client's working directory for the rest of its life. From tmux 3.7, `spawn.c` only
+ * honours a new pane's `-c <dir>` when the SERVER's own `getcwd()` succeeds; once the directory the
+ * server started in is deleted (a removed worktree, a cleaned-up station), `getcwd()` fails, the
+ * `chdir(-c)` is skipped and every new pane inherits the server's deleted cwd — whatever project it
+ * belongs to. MEASURED on a locally built tmux 3.7c (private socket): server started from a dir
+ * that was then removed → `new-session -c <proj>` pane at `<gone> (deleted)`; same server started
+ * from $HOME → pane at `<proj>`. tmux 3.4–3.6 do not have the guard and honour `-c` either way.
+ *
+ * So the tmux client runs from a stable directory and the pane's directory rides `-c` only. The
+ * plain-shell fallback is the pane itself and keeps the project cwd.
+ *
+ * MUTATION: pass `cwd` instead of `localTmuxClientCwd()` to `pty.spawn` for the tmux branch → the
+ * first case reddens.
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { mkdtempSync, rmSync } from 'fs'
+import os from 'os'
+import path from 'path'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform, type FakePlatform } from './platform-fake'
+import { IPC } from '../shared/ipc'
+import { DEFAULT_SETTINGS } from '../shared/types'
+import type { PtyCreateOptions, PtyCreateResult, Settings } from '../shared/types'
+
+const spawned: Array<{ file: string; args: string[]; cwd: string | undefined }> = []
+
+vi.mock('node-pty', () => ({
+ spawn: (file: string, args: string[], options: { cwd?: string }) => {
+ spawned.push({ file, args, cwd: options?.cwd })
+ return {
+ onData: () => {}, onExit: () => {}, write: () => {}, resize: () => {},
+ pause: () => {}, resume: () => {}, kill: () => {}, pid: 4321
+ }
+ }
+}))
+vi.mock('./pty-devices', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./pty-devices')>()),
+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })
+}))
+
+const ALICE = 1
+
+describe('the local tmux client never pins the project dir as the server cwd (#1131)', () => {
+ let fake: FakePlatform
+ let userDataDir: string
+ let projectDir: string
+ let settings: Settings
+
+ beforeEach(async () => {
+ spawned.length = 0
+ userDataDir = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-client-cwd-'))
+ projectDir = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-client-cwd-proj-'))
+ fake = fakePlatform({ userDataDir })
+ initPlatform(fake)
+ const { PtyManager } = await import('./pty-manager')
+ settings = { ...DEFAULT_SETTINGS }
+ const mgr = new PtyManager()
+ mgr.init(() => settings)
+ mgr.registerIpc()
+ })
+ afterEach(() => {
+ resetPlatformForTests()
+ rmSync(userDataDir, { recursive: true, force: true })
+ rmSync(projectDir, { recursive: true, force: true })
+ })
+
+ const create = (options: Partial<PtyCreateOptions>) =>
+ fake.handlers[IPC.ptyCreate](ALICE, {
+ cols: 80, rows: 24, persistKey: 'node-1', cwd: projectDir, ...options
+ }) as Promise<PtyCreateResult>
+
+ it.skipIf(process.platform === 'win32')('spawns the tmux client from a stable dir and passes the project dir via -c', async () => {
+ const { localTmuxClientCwd } = await import('./pty-manager')
+ const res = await create({})
+ expect(res.unavailable).toBeUndefined()
+ expect(spawned).toHaveLength(1)
+ const [{ args, cwd }] = spawned
+ // This suite needs a real tmux on PATH (as the other pty suites do); without one the create
+ // takes the plain-shell branch and the next assertions would be about the wrong thing.
+ expect(args).toContain('new-session')
+ expect(args[args.indexOf('-c') + 1]).toBe(projectDir)
+ expect(cwd).toBe(localTmuxClientCwd())
+ expect(cwd).not.toBe(projectDir)
+ })
+
+ it('the plain-shell fallback is the pane itself and keeps the project cwd', async () => {
+ settings = { ...settings, tmuxEnabled: false }
+ await create({ persistKey: undefined })
+ expect(spawned).toHaveLength(1)
+ expect(spawned[0].cwd).toBe(projectDir)
+ })
+})
+
+describe('localTmuxClientCwd', () => {
+ it('answers the home directory when it exists, else /', async () => {
+ const { localTmuxClientCwd } = await import('./pty-manager')
+ expect(localTmuxClientCwd('/home/x', () => true)).toBe('/home/x')
+ expect(localTmuxClientCwd('/home/x', () => false)).toBe('/')
+ expect(localTmuxClientCwd('', () => true)).toBe('/')
+ })
+})