Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(accounts): per-node account chip, observed-account store, link existing config dirs (renderer)
freshjuicez15ae06d159d3
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 6fc443952..af9af207b 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -350,7 +350,8 @@ export function buildStubApi(): Omit<add: U('claudeAccounts.add'),waitLogin: U('claudeAccounts.waitLogin'),cancelWaitLogin: U('claudeAccounts.cancelWaitLogin'),- remove: U('claudeAccounts.remove')+ remove: U('claudeAccounts.remove'),+ link: U('claudeAccounts.link')},codexAccounts: {add: U('codexAccounts.add'),diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex ab583fd22..b26ad5e1f 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -1994,6 +1994,9 @@ export function Canvas() {title: n.data.title ?? n.id,color: n.data.color ?? '#888',agentId: n.data.agentId,+ // The node's creation-time account, for the sidebar row's account chip (the+ // serialized nodes of inactive projects carry it already).+ accountId: n.data.accountId,cwd: n.data.cwd,ssh: n.data.ssh,parentId: n.parentId@@ -10681,6 +10684,10 @@ export function Canvas() {return api.onAgentStatus((e: NormalizedAgentEvent) => {const cs = useAgentStatus.getState()if (e.sessionId) cs.setSessionId(e.nodeId, e.sessionId)+ // Which Claude account the posting session is ACTUALLY on (hook-derived label, D3). Captured+ // off any event that carries one, exactly like `sessionId` above: a plain terminal running+ // `CLAUDE_CONFIG_DIR=~/.claude-2 claude` announces its identity nowhere else.+ if (e.account) cs.setAccount(e.nodeId, e.account)const agentLabel = agentConfig(e.agentId)?.label ?? 'Agent'// "<folder> — Claude finished" + last assistant message as the body.const alert = (statusText: string, fallbackBody: string, sound: 'done' | 'needsYou') => {diff --git a/src/renderer/components/AccountChip.test.tsx b/src/renderer/components/AccountChip.test.tsxnew file mode 100644index 000000000..c7f114c6f--- /dev/null+++ b/src/renderer/components/AccountChip.test.tsx@@ -0,0 +1,119 @@+// @vitest-environment jsdom+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import { createRoot, type Root } from 'react-dom/client'+import { act } from 'react'+import type { ClaudeAccount, ObservedClaudeAccount } from '@shared/types'+import { DEFAULT_SETTINGS } from '@shared/types'+import { AccountChip, useAccountChip } from './AccountChip'+import { useAgentStatus } from '../state/agentStatus'+import { useSettings } from '../state/settings'++const SYSTEM: ObservedClaudeAccount = { configDir: '/home/me/.claude', accountId: null, known: true }+const CLAUDE_2: ObservedClaudeAccount = {+ configDir: '/home/me/.claude-2',+ accountId: null,+ known: false+}++/** The wiring under test: the hook resolves settings + the live status table, the component paints+ * the result. Rendering them together is the only way to pin the SUBSCRIPTIONS, which is where a+ * chip that never appears (or never updates) actually comes from. */+function Probe({+ accountId,+ observed+}: {+ accountId?: string+ observed?: ObservedClaudeAccount+}): React.JSX.Element | null {+ return <AccountChip chip={useAccountChip(accountId, observed)} />+}++function render(props: { accountId?: string; observed?: ObservedClaudeAccount }): {+ host: HTMLElement+ root: Root+} {+ const host = document.createElement('div')+ document.body.appendChild(host)+ const root = createRoot(host)+ act(() => {+ root.render(<Probe {...props} />)+ })+ return { host, root }+}++const chipEl = (host: HTMLElement): HTMLElement | null => host.querySelector('.node-account-chip')++const accounts: ClaudeAccount[] = [+ { id: 'a1', label: '[email protected]', email: '[email protected]', createdAt: 0 },+ { id: 'a2', label: 'second', configDir: '/home/me/.claude-2', createdAt: 0 }+]++beforeEach(() => {+ document.body.innerHTML = ''+ useAgentStatus.setState({ byId: {} })+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, claudeAccounts: accounts } })+ // `useSystemAccount.ensure()` fires as soon as a chip could be shown.+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {+ usage: { fetch: async () => ({ email: '[email protected]' }) }+ }+})++afterEach(() => {+ useAgentStatus.setState({ byId: {} })+ useSettings.setState({ settings: DEFAULT_SETTINGS })+})++describe('AccountChip (D6 visibility through the live stores)', () => {+ it('renders nothing for a system pane while it is the only identity in play', () => {+ useAgentStatus.setState({ byId: { n1: { unread: false, account: SYSTEM } } })+ const { host, root } = render({ observed: SYSTEM })+ expect(chipEl(host)).toBeNull()+ root.unmount()+ })++ it('renders nothing at all for a pane whose account is unknown', () => {+ const { host, root } = render({})+ expect(chipEl(host)).toBeNull()+ root.unmount()+ })++ it('chips the system pane once a second identity shows up on the canvas', () => {+ // The real case: `~/.claude` in one pane and `~/.claude-2` in another. Two panes on two logins+ // must never look alike, so BOTH get a chip.+ useAgentStatus.setState({+ byId: { n1: { unread: false, account: SYSTEM }, n2: { unread: false, account: CLAUDE_2 } }+ })+ const { host, root } = render({ observed: SYSTEM })+ expect(chipEl(host)?.className).toContain('node-account-chip--system')+ root.unmount()+ })++ it('names an unlinked dir by its folder, dashed, and says where to link it', () => {+ useAgentStatus.setState({ byId: { n2: { unread: false, account: CLAUDE_2 } } })+ const { host, root } = render({ observed: CLAUDE_2 })+ expect(chipEl(host)?.textContent).toBe('.claude-2')+ expect(chipEl(host)?.className).toContain('node-account-chip--unlinked')+ expect(chipEl(host)?.getAttribute('title')).toContain('Settings → Accounts')+ root.unmount()+ })++ it('chips a managed node whatever else is running', () => {+ const { host, root } = render({ accountId: 'a1' })+ expect(chipEl(host)?.textContent).toBe('work')+ expect(chipEl(host)?.className).toContain('node-account-chip--managed')+ root.unmount()+ })++ it('marks an account with a linked config dir as linked, not managed', () => {+ const { host, root } = render({ accountId: 'a2' })+ expect(chipEl(host)?.className).toContain('node-account-chip--linked')+ root.unmount()+ })++ it('follows the node’s own account over the observed one', () => {+ // Launch identity wins: the env is what it is, whatever a later observation says.+ const { host, root } = render({ accountId: 'a1', observed: CLAUDE_2 })+ expect(chipEl(host)?.textContent).toBe('work')+ root.unmount()+ })+})diff --git a/src/renderer/components/AccountChip.tsx b/src/renderer/components/AccountChip.tsxnew file mode 100644index 000000000..49b209074--- /dev/null+++ b/src/renderer/components/AccountChip.tsx@@ -0,0 +1,68 @@+import { useEffect, useMemo } from 'react'+import type { ObservedClaudeAccount } from '@shared/types'+import { accountChipFor, accountKey, hasMultipleAccountKeys, type AccountChipInfo } from '../lib/accountChip'+import { useAgentStatus } from '../state/agentStatus'+import { useSettings } from '../state/settings'+import { useSystemAccount } from '../state/systemAccount'++/**+ * Which Claude account a node is on — ONE component for the canvas node header, the kanban card,+ * the card modal and the sessions sidebar. The canvas and the board are two views of the same+ * nodes (CONTRIBUTING), so a chip that only existed on one of them would say a pane is on+ * `.claude-2` in one view and nothing at all in the other.+ */+export function AccountChip({+ chip,+ warning = false,+ className+}: {+ chip: AccountChipInfo | null+ /** The existing spawn-time fallback tint (account folder missing → ran on the system account). */+ warning?: boolean+ className?: string+}): React.JSX.Element | null {+ if (!chip) return null+ return (+ <span+ className={`node-account-chip node-account-chip--${chip.kind}${+ warning ? ' node-account-chip--warning' : ''+ }${className ? ` ${className}` : ''}`}+ title={chip.tooltip}+ >+ {chip.short}+ </span>+ )+}++/**+ * The chip for one node, resolved against live settings + agent status. `null` = render nothing+ * (D6: the system account with only one identity in play is the unremarkable case).+ *+ * Reads the DEFAULT agent-status store on purpose: it is the store Canvas's `agent:status`+ * listener writes and the store every one of these surfaces already reads its `status` from, so+ * the chip cannot disagree with the RUNNING/unread badges beside it.+ */+export function useAccountChip(+ /** The node's creation-time account (`data.accountId`) — absent for a plain terminal. */+ dataAccountId: string | undefined,+ /** What this node's session was observed running as (agent-status `account`). */+ observed: ObservedClaudeAccount | undefined+): AccountChipInfo | null {+ const accounts = useSettings((s) => s.settings.claudeAccounts)+ const systemLabel = useSettings((s) => s.settings.systemAccountLabel)+ const systemEmail = useSystemAccount((s) => s.email)+ // A PRIMITIVE selector (the `usageScopeKey` rule): this subscription lives on every node header+ // on the canvas, and returning the key set itself would re-render all of them on every hook+ // event of every node. `hasMultipleAccountKeys` early-exits at the second key.+ const multiple = useAgentStatus((s) => hasMultipleAccountKeys(s.byId, dataAccountId))+ // The system account's email is looked up lazily and only when something will show it — a node+ // whose account is entirely unknown renders no chip, so it must not trigger the fetch.+ const known = accountKey(dataAccountId, observed) !== null+ useEffect(() => {+ if (known) useSystemAccount.getState().ensure()+ }, [known])+ return useMemo(+ () => accountChipFor({ dataAccountId, observed, accounts, systemLabel, systemEmail, multiple }),+ [dataAccountId, observed, accounts, systemLabel, systemEmail, multiple]+ )+}diff --git a/src/renderer/components/SessionRow.tsx b/src/renderer/components/SessionRow.tsxindex bdc7dd214..12613dd40 100644--- a/src/renderer/components/SessionRow.tsx+++ b/src/renderer/components/SessionRow.tsx@@ -1,4 +1,5 @@import { useState } from 'react'+import { AccountChip, useAccountChip } from './AccountChip'import { IconBellFilled, IconCircleCheck } from './icons'import { ProjectGlyph } from './ProjectGlyph'import type { SessionRowVM } from '../lib/sessionList'@@ -44,6 +45,9 @@ export function SessionRow({const naming = useSessionNaming((s) => !!s.byId[row.id])const usage = useContextWindow((s) => (row.sessionId ? s.bySessionId[row.sessionId] : undefined))const percentMode = useSettings((s) => s.settings.usagePercentMode)+ // The sidebar is one more view of the same nodes, so it gets the canvas header's account chip+ // under the same visibility rule — two rows on two Claude logins are otherwise indistinguishable.+ const accountChip = useAccountChip(row.accountId, row.account)const commit = (): void => {const t = draft.trim()@@ -139,6 +143,7 @@ export function SessionRow({</span>)}{row.session && <span className="ss-chip">{row.session}</span>}+ <AccountChip chip={accountChip} />{row.loop && (<span className="ss-loop">{row.loop.kind} · {row.loop.count}diff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsxindex 5d8019863..e34cacdea 100644--- a/src/renderer/components/kanban/CardModal.tsx+++ b/src/renderer/components/kanban/CardModal.tsx@@ -3,6 +3,7 @@ import { createPortal } from 'react-dom'import { isTopDialog, nextDialogId, popDialog, pushDialog } from '../dialog-stack'import { IconChat, IconMic, IconSearch } from '../icons'import { ContextMeter } from '../ContextMeter'+import { AccountChip, useAccountChip } from '../AccountChip'import { useAgentStatus } from '../../state/agentStatus'import { useCardPanel } from '../../state/cardPanel'import {@@ -63,6 +64,10 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,const [editingNote, setEditingNote] = useState(false)const agentSessionId = useAgentStatus((st) => st.byId[session.id]?.sessionId)const paused = useAgentStatus((st) => !!st.byId[session.id]?.paused)+ // Same chip as the card and the canvas node header — the modal is where a user checks WHICH+ // session this is, so the account belongs in its header chips, not only two views away.+ const observedAccount = useAgentStatus((st) => st.byId[session.id]?.account)+ const accountChip = useAccountChip(session.spawn.accountId, observedAccount)const [naming, setNaming] = useState(false)// Comments & activity panel: OPEN by default in the modal; the header 💬 collapses it. The// choice is remembered (localStorage) — once collapsed, later cards open collapsed too.@@ -255,6 +260,7 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,</span>)}<span className="kanban-modal__column">{columnTitle ?? 'Ungrouped'}</span>+ {isTerminal && <AccountChip chip={accountChip} />}{/* The driving chip, so a user watching a browser card THROUGH the modal is notdriving-blind. The lease is keyed by node id (not by webview object), so this showswhen the node is being driven even though the drive lands on the CANVAS webview, notdiff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsxindex 0326c8fa4..4b82b26f9 100644--- a/src/renderer/components/kanban/ModalTerminal.tsx+++ b/src/renderer/components/kanban/ModalTerminal.tsx@@ -5,6 +5,7 @@ import { SearchAddon } from '@xterm/addon-search'import { quantizeCharSize } from '../../terminal/char-size-quantize'import { reportsOwnCopy } from '@shared/agents/config'import type { AgentId } from '@shared/agents/config'+import { effectiveAccountId } from '../../lib/accountChip'import { readsClaudeTranscript } from '../../lib/transcriptGates'import { liveProjectJumpTarget } from '../../lib/projectJump'import { terminalChordBubbles, terminalShortcutPolicy } from '../../lib/keybindingOverrides'@@ -100,6 +101,10 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Modaconst fitRef = useRef<FitAddon | null>(null)const transportRef = useRef<LocalTransport | null>(null)const agentSessionId = useAgentStatus((s) => s.byId[nodeId]?.sessionId)+ // MIRROR TerminalNode: transcript READS go to the account the session is actually running as+ // (D5), which for a plain terminal is only ever the observed one. The spawn below keeps+ // `spawn.accountId` — launch identity stays creation-time.+ const observedAccount = useAgentStatus((s) => s.byId[nodeId]?.account)// One shallow-compared subscription for the whole appearance slice — see useXtermVisualSettings.// MIRROR TerminalNode: scoped to the OWNING project (`owningProjectId`, the active one — a modal// only ever opens over it), deliberately NOT this card's connection scope. `sshConnectionScope`@@ -128,7 +133,7 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: ModanodeId,sessionId: agentSessionId,cwd: spawn.cwd,- accountId: spawn.accountId,+ accountId: effectiveAccountId(spawn.accountId, observedAccount),// MIRROR TerminalNode: the transcript index reads claude's JSONL through claude's resolver, so// it is gated on the claude-transcript fact, NOT on the context meter's `hasUsage` (which now// spans codex and gemini too) — see lib/transcriptGates.ts.diff --git a/src/renderer/components/kanban/SessionCard.tsx b/src/renderer/components/kanban/SessionCard.tsxindex 48a571809..ed9fda17b 100644--- a/src/renderer/components/kanban/SessionCard.tsx+++ b/src/renderer/components/kanban/SessionCard.tsx@@ -1,6 +1,7 @@import { memo, useState } from 'react'import type { KanbanCardMeta, KanbanLabel, KanbanPriority } from '@shared/types'import { useAgentStatus } from '../../state/agentStatus'+import { AccountChip, useAccountChip } from '../AccountChip'import { ContextMeter } from '../ContextMeter'import { LabelChips } from './LabelChips'import type { KanbanSession } from './KanbanView'@@ -39,6 +40,10 @@ export const SessionCard = memo(function SessionCard({// (see its loopSig comment) and StatusAwareMiniMap demonstrates: subscribe where the value is// read, so the re-render is confined to the one thing that changed.const status = useAgentStatus((s) => s.byId[session.id])+ // The board is the canvas's other view of the same node (CONTRIBUTING), so the card carries the+ // node header's account chip from the same helper — created-with account, else what the session+ // was observed running as.+ const accountChip = useAccountChip(session.spawn.accountId, status?.account)// Local drag state only styles THIS card (ghost look) — the drag payload lives in KanbanView.const [dragging, setDragging] = useState(false)// Which edge a drag is hovering over → shows the drop line (top = before, bottom = after).@@ -66,7 +71,10 @@ export const SessionCard = memo(function SessionCard({const due = meta?.dueAtconst overdue = due !== undefined && due < Date.now()const priority = meta?.priority- const hasDetail = !!status?.sessionId || !!status?.session || stickyPreview.includes('\n')+ // The account chip counts as detail in its own right: a card whose only thing to say is "this+ // one is on the other Claude login" is exactly the card that must say it.+ const hasDetail =+ !!status?.sessionId || !!status?.session || !!accountChip || stickyPreview.includes('\n')return (<divclassName={`kanban-card kanban-card--session${dragging ? ' kanban-card--dragging' : ''}${@@ -168,6 +176,7 @@ export const SessionCard = memo(function SessionCard({) : (<><ContextMeter sessionId={status?.sessionId ?? null} />+ <AccountChip chip={accountChip} />{status?.session && (<span className="kanban-card__session" title={status.session}>{status.session}diff --git a/src/renderer/components/settings/sections/AccountsSection.link.test.tsx b/src/renderer/components/settings/sections/AccountsSection.link.test.tsxnew file mode 100644index 000000000..20a6c6eea--- /dev/null+++ b/src/renderer/components/settings/sections/AccountsSection.link.test.tsx@@ -0,0 +1,237 @@+// @vitest-environment jsdom+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { createRoot, type Root } from 'react-dom/client'+import { act } from 'react'+import { AccountsSection } from './AccountsSection'+import { useAgentStatus } from '../../../state/agentStatus'+import { useSettings } from '../../../state/settings'+import { DEFAULT_SETTINGS, type ClaudeAccount, type ObservedClaudeAccount } from '@shared/types'++const CLAUDE_2 = '/home/me/.claude-2'+const observed = (over: Partial<ObservedClaudeAccount> = {}): ObservedClaudeAccount => ({+ configDir: CLAUDE_2,+ accountId: null,+ known: false,+ ...over+})++/** The one call this suite is about; each test swaps in its own behaviour. The default stands in+ * for core: it expands `~` and answers with the NORMALIZED path, which is what gets stored. */+let link = vi.fn(async (configDir: string) => ({+ id: 'linked-1',+ configDir: configDir.replace('~', '/home/me'),+ email: '[email protected]' as string | null+}))+let selectFolder = vi.fn(async () => null as string | null)++function renderSection(accounts: ClaudeAccount[] = []): { host: HTMLElement; root: Root } {+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, claudeAccounts: accounts } })+ const host = document.createElement('div')+ document.body.appendChild(host)+ const root = createRoot(host)+ act(() => {+ root.render(<AccountsSection isActive />)+ })+ return { host, root }+}++const byLabel = (host: HTMLElement, label: string): HTMLButtonElement | undefined =>+ Array.from(host.querySelectorAll('button')).find((b) => b.getAttribute('aria-label') === label) as+ | HTMLButtonElement+ | undefined++const pathInput = (host: HTMLElement): HTMLInputElement =>+ host.querySelector('input[placeholder="~/.claude-2"]') as HTMLInputElement++/** Type into a controlled React input (the native setter, or React never sees the change). */+function type(input: HTMLInputElement, value: string): void {+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!+ act(() => {+ setter.call(input, value)+ input.dispatchEvent(new Event('input', { bubbles: true }))+ })+}++const linkedAccounts = (): ClaudeAccount[] => useSettings.getState().settings.claudeAccounts++beforeEach(() => {+ // Every `applyAccounts` schedules the settings store's 300 ms coalesced save, and that timer+ // reaches for `window` when it fires. Under real timers it can land AFTER vitest tore this+ // file's jsdom down — an unhandled "window is not defined" that fails the whole run, including+ // whatever file happened to share the worker. Faking only setTimeout keeps the timer from ever+ // firing while leaving React's microtask scheduling alone.+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ document.body.innerHTML = ''+ useAgentStatus.setState({ byId: {} })+ link = vi.fn(async (configDir: string) => ({+ id: 'linked-1',+ configDir: configDir.replace('~', '/home/me'),+ email: '[email protected]' as string | null+ }))+ selectFolder = vi.fn(async () => null as string | null)+ // The section also mounts the Codex panel, which hydrates the SSH server list and the system+ // identities on mount — stubbed so those effects resolve instead of throwing on an absent bridge+ // member (a throw takes the whole section down with it, this row included). `settings.save`+ // catches the coalesced 300 ms write every `update()` schedules.+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {+ usage: { fetch: async () => null },+ ssh: { list: async () => [] },+ codexAccounts: { systemIdentity: async () => null, identity: async () => null },+ claudeAccounts: { link: (dir: string) => link(dir) },+ dialog: { selectFolder: () => selectFolder() },+ settings: { save: async () => {} }+ }+})++afterEach(() => {+ vi.useRealTimers()+ useSettings.setState({ settings: DEFAULT_SETTINGS })+ useAgentStatus.setState({ byId: {} })+})++describe('AccountsSection — link an existing config dir', () => {+ it('links the typed path and adopts the captured email as the label', async () => {+ const { host, root } = renderSection()+ type(pathInput(host), '~/.claude-2')+ await act(async () => {+ byLabel(host, 'Link config dir')!.click()+ })+ // `~` expansion belongs to core (it owns the files' machine), so the raw text is what we send.+ expect(link).toHaveBeenCalledWith('~/.claude-2')+ expect(linkedAccounts()).toHaveLength(1)+ expect(linkedAccounts()[0]).toMatchObject({+ id: 'linked-1',+ label: '[email protected]',+ email: '[email protected]',+ // The NORMALIZED path core answered with, not the typed text — the jail matches on this one.+ configDir: CLAUDE_2+ })+ root.unmount()+ })++ it('names a not-yet-signed-in dir by its folder rather than leaving it blank', async () => {+ link = vi.fn(async (configDir: string) => ({ id: 'linked-2', configDir, email: null }))+ const { host, root } = renderSection()+ type(pathInput(host), CLAUDE_2)+ await act(async () => {+ byLabel(host, 'Link config dir')!.click()+ })+ expect(linkedAccounts()[0]).toMatchObject({ label: '.claude-2', configDir: CLAUDE_2 })+ expect(linkedAccounts()[0].email).toBeUndefined()+ root.unmount()+ })++ it('shows the refusal core gave, not a generic failure', async () => {+ // `link` refuses for specific, fixable reasons ("that is the system account", "already+ // linked"); replacing them with "could not link" would leave the user with nothing to do.+ link = vi.fn(async () => {+ throw new Error('That is the system account (~/.claude)')+ })+ const { host, root } = renderSection()+ type(pathInput(host), '~/.claude')+ await act(async () => {+ byLabel(host, 'Link config dir')!.click()+ })+ expect(host.textContent).toContain('That is the system account (~/.claude)')+ expect(linkedAccounts()).toHaveLength(0)+ root.unmount()+ })++ it('fills the path from the folder picker', async () => {+ selectFolder = vi.fn(async () => CLAUDE_2)+ const { host, root } = renderSection()+ await act(async () => {+ Array.from(host.querySelectorAll('button'))+ .find((b) => b.textContent === 'Browse…')!+ .click()+ })+ expect(pathInput(host).value).toBe(CLAUDE_2)+ root.unmount()+ })++ it('hides Browse on a surface whose bridge has no folder picker', async () => {+ // Same fail-closed shape the Add buttons use: E_UNSUPPORTED is a fact about the SURFACE, and+ // typing the path still works — Browse is a convenience, never the only way in.+ selectFolder = vi.fn(async () => {+ throw Object.assign(new Error('unsupported'), { code: 'E_UNSUPPORTED' })+ })+ const { host, root } = renderSection()+ await act(async () => {+ Array.from(host.querySelectorAll('button'))+ .find((b) => b.textContent === 'Browse…')!+ .click()+ })+ expect(Array.from(host.querySelectorAll('button')).some((b) => b.textContent === 'Browse…')).toBe(false)+ root.unmount()+ })+})++describe('AccountsSection — detected config dirs', () => {+ it('lists a dir seen running that has no account, and links it in one click', async () => {+ useAgentStatus.setState({ byId: { n1: { unread: false, account: observed() } } })+ const { host, root } = renderSection()+ expect(host.textContent).toContain('Detected config dirs')+ await act(async () => {+ byLabel(host, `Link ${CLAUDE_2}`)!.click()+ })+ expect(link).toHaveBeenCalledWith(CLAUDE_2)+ expect(linkedAccounts()[0]).toMatchObject({ configDir: CLAUDE_2 })+ root.unmount()+ })++ it('renders nothing when every observed dir is already known', () => {+ useAgentStatus.setState({+ byId: {+ n1: { unread: false, account: observed({ known: true, accountId: null }) }, // the system one+ n2: { unread: false, account: observed({ configDir: '/x/.claude-9' }) }+ }+ })+ // …and an already-linked dir is not offered a second time.+ const { host, root } = renderSection([+ { id: 'a9', label: 'nine', configDir: '/x/.claude-9', createdAt: 0 }+ ])+ expect(host.textContent).not.toContain('Detected config dirs')+ root.unmount()+ })+})++describe('AccountsSection — a linked account is unlinked, never deleted', () => {+ const linked: ClaudeAccount = {+ id: 'a1',+ label: 'second',+ email: '[email protected]',+ configDir: CLAUDE_2,+ createdAt: 0+ }++ it('shows the Linked provenance pill with the path in its tooltip', () => {+ const { host, root } = renderSection([linked])+ const pill = Array.from(host.querySelectorAll('span')).find((el) => el.textContent === 'Linked')+ expect(pill).toBeTruthy()+ expect(pill!.getAttribute('title')).toContain(CLAUDE_2)+ root.unmount()+ })++ it('offers Unlink — and says the folder is kept', () => {+ const { host, root } = renderSection([linked])+ expect(byLabel(host, 'Unlink account')).toBeTruthy()+ expect(byLabel(host, 'Remove account')).toBeUndefined()+ act(() => {+ byLabel(host, 'Unlink account')!.click()+ })+ // The confirm must not promise a deletion that core will not do (it refuses to rm anything+ // outside its own managed dirs) — that wording is what stops people unlinking at all.+ expect(document.body.textContent).toContain(`the folder ${CLAUDE_2} keeps its login`)+ expect(document.body.textContent).not.toContain('will be deleted')+ root.unmount()+ })++ it('keeps the destructive wording for a MANAGED account', () => {+ const { host, root } = renderSection([{ id: 'm1', label: 'managed', createdAt: 0 }])+ act(() => {+ byLabel(host, 'Remove account')!.click()+ })+ expect(document.body.textContent).toContain('will be deleted')+ root.unmount()+ })+})diff --git a/src/renderer/components/settings/sections/AccountsSection.tsx b/src/renderer/components/settings/sections/AccountsSection.tsxindex a45c296d2..bc9314ec4 100644--- a/src/renderer/components/settings/sections/AccountsSection.tsx+++ b/src/renderer/components/settings/sections/AccountsSection.tsx@@ -3,6 +3,7 @@ import type { ClaudeAccount } from '@shared/types'import type { CodexAccount } from '@shared/codex-account'import { E_UNSUPPORTED } from '@shared/rpc'import { sshHostKey } from '@shared/ssh'+import { useAgentStatus } from '../../../state/agentStatus'import { useSettings } from '../../../state/settings'import { useSystemAccount } from '../../../state/systemAccount'import { useSystemCodexAccount } from '../../../state/systemCodexAccount'@@ -19,6 +20,7 @@ import {groupCodexAccountsByMachine,strayCodexAccounts} from '../../../lib/codexMachineGroups'+import { configDirLabel, unlinkedConfigDirs } from '../../../lib/accountChip'import { presentAccount } from '../../../lib/accountPresentation'import { codexAccountSelectable } from '../../../canvas/codex-account-switch'import { AccountIdentityPills } from '../../AccountIdentityPills'@@ -32,7 +34,18 @@ import { cn } from '@renderer/ui/cn'const ROWS = {accounts: {title: 'Claude accounts',- keywords: ['account', 'claude', 'login', 'isolated', 'multi', 'email']+ keywords: [+ 'account',+ 'claude',+ 'login',+ 'isolated',+ 'multi',+ 'email',+ 'link',+ 'config dir',+ 'existing',+ 'detected'+ ]},codex: {title: 'Codex accounts',@@ -46,6 +59,15 @@ const ENTRIES = Object.values(ROWS)const isUnsupported = (e: unknown): boolean =>!!e && typeof e === 'object' && (e as { code?: string }).code === E_UNSUPPORTED+/** The rejection's own message when it has one, else `fallback`. `link` refuses for a handful of+ * specific, user-fixable reasons (not a directory, already linked, that IS the system account) and+ * every one of them is worth more than a generic failure line. Errors arrive as plain objects over+ * the WS bridge, so this reads the field rather than testing `instanceof Error`. */+const errorText = (e: unknown, fallback: string): string => {+ const m = e && typeof e === 'object' ? (e as { message?: unknown }).message : undefined+ return typeof m === 'string' && m.trim() ? m.trim() : fallback+}+/** One machine's card in the accounts UI: a connectivity dot, the machine label, a Local/SSH pill,* and (for a remote machine) its `user@host` subtitle. Children are the provider account rows. */function MachinePanel({@@ -200,6 +222,25 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.*/const [addingOn, setAddingOn] = useState<string | null>(null)const [addError, setAddError] = useState<string | null>(null)+ // "Link existing config dir…": the typed path, the in-flight guard, and the inline error.+ const [linkPath, setLinkPath] = useState('')+ const [linking, setLinking] = useState(false)+ const [linkError, setLinkError] = useState<string | null>(null)+ // A surface whose bridge registers no folder picker (a relay tab, an older server) answers+ // E_UNSUPPORTED once — after that the button is hidden rather than offered and broken. Typing+ // the path still works, which is why Browse is a convenience and never the only way in.+ const [browseUnsupported, setBrowseUnsupported] = useState(false)+ /**+ * Config dirs SEEN running on this core that we have no account for (D7) — the one-click Link+ * candidates. A primitive selector (newline-joined) so the settings page does not re-render on+ * every hook event of every node just to discover the same list again.+ */+ const detectedDirs = useAgentStatus((s) =>+ // NUL-joined, not newline-joined: a path may legally contain a newline, and splitting one back+ // into two rows would offer the user a dir that does not exist.+ unlinkedConfigDirs(s.byId, accounts.map((a) => a.configDir)).join('\u0000')+ )+ const detected = detectedDirs ? detectedDirs.split('\u0000') : []const setLabel = (id: string, label: string): void =>applyAccounts((accs) => accs.map((a) => (a.id === id ? { ...a, label } : a)))@@ -341,6 +382,18 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.}))}+ /** The presented Claude account for a row. Mirrors `presentCodex` — one contract, so a linked+ * account reads the same here as it would anywhere else it is shown. */+ const presentClaude = (account: ClaudeAccount): ReturnType<typeof presentAccount> =>+ presentAccount({+ label: account.label,+ email: account.email,+ host: account.host,+ machineLabel: sshServers.find((entry) => sshHostKey(entry) === account.host)?.label,+ linked: !!account.configDir,+ configDir: account.configDir+ })+// The presented account for a row, resolving the friendly machine label from saved servers.const presentCodex = (account: CodexAccount) => {const server = account.host@@ -506,6 +559,58 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.await runLogin(account)}+ /**+ * Adopt a config dir the user already owns (`~/.claude-2` and friends) as a real account: core+ * validates the path, reads its `.claude.json` for the signed-in email, and installs the managed+ * status hook into it. From then on the dir has an id, so env injection, the transcript jail, the+ * usage rows, the pickers and the node chip all treat it like any other account.+ *+ * `~` is expanded by CORE, not here: the renderer does not know the home dir of the machine that+ * owns the files (the Server Edition's browser is not the filesystem's host).+ */+ const onLink = async (dir: string): Promise<void> => {+ const path = dir.trim()+ if (!path || linking) return+ setLinking(true)+ setLinkError(null)+ try {+ const linked = await window.nodeTerminal.claudeAccounts.link(path)+ applyAccounts((accs) => [+ ...accs,+ {+ id: linked.id,+ // Named by its login when the dir is signed in; otherwise by the folder, which is how+ // the user thinks of it anyway ("the .claude-2 one"). Never a generated placeholder.+ label: linked.email ?? configDirLabel(linked.configDir),+ ...(linked.email ? { email: linked.email } : {}),+ // The NORMALIZED path core resolved, never the raw text typed here: it is re-validated+ // at every point of use, and the two must be the same string for the jail to match.+ configDir: linked.configDir,+ createdAt: Date.now()+ }+ ])+ setLinkPath('')+ } catch (e) {+ setLinkError(+ isUnsupported(e)+ ? 'Linking a config dir is not available on this surface — do it from the desktop app or the Server Edition directly.'+ : errorText(e, 'Could not link that config dir.')+ )+ } finally {+ setLinking(false)+ }+ }++ const onBrowse = async (): Promise<void> => {+ try {+ const folder = await window.nodeTerminal.dialog.selectFolder()+ if (folder) setLinkPath(folder)+ } catch (e) {+ if (isUnsupported(e)) setBrowseUnsupported(true)+ else setLinkError(errorText(e, 'Could not open the folder picker.'))+ }+ }+const confirmRemove = async (account: ClaudeAccount): Promise<void> => {setPendingRemove(null)// Removing a pending account: stop the 5-minute waitLogin poll loop first.@@ -537,7 +642,14 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.const removeMessage = (a: ClaudeAccount): string => {const n = countNodesUsing(a.id)- return `Remove account "${a.label}"? Its logged-in credentials and all its Claude transcripts will be deleted. ${n} node(s) currently use it and will fall back to the system account.`+ const fallout = `${n} node(s) currently use it and will fall back to the system account.`+ // A LINKED dir is the user's own folder — removing the account forgets the record and deletes+ // NOTHING (core refuses to `rm -rf` anything outside its own managed dirs). Saying "will be+ // deleted" here would be a lie that stops people unlinking.+ if (a.configDir) {+ return `Unlink account "${a.label}"? nodeterm forgets it — the folder ${a.configDir} keeps its login and transcripts exactly as they are. ${fallout}`+ }+ return `Remove account "${a.label}"? Its logged-in credentials and all its Claude transcripts will be deleted. ${fallout}`}return (@@ -616,6 +728,18 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.{account.host}</span>) : null}+ {/* A LINKED account: the user's own dir, adopted rather than minted. The path+ is the identifying fact (no label reliably tells `.claude-2` from+ `.claude-work`), so it rides the tooltip — through `presentAccount`, so+ this row says the same thing every other account surface would. */}+ {account.configDir ? (+ <span+ className="rounded-full bg-fill-weak px-2 py-0.5 text-[11px] font-medium text-muted"+ title={presentClaude(account).tooltip}+ >+ {presentClaude(account).provenance}+ </span>+ ) : null}</div>{account.email && !account.pending ? (<p className="text-[12px] text-muted">{account.email}</p>@@ -650,7 +774,9 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.: null}<Buttonvariant="ghost"- aria-label="Remove account"+ // "Unlink" for a linked dir: the action really is different (the folder stays),+ // and the label is what a screen reader and the tests both go by.+ aria-label={account.configDir ? 'Unlink account' : 'Remove account'}onClick={() => setPendingRemove(account)}>×@@ -718,6 +844,77 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.</div>)}+ {/* LINK an existing config dir (D4). The other half of "several Claude logins": a user+ who already keeps `~/.claude-2` and drives it from their own shell function does not+ want a new managed dir — they want THIS one to have an id, so the chip, the transcript+ readers and the pickers stop treating their second login as a stranger. Local only:+ a linked dir is a path on the machine that owns the files. */}+ <div className="space-y-2 rounded-md border border-border p-3">+ <div className="text-[13px] font-medium text-text">Link existing config dir…</div>+ <p className="text-[12px] leading-relaxed text-muted">+ Already have a second login in its own folder (say <code>~/.claude-2</code>)? Link it+ and nodeterm will label its terminals, read its transcripts, and offer it in the add+ menus. Nothing is copied or moved, and unlinking later leaves the folder alone.+ </p>+ <div className="flex flex-wrap items-center gap-2">+ <Input+ className="w-72"+ placeholder="~/.claude-2"+ value={linkPath}+ onChange={(e) => setLinkPath(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') void onLink(linkPath)+ }}+ />+ {browseUnsupported ? null : (+ <Button disabled={linking} onClick={() => void onBrowse()}>+ Browse…+ </Button>+ )}+ <Button+ variant="primary"+ // Named: the detected list below repeats the word "Link" once per row, and a+ // bare label leaves both the user's screen reader and the tests guessing which.+ aria-label="Link config dir"+ disabled={linking || !linkPath.trim()}+ onClick={() => void onLink(linkPath)}+ >+ {linking ? (+ <span className="inline-flex items-center gap-2">+ <span className="ui-spinner" aria-hidden />+ Linking…+ </span>+ ) : (+ 'Link'+ )}+ </Button>+ </div>+ {linkError ? <p className="text-[12px] text-[color:var(--danger)]">{linkError}</p> : null}++ {/* DETECTED dirs: config dirs whose sessions actually posted hooks here and that we+ have no account for. Derived from observations only — nothing on disk is read for+ an unlinked dir (a forged POST must not make us stat anything), so the path is all+ that is shown. Empty ⇒ this whole block is absent. */}+ {detected.length > 0 ? (+ <div className="space-y-2 pt-1">+ <div className="text-[12px] font-medium text-text">Detected config dirs</div>+ {detected.map((dir) => (+ <div+ key={dir}+ className="flex items-center justify-between gap-3 rounded-md border border-border/60 p-2"+ >+ <span className="min-w-0 flex-1 truncate text-[12px] text-muted" title={dir}>+ {dir}+ </span>+ <Button aria-label={`Link ${dir}`} disabled={linking} onClick={() => void onLink(dir)}>+ Link+ </Button>+ </div>+ ))}+ </div>+ ) : null}+ </div>+<p className="text-[12px] leading-relaxed text-muted">Accounts are isolated Claude logins. New Claude nodes pick an account from the addmenus; each node keeps its account for life. A node color applies to nodes opened under@@ -787,7 +984,7 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.{pendingRemove ? (<ConfirmDialogmessage={removeMessage(pendingRemove)}- confirmLabel="Remove"+ confirmLabel={pendingRemove.configDir ? 'Unlink' : 'Remove'}onConfirm={() => void confirmRemove(pendingRemove)}onCancel={() => setPendingRemove(null)}/>diff --git a/src/renderer/lib/accountChip.test.ts b/src/renderer/lib/accountChip.test.tsnew file mode 100644index 000000000..be2aa6720--- /dev/null+++ b/src/renderer/lib/accountChip.test.ts@@ -0,0 +1,216 @@+import { describe, it, expect } from 'vitest'+import type { ClaudeAccount, ObservedClaudeAccount } from '@shared/types'+import {+ accountChipFor,+ accountKey,+ configDirLabel,+ distinctAccountKeys,+ effectiveAccountId,+ hasMultipleAccountKeys,+ SYSTEM_ACCOUNT_KEY,+ unlinkedConfigDirs+} from './accountChip'++const acct = (over: Partial<ClaudeAccount> = {}): ClaudeAccount => ({+ id: 'a1',+ label: '[email protected]',+ email: '[email protected]',+ createdAt: 0,+ ...over+})++const observed = (over: Partial<ObservedClaudeAccount> = {}): ObservedClaudeAccount => ({+ configDir: '/home/me/.claude',+ accountId: null,+ known: true,+ ...over+})++const system = observed()+const managed = observed({ configDir: '/data/claude-accounts/a1', accountId: 'a1' })+const unlinked = observed({ configDir: '/home/me/.claude-2', accountId: null, known: false })++describe('effectiveAccountId (D5)', () => {+ it('prefers the node\u2019s own account over the observed one', () => {+ // Launch identity is what the env actually injected; an observation cannot outrank it.+ expect(effectiveAccountId('a1', managed)).toBe('a1')+ expect(effectiveAccountId('a1', system)).toBe('a1')+ })++ it('falls back to a KNOWN observed account for a node created without one', () => {+ expect(effectiveAccountId(undefined, managed)).toBe('a1')+ })++ it('resolves to nothing for the system account and for an unknown dir', () => {+ // Both must read the system account's transcripts, not a stranger's.+ expect(effectiveAccountId(undefined, system)).toBeUndefined()+ expect(effectiveAccountId(undefined, unlinked)).toBeUndefined()+ expect(effectiveAccountId(undefined, undefined)).toBeUndefined()+ })+})++describe('accountKey (D6)', () => {+ it('keys the system account as "sys" only when it is actually observed', () => {+ expect(accountKey(undefined, system)).toBe(SYSTEM_ACCOUNT_KEY)+ // Unobserved is NOT the system account: a plain shell nobody ran claude in must not count as+ // a second identity, or one open terminal would chip every pane on the canvas.+ expect(accountKey(undefined, undefined)).toBeNull()+ })++ it('keys a managed/linked account by id, from either source', () => {+ expect(accountKey('a1', undefined)).toBe('a1')+ expect(accountKey(undefined, managed)).toBe('a1')+ })++ it('keys an unlinked dir by its path', () => {+ expect(accountKey(undefined, unlinked)).toBe('ext:/home/me/.claude-2')+ // Two different unlinked dirs are two identities.+ expect(accountKey(undefined, observed({ configDir: '/home/me/.claude-3', known: false })))+ .toBe('ext:/home/me/.claude-3')+ })++ it('refuses to key an unknown observation with no dir', () => {+ expect(accountKey(undefined, observed({ configDir: '', known: false }))).toBeNull()+ })+})++describe('distinctAccountKeys', () => {+ it('counts identities and ignores unknown nodes', () => {+ const keys = distinctAccountKeys([+ { observed: system },+ { observed: system },+ { observed: unlinked },+ { dataAccountId: 'a1' },+ {} // an unobserved plain terminal contributes nothing+ ])+ expect([...keys].sort()).toEqual(['a1', 'ext:/home/me/.claude-2', 'sys'])+ })+})++describe('hasMultipleAccountKeys (the selector form)', () => {+ it('is false while one identity is in play', () => {+ expect(hasMultipleAccountKeys({ n1: { account: system }, n2: { account: system } })).toBe(false)+ expect(hasMultipleAccountKeys({ n1: {}, n2: {} })).toBe(false)+ })++ it('is true once a second identity appears — the real two-logins case', () => {+ // ~/.claude in one pane, ~/.claude-2 in another: exactly what the feature exists for.+ expect(hasMultipleAccountKeys({ n1: { account: system }, n2: { account: unlinked } })).toBe(true)+ })++ it('counts THIS node\u2019s creation-time account too', () => {+ // The store only holds observed accounts, so a managed node that has posted no hook yet is+ // only visible through its own `data.accountId`.+ expect(hasMultipleAccountKeys({ n1: { account: system } }, 'a1')).toBe(true)+ expect(hasMultipleAccountKeys({ n1: { account: managed } }, 'a1')).toBe(false)+ })+})++describe('configDirLabel', () => {+ it('names a POSIX dir by its last segment, trailing slash or not', () => {+ expect(configDirLabel('/home/me/.claude-2')).toBe('.claude-2')+ expect(configDirLabel('/home/me/.claude-2/')).toBe('.claude-2')+ })++ it('names a Windows-shaped dir by its last segment', () => {+ // Windows is a delivery target and an SSH node can report a remote path either way.+ expect(configDirLabel('C:\\Users\\me\\.claude-2')).toBe('.claude-2')+ expect(configDirLabel('\\\\server\\share\\.claude-2')).toBe('.claude-2')+ })++ it('keeps a POSIX backslash as filename text, not as a separator', () => {+ // A backslash is legal in a POSIX filename; splitting on it would mislabel the dir.+ expect(configDirLabel('/home/me/weird\\name')).toBe('weird\\name')+ })++ it('falls back to the whole string when there is no segment', () => {+ expect(configDirLabel('/')).toBe('/')+ })+})++describe('accountChipFor (D6 visibility, D7 unlinked naming)', () => {+ const accounts = [acct(), acct({ id: 'a2', label: 'personal', email: undefined, configDir: '/home/me/.claude-2' })]++ it('shows no chip for a system node while one identity is in play', () => {+ expect(accountChipFor({ observed: system, accounts, multiple: false })).toBeNull()+ })++ it('shows the system chip once a second identity is in play', () => {+ const chip = accountChipFor({+ observed: system,+ accounts,+ systemLabel: '',+ systemEmail: '[email protected]',+ multiple: true+ })+ expect(chip).toEqual({+ short: 'me',+ tooltip: '[email protected] — system Claude account (~/.claude)',+ kind: 'system'+ })+ })++ it('prefers the user\u2019s own system label over the detected email', () => {+ expect(+ accountChipFor({ observed: system, accounts, systemLabel: 'Personal', systemEmail: '[email protected]', multiple: true })+ ?.short+ ).toBe('Personal')+ })++ it('chips a managed account whatever the count — the exception is what must be seen', () => {+ expect(accountChipFor({ dataAccountId: 'a1', accounts, multiple: false })).toEqual({+ short: 'work',+ tooltip: '[email protected] ([email protected])',+ kind: 'managed'+ })+ })++ it('marks an account that carries a linked config dir as linked', () => {+ expect(accountChipFor({ dataAccountId: 'a2', accounts, multiple: false })).toEqual({+ short: 'personal',+ tooltip: 'personal',+ kind: 'linked'+ })+ })++ it('names an unlinked dir by its last segment and says how to link it', () => {+ expect(accountChipFor({ observed: unlinked, accounts, multiple: false })).toEqual({+ short: '.claude-2',+ tooltip: 'Unlinked Claude config dir /home/me/.claude-2 — link it in Settings → Accounts',+ kind: 'unlinked'+ })+ })++ it('shows nothing for a node whose account is unknown', () => {+ expect(accountChipFor({ accounts, multiple: true })).toBeNull()+ })++ it('follows the observed account when the node was created without one', () => {+ // The plain-terminal case: nodeterm never launched this claude, so the chip is the only place+ // the identity shows up at all.+ expect(accountChipFor({ observed: managed, accounts, multiple: false })?.short).toBe('work')+ })+})++describe('unlinkedConfigDirs (Settings → Accounts “Detected config dirs”)', () => {+ it('lists each unknown dir once, sorted, and never a known one', () => {+ expect(+ unlinkedConfigDirs({+ n1: { account: unlinked },+ n2: { account: unlinked }, // same dir, two panes+ n3: { account: observed({ configDir: '/home/me/.claude-3', known: false }) },+ n4: { account: system }, // known: not a candidate+ n5: { account: managed },+ n6: {}+ })+ ).toEqual(['/home/me/.claude-2', '/home/me/.claude-3'])+ })++ it('drops a dir that is already linked', () => {+ expect(unlinkedConfigDirs({ n1: { account: unlinked } }, ['/home/me/.claude-2'])).toEqual([])+ // …and tolerates the undefined `configDir` every managed account has.+ expect(unlinkedConfigDirs({ n1: { account: unlinked } }, [undefined])).toEqual([+ '/home/me/.claude-2'+ ])+ })+})diff --git a/src/renderer/lib/accountChip.ts b/src/renderer/lib/accountChip.tsnew file mode 100644index 000000000..56f411756--- /dev/null+++ b/src/renderer/lib/accountChip.ts@@ -0,0 +1,220 @@+import type { ClaudeAccount, ObservedClaudeAccount } from '@shared/types'+import { accountChipLabel, systemAccountDisplay } from '../state/workspace'++/**+ * Per-node Claude account labelling — the pure half of the account chip (plan §5 WP-B.2,+ * decisions D5–D7).+ *+ * A node's account has TWO possible sources and they routinely disagree:+ * - `data.accountId` — the managed/linked account the node was CREATED with. Immutable, and the+ * only thing that steers `CLAUDE_CONFIG_DIR` at spawn.+ * - `ObservedClaudeAccount` — what the RUNNING session's hooks reported (agent-status store).+ * For a plain terminal where the user ran `export CLAUDE_CONFIG_DIR=~/.claude-2; claude`, this+ * is the only identity that exists anywhere.+ *+ * Everything here is pure and display/read-only. An observed account is a LABEL (see the+ * `ObservedClaudeAccount` doc comment in shared/types): it may decide what we SHOW and whose+ * transcripts we READ, never what is permitted — so nothing in this module is a gate.+ */++/** The account key for the system default (`~/.claude`), which has no `ClaudeAccount` record. */+export const SYSTEM_ACCOUNT_KEY = 'sys'++/** Chip labels are ~one word wide; the same cap `accountChipLabel` applies to a managed label. */+const MAX_CHIP_LABEL = 10++/**+ * D5 — the account a node's READERS (transcript root, session name, context meter, ⌘M chat) must+ * use: the node's own account when it has one, else whatever the session was observed running as.+ *+ * `known` is what makes the observed id meaningful: an unrecognised config dir reports+ * `accountId: null`, and must resolve to `undefined` (→ the system account's readers) rather than+ * to some other account's transcripts. Deliberately NOT used for spawn/env — launch identity stays+ * creation-time.+ */+export function effectiveAccountId(+ dataAccountId?: string,+ observed?: ObservedClaudeAccount+): string | undefined {+ if (dataAccountId) return dataAccountId+ if (observed?.known && observed.accountId) return observed.accountId+ return undefined+}++/**+ * D6 — the identity key a node counts as, for "is more than one account in play?".+ *+ * - `<accountId>` — a managed or linked account (from the node, or observed);+ * - `'sys'` — the system default (`~/.claude`), which has no id of its own;+ * - `ext:<dir>` — a config dir nodeterm has no record of, keyed by its path because that is the+ * only thing that tells two unlinked dirs apart;+ * - `null` — nothing is known about this node's account. NOT a key: an unobserved plain+ * terminal must not count as a second identity (it would put a chip on every+ * system pane the moment one shell was opened), and it gets no chip.+ */+export function accountKey(+ dataAccountId?: string,+ observed?: ObservedClaudeAccount+): string | null {+ if (dataAccountId) return dataAccountId+ if (!observed) return null+ if (observed.known) return observed.accountId ?? SYSTEM_ACCOUNT_KEY+ // A `known: false` entry with no dir is not evidence of anything — it names no identity, so it+ // cannot be a distinct key (degrade to nothing, never to something wrong).+ return observed.configDir ? `ext:${observed.configDir}` : null+}++/** The distinct account keys across a set of nodes (see `accountKey`); unknown nodes contribute+ * nothing. `size >= 2` is D6's "there's multiple". */+export function distinctAccountKeys(+ entries: Iterable<{ dataAccountId?: string; observed?: ObservedClaudeAccount }>+): Set<string> {+ const keys = new Set<string>()+ for (const e of entries) {+ const key = accountKey(e.dataAccountId, e.observed)+ if (key) keys.add(key)+ }+ return keys+}++/**+ * The selector form of `distinctAccountKeys().size >= 2`, over an agent-status table plus THIS+ * node's own `data.accountId`.+ *+ * Returns a PRIMITIVE on purpose (the `usageScopeKey` rule): a chip subscriber runs this on every+ * hook event of every node, and a Set/array result would give each of them fresh props and+ * re-render every node header on an unrelated status edit. Early-exits at two keys.+ *+ * The store only knows OBSERVED accounts, so other nodes' creation-time `data.accountId` is not+ * counted — a managed node that has never posted a hook is invisible here. That is the cheap,+ * store-only reading of D6 and it fails in the safe direction: one chip fewer, never a wrong one.+ */+export function hasMultipleAccountKeys(+ byId: Record<string, { account?: ObservedClaudeAccount }>,+ ownAccountId?: string+): boolean {+ const keys = new Set<string>()+ const own = accountKey(ownAccountId, undefined)+ if (own) keys.add(own)+ for (const entry of Object.values(byId)) {+ const key = accountKey(undefined, entry.account)+ if (key) keys.add(key)+ if (keys.size >= 2) return true+ }+ return keys.size >= 2+}++/**+ * The config dirs seen running on this core that nodeterm has no account for — Settings →+ * Accounts lists these as one-click "Link" candidates (D7).+ *+ * Derived from OBSERVATIONS only: a dir gets in here because a session posted a hook from it, so+ * the list is a record of what actually ran, and nothing here reads the filesystem (a forged POST+ * must not make us stat anything). `linkedDirs` is compared by exact string — the same normalized+ * form the classifier failed to match is the one that would still fail to match.+ */+export function unlinkedConfigDirs(+ byId: Record<string, { account?: ObservedClaudeAccount }>,+ linkedDirs: readonly (string | undefined)[] = []+): string[] {+ const already = new Set(linkedDirs.filter((d): d is string => !!d))+ const dirs = new Set<string>()+ for (const entry of Object.values(byId)) {+ const a = entry.account+ if (a && !a.known && a.configDir && !already.has(a.configDir)) dirs.add(a.configDir)+ }+ // Sorted so the list does not reshuffle itself as unrelated nodes come and go.+ return [...dirs].sort()+}++export interface AccountChipInfo {+ /** Chip text — one short word. */+ short: string+ /** Native tooltip: the full identity, or (unlinked) what to do about it. */+ tooltip: string+ kind: 'system' | 'managed' | 'linked' | 'unlinked'+}++/** `label` → chip text: the part before `@`, capped with an ellipsis. Same rule as+ * `accountChipLabel` (which owns it for managed accounts and also builds their tooltip); kept+ * here for the system/unlinked labels rather than importing a cycle back out of `state/`. */+function shortAccountLabel(label: string): string {+ const base = label.split('@')[0]+ return base.length > MAX_CHIP_LABEL ? `${base.slice(0, MAX_CHIP_LABEL)}…` : base+}++/**+ * Last segment of a config dir path, for an unlinked dir's chip (D7 — named by path, never read).+ *+ * The owning filesystem is NOT known here: the dir string comes from a hook that may have run on+ * this machine, on an SSH host, or on Windows. So the separator is picked from the SHAPE of the+ * string instead of treating both as interchangeable — on POSIX a backslash is legal filename text+ * (CONTRIBUTING: "do not treat both separators as interchangeable unless the owning filesystem is+ * known to be Windows"). A drive letter, a UNC prefix, or backslashes with no forward slash is+ * Windows-shaped; everything else is POSIX-shaped.+ */+export function configDirLabel(configDir: string): string {+ const dir = configDir.trim()+ if (!dir) return ''+ const windowsShaped = /^[a-zA-Z]:[\\/]/.test(dir) || dir.startsWith('\\\\') || (dir.includes('\\') && !dir.includes('/'))+ const sep = windowsShaped ? '\\' : '/'+ const parts = dir.split(sep).filter((p) => p.length > 0)+ // A bare root (`/`, `C:\`) has no segment to name; fall back to the whole string so the chip+ // still says something rather than rendering empty.+ return parts[parts.length - 1] ?? dir+}++/**+ * The chip for one node, or `null` for no chip.+ *+ * D6 visibility: a node that is NOT on the system account always gets a chip (it is the exception+ * the user needs to see), and system nodes get one only when `multiple` — i.e. when at least two+ * identities are in play, so two panes side by side are always told apart.+ */+export function accountChipFor({+ dataAccountId,+ observed,+ accounts,+ systemLabel,+ systemEmail,+ multiple+}: {+ dataAccountId?: string+ observed?: ObservedClaudeAccount+ accounts: ClaudeAccount[]+ /** `settings.systemAccountLabel` — the user's own name for the `~/.claude` login. */+ systemLabel?: string+ /** The detected `~/.claude` login email (`state/systemAccount`), when known. */+ systemEmail?: string | null+ /** D6: are ≥ 2 distinct account keys in play on this core? (`hasMultipleAccountKeys`) */+ multiple?: boolean+}): AccountChipInfo | null {+ const key = accountKey(dataAccountId, observed)+ if (!key) return null // nothing known — no chip, and nothing counted either+ if (key === SYSTEM_ACCOUNT_KEY) {+ if (!multiple) return null // one identity in play: the system pane is the unremarkable case+ const display = systemAccountDisplay(systemLabel, systemEmail)+ return {+ short: shortAccountLabel(display),+ tooltip: `${display} — system Claude account (~/.claude)`,+ kind: 'system'+ }+ }+ if (key.startsWith('ext:')) {+ // D7: named by its path and NEVER read. The tooltip is the whole affordance — it says what the+ // dir is and where to turn it into a real account.+ const dir = key.slice('ext:'.length)+ return {+ short: shortAccountLabel(configDirLabel(dir)),+ tooltip: `Unlinked Claude config dir ${dir} — link it in Settings → Accounts`,+ kind: 'unlinked'+ }+ }+ const label = accountChipLabel(key, accounts)+ if (!label) return null // unreachable: `key` is a non-empty id here+ // A linked account is a dir the user already owned (`ClaudeAccount.configDir`), which is worth+ // showing differently from a managed one: removing it keeps the folder, and it is the identity a+ // hand-launched `claude` will keep using whatever nodeterm does.+ const linked = !!accounts.find((a) => a.id === key)?.configDir+ return { short: label.short, tooltip: label.tooltip, kind: linked ? 'linked' : 'managed' }+}diff --git a/src/renderer/lib/accountPresentation.test.ts b/src/renderer/lib/accountPresentation.test.tsindex 78d875439..bbb66b8ac 100644--- a/src/renderer/lib/accountPresentation.test.ts+++ b/src/renderer/lib/accountPresentation.test.ts@@ -47,4 +47,22 @@ describe('presentAccount', () => {// absent the raw `user@host` must still read as SSH, never as Local.expect(presentAccount({ email: 'r@x', host: 'me@box' }).provenance).toBe('SSH · me@box')})++ it('gives a linked config dir its own provenance, with the path in the tooltip', () => {+ // A linked account is local, but "Local" alone loses the one fact that identifies it: WHICH+ // dir. Removing it keeps that folder, so the path is what the user is deciding about.+ expect(+ presentAccount({ label: 'second', email: '[email protected]', linked: true, configDir: '/home/me/.claude-2' })+ ).toEqual({+ identity: 'second',+ provenance: 'Linked',+ tooltip: 'second ([email protected]) · Linked /home/me/.claude-2'+ })+ })++ it('never calls a remote account linked (a linked dir is local by definition)', () => {+ const p = presentAccount({ email: 'r@x', host: 'me@box', linked: true, configDir: '/nope' })+ expect(p.provenance).toBe('SSH · me@box')+ expect(p.tooltip).toBe('r@x · SSH me@box')+ })})diff --git a/src/renderer/lib/accountPresentation.ts b/src/renderer/lib/accountPresentation.tsindex 9d5c09edc..5eea31119 100644--- a/src/renderer/lib/accountPresentation.ts+++ b/src/renderer/lib/accountPresentation.ts@@ -42,7 +42,9 @@ export function presentAccount({label,email,host,- machineLabel+ machineLabel,+ linked,+ configDir}: {label?: string | nullemail?: string | null@@ -50,12 +52,27 @@ export function presentAccount({host?: string | null/** Friendly saved SSH-machine name. */machineLabel?: string | null+ /**+ * A LINKED account: a config dir the user already owned, adopted by `claudeAccounts.link`+ * (`ClaudeAccount.configDir`). Still local — but worth its own provenance, because it is the one+ * kind whose removal keeps the folder and whose dir the user drives from their own shell.+ * Ignored when `host` is set: a linked account is local by definition.+ */+ linked?: boolean+ /** The linked dir, for the tooltip. The path IS the useful fact about a linked account — it is+ * what tells `~/.claude-2` from `~/.claude-work`, which no label reliably does. */+ configDir?: string | null}): AccountPresentation {const displayLabel = chosenLabel(label)const cleanEmail = email?.trim() || undefinedconst identity = displayLabel || cleanEmail || 'Default account'- const provenance = host ? `SSH · ${machineLabel?.trim() || host}` : 'Local'- const originDetail = host ? `SSH ${host}` : 'This Mac'+ const isLinked = !host && !!linked+ const provenance = host ? `SSH · ${machineLabel?.trim() || host}` : isLinked ? 'Linked' : 'Local'+ const originDetail = host+ ? `SSH ${host}`+ : isLinked+ ? `Linked ${configDir?.trim() || 'config dir'}`+ : 'This Mac'const identityDetail =cleanEmail && cleanEmail !== identity ? `${identity} (${cleanEmail})` : identityreturn {diff --git a/src/renderer/lib/sessionList.ts b/src/renderer/lib/sessionList.tsindex 83617f3b4..0edef64c0 100644--- a/src/renderer/lib/sessionList.ts+++ b/src/renderer/lib/sessionList.ts@@ -1,6 +1,6 @@import type { AgentNodeStatus } from '../state/agentStatus'import type { AgentId } from '@shared/agents/config'-import type { NodeKind } from '@shared/types'+import type { NodeKind, ObservedClaudeAccount } from '@shared/types'import { hasUsage } from '@shared/agents/config'import type { SshConnection } from '@shared/ssh'import type { ProjectIcon } from '@shared/project-icon'@@ -12,6 +12,10 @@ export interface SessionNodeInput {title: stringcolor: stringagentId?: AgentId+ /** The node's creation-time managed/linked Claude account (`data.accountId`), for the row's+ * account chip. Absent for a plain terminal — which is exactly the case the OBSERVED account+ * on the status entry covers. */+ accountId?: stringcwd?: stringssh?: SshConnection/** Parent group node id when this node lives inside a canvas group frame. */@@ -234,6 +238,10 @@ export interface SessionRowVM {cwd?: stringsshHost?: stringsessionId?: string+ /** Creation-time account + what the session was OBSERVED running as — the two halves the+ * account chip resolves (`lib/accountChip`). */+ accountId?: string+ account?: ObservedClaudeAccountusesContext: boolean/** Populated only when the sidebar is grouped by status (rows are flattened across projects):* the project the session belongs to, so the row can show a project monogram and route@@ -307,6 +315,8 @@ function toRow(cwd: n.cwd,sshHost: n.ssh?.host,sessionId: status?.sessionId,+ accountId: n.accountId,+ account: status?.account,usesContext: n.agentId ? hasUsage(n.agentId) : false,// Only populated in status mode (flattened across projects); absent in project mode.projectId: project?.id,diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex f6fdce20b..6dde13824 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -154,7 +154,9 @@ import { useWorktrees } from '../state/worktrees'import { isRemoteSessionNode } from '@shared/worktree'import { useSession, useActiveSessionPresence } from '../session/session'import { isBrowserRuntime } from '../bridge/runtime'-import { accountChipLabel, agentLaunchOverride, COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'+import { agentLaunchOverride, COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'+import { AccountChip, useAccountChip } from '../components/AccountChip'+import { effectiveAccountId } from '../lib/accountChip'import {hasHooks,canRecur,@@ -1084,12 +1086,10 @@ export function TerminalNode({// Scoped to the OWNING project so its `terminal.theme` / `terminal.fontFamily` layer over the// global settings for this node, and for no other project's nodes.const visual = useXtermVisualSettings(owningProjectId())- const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)// Header buttons the user chose to hide (Settings). A selector, so toggling one re-renders every// mounted node right away instead of waiting for a remount. Search, Close and the worktree-move// button are absent from `isHidden`'s inventory and stay put whatever the list says.const hiddenHeaderButtons = useSettings((s) => s.settings.hiddenHeaderButtons)- const accountChip = accountChipLabel(data.accountId, claudeAccounts)const bodyRef = useRef<HTMLDivElement>(null)/** Where a press on the hover guard started, for the click-vs-drag test in `onGuardUp`. */const guardDownAt = useRef<{ x: number; y: number } | null>(null)@@ -1454,6 +1454,22 @@ export function TerminalNode({!remoteSession &&(data.cwd as string | undefined) !== parentWtPathconst status = useAgentStatus((s) => s.byId[id])+ /**+ * Which Claude account this node is ACTUALLY on (D5). `data.accountId` is what nodeterm launched+ * it as and is immutable; `status.account` is what the session's hooks reported — the only+ * identity a plain terminal running `CLAUDE_CONFIG_DIR=~/.claude-2 claude` ever has.+ *+ * The chip and every READER below use the effective id, so a node that was never created AS an+ * account but runs as one reads that account's transcripts. NOT the spawn env: launch identity+ * stays creation-time (`transport.create` keeps passing `data.accountId`).+ */+ const observedAccount = status?.account+ const accountChip = useAccountChip(data.accountId, observedAccount)+ const accountForReads = effectiveAccountId(data.accountId, observedAccount)+ /** Mirror for the session-name poll, whose effect must not restart when a late hook event+ * finally reveals the account (see its comment). */+ const accountForReadsRef = useRef(accountForReads)+ accountForReadsRef.current = accountForReads// Fan-out (subagent/loop card) visibility + tidy — any agent capable of either kind of card.const fanoutCapable = !!agentId && (canSubagent(agentId) || canRecur(agentId))const hideFanout = !!data.hideFanout@@ -1593,8 +1609,11 @@ export function TerminalNode({useEffect(() => {const sid = status?.sessionIdif (claudeTranscript && sid)- window.nodeTerminal.context.ensure(sid, (data.cwd as string) || undefined, data.accountId)- }, [claudeTranscript, status?.sessionId, data.cwd, data.accountId])+ window.nodeTerminal.context.ensure(sid, (data.cwd as string) || undefined, accountForReads)+ // `accountForReads`, not `data.accountId`: the transcript this meter tails lives under the+ // account the session is RUNNING as, which for a plain terminal is only ever the observed one.+ // It can arrive after mount (the first hook event), hence its place in the deps.+ }, [claudeTranscript, status?.sessionId, data.cwd, accountForReads])const updateNodeInternals = useUpdateNodeInternals()const [searchOpen, setSearchOpen] = useState(false)@@ -1697,7 +1716,9 @@ export function TerminalNode({nodeId: id,sessionId: status?.sessionId,cwd: data.cwd as string | undefined,- accountId: data.accountId,+ // A READER: the search hits the transcript index under whichever account the session is+ // actually running as (D5), not the one the node was created with.+ accountId: accountForReads,// The transcript index reads claude's JSONL through the same resolver, so it is gated on the// claude-transcript fact, NOT on the meter's `showUsage` — see lib/transcriptGates.ts.searchTranscript: claudeTranscript,@@ -4430,8 +4451,13 @@ export function TerminalNode({// Gated on canReadTitleNode (TITLE_READ_CAPABLE), NOT on canRenameNode: reading a session's name// and being able to set one are different capabilities, and gemini has only the first. `agentId`// rides along so main picks the right reader: claude's transcript .jsonl vs grok's summary.json vs- // gemini's update_topic tool call. It is resolved at node creation and immutable thereafter —- // same as `data.accountId` beside it — so neither belongs in the dep array.+ // gemini's update_topic tool call. It is resolved at node creation and immutable thereafter, so+ // it does not belong in the dep array.+ //+ // The ACCOUNT does not get that treatment any more: it is the effective one (D5), which for a+ // plain terminal arrives with the first hook event, i.e. AFTER this effect mounted. It rides a+ // ref (`accountForReadsRef`, refreshed every render) rather than the deps so a late observation+ // is picked up by the very next poll instead of tearing down and restarting the timer chain.useEffect(() => {if (!canReadTitleNode || data.titleAuto === false) returnconst sid = status?.sessionId ?? ''@@ -4444,7 +4470,7 @@ export function TerminalNode({let timer: ReturnType<typeof setTimeout> | undefinedconst sync = async () => {if (!titleAutoRef.current || editingTitleRef.current) return- const name = await api.pty.readSessionName(sid, data.accountId, agentId)+ const name = await api.pty.readSessionName(sid, accountForReadsRef.current, agentId)if (cancelled) returnif (name) delayMs = 15000if (@@ -4665,18 +4691,19 @@ export function TerminalNode({plain codex</span>)}- {accountChip && (- <span- className={`node-account-chip${accountFallback ? ' node-account-chip--warning' : ''}`}- title={- accountFallback- ? 'Account folder missing — running on system account'- : accountChip.tooltip- }- >- {accountChip.short}- </span>- )}+ {/* Which Claude account this pane is on — the same component the board card, the card+ modal and the sessions sidebar render (CONTRIBUTING: two views of the same nodes).+ The spawn-time fallback branch is kept: when the account folder was missing the session+ IS on the system account, and the chip must say so rather than name the account we+ failed to launch under. */}+ <AccountChip+ chip={+ accountChip && accountFallback+ ? { ...accountChip, tooltip: 'Account folder missing — running on system account' }+ : accountChip+ }+ warning={accountFallback}+ />{data.ssh ? (<spanclassName="term-ssh-chip"@@ -5077,7 +5104,9 @@ export function TerminalNode({nodeId={id}sessionId={status?.sessionId}cwd={data.cwd as string | undefined}- accountId={data.accountId}+ // A READER (the ⌘M transcript view): the account the session RUNS as (D5), so a+ // plain terminal on ~/.claude-2 reads ITS transcript instead of an empty system one.+ accountId={accountForReads}/></Suspense>) : (diff --git a/src/renderer/state/agentStatus.persist.test.ts b/src/renderer/state/agentStatus.persist.test.tsindex c9da6f4c2..2cb65217d 100644--- a/src/renderer/state/agentStatus.persist.test.ts+++ b/src/renderer/state/agentStatus.persist.test.ts@@ -390,3 +390,73 @@ describe('loop persistence (cron/schedule survive an app restart)', () => {expect(useAgentStatus.getState().byId['n3'].loop).toBeUndefined()})})++describe('observed Claude account persistence (a plain terminal knows it nowhere else)', () => {+ const claude2 = { configDir: '/home/me/.claude-2', accountId: null, known: false }++ it('persists the observed account and restores it on load', async () => {+ const store = memStorage()+ vi.stubGlobal('localStorage', store)+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setAccount('n1', claude2)+ expect(JSON.parse(store.getItem('nodeterm.agentStatus')!).n1.account).toEqual(claude2)++ // …and it comes back on the next launch. Without this the chip on a hand-launched+ // `CLAUDE_CONFIG_DIR=~/.claude-2 claude` pane would vanish on every restart, while the tmux+ // session it describes carried straight on.+ vi.resetModules()+ vi.stubGlobal(+ 'localStorage',+ memStorage({ 'nodeterm.agentStatus': store.getItem('nodeterm.agentStatus')! })+ )+ const reloaded = await import('./agentStatus')+ expect(reloaded.useAgentStatus.getState().byId['n1']?.account).toEqual(claude2)+ })++ it('is the ONLY durable field an account-only entry needs to survive', async () => {+ // `save` skips entries carrying nothing durable — an observed account on an otherwise blank+ // node (no unread, no session id, no agent) has to be enough to keep the entry.+ const store = memStorage()+ vi.stubGlobal('localStorage', store)+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setAccount('n2', claude2)+ expect(JSON.parse(store.getItem('nodeterm.agentStatus')!).n2).toBeTruthy()+ })++ it('ignores a corrupt account entry on load rather than chipping a node wrongly', async () => {+ vi.stubGlobal(+ 'localStorage',+ memStorage({+ 'nodeterm.agentStatus': JSON.stringify({+ n3: { unread: false, account: { accountId: 'a1' } }, // no configDir / known+ n4: { unread: false, account: 'nonsense' }+ })+ })+ )+ const { useAgentStatus } = await import('./agentStatus')+ expect(useAgentStatus.getState().byId['n3']?.account).toBeUndefined()+ expect(useAgentStatus.getState().byId['n4']?.account).toBeUndefined()+ })++ it('a new session in the same pane overwrites the account; a turn boundary does not', async () => {+ vi.stubGlobal('localStorage', memStorage())+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setAccount('n5', claude2)+ // Turns come and go; identity does not (same rule as `agentId`).+ useAgentStatus.getState().setState('n5', 'working', 'claude')+ useAgentStatus.getState().setState('n5', 'done', 'claude')+ expect(useAgentStatus.getState().byId['n5'].account).toEqual(claude2)+ const system = { configDir: '/home/me/.claude', accountId: null, known: true }+ useAgentStatus.getState().setAccount('n5', system)+ expect(useAgentStatus.getState().byId['n5'].account).toEqual(system)+ })++ it('re-asserting the same account changes nothing (no re-render per hook event)', async () => {+ vi.stubGlobal('localStorage', memStorage())+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setAccount('n6', claude2)+ const before = useAgentStatus.getState().byId+ useAgentStatus.getState().setAccount('n6', { ...claude2 })+ expect(useAgentStatus.getState().byId).toBe(before)+ })+})diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.tsindex 779e51d62..cee950300 100644--- a/src/renderer/state/agentStatus.ts+++ b/src/renderer/state/agentStatus.ts@@ -2,17 +2,18 @@ import { create, type StoreApi, type UseBoundStore } from 'zustand'import { WORKING_STALE_MS } from '@shared/agents/stale'import type { AgentId } from '@shared/agents/config'import type { AgentState } from '@shared/agents/normalize'-import type { NodeTerminalApi } from '@shared/types'+import type { NodeTerminalApi, ObservedClaudeAccount } from '@shared/types'/*** Transient per-node status for agent (e.g. Claude Code) sessions, driven by the agent's hooks.- * `unread`, `session`, `sessionId`, `agentId`, `loop` and `hibernated` are persisted to+ * `unread`, `session`, `sessionId`, `agentId`, `account`, `loop` and `hibernated` are persisted to* localStorage so they survive a reload/restart; the live `state` (working/waiting/…) is not* (it'd be stale on relaunch), and neither are its two clocks (`stateAt`, `lastEventAt`).* `agentId` is durable because a PLAIN terminal's agent identity exists nowhere else: an* explicit agent node re-derives it from `data.agentId`, but a hand-launched `claude` in a* plain terminal is only known here, and its context links must keep classifying across- * restarts (tmux keeps the session — and the agent — alive through them).+ * restarts (tmux keeps the session — and the agent — alive through them). `account` is durable+ * for exactly that reason too — see its field comment.** ONE STORE PER CORE (stage 4): `createAgentStatusSession(persistKey?)` builds an isolated* instance — node ids are per-core, so status tables from two cores must never mix. The module@@ -105,6 +106,23 @@ export interface AgentNodeStatus {paused?: boolean/** Which agent this node is running (claude/codex/gemini/…), when known. */agentId?: AgentId+ /**+ * Which Claude account this node's session was OBSERVED running under, off any hook event that+ * carried one (`NormalizedAgentEvent.account`, derived from the hook's `transcript_path`).+ *+ * PERSISTED beside `agentId`, and durable for the same reason: a hand-launched+ * `CLAUDE_CONFIG_DIR=~/.claude-2 claude` in a PLAIN terminal has its identity nowhere else —+ * the node carries no `data.accountId`, and tmux keeps the session alive across an app restart+ * that will see no further event until the user next talks to it. Without this the chip and the+ * account-scoped transcript readers would silently fall back to the system account after every+ * relaunch.+ *+ * Deliberately NOT cleared at a session end (same rule as `agentId`): identity survives turn+ * boundaries, and a new session in the same pane overwrites it with its own observation.+ *+ * A LABEL, never a gate — see `ObservedClaudeAccount` in shared/types.+ */+ account?: ObservedClaudeAccount/** A turn finished / needs attention while the user wasn't looking. */unread: boolean/** Claude's own session name/title (from the terminal title), shown beside the title. */@@ -167,6 +185,9 @@ export interface AgentStatusStore {sweepStaleWorking(staleMs?: number): voidsetSession(id: string, session: string): voidsetSessionId(id: string, sessionId: string): void+ /** Record the Claude account a hook event says this node is running under. Persisted; see+ * `account`. Idempotent — a re-assert of the same account writes nothing. */+ setAccount(id: string, account: ObservedClaudeAccount): void/** Mark the node's agent CLI as exited-for-RAM (true) or live again (false). Persisted.* Waking also restarts the idle clock (`lastEventAt`), so a quiet resumed session is not* re-hibernated on the next sweep. */@@ -273,6 +294,20 @@ export function createAgentStatusSession(const out: Record<string, AgentNodeStatus> = {}for (const [id, v] of Object.entries(data)) {out[id] = { unread: !!v.unread, session: v.session, sessionId: v.sessionId, agentId: v.agentId }+ // Minimal shape check, like `loop` below: this file is on disk and hand-editable, and a+ // half-written entry must not put a chip on a node claiming an identity it never had.+ if (+ v.account &&+ typeof v.account === 'object' &&+ typeof v.account.configDir === 'string' &&+ typeof v.account.known === 'boolean'+ ) {+ out[id].account = {+ configDir: v.account.configDir,+ accountId: typeof v.account.accountId === 'string' ? v.account.accountId : null,+ known: v.account.known+ }+ }// Only when set: an absent flag stays absent, so an entry saved before this field// existed hydrates byte-identically (and `hibernated: false` never grows in the file).if (v.hibernated) out[id].hibernated = true@@ -315,12 +350,25 @@ export function createAgentStatusSession(try {const out: Record<string, Partial<AgentNodeStatus>> = {}for (const [id, v] of Object.entries(byId)) {- if (v.unread || v.session || v.sessionId || v.loop || v.agentId || v.hibernated || v.paused) {+ if (+ v.unread ||+ v.session ||+ v.sessionId ||+ v.loop ||+ v.agentId ||+ v.account ||+ v.hibernated ||+ v.paused+ ) {out[id] = {unread: v.unread,session: v.session,sessionId: v.sessionId,agentId: v.agentId,+ // Durable beside `agentId`, and for the same reason (see the field comment): a plain+ // terminal's observed account exists nowhere else, and the tmux session that knows it+ // outlives the app.+ account: v.account,loop: v.loop,hibernated: v.hibernated,// Never written without a flag it belongs to (see `hibernatedPane`'s load comment).@@ -487,6 +535,26 @@ export function createAgentStatusSession(return { byId }}),+ setAccount: (id, account) =>+ set((s) => {+ const prev = s.byId[id] ?? EMPTY+ const cur = prev.account+ // Same-account events are the common case (every hook POST of every turn carries one), so+ // bail before allocating: a new object here would re-render every consumer of this node's+ // status on each tool event, for a value that did not change.+ if (+ cur &&+ cur.configDir === account.configDir &&+ cur.accountId === account.accountId &&+ cur.known === account.known+ ) {+ return s+ }+ const byId = { ...s.byId, [id]: { ...prev, account } }+ save(byId)+ return { byId }+ }),+setHibernated: (id, on) =>set((s) => {const prev = s.byId[id] ?? EMPTYdiff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex a7b1e8eff..1fe94e62a 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -1367,6 +1367,30 @@ body,background: rgba(255, 159, 10, 0.16);}+/* Observed-account variants. The base chip is the managed-account look; these keep the three+ other cases distinguishable at a glance, before anyone hovers for the tooltip. */++/* The system account (~/.claude). Shown only when a second identity is in play, so it must read+ as "the ordinary one" next to the account that is the exception. */+.node-account-chip--system {+ background: rgba(var(--tint-rgb), 0.08);+}++/* A config dir the user linked: theirs, not one nodeterm minted — a hairline instead of a fill. */+.node-account-chip--linked {+ background: transparent;+ box-shadow: inset 0 0 0 1px rgba(10, 132, 255, 0.35);+}++/* A config dir nodeterm has no record of. Dashed = provisional: the tooltip says to link it in+ Settings → Accounts. The padding drops by the border's width so the chip keeps the height of+ the filled chips beside it. */+.node-account-chip--unlinked {+ background: transparent;+ border: 1px dashed var(--border);+ padding: 0 7px;+}+/* Claude Code status: RUNNING badge while working, unread dot when finished. */.term-node__status {display: inline-flex;