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 a running Claude node to another logged-in account
enes4704c2fa20c6
diff --git a/CLAUDE.md b/CLAUDE.mdindex f108819c7..9ee9df32c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -218,8 +218,8 @@ reads as disarmed until armed on this machine). A node's `data`carries `title, color, group, tags, collapsed, expandedHeight, shell, cwd, text,initialCommand, filePath, diffStaged`, `icon` (a user-chosen emoji or picture — see **Node icons**below), `agentId` (which agent CLI a terminal node runs —-persisted), and `accountId` (which managed Claude account a terminal node runs under — immutable,-resolved at creation, persisted; see **Managed Claude accounts**). `nodeStatesToFlow` defaults a+persisted), and `accountId` (which managed Claude account a terminal node runs under — resolved+at creation, changed ONLY by the explicit account-switch actions, persisted; see **Managed Claude accounts**). `nodeStatesToFlow` defaults amissing `kind` to `terminal` for backward compat and migrates the legacy `tags:['claude']` markerto `data.agentId = 'claude'`. The SDK **chat node** was removed (2026-07); `nodeStatesToFlow` alsomigrates a persisted `chat` node into a **sticky tombstone** in place, reading its legacy@@ -2719,7 +2719,8 @@ else, and its context links must keep classifying across restarts).--version`, `isSupportedClaudeVersion`).- **`data.accountId` (terminal nodes)** — resolved **once at node creation**(`resolveNewNodeAccount`: explicit submenu pick → `project.defaultAccountId` → system default- `~/.claude`), then **immutable** and **persisted** (serializers). `undefined` = system default+ `~/.claude`), then **persisted** (serializers) and changed ONLY by an explicit **account switch**+ (below). `undefined` = system default= **bit-for-bit legacy behavior** (no env touched). Inherited by **Branch** (theterminal→chat fork it also fed is gone — the SDK chat node was removed 2026-07). Two #419rules inside the resolver: the submenu's **System row passes `null`** (an EXPLICIT system@@ -2727,6 +2728,21 @@ else, and its context links must keep classifying across restarts).the 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+ account ▸* 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";+ with the file copied into `<configDir>/projects/<encoded cwd>/<id>.jsonl` only the login is+ missing). Choreography = "Restart agent and shell" with a `beforeRecycle` step+ (`agent-restart.ts`): exit the CLI (refused while working/blocked) → core+ `claudeAccounts.copySession` (`core/claude-session-copy.ts`) → rebind `accountId` → recycle, whose+ respawn gets the new `CLAUDE_CONFIG_DIR` and whose cold restore resumes the same id. Two rules:+ the copy runs **after** the exit, so the source is final and a target that is a byte-**prefix**+ of it is just an older copy (A→B→A) and may be replaced, while a **diverged** target is never+ overwritten; 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 update+ queue 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(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 8dba3f6a4..2cc0295a3 100644--- a/src/core/claude-accounts-service.test.ts+++ b/src/core/claude-accounts-service.test.ts@@ -11,7 +11,7 @@* the skill case and the local-fallback case redden.*/import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'-import { existsSync, mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs'+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs'import os from 'os'import path from 'path'import { initPlatform, resetPlatformForTests } from './platform'@@ -71,13 +71,14 @@ afterEach(() => {rmSync(userDataDir, { recursive: true, force: true })})-describe('registerClaudeAccountsIpc — the six channels', () => {- it('registers exactly the six claude-accounts channels', () => {+describe('registerClaudeAccountsIpc — the seven channels', () => {+ it('registers exactly the seven claude-accounts channels', () => {registerClaudeAccountsIpc()expect(Object.keys(fake.handlers).sort()).toEqual([IPC.claudeAccountsAdd,IPC.claudeAccountsCancelWait,+ IPC.claudeAccountsCopySession,IPC.claudeAccountsLink,IPC.claudeAccountsRemove,IPC.claudeAccountsSetSkillSharing,@@ -384,3 +385,95 @@ describe('installHooksIntoLocalAccounts covers linked accounts', () => {expect(installed).toEqual(['/home/u/.claude-2', accountConfigDir(userDataDir, 'managed')])})})++// The running-node "Switch Claude account" copy. The renderer is not the boundary: core decides+// which accounts are real targets, and it never copies into a pending/remote/unknown one.+describe('claudeAccounts.copySession', () => {+ const SID = '0123abcd-4567-89ef-0123-456789abcdef'+ const acct = (id: string, extra: Partial<ClaudeAccount> = {}): ClaudeAccount => ({+ id,+ label: id,+ createdAt: 0,+ ...extra+ })+ const seed = (accountId: string, body: string): string => {+ const dir = path.join(accountConfigDir(userDataDir, accountId), 'projects', '-work-repo')+ mkdirSync(dir, { recursive: true })+ const f = path.join(dir, `${SID}.jsonl`)+ writeFileSync(f, body)+ return f+ }+ const targetFile = (accountId: string): string =>+ path.join(accountConfigDir(userDataDir, accountId), 'projects', '-work-repo', `${SID}.jsonl`)++ it('copies the transcript into the target account under the same project dir', async () => {+ registerClaudeAccountsSource(() => [acct('aaa'), acct('bbb')])+ registerClaudeAccountsIpc()+ seed('aaa', '{"a":1}\n')+ expect(await call(IPC.claudeAccountsCopySession, SID, 'aaa', 'bbb')).toEqual({+ ok: true,+ copied: true+ })+ expect(readFileSync(targetFile('bbb'), 'utf8')).toBe('{"a":1}\n')+ })++ it('copies into the SYSTEM ~/.claude when the target is undefined', async () => {+ const home = mkdtempSync(path.join(os.tmpdir(), 'nt-home-'))+ const prev = process.env.HOME+ process.env.HOME = home+ try {+ registerClaudeAccountsSource(() => [acct('aaa')])+ registerClaudeAccountsIpc()+ seed('aaa', 'x\n')+ expect(await call(IPC.claudeAccountsCopySession, SID, 'aaa', undefined)).toEqual({+ ok: true,+ copied: true+ })+ expect(+ readFileSync(path.join(home, '.claude', 'projects', '-work-repo', `${SID}.jsonl`), 'utf8')+ ).toBe('x\n')+ } finally {+ process.env.HOME = prev+ rmSync(home, { recursive: true, force: true })+ }+ })++ it('refuses a pending, remote or unlisted target — and copies nothing', async () => {+ registerClaudeAccountsSource(() => [+ acct('aaa'),+ acct('pend', { pending: true }),+ acct('rem', { host: 'u@h' })+ ])+ registerClaudeAccountsIpc()+ seed('aaa', 'x\n')+ for (const t of ['pend', 'rem', 'nope']) {+ expect(await call(IPC.claudeAccountsCopySession, SID, 'aaa', t)).toEqual({+ ok: false,+ reason: 'unknown-account'+ })+ expect(existsSync(targetFile(t))).toBe(false)+ }+ })++ it('refuses a malformed session id or account id', async () => {+ registerClaudeAccountsSource(() => [acct('aaa'), acct('bbb')])+ registerClaudeAccountsIpc()+ expect(await call(IPC.claudeAccountsCopySession, '../../etc', 'aaa', 'bbb')).toEqual({+ ok: false,+ reason: 'bad-request'+ })+ expect(await call(IPC.claudeAccountsCopySession, SID, 42, 'bbb')).toEqual({+ ok: false,+ reason: 'bad-request'+ })+ })++ it('answers no-transcript when the source account has no such conversation', async () => {+ registerClaudeAccountsSource(() => [acct('aaa'), acct('bbb')])+ registerClaudeAccountsIpc()+ expect(await call(IPC.claudeAccountsCopySession, SID, 'aaa', 'bbb')).toEqual({+ ok: false,+ reason: 'no-transcript'+ })+ })+})diff --git a/src/core/claude-accounts-service.ts b/src/core/claude-accounts-service.tsindex aaf41a1ed..f58826501 100644--- a/src/core/claude-accounts-service.ts+++ b/src/core/claude-accounts-service.ts@@ -29,6 +29,8 @@ import { applySkillShare, EMPTY_SKILL_SHARE } from './claude-skill-share'import { installClaudeHooksInto, ensureClaudeFullscreenTuiInto } from './agents/hooks/claude'import { findInLoginPath } from './pty-manager'import { platform } from './platform'+import { copyClaudeSession, type ClaudeSessionCopyOutcome } from './claude-session-copy'+import { resolveTranscriptPath, transcriptRoot, SESSION_ID_RE } from './transcript-reader'const execFileP = promisify(execFile)const LOGIN_POLL_MS = 2000@@ -273,6 +275,59 @@ export function registerClaudeAccountsIpc(deps: ClaudeAccountsDeps = {}): void {// hand-edited `configDir` of `~/.claude` from turning this into a self-link.return applySkillShare(claudeConfigDirFor(id), enabled)})++ /**+ * Copy a conversation into another LOCAL account so a switched node resumes it there (the+ * running-node "Switch Claude account" menu). The renderer runs it between the CLI's exit and the+ * pane recycle, so the source transcript is final; see `claude-session-copy.ts` for the+ * never-overwrite-a-diverged-copy rule.+ *+ * The renderer is not the boundary: the target must be a settled LOCAL account from the live+ * settings list (or `undefined` = the system `~/.claude`). A remote or pending account, or an id+ * nothing lists, is refused — a switch onto a dir with no login would only trade one `/login`+ * for another, and a remote account's dir is on another machine entirely.+ */+ platform().handle(+ IPC.claudeAccountsCopySession,+ async (+ sessionId: unknown,+ sourceAccountId: unknown,+ targetAccountId: unknown+ ): Promise<ClaudeSessionCopyOutcome> => {+ if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId))+ return { ok: false, reason: 'bad-request' }+ const optId = (v: unknown): v is string | undefined =>+ v === undefined || v === null || typeof v === 'string'+ if (!optId(sourceAccountId) || !optId(targetAccountId)) return { ok: false, reason: 'bad-request' }+ const source = sourceAccountId || undefined+ const target = targetAccountId || undefined+ if (source === target) return { ok: true, copied: false }+ 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' }+ // A source that is not a local account (removed, remote) has no local transcript to move.+ if (source !== undefined && !claudeAccountsSnapshot().some((a) => a.id === source && !a.host))+ return { ok: false, reason: 'unknown-account' }+ let sourceRoot: string+ let targetRoot: string+ try {+ // Both resolve through the id-alphabet gate (`accountConfigDir`), which throws on a bad id.+ sourceRoot = transcriptRoot(source)+ targetRoot = transcriptRoot(target)+ } catch {+ return { ok: false, reason: 'bad-request' }+ }+ const sourceFile = await resolveTranscriptPath(sessionId, source)+ if (!sourceFile) return { ok: false, reason: 'no-transcript' }+ return copyClaudeSession({+ sessionId,+ sourceFile,+ targetProjectsRoot: targetRoot,+ sourceConfigDir: path.dirname(sourceRoot),+ targetConfigDir: path.dirname(targetRoot)+ })+ }+ )}/**diff --git a/src/core/claude-session-copy.test.ts b/src/core/claude-session-copy.test.tsnew file mode 100644index 000000000..15517cb5b--- /dev/null+++ b/src/core/claude-session-copy.test.ts@@ -0,0 +1,103 @@+// The account-switch copy's one hard rule: a target copy is replaced ONLY when it is a byte-prefix+// of the source (an older copy of the same append-only conversation — A→B→A). A target that grew+// on its own is `diverged` and is never overwritten.+//+// MUTATION: make `prefixState` answer 'prefix' whenever sizes allow, or drop the `diverged` return+// → the diverged case copies over the target and reddens.+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'fs'+import os from 'os'+import path from 'path'+import { copyClaudeSession, prefixState } from './claude-session-copy'++const SID = '0123abcd-4567-89ef-0123-456789abcdef'+let root: string+let src: string+let dst: string+let sourceFile: string++const plan = () => ({+ sessionId: SID,+ sourceFile,+ targetProjectsRoot: path.join(dst, 'projects'),+ sourceConfigDir: src,+ targetConfigDir: dst+})+const target = (): string => path.join(dst, 'projects', '-repo', `${SID}.jsonl`)++beforeEach(() => {+ root = mkdtempSync(path.join(os.tmpdir(), 'nt-sesscopy-'))+ src = path.join(root, 'src')+ dst = path.join(root, 'dst')+ mkdirSync(path.join(src, 'projects', '-repo'), { recursive: true })+ sourceFile = path.join(src, 'projects', '-repo', `${SID}.jsonl`)+ writeFileSync(sourceFile, 'line1\nline2\n')+})+afterEach(() => rmSync(root, { recursive: true, force: true }))++describe('prefixState', () => {+ it('tells identical, prefix and diverged apart', async () => {+ const t = path.join(root, 't')+ writeFileSync(t, 'line1\nline2\n')+ expect(await prefixState(t, sourceFile)).toBe('identical')+ writeFileSync(t, 'line1\n')+ expect(await prefixState(t, sourceFile)).toBe('prefix')+ writeFileSync(t, 'line1\nother\n')+ expect(await prefixState(t, sourceFile)).toBe('diverged')+ writeFileSync(t, 'line1\nline2\nline3\n')+ expect(await prefixState(t, sourceFile)).toBe('diverged')+ })+})++describe('copyClaudeSession', () => {+ it('copies into the same project dir under the target root, leaving no temp behind', async () => {+ expect(await copyClaudeSession(plan())).toEqual({ ok: true, copied: true })+ expect(readFileSync(target(), 'utf8')).toBe('line1\nline2\n')+ expect(readdirSync(path.dirname(target()))).toEqual([`${SID}.jsonl`])+ })++ it('is a no-op when the target already holds the identical copy', async () => {+ mkdirSync(path.dirname(target()), { recursive: true })+ writeFileSync(target(), 'line1\nline2\n')+ expect(await copyClaudeSession(plan())).toEqual({ ok: true, copied: false })+ })++ it('replaces an older copy of the same conversation (switching back)', async () => {+ mkdirSync(path.dirname(target()), { recursive: true })+ writeFileSync(target(), 'line1\n')+ expect(await copyClaudeSession(plan())).toEqual({ ok: true, copied: true })+ expect(readFileSync(target(), 'utf8')).toBe('line1\nline2\n')+ })++ it('never overwrites a copy that diverged', async () => {+ mkdirSync(path.dirname(target()), { recursive: true })+ writeFileSync(target(), 'line1\nsomething else\n')+ expect(await copyClaudeSession(plan())).toEqual({ ok: false, reason: 'diverged' })+ expect(readFileSync(target(), 'utf8')).toBe('line1\nsomething else\n')+ })++ it('copies the session sidecar dir and file history without clobbering', async () => {+ const side = path.join(src, 'projects', '-repo', SID, 'subagents')+ mkdirSync(side, { recursive: true })+ writeFileSync(path.join(side, 'agent-1.jsonl'), 'sub\n')+ const hist = path.join(src, 'file-history', SID)+ mkdirSync(hist, { recursive: true })+ writeFileSync(path.join(hist, 'a@v1'), 'v1')+ const keep = path.join(dst, 'file-history', SID)+ mkdirSync(keep, { recursive: true })+ writeFileSync(path.join(keep, 'a@v1'), 'theirs')++ expect(await copyClaudeSession(plan())).toEqual({ ok: true, copied: true })+ expect(+ readFileSync(path.join(dst, 'projects', '-repo', SID, 'subagents', 'agent-1.jsonl'), 'utf8')+ ).toBe('sub\n')+ expect(readFileSync(path.join(keep, 'a@v1'), 'utf8')).toBe('theirs')+ })++ it('treats a target that IS the source (a linked dir) as already there', async () => {+ expect(+ await copyClaudeSession({ ...plan(), targetProjectsRoot: path.join(src, 'projects') })+ ).toEqual({ ok: true, copied: false })+ expect(existsSync(target())).toBe(false)+ })+})diff --git a/src/core/claude-session-copy.ts b/src/core/claude-session-copy.tsnew file mode 100644index 000000000..1b5f5377c--- /dev/null+++ b/src/core/claude-session-copy.ts@@ -0,0 +1,119 @@+// Move a Claude conversation from one account's config dir to another's, so a running node can be+// switched onto a different (already logged-in) account and `claude --resume <id>` finds the SAME+// conversation there — no `/login` in the pane.+//+// Why a copy is all it takes (measured on Claude Code 2.1.280): a transcript carries no account or+// org identity at all; `claude --resume <id>` under a config dir that lacks the file answers+// "No conversation found with session ID", and with the file copied into+// `<configDir>/projects/<encoded cwd>/<id>.jsonl` the lookup succeeds and only the login is left —+// which a managed account already has.+//+// The caller (the renderer's switch choreography) runs this AFTER the CLI has exited, so the source+// file is final. That ordering is what makes the prefix rule below sound: a transcript is+// append-only, so a target that is a byte-prefix of the source is simply an older copy of the same+// conversation (A→B→A), and replacing it loses nothing. A target that is NOT a prefix has diverged —+// both sides grew separately — and is never overwritten.+import { constants as fsConstants, promises as fs } from 'fs'+import path from 'path'+import { renameAtomic, tempNameFor } from './fs-atomic'+import type { ClaudeSessionCopyResult } from '../shared/types'++export type ClaudeSessionCopyOutcome = ClaudeSessionCopyResult++export interface ClaudeSessionCopyPlan {+ sessionId: string+ /** The transcript as it exists in the SOURCE account: `<srcConfig>/projects/<dir>/<id>.jsonl`. */+ sourceFile: string+ /** The TARGET account's `projects` root. */+ targetProjectsRoot: string+ /** Config dirs, for the best-effort `file-history/<id>` copy. */+ sourceConfigDir: string+ targetConfigDir: string+}++type PrefixState = 'identical' | 'prefix' | 'diverged'++const CHUNK = 1024 * 1024++/** Is `target` a byte-prefix of `source` (or identical to it)? Streamed, so a 100 MB transcript+ * costs two 1 MB buffers, not two whole files in memory. */+export async function prefixState(target: string, source: string): Promise<PrefixState> {+ const [ts, ss] = await Promise.all([fs.stat(target), fs.stat(source)])+ if (ts.size > ss.size) return 'diverged'+ const [tf, sf] = await Promise.all([fs.open(target, 'r'), fs.open(source, 'r')])+ try {+ const tb = Buffer.alloc(CHUNK)+ const sb = Buffer.alloc(CHUNK)+ let pos = 0+ while (pos < ts.size) {+ const len = Math.min(CHUNK, ts.size - pos)+ const [a, b] = await Promise.all([+ tf.read(tb, 0, len, pos),+ sf.read(sb, 0, len, pos)+ ])+ if (a.bytesRead !== len || b.bytesRead !== len) return 'diverged'+ if (!tb.subarray(0, len).equals(sb.subarray(0, len))) return 'diverged'+ pos += len+ }+ } finally {+ await Promise.all([tf.close(), sf.close()])+ }+ return ts.size === ss.size ? 'identical' : 'prefix'+}++async function exists(p: string): Promise<boolean> {+ try {+ await fs.lstat(p)+ return true+ } catch {+ return false+ }+}++/** Copy a directory tree without ever replacing a file the target already has. Best effort: the+ * transcript is what `--resume` needs; these sidecars (subagent transcripts, tool results,+ * `/rewind` file history) only make the resumed session more complete. */+async function copyTreeNoClobber(src: string, dst: string): Promise<void> {+ if (!(await exists(src))) return+ await fs.cp(src, dst, { recursive: true, force: false, errorOnExist: false }).catch(() => {})+}++export async function copyClaudeSession(plan: ClaudeSessionCopyPlan): Promise<ClaudeSessionCopyOutcome> {+ const projectDir = path.basename(path.dirname(plan.sourceFile))+ const targetDir = path.join(plan.targetProjectsRoot, projectDir)+ const targetFile = path.join(targetDir, `${plan.sessionId}.jsonl`)+ // Same file (a linked account pointing at the source's dir): nothing to move.+ if (path.resolve(targetFile) === path.resolve(plan.sourceFile)) return { ok: true, copied: false }++ let copied = false+ try {+ await fs.mkdir(targetDir, { recursive: true })+ const state: PrefixState | 'absent' = (await exists(targetFile))+ ? await prefixState(targetFile, plan.sourceFile)+ : 'absent'+ if (state === 'diverged') return { ok: false, reason: 'diverged' }+ if (state !== 'identical') {+ const tmp = tempNameFor(targetFile)+ try {+ // COPYFILE_EXCL: the temp name is unique, so this only refuses a pre-planted file/symlink.+ await fs.copyFile(plan.sourceFile, tmp, fsConstants.COPYFILE_EXCL)+ await renameAtomic(tmp, targetFile)+ } catch (e) {+ await fs.rm(tmp, { force: true }).catch(() => {})+ throw e+ }+ copied = true+ }+ } catch {+ return { ok: false, reason: 'failed' }+ }+ await copyTreeNoClobber(+ path.join(path.dirname(plan.sourceFile), plan.sessionId),+ path.join(targetDir, plan.sessionId)+ )+ await copyTreeNoClobber(+ path.join(plan.sourceConfigDir, 'file-history', plan.sessionId),+ path.join(plan.targetConfigDir, 'file-history', plan.sessionId)+ )+ return { ok: true, copied }+}diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.tsindex e554dcb0c..1388c44e1 100644--- a/src/core/transcript-reader.ts+++ b/src/core/transcript-reader.ts@@ -13,7 +13,7 @@ import { platform } from './platform'// (`~/.claude/projects` when accountId is undefined — bit-for-bit the old behavior). Impure// wrapper over the pure `transcriptRootFor`: the userData dir comes from the CorePlatform seam// (and only for the account branch) so this module — and its vitest test — stays electron-free.-function transcriptRoot(accountId?: string): string {+export function transcriptRoot(accountId?: string): string {const userData = accountId ? platform().userDataDir : null// A LINKED account's transcripts live in the dir the USER owns (`~/.claude-2/projects`), not// under `{userData}`. Resolved through the registry so this — and with it `resolveTranscriptPath`,diff --git a/src/preload/index.ts b/src/preload/index.tsindex ce50c6fd6..dccb9f93f 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -560,7 +560,9 @@ const api: NodeTerminalApi = {remove: (id, ctx) => ipcRenderer.invoke(IPC.claudeAccountsRemove, id, ctx),link: (configDir) => ipcRenderer.invoke(IPC.claudeAccountsLink, configDir),setSkillSharing: (id, enabled) =>- ipcRenderer.invoke(IPC.claudeAccountsSetSkillSharing, id, enabled)+ ipcRenderer.invoke(IPC.claudeAccountsSetSkillSharing, id, enabled),+ copySession: (sessionId, sourceAccountId, targetAccountId) =>+ ipcRenderer.invoke(IPC.claudeAccountsCopySession, sessionId, sourceAccountId, targetAccountId)},codexAccounts: {add: () => ipcRenderer.invoke(IPC.codexAccountsAdd),diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex cc48eb0aa..15e4f613c 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -379,7 +379,8 @@ export function buildStubApi(): Omit<cancelWaitLogin: U('claudeAccounts.cancelWaitLogin'),remove: U('claudeAccounts.remove'),link: U('claudeAccounts.link'),- setSkillSharing: U('claudeAccounts.setSkillSharing')+ setSkillSharing: U('claudeAccounts.setSkillSharing'),+ copySession: U('claudeAccounts.copySession')},codexAccounts: {add: U('codexAccounts.add'),diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex bc8a799ea..784e98b15 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -29,6 +29,7 @@ import {type GrokApi,type GrokCliCaps,type ClaudeSkillShareResult,+ type ClaudeSessionCopyResult,type CodexApi,type CodexIdentityCaps,UNKNOWN_CODEX_IDENTITY_CAPS,@@ -995,7 +996,16 @@ export function buildClaudeAccountsApi(client: RpcClient): Pick<NodeTerminalApi,IPC.claudeAccountsSetSkillSharing,id,enabled- ) as Promise<ClaudeSkillShareResult>+ ) 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) =>+ client.request(+ IPC.claudeAccountsCopySession,+ sessionId,+ sourceAccountId,+ targetAccountId+ ) as Promise<ClaudeSessionCopyResult>}}}diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 9cbed6b7a..6534bc91b 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -171,7 +171,7 @@ import {type AddHandlers} from '../lib/addMenuSpec'import { planSetProjectFolder } from '../lib/setProjectFolder'-import { observationIsRemote, type ObservationOrigin } from '../lib/accountChip'+import { effectiveAccountId, observationIsRemote, type ObservationOrigin } from '../lib/accountChip'import { transferConversationItems } from '../lib/transferItems'import { reopenVariants } from '../lib/reopenVariants'import { modelsForAgent, type GatewayModel } from '@shared/agents/model-gateway'@@ -508,6 +508,7 @@ import type { SshServer } from '@shared/ssh'import { sshHostKey } from '@shared/ssh'import type {BridgeLink,+ ClaudeSessionCopyResult,CanvasNodeState,ClosedSessionEntry,NodeKind,@@ -620,6 +621,11 @@ import {} from '../state/workspace'import { codexAccountSelectable, codexAccountSwitchStillEligible } from './codex-account-switch'import { resolveNewCodexNodeAccount, planCodexAccountSwitch } from './codex-account-ops'+import {+ claudeSwitchTargets,+ copyRefusalText,+ planClaudeAccountSwitch+} from './claude-account-switch'import type { CodexAccount } from '@shared/codex-account'import { useSystemCodexAccount } from '../state/systemCodexAccount'import { toKanbanSession } from './toKanbanSession'@@ -6572,6 +6578,79 @@ export function Canvas() {[setNodes, markDirty, connectedProjectIdForHost])+ // "Switch Claude account" on a running node (see `claude-account-switch.ts`): the ordinary+ // "Restart agent and shell" choreography, with the transcript copy + account rebind slotted in+ // between the CLI's exit and the pane recycle. The respawn then launches under the target's+ // CLAUDE_CONFIG_DIR and its cold-restore `--resume` continues the SAME conversation — no /login.+ const switchClaudeAccountNode = useCallback(+ async (nodeId: string, targetAccountId: string | undefined, targetLabel: string) => {+ const n = nodesRef.current.find((x) => x.id === nodeId)+ const st = useAgentStatus.getState().byId[nodeId]+ const accounts = useSettings.getState().settings.claudeAccounts+ const accountId = (n?.data.accountId as string | undefined) || undefined+ const decision = planClaudeAccountSwitch(+ {+ agentId: restartAgentIdOf(n),+ accountId,+ readAccountId: effectiveAccountId(accountId, st?.account, accounts),+ remote: !!n && isRemoteSessionNode(n.data),+ sessionId: restartSessionId(st?.sessionId, n?.data.agentSessionId)+ },+ targetAccountId,+ accounts+ )+ if (!decision.ok) {+ if (decision.reason === 'same-account') return+ setNotice({+ kind: 'error',+ text:+ 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.'+ : `${targetLabel} is no longer available. Nothing was changed.`+ })+ return+ }+ const fn = agentRestartFn(nodeId)+ if (!fn) {+ setNotice({ kind: 'error', text: 'Switch skipped: this terminal is not attached right now.' })+ return+ }+ const { plan } = decision+ let copy: ClaudeSessionCopyResult | undefined+ const outcome = await settleRestart(() =>+ fn(undefined, undefined, true, undefined, async () => {+ copy = await window.nodeTerminal.claudeAccounts+ .copySession(plan.sessionId, plan.sourceAccountId, plan.targetAccountId)+ .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+ // bump, so the respawn launches under the target's config dir (see `beforeRecycle`).+ return { accountId: plan.targetAccountId }+ })+ )+ if (copy?.ok) markDirty()+ if (outcome !== 'restarted') {+ setNotice({+ kind: 'error',+ text:+ outcome === 'not-eligible'+ ? 'Switch skipped: this session is busy or not attached — try again once its turn is done.'+ : 'Switch skipped: the agent did not quit in time. Nothing was changed.'+ })+ return+ }+ const moved = copy+ setNotice(+ moved?.ok+ ? { kind: 'info', text: `Switched to ${targetLabel} — resuming the same conversation.` }+ : { kind: 'error', text: copyRefusalText(moved?.ok === false ? moved.reason : 'failed', targetLabel) }+ )+ },+ [markDirty]+ )+// Who the bulk restart would act on, right now: the ACTIVE project's canvas (nodesRef holds// exactly that). Read fresh at every call — agent state and session ids arrive asynchronously.const bulkRestartPlan = useCallback((): BulkRestartPlan => {@@ -8401,6 +8480,56 @@ 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.+ ...(sourceAgentId === 'claude'+ ? (() => {+ const settingsNow = useSettings.getState().settings+ const targets = claudeSwitchTargets(settingsNow.claudeAccounts)+ 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+ )+ const row = (id: string | undefined, label: string): MenuItem => {+ const isCurrent = (id || undefined) === currentAccountId+ return {+ label: `${isCurrent ? '✓ ' : ''}${label}`,+ icon: <AgentIcon agentId="claude" />,+ disabled: !!why || isCurrent,+ hint: isCurrent+ ? 'This node already runs on this account.'+ : (why ??+ 'Quits Claude, moves this conversation to the account and resumes it there — no login needed.'),+ onClick: () => void switchClaudeAccountNode(ids[0], id, label)+ }+ }+ if (remote || session.source === 'relay')+ return [+ {+ label: 'Switch Claude account',+ icon: <IconSwitch />,+ disabled: true,+ hint: 'Not available for SSH or relay sessions yet.',+ onClick: () => {}+ }+ ] as MenuItem[]+ return [+ {+ type: 'submenu',+ label: 'Switch Claude account',+ icon: <IconSwitch />,+ children: [+ row(undefined, systemLabel),+ ...targets.map((a) => row(a.id, a.label || a.email || 'Account'))+ ]+ }+ ] as MenuItem[]+ })()+ : []),...(sourceAgentId === 'codex'? (() => {const codexAll = useSettings.getState().settings.codexAccounts@@ -8516,6 +8645,7 @@ export function Canvas() {pauseAgentNode,resumeAgentNode,switchCodexAccountNode,+ switchClaudeAccountNode,connectedProjectIdForHost,deleteNodes,gatewayModels,diff --git a/src/renderer/canvas/claude-account-switch.test.ts b/src/renderer/canvas/claude-account-switch.test.tsnew file mode 100644index 000000000..2277bf58c--- /dev/null+++ b/src/renderer/canvas/claude-account-switch.test.ts@@ -0,0 +1,60 @@+import { describe, it, expect } from 'vitest'+import type { ClaudeAccount } from '@shared/types'+import { claudeSwitchTargets, planClaudeAccountSwitch } from './claude-account-switch'++const acct = (id: string, extra: Partial<ClaudeAccount> = {}): ClaudeAccount => ({+ id,+ label: id,+ createdAt: 0,+ ...extra+})+const accounts = [acct('a'), acct('b'), acct('pend', { pending: true }), acct('rem', { host: 'u@h' })]+const node = { agentId: 'claude', accountId: 'a', remote: false, sessionId: 'sid-1' }++describe('claudeSwitchTargets', () => {+ it('offers only settled local accounts', () => {+ expect(claudeSwitchTargets(accounts).map((x) => x.id)).toEqual(['a', 'b'])+ })+})++describe('planClaudeAccountSwitch', () => {+ it('plans a switch that resumes the SAME conversation id', () => {+ expect(planClaudeAccountSwitch(node, 'b', accounts)).toEqual({+ ok: true,+ plan: { sessionId: 'sid-1', sourceAccountId: 'a', targetAccountId: 'b' }+ })+ })++ it('switches to and from the system account (undefined)', () => {+ expect(planClaudeAccountSwitch(node, undefined, accounts)).toMatchObject({+ ok: true,+ plan: { targetAccountId: undefined }+ })+ expect(+ planClaudeAccountSwitch({ ...node, accountId: undefined }, 'b', accounts)+ ).toMatchObject({ ok: true, plan: { sourceAccountId: undefined, targetAccountId: 'b' } })+ })++ it('reads the transcript from where the readers look (the observed account)', () => {+ expect(+ planClaudeAccountSwitch({ ...node, accountId: undefined, readAccountId: 'a' }, 'b', accounts)+ ).toMatchObject({ ok: true, plan: { sourceAccountId: 'a' } })+ })++ it('refuses — never substitutes — what cannot work', () => {+ const r = (n: Partial<typeof node> & { readAccountId?: string }, t: string | undefined) =>+ planClaudeAccountSwitch({ ...node, ...n }, t, accounts)+ expect(r({ agentId: 'codex' }, 'b')).toEqual({ ok: false, reason: 'not-claude' })+ // A custom agent on the claude harness never carries an account (boundAccountId).+ expect(r({ agentId: 'my-claude-wrapper' }, 'b')).toEqual({ ok: false, reason: 'not-claude' })+ expect(r({ remote: true }, 'b')).toEqual({ ok: false, reason: 'remote' })+ expect(r({}, 'a')).toEqual({ ok: false, reason: 'same-account' })+ expect(r({}, 'pend')).toEqual({ ok: false, reason: 'unavailable' })+ expect(r({}, 'rem')).toEqual({ ok: false, reason: 'unavailable' })+ expect(r({}, 'gone')).toEqual({ ok: false, reason: 'unavailable' })+ expect(r({ sessionId: undefined as unknown as string }, 'b')).toEqual({+ ok: false,+ reason: 'no-session'+ })+ })+})diff --git a/src/renderer/canvas/claude-account-switch.ts b/src/renderer/canvas/claude-account-switch.tsnew file mode 100644index 000000000..0bb960953--- /dev/null+++ b/src/renderer/canvas/claude-account-switch.ts@@ -0,0 +1,79 @@+// "Switch Claude account" on a RUNNING node: move the conversation onto another account the user+// has already logged into, with no `/login` in the pane. The Claude counterpart of the Codex switch+// (`codex-account-ops.ts`), and much simpler: Claude's account IS its config dir, and a transcript+// carries no account identity, so the whole switch is+//+// 1. quit the CLI (the ordinary "Restart agent and shell" exit — refused while busy/blocked),+// 2. copy the transcript into the target account's dir (core `claudeAccounts.copySession`),+// 3. rebind the node's `accountId`, and+// 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.+//+// 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'++/** 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)+}++export interface ClaudeSwitchNode {+ agentId?: string+ /** The account the node was launched under (`data.accountId`; undefined = system). */+ 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. */+ remote: boolean+ sessionId?: string+}++export interface ClaudeSwitchPlan {+ sessionId: string+ sourceAccountId: string | undefined+ targetAccountId: string | undefined+}++export type ClaudeSwitchDecision =+ | { ok: true; plan: ClaudeSwitchPlan }+ | { ok: false; reason: 'not-claude' | 'remote' | 'no-session' | 'same-account' | 'unavailable' }++export function planClaudeAccountSwitch(+ node: ClaudeSwitchNode,+ targetAccountId: string | undefined,+ accounts: readonly ClaudeAccount[]+): ClaudeSwitchDecision {+ // The builtin only: `boundAccountId` (shared/agents/account-binding.ts) never binds an account to+ // any other agent — a custom agent on the claude harness included — so neither may a switch.+ if (node.agentId !== 'claude') return { ok: false, reason: 'not-claude' }+ if (node.remote) return { ok: false, reason: 'remote' }+ const target = targetAccountId || undefined+ 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))+ return { ok: false, reason: 'unavailable' }+ if (!node.sessionId) return { ok: false, reason: 'no-session' }+ return {+ ok: true,+ plan: {+ sessionId: node.sessionId,+ sourceAccountId: node.readAccountId || node.accountId || undefined,+ targetAccountId: target+ }+ }+}++/** The notice for a copy refusal. The pane still comes back (on the old account) either way. */+export function copyRefusalText(reason: string, targetLabel: string): string {+ const why =+ reason === 'diverged'+ ? `${targetLabel} already holds a different copy of this conversation`+ : reason === 'no-transcript'+ ? 'its transcript could not be found'+ : reason === 'unknown-account'+ ? `${targetLabel} is no longer available`+ : 'the transcript could not be copied'+ return `Could not move this conversation to ${targetLabel} — ${why}. It was resumed on its current account.`+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex d7c01531f..2158070be 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -3771,7 +3771,7 @@ export function TerminalNode({}const unregisterRestart = registerAgentRestart(id,- guardConcurrentRestart(id, async (targetAgentId?: AgentId, targetModel?: string, restartShell?: boolean, clearEnv?: boolean) => {+ guardConcurrentRestart(id, async (targetAgentId?: AgentId, targetModel?: string, restartShell?: boolean, clearEnv?: boolean, beforeRecycle?: () => Promise<Record<string, unknown> | void>) => {const st = useAgentStatus.getState().byId[id]const currentNode = getNode(id)const agentSessionId = restartSessionId(st?.sessionId, currentNode?.data.agentSessionId)@@ -3877,8 +3877,12 @@ export function TerminalNode({isLive: restartTarget})if (exited !== 'exited') return exited+ // Swallowed: a failed step must not strand the pane at a bare shell — the recycle below+ // still brings the conversation back (on whatever account the node is bound to).+ const patch = beforeRecycle ? await beforeRecycle().catch(() => undefined) : undefinedtransport.recycle(id)updateNodeData(id, (node) => ({+ ...(patch ?? {}),agentId: target,respawnNonce: ((node.data.respawnNonce as number | undefined) ?? 0) + 1}))diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.tsindex 2109ab589..ad32c5975 100644--- a/src/renderer/terminal/agent-restart.ts+++ b/src/renderer/terminal/agent-restart.ts@@ -491,7 +491,17 @@ export type AgentRestartFn = (// cold-restore auto-resume keeps the same conversation. Uses `clearEnvEligibility` (permits busy,// since `terminateForeground` is PID-safe — no `/exit` typed into a dialog) and recycles the same// way a model switch does, because tmux env changes do not retroactively change an existing shell.- clearEnv?: boolean+ clearEnv?: boolean,+ // Only with `restartShell`: runs AFTER the CLI has exited and BEFORE the pane is recycled — the+ // one moment the conversation's transcript is final and nothing is writing it. The account switch+ // copies the transcript into the target account here and rebinds the node, so the recycle's+ // respawn launches under the new CLAUDE_CONFIG_DIR and its cold-restore `--resume` finds the SAME+ // conversation. It cannot veto the recycle: the CLI is already gone, and the recycle + auto-resume+ // is how the conversation comes back either way (on the old account when the step did nothing).+ // The node-data patch it returns is merged into the SAME update as the respawn bump — a separate+ // Canvas `setNodes` in the same tick races React Flow's `updateNodeData` queue, which rebuilds the+ // node from the store's copy and can silently drop the rebind.+ beforeRecycle?: () => Promise<Record<string, unknown> | void>) => Promise<RestartOutcome>const restartFns = new Map<string, AgentRestartFn>()diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 5854e1dec..a7ad2d665 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -64,6 +64,7 @@ export const IPC = {claudeAccountsRemove: 'claude-accounts:remove',claudeAccountsLink: 'claude-accounts:link',claudeAccountsSetSkillSharing: 'claude-accounts:set-skill-sharing',+ claudeAccountsCopySession: 'claude-accounts:copy-session',// Machine-scoped managed Codex accounts (S6). Add/device-login/removal, plus the three-phase,// owner-authorized account switch (resume the SAME conversation id, never fork) and the// source-side leg of moving an idle conversation to an SSH account. See main/codex-accounts.ts.diff --git a/src/shared/types.ts b/src/shared/types.tsindex d05cad046..fc278cd24 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -2783,8 +2783,27 @@ export interface ClaudeAccountsApi {* (the account's `skills/` resolves to the system one) and `failed` (an EPERM, a vanished skill).*/setSkillSharing(id: string, enabled: boolean): Promise<ClaudeSkillShareResult>+ /**+ * 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+ * diverged copy (`diverged`); never throws — every refusal is a reason.+ */+ copySession(+ sessionId: string,+ sourceAccountId: string | undefined,+ targetAccountId: string | undefined+ ): Promise<ClaudeSessionCopyResult>}+/** What `claudeAccounts.copySession` did. `copied: false` = the target already held this exact copy. */+export type ClaudeSessionCopyResult =+ | { ok: true; copied: boolean }+ | {+ ok: false+ reason: 'bad-request' | 'unknown-account' | 'no-transcript' | 'diverged' | 'failed'+ }+/** What one `setSkillSharing` / launch reconcile did. Counts, never an exception. */export interface ClaudeSkillShareResult {linked: number