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(recent): "Open recent" — resume a past agent conversation from its history
review7f0160300572
diff --git a/CLAUDE.md b/CLAUDE.mdindex a81a8d718..6652b01c2 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4999,6 +4999,73 @@ principle. Per-agent write-ups: `docs/grok-agent.md`, `docs/gemini-agent.md`.group (a typed `/exit` can land in the agent composer as prompt text), recycle the persistentsession, and let cold restore resume with the new model under the newly injected environment.+## Open recent (resume a past agent conversation from its history)++Past conversations live in each CLI's own history, and nodeterm used to resume only what a node+remembered. "Open recent" lists them — the start screen's **Recent conversations** (grouped by the+folder each ran in) and a **Recent conversations** section of ⌘K — and one click resumes one.+Reader: `core/recent-conversations.ts` (`recent-conversations:list`, registered by BOTH shells);+plan: the pure `renderer/lib/recentConversations.ts`; execution: Canvas `resumeRecentConversation`.++- **Which agents, and why only those** (`RECENT_CONVERSATION_AGENTS`, `@shared/recent-conversations`):+ claude (system root + every LOCAL settled managed and linked account — `claudeAccountsSnapshot`),+ codex (system `CODEX_HOME` + the managed homes whose ids the renderer sends; core re-validates+ each through `codexHomeForAccount`, which throws outside the id alphabet), gemini, grok, copilot.+ Each is in `RESUMABLE_AGENTS` AND has a measured on-disk shape. **opencode is out**: its history is+ a SQLite database we never open, and the only reader is `opencode export` (one spawn, ~1.5 s,+ ~320 MB per session). **antigravity is out**: its record shapes were never captured. An agent+ outside the list contributes no rows — nothing guesses at a layout.+- **Measured shapes the reader depends on** (dev host, 2026-09-30): codex `session_meta` carries+ `id`, `cwd` and `thread_source` — a spawned child says `"subagent"` with a `source: {subagent:…}`+ object (4 of 62 rollouts here) and is SKIPPED, a user's own thread says `"user"`; that first line+ also carries the whole base instructions (tens of KB), which is why the head read is 512 KB.+ gemini's project dir holds `.project_root` = the absolute cwd, and its header says `kind: "main"`;+ a session holding only harness `<session_context>` (no prompt, no title) is not a conversation+ and is skipped (all 3 gemini sessions on this host). grok's session group is the URL-encoded cwd;+ a group that does not re-encode to its own name (grok's slug+hash form for a long cwd) keeps a+ null 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.+- **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 `<…>` harness+ wrapper 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+ three times: `SAFE_SESSION_ID` at read, `canResumeWith` in the plan, and `createAgentNode`, which+ THROWS 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+ the line with `assembleResumeCommand` — the assembler cold restore uses, so a launch override,+ custom 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 same+ path; 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.+- **The account is the one that holds the history**, never the project default: a conversation in a+ managed 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+ another 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 (no+ disabled state there).+- **Surfaces.** Desktop: this machine's history. **Server Edition**: its own host's history — the+ machine the browser's sessions run on (real ws-bridge leg). **SSH projects: local history only in+ v1** — a remote host's transcripts would need a remote leg over the ControlMaster, and a local+ conversation is never resumed into an SSH project. **Relay tabs**: the list stays LOCAL (relay-api+ spreads `...local`), and `recent-conversations:list` is `HOST_ONLY` so a peer can never list the+ host's history (titles are prompts the host's user typed, in every project). **Mobile**: follow-up+ in nodeterm-ios — "open recent" on the phone needs this list over the relay dialect.+## Session memory (the RAM pill + the per-session panel)A bottom-left **RAM pill** (`components/SystemResourcePill.tsx`) beside the usage pill, and thediff --git a/src/core/recent-conversations.test.ts b/src/core/recent-conversations.test.tsnew file mode 100644index 000000000..e467e5391--- /dev/null+++ b/src/core/recent-conversations.test.ts@@ -0,0 +1,271 @@+import fs from 'node:fs'+import path from 'node:path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { testTmpDir } from './test-tmp'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'+import {+ clampLimit,+ defaultRecentRoots,+ firstPrompt,+ listRecentConversations,+ mergeRecent,+ normalizeRecentRequest,+ PER_ROOT,+ resetRecentConversationsCacheForTests,+ safeCwd,+ type RecentRoots+} from './recent-conversations'+import { registerClaudeAccountsSource, resetClaudeAccountsSourceForTests } from './claude-config-dir'+import { RECENT_CONVERSATIONS_MAX, RECENT_TITLE_MAX, type RecentConversation } from '../shared/recent-conversations'+import type { ClaudeAccount } from '../shared/types'++const CLAUDE_ID = '5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32'+const CODEX_ID = '01a0d2ec-38fd-7473-8152-b97b8fa090dd'+const CODEX_CHILD = '01a0d2ec-38fd-7473-8152-b97b8fa090de'+const GEMINI_ID = 'babc2a4a-f4fb-4781-814b-596d4ecf87a5'+const GROK_ID = '0e3f5a9c-1234-4abc-8def-0123456789ab'+const COPILOT_ID = '7c1d8e0f-4b32-4e61-9a24-5f0c2a9e3b7d'++const jl = (...recs: unknown[]): string => recs.map((r) => JSON.stringify(r)).join('\n') + '\n'++function write(file: string, body: string, mtimeSec?: number): string {+ fs.mkdirSync(path.dirname(file), { recursive: true })+ fs.writeFileSync(file, body)+ if (mtimeSec !== undefined) fs.utimesSync(file, mtimeSec, mtimeSec)+ return file+}++function claudeTranscript(opts: { id?: string; cwd?: string; prompt?: unknown; title?: string } = {}): string {+ const id = opts.id ?? CLAUDE_ID+ const cwd = opts.cwd ?? '/srv/demo'+ const recs: unknown[] = [+ { type: 'file-history-snapshot', sessionId: id, cwd, isSidechain: false },+ { type: 'user', message: { role: 'user', content: opts.prompt ?? 'Fix the flaky test' }, sessionId: id, cwd, isSidechain: false },+ { type: 'assistant', message: { role: 'assistant', content: [{ type: 'text', text: 'On it.' }] }, sessionId: id, cwd }+ ]+ if (opts.title) recs.push({ type: 'ai-title', aiTitle: opts.title, sessionId: id })+ return jl(...recs)+}++function codexRollout(id: string, cwd: string, prompt: string, child = false): string {+ return jl(+ {+ type: 'session_meta',+ payload: child+ ? { id, cwd, thread_source: 'subagent', source: { subagent: { thread_spawn: { parent_thread_id: CODEX_ID } } } }+ : { id, cwd, thread_source: 'user', source: 'cli', base_instructions: { text: 'x'.repeat(40_000) } }+ },+ { type: 'event_msg', payload: { type: 'user_message', message: prompt } }+ )+}++let home: string+let roots: RecentRoots++beforeEach(() => {+ resetRecentConversationsCacheForTests()+ home = testTmpDir('nt-recent-')+ roots = {+ claude: [{ root: path.join(home, '.claude', 'projects') }],+ codex: [{ home: path.join(home, '.codex') }],+ geminiTmp: path.join(home, '.gemini', 'tmp'),+ grokSessions: path.join(home, '.grok', 'sessions'),+ copilot: [path.join(home, '.copilot', 'session-state')]+ }+})++afterEach(() => {+ resetClaudeAccountsSourceForTests()+ resetPlatformForTests()+})++describe('listRecentConversations — per agent fixture trees', () => {+ it('reads every supported agent, newest first, with id, cwd, account and a title', async () => {+ write(path.join(roots.claude[0].root, '-srv-demo', `${CLAUDE_ID}.jsonl`), claudeTranscript({ title: 'Flaky test hunt' }), 1_000)+ write(path.join(home, '.codex', 'sessions', '2026', '09', '24', `rollout-2026-09-24T13-18-11-${CODEX_ID}.jsonl`), codexRollout(CODEX_ID, '/srv/api', 'Why does npm test fail?'), 2_000)+ const gdir = path.join(roots.geminiTmp!, 'demo')+ write(path.join(gdir, '.project_root'), '/srv/gem\n')+ write(+ path.join(gdir, 'chats', 'session-2026-09-25T21-53-babc2a4a.jsonl'),+ jl(+ { sessionId: GEMINI_ID, projectHash: 'h', kind: 'main' },+ { id: 'm1', type: 'user', content: [{ text: '<session_context>\nharness' }, { text: 'Refactor the parser' }] }+ ),+ 3_000+ )+ 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: 'search the web' }] }), 4_000)+ write(path.join(grokDir, 'summary.json'), JSON.stringify({ generated_title: 'Web search' }))+ fs.utimesSync(path.join(grokDir, 'chat_history.jsonl'), 4_000, 4_000)+ write(+ path.join(roots.copilot[0], COPILOT_ID, 'events.jsonl'),+ jl(+ { type: 'session.start', data: { sessionId: COPILOT_ID, context: { cwd: '/srv/pilot' } } },+ { type: 'user.message', data: { content: 'one', transformedContent: '<current_datetime>x</current_datetime>\n\none' } }+ ),+ 5_000+ )++ const items = await listRecentConversations(roots)+ expect(items.map((i) => i.agentId)).toEqual(['copilot', 'grok', 'gemini', 'codex', 'claude'])+ const by = Object.fromEntries(items.map((i) => [i.agentId, i]))+ expect(by.claude).toMatchObject({ sessionId: CLAUDE_ID, cwd: '/srv/demo', title: 'Flaky test hunt', titleSource: 'name', lastActiveAt: 1_000_000 })+ expect(by.claude.accountId).toBeUndefined()+ expect(by.codex).toMatchObject({ sessionId: CODEX_ID, cwd: '/srv/api', title: 'Why does npm test fail?', titleSource: 'prompt' })+ expect(by.gemini).toMatchObject({ sessionId: GEMINI_ID, cwd: '/srv/gem', title: 'Refactor the parser' })+ expect(by.grok).toMatchObject({ sessionId: GROK_ID, cwd: '/srv/grok', title: 'Web search', titleSource: 'name' })+ expect(by.copilot).toMatchObject({ sessionId: COPILOT_ID, cwd: '/srv/pilot', title: 'one' })+ })++ it('labels a conversation with the account whose root holds it', async () => {+ const acct = path.join(home, 'userData', 'claude-accounts', 'work', 'projects')+ roots.claude.push({ root: acct, accountId: 'work' })+ write(path.join(acct, '-srv-demo', `${CLAUDE_ID}.jsonl`), claudeTranscript())+ const codexAcct = path.join(home, 'codex-work')+ roots.codex.push({ home: codexAcct, accountId: 'cw' })+ write(path.join(codexAcct, 'sessions', '2026', '01', '01', `rollout-x-${CODEX_ID}.jsonl`), codexRollout(CODEX_ID, '/a', 'hi'))+ const items = await listRecentConversations(roots)+ expect(items.find((i) => i.agentId === 'claude')?.accountId).toBe('work')+ expect(items.find((i) => i.agentId === 'codex')?.accountId).toBe('cw')+ })++ it('skips codex subagent rollouts (measured: thread_source "subagent", source object)', async () => {+ const day = path.join(home, '.codex', 'sessions', '2026', '09', '24')+ write(path.join(day, `rollout-a-${CODEX_ID}.jsonl`), codexRollout(CODEX_ID, '/srv', 'parent'))+ write(path.join(day, `rollout-b-${CODEX_CHILD}.jsonl`), codexRollout(CODEX_CHILD, '/srv', 'child', true))+ const items = await listRecentConversations(roots)+ expect(items.map((i) => i.sessionId)).toEqual([CODEX_ID])+ })++ it('skips a gemini subagent session and one that never took a prompt', async () => {+ const chats = path.join(roots.geminiTmp!, 'p', 'chats')+ write(path.join(chats, 'a.jsonl'), jl({ sessionId: GEMINI_ID, kind: 'subagent' }, { id: '1', type: 'user', content: [{ text: 'x' }] }))+ write(path.join(chats, 'b.jsonl'), jl({ sessionId: 'aaaaaaaa-f4fb-4781-814b-596d4ecf87a5', kind: 'main' }, { id: '1', type: 'user', content: [{ text: '<session_context>only' }] }))+ expect(await listRecentConversations(roots)).toEqual([])+ })++ it('never lists a file whose name would be an unsafe session id', async () => {+ const dir = path.join(roots.claude[0].root, '-srv')+ for (const bad of ['-rf', 'a;b', '..x', 'a b', '$(id)']) write(path.join(dir, `${bad}.jsonl`), claudeTranscript())+ expect(await listRecentConversations(roots)).toEqual([])+ })++ it('does not follow a symlinked transcript', async () => {+ const secret = write(path.join(home, 'secret.jsonl'), claudeTranscript({ title: 'secret' }))+ const dir = path.join(roots.claude[0].root, '-srv')+ fs.mkdirSync(dir, { recursive: true })+ fs.symlinkSync(secret, path.join(dir, `${CLAUDE_ID}.jsonl`))+ expect(await listRecentConversations(roots)).toEqual([])+ })++ it('an unreadable or missing root adds no rows and never throws', async () => {+ const r: RecentRoots = { claude: [{ root: '/nonexistent/x' }], codex: [{ home: '/nonexistent/y' }], geminiTmp: null, grokSessions: null, copilot: ['/nonexistent/z'] }+ expect(await listRecentConversations(r)).toEqual([])+ })++ it('a grok group that is not a re-encodable cwd keeps a null cwd', async () => {+ const d = path.join(roots.grokSessions!, 'long-slug-abc123', GROK_ID)+ write(path.join(d, 'chat_history.jsonl'), jl({ type: 'user', content: [{ type: 'text', text: 'hi' }] }))+ const [row] = await listRecentConversations(roots)+ expect(row).toMatchObject({ agentId: 'grok', cwd: null })+ })++ it('a copilot journal whose own id differs from its directory is not that session', async () => {+ write(+ path.join(roots.copilot[0], COPILOT_ID, 'events.jsonl'),+ jl({ type: 'session.start', data: { sessionId: 'other-id', context: { cwd: '/x' } } }, { type: 'user.message', data: { content: 'hi' } })+ )+ expect(await listRecentConversations(roots)).toEqual([])+ })+})++describe('hostile titles', () => {+ it('makes a prompt ONE display line: no controls, no bidi / zero-width, capped', async () => {+ const hostile = '\u202Eevil\u200B\ttext\r\n\x1b[31mred\x07' + 'y'.repeat(500)+ write(path.join(roots.claude[0].root, '-srv', `${CLAUDE_ID}.jsonl`), claudeTranscript({ prompt: hostile }))+ const [row] = await listRecentConversations(roots)+ expect(row.title).not.toMatch(/[\x00-\x1f\x7f\u202E\u200B]/)+ expect(Array.from(row.title).length).toBeLessThanOrEqual(RECENT_TITLE_MAX)+ expect(row.title.startsWith('evil text')).toBe(true)+ expect(row.title.endsWith('…')).toBe(true)+ })++ it('a hostile session NAME is cleaned the same way and still wins over the prompt', async () => {+ write(path.join(roots.claude[0].root, '-srv', `${CLAUDE_ID}.jsonl`), claudeTranscript({ title: 'rm -rf /\n; echo pwned' }))+ const [row] = await listRecentConversations(roots)+ expect(row).toMatchObject({ title: 'rm -rf / ; echo pwned', titleSource: 'name' })+ })++ it('a harness wrapper is not a prompt', () => {+ expect(firstPrompt([{ role: 'user', parts: [{ kind: 'text', text: '<command-name>/clear</command-name>' }] }, { role: 'user', parts: [{ kind: 'text', text: 'real' }] }])).toBe('real')+ })++ it('a relative or control-bearing cwd is not a cwd', () => {+ expect(safeCwd('srv/demo')).toBeNull()+ expect(safeCwd('/srv/\ndemo')).toBeNull()+ expect(safeCwd(42)).toBeNull()+ expect(safeCwd('/srv/demo')).toBe('/srv/demo')+ expect(safeCwd('C:\\work')).toBe('C:\\work')+ })+})++describe('bounds and caching', () => {+ it('opens at most PER_ROOT candidates per root, newest by mtime', async () => {+ const dir = path.join(roots.claude[0].root, '-srv')+ for (let i = 0; i < PER_ROOT + 10; i++) {+ const id = `${String(i).padStart(8, '0')}-3b7d-4e61-9a24-7c1d8e0f4b32`+ write(path.join(dir, `${id}.jsonl`), claudeTranscript({ id }), 1_000 + i)+ }+ const items = await listRecentConversations(roots)+ expect(items).toHaveLength(PER_ROOT)+ expect(items[0].lastActiveAt).toBe((1_000 + PER_ROOT + 9) * 1000)+ })++ it('re-reads a transcript only when its size or mtime changed', async () => {+ const f = write(path.join(roots.claude[0].root, '-srv', `${CLAUDE_ID}.jsonl`), claudeTranscript({ title: 'One' }), 1_000)+ expect((await listRecentConversations(roots))[0].title).toBe('One')+ // Same size, same mtime, different bytes: served from the cache (nothing was re-read).+ fs.writeFileSync(f, claudeTranscript({ title: 'Two' }))+ fs.utimesSync(f, 1_000, 1_000)+ expect((await listRecentConversations(roots))[0].title).toBe('One')+ fs.utimesSync(f, 2_000, 2_000)+ expect((await listRecentConversations(roots))[0].title).toBe('Two')+ })++ it('mergeRecent keeps the newest sighting of one session and caps the list', () => {+ const r = (sessionId: string, at: number, agentId: RecentConversation['agentId'] = 'claude'): RecentConversation => ({+ agentId, sessionId, cwd: '/x', lastActiveAt: at, title: 't', titleSource: 'prompt'+ })+ const out = mergeRecent([r('a', 1), r('a', 5), r('b', 3), r('a', 2, 'codex')], 10)+ expect(out.map((x) => `${x.agentId}:${x.sessionId}:${x.lastActiveAt}`)).toEqual(['claude:a:5', 'claude:b:3', 'codex:a:2'])+ expect(mergeRecent([r('a', 1), r('b', 2)], 1)).toHaveLength(1)+ })++ it('clamps a limit and sanitizes a request from the wire', () => {+ expect(clampLimit(undefined)).toBe(RECENT_CONVERSATIONS_MAX)+ expect(clampLimit(0)).toBe(1)+ expect(clampLimit(1e9)).toBe(RECENT_CONVERSATIONS_MAX)+ expect(clampLimit('5')).toBe(RECENT_CONVERSATIONS_MAX)+ expect(normalizeRecentRequest(null)).toEqual({})+ expect(normalizeRecentRequest({ codexAccountIds: ['a', 7, 'b'], limit: 3 })).toEqual({ codexAccountIds: ['a', 'b'], limit: 3 })+ })+})++describe('defaultRecentRoots — account scoping', () => {+ it('includes local settled managed and linked claude accounts only; drops unsafe codex ids', () => {+ const linked = testTmpDir('nt-linked-')+ const accounts: ClaudeAccount[] = [+ { id: 'work', label: 'w', createdAt: 0 },+ { id: 'pend', label: 'p', pending: true, createdAt: 0 },+ { id: 'remote', label: 'r', host: 'me@box', createdAt: 0 },+ { id: 'mine', label: 'l', configDir: linked, createdAt: 0 }+ ] as ClaudeAccount[]+ registerClaudeAccountsSource(() => accounts)+ initPlatform(fakePlatform({ userDataDir: path.join(home, 'ud') }))+ const r = defaultRecentRoots({ codexAccountIds: ['cw', '../escape', '-x'] })+ expect(r.claude.map((c) => c.accountId)).toEqual([undefined, 'work', 'mine'])+ expect(r.claude.find((c) => c.accountId === 'mine')?.root).toBe(path.join(linked, 'projects'))+ expect(r.codex.map((c) => c.accountId)).toEqual([undefined, 'cw'])+ })+})diff --git a/src/core/recent-conversations.ts b/src/core/recent-conversations.tsnew file mode 100644index 000000000..0075fcdff--- /dev/null+++ b/src/core/recent-conversations.ts@@ -0,0 +1,502 @@+// "Open recent" — read the newest agent conversations THIS machine's CLIs keep on disk.+//+// Past conversations live in each CLI's own history (claude per config dir, codex rollouts, gemini,+// grok and copilot session stores), and until this existed nodeterm could only resume what a node+// happened to remember. This lists them; the renderer offers "Resume in <project>".+//+// Rules this module keeps, each for a reason:+// - ONLY this user's own roots: the system config dirs under `os.homedir()` (and each CLI's own+// relocation variable, read from this process's env exactly as the rest of core reads it), plus+// the managed / linked account dirs this app already knows. Never another user's home, never a+// path the caller names — the request carries account IDS, which resolve only under the managed+// root (`codexHomeForAccount` refuses an id outside its alphabet).+// - BOUNDED: per root, only the newest `PER_ROOT` candidates by mtime are opened, each read is a+// capped head (and, for the claude title, a capped tail), and the parsed answer is cached by+// (path, size, mtime), so a second open of the list reads nothing that did not change.+// - Unknown shapes are SKIPPED, never guessed: a file with no parsable id, a subagent/child+// session, an id that fails `SAFE_SESSION_ID` — none of those becomes a row.+// - A title is untrusted text (a prompt anyone could have typed, a model-written name) and is+// made into ONE display line with no control / bidi / zero-width characters (`untrustedLine`).+// It is never typed into a pane; only the validated session id is.+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { IPC } from '../shared/ipc'+import { SAFE_SESSION_ID } from '../shared/session-id'+import {+ RECENT_CONVERSATIONS_MAX,+ RECENT_TITLE_MAX,+ type RecentConversation,+ type RecentConversationAgent,+ type RecentConversationsRequest,+ type RecentConversationsResult+} from '../shared/recent-conversations'+import type { ChatMessage } from '../shared/types'+import { platform } from './platform'+import { transcriptRoot, parseChatMessages, pickSessionName } from './transcript-reader'+import { claudeAccountsSnapshot } from './claude-config-dir'+import { codexHomeForAccount } from './codex-accounts-core'+import { chatMessagesFromCodex, CODEX_THREAD_ID_RE } from './codex-chat'+import { chatFromGemini } from './gemini-chat'+import { pickGeminiTitle } from './gemini-session'+import { chatMessagesFromGrok } from './grok-chat'+import { readGrokSessionMeta } from './grok-session'+import {+ GROK_CHAT_HISTORY_FILE,+ grokEncodedCwdDirName,+ grokSessionsDir,+ isSafeGrokSessionId+} from './agents/grok-paths'+import { chatMessagesFromCopilot, COPILOT_EVENTS_FILE, copilotSessionStateRoots } from './copilot-chat'+import { untrustedLine } from './github/control-read'++/** Candidates opened per root (newest by mtime). A root with thousands of old transcripts costs a+ * directory listing and a stat each, never a read. */+export const PER_ROOT = 25+/** Head bytes read for id / cwd / first prompt. A codex `session_meta` line carries the full base+ * instructions (measured: tens of KB), so this is generous. */+export const HEAD_BYTES = 512 * 1024+/** Tail bytes read for a claude session name (`custom-title` / `ai-title` records). */+export const TITLE_TAIL_BYTES = 128 * 1024+const CACHE_MAX = 2000+/** More managed codex homes than anyone has is a hostile request, not a user. */+const MAX_CODEX_ACCOUNTS = 32++interface Candidate {+ file: string+ mtimeMs: number+ size: number+}++/** Where each agent's history lives. Injectable so tests point at fixture trees. */+export interface RecentRoots {+ claude: Array<{ root: string; accountId?: string }>+ codex: Array<{ home: string; accountId?: string }>+ geminiTmp: string | null+ grokSessions: string | null+ copilot: string[]+}++type Parsed = Omit<RecentConversation, 'lastActiveAt' | 'accountId'> | null++const cache = new Map<string, { size: number; mtimeMs: number; parsed: Parsed }>()++export function resetRecentConversationsCacheForTests(): void {+ cache.clear()+}++/** The real roots for this process: system dirs, every LOCAL settled managed/linked claude account,+ * and each requested managed codex account (ids re-validated by the resolver, which throws). */+export function defaultRecentRoots(req: RecentConversationsRequest = {}): RecentRoots {+ const claude: RecentRoots['claude'] = [{ root: transcriptRoot() }]+ const seen = new Set<string>([claude[0].root])+ for (const a of claudeAccountsSnapshot()) {+ // A host-pinned account's history is on that host; a pending one has never logged in.+ if (!a || typeof a.id !== 'string' || a.host || a.pending) continue+ let root: string+ try {+ root = transcriptRoot(a.id)+ } catch {+ continue+ }+ if (seen.has(root)) continue+ seen.add(root)+ claude.push({ root, accountId: a.id })+ }+ const codex: RecentRoots['codex'] = [{ home: codexHomeForAccount(platform().userDataDir) }]+ const ids = Array.isArray(req.codexAccountIds) ? req.codexAccountIds.slice(0, MAX_CODEX_ACCOUNTS) : []+ for (const id of ids) {+ if (typeof id !== 'string') continue+ try {+ codex.push({ home: codexHomeForAccount(platform().userDataDir, id), accountId: id })+ } catch {+ /* an id outside the account alphabet names no managed home */+ }+ }+ const geminiHome = process.env.GEMINI_CLI_HOME || os.homedir()+ return {+ claude,+ codex,+ geminiTmp: path.join(geminiHome, '.gemini', 'tmp'),+ grokSessions: grokSessionsDir(),+ copilot: copilotSessionStateRoots()+ }+}++// ── filesystem helpers ──────────────────────────────────────────────────────────────────────────++async function listDirs(dir: string): Promise<string[]> {+ try {+ const entries = await fs.promises.readdir(dir, { withFileTypes: true })+ return entries.filter((e) => e.isDirectory()).map((e) => e.name)+ } catch {+ return []+ }+}++async function listFiles(dir: string, suffix: string): Promise<string[]> {+ try {+ const entries = await fs.promises.readdir(dir, { withFileTypes: true })+ return entries.filter((e) => e.isFile() && e.name.endsWith(suffix)).map((e) => e.name)+ } catch {+ return []+ }+}++async function statCandidate(file: string): Promise<Candidate | null> {+ try {+ // lstat, then a regular-file check: a symlink planted in a history dir must not make us read+ // (and title-list) whatever it points at.+ const st = await fs.promises.lstat(file)+ if (!st.isFile()) return null+ return { file, mtimeMs: st.mtimeMs, size: st.size }+ } catch {+ return null+ }+}++function newest(cands: Array<Candidate | null>, n = PER_ROOT): Candidate[] {+ return cands+ .filter((c): c is Candidate => !!c && c.size > 0)+ .sort((a, b) => b.mtimeMs - a.mtimeMs)+ .slice(0, n)+}++async function readRange(file: string, start: number, len: number): Promise<string> {+ const fh = await fs.promises.open(file, 'r')+ try {+ const buf = Buffer.alloc(len)+ const { bytesRead } = await fh.read(buf, 0, len, start)+ return buf.toString('utf8', 0, bytesRead)+ } finally {+ await fh.close()+ }+}++/** Complete lines only: a capped head can end mid-record, and a torn record parses as nothing. */+async function headLines(c: Candidate): Promise<string[]> {+ const text = await readRange(c.file, 0, Math.min(c.size, HEAD_BYTES))+ const lines = text.split('\n')+ if (c.size > HEAD_BYTES) lines.pop()+ return lines.filter((l) => l.trim())+}++async function tailText(c: Candidate, bytes: number): Promise<string> {+ const start = Math.max(0, c.size - bytes)+ const text = await readRange(c.file, start, c.size - start)+ // Drop the (possibly torn) first line of a window that does not start at 0.+ return start > 0 ? text.slice(text.indexOf('\n') + 1) : text+}++function parseJson(line: string): Record<string, unknown> | null {+ try {+ const o = JSON.parse(line) as unknown+ return o && typeof o === 'object' && !Array.isArray(o) ? (o as Record<string, unknown>) : null+ } catch {+ return null+ }+}++const isObj = (v: unknown): v is Record<string, unknown> =>+ !!v && typeof v === 'object' && !Array.isArray(v)++/** An absolute directory string, or null. A history file is input we did not write. */+export function safeCwd(v: unknown): string | null {+ if (typeof v !== 'string') return null+ const s = v.trim()+ if (!s || s.length > 4096 || /[\x00-\x1f\x7f]/.test(s)) return null+ if (!path.isAbsolute(s) && !path.win32.isAbsolute(s)) return null+ return s+}++/** The first thing the human typed, as text. Harness-injected wrappers (`<command-…>`,+ * `<session_context>`, …) are not a prompt anyone would recognise as theirs. */+export function firstPrompt(messages: ChatMessage[]): string {+ for (const m of messages) {+ if (m.role !== 'user') continue+ const text = m.parts+ .map((p) => (p.kind === 'text' ? p.text : ''))+ .join(' ')+ .trim()+ if (!text || text.startsWith('<')) continue+ return text+ }+ return ''+}++function titled(name: string | null | undefined, prompt: string): Pick<RecentConversation, 'title' | 'titleSource'> {+ const n = untrustedLine(name ?? '', RECENT_TITLE_MAX)+ if (n) return { title: n, titleSource: 'name' }+ const p = untrustedLine(prompt, RECENT_TITLE_MAX)+ if (p) return { title: p, titleSource: 'prompt' }+ return { title: '', titleSource: 'none' }+}++function validId(id: unknown): id is string {+ return typeof id === 'string' && SAFE_SESSION_ID.test(id)+}++// ── per-agent parsers (pure over a candidate; cached by the caller) ───────────────────────────++async function parseClaude(c: Candidate): Promise<Parsed> {+ const id = path.basename(c.file, '.jsonl')+ if (!validId(id)) return null+ const lines = await headLines(c)+ let cwd: string | null = null+ for (const l of lines) {+ const o = parseJson(l)+ if (!o) continue+ // A session started as a sidechain (a subagent transcript at the top level of an old layout)+ // is not a conversation anyone resumes by hand.+ if (o.isSidechain === true && !cwd) return null+ cwd = safeCwd(o.cwd)+ if (cwd) break+ }+ const prompt = firstPrompt(parseChatMessages(lines))+ const name = pickSessionName(await tailText(c, TITLE_TAIL_BYTES))+ const t = titled(name, prompt)+ // No prompt and no name: a transcript holding only bookkeeping (a `/clear` stub, a session that+ // never took a turn) is not a conversation.+ if (t.titleSource === 'none') return null+ return { agentId: 'claude', sessionId: id, cwd, ...t }+}++async function parseCodex(c: Candidate): Promise<Parsed> {+ const lines = await headLines(c)+ const meta = lines.length ? parseJson(lines[0]) : null+ if (!meta || meta.type !== 'session_meta' || !isObj(meta.payload)) return null+ const p = meta.payload+ const id = p.id+ if (typeof id !== 'string' || !CODEX_THREAD_ID_RE.test(id) || !validId(id)) return null+ // MEASURED (codex 0.156): a spawned child rollout carries `thread_source: "subagent"` and a+ // `source: {subagent: …}` object; a user's own thread says `thread_source: "user"`.+ if (p.thread_source === 'subagent' || isObj(p.source)) return null+ const prompt = firstPrompt(chatMessagesFromCodex(lines.join('\n')))+ const t = titled(null, prompt)+ if (t.titleSource === 'none') return null+ return { agentId: 'codex', sessionId: id, cwd: safeCwd(p.cwd), ...t }+}++async function parseGemini(c: Candidate, cwd: string | null): Promise<Parsed> {+ const lines = await headLines(c)+ const header = lines.length ? parseJson(lines[0]) : null+ if (!header || !validId(header.sessionId)) return null+ // `kind: "main"` measured on the user's own session; anything else (a subagent) is skipped.+ if (header.kind !== undefined && header.kind !== 'main') return null+ const prompt = firstPrompt(chatFromGemini(lines.join('\n')).messages)+ const name = pickGeminiTitle(await tailText(c, TITLE_TAIL_BYTES))+ const t = titled(name, prompt)+ if (t.titleSource === 'none') return null+ return { agentId: 'gemini', sessionId: header.sessionId, cwd, ...t }+}++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 t = titled(meta?.title, prompt)+ if (t.titleSource === 'none') return null+ return { agentId: 'grok', sessionId, cwd, ...t }+}++async function parseCopilot(c: Candidate, dirId: string): Promise<Parsed> {+ const lines = await headLines(c)+ const start = lines.map(parseJson).find((o) => o?.type === 'session.start')+ const data = start && isObj(start.data) ? start.data : null+ // The journal's own id must name the directory it sits in — a copied journal is not this session.+ if (!data || data.sessionId !== dirId || !validId(dirId)) return null+ const cwd = isObj(data.context) ? safeCwd(data.context.cwd) : null+ const prompt = firstPrompt(chatMessagesFromCopilot(lines.join('\n')))+ const t = titled(null, prompt)+ if (t.titleSource === 'none') return null+ return { agentId: 'copilot', sessionId: dirId, cwd, ...t }+}++async function cached(c: Candidate, parse: () => Promise<Parsed>): Promise<Parsed> {+ const hit = cache.get(c.file)+ if (hit && hit.size === c.size && hit.mtimeMs === c.mtimeMs) return hit.parsed+ let parsed: Parsed+ try {+ parsed = await parse()+ } catch {+ // A read that failed is not cached: the file may be readable next time.+ return null+ }+ cache.delete(c.file)+ cache.set(c.file, { size: c.size, mtimeMs: c.mtimeMs, parsed })+ if (cache.size > CACHE_MAX) cache.delete(cache.keys().next().value!)+ return parsed+}++type Row = RecentConversation++function row(parsed: Parsed, c: Candidate, accountId?: string): Row | null {+ if (!parsed) return null+ return { ...parsed, lastActiveAt: Math.round(c.mtimeMs), ...(accountId ? { accountId } : {}) }+}++// ── 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 out: Row[] = []+ for (const c of newest(cands)) {+ const r = row(await cached(c, () => parseClaude(c)), c, accountId)+ if (r) out.push(r)+ }+ return out+}++async function codexRows(home: string, accountId?: string): Promise<Row[]> {+ // YYYY/MM/DD, newest first by NAME: the tree is dated, so walking it in reverse order finds the+ // newest rollouts without statting the whole history. A generous window (4× the per-root cap)+ // is statted, since a rollout's mtime (last activity) can be newer than a later-dated sibling.+ const root = path.join(home, 'sessions')+ const files: string[] = []+ const want = PER_ROOT * 4+ outer: for (const y of (await listDirs(root)).sort().reverse()) {+ for (const m of (await listDirs(path.join(root, y))).sort().reverse()) {+ for (const d of (await listDirs(path.join(root, y, m))).sort().reverse()) {+ const dir = path.join(root, y, m, d)+ for (const f of (await listFiles(dir, '.jsonl')).sort().reverse()) {+ files.push(path.join(dir, f))+ if (files.length >= want) break outer+ }+ }+ }+ }+ const out: Row[] = []+ for (const c of newest(await Promise.all(files.map(statCandidate)))) {+ const r = row(await cached(c, () => parseCodex(c)), c, accountId)+ if (r) out.push(r)+ }+ return out+}++async function geminiRows(tmp: string): Promise<Row[]> {+ const cands: Array<{ c: Candidate | null; cwd: string | null }> = []+ for (const proj of await listDirs(tmp)) {+ const projDir = path.join(tmp, proj)+ // MEASURED (gemini-cli, 2026-09): each project dir holds `.project_root`, the absolute cwd.+ let cwd: string | null = null+ try {+ cwd = safeCwd((await readRange(path.join(projDir, '.project_root'), 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 byFile = new Map(cands.filter((x) => x.c).map((x) => [x.c!.file, x.cwd]))+ const out: Row[] = []+ for (const c of newest(cands.map((x) => x.c))) {+ const r = row(await cached(c, () => parseGemini(c, byFile.get(c.file) ?? null)), c)+ if (r) out.push(r)+ }+ return out+}++async function grokRows(sessions: string): Promise<Row[]> {+ const cands: Array<{ c: Candidate | null; id: string; cwd: string | null }> = []+ for (const group of await listDirs(sessions)) {+ // grok names a session group by the URL-encoded cwd. Decoded, it must re-encode to the same+ // name — otherwise it is the slug+hash form (a long cwd) we cannot invert, and the cwd is null.+ let cwd: string | null = null+ try {+ const decoded = decodeURIComponent(group)+ if (grokEncodedCwdDirName(decoded) === group) cwd = safeCwd(decoded)+ } 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 meta = new Map(cands.filter((x) => x.c).map((x) => [x.c!.file, x]))+ const out: Row[] = []+ for (const c of newest(cands.map((x) => x.c))) {+ const m = meta.get(c.file)!+ const r = row(await cached(c, () => parseGrok(c, m.id, m.cwd)), c)+ if (r) out.push(r)+ }+ return out+}++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 out: Row[] = []+ for (const c of newest(cands)) {+ const id = path.basename(path.dirname(c.file))+ const r = row(await cached(c, () => parseCopilot(c, id)), c)+ if (r) out.push(r)+ }+ 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. */+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)+ }+ return [...best.values()].sort((a, b) => b.lastActiveAt - a.lastActiveAt).slice(0, limit)+}++export function clampLimit(limit: unknown): number {+ const n = typeof limit === 'number' && Number.isFinite(limit) ? Math.floor(limit) : RECENT_CONVERSATIONS_MAX+ return Math.min(RECENT_CONVERSATIONS_MAX, Math.max(1, n))+}++/** Every agent's newest conversations under `roots`. Never throws: an unreadable root adds no rows. */+export async function listRecentConversations(+ roots: RecentRoots,+ limit: number = RECENT_CONVERSATIONS_MAX+): Promise<RecentConversation[]> {+ const jobs: Array<Promise<Row[]>> = [+ ...roots.claude.map((r) => claudeRows(r.root, r.accountId)),+ ...roots.codex.map((r) => codexRows(r.home, r.accountId)),+ ...(roots.geminiTmp ? [geminiRows(roots.geminiTmp)] : []),+ ...(roots.grokSessions ? [grokRows(roots.grokSessions)] : []),+ ...roots.copilot.map((r) => copilotRows(r))+ ]+ const settled = await Promise.allSettled(jobs)+ const rows = settled.flatMap((s) => (s.status === 'fulfilled' ? s.value : []))+ return mergeRecent(rows, clampLimit(limit))+}++/** Sanitize a request that arrived over IPC / the WS bridge. */+export function normalizeRecentRequest(raw: unknown): RecentConversationsRequest {+ if (!isObj(raw)) return {}+ const ids = Array.isArray(raw.codexAccountIds)+ ? raw.codexAccountIds.filter((x): x is string => typeof x === 'string').slice(0, MAX_CODEX_ACCOUNTS)+ : undefined+ return { ...(ids ? { codexAccountIds: ids } : {}), limit: clampLimit(raw.limit) }+}++/** `recent-conversations:list`, registered by BOTH shells (each lists its own machine's history). */+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) }+ } catch {+ return { ok: false, reason: 'failed' }+ }+ })+}++export type { RecentConversationAgent }diff --git a/src/main/index.ts b/src/main/index.tsindex de78adbea..c3584994c 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -263,6 +263,7 @@ import {locateRemoteTranscriptCommand,remoteTranscriptRoots} from '../core/remote-transcript-locate'+import { registerRecentConversationsIpc } from '../core/recent-conversations'import { readChatTranscript, registerTranscriptIpc, resolveTranscript, type TranscriptIpcDeps } from '../core/transcript-ipc'import { createReadRemoteGrokChat } from '../core/remote-grok-chat'import { createHostChat, mirrorChatSendRefusal } from './remote/host-chat'@@ -2890,6 +2891,8 @@ app.whenReady().then(async () => {})}registerTranscriptIpc(transcriptIpcDeps)+ // "Open recent": this machine's agent histories (both shells register it — core/recent-conversations.ts).+ registerRecentConversationsIpc()initTranscriptIndex(() => settingsStore.get().claudeAccounts ?? [])corePlatform.handle(IPC.transcriptSearch, (query: string) => searchTranscripts(query))diff --git a/src/main/recent-conversations-wiring.test.ts b/src/main/recent-conversations-wiring.test.tsnew file mode 100644index 000000000..778ee745e--- /dev/null+++ b/src/main/recent-conversations-wiring.test.ts@@ -0,0 +1,31 @@+import fs from 'node:fs'+import path from 'node:path'+import { describe, expect, it } from 'vitest'+import { IPC } from '../shared/ipc'+import { isHostOnlyChannel } from '../shared/host-control'++/**+ * "Open recent" is served by BOTH shells, and nothing type-checks that: a shell that forgets+ * `registerRecentConversationsIpc()` compiles, and its renderer's list silently never appears+ * (the bridge answers `{ok:false}`, which the start screen draws as nothing). Pinned at source level.+ */+const read = (rel: string): string =>+ fs.readFileSync(path.join(__dirname, '..', rel), 'utf8').replace(/\r\n/g, '\n')++describe('recent conversations wiring', () => {+ it('both shells register the core handler', () => {+ expect(read('main/index.ts')).toMatch(/^\s+registerRecentConversationsIpc\(\)$/m)+ expect(read('server/index.ts')).toMatch(/^\s+registerRecentConversationsIpc\(\)$/m)+ })++ it('the preload and the browser bridge both reach the channel', () => {+ expect(read('preload/index.ts')).toContain('ipcRenderer.invoke(IPC.recentConversationsList')+ const bridge = read('renderer/bridge/ws-bridge.ts')+ expect(bridge).toContain('client.request(IPC.recentConversationsList')+ expect(bridge).toContain('...buildRecentConversationsApi(client)')+ })++ it('a relay peer may never list the host’s conversation history', () => {+ expect(isHostOnlyChannel(IPC.recentConversationsList)).toBe(true)+ })+})diff --git a/src/preload/index.ts b/src/preload/index.tsindex c37047a4e..75d1ecb61 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -2,6 +2,7 @@ import { subscribeAgentReplay } from '../shared/agent-replay-subscription'import { contextBridge, ipcRenderer, webFrame, webUtils } from 'electron'import { IPC } from '../shared/ipc'import { resolveUiScale } from '../shared/ui-scale'+import type { RecentConversationsRequest } from '../shared/recent-conversations'import type {CanvasMutation,CanvasState,@@ -501,6 +502,10 @@ const api: NodeTerminalApi = {read: (q?: SessionMemoryQuery) => ipcRenderer.invoke(IPC.sessionMemory, q),host: (q?: SessionMemoryQuery) => ipcRenderer.invoke(IPC.sessionMemoryHost, q)},+ recentConversations: {+ list: (req?: RecentConversationsRequest) =>+ ipcRenderer.invoke(IPC.recentConversationsList, req)+ },wallpaper: {listStills: () => ipcRenderer.invoke(IPC.wallpaperListStills),load: (w) => ipcRenderer.invoke(IPC.wallpaperLoad, w),diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.tsindex cea9427fc..436184da8 100644--- a/src/renderer/bridge/relay-api.ts+++ b/src/renderer/bridge/relay-api.ts@@ -178,6 +178,9 @@ export function buildRelayApi(// `...local` (a v1 degrade: they read/write on this machine, not the host). boardLog is now// bridged to the host (see above) — it no longer rides `...local`.chat: stub.chat,+ // `recentConversations` stays on `...local` ON PURPOSE: "Open recent" lists THIS machine's agent+ // histories and resumes them into this machine's local projects only. The host's list is+ // host-only (`HOST_ONLY_CHANNELS`) — a peer never reads the host's conversation titles.// Agent canvas-control (`agent:control`) is not wired over the relay (matches the Server// Edition); inert no-ops rather than a local subscription that never carries the host's events.onAgentControl: stub.onAgentControl,diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 2befe0138..fc6a22b5e 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -276,6 +276,11 @@ export function buildStubApi(): Omit<cookieProviders: () => Promise.resolve({}),onUpdate: noopUnsub},+ // Real in the browser (ws-bridge `buildRecentConversationsApi`). Where this stub stays in force+ // — nowhere today — `unsupported` is the honest answer: "could not look", never "no history".+ recentConversations: {+ list: () => Promise.resolve({ ok: false as const, reason: 'unsupported' as const })+ },sessionMemory: {// Superseded by the real WS-backed namespace in ws-bridge (the core session-memory service// runs in the server shell too), so nothing reaches these in a live browser session. Keptdiff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 2c53cb35e..9e08de011 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -1,6 +1,7 @@import type { NormalizedAgentEvent } from '../../shared/agents/normalize'import { subscribeAgentReplay } from '../../shared/agent-replay-subscription'import type { DesktopWallpaper, WallpaperStill } from '../../shared/wallpaper'+import type { RecentConversationsRequest, RecentConversationsResult } from '../../shared/recent-conversations'// WebSocket bridge that reconstructs `window.nodeTerminal` in the browser (Server Edition).//// Under Electron the preload already defines `window.nodeTerminal`; this module only runs when@@ -991,6 +992,19 @@ export function buildSessionMemoryApi(client: RpcClient): Pick<NodeTerminalApi,}}+/** The server lists ITS OWN host's history — the machine the browser's sessions run on. A failed+ * request is `{ok:false}`, never an empty list. */+export function buildRecentConversationsApi(client: RpcClient): Pick<NodeTerminalApi, 'recentConversations'> {+ return {+ recentConversations: {+ list: (req?: RecentConversationsRequest) =>+ (client.request(IPC.recentConversationsList, req) as Promise<RecentConversationsResult>).catch(+ () => ({ ok: false as const, reason: 'failed' as const })+ )+ }+ }+}+export function buildWallpaperApi(client: RpcClient): Pick<NodeTerminalApi, 'wallpaper'> {return {wallpaper: {@@ -1289,6 +1303,7 @@ export async function installWsBridge(): Promise<boolean> {...buildSpeechApi(client),...buildUsageApi(client),...buildSessionMemoryApi(client),+ ...buildRecentConversationsApi(client),...buildWallpaperApi(client),...buildTriggersApi(client),...buildGitHubApi(client),diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex a082383c3..6d5697f5a 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -464,6 +464,7 @@ import {capabilityAgentId,createdAgentId,resumeCommand,+ canResumeWith,vanillaEnvStripPattern,AGENT_CONFIG,BUILTIN_AGENT_IDS,@@ -476,6 +477,17 @@ import { encodeUtf8Base64, launchPromptFor } from '../lib/promptSpill'import { parseTeamSpec } from '../lib/teamSpec'import { relativeTime } from '../lib/relativeTime'import { AgentIcon } from '../lib/agentIcons'+import type { RecentConversation } from '@shared/recent-conversations'+import {+ heldSessions,+ localCodexAccountIds,+ planResume,+ folderLabel,+ recentTitle,+ resumeActionLabel,+ RESUME_REFUSALS,+ type ResumeContext+} from '../lib/recentConversations'import { nodeIconDialog } from '../components/NodeIconPicker'import { applyIconChoice } from '../lib/nodeIconChoice'import type { NodeIcon } from '@shared/node-icon'@@ -1557,6 +1569,8 @@ export function Canvas() {const [closedTranscript, setClosedTranscript] = useState<ClosedSessionEntry | null>(null)// Node to center once its project finishes loading (cross-project notification click).const pendingFocusRef = useRef<string | null>(null)+ // "Open recent": a conversation to resume once the project it belongs to is on the canvas.+ const pendingResumeRef = useRef<{ projectId: string; conv: RecentConversation } | null>(null)// One-shot: the next active-project load keeps the CURRENT camera instead of applying the// project's saved viewport. Set by reloadActiveProject (in-place external-change reload).const preserveViewportRef = useRef(false)@@ -3141,6 +3155,12 @@ export function Canvas() {} else {setResumeProject(null)}+ // Finish an "Open recent" resume that had to land on this project first.+ const pendingResume = pendingResumeRef.current+ if (pendingResume && pendingResume.projectId === project.id) {+ pendingResumeRef.current = null+ resumeCreateRef.current(pendingResume.conv)+ }// Consume a cross-project focus request (notification click on a background node).const pending = pendingFocusRef.currentif (pending) {@@ -7207,6 +7227,9 @@ export function Canvas() {/** Latest `travelToNode`, for the agent-control handler's off-canvas notice. Travel to a NODE is* the user's own click on the notice's "Go there" button, not something a verb does. */const travelToNodeRef = useRef<(nodeId: string) => void>(() => {})+ // "Open recent": the resume-node creator, published by the callback below so the project-load+ // effect (declared earlier) can finish a resume that had to switch projects first.+ const resumeCreateRef = useRef<(conv: RecentConversation) => void>(() => {})// #925 headless start: one in-flight set for the whole canvas (one start per node at a time),// shared by `open-* --run-now` and `run`. The two below are published beside travelToNodeRef's// assignment, for the same reason: the agent-control effect mounts ONCE.@@ -11642,8 +11665,10 @@ export function Canvas() {// No live node — open a resume node in the active project, using the transcript's cwd. The// resume line goes through that project's launch command, like every other launch it owns.const activeId = useProjects.getState().activeProjectId- const cmd = resumeCommand('claude', hit.sessionId, false, agentLaunchOverride('claude', activeId))- if (!cmd) return+ if (!canResumeWith('claude', hit.sessionId)) 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.const node = createAgentNode('claude',nodesRef.current.length,@@ -11652,14 +11677,12 @@ export function Canvas() {undefined,undefined,undefined,+ activePermissionMode('claude'),+ activeId,+ undefined,undefined,- activeId+ hit.sessionId)- // The resume command replaces (never wraps) the factory's command, so it is flagged once.- node.data = {- ...node.data,- initialCommand: withPermissionMode(cmd, 'claude', activePermissionMode())- }node.selected = truesetNodes((ns) => [...ns.map((n) => ({ ...n, selected: false })), node])markDirty()@@ -16557,6 +16580,146 @@ export function Canvas() {travelToNodeRef.current = travelToNode})+ // ── "Open recent": resume a past agent conversation from its CLI's own history ──────────────+ // The list is THIS machine's (window.nodeTerminal: the desktop's core, or the Server Edition's+ // host), read on demand — one read per welcome-screen appearance and per palette open, never a+ // timer. `ok:false` shows nothing rather than "no conversations". The plan is the pure+ // `planResume` (lib/recentConversations.ts); this only executes it.+ const [recentConvs, setRecentConvs] = useState<RecentConversation[] | null>(null)+ const refreshRecentConvs = useCallback(() => {+ const codexAccountIds = localCodexAccountIds(useSettings.getState().settings.codexAccounts ?? [])+ return window.nodeTerminal.recentConversations+ .list({ codexAccountIds })+ .then((r) => setRecentConvs(r.ok ? r.items : null))+ .catch(() => setRecentConvs(null))+ }, [])++ const resumeContext = useCallback((): ResumeContext => {+ const { projects, activeProjectId: active } = useProjects.getState()+ const byId = useAgentStatus.getState().byId+ const settings = useSettings.getState().settings+ const live = canCreateOnCanvas(nodesProjectIdRef.current, active) ? nodesRef.current : []+ return {+ projects,+ activeProjectId: active,+ held: heldSessions(projects, active, live as never, (id) => byId[id]?.sessionId),+ claudeAccounts: settings.claudeAccounts ?? [],+ codexAccounts: settings.codexAccounts ?? []+ }+ }, [])+++ /** Create the resume node in the ACTIVE project. Re-plans first: between the click and now a node+ * may have taken the session, or its account may have been removed. */+ const createRecentResumeNode = useCallback(+ (conv: RecentConversation): void => {+ const active = useProjects.getState().activeProjectId+ if (!canCreateOnCanvas(nodesProjectIdRef.current, active)) {+ setNotice({ kind: 'error', text: CANVAS_NOT_ACTIVE_NOTICE })+ return+ }+ const plan = planResume(conv, resumeContext())+ if (plan.kind === 'focus') {+ travelToNode(plan.nodeId)+ return+ }+ if (plan.kind === 'refuse') {+ setNotice({ kind: 'error', text: plan.reason })+ return+ }+ if (plan.kind !== 'resume' || plan.projectId !== active) return+ let node: CanvasNode+ try {+ node = createAgentNode(+ conv.agentId,+ nodesRef.current.length,+ conv.cwd ?? undefined,+ emptyNodePos(),+ undefined,+ undefined,+ // The account whose config dir HOLDS this history — never the project default, or the CLI+ // would look for the conversation under another login and answer "No conversation found".+ conv.accountId,+ activePermissionMode(conv.agentId),+ active,+ undefined,+ undefined,+ conv.sessionId+ )+ } catch {+ setNotice({ kind: 'error', text: RESUME_REFUSALS.unsafeId })+ return+ }+ 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])+ markDirty()+ goToNode(node)+ setWelcomeOpen(false)+ },+ [resumeContext, travelToNode, emptyNodePos, setNodes, markDirty, goToNode]+ )+ useEffect(() => {+ resumeCreateRef.current = createRecentResumeNode+ })++ /** Land on `projectId`, then resume there (now if the canvas already holds it). */+ const resumeWhenLanded = useCallback(+ (projectId: string, conv: RecentConversation) => {+ if (+ projectId === useProjects.getState().activeProjectId &&+ canCreateOnCanvas(nodesProjectIdRef.current, projectId)+ ) {+ createRecentResumeNode(conv)+ return+ }+ pendingResumeRef.current = { projectId, conv }+ },+ [createRecentResumeNode]+ )++ const resumeRecentConversation = useCallback(+ (conv: RecentConversation) => {+ const plan = planResume(conv, resumeContext())+ switch (plan.kind) {+ case 'focus':+ setWelcomeOpen(false)+ travelToNode(plan.nodeId)+ return+ case 'refuse':+ setNotice({ kind: 'error', text: plan.reason })+ return+ case 'resume':+ resumeWhenLanded(plan.projectId, conv)+ if (plan.reopen) reopenProject(plan.projectId)+ else switchProject(plan.projectId)+ return+ case '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)+ })+ return+ }+ },+ [resumeContext, travelToNode, resumeWhenLanded, reopenProject, switchProject, openOrAdoptFolder]+ )++ const recentActionFor = useCallback(+ (conv: RecentConversation): { label: string; disabled?: string } => {+ const plan = planResume(conv, resumeContext())+ const label = resumeActionLabel(+ plan,+ (id) => useProjects.getState().getProject(id)?.name ?? 'project'+ )+ return plan.kind === 'refuse' ? { label, disabled: plan.reason } : { label }+ },+ [resumeContext]+ )+// #925: start held launches headless in a project that is not on screen (`open-* --run-now`),// and `run --node` (the CLI twin of a QUEUED node's Run now). Wiring only: the flow and every// refusal live in lib/headlessRun. Published every render for the same reason as above.@@ -16808,6 +16971,11 @@ export function Canvas() {}}, [welcomeVisible, closedProjects])+ // "Open recent": one read per welcome-screen appearance and per palette open.+ useEffect(() => {+ if (welcomeVisible || paletteOpen) void refreshRecentConvs()+ }, [welcomeVisible, paletteOpen, refreshRecentConvs])+const now = useMemo(() => Date.now(), [transcriptHits])const transcriptCommands = useMemo<Command[]>(() =>@@ -17182,10 +17350,31 @@ export function Canvas() {// at the call site rebuilt the whole list (JSX icons for every node + project) on every Canvas// render while the palette was open. `nodes` is a dep because the list reads nodesRef.current;// capture-cache refreshes arrive via buildCommands' own identity (bufferCache is its dep).+ // "Open recent" rows in the palette: searchable by title, agent and folder. Capped — the list is+ // one read of up to 60, and a palette with nothing typed should not be all history.+ const recentCommands = useMemo<Command[]>(() => {+ if (!paletteOpen || !recentConvs) return []+ const at = Date.now()+ // A refused row is OMITTED here (the palette has no disabled state — a dead search result is+ // worse than none); the welcome screen shows it disabled with its reason instead.+ return recentConvs.slice(0, 30).flatMap((conv): Command[] => {+ const action = recentActionFor(conv)+ if (action.disabled) return []+ return [{+ id: `recent:${conv.agentId}:${conv.sessionId}`,+ label: `${action.label === 'Go to node' ? 'Go to' : 'Resume'}: ${recentTitle(conv)}`,+ hint: [folderLabel(conv.cwd), relativeTime(conv.lastActiveAt, at)].join(' · '),+ section: 'Recent conversations',+ icon: <AgentIcon agentId={conv.agentId} />,+ run: () => resumeRecentConversation(conv)+ }]+ })+ }, [paletteOpen, recentConvs, recentActionFor, resumeRecentConversation])+const paletteCommands = useMemo(- () => (paletteOpen ? buildCommands() : []),+ () => (paletteOpen ? [...buildCommands(), ...recentCommands] : []),// eslint-disable-next-line react-hooks/exhaustive-deps -- nodes stands in for nodesRef.current- [paletteOpen, buildCommands, nodes]+ [paletteOpen, buildCommands, recentCommands, nodes])// The palette's chord appears as a bare chip in two places (the cluster's search button and the@@ -17764,6 +17953,9 @@ export function Canvas() {sessionCounts={closedSessionBadges ?? undefined}onReopen={reopenProject}onDeleteClosed={requestDeleteClosed}+ recentConversations={recentConvs ?? undefined}+ recentActionFor={recentActionFor}+ onResumeRecent={resumeRecentConversation}onClose={hasProjects ? () => setWelcomeOpen(false) : undefined}overBoard={kanbanOpen}/>diff --git a/src/renderer/components/RecentConversations.test.tsx b/src/renderer/components/RecentConversations.test.tsxnew file mode 100644index 000000000..99d522d3e--- /dev/null+++ b/src/renderer/components/RecentConversations.test.tsx@@ -0,0 +1,106 @@+// @vitest-environment jsdom+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { WelcomeScreen } from './WelcomeScreen'+import { RECENT_CONVERSATIONS_VISIBLE } from './RecentConversations'+import type { RecentConversation } from '@shared/recent-conversations'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++const noop = (): void => {}+const base = { onNewProject: noop, onOpenFolder: noop, onCloneRepo: noop, onConnectSsh: noop }+const conv = (i: number, over: Partial<RecentConversation> = {}): RecentConversation => ({+ agentId: 'claude',+ sessionId: `s${i}`,+ cwd: '/srv/demo',+ lastActiveAt: 1000 - i,+ title: `Conversation ${i}`,+ titleSource: 'prompt',+ ...over+})++describe('WelcomeScreen — Recent conversations', () => {+ let root: Root+ let host: HTMLElement+ beforeEach(() => {+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+ })+ afterEach(() => {+ act(() => root.unmount())+ host.remove()+ })+ const render = async (el: React.ReactElement): Promise<void> => {+ await act(async () => root.render(el))+ }++ it('is not drawn when the list was not read — a failed read is never "no conversations"', async () => {+ await render(<WelcomeScreen {...base} />)+ expect(host.querySelector('.welcome__recent--convs')).toBeNull()+ })++ it('groups by folder, labels each row with its action, and resumes on click / Enter', async () => {+ const onResume = vi.fn()+ const items = [conv(1), conv(2, { cwd: '/srv/other', agentId: 'codex' })]+ await render(+ <WelcomeScreen+ {...base}+ recentConversations={items}+ recentActionFor={(c) => ({ label: c.agentId === 'codex' ? 'Go to node' : 'Resume in Web' })}+ onResumeRecent={onResume}+ />+ )+ const folders = [...host.querySelectorAll('.welcome__convs-folder')].map((f) => f.firstChild?.textContent)+ expect(folders).toEqual(['demo', 'other'])+ const rows = host.querySelectorAll<HTMLElement>('.welcome__conv')+ expect([...rows].map((r) => r.querySelector('.welcome__conv-action')?.textContent)).toEqual(['Resume in Web', 'Go to node'])+ act(() => rows[0].click())+ expect(onResume).toHaveBeenCalledWith(items[0])+ act(() => rows[1].dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })))+ expect(onResume).toHaveBeenLastCalledWith(items[1])+ })++ it('keeps a refused row visible, disabled, with its reason — and clicking it does nothing', async () => {+ const onResume = vi.fn()+ await render(+ <WelcomeScreen+ {...base}+ recentConversations={[conv(1)]}+ recentActionFor={() => ({ label: 'Cannot resume', disabled: 'The history does not say which folder' })}+ onResumeRecent={onResume}+ />+ )+ const row = host.querySelector<HTMLElement>('.welcome__conv')!+ expect(row.getAttribute('aria-disabled')).toBe('true')+ expect(row.getAttribute('title')).toContain('does not say which folder')+ act(() => row.click())+ expect(onResume).not.toHaveBeenCalled()+ })++ it('renders a hostile title as text, never markup', async () => {+ await render(+ <WelcomeScreen+ {...base}+ recentConversations={[conv(1, { title: '<img src=x onerror=alert(1)>' })]}+ recentActionFor={() => ({ label: 'Resume in Web' })}+ onResumeRecent={noop}+ />+ )+ expect(host.querySelector('.welcome__conv-title img')).toBeNull()+ expect(host.querySelector('.welcome__conv-title')?.textContent).toBe('<img src=x onerror=alert(1)>')+ })++ it('shows the newest few, with a way to see all', async () => {+ const items = Array.from({ length: RECENT_CONVERSATIONS_VISIBLE + 4 }, (_, i) => conv(i))+ await render(+ <WelcomeScreen {...base} recentConversations={items} recentActionFor={() => ({ label: 'x' })} onResumeRecent={noop} />+ )+ expect(host.querySelectorAll('.welcome__conv')).toHaveLength(RECENT_CONVERSATIONS_VISIBLE)+ const more = host.querySelector<HTMLButtonElement>('.welcome__convs-more')!+ expect(more.textContent).toBe(`Show all ${items.length}`)+ act(() => more.click())+ expect(host.querySelectorAll('.welcome__conv')).toHaveLength(items.length)+ })+})diff --git a/src/renderer/components/RecentConversations.tsx b/src/renderer/components/RecentConversations.tsxnew file mode 100644index 000000000..0ae0236a8--- /dev/null+++ b/src/renderer/components/RecentConversations.tsx@@ -0,0 +1,81 @@+import { useMemo, useState } from 'react'+import type { RecentConversation } from '@shared/recent-conversations'+import { AgentIcon } from '../lib/agentIcons'+import { relativeTime } from '../lib/relativeTime'+import { folderLabel, groupRecentByFolder, recentTitle } from '../lib/recentConversations'++/** Rows the start screen shows before "Show all" — the list is a door back into work, not an archive. */+export const RECENT_CONVERSATIONS_VISIBLE = 8++export interface RecentConversationsProps {+ items: readonly RecentConversation[]+ /** What clicking a row does, in words; `disabled` is the reason it cannot. */+ actionFor: (conv: RecentConversation) => { label: string; disabled?: string }+ onResume: (conv: RecentConversation) => void+ /** Injected for tests; the render-time clock otherwise. */+ now?: number+}++/**+ * "Recent conversations" on the start screen: past agent conversations from this machine's CLI+ * histories, grouped by the folder they ran in. A row resumes the conversation in the project that+ * owns that folder (or opens the folder as one); a conversation a node already holds says "Go to+ * node" instead. A row that cannot be resumed stays visible, disabled, with its reason — a row that+ * silently vanished would take the reason with it.+ */+export function RecentConversations({ items, actionFor, onResume, now }: RecentConversationsProps) {+ const [showAll, setShowAll] = useState(false)+ const at = now ?? Date.now()+ const shown = showAll ? items : items.slice(0, RECENT_CONVERSATIONS_VISIBLE)+ const groups = useMemo(() => groupRecentByFolder(shown), [shown])+ if (items.length === 0) return null+ return (+ <div className="welcome__recent welcome__recent--convs">+ <div className="welcome__recent-title">Recent conversations</div>+ <div className="welcome__recent-list welcome__convs-list">+ {groups.map((g) => (+ <div key={g.cwd ?? '\0'} className="welcome__convs-group">+ <div className="welcome__convs-folder" title={g.cwd ?? 'The history does not name a folder'}>+ {folderLabel(g.cwd)}+ {g.cwd && <span className="welcome__recent-path">{g.cwd}</span>}+ </div>+ {g.items.map((conv) => {+ const action = actionFor(conv)+ const disabled = !!action.disabled+ const run = (): void => {+ if (!disabled) onResume(conv)+ }+ return (+ <div+ key={`${conv.agentId}:${conv.sessionId}`}+ className={`welcome__recent-item welcome__conv${disabled ? ' welcome__conv--disabled' : ''}`}+ role="button"+ tabIndex={0}+ aria-disabled={disabled || undefined}+ title={action.disabled ?? `${action.label} — ${conv.agentId} ${conv.sessionId}`}+ onClick={run}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault()+ run()+ }+ }}+ >+ <AgentIcon agentId={conv.agentId} />+ <span className="welcome__conv-title">{recentTitle(conv)}</span>+ <span className="welcome__conv-age">{relativeTime(conv.lastActiveAt, at)}</span>+ <span className="welcome__conv-action">{action.label}</span>+ </div>+ )+ })}+ </div>+ ))}+ </div>+ {items.length > RECENT_CONVERSATIONS_VISIBLE && (+ <button className="welcome__convs-more" onClick={() => setShowAll((v) => !v)}>+ {showAll ? 'Show fewer' : `Show all ${items.length}`}+ </button>+ )}+ </div>+ )+}diff --git a/src/renderer/components/WelcomeScreen.tsx b/src/renderer/components/WelcomeScreen.tsxindex 8971fdd35..07a310312 100644--- a/src/renderer/components/WelcomeScreen.tsx+++ b/src/renderer/components/WelcomeScreen.tsx@@ -3,6 +3,8 @@ import { IconClose } from './icons'import type { ProjectIcon } from '@shared/project-icon'import { filterClosedProjects } from '../lib/closedHistory'import { ProjectGlyph } from './ProjectGlyph'+import type { RecentConversation } from '@shared/recent-conversations'+import { RecentConversations } from './RecentConversations'/*** Rows before the "Recently closed" filter box appears (issue #506). `.welcome__recent-list` is@@ -40,6 +42,11 @@ interface WelcomeScreenProps {* nothing appeared. No effect on the canvas, where the welcome screen already sits on top.*/overBoard?: boolean+ /** "Open recent": past agent conversations from this machine's CLI histories. Absent = not read+ * (or the read failed) — the section is simply not drawn, never "no conversations". */+ recentConversations?: readonly RecentConversation[]+ recentActionFor?: (conv: RecentConversation) => { label: string; disabled?: string }+ onResumeRecent?: (conv: RecentConversation) => void}/** Start screen with quick actions — shown when there are no projects, or on demand via "+". */@@ -53,7 +60,10 @@ export function WelcomeScreen({onReopen,onDeleteClosed,onClose,- overBoard+ overBoard,+ recentConversations,+ recentActionFor,+ onResumeRecent}: WelcomeScreenProps) {const [query, setQuery] = useState('')const visibleClosed = useMemo(@@ -158,6 +168,14 @@ export function WelcomeScreen({</button></div>+ {recentConversations && recentActionFor && onResumeRecent && (+ <RecentConversations+ items={recentConversations}+ actionFor={recentActionFor}+ onResume={onResumeRecent}+ />+ )}+{closedProjects.length > 0 && (<div className="welcome__recent"><div className="welcome__recent-title">Recently closed</div>diff --git a/src/renderer/lib/recentConversations.test.ts b/src/renderer/lib/recentConversations.test.tsnew file mode 100644index 000000000..65cb75484--- /dev/null+++ b/src/renderer/lib/recentConversations.test.ts@@ -0,0 +1,145 @@+import { describe, it, expect } from 'vitest'+import {+ groupRecentByFolder,+ heldSessions,+ localCodexAccountIds,+ planResume,+ RESUME_REFUSALS,+ resumeActionLabel,+ type ResumeContext+} from './recentConversations'+import type { RecentConversation } from '@shared/recent-conversations'++const SID = '5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32'+const conv = (over: Partial<RecentConversation> = {}): RecentConversation => ({+ agentId: 'claude',+ sessionId: SID,+ cwd: '/srv/demo',+ lastActiveAt: 1,+ title: 't',+ titleSource: 'prompt',+ ...over+})+const ctx = (over: Partial<ResumeContext> = {}): ResumeContext => ({+ projects: [],+ activeProjectId: '',+ held: [],+ claudeAccounts: [],+ codexAccounts: [],+ ...over+})++describe('planResume', () => {+ it('focuses the node that already holds the session instead of resuming it twice', () => {+ const plan = planResume(+ conv(),+ ctx({+ projects: [{ id: 'p1', cwd: '/srv/demo' }] as never,+ held: [{ nodeId: 'n7', projectId: 'p2', sessionIds: [undefined, 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'] }] }))+ expect(plan.kind).toBe('focus')+ })++ it('resumes in the LOCAL project whose cwd is the conversation’s; prefers active, then open', () => {+ const projects = [+ { id: 'closed', cwd: '/srv/demo', closed: true },+ { id: 'ssh', cwd: '/srv/demo', ssh: { server: {}, remoteCwd: '/srv/demo' } },+ { id: 'relay', cwd: '/srv/demo', remote: true },+ { id: 'gone', cwd: '/srv/demo', unavailable: true },+ { id: 'open', cwd: '/srv/demo/' }+ ] as never+ expect(planResume(conv(), ctx({ projects }))).toEqual({ kind: 'resume', projectId: 'open', reopen: false })+ expect(planResume(conv(), ctx({ projects, activeProjectId: 'closed' }))).toEqual({+ kind: 'resume',+ projectId: 'closed',+ reopen: true+ })+ })++ it('reopens a closed project when it is the only match', () => {+ const plan = planResume(conv(), ctx({ projects: [{ id: 'c', cwd: '/srv/demo', closed: true }] as never }))+ expect(plan).toEqual({ kind: 'resume', projectId: 'c', reopen: true })+ })++ it('never resumes into an SSH project or a relay tab — those cwds are on another machine', () => {+ const projects = [+ { id: 'ssh', cwd: '/srv/demo', ssh: { server: {}, remoteCwd: '/srv/demo' } },+ { id: 'relay', cwd: '/srv/demo', remote: true }+ ] as never+ expect(planResume(conv(), ctx({ projects }))).toEqual({ kind: 'open-folder', folder: '/srv/demo' })+ })++ it('offers to open the folder when no project owns it', () => {+ expect(planResume(conv(), ctx())).toEqual({ kind: 'open-folder', folder: '/srv/demo' })+ })++ it('refuses an unsafe session id before planning anything', () => {+ for (const bad of ['-rf', 'a;b', '$(id)']) {+ expect(planResume(conv({ sessionId: bad }), ctx())).toEqual({ kind: 'refuse', reason: RESUME_REFUSALS.unsafeId })+ }+ })++ it('refuses when the history names no folder', () => {+ expect(planResume(conv({ cwd: null }), ctx())).toEqual({ kind: 'refuse', reason: RESUME_REFUSALS.noCwd })+ })++ it('refuses a conversation whose account is gone, pending or host-pinned — never the system login', () => {+ const c = conv({ accountId: 'work' })+ expect(planResume(c, ctx()).kind).toBe('refuse')+ expect(planResume(c, ctx({ claudeAccounts: [{ id: 'work', pending: true }] as never })).kind).toBe('refuse')+ expect(planResume(c, ctx({ claudeAccounts: [{ id: 'work', host: 'me@box' }] as never })).kind).toBe('refuse')+ expect(planResume(c, ctx({ claudeAccounts: [{ id: 'work' }] as never })).kind).toBe('open-folder')+ const x = conv({ agentId: 'codex', accountId: 'cw' })+ expect(planResume(x, ctx({ claudeAccounts: [{ id: 'cw' }] as never })).kind).toBe('refuse')+ expect(planResume(x, ctx({ codexAccounts: [{ id: 'cw' }] as never })).kind).toBe('open-folder')+ // An agent with no managed accounts that claims one is not trusted.+ expect(planResume(conv({ agentId: 'gemini', accountId: 'work' }), ctx({ claudeAccounts: [{ id: 'work' }] as never })).kind).toBe('refuse')+ })+})++describe('heldSessions', () => {+ it('reads the live canvas for the active project and the store for the rest', () => {+ const projects = [+ { id: 'a', nodes: [{ id: 'stale', agentSessionId: 'old' }] },+ { id: 'b', nodes: [{ id: 'n2', agentSessionId: 'x2' }] }+ ] as never+ const 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'] }+ ])+ })+})++describe('presentation', () => {+ it('groups by folder, groups ordered by their newest row', () => {+ const g = groupRecentByFolder([+ conv({ sessionId: 'a', cwd: '/x', lastActiveAt: 1 }),+ conv({ sessionId: 'b', cwd: '/y', lastActiveAt: 5 }),+ conv({ sessionId: 'c', cwd: '/x', lastActiveAt: 3 }),+ conv({ sessionId: 'd', cwd: null, lastActiveAt: 2 })+ ])+ expect(g.map((x) => [x.cwd, x.items.map((i) => i.sessionId)])).toEqual([+ ['/y', ['b']],+ ['/x', ['c', 'a']],+ [null, ['d']]+ ])+ })++ it('labels each plan', () => {+ const name = (): string => 'Web'+ expect(resumeActionLabel({ kind: 'focus', nodeId: 'n', projectId: 'p' }, name)).toBe('Go to node')+ expect(resumeActionLabel({ kind: 'resume', projectId: 'p', reopen: false }, name)).toBe('Resume in Web')+ expect(resumeActionLabel({ kind: 'open-folder', folder: '/x' }, name)).toBe('Open folder & resume')+ })++ it('sends core only local, settled codex account ids', () => {+ expect(localCodexAccountIds([{ id: 'a' }, { id: 'b', host: 'h' }, { id: 'c', pending: true }] as never)).toEqual(['a'])+ })+})diff --git a/src/renderer/lib/recentConversations.ts b/src/renderer/lib/recentConversations.tsnew file mode 100644index 000000000..658f66698--- /dev/null+++ b/src/renderer/lib/recentConversations.ts@@ -0,0 +1,166 @@+// "Open recent" — the pure half: where a past conversation should be resumed, and how the list is+// grouped. Canvas executes the plan; nothing here touches a store or the disk.+//+// The rules, each a refusal or a dedupe the feature would be wrong without:+// - A conversation already held by a node (the node's live hook-fed id, else the id it persisted)+// is FOCUSED, never resumed twice — two CLIs writing one transcript interleave it.+// - The session id is re-validated (`canResumeWith` = SAFE_SESSION_ID) before anything is planned:+// it came off disk, and the plan ends with it on a typed command line.+// - Resume happens only in a LOCAL folder project whose cwd is exactly the conversation's. The+// history is this machine's, so an SSH project (its cwd is on the host) and a relay tab (another+// machine's project) never match. No project → offer to open the folder as one.+// - The conversation must run under the account whose config dir holds it: a managed/linked+// account that is gone (or pending, or pinned to a host) refuses rather than resuming under the+// system login, where the CLI would answer "No conversation found".+import type { ClaudeAccount, Project } from '@shared/types'+import type { CodexAccount } from '@shared/codex-account'+import { canResumeWith } from '@shared/agents/config'+import type { RecentConversation } from '@shared/recent-conversations'++export type ResumePlan =+ | { kind: 'focus'; nodeId: string; projectId: string }+ | { kind: 'resume'; projectId: string; reopen: boolean }+ | { 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.',+ accountGone: 'The account this conversation belongs to is no longer set up on this machine.'+} as const++/** A node's session as the planner needs it: its id, its project, the ids it could be holding. */+export interface HeldSession {+ nodeId: string+ projectId: string+ /** The live hook-fed id (wins), and the persisted `agentSessionId`. */+ sessionIds: Array<string | undefined>+}++export interface ResumeContext {+ projects: readonly Pick<Project, 'id' | 'cwd' | 'ssh' | 'closed' | 'unavailable' | 'remote'>[]+ activeProjectId: string+ held: readonly HeldSession[]+ claudeAccounts: readonly Pick<ClaudeAccount, 'id' | 'host' | 'pending'>[]+ codexAccounts: readonly Pick<CodexAccount, 'id' | 'host' | 'pending'>[]+}++/** Every node holding a session, from the live canvas (active project) and the stored projects.+ * The live copy of the active project wins: the store lags it by an autosave. */+export function heldSessions(+ projects: readonly Pick<Project, 'id' | 'nodes'>[],+ activeProjectId: string,+ liveNodes: ReadonlyArray<{ id: string; data?: { agentSessionId?: unknown } }>,+ liveSessionId: (nodeId: string) => string | undefined+): HeldSession[] {+ const out: HeldSession[] = []+ const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)+ for (const n of liveNodes) {+ out.push({+ nodeId: n.id,+ projectId: activeProjectId,+ sessionIds: [liveSessionId(n.id), str(n.data?.agentSessionId)]+ })+ }+ for (const p of projects) {+ if (p.id === activeProjectId && liveNodes.length) continue+ for (const n of p.nodes ?? []) {+ out.push({+ nodeId: n.id,+ projectId: p.id,+ sessionIds: [liveSessionId(n.id), str((n as { agentSessionId?: unknown }).agentSessionId)]+ })+ }+ }+ return out+}++export function findHolder(conv: RecentConversation, held: readonly HeldSession[]): HeldSession | undefined {+ return held.find((h) => h.sessionIds.some((id) => id === conv.sessionId))+}++function accountUsable(conv: RecentConversation, ctx: ResumeContext): boolean {+ if (!conv.accountId) return true+ if (conv.agentId === 'claude') {+ return ctx.claudeAccounts.some((a) => a.id === conv.accountId && !a.host && !a.pending)+ }+ if (conv.agentId === 'codex') {+ return ctx.codexAccounts.some((a) => a.id === conv.accountId && !a.host && !a.pending)+ }+ // Only claude and codex have managed accounts; anything else naming one is not ours to trust.+ 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)+}++export function planResume(conv: RecentConversation, ctx: ResumeContext): ResumePlan {+ // A conversation that is already open is where the user is going, whatever else is true.+ const holder = findHolder(conv, ctx.held)+ if (holder) return { kind: 'focus', nodeId: holder.nodeId, projectId: holder.projectId }+ if (!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 }+}++/** The action a row offers, in words. */+export function resumeActionLabel(plan: ResumePlan, projectName: (id: string) => string): string {+ switch (plan.kind) {+ case 'focus':+ return 'Go to node'+ case 'resume':+ return `Resume in ${projectName(plan.projectId)}`+ case 'open-folder':+ return 'Open folder & resume'+ case 'refuse':+ return 'Cannot resume'+ }+}++export interface RecentFolderGroup {+ /** null = the conversations whose history does not name a folder. */+ cwd: string | null+ items: RecentConversation[]+}++/** Group by folder, groups ordered by their newest conversation, rows newest-first within. */+export function groupRecentByFolder(items: readonly RecentConversation[]): RecentFolderGroup[] {+ const groups = new Map<string, RecentFolderGroup>()+ const sorted = [...items].sort((a, b) => b.lastActiveAt - a.lastActiveAt)+ for (const it of sorted) {+ const key = it.cwd ?? '\0'+ let g = groups.get(key)+ if (!g) groups.set(key, (g = { cwd: it.cwd, items: [] }))+ g.items.push(it)+ }+ return [...groups.values()]+}++/** The last path segment, for a compact folder label. */+export function folderLabel(cwd: string | null): string {+ if (!cwd) return 'Unknown folder'+ const segs = cwd.split(/[/\\]+/).filter(Boolean)+ return segs[segs.length - 1] ?? cwd+}++/** The display title, never empty. */+export function recentTitle(conv: RecentConversation): string {+ return conv.title || `Untitled ${conv.agentId} conversation`+}++/** The managed Codex homes this machine may read: local, settled accounts only (a host-pinned+ * account's home is on that host; a pending one has never logged in). */+export function localCodexAccountIds(accounts: readonly Pick<CodexAccount, 'id' | 'host' | 'pending'>[]): string[] {+ return accounts.filter((a) => a && typeof a.id === 'string' && !a.host && !a.pending).map((a) => a.id)+}diff --git a/src/renderer/state/workspace.resume.test.ts b/src/renderer/state/workspace.resume.test.tsnew file mode 100644index 000000000..18193e7b4--- /dev/null+++ b/src/renderer/state/workspace.resume.test.ts@@ -0,0 +1,62 @@+import { describe, it, expect, afterEach } from 'vitest'+import { createAgentNode } from './workspace'+import { useSettings } from './settings'+import { DEFAULT_SETTINGS } from '@shared/types'++/**+ * `createAgentNode`'s resume path ("Open recent", a transcript-search hit): the node runs the CLI's+ * OWN resume line through the same assembler cold restore uses, and persists the resumed id — never+ * a freshly minted one it never ran, which would make a later cold restore open a blank session.+ */+afterEach(() => useSettings.setState({ settings: DEFAULT_SETTINGS }))++const SID = '5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32'+const resumed = (agentId: string, sessionId: string, accountId?: string, mode?: 'manual' | 'bypassPermissions') =>+ createAgentNode(agentId, 0, '/srv/demo', undefined, undefined, undefined, accountId, mode, undefined, undefined, undefined, sessionId)++describe('createAgentNode — resume', () => {+ it.each([+ ['claude', `claude --resume ${SID}`],+ ['codex', `codex resume ${SID}`],+ ['gemini', `gemini --resume ${SID}`],+ ['grok', `grok --resume ${SID}`],+ ['copilot', `copilot --resume=${SID}`]+ ])('%s types its own resume grammar and persists the resumed id', (agentId, line) => {+ const node = resumed(agentId, SID)+ expect(node.data.initialCommand).toBe(line)+ expect(node.data.agentSessionId).toBe(SID)+ expect(node.data.cwd).toBe('/srv/demo')+ })++ it('applies the permission mode through the same funnel as a fresh launch', () => {+ expect(resumed('claude', SID, undefined, 'bypassPermissions').data.initialCommand).toBe(+ `claude --resume ${SID} --permission-mode bypassPermissions`+ )+ })++ it('resumes through a launch-command override, like cold restore', () => {+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, agentLaunchCommands: { claude: 'my-claude' } } })+ expect(resumed('claude', SID).data.initialCommand).toBe(`my-claude --resume ${SID}`)+ })++ it('binds the account that holds the history (claude), and none for an agent without accounts', () => {+ expect(resumed('claude', SID, 'work').data.accountId).toBe('work')+ expect(resumed('gemini', SID, 'work').data.accountId).toBeUndefined()+ })++ it('refuses an unsafe id instead of silently starting a fresh conversation', () => {+ for (const bad of ['-rf', 'a;id', '$(id)', '', ' x y ']) {+ expect(() => resumed('claude', bad)).toThrow(/refusing to resume/)+ }+ })++ it('refuses an agent that has no resume grammar', () => {+ expect(() => resumed('custom:nothing', SID)).toThrow(/refusing to resume/)+ })++ it('a fresh launch is untouched: no resume id means the old command line', () => {+ const fresh = createAgentNode('codex', 0, '/srv/demo')+ expect(fresh.data.initialCommand).toBe('codex')+ expect(fresh.data.agentSessionId).toBeUndefined()+ })+})diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 41eeedbe3..c59a3fdab 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -12,11 +12,12 @@ import { DEFAULT_SETTINGS } from '@shared/types'import type { AgentId, AgentPermissionMode, BuiltinAgentId } from '@shared/agents/config'import {agentConfig,+ canResumeWith,capabilityAgentId,FALLBACK_AGENT_COLOR,supportsSessionIdFlag} from '@shared/agents/config'-import { assembleLaunchCommand } from '@shared/agents/launch'+import { assembleLaunchCommand, assembleResumeCommand } from '@shared/agents/launch'import { agentAccountColor } from '@shared/agents/account-color'import { boundAccountId } from '@shared/agents/account-binding'import { agentEnvSnapshot } from '../lib/agentEnv'@@ -637,7 +638,15 @@ export function createAgentNode(* brief survives the single-line typed delivery. Validated by the caller* (`promptFilePathError` + an existence check) — the factory trusts it. Trailing/optional so* every existing caller is unchanged. */- promptFile?: string+ promptFile?: string,+ /** RESUME this provider session instead of starting a new one ("Open recent", a transcript-search+ * hit). The line comes from the SAME resume assembler cold restore uses (`assembleResumeCommand`:+ * launch override, custom args, codex launcher, permission flag, model), no id is minted, and the+ * node persists THIS id as `agentSessionId`, so a later cold restore resumes the same+ * conversation. An id the resume grammar refuses (`resumeCommandWith` re-validates it against+ * SAFE_SESSION_ID) yields NO node-level resume: the caller must check `canResumeWith` first —+ * this factory never silently starts a fresh conversation under a resume request, it throws. */+ resumeSessionId?: string): CanvasNode {const { label, color: agentColor } = resolveAgent(agentId)// ONE binding decision, shared with the phone-registration path (core/project-node-append) so@@ -686,7 +695,7 @@ export function createAgentNode(// synchronous against a warmed per-cwd memo (see grokSessionIds.ts for why the first mint in a// fresh cwd is deliberately unchecked), and `mintFreeGrokSessionId` returns undefined rather than// a taken id — which degrades to the pre-minting command line instead of a dead terminal.- const mintedSessionId = !sessionIdFlagSupported+ const mintedSessionId = resumeSessionId !== undefined || !sessionIdFlagSupported? undefined: capabilityAgentId(agentId) === 'grok'? (ensureGrokTakenIds(cwd ?? ''), mintFreeGrokSessionId(grokTakenIdsNow(cwd ?? ''), uuid))@@ -701,7 +710,22 @@ export function createAgentNode(const customAgent = agentConfig(agentId)? undefined: useSettings.getState().settings.customAgents.find((c) => c.id === agentId)- const { command: initialCommand, missingEnv } = assembleLaunchCommand(+ const resumeInputs = {+ agentId,+ customAgent,+ launchCmdOverride,+ sessionId: resumeSessionId,+ permissionMode,+ model,+ sharedIdentity: codexSharedIdentity(ssh),+ approvalCaps: codexApprovalCaps(ssh)+ }+ if (resumeSessionId !== undefined && !canResumeWith(capabilityAgentId(agentId), resumeSessionId)) {+ throw new Error(`createAgentNode: refusing to resume ${agentId} session ${JSON.stringify(resumeSessionId)}`)+ }+ const { command: initialCommand, missingEnv } = resumeSessionId !== undefined+ ? assembleResumeCommand(resumeInputs, agentEnvSnapshot())+ : assembleLaunchCommand({agentId,customAgent,@@ -757,6 +781,8 @@ export function createAgentNode(// Persisted alongside the node (unlike initialCommand, which is consumed on first open), so// a cold restore months later still knows which conversation this node owns....(mintedSessionId ? { agentSessionId: mintedSessionId } : {}),+ // A resumed conversation's own id: what cold restore falls back to before a hook names one.+ ...(resumeSessionId !== undefined ? { agentSessionId: resumeSessionId.trim() } : {}),// A model chosen at creation (Transfer-to-agent-with-model). Persisted so cold-restore and// later restarts keep it; `withAgentModel` re-applies it on relaunch. Only stamped when set....(model ? { agentModel: model } : {}),diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 3a38df8ad..03f644cd4 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -4199,6 +4199,81 @@ body,color: var(--danger);}+/* ---- "Recent conversations" on the start screen (core/recent-conversations.ts) ---- */+.welcome__convs-list {+ max-height: 300px;+ gap: 2px;+}++.welcome__convs-group + .welcome__convs-group {+ margin-top: 6px;+}++.welcome__convs-folder {+ display: flex;+ align-items: baseline;+ gap: 8px;+ padding: 2px 10px;+ font-size: 11px;+ font-weight: 600;+ color: var(--muted);+}++.welcome__convs-folder .welcome__recent-path {+ font-weight: 400;+}++.welcome__conv-title {+ flex: 1;+ min-width: 0;+ font-size: 13px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.welcome__conv-age {+ flex: none;+ font-size: 11px;+ color: var(--muted);+}++.welcome__conv-action {+ flex: none;+ font-size: 11px;+ color: var(--accent);+ opacity: 0;+ transition: opacity 0.12s;+}++.welcome__conv:hover .welcome__conv-action,+.welcome__conv:focus-visible .welcome__conv-action {+ opacity: 1;+}++.welcome__conv--disabled {+ cursor: default;+ opacity: 0.55;+}++.welcome__conv--disabled .welcome__conv-action {+ color: var(--muted);+}++.welcome__convs-more {+ margin-top: 4px;+ padding: 2px 10px;+ font-size: 11px;+ color: var(--muted);+ background: transparent;+ border: none;+ cursor: pointer;+}++.welcome__convs-more:hover {+ color: var(--text);+}+/* ---- Right-click context menu ---- */.ctx-backdrop {position: fixed;diff --git a/src/server/index.ts b/src/server/index.tsindex 4087c1443..c57d32c3d 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -106,6 +106,7 @@ import { wireAgentStatus } from './agent-status'import { initServerContextLink } from './context-link'import { createServerWorkspaceWatcher, outsideEditPublisher } from './workspace-external-watch'import { registerTranscriptIpc } from '../core/transcript-ipc'+import { registerRecentConversationsIpc } from '../core/recent-conversations'import { registerContextEnsureIpc } from '../core/context-ensure'import { IPC } from '@shared/ipc'import { WhisperModelStore } from '../core/speech/whisper-models'@@ -522,6 +523,8 @@ export async function startServer(// Codex's ⌘M reader takes ITS tail's hook path (claude's `pathFor` must never answer a codex id).codexPathFor: (sessionId) => codexContextTail.pathFor(sessionId)})+ // "Open recent": the SERVER host's agent histories — the machine the browser's sessions run on.+ registerRecentConversationsIpc()// The context meter's mount-time rehydration, registered beside the read channels and for the// same reason: the tails it feeds are the ones created just above. Until this landed the Server// Edition had NO handler for `context:ensure` at all — the browser cast it and nothing receiveddiff --git a/src/shared/host-control.ts b/src/shared/host-control.tsindex 08661f079..879ec0cb6 100644--- a/src/shared/host-control.ts+++ b/src/shared/host-control.ts@@ -82,6 +82,10 @@ export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([IPC.stationOutcomeList,// Same class: which of the host's stations (any project) have work handed to them.IPC.stationHandoverList,+ // "Open recent": the host's conversation history — titles are prompts the host's user typed, in+ // every project. A relay tab lists its OWN machine's history (relay-api keeps it `...local`), so+ // no legitimate peer asks the host for this.+ IPC.recentConversationsList,// The host's settings. `settings:save` is the dangerous half: `modelGateway.baseUrl` is the TRUST// ANCHOR `agent:discover-models` uses to decide whether it may resolve the stored// `${secret:model-gateway-api-key}` (core/agent-env-ipc.ts), so a peer that could save settingsdiff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 6c5293abe..a0c75ec34 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -63,6 +63,8 @@ export const IPC = {* (`present | absent | unknown`) — see `TranscriptPresence`. The one caller that ACTS on a* negative is cold restore, so "we could not look" must never read as "it is gone". */transcriptExists: 'transcript:exists',+ /** "Open recent": the newest agent conversations on THIS machine's disk (core/recent-conversations.ts). */+ recentConversationsList: 'recent-conversations:list',claudeAccountsAdd: 'claude-accounts:add',claudeAccountsWaitLogin: 'claude-accounts:wait-login',claudeAccountsCancelWait: 'claude-accounts:cancel-wait',diff --git a/src/shared/recent-conversations.ts b/src/shared/recent-conversations.tsnew file mode 100644index 000000000..97f7443e5--- /dev/null+++ b/src/shared/recent-conversations.ts@@ -0,0 +1,71 @@+// "Open recent": the agent conversations this machine's CLIs have on disk, listed so one can be+// resumed from its own history instead of only from a node that happens to remember its id.+//+// Shared because three sides speak it: core reads it (`core/recent-conversations.ts`), both+// shells serve it over `recent-conversations:list`, and the renderer groups and resumes it. No+// imports beyond the agent id list — usable everywhere.+import type { AgentId } from './agents/config'++/**+ * The agents whose history core can read, and ONLY those. Each is in `RESUMABLE_AGENTS` (the+ * resume line comes from `resumeCommandWith`) AND has an on-disk shape measured here:+ * - claude — `<config dir>/projects/<cwd>/<id>.jsonl`, per record `cwd`; system, managed and+ * linked accounts.+ * - codex — `<codex home>/sessions/YYYY/MM/DD/rollout-*.jsonl`, first line `session_meta`+ * (`id`, `cwd`, `thread_source`); system and managed accounts.+ * - gemini — `~/.gemini/tmp/<project>/chats/session-*.jsonl` + the project's `.project_root`.+ * - grok — `$GROK_HOME/sessions/<url-encoded cwd>/<id>/`.+ * - copilot — `<copilot home>/session-state/<id>/events.jsonl`, `session.start` `context.cwd`.+ *+ * Deliberately absent: opencode (its history is a SQLite database we never open; the only reader+ * is `opencode export`, one CLI spawn of ~1.5 s and ~320 MB per session — far too heavy for a+ * list) and antigravity (its transcript record shapes were never captured). An agent absent here+ * simply contributes no rows; nothing guesses at its layout.+ */+export const RECENT_CONVERSATION_AGENTS = ['claude', 'codex', 'gemini', 'grok', 'copilot'] as const+export type RecentConversationAgent = (typeof RECENT_CONVERSATION_AGENTS)[number]++export function isRecentConversationAgent(id: AgentId | string): id is RecentConversationAgent {+ return (RECENT_CONVERSATION_AGENTS as readonly string[]).includes(id)+}++/** Longest title we hand to a surface, in code points. A title is display text, never a name. */+export const RECENT_TITLE_MAX = 120++/** Newest conversations returned in total (every agent and account together). */+export const RECENT_CONVERSATIONS_MAX = 60++export interface RecentConversation {+ agentId: RecentConversationAgent+ /** The CLI's own session id — re-validated (`SAFE_SESSION_ID`) before it reaches a command. */+ sessionId: string+ /** The absolute directory the conversation ran in, or null when the history does not say. */+ cwd: string | null+ /** Last activity: the transcript's modification time, epoch ms. */+ lastActiveAt: number+ /** One line of display text: the agent's own session name when it has one, else the first thing+ * the user typed. Untrusted input made safe: no control, bidi or zero-width characters, capped. */+ title: string+ /** Where `title` came from — `none` means neither existed and the title is empty. */+ titleSource: 'name' | 'prompt' | 'none'+ /** 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+}++export interface RecentConversationsRequest {+ /** Managed Codex account ids to include (the renderer owns that list; core re-validates each). */+ codexAccountIds?: string[]+ /** Cap on the result; clamped to [1, RECENT_CONVERSATIONS_MAX]. */+ limit?: number+}++export type RecentConversationsResult =+ | { ok: true; items: RecentConversation[] }+ /** Could not look at all (a relay tab, a failed call) — never shown as "no conversations". */+ | { ok: false; reason: 'unsupported' | 'failed' }++export interface RecentConversationsApi {+ /** Never rejects on the real legs: a failure is `{ok:false}`, never an empty list. */+ list(req?: RecentConversationsRequest): Promise<RecentConversationsResult>+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 2e32a6b2e..41f9304a4 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -4035,6 +4035,8 @@ export interface NodeTerminalApi {githubControl: import('./github-issues').GitHubControlApiusage: UsageApisessionMemory: SessionMemoryApi+ /** "Open recent" — the newest agent conversations in this machine's CLI histories. */+ recentConversations: import('./recent-conversations').RecentConversationsApiwallpaper: import('./wallpaper').WallpaperApitriggers: TriggersApicontext: ContextApi