Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(accounts): move an account's sessions all at once, and survive a project switch
review8cb875587035
diff --git a/CLAUDE.md b/CLAUDE.mdindex 59881eaff..dad7d46d3 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -3700,9 +3700,19 @@ command-bearing opens; this does not add a human-confirm dialog or change mobilenode's rows from the SAME builder the canvas node menu uses (`accountSwitchRows` → KanbanView's`accountMenuItems`), and the **usage popover** puts "⇄ Move N sessions" on each account row —every Claude session on this canvas running on that account, on the popover's machine- (`bulkSwitchCandidates`), is moved to the picked account ONE AT A TIME (N parallel copies +- recycles on one host is a load spike), busy ones skipped and counted, one summary line- (`summarizeBulkSwitch`). The cross-project board (GlobalKanbanView) does not offer it:+ (`bulkSwitchCandidates`), is moved to the picked account ALL AT ONCE (`startBulkSwitch`), busy+ ones skipped and counted, one summary line (`summarizeBulkSwitch`). It was one-at-a-time and+ that broke twice: N sessions cost N exits in a row, and a switch reads its node off the live+ canvas when it STARTS, so a project switch mid-run refused every node still waiting its turn.+ An SSH host's load is paced in core (`SshChildGate`, the pty spawn gate), not by serializing.+ While it runs, Canvas hands the popover `accountMove`: the moving sessions keep their OLD+ account until each lands, so the source row reads "Moving N sessions…" instead of re-offering+ them, and every other row's move is disabled (a second bulk move would be refused).+ **A recycling restart can outlive its canvas** (`settleRecycledNode`): if the project was+ switched while the CLI quit, React Flow no longer holds the node and `updateNodeData` is a+ silent no-op — the rebind then goes into the stored project (`projects.rebindNode`) and the+ park is DROPPED, because it holds the session this recycle just killed and re-adopting it on+ return showed a dead pane on the old account. The cross-project board (GlobalKanbanView) does not offer it:its cards belong to other projects' canvases, whose nodes have no restart closure mounted.- **`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 colordiff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex b0df4e956..cc370314f 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -267,7 +267,7 @@ import {terminalShortcutPolicy} from '../lib/keybindingOverrides'import { CanvasPills } from '../components/CanvasPills'-import { UsageIndicator } from '../components/UsageIndicator'+import { UsageIndicator, type AccountMoveProgress } from '../components/UsageIndicator'import { SystemResourcePill } from '../components/SystemResourcePill'import { PresenceLayer } from '../components/PresenceLayer'import { Facepile } from '../components/Facepile'@@ -723,6 +723,7 @@ import {claudeSwitchHostKey,claudeSwitchTargets,planClaudeAccountSwitch,+ startBulkSwitch,summarizeBulkSwitch,switchOutcomeNotice,type ClaudeSwitchOutcome@@ -7293,20 +7294,24 @@ export function Canvas() {/*** The usage popover's bulk move: every Claude session on this canvas that runs on `from` (and on- * the popover's machine) is moved to `to`, ONE AT A TIME — each is the same quit → copy → recycle- * as the single switch, and running them in parallel would put N transcript copies and N pane- * recycles on one host at once. Busy sessions are skipped, never interrupted. One summary line.+ * the popover's machine) is moved to `to`, ALL AT ONCE — each is the same quit → copy → recycle+ * as the single switch (`startBulkSwitch` says why they are not serialized, and where an SSH+ * host's load is paced instead). Busy sessions are skipped, never interrupted. One summary line.*/const bulkSwitchRunning = useRef(false)+ // The same move, as the popover sees it: its sessions keep their OLD account until each lands, so+ // without this the source row re-offers them mid-move (see `MoveSessionsControl`).+ const [accountMove, setAccountMove] = useState<AccountMoveProgress | null>(null)const moveAccountSessions = useCallback(async (from: string | undefined, to: string | undefined, toLabel: string) => {if (bulkSwitchRunning.current) returnbulkSwitchRunning.current = truetry {const byId = useAgentStatus.getState().byId- const scope = scopeFromKey(- usageScopeKey(useProjects.getState().getProject(useProjects.getState().activeProjectId))+ const scopeKey = usageScopeKey(+ useProjects.getState().getProject(useProjects.getState().activeProjectId))+ const scope = scopeFromKey(scopeKey)const { ready, busy } = bulkSwitchCandidates(nodesRef.current.filter((n) => n.type === 'terminal')@@ -7321,15 +7326,22 @@ export function Canvas() {scope.kind === 'ssh' ? scope.hostKey : undefined)if (ready.length + busy.length === 0) return+ setAccountMove({ from, count: ready.length, scopeKey })setNotice({kind: 'info',text: `Moving ${ready.length} ${ready.length === 1 ? 'session' : 'sessions'} to ${toLabel}…`})- const outcomes: ClaudeSwitchOutcome[] = []- for (const n of ready) outcomes.push(await runClaudeAccountSwitch(n.id, to))+ // All at once, not one after another — see `startBulkSwitch`.+ const outcomes = (+ await startBulkSwitch(+ ready.map((n) => n.id),+ (id) => runClaudeAccountSwitch(id, to)+ )+ ).map((o): ClaudeSwitchOutcome => o ?? { kind: 'not-restarted', outcome: 'exit-timeout' })setNotice(summarizeBulkSwitch(outcomes, busy.length, toLabel))} finally {bulkSwitchRunning.current = false+ setAccountMove(null)}},[runClaudeAccountSwitch]@@ -16503,6 +16515,7 @@ export function Canvas() {onSetDefaultAccount={setProjectDefaultAccount}countAccountSessions={countAccountSessions}onMoveSessions={(from, to, label) => void moveAccountSessions(from, to, label)}+ accountMove={accountMove}/></CanvasPills>diff --git a/src/renderer/canvas/claude-account-switch.test.ts b/src/renderer/canvas/claude-account-switch.test.tsindex 4495f646a..6620419e3 100644--- a/src/renderer/canvas/claude-account-switch.test.ts+++ b/src/renderer/canvas/claude-account-switch.test.ts@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest'import type { ClaudeAccount } from '@shared/types'-import { claudeSwitchTargets, planClaudeAccountSwitch } from './claude-account-switch'+import { claudeSwitchTargets, planClaudeAccountSwitch, startBulkSwitch } from './claude-account-switch'const acct = (id: string, extra: Partial<ClaudeAccount> = {}): ClaudeAccount => ({id,@@ -130,3 +130,28 @@ describe('bulk move', () => {)})})++describe('startBulkSwitch', () => {+ // The bulk move used to await each switch before starting the next: N sessions took N exits in a+ // row, and a project switch mid-run unmounted every node that had not started yet, so they were+ // silently skipped. Every switch must be under way before the first one settles.+ it('starts every switch before any of them settles, and returns every outcome', async () => {+ const started: string[] = []+ const release: Array<() => void> = []+ const run = (id: string): Promise<string> => {+ started.push(id)+ return new Promise((r) => release.push(() => r(`done-${id}`)))+ }+ const all = startBulkSwitch(['a', 'b', 'c'], run)+ expect(started).toEqual(['a', 'b', 'c'])+ release.forEach((f) => f())+ expect(await all).toEqual(['done-a', 'done-b', 'done-c'])+ })++ it('one switch that rejects does not swallow the others', async () => {+ const out = await startBulkSwitch(['a', 'b'], (id) =>+ id === 'a' ? Promise.reject(new Error('boom')) : Promise.resolve('ok')+ )+ expect(out).toEqual([undefined, 'ok'])+ })+})diff --git a/src/renderer/canvas/claude-account-switch.ts b/src/renderer/canvas/claude-account-switch.tsindex 3ebfd7437..d4d7245ee 100644--- a/src/renderer/canvas/claude-account-switch.ts+++ b/src/renderer/canvas/claude-account-switch.ts@@ -186,6 +186,25 @@ export function bulkSwitchCandidates(return { ready: on.filter((n) => !n.busy), busy: on.filter((n) => n.busy) }}+/**+ * Run a bulk move's switches ALL AT ONCE, and come back with every outcome (a rejection reads as+ * `undefined`, which the caller counts as skipped — it never swallows the others).+ *+ * Each switch waits seconds for its CLI to quit, so awaiting them one after another made N sessions+ * cost N exits in a row — visibly one pane at a time. Worse, a switch reads its node off the live+ * canvas when it STARTS: a project switch mid-run unmounted every node still waiting its turn, and+ * each was then refused as "not attached" — the move stopped halfway. Starting them together means+ * every node is read while it is on the canvas; `settleRecycledNode` covers the one that finishes+ * after the user has left. Load on an SSH host is paced in core, not here: every exec child rides+ * the ControlMaster's `SshChildGate`, and the respawns ride the pty spawn gate.+ */+export function startBulkSwitch<T>(+ ids: readonly string[],+ run: (id: string) => Promise<T>+): Promise<(T | undefined)[]> {+ return Promise.all(ids.map((id) => run(id).catch((): undefined => undefined)))+}+/** One line for a bulk move: what moved, what came back on its old account, what was skipped. */export function summarizeBulkSwitch(outcomes: readonly ClaudeSwitchOutcome[],diff --git a/src/renderer/components/UsageIndicator.moveSessions.test.tsx b/src/renderer/components/UsageIndicator.moveSessions.test.tsxindex 0c5635bc8..001d82c2e 100644--- a/src/renderer/components/UsageIndicator.moveSessions.test.tsx+++ b/src/renderer/components/UsageIndicator.moveSessions.test.tsx@@ -68,17 +68,22 @@ afterEach(() => {vi.unstubAllGlobals()})-async function renderOpen(counts: Record<string, number>): Promise<void> {+type Move = { from: string | undefined; count: number; scopeKey: string } | null++const element = (counts: Record<string, number>, accountMove: Move = null) => (+ <UsageIndicator+ countAccountSessions={(id) => counts[id ?? 'system'] ?? 0}+ onMoveSessions={onMove}+ accountMove={accountMove}+ />+)++async function renderOpen(counts: Record<string, number>, accountMove: Move = null): Promise<void> {host = document.createElement('div')document.body.appendChild(host)root = createRoot(host)await act(async () => {- root.render(- <UsageIndicator- countAccountSessions={(id) => counts[id ?? 'system'] ?? 0}- onMoveSessions={onMove}- />- )+ root.render(element(counts, accountMove))})await act(async () => (host.querySelector('.usage-pill') as HTMLButtonElement).click())}@@ -112,3 +117,43 @@ describe('usage popover — Move N sessions', () => {expect(buttons().some((b) => b.textContent?.startsWith('⇄ Move'))).toBe(false)})})++// A move takes seconds, and the sessions it is moving keep their OLD account until each one lands.+// Reopening the popover meanwhile used to offer "Move 3 sessions" again — counting the sessions+// already on their way — and the click was then silently refused (one bulk move at a time).+describe('usage popover — while a move is running', () => {+ it('the source row says the move is under way, and offers nothing to click', async () => {+ await renderOpen({ w: 3 }, { from: 'w', count: 3, scopeKey: '' })+ const moving = buttons().find((b) => b.textContent === '⇄ Moving 3 sessions…')+ expect(moving).toBeTruthy()+ expect(moving!.disabled).toBe(true)+ expect(buttons().some((b) => b.textContent?.startsWith('⇄ Move '))).toBe(false)+ })++ it('keeps saying so even once the source row has emptied out', async () => {+ await renderOpen({}, { from: 'w', count: 3, scopeKey: '' })+ expect(buttons().find((b) => b.textContent === '⇄ Moving 3 sessions…')).toBeTruthy()+ })++ it('every other row’s move is disabled, since a second move would be refused', async () => {+ await renderOpen({ w: 3, p: 2 }, { from: 'w', count: 3, scopeKey: '' })+ const other = buttons().find((b) => b.textContent === '⇄ Move 2 sessions')!+ expect(other.disabled).toBe(true)+ await act(async () => other.click())+ expect(buttons().some((b) => b.textContent?.startsWith('→ '))).toBe(false)+ expect(onMove).not.toHaveBeenCalled()+ })++ it('a move on ANOTHER machine does not relabel this machine’s row as moving', async () => {+ await renderOpen({ w: 3 }, { from: 'w', count: 3, scopeKey: 'u@h' })+ expect(buttons().some((b) => b.textContent?.startsWith('⇄ Moving'))).toBe(false)+ expect(buttons().find((b) => b.textContent === '⇄ Move 3 sessions')!.disabled).toBe(true)+ })++ it('when the move ends, the row offers the fresh count again', async () => {+ await renderOpen({ w: 3 }, { from: 'w', count: 3, scopeKey: '' })+ await act(async () => root.render(element({ w: 1, p: 2 }, null)))+ const move = buttons().find((b) => b.textContent === '⇄ Move 1 session')!+ expect(move.disabled).toBe(false)+ })+})diff --git a/src/renderer/components/UsageIndicator.tsx b/src/renderer/components/UsageIndicator.tsxindex b6aaeb148..b2df2671e 100644--- a/src/renderer/components/UsageIndicator.tsx+++ b/src/renderer/components/UsageIndicator.tsx@@ -119,36 +119,66 @@ export interface MoveTarget {label: string}+/** A bulk move in flight (Canvas `moveAccountSessions`): which account it empties, on which machine+ * (`usageScopeKey`), and how many sessions it started. */+export interface AccountMoveProgress {+ from: string | undefined+ count: number+ scopeKey: string+}+/*** "⇄ Move N sessions" on an account row — the bulk version of a node's "Switch Claude account":* every Claude session on this canvas running on this account is quit, its conversation copied to* the picked account, and resumed there (Canvas `moveAccountSessions`). It sits where the limit is* read, because that is where the user learns an account is spent. Absent when there is nothing to* move or nowhere to move it.+ *+ * While a move runs (`moving`), the sessions it is moving still carry their OLD account until each+ * one lands, so the live count would offer them again — and a second bulk move is refused while one+ * runs. So the source row says "Moving N sessions…", and every other row's control is disabled.*/function MoveSessionsControl({count,targets,+ moving,onMove}: {count: numbertargets: readonly MoveTarget[]+ /** null = no move running; 'this' = this row's account is being moved; 'other' = some other. */+ moving: null | { row: 'this' | 'other'; count: number }onMove: (to: MoveTarget) => void}) {const [picking, setPicking] = useState(false)+ const plural = (n: number): string => `${n} ${n === 1 ? 'session' : 'sessions'}`+ if (moving?.row === 'this') {+ return (+ <span className="usage-account__move">+ <button type="button" className="usage-account__use" disabled>+ ⇄ Moving {plural(moving.count)}…+ </button>+ </span>+ )+ }if (count === 0 || targets.length === 0) return nullreturn (<span className="usage-account__move"><buttontype="button"className="usage-account__use"- aria-expanded={picking}- title="Quit these sessions, move their conversations to another account and resume them there — no login needed. Busy sessions are skipped."+ aria-expanded={!moving && picking}+ disabled={!!moving}+ title={+ moving+ ? 'Another move is still running — wait for it to finish.'+ : 'Quit these sessions, move their conversations to another account and resume them there — no login needed. Busy sessions are skipped.'+ }onClick={() => setPicking((v) => !v)}>- ⇄ Move {count} {count === 1 ? 'session' : 'sessions'}+ ⇄ Move {plural(count)}</button>- {picking ? (+ {!moving && picking ? (<span className="usage-account__move-targets" role="group" aria-label="Move sessions to">{targets.map((t) => (<button@@ -309,7 +339,8 @@ export function UsageIndicator({overBoard = false,onSetDefaultAccount,countAccountSessions,- onMoveSessions+ onMoveSessions,+ accountMove = null}: {overBoard?: boolean/** Writes `project.defaultAccountId` + persists (Canvas's own TabBar handler). When absent the@@ -320,6 +351,8 @@ export function UsageIndicator({countAccountSessions?: (accountId: string | undefined) => number/** Move every such session from one account to another (Canvas `moveAccountSessions`). */onMoveSessions?: (from: string | undefined, to: string | undefined, toLabel: string) => void+ /** The bulk move in flight, if any (Canvas owns it; see `MoveSessionsControl`). */+ accountMove?: AccountMoveProgress | null}): JSX.Element | null {const [usage, setUsage] = useState<ClaudeUsage | null>(null)const [open, setOpen] = useState(false)@@ -400,6 +433,18 @@ export function UsageIndicator({<MoveSessionsControlcount={countAccountSessions(from)}targets={targets}+ moving={+ accountMove+ ? {+ row:+ accountMove.scopeKey === scopeHostKey &&+ (accountMove.from || undefined) === (from || undefined)+ ? 'this'+ : 'other',+ count: accountMove.count+ }+ : null+ }onMove={(to) => {setOpen(false)onMoveSessions(from, to.id, to.label)diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex f38af3c3d..dc39e2377 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -175,8 +175,10 @@ import {restartSessionId,RESTART_EXIT_TIMEOUT_MS,RESTART_LATE_EXIT_MS,+ settleRecycledNode,type ExitPhaseOutcome,type PauseOutcome,+ type RecyclePatch,type ResumePhaseOutcome} from '../terminal/agent-restart'import { coldResumeDecision, shouldProbeTranscript } from '../terminal/cold-resume-session'@@ -226,6 +228,7 @@ import { PresenceChips } from '../components/PresenceChips'import { useAgentNodes } from '../state/agentNodes'import { useTerminalFocus } from '../state/terminalFocus'import { useProjects } from '../state/projects'+import { markWorkspaceDirty } from '../state/workspaceDirty'import { isGlobalKanbanOpen, isKanbanOpen, isOmniKanbanEnabled, openIssueOnBoard, useViewMode, viewFor } from '../state/viewMode'import { useSshConn } from '../state/sshConn'import { useWorktrees } from '../state/worktrees'@@ -4071,7 +4074,7 @@ export function TerminalNode({}const unregisterRestart = registerAgentRestart(id,- guardConcurrentRestart(id, async (targetAgentId?: AgentId, targetModel?: string, restartShell?: boolean, clearEnv?: boolean, beforeRecycle?: () => Promise<Record<string, unknown> | void>) => {+ guardConcurrentRestart(id, async (targetAgentId?: AgentId, targetModel?: string, restartShell?: boolean, clearEnv?: boolean, beforeRecycle?: () => Promise<RecyclePatch | void>) => {const st = useAgentStatus.getState().byId[id]const currentNode = getNode(id)const agentSessionId = restartSessionId(st?.sessionId, currentNode?.data.agentSessionId)@@ -4169,6 +4172,9 @@ export function TerminalNode({// to another core/settings store, and recycling here would respawn against this Mac's env.if (restartShell) {if (session.source === 'relay') return 'not-eligible'+ // Read NOW, before the first await: this node is on the active canvas at call time, and+ // the project may be switched while the CLI quits (see `settleRecycledNode`).+ const ownerProjectId = owningProjectId()const exited = await performExitPhase({agentId: target,sessionId: agentSessionId,@@ -4184,11 +4190,19 @@ export function TerminalNode({// 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 ?? {}),+ settleRecycledNode({+ onCanvas: !!getNode(id),agentId: target,- respawnNonce: ((node.data.respawnNonce as number | undefined) ?? 0) + 1- }))+ patch: patch ?? undefined,+ updateLive: (rebind) =>+ updateNodeData(id, (node) => ({+ ...rebind,+ respawnNonce: ((node.data.respawnNonce as number | undefined) ?? 0) + 1+ })),+ updateStored: (rebind) => useProjects.getState().rebindNode(ownerProjectId, id, rebind),+ dropPark: () => disposeParkedTerminal(termKey),+ markDirty: markWorkspaceDirty+ })return 'restarted'}// Built HERE, not inside the choreography: the shared assembly builder is the single funneldiff --git a/src/renderer/state/projects.test.ts b/src/renderer/state/projects.test.tsindex 13c70f21c..738552f5c 100644--- a/src/renderer/state/projects.test.ts+++ b/src/renderer/state/projects.test.ts@@ -283,3 +283,42 @@ describe('unhideProject (#925)', () => {expect(useProjects.getState().activeProjectId).toBe(a.id)})})++describe('rebindNode', () => {+ const seed = () => {+ const node = (id: string, accountId?: string) => ({+ id, kind: 'terminal' as const, position: { x: 0, y: 0 }, size: { width: 1, height: 1 },+ title: id, color: '#fff', group: null, agentId: 'claude', ...(accountId ? { accountId } : {})+ })+ useProjects.getState().hydrate({+ version: 2,+ activeProjectId: 'p2',+ projects: [+ { id: 'p1', name: 'one', color: '#fff', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [node('n1', 'a'), node('n2', 'a')] },+ { id: 'p2', name: 'two', color: '#fff', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [node('n3', 'a')] }+ ]+ })+ }+ const stored = (p: string, n: string) =>+ useProjects.getState().projects.find((x) => x.id === p)?.nodes.find((x) => x.id === n)++ it('writes the account into a background project\'s serialized node, touching nothing else', () => {+ seed()+ useProjects.getState().rebindNode('p1', 'n1', { agentId: 'claude', accountId: 'b' })+ expect(stored('p1', 'n1')?.accountId).toBe('b')+ expect(stored('p1', 'n2')?.accountId).toBe('a')+ expect(stored('p2', 'n3')?.accountId).toBe('a')+ })++ it('an explicit undefined account moves the node to the system account', () => {+ seed()+ useProjects.getState().rebindNode('p1', 'n1', { agentId: 'claude', accountId: undefined })+ expect(stored('p1', 'n1')?.accountId).toBeUndefined()+ })++ it('an absent account key leaves the account alone', () => {+ seed()+ useProjects.getState().rebindNode('p1', 'n1', { agentId: 'claude' })+ expect(stored('p1', 'n1')?.accountId).toBe('a')+ })+})diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.tsindex 1b02d773b..7244ffdfd 100644--- a/src/renderer/state/projects.ts+++ b/src/renderer/state/projects.ts@@ -158,6 +158,18 @@ interface ProjectsState {renameNode(projectId: string, nodeId: string, title: string): void/** Recolors a node within a project. */recolorNode(projectId: string, nodeId: string, color: string): void+ /**+ * Writes an in-place agent restart's rebind (which agent, which account) into a project's+ * serialized node — for a restart that finished after its project stopped being the active one+ * (the user switched away while the CLI was quitting), when React Flow no longer holds the node.+ * A key that is PRESENT is written, even as `undefined` (= the system account); an absent key is+ * left alone.+ */+ rebindNode(+ projectId: string,+ nodeId: string,+ patch: Pick<CanvasNodeState, 'agentId'> & Partial<Pick<CanvasNodeState, 'accountId'>>+ ): void/** Removes a node from a project. */removeNode(projectId: string, nodeId: string): void/** Duplicates a node within a project (fresh id, offset position). */@@ -608,6 +620,14 @@ export const useProjects = create<ProjectsState>((set, get) => ({}))},+ rebindNode(projectId, nodeId, patch) {+ set((s) => ({+ projects: mapProjectNodes(s.projects, projectId, (nodes) =>+ nodes.map((n) => (n.id === nodeId ? { ...n, ...patch } : n))+ )+ }))+ },+removeNode(projectId, nodeId) {set((s) => ({projects: mapProjectNodes(s.projects, projectId, (nodes) =>diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex ab35eec55..f4d9b8714 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -8099,10 +8099,14 @@ button.group-node__setup:disabled {vertical-align: middle;white-space: nowrap;}-.usage-account__use:hover {+.usage-account__use:hover:not(:disabled) {color: var(--accent);background: color-mix(in srgb, var(--accent) 12%, transparent);}+/* A bulk move in flight: "Moving N sessions…" on its row, every other row's move held. */+.usage-account__use:disabled {+ cursor: default;+}/* The bulk "Move N sessions" control: the picked targets wrap onto their own line under the label. */.usage-account__move-targets {display: flex;diff --git a/src/renderer/terminal/agent-restart.test.ts b/src/renderer/terminal/agent-restart.test.tsindex cfeb5ddb0..f2b217d93 100644--- a/src/renderer/terminal/agent-restart.test.ts+++ b/src/renderer/terminal/agent-restart.test.ts@@ -21,6 +21,7 @@ import {registerAgentRestart,restartEligibility,restartSessionId,+ settleRecycledNode,settleRestart,summarizeBulkRestart,summarizeOutcomes,@@ -1488,3 +1489,63 @@ describe('the write verb shares the restart lock', () => {expect(body.match(/api\.pty\.sendText\(/g) ?? []).toHaveLength(1)})})++describe('settleRecycledNode — the recycle outlives its canvas', () => {+ const deps = (onCanvas: boolean) => {+ const calls: string[] = []+ const live: unknown[] = []+ const stored: unknown[] = []+ return {+ calls,+ live,+ stored,+ d: {+ onCanvas,+ agentId: 'claude',+ updateLive: (p: unknown) => {+ calls.push('live')+ live.push(p)+ },+ updateStored: (p: unknown) => {+ calls.push('stored')+ stored.push(p)+ },+ dropPark: () => calls.push('dropPark'),+ markDirty: () => calls.push('dirty')+ }+ }+ }++ it('on the active canvas: one live update carrying the rebind, nothing else', () => {+ const t = deps(true)+ settleRecycledNode({ ...t.d, patch: { accountId: 'b' } })+ expect(t.calls).toEqual(['live'])+ expect(t.live).toEqual([{ accountId: 'b', agentId: 'claude' }])+ })++ // The bug: a project switch mid-move unmounted the node, React Flow's `updateNodeData` found no+ // node and dropped the rebind, and the returning mount re-adopted the park holding the session+ // the recycle had just killed — "interrupted halfway", on the OLD account.+ it('off the canvas: drops the dead park and writes the rebind into the stored project', () => {+ const t = deps(false)+ settleRecycledNode({ ...t.d, patch: { accountId: 'b' } })+ expect(t.calls).toEqual(['dropPark', 'stored', 'dirty'])+ expect(t.live).toEqual([])+ expect(t.stored).toEqual([{ agentId: 'claude', accountId: 'b' }])+ })++ it('off the canvas: a move to the SYSTEM account still writes the key (undefined = system)', () => {+ const t = deps(false)+ settleRecycledNode({ ...t.d, patch: { accountId: undefined } })+ expect(t.stored).toHaveLength(1)+ expect(Object.prototype.hasOwnProperty.call(t.stored[0], 'accountId')).toBe(true)+ expect((t.stored[0] as { accountId?: string }).accountId).toBeUndefined()+ })++ it('off the canvas with no rebind (copy failed / plain restart): the account is left alone', () => {+ const t = deps(false)+ settleRecycledNode({ ...t.d, patch: undefined })+ expect(t.stored).toEqual([{ agentId: 'claude' }])+ expect(t.calls).toContain('dropPark')+ })+})diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.tsindex dbf495a2d..feebee91a 100644--- a/src/renderer/terminal/agent-restart.ts+++ b/src/renderer/terminal/agent-restart.ts@@ -550,9 +550,47 @@ export type AgentRestartFn = (// 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>+ beforeRecycle?: () => Promise<RecyclePatch | void>) => Promise<RestartOutcome>+/** What a `beforeRecycle` step may rebind on the node: its account (the account switch). A key+ * that is PRESENT is applied even as `undefined` — that is a move to the system account. Narrow+ * on purpose: the same patch must also be expressible in a project's SERIALIZED node when the+ * restart outlives its canvas (see `settleRecycledNode`). */+export type RecyclePatch = { accountId?: string }++/**+ * The last step of a recycling restart ("Restart agent and shell", and the account switch built on+ * it): bind the node to what the respawn must launch as.+ *+ * On the active canvas this is ONE React Flow update — the rebind rides the respawn bump, see+ * `beforeRecycle`. But the exit it waited on takes seconds, and the user may switch projects+ * meanwhile (a bulk account move is several of them at once). Then React Flow no longer holds the+ * node, `updateNodeData` silently does nothing, and two things went wrong together: the rebind was+ * lost (the node came back on its OLD account), and the returning mount re-adopted the PARK —+ * whose tmux session this very recycle had just killed — so the node showed a dead pane instead of+ * resuming. Off the canvas, therefore: drop the park (the next mount creates fresh, and its cold+ * restore resumes the conversation), write the rebind into the stored project, and schedule a save.+ */+export function settleRecycledNode(d: {+ onCanvas: boolean+ agentId: AgentId+ patch: RecyclePatch | undefined+ updateLive: (patch: RecyclePatch & { agentId: AgentId }) => void+ updateStored: (patch: RecyclePatch & { agentId: AgentId }) => void+ dropPark: () => void+ markDirty: () => void+}): void {+ const patch = { ...(d.patch ?? {}), agentId: d.agentId }+ if (d.onCanvas) {+ d.updateLive(patch)+ return+ }+ d.dropPark()+ d.updateStored(patch)+ d.markDirty()+}+const restartFns = new Map<string, AgentRestartFn>()/** Register a node's restart closure; returns an unregister that is inert if superseded. */