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(ssh): honor IdentityAgent SSH_AUTH_SOCK despite the app-private agent (#427)
enes245381d2ea0e
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 6e9190e78..a24c49c37 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -38,6 +38,7 @@ import {remoteTerminateForegroundArgs,remotePaneCursorArgs} from './remote-ssh/control-master'+import { probeAgentSockToPin } from './remote-ssh/agent-probe'import { parsePaneCursor } from './pane-cursor'import {recordFreshSpawnOwner,@@ -2119,6 +2120,28 @@ export class PtyManager {// `ownerProjectId` — and no cwd, agent, account or hook env either. A mirrored client that// lands on a re-created session gets the same bare login shell it got before this feature.const projectOverrides = await this.projectSpawnOverrides(options)+ // Resolved HERE for the same synchronous-spawnSession reason as projectOverrides — and the+ // relay host's detached callers pass no `sshRemote` at all, so this is the one path that needs+ // it. Re-derive the login-agent pin for the endpoint (issue #427): same memoized `ssh -G`+ // probe the ControlMaster's connect uses, and it OVERWRITES any inbound value — `sshRemote` is+ // renderer-built and its conn can descend from a shareable project file, so only the local+ // probe may decide which agent socket the argv builders pin. The annotated conn is what the+ // session stores, so every later remote op (capture, sendText, remote git) rides the same+ // answer. Fail-open: a failed probe ⇒ undefined ⇒ the pre-#427 command lines.+ if (options.sshRemote) {+ options = {+ ...options,+ sshRemote: {+ ...options.sshRemote,+ conn: {+ ...options.sshRemote.conn,+ identityAgentSock: await probeAgentSockToPin(options.sshRemote.conn).catch(+ () => undefined+ )+ }+ }+ }+ }const sessionId = this.spawnSession(options,clientId,diff --git a/src/core/remote-ssh/agent-probe.test.ts b/src/core/remote-ssh/agent-probe.test.tsnew file mode 100644index 000000000..b0cd7037b--- /dev/null+++ b/src/core/remote-ssh/agent-probe.test.ts@@ -0,0 +1,177 @@+import { execFile } from 'child_process'+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'fs'+import os from 'os'+import path from 'path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import {+ agentSockToPin,+ clearAgentProbeCache,+ parseIdentityAgent,+ probeAgentSockToPin,+ probeArgs+} from './agent-probe'+import type { SshConnection } from '../../shared/ssh'++const conn: SshConnection = { host: 'h.example.com', user: 'deploy', port: 2222 }+const AMBIENT = '/tmp/launchd.abc/Listeners'++beforeEach(() => clearAgentProbeCache())++describe('parseIdentityAgent', () => {+ // Every shape below was measured against a real `ssh -G` (OpenSSH 9.6) — see agent-probe.ts.+ it('reads the identityagent line verbatim', () => {+ expect(parseIdentityAgent('user deploy\nidentityagent SSH_AUTH_SOCK\nport 22\n')).toBe(+ 'SSH_AUTH_SOCK'+ )+ expect(parseIdentityAgent('identityagent $MYVAR\n')).toBe('$MYVAR')+ expect(parseIdentityAgent('identityagent /tmp/some.sock\n')).toBe('/tmp/some.sock')+ expect(parseIdentityAgent('identityagent none\n')).toBe('none')+ })+ it('returns undefined when the line is absent (OpenSSH omits it when unset — measured)', () => {+ expect(parseIdentityAgent('user deploy\nhostname h\nport 22\n')).toBeUndefined()+ })+ it('does not match a value that merely CONTAINS the word (e.g. a banner line)', () => {+ expect(parseIdentityAgent('remotecommand echo identityagent SSH_AUTH_SOCK\n')).toBeUndefined()+ })+})++describe('agentSockToPin', () => {+ it('pins for the env-reference spellings — the shapes the app-agent env override breaks', () => {+ // `IdentityAgent SSH_AUTH_SOCK` and `$SSH_AUTH_SOCK` are connect-time env reads; under our+ // SSH_AUTH_SOCK override they resolve to the app-private agent instead of the login agent.+ expect(agentSockToPin('SSH_AUTH_SOCK', AMBIENT)).toBe(AMBIENT)+ expect(agentSockToPin('$SSH_AUTH_SOCK', AMBIENT)).toBe(AMBIENT)+ })+ it('pins when the resolved value equals the ambient socket (the ${SSH_AUTH_SOCK} parse-time form)', () => {+ // `${SSH_AUTH_SOCK}` expands at config-PARSE time, so the probe (run with the ambient env)+ // sees the ambient path itself. Pinning an identical literal is also a no-op, so equality is+ // safe for both readings.+ expect(agentSockToPin(AMBIENT, AMBIENT)).toBe(AMBIENT)+ })+ it('leaves everything else alone: none, unrelated literal, other env vars, absent line', () => {+ expect(agentSockToPin('none', AMBIENT)).toBeUndefined()+ expect(agentSockToPin('/tmp/other.sock', AMBIENT)).toBeUndefined()+ // `$MYVAR` reads a variable we never touch — the child inherits it correctly already.+ expect(agentSockToPin('$MYVAR', AMBIENT)).toBeUndefined()+ expect(agentSockToPin(undefined, AMBIENT)).toBeUndefined()+ })+ it('never pins without an ambient socket, or an ambient value unsafe as one -o token', () => {+ expect(agentSockToPin('SSH_AUTH_SOCK', undefined)).toBeUndefined()+ expect(agentSockToPin('SSH_AUTH_SOCK', '')).toBeUndefined()+ // ssh tokenizes the -o value with its config parser: whitespace would split it. A relative+ // path is no login-agent socket. Fail open (no pin) rather than emit a broken option.+ expect(agentSockToPin('SSH_AUTH_SOCK', '/tmp/has space/agent.sock')).toBeUndefined()+ expect(agentSockToPin('SSH_AUTH_SOCK', 'relative/agent.sock')).toBeUndefined()+ })+})++describe('probeArgs', () => {+ it('mirrors the master argv facts: -G + port + identity file + destination, no extraArgs', () => {+ expect(probeArgs({ ...conn, identityFile: '/k/id' })).toEqual([+ '-G',+ '-p',+ '2222',+ '-i',+ '/k/id',+ ])+ expect(probeArgs(conn)).toEqual(['-G', '-p', '2222', '[email protected]'])+ })+})++describe('probeAgentSockToPin', () => {+ it('answers from the injected runner and memoizes per endpoint', async () => {+ let calls = 0+ const run = async (): Promise<string> => {+ calls+++ return 'identityagent SSH_AUTH_SOCK\n'+ }+ const env = { SSH_AUTH_SOCK: AMBIENT }+ expect(await probeAgentSockToPin(conn, { run, env })).toBe(AMBIENT)+ expect(await probeAgentSockToPin(conn, { run, env })).toBe(AMBIENT)+ expect(calls).toBe(1)+ // A different endpoint probes on its own.+ expect(await probeAgentSockToPin({ ...conn, host: 'other' }, { run, env })).toBe(AMBIENT)+ expect(calls).toBe(2)+ })+ it('skips the subprocess entirely when there is no ambient agent', async () => {+ let calls = 0+ const run = async (): Promise<string> => {+ calls+++ return 'identityagent SSH_AUTH_SOCK\n'+ }+ expect(await probeAgentSockToPin(conn, { run, env: {} })).toBeUndefined()+ expect(calls).toBe(0)+ })+ it('a failed probe answers undefined — the pre-#427 command line, never a blocked connect', async () => {+ const run = async (): Promise<string> => {+ throw new Error('ssh -G blew up')+ }+ await expect(+ probeAgentSockToPin(conn, { run, env: { SSH_AUTH_SOCK: AMBIENT } })+ ).resolves.toBeUndefined()+ })+ it('re-probes after the TTL so a config fix lands on the next reconnect', async () => {+ let calls = 0+ let t = 0+ const run = async (): Promise<string> => {+ calls+++ return 'identityagent SSH_AUTH_SOCK\n'+ }+ const deps = { run, env: { SSH_AUTH_SOCK: AMBIENT }, now: () => t }+ await probeAgentSockToPin(conn, deps)+ t = 20_000+ await probeAgentSockToPin(conn, deps)+ expect(calls).toBe(2)+ })+})++// The probe's real substrate is `ssh -G` output, and the -G dialect is OpenSSH's, not ours — so+// run the REAL binary against a fixture config (same discipline as remote-claude-usage.test.ts+// running its generated sh for real). `-F` pins the config; ssh resolves ~/.ssh/config off+// pw_dir, so HOME games would not isolate it.+const realSsh = ['/usr/bin/ssh', '/usr/local/bin/ssh', '/opt/homebrew/bin/ssh'].find((p) =>+ existsSync(p)+)+describe.skipIf(!realSsh || process.platform === 'win32')('probe against a real ssh -G', () => {+ let dir: string+ let cfg: string+ beforeEach(() => {+ dir = mkdtempSync(path.join(os.tmpdir(), 'nt-agent-probe-'))+ cfg = path.join(dir, 'cfg')+ writeFileSync(+ cfg,+ [+ 'Host env-form',+ ' IdentityAgent SSH_AUTH_SOCK',+ 'Host literal-form',+ ' IdentityAgent /tmp/some.sock',+ 'Host plain',+ ''+ ].join('\n')+ )+ })+ afterEach(() => rmSync(dir, { recursive: true, force: true }))++ const runReal =+ (env: NodeJS.ProcessEnv) =>+ (args: string[]): Promise<string> =>+ new Promise((resolve, reject) => {+ // Splice the fixture config right after -G; the rest of the argv is the production shape.+ execFile(+ realSsh!,+ [args[0], '-F', cfg, ...args.slice(1)],+ { timeout: 5000, env },+ (err, stdout) => (err ? reject(err) : resolve(stdout ?? ''))+ )+ })++ it('pins a host whose config says IdentityAgent SSH_AUTH_SOCK, and only that host', async () => {+ const env = { ...process.env, SSH_AUTH_SOCK: AMBIENT }+ const probe = (host: string): Promise<string | undefined> =>+ probeAgentSockToPin({ host, user: 'u' }, { run: runReal(env), env })+ expect(await probe('env-form')).toBe(AMBIENT)+ expect(await probe('literal-form')).toBeUndefined()+ expect(await probe('plain')).toBeUndefined()+ })+})diff --git a/src/core/remote-ssh/agent-probe.ts b/src/core/remote-ssh/agent-probe.tsnew file mode 100644index 000000000..058fe965e--- /dev/null+++ b/src/core/remote-ssh/agent-probe.ts@@ -0,0 +1,159 @@+// Does this host's OWN ssh config route it at the agent named by the environment?+//+// Every ssh/scp this app spawns for an SSH project authenticates with `SSH_AUTH_SOCK` pointed at+// the app-private agent (src/main/remote-ssh/ssh-agent.ts), so an unlocked key is forgotten at+// quit. That override has one honest casualty (issue #427): OpenSSH's+//+// IdentityAgent SSH_AUTH_SOCK+//+// means "use the socket the environment variable names RIGHT NOW" — under our override that+// resolves back to the app-private agent, so the key sitting in the user's login agent is never+// offered and the connect fails `Permission denied`. A literal `IdentityAgent /path` is untouched+// (config beats env), so the ONLY broken shapes are the env-reference ones. All three were+// measured on OpenSSH 9.6:+// - `IdentityAgent SSH_AUTH_SOCK` → `ssh -G` prints the literal token `SSH_AUTH_SOCK`;+// resolved from the env at CONNECT time.+// - `IdentityAgent $SSH_AUTH_SOCK` → `-G` prints `$SSH_AUTH_SOCK`; connect-time env read.+// - `IdentityAgent ${SSH_AUTH_SOCK}` → expanded at CONFIG-PARSE time, so `-G` prints whatever+// the PROBE's env held — which is why the probe below runs with the AMBIENT env (the main+// process never mutates its own `SSH_AUTH_SOCK`), and why "resolved value equals the ambient+// socket" is part of the decision.+//+// The fix is a PIN, not an env change: when the effective config asks for the environment's+// agent, the argv builders (control-master.ts `agentArgs`) append+// `-o IdentityAgent=<ambient socket>`. A command-line `-o` is first-obtained and beats both the+// config line and the env, so the app-agent env override can stay exactly as it is everywhere —+// the user's EXPLICIT config choice wins for that host, nothing else changes. The decision rides+// `SshConnection.identityAgentSock`, which is derived HERE and only here: both annotation points+// (SshProjectManager.connect and PtyManager's remote spawn) OVERWRITE whatever value arrived on+// the wire, so a shared project.json or a canvas-sync peer can never point our ssh at a socket+// of their choosing.+//+// Fail-open in the pre-#427 direction: no ambient socket, an unreadable `ssh -G`, a timeout, or+// an identityagent value we do not recognise all yield `undefined` — the bare command, today's+// behavior, one passphrase prompt at worst. Never a blocked connect.+import { execFile } from 'child_process'+import path from 'path'+import { findExecutableSync } from '../exec-path'+import type { SshConnection } from '../../shared/ssh'++/** `ssh -G` may run the user's own `Match exec` commands; bound it so a hung one cannot stall a+ * connect. On timeout the probe fails open (no pin). */+const PROBE_TIMEOUT_MS = 3_000+/** Memo TTL: connects and node creates burst (a canvas of remote nodes = one create each), and+ * the answer only changes when the user edits ~/.ssh/config — short enough that a config fix is+ * picked up on the next reconnect without restarting the app. */+const PROBE_TTL_MS = 15_000++function findSsh(): string | null {+ return findExecutableSync('ssh', ['/usr/bin/ssh', '/usr/local/bin/ssh', '/opt/homebrew/bin/ssh'])+}++/** The `identityagent` line of an `ssh -G` dump, verbatim, or undefined when the effective config+ * sets none (OpenSSH omits the line entirely in that case — measured). */+export function parseIdentityAgent(sshGOutput: string): string | undefined {+ for (const line of sshGOutput.split('\n')) {+ const m = /^identityagent\s+(.*)$/i.exec(line.trim())+ if (m) return m[1].trim()+ }+ return undefined+}++/** A value safe to place after `-o IdentityAgent=` as ONE argv token. ssh parses the option value+ * with its config tokenizer, so whitespace would split it; a socket path is absolute on every+ * platform that has a login agent. Anything else → no pin (fail open). */+function isPinnableSock(sock: string): boolean {+ return path.isAbsolute(sock) && !/[\s\0]/.test(sock) && sock.length < 1024+}++/**+ * The pure decision: given the effective `identityagent` value and the ambient `SSH_AUTH_SOCK`,+ * the socket to pin — or undefined for "leave everything as it is". Pin exactly when the user's+ * config asks for the ENVIRONMENT's agent:+ * - the special token `SSH_AUTH_SOCK` or the env reference `$SSH_AUTH_SOCK` (connect-time reads+ * that our override would satisfy with the wrong socket), or+ * - a value equal to the ambient socket itself — which is what `${SSH_AUTH_SOCK}` looks like+ * after `-G`'s parse-time expansion, and what a literal path pointing at the same agent means+ * anyway (pinning an identical value is a no-op).+ * `none`, an unrelated literal path, `$OTHER_VAR` (the child inherits our unmodified copy of any+ * other variable) and an absent line all answer undefined.+ */+export function agentSockToPin(+ identityAgent: string | undefined,+ ambientSock: string | undefined+): string | undefined {+ if (!identityAgent || !ambientSock || !isPinnableSock(ambientSock)) return undefined+ if (identityAgent === 'SSH_AUTH_SOCK' || identityAgent === '$SSH_AUTH_SOCK') return ambientSock+ if (identityAgent === ambientSock) return ambientSock+ return undefined+}++/** The `-G` argv mirrors what the masters/children actually send (destination, port, identity+ * file), so `Host`/`Match` blocks resolve the same way. `extraArgs` is deliberately absent —+ * masterArgs/childArgs never splice it either. */+export function probeArgs(conn: SshConnection): string[] {+ return [+ '-G',+ '-p',+ String(conn.port ?? 22),+ ...(conn.identityFile ? ['-i', conn.identityFile] : []),+ `${conn.user}@${conn.host}`+ ]+}++export interface AgentProbeDeps {+ /** Run ssh with these args under this env, resolving stdout; reject/throw = probe failed. */+ run?: (args: string[], env: NodeJS.ProcessEnv) => Promise<string>+ /** The ambient environment (`SSH_AUTH_SOCK` untouched by the app — ssh-agent.ts only ever+ * publishes NODETERM_APP_AGENT_SOCK). Injectable for tests. */+ env?: NodeJS.ProcessEnv+ now?: () => number+}++function defaultRun(args: string[], env: NodeJS.ProcessEnv): Promise<string> {+ const ssh = findSsh()+ if (!ssh) return Promise.reject(new Error('ssh not found'))+ return new Promise((resolve, reject) => {+ execFile(+ ssh,+ args,+ { timeout: PROBE_TIMEOUT_MS, maxBuffer: 1024 * 1024, env },+ (err, stdout) => (err ? reject(err) : resolve(stdout ?? ''))+ )+ })+}++const cache = new Map<string, { at: number; value: Promise<string | undefined> }>()++/** Test-only: drop the memo so each case probes fresh. */+export function clearAgentProbeCache(): void {+ cache.clear()+}++function cacheKey(conn: SshConnection): string {+ return `${conn.user}\0${conn.host}\0${conn.port ?? 22}\0${conn.identityFile ?? ''}`+}++/**+ * The socket to pin for this connection, or undefined. Memoized per endpoint (TTL above) and+ * coalesced, so a burst of node creates costs one `ssh -G`. Never rejects.+ */+export function probeAgentSockToPin(+ conn: SshConnection,+ deps: AgentProbeDeps = {}+): Promise<string | undefined> {+ const env = deps.env ?? process.env+ const ambient = env.SSH_AUTH_SOCK+ // Nothing to pin without an ambient agent; skip the subprocess entirely.+ if (!ambient) return Promise.resolve(undefined)+ const now = deps.now ?? Date.now+ const key = cacheKey(conn)+ const hit = cache.get(key)+ if (hit && now() - hit.at < PROBE_TTL_MS) return hit.value+ const run = deps.run ?? defaultRun+ const value = run(probeArgs(conn), env)+ .then((out) => agentSockToPin(parseIdentityAgent(out), ambient))+ .catch(() => undefined)+ cache.set(key, { at: now(), value })+ return value+}diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.tsindex 27dae2855..4e38a8a56 100644--- a/src/core/remote-ssh/control-master.test.ts+++ b/src/core/remote-ssh/control-master.test.ts@@ -118,6 +118,41 @@ describe('masterArgs', () => {})})+describe('agent pin (identityAgentSock, issue #427)', () => {+ // A conn the `ssh -G` probe marked: this host's effective config says `IdentityAgent+ // SSH_AUTH_SOCK` (or equivalent), so the ambient login-agent socket is pinned on argv — a+ // command-line -o beats both the config line and the app-agent env override.+ const pinned = { ...conn, identityAgentSock: '/tmp/launchd.abc/Listeners' }++ it('masterArgs pins the login agent and drops the forced AddKeysToAgent', () => {+ const args = masterArgs(pinned, '/s.sock')+ expect(args.join(' ')).toContain('-o IdentityAgent=/tmp/launchd.abc/Listeners')+ // Forcing AddKeysToAgent=yes at a LOGIN agent would load an askpass-unlocked key into it+ // until logout — the exact leak the app-private agent exists to close. The user's own config+ // decides for a pinned host.+ expect(args).not.toContain('AddKeysToAgent=yes')+ })+ it('childArgs carries the pin too: the ControlMaster=auto fallback re-authenticates for real', () => {+ const args = childArgs(pinned, '/s.sock', 'tmux ls')+ expect(args.join(' ')).toContain('-o IdentityAgent=/tmp/launchd.abc/Listeners')+ expect(args.at(-1)).toBe('tmux ls')+ })+ it('scp up AND down carry the pin: scp re-authenticates when the master socket is gone', () => {+ expect(scpArgs(pinned, '/s.sock', '/l/f', '/r/f').join(' ')).toContain(+ '-o IdentityAgent=/tmp/launchd.abc/Listeners'+ )+ expect(scpDownArgs(pinned, '/s.sock', '/r/f', '/l/f').join(' ')).toContain(+ '-o IdentityAgent=/tmp/launchd.abc/Listeners'+ )+ })+ it('an unpinned conn is byte-identical to the pre-#427 argv (the exact-array tests above are the pin)', () => {+ // Belt and braces beside the toEqual pins: absence of the option, not just equality.+ for (const args of [masterArgs(conn, '/s.sock'), childArgs(conn, '/s.sock'), scpArgs(conn, '/s.sock', '/l', '/r')]) {+ expect(args.join(' ')).not.toContain('IdentityAgent=')+ }+ })+})+describe('childArgs', () => {it('muxes over the master socket, self-healing (auto + persist), and appends a remote command', () => {expect(childArgs(conn, '/s.sock', 'tmux ls')).toEqual([...childPrefix, '[email protected]', 'tmux ls'])diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex 3cc17a6ef..2003c649b 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -59,6 +59,18 @@ function identityArgs(conn: SshConnection): string[] {return conn.identityFile ? ['-o', 'IdentitiesOnly=yes', '-i', conn.identityFile] : []}+/**+ * Honor a config-level `IdentityAgent SSH_AUTH_SOCK` (issue #427). When the `ssh -G` probe+ * (agent-probe.ts) determined that this host's effective config routes it at the ENVIRONMENT's+ * agent, pin the user's ambient login-agent socket on the command line: a command-line `-o` is+ * first-obtained, so it beats both the config line (which would re-read our overridden env and+ * land back on the app-private agent) and the env override itself. Empty for every connection the+ * probe did not mark — byte-identical legacy argv.+ */+function agentArgs(conn: SshConnection): string[] {+ return conn.identityAgentSock ? ['-o', `IdentityAgent=${conn.identityAgentSock}`] : []+}+/** Args for the backgrounded multiplexing master (the one auth happens here). */export function masterArgs(conn: SshConnection, controlPath: string): string[] {const args = [@@ -126,8 +138,14 @@ export function masterArgs(conn: SshConnection, controlPath: string): string[] {// Harmless when no agent is reachable at all: ssh skips the add silently (measured: not one// stderr line, so nothing for lastSshErrorLine to mistake for a failure cause) and simply// prompts again next time.- '-o',- 'AddKeysToAgent=yes',+ //+ // OMITTED for a pinned-agent connection (agentArgs): there the designated agent is the user's+ // LOGIN agent, and forcing AddKeysToAgent=yes would load an askpass-unlocked key into it until+ // logout — the exact leak the app-private agent exists to close. The user's own ~/.ssh/config+ // decides for that host instead (and their key is normally already in that agent, which is why+ // they wrote `IdentityAgent SSH_AUTH_SOCK` in the first place).+ ...(conn.identityAgentSock ? [] : ['-o', 'AddKeysToAgent=yes']),+ ...agentArgs(conn),...portArgs(conn),...identityArgs(conn)]@@ -176,6 +194,10 @@ export function childArgs(conn: SshConnection, controlPath: string, remote?: str// identityArgs also pins the offer (IdentitiesOnly) so that same fallback cannot burn the// server's MaxAuthTries on unrelated agent keys; the agent still signs the pinned key, which// is the only way a tty-less child can use an ENCRYPTED key at all (it has no askpass wiring).+ // agentArgs matters in the same fallback case, for the same reason as masterArgs: the child's+ // env points at the app-private agent, and only the pin routes it back at the login agent the+ // user's config asked for.+ args.push(...agentArgs(conn))args.push(...identityArgs(conn))args.push(target(conn))if (remote !== undefined) args.push(remote)@@ -596,6 +618,7 @@ export function mkDirArgs(conn: SshConnection, controlPath: string, path: string* basenamed by the caller, and the path is absolute). scp uses `-P` (uppercase) for the port. */export function scpArgs(conn: SshConnection, controlPath: string, localPath: string, remotePath: string): string[] {const args = ['-o', 'ControlMaster=no', '-o', `ControlPath=${controlPath}`, '-o', 'BatchMode=yes', '-P', String(conn.port ?? 22)]+ args.push(...agentArgs(conn))args.push(...identityArgs(conn))args.push(localPath, `${conn.user}@${conn.host}:${remotePath}`)return args@@ -629,6 +652,7 @@ export function scpDownArgs(recursive = false): string[] {const args = ['-o', 'ControlMaster=no', '-o', `ControlPath=${controlPath}`, '-o', 'BatchMode=yes', '-P', String(conn.port ?? 22)]+ args.push(...agentArgs(conn))args.push(...identityArgs(conn))if (recursive) args.push('-r')args.push(`${conn.user}@${conn.host}:${remoteScpPath(remotePath)}`, localPath)diff --git a/src/main/remote-ssh/ssh-agent.ts b/src/main/remote-ssh/ssh-agent.tsindex 642f7138e..b5c319cfe 100644--- a/src/main/remote-ssh/ssh-agent.ts+++ b/src/main/remote-ssh/ssh-agent.ts@@ -23,6 +23,12 @@// `IdentityAgent` in ~/.ssh/config overrides `SSH_AUTH_SOCK` and is the documented setup for// them; ssh-project.ts surfaces an error hint naming IdentityAgent for the rest (a hint, not// a retry - see connectOnce's failure tail for why retrying on the ambient agent is wrong).+// CAVEAT (issue #427): the ENV-REFERENCE spellings — `IdentityAgent SSH_AUTH_SOCK` and+// friends — resolve through the very variable this file overrides, so "config overrides env"+// is false for exactly those users. They are honored anyway: an `ssh -G` probe+// (core/remote-ssh/agent-probe.ts) detects them per host and the argv builders pin the+// ambient socket with `-o IdentityAgent=…`, which beats both the config line and this+// override. This env override itself stays unconditional — read that file before touching it.//// The agent runs in the FOREGROUND (`-D`) as a direct child, so `kill()` really ends it (the// default double-forks away and would survive us), and with a default identity lifetime (`-t`)diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.tsindex 20c787404..04318bb52 100644--- a/src/main/remote-ssh/ssh-project.test.ts+++ b/src/main/remote-ssh/ssh-project.test.ts@@ -44,6 +44,36 @@ describe('SshProjectManager', () => {expect(spawnMaster).toHaveBeenCalledTimes(1)})+ it('pins the login agent on the master argv when the probe marks the endpoint (issue #427)', async () => {+ const statuses: string[] = []+ const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn() }))+ const mgr = new SshProjectManager({+ userDataDir: '/ud',+ spawnMaster,+ run: vi.fn(async () => ({ code: 0, stdout: '' })),+ runScp: vi.fn(async () => ({ code: 0 })),+ getHook: () => ({ port: 1, token: 't', version: '1' }),+ onStatus: (e) => statuses.push(e.status),+ probeAgentSock: async () => '/tmp/launchd.x/Listeners'+ })+ await mgr.connect('p1', conn)+ const args = ((spawnMaster.mock.calls[0] as unknown[])[0] as string[]).join(' ')+ expect(args).toContain('-o IdentityAgent=/tmp/launchd.x/Listeners')+ expect(args).not.toContain('AddKeysToAgent=yes')+ // The stored conn carries the pin, so every later childArgs consumer rides the same answer.+ expect(mgr.refForProject('p1')?.conn.identityAgentSock).toBe('/tmp/launchd.x/Listeners')+ })++ it('strips an INBOUND identityAgentSock: only the local probe may aim ssh at an agent socket', async () => {+ // conn descends from IPC (and its ancestors from a shareable project file); without the probe+ // dep the annotation must overwrite a smuggled value with undefined, not honor it.+ const { mgr, spawnMaster } = makeMgr()+ await mgr.connect('p1', { ...conn, identityAgentSock: '/tmp/evil.sock' } as SshConnection)+ const args = ((spawnMaster.mock.calls[0] as unknown[])[0] as string[]).join(' ')+ expect(args).not.toContain('IdentityAgent=')+ expect(mgr.refForProject('p1')?.conn.identityAgentSock).toBeUndefined()+ })+it('listDir parses remote dir entries', async () => {const { mgr } = makeMgr()await mgr.connect('p1', conn)diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 866ea706a..71e7448b7 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -42,6 +42,7 @@ import {import { setRemoteSessionEnvWriter } from '../../core/remote-ssh/session-env'import { askpassServer } from './ssh-askpass'import { appSshAgent } from './ssh-agent'+import { probeAgentSockToPin } from '../../core/remote-ssh/agent-probe'import { sessionName } from '../../core/tmux-naming'import { remoteAtomicWrite } from '../remote-atomic-write'import { buildCodexLauncherScript } from '../../core/codex-identity-proxy'@@ -99,6 +100,12 @@ interface Runners {* reject) at each spawn site rather than at the top of `connect()`, which must stay synchronous* through `inFlight.set` or concurrent connects stop coalescing. */ensureAgent?: () => Promise<void>+ /** Resolve the login-agent socket to pin for this endpoint (issue #427): the `ssh -G` probe in+ * core/remote-ssh/agent-probe.ts, injected so the manager stays testable. connectOnce OVERWRITES+ * `conn.identityAgentSock` with this answer (or undefined when the dep is absent / fails), so an+ * inbound value can never survive to the argv builders. Optional: absent ⇒ no pin ⇒ the+ * byte-identical legacy command lines. */+ probeAgentSock?: (conn: SshConnection) => Promise<string | undefined>/** The last SSH connection just went away through a user-facing disconnect. Production schedules* the app-private agent's shutdown, which is what "forget the key" actually means. */onIdle?: () => void@@ -484,6 +491,16 @@ export class SshProjectManager {remoteCwd?: string,ticket?: symbol): Promise<ConnectResult> {+ // Re-derive the login-agent pin for THIS endpoint (issue #427) — a config-level `IdentityAgent+ // SSH_AUTH_SOCK` must reach the user's login agent despite the app-agent env override. The+ // inbound value is unconditionally overwritten: `conn` arrives over IPC (and its ancestors from+ // a shareable project file), and only the local `ssh -G` probe may decide which socket our ssh+ // is pointed at. Fail-open: no dep, no ambient agent, or a failed probe ⇒ undefined ⇒ the+ // pre-#427 command lines, byte for byte.+ conn = {+ ...conn,+ identityAgentSock: await this.r.probeAgentSock?.(conn).catch(() => undefined)+ }const existing = this.conns.get(projectId)if (existing && !sameEndpoint(existing.conn, conn)) {// The project now points at a DIFFERENT endpoint/identity. `-O check` below would happily@@ -844,7 +861,7 @@ export class SshProjectManager {!cancelled &&/permission denied/i.test(stderr ?? '') &&!(this.r.askpassAsked?.(master.pid?.()) ?? false)- ? ' nodeterm authenticates through its own ssh-agent, so a key held only in your system agent is not offered. Set IdentityAgent in ~/.ssh/config, or give this server an identity file.'+ ? ' nodeterm authenticates through its own ssh-agent, so a key held only in your system agent is not offered. Set IdentityAgent for this host in ~/.ssh/config (e.g. "IdentityAgent SSH_AUTH_SOCK" to use your login agent), or give this server an identity file.': ''const message = cancelled? 'SSH connection cancelled: this key needs its passphrase.'@@ -2247,6 +2264,10 @@ export function initSshProject(...appSshAgent.env()}),ensureAgent: () => appSshAgent.start(),+ // The `ssh -G` probe that honors a config-level `IdentityAgent SSH_AUTH_SOCK` (issue #427):+ // shared with the pty spawn path in core, so the master and the fallback children can never+ // disagree about which agent a host is routed at.+ probeAgentSock: (conn) => probeAgentSockToPin(conn),// The last SSH project was disconnected by the user: forget the unlocked key (after a grace,// see scheduleStop — the connect dialog's throwaway browse master disconnects right before the// real project connects).diff --git a/src/shared/ssh.ts b/src/shared/ssh.tsindex 291fa9834..7f362d5be 100644--- a/src/shared/ssh.ts+++ b/src/shared/ssh.ts@@ -26,6 +26,16 @@ export interface SshConnection {* untrusted document is not. See `stripLocalExecArgs`.*/execTrusted?: boolean+ /**+ * DERIVED, in memory only (issue #427): the ambient login-agent socket to pin via+ * `-o IdentityAgent=<path>` because the host's own effective ssh config says+ * `IdentityAgent SSH_AUTH_SOCK` (or an equivalent env reference) — which under the app-private+ * agent's env override would resolve to the WRONG agent. Set exclusively by the `ssh -G` probe+ * (`core/remote-ssh/agent-probe.ts`); both annotation points (SshProjectManager.connect,+ * PtyManager's remote spawn) OVERWRITE any inbound value, so a shared project.json or a+ * canvas-sync peer cannot aim our ssh at a socket of their choosing. Never persisted.+ */+ identityAgentSock?: string/** Display label, copied from the saved server when the node is created. */label?: string}