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(chat): the ⌘M composer completes slash commands, skills and @files
reviewe2ad5261990f
diff --git a/CLAUDE.md b/CLAUDE.mdindex a81a8d718..f0e167d7c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -3163,6 +3163,65 @@ command-bearing opens; this does not add a human-confirm dialog or change mobilea modal showing the LIVE terminal still targets it), a chat view with no composer refuses, andotherwise it is the terminal as before. Every refusal says so in one `nodeterm:toast`(`announceChatDictationRefusal`, naming the composer mic) instead of a silent dead key.+- **The composer completes `/` and `@` (2026-09-30).** Typing `/` at the START of the message (after+ optional whitespace — every CLI measured reads `/x` mid-sentence as text) opens a menu of the+ node's CATALOG; `@` at the start of a word opens the node's files. Arrows move, Enter/Tab ACCEPT,+ Esc closes the menu only (CardModal's capture-phase Esc already stands aside inside+ `.term-chat__compose`). **Accepting only inserts text** (`/name ` / `@path `): nothing is typed into+ the pane, and the send is still the composer's own gated Enter (`chatSendRefusal`) — completing+ `/clear` then pressing Enter is exactly typing it. **Enter accepts only when accepting CHANGES the+ draft**: a fully typed `/model` with the menu still open is a message and Enter sends it (the+ first version swallowed it, and `ChatPanel.live.test.tsx` caught the regression). Pure decisions in+ `renderer/lib/chatComposerComplete.ts`; the wire shape, sanitizer, measured tables and ranking in+ `@shared/chat-catalog`; the builder in `core/chat-catalog.ts` behind `chat:catalog`+ (`registerChatCatalogIpc`, registered by BOTH shells). Rules a refactor must not undo:+ - **Built-ins are only what was MEASURED** (2026-09-30): claude 2.1.285, codex 0.156.1 and opencode+ 1.18.25 by typing `/` in each TUI inside a private tmux server and paging the whole menu; gemini+ 0.61.0 (no login on the measuring host) from its shipped `docs/reference/commands.md` ∩ the names+ its built-in loader registers; grok 1.0.13 (no login either) from the command reference embedded+ in its binary. Plan-, login- and experiment-gated entries are left out. Any other agent (copilot,+ antigravity, a custom agent with no base) has no table and gets `@` only; a custom agent inherits+ its base's table through `capabilityAgentId`. The descriptions are our own words.+ - **Custom commands and skills: claude and gemini only**, at the measured locations. claude:+ `<configDir>/commands/**/*.md` + `<cwd>/.claude/commands/**/*.md` (measured: a subfolder is a+ `dir:name` namespace; description = frontmatter `description`, else the first body line) and+ `<configDir>/skills/*/SKILL.md` + `<cwd>/.claude/skills/*/SKILL.md` (measured: the frontmatter+ `name` WINS over the folder name, the folder is the fallback, `user-invocable: false` is not+ offered). `<configDir>` is the bound account's dir (`claudeConfigDirFor`, linked accounts+ included), which REPLACES `~/.claude` — never both, and a malformed account id yields NO user+ root, never the system dir in its place (another identity's commands). gemini:+ `~/.gemini/commands/**/*.toml` + `<cwd>/.gemini/commands/**/*.toml` (its shipped+ custom-commands reference). Precedence project > user > built-in, deduped by name. Other agents'+ custom locations were not measured, so they list none — a guessed location offers commands the+ CLI does not have.+ - **Names and descriptions are hostile data** (a project's `.claude/commands` is whatever the+ repository holds): a name passes `catalogName` (closed alphabet `[A-Za-z0-9][A-Za-z0-9._:-]*`,+ ≤ 64, never trimmed) or the entry is dropped; a description is one line with C0/C1 and `\p{Cf}`+ (bidi, zero-width) removed, capped at 160 code points. The renderer re-runs+ `sanitizeChatCatalog` on every reply and renders both as text nodes. `@` never offers a path with+ whitespace, a control or format character, or one failing `isSafeQuickOpenRelPath`.+ - **Cost: nothing is polled.** A composer asks on its first `/` (or `@`) and reuses the answer for+ `CATALOG_REUSE_MS` (30 s). Core caches every directory listing by the directory's mtime and+ every file head (first 4 KB) by (mtime, size), so an unchanged tree costs stats, no reads. Per+ root at most 200 files, commands 3 levels deep.+ - **`@` is the existing quick-open index**, not a new walker: `files.quickOpen(cwd)` on the+ session's api (this machine, or a relay peer's core) or `sshFs.quickOpen(scope, cwd)` for an SSH+ node — gitignore-aware, capped, traversal-guarded — rooted at the node's cwd, ranked by the+ quick-open fuzzy ranker. The SSH scope is the one the composer's attach already uploads through+ (`nodeUploadScope`), passed as ChatPanel's `sshProjectId` from both mount sites.+ - **An SSH node's catalog is read on its HOST, in ONE round trip** (`remoteCatalogCommand`, run over+ the node's master by the desktop's `runRemote`; tested under a real `/bin/sh` against a fake host+ tree). A remote node whose host cannot be asked — or a shell with no remote leg — answers+ built-ins + `partial`, never this machine's folders. Every file's bytes pass `tr -d '\036'`, so a+ hostile file cannot forge a record boundary. Remoteness is the shell's own record+ (`isRemoteTranscriptNode`), never an argument.+ - **Surfaces.** Desktop full (local + SSH). Server Edition full, local only (real ws-bridge+ `chat.catalog`; it runs on the host it reads). Relay tabs: `chat.catalog` REJECTS (stub) and the+ composer offers the shared built-in table alone; `@` uses the peer's own quick-open index, which+ is the right machine. Kanban card modal: the same ChatPanel/composer. **Mobile**: `chat.status`+ carries the same catalog as an OPTIONAL field when the phone sends `catalog: true`+ (docs/mobile-chat-view.md); an older phone never asks. Adopting it in nodeterm mobile is an iOS+ follow-up.- **Subagent visualization** (agents in `SUBAGENT_CAPABLE`) — `subagent-start`/`subagent-end`normalized events drive a transient `state/agentNodes.ts` store. For Claude they come from**Claude's own `SubagentStart`/`SubagentStop` hooks** whenever a session sends them (2026-09,diff --git a/docs/mobile-chat-view.md b/docs/mobile-chat-view.mdindex 67ee76f5c..abbb7b19f 100644--- a/docs/mobile-chat-view.md+++ b/docs/mobile-chat-view.md@@ -104,7 +104,7 @@ as `hostBridge.chat` in `main/index.ts`, forwarded by both phone hosts).| verb | params | reply | does ||---|---|---|---|| `chat.page` | `{nodeId, before?, maxBytes?}` | `{page: ChatPage}` | Only for agents with a chat view — `canChat(capabilityAgentId(agent))` (claude, grok, gemini, codex, copilot, opencode, and custom agents whose base harness is one of them; codex is read by its own reader, `src/core/codex-chat.ts`, locally and on an SSH host — fixtures and the record rules in `src/shared/chat-fixtures/codex/`); anything else is refused before any read. `readChatTranscript` with the ⌘M panel's own deps (paged ALWAYS — an absent page is the default 256 KB tail; grok unpaged) + `model`/`effort`, `version: 1`. Session id: the RENDERER's agent-status id first (what ⌘M reads — after a desktop restart a hook-fed id lives only there), then the mirror's, then the node's minted id; the fallbacks apply only when the renderer does not answer within 3 s or knows none. **Remote (SSH-project) nodes are read REMOTE-ONLY** (`remoteOnly`): over the live pty's ControlMaster, else the node's PROJECT's master (an idle tab / any node after a restart has no pty), and never from this machine's disk — a remote node with no reachable master, or a host that did not answer, is `Could not read the transcript.`, not an empty page. The host-side locate is TRI-STATE (`locateRemoteTranscriptRef`, `src/main/remote-transcript-page.ts`): a CLEAN MISS (the host looked and has no such file, or there is no session id to look for) is `found:false`, and only a failure to ask (no master, no resolved home, a failed ssh, a path outside the jail, a failed ranged read) is the error. For REMOTE nodes the desktop ⌘M panel follows the same remote-only rule and the same absent-vs-unreadable split (same deps): its IPC handler decides remoteness from the shell's own records (`isRemoteNode` — live remote pty or `workspaceStore.sshProjectIdForNode`, never a renderer flag) and applies `remoteOnly` to the paged read, the legacy unpaged read, the find-bar index and the presence probe (`unknown`); it shows `unreadable` as "Couldn't read the transcript." (a remote grok node is read on its host too — `core/remote-grok-chat.ts`, whole-file and unpaged, with the same absent-vs-unreadable split; a remote node of an agent with no remote reader — `CHAT_LOCAL_ONLY` — as "not supported yet"). LOCAL nodes on ⌘M are unchanged — the renderer still sends the cwd, so claude's cwd fallback still applies there; the cwd-only-when-remote rule below is the phone path's. The cwd rides ONLY for a remote node with a known id (the host-side locate needs it); locally a known-but-dead id must not fall back to the cwd's newest transcript (another node's), and with no id at all ⇒ `found:false`. `found:false` therefore always means "looked, and there is no transcript". The reply's `page.sessionId` is exactly the id that read used (absent when none was resolved); the phone should PREFER it over the mirror's `sessionId` as the page's thread identity — the mirror lags — every 4 s on SSH, up to ~30 s on relay (`projects.list` off-LAN) — so right after `/clear` or a resume it still names the old session while the page already comes from the new transcript, and merging by byte `key` across the two would splice threads. `sessionId` is present on a `found:false` page too (an id was resolved, its transcript is missing — e.g. a fresh session that has not written yet): a new id on such a page alone is NOT a confirmed thread switch, so the phone must not clear the thread on it. Additive field: `version` stays 1, and an older desktop simply omits it (fall back to the mirror). |-| `chat.status` | `{nodeId}` | `{status: ChatStatus}` | the renderer's agent-status entry (`state` null = unknown, `held`, hibernated/paused/dropped/sessionEnded) + `structuredAnswers` = the held ticket is in main's structured-ticket ledger (script revision ≥ 5) + the host mirror's `hostRefuses`/`refusal` + `version: 1`. |+| `chat.status` | `{nodeId}` | `{status: ChatStatus}` | the renderer's agent-status entry (`state` null = unknown, `held`, hibernated/paused/dropped/sessionEnded) + `structuredAnswers` = the held ticket is in main's structured-ticket ledger (script revision ≥ 5) + the host mirror's `hostRefuses`/`refusal` + `version: 1`. With `{nodeId, catalog: true}` (a literal `true`; opt-in, so an older phone sees the old shape) the status also carries `catalog: ChatCatalog` (`src/shared/chat-catalog.ts`) — the composer's `/` list for the node: measured built-ins, custom commands and skills, read on the node's host for an SSH node. Absent when the host could not build it (never an error on the status). Names pass `catalogName`, descriptions are one sanitized line; render them as text. `partial: true` = a root could not be read. Adopting it in nodeterm mobile is an iOS follow-up. || `chat.send` | `{nodeId, text}` | `ChatSendOutcome` = `{result, reason?}` | text capped at 64000 UTF-16 units RAW, then ESC + C0/C1 stripped (`\n`, `\t` kept; `sanitizeChatText`); refused FIRST (`reason` `working`/`dialog`) when the host's mirror says the agent is working / waiting / blocked or holds a question or approval ticket (renderer state is transient after a reload); refused `busy` while another send to the same node is still in flight (held until that send SETTLES, capped at 30 s); then the renderer runs the ⌘M composer's gate at send time (`chatSendRefusal` = `agentProcessInPane` + state ∈ {done, unknown} → its own kind as `reason`) plus "no held request" (`dialog`), then `pty.sendText`. `'sent'` only for `sendText === true`; a paste the pane refused is `refused`/`failed`. || `agent.answer` | `{nodeId, pendingId, answer}` | `{ok: boolean}` | `answerHeldPermission` with the node's own I/O (local fs, or the SSH project's ControlMaster — the same `heldPermissionIoFor` the desktop answer path uses): validated against the pending request file, structured-ticket gated, no `setMode auto`. The `pendingId` must belong to THIS node — one of the mirror's approval tickets for it, or the renderer's `held.pendingId` (plans / questions) — else `{ok:false}` with no I/O and no answered event. Success emits the same optimistic "answered" event. |diff --git a/src/core/chat-catalog.test.ts b/src/core/chat-catalog.test.tsnew file mode 100644index 000000000..6ec6b97e2--- /dev/null+++ b/src/core/chat-catalog.test.ts@@ -0,0 +1,247 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { execFileSync } from 'child_process'+import fs from 'fs'+import path from 'path'+import { testTmpDir } from './test-tmp'+import { fakePlatform, type FakePlatform } from './platform-fake'+import { initPlatform, resetPlatformForTests } from './platform'+import { registerClaudeAccountsSource, resetClaudeAccountsSourceForTests } from './claude-config-dir'+import {+ buildLocalCatalog,+ catalogRoots,+ commandNameFromRel,+ parseFrontmatter,+ parseRemoteCatalog,+ readChatCatalog,+ registerChatCatalogIpc,+ remoteCatalogCommand,+ resetChatCatalogCache+} from './chat-catalog'+import { IPC } from '../shared/ipc'+import type { ChatCatalog } from '../shared/chat-catalog'++function write(file: string, text: string): void {+ fs.mkdirSync(path.dirname(file), { recursive: true })+ fs.writeFileSync(file, text)+}++const names = (c: ChatCatalog) => c.entries.map((e) => e.name)+const byName = (c: ChatCatalog, n: string) => c.entries.find((e) => e.name === n)++let home: string+let proj: string+let f: FakePlatform++beforeEach(() => {+ resetChatCatalogCache()+ home = testTmpDir('catalog-home-')+ proj = testTmpDir('catalog-proj-')+ f = fakePlatform()+ initPlatform(f)+})+afterEach(() => {+ resetPlatformForTests()+ resetClaudeAccountsSourceForTests()+})++describe('parsers', () => {+ it('namespaces subfolders with `:` and refuses untypeable or traversing segments', () => {+ expect(commandNameFromRel('git/commit.md', '.md')).toBe('git:commit')+ expect(commandNameFromRel('review.md', '.md')).toBe('review')+ expect(commandNameFromRel('a b.md', '.md')).toBeNull()+ expect(commandNameFromRel('../x.md', '.md')).toBeNull()+ expect(commandNameFromRel('x.txt', '.md')).toBeNull()+ expect(commandNameFromRel('a\u001b[31m.md', '.md')).toBeNull()+ })++ it('reads flat frontmatter and leaves a file without it as body', () => {+ expect(parseFrontmatter('---\nname: "x"\ndescription: hi there\n---\nbody').fields.description).toBe('hi there')+ expect(parseFrontmatter('no fm').body).toBe('no fm')+ // A prototype key is just a key.+ expect(Object.getPrototypeOf(parseFrontmatter('---\n__proto__: y\n---\n').fields)).toBeNull()+ })+})++describe('claude, local', () => {+ it('lists project + user commands and skills over the measured built-ins, project first', async () => {+ write(path.join(proj, '.claude/commands/git/commit.md'), '---\ndescription: Commit staged work\n---\nDo it\n')+ write(path.join(proj, '.claude/commands/plainone.md'), '# Plain first line here\nmore\n')+ write(path.join(proj, '.claude/skills/demo-skill/SKILL.md'), '---\nname: demo-skill\ndescription: A demo\n---\n')+ write(path.join(proj, '.claude/skills/dirname-x/SKILL.md'), '---\nname: fmname-y\ndescription: Name test\n---\n')+ write(path.join(proj, '.claude/skills/nofm/SKILL.md'), 'just a body')+ write(path.join(proj, '.claude/skills/hidden/SKILL.md'), '---\nname: hidden\nuser-invocable: false\n---\n')+ write(path.join(home, '.claude/commands/review.md'), '---\ndescription: user review\n---\n')+ // The same name at user and project scope: the project's wins.+ write(path.join(home, '.claude/commands/plainone.md'), '---\ndescription: USER copy\n---\n')+ // A custom command named like a built-in is the user's own and is the one offered.+ write(path.join(home, '.claude/commands/model.md'), '---\ndescription: my model macro\n---\n')++ const c = await buildLocalCatalog({ agentId: 'claude', accountId: undefined, cwd: proj }, { home })+ expect(byName(c, 'git:commit')).toEqual({ name: 'git:commit', description: 'Commit staged work', kind: 'command', scope: 'project' })+ expect(byName(c, 'plainone')?.description).toBe('Plain first line here')+ expect(byName(c, 'plainone')?.scope).toBe('project')+ expect(byName(c, 'demo-skill')?.kind).toBe('skill')+ // Measured: the frontmatter name wins over the folder name; the folder is the fallback.+ expect(byName(c, 'fmname-y')).toBeTruthy()+ expect(byName(c, 'dirname-x')).toBeUndefined()+ expect(byName(c, 'nofm')).toBeTruthy()+ // Measured: `user-invocable: false` is not offered.+ expect(byName(c, 'hidden')).toBeUndefined()+ expect(byName(c, 'review')?.scope).toBe('user')+ expect(byName(c, 'model')).toEqual({ name: 'model', description: 'my model macro', kind: 'command', scope: 'user' })+ expect(names(c).filter((n) => n === 'model')).toHaveLength(1)+ expect(byName(c, 'compact')?.kind).toBe('builtin')+ expect(c.partial).toBeUndefined()+ })++ it('treats hostile names and descriptions as data: dropped or flattened, never passed through', async () => {+ write(path.join(proj, '.claude/commands/ok.md'), '---\ndescription: line1\u001b[2Jgnp.exe x\n---\n')+ write(path.join(proj, '.claude/commands/has space.md'), 'x')+ write(path.join(proj, '.claude/commands/-flag.md'), 'x')+ write(path.join(proj, '.claude/commands/.hidden/x.md'), 'x')+ write(path.join(proj, '.claude/skills/evil/SKILL.md'), '---\nname: "rm -rf /"\ndescription: y\n---\n')+ write(path.join(proj, '.claude/skills/long/SKILL.md'), `---\nname: long\ndescription: ${'a'.repeat(1000)}\n---\n`)+ const c = await buildLocalCatalog({ agentId: 'claude', accountId: undefined, cwd: proj }, { home })+ const ok = byName(c, 'ok')!+ expect(ok.description).not.toMatch(/[\u0000-\u001f\u007f-\u009f]/)+ expect(ok.description.startsWith('line1')).toBe(true)+ expect(names(c)).not.toContain('has space')+ expect(names(c)).not.toContain('-flag')+ expect(names(c)).not.toContain('.hidden:x')+ expect(names(c)).not.toContain('evil')+ expect(names(c).some((n) => n.includes(' '))).toBe(false)+ expect(Array.from(byName(c, 'long')!.description).length).toBeLessThanOrEqual(160)+ })++ it('bounds command depth', async () => {+ write(path.join(proj, '.claude/commands/a/b/c/deep.md'), 'x')+ write(path.join(proj, '.claude/commands/a/b/shallow.md'), 'x')+ const c = await buildLocalCatalog({ agentId: 'claude', accountId: undefined, cwd: proj }, { home })+ expect(names(c)).toContain('a:b:shallow')+ expect(names(c)).not.toContain('a:b:c:deep')+ })++ it('a bound account REPLACES ~/.claude as the user root', async () => {+ registerClaudeAccountsSource(() => [{ id: 'acc1', label: 'Work', createdAt: 0 }])+ write(path.join(f.userDataDir, 'claude-accounts/acc1/commands/work-only.md'), 'from the account')+ write(path.join(home, '.claude/commands/system-only.md'), 'from the system dir')+ const c = await buildLocalCatalog({ agentId: 'claude', accountId: 'acc1', cwd: proj }, { home })+ expect(names(c)).toContain('work-only')+ expect(names(c)).not.toContain('system-only')+ })++ it('a malformed account id has NO user root — never the system dir in its place', async () => {+ write(path.join(home, '.claude/commands/system-only.md'), 'x')+ const c = await buildLocalCatalog({ agentId: 'claude', accountId: '../../etc', cwd: proj }, { home })+ expect(names(c)).not.toContain('system-only')+ })++ it('re-reads a changed file and serves an unchanged one from cache (mtime + size)', async () => {+ const file = path.join(proj, '.claude/commands/x.md')+ write(file, '---\ndescription: one\n---\n')+ const past = new Date(Date.now() - 60_000)+ fs.utimesSync(file, past, past)+ const q = { agentId: 'claude', accountId: undefined, cwd: proj }+ expect(byName(await buildLocalCatalog(q, { home }), 'x')?.description).toBe('one')+ // Same size, same mtime: the cached head answers (proves no re-read).+ fs.writeFileSync(file, '---\ndescription: two\n---\n')+ fs.utimesSync(file, past, past)+ expect(byName(await buildLocalCatalog(q, { home }), 'x')?.description).toBe('one')+ // A real edit moves the mtime: read again.+ const now = new Date()+ fs.utimesSync(file, now, now)+ expect(byName(await buildLocalCatalog(q, { home }), 'x')?.description).toBe('two')+ })+})++describe('other agents', () => {+ it('gemini: toml commands with `:` namespaces and an optional description', async () => {+ write(path.join(proj, '.gemini/commands/git/commit.toml'), 'description = "Commit it"\nprompt = "x"\n')+ write(path.join(home, '.gemini/commands/test.toml'), "prompt = 'x'\n")+ write(path.join(home, '.gemini/commands/esc.toml'), 'description = "say \\"hi\\""\n')+ const c = await buildLocalCatalog({ agentId: 'gemini', accountId: undefined, cwd: proj }, { home })+ expect(byName(c, 'git:commit')).toEqual({ name: 'git:commit', description: 'Commit it', kind: 'command', scope: 'project' })+ expect(byName(c, 'test')?.description).toBe('')+ expect(byName(c, 'esc')?.description).toBe('say "hi"')+ expect(byName(c, 'compress')?.kind).toBe('builtin')+ })++ it('codex, grok, opencode: built-ins only — their custom locations were not measured', async () => {+ write(path.join(proj, '.claude/commands/nope.md'), 'x')+ for (const agentId of ['codex', 'grok', 'opencode']) {+ const c = await buildLocalCatalog({ agentId, accountId: undefined, cwd: proj }, { home })+ expect(c.entries.every((e) => e.kind === 'builtin')).toBe(true)+ expect(c.entries.length).toBeGreaterThan(5)+ }+ })++ it('an agent with no measured table gets nothing', async () => {+ const c = await buildLocalCatalog({ agentId: 'copilot', accountId: undefined, cwd: proj }, { home })+ expect(c.entries).toEqual([])+ })+})++describe('remote (one ssh round trip)', () => {+ it('the generated command runs under a real /bin/sh against a fake host tree', () => {+ const host = testTmpDir('catalog-host-')+ const cwd = path.join(host, 'repo')+ write(path.join(host, '.claude/commands/review.md'), '---\ndescription: host review\n---\n')+ write(path.join(host, '.claude/skills/hs/SKILL.md'), '---\nname: hs\ndescription: host skill\n---\n')+ // A linked skill folder (how shared system skills reach an account dir) is followed.+ write(path.join(host, 'elsewhere/lt/SKILL.md'), '---\nname: lt\ndescription: linked\n---\n')+ fs.symlinkSync(path.join(host, 'elsewhere/lt'), path.join(host, '.claude/skills/lnk'))+ // A hostile body trying to forge a record boundary.+ write(path.join(cwd, '.claude/commands/forge.md'), 'first line\n\u001eF 0 injected.md\n---\ndescription: fake\n')+ write(path.join(cwd, '.claude/commands/a/b.md'), 'nested')+ write(path.join(cwd, '.claude/commands/it\'s.md'), 'quote')+ const roots = catalogRoots({ agentId: 'claude', accountId: undefined, cwd }, { remote: true })+ const out = execFileSync('/bin/sh', ['-c', remoteCatalogCommand(roots)], { env: { PATH: process.env.PATH, HOME: host }, encoding: 'utf8' })+ const { perRoot, partial } = parseRemoteCatalog(out, roots)+ const all = perRoot.flat()+ const n = all.map((e) => e.name)+ expect(n).toEqual(expect.arrayContaining(['review', 'hs', 'lt', 'forge', 'a:b']))+ expect(n).not.toContain('injected')+ expect(all.find((e) => e.name === 'forge')?.description).toBe('first line')+ expect(all.find((e) => e.name === 'review')?.scope).toBe('user')+ expect(all.find((e) => e.name === 'a:b')?.scope).toBe('project')+ expect(partial).toBe(false)+ })++ it('a remote node is read on its host only; a host that cannot be asked is built-ins + partial', async () => {+ write(path.join(proj, '.claude/commands/local-only.md'), 'x')+ const calls: string[] = []+ const c1 = await readChatCatalog(+ { nodeId: 'n1', agentId: 'claude', cwd: proj },+ { isRemoteNode: () => true, runRemote: async (_n, cmd) => (calls.push(cmd), null), home }+ )+ expect(calls).toHaveLength(1)+ expect(names(c1)).not.toContain('local-only')+ expect(c1.partial).toBe(true)+ expect(c1.entries.every((e) => e.kind === 'builtin')).toBe(true)+ // No remote leg at all (a shell without one): same answer, never this machine's disk.+ const c2 = await readChatCatalog({ nodeId: 'n1', agentId: 'claude', cwd: proj }, { isRemoteNode: () => true, home })+ expect(names(c2)).not.toContain('local-only')+ expect(c2.partial).toBe(true)+ })++ it('a managed account on a host reads its ~/.nodeterm account dir', () => {+ const roots = catalogRoots({ agentId: 'claude', accountId: 'acc1', cwd: '/srv/r' }, { remote: true })+ expect(roots.map((r) => r.dir)).toEqual([+ '/srv/r/.claude/commands',+ '/srv/r/.claude/skills',+ '~/.nodeterm/claude-accounts/acc1/commands',+ '~/.nodeterm/claude-accounts/acc1/skills'+ ])+ })+})++describe('registration', () => {+ it('serves chat:catalog and ignores non-string arguments', async () => {+ registerChatCatalogIpc({ home })+ write(path.join(proj, '.claude/commands/p.md'), 'x')+ const h = f.handlers[IPC.chatCatalog] as (...a: unknown[]) => Promise<ChatCatalog>+ expect(names(await h('n', 'claude', undefined, proj))).toContain('p')+ const weird = await h({}, 42, ['x'], { toString: () => proj })+ expect(weird.entries).toEqual([])+ })+})diff --git a/src/core/chat-catalog.ts b/src/core/chat-catalog.tsnew file mode 100644index 000000000..6f14f9aea--- /dev/null+++ b/src/core/chat-catalog.ts@@ -0,0 +1,417 @@+// The ⌘M composer's `/` catalog for one node: the agent's measured built-ins+// (@shared/chat-catalog), custom command files and SKILL.md skills — read from THIS machine's disk+// for a local node, or from the node's HOST in ONE ssh round trip for an SSH-project node. Served+// by `chat:catalog` in both shells (registerChatCatalogIpc); the phone gets the same catalog as an+// optional field on `chat.status`.+//+// Where each agent looks (measured 2026-09-30, see docs):+// - claude: `<configDir>/commands/**/*.md` and `<cwd>/.claude/commands/**/*.md` (a subfolder is a+// `dir:name` namespace; the description is the frontmatter `description`, else the first body+// line), and `<configDir>/skills/*/SKILL.md` + `<cwd>/.claude/skills/*/SKILL.md` (the name is the+// frontmatter `name`, else the folder; `user-invocable: false` hides it). `<configDir>` is the+// managed or linked account's dir when the node is bound to one — it REPLACES `~/.claude`, it+// does not add to it — else `~/.claude`.+// - gemini: `~/.gemini/commands/**/*.toml` and `<cwd>/.gemini/commands/**/*.toml` (the shipped+// custom-commands reference: subfolders are `:` namespaces, `description` is optional).+// - every other agent: built-ins only. Their custom-command and skill locations were not measured,+// and a guessed location lists commands the CLI does not have.+//+// Cost: nothing is polled. A read happens when a composer asks (the first `/` of a composer mount,+// then again only after the renderer's short freshness window). Locally every directory listing is+// cached by the directory's mtime and every file head by (mtime, size), so an unchanged tree costs+// one `stat` per entry and no reads.+import { promises as fsp } from 'fs'+import os from 'os'+import path from 'path'+import { IPC } from '../shared/ipc'+import { capabilityAgentId } from '../shared/agents/config'+import {+ CHAT_CATALOG_MAX_ENTRIES,+ builtinSlashCommands,+ catalogDescription,+ catalogName,+ mergeCatalogEntries,+ type ChatCatalog,+ type ChatCatalogEntry,+ type ChatCatalogScope+} from '../shared/chat-catalog'+import { posixQuote, quoteRemotePath } from '../shared/ssh'+import { platform } from './platform'+import { claudeConfigDirFor } from './claude-config-dir'+import { isSafeAccountId, remoteAccountConfigDir } from './claude-accounts-core'++/** Per root: at most this many files are looked at, this deep, this much of each is read. */+export const CATALOG_ROOT_MAX_FILES = 200+export const CATALOG_COMMAND_MAX_DEPTH = 3+export const CATALOG_HEAD_BYTES = 4096++export type CatalogRootKind = 'md-commands' | 'toml-commands' | 'skills'++export interface CatalogRoot {+ kind: CatalogRootKind+ scope: Exclude<ChatCatalogScope, 'builtin'>+ /** A local absolute path, or (remote) a path the remote shell resolves — `~/…` or absolute. */+ dir: string+}++export interface ChatCatalogQuery {+ agentId: string | undefined+ accountId: string | undefined+ cwd: string | undefined+}++/** The roots a node's agent reads, in PRECEDENCE order (project before user). */+export function catalogRoots(q: ChatCatalogQuery, opts: { remote: boolean; home?: string }): CatalogRoot[] {+ const base = q.agentId ? capabilityAgentId(q.agentId) : ''+ const home = opts.home ?? os.homedir()+ const cwd = typeof q.cwd === 'string' && q.cwd.trim() ? q.cwd : undefined+ const join = (a: string, ...b: string[]) => (opts.remote ? [a.replace(/\/+$/, ''), ...b].join('/') : path.join(a, ...b))+ const roots: CatalogRoot[] = []+ if (base === 'claude') {+ let configDir: string | null+ if (q.accountId) {+ // A bad id is no account: its roots are simply absent (never the system dir in its place —+ // that would list another identity's commands under this node).+ if (!isSafeAccountId(q.accountId)) configDir = null+ else if (opts.remote) configDir = remoteAccountConfigDir(q.accountId)+ else {+ try {+ configDir = claudeConfigDirFor(q.accountId)+ } catch {+ configDir = null+ }+ }+ } else configDir = opts.remote ? '~/.claude' : path.join(home, '.claude')+ if (cwd) {+ roots.push({ kind: 'md-commands', scope: 'project', dir: join(cwd, '.claude', 'commands') })+ roots.push({ kind: 'skills', scope: 'project', dir: join(cwd, '.claude', 'skills') })+ }+ if (configDir) {+ roots.push({ kind: 'md-commands', scope: 'user', dir: join(configDir, 'commands') })+ roots.push({ kind: 'skills', scope: 'user', dir: join(configDir, 'skills') })+ }+ } else if (base === 'gemini') {+ if (cwd) roots.push({ kind: 'toml-commands', scope: 'project', dir: join(cwd, '.gemini', 'commands') })+ roots.push({ kind: 'toml-commands', scope: 'user', dir: opts.remote ? '~/.gemini/commands' : path.join(home, '.gemini', 'commands') })+ }+ return roots+}++// ── Parsers (pure) ──────────────────────────────────────────────────────────────────────────────++/** `---` frontmatter as flat `key: value` pairs (quotes stripped) plus the body after it. Only the+ * scalar keys the catalog reads are meaningful; anything nested is ignored, never interpreted. */+export function parseFrontmatter(text: string): { fields: Record<string, string>; body: string } {+ const t = text.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n')+ const fields: Record<string, string> = Object.create(null)+ if (!t.startsWith('---\n')) return { fields, body: t }+ const end = t.indexOf('\n---', 4)+ if (end < 0) return { fields, body: t }+ for (const line of t.slice(4, end).split('\n')) {+ const m = /^([A-Za-z][A-Za-z0-9_-]*)\s*:\s*(.*)$/.exec(line)+ if (!m) continue+ let v = m[2].trim()+ if ((v.startsWith('"') && v.endsWith('"') && v.length >= 2) || (v.startsWith("'") && v.endsWith("'") && v.length >= 2)) v = v.slice(1, -1)+ fields[m[1].toLowerCase()] = v+ }+ const after = t.indexOf('\n', end + 1)+ return { fields, body: after < 0 ? '' : t.slice(after + 1) }+}++function firstBodyLine(body: string): string {+ for (const line of body.split('\n')) {+ const s = line.replace(/^#+\s*/, '').trim()+ if (s) return s+ }+ return ''+}++/** `git/commit.md` → `git:commit`. Null when any segment is not a typeable name. */+export function commandNameFromRel(rel: string, ext: '.md' | '.toml'): string | null {+ const norm = rel.replace(/\\/g, '/')+ if (!norm.toLowerCase().endsWith(ext)) return null+ const parts = norm.slice(0, -ext.length).split('/')+ if (parts.some((p) => !p || p === '.' || p === '..')) return null+ return catalogName(parts.join(':'))+}++export function markdownCommandEntry(rel: string, text: string, scope: CatalogRoot['scope']): ChatCatalogEntry | null {+ const name = commandNameFromRel(rel, '.md')+ if (!name) return null+ const { fields, body } = parseFrontmatter(text)+ return { name, description: catalogDescription(fields.description || firstBodyLine(body)), kind: 'command', scope }+}++export function skillEntry(dirName: string, text: string, scope: CatalogRoot['scope']): ChatCatalogEntry | null {+ const { fields } = parseFrontmatter(text)+ if ((fields['user-invocable'] ?? '').toLowerCase() === 'false') return null+ const name = catalogName(fields.name || dirName)+ if (!name) return null+ return { name, description: catalogDescription(fields.description), kind: 'skill', scope }+}++/** The one TOML field read: a single-line `description = "…"` (or '…'). Anything else — a+ * multi-line string, an escape we do not model — degrades to no description, never a guess. */+export function tomlCommandEntry(rel: string, text: string, scope: CatalogRoot['scope']): ChatCatalogEntry | null {+ const name = commandNameFromRel(rel, '.toml')+ if (!name) return null+ const m = /^\s*description\s*=\s*(?:"((?:[^"\\\n]|\\.)*)"|'([^'\n]*)')\s*$/m.exec(text.replace(/\r\n/g, '\n'))+ const raw = m ? (m[1] !== undefined ? m[1].replace(/\\(["\\])/g, '$1') : m[2]) : ''+ return { name, description: catalogDescription(raw), kind: 'command', scope }+}++/** One file of one root → its entry (or null). */+export function entryFor(root: CatalogRoot, rel: string, text: string): ChatCatalogEntry | null {+ if (root.kind === 'md-commands') return markdownCommandEntry(rel, text, root.scope)+ if (root.kind === 'toml-commands') return tomlCommandEntry(rel, text, root.scope)+ return skillEntry(rel, text, root.scope)+}++/** Built-ins last, custom entries in root order (project first), deduped. */+export function assembleCatalog(agentId: string | undefined, perRoot: readonly ChatCatalogEntry[][], partial: boolean): ChatCatalog {+ const project: ChatCatalogEntry[] = []+ const user: ChatCatalogEntry[] = []+ for (const list of perRoot) for (const e of list) (e.scope === 'project' ? project : user).push(e)+ const entries = mergeCatalogEntries(project, user, builtinSlashCommands(agentId))+ return { version: 1, entries, ...(partial ? { partial: true } : {}) }+}++// ── Local reader (mtime-cached) ─────────────────────────────────────────────────────────────────++const CACHE_MAX = 4000+const dirCache = new Map<string, { mtimeMs: number; entries: { name: string; dir: boolean }[] }>()+const headCache = new Map<string, { mtimeMs: number; size: number; text: string }>()++function bounded<K, V>(m: Map<K, V>, k: K, v: V): void {+ if (m.size >= CACHE_MAX) m.clear()+ m.set(k, v)+}++/** Test seam: forget every cached listing and head. */+export function resetChatCatalogCache(): void {+ dirCache.clear()+ headCache.clear()+}++/** A directory's entries (symlinks followed), from cache while the directory's mtime is unchanged.+ * `null` = the directory does not exist; a failure other than absence throws (→ `partial`). */+async function listLocalDir(dir: string): Promise<{ name: string; dir: boolean }[] | null> {+ let st+ try {+ st = await fsp.stat(dir)+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code === 'ENOENT' || (e as NodeJS.ErrnoException).code === 'ENOTDIR') return null+ throw e+ }+ if (!st.isDirectory()) return null+ const hit = dirCache.get(dir)+ if (hit && hit.mtimeMs === st.mtimeMs) return hit.entries+ const names = (await fsp.readdir(dir)).sort().slice(0, CATALOG_ROOT_MAX_FILES * 2)+ const entries: { name: string; dir: boolean }[] = []+ for (const name of names) {+ try {+ const s = await fsp.stat(path.join(dir, name))+ if (s.isDirectory()) entries.push({ name, dir: true })+ else if (s.isFile()) entries.push({ name, dir: false })+ } catch {+ /* a dangling link is no entry */+ }+ }+ bounded(dirCache, dir, { mtimeMs: st.mtimeMs, entries })+ return entries+}++async function readLocalHead(file: string): Promise<string | null> {+ try {+ const st = await fsp.stat(file)+ if (!st.isFile()) return null+ const hit = headCache.get(file)+ if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit.text+ const fh = await fsp.open(file, 'r')+ try {+ const buf = Buffer.alloc(Math.min(CATALOG_HEAD_BYTES, st.size))+ const { bytesRead } = await fh.read(buf, 0, buf.length, 0)+ const text = buf.subarray(0, bytesRead).toString('utf8')+ bounded(headCache, file, { mtimeMs: st.mtimeMs, size: st.size, text })+ return text+ } finally {+ await fh.close()+ }+ } catch {+ return null+ }+}++/** The (rel, file) pairs a root holds: `<name>/SKILL.md` for skills, command files up to the depth+ * cap otherwise. Bounded by `CATALOG_ROOT_MAX_FILES`. */+async function localRootFiles(root: CatalogRoot): Promise<{ rel: string; file: string }[] | null> {+ const top = await listLocalDir(root.dir)+ if (!top) return null+ const out: { rel: string; file: string }[] = []+ if (root.kind === 'skills') {+ for (const e of top) {+ if (out.length >= CATALOG_ROOT_MAX_FILES) break+ if (e.dir && !e.name.startsWith('.')) out.push({ rel: e.name, file: path.join(root.dir, e.name, 'SKILL.md') })+ }+ return out+ }+ const ext = root.kind === 'md-commands' ? '.md' : '.toml'+ const walk = async (dir: string, rel: string, entries: { name: string; dir: boolean }[], depth: number): Promise<void> => {+ for (const e of entries) {+ if (out.length >= CATALOG_ROOT_MAX_FILES) return+ if (e.name.startsWith('.')) continue+ const r = rel ? `${rel}/${e.name}` : e.name+ if (e.dir) {+ if (depth + 1 >= CATALOG_COMMAND_MAX_DEPTH) continue+ const sub = await listLocalDir(path.join(dir, e.name)).catch(() => null)+ if (sub) await walk(path.join(dir, e.name), r, sub, depth + 1)+ } else if (e.name.toLowerCase().endsWith(ext)) out.push({ rel: r, file: path.join(dir, e.name) })+ }+ }+ await walk(root.dir, '', top, 0)+ return out+}++export async function buildLocalCatalog(q: ChatCatalogQuery, opts: { home?: string } = {}): Promise<ChatCatalog> {+ const roots = catalogRoots(q, { remote: false, home: opts.home })+ let partial = false+ const perRoot = await Promise.all(+ roots.map(async (root) => {+ let files: { rel: string; file: string }[] | null+ try {+ files = await localRootFiles(root)+ } catch {+ partial = true+ return []+ }+ const out: ChatCatalogEntry[] = []+ for (const f of files ?? []) {+ const text = await readLocalHead(f.file)+ if (text === null) continue+ const e = entryFor(root, f.rel, text)+ if (e) out.push(e)+ }+ return out+ })+ )+ return assembleCatalog(q.agentId, perRoot, partial)+}++// ── Remote reader (one ssh round trip) ──────────────────────────────────────────────────────────++// Record marker at the start of a line. Every file's bytes go through `tr -d` of the marker byte, so+// a hostile file cannot forge a record boundary (it could at most add its own entries, which it can+// already do by being another file in that directory).+const RS = '\u001e'++/**+ * One POSIX sh line listing every root's files with the head of each. Output, per file:+ * `<RS>F <rootIndex> <rel>\n<first CATALOG_HEAD_BYTES bytes, RS removed>\n`+ * and `<RS>E <rootIndex>` for a root that exists but could not be listed. A missing root prints+ * nothing. `find -L` follows linked skill/command folders; `-maxdepth` bounds a link loop.+ */+export function remoteCatalogCommand(roots: readonly CatalogRoot[]): string {+ const parts = roots.map((root, i) => {+ const d = quoteRemotePath(root.dir)+ const emit = `printf '\\036F ${i} %s\\n' "$r"; head -c ${CATALOG_HEAD_BYTES} "$f" 2>/dev/null | tr -d '\\036'; printf '\\n'`+ if (root.kind === 'skills') {+ return (+ `d=${d}; if [ -d "$d" ]; then n=0; for f in "$d"/*/SKILL.md; do [ -f "$f" ] || continue; ` ++ `n=$((n+1)); [ "$n" -le ${CATALOG_ROOT_MAX_FILES} ] || break; r=\${f%/SKILL.md}; r=\${r##*/}; ${emit}; done; fi`+ )+ }+ const ext = root.kind === 'md-commands' ? '*.md' : '*.toml'+ return (+ `d=${d}; if [ -d "$d" ]; then { find -L "$d" -maxdepth ${CATALOG_COMMAND_MAX_DEPTH} -type f -name ${posixQuote(ext)} 2>/dev/null || printf '\\036E ${i}\\n'; } ` ++ `| head -n ${CATALOG_ROOT_MAX_FILES} | while IFS= read -r f; do case "$f" in "$(printf '\\036')"E*) printf '%s\\n' "$f"; continue;; esac; r=\${f#"$d"/}; ${emit}; done; fi`+ )+ })+ return parts.join('; ') + '; exit 0'+}++/** The remote command's output → the entries per root, plus whether a root failed. */+export function parseRemoteCatalog(stdout: string, roots: readonly CatalogRoot[]): { perRoot: ChatCatalogEntry[][]; partial: boolean } {+ const perRoot: ChatCatalogEntry[][] = roots.map(() => [])+ let partial = false+ const records = stdout.split(`\n${RS}`)+ if (records[0].startsWith(RS)) records[0] = records[0].slice(1)+ else records.shift() // anything before the first record is not ours (a noisy login shell)+ for (const rec of records) {+ const nl = rec.indexOf('\n')+ const head = nl < 0 ? rec : rec.slice(0, nl)+ const m = /^([FE]) (\d+)(?: (.*))?$/.exec(head)+ if (!m) continue+ const i = Number(m[2])+ const root = roots[i]+ if (!root) continue+ if (m[1] === 'E') {+ partial = true+ continue+ }+ const rel = m[3] ?? ''+ // Dot entries are skipped like the local walk skips them; `..` or an absolute path is not ours.+ if (!rel || rel.startsWith('/') || rel.split('/').some((seg) => !seg || seg.startsWith('.'))) continue+ if (perRoot[i].length >= CATALOG_ROOT_MAX_FILES) continue+ const e = entryFor(root, rel, nl < 0 ? '' : rec.slice(nl + 1))+ if (e) perRoot[i].push(e)+ }+ return { perRoot, partial }+}++export interface RemoteCatalogRunner {+ /** Run `cmd` on the node's host. `null` = not a remote node after all / no master. */+ (nodeId: string, cmd: string): Promise<{ code: number; stdout: string } | null>+}++export async function buildRemoteCatalog(q: ChatCatalogQuery & { nodeId: string }, run: RemoteCatalogRunner): Promise<ChatCatalog> {+ const roots = catalogRoots(q, { remote: true })+ if (!roots.length) return assembleCatalog(q.agentId, [], false)+ let res: { code: number; stdout: string } | null = null+ try {+ res = await run(q.nodeId, remoteCatalogCommand(roots))+ } catch {+ res = null+ }+ // The host could not be asked: built-ins only, and say the list is short.+ if (!res || res.code !== 0) return assembleCatalog(q.agentId, [], true)+ const { perRoot, partial } = parseRemoteCatalog(res.stdout, roots)+ return assembleCatalog(q.agentId, perRoot, partial)+}++// ── Registration (both shells) ──────────────────────────────────────────────────────────────────++export interface ChatCatalogDeps {+ /** From the SHELL's own records, never the renderer's arguments. Absent (Server Edition) = no+ * node is remote, which is correct there: it runs on the host it reads. */+ isRemoteNode?(nodeId: string): boolean+ /** The remote leg. A remote node with no runner answers built-ins only (`partial`), never a read+ * of THIS machine's disk for a node whose files are on another one. */+ runRemote?: RemoteCatalogRunner+ /** Test seam for the local home directory. */+ home?: string+}++const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)++export async function readChatCatalog(+ args: { nodeId?: unknown; agentId?: unknown; accountId?: unknown; cwd?: unknown },+ deps: ChatCatalogDeps = {}+): Promise<ChatCatalog> {+ const q: ChatCatalogQuery = { agentId: str(args.agentId), accountId: str(args.accountId), cwd: str(args.cwd) }+ const nodeId = str(args.nodeId)+ if (nodeId && deps.isRemoteNode?.(nodeId)) {+ if (!deps.runRemote) return assembleCatalog(q.agentId, [], true)+ return buildRemoteCatalog({ ...q, nodeId }, deps.runRemote)+ }+ return buildLocalCatalog(q, { home: deps.home })+}++export function registerChatCatalogIpc(deps: ChatCatalogDeps = {}): void {+ platform().handle(+ IPC.chatCatalog,+ (nodeId: unknown, agentId: unknown, accountId: unknown, cwd: unknown): Promise<ChatCatalog> =>+ readChatCatalog({ nodeId, agentId, accountId, cwd }, deps).then((c) =>+ c.entries.length > CHAT_CATALOG_MAX_ENTRIES ? { ...c, entries: c.entries.slice(0, CHAT_CATALOG_MAX_ENTRIES) } : c+ )+ )+}diff --git a/src/main/index.ts b/src/main/index.tsindex de78adbea..2f08d58f5 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -263,6 +263,7 @@ import {locateRemoteTranscriptCommand,remoteTranscriptRoots} from '../core/remote-transcript-locate'+import { readChatCatalog, registerChatCatalogIpc, type ChatCatalogDeps } from '../core/chat-catalog'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,19 @@ app.whenReady().then(async () => {})}registerTranscriptIpc(transcriptIpcDeps)+ // The ⌘M composer's `/` catalog. Core reads a local node's folders itself; the one thing this shell+ // adds is the remote leg — ONE ssh round trip over the node's master (the same resolution the+ // transcript legs above use), so an SSH node's commands and skills are the HOST's.+ // Named: the phone's `chat.status` catalog (hostBridge.chat) reads through the same deps.+ const chatCatalogDeps: ChatCatalogDeps = {+ isRemoteNode: isRemoteTranscriptNode,+ runRemote: async (nodeId, cmd) => {+ const rt = sshTargetForNode(nodeId)+ if (!rt || !sshProjectManager) return null+ return sshProjectManager.sshRun(childArgs(rt.conn, rt.controlPath, cmd))+ }+ }+ registerChatCatalogIpc(chatCatalogDeps)initTranscriptIndex(() => settingsStore.get().claudeAccounts ?? [])corePlatform.handle(IPC.transcriptSearch, (query: string) => searchTranscripts(query))@@ -4352,6 +4366,7 @@ app.whenReady().then(async () => {hostSendRefusal: (nodeId) => mirrorChatSendRefusal(mirrorEntry(nodeId)),knownTickets: pendingTicketsFor,readTranscript: (q, rawPage) => readChatTranscript(q, rawPage, transcriptIpcDeps),+ catalog: (q) => readChatCatalog(q, chatCatalogDeps),answerIo: heldPermissionIoFor,isStructuredTicket,onAnswered: (nodeId, pendingId, decision) => {diff --git a/src/main/remote/host-chat-wiring.test.ts b/src/main/remote/host-chat-wiring.test.tsindex 0a78f3a17..ac4998954 100644--- a/src/main/remote/host-chat-wiring.test.ts+++ b/src/main/remote/host-chat-wiring.test.ts@@ -33,6 +33,13 @@ describe('phone chat verbs are wired end to end', () => {expect(block).toMatch(/getMainWindow\(\)/)expect(block).not.toMatch(/\bwin\.(webContents|isDestroyed)/)})+ it('the phone catalog reads through the SAME deps the ⌘M composer\'s channel uses (remote leg included)', () => {+ const src = read('main/index.ts')+ expect(src).toMatch(/registerChatCatalogIpc\(chatCatalogDeps\)/)+ expect(src).toMatch(/catalog: \(q\) => readChatCatalog\(q, chatCatalogDeps\)/)+ expect(src).toMatch(/runRemote: async \(nodeId, cmd\) =>/)+ expect(read('server/index.ts')).toMatch(/registerChatCatalogIpc\(\)/)+ })it('the renderer answers the round-trip', () => {const canvas = read('renderer/canvas/Canvas.tsx')expect(canvas).toMatch(/api\.onHostChatQuery\(/)diff --git a/src/main/remote/host-chat.test.ts b/src/main/remote/host-chat.test.tsindex 89d298040..fcb826f2f 100644--- a/src/main/remote/host-chat.test.ts+++ b/src/main/remote/host-chat.test.ts@@ -194,6 +194,26 @@ describe('host-chat status', () => {const d = deps({ isStructuredTicket: vi.fn(() => true) })expect((await createHostChat(d).status('n1'))?.structuredAnswers).toBe(false)})+ it('the `/` catalog rides ONLY when asked, re-checked, and its failure drops the field, not the status', async () => {+ const catalog = vi.fn(async () => ({+ version: 1 as const,+ entries: [+ { name: 'ok', description: 'a\u001bb', kind: 'command' as const, scope: 'project' as const },+ { name: 'bad name', description: '', kind: 'command' as const, scope: 'project' as const }+ ]+ }))+ const d = deps({ catalog })+ // An older phone never asks: the old shape, and no catalog read at all.+ expect(await createHostChat(d).status('n1')).not.toHaveProperty('catalog')+ expect(catalog).not.toHaveBeenCalled()+ const s = await createHostChat(d).status('n1', { catalog: true })+ expect(catalog).toHaveBeenCalledWith({ nodeId: 'n1', agentId: 'claude', accountId: 'acc', cwd: '/srv/app' })+ expect(s?.catalog).toEqual({ version: 1, entries: [{ name: 'ok', description: 'a b', kind: 'command', scope: 'project' }] })+ const failing = deps({ catalog: vi.fn(async () => { throw new Error('host down') }) })+ const s2 = await createHostChat(failing).status('n1', { catalog: true })+ expect(s2).toMatchObject({ version: 1, state: 'done' })+ expect(s2).not.toHaveProperty('catalog')+ })it('unknown node ⇒ null, renderer never asked', async () => {const d = deps()expect(await createHostChat(d).status('nope')).toBeNull()diff --git a/src/main/remote/host-chat.ts b/src/main/remote/host-chat.tsindex 442fd1a1c..32c1678c0 100644--- a/src/main/remote/host-chat.ts+++ b/src/main/remote/host-chat.ts@@ -18,6 +18,7 @@ import type { ChatTranscriptResult } from '../../shared/types'import type { ChatHostRefusal, ChatSendOutcome, RendererChatStatus } from '../../shared/mobile-chat'import { canChat, capabilityAgentId } from '../../shared/agents/config'import type { ChatReadQuery } from '../../core/transcript-ipc'+import { sanitizeChatCatalog, type ChatCatalog } from '../../shared/chat-catalog'import {answerHeldPermission,type HeldPermissionIo@@ -59,6 +60,9 @@ export interface HostChatDeps {* and reported on every status: why the mirror refuses, or null. Renderer state is transient (a* reload or a desktop restart wipes it), the mirror is not — defense in depth, never the only gate. */hostSendRefusal(nodeId: string): ChatHostRefusal | null+ /** The composer's `/` catalog (`readChatCatalog` with the shell's deps bound), for a phone that+ * asks for it on `chat.status`. Absent = the field is never added. */+ catalog?(q: { nodeId: string; agentId?: string; accountId?: string; cwd?: string }): Promise<ChatCatalog>/** The approval tickets the host's mirror holds for this node (`pendingTicketsFor`). */knownTickets(nodeId: string): string[]/** How long a status query may take, and how long a send has to START (the renderer refuses a@@ -163,7 +167,7 @@ export function createHostChat(deps: HostChatDeps): HostChatOps {return { ...result, version: 1, ...(sessionId ? { sessionId } : {}) }},- async status(nodeId) {+ async status(nodeId, opts) {const node = deps.lookupNode(nodeId)if (!node) return nullconst answered = await withTimeout(deps.renderer.status({ nodeId, agentId: node.agentId }), timeoutMs)@@ -175,12 +179,25 @@ export function createHostChat(deps: HostChatDeps): HostChatOps {// null) while the mirror may still hold a live dialog, and `chat.send` refuses on it — the// phone must see the same lock the send will apply.const refusal = deps.hostSendRefusal(nodeId)+ // Only when asked, and never at the status's expense: a catalog that fails to build (a host+ // that did not answer) drops the field. Re-checked before it leaves the machine.+ let catalog: ChatCatalog | undefined+ if (opts?.catalog && deps.catalog) {+ try {+ catalog = sanitizeChatCatalog(+ await deps.catalog({ nodeId, agentId: node.agentId, accountId: node.accountId, cwd: node.cwd })+ )+ } catch {+ catalog = undefined+ }+ }return {version: 1 as const,...answered,structuredAnswers,hostRefuses: refusal !== null,- ...(refusal ? { refusal } : {})+ ...(refusal ? { refusal } : {}),+ ...(catalog ? { catalog } : {})}},diff --git a/src/main/remote/host-service.chat.test.ts b/src/main/remote/host-service.chat.test.tsindex b50c0a110..a05590e38 100644--- a/src/main/remote/host-service.chat.test.ts+++ b/src/main/remote/host-service.chat.test.ts@@ -150,6 +150,14 @@ describe('chat.status', () => {const { call } = make()expect(await call('chat.status', { nodeId: 'n1' })).toEqual({ id: 'r1', ok: true, body: { status: STATUS } })})+ it('passes the phone\'s catalog opt-in through — and only a literal true', async () => {+ const status = vi.fn(async (_nodeId: string, _opts?: { catalog?: boolean }) => STATUS)+ const { call } = make({ status })+ await call('chat.status', { nodeId: 'n1', catalog: true })+ await call('chat.status', { nodeId: 'n1', catalog: 'yes' })+ await call('chat.status', { nodeId: 'n1' })+ expect(status.mock.calls.map((c) => c[1])).toEqual([{ catalog: true }, undefined, undefined])+ })it('unknown node ⇒ "Unknown node."', async () => {const { call } = make({ status: vi.fn(async () => null) })expect(await call('chat.status', { nodeId: 'n1' })).toEqual({ id: 'r1', ok: false, body: { message: 'Unknown node.' } })diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex 5bf5c3c26..704b2a844 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -203,8 +203,9 @@ export interface HostChatOps {* for a failure). */page(nodeId: string, rawPage: unknown): Promise<ChatPage | null | 'unsupported'>/** The node's agent state + held request. `null` ⇒ unknown node. Rejects when the desktop- * window did not answer — never a guessed state. */- status(nodeId: string): Promise<ChatStatus | null>+ * window did not answer — never a guessed state. `catalog` (the phone asked for it) adds the+ * composer's `/` catalog; a failure to build it drops the field, never the status. */+ status(nodeId: string, opts?: { catalog?: boolean }): Promise<ChatStatus | null>/** Type `text` (already stripped of control chars) into the node's pane through the desktop's* own send gate. Only `'sent'` means Enter was confirmed. */send(nodeId: string, text: string): Promise<ChatSendOutcome | 'unknown-node'>@@ -867,7 +868,8 @@ export function createHostHandlers(}case 'chat.status':void chat- .status(nodeId)+ // Opt-in (`catalog: true`): an older phone sends no such param and gets the old shape.+ .status(nodeId, p.catalog === true ? { catalog: true } : undefined).then((status) => (status ? socket.respond(req.id, true, { status }) : fail('Unknown node.'))).catch(() => fail('The desktop window is not available.'))returndiff --git a/src/preload/index.ts b/src/preload/index.tsindex c37047a4e..f80e41581 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -575,7 +575,8 @@ const api: NodeTerminalApi = {readTranscript: (sessionId, cwd, accountId, nodeId, agentId, page) =>ipcRenderer.invoke(IPC.chatReadTranscript, sessionId, cwd, accountId, nodeId, agentId, page),transcriptExists: (sessionId, accountId, nodeId) =>- ipcRenderer.invoke(IPC.transcriptExists, sessionId, accountId, nodeId)+ ipcRenderer.invoke(IPC.transcriptExists, sessionId, accountId, nodeId),+ catalog: (nodeId, agentId, accountId, cwd) => ipcRenderer.invoke(IPC.chatCatalog, nodeId, agentId, accountId, cwd)},claudeAccounts: {add: (ctx) => ipcRenderer.invoke(IPC.claudeAccountsAdd, ctx),diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.tsindex cea9427fc..cfe264a67 100644--- a/src/renderer/bridge/relay-api.ts+++ b/src/renderer/bridge/relay-api.ts@@ -169,7 +169,9 @@ export function buildRelayApi(// ── Deferred over the relay in v1 — documented degrades (a clean refusal, not a wrong-machine// silent no-op): ──- // `chat` is now just readTranscript + transcriptExists (the SDK chat node was removed). It has+ // `chat` is readTranscript + transcriptExists + catalog (the SDK chat node was removed). `catalog`+ // rejects like `readTranscript` (the stub's E_UNSUPPORTED): the composer then offers the shared+ // built-in table alone, never this machine's command folders under the peer's node. It has// no relay builder: reading a transcript over the relay would read THIS machine's transcript,// not the host's, so `readTranscript` refuses with E_UNSUPPORTED instead. `transcriptExists`// takes the stub's `'unknown'` for the same reason and the opposite shape — its consumer actsdiff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 2befe0138..0e7d2b812 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -385,7 +385,10 @@ export function buildStubApi(): Omit<// restore awaits this on the boot path, and its whole contract is that anything it cannot// judge is `unknown` ⇒ resume exactly as before. A rejection here would be a second way of// saying the same thing that every caller would have to remember to catch.- transcriptExists: () => Promise.resolve('unknown' as const)+ transcriptExists: () => Promise.resolve('unknown' as const),+ // Rejects: a surface with no catalog reader (relay tabs) falls back to the shared built-in+ // table in the composer, which is the honest subset — never another machine's files.+ catalog: U('chat.catalog')},claudeAccounts: {add: U('claudeAccounts.add'),diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 2c53cb35e..4280f3c36 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -1,3 +1,4 @@+import type { ChatCatalog } from '@shared/chat-catalog'import type { NormalizedAgentEvent } from '../../shared/agents/normalize'import { subscribeAgentReplay } from '../../shared/agent-replay-subscription'import type { DesktopWallpaper, WallpaperStill } from '../../shared/wallpaper'@@ -1098,7 +1099,11 @@ export function buildTranscriptApi(accountId,nodeId) as Promise<TranscriptPresence>- ).catch(() => 'unknown' as const)+ ).catch(() => 'unknown' as const),+ // REAL: the server registers `registerChatCatalogIpc` and runs on the machine whose command+ // and skill folders these are. The reply is re-checked in the composer (sanitizeChatCatalog).+ catalog: (nodeId, agentId, accountId, cwd) =>+ client.request(IPC.chatCatalog, nodeId, agentId, accountId, cwd) as Promise<ChatCatalog>},claudeReadTranscript: (sessionId, cwd, accountId, nodeId) =>client.request(diff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsxindex 517433c3e..d2ce5b310 100644--- a/src/renderer/components/kanban/CardModal.tsx+++ b/src/renderer/components/kanban/CardModal.tsx@@ -596,6 +596,7 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,projectId: session.spawn.sshRemoteTmux ? nodeUploadScope(session.spawn.ssh) : ''})}+ sshProjectId={session.spawn.sshRemoteTmux ? nodeUploadScope(session.spawn.ssh) : undefined}onShowTerminal={() => {// The picker just opened in the live viewer needs the keyboard.requestTerminalFocusOnExit(session.id)diff --git a/src/renderer/lib/chatComposerComplete.test.ts b/src/renderer/lib/chatComposerComplete.test.tsnew file mode 100644index 000000000..c67011b0d--- /dev/null+++ b/src/renderer/lib/chatComposerComplete.test.ts@@ -0,0 +1,120 @@+import { describe, expect, it } from 'vitest'+import { applyCompletion, completionItems, completionTriggerAt, rankFileCompletions } from './chatComposerComplete'+import { prepareQuickOpenFiles } from './quickOpenSearch'+import {+ BUILTIN_CATALOG_AGENTS,+ builtinSlashCommands,+ catalogDescription,+ catalogName,+ rankCatalog,+ sanitizeChatCatalog,+ type ChatCatalogEntry+} from '@shared/chat-catalog'++const e = (name: string, description = '', kind: ChatCatalogEntry['kind'] = 'builtin'): ChatCatalogEntry => ({+ name,+ description,+ kind,+ scope: kind === 'builtin' ? 'builtin' : 'project'+})++describe('completionTriggerAt', () => {+ it('a slash is a command only at the start of the message', () => {+ expect(completionTriggerAt('/mo', 3)).toEqual({ kind: 'slash', query: 'mo', start: 0, end: 3 })+ expect(completionTriggerAt(' /', 3)).toEqual({ kind: 'slash', query: '', start: 2, end: 3 })+ expect(completionTriggerAt('see /usr', 8)).toBeNull()+ expect(completionTriggerAt('/model x', 8)).toBeNull()+ // Caret inside the word: the token runs to its end.+ expect(completionTriggerAt('/model', 2)).toEqual({ kind: 'slash', query: 'm', start: 0, end: 6 })+ })++ it('an @ opens only at the start of a word, anywhere in the message', () => {+ expect(completionTriggerAt('read @src/ma', 12)).toEqual({ kind: 'file', query: 'src/ma', start: 5, end: 12 })+ expect(completionTriggerAt('@', 1)).toEqual({ kind: 'file', query: '', start: 0, end: 1 })+ expect(completionTriggerAt('mail a@b', 8)).toBeNull()+ })++ it('a selection never completes', () => {+ expect(completionTriggerAt('/mo', 1, 3)).toBeNull()+ })+})++describe('applyCompletion', () => {+ it('replaces the whole token and adds one trailing space', () => {+ const t = completionTriggerAt('/mo', 3)!+ expect(applyCompletion('/mo', t, 'model')).toEqual({ text: '/model ', caret: 7 })+ const f = completionTriggerAt('read @sr and', 8)!+ expect(applyCompletion('read @sr and', f, 'src/a.ts')).toEqual({ text: 'read @src/a.ts and', caret: 14 })+ })+})++describe('rankCatalog', () => {+ const list = [e('compact'), e('config'), e('context'), e('git:commit', 'Commit staged work', 'command'), e('clear')]+ it('prefix first, then contains, then description', () => {+ expect(rankCatalog(list, 'co').map((x) => x.name)).toEqual(['config', 'compact', 'context', 'git:commit'])+ expect(rankCatalog(list, 'commit').map((x) => x.name)).toEqual(['git:commit'])+ expect(rankCatalog(list, 'staged').map((x) => x.name)).toEqual(['git:commit'])+ expect(rankCatalog(list, 'st')).toEqual([])+ })+})++describe('files', () => {+ it('ranks the node index and leaves out untypeable or traversing paths', () => {+ const idx = prepareQuickOpenFiles(['src/main.ts', 'src/my file.ts', 'src/\u001b[31m.ts', '../etc/passwd', 'src/mail.ts'])+ const out = rankFileCompletions(idx, 'ma')+ expect(out).toEqual(expect.arrayContaining(['src/main.ts', 'src/mail.ts']))+ expect(out).not.toContain('src/my file.ts')+ expect(out.some((p) => p.includes('\u001b'))).toBe(false)+ expect(out).not.toContain('../etc/passwd')+ // No index yet = no items (never a guess).+ expect(completionItems(completionTriggerAt('@ma', 3), [], null)).toEqual([])+ })+})++describe('the shared catalog', () => {+ it('names have a closed alphabet', () => {+ expect(catalogName('git:commit')).toBe('git:commit')+ for (const bad of ['', ' x', 'a b', '-x', ':x', 'x;rm', 'x\u001b', 'x', 'a'.repeat(65), 42, null]) {+ expect(catalogName(bad)).toBeNull()+ }+ })++ it('descriptions are one line with control and format characters gone', () => {+ expect(catalogDescription('a\nb\u001b[2Jc')).toBe('a b [2Jc')+ expect(catalogDescription({})).toBe('')+ })++ it('a catalog from a wire is re-checked entry by entry', () => {+ const c = sanitizeChatCatalog({+ entries: [+ { name: 'ok', description: 'x', kind: 'command', scope: 'project' },+ { name: 'bad name', description: 'x', kind: 'command', scope: 'project' },+ { name: 'k', description: 'x', kind: 'weird', scope: 'project' },+ { name: 'k2', description: 'x', kind: 'skill', scope: 'elsewhere' },+ null,+ 'str'+ ],+ partial: 'yes'+ })+ expect(c).toEqual({ version: 1, entries: [{ name: 'ok', description: 'x', kind: 'command', scope: 'project' }] })+ expect(sanitizeChatCatalog(undefined)).toEqual({ version: 1, entries: [] })+ })++ it('every measured table holds valid, unique names; a custom agent inherits its base', () => {+ expect([...BUILTIN_CATALOG_AGENTS].sort()).toEqual(['claude', 'codex', 'gemini', 'grok', 'opencode'])+ for (const a of BUILTIN_CATALOG_AGENTS) {+ const list = builtinSlashCommands(a)+ expect(list.length).toBeGreaterThan(0)+ for (const x of list) expect(catalogName(x.name)).toBe(x.name)+ expect(new Set(list.map((x) => x.name)).size).toBe(list.length)+ }+ expect(builtinSlashCommands('copilot')).toEqual([])+ expect(builtinSlashCommands(undefined)).toEqual([])+ expect(builtinSlashCommands('constructor')).toEqual([])+ })++ it('the picker commands the composer toolbar types are in claude’s measured table', () => {+ const n = builtinSlashCommands('claude').map((x) => x.name)+ expect(n).toEqual(expect.arrayContaining(['model', 'effort']))+ })+})diff --git a/src/renderer/lib/chatComposerComplete.ts b/src/renderer/lib/chatComposerComplete.tsnew file mode 100644index 000000000..83badff2a--- /dev/null+++ b/src/renderer/lib/chatComposerComplete.ts@@ -0,0 +1,103 @@+// Pure decisions behind the ⌘M composer's completion menu (ChatComposer): what the caret is in the+// middle of (`/command` at the start of the message, or an `@path` token anywhere), what the menu+// lists, and what accepting an item does to the draft. It only ever INSERTS text: sending stays the+// composer's existing gated send (`chatSendRefusal`), so completing `/clear` types nothing into the+// pane until the user presses Enter a second time on a message the gate allows.+import { rankCatalog, type ChatCatalogEntry } from '@shared/chat-catalog'+import { isSafeQuickOpenRelPath } from '@shared/quick-open-filter'+import { rankQuickOpenFiles, type QuickOpenIndexedFile } from './quickOpenSearch'++export type CompletionKind = 'slash' | 'file'++export interface CompletionTrigger {+ kind: CompletionKind+ /** What the user has typed after the `/` or `@`. */+ query: string+ /** Offsets of the whole token (the `/` or `@` included) in the draft. */+ start: number+ end: number+}++const NAME_CHAR = /[A-Za-z0-9._:-]/++/**+ * The token the caret is in, or null. A slash command is only a command at the very start of the+ * message (after optional whitespace) — every CLI measured reads `/x` mid-sentence as text — so+ * `see /usr` never opens the menu. An `@` opens it at the start of a word only, so an e-mail address+ * (`a@b`) does not. A selection (caret range) never completes.+ */+export function completionTriggerAt(text: string, caret: number, selectionEnd = caret): CompletionTrigger | null {+ if (caret !== selectionEnd || caret < 0 || caret > text.length) return null+ const before = text.slice(0, caret)+ const after = text.slice(caret)+ const slash = /^(\s*)\/([A-Za-z0-9._:-]*)$/.exec(before)+ if (slash) {+ let end = caret+ while (end < text.length && NAME_CHAR.test(text[end])) end+++ return { kind: 'slash', query: slash[2], start: slash[1].length, end }+ }+ const at = /(^|\s)@([^\s@]*)$/.exec(before)+ if (at) {+ const start = caret - at[2].length - 1+ const rest = /^[^\s]*/.exec(after)?.[0] ?? ''+ return { kind: 'file', query: at[2], start, end: caret + rest.length }+ }+ return null+}++/** Accepting an item: the token is replaced by `/name ` or `@path `, the caret lands after it. No+ * second space when one already follows. */+export function applyCompletion(text: string, t: CompletionTrigger, value: string): { text: string; caret: number } {+ const token = (t.kind === 'slash' ? '/' : '@') + value+ const next = text.slice(t.end)+ const insert = /^\s/.test(next) ? token : token + ' '+ return { text: text.slice(0, t.start) + insert + next, caret: t.start + insert.length }+}++export const FILE_RESULT_LIMIT = 30++// Whitespace, control and format characters: a path holding one is not offered (it would be typed+// into the agent's pane on send, and a control byte in a file name is a sequence, not a name).+// eslint-disable-next-line no-control-regex -- matching control characters is the point+const UNTYPEABLE = /[\s\x00-\x1f\x7f-\x9f\p{Cf}]/u++/** The `@` list: the node's file index ranked by the SAME fuzzy ranker as quick open. A path with+ * whitespace (or a control / format character) is left out — `@a b.md` would read as `@a` plus a+ * word, and no CLI we measured documents a quoting rule for it; a path that fails the traversal guard is left out too (an SSH+ * index is remote-supplied). */+export function rankFileCompletions(index: readonly QuickOpenIndexedFile[], query: string, limit = FILE_RESULT_LIMIT): string[] {+ const out: string[] = []+ for (const r of rankQuickOpenFiles(query, index, limit * 2)) {+ if (UNTYPEABLE.test(r.path) || !isSafeQuickOpenRelPath(r.path)) continue+ out.push(r.path)+ if (out.length >= limit) break+ }+ return out+}++export type CompletionItem =+ | { kind: 'slash'; value: string; entry: ChatCatalogEntry }+ | { kind: 'file'; value: string }++export function completionItems(+ t: CompletionTrigger | null,+ catalog: readonly ChatCatalogEntry[],+ files: readonly QuickOpenIndexedFile[] | null+): CompletionItem[] {+ if (!t) return []+ if (t.kind === 'slash') return rankCatalog(catalog, t.query).map((entry) => ({ kind: 'slash', value: entry.name, entry }))+ if (!files) return []+ return rankFileCompletions(files, t.query).map((value) => ({ kind: 'file', value }))+}++/** A short, human label for where an entry came from — never the path it was read from. */+export function catalogEntryTag(e: ChatCatalogEntry): string {+ if (e.kind === 'skill') return e.scope === 'project' ? 'project skill' : 'skill'+ if (e.kind === 'command') return e.scope === 'project' ? 'project command' : 'command'+ return ''+}++/** How long a fetched catalog / file index is reused within one composer before the next `/` or+ * `@` asks again. Not a poll: nothing is fetched unless the user opens the menu. Core's own mtime+ * cache makes a re-ask of an unchanged folder cost stats, not reads. */+export const CATALOG_REUSE_MS = 30_000diff --git a/src/renderer/nodes/ChatComposer.complete.test.tsx b/src/renderer/nodes/ChatComposer.complete.test.tsxnew file mode 100644index 000000000..e076a96df--- /dev/null+++ b/src/renderer/nodes/ChatComposer.complete.test.tsx@@ -0,0 +1,181 @@+// @vitest-environment jsdom+import { act, useState } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++/**+ * The ⌘M composer's `/` and `@` completion against the REAL component: it lists the node's catalog+ * and files, the keyboard drives it, accepting only INSERTS text (nothing reaches the pane, the send+ * stays the composer's own gated Enter), and hostile catalog text renders as text.+ */++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++const { api } = vi.hoisted(() => ({+ api: {+ pty: { sendText: vi.fn(async () => true as const) },+ chat: { catalog: vi.fn() },+ files: { quickOpen: vi.fn() }+ }+}))+vi.mock('../session/session', () => ({ useSession: () => ({ api }) }))++import { ChatComposer } from './ChatComposer'++let host: HTMLDivElement+let root: Root+let onSend: ReturnType<typeof vi.fn<() => void>>+let draft: () => string++beforeEach(() => {+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+ onSend = vi.fn<() => void>()+ api.pty.sendText.mockClear()+ api.chat.catalog.mockReset()+ api.files.quickOpen.mockReset()+ api.chat.catalog.mockResolvedValue({+ version: 1,+ entries: [+ { name: 'git:commit', description: 'Commit staged work', kind: 'command', scope: 'project' },+ { name: 'co evil', description: 'dropped', kind: 'command', scope: 'project' },+ { name: 'xss', description: '<img src=x onerror=alert(1)>', kind: 'skill', scope: 'user' },+ { name: 'compact', description: 'Summarize', kind: 'builtin', scope: 'builtin' }+ ]+ })+ api.files.quickOpen.mockResolvedValue(['src/renderer/app.ts', 'src/renderer/my file.ts', 'README.md'])+})+afterEach(async () => {+ await act(async () => root.unmount())+ host.remove()+})++function Harness({ disabled = false }: { disabled?: boolean }) {+ const [value, setValue] = useState('')+ draft = () => value+ return (+ <ChatComposer+ nodeId="n1"+ agentId="claude"+ agentLabel="Agent"+ value={value}+ onChange={setValue}+ onSend={onSend}+ placeholder="Message"+ disabled={disabled}+ onWriteRefused={() => {}}+ cwd="/proj"+ />+ )+}++const ta = () => host.querySelector('textarea') as HTMLTextAreaElement+const options = () => [...host.querySelectorAll('[role="option"]')].map((o) => o.textContent ?? '')++async function type(text: string): Promise<void> {+ const el = ta()+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!+ await act(async () => {+ setter.call(el, text)+ el.setSelectionRange(text.length, text.length)+ el.dispatchEvent(new Event('input', { bubbles: true }))+ })+ // Let the catalog / file promises settle.+ await act(async () => {+ await new Promise((r) => setTimeout(r, 0))+ })+}+async function key(k: string): Promise<KeyboardEvent> {+ const ev = new KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true })+ await act(async () => {+ ta().dispatchEvent(ev)+ })+ return ev+}++async function mount(disabled = false): Promise<void> {+ await act(async () => root.render(<Harness disabled={disabled} />))+}++describe('ChatComposer completion', () => {+ it('`/` lists the node catalog (asked with node, agent, account, cwd) and drops a bad name', async () => {+ await mount()+ await type('/co')+ expect(api.chat.catalog).toHaveBeenCalledWith('n1', 'claude', undefined, '/proj')+ const o = options()+ expect(o.some((t) => t.startsWith('/compact'))).toBe(true)+ expect(o.some((t) => t.startsWith('/git:commit'))).toBe(true)+ expect(o.some((t) => t.includes('evil'))).toBe(false)+ expect(ta().getAttribute('aria-expanded')).toBe('true')+ })++ it('a hostile description is text, never markup', async () => {+ await mount()+ await type('/xs')+ expect(options()[0]).toContain('<img src=x onerror=alert(1)>')+ expect(host.querySelector('.term-chat__complete img')).toBeNull()+ })++ it('Enter ACCEPTS (inserts text) and never sends or types into the pane; the next Enter sends', async () => {+ await mount()+ await type('/compa')+ const ev = await key('Enter')+ expect(ev.defaultPrevented).toBe(true)+ expect(draft()).toBe('/compact ')+ expect(onSend).not.toHaveBeenCalled()+ expect(api.pty.sendText).not.toHaveBeenCalled()+ expect(options()).toEqual([])+ await key('Enter')+ expect(onSend).toHaveBeenCalledTimes(1)+ })++ it('a fully typed command is a message: Enter sends it (the menu does not swallow it)', async () => {+ await mount()+ await type('/compact')+ expect(options()[0]).toMatch(/^\/compact/)+ await key('Enter')+ expect(onSend).toHaveBeenCalledTimes(1)+ expect(draft()).toBe('/compact')+ })++ it('arrows move the selection; Escape closes the menu without closing anything around it', async () => {+ await mount()+ await type('/')+ const first = host.querySelector('[aria-selected="true"]')?.textContent+ await key('ArrowDown')+ expect(host.querySelector('[aria-selected="true"]')?.textContent).not.toBe(first)+ const esc = await key('Escape')+ expect(esc.defaultPrevented).toBe(true)+ expect(options()).toEqual([])+ // With the menu closed, Enter is the ordinary send again.+ await key('Enter')+ expect(onSend).toHaveBeenCalledTimes(1)+ })++ it('`@` lists the node files (no path with a space) and inserts `@path `', async () => {+ await mount()+ await type('look at @rend')+ expect(api.files.quickOpen).toHaveBeenCalledWith('/proj')+ expect(options()).toContain('@src/renderer/app.ts')+ expect(options().some((t) => t.includes('my file'))).toBe(false)+ await key('Tab')+ expect(draft()).toBe('look at @src/renderer/app.ts ')+ })++ it('a surface with no catalog (rejects) still offers the measured built-ins', async () => {+ api.chat.catalog.mockRejectedValue(Object.assign(new Error('x'), { code: 'E_UNSUPPORTED' }))+ await mount()+ await type('/mod')+ expect(options().some((t) => t.startsWith('/model'))).toBe(true)+ })++ it('mid-sentence slashes and a disabled composer open nothing', async () => {+ await mount()+ await type('see /us')+ expect(options()).toEqual([])+ await act(async () => root.render(<Harness disabled />))+ await type('/co')+ expect(options()).toEqual([])+ })+})diff --git a/src/renderer/nodes/ChatComposer.tsx b/src/renderer/nodes/ChatComposer.tsxindex 0f055092a..08102fcb5 100644--- a/src/renderer/nodes/ChatComposer.tsx+++ b/src/renderer/nodes/ChatComposer.tsx@@ -21,6 +21,17 @@ import { requestComposerDictation, subscribeComposerDictation } from '../lib/chaimport { clipboardImages, pasteHasText, pastedFiles } from '../terminal/file-drop'import { IconMic, IconPlus } from '../components/icons'import { Spinner } from '../components/Spinner'+import { builtinSlashCommands, sanitizeChatCatalog, type ChatCatalogEntry } from '@shared/chat-catalog'+import { prepareQuickOpenFiles, type QuickOpenIndexedFile } from '../lib/quickOpenSearch'+import {+ CATALOG_REUSE_MS,+ applyCompletion,+ catalogEntryTag,+ completionItems,+ completionTriggerAt,+ type CompletionItem,+ type CompletionTrigger+} from '../lib/chatComposerComplete'export interface ChatComposerProps {nodeId: string@@ -49,6 +60,14 @@ export interface ChatComposerProps {pathsForFiles?: (files: File[]) => Promise<string[]>/** See ChatPanelProps. */onShowTerminal?: () => void+ /** The node's working directory — the root `@` completes under (never above it), and the project+ * whose custom commands and skills the `/` menu lists. Absent = no `@` list. */+ cwd?: string+ /** The account the session runs as: whose config dir holds its commands and skills. */+ accountId?: string+ /** An SSH node's project scope (the one its attach uploads to): `@` lists the HOST's files over+ * that project's master. Absent = the session's own `files.quickOpen` (local, or a relay peer's). */+ sshProjectId?: string}/**@@ -70,7 +89,10 @@ export function ChatComposer({onWriteRefused,sendUnconfirmed = false,pathsForFiles,- onShowTerminal+ onShowTerminal,+ cwd,+ accountId,+ sshProjectId}: ChatComposerProps) {const { api } = useSession()const inputRef = useRef<HTMLTextAreaElement>(null)@@ -96,6 +118,94 @@ export function ChatComposer({const [pickerBusy, setPickerBusy] = useState(false)const labels = composerLabels({ agentId, model: usage?.model, effort: usage?.effort, width: composerWidth })+ // ── Completion (`/` and `@`) ─────────────────────────────────────────────────────────────────+ // The trigger follows the caret; the lists are fetched on the first `/` or `@` of this mount and+ // reused for CATALOG_REUSE_MS (nothing is fetched while nobody types a trigger). Until the core+ // catalog answers — and for good on a surface that has none (a relay tab) — the `/` menu shows the+ // shared built-in table for this agent.+ const listboxId = useId()+ const [trigger, setTrigger] = useState<CompletionTrigger | null>(null)+ const triggerRef = useRef<CompletionTrigger | null>(null)+ const closeMenu = useCallback(() => {+ triggerRef.current = null+ setTrigger(null)+ }, [])+ const [activeIdx, setActiveIdx] = useState(0)+ const [dismissedAt, setDismissedAt] = useState<number | null>(null)+ const [catalog, setCatalog] = useState<ChatCatalogEntry[]>(() => builtinSlashCommands(agentId))+ const [fileIndex, setFileIndex] = useState<QuickOpenIndexedFile[] | null>(null)+ const catalogAtRef = useRef(0)+ const scopeKeyRef = useRef('')+ const filesAtRef = useRef(0)+ const scopeKey = `${agentId}\u0000${accountId ?? ''}\u0000${cwd ?? ''}\u0000${sshProjectId ?? ''}`+ scopeKeyRef.current = scopeKey+ useEffect(() => {+ // A different node scope (the card modal reuses a mount across sessions only via `key`, but be+ // exact): forget what was fetched for the old one.+ catalogAtRef.current = 0+ filesAtRef.current = 0+ setCatalog(builtinSlashCommands(agentId))+ setFileIndex(null)+ }, [scopeKey, agentId])++ const ensureLists = useCallback(+ (kind: CompletionTrigger['kind']) => {+ const now = Date.now()+ if (kind === 'slash' && now - catalogAtRef.current > CATALOG_REUSE_MS) {+ catalogAtRef.current = now+ const key = scopeKey+ Promise.resolve()+ .then(() => api.chat.catalog(nodeId, agentId, accountId, cwd))+ .then((c) => sanitizeChatCatalog(c).entries)+ .catch(() => builtinSlashCommands(agentId))+ .then((entries) => {+ if (key === scopeKeyRef.current) setCatalog(entries)+ })+ }+ if (kind === 'file' && cwd && now - filesAtRef.current > CATALOG_REUSE_MS) {+ filesAtRef.current = now+ const key = scopeKey+ Promise.resolve()+ .then(() => (sshProjectId ? window.nodeTerminal.sshFs.quickOpen(sshProjectId, cwd) : api.files.quickOpen(cwd)))+ .catch(() => [] as string[])+ .then((files) => {+ if (key === scopeKeyRef.current) setFileIndex(prepareQuickOpenFiles(Array.isArray(files) ? files : []))+ })+ }+ },+ [api, nodeId, agentId, accountId, cwd, sshProjectId, scopeKey]+ )+ const syncTrigger = useCallback(+ (text: string, caret: number, selEnd: number) => {+ const t = disabled ? null : completionTriggerAt(text, caret, selEnd)+ const prev = triggerRef.current+ // A new token starts at the top of its list; typing within the same token keeps the place.+ if (!t || !prev || prev.start !== t.start || prev.kind !== t.kind) setActiveIdx(0)+ triggerRef.current = t+ setTrigger(t)+ if (t) ensureLists(t.kind)+ },+ [disabled, ensureLists]+ )+ const items: CompletionItem[] =+ trigger && dismissedAt !== trigger.start ? completionItems(trigger, catalog, fileIndex) : []+ const menuOpen = items.length > 0+ const active = Math.min(activeIdx, Math.max(0, items.length - 1))++ const accept = (item: CompletionItem) => {+ if (!trigger) return+ const next = applyCompletion(value, trigger, item.value)+ onChange(next.text)+ closeMenu()+ // After React commits the new value, put the caret right after the inserted token.+ requestAnimationFrame(() => {+ const el = inputRef.current+ if (!el) return+ el.focus()+ el.setSelectionRange(next.caret, next.caret)+ })+ }+// The labels drop by the composer's OWN width (a narrow node, a split card modal), not the// window's. Guarded like the thread's observer: jsdom and old engines have none, and then every// label shows (`composerToolbarLayout(null)`).@@ -237,11 +347,39 @@ export function ChatComposer({)const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {+ const composing = e.nativeEvent.isComposing || e.keyCode === 229+ // The completion menu owns the navigation keys while it is open. Enter / Tab ACCEPT (insert the+ // text) and never send; Escape closes the menu only — the draft, the ⌘M view and a card modal+ // around it all stay (CardModal's capture-phase Esc already stands aside inside the composer).+ if (menuOpen && !composing) {+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {+ e.preventDefault()+ const d = e.key === 'ArrowDown' ? 1 : -1+ setActiveIdx((i) => (Math.min(i, items.length - 1) + d + items.length) % items.length)+ return+ }+ // Enter accepts only when accepting CHANGES the draft: a fully typed `/model` (the highlighted+ // item is exactly what is already there) is a message, and Enter sends it as before.+ const typedExactly =+ !!trigger && value.slice(trigger.start, trigger.end) === (trigger.kind === 'slash' ? '/' : '@') + items[active].value+ if ((e.key === 'Enter' && !e.shiftKey && !typedExactly) || e.key === 'Tab') {+ e.preventDefault()+ accept(items[active])+ return+ }+ if (e.key === 'Escape') {+ e.preventDefault()+ e.stopPropagation()+ if (trigger) setDismissedAt(trigger.start)+ return+ }+ }+ if (menuOpen && e.key === 'Enter') closeMenu()// Shift+Enter falls through to the textarea's own newline; an IME commit is not a send.const action = chatKeyAction({key: e.key,shiftKey: e.shiftKey,- isComposing: e.nativeEvent.isComposing || e.keyCode === 229+ isComposing: composing})if (action !== 'send') returne.preventDefault()@@ -254,6 +392,43 @@ export function ChatComposer({return (<div className="term-chat__compose">+ {menuOpen && (+ <div+ className="term-chat__complete"+ id={listboxId}+ role="listbox"+ aria-label={trigger?.kind === 'file' ? 'Files' : 'Commands and skills'}+ // Keep the textarea's focus (its blur would close the menu before the click lands).+ onMouseDown={(e) => e.preventDefault()}+ >+ {items.map((item, i) => (+ <div+ key={`${item.kind}:${item.value}`}+ id={`${listboxId}-${i}`}+ role="option"+ aria-selected={i === active}+ className={`term-chat__complete-item${i === active ? ' is-active' : ''}`}+ onMouseEnter={() => setActiveIdx(i)}+ onClick={() => accept(item)}+ >+ {item.kind === 'slash' ? (+ <>+ {/* Plain text nodes only: a name or description from a repository file is data. */}+ <span className="term-chat__complete-name">/{item.value}</span>+ {item.entry.description && (+ <span className="term-chat__complete-desc">{item.entry.description}</span>+ )}+ {catalogEntryTag(item.entry) && (+ <span className="term-chat__complete-tag">{catalogEntryTag(item.entry)}</span>+ )}+ </>+ ) : (+ <span className="term-chat__complete-name">@{item.value}</span>+ )}+ </div>+ ))}+ </div>+ )}<divref={composerRef}className={`term-chat__composer${dropping ? ' term-chat__composer--drop' : ''}${@@ -271,7 +446,30 @@ export function ChatComposer({ref={inputRef}className="term-chat__composer-input"value={value}- onChange={(e) => onChange(e.target.value)}+ onChange={(e) => {+ onChange(e.target.value)+ const caret = e.target.selectionStart ?? e.target.value.length+ // A new token (or none) forgets an Esc on the previous one.+ if (dismissedAt !== null && completionTriggerAt(e.target.value, caret)?.start !== dismissedAt) setDismissedAt(null)+ syncTrigger(e.target.value, caret, e.target.selectionEnd ?? caret)+ }}+ onKeyUp={(e) => {+ // Caret moves (arrows, Home/End) — keys that edit already went through onChange. The menu's+ // own navigation keys are not caret moves while it is open.+ if (e.nativeEvent.isComposing || (menuOpen && (e.key === 'ArrowDown' || e.key === 'ArrowUp'))) return+ const el = e.currentTarget+ syncTrigger(el.value, el.selectionStart ?? el.value.length, el.selectionEnd ?? el.value.length)+ }}+ onClick={(e) => {+ const el = e.currentTarget+ syncTrigger(el.value, el.selectionStart ?? el.value.length, el.selectionEnd ?? el.value.length)+ }}+ onBlur={closeMenu}+ role="combobox"+ aria-autocomplete="list"+ aria-expanded={menuOpen}+ aria-controls={menuOpen ? listboxId : undefined}+ aria-activedescendant={menuOpen ? `${listboxId}-${active}` : undefined}onKeyDown={onKeyDown}onPaste={onPaste}placeholder={placeholder}diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsxindex 152e92931..b31a7fd29 100644--- a/src/renderer/nodes/ChatPanel.tsx+++ b/src/renderer/nodes/ChatPanel.tsx@@ -79,6 +79,12 @@ interface ChatPanelProps {* see is worse than none).*/onShowTerminal?: () => void+ /**+ * An SSH node's project scope (the same one `pathsForFiles` uploads through): the composer's `@`+ * list is the HOST's files, read over that project's master. Absent = the session's own file+ * index (this machine, or a relay peer's core).+ */+ sshProjectId?: string}/**@@ -166,7 +172,8 @@ export function ChatPanel({title,hint,pathsForFiles,- onShowTerminal+ onShowTerminal,+ sshProjectId}: ChatPanelProps) {// This node's core api (stable for the session — the chat transcript and the tmux session// both live on the core this panel's project belongs to).@@ -929,6 +936,9 @@ export function ChatPanel({sendUnconfirmed={optimistic}pathsForFiles={pathsForFiles}onShowTerminal={onShowTerminal}+ cwd={cwd}+ accountId={accountId}+ sshProjectId={sshProjectId}/>)}</div>diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 93b63a57f..234cd5ea3 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -6563,6 +6563,9 @@ export function TerminalNode({projectId: data.sshRemoteTmux ? dropProjectId() : ''})}+ // `@` lists this node's files where they live: the host's for an SSH node, over the+ // same project scope the attach above uploads through.+ sshProjectId={data.sshRemoteTmux ? dropProjectId() : undefined}onShowTerminal={() => {// An explicit "go to the terminal": the picker just opened there needs the keyboard.requestTerminalFocusOnExit(id)diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 3a38df8ad..f86fc217c 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -3611,10 +3611,63 @@ body,gap: 6px;}.term-chat__compose {+ position: relative;flex: 0 0 auto;padding: 8px;border-top: 1px solid rgba(var(--tint-rgb), 0.08);}+/* The composer's `/` and `@` completion menu (ChatComposer), floating ABOVE the composer box. A solid+ token, not a glass fill: it sits inside a glass node, which is a backdrop root (Liquid Glass). */+.term-chat__complete {+ position: absolute;+ left: 8px;+ right: 8px;+ bottom: calc(100% - 4px);+ z-index: 8;+ max-height: 240px;+ overflow-y: auto;+ padding: 4px;+ background: var(--panel);+ border: 1px solid rgba(var(--tint-rgb), 0.14);+ border-radius: 10px;+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);+}+.term-chat__complete-item {+ display: flex;+ align-items: baseline;+ gap: 8px;+ min-width: 0;+ padding: 4px 8px;+ font-size: 12px;+ border-radius: 6px;+ cursor: pointer;+}+.term-chat__complete-item.is-active {+ background: rgba(var(--tint-rgb), 0.1);+ color: var(--text-strong);+}+.term-chat__complete-name {+ flex: 0 0 auto;+ max-width: 60%;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-family: ui-monospace, monospace;+ color: var(--text-strong);+}+.term-chat__complete-desc {+ flex: 1 1 auto;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: var(--muted);+}+.term-chat__complete-tag {+ flex: 0 0 auto;+ font-size: 10px;+ color: var(--muted);+}/* The claude.ai-style composer (ChatPanel): ONE rounded box holding the textarea on top and acompact toolbar under it — "+" attach on the left; model label, muted effort label and the micon the right. The focus ring belongs to the BOX, so the textarea itself draws no border. */diff --git a/src/server/index.ts b/src/server/index.tsindex 4087c1443..30261444d 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 { registerChatCatalogIpc } from '../core/chat-catalog'import { registerContextEnsureIpc } from '../core/context-ensure'import { IPC } from '@shared/ipc'import { WhisperModelStore } from '../core/speech/whisper-models'@@ -522,6 +523,9 @@ 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)})+ // The ⌘M composer's `/` catalog. No remote leg, for the reason above: this process runs on the+ // host whose command and skill folders a node's agent reads.+ registerChatCatalogIpc()// 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/chat-catalog.ts b/src/shared/chat-catalog.tsnew file mode 100644index 000000000..259516f4f--- /dev/null+++ b/src/shared/chat-catalog.ts@@ -0,0 +1,289 @@+// What the ⌘M chat composer can complete after a `/`: the agent's own built-in slash commands, the+// user's and the project's CUSTOM commands, and SKILLS. Core builds the catalog for a node+// (core/chat-catalog.ts, both shells); this module holds the wire shape, the one sanitizer every+// name and description passes through, the measured built-in tables, and the ranking the composer+// uses. Pure — no fs, no React.+import { capabilityAgentId } from './agents/config'++/** `builtin` = the CLI's own command; `command` = a custom command file; `skill` = a SKILL.md. */+export type ChatCatalogKind = 'builtin' | 'command' | 'skill'+/** Where an entry came from. `user` = the agent's config dir (the managed account's, when bound). */+export type ChatCatalogScope = 'builtin' | 'user' | 'project'++export interface ChatCatalogEntry {+ /** Without the leading `/`. Always passes `catalogName`. */+ name: string+ /** One line, sanitized, capped. May be empty. */+ description: string+ kind: ChatCatalogKind+ scope: ChatCatalogScope+}++export interface ChatCatalog {+ version: 1+ entries: ChatCatalogEntry[]+ /** Set when a root could not be read (remote host down, unreadable dir): the list is short, not+ * complete. The composer still offers what it has. */+ partial?: boolean+}++export const CHAT_CATALOG_MAX_ENTRIES = 400+export const CATALOG_NAME_MAX = 64+export const CATALOG_DESCRIPTION_MAX = 160++// A name is typed into a pane after `/`, so it gets a closed alphabet: letters, digits and the+// separators the CLIs themselves use (`git:commit`, `add-dir`, `v1.2`). Anything else — spaces,+// quotes, control or format characters, a leading separator — is not a command anyone can type.+const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/++export function catalogName(raw: unknown): string | null {+ // Not trimmed: a name that needs trimming came from somewhere that does not produce names.+ if (typeof raw !== 'string' || !raw || raw.length > CATALOG_NAME_MAX || !NAME_RE.test(raw)) return null+ return raw+}++// eslint-disable-next-line no-control-regex -- stripping control characters is the point+const CONTROL = /[\x00-\x1f\x7f-\x9f]+/g+// Bidi overrides, zero-width joiners and the rest of the format class: a description is data from a+// file anyone can commit, and a right-to-left override can make one entry read like another.+const FORMAT = /\p{Cf}+/gu++/** Descriptions are hostile data (a project's `.claude/commands` is whatever the repository holds):+ * one line, control and format characters removed, whitespace collapsed, capped by code point. */+export function catalogDescription(raw: unknown): string {+ if (typeof raw !== 'string') return ''+ const one = raw.replace(CONTROL, ' ').replace(FORMAT, '').replace(/\s+/g, ' ').trim()+ const chars = Array.from(one)+ return chars.length > CATALOG_DESCRIPTION_MAX ? chars.slice(0, CATALOG_DESCRIPTION_MAX - 1).join('') + '…' : one+}++const KINDS: ReadonlySet<string> = new Set(['builtin', 'command', 'skill'])+const SCOPES: ReadonlySet<string> = new Set(['builtin', 'user', 'project'])++/** A catalog that crossed a wire (IPC, WS, relay) is re-checked on arrival: every entry that does+ * not pass is DROPPED, never repaired. Anything that is not a catalog becomes an empty one. */+export function sanitizeChatCatalog(raw: unknown): ChatCatalog {+ const out: ChatCatalogEntry[] = []+ const rec = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : null+ const list = rec && Array.isArray(rec.entries) ? rec.entries : []+ for (const e of list) {+ if (out.length >= CHAT_CATALOG_MAX_ENTRIES) break+ if (!e || typeof e !== 'object') continue+ const r = e as Record<string, unknown>+ const name = catalogName(r.name)+ if (!name || typeof r.kind !== 'string' || !KINDS.has(r.kind) || typeof r.scope !== 'string' || !SCOPES.has(r.scope)) {+ continue+ }+ out.push({ name, description: catalogDescription(r.description), kind: r.kind as ChatCatalogKind, scope: r.scope as ChatCatalogScope })+ }+ return { version: 1, entries: out, ...(rec?.partial === true ? { partial: true } : {}) }+}++type Builtin = readonly [name: string, description: string]++/**+ * Built-in slash commands per base harness — ONLY what was measured against the installed CLI on+ * 2026-09-30, and only the general-purpose ones (plan-, login- and experiment-gated entries are+ * left out: a command the user's CLI does not accept is worse than one they have to type). The+ * descriptions are ours, not copied. How each list was measured:+ *+ * - claude 2.1.285: typed `/` in the interactive TUI (private tmux server) and paged the whole+ * menu; cross-checked against the command objects in the binary.+ * - codex 0.156.1: the same, in its TUI.+ * - opencode 1.18.25: the same, on a fresh session (its menu lists 17 commands there).+ * - gemini 0.61.0: its TUI would not start without a login on the measuring host, so the list is+ * the intersection of the shipped command reference (bundle/docs/reference/commands.md) and the+ * commands its built-in loader registers.+ * - grok 1.0.13: no login on the measuring host either; the list is the command reference embedded+ * in the binary (`### /name` sections and the command table).+ *+ * Any other agent (copilot, antigravity, a custom agent with no base) gets no built-ins — it still+ * gets `@` file completion. A custom agent built on one of these inherits its base's list.+ */+const BUILTINS: Readonly<Record<string, readonly Builtin[]>> = Object.freeze({+ claude: [+ ['add-dir', 'Add a working directory'],+ ['branch', 'Branch the conversation at this point'],+ ['btw', 'Ask a side question without interrupting'],+ ['clear', 'Start over with an empty context'],+ ['compact', 'Summarize the conversation to free context'],+ ['config', 'Open settings'],+ ['context', 'Show context usage'],+ ['copy', 'Copy the last response'],+ ['diff', 'Show uncommitted changes'],+ ['effort', 'Set the effort level'],+ ['exit', 'Exit the CLI'],+ ['export', 'Export the conversation'],+ ['help', 'Show help and commands'],+ ['hooks', 'View hook configuration'],+ ['init', 'Create the project instruction file'],+ ['mcp', 'Manage MCP servers'],+ ['memory', 'Edit memory files'],+ ['model', 'Choose the model'],+ ['output-style', 'Switch output style'],+ ['permissions', 'Manage permission rules'],+ ['plan', 'Enter plan mode or view the plan'],+ ['plugin', 'Manage plugins'],+ ['recap', 'Summarize the session in one line'],+ ['release-notes', 'View release notes'],+ ['reload-skills', 'Pick up skills changed on disk'],+ ['rename', 'Rename the conversation'],+ ['resume', 'Resume a previous conversation'],+ ['rewind', 'Restore code or conversation to an earlier point'],+ ['security-review', 'Security review of pending changes'],+ ['skills', 'List available skills'],+ ['status', 'Show version, model and account'],+ ['statusline', 'Set up the status line'],+ ['tasks', 'Manage background tasks'],+ ['theme', 'Change the theme'],+ ['usage', 'Show usage and cost']+ ],+ codex: [+ ['agents', 'Open the agent command center'],+ ['cd', 'Change the working directory'],+ ['clear', 'Clear and start a new chat'],+ ['compact', 'Summarize the conversation to free context'],+ ['copy', 'Copy the last response'],+ ['diff', 'Show the git diff'],+ ['exit', 'Exit the CLI'],+ ['export', 'Export the conversation as markdown'],+ ['fork', 'Fork the current chat'],+ ['goal', 'Set or view the goal'],+ ['hooks', 'View and manage hooks'],+ ['init', 'Create the project instruction file'],+ ['mcp', 'List configured MCP tools'],+ ['mention', 'Mention a file'],+ ['model', 'Choose the model and reasoning effort'],+ ['new', 'Start a new chat'],+ ['permissions', 'Choose what the agent may do'],+ ['plan', 'Switch to plan mode'],+ ['ps', 'List background terminals'],+ ['recap', 'Summarize the conversation now'],+ ['rename', 'Rename the thread'],+ ['resume', 'Resume a saved chat'],+ ['review', 'Review current changes'],+ ['skills', 'Use skills'],+ ['status', 'Show session configuration and token usage'],+ ['stop', 'Stop background terminals'],+ ['theme', 'Choose a syntax theme'],+ ['usage', 'View account usage']+ ],+ gemini: [+ ['about', 'Show version info'],+ ['agents', 'List available agents'],+ ['chat', 'Manage conversation checkpoints'],+ ['clear', 'Clear the screen and start a new session'],+ ['commands', 'List or reload custom commands'],+ ['compress', 'Replace the context with a summary'],+ ['copy', 'Copy the last result'],+ ['directory', 'Manage workspace directories'],+ ['help', 'Show help'],+ ['hooks', 'Manage hooks'],+ ['init', 'Create the project instruction file'],+ ['mcp', 'Manage MCP servers'],+ ['model', 'Choose the model'],+ ['permissions', 'Manage folder trust'],+ ['plan', 'Switch to plan mode'],+ ['quit', 'Exit the CLI'],+ ['resume', 'Browse saved conversations'],+ ['rewind', 'Rewind to an earlier point'],+ ['settings', 'View and edit settings'],+ ['skills', 'Manage skills'],+ ['stats', 'Show session statistics'],+ ['theme', 'Change the theme'],+ ['tools', 'List available tools']+ ],+ grok: [+ ['btw', 'Send an aside without interrupting'],+ ['compact', 'Compress the conversation to free context'],+ ['context', 'Show context usage'],+ ['copy', 'Copy the last response'],+ ['effort', 'Set the reasoning effort'],+ ['exit', 'Exit the CLI'],+ ['export', 'Export the conversation'],+ ['help', 'Browse commands and shortcuts'],+ ['hooks', 'Manage hooks'],+ ['memory', 'Manage memory'],+ ['model', 'Switch models or reasoning effort'],+ ['new', 'Start a fresh session'],+ ['plan', 'Plan mode'],+ ['rename', 'Rename the session'],+ ['resume', 'Resume a previous session'],+ ['rewind', 'Rewind to an earlier turn'],+ ['settings', 'Open settings'],+ ['skills', 'Manage skills'],+ ['usage', 'Show usage']+ ],+ opencode: [+ ['agents', 'Switch agent'],+ ['connect', 'Connect a provider'],+ ['diff', 'Open the diff viewer'],+ ['editor', 'Open the editor'],+ ['exit', 'Exit the app'],+ ['help', 'Help'],+ ['init', 'Create the project instruction file'],+ ['mcps', 'Toggle MCP servers'],+ ['models', 'Switch model'],+ ['new', 'New session'],+ ['review', 'Review changes'],+ ['sessions', 'Switch session'],+ ['skills', 'Skills'],+ ['status', 'View status'],+ ['themes', 'Switch theme']+ ]+})++/** The measured built-ins for a node's agent (through a custom agent's base harness), or `[]`. */+export function builtinSlashCommands(agentId: string | undefined): ChatCatalogEntry[] {+ if (!agentId) return []+ const base = capabilityAgentId(agentId)+ if (!Object.prototype.hasOwnProperty.call(BUILTINS, base)) return []+ return BUILTINS[base].map(([name, description]) => ({ name, description, kind: 'builtin', scope: 'builtin' }))+}++/** Every agent id with a built-in table (tests walk it). */+export const BUILTIN_CATALOG_AGENTS: readonly string[] = Object.freeze(Object.keys(BUILTINS))++/**+ * Merge entries in precedence order — earlier lists win a name clash. Core passes project, then+ * user, then built-ins: the project's own command shadows the user's (the documented rule for+ * gemini's custom commands; the same order for claude's is our choice), and a custom command+ * named like a built-in is the one the user wrote, so it is the one offered.+ */+export function mergeCatalogEntries(...lists: readonly (readonly ChatCatalogEntry[])[]): ChatCatalogEntry[] {+ const seen = new Set<string>()+ const out: ChatCatalogEntry[] = []+ for (const list of lists) {+ for (const e of list) {+ const key = e.name.toLowerCase()+ if (seen.has(key)) continue+ seen.add(key)+ out.push(e)+ if (out.length >= CHAT_CATALOG_MAX_ENTRIES) return out+ }+ }+ return out+}++export const CATALOG_RESULT_LIMIT = 50++/**+ * The composer's `/` list for a query (what follows the slash): prefix matches first, then+ * names containing the query, then description-only matches; within a band, shorter names first,+ * then alphabetical. Case-insensitive. An empty query lists everything in that order.+ */+export function rankCatalog(entries: readonly ChatCatalogEntry[], query: string, limit = CATALOG_RESULT_LIMIT): ChatCatalogEntry[] {+ const q = query.toLowerCase()+ const scored: { e: ChatCatalogEntry; band: number }[] = []+ for (const e of entries) {+ const n = e.name.toLowerCase()+ let band: number+ if (!q || n.startsWith(q)) band = 0+ else if (n.includes(q)) band = 1+ else if (q.length >= 3 && e.description.toLowerCase().includes(q)) band = 2+ else continue+ scored.push({ e, band })+ }+ scored.sort((a, b) => a.band - b.band || a.e.name.length - b.e.name.length || a.e.name.localeCompare(b.e.name))+ return scored.slice(0, limit).map((s) => s.e)+}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 6c5293abe..ec2ca80cd 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -59,6 +59,8 @@ export const IPC = {ptyRaiseDeviceLimit: 'pty:raise-device-limit',claudeReadTranscript: 'claude:read-transcript',chatReadTranscript: 'chat:read-transcript',+ // The ⌘M composer's `/` catalog for a node: built-ins, custom commands, skills (core/chat-catalog.ts).+ chatCatalog: 'chat:catalog',/** Does a claude-shaped transcript exist for this session id? Tri-state* (`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". */diff --git a/src/shared/mobile-chat.ts b/src/shared/mobile-chat.tsindex 4ab2b682e..b421aa298 100644--- a/src/shared/mobile-chat.ts+++ b/src/shared/mobile-chat.ts@@ -27,6 +27,8 @@ export type ChatHostRefusal = 'working' | 'dialog'* The phone's composer is unlocked ONLY when `version` is one it knows, `hostRefuses` is false,* `held` is null and `state` is `done` or `null`. Any `state` value it does not recognize (a newer* desktop) ⇒ locked. The desktop re-checks every send regardless. */+import type { ChatCatalog } from './chat-catalog'+export interface ChatStatus {/** Shape version; a phone that does not know it treats the composer as locked. */version: 1@@ -48,10 +50,18 @@ export interface ChatStatus {hostRefuses: boolean/** Why, when `hostRefuses`. */refusal?: ChatHostRefusal+ /**+ * The composer's `/` catalog for this node (built-ins, custom commands, skills — the same one the+ * desktop's ⌘M composer offers). Present ONLY when the request asked for it (`catalog: true` in+ * the `chat.status` params) and the host could build it; an older phone never asks and never sees+ * it. Names and descriptions are re-checked by `sanitizeChatCatalog` on the host before sending;+ * a client must treat them as data (one line each), never as markup.+ */+ catalog?: ChatCatalog}/** What the renderer contributes to `ChatStatus`; main adds the rest (ticket ledger, host mirror). */-export type RendererChatStatus = Omit<ChatStatus, 'structuredAnswers' | 'version' | 'hostRefuses' | 'refusal'>+export type RendererChatStatus = Omit<ChatStatus, 'structuredAnswers' | 'version' | 'hostRefuses' | 'refusal' | 'catalog'>/** `refused` = never started (nothing was typed: no window, the gate refused, or it arrived too* late to start). `unconfirmed` = the send WAS dispatched to the desktop but no result came back indiff --git a/src/shared/types.ts b/src/shared/types.tsindex 2e32a6b2e..a5164b82b 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -3232,6 +3232,16 @@ export interface ChatApi {accountId?: string,nodeId?: string): Promise<TranscriptPresence>++ /**+ * The ⌘M composer's `/` catalog for a node: its agent's measured built-in slash commands, custom+ * command files and skills (core/chat-catalog.ts). An SSH-project node's files are read on its+ * HOST (`nodeId` — remoteness is the shell's own record, never this call's). A relay tab REJECTS+ * (E_UNSUPPORTED — the peer's files are not this machine's to read, and the relay does not carry+ * the channel); the composer then offers the shared built-in table alone, and every caller must+ * treat any rejection the same way.+ */+ catalog(nodeId: string, agentId: string, accountId?: string, cwd?: string): Promise<import('./chat-catalog').ChatCatalog>}/** Optional SSH context for account ops. When `projectId` names a connected SSH project, the