Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(accounts): whole-branch review fixes (jail, retry-by-host, search, index, badge)
enes1322764c59ed
diff --git a/src/main/claude-accounts-core.test.ts b/src/main/claude-accounts-core.test.tsindex 343f58f8d..bed50ea46 100644--- a/src/main/claude-accounts-core.test.ts+++ b/src/main/claude-accounts-core.test.ts@@ -9,7 +9,8 @@ import {accountTmuxEnvArgs,parseLoginCapture,isSupportedClaudeVersion,- transcriptRootFor+ transcriptRootFor,+ isSafeLocalTranscriptPath} from './claude-accounts-core'describe('accountConfigDir', () => {@@ -142,3 +143,38 @@ describe('isSupportedClaudeVersion', () => {expect(isSupportedClaudeVersion('garbage')).toBe(false) // unparseable → unsupported (warn)})})++describe('isSafeLocalTranscriptPath', () => {+ const home = '/Users/x'+ const ud = '/Users/x/Library/Application Support/nodeterm'+ const legacy = '/Users/x/.claude/projects'+ const acctRoot = `${ud}/claude-accounts`++ it('accepts the legacy system root and paths under it', () => {+ expect(isSafeLocalTranscriptPath(legacy, home, ud)).toBe(true)+ expect(isSafeLocalTranscriptPath(`${legacy}/-repo/abc.jsonl`, home, ud)).toBe(true)+ })+ it('accepts a valid account transcript root and paths under it', () => {+ expect(isSafeLocalTranscriptPath(`${acctRoot}/a1/projects`, home, ud)).toBe(true)+ expect(isSafeLocalTranscriptPath(`${acctRoot}/a1/projects/-repo/s.jsonl`, home, ud)).toBe(true)+ expect(isSafeLocalTranscriptPath(`${acctRoot}/A1_b-2/projects/x.jsonl`, home, ud)).toBe(true)+ })+ it('rejects a `..` escape out of the accounts root', () => {+ // Callers pass an already-resolved path; a resolved traversal lands elsewhere entirely.+ expect(isSafeLocalTranscriptPath('/Users/x/.ssh/id_rsa', home, ud)).toBe(false)+ expect(isSafeLocalTranscriptPath(`${ud}/hook-endpoint.env`, home, ud)).toBe(false)+ })+ it('rejects an invalid account-id segment', () => {+ expect(isSafeLocalTranscriptPath(`${acctRoot}/../evil/projects/x`, home, ud)).toBe(false)+ expect(isSafeLocalTranscriptPath(`${acctRoot}/a.b/projects/x`, home, ud)).toBe(false)+ })+ it('rejects a non-projects subpath under a valid account', () => {+ expect(isSafeLocalTranscriptPath(`${acctRoot}/a1/.credentials.json`, home, ud)).toBe(false)+ expect(isSafeLocalTranscriptPath(`${acctRoot}/a1`, home, ud)).toBe(false)+ expect(isSafeLocalTranscriptPath(acctRoot, home, ud)).toBe(false)+ })+ it('rejects a sibling-prefix root (…/projects-evil)', () => {+ expect(isSafeLocalTranscriptPath(`${legacy}-evil/x.jsonl`, home, ud)).toBe(false)+ expect(isSafeLocalTranscriptPath(`${acctRoot}/a1/projects-evil/x`, home, ud)).toBe(false)+ })+})diff --git a/src/main/claude-accounts-core.ts b/src/main/claude-accounts-core.tsindex 36f02092a..bc2f2c02d 100644--- a/src/main/claude-accounts-core.ts+++ b/src/main/claude-accounts-core.ts@@ -56,6 +56,32 @@ export function transcriptRootFor(: path.join(homeDir, '.claude', 'projects')}+/**+ * Jail predicate for a hook-reported LOCAL `transcript_path`: hook POSTs can arrive over the+ * remote reverse tunnel, so a forged POST must not make the app read an arbitrary local file.+ * Legitimate local transcripts live under exactly two roots:+ * - the system default `~/.claude/projects`, and+ * - a managed account's `{userData}/claude-accounts/<accountId>/projects`.+ * For the account root the `<accountId>` segment is validated with `ACCOUNT_ID_RE` (dots barred,+ * so `..` can never sneak in) and the very next segment must be `projects` — a prefix match on+ * `{userData}/claude-accounts` alone is NOT enough (it would accept `…/claude-accounts/x/.ssh`).+ * `abs` must already be resolved/normalized by the caller (e.g. `path.resolve(tp)`).+ */+export function isSafeLocalTranscriptPath(+ abs: string,+ homeDir: string,+ userDataPath: string+): boolean {+ const legacyRoot = path.join(homeDir, '.claude', 'projects')+ if (abs === legacyRoot || abs.startsWith(legacyRoot + 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 normalized+ // and confirmed under `accountsRoot`, `path.relative` yields no leading `..`.+ const segs = path.relative(accountsRoot, abs).split(path.sep)+ return segs.length >= 2 && ACCOUNT_ID_RE.test(segs[0]) && segs[1] === 'projects'+}+/*** Claude Code ≥ 2.1 scopes its macOS Keychain service name per config dir:* 'Claude Code-credentials-' + first 8 hex chars of sha256(CLAUDE_CONFIG_DIR).diff --git a/src/main/index.ts b/src/main/index.tsindex 33310bab7..bff97d7da 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,4 +1,4 @@-import { join, resolve, sep, posix } from 'path'+import { join, resolve, posix } from 'path'import { homedir } from 'os'import { randomUUID } from 'crypto'import { app, BrowserWindow, dialog, ipcMain, Notification, shell } from 'electron'@@ -43,6 +43,7 @@ import { initTelemetry } from './telemetry'import { initClaudeUsage } from './claude-usage'import { initLicense } from './license'import { initClaudeAccounts, claudeConfigDirFor } from './claude-accounts'+import { isSafeLocalTranscriptPath } from './claude-accounts-core'import { installClaudeHooksInto } from './agents/hooks/claude'import { initRemoteHost } from './remote/host-service'import { initRemoteClient } from './remote/client-service'@@ -494,13 +495,18 @@ app.whenReady().then(async () => {const REMOTE_TRANSCRIPT_CAP = 5 * 1024 * 1024ipcMain.handle(IPC.claudeReadTranscript,- async (_e, sessionId: string | undefined, cwd: string | undefined) => {+ async (+ _e,+ sessionId: string | undefined,+ cwd: string | undefined,+ accountId: string | undefined+ ) => {const ref = sessionId ? remoteTranscriptBySession.get(sessionId) : undefinedif (ref) {const text = await remoteFile.readTail(ref, REMOTE_TRANSCRIPT_CAP)return parseTranscriptLines(text)}- const p = await resolveTranscript(sessionId, cwd)+ const p = await resolveTranscript(sessionId, cwd, accountId)return p ? readTranscriptLines(p) : []})@@ -523,18 +529,21 @@ app.whenReady().then(async () => {})- initTranscriptIndex()+ initTranscriptIndex(() => settingsStore.get().claudeAccounts ?? [])ipcMain.handle(IPC.transcriptSearch, (_e, query: string) => searchTranscripts(query))// Populate the context meter without a live hook event: the renderer calls this on mount// (the continuing session may be idle after a restart). Track under the sessionId (the key// the meter looks up); cwd is only a path fallback. contextTail.track reads immediately and// the 1s interval keeps it fresh while tracked.- ipcMain.on(IPC.contextEnsure, async (_e, sessionId?: string, cwd?: string) => {- if (!sessionId || !SESSION_ID_RE.test(sessionId)) return- let p = contextTail.pathFor(sessionId) ?? (await resolveTranscriptPath(sessionId))- if (!p && cwd) p = await transcriptPathForCwd(cwd)- if (p) contextTail.track(sessionId, p)- })+ ipcMain.on(+ IPC.contextEnsure,+ async (_e, sessionId?: string, cwd?: string, accountId?: string) => {+ if (!sessionId || !SESSION_ID_RE.test(sessionId)) return+ let p = contextTail.pathFor(sessionId) ?? (await resolveTranscriptPath(sessionId, accountId))+ if (!p && cwd) p = await transcriptPathForCwd(cwd)+ if (p) contextTail.track(sessionId, p)+ }+ )ipcMain.handle(IPC.handoffBuild,(@@ -571,14 +580,15 @@ app.whenReady().then(async () => {// Security: hook POSTs now arrive over the remote reverse tunnel too (SSH Phase 2a), so a// forged/remote POST could set transcript_path to an arbitrary LOCAL path (e.g. ~/.ssh/id_rsa)// and have the app read it. The tails read the LOCAL filesystem; legitimate LOCAL transcripts- // always live under ~/.claude/projects. Phase 2a does NOT tail remote transcripts (that's 2b),- // so we jail transcript_path to that root and skip the read otherwise. Returns the path only- // when it resolves under the projects root.- const TRANSCRIPT_ROOT = join(homedir(), '.claude', 'projects')+ // live under the system default `~/.claude/projects` OR a managed account's+ // `{userData}/claude-accounts/<id>/projects` (id-validated so a forged POST can't traverse out+ // — see isSafeLocalTranscriptPath). Phase 2a does NOT tail remote transcripts (that's 2b), so we+ // jail transcript_path to those roots and skip the read otherwise. Returns the path only when it+ // resolves under an allowed root.const safeTranscriptPath = (tp: string | undefined): string | undefined => {if (!tp) return undefinedconst abs = resolve(tp)- return abs === TRANSCRIPT_ROOT || abs.startsWith(TRANSCRIPT_ROOT + sep) ? abs : undefined+ return isSafeLocalTranscriptPath(abs, homedir(), app.getPath('userData')) ? abs : undefined}// Remote analogue of safeTranscriptPath: a remote node's transcript_path is a remote absolute// path arriving over the reverse tunnel — a forged POST must not read an arbitrary remote file.diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.tsindex 42d14e035..4bbed714a 100644--- a/src/main/pty-manager.ts+++ b/src/main/pty-manager.ts@@ -191,6 +191,9 @@ interface Session {sshRemote?: NonNullable<PtyCreateOptions['sshRemote']>/** Output arrived since the last scrollback snapshot — idle sessions skip the capture. */outputSinceSnapshot: boolean+ /** True when this node had an `accountId` but its config dir was gone at spawn, so we fell back+ * to the system account. `create()` surfaces it to the renderer (warning chip). */+ accountFallback?: boolean}/** Sinks for a detached session whose output is served somewhere other than the renderer@@ -333,7 +336,9 @@ export class PtyManager {// so the session env below picks it up — awaiting keeps the event loop free either way.await resolveShellPath()const sessionId = this.spawnSession(options, webContentsId, undefined)- return { sessionId, fresh }+ // Surface a missing-account-dir fallback so the renderer can flag the node's account chip.+ const accountFallback = this.sessions.get(sessionId)?.accountFallback+ return accountFallback ? { sessionId, fresh, accountFallback } : { sessionId, fresh }}/** Does the node's remote tmux session exist (over the project's ControlMaster)? Async so the@@ -492,9 +497,12 @@ export class PtyManager {options.accountId && !options.sshRemote ? claudeConfigDirFor(options.accountId) : null// Missing/deleted account dir (spec: error handling) → fall back to system default// instead of pointing claude at a dead dir; the node then behaves like an unbound one.+ // `accountFallback` is surfaced to the renderer (warning chip) via the create() result.+ let accountFallback = falseif (accountDir && !fs.existsSync(accountDir)) {console.warn(`[accounts] config dir missing for ${options.accountId}, using system default`)accountDir = null+ accountFallback = true}if (accountDir) {env.CLAUDE_CONFIG_DIR = accountDir@@ -653,7 +661,8 @@ export class PtyManager {flushTimer: null,persistKey: persisted ? options.persistKey : undefined,sshRemote: remote,- outputSinceSnapshot: true // capture the initial screen on the first tick+ outputSinceSnapshot: true, // capture the initial screen on the first tick+ accountFallback}if (persisted) this.ensureSnapshotTimer()this.sessions.set(sessionId, session)diff --git a/src/main/transcript-index.ts b/src/main/transcript-index.tsindex da8ac068d..50fbcf963 100644--- a/src/main/transcript-index.ts+++ b/src/main/transcript-index.ts@@ -1,10 +1,13 @@-// Background index of all Claude session transcripts under ~/.claude/projects. Built on-// launch + refreshed every 5 min, incrementally by mtime, and persisted to userData so a-// relaunch doesn't cold re-scan. Search runs in-memory over the index. Read-only and local.+// Background index of all Claude session transcripts under ~/.claude/projects AND every managed+// LOCAL account's {userData}/claude-accounts/<id>/projects. Built on launch + refreshed every 5+// min, incrementally by mtime, and persisted to userData so a relaunch doesn't cold re-scan.+// Search runs in-memory over the index. Read-only and local.import fs from 'fs'import os from 'os'import path from 'path'import { app } from 'electron'+import type { ClaudeAccount } from '../shared/types'+import { accountConfigDir } from './claude-accounts-core'import { SESSION_ID_RE } from './transcript-reader'import {extractEntryFields,@@ -20,42 +23,57 @@ const READ_CAP_BYTES = 5 * 1024 * 1024 // mirror transcript-reader: never read mlet entries: TranscriptIndexEntry[] = []let timer: NodeJS.Timeout | undefined+let accountsGetter: (() => ClaudeAccount[]) | undefinedfunction indexFilePath(): string {return path.join(app.getPath('userData'), 'transcript-index.json')}-function projectsRoot(): string {- return path.join(os.homedir(), '.claude', 'projects')+// Every LOCAL transcript root to index: the system default plus each managed LOCAL account's+// projects dir. Remote accounts (a `host` set) live on another host's fs → not scanned here.+function projectsRoots(): string[] {+ const roots = [path.join(os.homedir(), '.claude', 'projects')]+ const userData = app.getPath('userData')+ for (const acct of accountsGetter?.() ?? []) {+ if (acct.host || acct.pending) continue+ try {+ roots.push(path.join(accountConfigDir(userData, acct.id), 'projects'))+ } catch {+ /* invalid account id → skip that root (fail-open) */+ }+ }+ return roots}-// Walk ~/.claude/projects/*/ for <sessionId>.jsonl, returning {sessionId, path, mtime}.+// Walk each root's <projectDir>/<sessionId>.jsonl, returning {sessionId, path, mtime}. Fail-open+// per root (a missing/unreadable account dir just contributes nothing).async function scanTranscripts(): Promise<ScanFile[]> {- const root = projectsRoot()const out: ScanFile[] = []- let dirs: string[]- try {- dirs = await fs.promises.readdir(root)- } catch {- return out- }- for (const d of dirs) {- let files: string[]+ for (const root of projectsRoots()) {+ let dirs: string[]try {- files = await fs.promises.readdir(path.join(root, d))+ dirs = await fs.promises.readdir(root)} catch {continue}- for (const f of files) {- if (!f.endsWith('.jsonl')) continue- const sessionId = f.slice(0, -'.jsonl'.length)- if (!SESSION_ID_RE.test(sessionId)) continue- const p = path.join(root, d, f)+ for (const d of dirs) {+ let files: string[]try {- const st = await fs.promises.stat(p)- out.push({ sessionId, transcriptPath: p, mtime: Math.floor(st.mtimeMs) })+ files = await fs.promises.readdir(path.join(root, d))} catch {- /* skip */+ continue+ }+ for (const f of files) {+ if (!f.endsWith('.jsonl')) continue+ const sessionId = f.slice(0, -'.jsonl'.length)+ if (!SESSION_ID_RE.test(sessionId)) continue+ const p = path.join(root, d, f)+ try {+ const st = await fs.promises.stat(p)+ out.push({ sessionId, transcriptPath: p, mtime: Math.floor(st.mtimeMs) })+ } catch {+ /* skip */+ }}}}@@ -130,7 +148,8 @@ export function searchTranscripts(query: string): TranscriptHit[] {return searchEntries(entries, query)}-export function initTranscriptIndex(): void {+export function initTranscriptIndex(getAccounts?: () => ClaudeAccount[]): void {+ accountsGetter = getAccountsentries = loadPersisted()void refresh()timer = setInterval(() => void refresh(), TRANSCRIPT_INDEX_REFRESH_MS)diff --git a/src/preload/index.ts b/src/preload/index.tsindex 94ff3b851..ce39710b4 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -252,11 +252,12 @@ const api: NodeTerminalApi = {ipcRenderer.on(IPC.contextUpdate, handler)return () => ipcRenderer.removeListener(IPC.contextUpdate, handler)},- ensure: (sessionId, cwd) => ipcRenderer.send(IPC.contextEnsure, sessionId, cwd)+ ensure: (sessionId, cwd, accountId) =>+ ipcRenderer.send(IPC.contextEnsure, sessionId, cwd, accountId)},claude: {- readTranscript: (sessionId, cwd) =>- ipcRenderer.invoke(IPC.claudeReadTranscript, sessionId, cwd)+ readTranscript: (sessionId, cwd, accountId) =>+ ipcRenderer.invoke(IPC.claudeReadTranscript, sessionId, cwd, accountId)},chat: {readTranscript: (sessionId, cwd, accountId) =>diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 14c8fa3e8..6938156c1 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -111,6 +111,7 @@ import { useSshConn } from '../state/sshConn'import { requireProOr } from '../state/upgradeGate'import { useEntitlement } from '../state/entitlement'import type { SshServer } from '@shared/ssh'+import { sshHostKey } from '@shared/ssh'import type { SshProjectStatus, TranscriptHit } from '@shared/types'import {applyCanvasMutation,@@ -1350,14 +1351,27 @@ export function Canvas() {// to open a terminal node running `claude /login` under the new account's config dir.useEffect(() => {const onAddAccountLogin = (ev: Event): void => {- const detail = (ev as CustomEvent<{ accountId: string; remote?: boolean }>).detail+ const detail = (ev as CustomEvent<{ accountId: string; remote?: boolean; host?: string }>)+ .detailconst accountId = detail?.accountIdif (!accountId) return- // A REMOTE account (added inside an SSH project) logs in ON THE HOST: stamp the login node- // with the active project's ssh binding so `claude /login` runs in remote tmux under the- // remote account dir. Local accounts omit it (login runs locally).- const project = useProjects.getState().getProject(activeProjectId)- const ssh = detail?.remote ? project?.ssh : undefined+ // A REMOTE account logs in ON ITS HOST: resolve the ssh binding BY HOST (from the event),+ // NOT from the active project — Retry can fire from any project, so the active one may be+ // local or a different host. Match against CONNECTED projects only (live ControlMaster in+ // useSshConn). If none matches, do NOT spawn a node: a local `claude /login` would mutate the+ // user's SYSTEM ~/.claude login while waitLogin polls the remote host forever.+ let ssh: ReturnType<typeof useProjects.getState>['projects'][number]['ssh']+ if (detail?.remote) {+ const host = detail.host+ const conn = useSshConn.getState().byProject+ const project = host+ ? useProjects+ .getState()+ .projects.find((p) => p.ssh && sshHostKey(p.ssh.server) === host && conn[p.id])+ : undefined+ if (!project) return // defensive: mismatched/disconnected remote login — never spawn locally+ ssh = project.ssh+ }setNodes((ns) => [...ns.map((n) => ({ ...n, selected: false })),{ ...createAccountLoginNode(accountId, ns.length, viewCenter(), ssh), selected: true }@@ -1366,7 +1380,8 @@ export function Canvas() {}window.addEventListener('nodeterm:add-account-login', onAddAccountLogin)return () => window.removeEventListener('nodeterm:add-account-login', onAddAccountLogin)- }, [setNodes, markDirty, viewCenter, activeProjectId])+ // Resolves the ssh binding by host at fire time (reads stores directly), so no project dep.+ }, [setNodes, markDirty, viewCenter])// When an account is removed in Settings, clear it off the ACTIVE project's live nodes (the// projects store only holds the other projects' serialized copies). Referencing nodes falldiff --git a/src/renderer/components/settings/sections/AccountsSection.tsx b/src/renderer/components/settings/sections/AccountsSection.tsxindex 383164012..afc46f2fe 100644--- a/src/renderer/components/settings/sections/AccountsSection.tsx+++ b/src/renderer/components/settings/sections/AccountsSection.tsx@@ -3,6 +3,7 @@ import type { ClaudeAccount } from '@shared/types'import { sshHostKey } from '@shared/ssh'import { useSettings } from '../../../state/settings'import { useProjects } from '../../../state/projects'+import { useSshConn } from '../../../state/sshConn'import { ConfirmDialog } from '../../ConfirmDialog'import { SettingsSection } from '../SettingsSection'import { SearchableRow } from '../SearchableRow'@@ -43,6 +44,9 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.// The active project's SSH host key (`user@host`), when it's a connected SSH project. Present →// the "Add account" control also offers adding an account ON that host.const activeHostKey = activeProject?.ssh ? sshHostKey(activeProject.ssh.server) : undefined+ // Subscribe to live SSH connections so a remote account's Retry button enables/disables as its+ // host connects/disconnects while this panel is open.+ const sshByProject = useSshConn((s) => s.byProject)const [versionWarning, setVersionWarning] = useState(false)const [pendingRemove, setPendingRemove] = useState<ClaudeAccount | null>(null)@@ -56,6 +60,14 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.return useProjects.getState().projects.find((p) => p.ssh && sshHostKey(p.ssh.server) === host)?.id}+ // A remote account can only log in on a CONNECTED matching-host project (live ControlMaster in+ // useSshConn). Undefined when the account is remote but no such project is currently connected —+ // Retry is then disabled so `claude /login` never runs against the local system account.+ const connectedProjectIdForHost = (host?: string): string | undefined => {+ const id = projectIdForHost(host)+ return id && sshByProject[id] ? id : undefined+ }+// Open a login terminal for an account and wait (up to ~5 min) for the CLI to write its// credentials; on success flip the row out of `pending` and adopt the captured email. A remote// account (`host` set) logs in on its host: the login node runs in remote tmux and waitLogin polls@@ -63,8 +75,12 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.const runLogin = async (account: Pick<ClaudeAccount, 'id' | 'host'>): Promise<void> => {const remote = !!account.hostconst projectId = remote ? projectIdForHost(account.host) : undefined+ // Carry `host` so Canvas resolves the ssh binding BY HOST (among connected projects), not from+ // whatever project happens to be active when Retry fires.window.dispatchEvent(- new CustomEvent('nodeterm:add-account-login', { detail: { accountId: account.id, remote } })+ new CustomEvent('nodeterm:add-account-login', {+ detail: { accountId: account.id, remote, host: account.host }+ }))const captured = await window.nodeTerminal.claudeAccounts.waitLogin(account.id,@@ -198,9 +214,27 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.) : null}</div><div className="flex shrink-0 items-center gap-2">- {account.pending ? (- <Button onClick={() => void runLogin(account)}>Retry login</Button>- ) : null}+ {account.pending+ ? (() => {+ // A remote account can only retry login on a connected matching-host+ // project; without one, disable Retry (a local spawn would log into the+ // system account instead of the remote host).+ const blocked = !!account.host && !connectedProjectIdForHost(account.host)+ return (+ <Button+ disabled={blocked}+ title={+ blocked+ ? `Connect to ${account.host} to finish logging in`+ : undefined+ }+ onClick={() => void runLogin(account)}+ >+ Retry login+ </Button>+ )+ })()+ : null}<Buttonvariant="ghost"aria-label="Remove account"diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 3a851b63b..d12638141 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -188,11 +188,15 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN// re-fed. Re-runs if the sessionId changes (track is idempotent). cwd is a path fallback.useEffect(() => {const sid = status?.sessionId- if (showUsage && sid) window.nodeTerminal.context.ensure(sid, (data.cwd as string) || undefined)- }, [showUsage, status?.sessionId, data.cwd])+ if (showUsage && sid)+ window.nodeTerminal.context.ensure(sid, (data.cwd as string) || undefined, data.accountId)+ }, [showUsage, status?.sessionId, data.cwd, data.accountId])const updateNodeInternals = useUpdateNodeInternals()const [searchOpen, setSearchOpen] = useState(false)+ // Set when the session fell back to the system account because this node's account folder was+ // missing at spawn (Task 3 fallback) — flags the account chip with a warning tint + tooltip.+ const [accountFallback, setAccountFallback] = useState(false)// Stable fallback reader: serialize the live xterm buffer when tmux capture is unavailable.const readBuffer = useCallback(() => {@@ -209,6 +213,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNnodeId: id,sessionId: status?.sessionId,cwd: data.cwd as string | undefined,+ accountId: data.accountId,searchTranscript: showUsage,open: searchOpen,readBuffer@@ -369,12 +374,13 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNaccountId: data.accountId,sshRemote})- .then(async ({ sessionId: sid, fresh }) => {+ .then(async ({ sessionId: sid, fresh, accountFallback: fellBack }) => {if (disposed) {transport.kill(sid)return}sessionId = sid+ if (fellBack) setAccountFallback(true)// Cold restart: the tmux session (and anything that was running in it) is gone — replay// the last persisted scrollback so the user sees where they left off. Warm reattach// (`fresh` false) skips this: tmux redraws the live screen itself, so replaying would@@ -840,7 +846,14 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN</span>)}{accountChip && (- <span className="node-account-chip" title={accountChip.tooltip}>+ <span+ className={`node-account-chip${accountFallback ? ' node-account-chip--warning' : ''}`}+ title={+ accountFallback+ ? 'Account folder missing — running on system account'+ : accountChip.tooltip+ }+ >{accountChip.short}</span>)}diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 6287e51ac..1c883dcf8 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -716,6 +716,12 @@ body,border-radius: 6px;}+/* Account folder missing at spawn → session fell back to the system account (orange warning). */+.node-account-chip--warning {+ color: #ff9f0a;+ background: rgba(255, 159, 10, 0.16);+}+/* Claude Code status: RUNNING badge while working, unread dot when finished. */.term-node__status {display: inline-flex;diff --git a/src/renderer/terminal/useTerminalSearch.ts b/src/renderer/terminal/useTerminalSearch.tsindex 0612221e7..ca879927f 100644--- a/src/renderer/terminal/useTerminalSearch.ts+++ b/src/renderer/terminal/useTerminalSearch.ts@@ -12,6 +12,8 @@ interface Args {sessionId: string | undefined/** The node's working directory — durable fallback for resolving the transcript. */cwd: string | undefined+ /** Managed Claude account whose transcript root the search resolves against (default system). */+ accountId: string | undefined/** Whether this node has a readable Claude transcript (gated on hasUsage capability). */searchTranscript: booleanopen: boolean@@ -33,6 +35,7 @@ export function useTerminalSearch({nodeId,sessionId,cwd,+ accountId,searchTranscript,open,readBuffer@@ -66,7 +69,8 @@ export function useTerminalSearch({try {const tr: TranscriptLine[] = await window.nodeTerminal.claude.readTranscript(sessionId,- cwd+ cwd,+ accountId)for (const l of tr) {for (const t of l.text.split('\n')) lines.push({ source: 'claude', role: l.role, text: t })@@ -81,7 +85,7 @@ export function useTerminalSearch({cancelled = true}// readBuffer must be stable (useCallback in the caller) to avoid rebuilds.- }, [open, nodeId, sessionId, cwd, searchTranscript, readBuffer])+ }, [open, nodeId, sessionId, cwd, accountId, searchTranscript, readBuffer])// Lowercase once per snapshot, not per keystroke — the snapshot can be tens of thousands of// lines (full scrollback + transcript), and re-lowercasing all of it on every typed characterdiff --git a/src/shared/types.ts b/src/shared/types.tsindex 751d15f74..44af6cb81 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -40,6 +40,9 @@ export interface PtyCreateOptions {export interface PtyCreateResult {sessionId: stringfresh: boolean+ /** Set when the node's `accountId` had no config dir at spawn, so the session fell back to the+ * system account. The renderer flags the account chip (folder-missing warning) when true. */+ accountFallback?: boolean}// 'subagent' and 'loop' are render-only (ephemeral hook-driven viz) and never persisted.@@ -691,8 +694,9 @@ export interface ContextApi {* Ask main to start (or refresh) tracking a session's transcript so the meter populates* without waiting for a live hook event — e.g. on node mount after an app restart, when* the continuing session is idle. `cwd` is a transcript-path fallback only.+ * `accountId` scopes resolution to a managed Claude account's transcript root (default `~/.claude`).*/- ensure(sessionId: string, cwd?: string): void+ ensure(sessionId: string, cwd?: string, accountId?: string): void}/** One searchable line extracted from a Claude session transcript. */@@ -813,10 +817,12 @@ export interface ClaudeApi {* Reads a Claude session's full transcript as flat searchable lines ([] if unavailable).* Resolves by `sessionId` when known (exact); otherwise falls back to `cwd` (durable —* the newest transcript under that project dir, no live hook event required).+ * `accountId` scopes resolution to a managed Claude account's transcript root (default `~/.claude`).*/readTranscript(sessionId: string | undefined,- cwd: string | undefined+ cwd: string | undefined,+ accountId?: string): Promise<TranscriptLine[]>}