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): observe each session's Claude account from transcript_path; linked config dirs (core + shells)
freshjuicezfc1d9ffa696f
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.tsindex d7476686a..672124497 100644--- a/src/core/agent-status-mirror.test.ts+++ b/src/core/agent-status-mirror.test.ts@@ -2266,3 +2266,80 @@ describe('hibernated flag (Eco × phone — SLEEPING on external readers)', () =expect(_snapshot().n1.hibernated).toBe(true)})})++// ---- The observed Claude account (design D3/D4) ---------------------------------------------+//+// For a HAND-LAUNCHED claude (a plain terminal running `CLAUDE_CONFIG_DIR=~/.claude-2 claude`)+// the node's `data.accountId` is undefined forever, so this label is the only record of which+// identity the pane is on. It therefore has to behave like `agentId`: captured off any event,+// never cleared by one that lacks it, written to the file, and back after a restart.+describe('MirrorEntry.account (observed Claude account)', () => {+ const account = { configDir: '/home/u/.claude-2', accountId: 'linked-1', known: true }++ it('is captured off ANY event kind, like agentId/sessionId', () => {+ for (const kind of ['state', 'session', 'subagent-start', 'recurring'] as const) {+ const e = reduceEntry(undefined, ev({ kind, state: 'working', account }), 1000)+ expect(e.account, kind).toEqual(account)+ }+ })++ it('survives events that carry no account, and is replaced by one that carries another', () => {+ // A codex/gemini event, or a claude payload with no transcript_path, is not evidence that this+ // node stopped being on the account it was last seen on.+ const a = reduceEntry(undefined, ev({ kind: 'state', state: 'working', account }), 1000)+ const b = reduceEntry(a, ev({ kind: 'state', state: 'done' }), 2000)+ expect(b.account).toEqual(account)+ const other = { configDir: '/home/u/.claude', accountId: null, known: true }+ const c = reduceEntry(b, ev({ kind: 'state', state: 'working', account: other }), 3000)+ expect(c.account).toEqual(other)+ })++ it('is written to the mirror file, and absent for a node that never posted one', () => {+ const doc = buildFile(+ {+ n1: { state: 'working', agentId: 'claude', sessionId: 's1', account, updatedAt: 10 },+ n2: { state: 'working', agentId: 'codex', sessionId: 's2', updatedAt: 10 }+ },+ 10+ )+ expect(doc.nodes.n1.account).toEqual(account)+ // Old file shape preserved byte-for-byte where there is nothing to say.+ expect('account' in JSON.parse(JSON.stringify(doc)).nodes.n2).toBe(false)+ })++ it('comes back after a restart, and a malformed one does not', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-status-account-'))+ try {+ _resetForTest()+ const file = path.join(dir, 'agent-status.json')+ const now = Date.now()+ fs.writeFileSync(+ file,+ JSON.stringify({+ v: 1,+ updatedAt: now,+ nodes: {+ n1: { state: 'done', agentId: 'claude', account, updatedAt: now },+ // Hand-edited / written by another build: a chip rendered off `{}` would read as "no+ // account observed" while occupying the slot of one that was.+ n2: { state: 'done', agentId: 'claude', account: {}, updatedAt: now },+ n3: { state: 'done', agentId: 'claude', account: 'nope', updatedAt: now }+ }+ })+ )+ initAgentStatusMirror(file)+ expect(_snapshot().n1?.account).toEqual(account)+ expect(_snapshot().n2?.account).toBeUndefined()+ expect(_snapshot().n3?.account).toBeUndefined()+ } finally {+ _resetForTest()+ fs.rmSync(dir, { recursive: true, force: true })+ }+ })++ it('expires with its entry, like every other field on it', () => {+ const now = EXPIRE_MS + 100_000+ const doc = buildFile({ stale: { state: 'working', account, updatedAt: now - EXPIRE_MS - 1 } }, now)+ expect(Object.keys(doc.nodes)).toEqual([])+ })+})diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.tsindex b0028a32f..d5ae3edbe 100644--- a/src/core/agent-status-mirror.ts+++ b/src/core/agent-status-mirror.ts@@ -4,6 +4,7 @@ import { writeFileAtomic } from './fs-atomic'import { platform } from './platform'import type { AgentId } from '@shared/agents/config'import type { AgentState, NormalizedAgentEvent } from '@shared/agents/normalize'+import type { ObservedClaudeAccount } from '@shared/types'import { WORKING_STALE_MS, isStaleWorking } from '@shared/agents/stale'/**@@ -41,6 +42,18 @@ export interface MirrorEntry {state?: AgentStateagentId?: AgentIdsessionId?: string+ /**+ * Which Claude account this node was OBSERVED running under (`NormalizedAgentEvent.account`,+ * derived by the hook server from the payload's `transcript_path` — see `ObservedClaudeAccount`).+ *+ * Captured off ANY event, exactly like `agentId`/`sessionId`, and for a sharper reason than+ * either: for a hand-launched `claude` in a plain terminal the node's `data.accountId` is+ * undefined forever, so this label is the ONLY record of which identity the pane is on. It rides+ * the mirror file so a reader with no canvas (the phone) can render the same account chip.+ *+ * A LABEL, like `stateVerified` is not: nothing may gate on it.+ */+ account?: ObservedClaudeAccount/** The agent's own session name (the `/rename` name, read from its transcript) — published by* the session-name sweep so a reader with no canvas (the phone) sees the CURRENT name, not* whatever the node title was when it was last open. Absent until resolved. */@@ -166,6 +179,9 @@ export interface MirrorFile {state?: AgentStateagentId?: AgentIdsessionId?: string+ /** Observed Claude account (see MirrorEntry.account). Additive — absent on old files and+ * on every node that has never posted a claude hook payload. */+ account?: ObservedClaudeAccount/** The agent's own session name (see MirrorEntry.name). Absent until resolved. */name?: string/** Eco hibernation (see MirrorEntry.hibernated). Present = true; absent on old files. */@@ -413,6 +429,12 @@ export function reduceEntry(// agentId threading). agentId is always present on a NormalizedAgentEvent.if (ev.agentId) next.agentId = ev.agentIdif (ev.sessionId) next.sessionId = ev.sessionId+ // The observed Claude account is identity too, and follows the same rule as `agentId`: written+ // by any event that carries one, never cleared by one that does not. Only claude events carry it+ // (hook-server), and a claude session's config dir is fixed for the life of the process — an+ // event without the label is a codex/gemini event or a payload with no transcript_path, neither+ // of which is evidence that this node stopped being on the account it was last seen on.+ if (ev.account) next.account = ev.accountif (ev.kind === 'state' && ev.state) {// An `idle` done (Claude went quiet at its prompt) is a RESCUE, not a turn end: it may only@@ -519,6 +541,9 @@ export function buildFile(state: e.state,agentId: e.agentId,sessionId: e.sessionId,+ // Spread-when-present, like `name`/`hibernated`: a node that never posted a claude payload+ // keeps the byte-for-byte file shape it had before this field existed.+ ...(e.account ? { account: e.account } : {}),...(e.name ? { name: e.name } : {}),...(e.hibernated ? { hibernated: true as const } : {}),updatedAt: e.updatedAt@@ -1114,6 +1139,18 @@ export function onMirrorFlush(cb: (doc: MirrorFile) => void): () => void {* behavior. Stale entries are dropped with the SAME expiry sweep `buildFile`/`flush` apply, so a* "working" from a long-dead session is never resurrected.*/+/** Minimal shape check for a restored `account` block (see the call site's comment). */+function isObservedAccount(a: unknown): a is ObservedClaudeAccount {+ if (!a || typeof a !== 'object') return false+ const o = a as Record<string, unknown>+ return (+ typeof o.configDir === 'string' &&+ !!o.configDir &&+ (o.accountId === null || typeof o.accountId === 'string') &&+ typeof o.known === 'boolean'+ )+}+function loadPersisted(file: string): void {// Only seed empty memory — never clobber a live session (init runs once at boot, but guard so a// stray re-init can't wipe in-flight state).@@ -1141,6 +1178,11 @@ function loadPersisted(file: string): void {state: e.state,agentId: e.agentId,sessionId: e.sessionId,+ // Identity survives the restart like agentId/sessionId does — for a hand-launched+ // claude it is the only record there is. SHAPE-CHECKED rather than trusted: this file+ // can be hand-edited or written by another build, and a chip rendered off `{}` would+ // read as "no account observed" while occupying the slot of one that was.+ ...(isObservedAccount(e.account) ? { account: e.account } : {}),...(e.name ? { name: e.name } : {}),...(e.hibernated === true ? { hibernated: true as const } : {}),updatedAt,diff --git a/src/core/agents/hook-account-label.test.ts b/src/core/agents/hook-account-label.test.tsnew file mode 100644index 000000000..128acdf48--- /dev/null+++ b/src/core/agents/hook-account-label.test.ts@@ -0,0 +1,164 @@+/**+ * `/hook/*` learns a THIRD label: which Claude account the posting session is actually on+ * (design D1/D3 of the claude-account-tracking plan).+ *+ * Driven through the REAL server — a POST over the socket, not a call to a helper — because the+ * property under test is that the label is attached where `verified` / `clientRevision` are, i.e.+ * once, in core, for BOTH shells. A unit test of `classifyClaudeConfigDir` (which exists, in+ * claude-accounts-core.test.ts) cannot see whether the hook server ever calls it.+ *+ * MUTATIONS this file is meant to catch: drop the `account` spread at the listener call (every+ * case but the codex one reddens); classify for every agent instead of claude (the codex case+ * reddens); read the accounts source once at boot instead of per event (the linked case reddens);+ * attach the label to the RAW listener too (the raw-contract case reddens).+ */+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'+import { mkdtempSync, rmSync } from 'node:fs'+import { homedir, tmpdir } from 'node:os'+import { join } from 'node:path'+import { hookServer } from './hook-server'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'+import {+ registerClaudeAccountsSource,+ resetClaudeAccountsSourceForTests+} from '../claude-config-dir'+import { accountConfigDir } from '../claude-accounts-core'+import type { NormalizedAgentEvent } from '../../shared/agents/normalize'+import type { ClaudeAccount } from '../../shared/types'++let dir = ''+// The linked dir is a plain PATH here — nothing on disk is required, and that is itself the point+// (D7): classification is string work, so a forged POST cannot make the server open anything.+const LINKED_DIR = '/home/test-user/.claude-2'+const LINKED: ClaudeAccount = { id: 'linked-acct-1', label: 'second', configDir: LINKED_DIR, createdAt: 0 }++let events: NormalizedAgentEvent[] = []+let raws: { agentId: string; payload: Record<string, unknown> }[] = []++function post(agentId: string, transcriptPath?: string): Promise<Response> {+ const payload: Record<string, unknown> = {+ hook_event_name: agentId === 'codex' ? 'SessionStart' : 'UserPromptSubmit',+ session_id: 's1',+ prompt: 'hi'+ }+ if (transcriptPath) payload.transcript_path = transcriptPath+ return fetch(`http://127.0.0.1:${hookServer.getPort()}/hook/${agentId}`, {+ method: 'POST',+ headers: {+ 'X-Nodeterm-Hook-Token': hookServer.getToken(),+ 'content-type': 'application/x-www-form-urlencoded'+ },+ body: `nodeId=n1&payload=${encodeURIComponent(JSON.stringify(payload))}`+ })+}++beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), 'hooksrv-account-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dir }))+ registerClaudeAccountsSource(() => [LINKED])+ await hookServer.start()+ hookServer.setListener((e) => {+ events.push(e)+ })+ hookServer.setRawListener((agentId, _nodeId, payload) => {+ raws.push({ agentId, payload })+ })+})++afterAll(() => {+ hookServer.stop()+ resetClaudeAccountsSourceForTests()+ resetPlatformForTests()+ rmSync(dir, { recursive: true, force: true })+})++beforeEach(() => {+ events = []+ raws = []+})++describe('hook server: the observed-account label on /hook/claude', () => {+ it('labels the SYSTEM config dir — a known account with no id', async () => {+ const res = await post('claude', join(homedir(), '.claude', 'projects', '-repo', 's1.jsonl'))+ expect(res.status).toBe(204)+ expect(events).toHaveLength(1)+ expect(events[0].account).toEqual({+ configDir: join(homedir(), '.claude'),+ accountId: null,+ known: true+ })+ })++ it('labels a LINKED dir with the settings account id — read per event, not at boot', async () => {+ await post('claude', `${LINKED_DIR}/projects/-repo/s1.jsonl`)+ expect(events[0].account).toEqual({+ configDir: LINKED_DIR,+ accountId: LINKED.id,+ known: true+ })+ })++ it('labels a MANAGED dir under this instance`s userData with its id', async () => {+ const managed = accountConfigDir(dir, 'managed-1')+ await post('claude', join(managed, 'projects', '-repo', 's1.jsonl'))+ expect(events[0].account).toEqual({ configDir: managed, accountId: 'managed-1', known: true })+ })++ it('labels an UNRECORDED dir known:false — the case that offers "link it in Settings"', async () => {+ await post('claude', '/home/test-user/.claude-3/projects/-repo/s1.jsonl')+ expect(events[0].account).toEqual({+ configDir: '/home/test-user/.claude-3',+ accountId: null,+ known: false+ })+ })++ it('resolves a SUBAGENT transcript nested deeper under the same projects root', async () => {+ await post('claude', `${LINKED_DIR}/projects/-repo/parent/sub-agent.jsonl`)+ expect(events[0].account?.accountId).toBe(LINKED.id)+ })++ it('attaches NO account when the payload carries no usable transcript_path', async () => {+ // "We did not observe an account" and "the system account" are different facts: an absent+ // field is the honest answer, and a synthesized system row would be a claim nothing supports.+ await post('claude')+ expect(events[0].account).toBeUndefined()+ await post('claude', '/home/test-user/.claude/settings.json') // no `projects` segment+ expect(events[1].account).toBeUndefined()+ })++ it('never labels another agent — codex and gemini own their own identity spine', async () => {+ await post('codex', join(homedir(), '.codex', 'sessions', '2026', 'rollout-x.jsonl'))+ expect(events).toHaveLength(1)+ expect(events[0].agentId).toBe('codex')+ expect(events[0].account).toBeUndefined()+ })++ it('leaves the RAW listener contract untouched (D3: neither raw listener changes)', async () => {+ await post('claude', `${LINKED_DIR}/projects/-repo/s1.jsonl`)+ expect(raws).toHaveLength(1)+ expect('account' in raws[0].payload).toBe(false)+ expect(raws[0].payload.transcript_path).toBe(`${LINKED_DIR}/projects/-repo/s1.jsonl`)+ })++ it('a throwing accounts source costs the label, never the 204 or the event', async () => {+ registerClaudeAccountsSource(() => {+ throw new Error('settings unreadable mid-write')+ })+ try {+ const res = await post('claude', `${LINKED_DIR}/projects/-repo/s1.jsonl`)+ expect(res.status).toBe(204)+ expect(events).toHaveLength(1)+ // The snapshot fails open to `[]`, so the dir is simply unrecorded — the event still lands.+ expect(events[0].account).toEqual({+ configDir: LINKED_DIR,+ accountId: null,+ known: false+ })+ } finally {+ registerClaudeAccountsSource(() => [LINKED])+ }+ })+})diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex 25a6ebdf3..169e8b454 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -1,12 +1,15 @@import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'import { randomUUID, timingSafeEqual } from 'crypto'import { writeFileSync, mkdirSync, chmodSync, unlinkSync } from 'fs'+import { homedir } from 'os'import path from 'path'import { platform } from '../platform'import { hookSockPath } from './hook-sock-path'import { canControlCanvas, type AgentId } from '../../shared/agents/config'import { normalizeFor, type NormalizedAgentEvent } from '../../shared/agents/normalize'-import type { CodexIdentityEvent } from '../../shared/types'+import { classifyClaudeConfigDir, configDirFromTranscriptPath } from '../claude-accounts-core'+import { claudeAccountsSnapshot } from '../claude-config-dir'+import type { CodexIdentityEvent, ObservedClaudeAccount } from '../../shared/types'import type { NodeTokenVerdict } from './node-auth-token'import { nodeTokenDir } from './node-token-files'import { isForeignKidToken, isSafeNodeId, verifyNodeToken } from './node-auth-token'@@ -146,6 +149,38 @@ function parseClientRevision(raw: string | string[] | undefined): number | undefreturn Number.isSafeInteger(n) ? n : undefined}+/**+ * The `account` LABEL for a claude hook payload (design D1/D2): `transcript_path` →+ * `<configDir>/projects/…` → which account that dir is. Undefined for every other agent and for a+ * payload with no usable `transcript_path` — "we did not observe an account" and "the system+ * account" are different facts and must stay distinguishable (CONTRIBUTING: a failed read is never+ * evidence of absence), so an absent field is the honest answer, not a synthesized system row.+ *+ * NEVER throws: this sits on the 204 path, and a classification failure — a settings store mid-+ * write, a platform seam not yet initialized in an odd boot order — must cost the label, not the+ * event. NO filesystem access happens here (D7): the dir is classified as a string, so a forged+ * POST naming `~/.ssh/projects/x.jsonl` gets a `known: false` label and nothing is opened.+ */+function observedClaudeAccount(+ agentId: string,+ payload: Record<string, unknown>+): ObservedClaudeAccount | undefined {+ if (agentId !== 'claude') return undefined+ const tp = payload.transcript_path+ if (typeof tp !== 'string' || !tp) return undefined+ try {+ const dir = configDirFromTranscriptPath(tp)+ if (!dir) return undefined+ return classifyClaudeConfigDir(dir, {+ homeDir: homedir(),+ userDataDir: platform().userDataDir,+ accounts: claudeAccountsSnapshot()+ })+ } catch {+ return undefined+ }+}+/*** What the hook server knows about the POST an event arrived on, beyond the event itself.*@@ -719,8 +754,16 @@ class HookServer {// Raw listener first: it drives the transcript-tailing features (which need// transcript_path). Inside the try so a throwing raw listener still ends 204.this.rawListener?.(agentId, nodeId, payload, { verified })+ // WHICH CLAUDE ACCOUNT this session is on (design D1/D3). A third LABEL alongside+ // `verified`/`clientRevision`, computed HERE so ONE implementation serves both shells —+ // the "both raw listeners change together" rule is sidestepped rather than violated,+ // because neither raw listener changes. Claude only: `transcript_path` means a config+ // dir for claude alone (codex rollouts and gemini chats live in unrelated trees, and+ // those agents have their own identity spine).+ const account = observedClaudeAccount(agentId, payload)const normalized = normalizeFor(agentId, { nodeId, agentId, payload })- if (normalized && this.listener) this.listener({ ...normalized, verified, clientRevision })+ if (normalized && this.listener)+ this.listener({ ...normalized, verified, clientRevision, ...(account ? { account } : {}) })}res.writeHead(204)res.end()diff --git a/src/core/claude-accounts-core.test.ts b/src/core/claude-accounts-core.test.tsindex 05eb14e73..1976d8122 100644--- a/src/core/claude-accounts-core.test.ts+++ b/src/core/claude-accounts-core.test.ts@@ -11,8 +11,12 @@ import {parseLoginCapture,isSupportedClaudeVersion,transcriptRootFor,- isSafeLocalTranscriptPath+ isSafeLocalTranscriptPath,+ classifyClaudeConfigDir,+ configDirFromTranscriptPath,+ normalizeLinkedConfigDir} from './claude-accounts-core'+import type { ClaudeAccount } from '../shared/types'describe('accountConfigDir', () => {it('maps an account id under userData/claude-accounts', () => {@@ -253,3 +257,297 @@ describe('isSafeRemoteTranscriptPath', () => {expect(isSafeRemoteTranscriptPath('/home/enes/.claude/projects/x.jsonl', undefined)).toBe(false)})})++// ---- Observed accounts (design D1/D2) --------------------------------------------------------+//+// The whole feature turns on these three pure functions, so each is driven with BOTH path+// dialects: the desktop that classifies an SSH node's POSIX `transcript_path` may itself be+// running on Windows, and the config dir a Windows user posts is `C:\Users\x\.claude`.++describe('configDirFromTranscriptPath', () => {+ it('walks up to the projects root and names its parent (POSIX)', () => {+ expect(+ configDirFromTranscriptPath('/home/u/.claude/projects/-home-u-repo/abc-123.jsonl')+ ).toBe('/home/u/.claude')+ expect(+ configDirFromTranscriptPath('/home/u/.claude-2/projects/-home-u-repo/abc-123.jsonl')+ ).toBe('/home/u/.claude-2')+ })++ it('handles a Windows-shaped path', () => {+ expect(+ configDirFromTranscriptPath('C:\\Users\\x\\.claude\\projects\\slug\\id.jsonl')+ ).toBe('C:\\Users\\x\\.claude')+ // Forward slashes are separators on Windows too, and a drive letter is what says so.+ expect(configDirFromTranscriptPath('C:/Users/x/.claude-2/projects/slug/id.jsonl')).toBe(+ 'C:\\Users\\x\\.claude-2'+ )+ expect(+ configDirFromTranscriptPath('\\\\srv\\share\\.claude\\projects\\slug\\id.jsonl')+ ).toBe('\\\\srv\\share\\.claude')+ })++ it('resolves a SUBAGENT transcript nested deeper under the same projects root', () => {+ expect(+ configDirFromTranscriptPath('/home/u/.claude-2/projects/-repo/parent/sub/agent.jsonl')+ ).toBe('/home/u/.claude-2')+ })++ it('takes the NEAREST projects walking up, not the first one in the path', () => {+ // Someone who keeps their checkouts in ~/projects: taking the FIRST match would answer+ // `/home/u` — i.e. hand the jail a $HOME-wide root.+ expect(+ configDirFromTranscriptPath('/home/u/projects/.claude/projects/-repo/s.jsonl')+ ).toBe('/home/u/projects/.claude')+ })++ it('normalizes the answer (redundant separators, `.`, a resolved `..`)', () => {+ expect(configDirFromTranscriptPath('/home/u//.claude/./projects/slug/s.jsonl')).toBe(+ '/home/u/.claude'+ )+ expect(configDirFromTranscriptPath('/home/u/x/../.claude/projects/slug/s.jsonl')).toBe(+ '/home/u/.claude'+ )+ })++ it('is null when there is no projects segment to walk up to', () => {+ expect(configDirFromTranscriptPath('/home/u/.claude/settings.json')).toBeNull()+ expect(configDirFromTranscriptPath('/home/u/projects')).toBeNull() // no parent-of-projects file+ expect(configDirFromTranscriptPath('')).toBeNull()+ expect(configDirFromTranscriptPath(' ')).toBeNull()+ expect(configDirFromTranscriptPath(undefined as unknown as string)).toBeNull()+ // A sibling-prefix segment is not a `projects` segment.+ expect(configDirFromTranscriptPath('/home/u/.claude/projects-evil/s.jsonl')).toBeNull()+ })++ it('takes an explicit dialect when the caller knows the owning filesystem', () => {+ // A relative Windows path has no drive letter to detect, so the caller must say.+ expect(configDirFromTranscriptPath('x\\.claude\\projects\\s\\id.jsonl', 'win32')).toBe(+ 'x\\.claude'+ )+ // …and the same string read as POSIX is one segment with backslashes IN ITS NAME.+ expect(configDirFromTranscriptPath('x\\.claude\\projects\\s\\id.jsonl', 'posix')).toBeNull()+ })+})++describe('normalizeLinkedConfigDir', () => {+ it('accepts an absolute path and normalizes it', () => {+ expect(normalizeLinkedConfigDir('/home/u/.claude-2')).toBe('/home/u/.claude-2')+ expect(normalizeLinkedConfigDir('/home/u/.claude-2/')).toBe('/home/u/.claude-2')+ expect(normalizeLinkedConfigDir(' /home/u//./.claude-2 ')).toBe('/home/u/.claude-2')+ expect(normalizeLinkedConfigDir('C:\\Users\\x\\.claude-2\\')).toBe('C:\\Users\\x\\.claude-2')+ expect(normalizeLinkedConfigDir('C:/Users/x/.claude-2')).toBe('C:\\Users\\x\\.claude-2')+ })++ it('never strips a path down INTO its root', () => {+ expect(normalizeLinkedConfigDir('/')).toBe('/')+ expect(normalizeLinkedConfigDir('C:\\')).toBe('C:\\')+ })++ it('refuses anything that is not an absolute, `..`-free string', () => {+ expect(normalizeLinkedConfigDir('.claude-2')).toBeNull()+ expect(normalizeLinkedConfigDir('~/.claude-2')).toBeNull() // `~` is the caller's to expand+ expect(normalizeLinkedConfigDir('../.claude-2')).toBeNull()+ expect(normalizeLinkedConfigDir('')).toBeNull()+ expect(normalizeLinkedConfigDir(' ')).toBeNull()+ expect(normalizeLinkedConfigDir(undefined)).toBeNull()+ expect(normalizeLinkedConfigDir(null)).toBeNull()+ expect(normalizeLinkedConfigDir(42)).toBeNull()+ expect(normalizeLinkedConfigDir({ configDir: '/x' })).toBeNull()+ })++ it('resolves a `..` that normalize can absorb rather than refusing it', () => {+ expect(normalizeLinkedConfigDir('/home/u/x/../.claude-2')).toBe('/home/u/.claude-2')+ // …and one that walks past the root is clamped by normalize, never left as `..`.+ expect(normalizeLinkedConfigDir('/../../etc')).toBe('/etc')+ })+})++describe('classifyClaudeConfigDir', () => {+ const homeDir = '/home/u'+ const userDataDir = '/home/u/.config/nodeterm'+ const linked: ClaudeAccount = {+ id: 'linked-1',+ label: 'second',+ configDir: '/home/u/.claude-2',+ createdAt: 0+ }+ const at = (dir: string, accounts: ClaudeAccount[] = [linked]) =>+ classifyClaudeConfigDir(dir, { homeDir, userDataDir, accounts })++ it('names a MANAGED local dir by its id, without consulting settings', () => {+ // The path IS nodeterm's own root, so the id in it is the id nodeterm minted — including for+ // an account still `pending` its login, whose login node is the session posting from there.+ expect(at(`${userDataDir}/claude-accounts/abc-1`, [])).toEqual({+ configDir: `${userDataDir}/claude-accounts/abc-1`,+ accountId: 'abc-1',+ known: true+ })+ })++ it('names a MANAGED REMOTE dir by its id (an SSH node posts the host path)', () => {+ expect(at('/home/enes/.nodeterm/claude-accounts/xyz_2', [])).toEqual({+ configDir: '/home/enes/.nodeterm/claude-accounts/xyz_2',+ accountId: 'xyz_2',+ known: true+ })+ })++ it('names a LINKED dir by its account id, trailing slash and `.`-segments included', () => {+ for (const p of ['/home/u/.claude-2', '/home/u/.claude-2/', '/home/u/./.claude-2']) {+ expect(at(p)).toEqual({ configDir: '/home/u/.claude-2', accountId: 'linked-1', known: true })+ }+ })++ it('ignores a linked row that is pending, host-scoped, or holds an unusable path', () => {+ const unusable: ClaudeAccount[] = [+ { ...linked, id: 'p', pending: true },+ { ...linked, id: 'h', host: 'u@example' },+ { ...linked, id: 'rel', configDir: '.claude-2' },+ { ...linked, id: 'dots', configDir: '/home/u/../u/.claude-2' } // normalizes to the same dir+ ]+ // The first three contribute nothing; the fourth normalizes onto the observed dir and wins.+ expect(at('/home/u/.claude-2', unusable).accountId).toBe('dots')+ expect(at('/home/u/.claude-2', unusable.slice(0, 3))).toEqual({+ configDir: '/home/u/.claude-2',+ accountId: null,+ known: false+ })+ })++ it('calls the system dir system — this machine`s and a remote host`s alike', () => {+ expect(at('/home/u/.claude')).toEqual({+ configDir: '/home/u/.claude',+ accountId: null,+ known: true+ })+ // D2 is host-agnostic on purpose: an SSH node's `<remoteHome>/.claude` is that host's system+ // account, and the observed dir is a label — nothing branches on it for permission.+ expect(at('/home/enes/.claude')).toEqual({+ configDir: '/home/enes/.claude',+ accountId: null,+ known: true+ })+ })++ it('prefers a LINKED match over the `.claude` basename rule', () => {+ const odd: ClaudeAccount = { id: 'odd', label: 'o', configDir: '/opt/profiles/.claude', createdAt: 0 }+ expect(at('/opt/profiles/.claude', [odd]).accountId).toBe('odd')+ })++ it('leaves an unrecorded dir unknown — and never reads it', () => {+ // The real motivating case BEFORE the user links it: the chip labels it `.claude-3` by path.+ expect(at('/home/u/.claude-3', [])).toEqual({+ configDir: '/home/u/.claude-3',+ accountId: null,+ known: false+ })+ // A forged POST aiming at a credential tree is unknown too — a label, and nothing is opened.+ expect(at('/home/u/.ssh', [])).toEqual({+ configDir: '/home/u/.ssh',+ accountId: null,+ known: false+ })+ // A bad id segment under the managed root is NOT a managed account.+ expect(at(`${userDataDir}/claude-accounts/a.b`, [])).toEqual({+ configDir: `${userDataDir}/claude-accounts/a.b`,+ accountId: null,+ known: false+ })+ // …nor is a dir two levels down inside one.+ expect(at(`${userDataDir}/claude-accounts/a1/projects`, []).known).toBe(false)+ })++ it('classifies Windows-shaped dirs, case-insensitively as that filesystem is', () => {+ const win = (dir: string, accounts: ClaudeAccount[] = []) =>+ classifyClaudeConfigDir(dir, {+ homeDir: 'C:\\Users\\x',+ userDataDir: 'C:\\Users\\x\\AppData\\Roaming\\nodeterm',+ accounts+ })+ expect(win('C:\\Users\\x\\.claude')).toEqual({+ configDir: 'C:\\Users\\x\\.claude',+ accountId: null,+ known: true+ })+ expect(win('C:\\Users\\x\\AppData\\Roaming\\nodeterm\\claude-accounts\\a1').accountId).toBe('a1')+ expect(+ win('c:\\users\\X\\.claude-2\\', [+ { id: 'w1', label: 'w', configDir: 'C:\\Users\\x\\.claude-2', createdAt: 0 }+ ]).accountId+ ).toBe('w1')+ })++ it('does not match a POSIX dir against a WINDOWS local root (or the reverse)', () => {+ // A Windows desktop classifying an SSH node's POSIX path must not confuse the two trees —+ // and `/home/u/.claude` still reads as a system dir through the host-agnostic basename rule.+ const onWindows = classifyClaudeConfigDir('/home/u/.claude-2', {+ homeDir: 'C:\\Users\\x',+ userDataDir: 'C:\\Users\\x\\AppData\\Roaming\\nodeterm',+ accounts: [{ id: 'w1', label: 'w', configDir: 'C:\\Users\\x\\.claude-2', createdAt: 0 }]+ })+ expect(onWindows).toEqual({ configDir: '/home/u/.claude-2', accountId: null, known: false })+ })+})++describe('transcriptRootFor — linked accounts', () => {+ it('uses the linked config dir`s projects when one is given', () => {+ expect(transcriptRootFor('/Users/x', '/ud', 'a1', '/Users/x/.claude-2')).toBe(+ '/Users/x/.claude-2/projects'+ )+ // A linked root does not need the account id to be resolvable as a managed one.+ expect(transcriptRootFor('/Users/x', null, undefined, '/Users/x/.claude-2')).toBe(+ '/Users/x/.claude-2/projects'+ )+ })+ it('degrades to the managed/system root when the linked value is unusable', () => {+ // "Never something more destructive than the default" — a hand-edited relative path must not+ // resolve against the process cwd.+ expect(transcriptRootFor('/Users/x', '/ud', 'a1', '.claude-2')).toBe(+ '/ud/claude-accounts/a1/projects'+ )+ expect(transcriptRootFor('/Users/x', '/ud', undefined, '')).toBe('/Users/x/.claude/projects')+ })+})++describe('isSafeLocalTranscriptPath — linked config dirs', () => {+ const home = '/home/u'+ const ud = '/home/u/.config/nodeterm'+ const linkedDirs = ['/home/u/.claude-2']++ it('accepts <linkedDir>/projects and everything under it', () => {+ expect(isSafeLocalTranscriptPath(`${home}/.claude-2/projects`, home, ud, undefined, linkedDirs)).toBe(true)+ expect(+ isSafeLocalTranscriptPath(`${home}/.claude-2/projects/-repo/s.jsonl`, home, ud, undefined, linkedDirs)+ ).toBe(true)+ })++ it('still refuses everything ELSE in that dir — the `.ssh` case §3 names', () => {+ expect(isSafeLocalTranscriptPath(`${home}/.claude-2/.ssh`, home, ud, undefined, linkedDirs)).toBe(false)+ expect(+ isSafeLocalTranscriptPath(`${home}/.claude-2/.credentials.json`, home, ud, undefined, linkedDirs)+ ).toBe(false)+ expect(isSafeLocalTranscriptPath(`${home}/.claude-2`, home, ud, undefined, linkedDirs)).toBe(false)+ // A sibling-prefix root, as for every other allowed root.+ expect(+ isSafeLocalTranscriptPath(`${home}/.claude-2/projects-evil/x`, home, ud, undefined, linkedDirs)+ ).toBe(false)+ // The PARENT of a linked dir is not opened up by linking the child.+ expect(isSafeLocalTranscriptPath(`${home}/projects/x.jsonl`, home, ud, undefined, linkedDirs)).toBe(false)+ })++ it('contributes no root for a value that fails re-validation at the point of use', () => {+ // Hand-editable settings JSON: a relative or `..`-bearing dir is ignored, not resolved.+ expect(isSafeLocalTranscriptPath(`${home}/.claude-2/projects/s.jsonl`, home, ud, undefined, ['.claude-2'])).toBe(+ false+ )+ expect(isSafeLocalTranscriptPath('/etc/projects/x', home, ud, undefined, ['/etc/../etc'])).toBe(true)+ expect(isSafeLocalTranscriptPath(`${home}/.ssh/id_rsa`, home, ud, undefined, ['/'])).toBe(false)+ })++ it('is bit-for-bit the old predicate when no linked dirs are passed', () => {+ expect(isSafeLocalTranscriptPath(`${home}/.claude-2/projects/s.jsonl`, home, ud)).toBe(false)+ expect(isSafeLocalTranscriptPath(`${home}/.claude-2/projects/s.jsonl`, home, ud, undefined, [])).toBe(false)+ expect(isSafeLocalTranscriptPath(`${home}/.claude/projects/s.jsonl`, home, ud, undefined, linkedDirs)).toBe(true)+ })+})diff --git a/src/core/claude-accounts-core.ts b/src/core/claude-accounts-core.tsindex c9f3e3f0d..dc459d6ad 100644--- a/src/core/claude-accounts-core.ts+++ b/src/core/claude-accounts-core.ts@@ -3,6 +3,7 @@import { createHash } from 'crypto'import path from 'path'import { MODEL_GATEWAY_ENV_KEYS } from '../shared/agents/model-gateway'+import type { ClaudeAccount, ObservedClaudeAccount } from '../shared/types'/** Shape of a valid account id (uuid / opaque token). Shared by every path builder so a bad id* can never traverse out of the accounts root — locally OR on a remote host over ssh. */@@ -48,17 +49,200 @@ export function remoteAccountConfigDirAbs(remoteHome: string, accountId: string)return `${remoteHome.replace(/\/+$/, '')}/.nodeterm/claude-accounts/${accountId}`}+// ---- Observed config dirs (D1/D2: which account a RUNNING session is actually on) -----------+//+// The hook payload's `transcript_path` is the only account signal that exists for a session+// nodeterm did not launch — a hand-run `CLAUDE_CONFIG_DIR=~/.claude-2 claude` in a plain terminal+// carries `data.accountId: undefined` forever. Everything below is pure string work on that path:+// the observed dir is a LABEL (see `ObservedClaudeAccount`), nothing branches on it for+// permission, so a host-agnostic match is correct and covers SSH nodes without a remote lookup.++/** Which `path` implementation owns a given path string. */+export type PathDialect = 'posix' | 'win32'++/**+ * Dialect of a path string, by SHAPE and only by shape: a drive letter (`C:\…`, `C:/…`) or a UNC+ * prefix (`\\host\share`). Deliberately NOT "contains a backslash" — on POSIX a backslash is legal+ * filename text, and treating the two separators as interchangeable there would split real names+ * apart (CONTRIBUTING: "do not treat both separators as interchangeable unless the owning+ * filesystem is known to be Windows"). Anything else is POSIX, which is also the right answer for+ * the remote paths an SSH node's hooks post.+ */+export function pathDialectOf(p: string): PathDialect {+ return /^[A-Za-z]:[\\/]/.test(p) || p.startsWith('\\\\') ? 'win32' : 'posix'+}++function pathFor(d: PathDialect): typeof path.posix {+ return d === 'win32' ? path.win32 : path.posix+}++/**+ * Normalize a directory path for COMPARISON: dialect-correct `normalize`, then trailing separators+ * stripped down to (but never into) the root. Trailing-slash insensitivity is not cosmetic — the+ * two spellings arrive from different places (a hook payload's `transcript_path` vs. a path the+ * user typed into Settings), and CONTRIBUTING's rule is that BOTH sides of a path comparison go+ * through one function.+ */+function normDir(p: string, d: PathDialect): string {+ const P = pathFor(d)+ let n = P.normalize(p)+ const root = P.parse(n).root+ // On win32 both separators end a path; on POSIX only `/` does (a trailing `\` is a filename).+ const endsWithSep = (s: string): boolean => s.endsWith('/') || (d === 'win32' && s.endsWith('\\'))+ while (n.length > root.length && endsWithSep(n)) n = n.slice(0, -1)+ return n+}++/** Compare two already-`normDir`'d dirs. Case-insensitive on win32 — that IS the filesystem's own+ * rule there, and a chip that fails to match `C:\Users\X` against `c:\users\x` is a silent miss. */+function sameDir(a: string, b: string, d: PathDialect): boolean {+ return d === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b+}++/** Split a normalized dir into segments in its own dialect. */+function segmentsOf(p: string, d: PathDialect): string[] {+ return d === 'win32' ? p.split(/[\\/]/) : p.split('/')+}++/**+ * The Claude config dir a `transcript_path` belongs to, or null when the path is not shaped like a+ * Claude transcript. Claude writes `<configDir>/projects/<slug>/<session>.jsonl`, and a SUBAGENT+ * transcript sits deeper under the same `projects` root — so the rule is "walk UP from the file to+ * the nearest segment named `projects`, take its parent".+ *+ * Nearest going UP means the LAST `projects` segment, not the first. A config dir can itself live+ * under a directory called `projects` (`~/projects/.claude/projects/<slug>/<id>.jsonl` is an+ * ordinary layout for someone who keeps their checkouts in `~/projects`), and taking the first+ * match there would name `~` as the config dir — i.e. hand the jail a $HOME-wide root.+ *+ * `dialect` is normally detected from the string (an SSH node posts a POSIX path to a Windows+ * desktop, so the LOCAL platform is the wrong authority — CONTRIBUTING: "the browser's OS is NOT+ * the filesystem's OS"); pass it explicitly when the caller knows the owning filesystem.+ */+export function configDirFromTranscriptPath(p: string, dialect?: PathDialect): string | null {+ if (typeof p !== 'string' || !p.trim()) return null+ const d = dialect ?? pathDialectOf(p)+ const P = pathFor(d)+ const segs = segmentsOf(P.normalize(p.trim()), d)+ const i = segs.lastIndexOf('projects')+ // `i < 1` covers both "no projects segment at all" and a `projects` with no parent to name.+ // The trailing check is the other half of the same honesty: `transcript_path` is a FILE, so a+ // `projects` with nothing under it is not a transcript and answering `/home/u` for `/home/u/+ // projects` would invent a config dir out of an ordinary checkout directory.+ if (i < 1 || i >= segs.length - 1) return null+ // An absolute POSIX path splits to a leading '' — joining ['', 'home', 'x'] yields '/home/x'.+ // `/projects/x.jsonl` slices to [''], which joins to '' and means the root itself.+ const joined = segs.slice(0, i).join(P.sep)+ return normDir(joined || P.sep, d)+}++/**+ * Re-validate a hand-editable `ClaudeAccount.configDir` at the POINT OF USE (CONTRIBUTING: never+ * by its TypeScript type — settings.json is hand-edited and git-shared). Absolute, normalized, no+ * surviving `..`; anything else is `null`, and every caller degrades to the managed-dir default+ * rather than to something wider ("degrade to nothing, never to something wrong").+ *+ * `..` cannot survive `normalize` on an absolute path, so the check is belt-and-braces — kept+ * because this value ends up as a JAIL ROOT, where a survivor would walk straight out of it.+ */+export function normalizeLinkedConfigDir(raw: unknown): string | null {+ if (typeof raw !== 'string') return null+ const s = raw.trim()+ if (!s) return null+ const d = pathDialectOf(s)+ if (!pathFor(d).isAbsolute(s)) return null+ const n = normDir(s, d)+ return segmentsOf(n, d).includes('..') ? null : n+}++/** The settings rows a linked-dir match may consult: local (a linked dir is local by definition —+ * see §7 of the plan), settled, and carrying a value that survives re-validation. */+function linkedDirOf(acct: ClaudeAccount): string | null {+ if (acct.host || acct.pending) return null+ return normalizeLinkedConfigDir(acct.configDir)+}++/**+ * Classify an observed config dir into an `ObservedClaudeAccount` (design D2). PURE string+ * matching — no fs, and deliberately host-agnostic, because the same classification has to answer+ * for a remote path an SSH node's hooks posted:+ * 1. `<userData>/claude-accounts/<id>` — this app's own managed root on THIS machine.+ * 2. `<anything>/.nodeterm/claude-accounts/<id>` — the same thing on a remote host (POSIX).+ * 3. a settings row's linked `configDir` — the user declared this dir an account.+ * 4. any `…/.claude` — the system default, on this machine or on the host (`accountId: null`).+ * 5. anything else — `known: false`; the UI labels it by its last path segment and offers to+ * link it. NOTHING reads such a dir (D7): a forged POST must not make us open a file.+ *+ * (1) and (2) answer with the id WITHOUT consulting settings: the path IS nodeterm's own root, so+ * the id in it is the id nodeterm minted — including for an account still `pending` its login,+ * whose login node is precisely the session posting from that dir.+ */+export function classifyClaudeConfigDir(+ dir: string,+ ctx: { homeDir: string; userDataDir: string; accounts: readonly ClaudeAccount[] }+): ObservedClaudeAccount {+ const d = pathDialectOf(dir)+ const configDir = normDir(dir, d)+ const P = pathFor(d)++ // 1. Managed, local. Compared in the LOCAL dialect on both sides: a POSIX remote path can never+ // match a Windows userData root, which is the correct answer, not a miss.+ const udDialect = pathDialectOf(ctx.userDataDir)+ if (udDialect === d) {+ // Joined in the userData path's OWN dialect, not the local platform's: this module is pure+ // path math and the LOCAL `path` is the wrong authority for a string that came off the wire.+ const localRoot = normDir(pathFor(udDialect).join(ctx.userDataDir, 'claude-accounts'), udDialect)+ const base = P.basename(configDir)+ if (sameDir(normDir(P.dirname(configDir), d), localRoot, d) && isSafeAccountId(base)) {+ return { configDir, accountId: base, known: true }+ }+ }+ // 2. Managed, remote (`remoteAccountConfigDir`). Remote hosts are POSIX; matched by SHAPE rather+ // than against a resolved `$HOME`, because the hook payload is the only thing we have.+ if (d === 'posix') {+ const segs = segmentsOf(configDir, d)+ const [a, b, c] = segs.slice(-3)+ if (segs.length >= 3 && a === '.nodeterm' && b === 'claude-accounts' && isSafeAccountId(c)) {+ return { configDir, accountId: c, known: true }+ }+ }+ // 3. Linked. Before the `.claude` rule below so that linking a dir whose basename happens to be+ // `.claude` (another user's home, a relocated profile) reports the account the user declared.+ for (const acct of ctx.accounts) {+ const linked = linkedDirOf(acct)+ if (linked && pathDialectOf(linked) === d && sameDir(configDir, linked, d)) {+ return { configDir, accountId: acct.id, known: true }+ }+ }+ // 4. System. `<home>/.claude` is the local one; the basename rule generalizes it to a remote+ // host's own system account, which is `known` for the same reason — the dir is a label.+ const homeDialect = pathDialectOf(ctx.homeDir)+ if (homeDialect === d && sameDir(configDir, normDir(P.join(ctx.homeDir, '.claude'), d), d)) {+ return { configDir, accountId: null, known: true }+ }+ if (P.basename(configDir) === '.claude') return { configDir, accountId: null, known: true }+ return { configDir, accountId: null, known: false }+}+/*** Transcript root for a session lookup: an account's `projects` dir under its config dir, or* the system default `~/.claude/projects` when no account. Pure path math (no fs) — the impure* wrapper in transcript-reader.ts feeds `os.homedir()` / `app.getPath('userData')`. Reuses* `accountConfigDir`'s id validation so a bad account id can never escape the accounts root.+ *+ * `linkedConfigDir` is a LINKED account's own dir (`ClaudeAccount.configDir`): its transcripts+ * live in the user's directory, not under `{userData}`. Trailing and optional, so every+ * pre-existing caller is unchanged. Re-validated here rather than trusted — an unusable value+ * falls back to the managed/system root, which is the pre-existing behavior, never something wider.*/export function transcriptRootFor(homeDir: string,userDataPath: string | null,- accountId?: string+ accountId?: string,+ linkedConfigDir?: string): string {+ const linked = normalizeLinkedConfigDir(linkedConfigDir)+ if (linked) return path.join(linked, 'projects')return accountId? path.join(accountConfigDir(userDataPath ?? '', accountId), 'projects'): path.join(homeDir, '.claude', 'projects')@@ -83,12 +267,22 @@ export function transcriptRootFor(* PARAMETER rather than an env read because this module is pure path math: the shells own the env.* Getting it wrong fails CLOSED (a relocated codex home would silently never fill its meter, not* leak anything) — which is the quieter and therefore worse failure, hence the parameter.+ *+ * `linkedDirs` are the LINKED accounts' config dirs from settings (`ClaudeAccount.configDir`) —+ * user-declared, so `<dir>/projects/**` is legitimate and the meter/subagent cards fill for a pane+ * running `CLAUDE_CONFIG_DIR=~/.claude-2 claude`. Exactly the same two rules as the managed root:+ * the dirs come from SETTINGS and never from the POST (a forged payload cannot name its own jail+ * root), and the segment after the dir must be `projects` — `<linkedDir>/.ssh` and `<linkedDir>`+ * itself stay refused. Each value is re-validated here (absolute, normalized, no `..`) rather than+ * trusted for having a TypeScript type: it is hand-editable settings JSON, and an unusable one+ * simply contributes no root.*/export function isSafeLocalTranscriptPath(abs: string,homeDir: string,userDataPath: string,- codexHomeDir?: string+ codexHomeDir?: string,+ linkedDirs?: readonly string[]): boolean {const legacyRoot = path.join(homeDir, '.claude', 'projects')if (abs === legacyRoot || abs.startsWith(legacyRoot + path.sep)) return true@@ -101,6 +295,14 @@ export function isSafeLocalTranscriptPath(if (abs === geminiRoot || abs.startsWith(geminiRoot + path.sep)) return trueconst codexRoot = path.join(codexHomeDir || path.join(homeDir, '.codex'), 'sessions')if (abs === codexRoot || abs.startsWith(codexRoot + path.sep)) return true+ // Linked accounts (D4). `<dir>/projects` and below only — the `+ path.sep` is what keeps a+ // sibling-prefix root (`…/projects-evil`) out, exactly as for the two roots above.+ for (const raw of linkedDirs ?? []) {+ const dir = normalizeLinkedConfigDir(raw)+ if (!dir) continue+ const root = path.join(dir, 'projects')+ if (abs === root || abs.startsWith(root + path.sep)) return true+ }const accountsRoot = path.join(userDataPath, 'claude-accounts')if (abs !== accountsRoot && !abs.startsWith(accountsRoot + path.sep)) return false// Relative to the accounts root: expect `<accountId>/projects[/…]`. Because `abs` is normalizeddiff --git a/src/core/claude-accounts-link-symlink.test.ts b/src/core/claude-accounts-link-symlink.test.tsnew file mode 100644index 000000000..38e453466--- /dev/null+++ b/src/core/claude-accounts-link-symlink.test.ts@@ -0,0 +1,96 @@+/**+ * Linking a config dir whose `settings.json` is a SYMLINK must keep it a symlink.+ *+ * This is not a hypothetical shape — it is the layout the feature was built for. A user running+ * two logins keeps `~/.claude-2` with `settings.json`, `hooks/`, `skills/` and `projects/` all+ * symlinked into `~/.claude/`, so the two identities share one configuration and differ only in+ * `.claude.json` + `.credentials.json`. If `link` replaced the link with a regular file, the two+ * profiles would silently fork: every later edit to the real `~/.claude/settings.json` — including+ * this app's own hook upgrades — would stop reaching the second account.+ *+ * Deliberately NO `vi.mock` here (unlike claude-accounts-service.test.ts, which observes the+ * installer): the property under test is what the REAL writer does to a REAL symlink, and a mock+ * of the writer is exactly the fixture that cannot discriminate.+ *+ * MUTATION: swap `installHooksInto`'s `writeFileSync` for an unlink-then-write, or for the atomic+ * write-temp-then-rename this repo uses for PUBLISHED files, and the symlink assertion reddens.+ * (Atomic rename is the right rule for a file we own and the wrong one here: `renameAtomic`+ * REPLACES the link with the temp file, which is the fork this test exists to prevent. That is+ * why `installHooksInto` is left writing in place — the file belongs to the CLI, not to us.)+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import {+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ symlinkSync,+ writeFileSync+} from 'fs'+import os from 'os'+import path from 'path'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform, type FakePlatform } from './platform-fake'+import { IPC } from '../shared/ipc'+import { registerClaudeAccountsIpc } from './claude-accounts-service'+import { resetClaudeAccountsSourceForTests } from './claude-config-dir'++let fake: FakePlatform+let root = ''+let userDataDir = ''++const call = (channel: string, ...args: unknown[]): Promise<any> =>+ Promise.resolve(fake.handlers[channel](...args))++beforeEach(() => {+ root = mkdtempSync(path.join(os.tmpdir(), 'nt-link-symlink-'))+ userDataDir = path.join(root, 'userData')+ mkdirSync(userDataDir, { recursive: true })+ fake = fakePlatform({ userDataDir })+ initPlatform(fake)+ registerClaudeAccountsIpc()+})+afterEach(() => {+ resetPlatformForTests()+ resetClaudeAccountsSourceForTests()+ rmSync(root, { recursive: true, force: true })+})++describe('link() installs the managed hook THROUGH a symlinked settings.json', () => {+ it('keeps the symlink and writes the hook into its shared target', async () => {+ // The real two-profile layout: `.claude` holds the real settings, `.claude-2` symlinks to it.+ const primary = path.join(root, '.claude')+ const second = path.join(root, '.claude-2')+ mkdirSync(primary, { recursive: true })+ mkdirSync(second, { recursive: true })+ const target = path.join(primary, 'settings.json')+ const link = path.join(second, 'settings.json')+ writeFileSync(target, JSON.stringify({ theme: 'dark', hooks: {} }, null, 2))+ symlinkSync(target, link)++ const res = await call(IPC.claudeAccountsLink, second)+ expect(res.configDir).toBe(second)++ // 1. Still a symlink — the two profiles did not fork.+ expect(lstatSync(link).isSymbolicLink()).toBe(true)+ // 2. The SHARED target gained the managed hook (written through the link).+ const written = JSON.parse(readFileSync(target, 'utf8')) as {+ theme?: string+ hooks?: Record<string, unknown[]>+ }+ expect(written.theme).toBe('dark') // the user's own settings survived the merge+ expect(Object.keys(written.hooks ?? {}).length).toBeGreaterThan(0)+ expect(JSON.stringify(written.hooks)).toContain('agent-hooks')+ })++ it('creates settings.json when the linked dir has none (an unconfigured profile)', async () => {+ const second = path.join(root, '.claude-3')+ mkdirSync(second, { recursive: true })+ await call(IPC.claudeAccountsLink, second)+ const written = JSON.parse(readFileSync(path.join(second, 'settings.json'), 'utf8')) as {+ hooks?: Record<string, unknown[]>+ }+ expect(Object.keys(written.hooks ?? {}).length).toBeGreaterThan(0)+ })+})diff --git a/src/core/claude-accounts-service.test.ts b/src/core/claude-accounts-service.test.tsindex 5f7bd7dc5..5757ab79b 100644--- a/src/core/claude-accounts-service.test.ts+++ b/src/core/claude-accounts-service.test.ts@@ -19,6 +19,11 @@ import { fakePlatform, type FakePlatform } from './platform-fake'import { IPC } from '../shared/ipc'import { registerClaudeAccountsIpc, installHooksIntoLocalAccounts } from './claude-accounts-service'import { accountConfigDir } from './claude-accounts-core'+import {+ registerClaudeAccountsSource,+ resetClaudeAccountsSourceForTests+} from './claude-config-dir'+import type { ClaudeAccount } from '../shared/types'// The hook + TUI writers are exercised by their own suites; here they only have to be OBSERVED,// and a real write would touch the account dir this file then asserts about.@@ -48,16 +53,18 @@ beforeEach(() => {})afterEach(() => {resetPlatformForTests()+ resetClaudeAccountsSourceForTests()rmSync(userDataDir, { recursive: true, force: true })})-describe('registerClaudeAccountsIpc — the four channels', () => {- it('registers exactly the four claude-accounts channels', () => {+describe('registerClaudeAccountsIpc — the five channels', () => {+ it('registers exactly the five claude-accounts channels', () => {registerClaudeAccountsIpc()expect(Object.keys(fake.handlers).sort()).toEqual([IPC.claudeAccountsAdd,IPC.claudeAccountsCancelWait,+ IPC.claudeAccountsLink,IPC.claudeAccountsRemove,IPC.claudeAccountsWaitLogin].sort()@@ -180,3 +187,144 @@ describe('installHooksIntoLocalAccounts', () => {warn.mockRestore()})})++// ---- Linked accounts (design D4 / §3) --------------------------------------------------------+//+// A linked account is a config dir the USER already owns (`~/.claude-2` driven by their own+// `CLAUDE_CONFIG_DIR` shell function). Two properties matter more than the rest and are pinned+// against REAL temp directories rather than mocks: the validation actually refuses each bad shape,+// and removing a linked account never deletes anything.+describe('claudeAccounts.link', () => {+ let linkDir = ''+ beforeEach(() => {+ linkDir = mkdtempSync(path.join(os.tmpdir(), 'nt-linked-'))+ registerClaudeAccountsIpc()+ })+ afterEach(() => rmSync(linkDir, { recursive: true, force: true }))++ it('links an existing dir: id + normalized path + email, hook and TUI installed into it', async () => {+ writeFileSync(+ path.join(linkDir, '.claude.json'),+ JSON.stringify({ oauthAccount: { emailAddress: '[email protected]' } })+ )+ const res = await call(IPC.claudeAccountsLink, `${linkDir}/`)+ expect(res.id).toMatch(/^[A-Za-z0-9-]+$/)+ expect(res.configDir).toBe(linkDir) // trailing slash normalized away+ expect(res.email).toBe('[email protected]')+ // The same two writes an ADDED account gets — or the linked identity reports no agent status.+ expect(installed).toEqual([linkDir])+ expect(tui).toEqual([linkDir])+ })++ it('is email: null — not a failure — when the dir is not signed in yet', async () => {+ await expect(call(IPC.claudeAccountsLink, linkDir)).resolves.toMatchObject({ email: null })+ writeFileSync(path.join(linkDir, '.claude.json'), 'not json at all')+ await expect(call(IPC.claudeAccountsLink, linkDir)).resolves.toMatchObject({ email: null })+ writeFileSync(path.join(linkDir, '.claude.json'), JSON.stringify({ oauthAccount: {} }))+ await expect(call(IPC.claudeAccountsLink, linkDir)).resolves.toMatchObject({ email: null })+ })++ it('expands a leading ~ (the value is typed, not shell-expanded by anything else)', async () => {+ // Proved through the REFUSAL rather than by linking something inside the real home: the+ // message names the path we actually resolved, so an unexpanded `~` would read as+ // `No such directory: ~/nodeterm-link-probe` and this assertion would fail.+ await expect(call(IPC.claudeAccountsLink, '~/nodeterm-link-probe-does-not-exist')).rejects.toThrow(+ `No such directory: ${path.join(os.homedir(), 'nodeterm-link-probe-does-not-exist')}`+ )+ // A bare `~` is the home dir itself; `~evil` is NOT a home-relative path and stays literal+ // (so it is refused as relative, never resolved against $HOME).+ await expect(call(IPC.claudeAccountsLink, '~notauser/.claude-2')).rejects.toThrow(+ /Not an absolute path/+ )+ })++ it('refuses a relative path, a `..` path, and a non-string', async () => {+ for (const bad of ['.claude-2', '../.claude-2', 'claude', '', ' ']) {+ await expect(call(IPC.claudeAccountsLink, bad)).rejects.toThrow()+ }+ await expect(call(IPC.claudeAccountsLink, 42 as unknown as string)).rejects.toThrow()+ expect(installed).toEqual([]) // nothing was written for any refusal+ })++ it('refuses the system ~/.claude by name, without stat-ing anything', async () => {+ await expect(call(IPC.claudeAccountsLink, path.join(os.homedir(), '.claude'))).rejects.toThrow(+ /system Claude config dir/+ )+ // Same dir spelled differently must give the same refusal — both sides go through one+ // normalizer (CONTRIBUTING: normalize BOTH sides of a path comparison).+ await expect(+ call(IPC.claudeAccountsLink, path.join(os.homedir(), 'x', '..', '.claude') + '/')+ ).rejects.toThrow(/system Claude config dir/)+ })++ it('refuses a nodeterm-managed account dir (one dir must not have two account ids)', async () => {+ const managed = accountConfigDir(userDataDir, 'abc')+ mkdirSync(managed, { recursive: true })+ await expect(call(IPC.claudeAccountsLink, managed)).rejects.toThrow(/nodeterm-managed/)+ await expect(call(IPC.claudeAccountsLink, path.join(userDataDir, 'claude-accounts'))).rejects.toThrow(+ /nodeterm-managed/+ )+ })++ it('refuses a dir already linked — by NORMALIZED path, not by the string typed', async () => {+ registerClaudeAccountsSource(() => [+ { id: 'existing', label: 'first', configDir: linkDir, createdAt: 0 } as ClaudeAccount+ ])+ await expect(call(IPC.claudeAccountsLink, `${linkDir}/`)).rejects.toThrow(/already linked/)+ await expect(call(IPC.claudeAccountsLink, path.join(linkDir, 'x', '..'))).rejects.toThrow(+ /already linked/+ )+ })++ it('refuses a path that does not exist, and a path that is a FILE', async () => {+ await expect(call(IPC.claudeAccountsLink, path.join(linkDir, 'nope'))).rejects.toThrow(+ /No such directory/+ )+ const file = path.join(linkDir, 'a-file')+ writeFileSync(file, 'x')+ await expect(call(IPC.claudeAccountsLink, file)).rejects.toThrow(/Not a directory/)+ expect(installed).toEqual([])+ })+})++describe('removing a LINKED account never deletes the directory', () => {+ it('forgets the record and leaves a REAL directory (and its contents) on disk', async () => {+ const linkDir = mkdtempSync(path.join(os.tmpdir(), 'nt-linked-rm-'))+ const credentials = path.join(linkDir, '.credentials.json')+ writeFileSync(credentials, '{"token":"the user\'s own login"}')+ try {+ registerClaudeAccountsIpc()+ const res = await call(IPC.claudeAccountsLink, linkDir)+ registerClaudeAccountsSource(() => [+ { id: res.id, label: 'second', configDir: linkDir, createdAt: 0 } as ClaudeAccount+ ])+ await call(IPC.claudeAccountsRemove, res.id)+ // THE assertion of this whole work package: the dir is the user's, and it is still there.+ expect(existsSync(linkDir)).toBe(true)+ expect(existsSync(credentials)).toBe(true)+ // …and no managed dir was invented and deleted in its place either.+ expect(existsSync(accountConfigDir(userDataDir, res.id))).toBe(false)+ } finally {+ rmSync(linkDir, { recursive: true, force: true })+ }+ })++ it('still deletes a MANAGED dir — the rm path is unchanged for the accounts nodeterm created', async () => {+ registerClaudeAccountsIpc()+ const { id, configDir } = await call(IPC.claudeAccountsAdd)+ // A settings list that mentions the id but carries NO configDir must not turn off the delete.+ registerClaudeAccountsSource(() => [{ id, label: 'm', createdAt: 0 } as ClaudeAccount])+ await call(IPC.claudeAccountsRemove, id)+ expect(existsSync(configDir)).toBe(false)+ })+})++describe('installHooksIntoLocalAccounts covers linked accounts', () => {+ it('installs into the linked dir, not into a managed dir that does not exist', () => {+ registerClaudeAccountsSource(() => [+ { id: 'linked', label: 'l', configDir: '/home/u/.claude-2', createdAt: 0 } as ClaudeAccount+ ])+ installHooksIntoLocalAccounts([{ id: 'linked' }, { id: 'managed' }])+ expect(installed).toEqual(['/home/u/.claude-2', accountConfigDir(userDataDir, 'managed')])+ })+})diff --git a/src/core/claude-accounts-service.ts b/src/core/claude-accounts-service.tsindex 1b8e0ec30..b0a33d69d 100644--- a/src/core/claude-accounts-service.ts+++ b/src/core/claude-accounts-service.ts@@ -2,19 +2,29 @@// (poll .claude.json), CLI version check, per-account hook install. The account LIST lives in// settings.json (renderer-owned via useSettings); this module only owns the filesystem.//-// Lives in core so BOTH shells serve it. Before this the four channels were registered only by+// Lives in core so BOTH shells serve it. Before this the channels were registered only by// src/main, so the Server Edition's bridge answered E_UNSUPPORTED for every one of them: a// browser-only deployment could select a managed account (env injection, transcript readers,// usage and the pickers are all core already) but could never CREATE, log into or remove one// (issue #313).import { randomUUID } from 'crypto'import { promises as fs } from 'fs'+import { homedir } from 'os'import path from 'path'import { execFile } from 'child_process'import { promisify } from 'util'import { IPC } from '../shared/ipc'-import { isSupportedClaudeVersion, parseLoginCapture } from './claude-accounts-core'-import { claudeConfigDirFor } from './claude-config-dir'+import {+ accountConfigDir,+ isSupportedClaudeVersion,+ normalizeLinkedConfigDir,+ parseLoginCapture+} from './claude-accounts-core'+import {+ claudeAccountsSnapshot,+ claudeConfigDirFor,+ linkedClaudeConfigDirFor+} from './claude-config-dir'import { installClaudeHooksInto, ensureClaudeFullscreenTuiInto } from './agents/hooks/claude'import { findInLoginPath } from './pty-manager'import { platform } from './platform'@@ -79,7 +89,7 @@ async function checkClaudeVersion(): Promise<boolean> {}}-/** Register the four `claude-accounts:*` channels on the core platform seam. */+/** Register the five `claude-accounts:*` channels on the core platform seam. */export function registerClaudeAccountsIpc(deps: ClaudeAccountsDeps = {}): void {const pollMs = deps.pollMs ?? LOGIN_POLL_MS// Resolve the live remote legs for a context, or null when the context is local / not connected.@@ -153,9 +163,94 @@ export function registerClaudeAccountsIpc(deps: ClaudeAccountsDeps = {}): void {await remote.r.remove(remote.projectId, id)return}- const configDir = claudeConfigDirFor(id) // id validation prevents traversal+ // LINKED account (design D4/§3): the directory is the USER's — `~/.claude-2` with their real+ // login in it — and removing the account only forgets the settings row (the renderer owns the+ // list). Forgetting is the whole operation here; `rm -rf` would delete a second Claude+ // identity the app never created.+ if (linkedClaudeConfigDirFor(id)) return+ // `accountConfigDir`, NOT `claudeConfigDirFor`: the resolver now answers with a LINKED dir for+ // a linked account, and the one call in this file that deletes recursively must be incapable+ // of naming anything but `{userData}/claude-accounts/<id>` — id-validated, as it always was.+ // The early return above is the behaviour; this line is the structural guarantee behind it.+ const configDir = accountConfigDir(platform().userDataDir, id)await fs.rm(configDir, { recursive: true, force: true })})++ /**+ * Link a PRE-EXISTING Claude config dir as an account (design D4; validation is §3 verbatim).+ * The renderer owns the settings list, so this returns the record and appends nothing itself.+ *+ * Every refusal is a distinct `Error` message because the Settings UI shows it: "that path does+ * not exist" and "that is already linked" need different fixes from the user, and one generic+ * "invalid config dir" would make the second one look like a typo in the first.+ */+ platform().handle(IPC.claudeAccountsLink, async (rawDir: string) => {+ if (typeof rawDir !== 'string' || !rawDir.trim()) {+ throw new Error('Enter the path to a Claude config directory.')+ }+ // `~` expansion is ours to do: the value is typed into a text field, not passed through a+ // shell, so nothing else would ever expand it — and `~/.claude-2` is exactly how the user+ // refers to the dir their own shell function exports.+ const typed = rawDir.trim()+ const expanded =+ typed === '~' || typed.startsWith('~/') ? path.join(homedir(), typed.slice(1)) : typed+ const configDir = normalizeLinkedConfigDir(expanded)+ if (!configDir) {+ throw new Error(`Not an absolute path: ${typed}`)+ }+ // The three STRING refusals run before the fs is touched at all. §3 lists exists/isDirectory+ // first, but the order here is deliberate: a path we are going to refuse on its shape alone is+ // a path we should not be stat'ing, and refusing `~/.claude` needs to say so even on a machine+ // where the dir has not been created yet ("no such directory" would be a misleading answer to+ // "why can't I link my system account?").+ if (configDir === normalizeLinkedConfigDir(path.join(homedir(), '.claude'))) {+ throw new Error('That is the system Claude config dir — it is already the default account.')+ }+ const managedRoot = normalizeLinkedConfigDir(+ path.join(platform().userDataDir, 'claude-accounts')+ )+ // Under the managed root ⇒ it is an account nodeterm created. Linking it would give one dir two+ // account ids, and the second one would be removable-without-delete while the first still+ // `rm -rf`s the same directory.+ if (managedRoot && (configDir === managedRoot || configDir.startsWith(managedRoot + path.sep))) {+ throw new Error('That is a nodeterm-managed account directory — add it with Add account.')+ }+ // Duplicate by NORMALIZED path, not by the string typed: `~/.claude-2/` and `/home/u/.claude-2`+ // are the same dir, and two rows for one dir would show two chips for one identity.+ for (const a of claudeAccountsSnapshot()) {+ if (!a.host && normalizeLinkedConfigDir(a.configDir) === configDir) {+ throw new Error(`That config dir is already linked (${a.label || a.email || a.id}).`)+ }+ }+ // EXISTS and IS A DIRECTORY, checked before anything is written into it. `stat`, not `lstat`:+ // a symlinked config dir is a normal way to keep one, and the target is what everything else+ // — the CLI, the jail, the transcript reader — resolves through.+ let isDir = false+ try {+ isDir = (await fs.stat(configDir)).isDirectory()+ } catch {+ throw new Error(`No such directory: ${configDir}`)+ }+ if (!isDir) throw new Error(`Not a directory: ${configDir}`)+ // The ONLY read of the dir's contents, and only after the user asked for this dir by name.+ // Missing / not-logged-in is `email: null`, NOT a failure (§3): linking a dir the user has not+ // signed into yet is legitimate — the CLI writes the email when they do.+ let email: string | null = null+ try {+ const raw = await fs.readFile(path.join(configDir, '.claude.json'), 'utf-8')+ email = parseLoginCapture(raw)?.email ?? null+ } catch {+ email = null+ }+ // Same two writes an ADDED account gets, so a linked account reports agent status from its+ // very next session. `installClaudeHooksInto` MERGES into an existing settings.json and writes+ // it back through `writeFileSync`, which follows a symlink — the two-profile layout where+ // `<dir>/settings.json` is a symlink into `~/.claude/` keeps its symlink and the shared target+ // gains the managed hook (pinned by test).+ installClaudeHooksInto(configDir)+ void ensureClaudeFullscreenTuiInto(configDir)+ return { id: randomUUID(), configDir, email }+ })}/**@@ -164,6 +259,12 @@ export function registerClaudeAccountsIpc(deps: ClaudeAccountsDeps = {}): void {* CLAUDE_CONFIG_DIR), so an app update's new hook version must reach them too. Best-effort per* account: one failing account must never block launch (matches installManagedAgentHooks'* fail-open). `extra` is the shell's per-account addition — desktop installs the canvas skill.+ *+ * LINKED accounts (`ClaudeAccount.configDir`) are covered by the same loop and need no branch:+ * they carry no `host`, and `claudeConfigDirFor` answers with the user's own dir — which is the+ * point, because an app update's new hook version has to reach `~/.claude-2` too or that identity+ * silently stops reporting agent status. The shells register the accounts source BEFORE calling+ * this, or the resolver would hand back a managed dir that does not exist for those rows.*/export function installHooksIntoLocalAccounts(accounts: readonly { id: string; host?: string }[],diff --git a/src/core/claude-config-dir.test.ts b/src/core/claude-config-dir.test.tsindex e032d7129..8989056a8 100644--- a/src/core/claude-config-dir.test.ts+++ b/src/core/claude-config-dir.test.ts@@ -1,10 +1,27 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest'import { initPlatform, resetPlatformForTests } from './platform'import { fakePlatform } from './platform-fake'-import { claudeConfigDirFor } from './claude-config-dir'+import {+ claudeConfigDirFor,+ claudeAccountsSnapshot,+ linkedClaudeConfigDirFor,+ linkedClaudeConfigDirs,+ registerClaudeAccountsSource,+ resetClaudeAccountsSourceForTests+} from './claude-config-dir'+import type { ClaudeAccount } from '../shared/types'++const acct = (over: Partial<ClaudeAccount> & { id: string }): ClaudeAccount => ({+ label: over.id,+ createdAt: 0,+ ...over+})beforeEach(() => initPlatform(fakePlatform({ userDataDir: '/tmp/ud' })))-afterEach(() => resetPlatformForTests())+afterEach(() => {+ resetPlatformForTests()+ resetClaudeAccountsSourceForTests()+})describe('claudeConfigDirFor', () => {// NOTE: the actual current signature in claude-accounts.ts is@@ -34,3 +51,82 @@ describe('claudeConfigDirFor', () => {expect(() => claudeConfigDirFor(undefined as unknown as string)).toThrow()})})++// ---- Linked accounts (design D4) ------------------------------------------------------------+//+// `claudeConfigDirFor` is THE resolver: env injection at spawn, the usage reader, the transcript+// roots and the mirror's account list all call it and nothing else. So the linked branch is added+// here rather than at seven call sites — and these cases are what keep the managed branch, and its+// id validation, exactly as it was.++describe('registerClaudeAccountsSource + claudeConfigDirFor', () => {+ it('with no source registered, every id resolves managed (bit-for-bit legacy)', () => {+ expect(claudeAccountsSnapshot()).toEqual([])+ expect(claudeConfigDirFor('abc')).toBe('/tmp/ud/claude-accounts/abc')+ expect(linkedClaudeConfigDirs()).toEqual([])+ })++ it('resolves a linked account to its own dir, and its neighbours to the managed root', () => {+ registerClaudeAccountsSource(() => [+ acct({ id: 'linked', configDir: '/home/u/.claude-2' }),+ acct({ id: 'managed' })+ ])+ expect(claudeConfigDirFor('linked')).toBe('/home/u/.claude-2')+ expect(claudeConfigDirFor('managed')).toBe('/tmp/ud/claude-accounts/managed')+ expect(linkedClaudeConfigDirFor('linked')).toBe('/home/u/.claude-2')+ expect(linkedClaudeConfigDirFor('managed')).toBeNull()+ })++ it('normalizes the stored value (trailing slash, `.`, an absorbable `..`)', () => {+ registerClaudeAccountsSource(() => [acct({ id: 'l', configDir: '/home/u/x/.././.claude-2/' })])+ expect(claudeConfigDirFor('l')).toBe('/home/u/.claude-2')+ })++ it('IGNORES a relative or `..`-bearing configDir → managed fallback, never something wider', () => {+ // settings.json is hand-edited; a relative value must not resolve against the process cwd,+ // and the safe default is the managed dir (which then hits the existing missing-dir warn ++ // system fallback at spawn).+ for (const bad of ['.claude-2', '../.claude-2', '', ' ', 42 as unknown as string]) {+ resetClaudeAccountsSourceForTests()+ registerClaudeAccountsSource(() => [acct({ id: 'l', configDir: bad })])+ expect(claudeConfigDirFor('l')).toBe('/tmp/ud/claude-accounts/l')+ expect(linkedClaudeConfigDirFor('l')).toBeNull()+ expect(linkedClaudeConfigDirs()).toEqual([])+ }+ })++ it('ignores a host-scoped or pending row (a linked dir is LOCAL and settled by definition)', () => {+ registerClaudeAccountsSource(() => [+ acct({ id: 'r', configDir: '/home/u/.claude-2', host: 'u@example' }),+ acct({ id: 'p', configDir: '/home/u/.claude-3', pending: true })+ ])+ expect(claudeConfigDirFor('r')).toBe('/tmp/ud/claude-accounts/r')+ expect(claudeConfigDirFor('p')).toBe('/tmp/ud/claude-accounts/p')+ expect(linkedClaudeConfigDirs()).toEqual([])+ })++ it('keeps the id validation even for a linked row (the one gate, not seven)', () => {+ registerClaudeAccountsSource(() => [acct({ id: '../escape', configDir: '/home/u/.claude-2' })])+ expect(() => claudeConfigDirFor('../escape')).toThrow(/invalid account id/)+ })++ it('a throwing settings source costs the linked answer, never the call', () => {+ // This runs on the hook-event hot path and from both jails: a settings store mid-write must+ // not take a 204 down with it, and "no linked accounts" is the safe direction.+ registerClaudeAccountsSource(() => {+ throw new Error('settings unreadable')+ })+ expect(claudeAccountsSnapshot()).toEqual([])+ expect(claudeConfigDirFor('abc')).toBe('/tmp/ud/claude-accounts/abc')+ expect(linkedClaudeConfigDirs()).toEqual([])+ })++ it('linkedClaudeConfigDirs dedupes two rows naming one dir', () => {+ registerClaudeAccountsSource(() => [+ acct({ id: 'a', configDir: '/home/u/.claude-2' }),+ acct({ id: 'b', configDir: '/home/u/.claude-2/' }),+ acct({ id: 'c', configDir: '/home/u/.claude-3' })+ ])+ expect(linkedClaudeConfigDirs()).toEqual(['/home/u/.claude-2', '/home/u/.claude-3'])+ })+})diff --git a/src/core/claude-config-dir.ts b/src/core/claude-config-dir.tsindex 1fbf295a1..3b087e3f4 100644--- a/src/core/claude-config-dir.ts+++ b/src/core/claude-config-dir.ts@@ -1,10 +1,84 @@-// Resolve a managed Claude account's config dir under this app's persistent state root.+// Resolve a Claude account's config dir under this app's persistent state root — or, for a LINKED+// account, the pre-existing dir the user already owns (`ClaudeAccount.configDir`, design D4).// The account LIST + login lifecycle live in main/claude-accounts.ts; this is just the// impure path resolution (needs the platform seam for userDataDir) split out so core// modules (pty-manager, etc.) can use it without importing electron.+//+// The linked half needs the account LIST, which core does not own — the settings store lives in+// each shell. So each shell REGISTERS a getter at boot (`registerClaudeAccountsSource`) and every+// account-aware reader keeps calling the one resolver it already called. One registration point+// rather than threading the list through pty-manager, the usage service, the transcript readers+// and both jails: a second copy of "where does this account's config live?" is exactly the drift+// CLAUDE.md warns about, and the answer moved for linked accounts.import { platform } from './platform'-import { accountConfigDir } from './claude-accounts-core'+import { accountConfigDir, normalizeLinkedConfigDir } from './claude-accounts-core'+import type { ClaudeAccount } from '../shared/types'++let accountsSource: (() => readonly ClaudeAccount[]) | undefined++/**+ * Register the shell's settings-backed account list. Called once at boot by BOTH shells+ * (`src/main/index.ts`, `src/server/index.ts`). Unregistered — a unit test, or a boot path that+ * runs before settings exist — means "no linked accounts", i.e. bit-for-bit the managed-only+ * behavior that predates this file's linked branch.+ */+export function registerClaudeAccountsSource(fn: () => readonly ClaudeAccount[]): void {+ accountsSource = fn+}++/** Drop the registration (tests only — the singleton outlives a test file otherwise). */+export function resetClaudeAccountsSourceForTests(): void {+ accountsSource = undefined+}++/**+ * The registered account list, or `[]`. Never throws: this is read on the hook-event hot path and+ * from both jails, and a settings store that throws mid-read must not take a 204 (or a transcript+ * read) down with it. A failed read yields "no linked accounts", which is the safe direction — it+ * can only make a dir read as unknown, never widen a jail.+ */+export function claudeAccountsSnapshot(): readonly ClaudeAccount[] {+ try {+ return accountsSource?.() ?? []+ } catch {+ return []+ }+}++/**+ * A linked account's validated config dir, or null when the id names no linked account. The value+ * is re-validated (absolute, normalized, no `..`) at THIS point of use — it comes from a+ * hand-editable settings.json — and an unusable one yields null, which sends every caller back to+ * the managed path (§3: "never something more destructive than the default").+ */+export function linkedClaudeConfigDirFor(accountId: string): string | null {+ for (const a of claudeAccountsSnapshot()) {+ if (a.id !== accountId || a.host || a.pending) continue+ return normalizeLinkedConfigDir(a.configDir)+ }+ return null+}++/**+ * Every linked account's config dir, for the two raw listeners' transcript jails. Local, settled+ * and re-validated (see above); deduped, because a hand-edited settings.json can name the same dir+ * twice and a duplicated jail root is a duplicated string compare, not a second permission.+ */+export function linkedClaudeConfigDirs(): string[] {+ const out: string[] = []+ for (const a of claudeAccountsSnapshot()) {+ if (a.host || a.pending) continue+ const dir = normalizeLinkedConfigDir(a.configDir)+ if (dir && !out.includes(dir)) out.push(dir)+ }+ return out+}export function claudeConfigDirFor(accountId: string): string {- return accountConfigDir(platform().userDataDir, accountId)+ // The managed path is resolved FIRST even for a linked account, because `accountConfigDir` is+ // what validates the id alphabet and it must stay the one gate: a hand-edited row pairing a+ // traversing id with a linked dir must not become the single place that id escapes the check+ // (every other path builder — local and remote — keys off the same alphabet).+ const managed = accountConfigDir(platform().userDataDir, accountId)+ return linkedClaudeConfigDirFor(accountId) ?? managed}diff --git a/src/core/transcript-index.ts b/src/core/transcript-index.tsindex c3714081f..5096c3a29 100644--- a/src/core/transcript-index.ts+++ b/src/core/transcript-index.ts@@ -7,7 +7,7 @@ import os from 'os'import path from 'path'import { platform } from './platform'import type { ClaudeAccount } from '../shared/types'-import { accountConfigDir } from './claude-accounts-core'+import { accountConfigDir, normalizeLinkedConfigDir } from './claude-accounts-core'import { SESSION_ID_RE } from './transcript-reader'import {extractEntryFields,@@ -37,7 +37,11 @@ function projectsRoots(): string[] {for (const acct of accountsGetter?.() ?? []) {if (acct.host || acct.pending) continuetry {- roots.push(path.join(accountConfigDir(userData, acct.id), 'projects'))+ // A LINKED account indexes the user's OWN dir (design D4). Re-validated here rather than+ // trusted — settings.json is hand-editable — and an unusable value falls back to the managed+ // path, which simply contributes an absent root.+ const dir = normalizeLinkedConfigDir(acct.configDir) ?? accountConfigDir(userData, acct.id)+ roots.push(path.join(dir, 'projects'))} catch {/* invalid account id → skip that root (fail-open) */}diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.tsindex fb9bfd39c..d50278de9 100644--- a/src/core/transcript-reader.ts+++ b/src/core/transcript-reader.ts@@ -6,6 +6,7 @@ import os from 'os'import path from 'path'import type { TranscriptLine, ChatMessage, ChatPart } from '../shared/types'import { transcriptRootFor } from './claude-accounts-core'+import { linkedClaudeConfigDirFor } from './claude-config-dir'import { platform } from './platform'// Transcript root for a managed account (its `projects` dir) or the system default@@ -14,7 +15,12 @@ import { platform } from './platform'// (and only for the account branch) so this module — and its vitest test — stays electron-free.function transcriptRoot(accountId?: string): string {const userData = accountId ? platform().userDataDir : null- return transcriptRootFor(os.homedir(), userData, accountId)+ // A LINKED account's transcripts live in the dir the USER owns (`~/.claude-2/projects`), not+ // under `{userData}`. Resolved through the registry so this — and with it `resolveTranscriptPath`,+ // `readSessionName`, `transcriptPathForCwd`, and therefore handoff/locate, agent-session-name,+ // context-link and the session-name sweep — is the ONE place the answer moved.+ const linked = accountId ? linkedClaudeConfigDirFor(accountId) : null+ return transcriptRootFor(os.homedir(), userData, accountId, linked ?? undefined)}// Only read the last ~5 MB of a transcript so a very large session can't block the maindiff --git a/src/main/index.ts b/src/main/index.tsindex c1c25498a..6ed272225 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -242,7 +242,11 @@ import { codexUsageAccounts } from '../core/codex-accounts-core'import { codexHomeFor } from '../core/codex-config-dir'import { loadOrCreateNodeAuthSecret } from '../core/agents/node-auth-secret'import { initNodeTokens, refreshNodeTokens } from '../core/agents/node-token-service'-import { claudeConfigDirFor } from '../core/claude-config-dir'+import {+ claudeConfigDirFor,+ linkedClaudeConfigDirs,+ registerClaudeAccountsSource+} from '../core/claude-config-dir'import {isSafeLocalTranscriptPath,isSafeRemoteTranscriptPath,@@ -1162,6 +1166,15 @@ app.whenReady().then(async () => {})settingsStore.init()+ // The linked-account resolver's one source of truth on this shell (design D4). Registered as+ // soon as settings exist — not down beside `initTranscriptIndex`, where the other account wiring+ // sits — because EVERY config-dir resolution has to be able to see it, including the earliest:+ // the mirror settings provider is a lazy callback and an agent-status flush can fire from the+ // `claudeCliCaps()` probe before boot reaches that point. An unregistered source means "no+ // linked accounts", so such a flush would advertise a managed dir that does not exist for a+ // linked row, and the phone would launch under it. The Server Edition registers the identical+ // getter at the same point in its own boot.+ registerClaudeAccountsSource(() => settingsStore.get().claudeAccounts ?? [])const gatewayCredentials = new ModelGatewayCredentialService(new ElectronSecretStore(app.getPath('userData'), safeStorage, MODEL_GATEWAY_SECRET_FILE))@@ -2578,7 +2591,16 @@ app.whenReady().then(async () => {const abs = resolve(tp)// codexHome() honors $CODEX_HOME — a relocated codex (the snap-codex case this project has hit// before) would otherwise fail the jail and its meter would silently never fill.- return isSafeLocalTranscriptPath(abs, homedir(), app.getPath('userData'), codexHome())+ // Linked accounts' dirs come from SETTINGS, never from the POST — `<dir>/projects/**` only,+ // so `~/.claude-2/.ssh` is as refused as it ever was. Without them the meter and the subagent+ // cards silently never fill for a pane running the user's own CLAUDE_CONFIG_DIR.+ return isSafeLocalTranscriptPath(+ abs,+ homedir(),+ app.getPath('userData'),+ codexHome(),+ linkedClaudeConfigDirs()+ )? abs: undefined}diff --git a/src/server/agent-status.test.ts b/src/server/agent-status.test.tsindex c782dc737..b84421b31 100644--- a/src/server/agent-status.test.ts+++ b/src/server/agent-status.test.ts@@ -6,6 +6,10 @@ import { ServerPlatform } from './platform-server'import { wireAgentStatus } from './agent-status'import { _resetForTest } from '../core/agent-status-mirror'import { forgetGrokSession, grokSessionDirFor, readGrokSessionName } from '../core/grok-session'+import {+ registerClaudeAccountsSource,+ resetClaudeAccountsSourceForTests+} from '../core/claude-config-dir'import { IPC } from '../shared/ipc'import { decodePtyData } from '../shared/rpc'@@ -73,6 +77,7 @@ beforeEach(() => {})afterEach(() => {fs.rmSync(dir, { recursive: true, force: true })+ resetClaudeAccountsSourceForTests()_resetForTest()})@@ -264,6 +269,56 @@ describe('wireAgentStatus', () => {})})+// The transcript jail on THIS shell, and the linked half of it (design D4 / §3). Both raw+// listeners have to learn the same widening or the Server Edition silently keeps the pre-fix+// behavior for a pane running the user's own `CLAUDE_CONFIG_DIR` — the "both raw listeners change+// together" rule, which this repo has broken three times.+describe('wireAgentStatus — the transcript jail admits LINKED config dirs', () => {+ it('tracks a transcript under <linkedDir>/projects, and refuses everything else in that dir', () => {+ const linked = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-linked-jail-'))+ try {+ registerClaudeAccountsSource(() => [+ { id: 'linked-1', label: 'second', configDir: linked, createdAt: 0 }+ ])+ const fh = fakeHooks()+ const ctx = recTail()+ wireAgentStatus(platform, { hooks: fh.hooks as never, contextTail: ctx.tail as never })+ const ok = path.join(linked, 'projects', '-repo', 's1.jsonl')+ fh.fireRaw('claude', 'n1', {+ hook_event_name: 'PreToolUse',+ tool_name: 'Read',+ session_id: 's1',+ transcript_path: ok+ })+ expect(ctx.calls.some((c) => c.m === 'track' && c.args[1] === ok)).toBe(true)+ // The linked dir is not opened up wholesale: the segment after it must be `projects`.+ const before = ctx.calls.length+ fh.fireRaw('claude', 'n2', {+ hook_event_name: 'PreToolUse',+ tool_name: 'Read',+ session_id: 's2',+ transcript_path: path.join(linked, '.ssh', 'id_rsa')+ })+ expect(ctx.calls.length).toBe(before)+ } finally {+ fs.rmSync(linked, { recursive: true, force: true })+ }+ })++ it('refuses that same path when the dir is NOT in settings (the jail reads settings, not the POST)', () => {+ const fh = fakeHooks()+ const ctx = recTail()+ wireAgentStatus(platform, { hooks: fh.hooks as never, contextTail: ctx.tail as never })+ fh.fireRaw('claude', 'n1', {+ hook_event_name: 'PreToolUse',+ tool_name: 'Read',+ session_id: 's1',+ transcript_path: path.join(os.tmpdir(), 'not-linked', 'projects', 's1.jsonl')+ })+ expect(ctx.calls.filter((c) => c.m === 'track' && c.args[1] !== undefined)).toEqual([])+ })+})+/*** The grok branch of the raw listener (`src/server/agent-status.ts`) had no coverage at all: a* mutation to `if (false && agentId === 'grok')` left the whole suite green. It is the only placediff --git a/src/server/agent-status.ts b/src/server/agent-status.tsindex 16c66be94..f5a172b68 100644--- a/src/server/agent-status.ts+++ b/src/server/agent-status.ts@@ -21,6 +21,7 @@ import { createCodexSubagentFormatter } from '../core/codex-subagent-format'import { codexHome } from '../core/usage/codex-usage'import { setNodeTranscript } from '../core/context-link'import { isSafeLocalTranscriptPath } from '../core/claude-accounts-core'+import { linkedClaudeConfigDirs } from '../core/claude-config-dir'import { grokRawFields, isAsyncSubagentLaunch, type NormalizedAgentEvent } from '../shared/agents/normalize'import { grokSessionDir, grokSessionsDir } from '../core/agents/grok-paths'import { forgetGrokSession, rememberGrokSessionDir } from '../core/grok-session'@@ -162,7 +163,16 @@ export function wireAgentStatus(const abs = resolve(tp)// codexHome() honors $CODEX_HOME — a relocated codex (the snap-codex case this project has hit// before) would otherwise fail the jail and its meter would silently never fill.- return isSafeLocalTranscriptPath(abs, homedir(), platform.userDataDir, codexHome())+ // Linked accounts' dirs come from SETTINGS, never from the POST — `<dir>/projects/**` only,+ // so `~/.claude-2/.ssh` is as refused as it ever was. Without them the meter and the subagent+ // cards silently never fill for a pane running the user's own CLAUDE_CONFIG_DIR.+ return isSafeLocalTranscriptPath(+ abs,+ homedir(),+ platform.userDataDir,+ codexHome(),+ linkedClaudeConfigDirs()+ )? abs: undefined}diff --git a/src/server/index.ts b/src/server/index.tsindex 7d889135a..d6f2db932 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -84,7 +84,7 @@ import { startSessionMemoryService, sshScopePredicate } from '../core/session-meimport { createMemoryPressureMonitor } from '../core/memory-pressure'import { createPtyPressureMonitor } from '../core/pty-pressure'import { claudeCliCaps, type ClaudeCliCaps } from '../core/claude-cli'-import { claudeConfigDirFor } from '../core/claude-config-dir'+import { claudeConfigDirFor, registerClaudeAccountsSource } from '../core/claude-config-dir'import { presenceHub } from '../core/presence/hub'import { initCanvasSync } from '../core/canvas-sync'import { wireAgentStatus } from './agent-status'@@ -186,6 +186,12 @@ export async function startServer(const workspaceStore = new WorkspaceStore()settingsStore.init()+ // The linked-account resolver's one source of truth on this shell (design D4). Registered as+ // soon as settings exist and BEFORE anything that resolves a config dir — the mirror settings+ // provider, `installHooksIntoLocalAccounts`, the transcript jail — because an unregistered+ // source means "no linked accounts", i.e. a linked row would resolve to a managed dir that does+ // not exist. The desktop registers the identical getter next to `initTranscriptIndex`.+ registerClaudeAccountsSource(() => settingsStore.get().claudeAccounts ?? [])const gatewayCredentials = new ModelGatewayCredentialService(new ServerSecretStore(config.dataDir, MODEL_GATEWAY_SECRET_FILE))