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): switch Claude accounts on SSH project nodes too
reviewf49d93be2cb5
diff --git a/CLAUDE.md b/CLAUDE.mdindex 148e8508b..82ac70395 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2789,7 +2789,7 @@ command-bearing opens; this does not add a human-confirm dialog or change mobilethe project-default account), and validation runs against `accountsForProject`, not the rawlist, so a **pending** account or one **pinned to another machine's host** is never stampedonto a node it cannot run on (both used to reach the missing-dir fallback at spawn).- - **Switch Claude account (running node, local only)** — node right-click → *Switch Claude+ - **Switch Claude account (running node)** — node right-click → *Switch Claudeaccount ▸* moves the conversation onto another account **already logged in** on this machine,with no `/login` in the pane. It works because a transcript carries **no account identity**(measured on 2.1.280: under a config dir lacking the file `--resume` says "No conversation found";@@ -2803,7 +2803,12 @@ command-bearing opens; this does not add a human-confirm dialog or change mobileoverwritten; and the rebind is **returned** by `beforeRecycle` and merged into the closure's own`updateNodeData`, never set by a separate Canvas `setNodes` in the same tick (React Flow's updatequeue rebuilds the node from the store's copy and can drop it). Builtin `claude` only (the- `boundAccountId` rule below). SSH / relay: shown disabled — the host-side copy is a follow-up.+ `boundAccountId` rule below). **SSH nodes** switch between the accounts pinned to THEIR host (and+ the host's own `~/.claude`): the copy runs ON the host as one generated `sh` script over the+ project's master (`core/remote-claude-session-copy.ts`, tested under a real `/bin/sh`; same+ prefix/diverged rule, via `head -c | cmp`), and `SshProjectManager.remoteClaudeSessionCopy`+ refuses an account pinned to another host. An SSH ctx with no remote leg (Server Edition) is+ refused, never answered from the local disk. Relay tabs: shown disabled.- **`boundAccountId(accountId, agentId)` (`shared/agents/account-binding.ts`) is the ONE rule forwhether a node is account-bound at all**, and it feeds `data.accountId` *and* the account colorfrom a single decision — split them and a node carries an account it is not painted for, or isdiff --git a/src/core/claude-accounts-service.test.ts b/src/core/claude-accounts-service.test.tsindex 2cc0295a3..922045ffd 100644--- a/src/core/claude-accounts-service.test.ts+++ b/src/core/claude-accounts-service.test.ts@@ -477,3 +477,57 @@ describe('claudeAccounts.copySession', () => {})})})++describe('claudeAccounts.copySession over SSH (ctx.projectId)', () => {+ const SID = '0123abcd-4567-89ef-0123-456789abcdef'+ const acct = (id: string, extra: Partial<ClaudeAccount> = {}): ClaudeAccount => ({+ id,+ label: id,+ createdAt: 0,+ ...extra+ })+ const remoteWith = (copySession?: unknown) => ({+ remote: () => ({+ add: async () => null,+ readLogin: async () => null,+ remove: async () => {},+ ...(copySession ? { copySession } : {})+ })+ })++ it('hands remote accounts (with their hosts) to the shell leg and never touches local disk', async () => {+ const leg = vi.fn(async () => ({ ok: true as const, copied: true }))+ registerClaudeAccountsSource(() => [acct('r1', { host: 'u@h' }), acct('r2', { host: 'u@h' })])+ registerClaudeAccountsIpc(remoteWith(leg) as never)+ expect(await call(IPC.claudeAccountsCopySession, SID, 'r1', 'r2', { projectId: 'p1' })).toEqual({+ ok: true,+ copied: true+ })+ expect(leg).toHaveBeenCalledWith('p1', SID, { id: 'r1', host: 'u@h' }, { id: 'r2', host: 'u@h' })+ // The host's system ~/.claude is `{}` — no id, no host.+ await call(IPC.claudeAccountsCopySession, SID, 'r1', undefined, { projectId: 'p1' })+ expect(leg).toHaveBeenLastCalledWith('p1', SID, { id: 'r1', host: 'u@h' }, {})+ })++ it('refuses a LOCAL or pending account as an SSH target', async () => {+ const leg = vi.fn()+ registerClaudeAccountsSource(() => [acct('loc'), acct('pend', { host: 'u@h', pending: true })])+ registerClaudeAccountsIpc(remoteWith(leg) as never)+ for (const t of ['loc', 'pend']) {+ expect(await call(IPC.claudeAccountsCopySession, SID, undefined, t, { projectId: 'p1' })).toEqual({+ ok: false,+ reason: 'unknown-account'+ })+ }+ expect(leg).not.toHaveBeenCalled()+ })++ it('answers failed for an SSH ctx with no remote leg (the Server Edition) — not a local copy', async () => {+ registerClaudeAccountsSource(() => [acct('r1', { host: 'u@h' })])+ registerClaudeAccountsIpc()+ expect(await call(IPC.claudeAccountsCopySession, SID, undefined, 'r1', { projectId: 'p1' })).toEqual({+ ok: false,+ reason: 'failed'+ })+ })+})diff --git a/src/core/claude-accounts-service.ts b/src/core/claude-accounts-service.tsindex 034bf3f39..464c6dfa5 100644--- a/src/core/claude-accounts-service.ts+++ b/src/core/claude-accounts-service.ts@@ -30,6 +30,7 @@ import { installClaudeHooksInto, ensureClaudeFullscreenTuiInto } from './agents/import { findInLoginPath } from './pty-manager'import { platform } from './platform'import { copyClaudeSession, type ClaudeSessionCopyOutcome } from './claude-session-copy'+import type { ClaudeSessionCopyResult } from '../shared/types'import { resolveTranscriptPath, transcriptRoot, SESSION_ID_RE } from './transcript-reader'const execFileP = promisify(execFile)@@ -54,6 +55,18 @@ export interface ClaudeAccountsRemote {): Promise<{ configDir: string; versionSupported: boolean } | null>readLogin(projectId: string, id: string): Promise<string | null>remove(projectId: string, id: string): Promise<void>+ /**+ * Copy a conversation between two account dirs ON THE HOST (the SSH leg of `copySession`).+ * `host` is each account's `ClaudeAccount.host` (undefined = the host's system `~/.claude`); the+ * implementation refuses an account pinned to a different host than this project's connection.+ * Optional: a shell without it (older wiring) answers `failed` for an SSH switch.+ */+ copySession?(+ projectId: string,+ sessionId: string,+ source: { id?: string; host?: string },+ target: { id?: string; host?: string }+ ): Promise<ClaudeSessionCopyResult>}export interface ClaudeAccountsDeps {@@ -292,7 +305,8 @@ export function registerClaudeAccountsIpc(deps: ClaudeAccountsDeps = {}): void {async (sessionId: unknown,sourceAccountId: unknown,- targetAccountId: unknown+ targetAccountId: unknown,+ ctx?: AccountCtx): Promise<ClaudeSessionCopyOutcome> => {if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId))return { ok: false, reason: 'bad-request' }@@ -302,6 +316,26 @@ export function registerClaudeAccountsIpc(deps: ClaudeAccountsDeps = {}): void {const source = sourceAccountId || undefinedconst target = targetAccountId || undefinedif (source === target) return { ok: true, copied: false }+ // SSH project: the transcripts and account dirs are on the host. Only REMOTE accounts (or the+ // host's system dir) qualify; the shell's leg re-checks that each is pinned to THIS host.+ // A projectId with no live remote leg (not connected, or the Server Edition, which has no SSH+ // manager) is refused rather than answered from THIS machine's disk.+ if (typeof ctx?.projectId === 'string' && ctx.projectId) {+ const remote = remoteFor(ctx)+ if (!remote?.r.copySession) return { ok: false, reason: 'failed' }+ const accounts = claudeAccountsSnapshot()+ const remoteAcct = (id: string | undefined, settled: boolean): { id?: string; host?: string } | null => {+ if (id === undefined) return {}+ const a = accounts.find((x) => x.id === id && x.host && (!settled || !x.pending))+ return a ? { id: a.id, host: a.host } : null+ }+ const src = remoteAcct(source, false)+ const tgt = remoteAcct(target, true)+ if (!src || !tgt) return { ok: false, reason: 'unknown-account' }+ return remote.r+ .copySession(remote.projectId, sessionId, src, tgt)+ .catch((): ClaudeSessionCopyOutcome => ({ ok: false, reason: 'failed' }))+ }const localSettled = (id: string): boolean =>claudeAccountsSnapshot().some((a) => a.id === id && !a.host && !a.pending)if (target !== undefined && !localSettled(target)) return { ok: false, reason: 'unknown-account' }diff --git a/src/core/remote-claude-session-copy.test.ts b/src/core/remote-claude-session-copy.test.tsnew file mode 100644index 000000000..8e3dc1a7f--- /dev/null+++ b/src/core/remote-claude-session-copy.test.ts@@ -0,0 +1,111 @@+// The generated host-side copy script, run for REAL under /bin/sh against a fake host tree — the+// discipline every generated remote shell in this repo gets (remote-transcript-locate,+// remote-claude-usage, the canvas-control shim): a quoting slip is invisible to the type checker.+//+// MUTATION: drop the `cmp` prefix check → the diverged case copies over the target and reddens;+// print the marker unquoted (`echo ##COPY …`) → sh reads a comment and every case reads `failed`.+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import { execFileSync } from 'child_process'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'fs'+import os from 'os'+import path from 'path'+import {+ parseRemoteSessionCopy,+ remoteClaudeConfigDir,+ remoteSessionCopyCommand+} from './remote-claude-session-copy'++const SID = '0123abcd-4567-89ef-0123-456789abcdef'+const ACCT = '11111111-2222-3333-4444-555555555555'+const TMP = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'+let home: string+let src: string+let dst: string++const run = (sourceConfigDir = src, targetConfigDir = dst): string => {+ const cmd = remoteSessionCopyCommand({ sessionId: SID, sourceConfigDir, targetConfigDir, tempId: TMP })+ if (!cmd) throw new Error('no command')+ return execFileSync('/bin/sh', ['-c', cmd], { encoding: 'utf8' })+}+const srcFile = (): string => path.join(src, 'projects', '-home-u-repo', `${SID}.jsonl`)+const dstFile = (): string => path.join(dst, 'projects', '-home-u-repo', `${SID}.jsonl`)++beforeEach(() => {+ home = mkdtempSync(path.join(os.tmpdir(), "nt-rcopy home '$x"))+ src = remoteClaudeConfigDir(home, undefined)+ dst = remoteClaudeConfigDir(home, ACCT)+ mkdirSync(path.dirname(srcFile()), { recursive: true })+ writeFileSync(srcFile(), 'one\ntwo\n')+})+afterEach(() => rmSync(home, { recursive: true, force: true }))++describe('remoteClaudeConfigDir', () => {+ it('is the system ~/.claude or the managed remote account dir, absolute', () => {+ expect(remoteClaudeConfigDir('/home/u/', undefined)).toBe('/home/u/.claude')+ expect(remoteClaudeConfigDir('/home/u', ACCT)).toBe(`/home/u/.nodeterm/claude-accounts/${ACCT}`)+ expect(() => remoteClaudeConfigDir('/home/u', '../x')).toThrow()+ })+})++describe('remoteSessionCopyCommand under a real /bin/sh', () => {+ it('copies into the same project dir and leaves no temp behind', () => {+ expect(parseRemoteSessionCopy(run())).toEqual({ ok: true, copied: true })+ expect(readFileSync(dstFile(), 'utf8')).toBe('one\ntwo\n')+ expect(readdirSync(path.dirname(dstFile()))).toEqual([`${SID}.jsonl`])+ })++ it('answers identical for the same copy, and replaces an older prefix copy', () => {+ mkdirSync(path.dirname(dstFile()), { recursive: true })+ writeFileSync(dstFile(), 'one\ntwo\n')+ expect(parseRemoteSessionCopy(run())).toEqual({ ok: true, copied: false })+ writeFileSync(dstFile(), 'one\n')+ expect(parseRemoteSessionCopy(run())).toEqual({ ok: true, copied: true })+ expect(readFileSync(dstFile(), 'utf8')).toBe('one\ntwo\n')+ })++ it('never overwrites a diverged or longer target', () => {+ mkdirSync(path.dirname(dstFile()), { recursive: true })+ // Shorter than the source but not its prefix: only the byte compare can tell.+ writeFileSync(dstFile(), 'onX\n')+ expect(parseRemoteSessionCopy(run())).toEqual({ ok: false, reason: 'diverged' })+ expect(readFileSync(dstFile(), 'utf8')).toBe('onX\n')+ writeFileSync(dstFile(), 'one\ntwo\nthree\n')+ expect(parseRemoteSessionCopy(run())).toEqual({ ok: false, reason: 'diverged' })+ })++ it('answers no-transcript (exit 0) when the source has no such conversation', () => {+ rmSync(srcFile())+ expect(parseRemoteSessionCopy(run())).toEqual({ ok: false, reason: 'no-transcript' })+ expect(existsSync(dstFile())).toBe(false)+ })++ it('copies sidecars and file history without clobbering', () => {+ const side = path.join(path.dirname(srcFile()), SID, 'subagents')+ mkdirSync(side, { recursive: true })+ writeFileSync(path.join(side, 'agent-1.jsonl'), 'sub\n')+ mkdirSync(path.join(src, 'file-history', SID), { recursive: true })+ writeFileSync(path.join(src, 'file-history', SID, 'f@v1'), 'mine')+ mkdirSync(path.join(dst, 'file-history', SID), { recursive: true })+ writeFileSync(path.join(dst, 'file-history', SID, 'f@v1'), 'theirs')+ expect(parseRemoteSessionCopy(run())).toEqual({ ok: true, copied: true })+ expect(+ readFileSync(path.join(path.dirname(dstFile()), SID, 'subagents', 'agent-1.jsonl'), 'utf8')+ ).toBe('sub\n')+ expect(readFileSync(path.join(dst, 'file-history', SID, 'f@v1'), 'utf8')).toBe('theirs')+ })++ it('refuses inputs that must never reach a shell', () => {+ const base = { sessionId: SID, sourceConfigDir: '/a', targetConfigDir: '/b', tempId: TMP }+ expect(remoteSessionCopyCommand({ ...base, sessionId: "x'; rm -rf ~" })).toBeNull()+ expect(remoteSessionCopyCommand({ ...base, tempId: '../x' })).toBeNull()+ expect(remoteSessionCopyCommand({ ...base, targetConfigDir: '~/.claude' })).toBeNull()+ })+})++describe('parseRemoteSessionCopy', () => {+ it('reads the last marker and treats a missing one as failed', () => {+ expect(parseRemoteSessionCopy('motd banner\n##COPY copied\n')).toEqual({ ok: true, copied: true })+ expect(parseRemoteSessionCopy('')).toEqual({ ok: false, reason: 'failed' })+ expect(parseRemoteSessionCopy('##COPY bogus\n')).toEqual({ ok: false, reason: 'failed' })+ })+})diff --git a/src/core/remote-claude-session-copy.ts b/src/core/remote-claude-session-copy.tsnew file mode 100644index 000000000..cab8db332--- /dev/null+++ b/src/core/remote-claude-session-copy.ts@@ -0,0 +1,108 @@+// The SSH leg of the running-node "Switch Claude account" copy (`claude-session-copy.ts` is the+// local one). An SSH project's transcripts and account dirs live ON THE HOST, so the copy runs+// there: one POSIX `sh` script over the project's ControlMaster, whose only output is a marker line.+// Same rules as the local copy — the renderer runs it after the CLI has exited, a target that is a+// byte-prefix of the source is an older copy and is replaced, a diverged target is never touched,+// and the sidecars (subagent transcripts, `/rewind` file history) are copied best-effort without+// ever overwriting a file the target already has.+//+// Pure string builder + parser. `src/main` runs it; `remote-claude-session-copy.test.ts` runs the+// generated script for real under `/bin/sh` against a fake host tree (the same discipline as the+// other generated remote shells — a quoting slip here is invisible to the type checker).+import type { ClaudeSessionCopyResult } from '../shared/types'+import { posixQuote } from '../shared/ssh'+import { remoteAccountConfigDirAbs } from './claude-accounts-core'+import { SESSION_ID_RE } from './transcript-reader'++/** Absolute config dir ON THE HOST: a managed remote account's, or the system `~/.claude`. */+export function remoteClaudeConfigDir(remoteHome: string, accountId: string | undefined): string {+ return accountId+ ? remoteAccountConfigDirAbs(remoteHome, accountId)+ : `${remoteHome.replace(/\/+$/, '')}/.claude`+}++export interface RemoteSessionCopyPlan {+ sessionId: string+ /** Absolute config dirs on the host (`remoteClaudeConfigDir`). */+ sourceConfigDir: string+ targetConfigDir: string+ /** A fresh UUID for the temp leaf. Independent of the target's own name, and chosen app-side so+ * two concurrent copies can never share a temp. */+ tempId: string+}++const TEMP_ID_RE = /^[0-9a-fA-F-]{8,64}$/+const MARKER = '##COPY'++/**+ * The script, or null for an input that must never reach a shell (a malformed session or temp id,+ * a relative dir). Every interpolated value is either validated here or app-built from a validated+ * account id, and each is passed through `posixQuote` — the script body only ever references the+ * shell variables.+ *+ * Exits 0 in every branch: "no such conversation" and "diverged" are ANSWERS carried by the marker.+ * A non-zero exit or a missing marker therefore means the ssh call itself failed.+ */+export function remoteSessionCopyCommand(plan: RemoteSessionCopyPlan): string | null {+ if (!SESSION_ID_RE.test(plan.sessionId) || !TEMP_ID_RE.test(plan.tempId)) return null+ if (!plan.sourceConfigDir.startsWith('/') || !plan.targetConfigDir.startsWith('/')) return null+ const out = (what: string): string => `printf '%s %s\\n' '${MARKER}' ${what}`+ return [+ `SC=${posixQuote(plan.sourceConfigDir)}`,+ `TC=${posixQuote(plan.targetConfigDir)}`,+ `ID=${posixQuote(plan.sessionId)}`,+ `TMPLEAF=${posixQuote(`.nodeterm-${plan.tempId}.tmp`)}`,+ 'S="$SC/projects"',+ 'T="$TC/projects"',+ // The session's project dir is whichever one holds it (the pane may have `cd`ed since launch).+ // An unmatched glob stays literal, and `[ -f ]` rejects it.+ 'src=',+ 'for f in "$S"/*/"$ID.jsonl"; do [ -f "$f" ] && { src=$f; break; }; done',+ `if [ -z "$src" ]; then ${out('no-transcript')}; exit 0; fi`,+ 'd=${src%/*}',+ 'd=${d##*/}',+ 'tgt="$T/$d/$ID.jsonl"',+ `if [ "$src" = "$tgt" ]; then ${out('identical')}; exit 0; fi`,+ `mkdir -p "$T/$d" || { ${out('failed')}; exit 0; }`,+ 'st=copied',+ 'if [ -e "$tgt" ]; then',+ ` ts=$(wc -c < "$tgt") && ss=$(wc -c < "$src") || { ${out('failed')}; exit 0; }`,+ // `$((…))` strips the leading blanks BSD `wc` prints.+ ' ts=$((ts)); ss=$((ss))',+ ` if [ "$ts" -gt "$ss" ]; then ${out('diverged')}; exit 0; fi`,+ ` head -c "$ts" "$src" | cmp -s - "$tgt" || { ${out('diverged')}; exit 0; }`,+ ' [ "$ts" -eq "$ss" ] && st=identical',+ 'fi',+ 'if [ "$st" = copied ]; then',+ ' tmp="$T/$d/$TMPLEAF"',+ ` if cp "$src" "$tmp" && mv -f "$tmp" "$tgt"; then :; else rm -f "$tmp"; ${out('failed')}; exit 0; fi`,+ 'fi',+ // Sidecars: best-effort, never clobbering (`-n`), silent. The transcript is what `--resume` needs.+ '[ -d "$S/$d/$ID" ] && { mkdir -p "$T/$d/$ID" && cp -R -n "$S/$d/$ID/." "$T/$d/$ID/"; } >/dev/null 2>&1',+ '[ -d "$SC/file-history/$ID" ] && { mkdir -p "$TC/file-history/$ID" && cp -R -n "$SC/file-history/$ID/." "$TC/file-history/$ID/"; } >/dev/null 2>&1',+ out('"$st"'),+ 'exit 0'+ ].join('\n')+}++/** The marker line's answer. No marker (a cut stream, a failed ssh) is `failed`, never `ok`. */+export function parseRemoteSessionCopy(stdout: string): ClaudeSessionCopyResult {+ const lines = stdout.split('\n')+ for (let i = lines.length - 1; i >= 0; i--) {+ const m = /^##COPY (copied|identical|diverged|no-transcript|failed)$/.exec(lines[i].trim())+ if (!m) continue+ switch (m[1]) {+ case 'copied':+ return { ok: true, copied: true }+ case 'identical':+ return { ok: true, copied: false }+ case 'diverged':+ return { ok: false, reason: 'diverged' }+ case 'no-transcript':+ return { ok: false, reason: 'no-transcript' }+ default:+ return { ok: false, reason: 'failed' }+ }+ }+ return { ok: false, reason: 'failed' }+}diff --git a/src/main/claude-accounts.ts b/src/main/claude-accounts.tsindex ab6fad529..6be801000 100644--- a/src/main/claude-accounts.ts+++ b/src/main/claude-accounts.ts@@ -23,7 +23,9 @@ export function initClaudeAccounts(getSshManager?: () => SshProjectManager | undreturn {add: (projectId, id) => mgr.remoteAccountAdd(projectId, id),readLogin: (projectId, id) => mgr.remoteAccountReadLogin(projectId, id),- remove: (projectId, id) => mgr.remoteAccountRemove(projectId, id)+ remove: (projectId, id) => mgr.remoteAccountRemove(projectId, id),+ copySession: (projectId, sessionId, source, target) =>+ mgr.remoteClaudeSessionCopy(projectId, sessionId, source, target)}}})diff --git a/src/main/remote-ssh/ssh-project.claude-session-copy.test.ts b/src/main/remote-ssh/ssh-project.claude-session-copy.test.tsnew file mode 100644index 000000000..e651fe963--- /dev/null+++ b/src/main/remote-ssh/ssh-project.claude-session-copy.test.ts@@ -0,0 +1,74 @@+// The desktop's SSH leg of "Switch Claude account": the host-side copy runs over THIS project's+// master, only between accounts pinned to this connection's host. The script itself is exercised+// under a real /bin/sh in core/remote-claude-session-copy.test.ts; here only the wiring.+import { describe, expect, it, vi } from 'vitest'+import { SshProjectManager } from './ssh-project'+import { sshHostKey, type SshConnection } from '@shared/ssh'++const conn: SshConnection = { host: 'h', user: 'u' }+const HOST = sshHostKey(conn)+const SID = '0123abcd-4567-89ef-0123-456789abcdef'+const A = '11111111-2222-3333-4444-555555555555'++function makeMgr(copyReply = { code: 0, stdout: 'motd\n##COPY copied\n' }) {+ const copies: string[] = []+ const run = vi.fn(async (args: string[]) => {+ const cmd = args.at(-1) ?? ''+ if (cmd.includes('##COPY')) {+ copies.push(cmd)+ return copyReply+ }+ return args.join(' ').includes('printf %s') ? { code: 0, stdout: '/home/u' } : { code: 0, stdout: '' }+ })+ const mgr = new SshProjectManager({+ userDataDir: '/ud',+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),+ run,+ runScp: vi.fn(async () => ({ code: 0 })),+ getHook: () => ({ port: 1, token: 't', version: '1' }),+ onStatus: vi.fn()+ })+ return { mgr, copies }+}++describe('SshProjectManager.remoteClaudeSessionCopy', () => {+ it('runs the copy on the host between absolute account dirs under $HOME', async () => {+ const { mgr, copies } = makeMgr()+ await mgr.connect('p1', conn, '/srv/repo')+ expect(await mgr.remoteClaudeSessionCopy('p1', SID, {}, { id: A, host: HOST })).toEqual({+ ok: true,+ copied: true+ })+ expect(copies).toHaveLength(1)+ expect(copies[0]).toContain(`SC='/home/u/.claude'`)+ expect(copies[0]).toContain(`TC='/home/u/.nodeterm/claude-accounts/${A}'`)+ })++ it('refuses an account pinned to another host without touching the host', async () => {+ const { mgr, copies } = makeMgr()+ await mgr.connect('p1', conn, '/srv/repo')+ expect(await mgr.remoteClaudeSessionCopy('p1', SID, {}, { id: A, host: 'x@elsewhere' })).toEqual({+ ok: false,+ reason: 'unknown-account'+ })+ expect(await mgr.remoteClaudeSessionCopy('p1', SID, { id: A, host: 'x@elsewhere' }, {})).toEqual({+ ok: false,+ reason: 'unknown-account'+ })+ expect(copies).toEqual([])+ })++ it('answers failed — never success — when not connected or the ssh call fails', async () => {+ const idle = makeMgr()+ expect(await idle.mgr.remoteClaudeSessionCopy('p1', SID, {}, { id: A, host: HOST })).toEqual({+ ok: false,+ reason: 'failed'+ })+ const broken = makeMgr({ code: 255, stdout: '##COPY copied\n' })+ await broken.mgr.connect('p1', conn, '/srv/repo')+ expect(await broken.mgr.remoteClaudeSessionCopy('p1', SID, {}, { id: A, host: HOST })).toEqual({+ ok: false,+ reason: 'failed'+ })+ })+})diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 90106d796..cfb7836dd 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -14,7 +14,17 @@ import {sshHostKey,type SshConnection} from '../../shared/ssh'-import type { DownloadResult, SshPassphraseRequest, SshProjectStatusEvent } from '../../shared/types'+import type {+ ClaudeSessionCopyResult,+ DownloadResult,+ SshPassphraseRequest,+ SshProjectStatusEvent+} from '../../shared/types'+import {+ parseRemoteSessionCopy,+ remoteClaudeConfigDir,+ remoteSessionCopyCommand+} from '../../core/remote-claude-session-copy'import { candidateName, safeDownloadBasename } from '../../core/download-name'import { removeAtomic, renameAtomic } from '../../core/fs-atomic'import { findExecutableSync, shellPathNow } from '../../core/exec-path'@@ -2217,6 +2227,44 @@ export class SshProjectManager {await this.r.run(childArgs(c.conn, c.controlPath, `rm -rf ${quoteRemotePath(dir)}`))}+ /**+ * The SSH leg of "Switch Claude account": copy a conversation between two account dirs ON THE+ * HOST (`remote-claude-session-copy.ts` builds the script; it runs over this project's master).+ * Refuses an account pinned to another host — its dir would name a path on a machine this+ * connection does not reach — and a connection whose `$HOME` never resolved (the account dirs are+ * absolute paths under it). A cut stream or failed ssh parses as `failed`, never as success.+ */+ async remoteClaudeSessionCopy(+ projectId: string,+ sessionId: string,+ source: { id?: string; host?: string },+ target: { id?: string; host?: string }+ ): Promise<ClaudeSessionCopyResult> {+ const c = this.conns.get(projectId)+ if (!c || !c.remoteHome) return { ok: false, reason: 'failed' }+ const here = sshHostKey(c.conn)+ if ((source.id && source.host !== here) || (target.id && target.host !== here))+ return { ok: false, reason: 'unknown-account' }+ let cmd: string | null+ try {+ cmd = remoteSessionCopyCommand({+ sessionId,+ sourceConfigDir: remoteClaudeConfigDir(c.remoteHome, source.id),+ targetConfigDir: remoteClaudeConfigDir(c.remoteHome, target.id),+ tempId: randomUUID()+ })+ } catch {+ return { ok: false, reason: 'bad-request' } // an account id outside the alphabet+ }+ if (!cmd) return { ok: false, reason: 'bad-request' }+ try {+ const { code, stdout } = await this.r.run(childArgs(c.conn, c.controlPath, cmd))+ return code === 0 ? parseRemoteSessionCopy(stdout) : { ok: false, reason: 'failed' }+ } catch {+ return { ok: false, reason: 'failed' }+ }+ }+/*** Best-effort `claude --version` ON THE REMOTE HOST. Null when it can't be determined.*diff --git a/src/preload/index.ts b/src/preload/index.tsindex 6ded394a6..d4cc898b3 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -561,8 +561,8 @@ const api: NodeTerminalApi = {link: (configDir) => ipcRenderer.invoke(IPC.claudeAccountsLink, configDir),setSkillSharing: (id, enabled) =>ipcRenderer.invoke(IPC.claudeAccountsSetSkillSharing, id, enabled),- copySession: (sessionId, sourceAccountId, targetAccountId) =>- ipcRenderer.invoke(IPC.claudeAccountsCopySession, sessionId, sourceAccountId, targetAccountId)+ copySession: (sessionId, sourceAccountId, targetAccountId, ctx) =>+ ipcRenderer.invoke(IPC.claudeAccountsCopySession, sessionId, sourceAccountId, targetAccountId, ctx)},codexAccounts: {add: (ctx) => ipcRenderer.invoke(IPC.codexAccountsAdd, ctx),diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 3b3d4db19..c9984050f 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -999,12 +999,15 @@ export function buildClaudeAccountsApi(client: RpcClient): Pick<NodeTerminalApi,) as Promise<ClaudeSkillShareResult>,// Real: the copy is core, on the machine the browser is served from — the same machine whose// account dirs the Server Edition's panes run under.- copySession: (sessionId, sourceAccountId, targetAccountId) =>+ // An SSH ctx is forwarded as-is: the server registers no SSH leg, so core refuses it+ // (`failed`) instead of copying on the server's own disk.+ copySession: (sessionId, sourceAccountId, targetAccountId, ctx) =>client.request(IPC.claudeAccountsCopySession,sessionId,sourceAccountId,- targetAccountId+ targetAccountId,+ ctx) as Promise<ClaudeSessionCopyResult>}}diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 2326fef99..ef6f8d014 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -624,6 +624,7 @@ import {import { codexAccountSelectable, codexAccountSwitchStillEligible } from './codex-account-switch'import { resolveNewCodexNodeAccount, planCodexAccountSwitch } from './codex-account-ops'import {+ claudeSwitchHostKey,claudeSwitchTargets,copyRefusalText,planClaudeAccountSwitch@@ -6607,12 +6608,14 @@ export function Canvas() {const st = useAgentStatus.getState().byId[nodeId]const accounts = useSettings.getState().settings.claudeAccountsconst accountId = (n?.data.accountId as string | undefined) || undefined+ const hostKey = claudeSwitchHostKey(n)const decision = planClaudeAccountSwitch({agentId: restartAgentIdOf(n),accountId,readAccountId: effectiveAccountId(accountId, st?.account, accounts),- remote: !!n && isRemoteSessionNode(n.data),+ hostKey,+ remote: session.source === 'relay' || (!!n && isRemoteSessionNode(n.data) && !hostKey),sessionId: restartSessionId(st?.sessionId, n?.data.agentSessionId)},targetAccountId,@@ -6626,11 +6629,32 @@ export function Canvas() {decision.reason === 'no-session'? 'This session has no resumable conversation id yet — nothing to switch.': decision.reason === 'remote'- ? 'Switching accounts is not available for SSH sessions yet.'+ ? 'Switching accounts is not available for this session.': `${targetLabel} is no longer available. Nothing was changed.`})return}+ // An SSH node's copy runs on its host, over a project connected to it — the active one first+ // (the node is on this canvas), else any connected project on the same host.+ let ctx: { projectId: string } | undefined+ if (hostKey) {+ const active = useProjects.getState().getProject(useProjects.getState().activeProjectId)+ const activeId =+ active?.ssh &&+ sshHostKey(active.ssh.server) === hostKey &&+ useSshConn.getState().byProject[active.id]+ ? active.id+ : undefined+ const projectId = activeId ?? connectedProjectIdForHost(hostKey)+ if (!projectId) {+ setNotice({+ kind: 'error',+ text: 'This host is not connected — reconnect the project, then switch. Nothing was changed.'+ })+ return+ }+ ctx = { projectId }+ }const fn = agentRestartFn(nodeId)if (!fn) {setNotice({ kind: 'error', text: 'Switch skipped: this terminal is not attached right now.' })@@ -6641,7 +6665,7 @@ export function Canvas() {const outcome = await settleRestart(() =>fn(undefined, undefined, true, undefined, async () => {copy = await window.nodeTerminal.claudeAccounts- .copySession(plan.sessionId, plan.sourceAccountId, plan.targetAccountId)+ .copySession(plan.sessionId, plan.sourceAccountId, plan.targetAccountId, ctx).catch((): ClaudeSessionCopyResult => ({ ok: false, reason: 'failed' }))if (!copy.ok) return// Returned, not set here: the closure merges it into the SAME node update as its respawn@@ -6667,7 +6691,7 @@ export function Canvas() {: { kind: 'error', text: copyRefusalText(moved?.ok === false ? moved.reason : 'failed', targetLabel) })},- [markDirty]+ [markDirty, session.source, connectedProjectIdForHost])// Who the bulk restart would act on, right now: the ACTIVE project's canvas (nodesRef holds@@ -8509,20 +8533,26 @@ export function Canvas() {// only for a Codex node with managed accounts on its machine. Each row is gated through// `codexAccountSelectable`; the actual switch is owner-authorized MAIN-SIDE and resumes// the SAME conversation id (`switchCodexAccountNode`) — the UI is not the boundary.- // Switch this running Claude node onto another account already logged in on this- // machine — no /login in the pane (`switchClaudeAccountNode`). Shown only when there is- // somewhere to switch to; disabled (never hidden) with the reason on an SSH session.+ // Switch this running Claude node onto another account already logged in on its+ // machine — this one, or the SSH host its pane runs on — with no /login in the pane+ // (`switchClaudeAccountNode`). Shown only when there is somewhere to switch to....(sourceAgentId === 'claude'? (() => {const settingsNow = useSettings.getState().settings- const targets = claudeSwitchTargets(settingsNow.claudeAccounts)+ const hostKey = claudeSwitchHostKey(n)+ const unswitchable =+ session.source === 'relay' || (!!n && isRemoteSessionNode(n.data) && !hostKey)+ const targets = claudeSwitchTargets(settingsNow.claudeAccounts, hostKey)if (targets.length === 0) return []- const remote = !!n && isRemoteSessionNode(n.data)const currentAccountId = (n?.data.accountId as string | undefined) || undefined- const systemLabel = systemAccountDisplay(- settingsNow.systemAccountLabel,- useSystemAccount.getState().email- )+ // The system row names the machine it is on: an SSH node's is the HOST's+ // `~/.claude`, whose identity this machine's system email says nothing about.+ const systemLabel = hostKey+ ? `System account (${hostKey})`+ : systemAccountDisplay(+ settingsNow.systemAccountLabel,+ useSystemAccount.getState().email+ )const row = (id: string | undefined, label: string): MenuItem => {const isCurrent = (id || undefined) === currentAccountIdreturn {@@ -8536,13 +8566,13 @@ export function Canvas() {onClick: () => void switchClaudeAccountNode(ids[0], id, label)}}- if (remote || session.source === 'relay')+ if (unswitchable)return [{label: 'Switch Claude account',icon: <IconSwitch />,disabled: true,- hint: 'Not available for SSH or relay sessions yet.',+ hint: 'Not available for relay sessions.',onClick: () => {}}] as MenuItem[]diff --git a/src/renderer/canvas/claude-account-switch.test.ts b/src/renderer/canvas/claude-account-switch.test.tsindex 2277bf58c..10b9cb670 100644--- a/src/renderer/canvas/claude-account-switch.test.ts+++ b/src/renderer/canvas/claude-account-switch.test.ts@@ -12,8 +12,26 @@ const accounts = [acct('a'), acct('b'), acct('pend', { pending: true }), acct('rconst node = { agentId: 'claude', accountId: 'a', remote: false, sessionId: 'sid-1' }describe('claudeSwitchTargets', () => {- it('offers only settled local accounts', () => {+ it('offers only settled accounts on the node\'s own machine', () => {expect(claudeSwitchTargets(accounts).map((x) => x.id)).toEqual(['a', 'b'])+ const hosted = [...accounts, acct('rem2', { host: 'u@h' }), acct('other', { host: 'x@y' })]+ expect(claudeSwitchTargets(hosted, 'u@h').map((x) => x.id)).toEqual(['rem', 'rem2'])+ })+})++describe('planClaudeAccountSwitch — SSH', () => {+ const ssh = { agentId: 'claude', accountId: 'rem', remote: false, hostKey: 'u@h', sessionId: 's' }+ const hosted = [...accounts, acct('rem2', { host: 'u@h' }), acct('other', { host: 'x@y' })]+ it('switches between accounts pinned to the node\'s host, and to the host system dir', () => {+ expect(planClaudeAccountSwitch(ssh, 'rem2', hosted)).toEqual({+ ok: true,+ plan: { sessionId: 's', sourceAccountId: 'rem', targetAccountId: 'rem2' }+ })+ expect(planClaudeAccountSwitch(ssh, undefined, hosted)).toMatchObject({ ok: true })+ })+ it('refuses a local account or another host\'s account for an SSH node', () => {+ expect(planClaudeAccountSwitch(ssh, 'a', hosted)).toEqual({ ok: false, reason: 'unavailable' })+ expect(planClaudeAccountSwitch(ssh, 'other', hosted)).toEqual({ ok: false, reason: 'unavailable' })})})diff --git a/src/renderer/canvas/claude-account-switch.ts b/src/renderer/canvas/claude-account-switch.tsindex 0bb960953..335bf4c44 100644--- a/src/renderer/canvas/claude-account-switch.ts+++ b/src/renderer/canvas/claude-account-switch.ts@@ -9,13 +9,24 @@// 4. recycle the tmux session, whose respawn gets the new CLAUDE_CONFIG_DIR and whose cold-restore// auto-resume runs `claude --resume <same id>` under it.//+// An SSH project's node switches the same way between the accounts pinned to ITS host; step 2 then+// runs on the host (`claudeAccounts.copySession` with the project's ctx).+//// This file is the renderer's own fail-closed refusal of what cannot work; core re-checks the target.import type { ClaudeAccount } from '@shared/types'+import { sshHostKey, type SshServer } from '@shared/ssh'-/** Accounts a node on THIS machine can be switched onto: settled, local (managed or linked). */-export function claudeSwitchTargets(accounts: readonly ClaudeAccount[]): ClaudeAccount[] {- return accounts.filter((a) => !a.host && !a.pending)+/**+ * Accounts a node can be switched onto: settled ones on the node's OWN machine — local (managed or+ * linked) for a local node, the accounts pinned to its host for an SSH node (`hostKey` =+ * `sshHostKey`). An account on another machine has no dir where the pane runs.+ */+export function claudeSwitchTargets(+ accounts: readonly ClaudeAccount[],+ hostKey?: string+): ClaudeAccount[] {+ return accounts.filter((a) => !a.pending && (hostKey ? a.host === hostKey : !a.host))}export interface ClaudeSwitchNode {@@ -24,7 +35,10 @@ export interface ClaudeSwitchNode {accountId?: string/** Where its transcript actually lives — `effectiveAccountId(...)`, the same id its readers use. */readAccountId?: string- /** A remote (SSH) or relay session: its transcript and account dirs are on another machine. */+ /** An SSH project's node: the `sshHostKey` of the host its pane runs on. */+ hostKey?: string+ /** A session this canvas cannot switch: a relay tab (another core's accounts), or a remote node+ * whose host could not be identified. */remote: booleansessionId?: string}@@ -52,7 +66,7 @@ export function planClaudeAccountSwitch(if (target === (node.accountId || undefined)) return { ok: false, reason: 'same-account' }// Never substitute: a target that is gone, pending or on another host is refused, not swapped for// the system account.- if (target !== undefined && !claudeSwitchTargets(accounts).some((a) => a.id === target))+ if (target !== undefined && !claudeSwitchTargets(accounts, node.hostKey).some((a) => a.id === target))return { ok: false, reason: 'unavailable' }if (!node.sessionId) return { ok: false, reason: 'no-session' }return {@@ -77,3 +91,12 @@ export function copyRefusalText(reason: string, targetLabel: string): string {: 'the transcript could not be copied'return `Could not move this conversation to ${targetLabel} — ${why}. It was resumed on its current account.`}++/** The `sshHostKey` of the host an SSH project's node runs on, or undefined for a local node (and+ * for a remote node carrying no `data.ssh`, which the caller then refuses as unswitchable). */+export function claudeSwitchHostKey(+ n: { data: Record<string, unknown> } | undefined+): string | undefined {+ const ssh = n?.data.ssh as SshServer | undefined+ return ssh ? sshHostKey(ssh) : undefined+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 0c0ebc7c4..687d61ec6 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -2791,13 +2791,16 @@ export interface ClaudeAccountsApi {/*** Copy a conversation's transcript from one LOCAL account's config dir into another's (`undefined`* = the system `~/.claude`), so a node switched onto the target account resumes the SAME- * conversation there with no `/login`. Called only after the CLI has exited. Never overwrites a+ * conversation there with no `/login`. With an SSH `ctx` the same copy runs on that project's host,+ * between REMOTE accounts pinned to it. Called only after the CLI has exited. Never overwrites a* diverged copy (`diverged`); never throws — every refusal is a reason.*/copySession(sessionId: string,sourceAccountId: string | undefined,- targetAccountId: string | undefined+ targetAccountId: string | undefined,+ /** An SSH project's node: the copy runs ON THAT HOST, between its remote account dirs. */+ ctx?: AccountSshCtx): Promise<ClaudeSessionCopyResult>}