A menu of one-click actions under the header, above the prompt or in a pane, and a control panel from ◆ pad: model and effort in one click, this collection's…

A menu of one-click actions under the Claude Code header, right above the prompt or in a pane of its own, so nobody has to know a /command before they can get something done. Each button runs a command, a skill or an agent that this session has installed. ◆ pad opens a control panel: the session's model and effort in one click, this collection's mods, and the shortcuts.
/clear: a framed card under the header, each button an icon and an action in a bordered tile, in columns that fit the window. The card is the output of /pad, which the mod runs for you, so it sits in the conversation and scrolls up as the conversation grows. /pad draws a fresh one at any time./name runs that command or skill: 🗜️ Compactar conversa runs /compact./name [blank] puts the command in the prompt with the blank marked, for you to fill in and send: /code-review [level] waits for the level. Arguments with no brackets (/code-review high) run as written. A command whose arguments are all optional runs bare: /clear [name] runs /clear.@name calls that agent: 🔍 Explorar código puts Use o agente Explore para [tarefa] in the prompt with the blank marked, for you to say what to explore.general-purpose, Explore, Plan) and the agent files in .claude/agents/ of the project and of your home folder. A button whose command another session has (/limits comes with limits-meter) stays in your list and shows where it works.configuration · list · add · remove · reset · place · off · help. Nothing there leaves a command in the prompt for you to type: configuration opens the pane, and so do add and remove, which are a press there; place asks where the menu goes and reset asks before it resets, in Claude Code's own dialog, where each choice says what it does and each place shows a sketch of itself; list and help print as a dim line in the conversation (Claude does not read it); off turns the menu off, and the row then offers on./pad place, or the placement option):header, the default: the card under the header described above.prompt: the buttons in a row right above the prompt box that stays there, under the bands of other mods (limits-meter's), with ⋯ configure to open the pane.pane: a pane of its own, a tab like those of /limits and /watch, with the card's bordered tiles. It opens when a session starts and after /clear, and on /pad. Claude Code opens a pane only with the keyboard on it: Esc closes it and gives the prompt back.◆ pad, the control panel. A bordered button under Claude Code's hint line, below the prompt, in every placement, and while the menu is off too. It opens a pane with:haiku · sonnet · opus, or the plain names the /config model row lists) and the effort levels (low to max) as buttons, the current ones marked ●. A press runs /model sonnet or /effort low, as typing would. The model comes from the session; the effort from the last request, so before the first one none is marked. With the 5-hour window at 70% or more, opus and max get a yellow border and a line says so; a press still switches at once.⏳ limits-meter, 🔐 allowlist-coach, 👀 agent-watch, 📜 plain-view), that opens its pane, then one for each missing, which puts its /plugin install command in the prompt, or a line saying all are installed. test-hud is left out: it is a tool for developers. A mod whose command takes on and off (plain-view) also gets its switch, its state read from its enabled option.Trocar modelo, which the controls replace. /pad configuration lists the mods installed and missing the same way./pad show the menu again
/pad panel open the control panel, as ◆ pad does
/pad configuration pane to order, remove and add buttons, and the mods to install
/pad list every button, numbered, with what it runs
/pad add 🔎 Revisão | /code-review a button that runs a command or skill
/pad add Revisor | @revisor a button that calls an agent
/pad remove 3 drop button 3
/pad reset back to the default buttons
/pad place header | prompt | pane where the menu shows: under the header, right above the prompt, or in a pane
/pad off turn the menu off: no card at the start, after /clear or on /pad
/pad on turn it back on
/pad configuration (or /pad config) opens a pane with your buttons, each with ↑, ↓ and remover, and below them every installed command, skill and agent not yet in the menu, with a filter to type into and + adicionar on each. Enter in the filter adds the first match. A command that takes an argument comes in with it as a blank (/code-review [level]), from the hint Claude Code shows for it in the / menu. The mod learns the hints as that menu lists the commands, so one you have not yet seen there in this session comes in bare: add the blank with /pad add. A hint of optional arguments only ([name], [auto|<tokens>]) gives no blank: the button runs the command bare. A button saved with such blanks by an earlier version (/clear [name]) is saved back bare once Claude Code lists the command. Once 8 buttons work, the pane says the menu is full until you remove one.
/pad off is kept across sessions and hides the cards already in the conversation too. The other commands and the pane go on working, so you can set the menu up before /pad on. The showOnStart option below only stops the card at the start and after /clear.
The icon in /pad add is optional. It can be any emoji or symbol, or a built-in name between colons (/pad add :chart: Vendas | /cost): folder, doc, pen, search, compress, gauge, chart, table, mail, undo, spark, brain, sliders, help, agent, tool, plug, shield, agents, scroll, broom, reload, puzzle, money, doctor. A plain first word stays in the label. With no icon, a button gets its command's own when the launchpad knows it (/clear 🧹, /compact 📦, /reload-plugins 🔄, ...), else one for where the command comes from: 🔧 built-in, 🧩 plugin, 🔌 MCP, ✨ skill, 🤖 agent. A button saved with one of those last icons takes its command's own when it has one. The table lives in hooks/icons.ts; it is not an option. An agent button can carry its task (@revisor revise [arquivo]); without one, the prompt waits with [tarefa]. Your list is kept across sessions.
A project can ship its own buttons in .claude/launchpad.json:
{
"buttons": [
{ "icon": "🧾", "label": "Fechamento do mês", "text": "/fechamento" },
{ "icon": "chart", "label": "Revisor", "text": "@revisor" }
]
}
Each text is a /command or an @agent, and the button shows only when the session has it. They show after your own, up to 8 in the menu. Their text comes from the repository, so a project button never runs a command on its own: a press only puts its text in the prompt, and you read it before pressing Enter. To remove one, edit the file.
Set them in /config or under pluginConfigs in ~/.claude/settings.json, keyed by the installed name (launchpad@lfernandes-mods).
| Option | Values | Default |
|---|---|---|
language | auto, pt-BR, en: the default buttons and the messages. auto follows the system's LANG: Portuguese for pt_*, English otherwise and when LANG is unset | auto |
icons | auto, emoji, or symbol (⇲ ▥ ◔) for terminals that draw emoji at odd widths. auto uses symbols in a JetBrains IDE's terminal (IntelliJ, PyCharm, ...: TERMINAL_EMULATOR=JetBrains-JediTerm), which gives many emoji one column, and emoji elsewhere | auto |
showOnStart | false shows the menu only on /pad | true |
placement | header, prompt or pane: where the menu shows. /pad place overrides it and is kept across sessions | header |
In the desktop app the buttons are native buttons and always use emoji.
An option already saved in your settings wins over a new default. Installing the plugin can save every option with the value it had then, so after an update that adds auto to an option, set it to auto yourself to get the new behaviour.
terminal.integrated.gpuAcceleration set to off) shifts the rest of the row and bends the borders. icons: auto covers JetBrains; in VS Code, turn GPU acceleration on, or set icons to symbol.general-purpose, Explore, Plan and the .md files directly in .claude/agents/ of the project and of your home folder. An agent a plugin brings, or one in a subfolder, counts as not installed: Claude Code gives a mod no list of agent types./ menu. The pane gives a command its argument as a blank from the hint Claude Code shows in the / menu. The mod learns the hints as that menu lists the commands, and forgets them when it reloads.◆ pad adds three rows under the prompt. A bordered button is three rows tall, under the hint line./pad draws a new one. Claude reads /pad's one-line output (Menu de atalhos do launchpad.), not the buttons./plugin install launchpad --marketplace ice-lfernandes/claude-code-mods
Or for one session: claude --plugin-dir ./launchpad
| Mod | Network | Runs processes | Files | Calls a model | Sends data anywhere |
|---|---|---|---|---|---|
| launchpad | No | No | Reads .claude/launchpad.json, and the agent files in .claude/agents/ of the session's folder and of $HOME | No | No |
The panel also reads the /config rows (the model row's options, a mod's enabled), the session's model and its rate-limit windows. A pressed button does what typing would do: it runs a slash command (/model, /effort, a mod's command) or fills the prompt box. Those go through Claude Code and every other mod's hooks as usual, so permission dialogs and other guards still apply. The mod keeps your list of buttons in its plugin store, on this machine.
hooks/register.tsx 1009 lines1// launchpad: a welcome menu of one-click actions, so nobody has to know a /command first.
2//
3// menu a card in the transcript, under the header: an icon and an action per button, in
4// bordered tiles. It is /pad's output row drawn as buttons, so the mod runs /pad when
5// a session starts with an empty conversation and after /clear, and the card scrolls
6// up with the conversation. Typing /pad draws a new one.
7// buttons each one runs a command or skill (`/compact`) or calls an agent (`@Explore`, which
8// puts "use the Explore agent to [task]" in the prompt). Only what this session has
9// installed shows or can be added: the catalog is $.command.list() (commands and
10// skills), the built-in agents and the files in .claude/agents/ (project and user).
11// /pad configuration a pane to order, remove and add buttons from the catalog, up to
12// MAX_SHOWN. /pad add, remove, list and reset do the same from the prompt. The
13// person's list is kept across sessions in the plugin's store.
14// /pad off | on turns the menu off (no card at the start, after /clear or on /pad) and back
15// on, kept across sessions.
16// /pad place header | prompt | pane where the menu shows: the card under the header, a row
17// right above the prompt box that stays (under the other mods' bands), or a pane of
18// its own, a tab like other mods' panes, with the card's tiles.
19// Kept across sessions; the `placement` option is the default.
20// panel `◆ pad`, a bordered button at the end of the engine's hint line in every placement,
21// or /pad panel: a pane with the session's model and effort as chips (a press runs
22// /model or /effort), a warning on opus and max when the 5-hour window passes 70%,
23// a button per mod of this collection installed (it opens the mod's pane) and the
24// shortcuts. /pad configuration lists the mods missing, with their install command
25// for the prompt.
26// project .claude/launchpad.json adds the repository's buttons. They come from the repo, so
27// a press only puts the text in the prompt: the person reads it before pressing Enter.
28//
29// Reads .claude/launchpad.json and the agent files in .claude/agents/ (the session's folder and
30// the home folder), the /config rows (the model row's options, a mod's `enabled`) and the
31// session's model and rate limits. Runs no process, calls no model.
32
33import { atom, read, update } from 'claude-code'
34import type { Elements, EngineInterface, Register } from 'claude-code'
35
36import type { Effort, IconStyle, Lang, ModInfo, Pad, Placement, Target } from '../types'
37import {
38 agentName,
39 agentOf,
40 agentTask,
41 asPads,
42 available,
43 activeModel,
44 ASK_HEADER,
45 BUILTIN_AGENTS,
46 blankIn,
47 blanksOf,
48 buttonLabel,
49 cells,
50 commandOf,
51 defaults,
52 dressQuestion,
53 EFFORTS,
54 effortOf,
55 fiveHourOf,
56 installText,
57 isWarned,
58 keyOf,
59 langOf,
60 layout,
61 listText,
62 localize,
63 matches,
64 MAX_SHOWN,
65 modelsOf,
66 modLabel,
67 modsOf,
68 moveId,
69 windowOf,
70 padFor,
71 padKey,
72 panelShortcuts,
73 parseAdd,
74 parseProject,
75 placementOf,
76 sameText,
77 shownOf,
78 spell,
79 styleOf,
80 tileLabel,
81 toggleOf,
82 unblank,
83 WORDS,
84} from './pad'
85
86const PANE = 'launchpad'
87/** The menu's own pane, under `/pad place pane`. */
88const MENU_PANE = 'launchpad-menu'
89/** The control panel: model, effort, mods and shortcuts. */
90const PANEL = 'launchpad-panel'
91const PROJECT_FILE = '.claude/launchpad.json'
92const AGENTS_DIR = '.claude/agents'
93const KEY_MENU = 'menu'
94const KEY_OFF = 'off'
95const KEY_PLACE = 'placement'
96
97const menu = atom({ plugin: 'launchpad', key: 'menu' } as const, [] as Pad[])
98const project = atom({ plugin: 'launchpad', key: 'project' } as const, [] as Pad[])
99const catalog = atom({ plugin: 'launchpad', key: 'catalog' } as const, [] as Target[])
100const filter = atom({ plugin: 'launchpad', key: 'filter' } as const, '')
101const offset = atom({ plugin: 'launchpad', key: 'offset' } as const, 0)
102const isOff = atom({ plugin: 'launchpad', key: 'isOff' } as const, false)
103const placement = atom({ plugin: 'launchpad', key: 'placement' } as const, 'header' as Placement)
104const model = atom({ plugin: 'launchpad', key: 'model' } as const, '')
105const effort = atom({ plugin: 'launchpad', key: 'effort' } as const, null as Effort | null)
106
107/**
108 * Argument hints by command name, as the engine lists the commands for the typeahead and /help
109 * (command.describe). $.command.list() carries none, so a command the person has not yet seen
110 * listed in this session has no hint here.
111 */
112const hints = new Map<string, string>()
113
114/** The last first row the pane's catalog list can start at, as last drawn: where the wheel stops. */
115let lastStart = 0
116
117// Set by register from the options, and by session.start for the folder.
118let lang: Lang = 'pt-BR'
119let style: IconStyle = 'emoji'
120let cwd = ''
121/** The `placement` option: where the menu shows until /pad place picks a place. */
122let placeOption: Placement = 'header'
123
124/** The agent types in one `.claude/agents` folder; none where it cannot be read. */
125async function agentsIn($: EngineInterface, dir: string): Promise<Target[]> {
126 const entries = (await $.fs.list(dir).catch(() => [])).filter(f => f.kind === 'file' && f.name.endsWith('.md'))
127 const names = await Promise.all(
128 entries.map(async f => {
129 const raw = await $.fs.read(`${dir}/${f.name}`).catch(() => null)
130 return agentName(f.name, typeof raw === 'string' ? raw : null)
131 }),
132 )
133 return names.filter(Boolean).map(name => ({ kind: 'agent' as const, name, description: '', source: 'agent' }))
134}
135
136/** Every command, skill and agent this session has, less /pad itself. */
137async function readCatalog($: EngineInterface): Promise<Target[]> {
138 const commands = await $.command.list().catch(() => [])
139 const home = await $.env.get('HOME').catch(() => undefined)
140 const [here, mine] = await Promise.all([cwd ? agentsIn($, `${cwd}/${AGENTS_DIR}`) : [], home ? agentsIn($, `${home}/${AGENTS_DIR}`) : []])
141 const files = [...here, ...mine]
142 const seen = new Set<string>()
143 const out: Target[] = []
144 const push = (t: Target) => {
145 const key = keyOf(t.kind, t.name)
146 if (seen.has(key)) return
147 seen.add(key)
148 out.push(t)
149 }
150 for (const c of commands) {
151 const name = c.name.replace(/^\//, '')
152 if (name && name !== 'pad') push({ kind: 'command', name, description: c.description, source: c.source, ...(c.plugin ? { plugin: c.plugin } : {}) })
153 }
154 for (const name of BUILTIN_AGENTS) push({ kind: 'agent', name, description: '', source: 'agent' })
155 for (const a of files) push(a)
156 return out
157}
158
159/**
160 * Reads the person's list, the project's buttons and the on/off switch. The catalog is read once
161 * a session (and again when the pane opens, or an add names something it lacks): `fresh` reads
162 * it now.
163 */
164async function load($: EngineInterface, fresh = false) {
165 const stored = asPads(await $.store.get(KEY_MENU).catch(() => undefined))
166 const raw = cwd ? await $.fs.read(`${cwd}/${PROJECT_FILE}`).catch(() => null) : null
167 await update($, menu, () => (stored ? localize(stored, lang) : defaults(lang)))
168 const off = (await $.store.get(KEY_OFF).catch(() => undefined)) === true
169 await update($, isOff, () => off)
170 const place = await $.store.get(KEY_PLACE).catch(() => undefined)
171 await update($, placement, () => (typeof place === 'string' ? placementOf(place) : placeOption))
172 await update($, project, () => parseProject(typeof raw === 'string' ? raw : null))
173 if (fresh || (await read($, catalog)).length === 0) {
174 const list = await readCatalog($)
175 await update($, catalog, () => list)
176 }
177}
178
179/** Applies a change to the list as it stands now, not as a drawing last saw it. */
180async function editMenu($: EngineInterface, change: (list: Pad[]) => Pad[]) {
181 await saveMenu($, change(await read($, menu)))
182}
183
184async function saveMenu($: EngineInterface, list: Pad[]) {
185 await $.store.set(KEY_MENU, list)
186 await update($, menu, () => list)
187}
188
189/** The buttons as shown and numbered: the person's that work here, then the project's. */
190async function shown($: EngineInterface) {
191 return shownOf(await read($, menu), await read($, project), await read($, catalog))
192}
193
194/** Puts a text in the prompt, its `[blank]` marked for the person to replace. */
195async function fill($: EngineInterface, text: string) {
196 const blank = blankIn(text)
197 await $.prompt.fill(blank ? { text, decorations: [{ ...blank, bold: true, underline: true }] } : { text })
198}
199
200async function press($: EngineInterface, p: Pad) {
201 try {
202 if (p.kind === 'agent') return await fill($, WORDS[lang].useAgent(agentOf(p.text), agentTask(p.text)))
203 // A command with a [blank] waits in the prompt for the person to fill in; so does any
204 // project button, whose text comes from the repository.
205 // A command whose blanks came from an optional hint (`/clear [name]`) runs bare.
206 const text = p.origin === 'project' ? p.text : unblank(p.text, hints.get(commandOf(p.text).command))
207 if (p.origin === 'project' || blankIn(text)) return await fill($, text)
208 const { command, args } = commandOf(text)
209 await $.command.run({ command, args })
210 } catch {
211 $.ui.toast(WORDS[lang].failed(p.label))
212 }
213}
214
215/** Adds a button to the person's list. Returns why not, or null when it was added. */
216async function add($: EngineInterface, p: Pad): Promise<string | null> {
217 const w = WORDS[lang]
218 const list = await read($, menu)
219 const key = padKey(p)
220 const known = async () => (await read($, catalog)).some(t => keyOf(t.kind, t.name) === key)
221 // Installed since the catalog was read? Read it again before saying no.
222 if (!(await known())) await load($, true)
223 if (!(await known())) return w.missing(p.text.split(/\s+/)[0] ?? p.text)
224 if ([...list, ...(await read($, project))].some(x => sameText(x.text, p.text))) return w.already(p.text)
225 // The limit counts the buttons that work here: one whose command another session has stays
226 // in the list, marked in the pane, and takes no place in this menu.
227 if (available(list, await read($, catalog)).length >= MAX_SHOWN) return w.full
228 await saveMenu($, [...list, p])
229 return null
230}
231
232/**
233 * Every bordered button under the pointer: the whole box in the accent, its label in the theme's
234 * text for a filled background, so it reads on dark and light.
235 */
236const BOX_HOVER = { borderColor: 'claude', borderDimColor: false, backgroundColor: 'claude' } as const
237const LABEL_HOVER = { color: 'inverseText', bold: true } as const
238
239/**
240 * /pad's arguments in the row under the menu. None waits in the prompt for typing: `add` and
241 * `remove` open /pad configuration, where both are a press; `place` and `reset` ask in the
242 * engine's dialog; the rest run.
243 */
244const PAD_ACTIONS: { verb: string; via?: 'pane' | 'ask' }[] = [
245 { verb: 'configuration' },
246 { verb: 'list' },
247 { verb: 'add', via: 'pane' },
248 { verb: 'remove', via: 'pane' },
249 { verb: 'reset', via: 'ask' },
250 { verb: 'place', via: 'ask' },
251 { verb: 'off' },
252 { verb: 'help' },
253]
254
255/** An id no button in the list has: the time, and the list's length for two in one millisecond. */
256async function newId($: EngineInterface) {
257 return `user:${await $.clock.now()}:${(await read($, menu)).length}`
258}
259
260/** Opens the menu's own pane. The host opens a pane only with the keyboard on it; Esc closes it. */
261function openMenuPane($: EngineInterface) {
262 return $.ui.open({ id: MENU_PANE, title: WORDS[lang].menuPane, focus: true, closeOnEscape: true }).catch(() => null)
263}
264
265/**
266 * Shows the menu at the start and after /clear, where it lives: under the header, /pad's row
267 * drawn as the card (not awaited: the row lands once the hook has returned); in its pane, opened
268 * with the keyboard on it, as the host opens every pane. The band above the prompt is there
269 * already.
270 */
271async function showMenu($: EngineInterface) {
272 const place = await read($, placement)
273 if (place === 'header') $.command.run({ command: 'pad' }).catch(() => undefined)
274 else if (place === 'pane') await openMenuPane($)
275}
276
277/**
278 * The question a `place` or `reset` press asks, and the /pad arguments its answer runs; null when
279 * dismissed or answered with no choice of the list.
280 */
281async function askVerb($: EngineInterface, verb: string): Promise<string | null> {
282 const w = WORDS[lang]
283 if (verb === 'place') {
284 const now = await read($, placement)
285 const places = (['header', 'prompt', 'pane'] as const).map(p => ({ p, label: p === now ? `${w.ask2.places[p]} ${w.ask2.current}` : w.ask2.places[p] }))
286 const answer = await $.ui.ask(w.ask2.place, { options: places.map(x => x.label), header: ASK_HEADER }).catch(() => null)
287 const hit = places.find(x => x.label === answer)
288 return hit ? `place ${hit.p}` : null
289 }
290 const answer = await $.ui.ask(w.ask2.reset, { options: [w.ask2.resetYes, w.ask2.cancel], header: ASK_HEADER }).catch(() => null)
291 return answer === w.ask2.resetYes ? 'reset' : null
292}
293
294/** Runs one of /pad's arguments from the row: its answer, if any, as dim lines in the transcript. */
295async function pressVerb($: EngineInterface, a: (typeof PAD_ACTIONS)[number]) {
296 const w = WORDS[lang]
297 try {
298 const args = a.via === 'pane' ? 'configuration' : a.via === 'ask' ? await askVerb($, a.verb) : a.verb
299 if (!args) return
300 const { text } = await runPad($, args)
301 // A log line is drawn as one row: a list or the help goes out a line at a time.
302 for (const line of text?.split('\n') ?? []) if (line.trim()) $.ui.log(line)
303 } catch {
304 $.ui.toast(w.failed(`/pad ${a.verb}`))
305 }
306}
307
308/**
309 * The row under the buttons: /pad's own arguments, one press each. Those that run at once (the
310 * pane, the list, off, help) run; those that take an argument or undo the person's list (add,
311 * remove, reset) wait in the prompt, so nothing is lost on a stray click.
312 */
313function padRow($: EngineInterface, ui: Pick<Elements[keyof Elements], 'Box' | 'Text' | 'Button'>, more: number, off = false) {
314 const { Box, Text, Button } = ui
315 const w = WORDS[lang]
316 // Off, the row offers `on`: the way back is a press, not something to type.
317 const actions = off ? PAD_ACTIONS.map(a => (a.verb === 'off' ? { verb: 'on' } : a)) : PAD_ACTIONS
318 return (
319 <Box flexDirection="row" flexWrap="wrap">
320 {more > 0 && <Text dimColor>{`${w.more(more)} · `}</Text>}
321 <Text dimColor>/pad </Text>
322 {actions.map((a, i) => (
323 <Box key={`padrow:${a.verb}`} flexDirection="row">
324 {i > 0 && <Text dimColor> · </Text>}
325 <Button key={`cmd:${a.verb}`} plain dimColor label={a.verb} onPress={() => pressVerb($, a)} />
326 </Box>
327 ))}
328 </Box>
329 )
330}
331
332/**
333 * The terminal's grid of bordered tiles, in columns that fit `columns` cells. Each tile adds 5
334 * cells to its label (border and padding on both sides, one cell of gap).
335 */
336function tiles($: EngineInterface, ui: Elements['terminal'], visible: Pad[], columns: number) {
337 const { Box, Button } = ui
338 const { width, rows } = layout(visible, style, Math.max(1, columns), 5)
339 return (
340 <Box flexDirection="column">
341 {rows.map((row, r) => (
342 <Box key={`row:${r}`} flexDirection="row">
343 {row.map(p => (
344 <Box key={`cell:${p.id}`} width={width} paddingRight={1}>
345 {/* The border is the Box's: a Button there would show inverted under the pointer.
346 The label fills the row inside it, so a press anywhere on that row counts.
347 Over the tile, the whole tile turns the accent color. */}
348 <Box
349 key={`tile:${p.id}`}
350 flexGrow={1}
351 borderStyle="round"
352 borderDimColor
353 hover={BOX_HOVER}
354 >
355 <Button
356 key={`pad:${p.id}`}
357 plain
358 label={tileLabel(buttonLabel(p, style), width - 3)}
359 hover={LABEL_HOVER}
360 onPress={() => press($, p)}
361 />
362 </Box>
363 </Box>
364 ))}
365 </Box>
366 ))}
367 </Box>
368 )
369}
370
371/** The terminal's card: a frame in the accent color (4 cells), the question, the tiles and /pad's row. */
372function terminalCard($: EngineInterface, ui: Elements['terminal'], list: Pad[], columns: number) {
373 const { Box, Text } = ui
374 const w = WORDS[lang]
375 const visible = list.slice(0, MAX_SHOWN)
376 const more = list.length - visible.length
377 return (
378 <Box flexDirection="column" borderStyle="round" borderColor="claude" paddingX={1}>
379 <Text color="claude" bold>
380 ✻ {w.ask}
381 </Text>
382 {tiles($, ui, visible, columns - 4)}
383 {padRow($, ui, more)}
384 </Box>
385 )
386}
387
388/**
389 * A bordered button, the tiles' look: a dim border at rest, the whole box in the accent under
390 * the pointer. `isOn` draws the current choice, in the accent and not pressable; `isWarned` gives
391 * the border the warning color. `width` pads the label to that many cells inside the border.
392 */
393function boxButton(
394 ui: Elements['terminal'],
395 key: string,
396 label: string,
397 onPress: () => unknown,
398 opts: { isOn?: boolean; isWarned?: boolean; width?: number } = {},
399) {
400 const { Box, Button, Text } = ui
401 const text = opts.width ? tileLabel(label, opts.width) : ` ${label} `
402 if (opts.isOn) {
403 return (
404 <Box key={`box:${key}`} borderStyle="round" borderColor={opts.isWarned ? 'warning' : 'claude'}>
405 <Text color="claude" bold>
406 {text}
407 </Text>
408 </Box>
409 )
410 }
411 return (
412 <Box key={`box:${key}`} borderStyle="round" {...(opts.isWarned ? { borderColor: 'warning' } : { borderDimColor: true })} hover={BOX_HOVER}>
413 <Button key={key} plain label={text} hover={LABEL_HOVER} onPress={onPress} />
414 </Box>
415 )
416}
417
418/**
419 * A control on any surface: the bordered button on the terminal, the surface's own button
420 * elsewhere, and the current choice as accent text there.
421 */
422function control(
423 $: EngineInterface,
424 e: { surface: string },
425 key: string,
426 label: string,
427 onPress: () => unknown,
428 opts: { isOn?: boolean; isWarned?: boolean; width?: number } = {},
429) {
430 if (e.surface === 'terminal') return boxButton($.ui.resolve({ ...e, surface: 'terminal' } as never) as Elements['terminal'], key, label, onPress, opts)
431 const { Button, Text } = $.ui.resolve(e as never) as Elements['desktop']
432 if (opts.isOn) {
433 return (
434 <Text key={`on:${key}`} color="claude" bold>
435 {label}
436 </Text>
437 )
438 }
439 return <Button key={key} label={label} onPress={onPress} />
440}
441
442/** Opens the control panel, with the model read fresh. Opened by the person, it seats at any width. */
443async function openPanel($: EngineInterface) {
444 await load($)
445 const now = await $.session.model().catch(() => '')
446 if (now) await update($, model, () => now)
447 return $.ui.open({ id: PANEL, title: WORDS[lang].panel.title, focus: true, closeOnEscape: true }).catch(() => null)
448}
449
450/** A chip's press: /model or /effort with the chip's value, as if typed; the chip moves at once. */
451async function choose($: EngineInterface, command: 'model' | 'effort', value: string) {
452 try {
453 await $.command.run({ command, args: value })
454 if (command === 'model') {
455 const now = await $.session.model().catch(() => value)
456 await update($, model, () => now || value)
457 } else await update($, effort, () => effortOf(value))
458 } catch {
459 $.ui.toast(WORDS[lang].failed(`/${command} ${value}`))
460 }
461}
462
463/** A mod's button or switch: its command, as if typed. */
464async function runMod($: EngineInterface, m: ModInfo, args = '') {
465 try {
466 await $.command.run({ command: m.command, args })
467 } catch {
468 $.ui.toast(WORDS[lang].failed(`/${m.command}${args ? ` ${args}` : ''}`))
469 }
470}
471
472/** /pad and its arguments: what the command answers, and what the row under the menu runs. */
473async function runPad($: EngineInterface, args: string): Promise<{ text?: string }> {
474 const w = WORDS[lang]
475 const [verb = '', ...rest] = args.trim().split(/\s+/)
476 const arg = rest.join(' ')
477
478 switch (verb.toLowerCase()) {
479 case '':
480 case 'show': {
481 await load($)
482 if (await read($, isOff)) return { text: w.isOff }
483 if (!(await shown($)).length) return { text: w.empty }
484 const place = await read($, placement)
485 if (place === 'prompt') return { text: w.inBand }
486 if (place === 'pane') {
487 const opened = await openMenuPane($)
488 if (opened?.isPlaced) return {}
489 return { text: listText(await shown($), lang, style) }
490 }
491 return { text: w.shown }
492 }
493
494 case 'place': {
495 const where = arg.toLowerCase()
496 if (where !== 'header' && where !== 'prompt' && where !== 'pane') return { text: w.badPlace }
497 await $.store.set(KEY_PLACE, where)
498 await update($, placement, () => where)
499 if (where === 'pane') await openMenuPane($)
500 else await $.ui.close({ id: MENU_PANE }).catch(() => undefined)
501 return { text: w.placed[where] }
502 }
503
504 // Kept across sessions. Off hides every card, those already in the transcript too; the
505 // commands and the pane go on working, to set the menu up before turning it back on.
506 case 'off':
507 case 'on': {
508 const off = verb.toLowerCase() === 'off'
509 await $.store.set(KEY_OFF, off)
510 await update($, isOff, () => off)
511 return { text: off ? w.off : w.on }
512 }
513
514 case 'panel': {
515 const opened = await openPanel($)
516 if (opened?.isPlaced) return {}
517 return { text: listText(await shown($), lang, style) }
518 }
519
520 case 'configuration':
521 case 'config':
522 case 'configure': {
523 await load($, true)
524 await update($, filter, () => '')
525 await update($, offset, () => 0)
526 const opened = await $.ui.open({ id: PANE, title: w.pane.title, focus: true, closeOnEscape: true }).catch(() => null)
527 if (opened?.isPlaced) return {}
528 return { text: listText(await shown($), lang, style) }
529 }
530
531 case 'list':
532 await load($)
533 return { text: listText(await shown($), lang, style) }
534
535 case 'add': {
536 await load($)
537 const p = parseAdd(args.trim().slice(3), await newId($))
538 if (!p) return { text: w.badAdd }
539 const why = await add($, p)
540 if (why) return { text: why }
541 const n = (await shown($)).findIndex(x => x.id === p.id) + 1
542 return { text: w.added(n, buttonLabel(p, style)) }
543 }
544
545 case 'remove': {
546 await load($)
547 const p = (await shown($))[Number(arg) - 1]
548 if (!/^\d+$/.test(arg) || !p) return { text: w.noSuch(arg || '?') }
549 if (p.origin === 'project') return { text: w.projectRemove }
550 await saveMenu($, (await read($, menu)).filter(x => x.id !== p.id))
551 return { text: w.removed(p.label) }
552 }
553
554 case 'reset':
555 await saveMenu($, defaults(lang))
556 return { text: w.reset }
557
558 default:
559 return { text: w.help }
560 }
561}
562
563export const register: Register = (on, options) => {
564 // The options alone until session.start can read the system's LANG and which terminal this is.
565 lang = langOf(options.language)
566 style = styleOf(options.icons)
567 const showOnStart = options.showOnStart !== false
568 placeOption = placementOf(options.placement)
569 let w = WORDS[lang]
570
571 on('session.start', async ($, e, next) => {
572 const result = await next(e)
573 cwd = e.cwd
574 lang = langOf(options.language, await $.env.get('LANG').catch(() => undefined))
575 style = styleOf(options.icons, await $.env.get('TERMINAL_EMULATOR').catch(() => undefined))
576 w = WORDS[lang]
577 await $.command.register({
578 name: 'pad',
579 description:
580 lang === 'en'
581 ? 'Shortcuts: /pad shows them; configuration, list, add, remove, reset, place, off, on'
582 : 'Atalhos: /pad mostra; configuration, list, add, remove, reset, place, off, on',
583 argumentHint: '[configuration|list|add|remove|reset|place|off|on]',
584 })
585 await load($, true)
586 const now = await $.session.model().catch(() => '')
587 if (now) await update($, model, () => now)
588 if (showOnStart && e.isInteractive) {
589 const messages = await $.session.messages().catch(() => [])
590 if (messages.length === 0 && !(await read($, isOff))) await showMenu($)
591 }
592 return result
593 })
594
595 // Watches the engine list the commands, to learn which take an argument.
596 on('command.describe', async ($, e, next) => {
597 const result = await next(e)
598 const name = e.command.replace(/^\//, '')
599 const hint = result.argumentHint?.trim()
600 if (hint) hints.set(name, hint)
601 else hints.delete(name)
602 // A button saved with blanks from an optional hint (`/clear [name]`) is saved back bare.
603 const list = await read($, menu)
604 const fixed = list.map(p => (p.kind === 'command' && p.origin === 'user' && commandOf(p.text).command === name ? { ...p, text: unblank(p.text, hint) } : p))
605 if (fixed.some((p, i) => p !== list[i] && p.text !== list[i]!.text)) await saveMenu($, fixed)
606 return result
607 }).catch(($, e, next) => next(e))
608
609 // A /clear starts the conversation over with no session.start; the classic SessionStart says so.
610 on('classic.SessionStart', async ($, e, next) => {
611 const result = await next(e)
612 if (e.source === 'clear' && showOnStart && !(await read($, isOff))) await showMenu($)
613 return result
614 }).catch(($, e, next) => next(e))
615
616 on('command.run', { command: 'pad' }, ($, e) => runPad($, e.args))
617
618 // The main loop's model and effort, as each request goes out: the panel's active chips.
619 on('turn.step', async function* ($, e, next) {
620 if (!e.agentId) {
621 try {
622 await update($, model, () => e.model)
623 await update($, effort, () => effortOf(e.effort))
624 } catch {
625 // The chips keep what they had.
626 }
627 }
628 return yield* next(e)
629 })
630
631 // /pad's own row, drawn as the menu. Any other /pad output (list, add, ...) stays text.
632 on('ui.render', { component: 'CommandOutput' }, async ($, e, next) => {
633 const verb = e.props.args.trim().toLowerCase()
634 if (e.props.command !== 'pad' || e.props.isErrored || (verb !== '' && verb !== 'show')) return next(e)
635 if ((await read($, isOff)) || (await read($, placement)) !== 'header') return next(e)
636 const list = await shown($)
637 if (list.length === 0) return next(e)
638
639 if (e.surface === 'terminal') {
640 return terminalCard($, $.ui.resolve({ ...e, surface: 'terminal' }), list, e.viewport?.columns ?? 80)
641 }
642
643 const { Box, Text, Button } = $.ui.resolve(e)
644 const visible = list.slice(0, MAX_SHOWN)
645 const more = list.length - visible.length
646 return (
647 <Box flexDirection="column" rowGap={1}>
648 <Text bold>{w.ask}</Text>
649 <Box flexDirection="row" flexWrap="wrap" columnGap={1} rowGap={1}>
650 {visible.map(p => (
651 <Button key={`pad:${p.id}`} label={buttonLabel(p, 'emoji')} onPress={() => press($, p)} />
652 ))}
653 </Box>
654 {padRow($, { Box, Text, Button }, more)}
655 </Box>
656 )
657 })
658
659 // `◆ pad` under the engine's hint line, at its left, in every placement and while the menu is off
660 // too (the panel's /pad row turns it back on). The engine's hint stays as it draws it, above.
661 on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
662 const theirs = await next(e)
663 const { Box } = $.ui.resolve(e)
664 return (
665 <Box flexDirection="column" alignItems="flex-start">
666 {theirs}
667 {control($, e, 'pad:panel', w.panel.entry, () => openPanel($))}
668 </Box>
669 )
670 })
671
672 // `/pad place prompt`: the buttons in a row right above the prompt box. The row goes after what
673 // the mods beneath drew, so it sits against the box whatever order the mods load in.
674 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
675 const theirs = await next(e)
676 if (e.props.hasSurvey || (await read($, placement)) !== 'prompt' || (await read($, isOff))) return theirs
677 const list = await shown($)
678 if (list.length === 0) return theirs
679 const { Box, Text, Button } = $.ui.resolve(e)
680 const icons = e.surface === 'terminal' ? style : 'emoji'
681 const mine = (
682 <Box key="launchpad" flexDirection="row" flexWrap="wrap" gap={2} paddingX={1}>
683 <Text color="claude">✻</Text>
684 {list.slice(0, MAX_SHOWN).map(p => (
685 <Box key={`cell:${p.id}`}>
686 <Button key={`pad:${p.id}`} plain label={buttonLabel(p, icons)} hover={{ backgroundColor: 'claude', ...LABEL_HOVER }} onPress={() => press($, p)} />
687 </Box>
688 ))}
689 <Button key="band:settings" plain dimColor label={w.settings} onPress={() => pressVerb($, PAD_ACTIONS[0]!)} />
690 </Box>
691 )
692 return theirs ? (
693 <Box flexDirection="column">
694 {theirs}
695 {mine}
696 </Box>
697 ) : (
698 mine
699 )
700 })
701
702 // The /pad row's questions (place, reset) in the engine's dialog, with a line on what each choice
703 // does and a sketch of each place. The engine draws them; only the launchpad's own are touched.
704 on('ui.render', { component: 'AskUserQuestion' }, async ($, e, next) => {
705 const questions = e.props.questions as Parameters<typeof dressQuestion>[0][]
706 if (questions.length !== 1 || questions[0]?.header !== ASK_HEADER) return next(e)
707 return next({ ...e, props: { ...e.props, questions: [dressQuestion(questions[0], lang)] } })
708 }).catch(($, e, next) => next(e))
709
710 // The control panel: the session's model and effort, this collection's mods, the shortcuts.
711 on('ui.render', { component: 'Pane', requestId: PANEL }, async ($, e) => {
712 const ui = $.ui.resolve(e)
713 const { Box, Text, Button } = ui
714 const p = w.panel
715 const all = await read($, catalog)
716 const has = (name: string) => all.some(t => t.kind === 'command' && t.name === name)
717 const rows = await $.config.list().catch(() => [])
718 const chips = modelsOf(rows.find(r => r.key === 'model')?.options)
719 const current = activeModel(await read($, model), chips)
720 const level = await read($, effort)
721 const usage = await $.session.usage().catch(() => null)
722 const fiveHour = fiveHourOf(usage?.rateLimits)
723 const warned = chips.some(c => isWarned(c, fiveHour)) || EFFORTS.some(x => isWarned(x, fiveHour))
724 const { installed, missing } = modsOf(all)
725 const icons = e.surface === 'terminal' ? style : 'emoji'
726 const shortcuts = panelShortcuts(await shown($)).slice(0, MAX_SHOWN)
727 const columns = Math.max(20, (e.props.bodyColumns || e.viewport?.columns || 80) - 2)
728 const chipRow = (label: string, command: 'model' | 'effort', values: readonly string[], active: string | null) => (
729 <Box key={`chips:${command}`} flexDirection="row" flexWrap="wrap" alignItems="center" gap={1}>
730 <Text dimColor>{label}</Text>
731 {values.map(v =>
732 control($, e, `${command}:${v}`, `${v === active ? '●' : '○'} ${v}`, () => choose($, command, v), { isOn: v === active, isWarned: isWarned(v, fiveHour) }),
733 )}
734 </Box>
735 )
736
737 return (
738 <Box flexDirection="column" paddingX={1} gap={1}>
739 <Box flexDirection="column">
740 <Text color="claude" bold>{`✻ ${p.title}`}</Text>
741 <Text dimColor>{p.hint}</Text>
742 </Box>
743
744 {(has('model') || has('effort')) && (
745 <Box flexDirection="column">
746 <Text bold>{p.controls}</Text>
747 {has('model') && chipRow(p.model, 'model', chips, current)}
748 {has('effort') && chipRow(p.effort, 'effort', EFFORTS, level)}
749 {has('effort') && level === null && <Text dimColor>{p.effortUnknown}</Text>}
750 {warned && fiveHour !== null && <Text color="warning">{p.warn(Math.round(fiveHour))}</Text>}
751 </Box>
752 )}
753
754 <Box flexDirection="column">
755 <Text bold>{p.mods}</Text>
756 {installed.length > 0 && (
757 <Box flexDirection="column">
758 <Box flexDirection="row" flexWrap="wrap" gap={1}>
759 {installed.map(m => control($, e, `mod:${m.plugin}`, modLabel(m, icons), () => runMod($, m), { width: 20 }))}
760 </Box>
761 {installed
762 .filter(m => m.toggles)
763 .map(m => {
764 const isOn = toggleOf(m, rows)
765 return (
766 <Box key={`toggle:${m.plugin}`} flexDirection="row" alignItems="center" gap={2}>
767 <Text>{modLabel(m, icons)}</Text>
768 {isOn !== null && <Text color={isOn ? 'success' : 'inactive'}>{isOn ? p.isOn : p.isOff}</Text>}
769 {isOn !== false && control($, e, `off:${m.plugin}`, p.turnOff, () => runMod($, m, 'off'))}
770 {isOn !== true && control($, e, `on:${m.plugin}`, p.turnOn, () => runMod($, m, 'on'))}
771 </Box>
772 )
773 })}
774 </Box>
775 )}
776 {/* What is missing, each with a button that puts its install command in the prompt. */}
777 {missing.length === 0 ? (
778 <Text dimColor>{w.modsSection.allInstalled}</Text>
779 ) : (
780 <Box flexDirection="column">
781 <Text dimColor>{installed.length === 0 ? p.noMods : w.modsSection.missing}</Text>
782 <Box flexDirection="row" flexWrap="wrap" gap={1}>
783 {missing.map(m => control($, e, `install:${m.plugin}`, w.modsSection.install(m.plugin), () => fill($, installText(m.plugin))))}
784 </Box>
785 </Box>
786 )}
787 </Box>
788
789 {shortcuts.length > 0 && (
790 <Box flexDirection="column">
791 <Text bold>{p.shortcuts}</Text>
792 {e.surface === 'terminal' ? (
793 tiles($, $.ui.resolve({ ...e, surface: 'terminal' }), shortcuts, columns)
794 ) : (
795 <Box flexDirection="row" flexWrap="wrap" columnGap={1} rowGap={1}>
796 {shortcuts.map(x => (
797 <Button key={`pad:${x.id}`} label={buttonLabel(x, 'emoji')} onPress={() => press($, x)} />
798 ))}
799 </Box>
800 )}
801 </Box>
802 )}
803
804 <Box flexDirection="column" alignItems="flex-start">
805 {padRow($, { Box, Text, Button }, 0, await read($, isOff))}
806 {control($, e, 'close', p.close, () => $.ui.close({ id: PANEL }))}
807 </Box>
808 </Box>
809 )
810 })
811
812 // `/pad place pane`: the menu in a pane of its own, a tab beside the other mods' panes, with
813 // the card's bordered tiles on the terminal and its native buttons elsewhere.
814 on('ui.render', { component: 'Pane', requestId: MENU_PANE }, async ($, e) => {
815 const ui = $.ui.resolve(e)
816 const { Box, Text, Button } = ui
817 const list = await shown($)
818 const visible = list.slice(0, MAX_SHOWN)
819 const more = list.length - visible.length
820 const columns = Math.max(20, (e.props.bodyColumns || e.viewport?.columns || 80) - 2)
821 const body =
822 e.surface === 'terminal' ? (
823 tiles($, $.ui.resolve({ ...e, surface: 'terminal' }), visible, columns)
824 ) : (
825 <Box flexDirection="row" flexWrap="wrap" columnGap={1} rowGap={1}>
826 {visible.map(p => (
827 <Button key={`pad:${p.id}`} label={buttonLabel(p, 'emoji')} onPress={() => press($, p)} />
828 ))}
829 </Box>
830 )
831 return (
832 <Box flexDirection="column" paddingX={1} gap={1}>
833 <Text color="claude" bold>{`✻ ${w.ask}`}</Text>
834 {(await read($, isOff)) ? <Text dimColor>{w.isOff}</Text> : visible.length === 0 ? <Text dimColor>{w.empty}</Text> : body}
835 <Box flexDirection="row" flexWrap="wrap" gap={2}>
836 {padRow($, { Box, Text, Button }, more, await read($, isOff))}
837 <Button key="close" role="dismiss" label={w.pane.close} onPress={() => $.ui.close({ id: MENU_PANE })} />
838 </Box>
839 </Box>
840 )
841 })
842
843 // The wheel over the pane moves the catalog list, which the pane keeps whole in view.
844 on('ui.scroll', { component: 'Pane', requestId: PANE }, async ($, e) => {
845 await update($, offset, o => Math.max(0, Math.min(lastStart, o + e.by)))
846 return {}
847 }).catch(($, e, next) => next(e))
848
849 // /pad configuration: the person's buttons to order and remove, the project's, and the catalog
850 // to add from, filtered as they type.
851 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
852 const els = $.ui.resolve(e)
853 const { Box, Text, Button } = els
854 // The mobile app draws no field yet: there the catalog lists unfiltered.
855 const Input = 'Input' in els ? els.Input : null
856 const icons = e.surface === 'terminal' ? style : 'emoji'
857 const all = await read($, catalog)
858 const mine = await read($, menu)
859 const theirs = available(await read($, project), all)
860 const working = available(mine, all)
861 const query = await read($, filter)
862 const found = matches(all, mine, query)
863 const mods = modsOf(all)
864 // The catalog list takes the rows the rest leaves: hint, menu, project, headings, filter,
865 // the scroll row, the footer and the gaps between them. The pane keeps it in view whole.
866 // The Mods section: its heading and gap, a row of the installed, and the missing as bordered
867 // buttons (3 rows a line) under their line of text.
868 const installWidth = Math.max(0, ...mods.missing.map(m => cells(w.modsSection.install(m.plugin)) + 5))
869 const perLine = Math.max(1, Math.floor((e.props.bodyColumns - 2) / Math.max(1, installWidth)))
870 const modsRows = 2 + (mods.installed.length ? 1 : 0) + (mods.missing.length ? 1 + 3 * Math.ceil(mods.missing.length / perLine) : 0)
871 const fixed = 10 + mine.length + (theirs.length ? theirs.length + 2 : 0) + modsRows
872 const listRows = Math.max(5, e.props.scroll.bodyRows - fixed)
873 const view = windowOf(found.length, await read($, offset), listRows)
874 const nameWidth = Math.max(24, Math.min(44, Math.floor(e.props.bodyColumns * 0.4)))
875 lastStart = Math.max(0, found.length - listRows)
876 const scrollList = (by: number) => update($, offset, o => windowOf(found.length, o + by, listRows).start)
877 const addTarget = async (t: Target) => {
878 const why = await add($, padFor(t, await newId($), hints.get(t.name)))
879 if (why) $.ui.toast(why)
880 }
881
882 return (
883 <Box flexDirection="column" paddingX={1} gap={1}>
884 <Text dimColor>{w.pane.hint}</Text>
885
886 <Box flexDirection="column">
887 <Text bold>{w.pane.menu(working.length)}</Text>
888 {mine.map((p, i) => {
889 // Numbered as /pad list and /pad remove number them: the buttons that work here.
890 const n = working.indexOf(p) + 1
891 return (
892 <Box key={`menu:${p.id}`} flexDirection="row" gap={1}>
893 <Text dimColor>{n > 0 ? String(n).padStart(2) : ' –'}</Text>
894 <Box width={26}>
895 <Text wrap="truncate-end">{buttonLabel(p, icons)}</Text>
896 </Box>
897 <Box width={22}>
898 <Text dimColor={n > 0} color={n > 0 ? undefined : 'warning'} wrap="truncate-end">
899 {n > 0 ? p.text : `${p.text} ${w.pane.gone}`}
900 </Text>
901 </Box>
902 <Box width={2}>{i > 0 && <Button key={`up:${p.id}`} plain label="↑" onPress={() => editMenu($, list => moveId(list, p.id, -1))} />}</Box>
903 <Box width={2}>
904 {i < mine.length - 1 && <Button key={`down:${p.id}`} plain label="↓" onPress={() => editMenu($, list => moveId(list, p.id, 1))} />}
905 </Box>
906 <Button
907 key={`remove:${p.id}`}
908 plain
909 dimColor
910 label={w.pane.remove}
911 onPress={() => editMenu($, list => list.filter(x => x.id !== p.id))}
912 />
913 </Box>
914 )
915 })}
916 </Box>
917
918 {theirs.length > 0 && (
919 <Box flexDirection="column">
920 <Text bold>{w.pane.project}</Text>
921 {theirs.map((p, i) => (
922 <Text key={`project:${p.id}`} dimColor wrap="truncate-end">{`${String(working.length + i + 1).padStart(2)} ${buttonLabel(p, icons)} ${p.text}`}</Text>
923 ))}
924 </Box>
925 )}
926
927 <Box flexDirection="column">
928 <Text bold>{w.pane.add}</Text>
929 {working.length >= MAX_SHOWN ? (
930 <Text color="warning">{w.pane.full}</Text>
931 ) : (
932 <Box flexDirection="column">
933 {Input && (
934 <Input
935 key="filter"
936 label={w.pane.filter}
937 placeholder={w.pane.placeholder}
938 value={query}
939 autoFocus
940 submitLabel={w.pane.plus}
941 onInput={async (value: string) => {
942 await update($, filter, () => value)
943 await update($, offset, () => 0)
944 }}
945 onSubmit={(value: string) => {
946 const first = matches(all, mine, value)[0]
947 if (first) addTarget(first)
948 }}
949 />
950 )}
951 {found.length === 0 && <Text dimColor>{w.pane.none}</Text>}
952 {found.slice(view.start, view.end).map(t => (
953 <Box key={`find:${keyOf(t.kind, t.name)}`} flexDirection="row" gap={1}>
954 <Button key={`add:${keyOf(t.kind, t.name)}`} plain label={w.pane.plus} onPress={() => addTarget(t)} />
955 <Box width={nameWidth}>
956 <Text wrap="truncate-end">
957 {spell(t)}
958 {t.kind === 'command' && hints.has(t.name) && <Text dimColor>{` ${blanksOf(hints.get(t.name))}`}</Text>}
959 </Text>
960 </Box>
961 <Text dimColor wrap="truncate-end">
962 {t.description || w.kinds[t.kind]}
963 </Text>
964 </Box>
965 ))}
966 {found.length > listRows && (
967 <Box flexDirection="row" gap={2}>
968 <Button key="list:up" plain dimColor={view.start === 0} label={w.pane.up} onPress={() => scrollList(-listRows + 1)} />
969 <Button key="list:down" plain dimColor={view.end === found.length} label={w.pane.down} onPress={() => scrollList(listRows - 1)} />
970 <Text dimColor>{w.pane.range(view.start + 1, view.end, found.length)}</Text>
971 </Box>
972 )}
973 </Box>
974 )}
975 </Box>
976
977 <Box flexDirection="column">
978 <Text bold>{w.modsSection.title}</Text>
979 {mods.installed.length > 0 && (
980 <Box flexDirection="row" flexWrap="wrap" gap={2}>
981 {mods.installed.map(m => (
982 <Text key={`has:${m.plugin}`}>
983 <Text color="success">✓ </Text>
984 {m.plugin}
985 </Text>
986 ))}
987 </Box>
988 )}
989 {mods.missing.length === 0 && <Text dimColor>{w.modsSection.allInstalled}</Text>}
990 {mods.missing.length > 0 && (
991 <Box flexDirection="column">
992 <Text dimColor>{w.modsSection.missing}</Text>
993 <Box flexDirection="row" flexWrap="wrap" gap={1}>
994 {mods.missing.map(m => control($, e, `install:${m.plugin}`, w.modsSection.install(m.plugin), () => fill($, installText(m.plugin))))}
995 </Box>
996 </Box>
997 )}
998 </Box>
999
1000 <Box flexDirection="row" gap={2}>
1001 <Button key="reset" label={w.pane.reset} onPress={() => saveMenu($, defaults(lang))} />
1002 <Button key="panel" label={w.modsSection.back} onPress={() => openPanel($)} />
1003 <Button key="close" role="dismiss" label={w.pane.close} onPress={() => $.ui.close({ id: PANE })} />
1004 </Box>
1005 </Box>
1006 )
1007 })
1008}
1009hooks/pad.ts 759 lines1// Pure logic for launchpad: the default buttons, icons, parsing /pad add and the project file,
2// checking buttons against what the session has installed, and laying them out in columns.
3// No `$` here, so it tests without an engine.
4
5import type { Effort, IconStyle, Kind, Lang, ModInfo, Origin, Pad, Placement, Target } from '../types'
6import { COMMAND_ICONS, GENERIC, ICONS, SOURCE_ICONS } from './icons'
7
8/** Buttons the menu shows, and the most the person's own list may hold. */
9export const MAX_SHOWN = 8
10export const MAX_LABEL = 24
11export const MAX_TEXT = 2000
12export const MAX_PROJECT = 8
13
14/** Agent types every session has, besides the ones in `.claude/agents/`. */
15export const BUILTIN_AGENTS = ['general-purpose', 'Explore', 'Plan']
16
17export { ICONS }
18
19type Words = {
20 ask: string
21 defaults: { id: string; icon: string; label: string; text: string }[]
22 kinds: Record<Kind, string>
23 origins: Record<Origin, string>
24 shown: string
25 empty: string
26 off: string
27 on: string
28 isOff: string
29 added: (n: number, label: string) => string
30 removed: (label: string) => string
31 reset: string
32 projectRemove: string
33 noSuch: (n: string) => string
34 help: string
35 badAdd: string
36 missing: (text: string) => string
37 full: string
38 already: (text: string) => string
39 failed: (what: string) => string
40 more: (n: number) => string
41 /** Where the menu shows: the answer to /pad place, and what /pad says when the menu is not a card. */
42 placed: Record<Placement, string>
43 badPlace: string
44 inBand: string
45 /** The menu's own pane, when it shows as one. */
46 menuPane: string
47 /** The band's button that opens /pad configuration. */
48 settings: string
49 /** What an agent button puts in the prompt, its `[blank]` for the task. */
50 useAgent: (name: string, task?: string) => string
51 /** What the /pad row's `place` and `reset` ask in the engine's dialog. */
52 ask2: {
53 place: string
54 places: Record<Placement, string>
55 /** What each place is, and a sketch of it, for the engine's dialog. */
56 placeNotes: Record<Placement, { description: string; preview: string }>
57 current: string
58 reset: string
59 resetYes: string
60 resetNote: string
61 cancel: string
62 cancelNote: string
63 }
64 /** The control panel: `◆ pad` on the hint line, or /pad panel. */
65 panel: {
66 entry: string
67 title: string
68 hint: string
69 controls: string
70 model: string
71 effort: string
72 effortUnknown: string
73 warn: (percent: number) => string
74 mods: string
75 noMods: string
76 isOn: string
77 isOff: string
78 turnOn: string
79 turnOff: string
80 shortcuts: string
81 close: string
82 }
83 /** The Mods section of /pad configuration. */
84 modsSection: {
85 title: string
86 missing: string
87 install: (plugin: string) => string
88 allInstalled: string
89 back: string
90 }
91 pane: {
92 title: string
93 hint: string
94 menu: (n: number) => string
95 project: string
96 add: string
97 filter: string
98 placeholder: string
99 plus: string
100 remove: string
101 gone: string
102 full: string
103 none: string
104 range: (from: number, to: number, of: number) => string
105 up: string
106 down: string
107 reset: string
108 close: string
109 }
110}
111
112export const WORDS: Record<Lang, Words> = {
113 'pt-BR': {
114 ask: 'O que você quer fazer?',
115 defaults: [
116 { id: 'compact', icon: 'compress', label: 'Compactar conversa', text: '/compact' },
117 { id: 'context', icon: 'chart', label: 'Ver contexto', text: '/context' },
118 { id: 'limits', icon: 'gauge', label: 'Ver limites', text: '/limits' },
119 { id: 'resume', icon: 'undo', label: 'Retomar conversa', text: '/resume' },
120 { id: 'memory', icon: 'brain', label: 'Editar memória', text: '/memory' },
121 { id: 'model', icon: 'sliders', label: 'Trocar modelo', text: '/model' },
122 { id: 'explore', icon: 'search', label: 'Explorar código', text: '@Explore' },
123 { id: 'help', icon: 'help', label: 'Ajuda', text: '/help' },
124 ],
125 kinds: { command: 'comando', agent: 'agente' },
126 origins: { default: 'padrão', user: 'seu', project: 'projeto' },
127 shown: 'Menu de atalhos do launchpad.',
128 empty: 'Nenhum atalho disponível. /pad configuration escolhe os do menu.',
129 off: 'Launchpad desligado: o menu não aparece mais ao abrir a sessão nem com /pad. /pad on liga de novo.',
130 on: 'Launchpad ligado: o menu aparece ao abrir a sessão, depois do /clear e com /pad.',
131 isOff: 'O launchpad está desligado. /pad on liga de novo.',
132 added: (n, label) => `Atalho ${n} criado: ${label}.`,
133 removed: label => `Atalho removido: ${label}.`,
134 reset: 'Atalhos de volta aos padrões.',
135 projectRemove: 'Esse atalho vem do projeto. Edite .claude/launchpad.json para tirá-lo.',
136 noSuch: n => `Não existe atalho ${n}. /pad list mostra os números.`,
137 help: [
138 '/pad mostra o menu',
139 '/pad panel abre o painel: modelo, esforço, mods e atalhos (ou ◆ pad na linha de dica)',
140 '/pad configuration abre o painel para escolher e ordenar os atalhos',
141 '/pad list lista os atalhos',
142 '/pad add 📊 Nome | /comando um atalho que roda um comando ou skill',
143 '/pad add Nome | @agente um atalho que chama um agente',
144 '/pad remove 3 tira o atalho 3',
145 '/pad reset volta aos atalhos padrão',
146 '/pad off | on desliga ou liga o menu',
147 '/pad place header o menu como cartão sob o cabeçalho (padrão)',
148 '/pad place prompt o menu numa linha logo acima do prompt, sempre à mão',
149 '/pad place pane o menu num painel, uma aba como as de /limits e /watch',
150 `Só entram comandos, skills e agentes instalados, até ${MAX_SHOWN} atalhos.`,
151 ].join('\n'),
152 badAdd: 'Use: /pad add 📊 Nome | /comando ou /pad add Nome | @agente',
153 missing: text => `${text} não está instalado nesta sessão. /pad configuration mostra o que está.`,
154 full: `O menu já tem ${MAX_SHOWN} atalhos. Tire um com /pad remove ou no painel.`,
155 already: text => `${text} já está no menu.`,
156 failed: what => `Não deu para rodar: ${what}`,
157 more: n => `+${n} em /pad list`,
158 placed: {
159 header: 'O menu volta a ser um cartão sob o cabeçalho, ao abrir a sessão, depois do /clear e com /pad.',
160 prompt: 'O menu agora fica numa linha logo acima do prompt, sempre à mão.',
161 pane: 'O menu agora abre num painel, uma aba como as de /limits e /watch.',
162 },
163 badPlace: 'Use: /pad place header | prompt | pane',
164 inBand: 'O menu está na linha acima do prompt. /pad place header volta ao cartão.',
165 menuPane: 'Atalhos',
166 settings: '⋯ configurar',
167 useAgent: (name, task) => `Use o agente ${name} para ${task || '[tarefa]'}`,
168 ask2: {
169 place: 'Onde o menu deve ficar?',
170 places: { header: 'Sob o cabeçalho', prompt: 'Acima do prompt', pane: 'Num painel' },
171 placeNotes: {
172 header: {
173 description: 'Um cartão sob o cabeçalho, ao abrir a sessão e depois do /clear. Sobe com a conversa.',
174 preview: ['╭ ✻ O que você quer fazer? ──────╮', '│ ▐ Compactar ▌ ▐ Ver contexto ▌ │', '│ ▐ Ver limites ▌ ▐ Retomar ▌ │', '╰────────────────────────────────╯', '', ' ... a conversa segue aqui ...', '', '╭────────────────────────────────╮', '│ > │', '╰────────────────────────────────╯'].join('\n'),
175 },
176 prompt: {
177 description: 'Uma linha logo acima da caixa do prompt, sempre à mão.',
178 preview: [' ... a conversa ...', '', ' 5h ██░░░ 12% (faixas de outros mods)', ' ✻ Compactar Ver contexto Retomar ⋯', '╭────────────────────────────────╮', '│ > │', '╰────────────────────────────────╯'].join('\n'),
179 },
180 pane: {
181 description: 'Um painel ao lado da conversa, uma aba como /limits e /watch. Esc fecha.',
182 preview: [' ... a conversa ... │ Atalhos', ' │ ✻ O que você quer', ' │ fazer?', ' │ ▐ Compactar ▌', ' │ ▐ Ver contexto ▌', '╭─────────────────────╮│ ▐ Retomar ▌', '│ > ││', '╰─────────────────────╯│ Esc fecha'].join('\n'),
183 },
184 },
185 current: '(atual)',
186 reset: 'Voltar aos atalhos padrão? Os que você adicionou somem.',
187 resetYes: 'Voltar aos padrões',
188 resetNote: 'Volta aos 8 atalhos padrão. Os que você adicionou somem; os do projeto ficam.',
189 cancel: 'Cancelar',
190 cancelNote: 'Nada muda.',
191 },
192 panel: {
193 entry: '◆ pad',
194 title: 'Painel',
195 hint: 'Modelo e esforço desta sessão, os mods instalados e os atalhos.',
196 controls: 'Controles',
197 model: 'modelo ',
198 effort: 'esforço',
199 effortUnknown: 'esforço: o do modelo, até o 1º pedido',
200 warn: p => `! 5h em ${p}%: opus e max gastam a janela mais rápido`,
201 mods: 'Mods',
202 noMods: 'Nenhum mod desta coleção instalado. Para instalar (o comando vai para o prompt; Enter instala):',
203 isOn: '● ligado',
204 isOff: '○ desligado',
205 turnOn: 'ligar',
206 turnOff: 'desligar',
207 shortcuts: 'Atalhos',
208 close: 'Fechar',
209 },
210 modsSection: {
211 title: 'Mods',
212 missing: 'Faltam (o comando vai para o prompt; Enter instala):',
213 install: plugin => `instalar ${plugin}`,
214 allInstalled: 'Todos os mods desta coleção já estão instalados.',
215 back: 'voltar ao painel',
216 },
217 pane: {
218 title: 'Launchpad',
219 hint: `Só aparecem comandos, skills e agentes instalados nesta sessão. Até ${MAX_SHOWN} no menu.`,
220 menu: n => `No menu (${n}/${MAX_SHOWN})`,
221 project: 'Do projeto (.claude/launchpad.json)',
222 add: 'Adicionar',
223 filter: 'Filtrar',
224 placeholder: 'nome de comando, skill ou agente',
225 plus: '+ adicionar',
226 remove: 'remover',
227 gone: '(não instalado)',
228 full: `Menu cheio. Tire um atalho para adicionar outro.`,
229 none: 'Nada com esse nome.',
230 range: (from, to, of) => `${from}–${to} de ${of}`,
231 up: '▲ acima',
232 down: '▼ abaixo',
233 reset: 'Restaurar padrões',
234 close: 'Fechar',
235 },
236 },
237 en: {
238 ask: 'What do you want to do?',
239 defaults: [
240 { id: 'compact', icon: 'compress', label: 'Compact chat', text: '/compact' },
241 { id: 'context', icon: 'chart', label: 'See context', text: '/context' },
242 { id: 'limits', icon: 'gauge', label: 'See limits', text: '/limits' },
243 { id: 'resume', icon: 'undo', label: 'Resume a chat', text: '/resume' },
244 { id: 'memory', icon: 'brain', label: 'Edit memory', text: '/memory' },
245 { id: 'model', icon: 'sliders', label: 'Switch model', text: '/model' },
246 { id: 'explore', icon: 'search', label: 'Explore code', text: '@Explore' },
247 { id: 'help', icon: 'help', label: 'Help', text: '/help' },
248 ],
249 kinds: { command: 'command', agent: 'agent' },
250 origins: { default: 'default', user: 'yours', project: 'project' },
251 shown: 'Launchpad shortcuts menu.',
252 empty: 'No shortcuts available. /pad configuration picks the menu.',
253 off: 'Launchpad off: the menu no longer shows when a session starts or on /pad. /pad on turns it back on.',
254 on: 'Launchpad on: the menu shows when a session starts, after /clear and on /pad.',
255 isOff: 'The launchpad is off. /pad on turns it back on.',
256 added: (n, label) => `Shortcut ${n} added: ${label}.`,
257 removed: label => `Shortcut removed: ${label}.`,
258 reset: 'Shortcuts back to the defaults.',
259 projectRemove: 'That shortcut comes from the project. Edit .claude/launchpad.json to drop it.',
260 noSuch: n => `There is no shortcut ${n}. /pad list shows the numbers.`,
261 help: [
262 '/pad show the menu',
263 '/pad panel open the panel: model, effort, mods and shortcuts (or ◆ pad on the hint line)',
264 '/pad configuration open the pane to pick and order the shortcuts',
265 '/pad list list the shortcuts',
266 '/pad add 📊 Name | /command a shortcut that runs a command or skill',
267 '/pad add Name | @agent a shortcut that calls an agent',
268 '/pad remove 3 drop shortcut 3',
269 '/pad reset back to the default shortcuts',
270 '/pad off | on turn the menu off or on',
271 '/pad place header the menu as a card under the header (the default)',
272 '/pad place prompt the menu in a row right above the prompt, always at hand',
273 '/pad place pane the menu in a pane, a tab like those of /limits and /watch',
274 `Only installed commands, skills and agents, up to ${MAX_SHOWN} shortcuts.`,
275 ].join('\n'),
276 badAdd: 'Use: /pad add 📊 Name | /command or /pad add Name | @agent',
277 missing: text => `${text} is not installed in this session. /pad configuration shows what is.`,
278 full: `The menu already has ${MAX_SHOWN} shortcuts. Drop one with /pad remove or in the pane.`,
279 already: text => `${text} is already in the menu.`,
280 failed: what => `Could not run: ${what}`,
281 more: n => `+${n} in /pad list`,
282 placed: {
283 header: 'The menu is a card under the header again: when a session starts, after /clear and on /pad.',
284 prompt: 'The menu now sits in a row right above the prompt, always at hand.',
285 pane: 'The menu now opens in a pane, a tab like those of /limits and /watch.',
286 },
287 badPlace: 'Use: /pad place header | prompt | pane',
288 inBand: 'The menu is in the row above the prompt. /pad place header brings the card back.',
289 menuPane: 'Shortcuts',
290 settings: '⋯ configure',
291 useAgent: (name, task) => `Use the ${name} agent to ${task || '[task]'}`,
292 ask2: {
293 place: 'Where should the menu go?',
294 places: { header: 'Under the header', prompt: 'Above the prompt', pane: 'In a pane' },
295 placeNotes: {
296 header: {
297 description: 'A card under the header, when a session starts and after /clear. It scrolls up with the chat.',
298 preview: ['╭ ✻ What do you want to do? ─────╮', '│ ▐ Compact chat ▌ ▐ See context ▌│', '│ ▐ See limits ▌ ▐ Resume ▌ │', '╰────────────────────────────────╯', '', ' ... the chat goes on here ...', '', '╭────────────────────────────────╮', '│ > │', '╰────────────────────────────────╯'].join('\n'),
299 },
300 prompt: {
301 description: 'A row right above the prompt box, always at hand.',
302 preview: [' ... the chat ...', '', ' 5h ██░░░ 12% (other mods\' bands)', ' ✻ Compact See context Resume ⋯', '╭────────────────────────────────╮', '│ > │', '╰────────────────────────────────╯'].join('\n'),
303 },
304 pane: {
305 description: 'A pane beside the chat, a tab like /limits and /watch. Esc closes it.',
306 preview: [' ... the chat ... │ Shortcuts', ' │ ✻ What do you want', ' │ to do?', ' │ ▐ Compact chat ▌', ' │ ▐ See context ▌', '╭─────────────────────╮│ ▐ Resume ▌', '│ > ││', '╰─────────────────────╯│ Esc closes'].join('\n'),
307 },
308 },
309 current: '(current)',
310 reset: 'Back to the default shortcuts? The ones you added go.',
311 resetYes: 'Back to the defaults',
312 resetNote: "Back to the 8 default shortcuts. The ones you added go; the project's stay.",
313 cancel: 'Cancel',
314 cancelNote: 'Nothing changes.',
315 },
316 panel: {
317 entry: '◆ pad',
318 title: 'Panel',
319 hint: "This session's model and effort, the installed mods and the shortcuts.",
320 controls: 'Controls',
321 model: 'model ',
322 effort: 'effort',
323 effortUnknown: "effort: the model's own, until the first request",
324 warn: p => `! 5h at ${p}%: opus and max use the window faster`,
325 mods: 'Mods',
326 noMods: 'No mod from this collection installed. To install (the command goes into the prompt; Enter installs):',
327 isOn: '● on',
328 isOff: '○ off',
329 turnOn: 'turn on',
330 turnOff: 'turn off',
331 shortcuts: 'Shortcuts',
332 close: 'Close',
333 },
334 modsSection: {
335 title: 'Mods',
336 missing: 'Missing (the command goes into the prompt; Enter installs):',
337 install: plugin => `install ${plugin}`,
338 allInstalled: 'Every mod of this collection is installed.',
339 back: 'back to the panel',
340 },
341 pane: {
342 title: 'Launchpad',
343 hint: `Only commands, skills and agents installed in this session show. Up to ${MAX_SHOWN} in the menu.`,
344 menu: n => `In the menu (${n}/${MAX_SHOWN})`,
345 project: 'From the project (.claude/launchpad.json)',
346 add: 'Add',
347 filter: 'Filter',
348 placeholder: 'command, skill or agent name',
349 plus: '+ add',
350 remove: 'remove',
351 gone: '(not installed)',
352 full: 'The menu is full. Drop a shortcut to add another.',
353 none: 'Nothing by that name.',
354 range: (from, to, of) => `${from}–${to} of ${of}`,
355 up: '▲ up',
356 down: '▼ down',
357 reset: 'Restore defaults',
358 close: 'Close',
359 },
360 },
361}
362
363/**
364 * The language: the `language` option when it names one; on `auto` (or none), Portuguese when the
365 * system's LANG is Portuguese (`pt_BR.UTF-8`, `pt_PT`, `pt`), English otherwise and when unset.
366 */
367export const langOf = (option: unknown, systemLang?: string | null): Lang =>
368 option === 'en' || option === 'pt-BR' ? option : /^pt([_.@-]|$)/i.test(systemLang ?? '') ? 'pt-BR' : 'en'
369/**
370 * The icon style: the `icons` option when it names one; on `auto` (or none), symbols in a
371 * JetBrains IDE's terminal (TERMINAL_EMULATOR=JetBrains-JediTerm), which gives many emoji one
372 * column where Claude Code counts two, and emoji everywhere else.
373 */
374export const styleOf = (option: unknown, terminal?: string | null): IconStyle =>
375 option === 'emoji' || option === 'symbol' ? option : /^JetBrains/i.test(terminal ?? '') ? 'symbol' : 'emoji'
376
377/** `/x` runs a command or skill, `@x` calls an agent; anything else is no button. */
378export const kindOf = (text: string): Kind | null => (/^\/[^\s/]/.test(text) ? 'command' : /^@[^\s@]/.test(text) ? 'agent' : null)
379
380const BLANK = /\[[^\]\n]+\]/
381
382/** The first `[blank]` in a text, as offsets, so the prompt can mark what to replace. */
383export const blankIn = (text: string): { start: number; end: number } | null => {
384 const m = BLANK.exec(text)
385 return m ? { start: m.index, end: m.index + m[0].length } : null
386}
387
388/** A command button's name and arguments: `/compact focus` is `compact` and `focus`. */
389export const commandOf = (text: string): { command: string; args: string } => {
390 const [name = '', ...rest] = text.replace(/^\//, '').trim().split(/\s+/)
391 return { command: name, args: rest.join(' ') }
392}
393
394/** An agent button's type: `@Explore` is `Explore`. */
395export const agentOf = (text: string): string => text.replace(/^@/, '').trim().split(/\s+/)[0] ?? ''
396
397/** What an agent button asks after the agent's name: `@revisor review [file]` is `review [file]`. */
398export const agentTask = (text: string): string => text.replace(/^@/, '').trim().split(/\s+/).slice(1).join(' ')
399
400/** What a button or a target stands for, the same spelling for both: `command:compact`, `agent:Explore`. */
401export const keyOf = (kind: Kind, name: string) => `${kind}:${name}`
402export const padKey = (p: Pad) => keyOf(p.kind, p.kind === 'command' ? commandOf(p.text).command : agentOf(p.text))
403
404/** How a target is written on a button: `/compact`, `@Explore`. */
405export const spell = (t: Target) => (t.kind === 'command' ? `/${t.name}` : `@${t.name}`)
406
407export const defaults = (lang: Lang): Pad[] =>
408 WORDS[lang].defaults.map(d => ({ ...d, kind: kindOf(d.text)!, origin: 'default' as const }))
409
410/** A saved list in the current language: a default button takes its label from `defaults(lang)`. */
411export const localize = (list: Pad[], lang: Lang): Pad[] => {
412 const labels = new Map(defaults(lang).map(d => [d.id, d.label]))
413 return list.map(p => (p.origin === 'default' && labels.has(p.id) ? { ...p, label: labels.get(p.id)! } : p))
414}
415
416/** A command's own icon in COMMAND_ICONS, or null; own keys only, so `constructor` is none. */
417export const commandIcon = (name: string): string | null => (Object.hasOwn(COMMAND_ICONS, name) ? COMMAND_ICONS[name]! : null)
418
419/** The icon a target gets when the pane adds it: an agent's, a command's own, else by where it comes from. */
420export const iconFor = (t: Target) =>
421 t.kind === 'agent' ? 'agent' : (commandIcon(t.name) ?? (Object.hasOwn(SOURCE_ICONS, t.source) ? SOURCE_ICONS[t.source]! : 'spark'))
422
423/**
424 * Whether a command's argument hint names only optional arguments: every part in square
425 * brackets, as `/clear [name]` or `/autocompact [auto|<tokens>]`. Such a command runs bare.
426 */
427export const isOptionalHint = (hint: string | undefined) => /^\s*(\[[^\]]*\]\s*)+$/.test(hint ?? '')
428
429/** Where the menu shows: the option or /pad place when it names one, else under the header. */
430export const placementOf = (v: unknown): Placement => (v === 'prompt' || v === 'pane' || v === 'header' ? v : 'header')
431
432/**
433 * A command button's text without the blanks an optional hint gave it: `/clear [name]` back to
434 * `/clear`, so it runs. Any other text, and an agent's, as it is.
435 */
436export const unblank = (text: string, hint: string | undefined) => {
437 if (!isOptionalHint(hint)) return text
438 const { command, args } = commandOf(text)
439 return sameText(args, blanksOf(hint)) ? `/${command}` : text
440}
441
442/**
443 * A command's argument hint as blanks to fill: `[level]` and `[a] [b]` stay, `<file>` becomes
444 * `[file]`, a bare `message` becomes `[message]`; empty when there is no hint.
445 */
446export const blanksOf = (hint: string | undefined): string => {
447 const h = (hint ?? '').trim()
448 if (!h) return ''
449 if (h.includes('[')) return h
450 return /<[^>]+>/.test(h) ? h.replace(/<([^>]+)>/g, '[$1]') : `[${h}]`
451}
452
453/**
454 * A button for a target the pane lists. A command whose hint asks for an argument gets it as
455 * blanks, so a press puts it in the prompt to finish rather than running it bare. A hint of
456 * optional arguments only gives none: the command runs as it is.
457 */
458export const padFor = (t: Target, id: string, hint?: string): Pad => {
459 const blanks = t.kind === 'command' && !isOptionalHint(hint) ? blanksOf(hint) : ''
460 return {
461 id,
462 icon: iconFor(t),
463 label: t.name.slice(0, MAX_LABEL),
464 text: blanks ? `${spell(t)} ${blanks}` : spell(t),
465 kind: t.kind,
466 origin: 'user',
467 }
468}
469
470/** Whether a name is one of the built-in icons; own keys only, so `constructor` is none. */
471export const isIcon = (name: string) => Object.hasOwn(ICONS, name)
472
473/**
474 * The icon a word of /pad add names, or null: a built-in name written `:chart:`, or a glyph (any
475 * token that starts with no letter or digit). A bare word is part of the label, so `search docs`
476 * is a label and not the icon `search`.
477 */
478const iconIn = (token: string): string | null => {
479 const named = /^:([\w-]+):$/.exec(token)?.[1]
480 if (named) return isIcon(named) ? named : null
481 return /^[^\p{L}\p{N}]/u.test(token) ? token : null
482}
483
484/** `/pad add 📊 Name | /command` or `| @agent` (icon optional) as a button, or null. */
485export const parseAdd = (args: string, id: string): Pad | null => {
486 const bar = args.indexOf('|')
487 if (bar < 0) return null
488 const left = args.slice(0, bar).trim()
489 const text = args.slice(bar + 1).trim().slice(0, MAX_TEXT)
490 const [first = '', ...rest] = left.split(/\s+/)
491 const icon = rest.length > 0 ? iconIn(first) : null
492 const label = (icon ? rest.join(' ') : left).trim().slice(0, MAX_LABEL)
493 const kind = kindOf(text)
494 if (!/[\p{L}\p{N}]/u.test(label) || !kind) return null
495 return { id, icon: icon ?? (kind === 'agent' ? 'agent' : (commandIcon(commandOf(text).command) ?? 'tool')), label, text, kind, origin: 'user' }
496}
497
498/**
499 * The project's `.claude/launchpad.json`: `{ "buttons": [{ "icon", "label", "text" }] }`, each
500 * text a `/command` or an `@agent`. It comes from the repository, so a press only puts the text in
501 * the prompt and the person reads it before pressing Enter. Nothing from the file runs on a press.
502 */
503export const parseProject = (raw: string | null | undefined): Pad[] => {
504 if (!raw) return []
505 let data: unknown
506 try {
507 data = JSON.parse(raw)
508 } catch {
509 return []
510 }
511 const list = (data as { buttons?: unknown })?.buttons
512 if (!Array.isArray(list)) return []
513 const out: Pad[] = []
514 for (const b of list) {
515 if (out.length >= MAX_PROJECT) break
516 const label = typeof b?.label === 'string' ? b.label.trim().slice(0, MAX_LABEL) : ''
517 const text = typeof b?.text === 'string' ? b.text.trim().slice(0, MAX_TEXT) : ''
518 const kind = kindOf(text)
519 if (!label || !kind) continue
520 const icon = typeof b?.icon === 'string' && b.icon.trim() ? b.icon.trim().slice(0, 8) : 'table'
521 out.push({ id: `project:${out.length}`, icon, label, text, kind, origin: 'project' })
522 }
523 return out
524}
525
526/** An agent file's type: the `name:` in its frontmatter, else the file name less `.md`. */
527export const agentName = (file: string, raw: string | null | undefined): string => {
528 const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(raw ?? '')?.[1] ?? ''
529 const name = /^name:\s*["']?([^"'\r\n]+?)["']?\s*$/m.exec(front)?.[1]
530 return (name ?? file.replace(/\.md$/i, '')).trim()
531}
532
533/**
534 * A saved list as buttons: entries with no id, label or button text are dropped, and a missing
535 * icon or origin takes the kind's icon and `user`, so nothing malformed reaches the drawing.
536 */
537export const asPads = (v: unknown): Pad[] | null => {
538 if (!Array.isArray(v)) return null
539 const out: Pad[] = []
540 for (const p of v) {
541 if (typeof p?.id !== 'string' || typeof p?.label !== 'string' || typeof p?.text !== 'string') continue
542 const kind = kindOf(p.text)
543 if (!kind) continue
544 const icon = typeof p.icon === 'string' && p.icon ? p.icon : kind === 'agent' ? 'agent' : 'tool'
545 const origin: Origin = p.origin === 'default' || p.origin === 'project' ? p.origin : 'user'
546 out.push({ id: p.id, icon, label: p.label, text: p.text, kind, origin })
547 }
548 return out
549}
550
551/** Whether two button texts run the same thing: the same words, whatever the spaces. */
552export const sameText = (a: string, b: string) => a.trim().split(/\s+/).join(' ') === b.trim().split(/\s+/).join(' ')
553
554/** Keeps the buttons whose command, skill or agent this session has. */
555export const available = (pads: Pad[], catalog: readonly Target[]): Pad[] => {
556 const have = new Set(catalog.map(t => keyOf(t.kind, t.name)))
557 return pads.filter(p => have.has(padKey(p)))
558}
559
560/** The person's buttons that work here, then the project's: what the menu shows and numbers. */
561export const shownOf = (menu: Pad[], project: Pad[], catalog: readonly Target[]): Pad[] => available([...menu, ...project], catalog)
562
563/** Targets not yet in the menu that match the filter, commands first, then agents, by name. */
564export const matches = (catalog: readonly Target[], menu: Pad[], filter: string): Target[] => {
565 const taken = new Set(menu.map(padKey))
566 const q = filter.trim().toLowerCase().replace(/^[/@]/, '')
567 return catalog
568 .filter(t => !taken.has(keyOf(t.kind, t.name)))
569 .filter(t => !q || t.name.toLowerCase().includes(q) || t.description.toLowerCase().includes(q))
570 .sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === 'command' ? -1 : 1))
571}
572
573/** The window of `rows` items a list of `total` shows from `offset`, kept inside the list. */
574export const windowOf = (total: number, offset: number, rows: number): { start: number; end: number } => {
575 const size = Math.max(1, rows)
576 const start = Math.max(0, Math.min(offset, total - size))
577 return { start, end: Math.min(total, start + size) }
578}
579
580/** The list with the button `id` moved by `delta` places; unchanged where it cannot move. */
581export const moveId = (list: readonly Pad[], id: string, delta: number): Pad[] => move(list, list.findIndex(p => p.id === id), delta)
582
583/** The list with item `i` moved by `delta` places; unchanged where it cannot move. */
584export const move = <T>(list: readonly T[], i: number, delta: number): T[] => {
585 const j = i + delta
586 if (i < 0 || i >= list.length || j < 0 || j >= list.length) return [...list]
587 const out = [...list]
588 ;[out[i], out[j]] = [out[j]!, out[i]!]
589 return out
590}
591
592export const glyph = (icon: string, style: IconStyle): string => {
593 return isIcon(icon) ? ICONS[icon]![style] : icon
594}
595
596const EMOJI = /\p{Emoji_Presentation}/u
597const PICTO = /\p{Extended_Pictographic}/u
598
599/**
600 * Cells a string takes in a terminal: two for an emoji drawn as one (📁, or ✏️ with its variation
601 * selector), one for a symbol drawn as text (⚙, ✉) and the rest, none for the selectors.
602 */
603export const cells = (s: string): number => {
604 const chars = [...s]
605 let n = 0
606 chars.forEach((ch, i) => {
607 if (ch === '\uFE0F' || ch === '\u200D') return
608 n += EMOJI.test(ch) || (PICTO.test(ch) && chars[i + 1] === '\uFE0F') ? 2 : 1
609 })
610 return n
611}
612
613/**
614 * The icon a button draws: a command button saved with an origin's generic icon (🔧 ✨ 🔌 🧩) takes
615 * its command's own, so buttons added before COMMAND_ICONS had a row get it too.
616 */
617export const iconOf = (p: Pad): string =>
618 p.kind === 'command' && GENERIC.includes(p.icon) ? (commandIcon(commandOf(p.text).command) ?? p.icon) : p.icon
619
620/**
621 * A button's icon and label. With symbols, an icon of the person's own that is not one cell wide
622 * (an emoji from /pad add or the project file) gives way to the symbol of the button's kind, so
623 * the columns stay aligned.
624 */
625export const buttonLabel = (p: Pad, style: IconStyle) => {
626 const own = iconOf(p)
627 const icon = style === 'symbol' && !isIcon(own) && cells(own) !== 1 ? (p.kind === 'agent' ? 'agent' : 'tool') : own
628 return `${glyph(icon, style)} ${p.label}`
629}
630
631/**
632 * A tile's label padded to the cells inside its border, a space each side: the whole row between
633 * the side borders is the button, so a press anywhere on it counts.
634 */
635export const tileLabel = (label: string, inner: number): string => {
636 const room = Math.max(cells(label) + 2, inner)
637 return ` ${label}${' '.repeat(room - 1 - cells(label))}`
638}
639
640/** Columns of equal width that fit `columns` cells: the cell width and the rows of buttons. */
641export const layout = (pads: Pad[], style: IconStyle, columns: number, gap = 3): { width: number; rows: Pad[][] } => {
642 const width = Math.max(1, ...pads.map(p => cells(buttonLabel(p, style)))) + gap
643 const per = Math.max(1, Math.floor(Math.max(columns, width) / width))
644 const rows: Pad[][] = []
645 for (let i = 0; i < pads.length; i += per) rows.push(pads.slice(i, i + per))
646 return { width, rows }
647}
648
649/** /pad list: every button, numbered, with what it runs, its kind and where it comes from. */
650export const listText = (pads: Pad[], lang: Lang, style: IconStyle): string => {
651 const w = WORDS[lang]
652 if (pads.length === 0) return w.empty
653 return pads.map((p, i) => `${i + 1}. ${buttonLabel(p, style)} ${p.text} (${w.kinds[p.kind]}, ${w.origins[p.origin]})`).join('\n')
654}
655
656/** Effort levels, in the order the panel's chips show them. */
657export const EFFORTS: readonly Effort[] = ['low', 'medium', 'high', 'xhigh', 'max']
658
659/** The models the panel offers when the engine lists none. */
660export const FALLBACK_MODELS = ['haiku', 'sonnet', 'opus']
661
662/** The chips the 5-hour warning marks, and from what share of the window. */
663export const EXPENSIVE = ['opus', 'max']
664export const WARN_AT = 70
665
666/**
667 * This collection's mods besides the launchpad: what the panel's Mods section looks for. test-hud
668 * is left out on purpose: it is for developers, and it leaves this collection after plan v2.
669 */
670export const MODS: readonly ModInfo[] = [
671 { plugin: 'limits-meter', command: 'limits', toggles: false },
672 { plugin: 'allowlist-coach', command: 'allowlist', toggles: false },
673 { plugin: 'agent-watch', command: 'watch', toggles: false },
674 { plugin: 'plain-view', command: 'plain-view', toggles: true },
675]
676
677/** The marketplace the collection installs from. */
678export const MARKETPLACE = 'ice-lfernandes/claude-code-mods'
679
680/** What installs a mod: the text the Mods section puts in the prompt. */
681export const installText = (plugin: string) => `/plugin install ${plugin} --marketplace ${MARKETPLACE}`
682
683/**
684 * The mods this session has and the ones it lacks: a mod counts when a command of its name is
685 * listed, from that plugin when the engine says which.
686 */
687export const modsOf = (catalog: readonly Target[], mods: readonly ModInfo[] = MODS): { installed: ModInfo[]; missing: ModInfo[] } => {
688 const has = (m: ModInfo) => catalog.some(t => t.kind === 'command' && t.name === m.command && (!t.plugin || t.plugin === m.plugin))
689 return { installed: mods.filter(has), missing: mods.filter(m => !has(m)) }
690}
691
692/**
693 * The model chips: the plain aliases of the `/config` model row's options (`sonnet`, not
694 * `default` or `sonnet[1m]`), at most five; the fallback when the row lists none.
695 */
696export const modelsOf = (options: readonly string[] | undefined): string[] => {
697 const plain = (options ?? []).map(o => o.trim().toLowerCase()).filter(o => /^[a-z][a-z0-9.-]*$/.test(o) && o !== 'default')
698 const unique = [...new Set(plain)].slice(0, 5)
699 return unique.length ? unique : [...FALLBACK_MODELS]
700}
701
702/** The chip the session's model is: the first whose name the model's id holds (`claude-opus-5-5`: `opus`). */
703export const activeModel = (model: string, chips: readonly string[]): string | null => {
704 const id = model.toLowerCase()
705 return chips.find(c => id === c || id.includes(c)) ?? null
706}
707
708/** A request's effort as a level; null for none or a number of tokens. */
709export const effortOf = (v: unknown): Effort | null => (typeof v === 'string' && (EFFORTS as readonly string[]).includes(v) ? (v as Effort) : null)
710
711/** The share of the 5-hour window used, from the session's rate limits; null without a reading. */
712export const fiveHourOf = (limits: readonly { kind: string; percentUsed: number }[] | undefined): number | null => {
713 const hit = (limits ?? []).find(l => l.kind === 'five_hour')
714 return hit ? hit.percentUsed : null
715}
716
717/** Whether a chip gets the 5-hour warning: an expensive one, with the window at WARN_AT or more. */
718export const isWarned = (chip: string, fiveHour: number | null) => fiveHour !== null && fiveHour >= WARN_AT && EXPENSIVE.includes(chip)
719
720/**
721 * A mod's on/off state from the `/config` rows: its `<plugin>.enabled` option; null when the mod
722 * does not toggle or has no such row.
723 */
724export const toggleOf = (m: ModInfo, rows: readonly { key: string; value: unknown }[]): boolean | null => {
725 if (!m.toggles) return null
726 const row = rows.find(r => r.key === `${m.plugin}.enabled`)
727 return typeof row?.value === 'boolean' ? row.value : null
728}
729
730/** A mod's button label: its command's icon and the plugin's name, the same in every language. */
731export const modLabel = (m: ModInfo, style: IconStyle) => `${glyph(commandIcon(m.command) ?? 'puzzle', style)} ${m.plugin}`
732
733/** The shortcuts the panel shows: the menu's, less `/model`, which the chips replace. */
734export const panelShortcuts = (pads: readonly Pad[]) => pads.filter(p => !(p.kind === 'command' && commandOf(p.text).command === 'model'))
735
736/** The chip on the launchpad's own questions in the engine's dialog: how its render hook knows them. */
737export const ASK_HEADER = '◆ pad'
738
739type AskQuestion = { question?: unknown; header?: unknown; multiSelect?: unknown; options?: { label?: unknown; description?: unknown; preview?: unknown }[] }
740
741/**
742 * One of the launchpad's questions with more to go on: what each choice does and, for a place, a
743 * sketch of it. The labels stay as asked, so the answer still matches them. Any other question,
744 * and an option the launchpad does not know, as it is.
745 */
746export const dressQuestion = (q: AskQuestion, lang: Lang): AskQuestion => {
747 if (q.header !== ASK_HEADER || !Array.isArray(q.options)) return q
748 const w = WORDS[lang].ask2
749 const notes = new Map<string, { description: string; preview?: string }>([
750 ...(['header', 'prompt', 'pane'] as const).flatMap(p => [
751 [w.places[p], w.placeNotes[p]] as const,
752 [`${w.places[p]} ${w.current}`, w.placeNotes[p]] as const,
753 ]),
754 [w.resetYes, { description: w.resetNote }],
755 [w.cancel, { description: w.cancelNote }],
756 ])
757 return { ...q, options: q.options.map(o => ({ ...o, ...(typeof o.label === 'string' ? notes.get(o.label) : undefined) })) }
758}
759hooks/icons.ts 89 lines1// launchpad's icon map. Kept by the mod's owner: it is not a plugin option and no /pad verb
2// changes it. To re-icon something, change one line here.
3//
4// ICONS key → an emoji for most terminals and a one-cell symbol for those that draw
5// emoji badly (the `icons` option picks one). An emoji here is always one with
6// default emoji presentation (📦, not 🗜️): those that need U+FE0F take one or two
7// columns depending on the terminal, and break the tiles. A symbol is one cell.
8// tests/icons.test.ts checks both.
9// COMMAND_ICONS command name → key: the icon a command gets as a button, in the panel's Mods
10// section, on the menu and in /pad configuration.
11// SOURCE_ICONS where a command comes from → key: the icon of a command with no row above.
12//
13// Keys are also what `/pad add :chart: ...` takes, so renaming one breaks buttons people saved.
14
15export const ICONS: Record<string, { emoji: string; symbol: string }> = {
16 // this collection's mods
17 gauge: { emoji: '⏳', symbol: '◔' },
18 shield: { emoji: '🔐', symbol: '⊘' },
19 agents: { emoji: '👀', symbol: '◈' },
20 scroll: { emoji: '📜', symbol: '§' },
21 // commands
22 compress: { emoji: '📦', symbol: '⇲' },
23 chart: { emoji: '📊', symbol: '▥' },
24 undo: { emoji: '⏪', symbol: '↺' },
25 brain: { emoji: '🧠', symbol: '◎' },
26 sliders: { emoji: '🔀', symbol: '≡' },
27 help: { emoji: '❓', symbol: '?' },
28 search: { emoji: '🔍', symbol: 'Δ' },
29 broom: { emoji: '🧹', symbol: '⌫' },
30 reload: { emoji: '🔄', symbol: '↻' },
31 money: { emoji: '💰', symbol: '$' },
32 doctor: { emoji: '🩺', symbol: '+' },
33 doc: { emoji: '📄', symbol: '¶' },
34 folder: { emoji: '📁', symbol: '▤' },
35 // by origin
36 tool: { emoji: '🔧', symbol: '⚙' },
37 puzzle: { emoji: '🧩', symbol: '⊞' },
38 plug: { emoji: '🔌', symbol: '⌁' },
39 spark: { emoji: '✨', symbol: '✦' },
40 agent: { emoji: '🤖', symbol: '◉' },
41 // for /pad add and .claude/launchpad.json
42 pen: { emoji: '📝', symbol: '✎' },
43 mail: { emoji: '📧', symbol: '✉' },
44 table: { emoji: '📋', symbol: '▦' },
45}
46
47export const COMMAND_ICONS: Record<string, string> = {
48 // this collection's mods
49 limits: 'gauge',
50 allowlist: 'shield',
51 watch: 'agents',
52 'plain-view': 'scroll',
53 // built-in commands
54 clear: 'broom',
55 compact: 'compress',
56 context: 'chart',
57 usage: 'chart',
58 cost: 'money',
59 resume: 'undo',
60 rewind: 'undo',
61 memory: 'brain',
62 model: 'sliders',
63 help: 'help',
64 init: 'doc',
65 export: 'doc',
66 review: 'search',
67 'security-review': 'shield',
68 permissions: 'shield',
69 config: 'tool',
70 doctor: 'doctor',
71 mcp: 'plug',
72 agents: 'agent',
73 plugin: 'puzzle',
74 'reload-plugins': 'reload',
75 'add-dir': 'folder',
76}
77
78export const SOURCE_ICONS: Record<string, string> = {
79 builtin: 'tool',
80 plugin: 'puzzle',
81 mcp: 'plug',
82 user: 'spark',
83 project: 'spark',
84 agent: 'agent',
85}
86
87/** The icons a button gets from where its command comes from: a saved one with these may take a better one. */
88export const GENERIC = ['tool', 'spark', 'plug', 'puzzle']
89types/index.d.ts 74 lines1/** What a button does when pressed: run a command or skill, or call an agent. */
2export type Kind = 'command' | 'agent'
3
4/** Where a button comes from: built in, the person's own, or the project's .claude/launchpad.json. */
5export type Origin = 'default' | 'user' | 'project'
6
7export type Lang = 'pt-BR' | 'en'
8
9export type IconStyle = 'emoji' | 'symbol'
10
11/** Where the menu shows: a card under the header, a band above the prompt, or its own pane. */
12export type Placement = 'header' | 'prompt' | 'pane'
13
14export type Pad = {
15 id: string
16 /** A key of ICONS (`folder`) or a glyph of the person's own (`🧾`). */
17 icon: string
18 label: string
19 /** `/name args` for a command or skill, `@type` for an agent. */
20 text: string
21 kind: Kind
22 origin: Origin
23}
24
25/** A command, skill or agent this session has: what a button may point at. */
26export type Target = {
27 kind: Kind
28 /** Without the slash or the at sign. */
29 name: string
30 description: string
31 /** Where a command comes from (`builtin`, `plugin`, `user`, `mcp`); `agent` for an agent. */
32 source: string
33 /** The plugin that added a command, when the engine knows. */
34 plugin?: string
35}
36
37/** A reasoning effort level, as `/effort` takes it. */
38export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
39
40/** One of this collection's mods, as the panel's Mods section knows it. */
41export type ModInfo = {
42 /** The plugin's name, as `/plugin install` takes it. */
43 plugin: string
44 /** Its command, without the slash: what opens its pane. */
45 command: string
46 /** Whether its command takes `on` and `off`, its state in the `<plugin>.enabled` option. */
47 toggles: boolean
48}
49
50declare module 'claude-code' {
51 interface PluginState {
52 launchpad: {
53 /** The person's buttons in order, at most MAX_SHOWN: the defaults until they change them. */
54 menu: Pad[]
55 /** The buttons of the project's .claude/launchpad.json. */
56 project: Pad[]
57 /** The commands, skills and agents this session has, read when the menu or the pane loads. */
58 catalog: Target[]
59 /** The pane's filter over the catalog. */
60 filter: string
61 /** The first catalog row the pane's list shows: moved by its arrows and the wheel. */
62 offset: number
63 /** True after /pad off: no menu at the start, after /clear or on /pad, until /pad on. */
64 isOff: boolean
65 /** Where the menu shows: /pad place, else the `placement` option. */
66 placement: Placement
67 /** The session's model as the engine names it (`claude-opus-5-5`): the panel's active chip. */
68 model: string
69 /** The effort of the last model request; null until the first one, or for a model without effort. */
70 effort: Effort | null
71 }
72 }
73}
74