Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(accounts): host-scoped remote SSH accounts
enes5e96fc79de23
diff --git a/src/main/claude-accounts-core.test.ts b/src/main/claude-accounts-core.test.tsindex c1b7d2368..343f58f8d 100644--- a/src/main/claude-accounts-core.test.ts+++ b/src/main/claude-accounts-core.test.ts@@ -1,6 +1,8 @@import { describe, expect, it } from 'vitest'import {accountConfigDir,+ remoteAccountConfigDir,+ remoteAccountConfigDirAbs,claudeKeychainService,usageCredsPaths,AUTH_ENV_STRIP,@@ -23,6 +25,33 @@ describe('accountConfigDir', () => {})})+describe('remoteAccountConfigDir', () => {+ it('is a ~-relative path under .nodeterm/claude-accounts (leading ~ for ssh expansion)', () => {+ expect(remoteAccountConfigDir('a1')).toBe('~/.nodeterm/claude-accounts/a1')+ })+ it('rejects ids that could traverse out of the remote root', () => {+ expect(() => remoteAccountConfigDir('../evil')).toThrow()+ expect(() => remoteAccountConfigDir('a/b')).toThrow()+ expect(() => remoteAccountConfigDir('')).toThrow()+ })+})++describe('remoteAccountConfigDirAbs', () => {+ it('joins the resolved remote $HOME with the account dir (absolute for tmux -e)', () => {+ expect(remoteAccountConfigDirAbs('/home/bob', 'a1')).toBe(+ '/home/bob/.nodeterm/claude-accounts/a1'+ )+ })+ it('tolerates a trailing slash on the remote home', () => {+ expect(remoteAccountConfigDirAbs('/home/bob/', 'a1')).toBe(+ '/home/bob/.nodeterm/claude-accounts/a1'+ )+ })+ it('rejects traversing ids', () => {+ expect(() => remoteAccountConfigDirAbs('/home/bob', '../evil')).toThrow()+ })+})+describe('claudeKeychainService', () => {// Claude Code ≥ 2.1 scopes the macOS Keychain service per config dir:// 'Claude Code-credentials-' + first 8 hex chars of sha256(configDir).diff --git a/src/main/claude-accounts-core.ts b/src/main/claude-accounts-core.tsindex a5df4a370..36f02092a 100644--- a/src/main/claude-accounts-core.ts+++ b/src/main/claude-accounts-core.ts@@ -3,14 +3,43 @@import { createHash } from 'crypto'import path from 'path'-/** Root-relative config dir for a managed account. Rejects ids that could escape the root. */-export function accountConfigDir(userDataPath: string, accountId: string): string {- if (!/^[A-Za-z0-9_-]+$/.test(accountId)) {+/** Shape of a valid account id (uuid / opaque token). Shared by every path builder so a bad id+ * can never traverse out of the accounts root — locally OR on a remote host over ssh. */+const ACCOUNT_ID_RE = /^[A-Za-z0-9_-]+$/+function assertAccountId(accountId: string): void {+ if (!ACCOUNT_ID_RE.test(accountId)) {throw new Error(`invalid account id: ${JSON.stringify(accountId)}`)}+}++/** Root-relative config dir for a managed account. Rejects ids that could escape the root. */+export function accountConfigDir(userDataPath: string, accountId: string): string {+ assertAccountId(accountId)return path.join(userDataPath, 'claude-accounts', accountId)}+/**+ * Remote (SSH) config dir for a managed account, relative to the remote `$HOME` as a `~`-prefixed+ * path (`~/.nodeterm/claude-accounts/<id>`). Used for ssh EXEC args (mkdir / cat / rm), where+ * `quoteRemotePath` leaves the leading `~` unquoted so the remote shell expands it. NOT for tmux+ * `-e` (tmux does not shell-expand values — use `remoteAccountConfigDirAbs` there). Id-validated so+ * a hostile id can never escape `~/.nodeterm/claude-accounts/` on the remote host.+ */+export function remoteAccountConfigDir(accountId: string): string {+ assertAccountId(accountId)+ return `~/.nodeterm/claude-accounts/${accountId}`+}++/**+ * Absolute remote config dir for a managed account, given the resolved remote `$HOME`. Needed for+ * the tmux `-e CLAUDE_CONFIG_DIR=…` env: tmux copies the value literally (no `$HOME`/`~` expansion),+ * so the path must already be absolute. `remoteHome` is the connection's cached `$HOME`.+ */+export function remoteAccountConfigDirAbs(remoteHome: string, accountId: string): string {+ assertAccountId(accountId)+ return `${remoteHome.replace(/\/+$/, '')}/.nodeterm/claude-accounts/${accountId}`+}+/*** Transcript root for a session lookup: an account's `projects` dir under its config dir, or* the system default `~/.claude/projects` when no account. Pure path math (no fs) — the impurediff --git a/src/main/claude-accounts.ts b/src/main/claude-accounts.tsindex af9f38a31..bce4bfed9 100644--- a/src/main/claude-accounts.ts+++ b/src/main/claude-accounts.ts@@ -11,6 +11,7 @@ import { IPC } from '../shared/ipc'import { accountConfigDir, isSupportedClaudeVersion, parseLoginCapture } from './claude-accounts-core'import { installClaudeHooksInto } from './agents/hooks/claude'import { findInLoginPath } from './pty-manager'+import type { SshProjectManager } from './remote-ssh/ssh-project'const execFileP = promisify(execFile)const LOGIN_POLL_MS = 2000@@ -20,6 +21,16 @@ export function claudeConfigDirFor(accountId: string): string {return accountConfigDir(app.getPath('userData'), accountId)}+/**+ * Optional per-call SSH context. When `projectId` is present AND that project has a live+ * ControlMaster, the account is a REMOTE one: its config dir + login capture + removal happen on the+ * host over ssh instead of on the local filesystem. The renderer passes it only for accounts scoped+ * to an SSH project (`ClaudeAccount.host`); local accounts omit it entirely (unchanged behavior).+ */+interface AccountCtx {+ projectId?: string+}+const waiters = new Map<string, { cancelled: boolean }>()async function checkClaudeVersion(): Promise<boolean> {@@ -33,9 +44,29 @@ async function checkClaudeVersion(): Promise<boolean> {}}-export function initClaudeAccounts(): void {- ipcMain.handle(IPC.claudeAccountsAdd, async () => {+/**+ * @param getSshManager Lazily resolves the SSH project manager (created after this init in index.ts).+ * Returns undefined when SSH isn't wired — every remote path then falls back to local behavior.+ */+export function initClaudeAccounts(getSshManager?: () => SshProjectManager | undefined): void {+ // Resolve the live remote manager for a context, or null when the context is local / not connected.+ const remoteFor = (ctx?: AccountCtx): { mgr: SshProjectManager; projectId: string } | null => {+ const projectId = ctx?.projectId+ const mgr = getSshManager?.()+ return projectId && mgr ? { mgr, projectId } : null+ }++ ipcMain.handle(IPC.claudeAccountsAdd, async (_e, ctx?: AccountCtx) => {const id = randomUUID()+ const remote = remoteFor(ctx)+ if (remote) {+ // REMOTE account: create the config dir + install the status hook on the host. No local dir+ // and no local hook install — the session runs entirely on the remote host.+ const res = await remote.mgr.remoteAccountAdd(remote.projectId, id)+ // Null means the project wasn't connected / mkdir failed: still return the id so the renderer+ // can show the pending row; the login node will surface the connection error itself.+ return { id, configDir: res?.configDir ?? '', versionSupported: res?.versionSupported ?? true }+ }const configDir = claudeConfigDirFor(id)await fs.mkdir(configDir, { recursive: true })// Install the managed hook up front so the very first session in this account@@ -45,16 +76,20 @@ export function initClaudeAccounts(): void {return { id, configDir, versionSupported }})- ipcMain.handle(IPC.claudeAccountsWaitLogin, async (_e, id: string) => {- const configDir = claudeConfigDirFor(id) // validates the id shape+ ipcMain.handle(IPC.claudeAccountsWaitLogin, async (_e, id: string, ctx?: AccountCtx) => {+ const remote = remoteFor(ctx)+ // Local path: `claudeConfigDirFor` also validates the id shape (rejects traversal).+ const configDir = remote ? null : claudeConfigDirFor(id)const w = { cancelled: false }waiters.set(id, w)const deadline = Date.now() + LOGIN_TIMEOUT_MStry {while (!w.cancelled && Date.now() < deadline) {try {- const raw = await fs.readFile(path.join(configDir, '.claude.json'), 'utf-8')- const captured = parseLoginCapture(raw)+ const raw = remote+ ? await remote.mgr.remoteAccountReadLogin(remote.projectId, id)+ : await fs.readFile(path.join(configDir as string, '.claude.json'), 'utf-8')+ const captured = raw ? parseLoginCapture(raw) : nullif (captured) return captured} catch {// not written yet — keep polling@@ -72,7 +107,14 @@ export function initClaudeAccounts(): void {if (w) w.cancelled = true})- ipcMain.handle(IPC.claudeAccountsRemove, async (_e, id: string) => {+ ipcMain.handle(IPC.claudeAccountsRemove, async (_e, id: string, ctx?: AccountCtx) => {+ const remote = remoteFor(ctx)+ if (remote) {+ // Best-effort remote cleanup; if the project isn't connected the manager no-ops and the+ // renderer still drops the account from its list (the dir is orphaned, harmless).+ await remote.mgr.remoteAccountRemove(remote.projectId, id)+ return+ }const configDir = claudeConfigDirFor(id) // id validation prevents traversalawait fs.rm(configDir, { recursive: true, force: true })})diff --git a/src/main/index.ts b/src/main/index.tsindex cd3de9b32..33310bab7 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -759,7 +759,9 @@ app.whenReady().then(async () => {initClaudeUsage(win)initTelemetry(() => settingsStore.get())initLicense(win)- initClaudeAccounts()+ // Lazy getter: sshProjectManager is created just below, so a remote account op (which only runs+ // after the user has connected an SSH project) always sees the live manager.+ initClaudeAccounts(() => sshProjectManager)initRemoteHost(win, ptyManager)initRemoteClient(win, { isPackaged: app.isPackaged })sshProjectManager = initSshProject(win)diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.tsindex b30acb520..42d14e035 100644--- a/src/main/pty-manager.ts+++ b/src/main/pty-manager.ts@@ -23,7 +23,7 @@ import {import { TMUX_SOCKET, sessionName } from './tmux-naming'import { writeScrollback, readScrollback, deleteScrollback } from './scrollback-store'import { claudeConfigDirFor } from './claude-accounts'-import { AUTH_ENV_STRIP, accountTmuxEnvArgs } from './claude-accounts-core'+import { AUTH_ENV_STRIP, accountTmuxEnvArgs, remoteAccountConfigDirAbs } from './claude-accounts-core'// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which// kills the tmux server) can still replay recent output on cold restart. A final snapshot also@@ -534,6 +534,15 @@ export class PtyManager {hookServer.getVersion()): []+ // Managed REMOTE Claude account (Task 12): inject CLAUDE_CONFIG_DIR into the remote tmux+ // session via `-e`, pointing at the account's config dir on the remote host. The path must be+ // ABSOLUTE — tmux copies `-e` values verbatim (no `$HOME`/`~` expansion) — so we build it from+ // the connection's resolved remote $HOME. Fail-open: an unknown remoteHome (home resolution+ // failed on connect) skips the account env and the session runs under the remote `~/.claude`.+ const remoteAccountEnv =+ options.accountId && options.sshRemote.remoteHome+ ? accountTmuxEnvArgs(remoteAccountConfigDirAbs(options.sshRemote.remoteHome, options.accountId))+ : []args = remoteTmuxPtyArgs(options.sshRemote.conn,options.sshRemote.controlPath,@@ -542,7 +551,7 @@ export class PtyManager {// An agent preset may pass a remote program to run inside the remote tmux; usually undefined.options.shell,options.shellArgs,- hookExtraEnv,+ [...hookExtraEnv, ...remoteAccountEnv],// Source nodeterm's remote tmux.conf via `-f` (written on connect, Task 2) so a cold-start// session gets mouse/clipboard/scrollback. Fail-open: undefined → remote tmux host defaults.options.sshRemote.tmuxConfPathdiff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.tsindex 82ffd1a23..7b99c1d1d 100644--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@ -7,7 +7,7 @@import { childArgs, hookForwardArgs, hookForwardCancelArgs, remoteEndpointFileContents } from './control-master'import { buildManagedScript } from '../agents/hooks/managed-script'import { mergeManagedHook, type HookSettings } from '../agents/hooks/install-helper'-import type { SshConnection } from '../../shared/ssh'+import { posixQuote, type SshConnection } from '../../shared/ssh'export interface RemoteRunner {/** Run one ssh child command (over the master); optional stdin written to the child. */@@ -89,6 +89,52 @@ export class RemoteHooks {}}+ /**+ * Merge the managed claude hook into a REMOTE managed-account config dir's `settings.json`, so an+ * agent that runs under `CLAUDE_CONFIG_DIR=<accountDir>` reports status like the default+ * `~/.claude` does (badges / notifications / subagent viz). The claude CLI reads its hooks from+ * `$CLAUDE_CONFIG_DIR/settings.json`, so `setup()`'s merge into `~/.claude/settings.json` does NOT+ * cover account sessions — this fills the gap. Reuses the same hook SCRIPT `setup()` wrote (writing+ * it idempotently in case setup didn't run) + the shared merge helper, preserving any hooks the+ * account dir already has. `remoteHome` is the resolved remote `$HOME`; every path is absolute+ * (a literal `~` inside the merged `sh "…"` command would not expand). Fail-open.+ */+ async installIntoAccountDir(+ conn: SshConnection,+ controlPath: string,+ remoteHome: string,+ accountId: string+ ): Promise<void> {+ try {+ const remoteDir = `${remoteHome}/.nodeterm`+ const script = `${remoteDir}/agent-hooks/claude.sh`+ const accountDir = `${remoteHome}/.nodeterm/claude-accounts/${accountId}`+ const config = `${accountDir}/settings.json`+ const events = AGENT_TARGETS.find((t) => t.agentId === 'claude')?.events ?? []+ // Idempotently (re)write the shared hook script — setup() may not have run (fail-open) yet.+ await this.r.run(+ childArgs(conn, controlPath, `mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`),+ buildManagedScript('claude')+ )+ const { stdout: cfgRaw } = await this.r.run(+ childArgs(conn, controlPath, `cat ${posixQuote(config)} 2>/dev/null || echo '{}'`)+ )+ let cfg: HookSettings = {}+ try {+ cfg = JSON.parse(cfgRaw || '{}') as HookSettings+ } catch {+ cfg = {}+ }+ const merged = mergeManagedHook(cfg, `sh "${script}"`, events)+ await this.r.run(+ childArgs(conn, controlPath, `mkdir -p ${posixQuote(accountDir)} && cat > ${posixQuote(config)}`),+ JSON.stringify(merged, null, 2)+ )+ } catch {+ /* fail-open: the account session simply runs without status hooks */+ }+ }+async teardown(projectId: string, conn: SshConnection, controlPath: string): Promise<void> {const spec = this.specs.get(projectId)this.specs.delete(projectId)diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 8d0189d25..4e529a361 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -3,8 +3,9 @@ import path from 'path'import { spawn, execFile, execFileSync } from 'child_process'import { app, ipcMain, type BrowserWindow } from 'electron'import { IPC } from '../../shared/ipc'-import { parseLsDirs, posixQuote, remoteTmuxConf, type SshConnection } from '../../shared/ssh'+import { parseLsDirs, posixQuote, quoteRemotePath, remoteTmuxConf, type SshConnection } from '../../shared/ssh'import type { SshProjectStatus } from '../../shared/types'+import { remoteAccountConfigDir, isSupportedClaudeVersion } from '../claude-accounts-core'import {controlPathFor,masterArgs,@@ -120,7 +121,7 @@ export class SshProjectManager {projectId: string,conn: SshConnection,remoteCwd?: string- ): Promise<{ controlPath: string; hookEndpointPath?: string; tmuxConfPath?: string }> {+ ): Promise<{ controlPath: string; hookEndpointPath?: string; tmuxConfPath?: string; remoteHome?: string }> {const existing = this.conns.get(projectId)if (existing) {// Verify the cached master is still alive before reusing it — a dropped/timed-out master@@ -131,7 +132,7 @@ export class SshProjectManager {// Keep the remote git cwd current even on an idempotent reuse (the folder may have changed).// Guard against a later connect without remoteCwd clearing a known cwd.existing.remoteCwd = remoteCwd ?? existing.remoteCwd- return { controlPath: existing.controlPath, hookEndpointPath: existing.hookEndpointPath, tmuxConfPath: existing.tmuxConfPath }+ return { controlPath: existing.controlPath, hookEndpointPath: existing.hookEndpointPath, tmuxConfPath: existing.tmuxConfPath, remoteHome: existing.remoteHome }}this.r.onStatus({ projectId, status: 'reconnecting' })existing.master.kill()@@ -198,7 +199,7 @@ export class SshProjectManager {entry.tmuxConfPath = tmuxConfPath}this.r.onStatus({ projectId, status: 'connected' })- return { controlPath, hookEndpointPath, tmuxConfPath }+ return { controlPath, hookEndpointPath, tmuxConfPath, remoteHome }}await new Promise((res) => setTimeout(res, 100))}@@ -323,6 +324,63 @@ export class SshProjectManager {return undefined}+ // ── Managed REMOTE Claude accounts (Task 12) ──────────────────────────────────────────────+ // These run over the project's live master. Every op no-ops (null / silently) when the project+ // isn't connected, so the renderer's account list stays authoritative and fails open.++ /**+ * Create a managed remote account's config dir on the host and merge the status hook into its+ * `settings.json`. Returns the remote dir (`~/.nodeterm/claude-accounts/<id>`) + whether the+ * remote claude CLI is new enough to scope credentials per config dir, or null when not connected.+ */+ async remoteAccountAdd(+ projectId: string,+ accountId: string+ ): Promise<{ configDir: string; versionSupported: boolean } | null> {+ const c = this.conns.get(projectId)+ if (!c) return null+ const dir = remoteAccountConfigDir(accountId) // id-validated ~-relative path+ const mk = await this.r.run(mkDirArgs(c.conn, c.controlPath, dir))+ if (mk.code !== 0) return null+ // Install the managed hook into the account dir's settings.json (needs the absolute $HOME so the+ // merged `sh "…"` command has no unexpanded ~). Fail-open when the home never resolved.+ if (c.remoteHome) await this.remoteHooks.installIntoAccountDir(c.conn, c.controlPath, c.remoteHome, accountId)+ return { configDir: dir, versionSupported: await this.remoteClaudeVersionOk(c) }+ }++ /** Read a managed remote account's `.claude.json` (login capture); null when not connected or the+ * file isn't written yet. The renderer's waitLogin loop parses it with `parseLoginCapture`. */+ async remoteAccountReadLogin(projectId: string, accountId: string): Promise<string | null> {+ const c = this.conns.get(projectId)+ if (!c) return null+ const file = `${remoteAccountConfigDir(accountId)}/.claude.json`+ const { code, stdout } = await this.r.run(+ childArgs(c.conn, c.controlPath, `cat ${quoteRemotePath(file)} 2>/dev/null`)+ )+ return code === 0 && stdout ? stdout : null+ }++ /** Delete a managed remote account's config dir (`rm -rf`). No-op when not connected. The id is+ * regex-validated and the prefix (`~/.nodeterm/claude-accounts/`) fixed, so no traversal. */+ async remoteAccountRemove(projectId: string, accountId: string): Promise<void> {+ const c = this.conns.get(projectId)+ if (!c) return+ const dir = remoteAccountConfigDir(accountId)+ await this.r.run(childArgs(c.conn, c.controlPath, `rm -rf ${quoteRemotePath(dir)}`))+ }++ /** Best-effort remote `claude --version` check. Returns true when it can't be determined (a+ * non-login ssh shell may lack claude on PATH) so remote add is never blocked on detection. */+ private async remoteClaudeVersionOk(c: Conn): Promise<boolean> {+ try {+ const { code, stdout } = await this.r.run(childArgs(c.conn, c.controlPath, 'claude --version'))+ if (code !== 0) return true+ return isSupportedClaudeVersion(stdout.trim())+ } catch {+ return true+ }+ }+async disconnect(projectId: string): Promise<void> {const c = this.conns.get(projectId)if (!c) returndiff --git a/src/preload/index.ts b/src/preload/index.tsindex 4d5f4f374..94ff3b851 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -276,10 +276,10 @@ const api: NodeTerminalApi = {}},claudeAccounts: {- add: () => ipcRenderer.invoke(IPC.claudeAccountsAdd),- waitLogin: (id) => ipcRenderer.invoke(IPC.claudeAccountsWaitLogin, id),+ add: (ctx) => ipcRenderer.invoke(IPC.claudeAccountsAdd, ctx),+ waitLogin: (id, ctx) => ipcRenderer.invoke(IPC.claudeAccountsWaitLogin, id, ctx),cancelWaitLogin: (id) => ipcRenderer.invoke(IPC.claudeAccountsCancelWait, id),- remove: (id) => ipcRenderer.invoke(IPC.claudeAccountsRemove, id)+ remove: (id, ctx) => ipcRenderer.invoke(IPC.claudeAccountsRemove, id, ctx)},transcripts: {search: (query: string) => ipcRenderer.invoke(IPC.transcriptSearch, query)diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 652779b16..14c8fa3e8 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -136,6 +136,7 @@ import {reorderNodeBefore,reparentNode,resolveNewNodeAccount,+ accountsForProject,ungroupNodes,type CanvasNode} from '../state/workspace'@@ -664,11 +665,11 @@ export function Canvas() {requireProOr('SSH Remote Projects', () => {window.nodeTerminal.sshProject.connect(project.id, ssh.server, ssh.remoteCwd)- .then(async ({ controlPath, hookEndpointPath, tmuxConfPath }) => {+ .then(async ({ controlPath, hookEndpointPath, tmuxConfPath, remoteHome }) => {// Arm remote git routing for the active project BEFORE the sshConn entry appears, so the// Source Control panel's re-fetch (which keys off that entry) already hits the master.await window.nodeTerminal.git.setActiveRemote(project.id)- useSshConn.getState().setConn(project.id, { controlPath, hookEndpointPath, tmuxConfPath })+ useSshConn.getState().setConn(project.id, { controlPath, hookEndpointPath, tmuxConfPath, remoteHome })}).catch(() => {/* status surfaced via onStatus → the connection banner */@@ -1349,17 +1350,23 @@ export function Canvas() {// to open a terminal node running `claude /login` under the new account's config dir.useEffect(() => {const onAddAccountLogin = (ev: Event): void => {- const accountId = (ev as CustomEvent<{ accountId: string }>).detail?.accountId+ const detail = (ev as CustomEvent<{ accountId: string; remote?: boolean }>).detail+ const accountId = detail?.accountIdif (!accountId) return+ // A REMOTE account (added inside an SSH project) logs in ON THE HOST: stamp the login node+ // with the active project's ssh binding so `claude /login` runs in remote tmux under the+ // remote account dir. Local accounts omit it (login runs locally).+ const project = useProjects.getState().getProject(activeProjectId)+ const ssh = detail?.remote ? project?.ssh : undefinedsetNodes((ns) => [...ns.map((n) => ({ ...n, selected: false })),- { ...createAccountLoginNode(accountId, ns.length, viewCenter()), selected: true }+ { ...createAccountLoginNode(accountId, ns.length, viewCenter(), ssh), selected: true }])markDirty()}window.addEventListener('nodeterm:add-account-login', onAddAccountLogin)return () => window.removeEventListener('nodeterm:add-account-login', onAddAccountLogin)- }, [setNodes, markDirty, viewCenter])+ }, [setNodes, markDirty, viewCenter, activeProjectId])// When an account is removed in Settings, clear it off the ACTIVE project's live nodes (the// projects store only holds the other projects' serialized copies). Referencing nodes fall@@ -2105,10 +2112,12 @@ export function Canvas() {e.preventDefault()const at = screenToFlowPosition({ x: e.clientX, y: e.clientY })const disabled = useSettings.getState().settings.disabledAgents- // Local, logged-in accounts only (pending logins + remote/host accounts are excluded).- const accounts = useSettings- .getState()- .settings.claudeAccounts.filter((a) => !a.pending && !a.host)+ // Accounts selectable in the active project: local accounts for a local project, or this+ // host's accounts for an SSH project (pending logins always excluded).+ const accounts = accountsForProject(+ useSettings.getState().settings.claudeAccounts,+ useProjects.getState().getProject(activeProjectId)+ )setMenu({x: e.clientX,y: e.clientY,@@ -2191,7 +2200,8 @@ export function Canvas() {openFileDialog,openRemotePicker,selectAll,- fitView+ fitView,+ activeProjectId])@@ -3114,11 +3124,13 @@ export function Canvas() {run: () => addAgentNode(c.id)})),- // One "New Claude — <label>" per logged-in local account. Plain "New Claude" above uses- // the resolved project default; these pin a specific account.- ...useSettings- .getState()- .settings.claudeAccounts.filter((a) => !a.pending && !a.host)+ // One "New Claude — <label>" per account usable in the active project (local accounts for a+ // local project, this host's accounts for an SSH project). Plain "New Claude" above uses the+ // resolved project default; these pin a specific account.+ ...accountsForProject(+ useSettings.getState().settings.claudeAccounts,+ useProjects.getState().getProject(activeProjectId)+ ).map((a): Command => ({id: `new-claude-${a.id}`,diff --git a/src/renderer/components/Dock.tsx b/src/renderer/components/Dock.tsxindex e46695a91..f54ce3cad 100644--- a/src/renderer/components/Dock.tsx+++ b/src/renderer/components/Dock.tsx@@ -2,6 +2,8 @@ import { useState } from 'react'import { AGENT_CONFIG, BUILTIN_AGENT_IDS, type AgentId } from '@shared/agents/config'import { AgentIcon } from '../lib/agentIcons'import { useSettings } from '../state/settings'+import { useProjects } from '../state/projects'+import { accountsForProject } from '../state/workspace'interface DockProps {dirty: boolean@@ -52,9 +54,12 @@ export function Dock({const customAgents = useSettings((s) => s.settings.customAgents)const disabledAgents = useSettings((s) => s.settings.disabledAgents)const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)- // Local, logged-in accounts only. The flat dock menu can't nest, so Claude gets one- // "New Claude — <label>" entry per account (plus the base "Claude" = project default).- const localAccounts = claudeAccounts.filter((a) => !a.pending && !a.host)+ const activeProjectId = useProjects((s) => s.activeProjectId)+ const activeProject = useProjects((s) => s.projects.find((p) => p.id === activeProjectId))+ // Accounts usable in the active project (local for a local project, this host's for an SSH+ // project). The flat dock menu can't nest, so Claude gets one "New Claude — <label>" entry per+ // account (plus the base "Claude" = project default).+ const localAccounts = accountsForProject(claudeAccounts, activeProject)const pick = (fn: () => void) => () => {fn()diff --git a/src/renderer/components/TabBar.tsx b/src/renderer/components/TabBar.tsxindex bbf435a47..1865b0d5b 100644--- a/src/renderer/components/TabBar.tsx+++ b/src/renderer/components/TabBar.tsx@@ -3,6 +3,7 @@ import { createPortal } from 'react-dom'import { useProjects } from '../state/projects'import { useAgentStatus } from '../state/agentStatus'import { useSettings } from '../state/settings'+import { accountsForProject } from '../state/workspace'interface TabBarProps {onSwitch: (id: string) => void@@ -53,14 +54,12 @@ export function TabBar({const [draft, setDraft] = useState('')// Whether the caret menu's "Default Claude account" group is expanded (inline, in-place).const [acctOpen, setAcctOpen] = useState(false)- // Local, logged-in accounts only (pending logins + remote/host accounts excluded).const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)- const localAccounts = useMemo(- () => claudeAccounts.filter((a) => !a.pending && !a.host),- [claudeAccounts]- )const menuProject = projects.find((p) => p.id === menuId)+ // Accounts eligible as the caret-menu project's default: local accounts for a local project, this+ // host's accounts for an SSH project (pending logins always excluded).+ const menuAccounts = accountsForProject(claudeAccounts, menuProject)const closeMenu = () => {setMenuId(null)@@ -214,7 +213,7 @@ export function TabBar({>Remote access…</button>- {localAccounts.length > 0 && (+ {menuAccounts.length > 0 && (<><buttonclassName={`tab-menu__group${acctOpen ? ' open' : ''}`}@@ -236,7 +235,7 @@ export function TabBar({</span>System account</button>- {localAccounts.map((a) => (+ {menuAccounts.map((a) => (<buttonkey={a.id}onClick={() => {diff --git a/src/renderer/components/settings/sections/AccountsSection.tsx b/src/renderer/components/settings/sections/AccountsSection.tsxindex cd3becb2a..383164012 100644--- a/src/renderer/components/settings/sections/AccountsSection.tsx+++ b/src/renderer/components/settings/sections/AccountsSection.tsx@@ -1,5 +1,6 @@import { useState } from 'react'import type { ClaudeAccount } from '@shared/types'+import { sshHostKey } from '@shared/ssh'import { useSettings } from '../../../state/settings'import { useProjects } from '../../../state/projects'import { ConfirmDialog } from '../../ConfirmDialog'@@ -37,21 +38,42 @@ function countNodesUsing(accountId: string): number {export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.Element {const accounts = useSettings((s) => s.settings.claudeAccounts)+ const activeProjectId = useProjects((s) => s.activeProjectId)+ const activeProject = useProjects((s) => s.projects.find((p) => p.id === activeProjectId))+ // The active project's SSH host key (`user@host`), when it's a connected SSH project. Present →+ // the "Add account" control also offers adding an account ON that host.+ const activeHostKey = activeProject?.ssh ? sshHostKey(activeProject.ssh.server) : undefinedconst [versionWarning, setVersionWarning] = useState(false)const [pendingRemove, setPendingRemove] = useState<ClaudeAccount | null>(null)const setLabel = (id: string, label: string): void =>applyAccounts((accs) => accs.map((a) => (a.id === id ? { ...a, label } : a)))+ // The open project whose SSH host matches a remote account (needed for the ssh context of+ // waitLogin / remove). Undefined for local accounts, or when no such project is open.+ const projectIdForHost = (host?: string): string | undefined => {+ if (!host) return undefined+ return useProjects.getState().projects.find((p) => p.ssh && sshHostKey(p.ssh.server) === host)?.id+ }+// Open a login terminal for an account and wait (up to ~5 min) for the CLI to write its- // credentials; on success flip the row out of `pending` and adopt the captured email.- const runLogin = async (id: string): Promise<void> => {- window.dispatchEvent(new CustomEvent('nodeterm:add-account-login', { detail: { accountId: id } }))- const captured = await window.nodeTerminal.claudeAccounts.waitLogin(id)+ // credentials; on success flip the row out of `pending` and adopt the captured email. A remote+ // account (`host` set) logs in on its host: the login node runs in remote tmux and waitLogin polls+ // the remote `.claude.json` over ssh (via the ctx `projectId`).+ const runLogin = async (account: Pick<ClaudeAccount, 'id' | 'host'>): Promise<void> => {+ const remote = !!account.host+ const projectId = remote ? projectIdForHost(account.host) : undefined+ window.dispatchEvent(+ new CustomEvent('nodeterm:add-account-login', { detail: { accountId: account.id, remote } })+ )+ const captured = await window.nodeTerminal.claudeAccounts.waitLogin(+ account.id,+ projectId ? { projectId } : undefined+ )if (!captured) return // timeout / cancel: row stays pending, offers RetryapplyAccounts((accs) =>accs.map((a) =>- a.id === id+ a.id === account.id? {...a,label: a.label === 'New account' ? captured.email : a.label,@@ -63,8 +85,13 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.)}- const onAddAccount = async (): Promise<void> => {- const { id, versionSupported } = await window.nodeTerminal.claudeAccounts.add()+ // `host` set → create the account dir + hook ON that SSH host (via the ctx projectId); the row+ // then carries the host chip and only appears in that host's projects.+ const onAddAccount = async (host?: string): Promise<void> => {+ const projectId = host ? projectIdForHost(host) : undefined+ const { id, versionSupported } = await window.nodeTerminal.claudeAccounts.add(+ projectId ? { projectId } : undefined+ )// Non-blocking: the account still isolates config, but an old CLI's unscoped macOS keychain// service would collide across accounts — surface a dismissable warning.if (!versionSupported) setVersionWarning(true)@@ -72,17 +99,22 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.id,label: 'New account',pending: true,- createdAt: Date.now()+ createdAt: Date.now(),+ ...(host ? { host } : {})}applyAccounts((accs) => [...accs, account])- await runLogin(id)+ await runLogin(account)}const confirmRemove = async (account: ClaudeAccount): Promise<void> => {setPendingRemove(null)// Removing a pending account: stop the 5-minute waitLogin poll loop first.if (account.pending) await window.nodeTerminal.claudeAccounts.cancelWaitLogin(account.id)- await window.nodeTerminal.claudeAccounts.remove(account.id)+ const projectId = projectIdForHost(account.host)+ await window.nodeTerminal.claudeAccounts.remove(+ account.id,+ projectId ? { projectId } : undefined+ )applyAccounts((accs) => accs.filter((a) => a.id !== account.id))// Clear the account off serialized nodes (all projects) + any project default...useProjects.setState((s) => ({@@ -152,6 +184,14 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.pending</span>) : null}+ {account.host ? (+ <span+ className="rounded-full bg-[#0a84ff]/15 px-2 py-0.5 text-[11px] font-medium text-[#0a84ff]"+ title={`Remote account on ${account.host}`}+ >+ {account.host}+ </span>+ ) : null}</div>{account.email && !account.pending ? (<p className="text-[12px] text-muted">{account.email}</p>@@ -159,7 +199,7 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.</div><div className="flex shrink-0 items-center gap-2">{account.pending ? (- <Button onClick={() => void runLogin(account.id)}>Retry login</Button>+ <Button onClick={() => void runLogin(account)}>Retry login</Button>) : null}<Buttonvariant="ghost"@@ -173,13 +213,27 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.)))}- <Button variant="primary" onClick={() => void onAddAccount()}>- Add account- </Button>+ {activeHostKey ? (+ // Inside an SSH project: choose where the new account lives. "On this Mac" is a normal+ // local account; "On <host>" creates it on the remote host (usable only there).+ <div className="flex flex-wrap items-center gap-2">+ <Button variant="primary" onClick={() => void onAddAccount()}>+ Add account — On this Mac+ </Button>+ <Button variant="primary" onClick={() => void onAddAccount(activeHostKey)}>+ Add account — On {activeHostKey}+ </Button>+ </div>+ ) : (+ <Button variant="primary" onClick={() => void onAddAccount()}>+ Add account+ </Button>+ )}<p className="text-[12px] leading-relaxed text-muted">Accounts are isolated Claude logins. New Claude nodes pick an account from the add- menus; each node keeps its account for life.+ menus; each node keeps its account for life. Remote accounts live on an SSH host and are+ only offered in that host's projects.</p></div></SearchableRow>diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 0cd1cadc7..3a851b63b 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -57,6 +57,7 @@ async function resolveSshRemote(remoteCwd: stringhookEndpointPath?: stringtmuxConfPath?: string+ remoteHome?: string}| undefined> {@@ -86,7 +87,11 @@ async function resolveSshRemote(// The remote tmux config (mouse on → scroll; set-clipboard on → OSC 52) is written + sourced// alongside the master; pass its path so a fresh remote session launches with `-f`. Optional.const tmuxConfPath = useSshConn.getState().getTmuxConfPath(projectId)- return { controlPath, conn, remoteCwd: cwd || '~', hookEndpointPath, tmuxConfPath }+ // The connection's resolved remote $HOME, used to build an ABSOLUTE remote CLAUDE_CONFIG_DIR for a+ // managed remote account (Task 12). Optional (fail-open): absent → the remote account env is+ // skipped and the session runs under the remote system default `~/.claude`.+ const remoteHome = useSshConn.getState().getRemoteHome(projectId)+ return { controlPath, conn, remoteCwd: cwd || '~', hookEndpointPath, tmuxConfPath, remoteHome }}/**diff --git a/src/renderer/state/sshConn.ts b/src/renderer/state/sshConn.tsindex bd56f7140..ca69fb0e1 100644--- a/src/renderer/state/sshConn.ts+++ b/src/renderer/state/sshConn.ts@@ -10,6 +10,9 @@ export interface SshConnInfo {/** Remote path of the injected tmux config (`-f`), written + sourced on connect.* Optional: absent when the conf write failed (fail-open → remote tmux defaults). */tmuxConfPath?: string+ /** The connection's resolved remote `$HOME`. Used to build an ABSOLUTE remote+ * `CLAUDE_CONFIG_DIR` for a managed remote account. Optional: absent if it couldn't resolve. */+ remoteHome?: string}/**@@ -25,6 +28,7 @@ interface SshConnState {getControlPath(projectId: string): string | undefinedgetHookEndpointPath(projectId: string): string | undefinedgetTmuxConfPath(projectId: string): string | undefined+ getRemoteHome(projectId: string): string | undefinedclear(projectId: string): void}@@ -42,6 +46,9 @@ export const useSshConn = create<SshConnState>((set, get) => ({getTmuxConfPath(projectId) {return get().byProject[projectId]?.tmuxConfPath},+ getRemoteHome(projectId) {+ return get().byProject[projectId]?.remoteHome+ },clear(projectId) {set((s) => {const next = { ...s.byProject }diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 6c497994b..9914e6ee0 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -2,6 +2,7 @@ import type { Node } from '@xyflow/react'import type { CanvasMutation, CanvasNodeState, ClaudeAccount, NodeKind, Project } from '@shared/types'import type { AgentId } from '@shared/agents/config'import { agentConfig } from '@shared/agents/config'+import { sshHostKey } from '@shared/ssh'import { useSettings } from './settings'/** Preset color palette — macOS system colors (dark mode). */@@ -245,6 +246,21 @@ function resolveAgent(agentId: AgentId): { label: string; color: string; launchCreturn { label: agentId, color: FALLBACK_AGENT_COLOR, launchCmd: agentId }}+/**+ * The managed accounts selectable in a given project, host-scoped. A LOCAL project shows only+ * local accounts (no `host`); an SSH project shows only accounts whose `host` matches that+ * project's connection identity (`sshHostKey` = `user@host`). Pending (not-yet-logged-in) accounts+ * are always excluded. Keeps a project's add-menus / default-account picker from offering an+ * account that can't run there (a remote account's credentials live on its host's filesystem).+ */+export function accountsForProject(+ accounts: ClaudeAccount[],+ project: { ssh?: { server: { host: string; user: string } } } | undefined+): ClaudeAccount[] {+ const hostKey = project?.ssh ? sshHostKey(project.ssh.server) : undefined+ return accounts.filter((a) => !a.pending && (hostKey ? a.host === hostKey : !a.host))+}+/** Account for a NEW Claude node: explicit pick, else the project default, else system. */export function resolveNewNodeAccount(explicit: string | undefined,@@ -334,13 +350,18 @@ export function accountChipLabel(* CLAUDE_CONFIG_DIR (Task-3 env injection keyed off `data.accountId`), so `claude /login`* writes credentials + `.claude.json` into the account dir, where the main process captures* the email. A plain terminal (not an agent node) so no session-name tracking kicks in.+ *+ * In an SSH project, pass the project's `ssh` binding: the node then runs in REMOTE tmux (Task 12),+ * so `CLAUDE_CONFIG_DIR` resolves to the account dir ON THE HOST and `claude /login` writes the+ * remote `.claude.json` (the main process polls it over ssh). For a local account, omit `ssh`.*/export function createAccountLoginNode(accountId: string,index: number,- center?: { x: number; y: number }+ center?: { x: number; y: number },+ ssh?: Project['ssh']): CanvasNode {- const node = createTerminalNode(index, undefined, center)+ const node = createTerminalNode(index, undefined, center, undefined, ssh)node.data = {...node.data,title: 'Claude login',diff --git a/src/shared/ssh.test.ts b/src/shared/ssh.test.tsindex 6512ee6f9..193ac62a5 100644--- a/src/shared/ssh.test.ts+++ b/src/shared/ssh.test.ts@@ -7,9 +7,21 @@ import {quoteRemotePath,remoteTmuxCommand,remoteTmuxConf,- parseLsDirs+ parseLsDirs,+ sshHostKey} from './ssh'+describe('sshHostKey', () => {+ it('is user@host', () => {+ expect(sshHostKey({ host: 'box.example.com', user: 'bob' })).toBe('[email protected]')+ })+ it('ignores port + identity (same remote $HOME → same key)', () => {+ expect(sshHostKey({ host: 'h', user: 'u', port: 22 } as never)).toBe(+ sshHostKey({ host: 'h', user: 'u', port: 2222 } as never)+ )+ })+})+describe('parseSshConfig', () => {it('parses a named host with HostName/User/Port/IdentityFile', () => {const cfg = `Host proddiff --git a/src/shared/ssh.ts b/src/shared/ssh.tsindex ef0be543f..d60ae3d44 100644--- a/src/shared/ssh.ts+++ b/src/shared/ssh.ts@@ -53,6 +53,17 @@ export function parseExtraArgs(s: string | undefined): string[] {return tokens}+/**+ * Stable identity key for the host a connection targets, used to scope managed Claude accounts to+ * an SSH project (`ClaudeAccount.host`). `${user}@${host}` — the same target string ssh itself+ * builds. Port and identity file are intentionally excluded: a remote account is defined by which+ * remote `$HOME` (i.e. which user on which host) its config dir lives under, and two projects that+ * reach the same account over different ports still share that one remote dir.+ */+export function sshHostKey(conn: Pick<SshConnection, 'host' | 'user'>): string {+ return `${conn.user}@${conn.host}`+}+/** Build the `ssh` argv: `-p <port> [-i <id>] [...extra] user@host`. */export function buildSshArgs(conn: SshConnection): string[] {const args = ['-p', String(conn.port ?? 22)]diff --git a/src/shared/types.ts b/src/shared/types.tsindex a3acb5a7c..751d15f74 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -25,8 +25,10 @@ export interface PtyCreateOptions {agentId?: AgentId/** Managed Claude account: inject CLAUDE_CONFIG_DIR for this account into the session env. */accountId?: string- /** When set, this PTY runs on a remote host over the project's ssh ControlMaster, in remote tmux. */- sshRemote?: { controlPath: string; conn: import('./ssh').SshConnection; remoteCwd: string; hookEndpointPath?: string; tmuxConfPath?: string }+ /** When set, this PTY runs on a remote host over the project's ssh ControlMaster, in remote tmux.+ * `remoteHome` is the connection's resolved `$HOME`, used to build an ABSOLUTE remote+ * `CLAUDE_CONFIG_DIR` for a managed remote account (tmux `-e` values are not shell-expanded). */+ sshRemote?: { controlPath: string; conn: import('./ssh').SshConnection; remoteCwd: string; hookEndpointPath?: string; tmuxConfPath?: string; remoteHome?: string }}/**@@ -399,7 +401,7 @@ export interface SshProjectApi {projectId: string,server: import('./ssh').SshConnection,remoteCwd?: string- ): Promise<{ controlPath: string; hookEndpointPath?: string; tmuxConfPath?: string }>+ ): Promise<{ controlPath: string; hookEndpointPath?: string; tmuxConfPath?: string; remoteHome?: string }>/** Tear down the master (remote tmux is unaffected). */disconnect(projectId: string): Promise<void>/**@@ -773,15 +775,22 @@ export interface ChatApi {onEvent(nodeId: string, listener: (e: ChatEvent) => void): () => void}+/** Optional SSH context for account ops. When `projectId` names a connected SSH project, the+ * account lives on that host (config dir + login + removal happen over ssh). Omit it for local. */+export interface AccountSshCtx {+ projectId?: string+}export interface ClaudeAccountsApi {- /** Mint a new managed account: create its config dir, install the hook, check the CLI version. */- add(): Promise<{ id: string; configDir: string; versionSupported: boolean }>- /** Poll the account's `.claude.json` for a completed login; null on timeout/cancel. */- waitLogin(id: string): Promise<{ email: string } | null>+ /** Mint a new managed account: create its config dir, install the hook, check the CLI version.+ * With an SSH `ctx` the dir + hook are created on the remote host instead of locally. */+ add(ctx?: AccountSshCtx): Promise<{ id: string; configDir: string; versionSupported: boolean }>+ /** Poll the account's `.claude.json` for a completed login; null on timeout/cancel. With an SSH+ * `ctx` the poll reads the remote host's copy over ssh. */+ waitLogin(id: string, ctx?: AccountSshCtx): Promise<{ email: string } | null>/** Cancel an in-flight `waitLogin` for this account. */cancelWaitLogin(id: string): Promise<void>- /** Delete a managed account's config dir (recursive). */- remove(id: string): Promise<void>+ /** Delete a managed account's config dir (recursive). With an SSH `ctx`, `rm -rf` on the host. */+ remove(id: string, ctx?: AccountSshCtx): Promise<void>}/** One ranked search hit across all on-disk Claude session transcripts. */