SLOPSHOPPER

clarity

A clearer Claude Code terminal: boxed and organized you/claude conversations, colour-coded clickable tool rows, a live status band with a timer and task info…

panebandspinnerrowsguardcommand
★ 3v1.0.0MITupdated 2026-10-26CircularBlox/Clarity
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · clarity
│ ┃ Session ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ good morning ☁☁☁ ☁☁ │ clarity │ │ ┃ ▄ ▄▀▀▄ ▄ ♪ ⏺ Read(src/auth.ts) │ (^‿^) clarity is on. /clarity opens its │ │ ┃ ▀█▀██▀█▀ ⎿ Read 6 lines │ settings; /clarity off turns it off. │ │ ┃ ▀▀▀▀ ⏺ Update(src/auth.ts) ╰────────────────────────────────────────────╯ │ ┃ ╭─────────────────────────────────────────── ⎿ Added 2 lines, removed 1 line │ ┃ │ (^‿^) Ready ⏺ Bash(bun test) │ ┃ │ context ██████████░░░░░░░░░░ 49% $0.42 ⎿ 3 pass, 1 fail │ ┃ │ limit ♥♥♥♥♡ 69% left │ ┃ ╰─────────────────────────────────────────── ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ Changed ✻ Worked for 42s · done 4:20 PM │ ┃ ▮▮ src/auth.ts +2 −1 │ ┃ ▮▮▮▮ src/audit.ts +6 −0 › /clarity │ ┃ ▮▮▮▮▮ src/cache.ts +8 −0 │ ┃ │ ┃ Failed │ ┃ ✗ Bash bun test │ ┃ │ ┃ Recent l │ ┃ 8:53 am Bash cat .env │ ┃ 8:53 am Bash rm -rf build && git push --f │ ┃ 8:53 am Bash git status --porcelain │ ┃ 8:53 am Bash bun test │ ┃ 8:53 am Write src/cache.ts │ ┃ 8:53 am Write src/audit.ts ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Session
good morning ☁☁☁ ☁☁ ☁ ☀ ▄ ▄▀▀▄ ▄ ♪ ▀█▀██▀█▀ ▀▀▀▀ ╭──────────────────────────────────────────────────────╮ │ (^‿^) Ready │ │ context ██████████░░░░░░░░░░ 49% $0.42 │ │ limit ♥♥♥♥♡ 69% left │ ╰──────────────────────────────────────────────────────╯ Changed 3 files ▮▮ src/auth.ts +2 −1 ▮▮▮▮ src/audit.ts +6 −0 ▮▮▮▮▮ src/cache.ts +8 −0 Failed 1 ✗ Bash bun test Recent latest first 8:53 am Bash cat .env 8:53 am Bash rm -rf build && git push --force origi… 8:53 am Bash git status --porcelain 8:53 am Bash bun test 8:53 am Write src/cache.ts 8:53 am Write src/audit.ts Your prompts click to copy copy-turn-1
Pane · clarity
clarity settings General 1: cycle-on on-onon-off Turn it off for regular Claude Code. 2: cycle-focus focus-onfocus-off Hides startup notices and tool output that worked. Look 3: cycle-palette palette-autopalette-darkpalette-contrastpa Auto matches your Claude Code theme. 4: cycle-width width-70width-80width-100width-120width-0 How wide replies get before they wrap. i: cycle-icons icons-unicodeicons-ascii Plain ASCII for terminals or fonts without these symbols. f: cycle-font font-leavefont-readablefont-large Sets the editor terminal to JetBrains Mono, readable or large. 5: cycle-tools tools-summarytools-full Click any tool row to see its full output. c: cycle-companioncompanion-livelycompanion-facecompanion-o Pip, a small sprout that walks along the band and panel, and a face that shows what Claude is doing. Layout 6: cycle-band band-onband-off The bar just above where you type. 7: cycle-panel panel-autopanel-offpanel-open Opens beside the chat when there's room. Behaviour 8: cycle-alerts alerts-notifyalerts-soundalerts-bothalerts A ping when Claude needs you or finishes a long task. 9: cycle-copy copy-oncopy-off Copy buttons under code and long replies. Esc to close · /clarity panel to open the session panel Tip: clarity works best on its own. Turn off other mods that restyle the transcript (like skins) in /plugin. Preview ╭────────────────────────────────────────────────────────╮ │ │ │ ╭──────────────────────────────────────────────────╮ │ │ │ you │ │ │ │ add rate limiting to the api │ │ │ ╰──────────────────────────────────────────────────╯ │ │ │ │ ╭──────────────────────────────────────────────────╮ │ │ │ ● claude │ │ │ │ I'll check the server first. │ │ │ ╰──────────────────────────────────────────────────╯ │ │ ▸ Read ×2 Grep ✓ │ │ ▸ Bash npm test ✓ │ │ ▸ Edit src/server.ts … │ │ ━━ 42s ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │ ╰────────────────────────────────────────────────────────╯
README

clarity

A clearer Claude Code terminal: boxed and organized you/claude conversations, colour-coded clickable tool rows, a live status band with a timer and task info, a session panel, copy buttons, cards, alerts, readable palettes, and overall transforms Claude Code.

A turn in clarity: your prompt boxed with its attached file and image, Claude's reply in its own frame, tool rows as coloured badges, a failed test in a red box, and code in a box with a copy button

Install

Needs Claude Code 2.1.287 or later. Run this inside Claude Code:

/plugin install clarity --marketplace CircularBlox/Clarity

Answer y to add the marketplace and pick a scope. clarity is on as soon as it installs. Type /clarity to open its settings.

From a shell, the same thing is:

claude plugin install clarity --marketplace CircularBlox/Clarity

In the desktop app, click + next to the prompt box, then Plugins, Add marketplace with CircularBlox/Clarity, and Add plugin.

Update

claude plugin update clarity@clarity

Then run /reload-plugins in any open session.

Uninstall

claude plugin uninstall clarity@clarity

If you set a terminal font with clarity, set it back to leave first (in /clarity, under Look). That takes clarity's lines out of your editor's settings.

Use

/clarity opens the settings. Click a choice, or press a setting's number to step through its choices. Esc closes it.

Other commands, for when you know what you want:

CommandDoes
/clarity panelOpens the session panel
/clarity on / offTurns clarity on or off
/clarity focusHides startup notices and tool output that worked
/clarity tools full / summaryFull tool rows, or one line each
/clarity statusSays what is on

clarity works best on its own. If you run other mods that restyle the transcript, like skins, turn them off in /plugin. clarity still copes when they stay on: it labels and frames the rows they draw instead of redrawing them.

Preview

The status band, through one turn. It replaces the stock spinner while it is on.

The status band cycling through Thinking, Reading, Editing, Running npm test, Writing and Ready, with the time, tokens, plan step and context

Meet Pip, a small sprout who lives on clarity's boxes. It peeks over the status band and paces along it while Claude works, looks around while Claude thinks, hops with a ? when Claude is waiting on you, and sinks down for a nap after five quiet minutes. The face at the start of the band follows along.

Pip peeking over the status band through a turn: looking around while thinking, walking during Read, Edit and npm test, hopping with a question mark while waiting, humming when done, then asleep

It sweats once a usage limit passes 80%, and ends up belly-up when Claude stops at one.

Pip sweating during a build near a usage limit, then belly-up when the limit is reached

In the session panel, Pip walks along the top of the Now box under a sky: clouds that drift while Claude works, stars at night, and five hearts for what is left of your usage limit. After a long turn it sits on the "While you were away" card.

<table> <tr> <td width="46%"><img alt="The session panel: a greeting, drifting clouds and a sun by day, stars and a moon by night, Pip walking on the Now box, and five hearts for the usage limit" src="docs/previews/sky.gif"></td> <td><img alt="Pip sitting on the While you were away card, humming" src="docs/previews/away.png"></td> </tr> </table>

Tool rows. Each tool is a badge in the colour of what it does. Calls made back to back fold into one strip, and a click opens it.

Tool rows: Read and Grep badges, an Edit with +15 −3, three calls folded into one strip, and a failed test in a red box

<table> <tr> <td width="44%"><img alt="The session panel: what Claude is doing, a context meter and cost, the plan with done and pending steps, changed files with edit bars, failures, recent tool calls and past prompts" src="docs/previews/panel.svg"></td> <td><img alt="The /clarity settings: General, Look, Layout and Behaviour, each choice a chip with the current one filled" src="docs/previews/settings.svg"></td> </tr> </table>

These previews are drawn from clarity's own output, rendered through Claude Code's test kit. In a real Cursor terminal it looks like this:

clarity in Cursor's terminal: a boxed reply, a folded run of Bash calls, the status band, and the settings menu with its preview

A reply with a table in its frame, beside the settings menu

What it changes

PartWhat you see
Your promptA rounded box with a you label. Files you add with @, folders, pasted images and pasted text each get a small card under it. Prompts over 12 lines fold the same way.
Claude's replyIts own frame with a claude label. A line of room between paragraphs, and lines that wrap at 80 columns. Replies over 30 lines fold to their first lines, with a button to show the rest.
CodeIts own frame with the language and a copy button. Long replies get a copy button too.
Tool rowsOne line on a tinted strip. Reads are blue, searches purple, commands orange, edits green, the web cyan, agents pink. Edits show +12 −3.
Back-to-back callsFold into one strip, [Bash ×2] [Edit] 3 tools. Click to open, click again to fold.
FailuresAlways shown, in a red box that says what failed.
QuestionsA banner, so you notice Claude is waiting on you.
Slash commandsTheir output sits in a titled card.
End of a turnA rule with the time. After a turn over 45 seconds, a "While you were away" card with tool calls, files changed and failures.
Status bandWhat Claude is doing, for how long, tokens written, the plan step, running agents, failures and context. It shows compaction with a timer, waits for your permission like it waits for your answers, and warns once a plan usage limit passes 80%, with when it resets. A turn that stops on an error says why, in red. During a long turn a short tip sits under it. Facts that do not fit drop out whole.
CompanionPip, a pixel-art sprout that walks on the band, the panel and the away card, and a face at the start of the band. Both show how things are going: thinking, busy, waiting on you, worried near a limit, stopped, content, asleep. The panel also gets a greeting, a sky that follows the time of day, and hearts for your usage limit.
Session panelNow, context and cost, the plan, changed files, failures, recent calls and your prompts. Click a prompt to copy it. Past eight prompts the list folds, with a button to show them all. A fast scroll glides instead of jumping.

Buttons are always in brackets, like [ ⧉ copy ], and change when you point at them. Coloured words without brackets are labels.

Settings

SectionSettingChoices
Generalclarityon, off
Generalfocuson, off
Lookcoloursauto, dark, contrast, colorblind, theme
Looksymbolsunicode, ascii
Lookline width70, 80, 100, 120, full
Lookterminal fontleave, readable, large
Looktool rowsone line, full
Lookcompanionlively, face, off
Layoutstatus bandon, off
Layoutsession panelauto, off, open now
Behaviouralertsnotify, sound, both, off
Behaviourcopy buttonson, off

symbols: ascii swaps every symbol clarity draws (▸, ✓, rounded borders) for plain ASCII, for terminals or fonts that show boxes instead.

companion: face keeps the face and the sky but leaves Pip out, which saves the two rows Pip uses over the band. off puts the plain ● and ✓ symbols back and takes the sky away. The hearts stay either way, since they are information. Pip also steps aside when the space above the prompt is short, and in symbols: ascii.

auto colours follow your Claude Code theme. colorblind uses the Okabe–Ito set. theme uses only your theme's own colours, which suits light themes.

terminal font sets your editor's terminal (Cursor or VS Code) to JetBrains Mono: 13 with 1.3 line spacing for readable, 14 with 1.35 for large, and turns on the terminal's smooth scrolling. That applies in Claude Code's main-screen layout; in fullscreen, Claude Code scrolls the transcript itself. It falls back to Menlo when JetBrains Mono is missing. leave is the default and touches nothing.

Settings are kept between sessions.

What it can reach

What claude plugin validate reports, in words.

AccessDetail
ReadsYour prompts, each tool call's input and result, the model's output as it streams (counted, not kept), the final reply, and the session's context use and cost.
ChangesHow rows are drawn. Prompts, tool calls and replies pass through unchanged, and so does what the model reads.
WritesIts own settings, to its plugin store. Your editor's settings.json, only when you pick a terminal font, and only the font lines. A settings file with comments is left alone.
Runspbcopy when the terminal will not copy for it. ls ~/Library/Fonts after setting the font, to see if JetBrains Mono is there.
EnvironmentReads HOME, TERM_PROGRAM and VSCODE_GIT_ASKPASS_MAIN to find your editor.
Sound and notificationsOnly with alerts on.
NetworkNone.

Compatibility

WhereWorks
Terminal, fullscreen layoutEverything, clicks included
Terminal, main-screen layoutEverything but clicks
Desktop app, VS Code extension, mobileclarity steps aside and Claude Code draws as usual

The session panel docks once the terminal is about 110 columns wide when you open it, or 144 when it opens on its own. Below that, /clarity panel still opens it.

Known limitations

  • If another mod's hook runs before clarity's and draws a row itself, clarity never sees that row.
  • Edit line counts come from each edit's text, so a full rewrite counts whole.
  • Folding and the plan start from the turn after clarity loads.
  • The status band hides the stock spinner's tips. Turn the band off to get the spinner back.
  • Plan tracking reads Claude's TodoWrite lists.
  • Where an organization manages Claude Code, installed mods do not see compaction start and end. The band then leaves compaction to Claude Code's own spinner line, which still shows.
  • Smooth scrolling covers the editor's terminal. Inside Claude Code's fullscreen layout, Claude Code scrolls the transcript itself.

Develop

claude --plugin-dir ./
claude plugin validate .
claude plugin test .

The tests run against Claude Code's engine through its test kit. They cover the logic, every drawn part, the menu, the band, the panel, and tool calls folding into one strip.

Dependencies

None at runtime. clarity uses only Claude Code's mod API.

NameVersionLicense (SPDX)Source
JetBrains Mono, optionalanyOFL-1.1https://github.com/JetBrains/JetBrainsMono

Third-party notices

Claude and Anthropic are trademarks of Anthropic, PBC. Cursor is a trademark of Anysphere, Inc. Visual Studio Code is a trademark of Microsoft Corporation. JetBrains Mono is a trademark of JetBrains s.r.o. Use here is descriptive and implies no endorsement.

License

MIT. Not an official Anthropic product.

Source 4 files
hooks/register.tsx 994 lines
1import { atom, memberOf, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement, RenderInput } from 'claude-code'
3
4import type { Activity, Env, FontChoice, Ledger, Prefs, RunPlace, ToolRun } from '../types'
5import {
6  ALERTS,
7  COMPANIONS,
8  ICONS,
9  ASKS,
10  FONTS,
11  DEFAULT_PREFS,
12  EDITS,
13  FOLD_PROMPT,
14  FOLD_REPLY,
15  EMPTY_LEDGER,
16  IDLE,
17  KEEP_RESULT,
18  NARROW,
19  PALETTES,
20  PANELS,
21  WIDTHS,
22  activityText,
23  tipAt,
24  applyFont,
25  clip,
26  describeInput,
27  drawnByMod,
28  editDelta,
29  editedPath,
30  editorSettingsPath,
31  nearestLimit,
32  fillActivity,
33  fillLedger,
34  firstLine,
35  formatClock,
36  foldText,
37  groupTools,
38  lineCount,
39  palettes,
40  parseAttachments,
41  parseTodos,
42  readPrefs,
43  recordEdit,
44  resolvePalette,
45  runCommand,
46  runStatus,
47  splitBlocks,
48  statusOf,
49  summarizeTurn,
50  REST_MS,
51  faceOf,
52  greeting,
53  moodOf,
54  pipPose,
55  sky,
56} from './logic'
57import type { Mood, Status, TurnSnapshot } from './logic'
58import {
59  badge,
60  band,
61  card,
62  failHeader,
63  attachmentCards,
64  asciiUI,
65  awayCard,
66  menu,
67  openedRow,
68  panel,
69  questionBanner,
70  replyBlocks,
71  replyBox,
72  toolLine,
73  turnRule,
74  userRow,
75} from './rows'
76import type { Chip, Look, MenuSection, PanelMood, ToolParts, UI } from './rows'
77
78const prefsAtom = atom({ plugin: 'clarity', key: 'prefs' } as const, DEFAULT_PREFS)
79const envAtom = atom({ plugin: 'clarity', key: 'env' } as const, { theme: 'dark' } as Env)
80const tickAtom = atom({ plugin: 'clarity', key: 'tick' } as const, 0)
81const activityAtom = atom({ plugin: 'clarity', key: 'activity' } as const, IDLE)
82const ledgerAtom = atom({ plugin: 'clarity', key: 'ledger' } as const, EMPTY_LEDGER)
83const expandedAtom = atom({ plugin: 'clarity', key: 'expanded' } as const, false)
84const runsAtom = atom({ plugin: 'clarity', key: 'runs' } as const, null as ToolRun | null)
85const placesAtom = atom({ plugin: 'clarity', key: 'places' } as const, null as RunPlace | null)
86
87// Every read and write of the session's state goes through these, which fill in fields an
88// older clarity never wrote.
89// The companion's face for now. It sleeps once no turn has run for a while; the last tick a
90// turn left behind says when that was.
91async function companionFace($: EngineInterface, activity: Activity, ledger: Ledger): Promise<{ face: string; mood: Mood; frame: number; now: number; tick: number }> {
92  const tick = await read($, tickAtom)
93  // Without a clock (some hosts and tests), it stays awake.
94  const now = await $.clock.now().catch(() => tick)
95  const isResting = tick === 0 || now - tick > REST_MS
96  const mood = moodOf(activity, ledger, isResting)
97  const frame = Math.floor(tick / 1000)
98  return { face: faceOf(mood, frame), mood, frame, now, tick }
99}
100
101async function readLedger($: EngineInterface): Promise<Ledger> {
102  return fillLedger(await read($, ledgerAtom))
103}
104
105function editLedger($: EngineInterface, fn: (ledger: Ledger) => Ledger) {
106  return update($, ledgerAtom, raw => fn(fillLedger(raw)))
107}
108
109async function readActivity($: EngineInterface): Promise<Activity> {
110  return fillActivity(await read($, activityAtom))
111}
112
113function editActivity($: EngineInterface, fn: (activity: Activity) => Activity) {
114  return update($, activityAtom, raw => fn(fillActivity(raw)))
115}
116
117const STORE_KEY = 'prefs'
118const MENU = 'clarity-menu'
119const PANEL = 'clarity-session'
120// Below this many columns a docked pane is squeezing the transcript.
121const CRAMPED = 70
122// A turn longer than this raises the "done" alert.
123const LONG_TURN_MS = 45_000
124// A reply block at least this many lines tall gets a copy button.
125const COPY_LINES = 4
126
127let hasWarnedCramped = false
128// Plain ASCII symbols, as the last prefs read said; every drawing reads the prefs first.
129let isAscii = false
130// A pane gliding to where a fast scroll asked, a couple of rows a frame.
131let glide: { id: string; at: number; to: number } | null = null
132let glideTimer: ReturnType<EngineInterface['clock']['every']> | undefined
133const GLIDE_STEP = 2
134// Ticks the band's timer while a turn runs.
135let ticker: ReturnType<EngineInterface['clock']['every']> | undefined
136// The run the next tool call joins: set by a call, ended by any text the model writes.
137let currentRun: string | null = null
138// Tool calls this session, and the session as the running turn found it.
139let toolCount = 0
140let turnStart: TurnSnapshot | null = null
141
142// What a render hook needs, or null when clarity should hand the row back.
143async function look($: EngineInterface, e: RenderInput): Promise<Look | null> {
144  if (e.surface !== 'terminal') return null
145  const prefs = await read($, prefsAtom)
146  if (!prefs.isOn) return null
147  const env = await read($, envAtom)
148  const columns = e.viewport?.columns ?? 100
149  if (columns < CRAMPED && !hasWarnedCramped) {
150    hasWarnedCramped = true
151    $.ui.toast(
152      `clarity: only ${columns} columns to draw in. Move the terminal into the editor area, or close a side pane, for easier reading.`,
153    )
154  }
155  isAscii = prefs.icons === 'ascii'
156  return { prefs, colors: palettes[resolvePalette(prefs.palette, env.theme)], columns, isNarrow: columns < NARROW }
157}
158
159function elements($: EngineInterface, e: RenderInput): UI {
160  // look() has already returned null off the terminal.
161  const ui = $.ui.resolve(e) as unknown as UI
162  return isAscii ? asciiUI(ui) : ui
163}
164
165// Writes the prefs, keeps them for later sessions and redraws every row clarity draws.
166async function savePrefs($: EngineInterface, prefs: Prefs) {
167  await update($, prefsAtom, () => prefs)
168  await $.store.set(STORE_KEY, prefs)
169  $.ui.invalidate('ui.render')
170}
171
172// The settings button: opens the menu, or closes it when it is already showing.
173async function toggleMenu($: EngineInterface) {
174  const isOpen = (await $.ui.panes()).some(pane => pane.id === MENU && pane.isShown)
175  if (isOpen) await $.ui.close({ id: MENU }).catch(() => undefined)
176  else await openMenu($)
177}
178
179function openMenu($: EngineInterface) {
180  return $.ui.open({ id: MENU, title: 'clarity', focus: true, closeOnEscape: true, rows: 52 })
181}
182
183// Unasked (at start) it waits for room; asked (a press, a command) it opens at any width and
184// comes to the front, so the button never seems to do nothing.
185function openPanel($: EngineInterface, isAsked = true) {
186  return isAsked ? $.ui.open({ id: PANEL, title: 'Session', focus: true }) : $.ui.open({ id: PANEL, title: 'Session' })
187}
188
189// The terminal's own clipboard first; where it refuses (Cursor's terminal often does), the
190// Mac's pasteboard.
191function copyText($: EngineInterface, e: RenderInput, text: string) {
192  void (async () => {
193    const result = await $.ui.copy({ text, surface: e.surface }).catch(() => ({ isCopied: false }))
194    if (result.isCopied) return $.ui.toast('Copied')
195    const fallback = await $.process.run(['pbcopy'], { stdin: text }).catch(() => null)
196    $.ui.toast(fallback !== null && fallback.exitCode === 0 ? 'Copied' : 'Could not copy here')
197  })()
198}
199
200// Sets the font of the editor this terminal runs in (Cursor, VS Code) to the person's choice.
201// Asked (a pick in the menu), it says what it did; at session start it only keeps the editor
202// in step, quietly unless something needs saying.
203async function syncFont($: EngineInterface, choice: FontChoice, isAsked: boolean) {
204  const home = await $.env.get('HOME')
205  const path = editorSettingsPath({
206    home,
207    termProgram: await $.env.get('TERM_PROGRAM'),
208    askpass: await $.env.get('VSCODE_GIT_ASKPASS_MAIN'),
209    platform: home?.startsWith('/Users/') ? 'mac' : home?.startsWith('/home/') ? 'linux' : 'other',
210  })
211  if (path === null) {
212    if (isAsked) $.ui.toast('clarity: this terminal is not Cursor or VS Code, so set its font in its own settings.')
213    return
214  }
215  const before = await $.fs.read(path).catch(() => '')
216  const edit = applyFont(typeof before === 'string' ? before : '', choice)
217  if ('error' in edit) {
218    if (isAsked) $.ui.toast(`clarity: left the font alone: ${edit.error}.`)
219    return
220  }
221  if (!edit.isChanged) {
222    if (isAsked) $.ui.toast(choice === 'leave' ? 'clarity: the font is yours again.' : 'clarity: the font is already set.')
223    return
224  }
225  await $.fs.write(path, edit.text)
226  if (choice === 'leave') {
227    if (isAsked) $.ui.toast('clarity: took its font settings out; your editor\'s own font is back.')
228    return
229  }
230  const fonts = home === undefined ? '' : (await $.process.run(['ls', `${home}/Library/Fonts`]).catch(() => null))?.stdout ?? ''
231  const hasFont = /JetBrainsMono/i.test(fonts)
232  $.ui.toast(
233    hasFont
234      ? 'clarity: terminal font set. Quit and reopen the editor if any letters look out of line.'
235      : 'clarity: font set, using Menlo until JetBrains Mono is installed: brew install --cask font-jetbrains-mono',
236  )
237}
238
239async function alert($: EngineInterface, text: string) {
240  const { alerts } = await read($, prefsAtom)
241  if (alerts === 'notify' || alerts === 'both') {
242    await $.ui.notify(text, { title: 'Claude Code' }).catch(() => undefined)
243  }
244  if (alerts === 'sound' || alerts === 'both') {
245    await $.audio.play({ asset: 'assets/chime.wav' }).catch(() => undefined)
246  }
247}
248
249async function refreshContext($: EngineInterface) {
250  try {
251    const usage = await $.session.usage()
252    const percent = usage.context.percent ?? (usage.context.tokens !== undefined ? (usage.context.tokens / usage.context.window) * 100 : null)
253    await editLedger($, ledger => ({ ...ledger, context: percent, cost: usage.cost?.usd ?? ledger.cost, limit: nearestLimit(usage.rateLimits) }))
254  } catch {
255    // No usage to read here (a test, a headless run): the band leaves context out.
256  }
257}
258
259type RunView = { run: ToolRun; place: RunPlace; isOpen: boolean; toggle: () => void }
260
261// The run a row belongs to, when it is one of several calls made back to back.
262async function runOf($: EngineInterface, id: string | undefined): Promise<RunView | null> {
263  if (id === undefined) return null
264  const place = await read($, memberOf(placesAtom, { requestId: id }))
265  if (place === null) return null
266  const run = await read($, memberOf(runsAtom, { requestId: place.run }))
267  if (run === null || run.ids.length < 2) return null
268  const open = memberOf(expandedAtom, { requestId: place.run })
269  return { run, place, isOpen: await read($, open), toggle: () => void update($, open, v => !v) }
270}
271
272// ` 5 tools  [Bash ×2] [Edit] [Read ×2]  ✓ `: a run as one strip.
273function runLine(ui: UI, look: Look, view: RunView): RenderElement {
274  return toolLine(
275    ui,
276    look,
277    {
278      tools: groupTools(view.run.tools.map(tool => ({ tool }))),
279      detail: `${view.run.ids.length} tools`,
280      status: runStatus(view.run),
281      isOpen: view.isOpen,
282    },
283    view.toggle,
284  )
285}
286
287// A row in a run: the first draws the run's strip, the rest stay folded into it until it is
288// opened; a failure always shows.
289function inRun(ui: UI, look: Look, view: RunView, own: RenderElement, failure: RenderElement | null): RenderElement {
290  const { Box } = ui
291  if (!view.isOpen) {
292    if (view.place.index > 0) return failure ?? <Box />
293    return failure === null ? (
294      runLine(ui, look, view)
295    ) : (
296      <Box flexDirection="column">
297        {runLine(ui, look, view)}
298        {failure}
299      </Box>
300    )
301  }
302  return view.place.index === 0 ? (
303    <Box flexDirection="column">
304      {runLine(ui, look, view)}
305      {indent(ui, look, own)}
306    </Box>
307  ) : (
308    indent(ui, look, own)
309  )
310}
311
312function indent(ui: UI, look: Look, body: RenderElement): RenderElement {
313  return <ui.Box paddingLeft={look.isNarrow ? 0 : 2}>{body}</ui.Box>
314}
315
316export const register: Register = on => {
317  hasWarnedCramped = false
318
319  on('session.start', async ($, e, next) => {
320    await $.command.register({
321      name: 'clarity',
322      description: 'Readable transcript: opens the clarity menu (or: panel, on, off, focus, tools, status)',
323      argumentHint: '[panel | on | off | focus | tools summary | tools full | status]',
324    })
325    const prefs = readPrefs(await $.store.get(STORE_KEY))
326    // An older clarity pinned a status line; nothing here sets one now.
327    $.ui.status(undefined)
328    // The first session after installing says where the settings are, once.
329    if ((await $.store.get('welcomed')) !== true) {
330      await $.store.set('welcomed', true)
331      $.ui.toast('(^‿^) clarity is on. /clarity opens its settings; /clarity off turns it off.')
332    }
333    let theme = 'dark'
334    try {
335      const value = (await $.config.list()).find(row => row.key === 'theme')?.value
336      if (typeof value === 'string') theme = value
337    } catch {
338      // No /config here: the dark default stands.
339    }
340    await update($, prefsAtom, () => prefs)
341    await update($, envAtom, () => ({ theme }))
342    await refreshContext($)
343    // Opened unasked, the pane waits until the terminal is wide enough to dock it.
344    if (prefs.isOn && prefs.panel === 'auto') void openPanel($, false)
345    if (prefs.font !== 'leave') void syncFont($, prefs.font, false).catch(() => undefined)
346    // A session that opens or resumes draws its transcript before this module has loaded, and
347    // keeps those rows: ask for them again now, and once more after a resume finishes loading.
348    $.ui.invalidate('ui.render')
349    $.clock.after(1500, () => $.ui.invalidate('ui.render'))
350    return next(e)
351  })
352
353  on('command.run', { command: 'clarity' }, async ($, e) => {
354    const result = runCommand(e.args, await read($, prefsAtom))
355    if (result.open === 'menu') {
356      await openMenu($)
357      return {}
358    }
359    if (result.open === 'panel') {
360      await openPanel($)
361      return {}
362    }
363    await savePrefs($, result.prefs)
364    return { text: result.text }
365  })
366
367  // --- What the session is doing, for the band, the panel, the spinner and the alerts ---
368
369  on('prompt.submit', async ($, e, next) => {
370    if (e.origin.kind === 'composer' && e.command === undefined && e.isMeta !== true && e.text.trim() !== '') {
371      const text = firstLine(e.text, 200)
372      const whole = e.text.slice(0, 4000)
373      await editLedger($, ledger => ({
374        ...ledger,
375        turns: [...ledger.turns, text].slice(-200),
376        prompts: [...ledger.prompts, whole].slice(-200),
377      }))
378    }
379    return next(e)
380  })
381
382  on('turn.start', async ($, e, next) => {
383    if (e.agentId === undefined) {
384      const now = await $.clock.now()
385      await editActivity($, (): Activity => ({ phase: 'thinking', tool: '', detail: '', since: now, tokens: 0 }))
386      await update($, tickAtom, () => now)
387      const ledger = await readLedger($)
388      turnStart = { tools: toolCount, errors: ledger.errors.length, files: ledger.files }
389      if (ledger.stopped !== null) await editLedger($, l => ({ ...l, stopped: null }))
390      currentRun = null
391      ticker?.cancel()
392      ticker = $.clock.every(1000, () => void $.clock.now().then(t => update($, tickAtom, () => t)))
393    }
394    return next(e)
395  })
396
397  // The model's output as it streams: whether it is thinking or writing, and how many tokens
398  // so far (four characters a token while it streams, the exact count when each step ends).
399  on('turn.step', async function* ($, e, next) {
400    const stream = next(e)
401    const isMain = e.agentId === undefined
402    const base = isMain ? await readActivity($).then(a => a.tokens, () => 0) : 0
403    let chars = 0
404    let shown = 0
405    let phase: Activity['phase'] = 'thinking'
406    for (;;) {
407      const step = await stream.next()
408      if (step.done === true) return step.value
409      const chunk = step.value
410      // Counting never stands in the stream's way: a failure here leaves the chunk to pass.
411      try {
412        if (isMain && chunk.kind === 'text') currentRun = null
413        if (isMain && (chunk.kind === 'text' || chunk.kind === 'thinking')) {
414          chars += chunk.text.length
415          const now: Activity['phase'] = chunk.kind === 'text' ? 'writing' : 'thinking'
416          const estimate = Math.round(chars / 4)
417          if (estimate - shown >= 40 || now !== phase) {
418            shown = estimate
419            phase = now
420            await editActivity($, (a): Activity => ({ ...a, phase: a.phase === 'tool' || a.phase === 'waiting' ? a.phase : now, tokens: base + estimate }))
421          }
422        } else if (isMain && chunk.kind === 'stop' && chunk.usage !== null) {
423          const exact = base + chunk.usage.output_tokens
424          await editActivity($, (a): Activity => ({ ...a, tokens: exact }))
425        }
426      } catch {
427        // The band's count is a nicety; the model's output is not.
428      }
429      yield chunk
430    }
431  })
432
433  // A permission prompt: the verdict passes through untouched; the band says Claude is waiting
434  // on you, and an alert goes out, as for a question.
435  on('tool.check', async ($, e, next) => {
436    const verdict = await next(e)
437    if (verdict.decision === 'ask' && e.agentId === undefined) {
438      const tool = String(e.tool)
439      await editActivity($, (a): Activity => ({ ...a, phase: 'waiting', tool, detail: describeInput(tool, e) }))
440      void alert($, `Claude needs your permission: ${tool} ${describeInput(tool, e)}`.trim())
441    }
442    return verdict
443  }).catch(($, e, next) => next(e))
444
445  on('tool.call', async ($, e, next) => {
446    const isMain = e.agentId === undefined
447    const tool = String(e.tool)
448    const id = e.tool_use_id
449    let runId: string | null = null
450    if (isMain) {
451      const isAsk = ASKS.has(tool)
452      await editActivity($, (a): Activity => ({ ...a, phase: isAsk ? 'waiting' : 'tool', tool, detail: describeInput(tool, e) }))
453      if (isAsk) void alert($, 'Claude needs your answer')
454      if (id !== undefined) {
455        // Calls with no text between them join one run, keyed by its first call.
456        runId = currentRun ?? id
457        currentRun = runId
458        const run = (await read($, memberOf(runsAtom, { requestId: runId }))) ?? { ids: [], tools: [], running: 0, failed: 0 }
459        const joined: ToolRun = { ...run, ids: [...run.ids, id], tools: [...run.tools, tool], running: run.running + 1 }
460        await update($, memberOf(runsAtom, { requestId: runId }), () => joined)
461        await update($, memberOf(placesAtom, { requestId: id }), () => ({ run: runId ?? id, index: joined.ids.length - 1 }))
462      }
463      const todos = tool === 'TodoWrite' ? parseTodos(e) : null
464      await editLedger($, ledger => ({
465        ...ledger,
466        ...(todos === null ? {} : { todos }),
467        agents: ledger.agents + (tool === 'Agent' ? 1 : 0),
468      }))
469    }
470    const ran = await next(e)
471    toolCount += 1
472    const isError = ran.deny === undefined && ran.isError === true
473    if (ran.deny === undefined) {
474      const path = editedPath(e)
475      if (isError) {
476        const failure = { tool, detail: describeInput(tool, e), text: firstLine(ran.text) }
477        await editLedger($, ledger => ({ ...ledger, errors: [...ledger.errors, failure].slice(-50) }))
478      } else if (EDITS.has(tool) && path !== undefined) {
479        await editLedger($, ledger => recordEdit(ledger, path, editDelta(tool, e)))
480      }
481    }
482    if (isMain) {
483      if (runId !== null) {
484        const finished = runId
485        await update($, memberOf(runsAtom, { requestId: finished }), run =>
486          run === null ? null : { ...run, running: Math.max(0, run.running - 1), failed: run.failed + (isError ? 1 : 0) },
487        )
488      }
489      const at = await $.clock.now()
490      const action = { at, tool, detail: describeInput(tool, e), isOk: !isError && ran.deny === undefined }
491      await editLedger($, ledger => ({
492        ...ledger,
493        recent: [...ledger.recent, action].slice(-8),
494        agents: Math.max(0, ledger.agents - (tool === 'Agent' ? 1 : 0)),
495      }))
496      await editActivity($, (a): Activity => ({ ...a, phase: 'thinking', tool: '', detail: '' }))
497    }
498    return ran
499  })
500
501  // Compaction: the band says it is happening and for how long, and a toast says what it freed.
502  // A compaction worked out ahead of time, in the background, is left alone.
503  on('session.compact', async ($, e, next) => {
504    if (e.trigger === 'precompute') return next(e)
505    const now = await $.clock.now()
506    const before = (await readLedger($)).context
507    await editActivity($, (): Activity => ({ phase: 'compacting', tool: '', detail: '', since: now, tokens: 0 }))
508    await update($, tickAtom, () => now)
509    ticker?.cancel()
510    ticker = $.clock.every(1000, () => void $.clock.now().then(t => update($, tickAtom, () => t)))
511    try {
512      return await next(e)
513    } finally {
514      ticker?.cancel()
515      ticker = undefined
516      await editActivity($, () => IDLE)
517      await refreshContext($)
518      const after = (await readLedger($)).context
519      const took = Math.round(((await $.clock.now()) - now) / 1000)
520      const freed = before !== null && after !== null ? ` · context ${Math.round(before)}% → ${Math.round(after)}%` : ''
521      $.ui.toast(`clarity: compacted in ${took}s${freed}`)
522    }
523  }).catch(($, e, next) => next(e))
524
525  on('turn.complete', async ($, e, next) => {
526    const result = await next(e)
527    if (e.agentId === undefined) {
528      const reply = 'answer' in e ? e.answer : ''
529      ticker?.cancel()
530      ticker = undefined
531      await editActivity($, () => IDLE)
532      const durationMs = 'durationMs' in e ? e.durationMs : 0
533      const before = turnStart
534      turnStart = null
535      await editLedger($, (ledger): Ledger => {
536        const summary = before !== null && durationMs > LONG_TURN_MS ? summarizeTurn(before, { tools: toolCount, errors: ledger.errors.length, files: ledger.files }) : null
537        const kept = Object.entries(ledger.summaries).slice(-49)
538        return {
539          ...ledger,
540          lastReply: reply,
541          summaries: summary === null ? ledger.summaries : Object.fromEntries([...kept, [String(durationMs), summary]]),
542        }
543      })
544      await refreshContext($)
545      // The companion dozes off once the session has been quiet for a while.
546      $.clock.after(REST_MS + 1000, () => $.ui.invalidate('ui.render'))
547      if (e.reason === 'error') {
548        const { limit } = await readLedger($)
549        const resets = limit?.resetsAt != null && !Number.isNaN(Date.parse(limit.resetsAt)) ? ` · resets ${formatClock(Date.parse(limit.resetsAt))}` : ''
550        const why = limit !== null && limit.percent >= 100 ? `usage limit reached${resets}` : firstLine(reply, 80) || 'the turn ended on an error'
551        await editLedger($, l => ({ ...l, stopped: why }))
552        void alert($, `Claude stopped: ${why}`)
553      }
554      if ('durationMs' in e && e.durationMs > LONG_TURN_MS) void alert($, `Done: ${firstLine(reply, 100) || 'the turn finished'}`)
555    }
556    return result
557  })
558
559  // --- Panes: the menu and the session panel ---
560
561  on('ui.render', { component: 'Pane', requestId: MENU }, async ($, e) => {
562    const ui = $.ui.resolve(e)
563    if (e.surface !== 'terminal') return <ui.Text>Open the clarity menu in the terminal.</ui.Text>
564    const prefs = await read($, prefsAtom)
565    const env = await read($, envAtom)
566    isAscii = prefs.icons === 'ascii'
567    const l: Look = {
568      prefs,
569      colors: palettes[resolvePalette(prefs.palette, env.theme)],
570      columns: e.props.bodyColumns,
571      isNarrow: e.props.bodyColumns < NARROW,
572    }
573    const save = (change: Partial<Prefs>) => void savePrefs($, { ...prefs, ...change })
574    const onOff = [
575      { value: 'on', label: 'on' },
576      { value: 'off', label: 'off' },
577    ]
578    const flag = (v: boolean) => (v ? 'on' : 'off')
579    const choices = (values: readonly (string | number)[], label = (v: string | number) => String(v)) =>
580      values.map(v => ({ value: String(v), label: label(v) }))
581    const sections: MenuSection[] = [
582      {
583        title: 'General',
584        tone: l.colors.claude,
585        settings: [
586          { key: 'on', hotkey: '1', label: 'clarity', hint: 'Turn it off for regular Claude Code.', options: onOff, current: flag(prefs.isOn), pick: v => save({ isOn: v === 'on' }) },
587          { key: 'focus', hotkey: '2', label: 'focus', hint: 'Hides startup notices and tool output that worked.', options: onOff, current: flag(prefs.isFocus), pick: v => save({ isOn: true, isFocus: v === 'on' }) },
588        ],
589      },
590      {
591        title: 'Look',
592        tone: l.colors.you,
593        settings: [
594          { key: 'palette', hotkey: '3', label: 'colours', hint: 'Auto matches your Claude Code theme.', options: choices(PALETTES), current: prefs.palette, pick: v => save({ palette: v as Prefs['palette'] }) },
595          { key: 'width', hotkey: '4', label: 'line width', hint: 'How wide replies get before they wrap.', options: choices([...WIDTHS].sort((a, b) => (a || 999) - (b || 999)), v => (v === 0 ? 'full' : String(v))), current: String(prefs.measure), pick: v => save({ measure: Number(v) }) },
596          {
597            key: 'icons',
598            hotkey: 'i',
599            label: 'symbols',
600            hint: 'Plain ASCII for terminals or fonts without these symbols.',
601            options: ICONS.map(v => ({ value: v, label: v })),
602            current: prefs.icons,
603            pick: v => save({ icons: v === 'ascii' ? 'ascii' : 'unicode' }),
604          },
605          {
606            key: 'font',
607            hotkey: 'f',
608            label: 'terminal font',
609            hint: 'Sets the editor terminal to JetBrains Mono, readable or large.',
610            options: FONTS.map(f => ({ value: f, label: f })),
611            current: prefs.font,
612            pick: v => {
613              const font = v as FontChoice
614              save({ font })
615              void syncFont($, font, true).catch(() => $.ui.toast('clarity: could not change the font here.'))
616            },
617          },
618          {
619            key: 'tools',
620            hotkey: '5',
621            label: 'tool rows',
622            hint: 'Click any tool row to see its full output.',
623            options: [
624              { value: 'summary', label: 'one line' },
625              { value: 'full', label: 'full' },
626            ],
627            current: prefs.tools,
628            pick: v => save({ tools: v === 'full' ? 'full' : 'summary' }),
629          },
630          {
631            key: 'companion',
632            hotkey: 'c',
633            label: 'companion',
634            hint: 'Pip, a small sprout that walks along the band and panel, and a face that shows what Claude is doing.',
635            options: COMPANIONS.map(v => ({ value: v, label: v })),
636            current: prefs.companion,
637            pick: v => save({ companion: v as Prefs['companion'] }),
638          },
639        ],
640      },
641      {
642        title: 'Layout',
643        tone: l.colors.kinds.write,
644        settings: [
645          { key: 'band', hotkey: '6', label: 'status band', hint: 'The bar just above where you type.', options: onOff, current: flag(prefs.band), pick: v => save({ band: v === 'on' }) },
646          {
647            key: 'panel',
648            hotkey: '7',
649            label: 'session panel',
650            hint: "Opens beside the chat when there's room.",
651            options: [...choices(PANELS), { value: 'open', label: '▤ open now' }],
652            current: prefs.panel,
653            pick: v => {
654              if (v === 'open') {
655                void openPanel($)
656                return
657              }
658              save({ panel: v === 'off' ? 'off' : 'auto' })
659              if (v === 'auto') void openPanel($)
660              else void $.ui.close({ id: PANEL }).catch(() => undefined)
661            },
662          },
663        ],
664      },
665      {
666        title: 'Behaviour',
667        tone: l.colors.warn,
668        settings: [
669          { key: 'alerts', hotkey: '8', label: 'alerts', hint: 'A ping when Claude needs you or finishes a long task.', options: choices(ALERTS), current: prefs.alerts, pick: v => save({ alerts: v as Prefs['alerts'] }) },
670          { key: 'copy', hotkey: '9', label: 'copy buttons', hint: 'Copy buttons under code and long replies.', options: onOff, current: flag(prefs.copy), pick: v => save({ copy: v === 'on' }) },
671        ],
672      },
673    ]
674    return menu(elements($, e), l, sections, [
675      'Esc to close · /clarity panel to open the session panel',
676      'Tip: clarity works best on its own. Turn off other mods that restyle the transcript (like skins) in /plugin.',
677    ])
678  })
679
680  on('ui.render', { component: 'Pane', requestId: PANEL }, async ($, e) => {
681    const ui = $.ui.resolve(e)
682    if (e.surface !== 'terminal') return <ui.Text>The session panel draws in the terminal.</ui.Text>
683    const prefs = await read($, prefsAtom)
684    const env = await read($, envAtom)
685    isAscii = prefs.icons === 'ascii'
686    const l: Look = { prefs, colors: palettes[resolvePalette(prefs.palette, env.theme)], columns: e.props.bodyColumns, isNarrow: false }
687    const ledger = await readLedger($)
688    const allTurns = memberOf(expandedAtom, { requestId: 'clarity-panel-all-turns' })
689    const activity = await readActivity($)
690    let mood: PanelMood = null
691    if (prefs.companion !== 'off') {
692      const { face, mood: feeling, frame, now, tick } = await companionFace($, activity, ledger)
693      const hour = new Date(now).getHours()
694      // The clouds drift only while a turn runs, and rest where they stopped.
695      const hello = greeting(hour)
696      // The sky fills the row beside the greeting.
697      const walker = prefs.companion === 'lively' && !isAscii ? pipPose(feeling, frame, e.props.bodyColumns - 1) : null
698      mood = { face, sky: sky(e.props.bodyColumns - hello.length - 3, hour, Math.floor(tick / 1000)), greeting: hello, pip: walker }
699    }
700    return panel(
701      elements($, e),
702      l,
703      activity,
704      ledger,
705      e.props.bodyColumns,
706      {
707        copyTurn: i => copyText($, e, ledger.prompts[i] ?? ledger.turns[i] ?? ''),
708        toggleTurns: () => void update($, allTurns, v => !v),
709        isAllTurns: await read($, allTurns),
710      },
711      mood,
712    )
713  })
714
715  // A fast scroll in clarity's panes glides there a couple of rows a frame instead of jumping.
716  // Each frame is a scroll of clarity's own (origin plugin), which this hook steers to the next row.
717  on('ui.scroll', { component: 'Pane' }, ($, e, next) => {
718    if (e.requestId !== MENU && e.requestId !== PANEL) return next(e)
719    const last = Math.max(0, e.contentRows - e.bodyRows)
720    if (e.origin.kind === 'plugin') {
721      if (glide === null || glide.id !== e.requestId) return next(e)
722      const left = glide.to - glide.at
723      glide.at += Math.sign(left) * Math.min(GLIDE_STEP, Math.abs(left))
724      const offset = glide.at
725      if (glide.at === glide.to) {
726        glide = null
727        glideTimer?.cancel()
728        glideTimer = undefined
729      }
730      return next({ ...e, offset })
731    }
732    const from = glide !== null && glide.id === e.requestId ? glide.at : Math.min(last, Math.max(0, e.offset - e.by))
733    const to = Math.min(last, Math.max(0, (glide !== null && glide.id === e.requestId ? glide.to : from) + e.by))
734    if (Math.abs(to - from) <= GLIDE_STEP) {
735      glide = null
736      glideTimer?.cancel()
737      glideTimer = undefined
738      return next({ ...e, offset: to })
739    }
740    glide = { id: e.requestId, at: from + Math.sign(to - from) * GLIDE_STEP, to }
741    if (glideTimer === undefined) {
742      const id = e.requestId
743      glideTimer = $.clock.every(16, () => {
744        if (glide !== null) void $.ui.scroll({ in: id, to: 'start' }).catch(() => undefined)
745      })
746    }
747    return next({ ...e, offset: glide.at })
748  }).catch(($, e, next) => next(e))
749
750  // --- The band above the prompt ---
751
752  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
753    if (e.surface !== 'terminal' || e.props.hasSurvey) return next(e)
754    const prefs = await read($, prefsAtom)
755    if (!prefs.isOn || !prefs.band) return next(e)
756    const below = await next(e)
757    const env = await read($, envAtom)
758    isAscii = prefs.icons === 'ascii'
759    const l: Look = { prefs, colors: palettes[resolvePalette(prefs.palette, env.theme)], columns: e.props.bodyColumns, isNarrow: false }
760    const ui = elements($, e)
761    const ledger = await readLedger($)
762    const activity = await readActivity($)
763    const elapsed = activity.phase === 'idle' || activity.since === 0 ? 0 : Math.max(0, (await read($, tickAtom)) - activity.since)
764    const buddy = prefs.companion === 'off' ? null : await companionFace($, activity, ledger)
765    // Pip needs two rows over the band, and plain blocks: ASCII mode keeps to the face.
766    const tip = activity.phase === 'compacting' ? null : tipAt(elapsed)
767    const rowsLeft = e.props.maxRows - 1 - (activity.phase !== 'idle' && tip !== null ? 1 : 0)
768    const walker = buddy !== null && prefs.companion === 'lively' && !isAscii && rowsLeft >= 2 ? pipPose(buddy.mood, buddy.frame, e.props.bodyColumns - 2) : null
769    const ours = band(ui, l, activity, ledger, e.props.bodyColumns, { elapsedMs: elapsed, tokens: activity.tokens, tip, face: buddy?.face ?? null, pip: walker }, {
770      panel: () => void openPanel($),
771      menu: () => void toggleMenu($),
772      copy: prefs.copy && ledger.lastReply !== '' ? () => copyText($, e, ledger.lastReply) : undefined,
773    })
774    // Another mod's band keeps its place under ours.
775    return drawnByMod(next.trace) !== null && below !== undefined && below !== null ? (
776      <ui.Box flexDirection="column">
777        {ours}
778        {below}
779      </ui.Box>
780    ) : (
781      ours
782    )
783  })
784
785  // --- The transcript ---
786
787  // The person's prompt: a labelled, tinted block. Over another mod's row, the label alone.
788  on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
789    const l = await look($, e)
790    if (l === null || e.props.origin.kind !== 'composer') return next(e)
791    const below = await next(e)
792    const ui = elements($, e)
793    if (drawnByMod(next.trace) !== null) {
794      return (
795        <ui.Box flexDirection="column" marginTop={1}>
796          {badge(ui, l.colors, ' you ', l.colors.you)}
797          {below}
798          {attachmentCards(ui, l, parseAttachments(e.props.text))}
799        </ui.Box>
800      )
801    }
802    // A long prompt (a paste, say) folds to its first lines until opened.
803    const fold = foldText(e.props.text, FOLD_PROMPT)
804    const open = memberOf(expandedAtom, e)
805    const isOpen = fold !== null && (await read($, open))
806    const more: Chip | undefined =
807      fold === null
808        ? undefined
809        : { key: 'fold', label: isOpen ? '▴ show less' : `▾ show ${fold.hidden} more lines`, onPress: () => void update($, open, v => !v) }
810    return userRow(ui, l, fold === null || isOpen ? e.props.text : fold.head, parseAttachments(e.props.text), more)
811  })
812
813  // A reply: each block in a soft frame, paragraphs spaced, code in its own copyable box.
814  on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
815    const l = await look($, e)
816    if (l === null || e.props.isSummary === true) return next(e)
817    const below = await next(e)
818    const ui = elements($, e)
819    const byMod = drawnByMod(next.trace) !== null
820    const text = e.props.text
821    const onCopy = l.prefs.copy ? (code: string) => copyText($, e, code) : undefined
822    // A long reply folds to its first lines until opened (clarity's own drawing only).
823    const fold = byMod ? null : foldText(text, FOLD_REPLY)
824    const open = memberOf(expandedAtom, e)
825    const isOpen = fold !== null && (await read($, open))
826    const chips: Chip[] = [
827      ...(fold === null
828        ? []
829        : [{ key: 'fold', label: isOpen ? '▴ show less' : `▾ show ${fold.hidden} more lines`, onPress: () => void update($, open, v => !v) }]),
830      ...(l.prefs.copy && text.split('\n').length >= COPY_LINES
831        ? [{ key: 'copy-reply', label: '⧉ copy reply', onPress: () => copyText($, e, text) }]
832        : []),
833    ]
834    // Another mod sizes its own tables and cards to the width: leave it the whole of it.
835    const boxLook = byMod ? { ...l, prefs: { ...l.prefs, measure: 0 } } : l
836    const shown = fold === null || isOpen ? text : fold.head
837    const body = byMod ? below : replyBlocks(ui, l, splitBlocks(shown), onCopy)
838    return replyBox(ui, boxLook, e.props.isFirstOfReply, body, chips, !byMod)
839  })
840
841  // One tool call: one clickable line (an edit's line counts on it); a failure gets a red box.
842  // Calls made back to back fold into one strip for the run until it is opened.
843  on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
844    const l = await look($, e)
845    if (l === null) return next(e)
846    const p = e.props
847    const below = await next(e)
848    const ui = elements($, e)
849    if (drawnByMod(next.trace) !== null) return indent(ui, l, below)
850    const detail = describeInput(p.tool, p.input)
851    const failure = p.isErrored && !p.isInterrupted ? failHeader(ui, l, p.tool, detail, below) : null
852    if (l.prefs.tools === 'full') return failure ?? below
853    const open = memberOf(expandedAtom, e)
854    const isOpen = await read($, open)
855    const status: Status = p.isRunning ? 'running' : p.isInterrupted ? 'interrupted' : 'ok'
856    const delta = EDITS.has(p.tool) ? editDelta(p.tool, p.input) : undefined
857    const parts: ToolParts = { tools: [{ tool: p.tool, label: p.tool }], detail, status, ...(delta === undefined ? {} : { delta }) }
858    const toggle = () => void update($, open, v => !v)
859    const own = failure ?? (isOpen ? openedRow(ui, l, parts, toggle, below) : toolLine(ui, l, parts, toggle))
860    const view = await runOf($, p.tool_use_id)
861    return view === null ? own : inRun(ui, l, view, own, failure)
862  })
863
864  // A tool's output: shown when opened, for edits and errors; a line count for shell output.
865  on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
866    const l = await look($, e)
867    if (l === null) return next(e)
868    const p = e.props
869    const below = await next(e)
870    const ui = elements($, e)
871    if (drawnByMod(next.trace) !== null) return indent(ui, l, below)
872    if (l.prefs.tools === 'full' || p.isErrored) return below
873    const view = await runOf($, p.tool_use_id)
874    if (view !== null && !view.isOpen) return <ui.Box />
875    if (KEEP_RESULT.has(p.tool)) return below
876    if (await read($, memberOf(expandedAtom, e))) return indent(ui, l, below)
877    if (p.tool !== 'Bash' || l.prefs.isFocus) return <ui.Box />
878    const lines = lineCount(p.output)
879    return (
880      <ui.Box paddingLeft={l.isNarrow ? 2 : 4}>
881        <ui.Text color={l.colors.muted}>{lines === 0 ? '⎿ no output' : `⎿ ${lines} line${lines === 1 ? '' : 's'} of output · click the row to see it`}</ui.Text>
882      </ui.Box>
883    )
884  })
885
886  // A folded run of reads and searches: one clickable line of tool names.
887  on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
888    const l = await look($, e)
889    if (l === null || e.props.isExpanded) return next(e)
890    const ui = elements($, e)
891    if (l.prefs.tools === 'full') {
892      const below = await next(e)
893      return drawnByMod(next.trace) !== null ? indent(ui, l, below) : below
894    }
895    const calls = e.props.calls
896    const status = statusOf(calls)
897    const open = memberOf(expandedAtom, e)
898    const isOpen = await read($, open)
899    const first = calls[0]
900    const parts: ToolParts = {
901      tools: groupTools(calls),
902      detail: calls.length === 1 && first !== undefined ? describeInput(first.tool, first.input) : '',
903      status,
904    }
905    const toggle = () => void update($, open, v => !v)
906    const view = await runOf($, first?.tool_use_id)
907    if (isOpen || status === 'error') {
908      const below = await next({ ...e, props: { ...e.props, isExpanded: true } })
909      if (drawnByMod(next.trace) !== null) return indent(ui, l, below)
910      const own = openedRow(ui, l, parts, toggle, below)
911      return view === null ? own : inRun(ui, l, view, own, status === 'error' ? own : null)
912    }
913    const below = await next(e)
914    if (drawnByMod(next.trace) !== null) return indent(ui, l, below)
915    const own = toolLine(ui, l, parts, toggle)
916    return view === null ? own : inRun(ui, l, view, own, null)
917  })
918
919  // The end of a turn: a rule, so turns read as blocks. Under another mod's footer, the rule alone.
920  on('ui.render', { component: 'TurnDuration' }, async ($, e, next) => {
921    const l = await look($, e)
922    if (l === null) return next(e)
923    const below = await next(e)
924    const ui = elements($, e)
925    // A long turn closes with what it did, for whoever looked away while it ran.
926    const summary = (await readLedger($)).summaries[String(e.props.durationMs)]
927    const sitter = l.prefs.companion === 'lively' && !isAscii ? { ...pipPose('content', 1, 12), x: 2 } : null
928    const away = summary === undefined || summary.tools === 0 ? null : awayCard(ui, l, e.props.durationMs, summary, sitter)
929    if (drawnByMod(next.trace) !== null) {
930      return (
931        <ui.Box flexDirection="column" marginBottom={1}>
932          {away}
933          {below}
934          <ui.Text color={l.colors.rule}>{'─'.repeat(Math.max(10, l.columns - 2))}</ui.Text>
935        </ui.Box>
936      )
937    }
938    return away === null ? (
939      turnRule(ui, l, e.props.durationMs)
940    ) : (
941      <ui.Box flexDirection="column">
942        {away}
943        {turnRule(ui, l, e.props.durationMs)}
944      </ui.Box>
945    )
946  })
947
948  // A slash command's output in a titled card.
949  on('ui.render', { component: 'CommandOutput' }, async ($, e, next) => {
950    const l = await look($, e)
951    if (l === null || e.props.text.trim() === '') return next(e)
952    const below = await next(e)
953    if (drawnByMod(next.trace) !== null) return below
954    const ui = elements($, e)
955    const title = `/${e.props.command}${e.props.args === '' ? '' : ` ${clip(e.props.args, 40)}`}`
956    return card(ui, l, title, <ui.Markdown text={e.props.text} />, e.props.isErrored)
957  })
958
959  // A question for the person: a banner so it is never missed.
960  on('ui.render', { component: 'AskUserQuestion' }, async ($, e, next) => {
961    const l = await look($, e)
962    if (l === null) return next(e)
963    return questionBanner(elements($, e), l, await next(e))
964  })
965
966  // While the band is on it is the one status line, with its own timer: the stock spinner
967  // steps aside. With the band off, the spinner says what is happening.
968  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
969    const l = await look($, e)
970    if (l === null) return next(e)
971    // Claude Code's own messages (compacting, retrying) always show; only the word steps aside.
972    if (e.props.message !== null) return next(e)
973    if (l.prefs.band) return elements($, e).Box({})
974    const activity = await readActivity($)
975    if (activity.phase !== 'tool' && activity.phase !== 'waiting') return next(e)
976    return next({ ...e, props: { ...e.props, message: clip(activityText(activity), Math.max(20, l.columns - 40)) } })
977  })
978
979  // Startup notices: one short dim line, or none in focus mode.
980  on('ui.render', { component: 'InfoNotice' }, async ($, e, next) => {
981    const l = await look($, e)
982    if (l === null) return next(e)
983    const ui = elements($, e)
984    if (l.prefs.isFocus) return <ui.Box />
985    const command = e.props.command === null ? '' : `  ${e.props.command}`
986    return (
987      <ui.Text color={l.colors.muted} wrap="truncate">
988        · {e.props.text}
989        {command}
990      </ui.Text>
991    )
992  })
993}
994
hooks/logic.ts 859 lines
1// Pure helpers: no `$`, so tests import them directly.
2import type { Activity, Alerts, FileChange, FontChoice, IconChoice, Ledger, PaletteChoice, PaletteName, PanelChoice, Prefs, Todo, ToolRun, TurnSummary } from '../types'
3
4// What a tool does, for its colour: reading, searching, running, writing, the web, delegating.
5export type Kind = 'read' | 'search' | 'run' | 'write' | 'web' | 'agent' | 'other'
6
7export type Palette = {
8  kinds: Record<Kind, string>
9  text: string
10  muted: string
11  you: string
12  youBg: string | undefined
13  claude: string
14  tool: string
15  ok: string
16  error: string
17  warn: string
18  rule: string
19  accentBg: string | undefined
20  /** Dark text on a coloured chip; undefined draws chips inverse instead. */
21  chipText: string | undefined
22  /** The toolbar's background. */
23  barBg: string | undefined
24}
25
26// Hex chosen for at least 7:1 (text) and 4.5:1 (accents) against a near-black background.
27const DARK: Palette = {
28  kinds: { read: '#82AAFF', search: '#C3A6FF', run: '#FFB86C', write: '#A6E3A1', web: '#7DCFFF', agent: '#FF9AC1', other: '#A3ACBD' },
29  text: '#E6E9EF',
30  muted: '#A3ACBD',
31  you: '#82AAFF',
32  youBg: '#1B2233',
33  claude: '#F0A875',
34  tool: '#7FD6C2',
35  ok: '#A6E3A1',
36  error: '#FF8A9B',
37  warn: '#F2C97D',
38  rule: '#4A5263',
39  accentBg: '#262B38',
40  chipText: '#10131A',
41  barBg: '#1F2430',
42}
43
44// As bright as a terminal goes: white text, saturated accents, no mid-greys.
45const CONTRAST: Palette = {
46  kinds: { read: '#5FB3FF', search: '#D69CFF', run: '#FFA640', write: '#7CFF7C', web: '#4DF0F0', agent: '#FF7AC8', other: '#D0D4DC' },
47  text: '#FFFFFF',
48  muted: '#D0D4DC',
49  you: '#5FB3FF',
50  youBg: '#0B2340',
51  claude: '#FFB454',
52  tool: '#4DF0D0',
53  ok: '#7CFF7C',
54  error: '#FF5C7A',
55  warn: '#FFE066',
56  rule: '#8A93A6',
57  accentBg: '#1E2533',
58  chipText: '#000000',
59  barBg: '#141922',
60}
61
62// Okabe–Ito hues: told apart with any common colour-vision deficiency.
63const COLORBLIND: Palette = {
64  kinds: { read: '#56B4E9', search: '#CC79A7', run: '#E69F00', write: '#009E73', web: '#F0E442', agent: '#D55E00', other: '#B5B5B5' },
65  text: '#EDEDED',
66  muted: '#B5B5B5',
67  you: '#56B4E9',
68  youBg: '#13283A',
69  claude: '#E69F00',
70  tool: '#CC79A7',
71  ok: '#009E73',
72  error: '#D55E00',
73  warn: '#F0E442',
74  rule: '#5A5A5A',
75  accentBg: '#262626',
76  chipText: '#111111',
77  barBg: '#1E1E1E',
78}
79
80// Theme keys only, so a light (or any custom) theme stays legible.
81const THEME: Palette = {
82  kinds: { read: 'suggestion', search: 'remember', run: 'warning', write: 'success', web: 'ide', agent: 'claude', other: 'inactive' },
83  text: 'text',
84  muted: 'inactive',
85  you: 'suggestion',
86  youBg: undefined,
87  claude: 'claude',
88  tool: 'permission',
89  ok: 'success',
90  error: 'error',
91  warn: 'warning',
92  rule: 'subtle',
93  accentBg: undefined,
94  chipText: undefined,
95  barBg: undefined,
96}
97
98export const palettes: Record<PaletteName, Palette> = { dark: DARK, contrast: CONTRAST, colorblind: COLORBLIND, theme: THEME }
99
100export function resolvePalette(choice: PaletteChoice, theme: string): PaletteName {
101  if (choice !== 'auto') return choice
102  // auto: our hex only where the person's theme is a dark one.
103  return theme.startsWith('dark') ? 'dark' : 'theme'
104}
105
106type TraceLink = { readonly plugin: string; readonly tier: string }
107
108const KINDS: Record<string, Kind> = {
109  Read: 'read',
110  NotebookRead: 'read',
111  LSP: 'read',
112  Grep: 'search',
113  Glob: 'search',
114  ToolSearch: 'search',
115  Bash: 'run',
116  Monitor: 'run',
117  Edit: 'write',
118  MultiEdit: 'write',
119  Write: 'write',
120  NotebookEdit: 'write',
121  TodoWrite: 'write',
122  WebFetch: 'web',
123  WebSearch: 'web',
124  Agent: 'agent',
125  Skill: 'agent',
126  Workflow: 'agent',
127}
128
129export function kindOf(tool: string): Kind {
130  return KINDS[tool] ?? (tool.startsWith('mcp__') ? 'web' : 'other')
131}
132
133// The tools of a folded group as labels with counts, in first-seen order: `Read ×2`, `Grep`.
134export function groupTools(calls: readonly { tool: string }[]): { tool: string; label: string }[] {
135  const counts = new Map<string, number>()
136  for (const call of calls) counts.set(call.tool, (counts.get(call.tool) ?? 0) + 1)
137  return [...counts].map(([tool, n]) => ({ tool, label: n > 1 ? `${tool} ×${n}` : tool }))
138}
139
140// The tiers of plugins a person or their admin installs; `builtin` and
141// `core` are Claude Code's own drawing, which clarity replaces rather than decorates.
142const MOD_TIERS = new Set(['user', 'prepend', 'append'])
143
144// The mod that drew a row beneath clarity, or null when Claude Code drew it (or nothing did).
145// A trace ends at the link that answered itself, so its last entry is the one that drew.
146export function drawnByMod(trace: readonly TraceLink[]): string | null {
147  const last = trace[trace.length - 1]
148  if (last === undefined || !MOD_TIERS.has(last.tier)) return null
149  return last.plugin
150}
151
152// Below this the indents go; labels always stay, they are what tells rows apart.
153export const NARROW = 60
154
155function basename(path: string): string {
156  const parts = path.split('/').filter(Boolean)
157  return parts.slice(-2).join('/') || path
158}
159
160function field(input: unknown, key: string): string | undefined {
161  if (input === null || typeof input !== 'object') return undefined
162  const value = (input as Record<string, unknown>)[key]
163  return typeof value === 'string' && value.length > 0 ? value : undefined
164}
165
166export function shortPath(path: string): string {
167  return basename(path)
168}
169
170// The one fact that identifies a call: its file, command, pattern or target.
171export function describeInput(tool: string, input: unknown): string {
172  const path = field(input, 'file_path') ?? field(input, 'notebook_path') ?? field(input, 'path')
173  if (path !== undefined && tool !== 'Grep' && tool !== 'Glob') return basename(path)
174  const first =
175    field(input, 'command') ??
176    field(input, 'pattern') ??
177    field(input, 'query') ??
178    field(input, 'url') ??
179    field(input, 'description') ??
180    field(input, 'skill') ??
181    field(input, 'prompt')
182  if (first !== undefined) return first.split('\n')[0] ?? ''
183  if (input !== null && typeof input === 'object') {
184    for (const value of Object.values(input)) {
185      if (typeof value === 'string' && value.length > 0) return value.split('\n')[0] ?? ''
186    }
187  }
188  return ''
189}
190
191export function editedPath(input: unknown): string | undefined {
192  return field(input, 'file_path') ?? field(input, 'notebook_path')
193}
194
195const VERBS: Record<string, string> = {
196  Bash: 'Running',
197  Read: 'Reading',
198  Edit: 'Editing',
199  MultiEdit: 'Editing',
200  Write: 'Writing',
201  NotebookEdit: 'Editing',
202  Grep: 'Searching for',
203  Glob: 'Finding',
204  WebFetch: 'Fetching',
205  WebSearch: 'Searching the web for',
206  Agent: 'Delegating:',
207  Skill: 'Using skill',
208  TodoWrite: 'Updating the plan',
209}
210
211// `Running npm test`, `Editing src/app.ts`: what the spinner and the band say.
212export function activityText(activity: Activity): string {
213  switch (activity.phase) {
214    case 'idle':
215      return 'Ready'
216    case 'thinking':
217      return 'Thinking'
218    case 'writing':
219      return 'Writing'
220    case 'compacting':
221      return 'Compacting the conversation'
222    case 'waiting':
223      return 'Waiting for you'
224    case 'tool': {
225      const verb = VERBS[activity.tool] ?? `Using ${activity.tool}`
226      return activity.detail === '' ? verb : `${verb} ${activity.detail}`
227    }
228  }
229}
230
231// Tools that stop and wait on the person.
232export const ASKS = new Set(['AskUserQuestion', 'ExitPlanMode'])
233
234export const EDITS = new Set(['Edit', 'MultiEdit', 'Write', 'NotebookEdit'])
235
236function countLines(text: string | undefined): number {
237  return text === undefined || text === '' ? 0 : text.split('\n').length
238}
239
240// Lines in and out of one edit, from its input (an estimate: a rewrite counts whole).
241export function editDelta(tool: string, input: unknown): { added: number; removed: number } {
242  if (tool === 'Write') return { added: countLines(field(input, 'content')), removed: 0 }
243  if (tool === 'MultiEdit' && input !== null && typeof input === 'object') {
244    const edits = (input as { edits?: unknown }).edits
245    if (Array.isArray(edits)) {
246      return edits.reduce(
247        (sum: { added: number; removed: number }, one: unknown) => ({
248          added: sum.added + countLines(field(one, 'new_string')),
249          removed: sum.removed + countLines(field(one, 'old_string')),
250        }),
251        { added: 0, removed: 0 },
252      )
253    }
254  }
255  return {
256    added: countLines(field(input, 'new_string') ?? field(input, 'new_source')),
257    removed: countLines(field(input, 'old_string')),
258  }
259}
260
261export function recordEdit(ledger: Ledger, path: string, delta: { added: number; removed: number }): Ledger {
262  const before = ledger.files[path] ?? { added: 0, removed: 0, edits: 0 }
263  return {
264    ...ledger,
265    files: {
266      ...ledger.files,
267      [path]: { added: before.added + delta.added, removed: before.removed + delta.removed, edits: before.edits + 1 },
268    },
269  }
270}
271
272export function firstLine(text: unknown, room = 120): string {
273  const s = typeof text === 'string' ? text : ''
274  return clip((s.split('\n').find(line => line.trim() !== '') ?? '').trim(), room)
275}
276
277export type Attachment = { kind: 'file' | 'folder' | 'image' | 'paste'; name: string; detail: string }
278
279// What a prompt brings along, read from its text: `@path` mentions (a trailing slash is a
280// folder), pasted images (`[Image #1]`) and pasted text (`[Pasted text #1 +40 lines]`).
281export function parseAttachments(text: string): Attachment[] {
282  const found: Attachment[] = []
283  const seen = new Set<string>()
284  const add = (a: Attachment) => {
285    const id = `${a.kind}:${a.name}:${a.detail}`
286    if (!seen.has(id)) {
287      seen.add(id)
288      found.push(a)
289    }
290  }
291  for (const m of text.matchAll(/(?:^|\s)@(?:"([^"]+)"|([^\s@]+))/g)) {
292    const path = (m[1] ?? m[2] ?? '').replace(/[.,;:!?)]+$/, '')
293    if (path === '') continue
294    const isFolder = path.endsWith('/')
295    const parts = path.replace(/\/$/, '').split('/')
296    const name = parts.pop() ?? path
297    add({ kind: isFolder ? 'folder' : 'file', name, detail: parts.slice(-2).join('/') })
298  }
299  for (const m of text.matchAll(/\[Image #(\d+)\]/g)) add({ kind: 'image', name: `Image ${m[1]}`, detail: '' })
300  for (const m of text.matchAll(/\[Pasted text #(\d+)(?: \+(\d+) lines?)?\]/g)) {
301    add({ kind: 'paste', name: `Pasted text ${m[1]}`, detail: m[2] === undefined ? '' : `${m[2]} lines` })
302  }
303  return found
304}
305
306export type Block = { kind: 'prose'; text: string } | { kind: 'code'; text: string; lang: string; body: string }
307
308// A reply cut into paragraphs and fenced code blocks, so each can sit apart with room around it.
309// A list or table stays whole: only a blank line ends a prose block.
310export function splitBlocks(markdown: string): Block[] {
311  const blocks: Block[] = []
312  const lines = markdown.replace(/\r\n/g, '\n').split('\n')
313  let prose: string[] = []
314  const flush = () => {
315    const text = prose.join('\n').trim()
316    if (text !== '') blocks.push({ kind: 'prose', text })
317    prose = []
318  }
319  for (let i = 0; i < lines.length; i++) {
320    const line = lines[i] ?? ''
321    const fence = /^(\s*)(```+|~~~+)(.*)$/.exec(line)
322    if (fence !== null) {
323      flush()
324      const mark = fence[2] ?? '```'
325      const body: string[] = []
326      let j = i + 1
327      while (j < lines.length && !(lines[j] ?? '').trim().startsWith(mark)) body.push(lines[j++] ?? '')
328      const lang = (fence[3] ?? '').trim()
329      blocks.push({ kind: 'code', lang, body: body.join('\n'), text: [line, ...body, mark].join('\n') })
330      i = j
331      continue
332    }
333    if (line.trim() === '') flush()
334    else prose.push(line)
335  }
336  flush()
337  return blocks
338}
339
340// Every fenced code block's body, joined, for the copy-code button.
341export function codeBlocks(markdown: string): string {
342  const blocks: string[] = []
343  const re = /```[^\n]*\n([\s\S]*?)```/g
344  let m: RegExpExecArray | null
345  while ((m = re.exec(markdown)) !== null) blocks.push((m[1] ?? '').replace(/\n$/, ''))
346  return blocks.join('\n\n')
347}
348
349export function clip(text: string, room: number): string {
350  if (room <= 1) return ''
351  return text.length <= room ? text : `${text.slice(0, room - 1)}…`
352}
353
354type CallLike = { tool: string; isRunning: boolean; isErrored: boolean; isInterrupted: boolean }
355
356// `Read ×2 · Grep · Bash`, in first-seen order.
357export function groupSummary(calls: readonly CallLike[]): string {
358  const counts = new Map<string, number>()
359  for (const call of calls) counts.set(call.tool, (counts.get(call.tool) ?? 0) + 1)
360  return [...counts].map(([tool, n]) => (n > 1 ? `${tool} ×${n}` : tool)).join(' · ')
361}
362
363export type Status = 'running' | 'error' | 'interrupted' | 'ok'
364
365export function statusOf(calls: readonly CallLike[]): Status {
366  if (calls.some(call => call.isRunning)) return 'running'
367  if (calls.some(call => call.isErrored)) return 'error'
368  if (calls.some(call => call.isInterrupted)) return 'interrupted'
369  return 'ok'
370}
371
372export const MARK: Record<Status, string> = { running: '…', error: '✗', interrupted: '⊘', ok: '✓' }
373
374// Tools whose result is the point (a diff, a plan): their result stays in summary mode.
375export const KEEP_RESULT = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'ExitPlanMode', 'TodoWrite', 'AskUserQuestion'])
376
377export function lineCount(output: unknown): number {
378  const text =
379    typeof output === 'string'
380      ? output
381      : output !== null && typeof output === 'object'
382        ? [field(output, 'stdout'), field(output, 'stderr')].filter(Boolean).join('\n')
383        : ''
384  return text.length === 0 ? 0 : text.trimEnd().split('\n').length
385}
386
387// `8.5k`, as the stock spinner counts tokens.
388export function formatTokens(n: number): string {
389  return n < 1000 ? String(Math.round(n)) : `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`
390}
391
392export function formatDuration(ms: number): string {
393  const seconds = Math.round(ms / 1000)
394  if (seconds < 60) return `${seconds}s`
395  return `${Math.floor(seconds / 60)}m ${seconds % 60}s`
396}
397
398export function nextOf<T extends string | number>(list: readonly T[], current: T): T {
399  const at = list.indexOf(current)
400  return list[(at + 1) % list.length] ?? list[0]!
401}
402
403export const PALETTES: readonly PaletteChoice[] = ['auto', 'dark', 'contrast', 'colorblind', 'theme']
404export const ALERTS: readonly Alerts[] = ['notify', 'sound', 'both', 'off']
405export const PANELS: readonly PanelChoice[] = ['auto', 'off']
406// 80 is a comfortable reading measure; the menu cycles from it.
407export const WIDTHS: readonly number[] = [80, 70, 100, 120, 0]
408export const FONTS: readonly FontChoice[] = ['leave', 'readable', 'large']
409export const ICONS: readonly IconChoice[] = ['unicode', 'ascii']
410
411// The editor terminal settings each font choice writes. JetBrains Mono first, Menlo where it
412// is not installed; ligatures off so `!=` and `->` read as typed.
413const FONT_KEYS: Record<Exclude<FontChoice, 'leave'>, Record<string, unknown>> = {
414  readable: {
415    'terminal.integrated.fontFamily': "'JetBrains Mono', Menlo, monospace",
416    'terminal.integrated.fontSize': 13,
417    'terminal.integrated.lineHeight': 1.3,
418    'terminal.integrated.fontWeightBold': 'bold',
419    'terminal.integrated.fontLigatures.enabled': false,
420    'terminal.integrated.smoothScrolling': true,
421  },
422  large: {
423    'terminal.integrated.fontFamily': "'JetBrains Mono', Menlo, monospace",
424    'terminal.integrated.fontSize': 14,
425    'terminal.integrated.lineHeight': 1.35,
426    'terminal.integrated.fontWeightBold': 'bold',
427    'terminal.integrated.fontLigatures.enabled': false,
428    'terminal.integrated.smoothScrolling': true,
429  },
430}
431const FONT_KEY_NAMES = Object.keys(FONT_KEYS.readable)
432
433// Where the editor that hosts this terminal keeps its settings, from its environment.
434export function editorSettingsPath(env: { home?: string; termProgram?: string; askpass?: string; platform: 'mac' | 'linux' | 'other' }): string | null {
435  if (env.home === undefined || env.termProgram !== 'vscode' || env.platform === 'other') return null
436  const app = (env.askpass ?? '').includes('Cursor') ? 'Cursor' : 'Code'
437  return env.platform === 'mac' ? `${env.home}/Library/Application Support/${app}/User/settings.json` : `${env.home}/.config/${app}/User/settings.json`
438}
439
440export type FontEdit = { text: string; isChanged: boolean } | { error: string }
441
442// The editor's settings with clarity's font keys set (or, for `leave`, taken out). A file with
443// comments or trailing commas is not plain JSON: it is left alone rather than rewritten.
444export function applyFont(settingsText: string, choice: FontChoice): FontEdit {
445  let settings: Record<string, unknown>
446  try {
447    const parsed: unknown = settingsText.trim() === '' ? {} : JSON.parse(settingsText)
448    if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return { error: 'the settings file is not a JSON object' }
449    settings = parsed as Record<string, unknown>
450  } catch {
451    return { error: 'the settings file has comments or trailing commas' }
452  }
453  const next: Record<string, unknown> = { ...settings }
454  if (choice === 'leave') for (const key of FONT_KEY_NAMES) delete next[key]
455  else Object.assign(next, FONT_KEYS[choice])
456  const isChanged = JSON.stringify(next) !== JSON.stringify(settings)
457  return { text: `${JSON.stringify(next, null, 4)}\n`, isChanged }
458}
459
460export type CommandResult = { prefs: Prefs; text: string; open?: 'menu' | 'panel' }
461
462const HELP = '/clarity opens the menu · /clarity panel · on | off | focus | tools summary | tools full | status'
463
464export function runCommand(args: string, prefs: Prefs): CommandResult {
465  const [word, arg] = args.trim().toLowerCase().split(/\s+/)
466  const verb = word || 'menu'
467  switch (verb) {
468    case 'menu':
469      return { prefs, text: '', open: 'menu' }
470    case 'panel':
471      return { prefs, text: '', open: 'panel' }
472    case 'on':
473      return { prefs: { ...prefs, isOn: true }, text: 'on.' }
474    case 'off':
475      return { prefs: { ...prefs, isOn: false }, text: 'off: Claude Code draws everything as usual. /clarity on brings it back.' }
476    case 'focus': {
477      const isFocus = arg === 'on' ? true : arg === 'off' ? false : !prefs.isFocus
478      return {
479        prefs: { ...prefs, isOn: true, isFocus },
480        text: isFocus ? 'Focus on: notices and successful tool output are hidden.' : 'Focus off.',
481      }
482    }
483    case 'tools': {
484      const tools = arg === 'full' ? 'full' : arg === 'summary' ? 'summary' : prefs.tools === 'full' ? 'summary' : 'full'
485      return {
486        prefs: { ...prefs, tools },
487        text: tools === 'full' ? 'Tool rows are drawn in full.' : 'Tool rows are one line each; click one to open it.',
488      }
489    }
490    case 'status':
491      return { prefs, text: status(prefs) }
492    default:
493      return { prefs, text: HELP }
494  }
495}
496
497export function status(prefs: Prefs): string {
498  if (!prefs.isOn) return `off. ${HELP}`
499  return `on · colours ${prefs.palette} · tools ${prefs.tools} · focus ${prefs.isFocus ? 'on' : 'off'} · band ${prefs.band ? 'on' : 'off'} · alerts ${prefs.alerts}. ${HELP}`
500}
501
502export const COMPANIONS = ['lively', 'face', 'off'] as const
503
504export const DEFAULT_PREFS: Prefs = {
505  isOn: true,
506  isFocus: false,
507  tools: 'summary',
508  palette: 'auto',
509  alerts: 'notify',
510  band: true,
511  panel: 'auto',
512  measure: 80,
513  copy: true,
514  font: 'leave',
515  icons: 'unicode',
516  companion: 'lively',
517}
518
519function oneOf<T>(list: readonly T[], value: unknown, fallback: T): T {
520  return list.includes(value as T) ? (value as T) : fallback
521}
522
523export function readPrefs(stored: unknown): Prefs {
524  if (stored === null || typeof stored !== 'object') return DEFAULT_PREFS
525  const s = stored as Partial<Record<keyof Prefs, unknown>>
526  const bool = (v: unknown, d: boolean) => (typeof v === 'boolean' ? v : d)
527  return {
528    isOn: bool(s.isOn, DEFAULT_PREFS.isOn),
529    isFocus: bool(s.isFocus, DEFAULT_PREFS.isFocus),
530    tools: oneOf(['summary', 'full'] as const, s.tools, DEFAULT_PREFS.tools),
531    palette: oneOf(PALETTES, s.palette, DEFAULT_PREFS.palette),
532    alerts: oneOf(ALERTS, s.alerts, DEFAULT_PREFS.alerts),
533    band: bool(s.band, DEFAULT_PREFS.band),
534    panel: oneOf(PANELS, s.panel, DEFAULT_PREFS.panel),
535    measure: oneOf(WIDTHS, s.measure, DEFAULT_PREFS.measure),
536    copy: bool(s.copy, DEFAULT_PREFS.copy),
537    font: oneOf(FONTS, s.font, DEFAULT_PREFS.font),
538    icons: oneOf(ICONS, s.icons, DEFAULT_PREFS.icons),
539    // An early beta kept this as on or off.
540    companion: s.companion === true ? 'lively' : s.companion === false ? 'off' : oneOf(COMPANIONS, s.companion, DEFAULT_PREFS.companion),
541  }
542}
543
544export const EMPTY_LEDGER: Ledger = {
545  turns: [],
546  prompts: [],
547  files: {},
548  errors: [],
549  lastReply: '',
550  context: null,
551  cost: null,
552  limit: null,
553  stopped: null,
554  todos: [],
555  recent: [],
556  agents: 0,
557  summaries: {},
558}
559
560// Claude's plan, from a TodoWrite call's input; anything malformed is left out.
561export function parseTodos(input: unknown): Todo[] | null {
562  const todos = input !== null && typeof input === 'object' ? (input as { todos?: unknown }).todos : undefined
563  if (!Array.isArray(todos)) return null
564  return todos.flatMap((t: unknown): Todo[] => {
565    const content = field(t, 'content')
566    const status = field(t, 'status')
567    if (content === undefined || (status !== 'pending' && status !== 'in_progress' && status !== 'completed')) return []
568    return [{ content, status, activeForm: field(t, 'activeForm') ?? content }]
569  })
570}
571
572// `task 2/5`: the step Claude is on, counted from one.
573export function planProgress(todos: readonly Todo[]): { at: number; of: number; doing: string } | null {
574  const doing = todos.findIndex(t => t.status === 'in_progress')
575  if (todos.length === 0 || doing < 0) return null
576  return { at: doing + 1, of: todos.length, doing: todos[doing]?.activeForm ?? '' }
577}
578
579export type TurnSnapshot = { tools: number; errors: number; files: Record<string, FileChange> }
580
581// What a turn did: the difference between the session before it and after it.
582export function summarizeTurn(before: TurnSnapshot, after: TurnSnapshot): TurnSummary {
583  let files = 0
584  let added = 0
585  let removed = 0
586  for (const [path, change] of Object.entries(after.files)) {
587    const was = before.files[path] ?? { added: 0, removed: 0, edits: 0 }
588    if (change.edits > was.edits) files += 1
589    added += change.added - was.added
590    removed += change.removed - was.removed
591  }
592  return { tools: after.tools - before.tools, files, added, removed, failed: after.errors - before.errors }
593}
594
595export function runStatus(run: ToolRun): Status {
596  return run.running > 0 ? 'running' : run.failed > 0 ? 'error' : 'ok'
597}
598
599// `5:07 pm`, for the Recent list.
600export function formatClock(ms: number): string {
601  const d = new Date(ms)
602  const h = d.getHours()
603  return `${h % 12 === 0 ? 12 : h % 12}:${String(d.getMinutes()).padStart(2, '0')} ${h < 12 ? 'am' : 'pm'}`
604}
605export const IDLE: Activity = { phase: 'idle', tool: '', detail: '', since: 0, tokens: 0 }
606
607// State an earlier version of clarity wrote lacks the fields added since; a hot reload keeps
608// it. Reading through these fills in what is missing, so old state never breaks a hook.
609export function fillLedger(raw: unknown): Ledger {
610  const r = (raw !== null && typeof raw === 'object' ? raw : {}) as Partial<Record<keyof Ledger, unknown>>
611  const list = <T>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : [])
612  const record = <T>(v: unknown): Record<string, T> => (v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, T>) : {})
613  const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null)
614  return {
615    turns: list(r.turns),
616    prompts: list(r.prompts),
617    files: record(r.files),
618    errors: list(r.errors),
619    lastReply: typeof r.lastReply === 'string' ? r.lastReply : '',
620    context: num(r.context),
621    cost: num(r.cost),
622    limit: readLimit(r.limit),
623    stopped: typeof r.stopped === 'string' ? r.stopped : null,
624    todos: list(r.todos),
625    recent: list(r.recent),
626    agents: num(r.agents) ?? 0,
627    summaries: record(r.summaries),
628  }
629}
630
631function readLimit(v: unknown): Ledger['limit'] {
632  if (v === null || typeof v !== 'object') return null
633  const r = v as { percent?: unknown; resetsAt?: unknown }
634  if (typeof r.percent !== 'number') return null
635  return { percent: r.percent, resetsAt: typeof r.resetsAt === 'string' ? r.resetsAt : null }
636}
637
638// The limit nearest to running out, from Claude Code's report of the plan's limits.
639export function nearestLimit(limits: readonly { percentUsed: number; resetsAt?: string }[]): Ledger['limit'] {
640  const top = [...limits].sort((a, b) => b.percentUsed - a.percentUsed)[0]
641  return top === undefined ? null : { percent: top.percentUsed, resetsAt: top.resetsAt ?? null }
642}
643
644// Text over this many lines folds to its first lines until opened.
645export const FOLD_REPLY = 30
646export const FOLD_PROMPT = 12
647export const FOLD_SHOWN = 12
648
649// The first `shown` lines of a long text, with a code fence it cut open closed again so the
650// rest still draws as prose. Null when the text is short enough to show whole.
651export function foldText(text: string, over: number, shown = FOLD_SHOWN): { head: string; hidden: number } | null {
652  const lines = text.split('\n')
653  if (lines.length <= over) return null
654  const kept = lines.slice(0, shown)
655  const fences = kept.filter(line => /^\s*(```|~~~)/.test(line)).length
656  return { head: kept.join('\n') + (fences % 2 === 1 ? '\n```' : ''), hidden: lines.length - shown }
657}
658
659export function fillActivity(raw: unknown): Activity {
660  const r = (raw !== null && typeof raw === 'object' ? raw : {}) as Partial<Activity>
661  const phases = ['idle', 'thinking', 'writing', 'tool', 'waiting', 'compacting'] as const
662  return {
663    phase: phases.includes(r.phase as never) ? (r.phase as Activity['phase']) : 'idle',
664    tool: typeof r.tool === 'string' ? r.tool : '',
665    detail: typeof r.detail === 'string' ? r.detail : '',
666    since: typeof r.since === 'number' ? r.since : 0,
667    tokens: typeof r.tokens === 'number' ? r.tokens : 0,
668  }
669}
670
671// Every symbol clarity draws, and its plain ASCII stand-in for terminals or fonts without it.
672const ASCII: Record<string, string> = {
673  '▸': '>', '▾': 'v', '▴': '^', '✓': '+', '✗': 'x', '●': '*', '⧉': '#', '▤': '#', '☰': '=',
674  '━': '=', '─': '-', '│': '|', '↓': 'v', '…': '...', '⊘': '-', '▣': '#', '≡': '=', '○': 'o',
675  '❯': '>', '▮': '|', '█': '#', '░': '.', '·': '-', '−': '-', '→': '->', '×': 'x', '⎿': '\\',
676  '•': 'o', '‿': '_', '♥': '*', '♡': '.', '☁': '~', '☀': 'O', '☾': 'C', '⋆': '*', '♪': '~',
677}
678const ASCII_RE = new RegExp(`[${Object.keys(ASCII).join('')}]`, 'g')
679
680export function toAscii(text: string): string {
681  return text.replace(ASCII_RE, ch => ASCII[ch] ?? ch)
682}
683
684// Short tips the band shows, one at a time, while a turn runs long. Claude Code's own tips are
685// not readable by a mod, so these are clarity's.
686export const TIPS = [
687  'Esc stops Claude at any point.',
688  'Type @ in your prompt to add a file.',
689  '/compact frees context when it runs high.',
690  'Shift+Tab switches modes, like plan mode.',
691  'Ctrl+O shows every tool call in full.',
692  'Click a tool strip to open it.',
693  '/clarity panel shows the plan and changed files.',
694  '/clarity opens the settings.',
695]
696
697// The tip for this moment: a new one every 10 seconds, none in the first 6.
698export function tipAt(elapsedMs: number): string | null {
699  if (elapsedMs < 6000) return null
700  return TIPS[Math.floor((elapsedMs - 6000) / 10_000) % TIPS.length] ?? null
701}
702
703// How long the panel's prompt list is before it folds.
704export const PANEL_TURNS = 8
705
706// The companion: a small face in the band that shows how things are going. Each face has two
707// frames, swapped once a second while a turn runs, so it looks around, waves or works.
708const FACES = {
709  sleeping: ['(-.-)zz', '(-.-)zz'],
710  content: ['(^‿^)', '(^‿^)'],
711  thinking: ['(•.• )', '( •.•)'],
712  writing: ['(•‿•)_', '(•‿•)/'],
713  working: ['\\(•.•)', '(•.•)/'],
714  waiting: ['(•.•)?', '(-.-)?'],
715  tidying: ['(˘.˘)~', '(˘.˘) '],
716  worried: ['(•.•;)', '(;•.•)'],
717  stopped: ['(×_×)', '(×_×)'],
718} as const
719
720export type Mood = keyof typeof FACES
721
722// What the companion feels: work and waiting first, then worry near a usage limit,
723// and once idle for a while, sleep.
724export function moodOf(activity: Activity, ledger: Ledger, isResting: boolean): Mood {
725  const limit = ledger.limit?.percent ?? 0
726  if (activity.phase === 'idle') {
727    if (ledger.stopped !== null || limit >= 100) return 'stopped'
728    return isResting ? 'sleeping' : 'content'
729  }
730  if (activity.phase === 'waiting') return 'waiting'
731  if (activity.phase === 'compacting') return 'tidying'
732  if (limit >= 80) return 'worried'
733  if (activity.phase === 'thinking') return 'thinking'
734  return activity.phase === 'tool' ? 'working' : 'writing'
735}
736
737export function faceOf(mood: Mood, frame: number): string {
738  return FACES[mood][Math.abs(frame) % 2] ?? FACES[mood][0]
739}
740
741// After this long without a turn, the companion falls asleep.
742export const REST_MS = 5 * 60_000
743
744// What is left of a usage limit, as five hearts.
745export function hearts(percentUsed: number): { full: string; empty: string } {
746  const full = Math.max(0, Math.min(5, Math.ceil((100 - percentUsed) / 20)))
747  return { full: '♥'.repeat(full), empty: '♡'.repeat(5 - full) }
748}
749
750// The panel's sky: clouds by day, stars by night, and the sun or moon at the end. The clouds
751// drift a column a second while a turn runs, and the stars twinkle.
752export function sky(width: number, hour: number, frame: number): { clouds: string; body: string } {
753  const isNight = hour < 6 || hour >= 19
754  const span = Math.max(4, width - 3)
755  const row = Array.from({ length: span }, () => ' ')
756  if (isNight) {
757    for (let i = 0; i * 7 + 2 < span; i++) {
758      const at = (i * 7 + 2 + (i % 2) * 3) % span
759      row[at] = (i + frame) % 3 === 0 ? '⋆' : '·'
760    }
761  } else {
762    const shapes = ['☁☁', '☁', '☁☁☁']
763    shapes.forEach((shape, i) => {
764      const start = (((Math.floor((i * span) / shapes.length) + frame) % span) + span) % span
765      ;[...shape].forEach((ch, j) => {
766        if (ch !== ' ') row[(start + j) % span] = ch
767      })
768    })
769  }
770  return { clouds: row.join(''), body: isNight ? '☾' : '☀' }
771}
772
773export function greeting(hour: number): string {
774  if (hour >= 5 && hour < 12) return 'good morning'
775  if (hour >= 12 && hour < 17) return 'good afternoon'
776  if (hour >= 17 && hour < 23) return 'good evening'
777  return 'up late'
778}
779
780// Pip, the sprout who lives on clarity's boxes. It is drawn as pixel art: each grid is 8 pixels
781// wide and 6 tall, and each terminal cell holds two pixels, one above the other (▀ ▄ █), so
782// Pip stands 3 rows tall. `#` is its body, `e` its eyes, `b` its cheeks, `l` its leaf, `w` a
783// drop of sweat and `.` nothing.
784export type Pixel = 'body' | 'eye' | 'cheek' | 'leaf' | 'drop'
785export type PipCell = { ch: string; fg: Pixel | null; bg: Pixel | null }
786export type PipPose = { rows: PipCell[][]; x: number; bubble: string }
787
788const PIXELS: Record<string, Pixel> = { '#': 'body', e: 'eye', b: 'cheek', l: 'leaf', w: 'drop' }
789
790const PIP = {
791  standing: ['...ll...', '..####..', '.#e##e#.', '.#b##b#.', '..####..', '..#..#..'],
792  stepping: ['...ll...', '..####..', '.#e##e#.', '.#b##b#.', '..####..', '.#....#.'],
793  lookLeft: ['...ll...', '..####..', '.#e#e##.', '.#b##b#.', '..####..', '..#..#..'],
794  lookRight: ['...ll...', '..####..', '.##e#e#.', '.#b##b#.', '..####..', '..#..#..'],
795  blinking: ['...ll...', '..####..', '.######.', '.#b##b#.', '..####..', '..#..#..'],
796  cheering: ['...ll...', '#.####.#', '##e##e##', '.#b##b#.', '..####..', '........'],
797  worried: ['...ll...', '..####.w', '.#e##e#.', '.#b##b#.', '..####..', '..#..#..'],
798  worried2: ['...ll...', '..####..', '.#e##e#w', '.#b##b#.', '..####..', '..#..#..'],
799  sleeping: ['........', '........', '...ll...', '..####..', '.######.', '.#b##b#.'],
800  belly: ['..#..#..', '..####..', '.#b##b#.', '.#e##e#.', '..####..', '...ll...'],
801} as const
802
803export type PipFace = keyof typeof PIP
804
805// Pairs the pixel rows into cells. A cell with two different pixels draws the top one as the
806// glyph and the bottom one as its background.
807export function pipCells(grid: readonly string[], drop = 0): PipCell[][] {
808  const px = [...Array.from({ length: drop }, () => '........'), ...grid].slice(0, 6)
809  const cells: PipCell[][] = []
810  for (let y = 0; y < 6; y += 2) {
811    const top = px[y] ?? '........'
812    const bottom = px[y + 1] ?? '........'
813    const row: PipCell[] = []
814    for (let x = 0; x < 8; x++) {
815      const t = PIXELS[top[x] ?? '.'] ?? null
816      const b = PIXELS[bottom[x] ?? '.'] ?? null
817      if (t === null && b === null) row.push({ ch: ' ', fg: null, bg: null })
818      else if (t === b) row.push({ ch: '█', fg: t, bg: null })
819      else if (b === null) row.push({ ch: '▀', fg: t, bg: null })
820      else if (t === null) row.push({ ch: '▄', fg: b, bg: null })
821      else row.push({ ch: '▀', fg: t, bg: b })
822    }
823    cells.push(row)
824  }
825  return cells
826}
827
828// Where Pip is and what it does, for a mood, the second it is, and the room it has to walk in.
829// It paces while Claude works, hops when Claude waits on you, and stays put otherwise; the
830// spot it stopped at is where it rests, since the last tick keeps it there.
831export function pipPose(mood: Mood, frame: number, span: number): PipPose {
832  const room = Math.max(1, span - 9)
833  const lap = frame % (2 * room)
834  const paced = lap < room ? lap : 2 * room - lap
835  const isRight = lap < room
836  const at = (face: PipFace, x: number, bubble = '', drop = 0): PipPose => ({ rows: pipCells(PIP[face], drop), x, bubble })
837  const odd = frame % 2 === 1
838  switch (mood) {
839    case 'working':
840      return at(odd ? 'stepping' : isRight ? 'lookRight' : 'lookLeft', paced)
841    case 'writing':
842      return at(odd ? 'stepping' : 'standing', paced, odd ? '·' : '')
843    case 'tidying':
844      return at(odd ? 'stepping' : 'standing', paced, '~')
845    case 'thinking':
846      return at(odd ? 'lookRight' : 'lookLeft', paced, odd ? '°' : 'o')
847    case 'waiting':
848      return at(odd ? 'cheering' : 'standing', paced, '?', odd ? 0 : 1)
849    case 'worried':
850      return at(odd ? 'worried2' : 'worried', paced)
851    case 'stopped':
852      return at('belly', paced, '×')
853    case 'content':
854      return at(odd ? 'blinking' : 'cheering', paced, '♪')
855    case 'sleeping':
856      return at('sleeping', paced, odd ? 'z' : 'zz')
857  }
858}
859
hooks/rows.tsx 803 lines
1// Drawing, from the surface's element table: no `$`, so the transcript, the menu's live
2// preview, the band and the panel all draw from the same rows.
3import type { ElementTable, RenderElement } from 'claude-code'
4
5import type { Activity, Ledger, Prefs, TurnSummary } from '../types'
6import { MARK, PANEL_TURNS, activityText, clip, formatClock, formatDuration, formatTokens, hearts, kindOf, planProgress, shortPath, toAscii } from './logic'
7import type { Attachment, Block, Palette, PipCell, PipPose, Status } from './logic'
8
9export type UI = ElementTable<'terminal'>
10
11export type Look = { prefs: Prefs; colors: Palette; columns: number; isNarrow: boolean }
12
13// The element table with every symbol clarity draws swapped for plain ASCII, and borders drawn
14// in ASCII too. Everything clarity draws goes through the table, so this one wrap covers it all.
15export function asciiUI(ui: UI): UI {
16  const plain = (children: unknown): unknown =>
17    typeof children === 'string' ? toAscii(children) : Array.isArray(children) ? children.map(plain) : children
18  const table = { ...ui } as Record<string, unknown>
19  table.Text = (props: Record<string, unknown>) => (ui.Text as (p: unknown) => RenderElement)({ ...props, children: plain(props.children) })
20  table.Button = (props: Record<string, unknown>) =>
21    (ui.Button as (p: unknown) => RenderElement)({
22      ...props,
23      children: plain(props.children),
24      ...(typeof props.label === 'string' ? { label: toAscii(props.label) } : {}),
25    })
26  table.Box = (props: Record<string, unknown>) =>
27    (ui.Box as (p: unknown) => RenderElement)(props.borderStyle === undefined ? props : { ...props, borderStyle: 'classic' })
28  return table as unknown as UI
29}
30
31// A word on a coloured ground: dark text on the colour, or inverse where the theme has no hex.
32export function badge(ui: UI, colors: Palette, text: string, tone: string): RenderElement {
33  return colors.chipText === undefined ? (
34    <ui.Text color={tone} inverse bold>
35      {text}
36    </ui.Text>
37  ) : (
38    <ui.Text backgroundColor={tone} color={colors.chipText} bold>
39      {text}
40    </ui.Text>
41  )
42}
43
44export type Chip = { key: string; label: string; onPress: () => void; hotkey?: string; tone?: string }
45
46// A button: bracketed in its colour, filling in under the pointer. Filled words with no
47// brackets (badge) are labels, so nothing that only labels looks pressable.
48export function chip(ui: UI, look: Look, c: Chip): RenderElement {
49  const { colors } = look
50  const tone = c.tone ?? colors.you
51  const label = `[ ${c.label} ]`
52  const face =
53    // Under the pointer it lifts onto the bar's ground and brightens, staying in its colour.
54    colors.barBg === undefined ? (
55      <ui.Text color={tone} bold hover={{ color: colors.text, underline: true }}>
56        {label}
57      </ui.Text>
58    ) : (
59      <ui.Text color={tone} bold hover={{ backgroundColor: colors.accentBg, color: colors.text, underline: true }}>
60        {label}
61      </ui.Text>
62    )
63  // The keyed Box is what the pointer hovers, so the chip lights alone.
64  return (
65    <ui.Box key={`chip-${c.key}`}>
66      {c.hotkey === undefined ? (
67        <ui.Button key={c.key} plain onPress={c.onPress}>
68          {face}
69        </ui.Button>
70      ) : (
71        <ui.Button key={c.key} plain hotkey={c.hotkey} onPress={c.onPress}>
72          {face}
73        </ui.Button>
74      )}
75    </ui.Box>
76  )
77}
78
79const ATTACHMENT_ICON: Record<Attachment['kind'], string> = { file: '▤', folder: '▸', image: '▣', paste: '≡' }
80
81// What a prompt brought along, each in a small frame of its own, as files sit under a message
82// on claude.ai: the icon and name, then where it is or how long.
83export function attachmentCards(ui: UI, look: Look, attachments: readonly Attachment[]): RenderElement | null {
84  if (attachments.length === 0) return null
85  const { Box, Text } = ui
86  const { colors } = look
87  const tone = (a: Attachment) =>
88    a.kind === 'image' ? colors.kinds.web : a.kind === 'paste' ? colors.kinds.search : a.kind === 'folder' ? colors.kinds.write : colors.kinds.read
89  return (
90    <Box flexDirection="row" flexWrap="wrap" columnGap={1}>
91      {attachments.map(a => (
92        <Box borderStyle="round" borderColor={tone(a)} paddingX={1}>
93          <Text wrap="truncate">
94            <Text color={tone(a)} bold>
95              {ATTACHMENT_ICON[a.kind]} {clip(a.name, 28)}
96            </Text>
97            {a.detail !== '' && <Text color={colors.muted}> {clip(a.detail, 24)}</Text>}
98          </Text>
99        </Box>
100      ))}
101    </Box>
102  )
103}
104
105// The person's prompt: a rounded box in their colour, labelled, with what it brought along.
106export function userRow(ui: UI, look: Look, text: string, attachments: readonly Attachment[] = [], more?: Chip): RenderElement {
107  const { Box, Text } = ui
108  const { colors } = look
109  return (
110    <Box flexDirection="column" marginTop={1} borderStyle="round" borderColor={colors.you} paddingX={1} width={replyWidth(look) + (look.isNarrow ? 0 : 1)}>
111      {badge(ui, colors, ' you ', colors.you)}
112      <Text color={colors.text}>{text}</Text>
113      {more !== undefined && chip(ui, look, { ...more, tone: copyTone(colors) })}
114      {attachmentCards(ui, look, attachments)}
115    </Box>
116  )
117}
118
119export function claudeHeader(ui: UI, look: Look): RenderElement {
120  return badge(ui, look.colors, ' ● claude ', look.colors.claude)
121}
122
123// The width a reply's box takes: the person's line width plus the frame, never past the screen.
124function replyWidth(look: Look): number {
125  const room = Math.max(24, look.columns - (look.isNarrow ? 0 : 2))
126  return look.prefs.measure > 0 ? Math.min(room, look.prefs.measure + 4) : room
127}
128
129function copyTone(colors: Palette): string {
130  return colors.rule === 'subtle' ? 'inactive' : colors.muted
131}
132
133// One block of a reply in a soft frame: the `claude` badge on the first, copy chips at the foot.
134// `isOwnBody` false: the body holds Claude Code's own drawing, which may not sit under a sized Box.
135export function replyBox(ui: UI, look: Look, isFirst: boolean, body: RenderElement, chips: readonly Chip[], isOwnBody = true): RenderElement {
136  const { Box } = ui
137  const frame = {
138    flexDirection: 'column' as const,
139    marginTop: isFirst ? 1 : 0,
140    marginLeft: look.isNarrow ? 0 : 1,
141    borderStyle: 'round',
142    borderColor: look.colors.rule,
143    paddingX: 1,
144  }
145  return (
146    <Box {...frame} {...(isOwnBody ? { width: replyWidth(look) } : {})}>
147      {isFirst && claudeHeader(ui, look)}
148      {body}
149      {chips.length > 0 && (
150        <Box flexDirection="row" gap={1}>
151          {chips.map(c => chip(ui, look, { ...c, tone: copyTone(look.colors) }))}
152        </Box>
153      )}
154    </Box>
155  )
156}
157
158// A reply's paragraphs with a line of room between them, and each code block in its own
159// frame with its language and a copy chip.
160export function replyBlocks(ui: UI, look: Look, blocks: readonly Block[], onCopy?: (code: string) => void): RenderElement {
161  const { Box, Markdown } = ui
162  const { colors } = look
163  return (
164    <Box flexDirection="column">
165      {blocks.map((block, i) =>
166        block.kind === 'prose' ? (
167          <Box marginTop={i === 0 ? 0 : 1}>
168            <Markdown text={block.text} />
169          </Box>
170        ) : (
171          <Box flexDirection="column" marginTop={i === 0 ? 0 : 1} borderStyle="single" borderColor={colors.rule} paddingX={1}>
172            <Box flexDirection="row" justifyContent="space-between">
173              {badge(ui, colors, ` ${block.lang === '' ? 'code' : block.lang} `, colors.tool)}
174              {onCopy !== undefined && chip(ui, look, { key: `copy-code-${i}`, label: '⧉ copy', tone: copyTone(colors), onPress: () => onCopy(block.body) })}
175            </Box>
176            <Markdown text={block.text} />
177          </Box>
178        ),
179      )}
180    </Box>
181  )
182}
183
184export type ToolParts = {
185  tools: readonly { tool: string; label: string }[]
186  detail: string
187  status: Status
188  isOpen?: boolean
189  /** An edit's lines in and out, drawn green and red before its file. */
190  delta?: { added: number; removed: number }
191}
192
193function markColor(colors: Palette, status: Status): string {
194  return status === 'error' ? colors.error : status === 'running' ? colors.warn : status === 'interrupted' ? colors.muted : colors.ok
195}
196
197function badgesWidth(parts: ToolParts): number {
198  return parts.tools.reduce((n, t) => n + t.label.length + 3, 0)
199}
200
201// `▸ [Read ×2] [Grep] detail ✓`: each tool a badge in the colour of what it does.
202function toolFace(ui: UI, look: Look, parts: ToolParts, room: number): RenderElement[] {
203  const { Text } = ui
204  const { colors } = look
205  const badges = parts.tools.flatMap((t, i) => [
206    ...(i === 0 ? [] : [<Text> </Text>]),
207    badge(ui, colors, ` ${t.label} `, parts.status === 'error' ? colors.error : colors.kinds[kindOf(t.tool)]),
208  ])
209  const delta = parts.delta
210  return [
211    <Text color={colors.muted}>{parts.isOpen === true ? '▾ ' : '▸ '}</Text>,
212    ...badges,
213    ...(delta === undefined
214      ? []
215      : [
216          <Text color={colors.ok} bold>
217            {' '}+{delta.added}
218          </Text>,
219          <Text color={colors.error} bold>
220            {' '}−{delta.removed}
221          </Text>,
222        ]),
223    <Text color={colors.text}> {clip(parts.detail, room)} </Text>,
224    <Text color={markColor(colors, parts.status)} bold>
225      {MARK[parts.status]}
226    </Text>,
227  ]
228}
229
230// A tool row on a tinted strip; a press opens or folds it where it stands.
231export function toolLine(ui: UI, look: Look, parts: ToolParts, onPress?: () => void): RenderElement {
232  const { Box, Button, Text } = ui
233  const face = toolFace(ui, look, parts, look.columns - badgesWidth(parts) - 12)
234  return (
235    <Box marginLeft={look.isNarrow ? 0 : 2} paddingX={1} backgroundColor={look.colors.accentBg}>
236      {onPress === undefined ? (
237        <Text wrap="truncate">{face}</Text>
238      ) : (
239        <Button key="row" plain onPress={onPress}>
240          {face}
241        </Button>
242      )}
243    </Box>
244  )
245}
246
247// An opened row: a box in the tool colour, its line to fold it, the full row inside.
248export function openedRow(ui: UI, look: Look, parts: ToolParts, onFold: () => void, body: RenderElement): RenderElement {
249  const { Box, Button } = ui
250  return (
251    <Box
252      flexDirection="column"
253      marginLeft={look.isNarrow ? 0 : 2}
254      borderStyle="round"
255      borderColor={look.colors.kinds[kindOf(parts.tools[0]?.tool ?? '')]}
256      paddingX={1}
257    >
258      <Button key="row" plain onPress={onFold}>
259        {toolFace(ui, look, { ...parts, isOpen: true }, look.columns - badgesWidth(parts) - 14)}
260      </Button>
261      {body}
262    </Box>
263  )
264}
265
266// A failure: a red box with what failed on top and the full row inside.
267export function failHeader(ui: UI, look: Look, tool: string, detail: string, body: RenderElement): RenderElement {
268  const { Box, Text } = ui
269  return (
270    <Box flexDirection="column" marginLeft={look.isNarrow ? 0 : 2} borderStyle="round" borderColor={look.colors.error} paddingX={1}>
271      <Text color={look.colors.error} bold wrap="truncate">
272        ✗ {tool} failed{detail === '' ? '' : ` · ${clip(detail, look.columns - tool.length - 18)}`}
273      </Text>
274      {body}
275    </Box>
276  )
277}
278
279// The end of a turn: a rule with the time, so turns read as blocks.
280export function turnRule(ui: UI, look: Look, durationMs: number): RenderElement {
281  const label = ` ${formatDuration(durationMs)} `
282  const right = Math.max(0, Math.max(12, look.columns - 2) - 2 - label.length)
283  return (
284    <ui.Box>
285      <ui.Text color={look.colors.rule}>{'━━' + label + '━'.repeat(right)}</ui.Text>
286    </ui.Box>
287  )
288}
289
290// A slash command's output in a titled card.
291export function card(ui: UI, look: Look, title: string, body: RenderElement, isErrored: boolean): RenderElement {
292  const tone = isErrored ? look.colors.error : look.colors.claude
293  return (
294    <ui.Box flexDirection="column" borderStyle="round" borderColor={tone} paddingX={1}>
295      {badge(ui, look.colors, ` ${title} `, tone)}
296      {body}
297    </ui.Box>
298  )
299}
300
301export function questionBanner(ui: UI, look: Look, body: RenderElement): RenderElement {
302  return (
303    <ui.Box flexDirection="column" borderStyle="double" borderColor={look.colors.warn} paddingX={1}>
304      {badge(ui, look.colors, ' ❯ Claude needs your answer ', look.colors.warn)}
305      {body}
306    </ui.Box>
307  )
308}
309
310// The close of a long turn: what it did while you looked away.
311export function awayCard(ui: UI, look: Look, durationMs: number, summary: TurnSummary, sitter: PipPose | null = null): RenderElement {
312  const { Box, Text } = ui
313  const { colors } = look
314  const facts: { text: string; tone: string }[] = [
315    { text: `${summary.tools} tool call${summary.tools === 1 ? '' : 's'}`, tone: colors.tool },
316    ...(summary.files > 0 ? [{ text: `${summary.files} file${summary.files === 1 ? '' : 's'} changed (+${summary.added} −${summary.removed})`, tone: colors.kinds.write }] : []),
317    ...(summary.failed > 0 ? [{ text: `${summary.failed} failed`, tone: colors.error }] : []),
318  ]
319  const card = (
320    <Box flexDirection="column" marginTop={sitter === null ? 1 : 0} marginLeft={look.isNarrow ? 0 : 1} borderStyle="round" borderColor={colors.claude} paddingX={1}>
321      <Text>
322        {badge(ui, colors, ' While you were away ', colors.claude)}
323        <Text color={colors.muted}> {formatDuration(durationMs)}</Text>
324      </Text>
325      <Text wrap="wrap">
326        {facts.map((f, i) => (
327          <Text>
328            {i === 0 ? '' : <Text color={colors.rule}> · </Text>}
329            <Text color={f.tone} bold>
330              {f.text}
331            </Text>
332          </Text>
333        ))}
334      </Text>
335    </Box>
336  )
337  // Pip sits on the card's top edge, glad you are back.
338  return sitter === null ? (
339    card
340  ) : (
341    <Box flexDirection="column" marginTop={1}>
342      {pip(ui, colors, sitter)}
343      {card}
344    </Box>
345  )
346}
347
348// Pip, drawn from its cells: the top `rows` of it, so it can peek over a box, with what it is
349// saying beside its head. Cells of the same colours share one Text.
350export function pip(ui: UI, colors: Palette, pose: PipPose, rows = 3): RenderElement {
351  const { Box, Text } = ui
352  const paint = { body: colors.kinds.search, eye: colors.chipText ?? colors.text, cheek: colors.error, leaf: colors.ok, drop: colors.kinds.read }
353  const runs = (row: PipCell[]) => {
354    const out: { text: string; fg: PipCell['fg']; bg: PipCell['bg'] }[] = []
355    for (const c of row) {
356      const last = out[out.length - 1]
357      if (last !== undefined && last.fg === c.fg && last.bg === c.bg) last.text += c.ch
358      else out.push({ text: c.ch, fg: c.fg, bg: c.bg })
359    }
360    return out
361  }
362  return (
363    <Box flexDirection="column" paddingLeft={pose.x}>
364      {pose.rows.slice(0, rows).map((row, y) => (
365        <Text wrap="truncate">
366          {runs(row).map(r =>
367            r.fg === null ? (
368              r.text
369            ) : (
370              <Text color={paint[r.fg]} backgroundColor={r.bg === null ? undefined : paint[r.bg]}>
371                {r.text}
372              </Text>
373            ),
374          )}
375          {y === 0 && pose.bubble !== '' && <Text color={colors.muted}> {pose.bubble}</Text>}
376        </Text>
377      ))}
378    </Box>
379  )
380}
381
382function meter(percent: number, cells: number): { full: string; empty: string } {
383  const full = Math.round((Math.max(0, Math.min(100, percent)) / 100) * cells)
384  return { full: '█'.repeat(full), empty: '░'.repeat(cells - full) }
385}
386
387// Green with room to spare, yellow past half, red near the end.
388function levelColor(colors: Palette, percent: number): string {
389  return percent >= 80 ? colors.error : percent >= 50 ? colors.warn : colors.ok
390}
391
392function phaseColor(colors: Palette, activity: Activity): string {
393  if (activity.phase === 'waiting' || activity.phase === 'compacting') return colors.warn
394  if (activity.phase === 'idle') return colors.ok
395  return activity.phase === 'tool' ? colors.kinds[kindOf(activity.tool)] : colors.claude
396}
397
398function phaseLabel(activity: Activity, face: string | null): string {
399  if (face !== null) return ` ${face} `
400  return activity.phase === 'idle' ? ' ✓ ' : activity.phase === 'waiting' ? ' ❯ ' : ' ● '
401}
402
403// The phase, as a coloured badge: a symbol, or the companion's face when it is on.
404function phaseBadge(ui: UI, colors: Palette, activity: Activity, face: string | null = null): RenderElement {
405  return badge(ui, colors, phaseLabel(activity, face), phaseColor(colors, activity))
406}
407
408export type BandActions = { panel: () => void; menu: () => void; copy?: () => void }
409
410// The toolbar above the prompt: what Claude is doing, what changed, context, and chips.
411export type TurnStats = { elapsedMs: number; tokens: number; tip: string | null; face: string | null; pip: PipPose | null }
412
413export function band(ui: UI, look: Look, activity: Activity, ledger: Ledger, width: number, stats: TurnStats, actions: BandActions): RenderElement {
414  const { Box, Text } = ui
415  const { colors } = look
416  const files = Object.keys(ledger.files).length
417  // In order of what matters most when room is short.
418  const plan = planProgress(ledger.todos)
419  // A plan usage limit shows once it passes 80%, with when it resets.
420  const limit = ledger.limit !== null && ledger.limit.percent >= 80 ? ledger.limit : null
421  const resets = limit?.resetsAt != null && !Number.isNaN(Date.parse(limit.resetsAt)) ? ` · resets ${formatClock(Date.parse(limit.resetsAt))}` : ''
422  const wanted: { text: string; tone: string }[] = [
423    ...(limit !== null ? [{ text: `limit ${Math.round(limit.percent)}%${resets}`, tone: limit.percent >= 95 ? colors.error : colors.warn }] : []),
424    ...(ledger.errors.length > 0 ? [{ text: `${ledger.errors.length} failed`, tone: colors.error }] : []),
425    ...(plan !== null ? [{ text: `task ${plan.at}/${plan.of}`, tone: colors.claude }] : []),
426    ...(ledger.agents > 0 ? [{ text: `${ledger.agents} agent${ledger.agents === 1 ? '' : 's'}`, tone: colors.kinds.agent }] : []),
427    ...(ledger.context !== null ? [{ text: `context ${Math.round(ledger.context)}%`, tone: levelColor(colors, ledger.context) }] : []),
428    ...(files > 0 ? [{ text: `${files} file${files === 1 ? '' : 's'} changed`, tone: colors.kinds.write }] : []),
429  ]
430  // No hotkeys here: the terminal prints them as `c:` before each chip, which crowds the bar.
431  const chips: Chip[] = [
432    ...(actions.copy === undefined ? [] : [{ key: 'copy', label: '⧉ copy reply', onPress: actions.copy }]),
433    { key: 'panel', label: '▤ session', onPress: actions.panel },
434    { key: 'menu', label: '☰ settings', onPress: actions.menu },
435  ]
436  // Each button is `[ label ]` (four more than its label) with a column between, after a gap of two.
437  const chipsWidth = chips.reduce((n, c) => n + c.label.length + 5, 0) + 2
438  // While a turn runs: what it is doing, how long, and how much it has written, as the
439  // stock spinner says it (`Thinking · 1m 42s · ↓ 8.5k tokens`).
440  const running = activity.phase === 'idle' ? [] : [
441    ...(stats.elapsedMs >= 1000 ? [formatDuration(stats.elapsedMs)] : []),
442    ...(stats.tokens > 0 ? [`↓ ${formatTokens(stats.tokens)} tokens`] : []),
443  ]
444  // A turn that died on an error says so, in red, until the next one starts.
445  const isStopped = activity.phase === 'idle' && ledger.stopped !== null
446  const doingParts = isStopped ? [`Stopped: ${ledger.stopped}`] : [activityText(activity), ...running]
447  const doing = doingParts.join(' · ')
448  // The status comes first: it keeps up to 48 columns (enough for the step, its time and its
449  // tokens) before any fact gets a place; each fact then shows whole or not at all.
450  const badgeWidth = phaseLabel(activity, stats.face).length + 1
451  let room = width - 2 - chipsWidth - badgeWidth - Math.min(doing.length, 48)
452  const facts = wanted.filter(f => {
453    const cost = f.text.length + 3
454    if (cost > room) return false
455    room -= cost
456    return true
457  })
458  const statusRoom = Math.max(8, width - 2 - chipsWidth - badgeWidth - facts.reduce((n, f) => n + f.text.length + 3, 0))
459  // Short of room, the status sheds its tokens, then its time, whole; only the step itself is cut.
460  let shown = doingParts
461  while (shown.length > 1 && shown.join(' · ').length > statusRoom) shown = shown.slice(0, -1)
462  const status = clip(shown.join(' · '), statusRoom)
463  const tone = isStopped ? colors.error : phaseColor(colors, activity)
464  const line = (
465    <Box flexDirection="row" justifyContent="space-between" width={width} paddingX={1} backgroundColor={colors.barBg}>
466      {/* The status gives way first; the chips keep their size so they never wrap. */}
467      <Box flexShrink={1} overflow="hidden">
468      <Text wrap="truncate">
469        {isStopped ? badge(ui, colors, stats.face === null ? ' ✗ ' : ` ${stats.face} `, colors.error) : phaseBadge(ui, colors, activity, stats.face)}
470        <Text color={tone} bold>
471          {' '}
472          {status}
473        </Text>
474        {facts.map(f => (
475          <Text>
476            <Text color={colors.rule}> │ </Text>
477            <Text color={f.tone} bold>
478              {f.text}
479            </Text>
480          </Text>
481        ))}
482      </Text>
483      </Box>
484      <Box flexDirection="row" gap={1} marginLeft={2} flexShrink={0}>
485        {chips.map(c => chip(ui, look, c))}
486      </Box>
487    </Box>
488  )
489  // During a long turn, a tip under the bar, one at a time. Pip peeks over the bar's top edge.
490  const hasTip = activity.phase !== 'idle' && stats.tip !== null
491  if (!hasTip && stats.pip === null) return line
492  return (
493    <Box flexDirection="column">
494      {stats.pip !== null && pip(ui, colors, stats.pip, 2)}
495      {line}
496      {hasTip && (
497        <Box paddingX={1}>
498          <Text color={colors.muted} italic wrap="truncate">
499            Tip: {stats.tip}
500          </Text>
501        </Box>
502      )}
503    </Box>
504  )
505}
506
507// The sidebar: what is happening, the turns so far, what changed, what failed.
508export type PanelActions = { copyTurn: (index: number) => void; toggleTurns: () => void; isAllTurns: boolean }
509// The companion's face, and the sky over the panel, when the companion is on.
510export type PanelMood = { face: string; sky: { clouds: string; body: string }; greeting: string; pip: PipPose | null } | null
511
512export function panel(ui: UI, look: Look, activity: Activity, ledger: Ledger, width: number, actions: PanelActions, mood: PanelMood = null): RenderElement {
513  const { Box, Button, Text } = ui
514  const { colors } = look
515  const heading = (title: string, count: number | string, tone: string) => (
516    <Box marginTop={1} paddingX={1} backgroundColor={colors.barBg} width={width} justifyContent="space-between">
517      {badge(ui, colors, ` ${title} `, tone)}
518      <Text color={colors.muted}>{count}</Text>
519    </Box>
520  )
521  const empty = (text: string) => (
522    <Text color={colors.muted} italic>
523      {text}
524    </Text>
525  )
526  const files = Object.entries(ledger.files)
527  const biggest = Math.max(1, ...files.map(([, c]) => c.added + c.removed))
528  const turns = ledger.turns.slice(actions.isAllTurns ? -50 : -PANEL_TURNS)
529  const firstTurn = ledger.turns.length - turns.length + 1
530  const isFolded = ledger.turns.length > PANEL_TURNS
531  const cells = Math.max(6, Math.min(20, width - 20))
532  const level = ledger.context === null ? null : meter(ledger.context, cells)
533  const done = ledger.todos.filter(t => t.status === 'completed').length
534  const left = ledger.limit === null ? null : hearts(ledger.limit.percent)
535  const resets = ledger.limit?.resetsAt != null && !Number.isNaN(Date.parse(ledger.limit.resetsAt)) ? ` · resets ${formatClock(Date.parse(ledger.limit.resetsAt))}` : ''
536  return (
537    <Box flexDirection="column" width={width}>
538      {mood !== null && (
539        <Box flexDirection="row" justifyContent="space-between" paddingX={1}>
540          <Text color={colors.muted} italic>
541            {mood.greeting}
542          </Text>
543          <Text wrap="truncate">
544            <Text color={colors.muted}>{mood.sky.clouds}</Text>
545            <Text color={colors.warn}> {mood.sky.body}</Text>
546          </Text>
547        </Box>
548      )}
549      {/* Pip walks along the top of the Now box. */}
550      {mood?.pip != null && pip(ui, colors, mood.pip)}
551      {/* Now: what Claude is doing, and how full the context is. */}
552      <Box flexDirection="column" borderStyle="round" borderColor={phaseColor(colors, activity)} paddingX={1}>
553        <Text wrap="truncate">
554          {phaseBadge(ui, colors, activity, mood?.face ?? null)}
555          <Text color={phaseColor(colors, activity)} bold>
556            {' '}
557            {activityText(activity)}
558          </Text>
559        </Text>
560        {ledger.context !== null && level !== null && (
561          <Text>
562            <Text color={colors.muted}>context </Text>
563            <Text color={levelColor(colors, ledger.context)}>{level.full}</Text>
564            <Text color={colors.rule}>{level.empty}</Text>
565            <Text color={levelColor(colors, ledger.context)} bold>
566              {' '}
567              {Math.round(ledger.context)}%
568            </Text>
569            {ledger.cost !== null && <Text color={colors.muted}>  ${ledger.cost.toFixed(2)}</Text>}
570          </Text>
571        )}
572        {ledger.limit !== null && left !== null && (
573          <Text wrap="truncate">
574            <Text color={colors.muted}>limit   </Text>
575            <Text color={levelColor(colors, ledger.limit.percent)}>{left.full}</Text>
576            <Text color={colors.rule}>{left.empty}</Text>
577            <Text color={colors.muted}>
578              {' '}
579              {Math.max(0, 100 - Math.round(ledger.limit.percent))}% left{resets}
580            </Text>
581          </Text>
582        )}
583      </Box>
584      {ledger.todos.length > 0 && heading('Plan', `${done} of ${ledger.todos.length} done`, colors.claude)}
585      {ledger.todos.length > 0 && (
586        <Box flexDirection="column" paddingX={1}>
587          {ledger.todos.slice(0, 10).map(t => (
588            <Text wrap="truncate">
589              {t.status === 'completed' ? (
590                <Text color={colors.ok}>✓ </Text>
591              ) : t.status === 'in_progress' ? (
592                <Text color={colors.claude} bold>
593                  ▸{' '}
594                </Text>
595              ) : (
596                <Text color={colors.rule}>○ </Text>
597              )}
598              <Text color={t.status === 'in_progress' ? colors.text : colors.muted} bold={t.status === 'in_progress'} strikethrough={t.status === 'completed'}>
599                {t.status === 'in_progress' ? t.activeForm : t.content}
600              </Text>
601            </Text>
602          ))}
603        </Box>
604      )}
605      {heading('Changed', files.length === 1 ? '1 file' : `${files.length} files`, colors.kinds.write)}
606      <Box flexDirection="column" paddingX={1}>
607        {files.length === 0 && empty('No files changed yet.')}
608        {files.slice(-12).map(([path, change]) => {
609          const share = Math.max(1, Math.round(((change.added + change.removed) / biggest) * 5))
610          const greens = Math.round((change.added / Math.max(1, change.added + change.removed)) * share)
611          return (
612            <Text wrap="truncate">
613              <Text color={colors.ok}>{'▮'.repeat(greens)}</Text>
614              <Text color={colors.error}>{'▮'.repeat(share - greens)}</Text>
615              <Text>{' '.repeat(6 - share)}</Text>
616              <Text color={colors.text} bold>
617                {shortPath(path)}
618              </Text>
619              <Text color={colors.ok}> +{change.added}</Text>
620              <Text color={colors.error}> −{change.removed}</Text>
621            </Text>
622          )
623        })}
624      </Box>
625      {ledger.errors.length > 0 && heading('Failed', ledger.errors.length, colors.error)}
626      {ledger.errors.length > 0 && (
627        <Box flexDirection="column" paddingX={1}>
628          {ledger.errors.slice(-5).map(err => (
629            <Text wrap="truncate">
630              <Text color={colors.error} bold>
631                ✗ {err.tool}
632              </Text>
633              <Text color={colors.muted}> {err.detail || err.text}</Text>
634            </Text>
635          ))}
636        </Box>
637      )}
638      {ledger.recent.length > 0 && heading('Recent', 'latest first', colors.tool)}
639      {ledger.recent.length > 0 && (
640        <Box flexDirection="column" paddingX={1}>
641          {ledger.recent
642            .slice(-6)
643            .reverse()
644            .map(r => (
645              <Text wrap="truncate">
646                <Text color={colors.rule}>{formatClock(r.at).padStart(8)}  </Text>
647                <Text color={r.isOk ? colors.kinds[kindOf(r.tool)] : colors.error} bold>
648                  {r.tool}
649                </Text>
650                <Text color={colors.muted}> {r.detail}</Text>
651              </Text>
652            ))}
653        </Box>
654      )}
655      {heading('Your prompts', turns.length === 0 ? '' : 'click to copy', colors.you)}
656      <Box flexDirection="column" paddingX={1}>
657        {turns.length === 0 && empty('Nothing asked yet.')}
658        {turns.map((text, i) => {
659          const n = firstTurn + i
660          const isLatest = i === turns.length - 1
661          return (
662            <Box key={`turn-${n}`}>
663              <Button key={`copy-turn-${n}`} plain onPress={() => actions.copyTurn(n - 1)}>
664                <Text color={isLatest ? colors.you : colors.rule} bold>
665                  {String(n).padStart(2)}
666                </Text>
667                <Text color={isLatest ? colors.text : colors.muted} hover={{ color: colors.you, underline: true }}>
668                  {'  '}
669                  {clip(text, Math.max(8, width - 8))}
670                </Text>
671              </Button>
672            </Box>
673          )
674        })}
675        {isFolded &&
676          chip(ui, look, {
677            key: 'all-turns',
678            label: actions.isAllTurns ? '▴ show fewer' : `▾ show all ${Math.min(ledger.turns.length, 50)}`,
679            tone: copyTone(colors),
680            onPress: actions.toggleTurns,
681          })}
682      </Box>
683    </Box>
684  )
685}
686
687export type MenuOption = { value: string; label: string }
688
689// One setting: its label (a press, or its number key, steps to the next choice) and every
690// choice as a chip, the current one filled.
691export type MenuSetting = {
692  key: string
693  hotkey: string
694  label: string
695  hint: string
696  options: readonly MenuOption[]
697  current: string
698  pick: (value: string) => void
699}
700
701export type MenuSection = { title: string; tone: string; settings: readonly MenuSetting[] }
702
703const LABEL_WIDTH = 17
704
705function optionChip(ui: UI, look: Look, key: string, label: string, isCurrent: boolean, onPress: () => void): RenderElement {
706  const { colors } = look
707  const text = ` ${label} `
708  const face = isCurrent ? (
709    badge(ui, colors, text, colors.you)
710  ) : (
711    <ui.Text color={colors.muted} hover={{ color: colors.text, bold: true }}>
712      {text}
713    </ui.Text>
714  )
715  return (
716    <ui.Box key={`opt-${key}`}>
717      <ui.Button key={key} plain onPress={onPress}>
718        {face}
719      </ui.Button>
720    </ui.Box>
721  )
722}
723
724function settingRow(ui: UI, look: Look, setting: MenuSetting): RenderElement {
725  const { Box, Button, Text } = ui
726  const { colors } = look
727  const at = Math.max(0, setting.options.findIndex(o => o.value === setting.current))
728  const next = setting.options[(at + 1) % setting.options.length]
729  return (
730    <Box key={`set-${setting.key}`} flexDirection="column">
731      <Box flexDirection="row">
732        <Box key={`label-${setting.key}`} width={LABEL_WIDTH} flexShrink={0}>
733          <Button key={`cycle-${setting.key}`} plain hotkey={setting.hotkey} onPress={() => next !== undefined && setting.pick(next.value)}>
734            <Text color={colors.text} bold hover={{ color: colors.you }}>
735              {setting.label}
736            </Text>
737          </Button>
738        </Box>
739        <Box flexDirection="row" flexWrap="wrap">
740          {setting.options.map(o => optionChip(ui, look, `${setting.key}-${o.value}`, o.label, o.value === setting.current, () => setting.pick(o.value)))}
741        </Box>
742      </Box>
743      {/* The description sits on its own line under the choices, dim and set in. */}
744      {setting.hint !== '' && (
745        <Box paddingLeft={LABEL_WIDTH}>
746          <Text color={colors.muted} italic wrap="wrap">
747            {setting.hint}
748          </Text>
749        </Box>
750      )}
751    </Box>
752  )
753}
754
755export function menu(ui: UI, look: Look, sections: readonly MenuSection[], footer: readonly string[]): RenderElement {
756  const { Box, Text } = ui
757  const { colors } = look
758  return (
759    <Box flexDirection="column">
760      <Box paddingX={1} backgroundColor={colors.barBg}>
761        {badge(ui, colors, ' clarity ', colors.claude)}
762        <Text color={colors.muted}> settings</Text>
763      </Box>
764      {sections.map(section => (
765        <Box flexDirection="column" marginTop={1} paddingX={1}>
766          {badge(ui, colors, ` ${section.title} `, section.tone)}
767          {section.settings.map((setting, i) => (
768            <Box key={`gap-${setting.key}`} marginTop={i === 0 ? 0 : 1}>
769              {settingRow(ui, look, setting)}
770            </Box>
771          ))}
772        </Box>
773      ))}
774      <Box flexDirection="column" marginTop={1} paddingX={1}>
775        {footer.map(line => (
776          <Text color={colors.muted} wrap="wrap">
777            {line}
778          </Text>
779        ))}
780      </Box>
781      <Box flexDirection="column" marginTop={1} paddingX={1}>
782        {badge(ui, colors, ' Preview ', colors.rule === 'subtle' ? 'inactive' : colors.muted)}
783        {preview(ui, { ...look, columns: Math.min(look.columns - 4, 64) })}
784      </Box>
785    </Box>
786  )
787}
788
789// A sample turn in the current look, so a change in the menu shows at once.
790export function preview(ui: UI, look: Look): RenderElement {
791  const { Box, Text } = ui
792  return (
793    <Box flexDirection="column" borderStyle="round" borderColor={look.colors.rule} paddingX={1}>
794      {userRow(ui, look, 'add rate limiting to the api')}
795      {replyBox(ui, look, true, <Text color={look.colors.text}>I'll check the server first.</Text>, [])}
796      {toolLine(ui, look, { tools: [{ tool: 'Read', label: 'Read ×2' }, { tool: 'Grep', label: 'Grep' }], detail: '', status: 'ok' })}
797      {toolLine(ui, look, { tools: [{ tool: 'Bash', label: 'Bash' }], detail: 'npm test', status: 'ok' })}
798      {toolLine(ui, look, { tools: [{ tool: 'Edit', label: 'Edit' }], detail: 'src/server.ts', status: 'running' })}
799      {turnRule(ui, look, 42000)}
800    </Box>
801  )
802}
803
types/index.d.ts 111 lines
1export type ToolDetail = 'summary' | 'full'
2export type PaletteChoice = 'auto' | 'dark' | 'contrast' | 'colorblind' | 'theme'
3export type PaletteName = Exclude<PaletteChoice, 'auto'>
4export type Alerts = 'off' | 'notify' | 'sound' | 'both'
5export type PanelChoice = 'auto' | 'off'
6/** The editor terminal's font: clarity's readable sizes, or left as the person has it. */
7export type FontChoice = 'leave' | 'readable' | 'large'
8/** Symbols as drawn: unicode, or plain ASCII for terminals and fonts without them. */
9export type IconChoice = 'unicode' | 'ascii'
10
11export type CompanionChoice = 'lively' | 'face' | 'off'
12
13export type Prefs = {
14  /** The mod draws at all; off hands every row back to the engine. */
15  isOn: boolean
16  /** Focus hides notices and successful tool output entirely. */
17  isFocus: boolean
18  tools: ToolDetail
19  palette: PaletteChoice
20  alerts: Alerts
21  /** The status band above the prompt. */
22  band: boolean
23  /** auto opens the session panel beside the transcript once the terminal is wide enough. */
24  panel: PanelChoice
25  /** The widest a reply's prose runs, in columns; 0 for the full width. (Was `width`, whose
26   *  100-column default read too long: renamed so stored prefs take the new default.) */
27  measure: number
28  copy: boolean
29  font: FontChoice
30  icons: IconChoice
31  /** lively: Pip walks on the band and the panel, beside the face; face: the face alone. */
32  companion: CompanionChoice
33}
34
35export type Env = {
36  /** The person's /config theme, which `auto` follows. */
37  theme: string
38}
39
40export type Phase = 'idle' | 'thinking' | 'writing' | 'tool' | 'waiting' | 'compacting'
41
42/** What the main loop is doing now, for the band and the spinner. */
43export type Activity = {
44  phase: Phase
45  tool: string
46  detail: string
47  /** When the turn began, ms. */
48  since: number
49  /** Tokens the model has written this turn: estimated as it streams, exact at each step's end. */
50  tokens: number
51}
52
53export type FileChange = { added: number; removed: number; edits: number }
54export type ToolError = { tool: string; detail: string; text: string }
55
56/** One item of the plan Claude keeps with TodoWrite. */
57export type Todo = { content: string; status: 'pending' | 'in_progress' | 'completed'; activeForm: string }
58
59/** One finished tool call, for the panel's Recent list. */
60export type RecentAction = { at: number; tool: string; detail: string; isOk: boolean }
61
62/** What one turn did, for the card that closes a long turn. */
63export type TurnSummary = { tools: number; files: number; added: number; removed: number; failed: number }
64
65/** Tool calls made back to back, with no text between them: drawn as one strip until opened. */
66export type ToolRun = { ids: string[]; tools: string[]; running: number; failed: number }
67
68/** Where one call sits in its run; the run is keyed by its first call's id. */
69export type RunPlace = { run: string; index: number }
70
71/** What this session has done, for the panel and the band. */
72export type Ledger = {
73  /** Each prompt's first line, for the panel; `prompts` holds them whole, for copying. */
74  turns: string[]
75  prompts: string[]
76  files: Record<string, FileChange>
77  errors: ToolError[]
78  lastReply: string
79  /** Percent of the context window in use, when known. */
80  context: number | null
81  /** What the session has cost so far, in US dollars, when known. */
82  cost: number | null
83  /** The plan usage limit nearest to running out, when Claude Code reports one. */
84  limit: { percent: number; resetsAt: string | null } | null
85  /** Why the last turn stopped, when it died on an error (a usage limit, the context limit). */
86  stopped: string | null
87  todos: Todo[]
88  recent: RecentAction[]
89  /** Subagents running now. */
90  agents: number
91  /** Each long turn's summary, by its duration in ms (what the turn's closing row carries). */
92  summaries: Record<string, TurnSummary>
93}
94
95declare module 'claude-code' {
96  interface PluginState {
97    clarity: {
98      prefs: Prefs
99      env: Env
100      activity: Activity
101      ledger: Ledger
102      /** The clock, ticked each second while a turn runs, so the band's timer redraws. */
103      tick: number
104      /** Each tool row (or run, by its first id) the person clicked open, by tool_use_id. */
105      expanded: StateFamily<boolean>
106      runs: StateFamily<ToolRun | null>
107      places: StateFamily<RunPlace | null>
108    }
109  }
110}
111