SLOPSHOPPER

prettier

Chat layout and colours: user prompts in a right-aligned pill, replies at 85% width, code panels with Copy, a turn footer and the spinner, and colours in…

spinnerrowsguardcommandtoastprompt
v0.1.0no licenseupdated 2026-10-24MoizAsif616/claude-code-utilities/mods/cli/prettier
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · prettier
╭────────────────────────────────────────────╮ │ prettier │ │ prettier: Press ctrl+o to see full tool │ │ calls, their output and long prompts; │ │ ctrl+o again to go back. /prettier lists │ ⏺ Read(src/auth.ts) ╰────────────────────────────────────────────╯ ⎿ Read 6 lines ● Edit src/auth.ts ⏺ Bash(bun test) ⎿ 3 pass, 1 fail Done. I made refresh reject expired claims and added an audit call. 42s · tools › /prettier ⎿ prettier: prettier is **on**. `/prettier on`, `/prettier off`, `/prettier reset` (every setting back to its default). ⎿ prettier: ⎿ prettier: - `/prettier-prompt` prompt pill: width, lines, time ⎿ prettier: - `/prettier-response` replies and tool output: width, fold ⎿ prettier: - `/prettier-code` code diffs: width ⎿ prettier: ⠋ Thinking ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Spinner
⠋ Thinking
Turn line
42s · tools
Your message
Claude's reply
Done. I made refresh reject expired claims and added an audit call.
Tool row
● Edit src/auth.ts
README

prettier

Chat layout and colours for the Claude Code terminal.

  • Your prompts: a pill with a rounded purple border (no fill, one space of padding on each side) on the right, at most 70% of the terminal wide, with the time you sent it under it. A long prompt shows its first 6 lines, then … 14 more lines · ctrl+o to see all. In fullscreen, ⧉ beside the time (same grey) copies that prompt's text alone and reads a green ✓ for 3.5 seconds.
  • Replies and tool output: held to the left 85% of the terminal.
  • Code blocks in replies: each fenced block is a charcoal panel with a thin violet rounded border. Its top row holds the language (python, or code when unlabeled) on a slightly lighter chip at the left and, in fullscreen, ⧉ Copy at the right, which copies only the raw code (never the label) and reads Copied! for 3.5 seconds. A panel is as wide as its longest line, never wider than the reply width; longer lines wrap inside. Bash tool-call rows are not changed.
  • Edit diffs: redrawn by prettier so added/removed lines wrap inside a narrower 75%. While the reply is being written each diff shows whole; once it is done (fullscreen) each edited or created file is one row in place of its tool row, ▸ Edit hooks/app.ts +12 −3 (name in purple, +n green, −n red), that opens to its diff and closes on a click. A new file's content shows as added lines.
  • Reads, searches and commands: a run of them folds to one line, ▸ Ran 2 commands · 1.2s. A click opens it: each call on a filled block with the whole command and its output (up to 40 lines). A click on any block, or on the line, closes it again.
  • Failures: a failed tool's error in a red frame, ✗ Bash failed, as wide as the error and never wider than the reply width. Once the reply is done (fullscreen) the call is one row, ▸ Edit app.ts · ✗ failed, that opens to its frame on a click. A refusal at the permission dialog is not a failure and keeps Claude Code's own drawing.
  • Rows you did not type: background tasks finishing, messages from other agents, sessions or channels show as a quiet card on the left (⚙ Background task · completed · 2m 2s), not as your pill.
  • End of a reply: 39s · ▸ 2 tools under the reply: how long it took, dim like the prompt's time, and how many tools it used in purple. The time of day is shown only under your prompt.
  • Spinner: drawn whole by prettier: a purple animated ⠋ and Claude Code's word, or the tool running now, ⠋ ▸ running Bash….

Colours

  • Replies: orange headings and bold, lavender links, purple list and quote markers, and tables framed in light orange lines, with orange headers, striped rows, a little padding in each cell, column lines that run the full height of a wrapped row, and no column wider than 30% of the reply.
  • Tool-call rows: a status dot (purple when done, light purple while running, red when it failed, grey when interrupted), the tool's name in purple and what it worked on in grey.

/prettier on|off turns the layout and colours on or off. The choice is kept across sessions.

Seeing the details

Click to toggle (fullscreen mode). Every compact row opens and closes on a click, marked ▸ (closed) and ▾ (open): a folded prompt (▸ 14 more lines / ▾ show less), a folded run of reads and searches (its calls appear under it), a background-task card (▸ read all), and the tool count under a reply (▸ 2 tools lists each call: ✓ Bash npm test · 1.2s). Claude Code only reports mouse clicks to mods in its fullscreen (alternate-screen) layout; on the normal screen these rows stay compact and show ctrl+o where something is hidden.

Press ctrl+o (Claude Code's own transcript view) to see every folded thing in full: each tool call of a group, whole outputs, whole long prompts and messages. Press ctrl+o again to go back. A folded prompt or message says so; the first session after installing shows a one-time tip, and /prettier repeats it.

Commands

CommandSettings (defaults)
/prettierlists the commands; on, off (layout and colours together), reset (every setting to its default)
/prettier-promptwidth 70 (% of the terminal), lines 6 (shown before folding), time on
/prettier-responsewidth 85 (% of the terminal), fold on (fold reads and searches)
/prettier-codewidth 75 (% of the terminal, for diffs)

Each command alone lists its settings and what they do. Change one or several at once: /prettier-prompt width 60 lines 4. Settings are kept across sessions.

Long Bash and Read output is already folded by Claude Code itself (… +42 lines (ctrl+o to expand)); prettier leaves that as it is, since a mod cannot tell when ctrl+o is open for a result and would hide the output for good.

Load order: prettier goes FIRST

For Claude or anyone installing this mod: prettier must be loaded before every other mod. Otherwise the 85% width can silently do nothing.

Why

Mods hook the same drawing in a chain: the first mod loaded is the outermost and calls next(e) to reach the ones beneath it. prettier only wraps what is beneath it:

  • Replies and tool rows: a mod that draws a reply or tool row itself and never calls next(e) ends the chain there. Loaded after such a mod, prettier is never reached for those rows, so its 85% box is never applied. Loaded first, prettier wraps what it draws in the 85% box.

The spinner is prettier's alone (statusdeck no longer draws it), so its place in the order does not matter for the spinner.

prettier imports and reads no other mod; only the order connects them. In the wrong order nothing breaks: replies go back to full width.

How

List prettier first in CLAUDE_CODE_PLUGIN_DIRS (;-separated on Windows, : elsewhere). The mod API puts every installed mod in one tier and does not document the order within it, so this relies on Claude Code loading the list in order: confirm it with the check below.

[Environment]::SetEnvironmentVariable('CLAUDE_CODE_PLUGIN_DIRS',
  "$env:USERPROFILE\.claude\mods\prettier;$env:USERPROFILE\.claude\mods\statusdeck;$env:USERPROFILE\.claude\mods\hark",
  'User')

On macOS/Linux, in your shell profile:

export CLAUDE_CODE_PLUGIN_DIRS="$HOME/.claude/mods/prettier:$HOME/.claude/mods/statusdeck:$HOME/.claude/mods/hark"

Then restart Claude Code. The variable is read at startup, and on Windows a terminal only sees a changed user variable if the whole terminal app started after the change (Windows Terminal, VS Code, any IDE): closing a tab is not enough, since new tabs inherit the app's old copy. Check with echo $env:CLAUDE_CODE_PLUGIN_DIRS before starting claude; or refresh one terminal by hand:

$env:CLAUDE_CODE_PLUGIN_DIRS = [Environment]::GetEnvironmentVariable('CLAUDE_CODE_PLUGIN_DIRS','User')

Checking it worked

Ask Claude anything with a long answer. If the reply wraps at about 85% of the terminal, the order is right. If it runs the full width, prettier is not first.

Known limit

Rows Claude Code draws itself (a Bash or Read result, a tool group) are wrapped in the 85% box but sized by Claude Code; if one of them still runs the full width, it needs redrawing in prettier as the edit diff is.

The dim ● <mod>: ... lines Claude Code prints when a mod loads, reloads or fails are drawn by Claude Code itself, and no mod can restyle them. They only appear while mods are being developed or something is wrong with one.

Source 6 files
hooks/register.tsx 875 lines
1import { atom, memberOf, read, update } from 'claude-code'
2import type { Elements, EngineInterface, Register, RenderElement, RenderSurface, Timer } from 'claude-code'
3
4import type { Call, Live, Prompt, Settings, Timing, Turn } from '../types'
5import type { EditDiff } from './layout'
6import {
7  CALL_FILL,
8  CALL_OUTPUT_LINES,
9  CARD_BORDER,
10  COPIED_LABEL,
11  COPIED_MS,
12  COPY_LABEL,
13  EXPAND_KEY,
14  GREEN,
15  GREY,
16  PILL_BORDER,
17  PANEL_BORDER,
18  PANEL_FILL,
19  PANEL_LABEL,
20  PANEL_PAD_X,
21  PILL_PAD,
22  PROMPT_COPIED,
23  PROMPT_COPY,
24  PURPLE,
25  PURPLE_LIGHT,
26  RED,
27  RESULT_GUTTER,
28  ROW_GUTTER,
29  SPINNER_FRAMES,
30  SPIN_MS,
31  callOutput,
32  capText,
33  cardHead,
34  describeCall,
35  describeCallWhole,
36  editDiff,
37  errorText,
38  footerParts,
39  frameWidth,
40  formatClock,
41  formatShort,
42  groupDuration,
43  groupSummary,
44  inputDelta,
45  isRejection,
46  matchTurn,
47  panelLabel,
48  panelWidth,
49  pillWidth,
50  promptTime,
51  share,
52  shortPath,
53  spinnerText,
54  splitFences,
55  toolLabel,
56  untab,
57} from './layout'
58import { inkReply, inkToolRow } from './ink'
59import { COMMANDS, DEFAULTS, EXPAND_HINT, applyArgs, describeAll, describeSection, mergeSettings } from './settings'
60import type { Section } from './settings'
61
62const settingsAtom = atom({ plugin: 'prettier', key: 'settings' } as const, DEFAULTS as Settings)
63const turnsAtom = atom({ plugin: 'prettier', key: 'turns' } as const, [] as Turn[])
64const liveAtom = atom({ plugin: 'prettier', key: 'live' } as const, { running: [], tools: 0, calls: [] } as Live)
65const promptsAtom = atom({ plugin: 'prettier', key: 'prompts' } as const, [] as Prompt[])
66const timingsAtom = atom({ plugin: 'prettier', key: 'timings' } as const, [] as Timing[])
67// Whether a compact row is open, one value per row (memberOf adds its requestId).
68const openAtom = atom({ plugin: 'prettier', key: 'open' } as const, false)
69// Whether a code panel shows `Copied!`, one value per block (`<requestId>:<n>`).
70const copiedAtom = atom({ plugin: 'prettier', key: 'copied' } as const, false)
71const spinAtom = atom({ plugin: 'prettier', key: 'spin' } as const, 0)
72
73const MAX_TURNS = 500
74const MAX_PROMPTS = 300
75const MAX_TIMINGS = 600
76const MAX_CALLS = 100
77const EMPTY_LIVE: Live = { running: [], tools: 0, calls: [] }
78
79let nextId = 0
80let spinner: Timer | undefined
81
82// The spinner's frames turn while the main loop's turn runs.
83function startSpinner($: EngineInterface): void {
84  spinner?.cancel()
85  spinner = $.clock.every(SPIN_MS, () => void update($, spinAtom, n => n + 1))
86}
87
88function stopSpinner(): void {
89  spinner?.cancel()
90  spinner = undefined
91}
92
93async function settingsOf($: EngineInterface): Promise<Settings> {
94  return mergeSettings(await read($, settingsAtom))
95}
96
97async function saveSettings($: EngineInterface, settings: Settings): Promise<void> {
98  await update($, settingsAtom, () => settings)
99  await $.store.set('settings', settings)
100}
101
102// A failed call's error that is folded into its tool row, as an edit's diff is:
103// once its turn is done, in the fullscreen terminal, when the error is text and
104// not a refusal at the permission dialog. Both the tool row and the result row
105// ask here.
106async function foldedFailure(
107  $: EngineInterface,
108  call: { id: string; output: unknown; isErrored: boolean; isRunning: boolean },
109  isFullscreen: boolean,
110): Promise<string | undefined> {
111  if (!isFullscreen || !call.isErrored || call.isRunning || isRejection(call.output)) return undefined
112  const message = errorText(call.output)
113  if (message === undefined) return undefined
114  const isLive = ((await read($, liveAtom)).calls ?? []).some(c => c.id === call.id)
115  return isLive ? undefined : message
116}
117
118// A failed call's error in a red frame as wide as the error, at most `room`.
119function failureFrame(el: Elements['terminal'], tool: string, message: string, room: number): RenderElement {
120  const { Box, Text } = el
121  const title = `✗ ${toolLabel(tool)} failed`
122  return (
123    <Box
124      flexDirection="column"
125      width={frameWidth([title, ...message.split('\n')], room)}
126      flexShrink={0}
127      borderStyle="round"
128      borderColor={RED}
129      paddingX={1}
130    >
131      <Text color={RED} bold>
132        {title}
133      </Text>
134      <Text wrap="wrap">{message}</Text>
135    </Box>
136  )
137}
138
139// The diff of an edit or new file that is folded to one row: once its turn is
140// done, and only where a click can open it again (the fullscreen terminal).
141// The tool row draws that one row and the result row draws nothing, so the
142// two hooks must agree; both ask here.
143async function foldedDiff(
144  $: EngineInterface,
145  call: { tool: string; id: string; output: unknown; isErrored: boolean; isRunning: boolean },
146  isFullscreen: boolean,
147): Promise<EditDiff | undefined> {
148  if (!isFullscreen || call.isErrored || call.isRunning) return undefined
149  const diff = editDiff(call.tool, call.output)
150  if (diff === undefined) return undefined
151  const isLive = ((await read($, liveAtom)).calls ?? []).some(c => c.id === call.id)
152  return isLive ? undefined : diff
153}
154
155// The Copy control of a code panel: the raw code to the clipboard, then
156// `Copied!` for a while.
157// A press while one is still showing its mark is ignored, so one click never
158// puts the text on the clipboard twice.
159const copying = new Set<string>()
160async function copyCode($: EngineInterface, id: string, code: string, surface: RenderSurface): Promise<void> {
161  if (copying.has(id)) return
162  copying.add(id)
163  const done = await $.ui.copy({ text: code, surface })
164  if (!done.isCopied) {
165    copying.delete(id)
166    $.ui.toast(`prettier: the code could not be copied (${done.reason}).`)
167    return
168  }
169  const member = memberOf(copiedAtom, { requestId: id })
170  await update($, member, () => true)
171  $.clock.after(COPIED_MS, () => {
172    copying.delete(id)
173    void update($, member, () => false)
174  })
175}
176
177// Whether a drawing holds Claude Code's own (`{ type: 'engine' }`), as next(e)
178// gives when no mod beneath draws the row. Claude Code refuses a tree that puts
179// its own drawing inside a Box with a width (and then draws its own in place of
180// the whole tree), so such a drawing is never held to a width.
181function hasEngine(node: unknown): boolean {
182  if (Array.isArray(node)) return node.some(hasEngine)
183  if (typeof node !== 'object' || node === null) return false
184  const el = node as { type?: unknown; props?: { children?: unknown } }
185  return el.type === 'engine' || hasEngine(el.props?.children)
186}
187
188async function cwdOf($: EngineInterface): Promise<string> {
189  try {
190    return await $.session.cwd()
191  } catch {
192    // Without the session's folder a path reads as its last parts.
193    return ''
194  }
195}
196
197// One of the three section commands: no arguments lists the section,
198// `name value` pairs change it.
199async function runSection($: EngineInterface, section: Section, args: string): Promise<{ text: string }> {
200  const current = await settingsOf($)
201  if (args.trim() === '') return { text: describeSection(current, section) }
202  const applied = applyArgs(current, section, args)
203  if (applied.changed.length > 0) await saveSettings($, applied.settings)
204  const done = applied.changed.length > 0 ? [`Set ${applied.changed.join(', ')}.`] : []
205  const wrong = applied.errors.map(err => `Not changed: ${err}.`)
206  const off = applied.settings.isEnabled ? [] : ['prettier is off: `/prettier on` to see it.']
207  return { text: [...done, ...wrong, ...off].join('\n') }
208}
209
210export const register: Register = on => {
211  on('session.start', async ($, e, next) => {
212    const stored = await $.store.get('settings')
213    const legacy = await $.store.get('isEnabled')
214    const settings = mergeSettings(stored)
215    if (stored === undefined && typeof legacy === 'boolean') settings.isEnabled = legacy
216    await update($, settingsAtom, () => settings)
217
218    await $.command.register({
219      name: 'prettier',
220      description: 'prettier chat layout: on, off, reset, or list its settings',
221      argumentHint: '[on|off|reset]',
222    })
223    for (const section of Object.keys(COMMANDS) as Section[]) {
224      await $.command.register({
225        name: COMMANDS[section].name,
226        description: COMMANDS[section].description,
227        argumentHint: `[${COMMANDS[section].example}]`,
228      })
229    }
230
231    // Once per machine: say where the details went.
232    if ((await $.store.get('hintShown')) !== true) {
233      $.ui.toast(`prettier: ${EXPAND_HINT} /prettier lists the settings.`, { timeoutMs: 12_000 })
234      await $.store.set('hintShown', true)
235    }
236    return next(e)
237  })
238
239  // ---------------------------------------------------------------- commands
240
241  on('command.run', { command: 'prettier' }, async ($, e) => {
242    const arg = e.args.trim().toLowerCase()
243    const current = await settingsOf($)
244    if (arg === 'on' || arg === 'off') {
245      await saveSettings($, { ...current, isEnabled: arg === 'on' })
246      return { text: arg === 'on' ? 'prettier on.' : "prettier off: the transcript uses Claude Code's own layout." }
247    }
248    if (arg === 'reset') {
249      await saveSettings($, { ...structuredClone(DEFAULTS), isEnabled: current.isEnabled })
250      return { text: 'Every prettier setting is back to its default.' }
251    }
252    if (arg !== '') return { text: `\`${arg}\` is not a choice: \`/prettier on\`, \`/prettier off\` or \`/prettier reset\`.` }
253    return { text: describeAll(current) }
254  })
255
256  const unsaved = { text: 'prettier: the setting could not be saved; nothing changed.' }
257  on('command.run', { command: 'prettier-prompt' }, async ($, e) => runSection($, 'prompt', e.args)).catch(
258    () => unsaved,
259  )
260  on('command.run', { command: 'prettier-response' }, async ($, e) => runSection($, 'response', e.args)).catch(
261    () => unsaved,
262  )
263  on('command.run', { command: 'prettier-code' }, async ($, e) => runSection($, 'code', e.args)).catch(
264    () => unsaved,
265  )
266
267  // ---------------------------------------------------------------- recording
268
269  on('prompt.submit', async ($, e, next) => {
270    const kind = e.origin.kind
271    if ((kind === 'composer' || kind === 'bridge') && e.command === undefined && e.isMeta !== true) {
272      const at = Date.now()
273      // Kept as it entered, after any hook beneath rewrote it (a placeholder
274      // swapped for its text, say), so the row it draws as finds its time.
275      const entered = await next(e)
276      if (entered.drop === undefined) {
277        await update($, promptsAtom, prompts => [...prompts, { text: entered.text, at }].slice(-MAX_PROMPTS))
278      }
279      return entered
280    }
281    return next(e)
282  }).catch(($, e, next) => next(e))
283
284  on('turn.start', async ($, e, next) => {
285    if (e.agentId === undefined) {
286      await update($, liveAtom, () => EMPTY_LIVE)
287      startSpinner($)
288    }
289    return next(e)
290  })
291
292  on('tool.call', async ($, e, next) => {
293    if (e.agentId !== undefined) return next(e)
294    nextId += 1
295    const id = e.tool_use_id ?? `prettier-${nextId}`
296    const start = Date.now()
297    const call: Call = { id, tool: toolLabel(e.tool), detail: describeCall(e.tool, e) }
298    await update($, liveAtom, live => ({
299      running: [...live.running, { id, tool: call.tool }],
300      tools: live.tools + 1,
301      calls: [...(live.calls ?? []), call].slice(-MAX_CALLS),
302    }))
303    await update($, timingsAtom, timings => [...timings, { id, start }].slice(-MAX_TIMINGS))
304    let failed = true
305    try {
306      const ran = await next(e)
307      failed = ran.deny !== undefined || ran.isError === true
308      return ran
309    } finally {
310      const end = Date.now()
311      await update($, liveAtom, live => ({
312        ...live,
313        running: live.running.filter(r => r.id !== id),
314        calls: (live.calls ?? []).map(c => (c.id === id ? { ...c, ms: end - start, failed } : c)),
315      }))
316      await update($, timingsAtom, timings => timings.map(t => (t.id === id ? { ...t, end } : t)))
317    }
318  }).catch(($, e, next) => next(e))
319
320  on('turn.complete', async ($, e, next) => {
321    if (e.agentId === undefined) {
322      const live = await read($, liveAtom)
323      const turn: Turn = { durationMs: e.durationMs, tools: live.tools, calls: live.calls ?? [] }
324      await update($, turnsAtom, turns => [...turns, turn].slice(-MAX_TURNS))
325      await update($, liveAtom, () => EMPTY_LIVE)
326      stopSpinner()
327    }
328    return next(e)
329  })
330
331  // ---------------------------------------------------------------- drawing
332  //
333  // LOAD ORDER: prettier must load before any mod that draws these rows itself
334  // without calling next. Such a mod ends the chain, so a hook beneath it never
335  // runs and the width is lost. List prettier first in CLAUDE_CODE_PLUGIN_DIRS;
336  // see README.md.
337  //
338  // Replies and tool rows draw in the colours (ink.tsx) where the
339  // layout asks for the row beneath it; with the colours off, that is next.
340
341  // A user-role row. The person's own prompt is a purple-bordered pill on the right
342  // with its time under it; a row someone else sent (a background task, another
343  // agent, a channel) is a quiet card on the left.
344  on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
345    if (e.surface !== 'terminal') return next(e)
346    const settings = await settingsOf($)
347    if (!settings.isEnabled) return next(e)
348    const { Box, Button, Text } = $.ui.resolve({ ...e, surface: 'terminal' as const })
349    const columns = e.viewport?.columns ?? 80
350    const { origin, task, from, text, isExpanded } = e.props
351    const isOwn =
352      origin.kind === 'composer' ||
353      origin.kind === 'bridge' ||
354      (origin.kind === 'unclassified' && task === undefined && from === undefined)
355    // Clicks reach a row only in the fullscreen terminal; elsewhere ctrl+o
356    // (isExpanded) is the one way to see a folded row whole.
357    const canClick = e.viewport?.isFullscreen === true
358    const isOpen = canClick && (await read($, memberOf(openAtom, e)))
359    const toggle = () => update($, memberOf(openAtom, e), v => !v)
360
361    if (isOwn) {
362      const p = settings.prompt
363      const room = Math.max(8, Math.floor((columns * p.width) / 100) - PILL_PAD * 2 - 2)
364      const folded = capText(text, room, p.lines)
365      const capped = isExpanded || isOpen ? { shown: text, hidden: 0 } : folded
366      const more = `${folded.hidden} more ${folded.hidden === 1 ? 'line' : 'lines'}`
367      const hint =
368        isExpanded || folded.hidden === 0
369          ? undefined
370          : !canClick
371            ? `… ${more} · ${EXPAND_KEY} to see all`
372            : isOpen
373              ? '▾ show less'
374              : `▸ ${more}`
375      const width = pillWidth([...capped.shown.split('\n'), ...(hint === undefined ? [] : [hint])], columns, p.width)
376      const at = p.time ? promptTime(await read($, promptsAtom), text) : undefined
377      const promptCopyId = `${e.requestId}:prompt`
378      const isPromptCopied = canClick && (await read($, memberOf(copiedAtom, { requestId: promptCopyId })))
379      return (
380        <Box flexDirection="column" alignItems="flex-end" width={columns}>
381          <Box
382            flexDirection="column"
383            width={width}
384            flexShrink={0}
385            borderStyle="round"
386            borderColor={PILL_BORDER}
387            paddingX={PILL_PAD}
388          >
389            <Text wrap="wrap">{capped.shown}</Text>
390            {hint !== undefined &&
391              (canClick ? (
392                <Button plain key="more" onPress={toggle}>
393                  <Text color={PURPLE_LIGHT}>{hint}</Text>
394                </Button>
395              ) : (
396                <Text color={GREY}>{hint}</Text>
397              ))}
398          </Box>
399          {(at !== undefined || canClick) && (
400            <Box flexDirection="row" paddingRight={at !== undefined && canClick ? 0 : 1}>
401              {at !== undefined && <Text color={GREY}>{formatClock(at)}</Text>}
402              {at !== undefined && canClick && <Text color={GREY}>{' '}</Text>}
403              {/* Copies the prompt's own text, nothing else; ✓ for a moment after. */}
404              {canClick && (
405                <Button plain key="copy-prompt" onPress={press => void copyCode($, promptCopyId, text, press.surface)}>
406                  <Text color={isPromptCopied ? GREEN : GREY}>{isPromptCopied ? PROMPT_COPIED : PROMPT_COPY}</Text>
407                </Button>
408              )}
409            </Box>
410          )}
411        </Box>
412      )
413    }
414
415    if (origin.kind === 'auto-continuation' || origin.kind === 'sdk') return next(e)
416    const head = cardHead(origin, task, from)
417    const lines = text.split('\n')
418    const isWhole = isExpanded || isOpen
419    const body = isWhole ? text : lines[0] ?? ''
420    const canFold = !isExpanded && lines.length > 1
421    return (
422      <Box flexDirection="column" width={share(columns, settings.response.width)}>
423        <Box flexDirection="column" alignSelf="flex-start" borderStyle="round" borderColor={CARD_BORDER} paddingX={1}>
424          <Text>
425            <Text color={head.color}>{`${head.icon} ${head.label}`}</Text>
426            {head.meta !== '' && <Text color={GREY}>{` · ${head.meta}`}</Text>}
427          </Text>
428          {body !== '' && (
429            <Text color={GREY} wrap={isWhole ? 'wrap' : 'truncate-end'}>
430              {body}
431            </Text>
432          )}
433          {canFold &&
434            (canClick ? (
435              <Button plain key="more" onPress={toggle}>
436                <Text color={PURPLE_LIGHT}>{isOpen ? '▾ show less' : '▸ read all'}</Text>
437              </Button>
438            ) : (
439              <Text color={GREY}>{`${EXPAND_KEY} to read all`}</Text>
440            ))}
441        </Box>
442      </Box>
443    )
444  })
445
446  on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
447    if (e.surface !== 'terminal') return next(e)
448    const settings = await settingsOf($)
449    if (!settings.isEnabled) return next(e)
450    const { Box, Button, Code, Text } = $.ui.resolve({ ...e, surface: 'terminal' as const })
451    const width = share(e.viewport?.columns ?? 80, settings.response.width)
452    const parts = splitFences(e.props.text)
453    if (!parts.some(p => p.kind === 'code')) {
454      const inner = await inkReply($, e, next)
455      if (hasEngine(inner)) return inner
456      return (
457        <Box flexDirection="column" width={width}>
458          {inner}
459        </Box>
460      )
461    }
462
463    // Prose draws in the colours (or goes on to the mods beneath), one
464    // piece at a time; each fenced block is a filled panel of prettier's own.
465    const canClick = e.viewport?.isFullscreen === true
466    const room = width - ROW_GUTTER
467    const drawn = []
468    let block = 0
469    let isFirst = e.props.isFirstOfReply
470    for (const part of parts) {
471      if (part.kind === 'prose') {
472        drawn.push(await inkReply($, { ...e, props: { ...e.props, text: part.text, isFirstOfReply: isFirst } }, next))
473        isFirst = false
474        continue
475      }
476      const id = `${e.requestId}:${block}`
477      block += 1
478      const label = panelLabel(part.language)
479      const isCopied = canClick && (await read($, memberOf(copiedAtom, { requestId: id })))
480      const code = part.code
481      drawn.push(
482        <Box key={id} marginLeft={ROW_GUTTER} marginTop={isFirst ? 0 : 1} flexDirection="column">
483          <Box
484            flexDirection="column"
485            width={panelWidth(code, label, room)}
486            flexShrink={0}
487            borderStyle="round"
488            borderColor={PANEL_BORDER}
489            backgroundColor={PANEL_FILL}
490          >
491            <Box flexDirection="row" justifyContent="space-between" paddingX={PANEL_PAD_X}>
492              <Text color={PANEL_LABEL} backgroundColor={PANEL_FILL}>
493                {label}
494              </Text>
495              {canClick ? (
496                <Button plain key={`copy-${block}`} onPress={press => void copyCode($, id, code, press.surface)}>
497                  <Text color={isCopied ? GREEN : PANEL_LABEL} backgroundColor={PANEL_FILL}>
498                    {isCopied ? COPIED_LABEL : COPY_LABEL}
499                  </Text>
500                </Button>
501              ) : (
502                <Text backgroundColor={PANEL_FILL}> </Text>
503              )}
504            </Box>
505            {/* The rule under the label and Copy, wall to wall in the border's colour, cut to the panel. */}
506            <Box height={1} overflow="hidden">
507              <Text color={PANEL_BORDER}>{'─'.repeat(width)}</Text>
508            </Box>
509            <Box paddingX={PANEL_PAD_X}>
510              <Code source={untab(code)} language={part.language === '' ? undefined : part.language} />
511            </Box>
512          </Box>
513        </Box>,
514      )
515      isFirst = false
516    }
517    return (
518      <Box flexDirection="column" width={hasEngine(drawn) ? undefined : width}>
519        {drawn}
520      </Box>
521    )
522  }).catch(($, e, next) => inkReply($, e, next))
523
524  // A tool call's row. A finished edit or new file is one row of its own,
525  // `▸ Edit hooks/app.ts +12 −3`, that a click opens to its diff and closes;
526  // its result row then draws nothing. Any other row is the coloured
527  // one (or the one beneath), held to the response width, with an edit's
528  // `+12 −3` after it.
529  on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
530    if (e.surface !== 'terminal') return next(e)
531    const settings = await settingsOf($)
532    if (!settings.isEnabled) return next(e)
533    const el = $.ui.resolve({ ...e, surface: 'terminal' as const })
534    const { Box, Button, Code, Text } = el
535    const columns = e.viewport?.columns ?? 80
536    const { tool, tool_use_id, output, isErrored, isRunning, isInterrupted } = e.props
537    const isFullscreen = e.viewport?.isFullscreen === true
538
539    // A finished failed call: one row, `▸ Edit app.ts · ✗ failed`, that a click
540    // opens to its red frame and closes; its result row then draws nothing.
541    const failure = isInterrupted
542      ? undefined
543      : await foldedFailure($, { id: tool_use_id, output, isErrored, isRunning }, isFullscreen)
544    if (failure !== undefined) {
545      const width = share(columns, settings.response.width)
546      const isOpen = await read($, memberOf(openAtom, e))
547      const input = (e.props.input ?? {}) as Record<string, unknown>
548      const path = typeof input.file_path === 'string' ? input.file_path : undefined
549      const detail = path === undefined ? describeCall(tool, e.props.input) : shortPath(path, await cwdOf($))
550      return (
551        <Box flexDirection="column" width={width}>
552          <Box flexDirection="row">
553            <Box width={ROW_GUTTER} flexShrink={0}>
554              <Text color={PURPLE}>{isOpen ? '▾' : '▸'}</Text>
555            </Box>
556            <Button plain key="failure" onPress={() => update($, memberOf(openAtom, e), v => !v)}>
557              <Text color={GREY}>{`${toolLabel(tool)} `}</Text>
558              <Text color={PURPLE}>{detail}</Text>
559              <Text color={RED}>{' · ✗ failed'}</Text>
560            </Button>
561          </Box>
562          {isOpen && <Box marginLeft={ROW_GUTTER}>{failureFrame(el, tool, failure, width - ROW_GUTTER)}</Box>}
563        </Box>
564      )
565    }
566
567    const diff = isInterrupted
568      ? undefined
569      : await foldedDiff($, { tool, id: tool_use_id, output, isErrored, isRunning }, isFullscreen)
570    if (diff === undefined) {
571      const inner = await inkToolRow($, e, next)
572      if (hasEngine(inner)) return inner
573      // A failed edit changed nothing, so it has no count.
574      const delta = isErrored ? undefined : inputDelta(tool, e.props.input)
575      return (
576        <Box flexDirection="row" width={share(columns, settings.response.width)}>
577          <Box flexDirection="column" flexShrink={1}>
578            {inner}
579          </Box>
580          {delta !== undefined && (
581            <Box flexShrink={0}>
582              <Text>
583                <Text color={GREEN}>{` +${delta.added}`}</Text>
584                <Text color={RED}>{` −${delta.removed}`}</Text>
585              </Text>
586            </Box>
587          )}
588        </Box>
589      )
590    }
591    const isOpen = await read($, memberOf(openAtom, e))
592    const name = diff.path === undefined ? 'file' : shortPath(diff.path, await cwdOf($))
593    return (
594      <Box flexDirection="column" width={share(columns, settings.code.width)}>
595        <Box flexDirection="row">
596          <Box width={ROW_GUTTER} flexShrink={0}>
597            <Text color={PURPLE}>{isOpen ? '▾' : '▸'}</Text>
598          </Box>
599          <Button plain key="diff" onPress={() => update($, memberOf(openAtom, e), v => !v)}>
600            <Text color={GREY}>{diff.isNew ? 'Created ' : `${toolLabel(tool)} `}</Text>
601            <Text color={PURPLE}>{name}</Text>
602            <Text color={GREEN}>{` +${diff.added}`}</Text>
603            <Text color={RED}>{` −${diff.removed}`}</Text>
604          </Button>
605        </Box>
606        {isOpen && (
607          <Box marginLeft={ROW_GUTTER}>
608            <Code source={diff.source} format="diff" path={diff.path} />
609          </Box>
610        )}
611      </Box>
612    )
613  }).catch(($, e, next) => inkToolRow($, e, next))
614
615  // A run of reads, searches or commands, folded to one line. A click on it (fullscreen)
616  // opens the engine's rows under it and closes them again; ctrl+o, or
617  // `fold off`, shows the engine's rows as they are.
618  on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
619    if (e.surface !== 'terminal') return next(e)
620    const settings = await settingsOf($)
621    if (!settings.isEnabled) return next(e)
622    const { Box, Button, Text } = $.ui.resolve({ ...e, surface: 'terminal' as const })
623    const width = share(e.viewport?.columns ?? 80, settings.response.width)
624    if (!settings.response.fold || e.props.isExpanded) {
625      const inner = await next(e)
626      if (hasEngine(inner)) return inner
627      return (
628        <Box flexDirection="column" width={width}>
629          {inner}
630        </Box>
631      )
632    }
633    const canClick = e.viewport?.isFullscreen === true
634    const isOpen = canClick && (await read($, memberOf(openAtom, e)))
635    const calls = e.props.calls
636    const isRunning = calls.some(c => c.isRunning)
637    const failed = calls.filter(c => c.isErrored).length
638    const took = isRunning ? undefined : groupDuration(calls.map(c => c.tool_use_id), await read($, timingsAtom))
639    const mark = isRunning ? '○' : !canClick ? '▸' : isOpen ? '▾' : '▸'
640    const line = (
641      <Text wrap="wrap">
642        <Text>{groupSummary(calls.map(c => c.tool))}</Text>
643        {took !== undefined && <Text color={GREY}>{` · ${formatShort(took)}`}</Text>}
644        {failed > 0 && <Text color={RED}>{` · ✗ ${failed} failed`}</Text>}
645      </Text>
646    )
647    const head = (
648      <Box flexDirection="row">
649        <Box width={ROW_GUTTER} flexShrink={0}>
650          <Text color={isRunning ? PURPLE_LIGHT : PURPLE}>{mark}</Text>
651        </Box>
652        {canClick ? (
653          <Button plain key="group" onPress={() => update($, memberOf(openAtom, e), v => !v)}>
654            {line}
655          </Button>
656        ) : (
657          line
658        )}
659      </Box>
660    )
661    if (!isOpen) {
662      return (
663        <Box flexDirection="column" width={width}>
664          {head}
665        </Box>
666      )
667    }
668    // Opened: prettier draws each call on a filled block, the whole command and
669    // what it gave back; a click anywhere on a block closes the group again.
670    // (Claude Code's own rows would answer a click themselves, not close it.)
671    const timings = await read($, timingsAtom)
672    const close = () => update($, memberOf(openAtom, e), () => false)
673    return (
674      <Box flexDirection="column" width={width}>
675        {head}
676        {calls.map((c, i) => {
677          const lines = callOutput(c.tool, c.output).split('\n')
678          const shown = lines.slice(0, CALL_OUTPUT_LINES).join('\n')
679          const hidden = Math.max(0, lines.length - CALL_OUTPUT_LINES)
680          const timing = timings.find(t => t.id === c.tool_use_id)
681          const ms = timing?.end === undefined ? undefined : timing.end - timing.start
682          const mark = c.isRunning ? '○' : c.isErrored ? '✗' : '✓'
683          const markColor = c.isRunning ? PURPLE_LIGHT : c.isErrored ? RED : GREEN
684          return (
685            <Box
686              key={`call-${i}`}
687              flexDirection="column"
688              marginLeft={ROW_GUTTER}
689              marginTop={i === 0 ? 0 : 1}
690              backgroundColor={CALL_FILL}
691              paddingX={1}
692            >
693              <Button plain key={`call-${i}`} onPress={close}>
694                <Text color={markColor}>{`${mark} `}</Text>
695                <Text color={PURPLE} bold>
696                  {toolLabel(c.tool)}
697                </Text>
698                <Text color={GREY}>{` ${describeCallWhole(c.tool, c.input)}`}</Text>
699                {ms !== undefined && <Text color={GREY}>{` · ${formatShort(ms)}`}</Text>}
700                {shown !== '' && <Text>{`\n${shown}`}</Text>}
701                {hidden > 0 && <Text color={GREY}>{`\n… +${hidden} lines · ${EXPAND_KEY} to see all`}</Text>}
702              </Button>
703            </Box>
704          )
705        })}
706      </Box>
707    )
708  })
709
710  on('ui.render', { component: 'ToolProgress' }, async ($, e, next) => {
711    if (e.surface !== 'terminal') return next(e)
712    const settings = await settingsOf($)
713    if (!settings.isEnabled) return next(e)
714    const { Box } = $.ui.resolve({ ...e, surface: 'terminal' as const })
715    const inner = await next(e)
716    if (hasEngine(inner)) return inner
717    return (
718      <Box flexDirection="column" width={share(e.viewport?.columns ?? 80, settings.response.width)}>
719        {inner}
720      </Box>
721    )
722  })
723
724  on('ui.render', { component: 'CommandOutput' }, async ($, e, next) => {
725    if (e.surface !== 'terminal') return next(e)
726    const settings = await settingsOf($)
727    if (!settings.isEnabled) return next(e)
728    const { Box } = $.ui.resolve({ ...e, surface: 'terminal' as const })
729    const inner = await next(e)
730    if (hasEngine(inner)) return inner
731    return (
732      <Box flexDirection="column" width={share(e.viewport?.columns ?? 80, settings.response.width)}>
733        {inner}
734      </Box>
735    )
736  })
737
738  // A tool's result. An edit's or new file's diff is drawn here at the code
739  // width (its `+12 −3` is on the tool row above); a failure in a red frame;
740  // anything else is the engine's drawing at the response width.
741  on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
742    if (e.surface !== 'terminal') return next(e)
743    const settings = await settingsOf($)
744    if (!settings.isEnabled) return next(e)
745    const el = $.ui.resolve({ ...e, surface: 'terminal' as const })
746    const { Box, Code, Text } = el
747    const columns = e.viewport?.columns ?? 80
748    const width = share(columns, settings.response.width)
749    const { output, isErrored, tool } = e.props
750
751    if (isErrored && !isRejection(output)) {
752      // Folded into its tool row once the turn is done: drawn there, not here.
753      const folded = await foldedFailure(
754        $,
755        { id: e.props.tool_use_id, output, isErrored, isRunning: false },
756        e.viewport?.isFullscreen === true,
757      )
758      if (folded !== undefined) return <Box />
759      const message = errorText(output)
760      if (message !== undefined) {
761        return (
762          <Box flexDirection="row" width={width}>
763            <Box width={RESULT_GUTTER.length} flexShrink={0}>
764              <Text dimColor>{RESULT_GUTTER}</Text>
765            </Box>
766            {failureFrame(el, tool, message, width - RESULT_GUTTER.length)}
767          </Box>
768        )
769      }
770      const inner = await next(e)
771      if (hasEngine(inner)) return inner
772      return (
773        <Box flexDirection="row" width={width}>
774          <Box width={RESULT_GUTTER.length} flexShrink={0}>
775            <Text dimColor>{RESULT_GUTTER}</Text>
776          </Box>
777          <Box flexDirection="column" flexShrink={1} borderStyle="round" borderColor={RED} paddingX={1}>
778            <Text color={RED} bold>{`✗ ${toolLabel(tool)} failed`}</Text>
779            {inner}
780          </Box>
781        </Box>
782      )
783    }
784
785    const diff = isErrored ? undefined : editDiff(tool, output)
786    if (diff === undefined) {
787      const inner = await next(e)
788      if (hasEngine(inner)) return inner
789      return (
790        <Box flexDirection="column" width={width}>
791          {inner}
792        </Box>
793      )
794    }
795
796    // A finished edit is one row, drawn by the tool row's hook above: its
797    // result draws nothing. While its turn runs (or where no click could open
798    // it again) the diff shows whole here.
799    const folded = await foldedDiff(
800      $,
801      { tool, id: e.props.tool_use_id, output, isErrored, isRunning: false },
802      e.viewport?.isFullscreen === true,
803    )
804    if (folded !== undefined) return <Box />
805    return (
806      <Box flexDirection="row" width={share(columns, settings.code.width)}>
807        <Box width={RESULT_GUTTER.length} flexShrink={0}>
808          <Text dimColor>{RESULT_GUTTER}</Text>
809        </Box>
810        <Box flexDirection="column" flexGrow={1} flexShrink={1}>
811          <Code source={diff.source} format="diff" path={diff.path} />
812        </Box>
813      </Box>
814    )
815  })
816
817  // The line closing a turn, under the reply's text: `39s · ▸ 2 tools`, the
818  // length dim like a prompt's time, the count in purple. A click on the count
819  // (fullscreen) lists the turn's calls under it, and closes the list again.
820  on('ui.render', { component: 'TurnDuration' }, async ($, e, next) => {
821    if (e.surface !== 'terminal') return next(e)
822    const settings = await settingsOf($)
823    if (!settings.isEnabled) return next(e)
824    const { Box, Button, Text } = $.ui.resolve({ ...e, surface: 'terminal' as const })
825    const turn = matchTurn(await read($, turnsAtom), e.props.durationMs)
826    const { took, used } = footerParts(e.props.durationMs, turn?.tools)
827    const calls = turn?.calls ?? []
828    const canClick = e.viewport?.isFullscreen === true && calls.length > 0
829    const isOpen = canClick && (await read($, memberOf(openAtom, e)))
830    const room = Math.max(10, share(e.viewport?.columns ?? 80, settings.response.width) - ROW_GUTTER - 4)
831    return (
832      <Box flexDirection="column" marginLeft={ROW_GUTTER}>
833        <Box flexDirection="row">
834          <Text color={GREY}>{took}</Text>
835          {used !== undefined && <Text color={GREY}>{' · '}</Text>}
836          {used !== undefined &&
837            (canClick ? (
838              <Button plain key="tools" onPress={() => update($, memberOf(openAtom, e), v => !v)}>
839                <Text color={PURPLE_LIGHT}>{`${isOpen ? '▾' : '▸'} ${used}`}</Text>
840              </Button>
841            ) : (
842              <Text color={PURPLE_LIGHT}>{used}</Text>
843            ))}
844        </Box>
845        {isOpen &&
846          calls.map(c => (
847            <Box key={c.id} flexDirection="row" marginLeft={2}>
848              <Box width={2} flexShrink={0}>
849                <Text color={c.failed === true ? RED : GREEN}>{c.failed === true ? '✗' : '✓'}</Text>
850              </Box>
851              <Text wrap="truncate-end">
852                <Text color={PURPLE_LIGHT}>{c.tool}</Text>
853                {c.detail !== '' && <Text color={GREY}>{` ${c.detail.slice(0, room)}`}</Text>}
854                {c.ms !== undefined && <Text color={GREY}>{` · ${formatShort(c.ms)}`}</Text>}
855              </Text>
856            </Box>
857          ))}
858      </Box>
859    )
860  })
861
862  // The line animated while a turn runs, drawn whole by prettier: a purple
863  // braille frame and the engine's word, or the tool running now
864  // (`⠋ ▸ running Bash…`). No time or tokens: those are in the footer.
865  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
866    if (e.surface !== 'terminal') return next(e)
867    const settings = await settingsOf($)
868    if (!settings.isEnabled) return next(e)
869    const { Text } = $.ui.resolve({ ...e, surface: 'terminal' as const })
870    const { running } = await read($, liveAtom)
871    const frame = SPINNER_FRAMES[(await read($, spinAtom)) % SPINNER_FRAMES.length]
872    return <Text color={PURPLE}>{`${frame} ${spinnerText(e.props, running[running.length - 1]?.tool)}`}</Text>
873  })
874}
875
hooks/layout.ts 479 lines
1import type { Prompt, Timing, Turn } from '../types'
2
3// the reply colours' palette; prettier's own dim fills.
4export const PURPLE = '#A855F7'
5export const PURPLE_LIGHT = '#C4B5FD'
6export const GREY = '#71717A'
7export const RED = '#EF4444'
8export const GREEN = '#22C55E'
9export const CARD_BORDER = '#3F3F46'
10
11// The prompt pill's rounded border: the deep structure purple.
12export const PILL_BORDER = '#7C3AED'
13
14// One space inside the pill on each side, between the text and the border.
15export const PILL_PAD = 1
16export const RESULT_GUTTER = '  ⎿  '
17export const ROW_GUTTER = 2
18export const EXPAND_KEY = 'ctrl+o'
19
20// A fenced code block's panel: charcoal fill, thin violet border, lavender label.
21export const PANEL_FILL = '#111114'
22export const PANEL_BORDER = '#8B7CBD'
23export const PANEL_LABEL = '#B9A7E8'
24export const PANEL_PAD_X = 1
25export const COPY_LABEL = '⧉ Copy'
26export const COPIED_LABEL = 'Copied!'
27export const COPIED_MS = 3500
28
29// The copy mark beside a prompt's time, and what it reads just after a copy.
30// A space each side: terminals draw ⧉ wider than its one cell, so the hover
31// fill needs the cells around it to cover the whole glyph.
32export const PROMPT_COPY = ' ⧉ '
33export const PROMPT_COPIED = ' ✓ '
34
35// An opened group: each call on a filled block, its output up to this many lines.
36export const CALL_FILL = '#1C1B22'
37export const CALL_OUTPUT_LINES = 40
38
39// ---------------------------------------------------------------- measuring
40
41export function cellWidth(text: string): number {
42  let n = 0
43  for (const ch of text) {
44    const code = ch.codePointAt(0) ?? 0
45    // Wide East Asian characters and most emoji take two cells.
46    n += (code >= 0x1100 && code <= 0x115f) || (code >= 0x2e80 && code <= 0xa4cf) ||
47      (code >= 0xac00 && code <= 0xd7a3) || (code >= 0xf900 && code <= 0xfaff) ||
48      (code >= 0xfe30 && code <= 0xfe4f) || (code >= 0xff00 && code <= 0xff60) ||
49      (code >= 0x1f300 && code <= 0x1faff)
50      ? 2
51      : 1
52  }
53  return n
54}
55
56// `percent` of the terminal, in whole cells, never under 20.
57export function share(columns: number, percent: number): number {
58  return Math.max(20, Math.floor((columns * percent) / 100))
59}
60
61// The pill's outer width: its widest line plus a space and the border each side, no wider
62// than `percent` of the terminal.
63export function pillWidth(lines: readonly string[], columns: number, percent: number): number {
64  const widest = Math.max(1, ...lines.map(cellWidth))
65  return Math.min(widest + PILL_PAD * 2 + 2, Math.max(12, Math.floor((columns * percent) / 100)))
66}
67
68// ---------------------------------------------------------------- an edit's count
69
70// Lines added and removed, after the lines both sides share at either end.
71function lineDelta(before: string, after: string): { added: number; removed: number } {
72  const a = before === '' ? [] : before.split('\n')
73  const b = after === '' ? [] : after.split('\n')
74  let head = 0
75  while (head < a.length && head < b.length && a[head] === b[head]) head += 1
76  let tail = 0
77  while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) {
78    tail += 1
79  }
80  return { added: b.length - head - tail, removed: a.length - head - tail }
81}
82
83// The `+12 −3` of an Edit or Write call, read from its input so it shows while
84// the call runs; undefined for other tools and for a change of no lines.
85export function inputDelta(tool: string, input: unknown): { added: number; removed: number } | undefined {
86  const fields = (input !== null && typeof input === 'object' ? input : {}) as Record<string, unknown>
87  const text = (key: string) => (typeof fields[key] === 'string' ? (fields[key] as string) : '')
88  const delta =
89    tool === 'Edit'
90      ? lineDelta(text('old_string'), text('new_string'))
91      : tool === 'Write'
92        ? { added: text('content') === '' ? 0 : text('content').split('\n').length, removed: 0 }
93        : undefined
94  return delta === undefined || (delta.added === 0 && delta.removed === 0) ? undefined : delta
95}
96
97// ---------------------------------------------------------------- spinner
98
99export const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
100export const SPIN_MS = 160
101
102// The spinner's words: the tool running now, else the engine's message or
103// word; one ellipsis after, unless the text already ends in one.
104export function spinnerText(props: { word: string; message: string | null; suffix: string }, tool?: string): string {
105  const text = tool !== undefined ? `▸ running ${tool}` : props.message ?? props.word
106  return text.endsWith('…') ? text : `${text}${props.suffix}`
107}
108
109// ---------------------------------------------------------------- code panels
110
111// A reply cut at its fenced code blocks: prose between them, and each block's
112// language (empty when unlabeled) and raw code. A fence still open at the end
113// (a reply being written) runs to the end.
114export type ReplyPart = { kind: 'prose'; text: string } | { kind: 'code'; language: string; code: string }
115
116const FENCE_OPEN = /^([ \t]*)(`{3,}|~{3,})[ \t]*([^`\s]*)[^`]*$/
117
118export function splitFences(text: string): ReplyPart[] {
119  const parts: ReplyPart[] = []
120  const lines = text.split('\n')
121  let prose: string[] = []
122  const flushProse = () => {
123    const joined = prose.join('\n')
124    if (joined.trim() !== '') parts.push({ kind: 'prose', text: joined.replace(/^\n+|\n+$/g, '') })
125    prose = []
126  }
127  for (let i = 0; i < lines.length; i++) {
128    const open = FENCE_OPEN.exec(lines[i] ?? '')
129    if (open === null) {
130      prose.push(lines[i] ?? '')
131      continue
132    }
133    flushProse()
134    const indent = (open[1] ?? '').length
135    const fence = open[2] ?? '```'
136    const close = new RegExp(`^[ \\t]*${fence[0] === '`' ? '`' : '~'}{${fence.length},}[ \\t]*$`)
137    const code: string[] = []
138    i++
139    while (i < lines.length && !close.test(lines[i] ?? '')) {
140      // Drop the fence's own indent from each line (a block inside a list item).
141      const line = lines[i] ?? ''
142      const lead = /^[ \t]*/.exec(line)?.[0].length ?? 0
143      code.push(line.slice(Math.min(lead, indent)))
144      i++
145    }
146    parts.push({ kind: 'code', language: open[3] ?? '', code: code.join('\n') })
147  }
148  flushProse()
149  return parts
150}
151
152// The label in the panel's top border.
153export function panelLabel(language: string): string {
154  return language === '' ? 'code' : language.toLowerCase()
155}
156
157// Tabs as four spaces, so what is measured is what is drawn.
158export function untab(code: string): string {
159  return code.replace(/\t/g, '    ')
160}
161
162// The panel's outer width: the longest line, or the top row (the language chip,
163// a space, the Copy control) when wider, plus padding and border; never more
164// than `room`.
165export function panelWidth(code: string, label: string, room: number): number {
166  const widest = Math.max(0, ...untab(code).split('\n').map(cellWidth))
167  const controls = cellWidth(label) + 2 + 1 + Math.max(cellWidth(COPY_LABEL), cellWidth(COPIED_LABEL))
168  const inner = Math.max(widest, controls) + 2 * PANEL_PAD_X
169  return Math.max(12, Math.min(inner + 2, room))
170}
171
172// ---------------------------------------------------------------- folding a prompt
173
174export type Capped = { shown: string; hidden: number }
175
176// The head of `text` that fits in `rows` rows of `room` cells, and how many of
177// its lines are left out (a line cut part-way counts as left out).
178export function capText(text: string, room: number, rows: number): Capped {
179  const lines = text.replace(/\r\n?/g, '\n').split('\n')
180  const kept: string[] = []
181  let used = 0
182  for (let i = 0; i < lines.length; i++) {
183    const line = lines[i] ?? ''
184    const need = Math.max(1, Math.ceil(cellWidth(line) / Math.max(1, room)))
185    if (used + need <= rows) {
186      kept.push(line)
187      used += need
188      continue
189    }
190    const left = rows - used
191    if (left > 0) {
192      // Fill the rows that are left with the head of this line.
193      let cut = ''
194      for (const ch of line) {
195        if (cellWidth(cut + ch) > left * room - 1) break
196        cut += ch
197      }
198      kept.push(`${cut}…`)
199    }
200    return { shown: kept.join('\n'), hidden: lines.length - i }
201  }
202  return { shown: text, hidden: 0 }
203}
204
205// ---------------------------------------------------------------- diffs
206
207type Hunk = { oldStart: number; oldLines: number; newStart: number; newLines: number; lines: string[] }
208export type EditDiff = { path: string | undefined; source: string; added: number; removed: number; isNew: boolean }
209
210const plural = (n: number, word: string, many = `${word}s`) => `${n} ${n === 1 ? word : many}`
211
212// An Edit's or Write's result as unified-diff hunks: a new file's whole
213// content as added lines. Undefined when it carries none (an unchanged file),
214// which the engine then draws.
215export function editDiff(tool: string, output: unknown): EditDiff | undefined {
216  if (tool !== 'Edit' && tool !== 'Write') return undefined
217  if (output === null || typeof output !== 'object') return undefined
218  const out = output as { structuredPatch?: unknown; filePath?: unknown; type?: unknown; content?: unknown }
219  const path = typeof out.filePath === 'string' ? out.filePath : undefined
220  if (tool === 'Write' && out.type === 'create' && typeof out.content === 'string') {
221    const lines = out.content.replace(/\r\n?/g, '\n').replace(/\n$/, '').split('\n')
222    const source = `@@ -0,0 +1,${lines.length} @@\n${lines.map(l => `+${l}`).join('\n')}`
223    return { path, source, added: lines.length, removed: 0, isNew: true }
224  }
225  if (!Array.isArray(out.structuredPatch) || out.structuredPatch.length === 0) return undefined
226  const hunks = out.structuredPatch as Hunk[]
227  let added = 0
228  let removed = 0
229  const parts = hunks.map(h => {
230    for (const line of h.lines) {
231      if (line.startsWith('+')) added += 1
232      else if (line.startsWith('-')) removed += 1
233    }
234    return `@@ -${h.oldStart},${h.oldLines} +${h.newStart},${h.newLines} @@\n${h.lines.join('\n')}`
235  })
236  return { path, source: parts.join('\n'), added, removed, isNew: false }
237}
238
239// A file's path relative to the session's folder when inside it, else its
240// last three parts.
241export function shortPath(path: string, cwd: string): string {
242  const p = path.replace(/\\/g, '/')
243  const root = cwd.replace(/\\/g, '/').replace(/\/$/, '')
244  if (p.toLowerCase().startsWith(`${root.toLowerCase()}/`)) return p.slice(root.length + 1)
245  const parts = p.split('/').filter(s => s !== '')
246  return parts.length > 3 ? `…/${parts.slice(-3).join('/')}` : p
247}
248
249// As the engine sums a diff up: `Added 3 lines, removed 1 line`.
250export function diffSummary(added: number, removed: number): string {
251  if (added > 0 && removed > 0) return `Added ${plural(added, 'line')}, removed ${plural(removed, 'line')}`
252  if (added > 0) return `Added ${plural(added, 'line')}`
253  if (removed > 0) return `Removed ${plural(removed, 'line')}`
254  return 'No lines changed'
255}
256
257// ---------------------------------------------------------------- errors
258
259// A refusal at the permission dialog is an error to the model, not a failure
260// to show in red: the engine draws those itself.
261export function isRejection(output: unknown): boolean {
262  return typeof output === 'string' && /user (doesn't|does not) want|rejected|was denied|permission denied by the user/i.test(output)
263}
264
265// A failed call's error as plain words: Claude Code's <tool_use_error> wrapper
266// dropped, tabs as spaces, no carriage returns. Undefined when it is no text.
267export function errorText(output: unknown): string | undefined {
268  if (typeof output !== 'string') return undefined
269  const text = output.replace(/<\/?tool_use_error>/g, '').replace(/\r/g, '').replace(/\t/g, '    ').trim()
270  return text === '' ? undefined : text
271}
272
273// The red frame's outer width: its widest line (the title or the error) plus a
274// space and a border each side, never more than `room`.
275export function frameWidth(lines: readonly string[], room: number): number {
276  const widest = Math.max(1, ...lines.map(cellWidth))
277  return Math.max(12, Math.min(widest + 4, room))
278}
279
280// ---------------------------------------------------------------- times
281
282// As the engine formats a turn's length: `3s`, `1m 4s`, `1h 2m`.
283export function formatDuration(ms: number): string {
284  const total = Math.max(0, Math.round(ms / 1000))
285  const h = Math.floor(total / 3600)
286  const m = Math.floor((total % 3600) / 60)
287  const s = total % 60
288  if (h > 0) return `${h}h ${m}m`
289  if (m > 0) return `${m}m ${s}s`
290  return `${s}s`
291}
292
293// A short duration for a tool run: `0.4s` under ten seconds, else as above.
294export function formatShort(ms: number): string {
295  return ms < 10_000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatDuration(ms)
296}
297
298// The local wall-clock time, `14:02`.
299export function formatClock(at: number): string {
300  const d = new Date(at)
301  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
302}
303
304// How far apart turn.complete's duration and the footer's may be and still match.
305const MATCH_SLACK_MS = 2000
306
307// The recorded turn whose length is nearest the footer's, newest first on a tie.
308export function matchTurn(turns: readonly Turn[], durationMs: number): Turn | undefined {
309  let best: Turn | undefined
310  for (let i = turns.length - 1; i >= 0; i--) {
311    const t = turns[i]
312    if (t === undefined) continue
313    const gap = Math.abs(t.durationMs - durationMs)
314    if (gap <= MATCH_SLACK_MS && (best === undefined || gap < Math.abs(best.durationMs - durationMs))) best = t
315  }
316  return best
317}
318
319// The closing line's two parts, `39s` and `2 tools`; no count where none is known.
320export function footerParts(durationMs: number, tools: number | undefined): { took: string; used?: string } {
321  const took = formatDuration(durationMs)
322  return tools === undefined || tools === 0 ? { took } : { took, used: plural(tools, 'tool') }
323}
324
325// When the person sent this prompt: the newest record with the same words.
326export function promptTime(prompts: readonly Prompt[], text: string): number | undefined {
327  const want = text.trim()
328  for (let i = prompts.length - 1; i >= 0; i--) {
329    const p = prompts[i]
330    if (p !== undefined && p.text.trim() === want) return p.at
331  }
332  return undefined
333}
334
335// ---------------------------------------------------------------- tool groups
336
337// What a tool call worked on, in one short line: a command's first line, a
338// file's last two path parts, a pattern, a URL, a query.
339export function describeCall(tool: string, input: unknown): string {
340  const flat = callText(tool, input, false).replace(/\s+/g, ' ').trim()
341  return flat.length > 80 ? `${flat.slice(0, 79)}…` : flat
342}
343
344// What a tool call worked on, whole: a command with all its lines, a file's
345// full path, a pattern, a URL, a query.
346export function describeCallWhole(tool: string, input: unknown): string {
347  const text = callText(tool, input, true)
348  return tool === 'Bash' || tool === 'PowerShell' ? text.trim() : text.replace(/\s+/g, ' ').trim()
349}
350
351function callText(tool: string, input: unknown, isWhole: boolean): string {
352  const i = (input !== null && typeof input === 'object' ? input : {}) as Record<string, unknown>
353  const str = (k: string) => (typeof i[k] === 'string' && i[k] !== '' ? (i[k] as string) : undefined)
354  const short = (p: string) => p.replace(/\\/g, '/').split('/').filter(s => s !== '').slice(-2).join('/')
355  const path = str('file_path') ?? str('notebook_path') ?? str('path')
356  let text: string
357  switch (tool) {
358    case 'Bash':
359    case 'PowerShell':
360      text = isWhole ? str('command') ?? '' : (str('command') ?? '').split('\n')[0] ?? ''
361      break
362    case 'Read':
363    case 'Edit':
364    case 'Write':
365    case 'NotebookEdit':
366      text = path === undefined ? '' : isWhole ? path.replace(/\\/g, '/') : short(path)
367      break
368    case 'Grep':
369    case 'Glob':
370      text = str('pattern') ?? ''
371      break
372    case 'WebFetch':
373      text = (str('url') ?? '').replace(/^https?:\/\//, '')
374      break
375    case 'WebSearch':
376      text = str('query') ?? ''
377      break
378    case 'Agent':
379      text = str('description') ?? ''
380      break
381    case 'Skill':
382      text = str('skill') ?? ''
383      break
384    default: {
385      const first = Object.entries(i).find(([k, v]) => typeof v === 'string' && k !== 'tool' && k !== 'tool_use_id')
386      text = typeof first?.[1] === 'string' ? first[1] : ''
387    }
388  }
389  return text
390}
391
392// What a finished call gave back, as text to show under it in an opened
393// group: a command's output, the matches of a search, a read's line count.
394export function callOutput(tool: string, output: unknown): string {
395  if (typeof output === 'string') return output.trim()
396  if (output === null || typeof output !== 'object') return ''
397  const o = output as Record<string, unknown>
398  const text = (v: unknown) => (typeof v === 'string' ? v.trim() : '')
399  if (tool === 'Bash' || tool === 'PowerShell') return [text(o.stdout), text(o.stderr)].filter(t => t !== '').join('\n')
400  if (tool === 'Read') {
401    const file = o.file as Record<string, unknown> | undefined
402    return typeof file?.numLines === 'number' ? `${file.numLines} ${file.numLines === 1 ? 'line' : 'lines'}` : ''
403  }
404  if (text(o.content) !== '') return text(o.content)
405  if (Array.isArray(o.filenames)) return o.filenames.filter(f => typeof f === 'string').join('\n')
406  return ''
407}
408
409// `mcp__server__tool` reads as its tool's name.
410export function toolLabel(tool: string): string {
411  const mcp = /^mcp__.+?__(.+)$/.exec(tool)
412  return mcp?.[1] ?? tool
413}
414
415const VERBS: Record<string, { verb: string; one: string; many: string }> = {
416  Read: { verb: 'Read', one: 'file', many: 'files' },
417  Grep: { verb: 'Searched', one: 'pattern', many: 'patterns' },
418  Glob: { verb: 'Searched', one: 'pattern', many: 'patterns' },
419  LS: { verb: 'Listed', one: 'folder', many: 'folders' },
420  Bash: { verb: 'Ran', one: 'command', many: 'commands' },
421  PowerShell: { verb: 'Ran', one: 'command', many: 'commands' },
422  WebFetch: { verb: 'Fetched', one: 'page', many: 'pages' },
423  WebSearch: { verb: 'Searched the web', one: 'time', many: 'times' },
424  NotebookRead: { verb: 'Read', one: 'notebook', many: 'notebooks' },
425}
426
427// `Read 3 files, searched 2 patterns`, in the order the kinds first appear.
428export function groupSummary(tools: readonly string[]): string {
429  const counts = new Map<string, { verb: string; one: string; many: string; n: number }>()
430  for (const tool of tools) {
431    const v = VERBS[tool] ?? { verb: `Used ${toolLabel(tool)}`, one: 'time', many: 'times' }
432    const key = `${v.verb}|${v.one}`
433    const cur = counts.get(key)
434    if (cur === undefined) counts.set(key, { ...v, n: 1 })
435    else cur.n += 1
436  }
437  const parts = [...counts.values()].map(c => `${c.verb} ${plural(c.n, c.one, c.many)}`)
438  return parts.map((p, i) => (i === 0 ? p : p.charAt(0).toLowerCase() + p.slice(1))).join(', ')
439}
440
441// The wall time the group's calls took, first start to last end; undefined
442// while one runs or when a call's timing was not recorded.
443export function groupDuration(ids: readonly (string | undefined)[], timings: readonly Timing[]): number | undefined {
444  let start = Infinity
445  let end = -Infinity
446  for (const id of ids) {
447    const t = id === undefined ? undefined : timings.find(x => x.id === id)
448    if (t === undefined || t.end === undefined) return undefined
449    start = Math.min(start, t.start)
450    end = Math.max(end, t.end)
451  }
452  return ids.length === 0 ? undefined : end - start
453}
454
455// ---------------------------------------------------------------- message cards
456
457export type CardHead = { icon: string; label: string; color: string; meta: string }
458
459type Origin = { kind: string }
460type Task = { status?: string; durationMs?: number }
461
462// The heading of a card for a row the person did not type: a background
463// task's notification, or a message another agent, session or channel sent.
464export function cardHead(origin: Origin, task: Task | undefined, from: { name: string } | undefined): CardHead {
465  if (task !== undefined || origin.kind === 'task-notification') {
466    const status = task?.status
467    const color = status === 'failed' ? RED : status === 'completed' ? GREEN : GREY
468    const meta = [status, task?.durationMs === undefined ? undefined : formatDuration(task.durationMs)]
469      .filter((s): s is string => s !== undefined && s !== '')
470      .join(' · ')
471    return { icon: '⚙', label: 'Background task', color, meta }
472  }
473  if (origin.kind === 'scheduled-trigger') return { icon: '⏰', label: 'Scheduled task', color: PURPLE_LIGHT, meta: '' }
474  if (origin.kind === 'channel') return { icon: '#', label: from?.name ?? 'Channel', color: PURPLE_LIGHT, meta: 'channel' }
475  if (origin.kind === 'plugin') return { icon: '◆', label: 'From a mod', color: PURPLE_LIGHT, meta: '' }
476  if (origin.kind === 'slack-ping') return { icon: '✉', label: from?.name ?? 'Slack', color: PURPLE_LIGHT, meta: 'Slack' }
477  return { icon: '✉', label: from === undefined ? 'Message' : `From ${from.name}`, color: PURPLE_LIGHT, meta: '' }
478}
479
hooks/ink.tsx 157 lines
1// The colours inside replies and on tool-call rows. prettier's layout draws
2// around them; /prettier on|off turns both on or off together.
3import type { EngineInterface, RenderInput, RenderNode } from 'claude-code'
4
5import { drawMarkdown, ORANGE, PURPLE, PURPLE_LIGHT } from './markdown'
6
7const RED = '#EF4444'
8const GREY = '#71717A'
9const GUTTER = 2
10
11// ---------------------------------------------------------------- tool rows
12
13function normalize(path: string): string {
14  return path.replace(/\\/g, '/')
15}
16
17// Relative to the session's folder when inside it, else its last three parts.
18function shortPath(path: string, cwd: string): string {
19  const p = normalize(path)
20  const root = normalize(cwd).replace(/\/$/, '')
21  if (p.toLowerCase().startsWith(`${root.toLowerCase()}/`)) return p.slice(root.length + 1)
22  const parts = p.split('/').filter(s => s !== '')
23  return parts.length > 3 ? `…/${parts.slice(-3).join('/')}` : p
24}
25
26function str(input: Record<string, unknown>, key: string): string | undefined {
27  const v = input[key]
28  return typeof v === 'string' && v !== '' ? v : undefined
29}
30
31// `isCommand`: the summary is a shell command, drawn whole with its own lines.
32type Row = { name: string; scope?: string; summary: string; isCommand?: true }
33
34function describe(tool: string, raw: unknown, cwd: string): Row {
35  const input = (raw !== null && typeof raw === 'object' ? raw : {}) as Record<string, unknown>
36  const mcp = /^mcp__(.+?)__(.+)$/.exec(tool)
37  if (mcp !== null) {
38    const scope = (mcp[1] ?? '').replace(/^claude_ai_/, '').replace(/_/g, ' ')
39    const first = Object.values(input).find(v => typeof v === 'string')
40    return { name: (mcp[2] ?? tool).replace(/_/g, ' '), scope, summary: typeof first === 'string' ? first : '' }
41  }
42  const path = str(input, 'file_path') ?? str(input, 'notebook_path') ?? str(input, 'path')
43  switch (tool) {
44    case 'Bash':
45    case 'PowerShell':
46      return { name: tool, summary: (str(input, 'command') ?? '').trim(), isCommand: true }
47    case 'Read':
48    case 'NotebookEdit':
49      return { name: tool, summary: path === undefined ? '' : shortPath(path, cwd) }
50    case 'Edit':
51    case 'Write':
52      return { name: tool, summary: path === undefined ? '' : shortPath(path, cwd) }
53    case 'Grep': {
54      const where = path === undefined ? '' : ` in ${shortPath(path, cwd)}`
55      return { name: tool, summary: `${str(input, 'pattern') ?? ''}${where}` }
56    }
57    case 'Glob':
58      return { name: tool, summary: str(input, 'pattern') ?? '' }
59    case 'WebFetch':
60      return { name: tool, summary: (str(input, 'url') ?? '').replace(/^https?:\/\//, '') }
61    case 'WebSearch':
62      return { name: tool, summary: str(input, 'query') ?? '' }
63    case 'Agent':
64      return { name: tool, summary: str(input, 'description') ?? '' }
65    case 'Skill':
66      return { name: tool, summary: str(input, 'skill') ?? '' }
67    default: {
68      const first = Object.values(input).find(v => typeof v === 'string')
69      return { name: tool, summary: typeof first === 'string' ? first : '' }
70    }
71  }
72}
73
74// Whitespace runs as one space, so a summary reads as one line of words.
75function flatten(text: string): string {
76  return text.replace(/\s+/g, ' ').trim()
77}
78
79// ---------------------------------------------------------------- drawing
80//
81// Each answers what the row beneath prettier's layout draws: the colours when
82// they are on, else `next`. A drawing that fails is passed by, as Claude Code
83// passed by a mod's hook that failed, and `next` draws the row.
84
85type Next<E> = (e: E) => Promise<RenderNode>
86
87// The colours draw on the terminal; prettier hands every row on when it is off.
88function isInkOn(surface: string): boolean {
89  return surface === 'terminal'
90}
91
92// A reply's text, drawn from its markdown in the ink palette.
93export async function inkReply(
94  $: EngineInterface,
95  e: RenderInput<'AssistantMessage'>,
96  next: Next<RenderInput<'AssistantMessage'>>,
97): Promise<RenderNode> {
98  if (!isInkOn(e.surface)) return next(e)
99  try {
100    const el = $.ui.resolve({ ...e, surface: 'terminal' as const })
101    const { Box, Text } = el
102    const room = Math.max(20, (e.viewport?.columns ?? 80) - GUTTER - 1)
103    return (
104      <Box flexDirection="row">
105        <Box width={GUTTER} flexShrink={0}>
106          <Text color={ORANGE}>{e.props.isFirstOfReply ? '●' : ' '}</Text>
107        </Box>
108        {drawMarkdown(e.props.text, room, el)}
109      </Box>
110    )
111  } catch {
112    return next(e)
113  }
114}
115
116// A tool call's row: a status dot, the tool in purple, what it works on.
117export async function inkToolRow(
118  $: EngineInterface,
119  e: RenderInput<'ToolUse'>,
120  next: Next<RenderInput<'ToolUse'>>,
121): Promise<RenderNode> {
122  if (!isInkOn(e.surface)) return next(e)
123  try {
124    const { Box, Text } = $.ui.resolve({ ...e, surface: 'terminal' as const })
125    const cwd = await $.session.cwd()
126    const row = describe(e.props.tool, e.props.input, cwd)
127    const dot = e.props.isInterrupted
128      ? GREY
129      : e.props.isErrored
130        ? RED
131        : e.props.isRunning
132          ? PURPLE_LIGHT
133          : PURPLE
134    const scope = row.scope === undefined ? '' : ` ${row.scope}`
135    const note = e.props.isInterrupted ? ' · interrupted' : ''
136    // Drawn whole, never cut: the row wraps in whatever width it is given.
137    const summary = row.isCommand === true ? row.summary : flatten(row.summary)
138    return (
139      <Box flexDirection="row">
140        <Box width={GUTTER} flexShrink={0}>
141          <Text color={dot}>{e.props.isRunning ? '○' : '●'}</Text>
142        </Box>
143        <Text>
144          <Text color={PURPLE} bold>
145            {row.name}
146          </Text>
147          {scope !== '' && <Text dimColor>{scope}</Text>}
148          {summary !== '' && <Text dimColor>{` ${summary}`}</Text>}
149          {note !== '' && <Text dimColor>{note}</Text>}
150        </Text>
151      </Box>
152    )
153  } catch {
154    return next(e)
155  }
156}
157
hooks/settings.ts 139 lines
1import type { Settings } from '../types'
2
3export const DEFAULTS: Settings = {
4  isEnabled: true,
5  prompt: { width: 70, lines: 6, time: true },
6  response: { width: 85, fold: true },
7  code: { width: 75 },
8}
9
10export type Section = 'prompt' | 'response' | 'code'
11
12type Field =
13  | { kind: 'number'; min: number; max: number; about: string }
14  | { kind: 'switch'; about: string }
15  | { kind: 'choice'; options: readonly string[]; about: string }
16
17// Every setting a command takes, in the order its help lists them.
18export const FIELDS: { [S in Section]: Record<string, Field> } = {
19  prompt: {
20    width: { kind: 'number', min: 30, max: 100, about: 'widest the prompt pill gets, in % of the terminal' },
21    lines: { kind: 'number', min: 1, max: 50, about: 'lines of a long prompt shown before it folds' },
22    time: { kind: 'switch', about: 'the time under each prompt' },
23  },
24  response: {
25    width: { kind: 'number', min: 40, max: 100, about: 'widest replies and tool output get, in % of the terminal' },
26    fold: { kind: 'switch', about: 'fold runs of reads and searches into one line' },
27  },
28  code: {
29    width: { kind: 'number', min: 30, max: 100, about: 'widest an edit\'s added and removed lines get, in % of the terminal' },
30  },
31}
32
33export const COMMANDS: { [S in Section]: { name: string; description: string; example: string } } = {
34  prompt: { name: 'prettier-prompt', description: 'Prompt pill: width, lines, time', example: 'width 60 lines 4' },
35  response: { name: 'prettier-response', description: 'Replies and tool output: width, fold', example: 'width 80 fold off' },
36  code: { name: 'prettier-code', description: 'Code diffs: width', example: 'width 70' },
37}
38
39export const EXPAND_HINT = 'Press ctrl+o to see full tool calls, their output and long prompts; ctrl+o again to go back.'
40
41function fieldValue(field: Field, value: unknown): string {
42  if (field.kind === 'switch') return value === true ? 'on' : 'off'
43  return String(value)
44}
45
46function fieldRange(field: Field): string {
47  if (field.kind === 'number') return `${field.min}–${field.max}`
48  if (field.kind === 'switch') return 'on | off'
49  return field.options.join(' | ')
50}
51
52// The settings a stored value holds, every missing or invalid one at its default.
53export function mergeSettings(stored: unknown): Settings {
54  const out: Settings = structuredClone(DEFAULTS)
55  if (stored === null || typeof stored !== 'object') return out
56  const s = stored as Record<string, unknown>
57  if (typeof s.isEnabled === 'boolean') out.isEnabled = s.isEnabled
58  for (const section of Object.keys(FIELDS) as Section[]) {
59    const given = s[section]
60    if (given === null || typeof given !== 'object') continue
61    const target = out[section] as Record<string, unknown>
62    for (const [key, field] of Object.entries(FIELDS[section])) {
63      const v = (given as Record<string, unknown>)[key]
64      if (field.kind === 'number' && typeof v === 'number' && v >= field.min && v <= field.max) target[key] = v
65      if (field.kind === 'switch' && typeof v === 'boolean') target[key] = v
66      if (field.kind === 'choice' && typeof v === 'string' && field.options.includes(v)) target[key] = v
67    }
68  }
69  return out
70}
71
72export type Applied = { settings: Settings; changed: string[]; errors: string[] }
73
74// Applies `width 60 lines 4` (pairs of name and value) to one section.
75export function applyArgs(settings: Settings, section: Section, args: string): Applied {
76  const out: Settings = structuredClone(settings)
77  const target = out[section] as Record<string, unknown>
78  const fields = FIELDS[section]
79  const words = args.trim().toLowerCase().split(/\s+/).filter(w => w !== '')
80  const changed: string[] = []
81  const errors: string[] = []
82  for (let i = 0; i < words.length; i += 2) {
83    const name = words[i] ?? ''
84    const raw = words[i + 1]
85    const field = fields[name]
86    if (field === undefined) {
87      errors.push(`\`${name}\` is not a setting here; the settings are ${Object.keys(fields).map(k => `\`${k}\``).join(', ')}`)
88      continue
89    }
90    if (raw === undefined) {
91      errors.push(`\`${name}\` needs a value: ${fieldRange(field)}`)
92      continue
93    }
94    if (field.kind === 'number') {
95      const n = Number(raw.replace(/%$/, ''))
96      if (!Number.isInteger(n) || n < field.min || n > field.max) {
97        errors.push(`\`${name}\` must be a whole number from ${field.min} to ${field.max}`)
98        continue
99      }
100      target[name] = n
101    } else if (field.kind === 'switch') {
102      if (raw !== 'on' && raw !== 'off') {
103        errors.push(`\`${name}\` must be on or off`)
104        continue
105      }
106      target[name] = raw === 'on'
107    } else {
108      if (!field.options.includes(raw)) {
109        errors.push(`\`${name}\` must be one of ${field.options.join(', ')}`)
110        continue
111      }
112      target[name] = raw
113    }
114    changed.push(`${name} ${raw.replace(/%$/, '')}`)
115  }
116  return { settings: out, changed, errors }
117}
118
119// What a command prints with no arguments: each setting, its value and what it does.
120export function describeSection(settings: Settings, section: Section): string {
121  const { name, example } = COMMANDS[section]
122  const values = settings[section] as Record<string, unknown>
123  const lines = Object.entries(FIELDS[section]).map(
124    ([key, field]) => `- \`${key} ${fieldValue(field, values[key])}\` ${field.about} (${fieldRange(field)})`,
125  )
126  return [...lines, '', `To change: \`/${name} ${example}\``].join('\n')
127}
128
129// What /prettier prints with no arguments: the switch, the three commands, the key.
130export function describeAll(settings: Settings): string {
131  return [
132    `prettier is **${settings.isEnabled ? 'on' : 'off'}**. \`/prettier on\`, \`/prettier off\`, \`/prettier reset\` (every setting back to its default).`,
133    '',
134    ...(Object.keys(COMMANDS) as Section[]).map(s => `- \`/${COMMANDS[s].name}\` ${COMMANDS[s].description.toLowerCase()}`),
135    '',
136    EXPAND_HINT,
137  ].join('\n')
138}
139
hooks/markdown.tsx 495 lines
1import type { Elements, RenderNode } from 'claude-code'
2
3type El = Elements['terminal']
4type Inline = (RenderNode | string)[]
5
6// Palette shared with statusdeck and panes: orange for emphasis, purple for
7// structure. Body text keeps the terminal's own colour.
8export const ORANGE = '#F97316'
9export const ORANGE_BOLD = '#FB923C'
10export const ORANGE_LIGHT = '#FED7AA'
11export const PURPLE = '#A855F7'
12export const PURPLE_DEEP = '#7C3AED'
13export const PURPLE_LIGHT = '#C4B5FD'
14export const LAVENDER = '#D8B4FE'
15export const TABLE_HEAD = '#EA580C'
16export const ZEBRA = '#262626'
17export const RULE = '#3F3F46'
18
19type Ctx = { bold: string; color?: string }
20
21// ---------------------------------------------------------------- inline
22
23const INLINE: [RegExp, (m: RegExpExecArray, ctx: Ctx, el: El) => RenderNode][] = [
24  [/^(`+)([\s\S]+?)\1(?!`)/, (m, _ctx, { Text }) => <Text color={PURPLE_LIGHT}>{m[2] ?? ''}</Text>],
25  [
26    /^\*\*\*(?=\S)([\s\S]+?)(?<=\S)\*\*\*/,
27    (m, ctx, el) => (
28      <el.Text bold italic color={ctx.bold}>
29        {inline(m[1] ?? '', ctx, el)}
30      </el.Text>
31    ),
32  ],
33  [
34    /^(\*\*|__)(?=\S)([\s\S]+?)(?<=\S)\1/,
35    (m, ctx, el) => (
36      <el.Text bold color={ctx.color ?? ctx.bold}>
37        {inline(m[2] ?? '', ctx, el)}
38      </el.Text>
39    ),
40  ],
41  [
42    /^~~(?=\S)([\s\S]+?)(?<=\S)~~/,
43    (m, ctx, el) => <el.Text strikethrough>{inline(m[1] ?? '', ctx, el)}</el.Text>,
44  ],
45  [
46    /^\*(?=[^\s*])([\s\S]+?)(?<=[^\s*])\*(?!\*)/,
47    (m, ctx, el) => <el.Text italic>{inline(m[1] ?? '', ctx, el)}</el.Text>,
48  ],
49  [
50    /^_(?=\S)([\s\S]+?)(?<=\S)_(?!\w)/,
51    (m, ctx, el) => <el.Text italic>{inline(m[1] ?? '', ctx, el)}</el.Text>,
52  ],
53  [
54    /^\[([^\]\n]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/,
55    (m, ctx, el) => (
56      <el.Link href={m[2] ?? ''}>
57        <el.Text color={LAVENDER} underline>
58          {inline(m[1] ?? '', ctx, el)}
59        </el.Text>
60      </el.Link>
61    ),
62  ],
63  [
64    /^<?(https?:\/\/[^\s<>()]*[^\s<>().,;:!?'"`*])>?/,
65    (m, _ctx, el) => (
66      <el.Link href={m[1] ?? ''}>
67        <el.Text color={LAVENDER} underline>
68          {m[1] ?? ''}
69        </el.Text>
70      </el.Link>
71    ),
72  ],
73]
74
75export function inline(text: string, ctx: Ctx, el: El): Inline {
76  const out: Inline = []
77  let plain = ''
78  let i = 0
79  while (i < text.length) {
80    const rest = text.slice(i)
81    const escaped = /^\\([\\`*_{}[\]()#+\-.!~|>])/.exec(rest)
82    if (escaped !== null) {
83      plain += escaped[1]
84      i += 2
85      continue
86    }
87    // Underscores and asterisks inside a word are text, not emphasis.
88    const prev = i > 0 ? text[i - 1] ?? '' : ''
89    const isWordEdge = !/\w/.test(prev)
90    let matched = false
91    for (const [re, make] of INLINE) {
92      if ((rest.startsWith('_') || rest.startsWith('*')) && !isWordEdge && !rest.startsWith('**')) break
93      if (rest.startsWith('http') && !isWordEdge) break
94      const m = re.exec(rest)
95      if (m === null) continue
96      if (plain !== '') out.push(plain)
97      plain = ''
98      out.push(make(m, ctx, el))
99      i += m[0].length
100      matched = true
101      break
102    }
103    if (!matched) {
104      plain += text[i]
105      i += 1
106    }
107  }
108  if (plain !== '') out.push(plain)
109  return out
110}
111
112// The text a cell shows, for measuring its width.
113export function plainText(text: string): string {
114  return text
115    .replace(/\[([^\]\n]+)\]\([^)\s]+(?:\s+"[^"]*")?\)/g, '$1')
116    .replace(/(\*\*\*|\*\*|__|~~)(?=\S)([\s\S]+?)(?<=\S)\1/g, '$2')
117    .replace(/(`+)([\s\S]+?)\1/g, '$2')
118    .replace(/(^|\W)[*_](?=\S)([\s\S]+?)(?<=\S)[*_](?!\w)/g, '$1$2')
119    .replace(/\\([\\`*_{}[\]()#+\-.!~|>])/g, '$1')
120}
121
122function width(text: string): number {
123  let n = 0
124  for (const ch of plainText(text)) {
125    const code = ch.codePointAt(0) ?? 0
126    // Wide East Asian characters and most emoji take two cells.
127    n += (code >= 0x1100 && code <= 0x115f) || (code >= 0x2e80 && code <= 0xa4cf) ||
128      (code >= 0xac00 && code <= 0xd7a3) || (code >= 0xf900 && code <= 0xfaff) ||
129      (code >= 0xfe30 && code <= 0xfe4f) || (code >= 0xff00 && code <= 0xff60) ||
130      (code >= 0x1f300 && code <= 0x1faff)
131      ? 2
132      : 1
133  }
134  return n
135}
136
137// ---------------------------------------------------------------- blocks
138
139type Item = { level: number; marker: string; isOrdered: boolean; text: string }
140type Align = 'left' | 'center' | 'right'
141type Block =
142  | { kind: 'heading'; level: number; text: string }
143  | { kind: 'para'; text: string }
144  | { kind: 'code'; lang: string; source: string }
145  | { kind: 'list'; items: Item[] }
146  | { kind: 'quote'; text: string }
147  | { kind: 'table'; head: string[]; rows: string[][]; align: Align[] }
148  | { kind: 'rule' }
149
150const FENCE = /^(\s*)(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/
151const HEADING = /^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/
152const RULE_LINE = /^\s{0,3}([-*_])(\s*\1){2,}\s*$/
153const ITEM = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/
154const QUOTE = /^\s{0,3}>\s?(.*)$/
155const TABLE_SEP = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/
156
157function cells(line: string): string[] {
158  let s = line.trim()
159  if (s.startsWith('|')) s = s.slice(1)
160  if (s.endsWith('|') && !s.endsWith('\\|')) s = s.slice(0, -1)
161  const out: string[] = []
162  let cur = ''
163  let inCode = false
164  for (let i = 0; i < s.length; i++) {
165    const ch = s[i] ?? ''
166    if (ch === '\\' && s[i + 1] === '|') {
167      cur += '|'
168      i += 1
169    } else if (ch === '`') {
170      inCode = !inCode
171      cur += ch
172    } else if (ch === '|' && !inCode) {
173      out.push(cur.trim())
174      cur = ''
175    } else cur += ch
176  }
177  out.push(cur.trim())
178  return out
179}
180
181function isBlockStart(line: string, next: string | undefined): boolean {
182  return (
183    FENCE.test(line) || HEADING.test(line) || RULE_LINE.test(line) || ITEM.test(line) ||
184    QUOTE.test(line) || (line.includes('|') && next !== undefined && TABLE_SEP.test(next) && next.includes('-'))
185  )
186}
187
188export function parse(src: string): Block[] {
189  const lines = src.replace(/\r\n?/g, '\n').split('\n')
190  const out: Block[] = []
191  let i = 0
192  while (i < lines.length) {
193    const line = lines[i] ?? ''
194    const next = lines[i + 1]
195    if (line.trim() === '') {
196      i += 1
197      continue
198    }
199
200    const fence = FENCE.exec(line)
201    if (fence !== null) {
202      const mark = fence[2] ?? '```'
203      const body: string[] = []
204      i += 1
205      while (i < lines.length && !(lines[i] ?? '').trim().startsWith(mark)) {
206        body.push(lines[i] ?? '')
207        i += 1
208      }
209      i += 1
210      out.push({ kind: 'code', lang: fence[3] ?? '', source: body.join('\n') })
211      continue
212    }
213
214    const heading = HEADING.exec(line)
215    if (heading !== null) {
216      out.push({ kind: 'heading', level: (heading[1] ?? '#').length, text: heading[2] ?? '' })
217      i += 1
218      continue
219    }
220
221    if (RULE_LINE.test(line)) {
222      out.push({ kind: 'rule' })
223      i += 1
224      continue
225    }
226
227    if (line.includes('|') && next !== undefined && TABLE_SEP.test(next) && next.includes('-')) {
228      const head = cells(line)
229      const align = cells(next).map(c =>
230        c.startsWith(':') && c.endsWith(':') ? 'center' : c.endsWith(':') ? 'right' : 'left',
231      ) as Align[]
232      const rows: string[][] = []
233      i += 2
234      while (i < lines.length && (lines[i] ?? '').includes('|') && (lines[i] ?? '').trim() !== '') {
235        rows.push(cells(lines[i] ?? ''))
236        i += 1
237      }
238      out.push({ kind: 'table', head, rows, align })
239      continue
240    }
241
242    if (QUOTE.test(line)) {
243      const body: string[] = []
244      while (i < lines.length && QUOTE.test(lines[i] ?? '')) {
245        body.push(QUOTE.exec(lines[i] ?? '')?.[1] ?? '')
246        i += 1
247      }
248      out.push({ kind: 'quote', text: body.join('\n') })
249      continue
250    }
251
252    if (ITEM.test(line)) {
253      const items: Item[] = []
254      const indents: number[] = []
255      while (i < lines.length) {
256        const cur = lines[i] ?? ''
257        const m = ITEM.exec(cur)
258        if (m !== null) {
259          const indent = (m[1] ?? '').replace(/\t/g, '    ').length
260          // A top-level item of the other kind (bullets, numbers) starts a new list.
261          const first = items[0]
262          if (first !== undefined && indent <= (indents[0] ?? 0) && /\d/.test(m[2] ?? '') !== first.isOrdered) break
263          while (indents.length > 0 && (indents[indents.length - 1] ?? 0) > indent) indents.pop()
264          if (indents.length === 0 || (indents[indents.length - 1] ?? 0) < indent) indents.push(indent)
265          const marker = m[2] ?? '-'
266          items.push({ level: indents.length - 1, marker, isOrdered: /\d/.test(marker), text: m[3] ?? '' })
267          i += 1
268          continue
269        }
270        if (cur.trim() === '') {
271          // A blank line ends the list unless another item follows it.
272          let j = i + 1
273          while (j < lines.length && (lines[j] ?? '').trim() === '') j += 1
274          if (j < lines.length && ITEM.test(lines[j] ?? '')) {
275            i = j
276            continue
277          }
278          break
279        }
280        // An indented line continues the item above it.
281        if (/^\s+\S/.test(cur) && items.length > 0 && !isBlockStart(cur.trim(), lines[i + 1])) {
282          const last = items[items.length - 1]
283          if (last !== undefined) last.text += `\n${cur.trim()}`
284          i += 1
285          continue
286        }
287        break
288      }
289      out.push({ kind: 'list', items })
290      continue
291    }
292
293    const body: string[] = [line]
294    i += 1
295    while (i < lines.length && (lines[i] ?? '').trim() !== '' && !isBlockStart(lines[i] ?? '', lines[i + 1])) {
296      body.push(lines[i] ?? '')
297      i += 1
298    }
299    out.push({ kind: 'para', text: body.join('\n') })
300  }
301  return out
302}
303
304// ---------------------------------------------------------------- drawing
305
306// Headings are bold bright orange (the table-header orange), no background.
307const HEADINGS: Record<number, { color: string; underline?: boolean }> = {
308  1: { color: TABLE_HEAD, underline: true },
309  2: { color: TABLE_HEAD },
310  3: { color: TABLE_HEAD },
311}
312
313// Cell padding: one column a side, and a blank row above each body row's text.
314// The header has no blank rows.
315const PAD_X = 1
316const PAD_TOP = 0
317// No column takes more than this share of the reply's width.
318const MAX_SHARE = 0.3
319
320function drawTable(b: Extract<Block, { kind: 'table' }>, room: number, el: El): RenderNode {
321  const { Box, Text } = el
322  const count = Math.max(b.head.length, ...b.rows.map(r => r.length))
323  const most = Math.max(3, Math.floor(room * MAX_SHARE) - PAD_X * 2)
324  const widths: number[] = []
325  for (let c = 0; c < count; c++) {
326    widths.push(Math.min(most, Math.max(3, width(b.head[c] ?? ''), ...b.rows.map(r => width(r[c] ?? '')))))
327  }
328  // Each cell has its padding a side, with a rule between cells and one at
329  // each edge; shrink the widest column until the table fits.
330  while (widths.reduce((a, w) => a + w + PAD_X * 2, 0) + count + 1 > room) {
331    let at = 0
332    for (let c = 1; c < count; c++) if ((widths[c] ?? 0) > (widths[at] ?? 0)) at = c
333    if ((widths[at] ?? 0) <= 3) break
334    widths[at] = (widths[at] ?? 0) - 1
335  }
336  const justify = (a: Align | undefined) =>
337    a === 'right' ? 'flex-end' : a === 'center' ? 'center' : 'flex-start'
338
339  // A rule floats in a column that stretches to the row's height and cuts it
340  // there, so it spans however tall the row wraps. It holds a line per
341  // character of the longest cell, more than any wrap of it needs.
342  const rule = (lines: string, color: string) => (
343    <Box width={1} flexShrink={0} overflow="hidden">
344      <Box position="absolute" top={0} left={0} width={1}>
345        <Text color={color}>{lines}</Text>
346      </Box>
347    </Box>
348  )
349
350  const row = (values: string[], isHead: boolean, bg: string | undefined) => {
351    const tallest = Math.max(1, ...values.map(v => width(v))) + PAD_TOP
352    const lines = Array.from({ length: tallest }, () => '│').join('\n')
353    const cellsOut: RenderNode[] = []
354    widths.forEach((w, c) => {
355      if (c > 0) cellsOut.push(rule(lines, TABLE_HEAD))
356      cellsOut.push(
357        <Box width={w + PAD_X * 2} paddingX={PAD_X} paddingTop={isHead ? 0 : PAD_TOP} justifyContent={justify(b.align[c])}>
358          <Text bold={isHead} backgroundColor={bg} wrap="wrap">
359            {inline(values[c] ?? '', { bold: ORANGE_LIGHT }, el)}
360          </Text>
361        </Box>,
362      )
363    })
364    // The fill stays inside the frame: the edges sit outside the filled Box.
365    return (
366      <Box flexDirection="row">
367        {rule(lines, TABLE_HEAD)}
368        <Box flexDirection="row" backgroundColor={bg}>
369          {cellsOut}
370        </Box>
371        {rule(lines, TABLE_HEAD)}
372      </Box>
373    )
374  }
375
376  // The top and bottom edges, rounded at the corners: a run of ─ over or
377  // under each column, laid out as the cells are so it shrinks with them, and
378  // cut to one row.
379  const edge = (left: string, join: string, right: string) => {
380    const runs: RenderNode[] = []
381    widths.forEach((w, c) => {
382      if (c > 0) runs.push(<Text color={TABLE_HEAD}>{join}</Text>)
383      runs.push(
384        <Box width={w + PAD_X * 2} height={1} overflow="hidden">
385          <Text color={TABLE_HEAD}>{'─'.repeat(w + PAD_X * 2)}</Text>
386        </Box>,
387      )
388    })
389    return (
390      <Box flexDirection="row">
391        <Text color={TABLE_HEAD}>{left}</Text>
392        <Box flexDirection="row">{runs}</Box>
393        <Text color={TABLE_HEAD}>{right}</Text>
394      </Box>
395    )
396  }
397
398  return (
399    <Box flexDirection="column">
400      {edge('╭', '┬', '╮')}
401      {row(b.head, true, undefined)}
402      {edge('├', '┼', '┤')}
403      {b.rows.map((r, n) => row(r, false, n % 2 === 1 ? ZEBRA : undefined))}
404      {edge('╰', '┴', '╯')}
405    </Box>
406  )
407}
408
409function drawList(items: Item[], el: El): RenderNode {
410  const { Box, Text } = el
411  const counters: number[] = []
412  return (
413    <Box flexDirection="column">
414      {items.map(item => {
415        counters.length = item.level + 1
416        counters[item.level] = (counters[item.level] ?? 0) + 1
417        const start = /^\d+/.exec(item.marker)
418        if (item.isOrdered && counters[item.level] === 1 && start !== null) counters[item.level] = Number(start[0])
419        const task = /^\[([ xX])\]\s+/.exec(item.text)
420        const marker = item.isOrdered ? `${counters[item.level]}.` : '-'
421        const text = task !== null ? item.text.slice(task[0].length) : item.text
422        return (
423          <Box flexDirection="row" marginLeft={item.level * 2}>
424            <Text color={PURPLE} bold={item.isOrdered}>
425              {`${marker} `}
426            </Text>
427            {task !== null && <Text color={PURPLE}>{task[1] === ' ' ? '☐ ' : '☑ '}</Text>}
428            <Box flexShrink={1}>
429              <Text>{inline(text, { bold: ORANGE_LIGHT }, el)}</Text>
430            </Box>
431          </Box>
432        )
433      })}
434    </Box>
435  )
436}
437
438function drawBlock(b: Block, room: number, el: El): RenderNode {
439  const { Box, Code, Text } = el
440  switch (b.kind) {
441    case 'heading': {
442      const style = HEADINGS[b.level] ?? { color: TABLE_HEAD }
443      return (
444        <Text bold color={style.color} underline={style.underline}>
445          {inline(b.text, { bold: style.color }, el)}
446        </Text>
447      )
448    }
449    case 'para':
450      return <Text>{inline(b.text, { bold: ORANGE_LIGHT }, el)}</Text>
451    case 'code':
452      return (
453        <Box flexDirection="column">
454          <Text>
455            <Text color={PURPLE_DEEP}>▎</Text>
456            <Text dimColor>{` ${b.lang === '' ? 'code' : b.lang}`}</Text>
457          </Text>
458          <Box marginLeft={2}>
459            <Code source={b.source} language={b.lang === '' ? undefined : b.lang} />
460          </Box>
461        </Box>
462      )
463    case 'list':
464      return drawList(b.items, el)
465    case 'quote':
466      return (
467        <Box flexDirection="row">
468          <Text color={PURPLE_DEEP}>▎ </Text>
469          <Box flexShrink={1}>
470            <Text italic dimColor>
471              {inline(b.text, { bold: ORANGE_LIGHT }, el)}
472            </Text>
473          </Box>
474        </Box>
475      )
476    case 'table':
477      return drawTable(b, room, el)
478    case 'rule':
479      return <Text color={RULE}>{'─'.repeat(Math.max(3, Math.min(room, 60)))}</Text>
480  }
481}
482
483// A reply block: one blank row between blocks, as the engine spaces them.
484export function drawMarkdown(text: string, room: number, el: El): RenderNode {
485  const { Box } = el
486  const blocks = parse(text)
487  return (
488    <Box flexDirection="column" width={room}>
489      {blocks.map((b, n) => (
490        <Box marginTop={n === 0 ? 0 : 1}>{drawBlock(b, room, el)}</Box>
491      ))}
492    </Box>
493  )
494}
495
types/index.d.ts 53 lines
1// What /prettier-prompt sets: the pill holding the person's own prompt.
2export type PromptSettings = { width: number; lines: number; time: boolean }
3
4// What /prettier-response sets: everything a turn draws.
5export type ResponseSettings = { width: number; fold: boolean }
6
7// What /prettier-code sets: an edit's diff.
8export type CodeSettings = { width: number }
9
10export type Settings = {
11  isEnabled: boolean
12  prompt: PromptSettings
13  response: ResponseSettings
14  code: CodeSettings
15}
16
17// One main-loop tool call of a turn: what it worked on, how long it took,
18// whether it failed.
19export type Call = { id: string; tool: string; detail: string; ms?: number; failed?: boolean }
20
21// A finished main-loop turn: its length as turn.complete reported it, how many
22// tool calls it made, and those calls (absent on a turn recorded before).
23export type Turn = { durationMs: number; tools: number; calls?: Call[] }
24
25// The main loop's turn in progress: the tool calls running now, oldest first,
26// how many it has made so far, and each of them.
27export type Live = { running: { id: string; tool: string }[]; tools: number; calls?: Call[] }
28
29// A prompt the person sent, and when (epoch ms).
30export type Prompt = { text: string; at: number }
31
32// When a main-loop tool call started and ended (epoch ms).
33export type Timing = { id: string; start: number; end?: number }
34
35declare module 'claude-code' {
36  interface PluginState {
37    prettier: {
38      settings: Settings
39      turns: Turn[]
40      live: Live
41      prompts: Prompt[]
42      timings: Timing[]
43      // Whether a compact row (a folded prompt, a group, a turn's tools) is open,
44      // by the row's requestId.
45      open: StateFamily<boolean>
46      // Whether a code panel's Copy was just pressed, by `<requestId>:<block>`.
47      copied: StateFamily<boolean>
48      // The spinner's animation step while the main loop's turn runs.
49      spin: number
50    }
51  }
52}
53