An extra-mods menu in the bottom corner: Zen mode with a progress band, Claude Code themes from terminalcolors.com, model, effort and permission mode controls…

<h1 align="center"><img src="docs/screenshots/claudemods_icon.png" alt="Claude Mods" width="36" height="36" valign="middle"> Claude Mods</h1>
Hides all tool calls and giant code blocks and shows just a progress bar and small progress reports.
Pick a style and a color in the Zen tab. Prism (the default) gives every cell its own color, flowing along the bar with a glint passing through. Classic keeps flat colors.
Prism · green
<img src="docs/screenshots/zen-prism-green.gif" alt="Prism style, green band: the colors flow along the bar as the steps finish" width="560">
Prism · rainbow
<img src="docs/screenshots/zen-prism-rainbow.gif" alt="Prism style, rainbow band: the colors flow across the whole wheel" width="560">
Classic · green
<img src="docs/screenshots/zen-classic-green.gif" alt="Classic style, green band: one flat color" width="560">
Classic · rainbow
<img src="docs/screenshots/zen-classic-rainbow.gif" alt="Classic style, rainbow band: flat color blocks" width="560">
Band colors: blue, dark, light, green, rainbow or custom.
<img src="docs/screenshots/zen.png" alt="Zen tab with the Band style chips" width="320">
Applies any of 100+ themes from terminalcolors.com with one click.
<img src="docs/screenshots/theme-demo.gif" alt="Clicking through themes in the Theme tab: the whole session recolors live" width="720">
Switches the model and effort, and picks the mode new sessions start in.
<img src="docs/screenshots/mode-demo.png" alt="Model switched to Sonnet and effort to high from the Mode tab, mid-session" width="720">
<img src="docs/screenshots/mode.png" alt="Mode tab" width="360">
Shows model, folder, branch, context, 5h/7d limits and cache state on one row.
<img src="docs/screenshots/status-demov2.png" alt="The status line under the prompt, with a background shell running" width="720">
<img src="docs/screenshots/status.png" alt="Status tab" width="360">
The sidebar speaks English and Português. Keys: Tab moves, Enter selects, Esc closes.
Needs Claude Code 2.1.292 or newer.
claude plugin marketplace add Jhonatan-de-Souza/ClaudeMods
claude plugin install extra-mods@jdsjh-mods --scope user
Run /reload-plugins (or start a new session), then click ◆ extra-mods ▲ at the bottom right, or type /tools.
To update: claude plugin marketplace update jdsjh-mods && claude plugin update extra-mods@jdsjh-mods
zen_progress tool to post its plan and update each step. [–] shrinks the band to one line. Band colors: blue, dark, light, green, rainbow or custom.~/.claude/extra-mods/themes/. The pick is written as ~/.claude/themes/extra-mods.json and set in ~/.claude/settings.json. Restart Claude Code once the first time; after that themes change live. The terminal background follows too, on Windows Terminal (for the session, then restored) and on terminals that take OSC colors (Ghostty, iTerm2, kitty, WezTerm, Terminal.app)./model. The effort level applies to every request and is remembered. A running session's permission mode changes with shift+tab; the pick here is saved as permissions.defaultMode.statusLine out of settings.json and puts it back when you turn it off. Background shells and monitors show on a second row; click it for /tasks.*.extra-mods.bak.Point your coding agent at this repository and ask it to install the mod. Steps for the agent (ask the user before step 4):
claude --version; it must be 2.1.292 or higher.claude plugin marketplace add Jhonatan-de-Souza/ClaudeMods.claude plugin install extra-mods@jdsjh-mods --scope user.statusline/statusline.py to ~/.claude/statusline.py and set "statusLine": { "type": "command", "command": "python ~/.claude/statusline.py", "refreshInterval": 2 } in ~/.claude/settings.json (python3 on macOS and Linux).claude plugin list shows extra-mods enabled, then tell the user to run /reload-plugins.On Windows, use forward slashes in paths when running in Git Bash.
claude --plugin-dir ./plugins/extra-mods
claude plugin validate ./plugins/extra-mods
claude plugin test ./plugins/extra-modshooks/register.tsx 1594 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren, RenderInput, Timer } from 'claude-code'
3
4import type { Effort, Lang, Panel, RateLimit, StatusSnapshot, ThemeEntry, ZenColors, ZenStep, ZenStyle, ZenTask, ZenTheme } from '../types'
5import { EFFORT_HEAT, EFFORTS, type Mode, MODELS, MODES, modeLabel, modelFamily } from './lib/modes'
6import { isLang, LANGS, modeName, phrase, type Phrase } from './lib/i18n'
7import {
8 backgroundPill,
9 BAR_WIDTH,
10 barFill,
11 cacheState,
12 colorFor,
13 type Detail,
14 fmtDuration,
15 fmtTokens,
16 LIMIT_LABELS,
17 showsReset,
18 STATUS_CYAN,
19 STATUS_GREEN,
20 STATUS_RED,
21 statsWidth,
22} from './lib/status'
23import {
24 findProfile,
25 matchAll,
26 oscFor,
27 type Palette,
28 parseJsonc,
29 targetProfile,
30 toPalette,
31 toClaudeTheme,
32 withProfileTheme,
33 mix,
34 WT_SCHEME,
35 type WtSettings,
36} from './lib/palette'
37import {
38 asStatus,
39 barCells,
40 colorsFor,
41 elapsed,
42 percentOf,
43 prismCells,
44 prismColor,
45 RAINBOW,
46 stepLabel,
47 visibleSteps,
48 ZEN_PROMPT,
49 ZEN_TOOL_DESCRIPTION,
50 ZEN_TOOL_NAME,
51 ZEN_TOOL_SCHEMA,
52 ZEN_STYLES,
53 ZEN_THEMES,
54} from './lib/zen'
55
56// Every value the drawings read. Settings worth keeping across sessions are
57// mirrored to $.store under the same key.
58const menu = atom({ plugin: 'extra-mods', key: 'menu' } as const, null)
59const zenOn = atom({ plugin: 'extra-mods', key: 'zenOn' } as const, false)
60const zenTheme = atom({ plugin: 'extra-mods', key: 'zenTheme' } as const, 'blue')
61const zenCustom = atom(
62 { plugin: 'extra-mods', key: 'zenCustom' } as const,
63 { bar: '#3b82f6', text: '#e2e8f0', border: '#3b82f6' } satisfies ZenColors,
64)
65const zenStyle = atom({ plugin: 'extra-mods', key: 'zenStyle' } as const, 'prism')
66const zenCollapsed = atom({ plugin: 'extra-mods', key: 'zenCollapsed' } as const, false)
67const task = atom({ plugin: 'extra-mods', key: 'task' } as const, null)
68const now = atom({ plugin: 'extra-mods', key: 'now' } as const, 0)
69const themes = atom({ plugin: 'extra-mods', key: 'themes' } as const, [])
70const themeName = atom({ plugin: 'extra-mods', key: 'themeName' } as const, null)
71const themeQuery = atom({ plugin: 'extra-mods', key: 'themeQuery' } as const, '')
72const themeScroll = atom({ plugin: 'extra-mods', key: 'themeScroll' } as const, 0)
73const themeStatus = atom({ plugin: 'extra-mods', key: 'themeStatus' } as const, '')
74const effort = atom({ plugin: 'extra-mods', key: 'effort' } as const, null)
75const mode = atom({ plugin: 'extra-mods', key: 'mode' } as const, null)
76const defaultMode = atom({ plugin: 'extra-mods', key: 'defaultMode' } as const, null)
77const isDownloading = atom({ plugin: 'extra-mods', key: 'isDownloading' } as const, false)
78const sessionEffort = atom({ plugin: 'extra-mods', key: 'sessionEffort' } as const, null)
79const sessionModel = atom({ plugin: 'extra-mods', key: 'sessionModel' } as const, null)
80const paneBg = atom({ plugin: 'extra-mods', key: 'paneBg' } as const, null)
81const defaultModeChosen = atom({ plugin: 'extra-mods', key: 'defaultModeChosen' } as const, false)
82const statusOn = atom({ plugin: 'extra-mods', key: 'statusOn' } as const, false)
83const status = atom({ plugin: 'extra-mods', key: 'status' } as const, null)
84const lastResponseAt = atom({ plugin: 'extra-mods', key: 'lastResponseAt' } as const, null)
85const lang = atom({ plugin: 'extra-mods', key: 'lang' } as const, 'en')
86const statusClock = atom({ plugin: 'extra-mods', key: 'statusClock' } as const, 0)
87
88// The menu's pane: a sidebar in the fullscreen layout, a block above the prompt otherwise.
89// Claude's progress tool, as the model calls it.
90const ZEN_TOOL = 'mcp__extra-mods__zen_progress'
91
92const PANE = 'claude-tools'
93const PANE_SIZE = { rows: 26, columns: 56 }
94// Used until the terminal's own background is known: just short of pure black.
95const PANE_BACKGROUND = '#0b0b0b'
96const MENU_NAME = 'extra-mods'
97// Room the engine's own mode label takes left of the hint row (⏵⏵ auto mode on · ).
98const MODE_LABEL_COLUMNS = 22
99// How far the stats row is pulled left so it starts under the mode label
100// (measured on `auto mode on ·`; the other labels differ by a few columns).
101const STATS_SHIFT = 17
102// The slug of the Claude Code theme the mod writes: ~/.claude/themes/extra-mods.json.
103const CLAUDE_THEME = 'extra-mods'
104
105// Windows Terminal's built-in schemes, by name: their backgrounds.
106const WT_BUILTIN_BACKGROUNDS: Record<string, string> = {
107 Campbell: '#0C0C0C',
108 'Campbell Powershell': '#012456',
109 'Dark+': '#1E1E1E',
110 Dimidium: '#141414',
111 'One Half Dark': '#282C34',
112 'One Half Light': '#FFFFFF',
113 Ottosson: '#000000',
114 'Solarized Dark': '#002B36',
115 'Solarized Light': '#FDF6E3',
116 'Tango Dark': '#000000',
117 'Tango Light': '#FFFFFF',
118 Vintage: '#000000',
119}
120
121// Each permission mode in the color Claude Code draws it with.
122const MODE_COLORS: Record<string, string> = {
123 default: 'text',
124 plan: 'planMode',
125 acceptEdits: 'autoAccept',
126 auto: 'warning',
127 dontAsk: 'warning',
128 bypassPermissions: 'error',
129}
130
131const SITE = 'https://terminalcolors.com'
132const HEX = /^#[0-9a-f]{6}$/i
133
134// Paths and platform --------------------------------------------------------
135
136async function homeDir($: EngineInterface) {
137 const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '.'
138 return home.replaceAll('\\', '/')
139}
140
141async function themesDir($: EngineInterface) {
142 return `${await homeDir($)}/.claude/extra-mods/themes`
143}
144
145async function isWindows($: EngineInterface) {
146 return (await $.env.get('OS')) === 'Windows_NT'
147}
148
149// Zen settings ---------------------------------------------------------------
150
151async function setZenOn($: EngineInterface, isOn: boolean) {
152 await update($, zenOn, () => isOn)
153 await $.store.set('zenOn', isOn)
154 if (!isOn) await update($, task, () => null)
155}
156
157async function setZenTheme($: EngineInterface, theme: ZenTheme) {
158 await update($, zenTheme, () => theme)
159 await $.store.set('zenTheme', theme)
160}
161
162async function setZenStyle($: EngineInterface, style: ZenStyle) {
163 await update($, zenStyle, () => style)
164 await $.store.set('zenStyle', style)
165 // A running band's clock speeds up or slows down to match.
166 if (ticker !== undefined) await startTicker($)
167}
168
169async function setZenColor($: EngineInterface, part: keyof ZenColors, value: string) {
170 if (!HEX.test(value.trim())) {
171 $.ui.toast(`${value} is not a hex color like #3b82f6`)
172 return
173 }
174 const colors = await update($, zenCustom, c => ({ ...c, [part]: value.trim() }))
175 await $.store.set('zenCustom', colors)
176}
177
178// Themes ---------------------------------------------------------------------
179
180async function fetchText($: EngineInterface, url: string) {
181 const res = await $.http.fetch(url)
182 if (!res.ok) throw new Error(`${res.status} for ${url}`)
183 return res.text
184}
185
186async function sayTheme($: EngineInterface, text: string) {
187 await update($, themeStatus, () => text)
188}
189
190// Reads the saved YAML files into the list the picker shows.
191async function indexThemes($: EngineInterface) {
192 const dir = await themesDir($)
193 const list: ThemeEntry[] = []
194 if (await $.fs.exists(dir)) {
195 for (const entry of await $.fs.list(dir)) {
196 if (entry.kind !== 'file' || !entry.name.endsWith('.yaml')) continue
197 const palette = toPalette(await $.fs.read(`${dir}/${entry.name}`))
198 if (palette !== null) list.push({ slug: entry.name.replace(/\.yaml$/, ''), name: palette.name, colors: palette.normal })
199 }
200 }
201 list.sort((a, b) => a.name.localeCompare(b.name))
202 await update($, themes, () => list)
203 return list
204}
205
206// Scrapes every theme page on terminalcolors.com and saves each theme's YAML.
207async function downloadThemes($: EngineInterface) {
208 const dir = await themesDir($)
209 await sayTheme($, 'Reading terminalcolors.com…')
210 const homePage = await fetchText($, `${SITE}/`)
211 const variants = new Set(matchAll(homePage, /href="(\/themes\/[\w-]+\/[\w-]+\/)"/g))
212 // A family page can list variants the home page leaves out.
213 for (const family of new Set(matchAll(homePage, /href="(\/themes\/[\w-]+\/)"/g))) {
214 try {
215 for (const v of matchAll(await fetchText($, SITE + family), /href="(\/themes\/[\w-]+\/[\w-]+\/)"/g)) {
216 variants.add(v)
217 }
218 } catch {}
219 }
220
221 const pages = [...variants]
222 let done = 0
223 let saved = 0
224 // Six downloads at a time.
225 for (let i = 0; i < pages.length; i += 6) {
226 await Promise.all(
227 pages.slice(i, i + 6).map(async page => {
228 try {
229 const yamlPath = matchAll(await fetchText($, SITE + page), /href="(\/downloads\/warp\/[^"]+\.ya?ml)"/g)[0]
230 if (yamlPath === undefined) return
231 const yaml = await fetchText($, SITE + yamlPath)
232 if (toPalette(yaml) === null) return
233 const file = yamlPath.split('/').pop()!.replace(/\.yml$/, '.yaml')
234 await $.fs.write(`${dir}/${file}`, yaml)
235 saved++
236 } catch {
237 } finally {
238 done++
239 }
240 }),
241 )
242 await sayTheme($, `Downloading themes… ${done}/${pages.length}`)
243 }
244
245 await indexThemes($)
246 await sayTheme($, `Saved ${saved} themes to ${dir}`)
247}
248
249async function wtSettingsPath($: EngineInterface, profileId: string | null) {
250 const local = ((await $.env.get('LOCALAPPDATA')) ?? '').replaceAll('\\', '/')
251 const candidates = [
252 `${local}/Packages/Microsoft.WindowsTerminal_8wekyb3d8bbwe/LocalState/settings.json`,
253 `${local}/Packages/Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe/LocalState/settings.json`,
254 `${local}/Microsoft/Windows Terminal/settings.json`,
255 ]
256 let first: string | null = null
257 for (const path of candidates) {
258 if (local === '' || !(await $.fs.exists(path))) continue
259 first ??= path
260 const text = await $.fs.read(path)
261 if (profileId !== null && text.toLowerCase().includes(profileId.toLowerCase())) return path
262 }
263 return first
264}
265
266// The background of the terminal Claude Code runs in: Windows Terminal's
267// profile and scheme, else the kept theme's.
268async function terminalBackground($: EngineInterface): Promise<string | null> {
269 if (await isWindows($)) {
270 const profileId = (await $.env.get('WT_PROFILE_ID')) ?? null
271 const path = await wtSettingsPath($, profileId)
272 if (path === null) return null
273 const settings = parseJsonc(await $.fs.read(path)) as WtSettings
274 const profile = targetProfile(settings, profileId) as { background?: unknown; colorScheme?: unknown }
275 if (typeof profile.background === 'string') return profile.background
276 const defaults = (Array.isArray(settings.profiles) ? undefined : settings.profiles?.defaults) as
277 | { background?: unknown; colorScheme?: unknown }
278 | undefined
279 if (typeof defaults?.background === 'string') return defaults.background
280 const raw = profile.colorScheme ?? defaults?.colorScheme ?? 'Campbell'
281 const name = typeof raw === 'string' ? raw : ((raw as { dark?: string }).dark ?? 'Campbell')
282 const scheme = (settings.schemes ?? []).find(sc => sc.name === name) as { background?: unknown } | undefined
283 if (typeof scheme?.background === 'string') return scheme.background
284 return WT_BUILTIN_BACKGROUNDS[name] ?? null
285 }
286 const kept = (await $.store.get('theme')) as { slug: string } | undefined
287 if (kept === undefined) return null
288 return toPalette(await $.fs.read(`${await themesDir($)}/${kept.slug}.yaml`))?.background ?? null
289}
290
291async function refreshPaneBg($: EngineInterface) {
292 try {
293 const bg = await terminalBackground($)
294 await update($, paneBg, () => bg)
295 } catch {}
296}
297
298// The `theme` in ~/.claude/settings.json, written directly: /config's theme row
299// takes only the built-in themes ("For custom themes, use /theme"), so a custom
300// one can only be chosen here. Claude Code reads it once, at startup, and loads
301// ~/.claude/themes/ at startup only when that theme is a custom one.
302async function writeThemeSetting($: EngineInterface, value: string): Promise<boolean> {
303 const path = `${await homeDir($)}/.claude/settings.json`
304 const text = (await $.fs.exists(path)) ? await $.fs.read(path) : '{}'
305 const settings = JSON.parse(text) as { theme?: unknown }
306 if (settings.theme === value) return false
307 const backup = `${path}.extra-mods.bak`
308 if (!(await $.fs.exists(backup))) await $.fs.write(backup, text)
309 settings.theme = value
310 await $.fs.write(path, `${JSON.stringify(settings, null, 2)}\n`)
311 return true
312}
313
314// Selects a Claude Code theme by its /theme value (`dark`, `custom:<slug>`),
315// first keeping the one it replaces, so a reset can put it back.
316async function selectClaudeTheme($: EngineInterface, value: string) {
317 const row = (await $.config.list()).find(r => r.key === 'theme')
318 if (row === undefined) throw new Error('Claude Code has no theme setting to change')
319 if (row.value === value) return
320 if (value === `custom:${CLAUDE_THEME}` && (await $.store.get('themeBefore')) === undefined) {
321 await $.store.set('themeBefore', row.value)
322 }
323 if (!value.startsWith('custom:') || row.options?.includes(value)) {
324 const set = await $.config.set({ key: 'theme', value })
325 if (set.deny === undefined) return
326 if (!value.startsWith('custom:')) throw new Error(set.deny)
327 }
328 if (await writeThemeSetting($, value)) {
329 $.ui.toast(`Restart Claude Code once to switch to the ${CLAUDE_THEME} theme; after that, themes change live`)
330 }
331}
332
333// Windows: the kept theme, background included, on the Windows Terminal
334// profile this tab runs in. Windows Terminal reloads its settings live, so the
335// tab repaints at once; other open tabs on the same profile take the theme too
336// while the session runs. The profile's own scheme is kept in the store before
337// the first change and goes back with null, at session end; a session that
338// crashed leaves it there, and the next session's end puts it back.
339async function paintWindowsTerminal($: EngineInterface, palette: Palette | null) {
340 const profileId = (await $.env.get('WT_PROFILE_ID')) ?? null
341 if (profileId === null) return
342 const path = await wtSettingsPath($, profileId)
343 if (path === null) return
344 const text = await $.fs.read(path)
345 const settings = parseJsonc(text) as WtSettings
346 const profile = findProfile(settings, profileId)
347 if (profile === undefined) return
348 const key = profileId.toLowerCase()
349 const originals = ((await $.store.get('wtOriginal')) ?? {}) as Record<string, { colorScheme?: unknown }>
350 if (palette === null && originals[key] === undefined) return
351 if (originals[key] === undefined) {
352 originals[key] = profile.colorScheme === undefined || profile.colorScheme === WT_SCHEME ? {} : { colorScheme: profile.colorScheme }
353 await $.store.set('wtOriginal', originals)
354 }
355 withProfileTheme(settings, profile, palette, originals[key].colorScheme)
356 const out = JSON.stringify(settings, null, 4)
357 if (out !== JSON.stringify(parseJsonc(text), null, 4)) {
358 const backup = `${path}.extra-mods.bak`
359 if (!(await $.fs.exists(backup))) await $.fs.write(backup, text)
360 await $.fs.write(path, out)
361 }
362 if (palette === null) {
363 delete originals[key]
364 await $.store.set('wtOriginal', originals)
365 }
366 await refreshPaneBg($)
367}
368
369// The terminal device Claude Code draws on (/dev/ttys002, /dev/pts/3): the
370// first process up the tree that has one. A command the engine runs has no
371// terminal of its own, so /dev/tty is not there for it.
372const FIND_TTY = `p=$$
373while [ "$p" -gt 1 ]; do
374 t=$(ps -o tty= -p "$p" | tr -d ' ')
375 case "$t" in ''|'?'|'??') ;; *) printf '/dev/%s' "$t"; exit 0 ;; esac
376 p=$(ps -o ppid= -p "$p" | tr -d ' ')
377done
378exit 1`
379
380let ttyPath: string | null | undefined
381
382async function findTty($: EngineInterface) {
383 if (ttyPath !== undefined) return ttyPath
384 const ran = await $.process.run(['sh', '-c', FIND_TTY])
385 ttyPath = ran.exitCode === 0 && ran.stdout.startsWith('/dev/') ? ran.stdout : null
386 return ttyPath
387}
388
389// macOS and Linux: the theme's colors, background included, sent to the
390// terminal as OSC sequences (Ghostty, iTerm2, kitty, WezTerm, Terminal.app);
391// null gives the terminal its own colors back.
392async function paintOsc($: EngineInterface, palette: Palette | null) {
393 const tty = await findTty($)
394 if (tty === null) return
395 await $.process.run(['sh', '-c', 'printf "%s" "$1" > "$2"', 'sh', oscFor(palette), tty])
396}
397
398// Paints Claude Code with a saved theme: written as the custom theme
399// ~/.claude/themes/extra-mods.json, which Claude Code reloads live, and
400// selected. On Windows this tab's Windows Terminal profile takes the theme
401// too, background included. null selects the theme that was in use before
402// the mod's first one, and gives the profile its own colors back.
403async function paintTerminal($: EngineInterface, slug: string | null) {
404 if (slug === null) {
405 const before = (await $.store.get('themeBefore')) as string | undefined
406 await selectClaudeTheme($, before ?? 'dark')
407 await $.store.delete('themeBefore')
408 if (await isWindows($)) await paintWindowsTerminal($, null)
409 else await paintOsc($, null)
410 return null
411 }
412 const palette = toPalette(await $.fs.read(`${await themesDir($)}/${slug}.yaml`))
413 if (palette === null) throw new Error(`${slug}.yaml is not a theme this mod can read`)
414 const dir = `${await homeDir($)}/.claude/themes`
415 await $.fs.write(`${dir}/${CLAUDE_THEME}.json`, `${JSON.stringify(toClaudeTheme(palette), null, 2)}\n`)
416 await selectClaudeTheme($, `custom:${CLAUDE_THEME}`)
417 if (await isWindows($)) await paintWindowsTerminal($, palette)
418 else await paintOsc($, palette)
419 return palette
420}
421
422// Keeps a theme (null: the terminal's own colors) for this and later sessions.
423// The menu's pane takes its background too.
424async function applyTheme($: EngineInterface, slug: string | null) {
425 const palette = await paintTerminal($, slug)
426 await update($, themeName, () => palette?.name ?? null)
427 if (palette === null) await $.store.delete('theme')
428 else await $.store.set('theme', { slug: slug!, name: palette.name })
429 await refreshPaneBg($)
430 await sayTheme($, '')
431}
432
433// The first look at the themes downloads them; once, however often it is asked.
434async function ensureThemes($: EngineInterface) {
435 if ((await read($, themes)).length > 0 || (await read($, isDownloading))) return
436 await update($, isDownloading, () => true)
437 try {
438 await downloadThemes($)
439 } catch (error) {
440 await sayTheme($, `Download failed: ${error instanceof Error ? error.message : String(error)}`)
441 } finally {
442 await update($, isDownloading, () => false)
443 }
444}
445
446// Runs a theme action from a button, reporting a failure in the panel.
447function themeAction($: EngineInterface, work: () => Promise<unknown>) {
448 return () => {
449 void work().catch((error: unknown) =>
450 sayTheme($, `Failed: ${error instanceof Error ? error.message : String(error)}`),
451 )
452 }
453}
454
455async function loadThemes($: EngineInterface) {
456 const list = await indexThemes($)
457 const saved = (await $.store.get('theme')) as { slug: string; name: string } | undefined
458 if (saved === undefined) return
459 if (!list.some(t => t.slug === saved.slug)) return
460 await update($, themeName, () => saved.name)
461 // This tab's Windows Terminal profile, or elsewhere the terminal itself,
462 // takes the kept theme for the session.
463 try {
464 const palette = toPalette(await $.fs.read(`${await themesDir($)}/${saved.slug}.yaml`))
465 if (await isWindows($)) await paintWindowsTerminal($, palette)
466 else await paintOsc($, palette)
467 } catch {}
468}
469
470// Mode and effort --------------------------------------------------------------
471
472// The effort every request of this session is sent with. When /config has an
473// effort row, it is changed too, so Claude Code's own display agrees.
474async function setEffort($: EngineInterface, level: Effort) {
475 await update($, effort, () => level)
476 await $.store.set('effort', level)
477 try {
478 const row = (await $.config.list()).find(r => /effort/i.test(r.key) && r.options?.includes(level))
479 if (row !== undefined) await $.config.set({ key: row.key, value: level })
480 } catch {}
481 $.ui.toast(`Effort: ${level}`)
482}
483
484// Switches the session's model through Claude Code's own `/model`, so /model,
485// the status line and the requests all agree. It runs once the session is idle.
486async function setModel($: EngineInterface, alias: string) {
487 await $.command.run({ command: 'model', args: alias })
488 const id = await $.session.model()
489 await update($, sessionModel, () => id)
490 if (await read($, statusOn)) void refreshStatus($).catch(() => {})
491 $.ui.toast(`Model: ${prettyModel(id)}`)
492}
493
494async function trackModel($: EngineInterface, id: string) {
495 if (id !== (await read($, sessionModel))) await update($, sessionModel, () => id)
496}
497
498// permissions.defaultMode in ~/.claude/settings.json: the mode new sessions
499// start in. A running session's mode is shift+tab's; a mod cannot set it.
500async function setDefaultMode($: EngineInterface, next: Mode) {
501 const path = `${await homeDir($)}/.claude/settings.json`
502 const text = (await $.fs.exists(path)) ? await $.fs.read(path) : '{}'
503 const backup = `${path}.extra-mods.bak`
504 if (!(await $.fs.exists(backup))) await $.fs.write(backup, text)
505 const settings = JSON.parse(text) as { permissions?: Record<string, unknown> }
506 settings.permissions = { ...settings.permissions, defaultMode: next }
507 await $.fs.write(path, `${JSON.stringify(settings, null, 2)}\n`)
508 await update($, defaultMode, () => next)
509 await update($, defaultModeChosen, () => true)
510 $.ui.toast(`New sessions start in ${modeLabel(next)} mode`)
511}
512
513async function trackMode($: EngineInterface, current: string | undefined) {
514 if (current !== undefined && current !== (await read($, mode))) await update($, mode, () => current)
515}
516
517// The session's own effort level before any request. First match wins: a
518// /config row, the effortLevel setting, CLAUDE_EFFORT, the last level seen.
519async function loadSessionEffort($: EngineInterface) {
520 const found: unknown[] = []
521 try {
522 found.push((await $.config.list()).find(r => /effort/i.test(r.key))?.value)
523 } catch {}
524 try {
525 found.push(((await $.settings.read()) as { effortLevel?: unknown }).effortLevel)
526 } catch {}
527 found.push(await $.env.get('CLAUDE_EFFORT'))
528 found.push(await $.store.get('lastSessionEffort'))
529 const level = found.find((v): v is Effort => typeof v === 'string' && EFFORTS.includes(v as Effort))
530 if (level !== undefined) await update($, sessionEffort, () => level)
531}
532
533// Records the level a request actually ran at, as the engine reports it.
534async function trackEffort($: EngineInterface, level: unknown) {
535 if (typeof level !== 'string' || !EFFORTS.includes(level as Effort)) return
536 const own = level as Effort
537 if (own === (await read($, sessionEffort))) return
538 await update($, sessionEffort, () => own)
539 await $.store.set('lastSessionEffort', own)
540}
541
542async function loadSettings($: EngineInterface) {
543 const saved = {
544 zenOn: (await $.store.get('zenOn')) as boolean | undefined,
545 zenTheme: (await $.store.get('zenTheme')) as ZenTheme | undefined,
546 zenCustom: (await $.store.get('zenCustom')) as ZenColors | undefined,
547 zenStyle: (await $.store.get('zenStyle')) as ZenStyle | undefined,
548 effort: (await $.store.get('effort')) as Effort | undefined,
549 lang: await $.store.get('lang'),
550 }
551 if (saved.zenOn !== undefined) await update($, zenOn, () => saved.zenOn!)
552 if (saved.zenTheme !== undefined && ZEN_THEMES.includes(saved.zenTheme)) await update($, zenTheme, () => saved.zenTheme!)
553 if (saved.zenCustom !== undefined) await update($, zenCustom, () => saved.zenCustom!)
554 if (saved.zenStyle !== undefined && ZEN_STYLES.includes(saved.zenStyle)) await update($, zenStyle, () => saved.zenStyle!)
555 if (saved.effort !== undefined && EFFORTS.includes(saved.effort)) await update($, effort, () => saved.effort!)
556 if (isLang(saved.lang)) await update($, lang, () => saved.lang as Lang)
557 try {
558 const { permissions } = await $.settings.read({ source: 'user' })
559 const configured = (permissions as { defaultMode?: string } | undefined)?.defaultMode
560 await update($, defaultMode, () => configured ?? 'default')
561 } catch {}
562}
563
564// Status line -------------------------------------------------------------------
565
566// Gathers what the status line draws: the model, the folder and branch, the
567// context window and the rate limits, as Claude Code's own status line has them.
568async function refreshStatus($: EngineInterface) {
569 const [model, cwd, usage] = await Promise.all([$.session.model(), $.session.cwd(), $.session.usage()])
570 let branch = ''
571 try {
572 const ran = await $.process.run(['git', '-C', cwd, 'branch', '--show-current'])
573 if (ran.exitCode === 0) branch = ran.stdout.trim()
574 } catch {}
575 const limits: RateLimit[] = usage.rateLimits
576 .filter(l => LIMIT_LABELS[l.kind] !== undefined)
577 .map(l => ({
578 label: LIMIT_LABELS[l.kind]!,
579 percent: Math.round(l.percentUsed),
580 resetsAt: l.resetsAt === undefined ? null : Date.parse(l.resetsAt),
581 }))
582 const snapshot: StatusSnapshot = {
583 model,
584 dir: cwd.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || cwd,
585 branch,
586 ctxPercent: usage.context.percent ?? null,
587 ctxTokens: usage.context.tokens ?? null,
588 ctxWindow: usage.context.window,
589 limits,
590 }
591 await update($, status, () => snapshot)
592}
593
594type SavedStatusLine = { statusLine: unknown }
595
596// On: the mod draws the status line, so Claude Code's own statusLine command is
597// taken out of ~/.claude/settings.json (kept, to put back when it goes off).
598async function setStatusOn($: EngineInterface, isOn: boolean) {
599 const path = `${await homeDir($)}/.claude/settings.json`
600 const text = (await $.fs.exists(path)) ? await $.fs.read(path) : '{}'
601 const backup = `${path}.extra-mods.bak`
602 if (!(await $.fs.exists(backup))) await $.fs.write(backup, text)
603 const settings = JSON.parse(text) as { statusLine?: unknown }
604 const saved = (await $.store.get('savedStatusLine')) as SavedStatusLine | undefined
605 if (isOn && settings.statusLine !== undefined) {
606 await $.store.set('savedStatusLine', { statusLine: settings.statusLine } satisfies SavedStatusLine)
607 delete settings.statusLine
608 await $.fs.write(path, `${JSON.stringify(settings, null, 2)}\n`)
609 } else if (!isOn && saved !== undefined && settings.statusLine === undefined) {
610 settings.statusLine = saved.statusLine
611 await $.fs.write(path, `${JSON.stringify(settings, null, 2)}\n`)
612 await $.store.delete('savedStatusLine')
613 }
614 await update($, statusOn, () => isOn)
615 await $.store.set('statusOn', isOn)
616 if (isOn) await refreshStatus($)
617}
618
619async function loadStatus($: EngineInterface) {
620 const isOn = (await $.store.get('statusOn')) as boolean | undefined
621 if (isOn === true) await update($, statusOn, () => true)
622 // Never chosen: on, so the button shares the stats row (the status line
623 // command, if any, is kept and comes back with Off).
624 if (isOn === undefined) await setStatusOn($, true).catch(() => {})
625 await update($, statusClock, () => Date.now())
626 try {
627 await refreshStatus($)
628 } catch {}
629}
630
631// Drawing ----------------------------------------------------------------------
632
633// Zen's progress band; null when there is nothing to show.
634async function drawZenBand($: EngineInterface, e: RenderInput<'AbovePrompt'>) {
635 const t = await read($, task)
636 if (!(await read($, zenOn)) || t === null) return null
637
638 const theme = await read($, zenTheme)
639 const custom = await read($, zenCustom)
640 const colors = colorsFor(theme, custom)
641 const isPrism = (await read($, zenStyle)) === 'prism'
642 const isCollapsed = await read($, zenCollapsed)
643 const clock = await read($, now)
644 const { Box, Text, Button } = $.ui.resolve(e)
645
646 const columns = Math.max(30, e.props.bodyColumns ?? 80)
647 const percent = percentOf(t)
648 const mark = t.doneAt !== null ? '✓' : isPrism ? '◆' : '✶'
649 const width = Math.max(8, columns - 4 - 16 - 6 - (isCollapsed ? Math.min(30, t.title.length + 2) : 0))
650 // Prism's colors stop flowing once the task is done.
651 const seconds = (t.doneAt ?? clock) / 1000
652 const flow = (k: number) => prismColor(theme, custom, k)
653 const prism = isPrism ? prismCells(theme, custom, width, percent, seconds) : null
654 const { filled, runs } = prism
655 ? { filled: prism.filled, runs: prism.colors.map(color => ({ color, cells: 1 })) }
656 : barCells(theme, colors.bar, width, percent)
657 const border = isPrism ? flow(seconds * 0.12) : colors.border
658 const percentColor = prism?.colors.at(-1) ?? colors.text
659 // Prism runs the title through the window too, unless it is the terminal's own text color.
660 const title =
661 isPrism && colors.text !== 'text'
662 ? [...`${mark} ${t.title}`].map((ch, i) => <Text color={mix(flow(seconds * 0.14 + i * 0.035), '#ffffff', 0.35)}>{ch}</Text>)
663 : `${mark} ${t.title}`
664 const bar = (
665 <Box>
666 {runs.map(r => (
667 <Text color={r.color}>{'█'.repeat(r.cells)}</Text>
668 ))}
669 <Text dimColor>{'░'.repeat(width - filled)}</Text>
670 </Box>
671 )
672 const toggle = (
673 <Button
674 key="zen-collapse"
675 plain
676 dimColor
677 label={isCollapsed ? '[+]' : '[–]'}
678 onPress={() => update($, zenCollapsed, c => !c)}
679 />
680 )
681
682 if (isCollapsed) {
683 return (
684 <Box borderStyle="round" borderColor={border} paddingX={1} gap={1}>
685 <Box width={Math.min(30, t.title.length + 2)}>
686 <Text color={colors.text} bold wrap="truncate">
687 {title}
688 </Text>
689 </Box>
690 {bar}
691 <Text color={percentColor} bold>{`${percent}%`.padStart(4)}</Text>
692 {toggle}
693 </Box>
694 )
695 }
696
697 const shown = visibleSteps(t)
698 return (
699 <Box flexDirection="column" borderStyle="round" borderColor={border} paddingX={1}>
700 <Box justifyContent="space-between" gap={1}>
701 <Text color={colors.text} bold wrap="truncate">
702 {title}
703 </Text>
704 <Box gap={1} flexShrink={0}>
705 <Text dimColor>{elapsed((t.doneAt ?? clock) - t.startedAt)}</Text>
706 {toggle}
707 </Box>
708 </Box>
709 <Box gap={1}>
710 <Text dimColor>{stepLabel(t).padEnd(14)}</Text>
711 {bar}
712 <Text color={percentColor} bold>{`${percent}%`.padStart(4)}</Text>
713 </Box>
714 {shown.map(step => {
715 const isNow = step.status === 'in_progress'
716 const dot = isPrism
717 ? step.status === 'completed'
718 ? <Text color={flow(t.steps.indexOf(step) * 0.22 - seconds * 0.14)}>◆</Text>
719 : isNow
720 ? <Text color={flow(seconds * 0.6)}>◆</Text>
721 : '◇'
722 : step.status === 'completed' ? '●' : isNow ? '◉' : '○'
723 return (
724 <Box key={`step-${step.id}`} justifyContent="space-between" gap={1}>
725 <Text color={isNow ? colors.text : undefined} bold={isNow} dimColor={step.status === 'pending'} wrap="truncate">
726 {dot} {step.text}
727 </Text>
728 <Text color={isNow ? colors.text : undefined} dimColor={!isNow}>
729 {step.status === 'completed' ? 'Done' : isNow ? 'Working' : 'Next'}
730 </Text>
731 </Box>
732 )
733 })}
734 {t.steps.length > shown.length && <Text dimColor>{t.steps.length - shown.length} more</Text>}
735 </Box>
736 )
737}
738
739// Moves the menu to another tab.
740async function goTo($: EngineInterface, panel: Panel) {
741 await update($, menu, () => panel)
742 if (panel === 'themes') {
743 await revealKept($)
744 void ensureThemes($)
745 }
746}
747
748// Opens the menu in its pane with the keyboard, or closes it.
749async function toggleMenu($: EngineInterface, panel: Panel = 'zen') {
750 if ((await read($, menu)) !== null) {
751 // A plugin's own close skips its own ui.close hook, so reset here too.
752 await $.ui.close({ id: PANE })
753 await update($, menu, () => null)
754 return
755 }
756 await update($, menu, () => panel)
757 if (panel === 'themes') {
758 await revealKept($)
759 void ensureThemes($)
760 }
761 await $.ui.open({ id: PANE, title: MENU_NAME, focus: true, closeOnEscape: true, ...PANE_SIZE })
762}
763
764// The theme list scrolls on its own, inside a pane exactly the body's height,
765// so the tabs above it and the language row under it stay where they are.
766// Rows the themes page takes besides the list: the tab strip (3), the kept
767// theme, the search, the actions, a status line while there is one, the
768// language footer (6, its chips framed), and one spare in case a row wraps.
769const listRows = (bodyRows: number, hasStatus: boolean) => Math.max(3, bodyRows - (3 + 3 + (hasStatus ? 1 : 0) + 6 + 1))
770
771async function foundThemes($: EngineInterface) {
772 const query = (await read($, themeQuery)).trim().toLowerCase()
773 return (await read($, themes)).filter(th => th.name.toLowerCase().includes(query))
774}
775
776// Moves the list's window to `top`, kept inside the list.
777async function scrollThemes($: EngineInterface, top: number, bodyRows: number) {
778 const rows = listRows(bodyRows, (await read($, themeStatus)) !== '')
779 const last = Math.max(0, (await foundThemes($)).length - rows)
780 const at = Math.max(0, Math.min(last, top))
781 if (at !== (await read($, themeScroll))) await update($, themeScroll, () => at)
782}
783
784// Opens the list with the kept theme in view, a few rows down from the top.
785async function revealKept($: EngineInterface) {
786 const kept = ((await $.store.get('theme')) as { slug: string } | undefined)?.slug
787 const at = kept === undefined ? -1 : (await foundThemes($)).findIndex(th => th.slug === kept)
788 await update($, themeScroll, () => Math.max(0, at - 3))
789}
790
791async function setLang($: EngineInterface, next: Lang) {
792 await update($, lang, () => next)
793 await $.store.set('lang', next)
794}
795
796const TABS: readonly { panel: Exclude<Panel, 'main'>; name: Phrase }[] = [
797 { panel: 'zen', name: 'tabZen' },
798 { panel: 'themes', name: 'tabThemes' },
799 { panel: 'mode', name: 'tabMode' },
800 { panel: 'status', name: 'tabStatus' },
801]
802
803// Text in the rainbow, one color a letter.
804const rainbow = (text: string) => [...text].map((ch, i) => ({ ch, color: RAINBOW[i % RAINBOW.length]! }))
805
806// The menu: a tab row with its close, the tab's settings, the language row.
807// Each setting is a chip, one per Button, so the arrow keys walk them.
808async function drawPane($: EngineInterface, e: RenderInput<'Pane'>, panel: Panel) {
809 if (e.surface !== 'terminal' && e.surface !== 'desktop') return null
810 const { Box, Text, Button, Input } = $.ui.resolve(e)
811 const tab: Exclude<Panel, 'main'> = panel === 'main' ? 'zen' : panel
812 const lng = await read($, lang)
813 const t = (key: Phrase, vars?: Record<string, string | number>) => phrase(lng, key, vars)
814 const background = (await read($, paneBg)) ?? PANE_BACKGROUND
815 const columns = e.props.bodyColumns ?? PANE_SIZE.columns
816 const rule = <Text dimColor>{'─'.repeat(Math.max(10, columns - 2))}</Text>
817
818 // A chip: a framed button, the chosen one framed and written in the accent
819 // color (or `frame`), the rest in a dim frame. The frame's key is the
820 // Button's with `-box`.
821 const framed = (key: string, isOn: boolean, button: RenderChildren, frame?: string) => (
822 <Box key={`${key}-box`} borderStyle="round" borderColor={isOn ? (frame ?? 'claude') : undefined} borderDimColor={!isOn} paddingX={1}>
823 {button}
824 </Box>
825 )
826 const chip = (key: string, label: string, isOn: boolean, onPress: () => unknown, color?: string) =>
827 framed(
828 key,
829 isOn,
830 <Button key={key} plain label={label} onPress={onPress}>
831 <Text bold={isOn} color={isOn ? 'claude' : color}>
832 {label}
833 </Text>
834 </Button>,
835 )
836 const chips = (key: string, items: RenderChildren[]) => (
837 <Box key={key} flexWrap="wrap" columnGap={1}>
838 {items}
839 </Box>
840 )
841 const check = (isOn: boolean) => isOn && <Text color="claude">{' ✓'}</Text>
842 // Swatches: one square a color, a space between.
843 const swatches = (colors: readonly string[]) => (
844 <Text>
845 {colors.map(c => (
846 <Text color={c}>{'■ '}</Text>
847 ))}
848 </Text>
849 )
850 const heading = (text: string, extra?: RenderChildren) => (
851 <Box key={`h-${text}`} marginTop={1} gap={1}>
852 <Text dimColor>{text}</Text>
853 {extra}
854 </Box>
855 )
856
857 const rows: RenderChildren[] = []
858
859 if (tab === 'zen') {
860 const isZenOn = await read($, zenOn)
861 const zenThemeNow = await read($, zenTheme)
862 const custom = await read($, zenCustom)
863 const style = await read($, zenStyle)
864 rows.push(
865 heading(t('zenMode')),
866 chips('zen-onoff', [
867 chip('zen-on', t('on'), isZenOn, () => setZenOn($, true)),
868 chip('zen-off', t('off'), !isZenOn, () => setZenOn($, false)),
869 ]),
870 heading(t('bandStyle')),
871 chips(
872 'zen-style',
873 ZEN_STYLES.map(s => chip(`zen-style-${s}`, t(s === 'prism' ? 'stylePrism' : 'styleClassic'), s === style, () => setZenStyle($, s))),
874 ),
875 heading(t('bandColor')),
876 ...ZEN_THEMES.map(theme => {
877 const isOn = theme === zenThemeNow
878 // Prism's swatches walk its window; classic's show the flat colors.
879 const colors =
880 style === 'prism'
881 ? Array.from({ length: 6 }, (_, i) => prismColor(theme, custom, theme === 'rainbow' ? i / 6 : i / 10))
882 : theme === 'rainbow'
883 ? RAINBOW.slice(0, 6)
884 : Array(6).fill(colorsFor(theme, custom).bar)
885 return (
886 <Button key={`zen-theme-${theme}`} plain label={theme} onPress={() => setZenTheme($, theme)}>
887 {swatches(colors)}
888 <Text bold={isOn}>{theme}</Text>
889 {check(isOn)}
890 </Button>
891 )
892 }),
893 )
894 if (zenThemeNow === 'custom') {
895 rows.push(
896 <Box key="zen-custom" flexDirection="column">
897 {(['bar', 'text', 'border'] as const).map(part => (
898 <Input
899 key={`zen-color-${part}`}
900 label={`${part} ${t('colorSuffix')}`}
901 value={custom[part]}
902 placeholder="#3b82f6"
903 submitLabel="set"
904 onSubmit={value => setZenColor($, part, value)}
905 />
906 ))}
907 </Box>,
908 )
909 }
910 }
911
912 if (tab === 'themes') {
913 const list = await read($, themes)
914 const query = await read($, themeQuery)
915 const status = await read($, themeStatus)
916 const busy = await read($, isDownloading)
917 const kept = ((await $.store.get('theme')) as { slug: string } | undefined)?.slug ?? null
918 const found = await foundThemes($)
919 if (list.length === 0) {
920 rows.push(
921 <Text key="themes-wait" dimColor>
922 {status || t('themesWait')}
923 </Text>,
924 )
925 if (!busy) rows.push(<Button key="themes-download" plain label={t('themesRetry')} onPress={() => ensureThemes($)} />)
926 } else {
927 const top = await read($, themeScroll)
928 const shown = listRows(e.props.scroll.bodyRows, status !== '')
929 const below = Math.max(0, found.length - top - shown)
930 rows.push(
931 <Box key="themes-current" justifyContent="space-between" gap={1} flexShrink={0}>
932 <Text wrap="truncate">
933 <Text dimColor>{t('kept')} </Text>
934 <Text bold>{(await read($, themeName)) ?? t('terminalDefault')}</Text>
935 </Text>
936 <Text dimColor>{top > 0 || below > 0 ? `${top + 1}–${Math.min(found.length, top + shown)}/${found.length}` : ''}</Text>
937 </Box>,
938 <Input
939 key="themes-search"
940 label={t('search')}
941 value={query}
942 placeholder={t('themesCount', { n: list.length })}
943 onInput={value => update($, themeQuery, () => value).then(() => update($, themeScroll, () => 0))}
944 onSubmit={value => update($, themeQuery, () => value).then(() => update($, themeScroll, () => 0))}
945 />,
946 <Box key="themes-actions" columnGap={2} flexWrap="wrap" flexShrink={0}>
947 <Button key="themes-reset" plain dimColor label={t('defaultTheme')} onPress={themeAction($, () => applyTheme($, null))} />
948 <Button key="themes-refresh" plain dimColor label={t('downloadAgain')} onPress={themeAction($, () => downloadThemes($))} />
949 </Box>,
950 )
951 if (status !== '') {
952 rows.push(
953 <Text key="themes-status" color="claude" wrap="truncate">
954 {status}
955 </Text>,
956 )
957 }
958 if (found.length === 0) {
959 rows.push(
960 <Text key="themes-none" dimColor>
961 {t('themesNone', { q: query })}
962 </Text>,
963 )
964 }
965 // A window over the list, a little longer than the room so the focus
966 // ring can step past its last row (the window then follows it).
967 rows.push(
968 ...found.slice(top, top + shown + 2).map(th => {
969 const isKept = th.slug === kept
970 return (
971 <Button key={`theme:${th.slug}`} plain label={th.name} onPress={themeAction($, () => applyTheme($, th.slug))}>
972 {swatches(th.colors)}
973 <Text bold={isKept}>{th.name}</Text>
974 {check(isKept)}
975 </Button>
976 )
977 }),
978 )
979 }
980 }
981
982 if (tab === 'mode') {
983 const running = await read($, mode)
984 const family = modelFamily(await read($, sessionModel))
985 const level = (await read($, effort)) ?? (await read($, sessionEffort))
986 // Marked: what this session runs in, until a new-session mode is chosen here.
987 const next = (await read($, defaultModeChosen)) ? await read($, defaultMode) : (running ?? (await read($, defaultMode)))
988 const switchModel = (alias: string) => () =>
989 setModel($, alias).catch((error: unknown) => $.ui.toast(`Could not switch the model: ${String(error)}`))
990 const meter = (
991 <Text>
992 {EFFORTS.map((l, i) =>
993 level !== null && i <= EFFORTS.indexOf(level) ? (
994 <Text color={level === 'max' ? RAINBOW[i * 2] : (EFFORT_HEAT[l] ?? undefined)}>▰</Text>
995 ) : (
996 <Text dimColor>▱</Text>
997 ),
998 )}
999 </Text>
1000 )
1001 rows.push(
1002 heading(t('model')),
1003 chips('models', [
1004 ...MODELS.map(m => chip(`model-${m.alias}`, m.label, m.alias === family, switchModel(m.alias))),
1005 <Button key="model-default" plain dimColor label={t('modelDefault')} onPress={switchModel('default')} />,
1006 ]),
1007 heading(t('effort'), meter),
1008 chips(
1009 'efforts',
1010 EFFORTS.map(l => {
1011 const heat = EFFORT_HEAT[l]
1012 const isOn = l === level
1013 const press = () => setEffort($, l)
1014 // Cool blue up to red hot; max is the whole rainbow.
1015 const label =
1016 heat === null ? (
1017 <Text bold={isOn}>
1018 {isOn && '✦ '}
1019 {rainbow(l).map(({ ch, color }) => (
1020 <Text color={color}>{ch}</Text>
1021 ))}
1022 </Text>
1023 ) : isOn ? (
1024 <Text bold color="#111111" backgroundColor={heat}>{` ${l} `}</Text>
1025 ) : (
1026 <Text color={heat}>{l}</Text>
1027 )
1028 return framed(
1029 `effort-${l}`,
1030 isOn,
1031 <Button key={`effort-${l}`} plain label={l} onPress={press}>
1032 {label}
1033 </Button>,
1034 heat ?? RAINBOW[7],
1035 )
1036 }),
1037 ),
1038 heading(t('runningIn')),
1039 <Text key="mode-running">
1040 {running === null ? t('runningUnknown') : <Text color={MODE_COLORS[running] ?? 'text'}>{modeName(lng, running)}</Text>}
1041 <Text dimColor> · {t('shiftTab')}</Text>
1042 </Text>,
1043 heading(t('newSessions')),
1044 chips(
1045 'default-modes',
1046 MODES.map(m =>
1047 framed(
1048 `default-mode-${m}`,
1049 m === next,
1050 <Button
1051 key={`default-mode-${m}`}
1052 plain
1053 label={modeName(lng, m)}
1054 onPress={() => setDefaultMode($, m).catch((error: unknown) => $.ui.toast(`Could not save the mode: ${String(error)}`))}
1055 >
1056 <Text color={MODE_COLORS[m] ?? 'text'} bold={m === next}>
1057 {modeName(lng, m)}
1058 </Text>
1059 {m === running && <Text color={MODE_COLORS[m] ?? 'text'}>{` · ${t('now')}`}</Text>}
1060 </Button>,
1061 ),
1062 ),
1063 ),
1064 )
1065 if (next === 'bypassPermissions') {
1066 rows.push(
1067 <Text key="mode-warning" color="warning">
1068 {t('bypassWarning')}
1069 </Text>,
1070 )
1071 }
1072 }
1073
1074 if (tab === 'status') {
1075 const isOn = await read($, statusOn)
1076 rows.push(
1077 heading(t('statusLine')),
1078 chips('status-onoff', [
1079 chip('status-on', t('on'), isOn, () =>
1080 setStatusOn($, true).catch((error: unknown) => $.ui.toast(`Could not turn it on: ${String(error)}`)),
1081 ),
1082 chip('status-off', t('off'), !isOn, () =>
1083 setStatusOn($, false).catch((error: unknown) => $.ui.toast(`Could not turn it off: ${String(error)}`)),
1084 ),
1085 ]),
1086 <Text key="status-note" dimColor>
1087 {t('statusNote')}
1088 </Text>,
1089 )
1090 }
1091
1092 // Folder tabs: the chosen one framed and open into the page, the rest
1093 // dim on the rule, the close at the end of the row.
1094 const width = Math.max(10, columns - 2)
1095 const cells = TABS.map(({ panel: p, name }) => {
1096 const isOn = p === tab
1097 const inner = ` ${isOn ? '◆ ' : ''}${t(name)} `
1098 return { p, name, isOn, inner, cells: inner.length + (isOn ? 2 : 0) }
1099 })
1100 const used = cells.reduce((n, c) => n + c.cells, 0)
1101 const tabStrip = (
1102 <Box key="tabs" flexDirection="column">
1103 <Text dimColor>{cells.map(c => (c.isOn ? `╭${'─'.repeat(c.inner.length)}╮` : ' '.repeat(c.cells))).join('')}</Text>
1104 <Box>
1105 {cells.map(c => (
1106 <Box key={`tab-row-${c.p}`}>
1107 {c.isOn && <Text dimColor>│</Text>}
1108 <Button key={`tab-${c.p}`} plain label={t(c.name)} autoFocus={c.isOn ? true : undefined} onPress={() => goTo($, c.p)}>
1109 {c.isOn ? (
1110 <Text bold color="claude">
1111 {' ◆ '}
1112 <Text underline>{t(c.name)}</Text>{' '}
1113 </Text>
1114 ) : (
1115 <Text dimColor>{c.inner}</Text>
1116 )}
1117 </Button>
1118 {c.isOn && <Text dimColor>│</Text>}
1119 </Box>
1120 ))}
1121 <Box flexGrow={1} />
1122 <Button key="tools-close" plain dimColor label={t('close')} onPress={() => toggleMenu($)} />
1123 </Box>
1124 <Text dimColor>
1125 {cells.map(c => (c.isOn ? `╯${' '.repeat(c.inner.length)}╰` : '─'.repeat(c.cells))).join('')}
1126 {'─'.repeat(Math.max(0, width - used))}
1127 </Text>
1128 </Box>
1129 )
1130
1131 const footer = (
1132 <Box key="footer" flexDirection="column" marginTop={1} flexShrink={0}>
1133 {rule}
1134 <Box columnGap={1} flexWrap="wrap" alignItems="center">
1135 <Text dimColor>{t('language')}</Text>
1136 {LANGS.map(l => chip(`lang-${l.lang}`, l.label, l.lang === lng, () => setLang($, l.lang)))}
1137 </Box>
1138 <Text dimColor>{t('keys')}</Text>
1139 </Box>
1140 )
1141
1142 // The themes page is exactly the body's height, its list scrolling inside;
1143 // the other pages grow, the footer at the bottom while they fit.
1144 const isThemes = tab === 'themes'
1145 return (
1146 <Box
1147 flexDirection="column"
1148 paddingX={1}
1149 backgroundColor={background}
1150 width={e.props.bodyColumns}
1151 height={isThemes ? e.props.scroll.bodyRows : undefined}
1152 minHeight={isThemes ? undefined : e.props.scroll.bodyRows}
1153 >
1154 {tabStrip}
1155 <Box flexDirection="column" flexGrow={1} flexShrink={1} overflow={isThemes ? 'hidden' : undefined}>
1156 {rows}
1157 </Box>
1158 {footer}
1159 </Box>
1160 )
1161}
1162
1163// The row under the prompt: with the status line on, the status line with the
1164// extra-mods button at its end, and under it, while Claude has a background
1165// shell or monitor running, the engine's pill for them; otherwise the hint and
1166// the button.
1167// The engine's hint, on one row: it can carry a second line holding only a
1168// separator, which drew as a stray dot under the hint.
1169function hintText(hint: string) {
1170 return hint
1171 .split(/\r?\n/)
1172 .map(line => line.trim())
1173 .filter(line => /[\p{L}\p{N}]/u.test(line))
1174 .join(' · ')
1175}
1176
1177async function drawPromptHint($: EngineInterface, e: RenderInput<'PromptHint'>) {
1178 const { Box, Text, Button } = $.ui.resolve(e)
1179 const isOpen = (await read($, menu)) !== null
1180 const label = `◆ ${MENU_NAME} ${isOpen ? '▼' : '▲'}`
1181 const button = <Button key="tools-toggle" plain label={label} onPress={() => toggleMenu($)} />
1182 const snapshot = (await read($, statusOn)) ? await read($, status) : null
1183
1184 // The engine keeps its mode label (⏵⏵ auto mode on ·) in a column of its own
1185 // to the left of this tree, so the tree grows into the rest of one row: a
1186 // full-width or multi-row tree wraps that label and pushes everything right.
1187 if (snapshot === null) {
1188 return (
1189 <Box justifyContent="space-between" flexGrow={1} gap={1}>
1190 <Text dimColor wrap="truncate">
1191 {hintText(e.props.hint)}
1192 </Text>
1193 {button}
1194 </Box>
1195 )
1196 }
1197
1198 const now = await read($, statusClock)
1199 const cache = cacheState(await read($, lastResponseAt), now)
1200 const columns = e.viewport?.columns ?? 120hooks/lib/modes.ts 40 lines1import type { Effort } from '../../types'
2
3export const EFFORTS: readonly Effort[] = ['low', 'medium', 'high', 'xhigh', 'max']
4
5// Effort as heat, cool blue up to red hot; max (null) is the whole rainbow.
6export const EFFORT_HEAT: Record<Effort, string | null> = {
7 low: '#38bdf8',
8 medium: '#a3e635',
9 high: '#fbbf24',
10 xhigh: '#f97316',
11 max: null,
12}
13
14export const MODES = ['default', 'plan', 'acceptEdits', 'auto', 'bypassPermissions'] as const
15
16export type Mode = (typeof MODES)[number]
17
18export const MODE_LABELS: Record<string, string> = {
19 default: 'ask',
20 plan: 'plan',
21 acceptEdits: 'accept edits',
22 auto: 'auto',
23 dontAsk: "don't ask",
24 bypassPermissions: 'bypass permissions',
25}
26
27export const modeLabel = (m: string | null): string => (m === null ? 'unknown' : (MODE_LABELS[m] ?? m))
28
29// The models the Mode page offers, by the alias `/model` takes.
30export const MODELS = [
31 { alias: 'fable', label: 'Fable' },
32 { alias: 'opus', label: 'Opus' },
33 { alias: 'sonnet', label: 'Sonnet' },
34 { alias: 'haiku', label: 'Haiku' },
35] as const
36
37// `claude-opus-5-5` → `opus`; null for an id that is not a Claude model's.
38export const modelFamily = (id: string | null): string | null =>
39 id?.match(/^claude-([a-z]+)-/i)?.[1]?.toLowerCase() ?? null
40hooks/lib/i18n.ts 111 lines1// The panel's words in each language it speaks. Pure; the hooks are in register.tsx.
2
3import type { Lang } from '../../types'
4
5export const LANGS: readonly { lang: Lang; label: string }[] = [
6 { lang: 'en', label: 'English' },
7 { lang: 'pt', label: 'Português' },
8]
9
10const EN = {
11 tabZen: 'Zen',
12 tabThemes: 'Theme',
13 tabMode: 'Mode',
14 tabStatus: 'Status',
15 close: 'esc ✕',
16 keys: 'tab move · enter select · wheel scrolls · esc close',
17 language: 'Language',
18 on: 'On',
19 off: 'Off',
20 now: 'now',
21 zenMode: 'Zen mode',
22 bandStyle: 'Band style',
23 stylePrism: 'Prism',
24 styleClassic: 'Classic',
25 bandColor: 'Band color',
26 colorSuffix: 'color',
27 kept: 'Kept',
28 search: 'Search',
29 themesCount: '{n} themes · click one to apply it',
30 themesWait: 'Getting the themes from terminalcolors.com…',
31 themesRetry: '↻ Try again',
32 themesNone: 'No theme matches “{q}”.',
33 defaultTheme: '↺ Claude Code default',
34 downloadAgain: '⟳ Download again',
35 terminalDefault: 'Terminal default',
36 model: 'Model',
37 modelDefault: "↺ Claude Code's default",
38 effort: 'Effort',
39 runningIn: 'Running in',
40 runningUnknown: 'Shown after your next prompt',
41 shiftTab: 'shift+tab switches it',
42 newSessions: 'New sessions start in',
43 bypassWarning: 'Bypass skips every permission check. Claude Code asks you to confirm it when the next session starts.',
44 statusLine: 'Status line',
45 statusNote: 'On takes your own statusLine command out of settings.json; Off puts it back.',
46 m_default: 'ask',
47 m_plan: 'plan',
48 m_acceptEdits: 'accept edits',
49 m_auto: 'auto',
50 m_dontAsk: "don't ask",
51 m_bypassPermissions: 'bypass permissions',
52}
53
54export type Phrase = keyof typeof EN
55
56const PT: Record<Phrase, string> = {
57 tabZen: 'Zen',
58 tabThemes: 'Tema',
59 tabMode: 'Modo',
60 tabStatus: 'Status',
61 close: 'esc ✕',
62 keys: 'tab mover · enter escolher · roda rola · esc fechar',
63 language: 'Idioma',
64 on: 'Ligado',
65 off: 'Desligado',
66 now: 'agora',
67 zenMode: 'Modo Zen',
68 bandStyle: 'Estilo da faixa',
69 stylePrism: 'Prisma',
70 styleClassic: 'Clássico',
71 bandColor: 'Cor da faixa',
72 colorSuffix: 'cor',
73 kept: 'Atual',
74 search: 'Buscar',
75 themesCount: '{n} temas · clique em um para aplicar',
76 themesWait: 'Baixando os temas do terminalcolors.com…',
77 themesRetry: '↻ Tentar de novo',
78 themesNone: 'Nenhum tema com “{q}”.',
79 defaultTheme: '↺ Padrão do Claude Code',
80 downloadAgain: '⟳ Baixar de novo',
81 terminalDefault: 'Padrão do terminal',
82 model: 'Modelo',
83 modelDefault: '↺ Padrão do Claude Code',
84 effort: 'Esforço',
85 runningIn: 'Rodando em',
86 runningUnknown: 'Aparece depois do próximo prompt',
87 shiftTab: 'shift+tab troca',
88 newSessions: 'Novas sessões começam em',
89 bypassWarning: 'Ignorar permissões pula todas as verificações. O Claude Code pede confirmação quando a próxima sessão começar.',
90 statusLine: 'Linha de status',
91 statusNote: 'Ligado tira o seu comando statusLine do settings.json; Desligado coloca de volta.',
92 m_default: 'perguntar',
93 m_plan: 'planejar',
94 m_acceptEdits: 'aceitar edições',
95 m_auto: 'auto',
96 m_dontAsk: 'não perguntar',
97 m_bypassPermissions: 'ignorar permissões',
98}
99
100const PHRASES: Record<Lang, Record<Phrase, string>> = { en: EN, pt: PT }
101
102export const isLang = (v: unknown): v is Lang => v === 'en' || v === 'pt'
103
104// A phrase in `lang`, each {name} filled from `vars`.
105export const phrase = (lang: Lang, key: Phrase, vars: Record<string, string | number> = {}) =>
106 PHRASES[lang][key].replace(/\{(\w+)\}/g, (_, name: string) => String(vars[name] ?? ''))
107
108// A permission mode's name in `lang`: `acceptEdits` → `accept edits`.
109export const modeName = (lang: Lang, mode: string | null) =>
110 mode === null ? '—' : `m_${mode}` in EN ? phrase(lang, `m_${mode}` as Phrase) : mode
111hooks/lib/status.ts 74 lines1// The status line's arithmetic, ported from statusline-command.py. Pure; the
2// drawing and the data gathering are in register.tsx.
3
4export const STATUS_GREEN = '#22c55e'
5export const STATUS_YELLOW = '#eab308'
6export const STATUS_RED = '#ef4444'
7export const STATUS_CYAN = '#22d3ee'
8export const BAR_WIDTH = 10
9
10// Claude Code's main-thread prompt cache lives for an hour on a subscription.
11export const CACHE_TTL_MS = 60 * 60 * 1000
12
13export const colorFor = (percent: number): string =>
14 percent >= 90 ? STATUS_RED : percent >= 70 ? STATUS_YELLOW : STATUS_GREEN
15
16export const fmtTokens = (n: number): string => {
17 if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
18 if (n >= 1000) return `${Math.round(n / 1000)}k`
19 return String(n)
20}
21
22// Short countdown: 45s, 12m, 4h38m, 5d18h.
23export const fmtDuration = (ms: number): string => {
24 const secs = Math.max(0, Math.floor(ms / 1000))
25 if (secs < 60) return `${secs}s`
26 const m = Math.floor(secs / 60)
27 if (m < 60) return `${m}m`
28 const h = Math.floor(m / 60)
29 if (h < 24) return `${h}h${String(m % 60).padStart(2, '0')}m`
30 return `${Math.floor(h / 24)}d${String(h % 24).padStart(2, '0')}h`
31}
32
33// How many of the bar's cells are filled at `percent`.
34export const barFill = (percent: number): number =>
35 Math.floor((Math.min(Math.max(percent, 0), 100) * BAR_WIDTH) / 100)
36
37// "ok" while the last response is younger than the cache, "over" after;
38// null before the first response, when there is no cache to speak of.
39export const cacheState = (lastResponseAt: number | null, now: number): 'ok' | 'over' | null =>
40 lastResponseAt === null ? null : now - lastResponseAt < CACHE_TTL_MS ? 'ok' : 'over'
41
42export const LIMIT_LABELS: Record<string, string> = { five_hour: '5h', seven_day: '7d' }
43
44// The engine's background-work pill as its hint reads it: `1 shell`,
45// `2 shells, 1 monitor`, `1 monitor`, or `3 background tasks` when the kinds
46// mix. null while no shell or monitor Claude started is running. (`ran 2 shell
47// commands` is a finished tool group, not a running shell.)
48const BACKGROUND_PILL = /\b\d+ (?:shells?(?:, \d+ monitors?)?|(?:Artifact comment )?monitors?|background tasks?)\b(?! commands?\b)/
49
50export const backgroundPill = (hint: string): string | null => hint.match(BACKGROUND_PILL)?.[0] ?? null
51
52// Detail levels, most detailed first: bars and reset times, then no bars,
53// then only the 5h reset time, then no reset times. The widest that fits
54// `columns` wins.
55export type Detail = 0 | 1 | 2 | 3
56
57// Whether the limit called `label` shows its reset time at `detail`: the 5h
58// one is the last to go, since it says when the session frees up.
59export const showsReset = (label: string, detail: Detail): boolean => (label === '5h' ? detail < 3 : detail < 2)
60
61export const statsWidth = (
62 ctxText: string,
63 limits: readonly { label: string; percentText: string; resetText: string }[],
64 cacheText: string,
65 detail: Detail,
66): number => {
67 const bar = detail === 0 ? BAR_WIDTH + 1 : 0
68 const sep = 5
69 let width = 4 + bar + ctxText.length
70 for (const l of limits) width += sep + l.label.length + 1 + bar + l.percentText.length + (showsReset(l.label, detail) ? l.resetText.length : 0)
71 if (cacheText !== '') width += sep + cacheText.length
72 return width
73}
74hooks/lib/palette.ts 260 lines1// Terminal palettes: terminalcolors.com's YAML in, Windows Terminal schemes and
2// OSC sequences out. Pure functions; nothing here touches the engine.
3
4const ANSI = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'] as const
5
6export type Palette = {
7 name: string
8 background: string
9 foreground: string
10 cursor: string
11 accent: string
12 normal: string[]
13 bright: string[]
14}
15
16// The themes' YAML (Warp's format): flat `key: value` lines, nested by indentation.
17export const parseYaml = (text: string): Record<string, string> => {
18 const flat: Record<string, string> = {}
19 const parents: { indent: number; key: string }[] = []
20 for (const line of text.split(/\r?\n/)) {
21 const body = line.trim()
22 if (body === '' || body.startsWith('#')) continue
23 const match = body.match(/^([\w-]+):\s*(.*)$/)
24 if (match === null) continue
25 const [, key = '', raw = ''] = match
26 const indent = line.length - line.trimStart().length
27 while ((parents.at(-1)?.indent ?? -1) >= indent) parents.pop()
28 const value = raw.replace(/^(["'])(.*)\1$/, '$2')
29 if (value === '') parents.push({ indent, key })
30 else flat[[...parents.map(p => p.key), key].join('.')] = value
31 }
32 return flat
33}
34
35export const toPalette = (yaml: string): Palette | null => {
36 const flat = parseYaml(yaml)
37 const normal = ANSI.map(c => flat[`terminal_colors.normal.${c}`] ?? '')
38 const bright = ANSI.map(c => flat[`terminal_colors.bright.${c}`] ?? '')
39 if (!flat.background || !flat.foreground || [...normal, ...bright].some(c => c === '')) return null
40 return {
41 name: flat.name ?? 'Unnamed',
42 background: flat.background,
43 foreground: flat.foreground,
44 cursor: flat.cursor ?? flat.foreground,
45 accent: flat.accent ?? normal[5] ?? flat.foreground,
46 normal,
47 bright,
48 }
49}
50
51// Claude Code themes ------------------------------------------------------------
52
53const rgb = (hex: string): [number, number, number] => {
54 const h = hex.replace('#', '')
55 const full = h.length === 3 ? [...h].map(c => c + c).join('') : h.slice(0, 6)
56 const n = Number.parseInt(full, 16)
57 return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
58}
59
60const hex = (c: readonly number[]): string =>
61 `#${c.map(v => Math.round(Math.max(0, Math.min(255, v))).toString(16).padStart(2, '0')).join('')}`
62
63// `amount` of the way from color `a` to color `b`.
64export const mix = (a: string, b: string, amount: number): string => {
65 const [x, y] = [rgb(a), rgb(b)]
66 return hex(x.map((v, i) => v + ((y[i] ?? v) - v) * amount))
67}
68
69export const isLight = (color: string): boolean => {
70 const [r, g, b] = rgb(color)
71 return 0.2126 * r + 0.7152 * g + 0.0722 * b > 140
72}
73
74export type ClaudeTheme = { name: string; base: 'dark' | 'light'; overrides: Record<string, string> }
75
76// A Claude Code custom theme (~/.claude/themes/<slug>.json) in the palette's
77// colors. Claude Code keeps the terminal's own background; the colors it draws
78// on it (text, accents, borders, diffs, message backgrounds) come from here.
79// Every color token Claude Code has (2.1.292) is set: a token left out keeps
80// the base theme's color, so a partial theme looks like dark/light with a tint.
81export const toClaudeTheme = (p: Palette): ClaudeTheme => {
82 const fg = p.foreground
83 const bg = p.background
84 const [, red = fg, green = fg, yellow = fg, blue = fg, magenta = fg, cyan = fg] = p.normal
85 const [gray = mix(bg, fg, 0.5), redB = red, greenB = green, yellowB = yellow, blueB = blue, magentaB = magenta] = p.bright
86 const orange = mix(red, yellow, 0.5)
87 const indigo = mix(blue, magenta, 0.5)
88 // The lighter (dark themes) or darker (light themes) twin an animation pulses to.
89 const shimmer = (c: string) => mix(c, fg, 0.35)
90 const rainbow = { red, orange, yellow, green, blue: cyan, indigo, violet: magenta }
91 return {
92 name: p.name,
93 base: isLight(bg) ? 'light' : 'dark',
94 overrides: {
95 claude: p.accent,
96 claudeShimmer: shimmer(p.accent),
97 claudeBlue_FOR_SYSTEM_SPINNER: blue,
98 claudeBlueShimmer_FOR_SYSTEM_SPINNER: shimmer(blue),
99 text: fg,
100 inverseText: bg,
101 inactive: gray,
102 inactiveShimmer: shimmer(gray),
103 subtle: mix(bg, fg, 0.3),
104 background: cyan,
105 suggestion: blue,
106 permission: blue,
107 permissionShimmer: shimmer(blue),
108 remember: magenta,
109 skill: magentaB,
110 success: green,
111 error: red,
112 warning: yellow,
113 warningShimmer: shimmer(yellow),
114 planMode: cyan,
115 autoAccept: magenta,
116 autoAcceptShimmer: shimmer(magenta),
117 promptBorder: mix(bg, fg, 0.35),
118 promptBorderShimmer: mix(bg, fg, 0.6),
119 bashBorder: magenta,
120 ide: blue,
121 merged: magenta,
122 professionalBlue: blueB,
123 chromeYellow: yellowB,
124 fastMode: orange,
125 fastModeShimmer: shimmer(orange),
126 effortUltra: magenta,
127 briefLabelYou: blue,
128 briefLabelClaude: p.accent,
129 clawd_body: p.accent,
130 clawd_background: bg,
131 rate_limit_fill: blue,
132 rate_limit_empty: mix(bg, blue, 0.3),
133 red_FOR_SUBAGENTS_ONLY: red,
134 blue_FOR_SUBAGENTS_ONLY: blue,
135 green_FOR_SUBAGENTS_ONLY: green,
136 yellow_FOR_SUBAGENTS_ONLY: yellow,
137 purple_FOR_SUBAGENTS_ONLY: magenta,
138 orange_FOR_SUBAGENTS_ONLY: orange,
139 pink_FOR_SUBAGENTS_ONLY: magentaB,
140 cyan_FOR_SUBAGENTS_ONLY: cyan,
141 ...Object.fromEntries(
142 Object.entries(rainbow).flatMap(([name, c]) => [
143 [`rainbow_${name}`, c],
144 [`rainbow_${name}_shimmer`, shimmer(c)],
145 ]),
146 ),
147 userMessageBackground: mix(bg, fg, 0.08),
148 userMessageBackgroundHover: mix(bg, fg, 0.12),
149 composerSidebarBackground: mix(bg, fg, 0.05),
150 bashMessageBackgroundColor: mix(bg, magenta, 0.08),
151 memoryBackgroundColor: mix(bg, cyan, 0.08),
152 selectionBg: mix(bg, blue, 0.35),
153 diffAdded: mix(bg, green, 0.22),
154 diffRemoved: mix(bg, red, 0.22),
155 diffAddedDimmed: mix(bg, green, 0.12),
156 diffRemovedDimmed: mix(bg, red, 0.12),
157 diffAddedWord: mix(bg, greenB, 0.45),
158 diffRemovedWord: mix(bg, redB, 0.45),
159 },
160 }
161}
162
163// Windows Terminal's settings.json is JSON with comments and trailing commas.
164export const parseJsonc = (text: string): unknown => {
165 let out = ''
166 let inString = false
167 for (let i = 0; i < text.length; i++) {
168 const c = text[i]
169 if (inString) {
170 out += c
171 if (c === '\\') out += text[++i] ?? ''
172 else if (c === '"') inString = false
173 } else if (c === '"') {
174 inString = true
175 out += c
176 } else if (c === '/' && text[i + 1] === '/') {
177 while (i < text.length && text[i] !== '\n') i++
178 out += '\n'
179 } else if (c === '/' && text[i + 1] === '*') {
180 i = text.indexOf('*/', i + 2)
181 if (i < 0) break
182 i++
183 } else out += c
184 }
185 return JSON.parse(out.replace(/,(\s*[}\]])/g, '$1'))
186}
187
188export type WtProfile = { guid?: string; colorScheme?: unknown }
189export type WtSettings = {
190 schemes?: Record<string, unknown>[]
191 profiles?: { defaults?: WtProfile; list?: WtProfile[] } | WtProfile[]
192}
193
194// The profile this Claude Code runs in, else the defaults every profile inherits.
195export const targetProfile = (settings: WtSettings, profileId: string | null): WtProfile => {
196 const profiles = settings.profiles
197 const list = Array.isArray(profiles) ? profiles : (profiles?.list ?? [])
198 const id = profileId?.toLowerCase()
199 const mine = id ? list.find(p => p.guid?.toLowerCase() === id) : undefined
200 if (mine !== undefined) return mine
201 if (Array.isArray(profiles) || profiles === undefined) settings.profiles = { defaults: {}, list }
202 const holder = settings.profiles as { defaults?: WtProfile }
203 holder.defaults ??= {}
204 return holder.defaults
205}
206
207// The color scheme the mod writes into Windows Terminal's settings: the kept
208// theme, put on the profile Claude Code runs in while a session lasts.
209export const WT_SCHEME = 'extra-mods'
210
211const profileList = (settings: WtSettings): WtProfile[] =>
212 Array.isArray(settings.profiles) ? settings.profiles : (settings.profiles?.list ?? [])
213
214export const findProfile = (settings: WtSettings, profileId: string): WtProfile | undefined =>
215 profileList(settings).find(p => p.guid?.toLowerCase() === profileId.toLowerCase())
216
217// Themes `profile` with the palette, or with null gives it back `original`,
218// the scheme it had (undefined: none of its own, so it follows the defaults).
219// The mod's scheme stays in the settings only while some profile uses it.
220export const withProfileTheme = (settings: WtSettings, profile: WtProfile, palette: Palette | null, original?: unknown): void => {
221 if (palette !== null) profile.colorScheme = WT_SCHEME
222 else if (original === undefined) delete profile.colorScheme
223 else profile.colorScheme = original
224 const schemes = (settings.schemes ?? []).filter(s => s.name !== WT_SCHEME)
225 const defaults = Array.isArray(settings.profiles) ? undefined : settings.profiles?.defaults
226 const inUse = [...profileList(settings), defaults].some(p => p?.colorScheme === WT_SCHEME)
227 if (palette !== null) schemes.push({ ...toWtScheme(palette), name: WT_SCHEME })
228 settings.schemes = palette !== null || !inUse ? schemes : (settings.schemes ?? [])
229}
230
231export const toWtScheme = (p: Palette): Record<string, string> => {
232 const names = ['black', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white']
233 const scheme: Record<string, string> = {
234 name: p.name,
235 background: p.background,
236 foreground: p.foreground,
237 cursorColor: p.cursor,
238 selectionBackground: p.bright[0] ?? p.foreground,
239 }
240 names.forEach((n, i) => {
241 scheme[n] = p.normal[i] ?? p.foreground
242 scheme[`bright${n.charAt(0).toUpperCase()}${n.slice(1)}`] = p.bright[i] ?? p.foreground
243 })
244 return scheme
245}
246
247const OSC = (body: string) => `\u001b]${body}\u0007`
248
249// The sequences that recolor the terminal (null resets it to its own colors).
250export const oscFor = (p: Palette | null): string =>
251 p === null
252 ? OSC('104') + OSC('110') + OSC('111') + OSC('112')
253 : [...p.normal, ...p.bright].map((c, i) => OSC(`4;${i};${c}`)).join('') +
254 OSC(`10;${p.foreground}`) +
255 OSC(`11;${p.background}`) +
256 OSC(`12;${p.cursor}`)
257
258export const matchAll = (html: string, re: RegExp): string[] =>
259 [...html.matchAll(re)].flatMap(m => (m[1] === undefined ? [] : [m[1]]))
260hooks/lib/zen.ts 172 lines1// Zen mode's look and arithmetic. Pure; the hooks are in register.tsx.
2
3import type { StepStatus, ZenColors, ZenStyle, ZenTask, ZenTheme } from '../../types'
4import { mix } from './palette'
5
6export const ZEN_THEMES: readonly ZenTheme[] = ['blue', 'dark', 'light', 'green', 'rainbow', 'custom']
7
8export const ZEN_STYLES: readonly ZenStyle[] = ['prism', 'classic']
9
10export const RAINBOW = ['#ef4444', '#f97316', '#eab308', '#22c55e', '#06b6d4', '#3b82f6', '#a855f7', '#ec4899']
11
12const PRESETS: Record<Exclude<ZenTheme, 'custom'>, ZenColors> = {
13 blue: { bar: '#3b82f6', text: '#bfdbfe', border: '#3b82f6' },
14 dark: { bar: '#e5e7eb', text: '#d1d5db', border: '#6b7280' },
15 // Its text is the theme's own, readable on a dark terminal and a light one.
16 light: { bar: '#93c5fd', text: 'text', border: '#cbd5e1' },
17 green: { bar: '#22c55e', text: '#bbf7d0', border: '#16a34a' },
18 rainbow: { bar: '#ef4444', text: '#f9a8d4', border: '#ec4899' },
19}
20
21export const ZEN_TOOL_NAME = 'zen_progress'
22
23export const ZEN_PROMPT = [
24 'Zen mode is on: the user sees only your text messages, not your tool calls or their output.',
25 'They follow your work on a progress band fed by the zen_progress tool (mcp__extra-mods__zen_progress).',
26 'Before you start, call it with your plan as a list of short steps. Call it again with the whole list each time a step starts or finishes,',
27 'so exactly one step is in_progress while you work and every step is completed when you are done.',
28 'Before acting, say in a sentence what you are about to do and why.',
29].join(' ')
30
31export const ZEN_TOOL_DESCRIPTION =
32 'Updates the Zen mode progress band the user watches. Send your whole plan each call: every step with its status ' +
33 '(pending, in_progress or completed). Call it when you start a task and whenever a step starts or finishes.'
34
35export const ZEN_TOOL_SCHEMA = {
36 type: 'object',
37 properties: {
38 title: { type: 'string', description: 'Optional short name for the whole task.' },
39 steps: {
40 type: 'array',
41 description: 'The full plan, in order.',
42 items: {
43 type: 'object',
44 properties: {
45 text: { type: 'string', description: 'The step, in a few words.' },
46 status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] },
47 },
48 required: ['text', 'status'],
49 },
50 },
51 },
52 required: ['steps'],
53}
54
55export const colorsFor = (theme: ZenTheme, custom: ZenColors): ZenColors =>
56 theme === 'custom' ? custom : PRESETS[theme]
57
58export const percentOf = (t: ZenTask): number => {
59 if (t.doneAt !== null) return 100
60 if (t.steps.length === 0) return 0
61 const done = t.steps.filter(s => s.status === 'completed').length
62 return Math.round((done / t.steps.length) * 100)
63}
64
65const STATUSES: readonly StepStatus[] = ['pending', 'in_progress', 'completed']
66export const asStatus = (s: unknown): StepStatus =>
67 STATUSES.includes(s as StepStatus) ? (s as StepStatus) : 'pending'
68
69export const elapsed = (ms: number): string => {
70 const s = Math.max(0, Math.floor(ms / 1000))
71 return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`
72}
73
74export const stepLabel = (t: ZenTask): string => {
75 if (t.doneAt !== null) return 'Done'
76 if (t.steps.length === 0) return 'Working…'
77 const current = t.steps.findIndex(s => s.status === 'in_progress')
78 const done = t.steps.filter(s => s.status === 'completed').length
79 return `Step ${Math.min(t.steps.length, (current >= 0 ? current : done) + 1)} of ${t.steps.length}`
80}
81
82// How many cells of each color a bar `width` wide fills at `percent`.
83export const barCells = (theme: ZenTheme, bar: string, width: number, percent: number) => {
84 const filled = Math.round((width * Math.max(0, Math.min(100, percent))) / 100)
85 if (theme !== 'rainbow') return { filled, runs: filled > 0 ? [{ color: bar, cells: filled }] : [] }
86 const runs = RAINBOW.map((color, i) => {
87 const from = Math.floor((width * i) / RAINBOW.length)
88 const to = Math.floor((width * (i + 1)) / RAINBOW.length)
89 return { color, cells: Math.max(0, Math.min(to, filled) - from) }
90 }).filter(r => r.cells > 0)
91 return { filled, runs }
92}
93
94// Prism ------------------------------------------------------------------------
95// Each theme's one color opened into a window on the color wheel; every cell
96// takes its own spot in it, and the spots slide with time.
97
98// Hue from → to, saturation, lightness from → to. Rainbow runs the whole wheel.
99type ColorWindow = readonly [number, number, number, number, number]
100
101const WINDOWS: Record<Exclude<ZenTheme, 'custom'>, ColorWindow> = {
102 blue: [195, 245, 92, 50, 72],
103 green: [125, 175, 80, 42, 66],
104 // Chrome: no hue to spread, so only the shade moves.
105 dark: [220, 220, 8, 42, 94],
106 light: [200, 250, 90, 70, 86],
107 rainbow: [0, 300, 95, 58, 58],
108}
109
110const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v))
111
112const hsl = (h: number, s: number, l: number): string => {
113 const [sat, light] = [s / 100, l / 100]
114 const f = (n: number) => {
115 const k = (n + (((h % 360) + 360) % 360) / 30) % 12
116 const v = light - sat * Math.min(light, 1 - light) * Math.max(-1, Math.min(k - 3, 9 - k, 1))
117 return Math.round(v * 255).toString(16).padStart(2, '0')
118 }
119 return `#${f(0)}${f(8)}${f(4)}`
120}
121
122const toHsl = (hex: string): [number, number, number] => {
123 const [r, g, b] = [1, 3, 5].map(i => Number.parseInt(hex.slice(i, i + 2), 16) / 255) as [number, number, number]
124 const [max, min] = [Math.max(r, g, b), Math.min(r, g, b)]
125 const [l, d] = [(max + min) / 2, max - min]
126 if (d === 0) return [0, 0, l * 100]
127 const h = max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4
128 return [(h * 60 + 360) % 360, (d / (1 - Math.abs(2 * l - 1))) * 100, l * 100]
129}
130
131// A custom bar color's window: ±25° around its hue, a shade either side.
132const windowOf = (bar: string): ColorWindow => {
133 if (!/^#[0-9a-f]{6}$/i.test(bar)) return WINDOWS.blue
134 const [h, s, l] = toHsl(bar)
135 if (s < 12) return [h, h, s, clamp(l - 30, 25, 60), clamp(l + 20, 70, 95)]
136 return [h - 25, h + 25, clamp(s, 60, 95), clamp(l - 12, 35, 60), clamp(l + 14, 60, 85)]
137}
138
139const windowFor = (theme: ZenTheme, custom: ZenColors) => (theme === 'custom' ? windowOf(custom.bar) : WINDOWS[theme])
140
141// Folds any number into 0 → 1 → 0, so a narrow window flows back and forth with no seam.
142const fold = (x: number) => 1 - Math.abs(2 * (((x % 1) + 1) % 1) - 1)
143
144// The color at spot `k` of the theme's window; `k` may be any number.
145export const prismColor = (theme: ZenTheme, custom: ZenColors, k: number): string => {
146 const [h1, h2, s, l1, l2] = windowFor(theme, custom)
147 if (theme === 'rainbow') return hsl(h1 + (h2 - h1) * k, s, l1)
148 const f = fold(k)
149 return hsl(h1 + (h2 - h1) * f, s, l1 + (l2 - l1) * f)
150}
151
152// One color per filled cell of a bar `width` wide at `seconds`: the window
153// flowing along the bar, and a white glint sweeping through it.
154export const prismCells = (theme: ZenTheme, custom: ZenColors, width: number, percent: number, seconds: number) => {
155 const filled = Math.round((width * clamp(percent, 0, 100)) / 100)
156 const glint = (((seconds * 0.55) % 1.5) - 0.25) * Math.max(filled, 1)
157 const colors = Array.from({ length: filled }, (_, i) => {
158 const k = theme === 'rainbow' ? i / width - seconds / 6 : (i / width) * 0.9 - seconds * 0.14
159 const away = Math.abs(i - glint)
160 const color = prismColor(theme, custom, k)
161 return away < 3 ? mix(color, '#ffffff', (1 - away / 3) * 0.75) : color
162 })
163 return { filled, colors }
164}
165
166// At most `room` steps, keeping the current one in view.
167export const visibleSteps = (t: ZenTask, room = 6) => {
168 const current = t.steps.findIndex(s => s.status === 'in_progress')
169 const first = Math.max(0, Math.min(current - 2, t.steps.length - room))
170 return t.steps.slice(first, first + room)
171}
172types/index.d.ts 73 lines1export type Panel = 'main' | 'zen' | 'themes' | 'mode' | 'status'
2
3export type ZenTheme = 'blue' | 'dark' | 'light' | 'green' | 'rainbow' | 'custom'
4
5// prism: each cell its own color, flowing; classic: the flat colors from before.
6export type ZenStyle = 'prism' | 'classic'
7
8export type ZenColors ={ bar: string; text: string; border: string }
9
10export type StepStatus = 'pending' | 'in_progress' | 'completed'
11
12export type ZenStep = { id: string; text: string; status: StepStatus }
13
14export type ZenTask = {
15 title: string
16 startedAt: number
17 doneAt: number | null
18 steps: ZenStep[]
19}
20
21// colors: the theme's eight normal ANSI colors, drawn as its swatch.
22export type ThemeEntry = { slug: string; name: string; colors: string[] }
23
24export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
25
26export type Lang = 'en' | 'pt'
27
28export type RateLimit = { label: string; percent: number; resetsAt: number | null }
29
30// What the status line draws, refreshed after each model response and on a timer.
31export type StatusSnapshot = {
32 model: string
33 dir: string
34 branch: string
35 ctxPercent: number | null
36 ctxTokens: number | null
37 ctxWindow: number | null
38 limits: RateLimit[]
39}
40
41declare module 'claude-code' {
42 interface PluginState {
43 'extra-mods': {
44 menu: Panel | null
45 zenOn: boolean
46 zenTheme: ZenTheme
47 zenCustom: ZenColors
48 zenStyle: ZenStyle
49 zenCollapsed: boolean
50 task: ZenTask | null
51 now: number
52 themes: ThemeEntry[]
53 themeName: string | null
54 themeQuery: string
55 themeScroll: number
56 themeStatus: string
57 effort: Effort | null
58 mode: string | null
59 defaultMode: string | null
60 isDownloading: boolean
61 statusOn: boolean
62 status: StatusSnapshot | null
63 lastResponseAt: number | null
64 statusClock: number
65 sessionEffort: Effort | null
66 sessionModel: string | null
67 paneBg: string | null
68 defaultModeChosen: boolean
69 lang: Lang
70 }
71 }
72}
73