Skip to content

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

fix(accounts): re-resolve an unlinked observation against the account list

freshjuicez544e39d9f714
diff --git a/src/renderer/components/AccountChip.test.tsx b/src/renderer/components/AccountChip.test.tsx
index c7f114c6f..181eb5130 100644
--- a/src/renderer/components/AccountChip.test.tsx
+++ b/src/renderer/components/AccountChip.test.tsx
@@ -89,14 +89,48 @@ describe('AccountChip (D6 visibility through the live stores)', () => {
})
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')
+ // A dir NO account claims — `CLAUDE_2` is linked by the `a2` fixture below.
+ const stranger: ObservedClaudeAccount = {
+ configDir: '/home/me/.claude-7',
+ accountId: null,
+ known: false
+ }
+ useAgentStatus.setState({ byId: { n2: { unread: false, account: stranger } } })
+ const { host, root } = render({ observed: stranger })
+ expect(chipEl(host)?.textContent).toBe('.claude-7')
expect(chipEl(host)?.className).toContain('node-account-chip--unlinked')
expect(chipEl(host)?.getAttribute('title')).toContain('Settings → Accounts')
root.unmount()
})
+ it('flips an unlinked chip to the account the moment the dir is LINKED', () => {
+ // The smoke-test regression: the store's observation was classified before the account existed
+ // (`known:false`), and a quiet pane may not post another hook for hours. Linking is a settings
+ // edit, so the repaint has to come from here — no new event is delivered in this test.
+ const fresh: ObservedClaudeAccount = {
+ configDir: '/home/me/.claude-8',
+ accountId: null,
+ known: false
+ }
+ useAgentStatus.setState({ byId: { n8: { unread: false, account: fresh } } })
+ const { host, root } = render({ observed: fresh })
+ expect(chipEl(host)?.className).toContain('node-account-chip--unlinked')
+ act(() => {
+ useSettings.setState({
+ settings: {
+ ...DEFAULT_SETTINGS,
+ claudeAccounts: [
+ ...accounts,
+ { id: 'a3', label: 'linked-now', configDir: '/home/me/.claude-8/', createdAt: 0 }
+ ]
+ }
+ })
+ })
+ expect(chipEl(host)?.textContent).toBe('linked-now')
+ expect(chipEl(host)?.className).toContain('node-account-chip--linked')
+ root.unmount()
+ })
+
it('chips a managed node whatever else is running', () => {
const { host, root } = render({ accountId: 'a1' })
expect(chipEl(host)?.textContent).toBe('work')
diff --git a/src/renderer/components/AccountChip.tsx b/src/renderer/components/AccountChip.tsx
index 49b209074..57f041408 100644
--- a/src/renderer/components/AccountChip.tsx
+++ b/src/renderer/components/AccountChip.tsx
@@ -53,8 +53,10 @@ export function useAccountChip(
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))
+ // event of every node. `hasMultipleAccountKeys` early-exits at the second key. `accounts` rides
+ // along so a dir that was linked since its observation counts as ONE identity with the account
+ // it now belongs to, not two.
+ const multiple = useAgentStatus((s) => hasMultipleAccountKeys(s.byId, dataAccountId, accounts))
// 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
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index 4b82b26f9..9fa6f39e6 100644
--- a/src/renderer/components/kanban/ModalTerminal.tsx
+++ b/src/renderer/components/kanban/ModalTerminal.tsx
@@ -105,6 +105,8 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Moda
// (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)
+ // …resolved against the live account list, so linking the dir repoints the reader at once.
+ const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)
// 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`
@@ -133,7 +135,7 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Moda
nodeId,
sessionId: agentSessionId,
cwd: spawn.cwd,
- accountId: effectiveAccountId(spawn.accountId, observedAccount),
+ accountId: effectiveAccountId(spawn.accountId, observedAccount, claudeAccounts),
// 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/lib/accountChip.test.ts b/src/renderer/lib/accountChip.test.ts
index be2aa6720..e9b6d2d06 100644
--- a/src/renderer/lib/accountChip.test.ts
+++ b/src/renderer/lib/accountChip.test.ts
@@ -8,6 +8,8 @@ import {
effectiveAccountId,
hasMultipleAccountKeys,
SYSTEM_ACCOUNT_KEY,
+ configDirsMatch,
+ resolveObserved,
unlinkedConfigDirs
} from './accountChip'
@@ -174,13 +176,25 @@ describe('accountChipFor (D6 visibility, D7 unlinked naming)', () => {
})
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',
+ // A dir NO account claims. (`unlinked` above is `.claude-2`, which `accounts` here has since
+ // linked as `a2` — that case is the "linking flows through every reader" block below.)
+ const stranger = observed({ configDir: '/home/me/.claude-7', known: false })
+ expect(accountChipFor({ observed: stranger, accounts, multiple: false })).toEqual({
+ short: '.claude-7',
+ tooltip: 'Unlinked Claude config dir /home/me/.claude-7 — link it in Settings → Accounts',
kind: 'unlinked'
})
})
+ it('follows a dir that has since been LINKED to its account, with no new event', () => {
+ // The smoke-test regression: the store still holds `{known:false}` from before the link.
+ expect(accountChipFor({ observed: unlinked, accounts, multiple: false })).toEqual({
+ short: 'personal',
+ tooltip: 'personal',
+ kind: 'linked'
+ })
+ })
+
it('shows nothing for a node whose account is unknown', () => {
expect(accountChipFor({ accounts, multiple: true })).toBeNull()
})
@@ -214,3 +228,102 @@ describe('unlinkedConfigDirs (Settings → Accounts “Detected config dirs”)'
])
})
})
+
+// ── Follow-up 1: an observation classified BEFORE the user linked its dir ──────────────────────
+// The hook server stamps `known:false` at POST time and a quiet pane may not post again for hours,
+// so linking has to repaint from the renderer side or the chip lies until the next turn.
+describe('resolveObserved (a dir linked since the observation)', () => {
+ const linkedAcct = acct({ id: 'lnk', label: 'second', email: undefined, configDir: '/home/me/.claude-2' })
+
+ it('upgrades an unknown dir to the account that now owns it', () => {
+ expect(resolveObserved(unlinked, [linkedAcct])).toEqual({
+ configDir: '/home/me/.claude-2',
+ accountId: 'lnk',
+ known: true
+ })
+ })
+
+ it('leaves an unknown dir alone when nothing matches', () => {
+ expect(resolveObserved(unlinked, [acct({ configDir: '/home/me/.claude-9' })])).toBe(unlinked)
+ expect(resolveObserved(unlinked, [acct()])).toBe(unlinked) // a MANAGED account has no configDir
+ })
+
+ it('never downgrades a known observation', () => {
+ // Core classified these against the managed layout; settings cannot outrank that.
+ expect(resolveObserved(system, [linkedAcct])).toBe(system)
+ expect(resolveObserved(managed, [linkedAcct])).toBe(managed)
+ })
+})
+
+describe('configDirsMatch (one comparison, both sides normalized)', () => {
+ it('ignores a trailing separator', () => {
+ expect(configDirsMatch('/home/me/.claude-2/', '/home/me/.claude-2')).toBe(true)
+ })
+
+ it('is case- and separator-insensitive for Windows-shaped paths only', () => {
+ expect(configDirsMatch('C:\\Users\\Me\\.claude-2', 'c:/users/me/.claude-2')).toBe(true)
+ // POSIX: case and backslash are both significant filename text, so these are DIFFERENT dirs.
+ expect(configDirsMatch('/home/me/.Claude-2', '/home/me/.claude-2')).toBe(false)
+ })
+
+ it('never matches on an absent dir (every managed account has none)', () => {
+ expect(configDirsMatch(undefined, undefined)).toBe(false)
+ expect(configDirsMatch('', '/home/me/.claude-2')).toBe(false)
+ })
+})
+
+describe('linking flows through every reader of the observation', () => {
+ const linkedAcct = acct({ id: 'lnk', label: 'second', email: undefined, configDir: '/home/me/.claude-2/' })
+
+ it('gives the readers the account id (no new hook event needed)', () => {
+ expect(effectiveAccountId(undefined, unlinked)).toBeUndefined()
+ expect(effectiveAccountId(undefined, unlinked, [linkedAcct])).toBe('lnk')
+ })
+
+ it('keys the pane by account instead of by path', () => {
+ expect(accountKey(undefined, unlinked)).toBe('ext:/home/me/.claude-2')
+ expect(accountKey(undefined, unlinked, [linkedAcct])).toBe('lnk')
+ })
+
+ it('stops counting the linked pane as a second identity next to its own account', () => {
+ // A node created under the account and a pane observed on its dir are ONE identity.
+ expect(hasMultipleAccountKeys({ n1: { account: unlinked } }, 'lnk')).toBe(true)
+ expect(hasMultipleAccountKeys({ n1: { account: unlinked } }, 'lnk', [linkedAcct])).toBe(false)
+ })
+
+ it('flips the chip to the account\u2019s own label and kind', () => {
+ const chip = accountChipFor({ observed: unlinked, accounts: [linkedAcct], multiple: false })
+ expect(chip).toEqual({ short: 'second', tooltip: 'second', kind: 'linked' })
+ })
+
+ it('leaves a dir nobody linked dashed and unlinked', () => {
+ const chip = accountChipFor({
+ observed: unlinked,
+ accounts: [acct({ id: 'other', configDir: '/home/me/.claude-9' })],
+ multiple: false
+ })
+ expect(chip?.kind).toBe('unlinked')
+ expect(chip?.short).toBe('.claude-2')
+ })
+
+ it('drops the dir from the detected list the moment it is linked', () => {
+ const byId = { n1: { account: unlinked } }
+ expect(unlinkedConfigDirs(byId, ['/home/me/.claude-2/'])).toEqual([]) // trailing slash
+ expect(unlinkedConfigDirs(byId, ['/home/me/.claude-9'])).toEqual(['/home/me/.claude-2'])
+ })
+
+ it('excludes a Windows-shaped linked dir whatever its case', () => {
+ const byId = { n1: { account: observed({ configDir: 'C:\\Users\\Me\\.claude-2', known: false }) } }
+ expect(unlinkedConfigDirs(byId, ['c:/users/me/.claude-2'])).toEqual([])
+ })
+})
+
+describe('the system chip has nothing to truncate', () => {
+ it('says "System" rather than the 10-char cut of the generic display', () => {
+ // "System account" through the chip cap reads "System acc…", an ellipsis promising a longer
+ // name that does not exist.
+ const chip = accountChipFor({ observed: system, accounts: [], multiple: true })
+ expect(chip?.short).toBe('System')
+ expect(chip?.tooltip).toContain('System account')
+ })
+})
diff --git a/src/renderer/lib/accountChip.ts b/src/renderer/lib/accountChip.ts
index 56f411756..228e0bac4 100644
--- a/src/renderer/lib/accountChip.ts
+++ b/src/renderer/lib/accountChip.ts
@@ -23,6 +23,74 @@ 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
+/** `systemAccountDisplay`'s generic fallback, mirrored so the chip can recognise "there is no
+ * identity here to shorten" (see `accountChipFor`). */
+const GENERIC_SYSTEM_DISPLAY = 'System account'
+
+/**
+ * Is this path string Windows-shaped? The owning filesystem is NOT known here — a config dir may
+ * come from this machine, an SSH host, or Windows — so the shape of the string decides, rather
+ * than treating `/` and `\` as interchangeable: on POSIX a backslash is legal filename text
+ * (CONTRIBUTING). A drive letter, a UNC prefix, or backslashes with no forward slash is Windows.
+ */
+function isWindowsShapedPath(dir: string): boolean {
+ return (
+ /^[a-zA-Z]:[\\/]/.test(dir) ||
+ dir.startsWith('\\\\') ||
+ (dir.includes('\\') && !dir.includes('/'))
+ )
+}
+
+/**
+ * The comparable form of a config dir. ONE function, used on BOTH sides of every config-dir
+ * comparison in this module (CONTRIBUTING: "normalize BOTH sides of a path comparison, through one
+ * function" — the half-normalized version of this is issue #558).
+ *
+ * Trims, drops trailing separators, and — only for a Windows-shaped path — folds separators to `\`
+ * and lowercases, because Windows paths are case-insensitive and `C:/x` and `C:\x` name the same
+ * dir. A POSIX path is left case- and backslash-sensitive, because there both are significant.
+ *
+ * This is a LABEL comparison (which account name to show, whose transcripts to read); the jail and
+ * every real permission check live in core and are unaffected by it.
+ */
+export function normalizeConfigDirForCompare(dir: string | undefined | null): string {
+ const trimmed = (dir ?? '').trim()
+ if (!trimmed) return ''
+ const windows = isWindowsShapedPath(trimmed)
+ let out = windows ? trimmed.replace(/\//g, '\\') : trimmed
+ const sep = windows ? '\\' : '/'
+ while (out.length > 1 && out.endsWith(sep)) out = out.slice(0, -1)
+ return windows ? out.toLowerCase() : out
+}
+
+/** Do these two config dirs name the same directory? Empty never matches — an absent `configDir`
+ * (every managed account has none) must not collide with an unlinked observation. */
+export function configDirsMatch(a: string | undefined | null, b: string | undefined | null): boolean {
+ const left = normalizeConfigDirForCompare(a)
+ return !!left && left === normalizeConfigDirForCompare(b)
+}
+
+/**
+ * Re-resolve an observation against the CURRENT account list.
+ *
+ * The hook server classifies `transcript_path` at POST time, so an observation captured before the
+ * user linked its dir is frozen as `{ known: false }` — and nothing else would ever revisit it: a
+ * quiet pane may not post another hook for hours. Linking is a settings edit, so the renderer is
+ * the only place that can notice, and this is where it does. Everything else in this module goes
+ * through it, so the chip, the keys and the readers cannot disagree about the same dir.
+ *
+ * Only ever UPGRADES an unknown dir to a linked account (never the reverse): a `known` observation
+ * was classified by core against the managed layout and stays authoritative.
+ */
+export function resolveObserved(
+ observed: ObservedClaudeAccount | undefined,
+ accounts: readonly ClaudeAccount[] = []
+): ObservedClaudeAccount | undefined {
+ if (!observed || observed.known || !observed.configDir) return observed
+ const match = accounts.find((a) => configDirsMatch(a.configDir, observed.configDir))
+ return match ? { ...observed, accountId: match.id, known: true } : observed
+}
+
/**
* 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.
@@ -34,10 +102,14 @@ const MAX_CHIP_LABEL = 10
*/
export function effectiveAccountId(
dataAccountId?: string,
- observed?: ObservedClaudeAccount
+ observed?: ObservedClaudeAccount,
+ /** The current account list, so a dir linked SINCE the observation resolves to its account
+ * without waiting for the pane's next hook event (see `resolveObserved`). */
+ accounts: readonly ClaudeAccount[] = []
): string | undefined {
if (dataAccountId) return dataAccountId
- if (observed?.known && observed.accountId) return observed.accountId
+ const known = resolveObserved(observed, accounts)
+ if (known?.known && known.accountId) return known.accountId
return undefined
}
@@ -54,24 +126,29 @@ export function effectiveAccountId(
*/
export function accountKey(
dataAccountId?: string,
- observed?: ObservedClaudeAccount
+ observed?: ObservedClaudeAccount,
+ /** See `resolveObserved`: a dir linked since the observation keys as its ACCOUNT, so the linked
+ * pane and a node created under that account count as one identity, not two. */
+ accounts: readonly ClaudeAccount[] = []
): string | null {
if (dataAccountId) return dataAccountId
- if (!observed) return null
- if (observed.known) return observed.accountId ?? SYSTEM_ACCOUNT_KEY
+ const resolved = resolveObserved(observed, accounts)
+ if (!resolved) return null
+ if (resolved.known) return resolved.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
+ return resolved.configDir ? `ext:${resolved.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 }>
+ entries: Iterable<{ dataAccountId?: string; observed?: ObservedClaudeAccount }>,
+ accounts: readonly ClaudeAccount[] = []
): Set<string> {
const keys = new Set<string>()
for (const e of entries) {
- const key = accountKey(e.dataAccountId, e.observed)
+ const key = accountKey(e.dataAccountId, e.observed, accounts)
if (key) keys.add(key)
}
return keys
@@ -91,13 +168,14 @@ export function distinctAccountKeys(
*/
export function hasMultipleAccountKeys(
byId: Record<string, { account?: ObservedClaudeAccount }>,
- ownAccountId?: string
+ ownAccountId?: string,
+ accounts: readonly ClaudeAccount[] = []
): boolean {
const keys = new Set<string>()
- const own = accountKey(ownAccountId, undefined)
+ const own = accountKey(ownAccountId, undefined, accounts)
if (own) keys.add(own)
for (const entry of Object.values(byId)) {
- const key = accountKey(undefined, entry.account)
+ const key = accountKey(undefined, entry.account, accounts)
if (key) keys.add(key)
if (keys.size >= 2) return true
}
@@ -110,18 +188,23 @@ export function hasMultipleAccountKeys(
*
* 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.
+ * must not make us stat anything). `linkedDirs` is compared through `configDirsMatch` — the SAME
+ * comparison `resolveObserved` uses, so a dir can never be both "already linked" (hidden from the
+ * chip) and "detected" (offered for linking).
*/
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 already = linkedDirs
+ .map((d) => normalizeConfigDirForCompare(d))
+ .filter((d) => d.length > 0)
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)
+ if (!a || a.known || !a.configDir) continue
+ if (already.includes(normalizeConfigDirForCompare(a.configDir))) continue
+ dirs.add(a.configDir)
}
// Sorted so the list does not reshuffle itself as unrelated nodes come and go.
return [...dirs].sort()
@@ -156,7 +239,7 @@ function shortAccountLabel(label: string): string {
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 windowsShaped = isWindowsShapedPath(dir)
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
@@ -189,13 +272,18 @@ export function accountChipFor({
/** D6: are ≥ 2 distinct account keys in play on this core? (`hasMultipleAccountKeys`) */
multiple?: boolean
}): AccountChipInfo | null {
- const key = accountKey(dataAccountId, observed)
+ // Resolved against the CURRENT list: linking a detected dir must repaint every chip on it
+ // immediately, not at that pane's next hook event (see `resolveObserved`).
+ const key = accountKey(dataAccountId, observed, accounts)
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),
+ // With neither a custom label nor a detected email the display is the generic "System
+ // account", which the 10-char cap turns into "System acc…" — an ellipsis that promises a
+ // longer name there isn't one of. Nothing to shorten: say "System".
+ short: display === GENERIC_SYSTEM_DISPLAY ? 'System' : shortAccountLabel(display),
tooltip: `${display} — system Claude account (~/.claude)`,
kind: 'system'
}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 6dde13824..83d8cb4f5 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -1086,6 +1086,9 @@ 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())
+ // The account list, for the chip and for the READERS below: a config dir the user links while
+ // this pane sits quiet must resolve to its new account immediately, not at the next hook event.
+ 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.
@@ -1465,7 +1468,7 @@ export function TerminalNode({
*/
const observedAccount = status?.account
const accountChip = useAccountChip(data.accountId, observedAccount)
- const accountForReads = effectiveAccountId(data.accountId, observedAccount)
+ const accountForReads = effectiveAccountId(data.accountId, observedAccount, claudeAccounts)
/** 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)