Skip to content

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.

fix(chat-catalog): review round — dialog built-ins flip to the terminal, derived menu, no symlinks in project roots

review868c718d8448
diff --git a/CLAUDE.md b/CLAUDE.md
index 3cbe9dbf4..028035f1e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3221,16 +3221,29 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
`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.
+ - **Built-ins are only what was MEASURED** (2026-09-30), by typing `/` in each TUI inside a private
+ tmux server and paging the whole menu: claude 2.1.285, codex 0.156.1, opencode 1.18.25, gemini
+ 0.62.0 (throwaway HOME + a dummy API key — the menu is client-side). **grok has no table**: 1.0.44
+ would not start past its browser sign-in on the measuring host, and a list copied from docs is a
+ guess about the binary the user runs. Plan-, login- and experiment-gated entries are left out.
+ Any other agent (grok, copilot, antigravity, a custom agent with no base) gets `@` only; a custom
+ agent inherits its base's table through `capabilityAgentId`. The descriptions are our own words.
+ - **A built-in that opens a DIALOG in the TUI is `interactive`, and sending one flips to the
+ terminal.** `/model`, `/rewind`, `/resume`, `/config`, `/permissions`, … open a picker the ⌘M view
+ cannot see while the state still reads `done` — the next message's Enter would ANSWER it (confirm
+ the highlighted row), the hazard the toolbar labels already guard. So every built-in is tagged
+ `interactive` EXCEPT a per-agent `SAFE` set of measured no-dialog commands (claude
+ `clear compact init recap reload-skills security-review`, codex `clear compact init new recap`,
+ gemini `clear compress init`, opencode `new`) — unknown means dialog, because over-tagging costs a
+ flip and under-tagging costs a wrong answer. `ChatPanel.send` calls `onShowTerminal` after a send
+ confirmed `=== true` whose text `isInteractiveBuiltin` (menu-completed OR typed by hand, with or
+ without arguments); a composer with no `onShowTerminal` does not offer those entries at all. The
+ phone gets the tag in its catalog and owes the same rule.
- **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
+ `dir:name` namespace; description = frontmatter `description`, else the first body line; a
+ `SKILL.md` inside a commands folder names its FOLDER, `review/SKILL.md` → `review`, per the 2.1.285
+ loader) 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
@@ -3240,12 +3253,25 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
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.
+ - **A PROJECT root follows no symlink, at any level** (`CatalogRoot.within`). A cloned repository's
+ `.claude/commands/notes.md -> ~/.git-credentials` otherwise put the token-bearing first line in
+ the menu and in the phone's catalog (reproduced in review, both legs). Locally entries are
+ lstat'ed and files opened `O_NOFOLLOW`; remotely `find -P` and `[ -L ]` on the skill folder and
+ its SKILL.md; and the root itself must resolve inside the cwd (realpath / `pwd -P`), so a
+ `.claude` linked out of the project lists nothing. USER roots (the person's own config dir) are
+ followed — that is how shared system skills reach an account dir.
- **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`.
+ - **The menu is DERIVED from the draft plus a caret snapshot taken for that exact draft**
+ (`caretSnap.value === value`), never kept as its own state. A draft changed outside the textarea
+ — ChatPanel clearing it after the async send, dictation, an attach — invalidates the snapshot and
+ closes the menu (reproduced in review: send `/compact`, the Enter's keyup re-armed the menu from the
+ old text, and Tab then turned the emptied draft back into `/compact `). A disabled composer derives
+ nothing. A bare `@` is not a choice: Enter sends `hello @`, Tab still accepts.
- **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
@@ -3266,7 +3292,12 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
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
+ (docs/mobile-chat-view.md); an older phone never asks. It is bounded
+ (`HOST_CHAT_CATALOG_TIMEOUT_MS`, 4 s, then the status goes out WITHOUT it — `chat.status` is the
+ relay's status poll and must never wait on an ssh round trip to a half-dead master), and a client
+ asks once per composer open, not on every poll. The Server Edition names an SSH-project node
+ remote (`workspaceStore.sshProjectIdForNode`), so it answers built-ins + `partial` there instead of
+ reading the server's own `~/.claude`. 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
diff --git a/docs/mobile-chat-view.md b/docs/mobile-chat-view.md
index abbb7b19f..68d39c2c7 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`. 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.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. The host waits at most 4 s for it (an SSH node's catalog is an ssh round trip) and then answers WITHOUT it — so a client asks with `catalog: true` ONCE per composer open (and again only when the user opens the menu after a while), never on every status poll. An entry with `interactive: true` is a built-in that opens a dialog in the agent's TUI: a client that cannot show the terminal after sending it must not offer it (the dialog would be invisible and the next send would answer it). 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.ts
index aa173d2a3..c717f660e 100644
--- a/src/core/chat-catalog.test.ts
+++ b/src/core/chat-catalog.test.ts
@@ -52,6 +52,10 @@ describe('parsers', () => {
expect(commandNameFromRel('../x.md', '.md')).toBeNull()
expect(commandNameFromRel('x.txt', '.md')).toBeNull()
expect(commandNameFromRel('a\u001b[31m.md', '.md')).toBeNull()
+ // Measured (2.1.285 loader): a SKILL.md inside commands names its FOLDER; one at the top names nothing.
+ expect(commandNameFromRel('review/SKILL.md', '.md')).toBe('review')
+ expect(commandNameFromRel('git/pr/skill.md', '.md')).toBe('git:pr')
+ expect(commandNameFromRel('SKILL.md', '.md')).toBeNull()
})
it('reads flat frontmatter and leaves a file without it as body', () => {
@@ -121,6 +125,43 @@ describe('claude, local', () => {
expect(names(c)).not.toContain('a:b:c:deep')
})
+ it('a PROJECT root follows no symlink: a committed link cannot leak a file outside the project', async () => {
+ const outside = testTmpDir('catalog-outside-')
+ write(path.join(outside, 'creds'), 'https://alice:[email protected]\n')
+ write(path.join(outside, 'skill/SKILL.md'), '---\nname: leaked-skill\ndescription: ghp_SECRET2\n---\n')
+ write(path.join(outside, 'cmds/stolen.md'), 'ghp_SECRET3')
+ write(path.join(proj, '.claude/commands/real.md'), 'fine')
+ fs.symlinkSync(path.join(outside, 'creds'), path.join(proj, '.claude/commands/notes.md'))
+ fs.symlinkSync(path.join(outside, 'cmds'), path.join(proj, '.claude/commands/sub'))
+ fs.mkdirSync(path.join(proj, '.claude/skills'), { recursive: true })
+ fs.symlinkSync(path.join(outside, 'skill'), path.join(proj, '.claude/skills/lnk'))
+ write(path.join(proj, '.claude/skills/own/x'), '')
+ fs.symlinkSync(path.join(outside, 'skill/SKILL.md'), path.join(proj, '.claude/skills/own/SKILL.md'))
+ const c = await buildLocalCatalog({ agentId: 'claude', accountId: undefined, cwd: proj }, { home })
+ expect(names(c)).toContain('real')
+ expect(JSON.stringify(c)).not.toMatch(/SECRET/)
+ expect(names(c)).not.toContain('notes')
+ expect(names(c)).not.toContain('sub:stolen')
+ expect(names(c)).not.toContain('leaked-skill')
+ })
+
+ it('a project whose .claude is a link OUT of the project lists nothing from it', async () => {
+ const outside = testTmpDir('catalog-outside-')
+ write(path.join(outside, 'commands/x.md'), 'ghp_SECRET')
+ fs.symlinkSync(outside, path.join(proj, '.claude'))
+ const c = await buildLocalCatalog({ agentId: 'claude', accountId: undefined, cwd: proj }, { home })
+ expect(names(c)).not.toContain('x')
+ })
+
+ it('a USER root still follows links (how shared skills reach an account dir)', async () => {
+ const shared = testTmpDir('catalog-shared-')
+ write(path.join(shared, 'sk/SKILL.md'), '---\nname: shared-skill\ndescription: d\n---\n')
+ fs.mkdirSync(path.join(home, '.claude/skills'), { recursive: true })
+ fs.symlinkSync(path.join(shared, 'sk'), path.join(home, '.claude/skills/sk'))
+ const c = await buildLocalCatalog({ agentId: 'claude', accountId: undefined, cwd: proj }, { home })
+ expect(names(c)).toContain('shared-skill')
+ })
+
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')
@@ -166,18 +207,20 @@ describe('other agents', () => {
expect(byName(c, 'compress')?.kind).toBe('builtin')
})
- it('codex, grok, opencode: built-ins only — their custom locations were not measured', async () => {
+ it('codex, 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']) {
+ for (const agentId of ['codex', '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([])
+ it('an agent with no measured table gets nothing (grok 1.0.44 could not be measured)', async () => {
+ for (const agentId of ['copilot', 'grok']) {
+ const c = await buildLocalCatalog({ agentId, accountId: undefined, cwd: proj }, { home })
+ expect(c.entries).toEqual([])
+ }
})
})
@@ -207,6 +250,36 @@ describe('remote (one ssh round trip)', () => {
expect(partial).toBe(false)
})
+ it('the remote leg follows no link in a PROJECT root either (real /bin/sh)', () => {
+ const host = testTmpDir('catalog-host-')
+ const cwd = path.join(host, 'repo')
+ write(path.join(host, 'secret/creds'), 'https://alice:[email protected]\n')
+ write(path.join(host, 'secret/sk/SKILL.md'), '---\nname: leaked\ndescription: ghp_SECRET2\n---\n')
+ write(path.join(host, 'secret/cmds/stolen.md'), 'ghp_SECRET3')
+ write(path.join(cwd, '.claude/commands/real.md'), 'fine')
+ fs.symlinkSync(path.join(host, 'secret/creds'), path.join(cwd, '.claude/commands/notes.md'))
+ fs.symlinkSync(path.join(host, 'secret/cmds'), path.join(cwd, '.claude/commands/sub'))
+ fs.mkdirSync(path.join(cwd, '.claude/skills/own'), { recursive: true })
+ fs.symlinkSync(path.join(host, 'secret/sk'), path.join(cwd, '.claude/skills/lnk'))
+ fs.symlinkSync(path.join(host, 'secret/sk/SKILL.md'), path.join(cwd, '.claude/skills/own/SKILL.md'))
+ // A second project whose whole .claude points out of it.
+ const cwd2 = path.join(host, 'repo2')
+ fs.mkdirSync(cwd2, { recursive: true })
+ write(path.join(host, 'secret/dotclaude/commands/x.md'), 'ghp_SECRET4')
+ fs.symlinkSync(path.join(host, 'secret/dotclaude'), path.join(cwd2, '.claude'))
+ for (const dir of [cwd, cwd2]) {
+ const roots = catalogRoots({ agentId: 'claude', accountId: undefined, cwd: dir }, { remote: true })
+ const out = execFileSync('/bin/sh', ['-c', remoteCatalogCommand(roots)], {
+ env: { PATH: '/usr/local/bin:/usr/bin:/bin', HOME: path.join(host, 'nohome') },
+ encoding: 'utf8'
+ })
+ expect(out).not.toMatch(/SECRET/)
+ const n = parseRemoteCatalog(out, roots).perRoot.flat().map((e) => e.name)
+ if (dir === cwd) expect(n).toEqual(['real'])
+ else expect(n).toEqual([])
+ }
+ })
+
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[] = []
diff --git a/src/core/chat-catalog.ts b/src/core/chat-catalog.ts
index 29fbedcc7..3bfdfe8e4 100644
--- a/src/core/chat-catalog.ts
+++ b/src/core/chat-catalog.ts
@@ -20,7 +20,7 @@
// 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 { constants as fsConstants, promises as fsp } from 'fs'
import os from 'os'
import path from 'path'
import { IPC } from '../shared/ipc'
@@ -52,6 +52,16 @@ export interface CatalogRoot {
scope: Exclude<ChatCatalogScope, 'builtin'>
/** A local absolute path, or (remote) a path the remote shell resolves — `~/…` or absolute. */
dir: string
+ /**
+ * PROJECT roots only: the node's cwd. A project's command and skill folders are whatever the
+ * repository holds, and a symlink committed there (`notes.md -> ~/.git-credentials`) would put the
+ * first line of a file OUTSIDE the project into the menu — and into the phone's catalog. So for a
+ * project root no symlink is followed at any level (entries are lstat'ed, files opened
+ * O_NOFOLLOW; remotely `find -P` and `[ -L ]`), and the root itself must resolve inside `within`.
+ * User roots (the person's own config dir) are followed: that is how shared system skills reach
+ * an account dir.
+ */
+ within?: string
}
export interface ChatCatalogQuery {
@@ -83,15 +93,15 @@ export function catalogRoots(q: ChatCatalogQuery, opts: { remote: boolean; home?
}
} 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') })
+ roots.push({ kind: 'md-commands', scope: 'project', dir: join(cwd, '.claude', 'commands'), within: cwd })
+ roots.push({ kind: 'skills', scope: 'project', dir: join(cwd, '.claude', 'skills'), within: cwd })
}
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') })
+ if (cwd) roots.push({ kind: 'toml-commands', scope: 'project', dir: join(cwd, '.gemini', 'commands'), within: cwd })
roots.push({ kind: 'toml-commands', scope: 'user', dir: opts.remote ? '~/.gemini/commands' : path.join(home, '.gemini', 'commands') })
}
return roots
@@ -126,10 +136,18 @@ function firstBodyLine(body: string): string {
return ''
}
-/** `git/commit.md` → `git:commit`. Null when any segment is not a typeable name. */
+/** `git/commit.md` → `git:commit`. Null when any segment is not a typeable name. A `SKILL.md` inside
+ * a claude commands folder names its FOLDER (`review/SKILL.md` → `review`, measured against the
+ * 2.1.285 loader: a file matching `skill.md`, any case, takes the joined folder path); one at the
+ * top of the root has no folder and is no command. */
export function commandNameFromRel(rel: string, ext: '.md' | '.toml'): string | null {
const norm = rel.replace(/\\/g, '/')
if (!norm.toLowerCase().endsWith(ext)) return null
+ if (ext === '.md' && /(^|\/)skill\.md$/i.test(norm)) {
+ const dirs = norm.split('/').slice(0, -1)
+ if (!dirs.length || dirs.some((p) => !p || p === '.' || p === '..')) return null
+ return catalogName(dirs.join(':'))
+ }
const parts = norm.slice(0, -ext.length).split('/')
if (parts.some((p) => !p || p === '.' || p === '..')) return null
return catalogName(parts.join(':'))
@@ -193,39 +211,47 @@ export function resetChatCatalogCache(): void {
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> {
+/** A directory's entries, from cache while the directory's mtime is unchanged. `follow` = symlinks
+ * are followed (user roots); otherwise a symlink is no entry at all and the directory itself must
+ * not be one (project roots). `null` = the directory does not exist (or is a refused link); a
+ * failure other than absence throws (→ `partial`). */
+async function listLocalDir(dir: string, follow: boolean): Promise<{ name: string; dir: boolean }[] | null> {
let st
try {
- st = await fsp.stat(dir)
+ st = await (follow ? fsp.stat(dir) : fsp.lstat(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)
+ const key = `${follow ? 'f' : 'n'}:${dir}`
+ const hit = dirCache.get(key)
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))
+ const s = await (follow ? fsp.stat(path.join(dir, name)) : fsp.lstat(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 })
+ bounded(dirCache, key, { mtimeMs: st.mtimeMs, entries })
return entries
}
-async function readLocalHead(file: string): Promise<string | null> {
+// Absent on Windows, where a project symlink is rare and needs privilege to create; the lstat'ed
+// listing above is the guard there.
+const O_NOFOLLOW = fsConstants.O_NOFOLLOW ?? 0
+
+async function readLocalHead(file: string, follow: boolean): Promise<string | null> {
try {
// Open FIRST and stat the handle: the (mtime, size) the cache is keyed on then describes the very
- // bytes read, never a file swapped in between a path stat and the open.
- const fh = await fsp.open(file, 'r')
+ // bytes read, never a file swapped in between a path stat and the open. A project file is opened
+ // O_NOFOLLOW, so a symlink swapped in after the listing fails the open instead of being read.
+ const fh = await fsp.open(file, follow ? fsConstants.O_RDONLY : fsConstants.O_RDONLY | O_NOFOLLOW)
try {
const st = await fh.stat()
if (!st.isFile()) return null
@@ -247,7 +273,21 @@ async function readLocalHead(file: string): Promise<string | 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)
+ const follow = root.within === undefined
+ if (!follow) {
+ // The root must resolve inside the project (`.claude -> /elsewhere` leaves it). A root that does
+ // not exist is simply absent.
+ let real: string
+ let realWithin: string
+ try {
+ real = await fsp.realpath(root.dir)
+ realWithin = await fsp.realpath(root.within!)
+ } catch {
+ return null
+ }
+ if (real !== realWithin && !real.startsWith(realWithin.endsWith(path.sep) ? realWithin : realWithin + path.sep)) return null
+ }
+ const top = await listLocalDir(root.dir, follow)
if (!top) return null
const out: { rel: string; file: string }[] = []
if (root.kind === 'skills') {
@@ -265,7 +305,7 @@ async function localRootFiles(root: CatalogRoot): Promise<{ rel: string; file: s
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)
+ const sub = await listLocalDir(path.join(dir, e.name), follow).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) })
}
@@ -288,7 +328,7 @@ export async function buildLocalCatalog(q: ChatCatalogQuery, opts: { home?: stri
}
const out: ChatCatalogEntry[] = []
for (const f of files ?? []) {
- const text = await readLocalHead(f.file)
+ const text = await readLocalHead(f.file, root.within === undefined)
if (text === null) continue
const e = entryFor(root, f.rel, text)
if (e) out.push(e)
@@ -315,16 +355,24 @@ const RS = '\u001e'
export function remoteCatalogCommand(roots: readonly CatalogRoot[]): string {
const parts = roots.map((root, i) => {
const d = quoteRemotePath(root.dir)
+ const project = root.within !== undefined
const emit = `printf '\\036F ${i} %s\\n' "$r"; head -c ${CATALOG_HEAD_BYTES} "$f" 2>/dev/null | tr -d '\\036'; printf '\\n'`
+ // A PROJECT root must resolve inside the node's cwd (`pwd -P` of both — POSIX, BSD and GNU alike),
+ // and nothing under it is followed: `find -P`, and `[ -L ]` on the skill folder and its SKILL.md.
+ // A user root follows links (`find -L`; the glob follows a linked skill folder).
+ const inside = project
+ ? `w=$(cd ${quoteRemotePath(root.within!)} 2>/dev/null && pwd -P) && r0=$(cd "$d" 2>/dev/null && pwd -P) && case "$r0/" in "$w"/*) true;; *) false;; esac`
+ : 'true'
+ const noLinks = project ? `[ -L "\${f%/SKILL.md}" ] && continue; [ -L "$f" ] && continue; ` : ''
if (root.kind === 'skills') {
return (
- `d=${d}; if [ -d "$d" ]; then n=0; for f in "$d"/*/SKILL.md; do [ -f "$f" ] || continue; ` +
+ `d=${d}; if [ -d "$d" ] && ${inside}; then n=0; for f in "$d"/*/SKILL.md; do ${noLinks}[ -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'; } ` +
+ `d=${d}; if [ -d "$d" ] && ${inside}; then { find ${project ? '-P' : '-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`
)
})
diff --git a/src/main/remote/host-chat-wiring.test.ts b/src/main/remote/host-chat-wiring.test.ts
index ac4998954..8533dc114 100644
--- a/src/main/remote/host-chat-wiring.test.ts
+++ b/src/main/remote/host-chat-wiring.test.ts
@@ -38,7 +38,8 @@ describe('phone chat verbs are wired end to end', () => {
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\(\)/)
+ // The Server Edition names an SSH-project node remote (built-ins + partial), never reads its own ~/.claude for it.
+ expect(read('server/index.ts')).toMatch(/registerChatCatalogIpc\(\{ isRemoteNode: \(nodeId\) => !!workspaceStore\.sshProjectIdForNode\(nodeId\) \}\)/)
})
it('the renderer answers the round-trip', () => {
const canvas = read('renderer/canvas/Canvas.tsx')
diff --git a/src/main/remote/host-chat.test.ts b/src/main/remote/host-chat.test.ts
index fcb826f2f..2e47cc036 100644
--- a/src/main/remote/host-chat.test.ts
+++ b/src/main/remote/host-chat.test.ts
@@ -214,6 +214,12 @@ describe('host-chat status', () => {
expect(s2).toMatchObject({ version: 1, state: 'done' })
expect(s2).not.toHaveProperty('catalog')
})
+ it('a catalog that does not answer in time is DROPPED — the status never waits on a half-dead master', async () => {
+ const d = deps({ catalog: vi.fn(() => new Promise<never>(() => {})), catalogTimeoutMs: 20 })
+ const s = await createHostChat(d).status('n1', { catalog: true })
+ expect(s).toMatchObject({ version: 1, state: 'done' })
+ expect(s).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.ts
index 32c1678c0..6c15eeeaf 100644
--- a/src/main/remote/host-chat.ts
+++ b/src/main/remote/host-chat.ts
@@ -63,6 +63,10 @@ export interface HostChatDeps {
/** 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>
+ /** How long the catalog may take before the status goes out WITHOUT it. An SSH node's catalog is
+ * an ssh round trip (and the child gate's queue) on a master that may be half dead; `chat.status`
+ * must never wait on that. Default `HOST_CHAT_CATALOG_TIMEOUT_MS`. */
+ catalogTimeoutMs?: number
/** 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
@@ -92,6 +96,7 @@ export function mirrorChatSendRefusal(
export const HOST_CHAT_BUSY_CAP_MS = 30_000
export const HOST_CHAT_RENDERER_TIMEOUT_MS = 3000
+export const HOST_CHAT_CATALOG_TIMEOUT_MS = 4000
export const HOST_CHAT_SEND_TIMEOUT_MS = 15_000
const TIMED_OUT = Symbol('timed-out')
@@ -184,9 +189,11 @@ export function createHostChat(deps: HostChatDeps): HostChatOps {
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 })
+ const built = await withTimeout(
+ deps.catalog({ nodeId, agentId: node.agentId, accountId: node.accountId, cwd: node.cwd }),
+ deps.catalogTimeoutMs ?? HOST_CHAT_CATALOG_TIMEOUT_MS
)
+ catalog = built === TIMED_OUT ? undefined : sanitizeChatCatalog(built)
} catch {
catalog = undefined
}
diff --git a/src/renderer/lib/chatComposerComplete.test.ts b/src/renderer/lib/chatComposerComplete.test.ts
index c67011b0d..0ecd180a6 100644
--- a/src/renderer/lib/chatComposerComplete.test.ts
+++ b/src/renderer/lib/chatComposerComplete.test.ts
@@ -6,6 +6,7 @@ import {
builtinSlashCommands,
catalogDescription,
catalogName,
+ isInteractiveBuiltin,
rankCatalog,
sanitizeChatCatalog,
type ChatCatalogEntry
@@ -101,7 +102,8 @@ describe('the shared catalog', () => {
})
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'])
+ // grok is deliberately absent: 1.0.44 could not be measured (browser sign-in) on the measuring host.
+ expect([...BUILTIN_CATALOG_AGENTS].sort()).toEqual(['claude', 'codex', 'gemini', 'opencode'])
for (const a of BUILTIN_CATALOG_AGENTS) {
const list = builtinSlashCommands(a)
expect(list.length).toBeGreaterThan(0)
@@ -109,6 +111,7 @@ describe('the shared catalog', () => {
expect(new Set(list.map((x) => x.name)).size).toBe(list.length)
}
expect(builtinSlashCommands('copilot')).toEqual([])
+ expect(builtinSlashCommands('grok')).toEqual([])
expect(builtinSlashCommands(undefined)).toEqual([])
expect(builtinSlashCommands('constructor')).toEqual([])
})
@@ -117,4 +120,36 @@ describe('the shared catalog', () => {
const n = builtinSlashCommands('claude').map((x) => x.name)
expect(n).toEqual(expect.arrayContaining(['model', 'effort']))
})
+
+ it('built-ins that open a TUI dialog are tagged; unknown means dialog, only the measured no-dialog ones are not', () => {
+ const tag = (a: string, n: string) => builtinSlashCommands(a).find((x) => x.name === n)?.interactive
+ for (const n of ['model', 'effort', 'rewind', 'resume', 'config', 'permissions', 'mcp', 'hooks', 'memory', 'plugin', 'theme', 'tasks']) {
+ expect(tag('claude', n)).toBe(true)
+ }
+ for (const n of ['clear', 'compact', 'init', 'recap']) expect(tag('claude', n)).toBeUndefined()
+ expect(tag('codex', 'model')).toBe(true)
+ expect(tag('gemini', 'compress')).toBeUndefined()
+ expect(tag('opencode', 'models')).toBe(true)
+ })
+
+ it('isInteractiveBuiltin reads the SENT text: typed or completed, with or without arguments, never a custom command', () => {
+ expect(isInteractiveBuiltin('claude', '/rewind')).toBe(true)
+ expect(isInteractiveBuiltin('claude', ' /model sonnet ')).toBe(true)
+ expect(isInteractiveBuiltin('claude', '/compact')).toBe(false)
+ expect(isInteractiveBuiltin('claude', '/git:commit')).toBe(false)
+ expect(isInteractiveBuiltin('claude', 'please /rewind')).toBe(false)
+ expect(isInteractiveBuiltin('claude', '/Rewind')).toBe(false)
+ expect(isInteractiveBuiltin('grok', '/model')).toBe(false)
+ expect(isInteractiveBuiltin(undefined, '/model')).toBe(false)
+ })
+
+ it('the interactive tag survives a wire, only as a literal true', () => {
+ const c = sanitizeChatCatalog({
+ entries: [
+ { name: 'a', description: '', kind: 'builtin', scope: 'builtin', interactive: true },
+ { name: 'b', description: '', kind: 'builtin', scope: 'builtin', interactive: 'yes' }
+ ]
+ })
+ expect(c.entries.map((e) => e.interactive)).toEqual([true, undefined])
+ })
})
diff --git a/src/renderer/nodes/ChatComposer.complete.test.tsx b/src/renderer/nodes/ChatComposer.complete.test.tsx
index e076a96df..7c7297e8e 100644
--- a/src/renderer/nodes/ChatComposer.complete.test.tsx
+++ b/src/renderer/nodes/ChatComposer.complete.test.tsx
@@ -51,9 +51,11 @@ afterEach(async () => {
host.remove()
})
-function Harness({ disabled = false }: { disabled?: boolean }) {
+let setDraft: (v: string) => void
+function Harness({ disabled = false, noTerminal = false, clearOnSend = false }: { disabled?: boolean; noTerminal?: boolean; clearOnSend?: boolean }) {
const [value, setValue] = useState('')
draft = () => value
+ setDraft = setValue
return (
<ChatComposer
nodeId="n1"
@@ -61,11 +63,16 @@ function Harness({ disabled = false }: { disabled?: boolean }) {
agentLabel="Agent"
value={value}
onChange={setValue}
- onSend={onSend}
+ onSend={() => {
+ onSend()
+ // ChatPanel clears the draft only AFTER its async pane check and send.
+ if (clearOnSend) setTimeout(() => setValue(''), 40)
+ }}
placeholder="Message"
disabled={disabled}
onWriteRefused={() => {}}
cwd="/proj"
+ onShowTerminal={noTerminal ? undefined : () => {}}
/>
)
}
@@ -94,8 +101,18 @@ async function key(k: string): Promise<KeyboardEvent> {
return ev
}
-async function mount(disabled = false): Promise<void> {
- await act(async () => root.render(<Harness disabled={disabled} />))
+async function mount(disabled = false, extra: { noTerminal?: boolean; clearOnSend?: boolean } = {}): Promise<void> {
+ await act(async () => root.render(<Harness disabled={disabled} {...extra} />))
+}
+async function keyup(k: string): Promise<void> {
+ await act(async () => {
+ ta().dispatchEvent(new KeyboardEvent('keyup', { key: k, bubbles: true }))
+ })
+}
+async function tick(): Promise<void> {
+ await act(async () => {
+ await new Promise((r) => setTimeout(r, 80))
+ })
}
describe('ChatComposer completion', () => {
@@ -178,4 +195,56 @@ describe('ChatComposer completion', () => {
await type('/co')
expect(options()).toEqual([])
})
+
+ it('a draft cleared AFTER the send (ChatPanel\'s async clear) closes the menu — Tab cannot resurrect the command', async () => {
+ await mount(false, { clearOnSend: true })
+ await type('/compact')
+ await key('Enter')
+ // The Enter's own keyup re-syncs from the still-full textarea, then the draft clears.
+ await keyup('Enter')
+ await tick()
+ expect(draft()).toBe('')
+ expect(options()).toEqual([])
+ const tab = await key('Tab')
+ expect(tab.defaultPrevented).toBe(false)
+ expect(draft()).toBe('')
+ expect(onSend).toHaveBeenCalledTimes(1)
+ })
+
+ it('text appended from outside (dictation, attach) closes the menu, so an accept never replaces a range it did not see', async () => {
+ await mount()
+ await type('/co')
+ expect(options().length).toBeGreaterThan(0)
+ await act(async () => setDraft('/co and some dictated words'))
+ expect(options()).toEqual([])
+ await key('Tab')
+ expect(draft()).toBe('/co and some dictated words')
+ })
+
+ it('a composer that becomes disabled with the menu open closes it and accepts nothing', async () => {
+ await mount()
+ await type('/co')
+ await act(async () => root.render(<Harness disabled />))
+ expect(options()).toEqual([])
+ expect(host.querySelector('.term-chat__complete')).toBeNull()
+ })
+
+ it('a bare `@` is not a choice: Enter sends "hello @"; Tab still accepts', async () => {
+ await mount()
+ await type('hello @')
+ expect(options().length).toBeGreaterThan(0)
+ await key('Enter')
+ expect(onSend).toHaveBeenCalledTimes(1)
+ expect(draft()).toBe('hello @')
+ })
+
+ it('without a way to show the terminal, built-ins that open a TUI dialog are not offered', async () => {
+ // The shared table (what a relay tab gets, and what core's catalog carries for built-ins).
+ api.chat.catalog.mockRejectedValue(new Error('no catalog here'))
+ await mount(false, { noTerminal: true })
+ await type('/mod')
+ expect(options().some((t) => t.startsWith('/model'))).toBe(false)
+ await type('/comp')
+ expect(options().some((t) => t.startsWith('/compact'))).toBe(true)
+ })
})
diff --git a/src/renderer/nodes/ChatComposer.tsx b/src/renderer/nodes/ChatComposer.tsx
index 08102fcb5..218ddd2d5 100644
--- a/src/renderer/nodes/ChatComposer.tsx
+++ b/src/renderer/nodes/ChatComposer.tsx
@@ -119,17 +119,21 @@ export function ChatComposer({
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.
+ // The trigger is DERIVED at render from the draft and the caret — and the caret is only known for
+ // the exact draft it was read with (`caretSnap.value`). Any change to the draft that did not come
+ // through this textarea (the send clearing it after its async pane check, dictation, an attach,
+ // an accept) leaves the snapshot describing another text, so the menu is closed until the user
+ // types or moves the caret again; an accept can therefore never replace a range of a draft it did
+ // not see. A disabled composer derives nothing. 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 [caretSnap, setCaretSnap] = useState<{ value: string; start: number; end: number } | null>(null)
+ const trigger: CompletionTrigger | null =
+ !disabled && caretSnap && caretSnap.value === value ? completionTriggerAt(value, caretSnap.start, caretSnap.end) : null
+ const lastTokenRef = useRef<string | null>(null)
+ const closeMenu = useCallback(() => setCaretSnap(null), [])
const [activeIdx, setActiveIdx] = useState(0)
const [dismissedAt, setDismissedAt] = useState<number | null>(null)
const [catalog, setCatalog] = useState<ChatCatalogEntry[]>(() => builtinSlashCommands(agentId))
@@ -177,23 +181,26 @@ export function ChatComposer({
)
const syncTrigger = useCallback(
(text: string, caret: number, selEnd: number) => {
+ setCaretSnap({ value: text, start: caret, end: selEnd })
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)
+ const token = t ? `${t.kind}:${t.start}` : null
+ if (token !== lastTokenRef.current) setActiveIdx(0)
+ lastTokenRef.current = token
if (t) ensureLists(t.kind)
},
[disabled, ensureLists]
)
+ // A composer that cannot flip to the terminal (no `onShowTerminal`) does not offer a built-in that
+ // opens a dialog there: the dialog would be invisible and the next Enter would answer it.
+ const offered = onShowTerminal ? catalog : catalog.filter((e) => !e.interactive)
const items: CompletionItem[] =
- trigger && dismissedAt !== trigger.start ? completionItems(trigger, catalog, fileIndex) : []
+ trigger && dismissedAt !== trigger.start ? completionItems(trigger, offered, fileIndex) : []
const menuOpen = items.length > 0
const active = Math.min(activeIdx, Math.max(0, items.length - 1))
const accept = (item: CompletionItem) => {
- if (!trigger) return
+ if (!trigger || disabled) return
const next = applyCompletion(value, trigger, item.value)
onChange(next.text)
closeMenu()
@@ -360,9 +367,11 @@ export function ChatComposer({
}
// 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.
+ // A bare `@` (no query yet) is not a choice either: "hello @" + Enter sends. Tab still accepts.
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') {
+ const bareAt = trigger?.kind === 'file' && !trigger.query
+ if ((e.key === 'Enter' && !e.shiftKey && !typedExactly && !bareAt) || e.key === 'Tab') {
e.preventDefault()
accept(items[active])
return
diff --git a/src/renderer/nodes/ChatPanel.live.test.tsx b/src/renderer/nodes/ChatPanel.live.test.tsx
index 33d68064e..90067c222 100644
--- a/src/renderer/nodes/ChatPanel.live.test.tsx
+++ b/src/renderer/nodes/ChatPanel.live.test.tsx
@@ -461,3 +461,54 @@ describe('ChatPanel — a sent local command', () => {
expect(pending.length).toBe(after)
})
})
+
+describe('ChatPanel — a sent built-in that opens a dialog in the TUI', () => {
+ async function renderWith(onShowTerminal: () => void): Promise<void> {
+ await act(async () => {
+ root.render(<ChatPanel nodeId={NODE} sessionId="s1" agentId="claude" onShowTerminal={onShowTerminal} />)
+ })
+ }
+ async function send(text: string): Promise<void> {
+ const ta = host.querySelector('textarea') as HTMLTextAreaElement
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(ta, text)
+ ta.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ await act(async () => {
+ ta.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
+ })
+ }
+
+ it('/rewind is sent, THEN the view flips to the terminal (the dialog is there, and the next Enter would answer it)', async () => {
+ const onShowTerminal = vi.fn(() => {
+ // The flip happens only after the pane accepted the text.
+ expect(sendText).toHaveBeenCalledWith(NODE, '/rewind')
+ })
+ await hook('done')
+ await renderWith(onShowTerminal)
+ await settle(0, { messages: [say(0, 'hello')] })
+ await send('/rewind')
+ expect(onShowTerminal).toHaveBeenCalledOnce()
+ })
+
+ it('a built-in that runs with no dialog (/compact) and a plain message stay in the view', async () => {
+ const onShowTerminal = vi.fn()
+ await hook('done')
+ await renderWith(onShowTerminal)
+ await settle(0, { messages: [say(0, 'hello')] })
+ await send('/compact')
+ await send('please rewind the file')
+ expect(sendText).toHaveBeenCalledTimes(2)
+ expect(onShowTerminal).not.toHaveBeenCalled()
+ })
+
+ it('a refused send (pane not writable) never flips', async () => {
+ const onShowTerminal = vi.fn()
+ sendText.mockResolvedValueOnce(false as never)
+ await hook('done')
+ await renderWith(onShowTerminal)
+ await settle(0, { messages: [say(0, 'hello')] })
+ await send('/model')
+ expect(onShowTerminal).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index b31a7fd29..cbe4247f0 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -24,6 +24,7 @@ import { GROK_AMBIGUOUS_SESSION_MESSAGE, isGrokAmbiguousSessionError } from '@sh
import { Spinner } from '../components/Spinner'
import { CHAT_LIVE_RELOAD_MIN_MS, CHAT_OPTIMISTIC_WORKING_MS, chatActivity, planLiveReload } from '../lib/chatLive'
import { sentCommand } from '@shared/chat-command'
+import { isInteractiveBuiltin } from '@shared/chat-catalog'
import { capabilityAgentId, chatReadsLocalOnly } from '@shared/agents/config'
import { ChatLoadingStatus } from './ChatPanelFallback'
import { answerCardState, answerRebindPending, rebindRetryDelay, type BoundAnswerCard } from '../lib/chatAnswer'
@@ -704,6 +705,14 @@ export function ChatPanel({
setThread((t) => ({ ...t, messages: [...t.messages, { role: 'user', parts: [{ kind: 'text', text }] }] }))
setOptimistic(true)
setInput('')
+ // A built-in that opens a dialog in the TUI (`/rewind`, `/resume`, `/model`, …) is now on screen
+ // THERE, invisible from here, and the state still reads `done`: the next message's Enter would
+ // answer it. Go to the terminal — the same hand-off the toolbar's model/effort labels make.
+ // Only after the send was confirmed (`ok === true` above): nothing opened otherwise.
+ if (onShowTerminal && isInteractiveBuiltin(agentId, text)) {
+ onShowTerminal()
+ return
+ }
// A local command (`/model`, `!ls`) fires no hook: schedule ONE live tail read, one throttle
// interval out (claude writes the command record once the command ran), so its confirmation
// retires the working row instead of the 15 s timeout. A read already in flight defers it.
@@ -719,7 +728,7 @@ export function ChatPanel({
}
commandReadTimerRef.current = setTimeout(fire, CHAT_LIVE_RELOAD_MIN_MS)
}
- }, [api, input, nodeId, agentId])
+ }, [api, input, nodeId, agentId, onShowTerminal])
// The scheduled command read belongs to THIS transcript and this mount.
useEffect(
diff --git a/src/server/index.ts b/src/server/index.ts
index 30261444d..64bbfd6c4 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -524,8 +524,10 @@ export async function startServer(
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()
+ // host whose command and skill folders a node's agent reads. An SSH-project node in this store is
+ // still someone ELSE's machine: named remote here, it answers built-ins + `partial`, never this
+ // server's own ~/.claude.
+ registerChatCatalogIpc({ isRemoteNode: (nodeId) => !!workspaceStore.sshProjectIdForNode(nodeId) })
// 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 received
diff --git a/src/shared/chat-catalog.ts b/src/shared/chat-catalog.ts
index 259516f4f..718731949 100644
--- a/src/shared/chat-catalog.ts
+++ b/src/shared/chat-catalog.ts
@@ -17,6 +17,14 @@ export interface ChatCatalogEntry {
description: string
kind: ChatCatalogKind
scope: ChatCatalogScope
+ /**
+ * A built-in that opens a DIALOG or picker in the agent's TUI (`/model`, `/rewind`, `/resume`, …).
+ * The ⌘M view cannot see that dialog, and the agent state still reads `done` while it is up, so the
+ * next message's Enter would ANSWER it (confirm its highlighted row). After such a command is sent
+ * the panel flips to the terminal (ChatPanel's send), and a composer that cannot flip does not
+ * offer it. Built-ins only; a custom command or skill is a prompt, never a dialog.
+ */
+ interactive?: true
}
export interface ChatCatalog {
@@ -74,7 +82,13 @@ export function sanitizeChatCatalog(raw: unknown): ChatCatalog {
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 })
+ out.push({
+ name,
+ description: catalogDescription(r.description),
+ kind: r.kind as ChatCatalogKind,
+ scope: r.scope as ChatCatalogScope,
+ ...(r.interactive === true ? { interactive: true as const } : {})
+ })
}
return { version: 1, entries: out, ...(rec?.partial === true ? { partial: true } : {}) }
}
@@ -82,23 +96,23 @@ export function sanitizeChatCatalog(raw: unknown): ChatCatalog {
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:
+ * Built-in slash commands per base harness — ONLY what was measured against the installed CLI, by
+ * typing `/` in its interactive TUI inside a private tmux server and paging the whole menu, 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.
*
- * - 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).
+ * - claude 2.1.285, codex 0.156.1, opencode 1.18.25 (fresh session: 17 commands) — 2026-09-30.
+ * - gemini 0.62.0 — 2026-09-30, with a throwaway HOME and a dummy API key (the menu is client-side;
+ * no request was made). Every entry below is in that menu.
+ * - grok: NOT listed. 1.0.44 would not start past its browser sign-in on the measuring host, and a
+ * list copied from docs is a guess about the binary the user runs.
*
- * 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.
+ * Any other agent (grok, 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.
+ *
+ * `SAFE` names the built-ins that run at once with no dialog; every OTHER built-in is treated as
+ * `interactive` (see ChatCatalogEntry). Over-tagging costs a flip to the terminal after the send;
+ * under-tagging lets the next message answer a dialog nobody can see — so unknown means dialog.
*/
const BUILTINS: Readonly<Record<string, readonly Builtin[]>> = Object.freeze({
claude: [
@@ -193,27 +207,6 @@ const BUILTINS: Readonly<Record<string, readonly Builtin[]>> = Object.freeze({
['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'],
@@ -233,12 +226,45 @@ const BUILTINS: Readonly<Record<string, readonly Builtin[]>> = Object.freeze({
]
})
+const SAFE: Readonly<Record<string, ReadonlySet<string>>> = Object.freeze({
+ claude: new Set(['clear', 'compact', 'init', 'recap', 'reload-skills', 'security-review']),
+ codex: new Set(['clear', 'compact', 'init', 'new', 'recap']),
+ gemini: new Set(['clear', 'compress', 'init']),
+ opencode: new Set(['new'])
+})
+
+function baseWithTable(agentId: string | undefined): string | null {
+ if (!agentId) return null
+ const base = capabilityAgentId(agentId)
+ return Object.prototype.hasOwnProperty.call(BUILTINS, base) ? base : null
+}
+
/** 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' }))
+ const base = baseWithTable(agentId)
+ if (!base) return []
+ const safe = SAFE[base]
+ return BUILTINS[base].map(([name, description]) => ({
+ name,
+ description,
+ kind: 'builtin' as const,
+ scope: 'builtin' as const,
+ ...(safe?.has(name) ? {} : { interactive: true as const })
+ }))
+}
+
+/**
+ * Does this SENT text open a dialog in the agent's TUI — a built-in of that agent tagged
+ * `interactive`, typed from the menu or by hand, with or without arguments (a flip after
+ * `/model sonnet` costs nothing; a missed dialog costs the next message)? Case-sensitive like the
+ * CLIs' own lookup.
+ */
+export function isInteractiveBuiltin(agentId: string | undefined, text: string): boolean {
+ const base = baseWithTable(agentId)
+ if (!base) return false
+ const m = /^\/([A-Za-z0-9._:-]+)(?:\s|$)/.exec(text.trim())
+ if (!m) return false
+ return BUILTINS[base].some(([name]) => name === m[1]) && !SAFE[base]?.has(m[1])
}
/** Every agent id with a built-in table (tests walk it). */