Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(accounts): move running Claude sessions to the system account before removing an account

Enes Kirca2e81d4caaa2d
diff --git a/CLAUDE.md b/CLAUDE.md
index 17c8262ec..f6f9029da 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -5920,7 +5920,14 @@ bridges enter live state only via `appendBridgeEdges`) and the server
**login node** that runs `claude /login` under the account dir. Core polls the dir's
`.claude.json` (`LOGIN_POLL_MS` 2 s, up to `LOGIN_TIMEOUT_MS` 5 min) for `oauthAccount.email`;
on capture the account flips out of `pending` with its email as the default label. Account
- removal cancels any pending wait + `markDirty`. **Codex accounts have the same two halves** —
+ removal cancels any pending wait + `markDirty`. **A removal that deletes the dir first MOVES the
+ account's Claude sessions to the system account** (`renderer/lib/accountRemoval.ts`): a running
+ `claude` keeps the account's `CLAUDE_CONFIG_DIR` in its tmux env, so deleting the dir under it
+ left the CLI logged out and repainting half-blank. Active canvas → the ordinary switch
+ (`runClaudeAccountSwitch` to system), or copy + recycle for an idle node the switch cannot drive;
+ other projects → `copySession` + tmux kill (they cold-resume on next open). Any busy session, or
+ one that could not be moved, refuses the removal and keeps the account. Linked accounts and a
+ disconnected host's account delete nothing, so they skip the move. **Codex accounts have the same two halves** —
`createCodexAccountLoginNode` (`codex login`, title "Codex login") behind the
`nodeterm:add-codex-account-login` listener, with `codexAccounts.waitLogin` polling the managed
home's `auth.json`. **On Windows the Codex identity comes from that `auth.json`'s id_token JWT
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 869247831..5477fb8da 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -963,6 +963,10 @@ import {
switchOutcomeNotice,
type ClaudeSwitchOutcome
} from './claude-account-switch'
+import {
+ isBusyState,
+ registerActiveCanvasAccountMover
+} from '../lib/accountRemoval'
import type { CodexAccount } from '@shared/codex-account'
import { useSystemCodexAccount } from '../state/systemCodexAccount'
import { kanbanSessionsFrom, toKanbanSession } from './toKanbanSession'
@@ -9121,6 +9125,93 @@ export function Canvas() {
return ready.length + busy.length
}, [])
+ // Account REMOVAL's side on the active canvas (lib/accountRemoval.ts): every Claude session on
+ // the account is moved onto the system account before Settings deletes the account's dir. The
+ // move is the ordinary switch (`runClaudeAccountSwitch`). A node the switch cannot drive — not
+ // attached (released offscreen), or no conversation id yet — but that is idle gets the same
+ // result the hard way: copy its transcript, then recycle its tmux session with the account
+ // cleared, so the respawn (or its revive) cold-starts under the system login and resumes.
+ useEffect(
+ () =>
+ registerActiveCanvasAccountMover({
+ sessions: (accountId, hostKey) => {
+ const byId = useAgentStatus.getState().byId
+ const { ready, busy } = bulkSwitchCandidates(
+ nodesRef.current
+ .filter((n) => n.type === 'terminal' && !isAccountLoginNode(n.data))
+ .map((n) => ({
+ id: n.id,
+ agentId: restartAgentIdOf(n),
+ accountId: (n.data.accountId as string | undefined) || undefined,
+ hostKey: claudeSwitchHostKey(n),
+ busy: isBusyState(byId[n.id]?.state)
+ })),
+ accountId,
+ hostKey
+ )
+ return { ready: ready.map((n) => n.id), busy: busy.map((n) => n.id) }
+ },
+ moveToSystem: async (accountId, ids, ctx) => {
+ const outcomes = await startBulkSwitch(ids, (id) => runClaudeAccountSwitch(id, undefined))
+ const stuck: string[] = []
+ const recycle: string[] = []
+ for (const [i, id] of ids.entries()) {
+ const o = outcomes[i]
+ if (o?.kind === 'switched') continue
+ const driveless =
+ (o?.kind === 'refused' && (o.reason === 'not-attached' || o.reason === 'no-session')) ||
+ (o?.kind === 'not-restarted' && o.outcome === 'not-eligible')
+ const st = useAgentStatus.getState().byId[id]
+ // Busy by now (it started a turn mid-move): recycling would kill that turn.
+ if (!driveless || isBusyState(st?.state)) {
+ stuck.push(id)
+ continue
+ }
+ const n = nodesRef.current.find((x) => x.id === id)
+ const sessionId = restartSessionId(st?.sessionId, n?.data.agentSessionId)
+ if (sessionId) {
+ const accounts = useSettings.getState().settings.claudeAccounts
+ const copy = await window.nodeTerminal.claudeAccounts
+ .copySession(
+ sessionId,
+ effectiveAccountId(accountId, st?.account, accounts) ?? accountId,
+ undefined,
+ ctx
+ )
+ .catch((): ClaudeSessionCopyResult => ({ ok: false, reason: 'failed' }))
+ if (!copy.ok) {
+ stuck.push(id)
+ continue
+ }
+ }
+ recycle.push(id)
+ }
+ if (recycle.length) {
+ const set = new Set(recycle)
+ for (const id of recycle) transport.recycle(id)
+ usePendingPause.getState().remove(recycle) // the recycled sessions' CLIs are gone with them
+ setNodes((ns) =>
+ ns.map((n) =>
+ set.has(n.id)
+ ? {
+ ...n,
+ data: {
+ ...n.data,
+ accountId: undefined,
+ respawnNonce: ((n.data.respawnNonce as number | undefined) ?? 0) + 1
+ }
+ }
+ : n
+ )
+ )
+ markDirty()
+ }
+ return stuck
+ }
+ }),
+ [runClaudeAccountSwitch, setNodes, 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 => {
diff --git a/src/renderer/components/settings/sections/AccountsSection.tsx b/src/renderer/components/settings/sections/AccountsSection.tsx
index 090347687..cc0366aed 100644
--- a/src/renderer/components/settings/sections/AccountsSection.tsx
+++ b/src/renderer/components/settings/sections/AccountsSection.tsx
@@ -5,6 +5,12 @@ import type { CodexAccount } from '@shared/codex-account'
import { E_UNSUPPORTED } from '@shared/rpc'
import { sshHostKey } from '@shared/ssh'
import { useAgentStatus } from '../../../state/agentStatus'
+import { transport } from '../../../terminal/local-transport'
+import {
+ activeCanvasAccountMover,
+ otherProjectSessions,
+ removalBlockedText
+} from '../../../lib/accountRemoval'
import { useSettings } from '../../../state/settings'
import { useSystemAccount } from '../../../state/systemAccount'
import { useSystemCodexAccount } from '../../../state/systemCodexAccount'
@@ -414,6 +420,9 @@ function SkillSharingRow({
)
}
+/** How long removal waits after ending other projects' local sessions before deleting the dir. */
+const LOCAL_KILL_SETTLE_MS = 1500
+
/** Counts nodes bound to an account across every project's SERIALIZED nodes. The active
* project's live React Flow edits since the last commit aren't reflected here, so the count
* can be slightly stale for the active canvas — acceptable for a confirmation warning. */
@@ -726,9 +735,81 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.
}
}
+ /**
+ * Move every Claude session on `account` onto the system account before its dir is deleted (see
+ * lib/accountRemoval.ts). Returns the refusal line, or null once nothing runs under it any more.
+ * Busy sessions refuse the removal up front, before anything is touched.
+ */
+ const moveSessionsOffAccount = async (account: ClaudeAccount): Promise<string | null> => {
+ const mover = activeCanvasAccountMover()
+ const live = mover?.sessions(account.id, account.host) ?? { ready: [], busy: [] }
+ const { projects, activeProjectId } = useProjects.getState()
+ const byId = useAgentStatus.getState().byId
+ const others = otherProjectSessions({
+ accountId: account.id,
+ accountHost: account.host,
+ activeProjectId,
+ projects: projects.map((p) => ({
+ id: p.id,
+ hostKey: p.ssh ? sshHostKey(p.ssh.server) : undefined,
+ nodes: p.nodes
+ .filter((n) => !n.kind || n.kind === 'terminal')
+ .map((n) => ({
+ id: n.id,
+ agentId: n.agentId,
+ accountId: n.accountId,
+ login: isAccountLoginNode(n)
+ }))
+ })),
+ stateOf: (id) => byId[id]?.state,
+ sessionIdOf: (id) =>
+ byId[id]?.sessionId ||
+ projects.flatMap((p) => p.nodes).find((n) => n.id === id)?.agentSessionId ||
+ undefined
+ })
+ const busy = removalBlockedText(account.label, live.busy.length + others.busy.length, 0)
+ if (busy) return busy
+ const projectId = account.host ? connectedProjectIdForHost(account.host) : undefined
+ const ctx = projectId ? { projectId } : undefined
+ // Other projects first: copying is the only step that can fail there, and it changes nothing.
+ for (const o of others.ready) {
+ if (!o.sessionId) continue
+ const copy = await window.nodeTerminal.claudeAccounts
+ .copySession(o.sessionId, account.id, undefined, ctx)
+ .catch(() => ({ ok: false as const }))
+ if (!copy.ok) return removalBlockedText(account.label, 0, 1)
+ }
+ const stuck = mover && live.ready.length ? await mover.moveToSystem(account.id, live.ready, ctx) : []
+ if (stuck.length) return removalBlockedText(account.label, 0, stuck.length)
+ // End the other projects' tmux sessions: their next open cold-starts under the system account
+ // (the store update in confirmRemove clears their accountId) and auto-resumes the copy.
+ const otherIds = others.ready.map((o) => o.nodeId)
+ if (otherIds.length) {
+ if (projectId) {
+ await window.nodeTerminal.sshProject.killSessions(projectId, otherIds).catch(() => {})
+ } else {
+ for (const id of otherIds) transport.recycle(id)
+ // Fire-and-forget kills: let the old CLIs go before the dir is deleted, or one still alive
+ // writes its files straight back into it.
+ await new Promise((r) => setTimeout(r, LOCAL_KILL_SETTLE_MS))
+ }
+ }
+ return null
+ }
+
const confirmRemove = async (account: ClaudeAccount): Promise<void> => {
setPendingRemove(null)
setRemoveError(null)
+ // Only a removal that DELETES the dir needs the move: a linked folder and a remote account on a
+ // disconnected host are only forgotten, and their sessions keep running unharmed.
+ const deletes = !account.configDir && (!account.host || !!connectedProjectIdForHost(account.host))
+ if (deletes && !account.pending) {
+ const blocked = await moveSessionsOffAccount(account)
+ if (blocked) {
+ setRemoveError(blocked)
+ return
+ }
+ }
try {
// Removing a pending account: stop the 5-minute waitLogin poll loop first.
if (account.pending) await window.nodeTerminal.claudeAccounts.cancelWaitLogin(account.id)
@@ -777,9 +858,9 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.
if (a.host && !connectedProjectIdForHost(a.host)) {
return `Remove account "${a.label}"? ${a.host} is not connected, so nodeterm only forgets it — its login and transcripts stay on that host. ${fallout}`
}
- return `Remove account "${a.label}"? Its logged-in credentials and all its Claude transcripts${
+ return `Remove account "${a.label}"? Its logged-in credentials and Claude transcripts${
a.host ? ` on ${a.host}` : ''
- } will be deleted. ${fallout}`
+ } will be deleted. Its running Claude sessions move to the system account first and resume there. ${fallout}`
}
// ── Codex ────────────────────────────────────────────────────────────────────────────────────
diff --git a/src/renderer/lib/accountRemoval.test.ts b/src/renderer/lib/accountRemoval.test.ts
new file mode 100644
index 000000000..cafddab52
--- /dev/null
+++ b/src/renderer/lib/accountRemoval.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest'
+import { otherProjectSessions, removalBlockedText, type RemovalNode } from './accountRemoval'
+
+const claude = (id: string, accountId?: string, extra: Partial<RemovalNode> = {}): RemovalNode => ({
+ id,
+ agentId: 'claude',
+ accountId,
+ login: false,
+ ...extra
+})
+
+describe('otherProjectSessions', () => {
+ const base = {
+ accountId: 'acc',
+ activeProjectId: 'active',
+ stateOf: (): string | undefined => undefined,
+ sessionIdOf: (id: string): string | undefined => `sid-${id}`
+ }
+
+ it('collects the account’s Claude sessions outside the active project', () => {
+ const r = otherProjectSessions({
+ ...base,
+ projects: [
+ { id: 'active', nodes: [claude('a1', 'acc')] },
+ { id: 'p2', nodes: [claude('b1', 'acc'), claude('b2', 'other'), claude('b3')] }
+ ]
+ })
+ expect(r).toEqual({ ready: [{ projectId: 'p2', nodeId: 'b1', sessionId: 'sid-b1' }], busy: [] })
+ })
+
+ it('skips login nodes, plain terminals and other agents', () => {
+ const r = otherProjectSessions({
+ ...base,
+ projects: [
+ {
+ id: 'p2',
+ nodes: [
+ claude('login', 'acc', { login: true }),
+ { id: 'shell', accountId: 'acc', login: false },
+ claude('cx', 'acc', { agentId: 'codex' })
+ ]
+ }
+ ]
+ })
+ expect(r.ready).toEqual([])
+ })
+
+ it('only looks at projects on the account’s own machine', () => {
+ const r = otherProjectSessions({
+ ...base,
+ accountHost: 'root@box',
+ projects: [
+ { id: 'local', nodes: [claude('l1', 'acc')] },
+ { id: 'other-host', hostKey: 'root@elsewhere', nodes: [claude('o1', 'acc')] },
+ { id: 'host', hostKey: 'root@box', nodes: [claude('h1', 'acc')] }
+ ]
+ })
+ expect(r.ready.map((s) => s.nodeId)).toEqual(['h1'])
+ })
+
+ it('reports working and blocked sessions as busy', () => {
+ const states: Record<string, string> = { b1: 'working', b2: 'blocked', b3: 'waiting' }
+ const r = otherProjectSessions({
+ ...base,
+ stateOf: (id) => states[id],
+ projects: [{ id: 'p2', nodes: [claude('b1', 'acc'), claude('b2', 'acc'), claude('b3', 'acc')] }]
+ })
+ expect(r.busy).toEqual(['b1', 'b2'])
+ expect(r.ready.map((s) => s.nodeId)).toEqual(['b3'])
+ })
+})
+
+describe('removalBlockedText', () => {
+ it('is null when nothing blocks the removal', () => {
+ expect(removalBlockedText('Work', 0, 0)).toBeNull()
+ })
+ it('names busy sessions before stuck ones', () => {
+ expect(removalBlockedText('Work', 2, 1)).toMatch(/^2 sessions on "Work" are working/)
+ expect(removalBlockedText('Work', 0, 1)).toMatch(/^1 session on "Work" could not be moved/)
+ })
+})
diff --git a/src/renderer/lib/accountRemoval.ts b/src/renderer/lib/accountRemoval.ts
new file mode 100644
index 000000000..63df526c4
--- /dev/null
+++ b/src/renderer/lib/accountRemoval.ts
@@ -0,0 +1,120 @@
+// Removing a managed Claude account MOVES its running sessions onto the system account before the
+// account's dir is deleted.
+//
+// Why: a running `claude` keeps `CLAUDE_CONFIG_DIR=<account dir>` in its tmux session's env, and
+// clearing the node's `accountId` cannot change that — the shell's env was fixed at spawn. Deleting
+// the dir under it left the CLI logged out with its transcripts gone, and the pane repainted
+// half-blank until the user restarted it by hand (and then had to /login again).
+//
+// So removal first runs the existing account switch onto the system account for every Claude
+// session on the account — the active canvas through `runClaudeAccountSwitch` (quit → copy the
+// transcript → rebind → recycle → `--resume`), every other project by copying the transcript and
+// ending its tmux session, so its next open cold-starts under the system login and resumes. Only
+// then is the dir deleted. A session that is mid-turn or waiting on a permission prompt refuses
+// the whole removal: quitting it would abandon its work or answer its prompt.
+//
+// Pure planning lives here (unit-tested). The active canvas registers its side through
+// `registerActiveCanvasAccountMover` — the Settings overlay cannot see the live React Flow nodes,
+// and the projects store's copy of the active project lags the canvas until the next commit.
+
+/** A serialized terminal node, reduced to what the plan needs. */
+export interface RemovalNode {
+ id: string
+ agentId?: string
+ accountId?: string
+ /** The account's own `claude /login` node — deleted with the account, never moved. */
+ login: boolean
+}
+
+export interface RemovalProject {
+ id: string
+ /** `sshHostKey` of an SSH project's server; undefined for a local project. */
+ hostKey?: string
+ nodes: RemovalNode[]
+}
+
+export interface OtherProjectSession {
+ projectId: string
+ nodeId: string
+ sessionId?: string
+}
+
+/**
+ * Claude sessions on `accountId` in every project EXCEPT the active one (the active canvas is
+ * read live). Only projects on the account's own machine count: a local account's sessions run in
+ * local projects, a remote account's in projects on its host. Builtin claude only — no other agent
+ * is ever bound to a Claude account (`boundAccountId`).
+ */
+export function otherProjectSessions(input: {
+ accountId: string
+ accountHost?: string
+ activeProjectId: string | null
+ projects: readonly RemovalProject[]
+ stateOf: (nodeId: string) => string | undefined
+ sessionIdOf: (nodeId: string) => string | undefined
+}): { ready: OtherProjectSession[]; busy: string[] } {
+ const ready: OtherProjectSession[] = []
+ const busy: string[] = []
+ for (const p of input.projects) {
+ if (p.id === input.activeProjectId) continue
+ if ((p.hostKey || undefined) !== (input.accountHost || undefined)) continue
+ for (const n of p.nodes) {
+ if (n.login || n.agentId !== 'claude' || n.accountId !== input.accountId) continue
+ if (isBusyState(input.stateOf(n.id))) busy.push(n.id)
+ else ready.push({ projectId: p.id, nodeId: n.id, sessionId: input.sessionIdOf(n.id) })
+ }
+ }
+ return { ready, busy }
+}
+
+export function isBusyState(state: string | undefined): boolean {
+ return state === 'working' || state === 'blocked'
+}
+
+/** The removal's refusal line, or null when nothing blocks it. */
+export function removalBlockedText(label: string, busy: number, stuck: number): string | null {
+ if (busy) {
+ return (
+ `${busy} ${busy === 1 ? 'session' : 'sessions'} on "${label}" ${busy === 1 ? 'is' : 'are'} ` +
+ 'working or waiting for an answer. Let them finish, then remove the account — their ' +
+ 'conversations move to the system account.'
+ )
+ }
+ if (stuck) {
+ return (
+ `${stuck} ${stuck === 1 ? 'session' : 'sessions'} on "${label}" could not be moved to the ` +
+ 'system account, so the account was kept. Check those panes and try again.'
+ )
+ }
+ return null
+}
+
+// ── Active canvas bridge (same register/lookup shape as agent-restart's closures) ─────────────
+
+export interface ActiveCanvasAccountMover {
+ /** The active canvas's Claude sessions on `accountId` (on `hostKey`'s machine). */
+ sessions(accountId: string, hostKey: string | undefined): { ready: string[]; busy: string[] }
+ /**
+ * Move `ids` onto the system account. Resolves the ids that did NOT land — those still run under
+ * the account, so its dir must not be deleted. `ctx` is the connected project on the account's
+ * host, for an SSH account.
+ */
+ moveToSystem(
+ accountId: string,
+ ids: readonly string[],
+ ctx: { projectId: string } | undefined
+ ): Promise<string[]>
+}
+
+let activeMover: ActiveCanvasAccountMover | undefined
+
+export function registerActiveCanvasAccountMover(mover: ActiveCanvasAccountMover): () => void {
+ activeMover = mover
+ return () => {
+ if (activeMover === mover) activeMover = undefined
+ }
+}
+
+export function activeCanvasAccountMover(): ActiveCanvasAccountMover | undefined {
+ return activeMover
+}