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(accounts): stop the shared tmux server leaking a managed account into other sessions

enes13d419f981a8
diff --git a/CLAUDE.md b/CLAUDE.md
index f1560be0b..28c3a466b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1311,14 +1311,31 @@ else, and its context links must keep classifying across restarts).
(`resolveNewNodeAccount`: explicit submenu pick → `project.defaultAccountId` → system default
`~/.claude`), then **immutable** and **persisted** (serializers). `undefined` = system default
= **bit-for-bit legacy behavior** (no env touched). Inherited by **Branch** (the
- terminal→chat fork it also fed is gone — the SDK chat node was removed 2026-07). A pending
- (not-yet-logged-in) account resolves to `undefined` until it completes.
+ terminal→chat fork it also fed is gone — the SDK chat node was removed 2026-07). Two #419
+ rules inside the resolver: the submenu's **System row passes `null`** (an EXPLICIT system
+ pick that skips the project default — before that, the row wearing the system email launched
+ the project-default account), and validation runs against `accountsForProject`, not the raw
+ list, so a **pending** account or one **pinned to another machine's host** is never stamped
+ onto a node it cannot run on (both used to reach the missing-dir fallback at spawn).
- **Env injection** — `pty-manager` sets `CLAUDE_CONFIG_DIR` in the spawn env AND as a tmux `-e`
(local); for a remote node it emits an **absolute-path** remote tmux `-e` built from the
connection-cached `remoteHome` (skipped **fail-open** if home is unresolved). `AUTH_ENV_STRIP`
(`ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` / `CLAUDE_CODE_OAUTH_TOKEN`) is deleted from the
child env so a stray env key can't shadow the account. A **missing** account dir → warn +
- silent system fallback.
+ silent system fallback. **The account-scope names ride the LOCAL conf's `update-environment`
+ (`ACCOUNT_SCOPE_UPDATE_ENV`, issue #419)** — the shared tmux server inherits the env of the
+ client that STARTS it, so a server started by a managed-account node used to leak that
+ account's `CLAUDE_CONFIG_DIR` (and any un-stripped auth key) into every session created
+ without a `-e` override: system nodes, plain terminals and the missing-dir fallback silently
+ ran as that account ("the system account is entangled with the next account in the list").
+ Listing the names makes tmux copy each from the creating client's env and **strip it when the
+ client lacks it** (proven against a real tmux in `account-env.realtmux.test.ts`, seeded-server
+ case included; `ensureUpdateEnvKeys` retrofits a long-lived pre-fix server). The same listing
+ is what makes codex's explicit system-scope overwrite (`CODEX_HOME` /
+ `NODETERM_CODEX_ACCOUNT_ID`) actually reach sessions on a shared server. **LOCAL conf only**
+ — the remote conf must NOT get these names: a remote attach client's env is the login
+ shell's, and the copy/strip would run against that wrong environment (pinned in
+ `ssh.test.ts`).
- **Login flow** — Settings → Accounts → **Add** creates a `pending` account and drops a canvas
**login node** that runs `claude /login` under the account dir. Main polls the dir's
`.claude.json` (`LOGIN_POLL_MS` 2 s, up to `LOGIN_TIMEOUT_MS` 5 min) for `oauthAccount.email`;
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 2af6e84e5..6ce6bf0b7 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -120,6 +120,16 @@ three times.
screen. A previous design moved that into the emulator and failed structurally; `CLAUDE.md` explains
why in detail.
+**A spawn-env write does not reach a tmux session on its own.** The shared tmux server takes each
+new session's env from its own GLOBAL env (inherited from whichever client *started* the server) —
+the creating client's process env only matters for names listed in `update-environment` (or passed
+as non-secret `-e` pairs). Setting `env.FOO` in `pty-manager` therefore works for the plain-shell
+fallback and for the one client that happens to start the server, and silently does nothing (or
+worse, leaks the server-starter's value into everyone else) after that. That is how issue #419
+shipped: managed-account `CLAUDE_CONFIG_DIR` leaked into system-account sessions. New per-session
+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).
+
**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/account-env.realtmux.test.ts b/src/core/account-env.realtmux.test.ts
new file mode 100644
index 000000000..46531aca9
--- /dev/null
+++ b/src/core/account-env.realtmux.test.ts
@@ -0,0 +1,143 @@
+// ISSUE #419, PROVEN AGAINST A REAL TMUX: the shared server must not leak one node's managed
+// Claude/Codex account into another node's session.
+//
+// The mechanism under test: a tmux server inherits the process environment of whichever client
+// STARTS it. An account node's client carries `CLAUDE_CONFIG_DIR=<account dir>` (pty-manager sets
+// it in the spawn env), so a server started by that client holds the account dir in its GLOBAL
+// env — and every later session created withOUT a `-e` override (system-account nodes, plain
+// terminals, the missing-dir fallback) inherited it and silently ran as that account. That is the
+// reporter's "the system account is somehow being entangled with the next account in the list",
+// and "sometimes" because it depends on which node's client happened to start the server.
+//
+// The fix is the REMOVAL half of `update-environment`: the account-scope names are listed in the
+// LOCAL conf (ACCOUNT_SCOPE_UPDATE_ENV), so tmux copies each one from the creating client's env —
+// set for the node that owns it, STRIPPED from the session when the client lacks it. Whether tmux
+// actually does that is a property of tmux, so it is measured here with the EXACT conf text
+// `tmuxConf()` ships — same discipline as session-env.realtmux.test.ts, whose harness this copies
+// (its server is seeded with the GATEWAY var; this one needs a server seeded with the ACCOUNT
+// vars, which is why it runs its own private socket).
+import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import { execFileSync } from 'child_process'
+import fs from 'fs'
+import path from 'path'
+import { tmuxConf } from './pty-manager'
+import { makeTmuxTmpdir } from './tmux-test-socket'
+
+const SOCKET = `nt-accttest-${process.pid}`
+
+let tmp: string
+let conf: string
+let tmuxOk = false
+
+function tmux(args: string[], env?: Record<string, string>): string {
+ // TMUX_TMPDIR last: a caller's `env` chooses what the CLIENT carries, never which server it
+ // reaches (see session-env.realtmux.test.ts).
+ return execFileSync('tmux', ['-L', SOCKET, ...args], {
+ env: { ...cleanEnv(), ...env, TMUX_TMPDIR: tmp },
+ stdio: ['ignore', 'pipe', 'pipe']
+ }).toString()
+}
+
+/** process.env minus the account-scope vars, so the HOST machine's own CLAUDE_CONFIG_DIR (this
+ * repo's dev boxes run nodeterm sessions themselves) can never seed or satisfy an assertion. */
+function cleanEnv(): Record<string, string | undefined> {
+ const e = { ...process.env }
+ delete e.CLAUDE_CONFIG_DIR
+ delete e.CODEX_HOME
+ delete e.NODETERM_CODEX_ACCOUNT_ID
+ return e
+}
+
+beforeAll(() => {
+ try {
+ execFileSync('tmux', ['-V'], { stdio: 'ignore' })
+ tmuxOk = true
+ } catch {
+ return // no tmux on this host — every test below self-skips
+ }
+ tmp = makeTmuxTmpdir('ntacct-', SOCKET)
+ conf = path.join(tmp, 'tmux.conf')
+ fs.writeFileSync(conf, tmuxConf(2000))
+})
+
+afterAll(() => {
+ if (!tmuxOk) return
+ try {
+ tmux(['kill-server'])
+ } catch {
+ /* already gone */
+ }
+ fs.rmSync(tmp, { recursive: true, force: true })
+})
+
+const waitFor = async (file: string, ms = 3000): Promise<string> => {
+ const t0 = Date.now()
+ for (;;) {
+ if (fs.existsSync(file)) return fs.readFileSync(file, 'utf8')
+ if (Date.now() - t0 > ms) throw new Error(`timed out waiting for ${file}`)
+ await new Promise((r) => setTimeout(r, 25))
+ }
+}
+
+describe('managed-account isolation on a shared tmux server (issue #419)', () => {
+ it('an account node (client env + -e, the pty-manager shape) sees its own config dir', async () => {
+ if (!tmuxOk) return
+ const out = path.join(tmp, 'account-pane')
+ // This FIRST create also starts the server, seeding its global env with the account dir —
+ // the exact worst case the next test measures.
+ tmux(
+ [
+ '-f', conf, 'new-session', '-d',
+ '-e', 'CLAUDE_CONFIG_DIR=/ud/claude-accounts/a1',
+ '-s', 'acct',
+ `echo "DIR=[$CLAUDE_CONFIG_DIR] CX=[$CODEX_HOME]" > ${out}; sleep 5`
+ ],
+ {
+ CLAUDE_CONFIG_DIR: '/ud/claude-accounts/a1',
+ CODEX_HOME: '/ud/cx/a1',
+ NODETERM_CODEX_ACCOUNT_ID: 'a1'
+ }
+ )
+ expect(await waitFor(out)).toBe('DIR=[/ud/claude-accounts/a1] CX=[/ud/cx/a1]\n')
+ // The seed is real: the server's global env now carries account a1.
+ expect(tmux(['show-environment', '-g'])).toContain('CLAUDE_CONFIG_DIR=/ud/claude-accounts/a1')
+ })
+
+ it("a SYSTEM-account session on that seeded server does NOT inherit a1 — the #419 repro", async () => {
+ if (!tmuxOk) return
+ // A system node's client: no -e, no account vars in its env (pty-manager leaves them unset).
+ // Pre-fix, this pane printed a1's dir — the session silently ran as the managed account.
+ const out = path.join(tmp, 'system-pane')
+ tmux(['new-session', '-d', '-s', 'system', `echo "DIR=[$CLAUDE_CONFIG_DIR] CX=[$CODEX_HOME]" > ${out}`])
+ expect(await waitFor(out)).toBe('DIR=[] CX=[]\n')
+ })
+
+ it('a second account node on the seeded server still gets ITS dir, not the seed', async () => {
+ if (!tmuxOk) return
+ const out = path.join(tmp, 'account2-pane')
+ tmux(
+ [
+ 'new-session', '-d',
+ '-e', 'CLAUDE_CONFIG_DIR=/ud/claude-accounts/b2',
+ '-s', 'acct2',
+ `echo "DIR=[$CLAUDE_CONFIG_DIR]" > ${out}`
+ ],
+ { CLAUDE_CONFIG_DIR: '/ud/claude-accounts/b2' }
+ )
+ expect(await waitFor(out)).toBe('DIR=[/ud/claude-accounts/b2]\n')
+ })
+
+ it('the codex SYSTEM overwrite now actually reaches a session on the shared server', async () => {
+ if (!tmuxOk) return
+ // pty-manager writes the system Codex scope EXPLICITLY into the client env ("so it overwrites
+ // any managed scope a parent tmux server leaked in") — but a client's env only reaches the
+ // session for names in update-environment, so before #419 that overwrite worked solely for
+ // the client that started the server. Seeded server + explicit system client = system values.
+ const out = path.join(tmp, 'codex-system-pane')
+ tmux(
+ ['new-session', '-d', '-s', 'cxsys', `echo "CX=[$CODEX_HOME] ID=[$NODETERM_CODEX_ACCOUNT_ID]" > ${out}`],
+ { CODEX_HOME: '/home/u/.codex', NODETERM_CODEX_ACCOUNT_ID: '' }
+ )
+ expect(await waitFor(out)).toBe('CX=[/home/u/.codex] ID=[]\n')
+ })
+})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 6e9190e78..a3836a302 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -246,6 +246,29 @@ function runWithStdin(file: string, args: readonly string[], input: string): Pro
// payload with `terminal-features`). The renderer's OSC 52 handler writes the system clipboard, so
// this is the copy path on EVERY platform and over SSH — no `pbcopy` pipe (that was macOS-only,
// and half of why copying was broken).
+/**
+ * Session-identity env names the LOCAL conf's `update-environment` carries on top of the stock +
+ * gateway list (issue #419). The point is the REMOVAL half of update-environment's contract: the
+ * shared tmux server inherits the env of whichever client STARTS it, so a server started by a
+ * managed-account node's client held that account's `CLAUDE_CONFIG_DIR` in its GLOBAL env — and
+ * every later session created withOUT a `-e` override (system-account nodes, plain terminals, and
+ * the missing-dir fallback) inherited it and silently ran as that account ("the system account is
+ * entangled with the next account in the list"). With the names listed, tmux copies each one from
+ * the creating CLIENT's env — set for the node that owns it, and STRIPPED from the session when
+ * the client lacks it (measured in session-env.realtmux.test.ts, seeded-server case included).
+ * The auth-strip names ride along for the same reason: deleting them from the client env alone
+ * never touched a seeded server's global copy, so a managed-OAuth node could still run on an
+ * inherited API key. LOCAL conf only — see `tmuxUpdateEnvironmentLine` for why the remote conf
+ * must not get these.
+ */
+export const ACCOUNT_SCOPE_UPDATE_ENV: readonly string[] = [
+ 'CLAUDE_CONFIG_DIR',
+ ...AUTH_ENV_STRIP,
+ 'CODEX_HOME',
+ 'NODETERM_CODEX_ACCOUNT_ID',
+ ...CODEX_AUTH_ENV_STRIP
+]
+
export function tmuxConf(scrollback: number): string {
return `# auto-generated by node-terminal — do not edit
set -g status off
@@ -259,7 +282,10 @@ setw -g aggressive-resize on
# environment and update-environment copies them into the session at create/attach. The old
# '-e KEY=VALUE' route parked the API key on the long-lived attached client's command line —
# world-readable in /proc/<pid>/cmdline on any multi-user host (the PR #195 leak class).
-${tmuxUpdateEnvironmentLine()}
+# The account-scope names (CLAUDE_CONFIG_DIR et al.) are listed for their REMOVAL semantics:
+# a client that lacks one strips it from the session, so a server whose global env was seeded
+# by a managed-account client can no longer leak that account into unbound sessions (#419).
+${tmuxUpdateEnvironmentLine(ACCOUNT_SCOPE_UPDATE_ENV)}
# Copy to the SYSTEM clipboard via OSC 52 (the client's terminal writes it). BOTH lines are needed
# on tmux 3.2+ — see tmuxConf's doc comment before touching either.
# MIGRATION — do not remove. Older versions of this file blanked smcup/rmcup/indn via
@@ -2580,8 +2606,14 @@ export class PtyManager {
// dir. The claude CLI then reads/writes credentials + transcripts there. Also strip
// env auth vars that would silently shadow the account's OAuth login (an inherited
// ANTHROPIC_API_KEY wins over CLAUDE_CONFIG_DIR credentials). System-default nodes
- // (no accountId) are untouched. Remote (ssh) sessions get their account env via the
- // remote tmux `-e` list instead (the local ssh client process doesn't need it).
+ // (no accountId) set nothing HERE — but they are not "untouched" on the tmux leg:
+ // CLAUDE_CONFIG_DIR is in ACCOUNT_SCOPE_UPDATE_ENV, so a client whose env lacks it makes
+ // tmux STRIP it from the new session, which is what keeps a server seeded by a managed
+ // account's client from leaking that account into every unbound session (#419). The
+ // missing-dir fallback below rides the same rule: accountDir nulled ⇒ no env var ⇒ the
+ // session genuinely lands on `~/.claude`, not on whatever the server global env held.
+ // Remote (ssh) sessions get their account env via the remote tmux `-e` list instead
+ // (the local ssh client process doesn't need it).
let accountFallback = false
let accountDir =
options.accountId && !options.sshRemote ? claudeConfigDirFor(options.accountId) : null
@@ -2602,10 +2634,12 @@ export class PtyManager {
// CODEX_HOME + NODETERM_CODEX_ACCOUNT_ID: a managed id points at that account's private home
// (its own auth.json + thread DB); the SYSTEM account (no id) is written EXPLICITLY so it
// overwrites any managed scope a parent tmux server leaked in, rather than silently acting as
- // the wrong login. The missing-explicit-account case already refused in spawnNew (fail-closed,
+ // the wrong login. Note this write lands on the CLIENT env — on a shared tmux server it only
+ // reaches the session because both names are in ACCOUNT_SCOPE_UPDATE_ENV (before that, the
+ // overwrite-the-leak promise held only for the client that happened to START the server; #419).
+ // The missing-explicit-account case already refused in spawnNew (fail-closed,
// property 4), so `codexSessionEnv` here never resolves an explicit id to the system home. Also
- // strip env vars that would shadow the account's OAuth login with API-key auth. Remote (ssh)
- // Codex sessions get this via the remote tmux `-e` list, not the local ssh client env.
+ // strip env vars that would shadow the account's OAuth login with API-key auth.
if (needsCodexAccountScope(options.agentId, options.accountId, (id) => this.isCodexAccount(id)) && !options.sshRemote) {
const codexScope = codexSessionEnv(platform().userDataDir, options.accountId)
env.CODEX_HOME = codexScope.CODEX_HOME
@@ -2894,7 +2928,15 @@ export class PtyManager {
// The project's keys need the same treatment for the same reason: their VALUES are in this
// tmux client's process env (merged above) and must reach the session without ever appearing
// on the long-lived client's argv.
- this.ensureUpdateEnvKeys([...Object.keys(customEnvMerged), ...Object.keys(projectEnv ?? {})])
+ // The account-scope names lead the list for the LONG-LIVED server case (#419): the conf is
+ // read once at server start, so a server started by a pre-fix app keeps its old
+ // update-environment array forever — these appends are what retrofit it before this
+ // session is created. A fresh server already has them from the conf (the append dedupes).
+ this.ensureUpdateEnvKeys([
+ ...ACCOUNT_SCOPE_UPDATE_ENV,
+ ...Object.keys(customEnvMerged),
+ ...Object.keys(projectEnv ?? {})
+ ])
const attachFlags = tmuxAttachFlags(!!sinks)
args = [
'-L',
diff --git a/src/core/tmux-conf.test.ts b/src/core/tmux-conf.test.ts
index 23ccded89..ca5d61db9 100644
--- a/src/core/tmux-conf.test.ts
+++ b/src/core/tmux-conf.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest'
-import { tmuxConf } from './pty-manager'
+import { ACCOUNT_SCOPE_UPDATE_ENV, tmuxConf } from './pty-manager'
describe('tmuxConf', () => {
const c = tmuxConf(50000)
@@ -54,4 +54,19 @@ describe('tmuxConf', () => {
expect(tmuxConf(10)).toContain('set -g history-limit 1000')
expect(c).toContain('set -g history-limit 50000')
})
+
+ it('lists every account-scope env name in update-environment (issue #419)', () => {
+ // The REMOVAL half of update-environment's contract is the fix: the shared server's global
+ // env is inherited from whichever client STARTED it, so without these names a server seeded
+ // by a managed-account client leaked that account's CLAUDE_CONFIG_DIR into every session
+ // created without a `-e` override — system-account nodes silently ran as a managed account.
+ const line = c.split('\n').find((l) => l.startsWith('set -g update-environment '))
+ expect(line).toBeDefined()
+ for (const name of ACCOUNT_SCOPE_UPDATE_ENV) expect(line).toContain(name)
+ // Deduped: the overlap names (ANTHROPIC_AUTH_TOKEN is in the gateway list AND the claude
+ // auth strip; OPENAI_API_KEY likewise) must appear exactly once.
+ for (const dup of ['ANTHROPIC_AUTH_TOKEN', 'OPENAI_API_KEY']) {
+ expect(line!.split(dup).length - 1).toBe(1)
+ }
+ })
})
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 39a527a2b..e959ccec0 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -3847,7 +3847,9 @@ export function Canvas() {
agentId: AgentId,
center?: { x: number; y: number },
groupId?: string,
- accountId?: string,
+ // `null` = the user EXPLICITLY picked the System account row: resolveNewNodeAccount then
+ // skips the project default instead of treating the pick as "no pick" (#419).
+ accountId?: string | null,
initialPrompt?: string
) => {
const project = useProjects.getState().getProject(activeProjectId)
@@ -3859,7 +3861,7 @@ export function Canvas() {
let account: string | undefined
if (agentId === 'codex') {
const decision = resolveNewCodexNodeAccount(
- accountId,
+ accountId ?? undefined,
useSettings.getState().settings.codexAccounts,
connectedProjectIdForHost
)
@@ -6820,8 +6822,10 @@ export function Canvas() {
)
return [
...BUILTIN_AGENT_IDS.filter((aid) => !disabled.includes(aid)).map((aid): MenuItem => {
- // Claude gets an account picker submenu when ≥1 account exists; System = project
- // default (resolved). Other agents stay flat (accounts are Claude-only).
+ // Claude gets an account picker submenu when ≥1 account exists. The System row is an
+ // EXPLICIT pick (`null`), never "no pick": before that distinction, clicking the row
+ // labelled with the user's system email launched the PROJECT DEFAULT managed account
+ // (#419). Other agents stay flat (accounts are Claude-only).
if (aid === 'claude' && (accounts.length > 0 || accountsHint)) {
return {
type: 'submenu',
@@ -6831,7 +6835,7 @@ export function Canvas() {
{
label: withDefaultMark(systemLabel),
icon: <AgentIcon agentId="claude" />,
- onClick: () => addAgentNode('claude', at, groupId)
+ onClick: () => addAgentNode('claude', at, groupId, null)
},
...accounts.map(
(a): MenuItem => ({
diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.ts
index c3fdbcd4a..39b635880 100644
--- a/src/renderer/state/workspace.test.ts
+++ b/src/renderer/state/workspace.test.ts
@@ -550,6 +550,37 @@ describe('resolveNewNodeAccount', () => {
expect(resolveNewNodeAccount(undefined, {}, accounts)).toBeUndefined())
it('undefined when the project is undefined', () =>
expect(resolveNewNodeAccount(undefined, undefined, accounts)).toBeUndefined())
+ // #419 — the "picked X, ran as Y" legs.
+ it('null = the EXPLICIT System pick — it must not resolve to the project default (#419)', () =>
+ // Before null existed, the submenu's System row (labelled with the system email) passed
+ // "no account", which this resolver read as "apply the project default".
+ expect(resolveNewNodeAccount(null, { defaultAccountId: 'a1' }, accounts)).toBeUndefined())
+ it('a PENDING default never stamps its id — its dir exists but holds no login (#419)', () =>
+ expect(
+ resolveNewNodeAccount(
+ undefined,
+ { defaultAccountId: 'p1' },
+ [...accounts, { id: 'p1', label: 'new account', createdAt: 0, pending: true }]
+ )
+ ).toBeUndefined())
+ it("a default pinned to another machine's host never lands on a LOCAL project (#419)", () =>
+ // Its config dir exists only on that host, so locally the spawn would fall into the
+ // missing-dir fallback — and pre-fix, from there into whatever the shared tmux server held.
+ expect(
+ resolveNewNodeAccount(
+ undefined,
+ { defaultAccountId: 'r1' },
+ [{ id: 'r1', label: 'server', createdAt: 0, host: 'u@h' }]
+ )
+ ).toBeUndefined())
+ it('an SSH project keeps its own host-matched account', () =>
+ expect(
+ resolveNewNodeAccount(
+ 'r1',
+ { ssh: { server: { host: 'h', user: 'u' } } },
+ [{ id: 'r1', label: 'server', createdAt: 0, host: 'u@h' }]
+ )
+ ).toBe('r1'))
})
describe('accountId on Claude node factories', () => {
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index 406908004..2dfbb5f07 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -524,15 +524,32 @@ export function sshAccountsHint(
: null
}
-/** Account for a NEW Claude node: explicit pick, else the project default, else system. */
+/**
+ * Account for a NEW Claude node: explicit pick, else the project default, else system.
+ *
+ * `explicit === null` is an EXPLICIT "System account" pick and short-circuits past the project
+ * default. Before it existed, the submenu row wearing the user's system email launched the
+ * PROJECT DEFAULT account — the clearest "picked X, ran as Y" in issue #419 — because "no
+ * account passed" and "system picked" were the same value.
+ *
+ * Validation runs against the accounts ELIGIBLE for this project (`accountsForProject`), not the
+ * raw list, mirroring what every picker offers. The raw list also holds `pending` rows (their dir
+ * exists but no login lives in it yet) and accounts pinned to ANOTHER machine's host (their dir
+ * exists only over there) — a `defaultAccountId` pointing at either used to be stamped onto the
+ * node, whose spawn then fell into the missing/empty-dir fallback and silently ran under a
+ * different identity (#419 again). Ineligible ⇒ undefined ⇒ the honest system default.
+ */
export function resolveNewNodeAccount(
- explicit: string | undefined,
- project: { defaultAccountId?: string } | undefined,
+ explicit: string | null | undefined,
+ project:
+ | { defaultAccountId?: string; ssh?: { server: { host: string; user: string } } }
+ | undefined,
accounts: ClaudeAccount[]
): string | undefined {
+ if (explicit === null) return undefined
const id = explicit ?? project?.defaultAccountId
// A stale default (account since removed) must not stamp dead ids onto new nodes.
- return id && accounts.some((a) => a.id === id) ? id : undefined
+ return id && accountsForProject(accounts, project).some((a) => a.id === id) ? id : undefined
}
/**
diff --git a/src/shared/agents/model-gateway.ts b/src/shared/agents/model-gateway.ts
index 750561e53..1c9aca3ce 100644
--- a/src/shared/agents/model-gateway.ts
+++ b/src/shared/agents/model-gateway.ts
@@ -202,9 +202,17 @@ const TMUX_STOCK_UPDATE_ENV = [
* argv-free credential path: gateway values sit in the tmux CLIENT's process environment (never
* on a command line), and tmux copies the listed names into the session env on create/attach —
* MEASURED on tmux 3.4: the pane sees the value, a client withOUT the var strips it from its own
- * session (no cross-session bleed into plain terminals), and re-sourcing the conf is idempotent. */
-export function tmuxUpdateEnvironmentLine(): string {
- return `set -g update-environment "${[...TMUX_STOCK_UPDATE_ENV, ...MODEL_GATEWAY_ENV_KEYS].join(' ')}"`
+ * session (no cross-session bleed into plain terminals), and re-sourcing the conf is idempotent.
+ *
+ * `extraNames` lets the LOCAL conf append the account-scope names (`ACCOUNT_SCOPE_UPDATE_ENV` in
+ * pty-manager — issue #419): the REMOTE conf must NOT get them, because a remote session's
+ * account env arrives only via `-e` (the ssh-exec'd tmux client's own env is the login shell's,
+ * so listing the names there would have the copy/strip run against the WRONG environment).
+ * Deduped so an overlap (e.g. ANTHROPIC_AUTH_TOKEN, in both the gateway list and the claude
+ * auth strip) cannot double an entry. */
+export function tmuxUpdateEnvironmentLine(extraNames: readonly string[] = []): string {
+ const names = [...new Set([...TMUX_STOCK_UPDATE_ENV, ...MODEL_GATEWAY_ENV_KEYS, ...extraNames])]
+ return `set -g update-environment "${names.join(' ')}"`
}
export function modelGatewayEnv(
diff --git a/src/shared/ssh.test.ts b/src/shared/ssh.test.ts
index b971798b0..46282b873 100644
--- a/src/shared/ssh.test.ts
+++ b/src/shared/ssh.test.ts
@@ -284,6 +284,17 @@ describe('remoteTmuxConf', () => {
expect(remoteTmuxConf(10)).toContain('set -g history-limit 1000')
expect(remoteTmuxConf(50000)).toContain('set -g history-limit 50000')
})
+ it('does NOT list the account-scope names in update-environment (they are LOCAL-conf only)', () => {
+ // A remote session's account env arrives via `-e` on the ssh-exec'd create; the attaching
+ // client's own env is the remote LOGIN SHELL's, which never carries our account dirs. Listing
+ // the names here would make every reattach copy/strip against that wrong environment —
+ // stripping a managed remote account's CLAUDE_CONFIG_DIR out of its own session. The local
+ // conf lists them (ACCOUNT_SCOPE_UPDATE_ENV in pty-manager, issue #419); this pin is what
+ // keeps a future "unify the two confs" cleanup from exporting the fix to the wrong side.
+ for (const name of ['CLAUDE_CONFIG_DIR', 'CODEX_HOME', 'NODETERM_CODEX_ACCOUNT_ID']) {
+ expect(c).not.toContain(name)
+ }
+ })
})
describe('remoteTmuxCommand confPath', () => {