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.

feat(accounts): bulk-move sessions from the usage popover; switch from kanban cards

reviewe1801d95db71
diff --git a/CLAUDE.md b/CLAUDE.md
index 82ac70395..ea9cc1b34 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2809,6 +2809,15 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
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.
+ **Two more surfaces, one choreography** (`runClaudeAccountSwitch` returns a
+ `ClaudeSwitchOutcome` instead of announcing it): the **kanban card** right-click menu gets the
+ node'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:
+ 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 for
whether a node is account-bound at all**, and it feeds `data.accountId` *and* the account color
from a single decision — split them and a node carries an account it is not painted for, or is
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index ef6f8d014..7eb18149f 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -504,6 +504,7 @@ import { useContextWindow } from '../state/contextWindow'
import { useSessionNaming } from '../state/sessionNaming'
import { useSshServers } from '../state/sshServers'
import { useSshConn } from '../state/sshConn'
+import { scopeFromKey, usageScopeKey } from '../lib/usageScope'
import { useSystemAccount } from '../state/systemAccount'
import { useEntitlement } from '../state/entitlement'
import type { SshServer } from '@shared/ssh'
@@ -624,10 +625,13 @@ import {
import { codexAccountSelectable, codexAccountSwitchStillEligible } from './codex-account-switch'
import { resolveNewCodexNodeAccount, planCodexAccountSwitch } from './codex-account-ops'
import {
+ bulkSwitchCandidates,
claudeSwitchHostKey,
claudeSwitchTargets,
- copyRefusalText,
- planClaudeAccountSwitch
+ planClaudeAccountSwitch,
+ summarizeBulkSwitch,
+ switchOutcomeNotice,
+ type ClaudeSwitchOutcome
} from './claude-account-switch'
import type { CodexAccount } from '@shared/codex-account'
import { useSystemCodexAccount } from '../state/systemCodexAccount'
@@ -6602,8 +6606,8 @@ export function Canvas() {
// "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 runClaudeAccountSwitch = useCallback(
+ async (nodeId: string, targetAccountId: string | undefined): Promise<ClaudeSwitchOutcome> => {
const n = nodesRef.current.find((x) => x.id === nodeId)
const st = useAgentStatus.getState().byId[nodeId]
const accounts = useSettings.getState().settings.claudeAccounts
@@ -6622,17 +6626,9 @@ export function Canvas() {
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 this session.'
- : `${targetLabel} is no longer available. Nothing was changed.`
- })
- return
+ return decision.reason === 'same-account'
+ ? { kind: 'same-account' }
+ : { kind: 'refused', reason: decision.reason }
}
// 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.
@@ -6646,20 +6642,11 @@ export function Canvas() {
? 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
- }
+ if (!projectId) return { kind: 'refused', reason: 'no-connection' }
ctx = { projectId }
}
const fn = agentRestartFn(nodeId)
- if (!fn) {
- setNotice({ kind: 'error', text: 'Switch skipped: this terminal is not attached right now.' })
- return
- }
+ if (!fn) return { kind: 'refused', reason: 'not-attached' }
const { plan } = decision
let copy: ClaudeSessionCopyResult | undefined
const outcome = await settleRestart(() =>
@@ -6674,24 +6661,235 @@ export function Canvas() {
})
)
if (copy?.ok) markDirty()
- if (outcome !== 'restarted') {
+ if (outcome !== 'restarted') return { kind: 'not-restarted', outcome }
+ const moved = copy as ClaudeSessionCopyResult | undefined
+ return moved?.ok ? { kind: 'switched' } : { kind: 'copy-failed', reason: moved?.ok === false ? moved.reason : 'failed' }
+ },
+ [markDirty, session.source, connectedProjectIdForHost]
+ )
+
+ const switchClaudeAccountNode = useCallback(
+ async (nodeId: string, targetAccountId: string | undefined, targetLabel: string) => {
+ const notice = switchOutcomeNotice(await runClaudeAccountSwitch(nodeId, targetAccountId), targetLabel)
+ if (notice) setNotice(notice)
+ },
+ [runClaudeAccountSwitch]
+ )
+
+ /**
+ * 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.
+ */
+ const bulkSwitchRunning = useRef(false)
+ const moveAccountSessions = useCallback(
+ async (from: string | undefined, to: string | undefined, toLabel: string) => {
+ if (bulkSwitchRunning.current) return
+ bulkSwitchRunning.current = true
+ try {
+ const byId = useAgentStatus.getState().byId
+ const scope = scopeFromKey(
+ usageScopeKey(useProjects.getState().getProject(useProjects.getState().activeProjectId))
+ )
+ const { ready, busy } = bulkSwitchCandidates(
+ nodesRef.current
+ .filter((n) => n.type === 'terminal')
+ .map((n) => ({
+ id: n.id,
+ agentId: restartAgentIdOf(n),
+ accountId: (n.data.accountId as string | undefined) || undefined,
+ hostKey: claudeSwitchHostKey(n),
+ busy: byId[n.id]?.state === 'working' || byId[n.id]?.state === 'blocked'
+ })),
+ from,
+ scope.kind === 'ssh' ? scope.hostKey : undefined
+ )
+ if (ready.length + busy.length === 0) return
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.'
+ kind: 'info',
+ text: `Moving ${ready.length} ${ready.length === 1 ? 'session' : 'sessions'} to ${toLabel}…`
})
- return
+ const outcomes: ClaudeSwitchOutcome[] = []
+ for (const n of ready) outcomes.push(await runClaudeAccountSwitch(n.id, to))
+ setNotice(summarizeBulkSwitch(outcomes, busy.length, toLabel))
+ } finally {
+ bulkSwitchRunning.current = false
}
- 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, session.source, connectedProjectIdForHost]
+ [runClaudeAccountSwitch]
+ )
+
+ /** How many Claude sessions on this canvas run on `accountId` on the popover's machine — the
+ * number the usage popover's "Move N sessions" button shows. Read live (the popover re-renders
+ * when it opens), from the same candidate rule the move walks. */
+ const countAccountSessions = useCallback((accountId: string | undefined): number => {
+ const byId = useAgentStatus.getState().byId
+ const scope = scopeFromKey(
+ usageScopeKey(useProjects.getState().getProject(useProjects.getState().activeProjectId))
+ )
+ const { ready, busy } = bulkSwitchCandidates(
+ nodesRef.current
+ .filter((n) => n.type === 'terminal')
+ .map((n) => ({
+ id: n.id,
+ agentId: restartAgentIdOf(n),
+ accountId: (n.data.accountId as string | undefined) || undefined,
+ hostKey: claudeSwitchHostKey(n),
+ busy: byId[n.id]?.state === 'working' || byId[n.id]?.state === 'blocked'
+ })),
+ accountId,
+ scope.kind === 'ssh' ? scope.hostKey : undefined
+ )
+ return ready.length + busy.length
+ }, [])
+
+ /**
+ * The running-node "Switch Claude account ▸" / "Switch Codex account ▸" rows for one node. ONE
+ * builder for the canvas node menu and the kanban card menu — the board is a second view of the
+ * same node, and two copies of these rows would drift. Carries the same gate the Restart row does
+ * (`restartEligibility` + a wired restart closure): a busy, id-less or detached node shows the
+ * rows disabled with the reason.
+ */
+ const accountSwitchRows = useCallback(
+ (nodeId: string): MenuItem[] => {
+ const n = nodesRef.current.find((x) => x.id === nodeId)
+ const st = useAgentStatus.getState().byId[nodeId]
+ const sourceAgentId = restartAgentIdOf(n)
+ const sessionId = restartSessionId(st?.sessionId, n?.data.agentSessionId)
+ const gate = restartEligibility(sourceAgentId, st?.state, sessionId)
+ if (!gate.ok && gate.reason === 'not-resumable') return []
+ const why = !gate.ok
+ ? gate.reason === 'working'
+ ? 'This session is busy — switch it once its turn (or permission prompt) is done.'
+ : 'Nothing to resume yet — this session has not reported an id.'
+ : !agentRestartFn(nodeId)
+ ? 'This terminal is not attached right now.'
+ : undefined
+ return [
+ // 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 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 currentAccountId = (n?.data.accountId as string | undefined) || undefined
+ // 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) === 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(nodeId, id, label)
+ }
+ }
+ if (unswitchable)
+ return [
+ {
+ label: 'Switch Claude account',
+ icon: <IconSwitch />,
+ disabled: true,
+ hint: 'Not available for relay sessions.',
+ 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[]
+ })()
+ : []),
+ // Switch this running Codex node onto another machine-scoped account (S6 §3.5). Shown
+ // 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.
+ ...(sourceAgentId === 'codex'
+ ? (() => {
+ const codexAll = useSettings.getState().settings.codexAccounts
+ const hostKey = n?.data.ssh ? sshHostKey(n.data.ssh as SshServer) : undefined
+ const onMachine = codexAll.filter(
+ (a) => !a.pending && (hostKey ? a.host === hostKey : !a.host)
+ )
+ if (onMachine.length === 0) return []
+ // The three-phase switch (`switchThread`) plans and links rollouts in LOCAL
+ // homes only; for a node on an SSH host it could only fail. Say so instead of
+ // offering rows that roll back — the host-side switch is a follow-up.
+ if (hostKey)
+ return [
+ {
+ label: 'Switch Codex account',
+ icon: <IconSwitch />,
+ disabled: true,
+ hint: 'Switching Codex accounts is not available for SSH sessions yet.',
+ onClick: () => {}
+ }
+ ] as MenuItem[]
+ const currentAccountId = (n?.data.accountId as string | undefined) || undefined
+ const systemCodexLabel = systemAccountDisplay(
+ undefined,
+ useSystemCodexAccount.getState().email
+ )
+ const row = (
+ id: string | undefined,
+ label: string
+ ): MenuItem => {
+ const isCurrent = (id || undefined) === currentAccountId
+ const sel = codexAccountSelectable(id, onMachine, connectedProjectIdForHost)
+ return {
+ label: `${isCurrent ? '✓ ' : ''}${label}`,
+ icon: <AgentIcon agentId="codex" />,
+ disabled: !!why || isCurrent || !sel.ok,
+ hint: isCurrent
+ ? 'This node already runs on this account.'
+ : !sel.ok
+ ? sel.reason === 'no-connection'
+ ? 'This account lives on a host that is not connected.'
+ : 'This account is no longer available.'
+ : (why ??
+ 'Moves this conversation to the account and resumes it there (same conversation).'),
+ onClick: () => void switchCodexAccountNode(nodeId, id)
+ }
+ }
+ return [
+ {
+ type: 'submenu',
+ label: 'Switch Codex account',
+ icon: <IconSwitch />,
+ children: [
+ row(undefined, systemCodexLabel),
+ ...onMachine.map((a) => row(a.id, a.label))
+ ]
+ }
+ ] as MenuItem[]
+ })()
+ : []),
+ ]
+ },
+ [switchClaudeAccountNode, switchCodexAccountNode, connectedProjectIdForHost, session.source]
)
// Who the bulk restart would act on, right now: the ACTIVE project's canvas (nodesRef holds
@@ -8529,126 +8727,8 @@ export function Canvas() {
}
] as MenuItem[])
: []),
- // Switch this running Codex node onto another machine-scoped account (S6 §3.5). Shown
- // 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 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 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 currentAccountId = (n?.data.accountId as string | undefined) || undefined
- // 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) === 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 (unswitchable)
- return [
- {
- label: 'Switch Claude account',
- icon: <IconSwitch />,
- disabled: true,
- hint: 'Not available for relay sessions.',
- 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
- const hostKey = n?.data.ssh ? sshHostKey(n.data.ssh as SshServer) : undefined
- const onMachine = codexAll.filter(
- (a) => !a.pending && (hostKey ? a.host === hostKey : !a.host)
- )
- if (onMachine.length === 0) return []
- // The three-phase switch (`switchThread`) plans and links rollouts in LOCAL
- // homes only; for a node on an SSH host it could only fail. Say so instead of
- // offering rows that roll back — the host-side switch is a follow-up.
- if (hostKey)
- return [
- {
- label: 'Switch Codex account',
- icon: <IconSwitch />,
- disabled: true,
- hint: 'Switching Codex accounts is not available for SSH sessions yet.',
- onClick: () => {}
- }
- ] as MenuItem[]
- const currentAccountId = (n?.data.accountId as string | undefined) || undefined
- const systemCodexLabel = systemAccountDisplay(
- undefined,
- useSystemCodexAccount.getState().email
- )
- const row = (
- id: string | undefined,
- label: string
- ): MenuItem => {
- const isCurrent = (id || undefined) === currentAccountId
- const sel = codexAccountSelectable(id, onMachine, connectedProjectIdForHost)
- return {
- label: `${isCurrent ? '✓ ' : ''}${label}`,
- icon: <AgentIcon agentId="codex" />,
- disabled: !!why || isCurrent || !sel.ok,
- hint: isCurrent
- ? 'This node already runs on this account.'
- : !sel.ok
- ? sel.reason === 'no-connection'
- ? 'This account lives on a host that is not connected.'
- : 'This account is no longer available.'
- : (why ??
- 'Moves this conversation to the account and resumes it there (same conversation).'),
- onClick: () => void switchCodexAccountNode(ids[0], id)
- }
- }
- return [
- {
- type: 'submenu',
- label: 'Switch Codex account',
- icon: <IconSwitch />,
- children: [
- row(undefined, systemCodexLabel),
- ...onMachine.map((a) => row(a.id, a.label))
- ]
- }
- ] as MenuItem[]
- })()
- : []),
+ // Switch Claude / Codex account — one builder shared with the kanban card menu.
+ ...accountSwitchRows(ids[0]),
]
return [
// The restart variants — plain restart, fresh shell, subscription, reopen as another
@@ -14576,6 +14656,7 @@ export function Canvas() {
onModalNodeChange={setKanbanModalNode}
onBrowserNav={browserNavFromKanban}
onSetIcon={setNodeIcon}
+ accountMenuItems={accountSwitchRows}
/>
)}
<UpdateCard />
@@ -14833,7 +14914,12 @@ export function Canvas() {
{/* Same write path as the TabBar caret menu (project.defaultAccountId + persist) — the
popover row is a second, better-placed entrance to the same action (issue #142). */}
- <UsageIndicator overBoard={kanbanOpen} onSetDefaultAccount={setProjectDefaultAccount} />
+ <UsageIndicator
+ overBoard={kanbanOpen}
+ onSetDefaultAccount={setProjectDefaultAccount}
+ countAccountSessions={countAccountSessions}
+ onMoveSessions={(from, to, label) => void moveAccountSessions(from, to, label)}
+ />
</CanvasPills>
{/* Canvas-mounted, deliberately NOT in the .top-banners column: this is about THIS canvas,
diff --git a/src/renderer/canvas/claude-account-switch.test.ts b/src/renderer/canvas/claude-account-switch.test.ts
index 10b9cb670..4495f646a 100644
--- a/src/renderer/canvas/claude-account-switch.test.ts
+++ b/src/renderer/canvas/claude-account-switch.test.ts
@@ -76,3 +76,57 @@ describe('planClaudeAccountSwitch', () => {
})
})
})
+
+describe('bulk move', () => {
+ const node = (id: string, over: Partial<import('./claude-account-switch').BulkSwitchNode> = {}) => ({
+ id,
+ agentId: 'claude',
+ busy: false,
+ ...over
+ })
+
+ it('picks the Claude sessions on the source account and on the scoped machine only', async () => {
+ const { bulkSwitchCandidates } = await import('./claude-account-switch')
+ const nodes = [
+ node('sys'),
+ node('work', { accountId: 'w' }),
+ node('busy-sys', { busy: true }),
+ node('codex', { agentId: 'codex' }),
+ node('remote-sys', { hostKey: 'u@h' })
+ ]
+ const local = bulkSwitchCandidates(nodes, undefined, undefined)
+ expect(local.ready.map((n) => n.id)).toEqual(['sys'])
+ expect(local.busy.map((n) => n.id)).toEqual(['busy-sys'])
+ expect(bulkSwitchCandidates(nodes, 'w', undefined).ready.map((n) => n.id)).toEqual(['work'])
+ expect(bulkSwitchCandidates(nodes, undefined, 'u@h').ready.map((n) => n.id)).toEqual(['remote-sys'])
+ })
+
+ it('summarizes what moved, what stayed and what was skipped', async () => {
+ const { summarizeBulkSwitch } = await import('./claude-account-switch')
+ expect(summarizeBulkSwitch([{ kind: 'switched' }, { kind: 'switched' }], 0, 'Work')).toEqual({
+ kind: 'info',
+ text: 'Moved 2 sessions to Work.'
+ })
+ const mixed = summarizeBulkSwitch(
+ [
+ { kind: 'switched' },
+ { kind: 'copy-failed', reason: 'diverged' },
+ { kind: 'not-restarted', outcome: 'not-eligible' }
+ ],
+ 1,
+ 'Work'
+ )
+ expect(mixed.kind).toBe('error')
+ expect(mixed.text).toBe(
+ 'Moved 1 session to Work · 1 resumed on their old account (the conversation could not be copied) · 2 skipped (busy, not attached or without a conversation yet).'
+ )
+ })
+
+ it('says nothing for a same-account pick and names the reason otherwise', async () => {
+ const { switchOutcomeNotice } = await import('./claude-account-switch')
+ expect(switchOutcomeNotice({ kind: 'same-account' }, 'X')).toBeNull()
+ expect(switchOutcomeNotice({ kind: 'refused', reason: 'no-connection' }, 'X')?.text).toMatch(
+ /not connected/
+ )
+ })
+})
diff --git a/src/renderer/canvas/claude-account-switch.ts b/src/renderer/canvas/claude-account-switch.ts
index 335bf4c44..3ebfd7437 100644
--- a/src/renderer/canvas/claude-account-switch.ts
+++ b/src/renderer/canvas/claude-account-switch.ts
@@ -100,3 +100,105 @@ export function claudeSwitchHostKey(
const ssh = n?.data.ssh as SshServer | undefined
return ssh ? sshHostKey(ssh) : undefined
}
+
+/**
+ * What one switch did — returned rather than announced, so the single switch (one notice) and the
+ * bulk move (one summary for N nodes) share the choreography and differ only in what they say.
+ */
+export type ClaudeSwitchOutcome =
+ | { kind: 'switched' }
+ | { kind: 'same-account' }
+ | {
+ kind: 'refused'
+ reason: 'not-claude' | 'remote' | 'no-session' | 'unavailable' | 'no-connection' | 'not-attached'
+ }
+ /** The CLI never quit (busy / not eligible at call time, or it did not exit in time). */
+ | { kind: 'not-restarted'; outcome: 'exit-timeout' | 'not-eligible' }
+ /** Quit and came back — on its ORIGINAL account, because the copy was refused. */
+ | { kind: 'copy-failed'; reason: string }
+
+/** The single-switch notice (null = say nothing: a no-op same-account pick). */
+export function switchOutcomeNotice(
+ o: ClaudeSwitchOutcome,
+ targetLabel: string
+): { kind: 'info' | 'error'; text: string } | null {
+ switch (o.kind) {
+ case 'switched':
+ return { kind: 'info', text: `Switched to ${targetLabel} — resuming the same conversation.` }
+ case 'same-account':
+ return null
+ case 'copy-failed':
+ return { kind: 'error', text: copyRefusalText(o.reason, targetLabel) }
+ case 'not-restarted':
+ return {
+ kind: 'error',
+ text:
+ o.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.'
+ }
+ case 'refused':
+ return {
+ kind: 'error',
+ text:
+ o.reason === 'no-session'
+ ? 'This session has no resumable conversation id yet — nothing to switch.'
+ : o.reason === 'remote' || o.reason === 'not-claude'
+ ? 'Switching accounts is not available for this session.'
+ : o.reason === 'no-connection'
+ ? 'This host is not connected — reconnect the project, then switch. Nothing was changed.'
+ : o.reason === 'not-attached'
+ ? 'Switch skipped: this terminal is not attached right now.'
+ : `${targetLabel} is no longer available. Nothing was changed.`
+ }
+ }
+}
+
+/** A live canvas node, as the bulk move needs to see it. */
+export interface BulkSwitchNode {
+ id: string
+ agentId?: string
+ /** `data.accountId` (undefined = the system account). */
+ accountId?: string
+ /** `claudeSwitchHostKey` — the machine the pane runs on (undefined = this one). */
+ hostKey?: string
+ /** The live agent state: a `working`/`blocked` session is skipped, never interrupted. */
+ busy: boolean
+}
+
+/**
+ * The Claude sessions on `from` (undefined = the system account) that live on the scoped machine
+ * — the set "Move N sessions" counts and the bulk move walks, in canvas order. `busy` ones are
+ * listed separately: they are counted (so the number the user saw is the number accounted for) but
+ * never switched, because a switch types `/exit`, which a permission prompt would take as an answer.
+ */
+export function bulkSwitchCandidates(
+ nodes: readonly BulkSwitchNode[],
+ from: string | undefined,
+ scopeHostKey: string | undefined
+): { ready: BulkSwitchNode[]; busy: BulkSwitchNode[] } {
+ const on = nodes.filter(
+ (n) =>
+ n.agentId === 'claude' &&
+ (n.accountId || undefined) === (from || undefined) &&
+ (n.hostKey || undefined) === (scopeHostKey || undefined)
+ )
+ return { ready: on.filter((n) => !n.busy), busy: on.filter((n) => n.busy) }
+}
+
+/** One line for a bulk move: what moved, what came back on its old account, what was skipped. */
+export function summarizeBulkSwitch(
+ outcomes: readonly ClaudeSwitchOutcome[],
+ busySkipped: number,
+ targetLabel: string
+): { kind: 'info' | 'error'; text: string } {
+ const moved = outcomes.filter((o) => o.kind === 'switched').length
+ const stayed = outcomes.filter((o) => o.kind === 'copy-failed').length
+ const skipped =
+ busySkipped + outcomes.filter((o) => o.kind === 'not-restarted' || o.kind === 'refused').length
+ const plural = (n: number, one: string, many: string): string => `${n} ${n === 1 ? one : many}`
+ const parts = [`Moved ${plural(moved, 'session', 'sessions')} to ${targetLabel}`]
+ if (stayed) parts.push(`${stayed} resumed on their old account (the conversation could not be copied)`)
+ if (skipped) parts.push(`${skipped} skipped (busy, not attached or without a conversation yet)`)
+ return { kind: stayed || skipped ? 'error' : 'info', text: `${parts.join(' · ')}.` }
+}
diff --git a/src/renderer/components/UsageIndicator.moveSessions.test.tsx b/src/renderer/components/UsageIndicator.moveSessions.test.tsx
new file mode 100644
index 000000000..0c5635bc8
--- /dev/null
+++ b/src/renderer/components/UsageIndicator.moveSessions.test.tsx
@@ -0,0 +1,114 @@
+// @vitest-environment jsdom
+//
+// The usage popover's bulk "Move N sessions": on an account row with sessions, it offers the OTHER
+// accounts of the same machine and hands the pick to Canvas. The rules pinned here: the row's own
+// account is never offered as a target, a row with nothing on it shows no control, and the pick
+// carries the source, the target and its label.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { UsageIndicator } from './UsageIndicator'
+import { useSettings } from '../state/settings'
+import { useProjects } from '../state/projects'
+import { DEFAULT_SETTINGS, type ClaudeUsage } from '@shared/types'
+
+const usage = (email: string): ClaudeUsage => ({
+ limits: [
+ {
+ kind: 'session',
+ group: 'session',
+ usedPercent: 100,
+ severity: null,
+ resetsAt: null,
+ windowMinutes: null,
+ scopeLabel: null,
+ isActive: true
+ }
+ ],
+ session: null,
+ weekly: null,
+ email,
+ updatedAt: 0,
+ status: 'ok'
+})
+
+let root: Root
+let host: HTMLElement
+const onMove = vi.fn()
+
+beforeEach(() => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
+ onMove.mockReset()
+ useSettings.setState({
+ settings: {
+ ...DEFAULT_SETTINGS,
+ claudeAccounts: [
+ { id: 'w', label: 'Work', email: '[email protected]', createdAt: 0 },
+ { id: 'p', label: 'Personal', email: '[email protected]', createdAt: 0 }
+ ]
+ },
+ hydrated: true
+ })
+ useProjects.setState({ projects: [{ id: 'p1', name: 'local', nodes: [] } as never], activeProjectId: 'p1' })
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ usage: {
+ fetch: async (id?: string) => usage(id ? `${id}@example.com` : '[email protected]'),
+ onUpdate: () => () => {},
+ providers: async () => [],
+ remote: async () => []
+ },
+ settings: { save: async () => {} }
+ }
+})
+
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ useSettings.setState({ settings: DEFAULT_SETTINGS })
+ vi.unstubAllGlobals()
+})
+
+async function renderOpen(counts: Record<string, number>): 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}
+ />
+ )
+ })
+ await act(async () => (host.querySelector('.usage-pill') as HTMLButtonElement).click())
+}
+
+const buttons = (): HTMLButtonElement[] => [...host.querySelectorAll('button')]
+
+describe('usage popover — Move N sessions', () => {
+ it('moves an account’s sessions to another account of the same machine', async () => {
+ await renderOpen({ w: 3 })
+ const move = buttons().find((b) => b.textContent === '⇄ Move 3 sessions')!
+ expect(move).toBeTruthy()
+ await act(async () => move.click())
+ const targets = buttons()
+ .filter((b) => b.textContent?.startsWith('→ '))
+ .map((b) => b.textContent)
+ // Its own account is never a target; the system login and the other account are.
+ expect(targets).toEqual(['→ [email protected]', '→ Personal'])
+ await act(async () => buttons().find((b) => b.textContent === '→ Personal')!.click())
+ expect(onMove).toHaveBeenCalledWith('w', 'p', 'Personal')
+ })
+
+ it('moves the system account’s sessions (source undefined)', async () => {
+ await renderOpen({ system: 1 })
+ await act(async () => buttons().find((b) => b.textContent === '⇄ Move 1 session')!.click())
+ await act(async () => buttons().find((b) => b.textContent === '→ Work')!.click())
+ expect(onMove).toHaveBeenCalledWith(undefined, 'w', 'Work')
+ })
+
+ it('shows no control on a row with no sessions', async () => {
+ await renderOpen({})
+ expect(buttons().some((b) => b.textContent?.startsWith('⇄ Move'))).toBe(false)
+ })
+})
diff --git a/src/renderer/components/UsageIndicator.tsx b/src/renderer/components/UsageIndicator.tsx
index 2c024f0ec..cb5ecb9ec 100644
--- a/src/renderer/components/UsageIndicator.tsx
+++ b/src/renderer/components/UsageIndicator.tsx
@@ -103,6 +103,62 @@ function DefaultAccountMark({
)
}
+/** Where a bulk move can send an account's sessions: another account on the same machine. */
+export interface MoveTarget {
+ id: string | undefined
+ label: 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.
+ */
+function MoveSessionsControl({
+ count,
+ targets,
+ onMove
+}: {
+ count: number
+ targets: readonly MoveTarget[]
+ onMove: (to: MoveTarget) => void
+}) {
+ const [picking, setPicking] = useState(false)
+ if (count === 0 || targets.length === 0) return null
+ return (
+ <span className="usage-account__move">
+ <button
+ type="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."
+ onClick={() => setPicking((v) => !v)}
+ >
+ ⇄ Move {count} {count === 1 ? 'session' : 'sessions'}
+ </button>
+ {picking ? (
+ <span className="usage-account__move-targets" role="group" aria-label="Move sessions to">
+ {targets.map((t) => (
+ <button
+ key={t.id ?? 'system'}
+ type="button"
+ className="usage-account__use"
+ onClick={() => {
+ setPicking(false)
+ onMove(t)
+ }}
+ >
+ → {t.label}
+ </button>
+ ))}
+ </span>
+ ) : null}
+ </span>
+ )
+}
+
/**
* One account's limit bars under a label, for the multi-account popover. Reuses LimitRow's
* markup — `u` is null while its on-demand fetch is in flight.
@@ -113,7 +169,8 @@ function AccountUsageBlock({
u,
mode,
isDefault = false,
- onUse
+ onUse,
+ move
}: {
label: string
email?: string
@@ -121,12 +178,14 @@ function AccountUsageBlock({
mode: 'used' | 'remaining' | 'tokens'
isDefault?: boolean
onUse?: () => void
+ move?: React.ReactNode
}) {
return (
<div className="usage-account">
<div className="usage-account__label">
{label}
<DefaultAccountMark isDefault={isDefault} onUse={onUse} />
+ {move}
</div>
{(email ?? u?.email) && <div className="usage-account__email">{email ?? u?.email}</div>}
{u?.limits.map((l) => (
@@ -155,12 +214,14 @@ function RemoteUsageBlock({
row,
mode,
isDefault = false,
- onUse
+ onUse,
+ move
}: {
row: RemoteAccountUsage
mode: 'used' | 'remaining' | 'tokens'
isDefault?: boolean
onUse?: () => void
+ move?: React.ReactNode
}) {
if (row.usage.status === 'unavailable') return null
const showHost = row.label !== row.hostKey
@@ -172,6 +233,7 @@ function RemoteUsageBlock({
{showHost ? row.hostKey : 'SSH'}
</span>
<DefaultAccountMark isDefault={isDefault} onUse={onUse} />
+ {move}
</div>
{row.usage.email && <div className="usage-account__email">{row.usage.email}</div>}
{row.usage.limits.map((l) => (
@@ -225,12 +287,19 @@ function ProviderBlock({ u, mode }: { u: ProviderUsage; mode: 'used' | 'remainin
*/
export function UsageIndicator({
overBoard = false,
- onSetDefaultAccount
+ onSetDefaultAccount,
+ countAccountSessions,
+ onMoveSessions
}: {
overBoard?: boolean
/** Writes `project.defaultAccountId` + persists (Canvas's own TabBar handler). When absent the
* popover is a pure readout, exactly as before issue #142. */
onSetDefaultAccount?: (projectId: string, accountId: string | undefined) => void
+ /** Claude sessions on this canvas running on an account (undefined = system), on the scoped
+ * machine. With `onMoveSessions`, turns on the rows' "Move N sessions". */
+ 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
}): JSX.Element | null {
const [usage, setUsage] = useState<ClaudeUsage | null>(null)
const [open, setOpen] = useState(false)
@@ -291,6 +360,34 @@ export function UsageIndicator({
}
}
+ // The bulk move's control for one row. Targets are the OTHER accounts this project can launch on
+ // this machine (the same `eligibleAccounts` rule) plus the machine's system login — never an
+ // account on another machine, whose dir does not exist where these panes run.
+ const moveFor = (accountId: string | null): React.ReactNode => {
+ if (!countAccountSessions || !onMoveSessions) return null
+ const from = accountId ?? undefined
+ const systemTarget: MoveTarget = {
+ id: undefined,
+ label: scopeHostKey
+ ? `System account (${scopeHostKey})`
+ : systemAccountDisplay(systemLabelSetting, usage?.email)
+ }
+ const targets = [
+ systemTarget,
+ ...eligibleAccounts.map((a) => ({ id: a.id, label: a.label || a.email || 'Account' }))
+ ].filter((t) => t.id !== from)
+ return (
+ <MoveSessionsControl
+ count={countAccountSessions(from)}
+ targets={targets}
+ onMove={(to) => {
+ setOpen(false)
+ onMoveSessions(from, to.id, to.label)
+ }}
+ />
+ )
+ }
+
useEffect(() => {
void window.nodeTerminal.usage.fetch().then(setUsage)
return window.nodeTerminal.usage.onUpdate(setUsage)
@@ -513,6 +610,7 @@ export function UsageIndicator({
email={systemLabelSetting.trim() ? (claudeUsage.email ?? undefined) : undefined}
u={claudeUsage}
{...rowMark(null)}
+ move={moveFor(null)}
/>
{scoped.accounts.map((a) => (
<AccountUsageBlock
@@ -522,6 +620,7 @@ export function UsageIndicator({
email={a.email}
u={acctUsage[a.id] ?? null}
{...rowMark(a.id)}
+ move={moveFor(a.id)}
/>
))}
</>
@@ -560,6 +659,7 @@ export function UsageIndicator({
row={r}
mode={percentMode}
{...rowMark(r.accountId)}
+ move={moveFor(r.accountId)}
/>
))}
{scope.kind === 'ssh' && visibleRemote.length === 0 && (
diff --git a/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx b/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx
new file mode 100644
index 000000000..34c823034
--- /dev/null
+++ b/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx
@@ -0,0 +1,100 @@
+// @vitest-environment jsdom
+//
+// The card right-click menu carries the node's account-switch rows — the SAME builder the canvas
+// node menu uses (Canvas `accountSwitchRows`), passed in as `accountMenuItems`. A card is a second
+// view of its node, so the switch must be reachable from the board without going back to the canvas.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { KanbanView, type KanbanSession } from './KanbanView'
+import { defaultKanban } from '../../lib/kanban'
+import type { MenuItem } from '../ContextMenu'
+
+vi.mock('../../session/session', () => ({
+ useSession: () => ({ source: 'local', api: window.nodeTerminal })
+}))
+
+let root: Root
+let host: HTMLElement
+const session = {
+ id: 'n1',
+ title: 'Agent',
+ color: '#fff',
+ kind: 'terminal',
+ agentId: 'claude',
+ spawn: {}
+} as unknown as KanbanSession
+
+beforeEach(() => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
+ // The context menu measures itself to stay on screen; jsdom has no ResizeObserver.
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe(): void {}
+ unobserve(): void {}
+ disconnect(): void {}
+ }
+ )
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ boardLog: { list: async () => [], onChanged: () => () => {} },
+ settings: { save: async () => {} }
+ }
+})
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ document.body.innerHTML = ''
+ vi.unstubAllGlobals()
+})
+
+function render(accountMenuItems?: (id: string) => MenuItem[]): void {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ const noop = (): void => {}
+ act(() =>
+ root.render(
+ <KanbanView
+ board={defaultKanban()}
+ sessions={[session]}
+ onChange={noop}
+ onOpenNode={noop}
+ onCreateNode={noop}
+ onRenameNode={noop}
+ onEditSticky={noop}
+ onDeleteNode={noop}
+ onModalNodeChange={noop}
+ onBrowserNav={noop}
+ onSetIcon={noop}
+ accountMenuItems={accountMenuItems}
+ />
+ )
+ )
+}
+
+function openCardMenu(): void {
+ const card = [...document.querySelectorAll('[title="Open card"]')][0] as HTMLElement
+ act(() => {
+ card.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 10, clientY: 10 }))
+ })
+}
+
+describe('KanbanView — card menu account switch', () => {
+ it('shows the node’s account-switch rows, built for that card’s node', () => {
+ const rows = vi.fn((id: string): MenuItem[] => [
+ { label: `Switch Claude account (${id})`, onClick: () => {} }
+ ])
+ render(rows)
+ openCardMenu()
+ expect(rows).toHaveBeenCalledWith('n1')
+ expect(document.body.textContent).toContain('Switch Claude account (n1)')
+ })
+
+ it('shows none without a builder (no canvas behind the board)', () => {
+ render()
+ openCardMenu()
+ expect(document.body.textContent).toContain('Open card')
+ expect(document.body.textContent).not.toContain('Switch Claude account')
+ })
+})
diff --git a/src/renderer/components/kanban/KanbanView.tsx b/src/renderer/components/kanban/KanbanView.tsx
index f8e0a716c..73b4fa593 100644
--- a/src/renderer/components/kanban/KanbanView.tsx
+++ b/src/renderer/components/kanban/KanbanView.tsx
@@ -98,6 +98,12 @@ export interface KanbanViewProps {
onBrowserNav: (nodeId: string, patch: { url?: string; title?: string }) => void
/** Set (or clear, with `undefined`) a node's icon — the card modal's icon button. */
onSetIcon: (nodeId: string, icon: NodeIcon | undefined) => void
+ /**
+ * The node's "Switch Claude/Codex account ▸" rows — the SAME builder the canvas node menu uses
+ * (`accountSwitchRows` in Canvas), so a card offers exactly what its node does. Optional: a board
+ * with no canvas behind it (a test, a future read-only view) simply shows no rows.
+ */
+ accountMenuItems?: (nodeId: string) => MenuItem[]
}
type Drag =
@@ -135,7 +141,7 @@ function useCanvasCovered(): void {
export const KanbanView = memo(function KanbanView({
board, sessions, onChange, onOpenNode, onCreateNode, onRenameNode, onEditSticky, onDeleteNode,
- onModalNodeChange, onBrowserNav, onSetIcon
+ onModalNodeChange, onBrowserNav, onSetIcon, accountMenuItems
}: KanbanViewProps) {
useCanvasCovered()
const { api } = useSession()
@@ -542,6 +548,7 @@ export const KanbanView = memo(function KanbanView({
...(moveTargets.length
? ([{ type: 'submenu', label: 'Move to', icon: <IconSwitch />, children: moveTargets }] as MenuItem[])
: []),
+ ...(accountMenuItems?.(nodeId) ?? []),
{ type: 'separator' },
{ label: 'Delete', icon: <IconTrash />, danger: true, onClick: () => onDeleteNode(nodeId) }
]
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index babcf9444..003b70fc9 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -7320,6 +7320,16 @@ button.group-node__setup:disabled {
color: var(--accent);
background: color-mix(in srgb, var(--accent) 12%, transparent);
}
+/* The bulk "Move N sessions" control: the picked targets wrap onto their own line under the label. */
+.usage-account__move-targets {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 2px 4px;
+ margin-top: 3px;
+}
+.usage-account__move-targets .usage-account__use {
+ margin-left: 0;
+}
/* Popover-footer action (issue #420): opens the system-scoped `claude /login` terminal. A quiet
full-width row, styled with the same tint/accent tokens as `.usage-account__use` so it reads