A pane and prompt band for plugin commands declared in quick-menu.json, plus plugin and Claude Code settings exposed through /config.

<img src=".claude-plugin/icon.png" alt="agent-quick-menu logo" width="128">
<h1 align="center">agent-quick-menu</h1>
<b>One menu for Claude Code:</b> every plugin's commands and settings, and Claude Code's own,<br> in a pane beside the transcript, a band of favourites above the prompt and a menu button below it.
<a href="LICENSE"><img src="https://img.shields.io/github/license/agentic-workbench/agent-quick-menu" alt="License: MIT"></a> <a href="https://github.com/agentic-workbench/agent-quick-menu/releases"><img src="https://img.shields.io/github/v/release/agentic-workbench/agent-quick-menu" alt="Latest release"></a> <a href="https://github.com/agentic-workbench/agent-quick-menu/actions/workflows/ci.yml"><img src="https://github.com/agentic-workbench/agent-quick-menu/actions/workflows/ci.yml/badge.svg" alt="CI"></a> <a href="https://github.com/karanb192/awesome-claude-code-mods"><img src="https://awesome.re/mentioned-badge.svg" alt="Listed in awesome-claude-code-mods"></a> <a href="https://github.com/karanb192/awesome-claude-code-mods"><img src="https://raw.githubusercontent.com/karanb192/awesome-claude-code-mods/main/badges/agentic-workbench--agent-quick-menu--agent-quick-menu-validates.svg" alt="validates"></a>
<a href="#install">Install</a> · <a href="#usage">Usage</a> · <a href="#for-plugin-authors">For plugin authors</a> · <a href="docs/convention.md">Convention</a> · <a href="#what-this-plugin-does-on-your-machine">What it does on your machine</a>
<img src="docs/screenshot.png" alt="The quick menu pane: foldable sections per plugin with command buttons, their slash commands and descriptions, and Claude Code's own settings with toggles and choices" width="900">
/config settings get one too..claude-plugin/quick-menu.json; no code, no dependency.Claude Code 2.1.287 or newer, in the terminal or the Desktop Code tab, on macOS or Linux. The VS Code chat panel is not supported. Windows paths (USERPROFILE, ; in CLAUDE_CODE_PLUGIN_DIRS) are read, but the menu is untested there.
In a Claude Code session:
/plugin marketplace add agentic-workbench/agent-quick-menu
/plugin install agent-quick-menu@agent-quick-menu
/reload-plugins
Or from a shell:
claude plugin marketplace add agentic-workbench/agent-quick-menu
claude plugin install agent-quick-menu@agent-quick-menu
Then run /reload-plugins in a running session.
/menu opens the pane. /menu refresh discovers plugin menus again.≣ menu ▸ sits at the bottom right of the prompt footer, after the dim mode labels. Click it to toggle: it closes the menu when it is open (▾) and opens it when closed (▸); it has no hotkey, as the footer cannot hold focus. /menu always opens or focuses it. The band above the prompt is one line holding your favourites only, after a dim caption: ★ favourites: Pull Status ….ctrl+x tab focuses the band.☆ / ★ on any row adds or removes a favourite. Favourites are listed first in the pane.▸ / ▾). Favourites start open, every other section folded. Expand all (e) and Collapse all (c) sit on the top line; the state is kept across sessions. The pane closes with Claude Code's own ×, Escape or ctrl+x x. With no favourites yet, the pane says to press ☆ on a row.filter…) matches setting labels, keys and descriptions and command names and labels, case-insensitive, across every section. Sections without a match are hidden, matching ones open while a filter is set, and the counts follow.● (on) or gray ○ (off) with the plain word on / off; a choice opens an inline row of option buttons (● current, ○ other), one editor open at a time; text and number rows show value ✎ and open an Input with ✓ save and ✕ cancel. Cancel is the button: Escape does not cancel the edit (it closes the pane). Commands and settings show a dim italic description after · .ask in its menu entry opens that same editor when pressed, in the pane or from a band favourite (which opens the pane at its row), with the default typed in and ✓ run / ✕ cancel. Enter or ✓ run runs /command <args> <input>; the row hint reads /command <args> …. The confirm-twice of a built-in or another plugin's command applies to ✓ run. See docs/convention.md.Close button, since the engine draws no close mark there) instead.[-] at the end of the band (drawn by Claude Code, or ctrl+x ctrl+a) folds the band..claude-plugin/quick-menu.json: its commands one per line (button, then the /command args hint) and its settings (userConfig) as an aligned label/value table. A setting's description (userConfig description) follows its value dimmed, clipped to the pane width and dropped when under 8 cells remain; the filter matches it too.--plugin-dir whose root is not known (see Limitations): its registered commands, and a dim line saying to set CLAUDE_CODE_PLUGIN_DIRS.userConfig rows.managed) is set by managed policy and cannot be changed here.Slash commands it runs, and when. Only when you press a button or a band favourite, and only the command that row shows: /<command> <args> from a plugin's quick-menu.json. Built-in commands and other plugins' commands need a second press within 5 seconds. When you change a setting row it writes it through $.config.set, as if you changed it in /config; no slash command runs for that. It runs nothing on its own.
What it sets. Only the /config rows you change in the pane. It sets no environment variables. It keeps favourites and folded sections in Claude Code's plugin store.
What it reads. The plugin registry installed_plugins.json under CLAUDE_CONFIG_DIR or ~/.claude, the environment variables CLAUDE_CONFIG_DIR, HOME, USERPROFILE and CLAUDE_CODE_PLUGIN_DIRS, each plugin's .claude-plugin/quick-menu.json, the .claude-plugin/plugin.json of the folders in CLAUDE_CODE_PLUGIN_DIRS, the list of commands Claude Code offers, and the rows /config shows. It sends nothing over the network and reads no credentials.
Its hooks.
ui.render on AbovePrompt: adds its own row of favourites and keeps every other mod's band beneath it.ui.render on SessionMode: draws the footer's mode labels as the engine does, then the menu button.ui.render on its Pane: draws the menu.command.run, matched to /menu only: answers /menu and /menu refresh itself. It never sees, changes or blocks any other command, including the ones it runs for you.plugin.register: reads the name, root and provenance of each plugin as it loads, to find the quick-menu.json of plugins loaded with --plugin-dir. It passes every registration on unchanged and never alters or blocks a plugin, its settings, instructions, hooks or tool descriptions.ui.close: observed only, to redraw the footer's menu button when the pane closes. It passes every close on unchanged.session.start: registers /menu, loads favourites and folds, and starts discovery.Add .claude-plugin/quick-menu.json to your plugin:
{
"$schema": "https://raw.githubusercontent.com/agentic-workbench/agent-quick-menu/main/schema/quick-menu.schema.json",
"version": 1,
"commands": [
{ "command": "my-plugin:status", "label": "Status", "description": "Show the plugin's state" },
{ "command": "my-plugin:deploy", "label": "Deploy to…", "ask": { "placeholder": "environment", "default": "staging" } }
],
"settings": ["verbose"]
}
That's it: commands become buttons, ask prompts for an argument first, and settings lists which of your userConfig fields to show (omit it to show all). Without agent-quick-menu installed the file is never read. The full format, limits and versioning promise are in docs/convention.md.
--plugin-dir plugin's root is only learned when its hooks module loads after this one (plugin.register; kept across a reload of the menu); a plugin without one, or loaded earlier, is listed from $.command.list() with its commands only. Set CLAUDE_CODE_PLUGIN_DIRS to the same folder to read its quick-menu.json. A --plugin-dir copy shadows an installed copy of the same plugin. The menu reads its own file from its own folder.session.start and on /menu refresh (which toasts the counts when it is done), so /menu answers at once./config are not shown here.Releases follow semantic versioning: version in plugin.json is the release, tagged as v<version> and listed in CHANGELOG.md. Claude Code updates an install when that version changes, so installs from main get each release.
make check # JSON check, claude plugin validate + test, and tsc --noEmit (tsc from PATH, else via npx)
claude --plugin-dir . # try the plugin from this checkout
See CONTRIBUTING.md for branches, commits and tests, and the Code of Conduct.
See PRIVACY.md: the plugin collects and sends nothing.
Report vulnerabilities privately, see SECURITY.md.
MIT, see LICENSE.
hooks/quick-menu.tsx 1648 lines1import { atom, read, update } from 'claude-code'
2import type { CommandInfo, ConfigRow, ConfigValue, Elements, EngineInterface, Register, RenderElement, RenderInput, RenderNode } from 'claude-code'
3
4import type { Favourite, MenuAsk, MenuCommand, MenuFile, MenuProblem, MenuSection, Note, RowState, SectionCommand } from '../types'
5
6const PANE_ID = 'quick-menu'
7const MENU_FILE = '.claude-plugin/quick-menu.json'
8const BUILTIN_PREFIX = 'cc-plugin-'
9const ENGINE = 'engine'
10const MENU_COMMAND = 'menu'
11const REFRESH = 'refresh'
12const DISARMED = { id: '', until: 0 }
13
14// Module state: the atoms live in the engine's `$.state` (they outlive a reload), the `let`s and the map in this instance.
15const sections = atom({ plugin: 'agent-quick-menu', key: 'sections' } as const, [] as MenuSection[])
16const problems = atom({ plugin: 'agent-quick-menu', key: 'problems' } as const, [] as MenuProblem[])
17const favourites = atom({ plugin: 'agent-quick-menu', key: 'favourites' } as const, [] as Favourite[])
18const folded = atom({ plugin: 'agent-quick-menu', key: 'folded' } as const, {} as Record<string, boolean>)
19const unplaced = atom({ plugin: 'agent-quick-menu', key: 'unplaced' } as const, false)
20const filter = atom({ plugin: 'agent-quick-menu', key: 'filter' } as const, '')
21/** The element key of the one choice or text row being edited; '' when none. */
22const openEditor = atom({ plugin: 'agent-quick-menu', key: 'openEditor' } as const, '')
23/** The text in the open text editor, as last typed. */
24const editDraft = atom({ plugin: 'agent-quick-menu', key: 'editDraft' } as const, '')
25const rowState = atom({ plugin: 'agent-quick-menu', key: 'rowState' } as const, {
26 queued: {},
27 notes: {},
28 armed: DISARMED,
29 written: {},
30} as RowState)
31const inlineRootState = atom({ plugin: 'agent-quick-menu', key: 'inlineRoots' } as const, {} as Record<string, string>)
32
33let sessionCwd = ''
34let sessionStarted = false
35let discoveryRun = 0
36/**
37 * Roots of `--plugin-dir` plugins, learned from `plugin.register` (the only place the types hand out another plugin's `root`).
38 * `plugin.register` fires once per load of the other plugin, never again when this module reloads, so the roots are kept in
39 * `$.state` (which outlives a reload) as well as here (which outlives a new session in the same process).
40 */
41const inlineRoots = new Map<string, string>()
42
43/** Cells a button takes beyond its label (`[ ` and ` ]`), and the gap that follows it. */
44const BUTTON_CHROME = 4
45const BUTTON_GAP = 2
46/** A star and the space after it; the ` · ` before a description; the least room a description is worth drawing in. */
47const STAR_CELLS = 2
48const SEP_CELLS = 3
49const MIN_HELP_CELLS = 8
50/** The indent of a section's rows under its title. */
51const BODY_INDENT = 2
52/** The band: the room the engine keeps for its `[-]`, and the dim caption before the favourites. */
53const BAND_RESERVE = 6
54const BAND_CAPTION = '★ favourites:'
55const MAX_RUNS_HINT = 60
56const MAX_TOAST = 200
57const MAX_PROBLEM_PLUGIN = 100
58const MAX_VERSION_TEXT = 20
59const PANE_COLUMNS = 100
60
61/** Limits on a menu file (a plugin's text, so untrusted); the schema mirrors them. */
62const MAX_FILE_BYTES = 64 * 1024
63const MAX_COMMANDS = 50
64const MAX_SETTINGS = 50
65const MAX_FAVOURITES = 50
66const MAX_SHOWN_COMMANDS = 30
67const MAX_PROBLEM = 300
68const CONFIRM_MS = 5000
69const LIMITS = { title: 60, label: 40, command: 64, args: 500, description: 200, setting: 64, askPlaceholder: 60, askDefault: 500, input: 500 } as const
70/** Control, line, bidi and zero-width characters: never shown, never accepted. */
71const BAD_CHARS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Co}\u{FE00}-\u{FE0F}\u{E0100}-\u{E01EF}]/u
72const BAD_CHARS_ALL = new RegExp(BAD_CHARS.source, 'gu')
73const RESERVED_TITLES = ['claude code', 'favourites', 'built-in']
74
75/** Text from outside, safe to show: bad characters replaced, cut to `max`. */
76const clean = (text: string, max = MAX_PROBLEM): string => text.replace(BAD_CHARS_ALL, '?').slice(0, max)
77
78/** Display width of a label in cells: code points, not UTF-16 units. */
79function width(text: string): number {
80 return [...text].length
81}
82
83/** Cut to `max` characters, ending in an ellipsis. */
84const clip = (text: string, max: number): string => (text.length > max ? `${text.slice(0, max - 1)}…` : text)
85
86const pad = (text: string, to: number): string => text + ' '.repeat(Math.max(0, to - width(text)))
87
88/** A path the engine's registry or the environment names must be absolute. */
89const isAbsolutePath = (p: string): boolean => p.startsWith('/') || /^[A-Za-z]:[\\/]/.test(p)
90
91type Validation = { ok: true; value: MenuFile } | { ok: false; error: string }
92
93const isObject = (v: unknown): v is Record<string, unknown> =>
94 typeof v === 'object' && v !== null && !Array.isArray(v)
95
96/** Why `value` is not an acceptable menu string, or null. A lone `title`, `label` or `command` must hold more than blanks. */
97function textError(where: string, value: unknown, max: number, nonBlank = false): string | null {
98 if (typeof value !== 'string') return `${where} must be a ${nonBlank ? 'non-empty ' : ''}string`
99 if (nonBlank && value.trim() === '') return `${where} must be a non-empty string`
100 if (BAD_CHARS.test(value)) return `${where} holds a control, line-break, bidi or zero-width character`
101 if ([...value].length > max) return `${where} is longer than ${max} characters`
102 return null
103}
104
105function validateAsk(where: string, ask: unknown): { ok: true; value: MenuAsk } | { ok: false; error: string } {
106 if (!isObject(ask)) return { ok: false, error: `${where} must be an object` }
107 const value: MenuAsk = {}
108 for (const [key, max] of [['placeholder', LIMITS.askPlaceholder], ['default', LIMITS.askDefault]] as const) {
109 const field = ask[key]
110 if (field === undefined) continue
111 const error = textError(`${where}.${key}`, field, max)
112 if (error) return { ok: false, error }
113 value[key] = field as string
114 }
115 return { ok: true, value }
116}
117
118function validateCommand(c: unknown, i: number): { ok: true; value: MenuCommand } | { ok: false; error: string } {
119 if (!isObject(c)) return { ok: false, error: `commands[${i}] must be an object` }
120 const bad = textError(`commands[${i}].command`, c.command, LIMITS.command, true)
121 if (bad) return { ok: false, error: bad }
122 const value: MenuCommand = { command: c.command as string }
123 for (const key of ['label', 'args', 'description'] as const) {
124 const field = c[key]
125 if (field === undefined) continue
126 const error = textError(`commands[${i}].${key}`, field, LIMITS[key], key === 'label')
127 if (error) return { ok: false, error }
128 value[key] = field as string
129 }
130 if (c.ask !== undefined) {
131 const asked = validateAsk(`commands[${i}].ask`, c.ask)
132 if (!asked.ok) return asked
133 value.ask = asked.value
134 }
135 return { ok: true, value }
136}
137
138/** Validates a menu file; `reserved` are the lower-cased names a title may not take (other plugins'). */
139export function validateMenuFile(json: unknown, reserved: readonly string[] = []): Validation {
140 if (!isObject(json)) return { ok: false, error: 'menu file must be a JSON object' }
141 if (json.version !== 1) {
142 return { ok: false, error: `unsupported version ${clean(String(JSON.stringify(json.version)), MAX_VERSION_TEXT)} (expected 1)` }
143 }
144 if (json.title !== undefined) {
145 const bad = textError('title', json.title, LIMITS.title, true)
146 if (bad) return { ok: false, error: bad }
147 if ([...RESERVED_TITLES, ...reserved].includes((json.title as string).trim().toLowerCase())) {
148 return { ok: false, error: 'title is reserved (Claude Code, Favourites, built-in or another plugin)' }
149 }
150 }
151 let commands: MenuCommand[] = []
152 if (json.commands !== undefined) {
153 if (!Array.isArray(json.commands)) return { ok: false, error: 'commands must be an array' }
154 if (json.commands.length > MAX_COMMANDS) return { ok: false, error: `commands has more than ${MAX_COMMANDS} entries` }
155 commands = []
156 for (const [i, c] of json.commands.entries()) {
157 const r = validateCommand(c, i)
158 if (!r.ok) return r
159 commands.push(r.value)
160 }
161 }
162 let settings: string[] | null = null
163 if (json.settings !== undefined) {
164 if (!Array.isArray(json.settings)) return { ok: false, error: 'settings must be an array of non-empty strings' }
165 if (json.settings.length > MAX_SETTINGS) return { ok: false, error: `settings has more than ${MAX_SETTINGS} entries` }
166 for (const [i, name] of json.settings.entries()) {
167 const bad = name === '' ? `settings[${i}] must be a non-empty string` : textError(`settings[${i}]`, name, LIMITS.setting)
168 if (bad) return { ok: false, error: bad }
169 }
170 settings = [...(json.settings as string[])]
171 }
172 return { ok: true, value: { version: 1, title: json.title as string | undefined, commands, settings } }
173}
174
175const message = (err: unknown): string => (err instanceof Error ? err.message : String(err))
176
177const decodeText = (raw: string | Uint8Array): string => (typeof raw === 'string' ? raw : new TextDecoder().decode(raw))
178
179async function readJson($: EngineInterface, path: string): Promise<unknown> {
180 return JSON.parse(decodeText(await $.fs.read(path)))
181}
182
183type Target = { name: string; root: string }
184
185/** The plugin name without its `@<marketplace>` suffix. */
186const bareName = (id: string): string => id.split('@')[0] ?? id
187
188const PLUGIN_DIR_NOTE = 'loaded with --plugin-dir: set CLAUDE_CODE_PLUGIN_DIRS to read its quick-menu.json'
189
190/** Plugins whose commands are not claimed by a built-in prefix or the engine. */
191const isForeign = (name: string): boolean => name !== ENGINE && !name.startsWith(BUILTIN_PREFIX)
192
193/** The install entry for this session: a project or local one for the cwd, else the user one (no other scope applies here). */
194function chooseEntry(entries: unknown): Record<string, unknown> | undefined {
195 if (!Array.isArray(entries)) return undefined
196 const objects = entries.filter(isObject)
197 const here = objects.find(
198 x => (x.scope === 'project' || x.scope === 'local') && sessionCwd !== '' && x.projectPath === sessionCwd,
199 )
200 return here ?? objects.find(x => x.scope === 'user')
201}
202
203/** The bare names of the plugins that are loaded: those with a registered command or a `userConfig` row (engine rows excluded). */
204async function loadedPlugins($: EngineInterface, listed: readonly CommandInfo[], issues: MenuProblem[]): Promise<Set<string>> {
205 const names = new Set<string>()
206 for (const c of listed) if (c.source === 'plugin' && c.plugin) names.add(bareName(c.plugin))
207 try {
208 for (const row of await $.config.list()) {
209 if (row.provider.plugin !== ENGINE) names.add(bareName(row.key.split('.')[0] ?? row.key))
210 }
211 } catch (err) {
212 issues.push({ plugin: 'config', message: `cannot list config rows: ${message(err)}` })
213 }
214 return names
215}
216
217async function registryTargets(
218 $: EngineInterface,
219 listed: readonly CommandInfo[],
220 issues: MenuProblem[],
221): Promise<Target[]> {
222 const loaded = await loadedPlugins($, listed, issues)
223 if (loaded.size === 0) return []
224 const configDir = await $.env.get('CLAUDE_CONFIG_DIR')
225 let base: string
226 if (configDir) {
227 if (!isAbsolutePath(configDir)) {
228 issues.push({ plugin: 'CLAUDE_CONFIG_DIR', message: 'must be an absolute path; plugin registry skipped' })
229 return []
230 }
231 base = configDir
232 } else {
233 const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'))
234 if (!home || !isAbsolutePath(home)) return []
235 base = `${home.replace(/[\\/]+$/, '')}/.claude`
236 }
237 const registryPath = `${base}/plugins/installed_plugins.json`
238 let plugins: Record<string, unknown> = {}
239 try {
240 const json = await readJson($, registryPath)
241 if (isObject(json) && isObject(json.plugins)) plugins = json.plugins
242 } catch (err) {
243 issues.push({ plugin: 'installed_plugins.json', message: `cannot read ${registryPath}: ${message(err)}` })
244 return []
245 }
246 const targets: Target[] = []
247 // Several marketplaces can ship one bare name: the entry installed for this project or local scope wins, else the first user one.
248 const chosen = new Map<string, { id: string; entry: Record<string, unknown>; isHere: boolean }>()
249 for (const id of Object.keys(plugins)) {
250 const name = bareName(id)
251 const entry = chooseEntry(plugins[id])
252 if (!loaded.has(name) || !entry) continue
253 const isHere = entry.scope !== 'user'
254 const held = chosen.get(name)
255 if (!held || (isHere && !held.isHere)) chosen.set(name, { id, entry, isHere })
256 }
257 for (const { id, entry } of chosen.values()) {
258 if (typeof entry.installPath !== 'string') continue
259 if (!isAbsolutePath(entry.installPath)) {
260 issues.push({ plugin: bareName(id), message: 'installPath is not absolute; skipped' })
261 continue
262 }
263 targets.push({ name: bareName(id), root: entry.installPath })
264 }
265 return targets
266}
267
268/** `--plugin-dir` folders: `CLAUDE_CODE_PLUGIN_DIRS`, then the roots `plugin.register` handed out. */
269async function dirTargets($: EngineInterface, issues: MenuProblem[]): Promise<Target[]> {
270 const raw = await $.env.get('CLAUDE_CODE_PLUGIN_DIRS')
271 const targets: Target[] = []
272 // `;` separates the folders where a drive letter holds a colon (Windows), `:` elsewhere.
273 const separator = /^[A-Za-z]:[\\/]/.test(raw ?? '') || (raw ?? '').includes(';') ? ';' : ':'
274 for (const root of (raw ?? '').split(separator).filter(Boolean)) {
275 try {
276 if (!isAbsolutePath(root)) throw new Error('not an absolute path')
277 const manifest = await readJson($, `${root}/.claude-plugin/plugin.json`)
278 const name = isObject(manifest) ? manifest.name : undefined
279 if (typeof name !== 'string' || name === '') throw new Error('plugin.json has no name')
280 targets.push({ name, root })
281 } catch (err) {
282 issues.push({ plugin: root, message: `cannot identify plugin dir: ${message(err)}` })
283 }
284 }
285 let kept: Record<string, string> = {}
286 try {
287 kept = await read($, inlineRootState)
288 } catch {
289 // The kept roots are a convenience: without them only the in-process ones count.
290 }
291 for (const [name, root] of [...inlineRoots, ...Object.entries(kept)]) if (isAbsolutePath(root)) targets.push({ name, root })
292 return targets
293}
294
295async function readMenuFile(
296 $: EngineInterface,
297 target: Target,
298 issues: MenuProblem[],
299 reserved: readonly string[],
300): Promise<MenuFile | null> {
301 const path = `${target.root}/${MENU_FILE}`
302 const problem = (text: string): null => (issues.push({ plugin: target.name, message: `${path}: ${text}` }), null)
303 try {
304 if (!(await $.fs.exists(path))) return null
305 const stat = await $.fs.stat(path)
306 if (stat.kind !== 'file' || stat.isLink) return problem('must be a regular file, not a link')
307 if (stat.size > MAX_FILE_BYTES) return problem(`larger than ${MAX_FILE_BYTES / 1024} KiB`)
308 const text = decodeText(await $.fs.read(path))
309 if (text.length > MAX_FILE_BYTES) return problem(`larger than ${MAX_FILE_BYTES / 1024} KiB`)
310 let json: unknown
311 try {
312 json = JSON.parse(text)
313 } catch {
314 return problem('not valid JSON')
315 }
316 const result = validateMenuFile(json, reserved)
317 return result.ok ? result.value : problem(result.error)
318 } catch (err) {
319 return problem(message(err))
320 }
321}
322
323/** The file's title, with the plugin's name after it unless that is the title already. */
324function sectionTitle(title: string | undefined, name: string): string {
325 if (title === undefined) return name
326 return title.toLowerCase() === name.toLowerCase() ? title : `${title} · ${name}`
327}
328
329/** Plugins the registry and the known roots do not explain (a `--plugin-dir` one): their registered commands, no menu file. */
330function commandSections(listed: readonly CommandInfo[], targets: readonly Target[]): MenuSection[] {
331 const known = new Set(targets.map(t => t.name))
332 const byPlugin = new Map<string, SectionCommand[]>()
333 for (const c of listed) {
334 if (c.source !== 'plugin' || !c.plugin) continue
335 const name = bareName(c.plugin)
336 if (known.has(name) || !isForeign(name)) continue
337 const list = byPlugin.get(name) ?? []
338 list.push({
339 command: c.name,
340 label: c.name,
341 ...(c.description !== '' && { description: c.description }),
342 isAvailable: true,
343 source: c.source,
344 owner: name,
345 })
346 byPlugin.set(name, list)
347 }
348 return [...byPlugin].map(([plugin, commands]) => ({
349 plugin,
350 title: plugin,
351 commands,
352 settings: null,
353 source: 'commands' as const,
354 note: PLUGIN_DIR_NOTE,
355 }))
356}
357
358/** What a listed command (or its absence) says about a menu command. */
359function availability(info: CommandInfo | undefined): Pick<SectionCommand, 'isAvailable' | 'source' | 'owner'> {
360 if (!info) return { isAvailable: false }
361 return { isAvailable: true, source: info.source, ...(info.plugin !== undefined && { owner: bareName(info.plugin) }) }
362}
363
364/** The file sections' commands marked against `listed`; the sections of commands the engine itself lists stay. */
365function applyListing(fileSections: readonly MenuSection[], listed: readonly CommandInfo[]): MenuSection[] {
366 const byName = new Map(listed.map(c => [c.name, c]))
367 return fileSections.map(section =>
368 section.source !== 'file'
369 ? section
370 : {
371 ...section,
372 commands: section.commands.map(({ source: _s, owner: _o, ...c }) => ({ ...c, ...availability(byName.get(c.command)) })),
373 },
374 )
375}
376
377/**
378 * Lists the commands afresh and marks every section against that, so a command registered after discovery (plugins
379 * register one after another in their session.start) shows as available. Null when the engine cannot list them.
380 */
381async function refreshListing($: EngineInterface): Promise<CommandInfo[] | null> {
382 let listed: CommandInfo[]
383 try {
384 listed = await $.command.list()
385 } catch {
386 return null
387 }
388 await update($, sections, s => applyListing(s, listed))
389 return listed
390}
391
392/**
393 * Reads every enabled plugin's menu file and builds the file sections; failures become problems.
394 * The first root per name wins: this plugin's own (`$.plugin.root`, which `plugin.register` never hands it), then the
395 * `--plugin-dir` folders, then the installed copies they shadow.
396 */
397async function discover($: EngineInterface): Promise<{ sections: MenuSection[]; problems: MenuProblem[] }> {
398 const issues: MenuProblem[] = []
399 let listed: CommandInfo[] = []
400 try {
401 listed = await $.command.list()
402 } catch (err) {
403 issues.push({ plugin: 'commands', message: `cannot list commands: ${message(err)}` })
404 }
405 const all = [
406 { name: $.plugin.name, root: $.plugin.root },
407 ...(await dirTargets($, issues)),
408 ...(await registryTargets($, listed, issues)),
409 ]
410 const targets = all.filter((t, i) => all.findIndex(o => o.name === t.name) === i)
411
412 const byName = new Map(listed.map(c => [c.name, c]))
413 const result: MenuSection[] = []
414 for (const target of targets) {
415 const reserved = targets.filter(t => t.name !== target.name).map(t => bareName(t.name).toLowerCase())
416 const file = await readMenuFile($, target, issues, reserved)
417 if (file) {
418 result.push({
419 plugin: target.name,
420 title: sectionTitle(file.title, target.name),
421 commands: file.commands.map(c => ({
422 command: c.command,
423 label: c.label ?? c.command,
424 ...(c.args !== undefined && { args: c.args }),
425 ...(c.description !== undefined && { description: c.description }),
426 ...(c.ask !== undefined && { ask: c.ask }),
427 ...availability(byName.get(c.command)),
428 })),
429 settings: file.settings,
430 source: 'file',
431 })
432 }
433 }
434 result.push(...commandSections(listed, targets))
435 result.sort((a, b) => a.title.localeCompare(b.title))
436 return { sections: result, problems: issues.map(p => ({ plugin: clean(p.plugin, MAX_PROBLEM_PLUGIN), message: clean(p.message) })) }
437}
438
439/** Discovers and stores the sections; a run overtaken by a later one leaves the later one's answer standing. */
440async function runDiscovery($: EngineInterface): Promise<{ sections: number; problems: number } | null> {
441 const run = ++discoveryRun
442 const discovered = await discover($)
443 if (run !== discoveryRun) return null
444 await update($, sections, () => discovered.sections)
445 await update($, problems, () => discovered.problems)
446 // The listing discovery took may predate a registration still under way; mark against a fresh one.
447 await refreshListing($)
448 $.ui.invalidate('ui.render')
449 return { sections: discovered.sections.length, problems: discovered.problems.length }
450}
451
452/** Starts a discovery without holding the dispatch that asked for it; `announce` toasts its counts, failures always toast. */
453function startDiscovery($: EngineInterface, announce = false): void {
454 void runDiscovery($).then(
455 counts => {
456 if (counts && announce) $.ui.toast(`Quick menu refreshed: ${counts.sections} sections, ${counts.problems} problems`)
457 },
458 err => $.ui.toast(toastLine(`Quick menu: discovery failed: ${message(err)}`)),
459 )
460}
461
462/** `/menu`: opens the pane, or starts a refresh, and answers at once; discovery runs on its own and redraws when it lands. */
463async function openMenu($: EngineInterface, args: string): Promise<{ text: string }> {
464 if (args.trim() === REFRESH) {
465 startDiscovery($, true)
466 return { text: 'Quick menu: discovering plugin menus again' }
467 }
468 // A load without a session.start (an update or enable mid-session) has not discovered yet: the pane would list no commands.
469 if (discoveryRun === 0) startDiscovery($)
470 await openPane($)
471 return { text: 'Quick menu opened' }
472}
473
474/** Commands this plugin registers; the menu answers them itself (runAny). */
475const OWN_COMMANDS = new Set([MENU_COMMAND])
476
477/**
478 * Runs a command a row or the band names. This plugin's own are answered here: the engine leaves a plugin's own hooks
479 * out of the `command.run` its own `$.command.run` raises (re-entry), so that call would reach the engine's
480 * "registered /menu but no command.run hook answered it".
481 */
482async function runAny($: EngineInterface, c: SectionCommand): Promise<{ text?: string }> {
483 if (OWN_COMMANDS.has(c.command)) {
484 const answer = await openMenu($, c.args ?? '')
485 // A refresh toasts its counts when discovery lands; a toast now would push that one out (toasts are spaced 2 s).
486 return (c.args ?? '').trim() === REFRESH ? {} : answer
487 }
488 return $.command.run({ command: c.command, ...(c.args !== undefined && { args: c.args }) })
489}
490
491const commandKey = (plugin: string, c: SectionCommand): string => `cmd:${plugin}:${c.command}:${c.args ?? ''}`
492const settingKey = (key: string): string => `set:${key}`
493
494const toastLine = (text: string): string => (text.split('\n')[0] ?? '').slice(0, MAX_TOAST)
495
496async function setNote($: EngineInterface, id: string, note: Note | null): Promise<void> {
497 await update($, rowState, s => {
498 const notes = { ...s.notes }
499 if (note) notes[id] = note
500 else delete notes[id]
501 return { ...s, notes }
502 })
503}
504
505async function setQueued($: EngineInterface, id: string, isQueued: boolean): Promise<void> {
506 await update($, rowState, s => {
507 const queued = { ...s.queued }
508 if (isQueued) queued[id] = true
509 else delete queued[id]
510 return { ...s, queued }
511 })
512}
513
514/** Who a command belongs to, when that is not the section's own plugin: the tag shown beside it and the reason to confirm. */
515function runsTag(plugin: string, c: SectionCommand): string | null {
516 if (!c.isAvailable) return null
517 if (c.source === 'plugin' && c.owner !== undefined && c.owner === bareName(plugin)) return null
518 if (c.source === 'builtin') return 'runs a built-in'
519 if (c.source === 'plugin' && c.owner !== undefined) return `runs ${c.owner}`
520 if (c.source === 'user') return 'runs a user command'
521 if (c.source === 'mcp') return 'runs an MCP command'
522 return 'runs a command of unknown origin'
523}
524
525/** Ends an arming that nobody confirmed in time; a newer arming stands. */
526async function disarm($: EngineInterface, id: string, until: number): Promise<void> {
527 await update($, rowState, st => (st.armed.id === id && st.armed.until === until ? { ...st, armed: DISARMED } : st))
528 $.ui.invalidate('ui.render')
529}
530
531/** Waits out the confirm window, then ends that arming. */
532async function expireArming($: EngineInterface, id: string, until: number): Promise<void> {
533 try {
534 await $.clock.sleep(CONFIRM_MS)
535 await disarm($, id, until)
536 } catch {
537 // The module was unloaded or the session ended while waiting: nothing is left to disarm.
538 }
539}
540
541/** Where a command button sits: the key prefix of its rows, whether a band press, and whether the surface can draw an Input. */
542type PressSite = { prefix: string; fromBand: boolean; canAsk: boolean }
543const PANE_SITE: PressSite = { prefix: '', fromBand: false, canAsk: true }
544
545/**
546 * The confirm-twice of a command of another plugin or a built-in: the first call arms (the button reads "press again: /x") and
547 * answers false; a second within 5 s answers true. True at once for a command of the section's own plugin.
548 */
549async function isConfirmed($: EngineInterface, plugin: string, c: SectionCommand): Promise<boolean> {
550 if (runsTag(plugin, c) === null) return true
551 const id = commandKey(plugin, c)
552 const now = await $.clock.now()
553 const armed = (await read($, rowState)).armed
554 if (armed.id !== id || now >= armed.until) {
555 const until = now + CONFIRM_MS
556 await update($, rowState, st => ({ ...st, armed: { id, until } }))
557 void expireArming($, id, until)
558 $.ui.invalidate('ui.render')
559 return false
560 }
561 await update($, rowState, st => ({ ...st, armed: DISARMED }))
562 return true
563}
564
565/**
566 * A press on a button. A command of another plugin or a built-in first arms (the button reads "press again: /x") and runs
567 * on a second press within 5 s, in the pane or the band alike. A command with `ask` opens its row editor instead; the
568 * confirming press is then the one on `✓ run`.
569 */
570async function pressCommand($: EngineInterface, plugin: string, shown: SectionCommand, site: PressSite = PANE_SITE): Promise<void> {
571 let c = shown
572 if (!c.isAvailable) {
573 // Marked unavailable by a listing that may predate its registration: ask again before refusing.
574 const listed = await refreshListing($)
575 const info = listed?.find(x => x.name === c.command)
576 if (!info) {
577 $.ui.toast(toastLine(`Quick menu: /${c.command} is not available`))
578 $.ui.invalidate('ui.render')
579 return
580 }
581 c = { ...c, ...availability(info) }
582 $.ui.invalidate('ui.render')
583 }
584 if (c.ask && site.canAsk) {
585 await openAsk($, plugin, c, site)
586 return
587 }
588 if (await isConfirmed($, plugin, c)) await runCommand($, plugin, c)
589}
590
591/** The fixed args, then what was typed, as one trimmed string; undefined when both are empty. */
592function joinArgs(fixed: string | undefined, input: string): string | undefined {
593 const joined = `${(fixed ?? '').trim()} ${input.trim()}`.trim()
594 return joined === '' ? undefined : joined
595}
596
597/**
598 * Opens the editor of a command with `ask`, its default typed in. From the band the pane opens first, with the pinned list
599 * unfolded, since a band row has no room for an input.
600 */
601async function openAsk($: EngineInterface, plugin: string, c: SectionCommand, site: PressSite): Promise<void> {
602 const id = site.prefix + commandKey(plugin, c)
603 if (site.fromBand) {
604 await openPane($)
605 const stored = await storedValue($, FOLDS)
606 if (isFolded(stored, FAV_ID)) await writeFolds($, { ...stored, [FAV_ID]: false })
607 }
608 await setNote($, commandKey(plugin, c), null)
609 await update($, rowState, st => ({ ...st, armed: DISARMED }))
610 await setOpenEditor($, id, c.ask?.default ?? '', id)
611}
612
613/**
614 * `✓ run` or Enter in an ask editor: invalid input says so and stays open; otherwise the confirm-twice of a foreign command
615 * (the editor stays open for the second press), then the editor closes and `/command <args> <input>` runs.
616 */
617async function runAsked($: EngineInterface, plugin: string, c: SectionCommand, raw: string): Promise<void> {
618 const rid = commandKey(plugin, c)
619 const bad = textError('input', raw, LIMITS.input)
620 if (bad) {
621 await setNote($, rid, { kind: 'error', text: bad, shown: '' })
622 await setDraft($, raw)
623 $.ui.invalidate('ui.render')
624 return
625 }
626 await setNote($, rid, null)
627 if (!(await isConfirmed($, plugin, c))) return
628 await putEditor($, '')
629 const args = joinArgs(c.args, raw)
630 const { args: _fixed, ...bare } = c
631 await runCommand($, plugin, args === undefined ? bare : { ...bare, args }, rid)
632}
633
634/** `✕ cancel` in an ask editor: closes it, runs nothing. */
635async function cancelAsk($: EngineInterface, plugin: string, c: SectionCommand): Promise<void> {
636 await setNote($, commandKey(plugin, c), null)
637 await update($, rowState, st => ({ ...st, armed: DISARMED }))
638 await setOpenEditor($, '')
639}
640
641async function runCommand($: EngineInterface, plugin: string, c: SectionCommand, id = commandKey(plugin, c)): Promise<void> {
642 let claimed = false
643 await update($, rowState, s => {
644 claimed = false
645 if (s.queued[id]) return s
646 claimed = true
647 return { ...s, queued: { ...s.queued, [id]: true as const } }
648 })
649 if (!claimed) return
650 $.ui.invalidate('ui.render')
651 try {
652 const result = await runAny($, c)
653 if (result.text) $.ui.toast(toastLine(result.text))
654 } catch (err) {
655 $.ui.toast(toastLine(message(err)))
656 } finally {
657 await setQueued($, id, false)
658 $.ui.invalidate('ui.render')
659 }
660}
661
662/** A value as the row shows it and as two values compare: bare text, a list comma-joined. */
663const configArg = (value: ConfigValue): string => (typeof value === 'object' ? value.join(',') : String(value))
664
665/**
666 * Writes one row through `$.config.set`, as the person would in `/config`: `{ deny }` is a refusal (a hook, a lock, a value
667 * that does not fit), shown beside the row; `{ value }` is a write, as asked or as a `config.set` hook clamped it, remembered
668 * so the next draw shows it even when the engine's own row (the editor mode, the output style) still reads the old value.
669 */
670async function writeSetting($: EngineInterface, row: ConfigRow, value: ConfigValue): Promise<void> {
671 const id = settingKey(row.key)
672 const before = configArg(row.value)
673 await setNote($, id, null)
674 try {
675 const result = await $.config.set({ key: row.key, value })
676 if (result.deny !== undefined) await setNote($, id, { kind: 'deny', text: result.deny || 'not changed', shown: before })
677 else await remember($, id, { value: result.value, was: before })
678 } catch (err) {
679 await setNote($, id, { kind: 'error', text: message(err), shown: before })
680 }
681 $.ui.invalidate('ui.render')
682}
683
684async function remember($: EngineInterface, id: string, write: RowState['written'][string]): Promise<void> {
685 await update($, rowState, s => ({ ...s, written: { ...s.written, [id]: write } }))
686}
687
688/** `row` with the value it was just written to while `$.config.list()` still reads the one before. */
689function withWrite(row: ConfigRow, state: RowState): ConfigRow {
690 const w = state.written[settingKey(row.key)]
691 return w && configArg(row.value) === w.was ? { ...row, value: w.value } : row
692}
693
694/** Sets the open editor and its draft without drawing: the caller draws once, after what it does next. */
695async function putEditor($: EngineInterface, id: string, draft = ''): Promise<void> {
696 await update($, openEditor, () => id)
697 await update($, editDraft, () => draft)
698}
699
700/**
701 * Opens the editor of row `id` (with `draft` in a text one), or closes every one with ''; draws. `focusKey`: the element that
702 * takes the focus ring once drawn (the pressed button keeps it otherwise, and `autoFocus` does not move a ring the press set).
703 */
704async function setOpenEditor($: EngineInterface, id: string, draft = '', focusKey = ''): Promise<void> {
705 await putEditor($, id, draft)
706 $.ui.invalidate('ui.render')
707 // Best effort: a test engine with no site holding the keys has nothing behind `ui.focus` and rejects.
708 if (id && focusKey) await $.ui.focus({ requestId: PANE_ID, key: focusKey }).catch(() => ({}))
709}
710
711/** Keeps what the person typed, so the save button knows it; the field already shows it, so no redraw. */
712async function setDraft($: EngineInterface, text: string): Promise<void> {
713 await update($, editDraft, () => text)
714}
715
716/** A pick of another option in an open choice row: folds the row back to `value ▾`, then writes the value (and draws). */
717async function pickChoice($: EngineInterface, row: ConfigRow, value: string): Promise<void> {
718 await putEditor($, '')
719 await writeSetting($, row, value)
720}
721
722/**
723 * Saves a text or number editor: an unchanged value just closes it, an invalid number says so and stays open, anything else
724 * closes it and writes once.
725 */
726async function saveEdit($: EngineInterface, row: ConfigRow, raw: string): Promise<void> {
727 let value: ConfigValue = raw
728 if (row.kind === 'number') {
729 const n = Number(raw)
730 if (raw.trim() === '' || !Number.isFinite(n)) {
731 await setNote($, settingKey(row.key), { kind: 'error', text: `"${raw}" is not a number`, shown: configArg(row.value) })
732 await setDraft($, raw)
733 $.ui.invalidate('ui.render')
734 return
735 }
736 value = n
737 }
738 if (configArg(value) === configArg(row.value)) {
739 await setOpenEditor($, '')
740 return
741 }
742 await putEditor($, '')
743 await writeSetting($, row, value)
744}
745
746/** The save button: saves what was last typed. */
747async function saveDraft($: EngineInterface, row: ConfigRow): Promise<void> {
748 await saveEdit($, row, await read($, editDraft))
749}
750
751/** The `✓ run` button: runs what was last typed. */
752async function runAskedDraft($: EngineInterface, plugin: string, c: SectionCommand): Promise<void> {
753 await runAsked($, plugin, c, await read($, editDraft))
754}
755
756/** The cancel button: closes the editor without a write, and drops the note an invalid number left. */
757async function cancelEdit($: EngineInterface, row: ConfigRow): Promise<void> {
758 await setNote($, settingKey(row.key), null)
759 await setOpenEditor($, '')
760}
761
762type Ui = ReturnType<EngineInterface['ui']['resolve']>
763
764const favCommandKey = (c: SectionCommand): string => (c.args ? `${c.command} ${c.args}` : c.command)
765const sameFav = (a: Favourite, b: Favourite): boolean =>
766 a.kind === b.kind && a.plugin === b.plugin && a.key === b.key
767
768function isFavourite(list: readonly Favourite[], f: Favourite): boolean {
769 return list.some(x => sameFav(x, f))
770}
771
772function isFavourites(v: unknown): v is Favourite[] {
773 return (
774 Array.isArray(v) &&
775 v.every(
776 x =>
777 isObject(x) &&
778 (x.kind === 'command' || x.kind === 'setting') &&
779 typeof x.plugin === 'string' &&
780 typeof x.key === 'string',
781 )
782 )
783}
784
785function isFolds(v: unknown): v is Record<string, boolean> {
786 return isObject(v) && Object.values(v).every(x => typeof x === 'boolean')
787}
788
789/** A value kept in `$.store` under `key`; a stored value `guard` refuses reads as `fallback`. */
790type Stored<T> = { key: string; guard: (v: unknown) => v is T; fallback: T; clamp: (v: T) => T }
791
792const FAVOURITES: Stored<Favourite[]> = {
793 key: 'favourites',
794 guard: isFavourites,
795 fallback: [],
796 clamp: list => list.slice(0, MAX_FAVOURITES),
797}
798const FOLDS: Stored<Record<string, boolean>> = { key: 'folded', guard: isFolds, fallback: {}, clamp: v => v }
799
800async function storedValue<T>($: EngineInterface, s: Stored<T>): Promise<T> {
801 try {
802 const stored: unknown = await $.store.get(s.key)
803 return s.guard(stored) ? s.clamp(stored) : s.fallback
804 } catch {
805 return s.fallback
806 }
807}
808
809async function loadFavourites($: EngineInterface): Promise<void> {
810 const stored = await storedValue($, FAVOURITES)
811 await update($, favourites, () => stored)
812}
813
814async function loadFolds($: EngineInterface): Promise<void> {
815 const stored = await storedValue($, FOLDS)
816 await update($, folded, () => stored)
817}
818
819/** Writes `$.store`; a failure toasts and answers false. */
820async function saveStore($: EngineInterface, key: string, value: unknown): Promise<boolean> {
821 try {
822 await $.store.set(key, value)
823 return true
824 } catch (err) {
825 $.ui.toast(toastLine(`Quick menu: cannot save ${key}: ${message(err)}`))
826 return false
827 }
828}
829
830/** The stores are written and mirrored in their atoms alike: save, then the atom, then a draw; a failed save changes neither. */
831async function writeFavourites($: EngineInterface, next: Favourite[]): Promise<void> {
832 if (!(await saveStore($, FAVOURITES.key, next))) return
833 await update($, favourites, () => next)
834 $.ui.invalidate('ui.render')
835}
836
837async function writeFolds($: EngineInterface, next: Record<string, boolean>): Promise<void> {
838 if (!(await saveStore($, FOLDS.key, next))) return
839 await update($, folded, () => next)
840 $.ui.invalidate('ui.render')
841}
842
843async function toggleFavourite($: EngineInterface, f: Favourite): Promise<void> {
844 const list = await storedValue($, FAVOURITES)
845 const pinned = isFavourite(list, f)
846 if (!pinned && list.length >= MAX_FAVOURITES) {
847 $.ui.toast(`Quick menu: at most ${MAX_FAVOURITES} favourites`)
848 return
849 }
850 await writeFavourites($, pinned ? list.filter(x => !sameFav(x, f)) : [...list, f])
851}
852
853/** What a row is drawn from: the context every row of a block shares. `hasFields`: the surface draws Input (the mobile table has none; its stand-ins draw nothing). `pad`: the block's longest setting label; `cmdPad`: its longest command label; `open`: the key of the row whose editor is open; `draft`: the text in a text editor. */
854type RowCtx = {
855 list: readonly Favourite[]
856 prefix: string
857 hasFields: boolean
858 pad: number
859 cmdPad: number
860 open: string
861 draft: string
862 columns: number
863}
864
865function renderStar($: EngineInterface, ui: Ui, f: Favourite, id: string, ctx: RowCtx) {
866 const { Button } = ui
867 const pinned = isFavourite(ctx.list, f)
868 return (
869 <Button
870 key={`${ctx.prefix}star:${id}`}
871 label={pinned ? '★' : '☆'}
872 plain
873 {...(pinned ? {} : { dimColor: true })}
874 onPress={() => void toggleFavourite($, f)}
875 />
876 )
877}
878
879/** The dim ` · description` that takes what is left of the line and truncates; nothing when there is none. */
880function renderHelp(ui: Ui, help: string | null) {
881 if (help === null) return null
882 const { Box, Text } = ui
883 return (
884 <Box flexDirection="row" flexShrink={1}>
885 <Text dimColor>{' · '}</Text>
886 <Box flexShrink={1}>
887 <Text dimColor italic wrap="truncate-end">{help}</Text>
888 </Box>
889 </Box>
890 )
891}
892
893/** `text` cut to `room` cells, or null when it is missing or `room` is under MIN_HELP_CELLS. */
894const helpFor = (text: string | undefined, room: number): string | null =>
895 text && room >= MIN_HELP_CELLS ? clip(text, room) : null
896
897/** The Input element of a surface that has one (the mobile table has none). */
898const inputOf = (ui: Ui) => (ui as Partial<Pick<Elements['terminal'], 'Input'>>).Input
899
900/** A row's control and the cells it takes (label included), so the description gets what is left. An open editor takes the line. */
901type Drawn = { control: RenderNode; cells: number }
902const WHOLE_LINE = Number.POSITIVE_INFINITY
903
904/** What one setting row shows: its key in the tree, the padded label and the value as text. */
905type SettingView = { row: ConfigRow; id: string; label: string; shown: string }
906
907/** The options cut into lines of at most `room` cells, as `[from, to)` index ranges; an option wider than that gets a line of its own. */
908function optionLines(cells: readonly number[], room: number): [number, number][] {
909 const lines: [number, number][] = []
910 let from = 0
911 let used = 0
912 cells.forEach((n, i) => {
913 if (i > from && used + n > room) {
914 lines.push([from, i])
915 from = i
916 used = 0
917 }
918 used += n
919 })
920 if (cells.length > from) lines.push([from, cells.length])
921 return lines
922}
923
924/** Folded to `value ▾`; pressed, `value ▴` and a row of option Buttons (`● current`, `○ other`), or lines of them under the value when the line is too short. */
925function renderChoice($: EngineInterface, ui: Ui, v: SettingView, options: readonly string[], ctx: RowCtx): Drawn {
926 const { Box, Text, Button } = ui
927 const { row, id, label, shown } = v
928 const open = ctx.open === id
929 const toggle = (
930 <Button key={id} label={`${shown} ${open ? '▴' : '▾'}`} plain onPress={() => void setOpenEditor($, open ? '' : id, '', `${id}:${shown}`)} />
931 )
932 const head = (
933 <Box key={`choice:${id}`} flexDirection="row">
934 <Text>{`${label} `}</Text>
935 {toggle}
936 </Box>
937 )
938 if (!open) return { control: head, cells: width(label) + 2 + width(shown) + 2 }
939 const buttons = options.map(value => (
940 <Box key={`opt:${id}:${value}`} flexDirection="row" flexShrink={0}>
941 <Text> </Text>
942 <Button
943 key={`${id}:${value}`}
944 label={`${value === shown ? '●' : '○'} ${value}`}
945 plain
946 autoFocus={value === shown ? true : undefined}
947 onPress={() => void (value === shown ? setOpenEditor($, '') : pickChoice($, row, value))}
948 />
949 </Box>
950 ))
951 // A space, the glyph, a space and the value.
952 const cells = options.map(value => 1 + 2 + width(value))
953 const optionsWidth = cells.reduce((sum, n) => sum + n, 0)
954 const indent = STAR_CELLS + width(label) + 2
955 const fits = indent + width(shown) + 2 + optionsWidth <= ctx.columns
956 const control = fits ? (
957 <Box key={`choice:${id}`} flexDirection="row">
958 <Text>{`${label} `}</Text>
959 {toggle}
960 {buttons}
961 </Box>
962 ) : (
963 <Box key={`choice:${id}`} flexDirection="column">
964 {head}
965 {optionLines(cells, ctx.columns - indent).map(([from, to]) => (
966 <Box key={`opts:${id}:${from}`} flexDirection="row">
967 <Text>{' '.repeat(indent - STAR_CELLS)}</Text>
968 {buttons.slice(from, to)}
969 </Box>
970 ))}
971 </Box>
972 )
973 return { control, cells: WHOLE_LINE }
974}
975
976/** A text or number value: `value ✎` until pressed, then an Input with save and cancel; Enter saves. */
977function renderTextEdit($: EngineInterface, ui: Ui, v: SettingView, Input: NonNullable<ReturnType<typeof inputOf>>, ctx: RowCtx): Drawn {
978 const { Box, Text, Button } = ui
979 const { row, id, label, shown } = v
980 if (ctx.open !== id) {
981 const control = (
982 <Box key={`field:${id}`} flexDirection="row">
983 <Text>{`${label} `}</Text>
984 <Button key={id} label={`${shown} ✎`} plain onPress={() => void setOpenEditor($, id, shown, id)} />
985 </Box>
986 )
987 return { control, cells: width(label) + 2 + width(shown) + 2 }
988 }
989 // The label is its own Text: an Input's own label draws a `: ` before the value.
990 const control = (
991 <Box key={`field:${id}`} flexDirection="row" columnGap={1}>
992 <Text>{`${label} `}</Text>
993 <Input
994 key={id}
995 value={ctx.draft}
996 autoFocus
997 onInput={(value: string) => void setDraft($, value)}
998 onSubmit={(value: string) => void saveEdit($, row, value)}
999 />
1000 <Button key={`${id}:save`} label="✓ save" onPress={() => void saveDraft($, row)} />
1001 <Button key={`${id}:cancel`} label="✕ cancel" onPress={() => void cancelEdit($, row)} />
1002 </Box>
1003 )
1004 return { control, cells: WHOLE_LINE }
1005}
1006
1007function renderBoolean($: EngineInterface, ui: Ui, v: SettingView): Drawn {
1008 const { Box, Text, Button } = ui
1009 const { row, id, label } = v
1010 const word = row.value ? 'on' : 'off'
1011 const control = (
1012 <Box key={`bool:${id}`} flexDirection="row">
1013 <Text>{`${label} `}</Text>
1014 {row.value ? <Text color="green">●</Text> : <Text color="gray">○</Text>}
1015 <Text> </Text>
1016 <Button key={id} label={word} plain onPress={() => void writeSetting($, row, !row.value)} />
1017 </Box>
1018 )
1019 // The glyph, a space, the word and one cell the plain button keeps.
1020 return { control, cells: width(label) + 2 + 1 + 1 + width(word) + 1 }
1021}
1022
1023function renderSetting(
1024 $: EngineInterface,
1025 ui: Ui,
1026 row: ConfigRow,
1027 plugin: string,
1028 notes: Record<string, Note>,
1029 ctx: RowCtx,
1030) {
1031 const { Box, Text } = ui
1032 const Input = inputOf(ui)
1033 const id = ctx.prefix + settingKey(row.key)
1034 const made = notes[settingKey(row.key)]
1035 // A note stands for the value it was made against: once the row shows another, it is stale and not drawn.
1036 const note = made && made.shown === configArg(row.value) ? made : undefined
1037 const shown = Array.isArray(row.value) ? row.value.join(', ') : String(row.value)
1038 const label = pad(row.label, ctx.pad)
1039 const view: SettingView = { row, id, label, shown }
1040 let drawn: Drawn
1041 if (row.isLocked) {
1042 drawn = { control: <Text key={id} dimColor>{`${label} ${shown} managed`}</Text>, cells: width(label) + 2 + width(`${shown} managed`) }
1043 } else if (row.kind === 'boolean') {
1044 drawn = renderBoolean($, ui, view)
1045 } else if (row.kind === 'choice' && row.options && row.options.length > 0 && ctx.hasFields) {
1046 drawn = renderChoice($, ui, view, row.options, ctx)
1047 } else if (Input && ctx.hasFields) {
1048 drawn = renderTextEdit($, ui, view, Input, ctx)
1049 } else {
1050 drawn = { control: <Text key={id}>{`${label} ${shown}`}</Text>, cells: width(label) + 2 + width(shown) }
1051 }
1052 // The description takes what is left of the line after star, label, value or editor and a note.
1053 const used = STAR_CELLS + drawn.cells + (note ? 2 + width(note.text) : 0) + SEP_CELLS
1054 const help = helpFor(row.description?.replace(/\s+/g, ' '), ctx.columns - used)
1055 return (
1056 <Box key={`row:${id}`} flexDirection="row">
1057 {renderStar($, ui, { kind: 'setting', plugin, key: row.key }, settingKey(row.key), ctx)}
1058 <Text> </Text>
1059 {drawn.control}
1060 {renderHelp(ui, help)}
1061 {note && <Text color="red">{` ${note.text}`}</Text>}
1062 </Box>
1063 )
1064}
1065
1066/** The label a command button shows: `press again: /x` while its confirming press is awaited. */
1067function commandLabel(plugin: string, c: SectionCommand, state: RowState): string {
1068 const isArmed = runsTag(plugin, c) !== null && state.armed.id === commandKey(plugin, c)
1069 return isArmed ? `press again: /${clip(c.command, LIMITS.command)}` : c.label
1070}
1071
1072type AskView = { plugin: string; c: SectionCommand; id: string; rid: string; runs: string; tag: string | null; state: RowState }
1073
1074/** An open ask editor: the label, an Input with the default, `✓ run` and `✕ cancel`; under it the hint, the origin tag and a note. */
1075function renderAsk($: EngineInterface, ui: Ui, v: AskView, Input: NonNullable<ReturnType<typeof inputOf>>, ctx: RowCtx) {
1076 const { Box, Text, Button } = ui
1077 const { plugin, c, id, rid, runs, tag, state } = v
1078 const note = state.notes[rid]
1079 const isArmed = tag !== null && state.armed.id === rid
1080 return (
1081 <Box key={`row:${id}`} flexDirection="column">
1082 <Box flexDirection="row" columnGap={1}>
1083 {renderStar($, ui, { kind: 'command', plugin, key: favCommandKey(c) }, rid, ctx)}
1084 <Text>{c.label}</Text>
1085 <Input
1086 key={id}
1087 value={ctx.draft}
1088 autoFocus
1089 {...(c.ask?.placeholder !== undefined && { placeholder: c.ask.placeholder })}
1090 onInput={(value: string) => void setDraft($, value)}
1091 onSubmit={(value: string) => void runAsked($, plugin, c, value)}
1092 />
1093 <Button key={`${id}:run`} label="✓ run" onPress={() => void runAskedDraft($, plugin, c)} />
1094 <Button key={`${id}:cancel`} label="✕ cancel" onPress={() => void cancelAsk($, plugin, c)} />
1095 </Box>
1096 <Box flexDirection="row">
1097 <Text>{' '.repeat(STAR_CELLS + 1)}</Text>
1098 <Text dimColor>{runs}</Text>
1099 {tag !== null && <Text dimColor>{` ${tag}`}</Text>}
1100 {isArmed && <Text color="yellow">{' press ✓ run again'}</Text>}
1101 {note && <Text color="red">{` ${note.text}`}</Text>}
1102 </Box>
1103 </Box>
1104 )
1105}
1106
1107function renderCommand(
1108 $: EngineInterface,
1109 ui: Ui,
1110 plugin: string,
1111 c: SectionCommand,
1112 state: RowState,
1113 ctx: RowCtx,
1114) {
1115 const { Box, Text, Button } = ui
1116 const rid = commandKey(plugin, c)
1117 const id = ctx.prefix + rid
1118 const tag = runsTag(plugin, c)
1119 const tagCells = tag === null ? 0 : 1 + width(tag)
1120 // The hint takes what is left after star, button and tag, so a narrow pane clips it rather than wrapping the row.
1121 const before = STAR_CELLS + Math.max(ctx.cmdPad, width(c.label)) + BUTTON_CHROME + BUTTON_GAP
1122 const runs = clip(`/${c.command}${c.args ? ` ${c.args}` : ''}${c.ask ? ' …' : ''}`, Math.max(1, Math.min(MAX_RUNS_HINT, ctx.columns - before - tagCells)))
1123 const Input = inputOf(ui)
1124 if (c.ask && c.isAvailable && Input && ctx.open === id) return renderAsk($, ui, { plugin, c, id, rid, runs, tag, state }, Input, ctx)
1125 // The help text takes what is left of the line after star, button, hint and tag.
1126 const used = before + width(runs) + tagCells + 1
1127 const help = helpFor(c.isAvailable ? c.description : undefined, ctx.columns - used - SEP_CELLS)
1128 return (
1129 <Box key={`row:${id}`} flexDirection="row">
1130 {renderStar($, ui, { kind: 'command', plugin, key: favCommandKey(c) }, rid, ctx)}
1131 <Text> </Text>
1132 {c.isAvailable ? (
1133 <Button key={id} label={commandLabel(plugin, c, state)} onPress={() => void pressCommand($, plugin, c, { prefix: ctx.prefix, fromBand: false, canAsk: ctx.hasFields })} />
1134 ) : (
1135 <Text key={id} dimColor>{`${c.label} (not available)`}</Text>
1136 )}
1137 {c.isAvailable && <Text>{' '.repeat(Math.max(0, ctx.cmdPad - width(c.label)) + BUTTON_GAP)}</Text>}
1138 {c.isAvailable && <Text dimColor>{runs}</Text>}
1139 {tag !== null && <Text dimColor>{` ${tag}`}</Text>}
1140 {renderHelp(ui, help)}
1141 {state.queued[rid] && <Text dimColor> queued</Text>}
1142 </Box>
1143 )
1144}
1145
1146function settingRows(section: MenuSection, rows: readonly ConfigRow[]): ConfigRow[] {
1147 const own = rows.filter(r => bareName(r.provider.plugin) === bareName(section.plugin))
1148 if (section.settings === null) return own
1149 const out: ConfigRow[] = []
1150 for (const field of section.settings) {
1151 const row = own.find(r => r.key === `${section.plugin}.${field}`)
1152 if (row) out.push(row)
1153 }
1154 return out
1155}
1156
1157function findFavCommand(f: Favourite, known: readonly MenuSection[]): SectionCommand | undefined {
1158 return known.find(x => x.plugin === f.plugin)?.commands.find(c => favCommandKey(c) === f.key)
1159}
1160
1161function renderFavourite(
1162 $: EngineInterface,
1163 ui: Ui,
1164 f: Favourite,
1165 known: readonly MenuSection[],
1166 rows: readonly ConfigRow[],
1167 state: RowState,
1168 ctx: RowCtx,
1169) {
1170 if (f.kind === 'command') {
1171 const c = findFavCommand(f, known)
1172 if (c) return renderCommand($, ui, f.plugin, c, state, ctx)
1173 } else {
1174 const r = rows.find(x => x.key === f.key)
1175 if (r) return renderSetting($, ui, r, f.plugin, state.notes, ctx)
1176 }
1177 const { Box, Text } = ui
1178 return (
1179 <Box key={`row:${ctx.prefix}gone:${f.kind}:${f.plugin}:${f.key}`} flexDirection="row">
1180 {renderStar($, ui, f, `${f.kind}:${f.plugin}:${f.key}`, ctx)}
1181 <Text> </Text>
1182 <Text dimColor>{`${f.key} (gone)`}</Text>
1183 </Box>
1184 )
1185}
1186
1187/** Settings-only sections: plugins with rows but no menu file section, built at draw time. */
1188function configSections(rows: readonly ConfigRow[], filed: readonly MenuSection[]): MenuSection[] {
1189 const names = new Set(rows.map(r => r.provider.plugin).filter(n => n !== ENGINE && !filed.some(x => bareName(x.plugin) === bareName(n))))
1190 const builtin = new Set(rows.filter(r => r.provider.tier === 'builtin').map(r => r.provider.plugin))
1191 return [...names]
1192 .map(plugin => {
1193 const isBuiltIn = builtin.has(plugin)
1194 const bare = bareName(plugin)
1195 const title = isBuiltIn && bare.startsWith(BUILTIN_PREFIX) ? bare.slice(BUILTIN_PREFIX.length) : bare
1196 return { plugin, title, commands: [], settings: null, source: 'config' as const, ...(isBuiltIn && { isBuiltIn }) }
1197 })
1198 .sort((a, b) => a.title.localeCompare(b.title))
1199}
1200types/index.d.ts 91 lines1/** Schema version of the menu file a plugin ships at `.claude-plugin/quick-menu.json`. */
2export type QuickMenuVersion = 1
3
4/** A command that asks for arguments when pressed: the hint shown in the empty field and the text it starts with. */
5export type MenuAsk = { placeholder?: string; default?: string }
6
7/** One quick-launch command of a menu file, as `/` would take it, without the slash. */
8export type MenuCommand = {
9 command: string
10 label?: string
11 args?: string
12 description?: string
13 ask?: MenuAsk
14}
15
16/** A validated menu file. `settings: null` means all of the plugin's `userConfig` rows. */
17export type MenuFile = {
18 version: QuickMenuVersion
19 title?: string
20 commands: MenuCommand[]
21 settings: string[] | null
22}
23
24/** One command of a discovered section; `isAvailable` is false when `$.command.list()` lacks it. */
25export type SectionCommand = {
26 command: string
27 label: string
28 args?: string
29 description?: string
30 ask?: MenuAsk
31 isAvailable: boolean
32 /** From `$.command.list()`: where the command comes from and, for a plugin's, which plugin (no `@marketplace`). */
33 source?: 'builtin' | 'plugin' | 'user' | 'mcp'
34 owner?: string
35}
36
37/** One plugin's section: `file` when its menu file was read, `config` when only `userConfig` rows exist, `commands` when only its registered commands are known (loaded with `--plugin-dir`). */
38export type MenuSection = {
39 plugin: string
40 title: string
41 commands: SectionCommand[]
42 settings: string[] | null
43 source: 'file' | 'config' | 'commands'
44 /** Dim line shown under the section's header while open. */
45 note?: string
46 /** A plugin bundled in the binary: its title carries a dim `built-in` tag. */
47 isBuiltIn?: boolean
48}
49
50/** A plugin whose menu file or registry entry could not be used. */
51export type MenuProblem = { plugin: string; message: string }
52
53/** A row's note. `shown`: the row's value (as `/config key=value` spells it) when the note was made; the note is drawn only while the row still shows it. */
54export type Note = { kind: 'deny' | 'error'; text: string; shown: string }
55
56/** Transient per-row pane state: commands waiting on `$.command.run`, the deny or error beside a row, and fresh writes. */
57export type RowState = {
58 queued: Record<string, true>
59 notes: Record<string, Note>
60 /** The command whose button was pressed once and waits for the confirming press until `until` (`$.clock.now()` ms). */
61 armed: { id: string; until: number }
62 /**
63 * The value each setting row was last written to, shown while `$.config.list()` still reports `was` (an engine row can lag
64 * its write by a draw); dropped when the pane opens again. `value` is a `ConfigValue`, spelled out: the contract imports nothing.
65 */
66 written: Record<string, { value: boolean | string | number | readonly string[]; was: string }>
67}
68
69/** A pinned command (key: command plus args) or setting (key: config key) of the plugin. */
70export type Favourite = { kind: 'command' | 'setting'; plugin: string; key: string }
71
72declare module 'claude-code' {
73 interface PluginState {
74 'agent-quick-menu': {
75 sections: MenuSection[]
76 problems: MenuProblem[]
77 rowState: RowState
78 favourites: Favourite[]
79 folded: Record<string, boolean>
80 unplaced: boolean
81 filter: string
82 /** `--plugin-dir` plugin name to root, from `plugin.register`, kept across a reload of this module. */
83 inlineRoots: Record<string, string>
84 /** The element key of the one choice or text row being edited; '' when all are folded to `value ▾` / `value ✎`. */
85 openEditor: string
86 /** The text in the open text editor, as last typed. */
87 editDraft: string
88 }
89 }
90}
91