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(recent): review round — one session per node, verified folders, faster lists
review96c89eebeebd
diff --git a/CLAUDE.md b/CLAUDE.mdindex 6652b01c2..93bf943c5 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -5025,17 +5025,24 @@ plan: the pure `renderer/lib/recentConversations.ts`; execution: Canvas `resumeRa group that does not re-encode to its own name (grok's slug+hash form for a long cwd) keeps anull cwd rather than a guessed one. copilot's `session.start` names `context.cwd`, and its`sessionId` must equal the directory it sits in.-- **Bounded**: per root only the newest `PER_ROOT` (25) files by mtime are OPENED (the rest cost a- stat; codex walks its dated tree newest-first and stats at most 100), each open is a 512 KB head- plus, for a claude/gemini title, a 128 KB tail, and the parse is cached by (path, size, mtime).- Measured on the dev host (313 claude transcripts, 62 codex rollouts): 227 ms cold, 20 ms cached,- 46 rows. Read on demand only — once per start-screen appearance and per palette open, never a timer.+- **Bounded**: per root only the newest `PER_ROOT` (25) files by mtime are OPENED; every other+ file costs a stat, and stats run in parallel capped at `STAT_CONCURRENCY` (32) — the first version+ awaited them one by one, which review measured at 2.8–4.0 s warm for 10,000 transcripts on every+ ⌘K. Codex walks its dated tree newest-first and stats at most 100. Each open is a 512 KB head plus,+ for a claude/gemini title, a 128 KB tail; the parse is cached by (path, size, mtime), and the whole+ answer is REUSED for `RESULT_REUSE_MS` (10 s, keyed by the exact roots + limit, concurrent callers+ share one read). Measured (fixture trees, this host): 300 files 45 ms cold / 17 ms warm, 3,000 →+ 209 / 356 ms, 10,000 → 630 / 617 ms; the real dev-host history (313 claude transcripts, 62 codex+ rollouts) 227 ms cold, 20 ms cached, 46 rows. Read on demand only — once per start-screen+ appearance and per palette open, never a timer. (`core/transcript-index.ts` was not reused: it is+ claude-only and carries no account per entry.)- **Title = display text, never a command.** The agent's own session name where it has one (claude`custom-title`/`ai-title` via `pickSessionName`, gemini `update_topic` via `pickGeminiTitle`, grok`summary.json`), else the first thing the user typed (the agent's own chat parser; a `<…>` harnesswrapper is not a prompt). Every title goes through `untrustedLine` (no control, bidi or zero-width- characters, one line, capped at 120). A transcript is `lstat`ed and must be a regular file — a- symlink planted in a history dir is never read. Only the SESSION ID reaches a pane, re-validated+ characters, one line, capped at 120). Every file the reader opens is `lstat`ed first and must be a+ regular file — transcripts, gemini's `.project_root` and grok's `summary.json` alike — so a symlink+ planted in a history dir is never followed. Only the SESSION ID reaches a pane, re-validatedthree times: `SAFE_SESSION_ID` at read, `canResumeWith` in the plan, and `createAgentNode`, whichTHROWS on an id the resume grammar refuses rather than silently starting a fresh conversation.- **The resume funnel is the factory's own**: `createAgentNode`'s trailing `resumeSessionId` builds@@ -5043,17 +5050,38 @@ plan: the pure `renderer/lib/recentConversations.ts`; execution: Canvas `resumeRcustom args, codex's launcher, `withPermissionMode` and the gateway model all apply — mints no id,and persists the RESUMED id as `agentSessionId`. The ⌘K transcript-search hit now uses the samepath; before, it replaced the command by hand and kept a freshly minted id the node never ran, so- its cold restore after a reboot resumed nothing.+ its cold restore after a reboot resumed nothing — and it passed no account, so a hit from a+ managed/linked root resumed under the system login. `TranscriptHit.accountId` (from the index root+ that holds the file) now travels with it, refused if that account is gone or not local.- **The account is the one that holds the history**, never the project default: a conversation in amanaged account's config dir resumed under the system login answers "No conversation found".`boundAccountId` still decides binding; the plan REFUSES when that account is gone, pending or- host-pinned (`RESUME_REFUSALS.accountGone`).-- **Where it resumes** (`planResume`): a node already holding the session (its live hook id, else- its persisted `agentSessionId`, live canvas first, then every stored project) is FOCUSED — two CLIs- on one transcript interleave it. Else a LOCAL folder project whose cwd equals the conversation's- (active first, then open, then closed → reopened). **Never an SSH project or a relay tab**: this- is this machine's history, and those cwds are on another machine. No project → "Open folder &- resume" through `openOrAdoptFolder` (the same probe/adopt rules as "Open folder…"). A resume into+ host-pinned (`RESUME_REFUSALS.accountGone`). A codex rollout HARDLINKED into a second home by+ "Switch Codex account" is one inode seen twice with the same mtime: `mergeRecent` credits the tie+ to the MANAGED account's copy. That is usually the account it was switched TO; a switch back to+ the system login is credited wrongly, which costs nothing — both homes hold the same file, so the+ resume finds it under either.+- **Where it resumes** (`planResume`):+ - A node already holding the session is FOCUSED — two CLIs on one transcript interleave it. A node+ holds exactly ONE session: its live hook id, ELSE its persisted `agentSessionId` — never both.+ `agentSessionId` is the launch-minted id and nothing rewrites it from hooks, so after `/clear`+ (live B) the node no longer holds A, and A must stay resumable (`closedHistory` uses the same+ `live || persisted`).+ - A folder that no longer exists (`cwdState: 'absent'`, a definite ENOENT/ENOTDIR from core — a+ failed stat is `unknown` and proceeds) is REFUSED: opening it would RECREATE it (the store+ mkdirs `<cwd>/.nodeterm`), and a removed worktree is the common case; a later+ `git worktree add` at that path would then fail.+ - Else the MOST SPECIFIC local owner of the folder: a worktree-bound group frame whose+ `worktree.path` is the folder or an ancestor (the node opens inside that frame), or the local+ project whose cwd is the folder or an ANCESTOR — segment-wise (`containsDir`), longest wins,+ then active > open > closed (reopened). A conversation in `/repo/packages/app` resumes in the+ `/repo` project; it does not mint a second project with a `project.json` inside the repository.+ The node's cwd is always the conversation's own folder (the CLI keys the transcript by it).+ - **Never an SSH project or a relay tab**: this is this machine's history, and those cwds are on+ another machine. `openFolderProject`/`openOrAdoptFolder` now skip relay tabs too — a relay tab+ carries the HOST's cwd, and the same path on two machines used to switch to it and do nothing.+ - No owner → "Open folder & resume" through `openOrAdoptFolder` (the same probe/adopt rules as+ "Open folder…"); the ⌘K row says "Open folder & resume: …", never a bare "Resume". A resume intoanother project lands via `pendingResumeRef`, consumed by the project-load effect beside`pendingFocusRef`, and RE-PLANS at creation (a node may have taken the session meanwhile).Refused rows stay on the start screen, disabled with the reason; the palette omits them (nodiff --git a/src/core/recent-conversations.test.ts b/src/core/recent-conversations.test.tsindex e467e5391..a61e16d99 100644--- a/src/core/recent-conversations.test.ts+++ b/src/core/recent-conversations.test.ts@@ -8,8 +8,13 @@ import {clampLimit,defaultRecentRoots,firstPrompt,+ dirState,listRecentConversations,+ listRecentConversationsReused,+ mapLimit,mergeRecent,+ resetRecentConversationsReuseForTests,+ RESULT_REUSE_MS,normalizeRecentRequest,PER_ROOT,resetRecentConversationsCacheForTests,@@ -65,6 +70,7 @@ let roots: RecentRootsbeforeEach(() => {resetRecentConversationsCacheForTests()+ resetRecentConversationsReuseForTests()home = testTmpDir('nt-recent-')roots = {claude: [{ root: path.join(home, '.claude', 'projects') }],@@ -252,6 +258,69 @@ describe('bounds and caching', () => {})})+describe('review #1062 fixes', () => {+ it('says whether each folder still exists — absent only on a definite ENOENT', async () => {+ const live = testTmpDir('nt-live-')+ write(path.join(roots.claude[0].root, '-a', `${CLAUDE_ID}.jsonl`), claudeTranscript({ cwd: live }))+ const gone = 'aaaaaaaa-3b7d-4e61-9a24-7c1d8e0f4b32'+ write(path.join(roots.claude[0].root, '-b', `${gone}.jsonl`), claudeTranscript({ id: gone, cwd: path.join(home, 'removed-worktree') }))+ const items = await listRecentConversations(roots)+ expect(items.find((i) => i.sessionId === CLAUDE_ID)?.cwdState).toBe('present')+ expect(items.find((i) => i.sessionId === gone)?.cwdState).toBe('absent')+ const file = write(path.join(home, 'f'), 'x')+ expect(await dirState(file)).toBe('absent')+ expect(await dirState(path.join(file, 'below'))).toBe('absent')+ })++ it('a hardlinked codex rollout (same inode, same mtime) is credited to the managed account', () => {+ const r = (accountId?: string): RecentConversation => ({+ agentId: 'codex', sessionId: CODEX_ID, cwd: '/x', lastActiveAt: 5, title: 't', titleSource: 'prompt',+ ...(accountId ? { accountId } : {})+ })+ expect(mergeRecent([r(), r('cw')], 10)[0].accountId).toBe('cw')+ expect(mergeRecent([r('cw'), r()], 10)[0].accountId).toBe('cw')+ })++ it('reuses one answer inside the window, and re-reads after it (or for other roots)', async () => {+ const f = write(path.join(roots.claude[0].root, '-a', `${CLAUDE_ID}.jsonl`), claudeTranscript({ title: 'One' }), 1_000)+ const first = await listRecentConversationsReused(roots, 60, 0)+ fs.writeFileSync(f, claudeTranscript({ title: 'Two!' }))+ expect(await listRecentConversationsReused(roots, 60, RESULT_REUSE_MS - 1)).toBe(first)+ expect((await listRecentConversationsReused(roots, 60, RESULT_REUSE_MS + 1))[0].title).toBe('Two!')+ const other = { ...roots, copilot: [] }+ expect(await listRecentConversationsReused(other, 60, RESULT_REUSE_MS + 2)).not.toBe(first)+ })++ it('mapLimit keeps order and never runs more than the limit at once', async () => {+ let live = 0+ let peak = 0+ const out = await mapLimit([1, 2, 3, 4, 5, 6, 7], 3, async (n) => {+ live+++ peak = Math.max(peak, live)+ await new Promise((r) => setTimeout(r, 1))+ live--+ return n * 2+ })+ expect(out).toEqual([2, 4, 6, 8, 10, 12, 14])+ expect(peak).toBe(3)+ })++ it('never follows a symlinked gemini .project_root or grok summary.json', async () => {+ const secret = write(path.join(home, 'secret.txt'), '/etc/secret-dir')+ const gdir = path.join(roots.geminiTmp!, 'p')+ fs.mkdirSync(gdir, { recursive: true })+ fs.symlinkSync(secret, path.join(gdir, '.project_root'))+ write(path.join(gdir, 'chats', 's.jsonl'), jl({ sessionId: GEMINI_ID, kind: 'main' }, { id: '1', type: 'user', content: [{ text: 'hello' }] }))+ const grokDir = path.join(roots.grokSessions!, encodeURIComponent('/srv/grok'), GROK_ID)+ write(path.join(grokDir, 'chat_history.jsonl'), jl({ type: 'user', content: [{ type: 'text', text: 'typed' }] }))+ const leak = write(path.join(home, 'leak.json'), JSON.stringify({ generated_title: 'LEAKED' }))+ fs.symlinkSync(leak, path.join(grokDir, 'summary.json'))+ const items = await listRecentConversations(roots)+ expect(items.find((i) => i.agentId === 'gemini')?.cwd).toBeNull()+ expect(items.find((i) => i.agentId === 'grok')).toMatchObject({ title: 'typed', titleSource: 'prompt' })+ })+})+describe('defaultRecentRoots — account scoping', () => {it('includes local settled managed and linked claude accounts only; drops unsafe codex ids', () => {const linked = testTmpDir('nt-linked-')diff --git a/src/core/recent-conversations.ts b/src/core/recent-conversations.tsindex 0075fcdff..12451cdcf 100644--- a/src/core/recent-conversations.ts+++ b/src/core/recent-conversations.ts@@ -155,6 +155,32 @@ async function statCandidate(file: string): Promise<Candidate | null> {}}+/** Stats run in parallel, but never more than this many at once: a history of 10,000 transcripts+ * (measured in review: 1.6 s cold / 2.8–4.0 s warm, awaited one by one) must not open 10,000+ * handles at the same instant either. */+export const STAT_CONCURRENCY = 32++export async function mapLimit<T, R>(items: readonly T[], limit: number, fn: (t: T) => Promise<R>): Promise<R[]> {+ const out = new Array<R>(items.length)+ let next = 0+ const worker = async (): Promise<void> => {+ while (next < items.length) {+ const i = next+++ out[i] = await fn(items[i])+ }+ }+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))+ return out+}++async function isRegularFile(file: string): Promise<boolean> {+ try {+ return (await fs.promises.lstat(file)).isFile()+ } catch {+ return false+ }+}+function newest(cands: Array<Candidate | null>, n = PER_ROOT): Candidate[] {return cands.filter((c): c is Candidate => !!c && c.size > 0)@@ -293,7 +319,9 @@ async function parseGemini(c: Candidate, cwd: string | null): Promise<Parsed> {async function parseGrok(c: Candidate, sessionId: string, cwd: string | null): Promise<Parsed> {const lines = await headLines(c)const prompt = firstPrompt(chatMessagesFromGrok(lines.join('\n')))- const meta = await readGrokSessionMeta(path.dirname(c.file))+ const dir = path.dirname(c.file)+ // summary.json is opened by the shared reader, which follows links — lstat it here first.+ const meta = (await isRegularFile(path.join(dir, 'summary.json'))) ? await readGrokSessionMeta(dir) : nullconst t = titled(meta?.title, prompt)if (t.titleSource === 'none') return nullreturn { agentId: 'grok', sessionId, cwd, ...t }@@ -338,11 +366,13 @@ function row(parsed: Parsed, c: Candidate, accountId?: string): Row | null {// ── per-agent enumeration ─────────────────────────────────────────────────────────────────────async function claudeRows(root: string, accountId?: string): Promise<Row[]> {- const cands: Array<Candidate | null> = []- for (const proj of await listDirs(root)) {- const dir = path.join(root, proj)- for (const f of await listFiles(dir, '.jsonl')) cands.push(await statCandidate(path.join(dir, f)))- }+ const files: string[] = []+ const projects = await listDirs(root)+ const lists = await mapLimit(projects, STAT_CONCURRENCY, (proj) => listFiles(path.join(root, proj), '.jsonl'))+ projects.forEach((proj, i) => {+ for (const f of lists[i]) files.push(path.join(root, proj, f))+ })+ const cands = await mapLimit(files, STAT_CONCURRENCY, statCandidate)const out: Row[] = []for (const c of newest(cands)) {const r = row(await cached(c, () => parseClaude(c)), c, accountId)@@ -370,7 +400,7 @@ async function codexRows(home: string, accountId?: string): Promise<Row[]> {}}const out: Row[] = []- for (const c of newest(await Promise.all(files.map(statCandidate)))) {+ for (const c of newest(await mapLimit(files, STAT_CONCURRENCY, statCandidate))) {const r = row(await cached(c, () => parseCodex(c)), c, accountId)if (r) out.push(r)}@@ -384,14 +414,17 @@ async function geminiRows(tmp: string): Promise<Row[]> {// MEASURED (gemini-cli, 2026-09): each project dir holds `.project_root`, the absolute cwd.let cwd: string | null = nulltry {- cwd = safeCwd((await readRange(path.join(projDir, '.project_root'), 0, 4096)).trim())+ const rootFile = path.join(projDir, '.project_root')+ // lstat first: a symlink planted here must not make us read whatever it points at.+ if (await isRegularFile(rootFile)) cwd = safeCwd((await readRange(rootFile, 0, 4096)).trim())} catch {/* an older layout (hash-named dir) has none — the row keeps a null cwd */}const chats = path.join(projDir, 'chats')- for (const f of await listFiles(chats, '.jsonl')) {- cands.push({ c: await statCandidate(path.join(chats, f)), cwd })- }+ const stats = await mapLimit(await listFiles(chats, '.jsonl'), STAT_CONCURRENCY, (f) =>+ statCandidate(path.join(chats, f))+ )+ for (const c of stats) cands.push({ c, cwd })}const byFile = new Map(cands.filter((x) => x.c).map((x) => [x.c!.file, x.cwd]))const out: Row[] = []@@ -414,10 +447,11 @@ async function grokRows(sessions: string): Promise<Row[]> {} catch {/* not an encoded path */}- for (const id of await listDirs(path.join(sessions, group))) {- if (!isSafeGrokSessionId(id) || !validId(id)) continue- cands.push({ c: await statCandidate(path.join(sessions, group, id, GROK_CHAT_HISTORY_FILE)), id, cwd })- }+ const ids = (await listDirs(path.join(sessions, group))).filter((id) => isSafeGrokSessionId(id) && validId(id))+ const stats = await mapLimit(ids, STAT_CONCURRENCY, (id) =>+ statCandidate(path.join(sessions, group, id, GROK_CHAT_HISTORY_FILE))+ )+ ids.forEach((id, i) => cands.push({ c: stats[i], id, cwd }))}const meta = new Map(cands.filter((x) => x.c).map((x) => [x.c!.file, x]))const out: Row[] = []@@ -430,11 +464,8 @@ async function grokRows(sessions: string): Promise<Row[]> {}async function copilotRows(root: string): Promise<Row[]> {- const cands: Array<Candidate | null> = []- for (const id of await listDirs(root)) {- if (!validId(id)) continue- cands.push(await statCandidate(path.join(root, id, COPILOT_EVENTS_FILE)))- }+ const ids = (await listDirs(root)).filter(validId)+ const cands = await mapLimit(ids, STAT_CONCURRENCY, (id) => statCandidate(path.join(root, id, COPILOT_EVENTS_FILE)))const out: Row[] = []for (const c of newest(cands)) {const id = path.basename(path.dirname(c.file))@@ -444,14 +475,23 @@ async function copilotRows(root: string): Promise<Row[]> {return out}-/** Newest first; the same (agent, session) seen twice (a root listed twice, a hardlinked rollout- * in two codex homes) keeps its NEWEST sighting. */+/** Newest first; the same (agent, session) seen twice keeps its NEWEST sighting. A tie — a codex+ * rollout HARDLINKED into a second home by "Switch Codex account" is one inode, so both sightings+ * carry the same mtime — goes to the MANAGED account's copy: that is the account the conversation+ * was usually switched to. A switch BACK to the system login is credited wrongly, at no cost: both+ * homes hold the same file, so the resume finds it under either login. */export function mergeRecent(rows: Row[], limit: number): Row[] {const best = new Map<string, Row>()for (const r of rows) {const key = `${r.agentId}\0${r.sessionId}`const prev = best.get(key)- if (!prev || r.lastActiveAt > prev.lastActiveAt) best.set(key, r)+ if (+ !prev ||+ r.lastActiveAt > prev.lastActiveAt ||+ (r.lastActiveAt === prev.lastActiveAt && !!r.accountId && !prev.accountId)+ ) {+ best.set(key, r)+ }}return [...best.values()].sort((a, b) => b.lastActiveAt - a.lastActiveAt).slice(0, limit)}@@ -475,7 +515,53 @@ export async function listRecentConversations(]const settled = await Promise.allSettled(jobs)const rows = settled.flatMap((s) => (s.status === 'fulfilled' ? s.value : []))- return mergeRecent(rows, clampLimit(limit))+ const merged = mergeRecent(rows, clampLimit(limit))+ // Does each folder still exist? A removed worktree is the common case, and "Open folder & resume"+ // would otherwise RECREATE it (the store mkdirs `<cwd>/.nodeterm`). One stat per distinct cwd.+ const cwds = [...new Set(merged.map((r) => r.cwd).filter((c): c is string => !!c))]+ const states = new Map(+ (await mapLimit(cwds, STAT_CONCURRENCY, async (c) => [c, await dirState(c)] as const)).map(([c, st]) => [c, st])+ )+ return merged.map((r) => (r.cwd ? { ...r, cwdState: states.get(r.cwd) ?? 'unknown' } : r))+}++/** `absent` only on a definite ENOENT/ENOTDIR (or a path that is not a directory) — any other error+ * is `unknown`: a failed stat is never evidence of absence. */+export async function dirState(dir: string): Promise<'present' | 'absent' | 'unknown'> {+ try {+ return (await fs.promises.stat(dir)).isDirectory() ? 'present' : 'absent'+ } catch (e) {+ const code = (e as NodeJS.ErrnoException).code+ return code === 'ENOENT' || code === 'ENOTDIR' ? 'absent' : 'unknown'+ }+}++/** How long one answer is reused. Opening ⌘K twice in a row must not re-stat the whole history;+ * a conversation that ended a few seconds ago appearing a few seconds late costs nothing. */+export const RESULT_REUSE_MS = 10_000+let reuse: { key: string; at: number; items: Promise<RecentConversation[]> } | null = null++export function resetRecentConversationsReuseForTests(): void {+ reuse = null+}++/** `listRecentConversations` with a short reuse window, keyed by the exact roots + limit (so an+ * account added in Settings is looked at on the next open, not after the window). A concurrent+ * second call shares the first's in-flight read. */+export function listRecentConversationsReused(+ roots: RecentRoots,+ limit: number,+ now: number = Date.now()+): Promise<RecentConversation[]> {+ const key = JSON.stringify([roots, limit])+ if (reuse && reuse.key === key && now - reuse.at < RESULT_REUSE_MS) return reuse.items+ const items = listRecentConversations(roots, limit)+ reuse = { key, at: now, items }+ // A failed read is not reused.+ items.catch(() => {+ if (reuse?.items === items) reuse = null+ })+ return items}/** Sanitize a request that arrived over IPC / the WS bridge. */@@ -492,7 +578,7 @@ export function registerRecentConversationsIpc(): void {platform().handle(IPC.recentConversationsList, async (raw: unknown): Promise<RecentConversationsResult> => {try {const req = normalizeRecentRequest(raw)- return { ok: true, items: await listRecentConversations(defaultRecentRoots(req), req.limit) }+ return { ok: true, items: await listRecentConversationsReused(defaultRecentRoots(req), clampLimit(req.limit)) }} catch {return { ok: false, reason: 'failed' }}diff --git a/src/core/transcript-index-core.test.ts b/src/core/transcript-index-core.test.tsindex f6e11d6d5..c0c158dcc 100644--- a/src/core/transcript-index-core.test.ts+++ b/src/core/transcript-index-core.test.ts@@ -66,6 +66,12 @@ describe('searchEntries', () => {it('respects the limit', () => {expect(searchEntries(entries, 'tmux', 1)).toHaveLength(1)})++ it('names the account whose root holds a hit, so its resume runs under that login', () => {+ const hits = searchEntries(entries, 'tmux', 20, (p) => (p === '/p/s1.jsonl' ? 'work' : undefined))+ expect(hits.find((h) => h.sessionId === 's1')?.accountId).toBe('work')+ expect('accountId' in hits.find((h) => h.sessionId === 's2')!).toBe(false)+ })})describe('planRefresh', () => {diff --git a/src/core/transcript-index-core.ts b/src/core/transcript-index-core.tsindex 9a66ee56e..700bc81ba 100644--- a/src/core/transcript-index-core.ts+++ b/src/core/transcript-index-core.ts@@ -55,7 +55,10 @@ export function makeSnippet(text: string, query: string): string {export function searchEntries(entries: TranscriptIndexEntry[],query: string,- limit = 20+ limit = 20,+ /** The managed/linked account whose root holds a transcript (undefined = system). A resume of the+ * hit must run under that account, or the CLI answers "No conversation found". */+ accountOf?: (transcriptPath: string) => string | undefined): TranscriptHit[] {const q = query.trim().toLowerCase()if (q.length < 2) return []@@ -69,7 +72,8 @@ export function searchEntries(snippet: makeSnippet(`${e.title}\n${e.text}`, q),cwd: e.cwd,projectLabel: e.cwd ? e.cwd.split('/').filter(Boolean).pop() ?? e.cwd : '',- mtime: e.mtime+ mtime: e.mtime,+ ...((a) => (a ? { accountId: a } : {}))(accountOf?.(e.transcriptPath))}))}diff --git a/src/core/transcript-index.ts b/src/core/transcript-index.tsindex 7c30ecbba..6313c7411 100644--- a/src/core/transcript-index.ts+++ b/src/core/transcript-index.ts@@ -32,7 +32,13 @@ function indexFilePath(): string {// 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')]+ return accountRoots().map((r) => r.root)+}++function accountRoots(): Array<{ root: string; accountId?: string }> {+ const roots: Array<{ root: string; accountId?: string }> = [+ { root: path.join(os.homedir(), '.claude', 'projects') }+ ]const userData = platform().userDataDirfor (const acct of accountsGetter?.() ?? []) {if (acct.host || acct.pending) continue@@ -41,7 +47,7 @@ function projectsRoots(): string[] {// 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'))+ roots.push({ root: path.join(dir, 'projects'), accountId: acct.id })} catch {/* invalid account id → skip that root (fail-open) */}@@ -149,7 +155,10 @@ async function refresh(): Promise<void> {}export function searchTranscripts(query: string): TranscriptHit[] {- return searchEntries(entries, query)+ const roots = accountRoots()+ return searchEntries(entries, query, undefined, (p) =>+ roots.find((r) => p.startsWith(r.root + path.sep))?.accountId+ )}export function initTranscriptIndex(getAccounts?: () => ClaudeAccount[]): void {diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 6d5697f5a..bda644147 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -481,6 +481,7 @@ import type { RecentConversation } from '@shared/recent-conversations'import {heldSessions,localCodexAccountIds,+ worktreeGroups,planResume,folderLabel,recentTitle,@@ -11666,6 +11667,16 @@ export function Canvas() {// resume line goes through that project's launch command, like every other launch it owns.const activeId = useProjects.getState().activeProjectIdif (!canResumeWith('claude', hit.sessionId)) return+ const hitAccount = hit.accountId+ if (+ hitAccount &&+ !(useSettings.getState().settings.claudeAccounts ?? []).some(+ (a) => a.id === hitAccount && !a.host && !a.pending+ )+ ) {+ setNotice({ kind: 'error', text: RESUME_REFUSALS.accountGone })+ return+ }// The factory's resume path: the same assembler cold restore uses (launch override, permission// flag), and the node persists THIS id — not a freshly minted one it never ran — so a later// cold restore resumes the same conversation.@@ -11676,7 +11687,9 @@ export function Canvas() {viewCenter(),undefined,undefined,- undefined,+ // The account whose root holds this transcript — the system login would not find it. A+ // hit naming an account that has since been removed or is not local is refused.+ hitAccount,activePermissionMode('claude'),activeId,undefined,@@ -16258,7 +16271,9 @@ export function Canvas() {async (folder: string): Promise<void> => {commitActiveToStore()// A folder maps to one project: reuse the already-registered one first…- const existing = useProjects.getState().projects.find((p) => p.cwd === folder)+ // A relay tab carries the HOST's cwd: the same path on two machines must not route a local+ // folder to another machine's tab (openFolderProject applies the same rule).+ const existing = useProjects.getState().projects.find((p) => p.cwd === folder && !p.remote)if (existing) {useProjects.getState().openFolderProject(folder)// An `unavailable` placeholder never recovers on its own: a save emits a header-only ref@@ -16603,6 +16618,7 @@ export function Canvas() {projects,activeProjectId: active,held: heldSessions(projects, active, live as never, (id) => byId[id]?.sessionId),+ worktreeGroups: worktreeGroups(projects, active, live as never),claudeAccounts: settings.claudeAccounts ?? [],codexAccounts: settings.codexAccounts ?? []}@@ -16652,12 +16668,17 @@ export function Canvas() {}if (conv.titleSource === 'name' && conv.title) node.data = { ...node.data, title: conv.title }node.selected = true- setNodes((ns) => [...ns.map((n) => ({ ...n, selected: false })), node])+ // Inside the worktree-bound frame that owns the folder, when there is one (its branch's work).+ const placed =+ plan.groupId && nodesRef.current.some((n) => n.id === plan.groupId)+ ? parentInto(node, plan.groupId)+ : node+ setNodes((ns) => [...ns.map((n) => ({ ...n, selected: false })), placed])markDirty()- goToNode(node)+ goToNode(placed)setWelcomeOpen(false)},- [resumeContext, travelToNode, emptyNodePos, setNodes, markDirty, goToNode]+ [resumeContext, travelToNode, emptyNodePos, parentInto, setNodes, markDirty, goToNode])useEffect(() => {resumeCreateRef.current = createRecentResumeNode@@ -16695,13 +16716,20 @@ export function Canvas() {else switchProject(plan.projectId)returncase 'open-folder':- void openOrAdoptFolder(plan.folder).then(() => {- setWelcomeOpen(false)- const landed = useProjects- .getState()- .projects.find((p) => !p.ssh && !p.remote && p.cwd === plan.folder)- if (landed) resumeWhenLanded(landed.id, conv)- })+ void openOrAdoptFolder(plan.folder)+ .then(() => {+ setWelcomeOpen(false)+ const landed = useProjects+ .getState()+ .projects.find((p) => !p.ssh && !p.remote && p.cwd === plan.folder)+ if (landed) resumeWhenLanded(landed.id, conv)+ })+ .catch((err: unknown) =>+ setNotice({+ kind: 'error',+ text: `Could not open ${plan.folder}: ${stripIpcPrefix(err instanceof Error ? err.message : String(err))}`+ })+ )return}},@@ -17362,7 +17390,8 @@ export function Canvas() {if (action.disabled) return []return [{id: `recent:${conv.agentId}:${conv.sessionId}`,- label: `${action.label === 'Go to node' ? 'Go to' : 'Resume'}: ${recentTitle(conv)}`,+ // The row says what it will DO — "Open folder & resume" opens a new project first.+ label: `${action.label}: ${recentTitle(conv)}`,hint: [folderLabel(conv.cwd), relativeTime(conv.lastActiveAt, at)].join(' · '),section: 'Recent conversations',icon: <AgentIcon agentId={conv.agentId} />,diff --git a/src/renderer/lib/recentConversations.test.ts b/src/renderer/lib/recentConversations.test.tsindex 65cb75484..85db39b90 100644--- a/src/renderer/lib/recentConversations.test.ts+++ b/src/renderer/lib/recentConversations.test.ts@@ -1,6 +1,8 @@import { describe, it, expect } from 'vitest'import {+ containsDir,groupRecentByFolder,+ worktreeGroups,heldSessions,localCodexAccountIds,planResume,@@ -35,14 +37,14 @@ describe('planResume', () => {conv(),ctx({projects: [{ id: 'p1', cwd: '/srv/demo' }] as never,- held: [{ nodeId: 'n7', projectId: 'p2', sessionIds: [undefined, SID] }]+ held: [{ nodeId: 'n7', projectId: 'p2', sessionId: SID }]}))expect(plan).toEqual({ kind: 'focus', nodeId: 'n7', projectId: 'p2' })})it('the live hook id counts as holding too', () => {- const plan = planResume(conv(), ctx({ held: [{ nodeId: 'n1', projectId: 'p', sessionIds: [SID, 'minted'] }] }))+ const plan = planResume(conv(), ctx({ held: [{ nodeId: 'n1', projectId: 'p', sessionId: SID }] }))expect(plan.kind).toBe('focus')})@@ -103,6 +105,67 @@ describe('planResume', () => {})})+describe('planResume — folder ownership (review #1062)', () => {+ it('refuses a folder that no longer exists — never recreates it', () => {+ expect(planResume(conv({ cwdState: 'absent' }), ctx())).toEqual({ kind: 'refuse', reason: RESUME_REFUSALS.folderGone })+ // Even when a project owns an ancestor: the CLI keys the conversation by its folder.+ expect(planResume(conv({ cwdState: 'absent' }), ctx({ projects: [{ id: 'p', cwd: '/srv' }] as never })).kind).toBe('refuse')+ })++ it('an unknown folder state is not absence', () => {+ expect(planResume(conv({ cwdState: 'unknown' }), ctx()).kind).toBe('open-folder')+ })++ it('a conversation in a subfolder resumes in the ancestor project (the longest prefix wins)', () => {+ const projects = [+ { id: 'root', cwd: '/srv' },+ { id: 'repo', cwd: '/srv/demo' },+ { id: 'lookalike', cwd: '/srv/dem' }+ ] as never+ expect(planResume(conv({ cwd: '/srv/demo/packages/app' }), ctx({ projects }))).toEqual({+ kind: 'resume',+ projectId: 'repo',+ reopen: false+ })+ expect(planResume(conv({ cwd: '/srv/demolition' }), ctx({ projects }))).toMatchObject({ projectId: 'root' })+ })++ it('a conversation in a bound worktree resumes inside that worktree’s group', () => {+ const projects = [{ id: 'repo', cwd: '/srv/demo' }] as never+ const groups = [{ projectId: 'repo', groupId: 'g1', path: '/srv/demo.worktrees/fix-x' }]+ expect(+ planResume(conv({ cwd: '/srv/demo.worktrees/fix-x' }), ctx({ projects, worktreeGroups: groups }))+ ).toEqual({ kind: 'resume', projectId: 'repo', reopen: false, groupId: 'g1' })+ })++ it('a worktree group in a relay tab or SSH project is not a local owner', () => {+ const projects = [{ id: 'relay', cwd: '/elsewhere', remote: true }] as never+ const groups = [{ projectId: 'relay', groupId: 'g1', path: '/srv/demo' }]+ expect(planResume(conv(), ctx({ projects, worktreeGroups: groups })).kind).toBe('open-folder')+ })++ it('containsDir is segment-wise and tolerates trailing separators', () => {+ expect(containsDir('/srv/demo/', '/srv/demo')).toBe('/srv/demo'.length)+ expect(containsDir('/srv/demo', '/srv/demo/a')).toBe('/srv/demo'.length)+ expect(containsDir('/srv/demo', '/srv/demolition')).toBe(-1)+ expect(containsDir('C:\\work', 'C:\\work\\app')).toBe('C:\\work'.length)+ expect(containsDir('/', '/srv')).toBe(1)+ expect(containsDir(undefined, '/srv')).toBe(-1)+ })++ it('collects worktree groups from the live canvas and the stored projects', () => {+ const projects = [+ { id: 'a', nodes: [{ id: 'old', kind: 'group', worktree: { path: '/stale' } }] },+ { id: 'b', nodes: [{ id: 'g2', kind: 'group', worktree: { path: '/wt/b' } }, { id: 't', kind: 'terminal' }] }+ ] as never+ const live = [{ id: 'g1', type: 'group', data: { worktree: { path: '/wt/a' } } }, { id: 'x', type: 'terminal', data: {} }]+ expect(worktreeGroups(projects, 'a', live)).toEqual([+ { projectId: 'a', groupId: 'g1', path: '/wt/a' },+ { projectId: 'b', groupId: 'g2', path: '/wt/b' }+ ])+ })+})+describe('heldSessions', () => {it('reads the live canvas for the active project and the store for the rest', () => {const projects = [@@ -111,10 +174,18 @@ describe('heldSessions', () => {] as neverconst held = heldSessions(projects, 'a', [{ id: 'n1', data: { agentSessionId: 'x1' } }], (id) => (id === 'n2' ? 'live2' : undefined))expect(held).toEqual([- { nodeId: 'n1', projectId: 'a', sessionIds: [undefined, 'x1'] },- { nodeId: 'n2', projectId: 'b', sessionIds: ['live2', 'x2'] }+ { nodeId: 'n1', projectId: 'a', sessionId: 'x1' },+ { nodeId: 'n2', projectId: 'b', sessionId: 'live2' }])})++ it('a node that moved to a new session (/clear) no longer holds its launch-minted one', () => {+ // Minted A at launch, live id now B: A must be resumable from the list, B must focus the node.+ const held = heldSessions([], 'p', [{ id: 'n1', data: { agentSessionId: 'A' } }], () => 'B')+ const planA = planResume(conv({ sessionId: 'A' }), ctx({ held }))+ expect(planA.kind).toBe('open-folder')+ expect(planResume(conv({ sessionId: 'B' }), ctx({ held }))).toMatchObject({ kind: 'focus', nodeId: 'n1' })+ })})describe('presentation', () => {diff --git a/src/renderer/lib/recentConversations.ts b/src/renderer/lib/recentConversations.tsindex 658f66698..44c75a823 100644--- a/src/renderer/lib/recentConversations.ts+++ b/src/renderer/lib/recentConversations.ts@@ -19,13 +19,17 @@ import type { RecentConversation } from '@shared/recent-conversations'export type ResumePlan =| { kind: 'focus'; nodeId: string; projectId: string }- | { kind: 'resume'; projectId: string; reopen: boolean }+ /** `groupId`: a worktree-bound group frame whose worktree holds the conversation's folder — the+ * node opens inside it, so it is where the user's branch work already is. */+ | { kind: 'resume'; projectId: string; reopen: boolean; groupId?: string }| { kind: 'open-folder'; folder: string }| { kind: 'refuse'; reason: string }export const RESUME_REFUSALS = {unsafeId: 'This conversation’s id cannot be put on a command line safely.',noCwd: 'The history does not say which folder this conversation ran in.',+ folderGone:+ 'The folder this conversation ran in no longer exists (a removed worktree?). Opening it would recreate an empty folder.',accountGone: 'The account this conversation belongs to is no longer set up on this machine.'} as const@@ -33,14 +37,26 @@ export const RESUME_REFUSALS = {export interface HeldSession {nodeId: stringprojectId: string- /** The live hook-fed id (wins), and the persisted `agentSessionId`. */- sessionIds: Array<string | undefined>+ /** The ONE session this node holds: the live hook-fed id, else the persisted `agentSessionId`.+ * Never both — `agentSessionId` is the id minted at launch and nothing rewrites it from hooks,+ * so after a `/clear` (live id B) the node no longer holds A, and A must stay resumable. Same+ * rule as `closedHistory` (`live || persisted`). */+ sessionId: string | undefined+}++/** A worktree-bound group frame on a canvas: its project, its id and its worktree folder. */+export interface WorktreeGroupRef {+ projectId: string+ groupId: string+ path: string}export interface ResumeContext {projects: readonly Pick<Project, 'id' | 'cwd' | 'ssh' | 'closed' | 'unavailable' | 'remote'>[]activeProjectId: stringheld: readonly HeldSession[]+ /** Worktree-bound groups (live canvas + stored projects), for a conversation that ran in one. */+ worktreeGroups?: readonly WorktreeGroupRef[]claudeAccounts: readonly Pick<ClaudeAccount, 'id' | 'host' | 'pending'>[]codexAccounts: readonly Pick<CodexAccount, 'id' | 'host' | 'pending'>[]}@@ -59,7 +75,7 @@ export function heldSessions(out.push({nodeId: n.id,projectId: activeProjectId,- sessionIds: [liveSessionId(n.id), str(n.data?.agentSessionId)]+ sessionId: liveSessionId(n.id) || str(n.data?.agentSessionId)})}for (const p of projects) {@@ -68,15 +84,40 @@ export function heldSessions(out.push({nodeId: n.id,projectId: p.id,- sessionIds: [liveSessionId(n.id), str((n as { agentSessionId?: unknown }).agentSessionId)]+ sessionId: liveSessionId(n.id) || str((n as { agentSessionId?: unknown }).agentSessionId)})}}return out}+/** Every worktree-bound group, live canvas first (the store lags it by an autosave). */+export function worktreeGroups(+ projects: readonly Pick<Project, 'id' | 'nodes'>[],+ activeProjectId: string,+ liveNodes: ReadonlyArray<{ id: string; type?: string; data?: { worktree?: unknown } }>+): WorktreeGroupRef[] {+ const out: WorktreeGroupRef[] = []+ const pathOf = (w: unknown): string | undefined =>+ w && typeof w === 'object' && typeof (w as { path?: unknown }).path === 'string'+ ? (w as { path: string }).path+ : undefined+ for (const n of liveNodes) {+ const p = n.type === 'group' ? pathOf(n.data?.worktree) : undefined+ if (p) out.push({ projectId: activeProjectId, groupId: n.id, path: p })+ }+ for (const pr of projects) {+ if (pr.id === activeProjectId && liveNodes.length) continue+ for (const n of pr.nodes ?? []) {+ const p = n.kind === 'group' ? pathOf((n as { worktree?: unknown }).worktree) : undefined+ if (p) out.push({ projectId: pr.id, groupId: n.id, path: p })+ }+ }+ return out+}+export function findHolder(conv: RecentConversation, held: readonly HeldSession[]): HeldSession | undefined {- return held.find((h) => h.sessionIds.some((id) => id === conv.sessionId))+ return held.find((h) => h.sessionId === conv.sessionId)}function accountUsable(conv: RecentConversation, ctx: ResumeContext): boolean {@@ -91,11 +132,17 @@ function accountUsable(conv: RecentConversation, ctx: ResumeContext): boolean {return false}-/** Normalize a folder for comparison: trailing separators do not make a different directory. */-function sameDir(a: string | undefined, b: string): boolean {- if (!a) return false- const trim = (s: string): string => (s.length > 1 ? s.replace(/[/\\]+$/, '') : s)- return trim(a) === trim(b)+const trimSep = (s: string): string => (s.length > 1 ? s.replace(/[/\\]+$/, '') : s)++/** Length of `dir` when it is `target` or an ANCESTOR of it (segment-wise: `/repo` holds+ * `/repo/packages/app`, never `/repository`), else -1. Longer = more specific. */+export function containsDir(dir: string | undefined, target: string): number {+ if (!dir) return -1+ const d = trimSep(dir)+ const t = trimSep(target)+ if (t === d) return d.length+ const prefixes = /[/\\]$/.test(d) ? [d] : [d + '/', d + '\\']+ return prefixes.some((p) => t.startsWith(p)) ? d.length : -1}export function planResume(conv: RecentConversation, ctx: ResumeContext): ResumePlan {@@ -105,13 +152,46 @@ export function planResume(conv: RecentConversation, ctx: ResumeContext): Resumeif (!canResumeWith(conv.agentId, conv.sessionId)) return { kind: 'refuse', reason: RESUME_REFUSALS.unsafeId }if (!accountUsable(conv, ctx)) return { kind: 'refuse', reason: RESUME_REFUSALS.accountGone }if (!conv.cwd) return { kind: 'refuse', reason: RESUME_REFUSALS.noCwd }- const local = ctx.projects.filter(- (p) => !p.ssh && !p.remote && !p.unavailable && sameDir(p.cwd, conv.cwd!)- )- const pick =- local.find((p) => p.id === ctx.activeProjectId) ?? local.find((p) => !p.closed) ?? local[0]- if (pick) return { kind: 'resume', projectId: pick.id, reopen: !!pick.closed }- return { kind: 'open-folder', folder: conv.cwd }+ // Only a DEFINITE absence refuses; `unknown` (a stat that failed otherwise) proceeds.+ if (conv.cwdState === 'absent') return { kind: 'refuse', reason: RESUME_REFUSALS.folderGone }+ const cwd = conv.cwd+ // The most specific owner of the folder wins: a worktree-bound group, or the local project whose+ // folder is the conversation's or an ANCESTOR of it (a subfolder like `/repo/packages/app`+ // resumes in the `/repo` project, it does not mint a second project inside the repository).+ const local = ctx.projects.filter((p) => !p.ssh && !p.remote && !p.unavailable)+ const localIds = new Set(local.map((p) => p.id))+ const rank = (p: (typeof local)[number]): number =>+ p.id === ctx.activeProjectId ? 0 : p.closed ? 2 : 1+ let best: { depth: number; projectId: string; groupId?: string; rank: number } | null = null+ const consider = (depth: number, projectId: string, groupId?: string): void => {+ if (depth < 0) return+ const p = local.find((x) => x.id === projectId)!+ const r = rank(p)+ // Deeper wins; at equal depth a group beats its project, then active > open > closed.+ if (+ !best ||+ depth > best.depth ||+ (depth === best.depth && !!groupId && !best.groupId) ||+ (depth === best.depth && !!groupId === !!best.groupId && r < best.rank)+ ) {+ best = { depth, projectId, groupId, rank: r }+ }+ }+ for (const p of local) consider(containsDir(p.cwd, cwd), p.id)+ for (const g of ctx.worktreeGroups ?? []) {+ if (localIds.has(g.projectId)) consider(containsDir(g.path, cwd), g.projectId, g.groupId)+ }+ const pick = best as { depth: number; projectId: string; groupId?: string; rank: number } | null+ if (pick) {+ const project = local.find((p) => p.id === pick.projectId)!+ return {+ kind: 'resume',+ projectId: pick.projectId,+ reopen: !!project.closed,+ ...(pick.groupId ? { groupId: pick.groupId } : {})+ }+ }+ return { kind: 'open-folder', folder: cwd }}/** The action a row offers, in words. */diff --git a/src/renderer/state/projects.test.ts b/src/renderer/state/projects.test.tsindex 738552f5c..0ef9f5c78 100644--- a/src/renderer/state/projects.test.ts+++ b/src/renderer/state/projects.test.ts@@ -6,6 +6,14 @@ beforeEach(() => {})describe('openFolderProject', () => {+ it('never routes a local folder to a relay tab carrying the same path (another machine)', () => {+ const relay = useProjects.getState().addProject('host', '/Users/me/dev/my-app')+ useProjects.setState((st) => ({ projects: st.projects.map((q) => (q.id === relay.id ? { ...q, remote: true } : q)) }))+ const p = useProjects.getState().openFolderProject('/Users/me/dev/my-app')+ expect(p.id).not.toBe(relay.id)+ expect(p.remote).toBeFalsy()+ })+it('creates a new project named after the folder and activates it', () => {const p = useProjects.getState().openFolderProject('/Users/me/dev/my-app')expect(p.name).toBe('my-app')diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.tsindex 7e6501b1a..b5f9b5dc0 100644--- a/src/renderer/state/projects.ts+++ b/src/renderer/state/projects.ts@@ -493,7 +493,8 @@ export const useProjects = create<ProjectsState>((set, get) => ({},openFolderProject(folder) {- const existing = get().projects.find((p) => p.cwd === folder)+ // Never a relay tab: it carries the HOST's cwd, and the same path can exist on both machines.+ const existing = get().projects.find((p) => p.cwd === folder && !p.remote)if (existing) {// reopenProject also clears `closed` — an "Open folder" on a previously closed// project must bring its tab back, not activate an invisible project.diff --git a/src/shared/recent-conversations.ts b/src/shared/recent-conversations.tsindex 97f7443e5..2e2c79463 100644--- a/src/shared/recent-conversations.ts+++ b/src/shared/recent-conversations.ts@@ -51,6 +51,10 @@ export interface RecentConversation {/** The managed or linked account whose config dir holds this history; absent = the system* account. A resume MUST run under this account or the CLI will not find the conversation. */accountId?: string+ /** Does `cwd` still exist as a directory on this machine? Only a definite ENOENT/ENOTDIR is+ * `absent` — a stat that failed otherwise is `unknown`, never evidence of absence. Absent when+ * `cwd` is null or the reader did not look. */+ cwdState?: 'present' | 'absent' | 'unknown'}export interface RecentConversationsRequest {diff --git a/src/shared/types.ts b/src/shared/types.tsindex 41f9304a4..a9576fe3e 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -3380,6 +3380,8 @@ export interface TranscriptHit {cwd: stringprojectLabel: stringmtime: number+ /** The managed/linked Claude account whose root holds this transcript; absent = system. */+ accountId?: string}export interface TranscriptsApi {