SLOPSHOPPER

handily-simple-view

One short row for each tool call, except a call that asks you or shows you a plan, with buttons to open and copy a Bash output, /simple to switch it and…

rowsguardcommandtoasttimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · handily-simple-view
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /simple ⎿ handily-simple-view: off for this session. Tool calls draw as Claude Code draws them. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

handily-simple-view

simple-view draws one short row for each tool call in the transcript: a built-in tool, an MCP tool or a tool that a plugin adds. Bash, Edit, Write, Read, Grep and Glob have rich rows. Every other tool has the generic row: the tool name, a short summary of the input, the state, and the size of the result and the time. A call that asks you or shows you a plan keeps the row of Claude Code. A Bash row with output has a more button that opens the output under the row, and a copy button that copies it. /simple off and /simple on switch the view for the session. /simple show N prints one call in full. The model still reads the full tool result. Only the screen changes.

● List the mods  ls  exit 0  7 lines  1.1s                                  [ more ] [ copy ]
● List a folder that does not exist  ls  exit 2  ls: cannot access '/n…  [ more ] [ copy ]
● Append a probe line  printf  exit 0  0 lines  2.8s
  Updated README.md (+1 -0)
● Edit  src/app.ts  +2 -1
● Read  mods/handily/.claude-plugin/plugin.json  18 lines
● Read  docs/design.md  lines 160-239 of 674
● WebSearch  handily claude code mods  done  16 lines  5.3s
● claude-in-chrome · list_connected_browsers  done  1 line

The approved mocks are in docs/mocks.md, sections 6 and 7.2. The design is in docs/design.md, section 4.8.

docs/install.md gives the install, update and uninstall steps.

Rows

CallRowResult block under it
Bash, Read, Grep, Glob, before the rundescription or tool, the parts of the input it can read, dim …as the engine draws it
Bash, runningdescription, program, dim running, time since the call startedas the engine draws it
Bash, no errordescription, program, exit 0, stdout line count, timeone Updated line per changed file
Bash, Exit code Ndescription, program, exit N, the first non-empty error line, timeempty
Edit, Writetool, file path, added and removed line totalsempty
Readtool, file path, line count, or the range of lines that the call readempty
Greptool, pattern in quotes, in and the folder, the count of the output modeempty
Globtool, pattern, in and the folder, the count of matched filesempty
Read, Grep, Glob, runningtool, the path or the pattern from the input, dim …as the engine draws it
Any other tool, before the runtool name, input summary, dim …as the engine draws it
Any other tool, runningtool name, input summary, dim running, time since the call startedas the engine draws it
Any other tool, no errortool name, input summary, done, line count of the result, timeempty
Any other tool, errortool name, input summary, erroras the engine draws it
  • The description is the description that the model gave. Without one, the row shows the first command segment. An ellipsis (…) marks a cut or a segment that follows.
  • The program is the first word of the first segment that is not cd, pushd or popd. A VAR=value word before it is skipped.
  • When the engine gives a meaning for a non-zero exit that is not an error, such as No matches found for grep, the row shows that meaning in place of exit 0.
  • When a call without an error wrote to stderr, the row adds the stderr line count and the first non-empty stderr line, dim and cut at the row end. The result block does not change.
  • When the engine saved a large output to a file, stdout holds only a preview. The row then shows output saved to a file in place of the line count, and /simple show N prints the path of that file.
  • The result block names each changed file as Updated, Created or Deleted, with (+added -removed). Files that the engine counts but does not list show as and N more changed files. When the engine reports that it could not track the changes, the block says File changes were not tracked for this call, and /simple show N prints File diff: not tracked by the engine.
  • A missing Updated line proves that the call changed no file only for a call without an error, and only when Bash edit tracking was on for that call. With tracking off, the engine sends no diff, also for a call that wrote a file. The block is then empty, and /simple show N prints File diff: not reported by the engine.
  • After exit N, the engine sends no diff, but the command can still have changed a file. /simple show N then prints File diff: not reported by the engine.
  • /simple show N prints File diff: none. for a Bash call only when the engine tracked the call and listed no changed file.
  • The bashEditDiffEnabled setting turns Bash edit tracking on or off. The CLAUDE_CODE_BASH_EDIT_DIFF environment variable wins over the setting. Without either, the engine decides, and the mod cannot read that decision.
  • When an error line or a stderr line follows the description, the description keeps up to 40 cells. The terminal cuts the error line or the stderr line first.
  • A path inside the session root shows relative to the root, and the root itself shows as .. Another path shows in full.
  • The row shows the time only from 1 second. The engine gives no run time for a Bash call, so the mod clock measures the time around the call. It includes the time that a permission question waited for an answer.
  • A Read of a whole file shows its line count, such as 18 lines. A Read of a part shows the range, such as lines 160-239 of 674.
  • A Grep row counts what its output mode returned: 12 lines for content, 3 files for files_with_matches and 7 matches for count. When the engine cut the output at head_limit, the row shows both counts, such as 10 of 12 lines.
  • A Glob row shows the total of matched files. When the engine knows the total only as a lower bound, the row adds a +, such as 100+ files.
  • Claude Code 2.1.295 offered no Grep or Glob tool in a live check, also not to an Explore agent. The mod reads their outputs in the shape of the 2.1.295 output schema. The transcripts of 2.1.294 show the same shape.
  • Write of a new file counts the lines of its content, blank lines at the end included, as its diff does. When the engine gives no diff for an update (for example, the old content was too large to diff), the row shows the path only, with no totals.

The generic row

Every tool that is not Bash, Edit, Write, Read, Grep or Glob and not on the list below draws the generic row. The mod keeps no list of supported tools, so a tool that a new Claude Code release adds, and any MCP tool, gets the generic row.

● WebSearch  ink flexbox text truncate end  running  3.0s
● WebSearch  ink flexbox text truncate end  done  14 lines  5.3s
● WebFetch  https://example.com  done  1 line  1.6s
● claude-in-chrome · list_connected_browsers  done  1 line
● Skill  no-comments  error
  ⎿  Initializing…
  ⎿  Error: Unknown skill: no-comments
  • The tool name of an MCP tool, mcp__server__tool, shows as server · tool. A name with no tool part shows in full.
  • The input summary is the first text that is not empty in these fields, in this order: title, subject, description, summary, url, query, pattern, skill, command, file_path, filePath, notebook_path, path, uri, prompt, message, name. Without one, it is the first text value of the input that is not empty. An input with no text value shows no summary.
  • In the summary, each run of spaces and line breaks becomes one space. Colour codes are dropped, and other hidden characters show as escapes such as ​. The terminal cuts the summary at the row end first. The tool name and the state stay.
  • The marker is green after done, red after error and dim before the run and while the call runs. done is green and error is red.
  • The line count is the count of lines in the result as the model read it. The time shows from 1 second. The mod clock measures it around the call, as for Bash.
  • After error, the engine draws the error text under the row. /simple show N prints the call in full.
  • A call has no line count and no time when a subagent made it, when it is from an ended session, or when a plugin above simple-view answered it.

These tools keep the row of Claude Code, because you must read or answer what the row shows:

ToolWhy the engine row stays
AskUserQuestionIt asks you questions, and the row shows your answers
EnterPlanMode, ExitPlanModeIt asks you to approve plan mode or the plan
ProposeGoalIt asks you to approve a goal
TodoWriteThe row shows the plan as a list
SendUserMessage, SendUserFile, PushNotificationIt sends a message or a file to you
ReportFindingsIt reports review findings to you
propose_skills, PublishPluginIt asks you to save a skill or to publish a plugin
SuggestPluginInstall, SuggestSkills, SuggestConnectorsIt offers you a choice
OfferChromeSetup, ShowOnboardingRolePickerIt asks you to set up a browser or to pick a role
request_computerIts schema has no description, so the mod stays safe

ToolSearch also keeps the row of Claude Code. Claude Code 2.1.300 draws no row for it, and simple-view does not add one.

Rows of other mods

simple-view asks the plugins beneath it and the engine first. It draws its row only when the answer is the engine row. When a plugin beneath it draws its own row, that row stays. A plugin above it draws before simple-view is asked. So the rows of handily-board for its task tools and the tracker rows of quiet-items stay, in either order of the plugins.

  • When such a plugin passes a call on to the engine, simple-view draws its row for the call. handily-board passes a running or failed task call on, so that call draws the generic row.
  • In a live check with Claude Code 2.1.300, the engine answered ref 1 for a row that no plugin had changed. So simple-view cannot see a plugin beneath it that only changes the props of the engine row, and it draws its own row in that case.

While the input streams

Claude Code sends the tool name of a call first, and its input when the model has written it. Before the call runs, a Bash, Read, Grep or Glob row shows what is readable, and a dim … in place of the result:

● Bash  …
● Count to five slowly  sleep  …
● Read  …
  • A Bash row shows the tool name until the description or the command arrives. Then it shows the same label and program as the finished row.
  • A Read row shows the path, and a Grep or Glob row shows the pattern and the folder, as soon as they arrive. A running Read, Grep or Glob call shows the same row.
  • A call is before its run while it does not run, has no output, and has no error and no abort. In that state a missing field has not arrived yet, so the row leaves it out. A field of the wrong type is not an input that streams, so the engine draws the row. This rule holds for a complete input too.
  • In a live check with Claude Code 2.1.296, the input of a call stayed {} until the model had written all of it. The row showed ● Bash … first, then the description and the program with … until the call started.

Open and copy the output

A finished Bash row with output ends with two buttons. They stand at the right edge of the row, dim until the pointer is on them.

● Run the unit tests  npm  exit 0  140 lines  3.0s                          [ more ] [ copy ]

more opens the output under the row, at most 20 lines, between two dim divider lines that show where the opened output starts and ends. Then all 140 lines opens every line, and less on the row folds the output again and removes both lines:

● Run the unit tests  npm  exit 0  140 lines  3.0s                          [ less ] [ copy ]
  ──────────────────────────────────────────────────────────────────────────────────────────
  line 1
  …
  line 20
  …
  [ all 140 lines ]
  ──────────────────────────────────────────────────────────────────────────────────────────
  • copy copies the full output of the call: stdout, then stderr, exactly as the engine gave them. Trailing spaces and blank lines stay. After exit N it copies the error output under the Error: Exit code N line. A toast says how many lines it copied, or why the copy failed.
  • When the engine saved a large output to a file, the row shows only the preview that the engine kept. copy reads the saved file and copies all of it.
  • The opened lines are dim and never wrap: a long line is cut at the row end. copy keeps the whole line. Colour codes are dropped, a line that a carriage return overwrote shows its last part, a tab becomes spaces up to the next 8-cell stop, and other hidden characters show as escapes such as \u200b. A wide character or an emoji takes 2 cells, and a combining mark takes none.
  • all N lines draws at most 60000 characters. Then a dim line says how many lines it did not draw, and copy still takes all of them.
  • A running call has more only. It opens the full command under the row, one dim line for each command line. When the call ends, an opened row shows the output in place of the command.
  • Each row opens and folds alone. A call with no output and an Edit or Write row have no buttons. An output of only spaces, tabs and blank lines counts as no output, so its row shows 0 lines and has no buttons.

When the engine row stays

simple-view draws the engine row unchanged in each of these cases:

  • The mode is off. /simple turned it off for this session, or the mode setting is off.
  • quiet-items stored a row for the call, and the quiet-items mode is on. The tracker row of quiet-items wins. While /quiet-items has turned its mode off, simple-view draws its own row for the call.
  • Another mod drew its own row for the call. Rows of other mods says how.
  • The call was interrupted, refused or ran in the background.
  • A Bash call errored without the Error: Exit code N text, for example a timeout or a refusal at the permission question.
  • The output or the input is not a shape that the mod reads, or a staged Edit or Write that did not change the file. A Read of an image, a PDF, a notebook or an unchanged file is not a shape that the mod reads.
  • A Read, Grep or Glob call that errored.
  • An input field of the wrong type, also while the input streams, such as a command that is not text.
  • Drawing the row failed. The mod writes the reason to the debug log.
  • A tool that keeps the row of Claude Code. The generic row lists them.

In the normal view the engine folds runs of read-only calls into one group line, such as Read 2 files, listed 1 directory, ran 1 shell command or Called claude-in-chrome. While its mode is on, simple-view unfolds a group when each call of the group draws as one row: a Bash call in the foreground, a Read, a Grep, a Glob or a call with the generic row. A ToolSearch call, which the engine does not draw, does not keep a group folded. The calls of the group then draw as their rows in its place:

● Read  README.md  123 lines
● Read  package.json  30 lines
● List the mods  ls  exit 0  9 lines                                        [ more ] [ copy ]

The group also unfolds while the input of its calls streams, as soon as the tool names are known. So the engine line Running 1 shell command… does not show first.

A group that holds another tool keeps the line of the engine, except in the two cases below. The ctrl+o transcript unfolds every group, and each call there shows its simple-view row.

When a folded group holds a call that failed, simple-view unfolds the group while its mode is on. Each call of the group then draws as its own row, so the failure is visible. When quiet-items also unfolds the group, the result is the same.

While the live group holds a Bash call that runs in the foreground, simple-view also unfolds that group. The engine would draw the full command of the running call there, over many lines. The running call draws as one row instead, and its more button opens the command. When no call of the group runs, the group folds again to the line of the engine, unless a call of the group failed.

Settings and the commands

SettingDefaultUse
modeonThe mode when a session starts: on or off
CommandEffect
/simple onTurns the view on for this session, and replies with the new mode
/simple offTurns the view off for this session, and replies with the new mode
/simpleTurns the view off or on for this session, and replies with the new mode
/simple show NPrints the input, the output and the file diff of the N-th last tool call. 1 is the last
  • The mod keeps the mode in the mode key of its $.state, so a change does not reach other sessions. When the session starts and the key is unset, the mod writes the mode setting to it. So a session starts with the mode of the setting, and /simple toggles from there. /handily shows the setting beside the mode when the two differ.
  • /simple show N refuses a number outside the kept calls, and gives the valid range.
  • Any other argument changes nothing, and the reply names the valid forms.
  • ctrl+o cannot expand a single row. The engine reuses the drawn row and does not call the mod again. Use more on the row, or /simple show N.

Memory limit

/simple show keeps the last 50 tool calls of the main session in $.state. It cuts each part of a call (the input, the output and the file diff) at 8000 characters, and says how many characters it cut. Calls of subagents are not kept.

When a session ends for any reason (/exit, /clear, a resume or a finished run), the mod resets the count of kept calls. The calls and the times of the ended session are no longer reachable: /simple show refuses them, and an old row draws without its time. $.state has no delete, so the mod writes each new call over a slot of the ended session. The 50 slots stay the upper limit. One small time record (three numbers) stays for each Bash call and each call with the generic row of the process. A call with the generic row also keeps one line count.

A press on more, all N lines or less keeps one small value for that call in $.state, so the row stays open or folded when it draws again.

Known limits

  • /simple does not change the mode of quiet-items. Claude Code refuses a write to the state of another plugin: handily-quiet-items owns that value and only its owner writes it. Use /quiet-items to switch the tracker rows.
  • The running time is updated once per second while the call runs.
  • /simple show N does not keep a call that a plugin above simple-view answers itself, such as a handily-board task tool. In a live check with Claude Code 2.1.300, handily-board stood above simple-view, so its task calls were not kept.
  • /simple show N prints File diff: not reported by the engine. for a call of a tool other than Bash, Edit, Write, Read, Grep and Glob. The mod reads a file diff only from those 6 tools, and another tool can still change a file.
Source 10 files
hooks/register.ts 585 lines
1import type {
2  EngineInterface,
3  Register,
4  RenderElement,
5  RenderPropsOf,
6  RenderSurface,
7  Timer,
8  ToolGroupCall,
9} from 'claude-code'
10import type { SimpleViewFold, SimpleViewMode } from '../types'
11import { commandLabel, programOf } from './command'
12import { KEPT_CALLS, callRecord, showText, slotOf, type CallFacts } from './detail'
13import {
14  callOutput,
15  copyRefusalText,
16  foldButtons,
17  outputBlock,
18  plural,
19  type CallOutput,
20  type FoldActions,
21} from './fold'
22import { drawsGenericRow, inputSummary, isHiddenByEngine, toolLabel } from './generic'
23import {
24  FILE_TOOLS,
25  bashChanges,
26  bashEnd,
27  fileEdit,
28  isRecord,
29  lineCount,
30  shownPath,
31} from './output'
32import { READING_TOOLS, readingCount, readingTarget, streamingTarget } from './reading'
33import {
34  bashRow,
35  changesBlock,
36  fileRow,
37  genericRow,
38  readingRow,
39  type BashState,
40  type GenericState,
41  type RowLook,
42} from './row'
43
44const COMMAND = 'simple'
45const TICK_MS = 1000
46const DEFAULT_COLUMNS = 80
47const COUNT_TRIES = 5
48const MODE = { plugin: 'handily-simple-view', key: 'mode' } as const
49const COUNT = { plugin: 'handily-simple-view', key: 'count' } as const
50const GENERATION = { plugin: 'handily-simple-view', key: 'generation' } as const
51const QUIET_ITEMS_MODE = { plugin: 'handily-quiet-items', key: 'mode' } as const
52const RESERVED_KEYS: ReadonlySet<string> = new Set(['tool', 'tool_use_id', 'agentId', 'consent'])
53
54const ON_TEXT =
55  'on for this session. Tool calls draw as one row, except a call that asks you or shows you a plan. /simple show N prints call N in full, where 1 is the last call.'
56const OFF_TEXT = 'off for this session. Tool calls draw as Claude Code draws them.'
57const USAGE_TEXT =
58  '/simple takes on, off, show N or no argument. /simple on and /simple off set this session, /simple toggles it, and /simple show N prints the N-th last tool call in full. Set the default with the plugin\'s "mode" setting.'
59const NO_CALL_TEXT = '/simple show has no tool call to print yet in this session.'
60
61type Answer = Awaited<ReturnType<EngineInterface['tool']['call']>>
62type StreamingBashInput = { command?: string; description?: string; run_in_background?: boolean }
63type BashInput = StreamingBashInput & { command: string }
64type CallProgress = Pick<ToolGroupCall, 'isRunning' | 'isErrored' | 'isInterrupted' | 'output'>
65
66function isStreamingBashInput(input: unknown): input is StreamingBashInput {
67  return (
68    isRecord(input) &&
69    (input.command === undefined || typeof input.command === 'string') &&
70    (input.description === undefined || typeof input.description === 'string')
71  )
72}
73
74function isBashInput(input: unknown): input is BashInput {
75  return isStreamingBashInput(input) && typeof input.command === 'string'
76}
77
78function isPending(call: CallProgress): boolean {
79  return !call.isRunning && !call.isErrored && !call.isInterrupted && call.output === undefined
80}
81
82function bashLabel(input: StreamingBashInput): string {
83  const description = input.description?.trim() ?? ''
84  return description === '' ? commandLabel(input.command ?? '') : description
85}
86
87function rangeText(kept: number): string {
88  return `/simple show takes a call number from 1 to ${String(kept)}, where 1 is the last tool call.`
89}
90
91function logFailure($: EngineInterface, what: string, error: unknown): void {
92  $.ui.log(`simple-view: ${what}: ${String(error)}`)
93}
94
95function isMode(word: string): word is SimpleViewMode {
96  return word === 'on' || word === 'off'
97}
98
99async function setMode(
100  $: EngineInterface,
101  asked: SimpleViewMode | null,
102  defaultMode: SimpleViewMode,
103): Promise<string> {
104  const { value: current = defaultMode } = await $.state.get(MODE)
105  const mode: SimpleViewMode = asked ?? (current === 'on' ? 'off' : 'on')
106  await $.state.set(MODE, mode)
107  return mode === 'on' ? ON_TEXT : OFF_TEXT
108}
109
110async function generationOf($: EngineInterface): Promise<number> {
111  const { value = 0 } = await $.state.get(GENERATION)
112  return value
113}
114
115function timingKey(generation: number, toolUseId: string): string {
116  return `${String(generation)}:${toolUseId}`
117}
118
119async function forgetSession($: EngineInterface): Promise<void> {
120  try {
121    await $.state.set(GENERATION, (await generationOf($)) + 1)
122    await $.state.set(COUNT, 0)
123  } catch (error) {
124    logFailure($, 'the calls of the ended session stay reachable', error)
125  }
126}
127
128async function show($: EngineInterface, raw: string | undefined): Promise<string> {
129  const generation = await generationOf($)
130  const { value: count = 0 } = await $.state.get(COUNT)
131  const kept = Math.min(count, KEPT_CALLS)
132  if (kept === 0) return NO_CALL_TEXT
133  if (raw === undefined || !/^\d+$/.test(raw)) return rangeText(kept)
134  const back = Number(raw)
135  if (back < 1 || back > kept) return `No call ${raw} is kept. ${rangeText(kept)}`
136  const seq = count - back
137  const { value: call } = await $.state.get({
138    plugin: 'handily-simple-view',
139    key: 'calls',
140    id: slotOf(seq),
141  })
142  if (call?.generation !== generation || call.seq !== seq) {
143    return `No call ${raw} is kept. ${rangeText(kept)}`
144  }
145  return showText(call, back, kept)
146}
147
148async function tick($: EngineInterface, id: string): Promise<void> {
149  try {
150    const ref = { plugin: 'handily-simple-view', key: 'timing', id } as const
151    const { value, version } = await $.state.get(ref)
152    if (value?.isRunning !== true) return
153    const now = await $.clock.now()
154    await $.state.set(ref, { ...value, elapsedMs: now - value.startedAt }, { ifVersion: version })
155  } catch (error) {
156    logFailure($, `no running time for ${id}`, error)
157  }
158}
159
160async function startTicker($: EngineInterface, id: string, startedAt: number): Promise<Timer> {
161  await $.state.set(
162    { plugin: 'handily-simple-view', key: 'timing', id },
163    { startedAt, elapsedMs: 0, isRunning: true },
164  )
165  return $.clock.every(TICK_MS, () => {
166    void tick($, id)
167  })
168}
169
170async function settleTiming(
171  $: EngineInterface,
172  id: string,
173  startedAt: number,
174  elapsedMs: number,
175): Promise<void> {
176  try {
177    await $.state.set(
178      { plugin: 'handily-simple-view', key: 'timing', id },
179      { startedAt, elapsedMs, isRunning: false },
180    )
181  } catch (error) {
182    logFailure($, `no time for ${id}`, error)
183  }
184}
185
186async function remember(
187  $: EngineInterface,
188  facts: Omit<CallFacts, 'seq' | 'generation'>,
189): Promise<void> {
190  try {
191    for (let attempt = 0; attempt < COUNT_TRIES; attempt += 1) {
192      const generation = await generationOf($)
193      const { value: count = 0, version } = await $.state.get(COUNT)
194      const { isSet } = await $.state.set(COUNT, count + 1, { ifVersion: version })
195      if (!isSet) continue
196      await $.state.set(
197        { plugin: 'handily-simple-view', key: 'calls', id: slotOf(count) },
198        callRecord({ ...facts, generation, seq: count }),
199      )
200      return
201    }
202    $.ui.log(`simple-view: /simple show misses ${facts.tool_use_id}; other calls kept the count`)
203  } catch (error) {
204    logFailure($, `/simple show misses ${facts.tool_use_id}`, error)
205  }
206}
207
208type Ended = {
209  facts: Omit<CallFacts, 'seq' | 'generation' | 'elapsedMs'>
210  startedAt: number
211  timing: string | null
212}
213
214async function recordCall($: EngineInterface, { facts, startedAt, timing }: Ended): Promise<void> {
215  let elapsedMs: number
216  try {
217    elapsedMs = (await $.clock.now()) - startedAt
218  } catch (error) {
219    logFailure($, `no time for ${facts.tool_use_id}`, error)
220    return
221  }
222  if (timing !== null) await settleTiming($, timing, startedAt, elapsedMs)
223  if (timing !== null && drawsGenericRow(facts.tool) && facts.answer.text !== undefined) {
224    await keepResultLines($, timing, lineCount(facts.answer.text))
225  }
226  await remember($, { ...facts, elapsedMs })
227}
228
229async function keepResultLines($: EngineInterface, id: string, lines: number): Promise<void> {
230  try {
231    await $.state.set({ plugin: 'handily-simple-view', key: 'resultLines', id }, lines)
232  } catch (error) {
233    logFailure($, `no result size for ${id}`, error)
234  }
235}
236
237function inputOf(e: object): Record<string, unknown> {
238  return Object.fromEntries(Object.entries(e).filter(([key]) => !RESERVED_KEYS.has(key)))
239}
240
241async function timingOf($: EngineInterface, toolUseId: string) {
242  const id = timingKey(await generationOf($), toolUseId)
243  const { value } = await $.state.get({ plugin: 'handily-simple-view', key: 'timing', id })
244  return value
245}
246
247async function copyOutput(
248  $: EngineInterface,
249  output: CallOutput,
250  surface: RenderSurface,
251): Promise<void> {
252  try {
253    const text = output.savedTo === null ? output.text : await $.fs.read(output.savedTo)
254    const result = await $.ui.copy({ text, surface })
255    $.ui.toast(
256      result.isCopied
257        ? `Copied ${plural(lineCount(text), 'line')} of output.`
258        : copyRefusalText(result.reason),
259    )
260  } catch (error) {
261    logFailure($, 'the output was not copied', error)
262    $.ui.toast('Not copied. The debug log says why.')
263  }
264}
265
266function foldActions($: EngineInterface, id: string, output: CallOutput | null): FoldActions {
267  return {
268    fold: (next) => {
269      void $.state
270        .set({ plugin: 'handily-simple-view', key: 'folds', id }, next)
271        .catch((error: unknown) => {
272          logFailure($, `the output of ${id} did not ${next === 'folded' ? 'fold' : 'open'}`, error)
273        })
274    },
275    copy:
276      output === null
277        ? undefined
278        : (surface) => {
279            void copyOutput($, output, surface)
280          },
281  }
282}
283
284function commandOutput(command: string): CallOutput {
285  return { text: command, lines: command.split(/\r?\n/), savedTo: null }
286}
287
288async function foldOf($: EngineInterface, id: string): Promise<SimpleViewFold> {
289  const { value = 'folded' } = await $.state.get({
290    plugin: 'handily-simple-view',
291    key: 'folds',
292    id,
293  })
294  return value
295}
296
297function pendingBashRow(look: RowLook, tool: string, input: unknown): RenderElement | null {
298  if (!isStreamingBashInput(input) || input.run_in_background === true) return null
299  const label = bashLabel(input)
300  return bashRow(look, {
301    label: label === '' ? tool : label,
302    program: programOf(input.command ?? ''),
303    state: { kind: 'pending' },
304    elapsedMs: null,
305  })
306}
307
308async function bashUse(
309  $: EngineInterface,
310  props: RenderPropsOf['ToolUse'],
311  look: RowLook,
312): Promise<RenderElement | null> {
313  if (isPending(props)) return pendingBashRow(look, props.tool, props.input)
314  if (!isBashInput(props.input) || props.input.run_in_background === true) return null
315  const state: BashState | null = props.isRunning
316    ? { kind: 'running' }
317    : bashEnd(props.output, props.isErrored)
318  if (state === null) return null
319  const timing = await timingOf($, props.tool_use_id)
320  const view = {
321    label: bashLabel(props.input),
322    program: programOf(props.input.command),
323    state,
324    elapsedMs: timing?.elapsedMs ?? null,
325  }
326  const isRunning = state.kind === 'running'
327  const output = isRunning ? null : callOutput(props.output, props.isErrored)
328  if (!isRunning && output === null) return bashRow(look, view)
329  const fold = await foldOf($, props.tool_use_id)
330  const actions = foldActions($, props.tool_use_id, output)
331  const row = bashRow(look, view, foldButtons(look, fold, actions))
332  if (fold === 'folded') return row
333  const opened =
334    output === null
335      ? outputBlock(look, commandOutput(props.input.command), 'all', actions)
336      : outputBlock(look, output, fold, actions)
337  const { Box } = look.elements
338  return Box({ flexDirection: 'column', children: [row, opened] })
339}
340
341async function fileUse(
342  $: EngineInterface,
343  props: RenderPropsOf['ToolUse'],
344  look: RowLook,
345): Promise<RenderElement | null> {
346  if (props.isRunning || props.isErrored) return null
347  const edit = fileEdit(props.tool, props.output)
348  if (edit === null) return null
349  return fileRow(look, props.tool, shownPath(edit.path, await $.session.root()), edit.totals)
350}
351
352async function readingUse(
353  $: EngineInterface,
354  props: RenderPropsOf['ToolUse'],
355  look: RowLook,
356): Promise<RenderElement | null> {
357  if (props.isErrored) return null
358  if (props.isRunning || isPending(props)) {
359    const target = streamingTarget(props.tool, props.input, await $.session.root())
360    return target === null ? null : readingRow(look, props.tool, target, null)
361  }
362  const count = readingCount(props.tool, props.output)
363  if (count === null) return null
364  const target = readingTarget(props.tool, props.input, props.output, await $.session.root())
365  if (target === null) return null
366  return readingRow(look, props.tool, target, count)
367}
368
369function genericState(props: RenderPropsOf['ToolUse']): GenericState {
370  if (isPending(props)) return 'pending'
371  if (props.isRunning) return 'running'
372  return props.isErrored ? 'error' : 'done'
373}
374
375async function genericUse(
376  $: EngineInterface,
377  props: RenderPropsOf['ToolUse'],
378  look: RowLook,
379): Promise<RenderElement> {
380  const view = {
381    label: toolLabel(props.tool),
382    summary: inputSummary(props.input),
383    state: genericState(props),
384    lines: null,
385    elapsedMs: null,
386  }
387  if (view.state === 'pending') return genericRow(look, view)
388  const id = timingKey(await generationOf($), props.tool_use_id)
389  const { value: timing } = await $.state.get({ plugin: 'handily-simple-view', key: 'timing', id })
390  const { value: lines = null } = await $.state.get({
391    plugin: 'handily-simple-view',
392    key: 'resultLines',
393    id,
394  })
395  return genericRow(look, { ...view, lines, elapsedMs: timing?.elapsedMs ?? null })
396}
397
398async function useDrawing(
399  $: EngineInterface,
400  props: RenderPropsOf['ToolUse'],
401  look: RowLook,
402): Promise<RenderElement | null> {
403  if (props.isInterrupted) return null
404  if (props.tool === 'Bash') return bashUse($, props, look)
405  if (FILE_TOOLS.has(props.tool)) return fileUse($, props, look)
406  if (READING_TOOLS.has(props.tool)) return readingUse($, props, look)
407  if (drawsGenericRow(props.tool)) return genericUse($, props, look)
408  return null
409}
410
411async function bashResult(
412  $: EngineInterface,
413  props: RenderPropsOf['ToolResult'],
414  look: RowLook,
415): Promise<RenderElement | null> {
416  const end = bashEnd(props.output, props.isErrored)
417  if (end === null) return null
418  if (end.kind === 'exit') return look.elements.Box({})
419  const changes = bashChanges(props.output)
420  if (changes === null) return null
421  if (changes.kind === 'unreported') return look.elements.Box({})
422  if (changes.kind === 'untracked') return changesBlock(look, null)
423  const root = changes.files.length === 0 ? '' : await $.session.root()
424  const files = changes.files.map((file) => ({ ...file, path: shownPath(file.path, root) }))
425  return changesBlock(look, { files, moreFiles: changes.moreFiles })
426}
427
428async function resultDrawing(
429  $: EngineInterface,
430  props: RenderPropsOf['ToolResult'],
431  look: RowLook,
432): Promise<RenderElement | null> {
433  if (props.tool === 'Bash') return bashResult($, props, look)
434  if (props.isErrored) return null
435  if (READING_TOOLS.has(props.tool)) {
436    return readingCount(props.tool, props.output) === null ? null : look.elements.Box({})
437  }
438  if (drawsGenericRow(props.tool)) return look.elements.Box({})
439  if (!FILE_TOOLS.has(props.tool)) return null
440  return fileEdit(props.tool, props.output) === null ? null : look.elements.Box({})
441}
442
443async function isSimple(
444  $: EngineInterface,
445  id: string,
446  defaultMode: SimpleViewMode,
447): Promise<boolean> {
448  const { value: mode = defaultMode } = await $.state.get(MODE)
449  if (mode === 'off') return false
450  const { value: rows } = await $.state.get({ plugin: 'handily-quiet-items', key: 'rows', id })
451  if (rows === undefined || rows.length === 0) return true
452  const { value: quietMode = 'on' } = await $.state.get(QUIET_ITEMS_MODE)
453  return quietMode === 'off'
454}
455
456function isEngineOwnRow(element: RenderElement): boolean {
457  return element.type === 'engine'
458}
459
460function isFailed(call: ToolGroupCall): boolean {
461  return call.isErrored && !call.isRunning
462}
463
464function isRunningForeground(call: ToolGroupCall): boolean {
465  return (
466    call.tool === 'Bash' &&
467    call.isRunning &&
468    !(isBashInput(call.input) && call.input.run_in_background === true)
469  )
470}
471
472function isDrawnAsRow(call: ToolGroupCall): boolean {
473  if (drawsGenericRow(call.tool) || isHiddenByEngine(call.tool)) return true
474  if (call.tool !== 'Bash') return READING_TOOLS.has(call.tool)
475  const { input } = call
476  if (!isStreamingBashInput(input) || input.run_in_background === true) return false
477  return isPending(call) || typeof input.command === 'string'
478}
479
480function shouldUnfold(props: RenderPropsOf['ToolGroup']): boolean {
481  if (props.isExpanded) return false
482  return (
483    (props.calls.length > 0 && props.calls.every(isDrawnAsRow)) ||
484    props.calls.some(isFailed) ||
485    (props.isActive && props.calls.some(isRunningForeground))
486  )
487}
488
489export const register: Register = (on, options) => {
490  const defaultMode: SimpleViewMode = options.mode === 'off' ? 'off' : 'on'
491  on('session.start', async ($, e, next) => {
492    await $.command.register({
493      name: COMMAND,
494      description:
495        'handily · Set or toggle the one-row view of tool calls, or print a call in full',
496      argumentHint: '[on|off|show N]',
497    })
498    await $.state.set({ plugin: 'handily-simple-view', key: 'ready' }, { root: $.plugin.root })
499    const { value: mode, version } = await $.state.get(MODE)
500    if (mode === undefined) await $.state.set(MODE, defaultMode, { ifVersion: version })
501    return next(e)
502  })
503
504  on('command.run', { command: COMMAND }, async ($, e) => {
505    const [verb, number, ...rest] = e.args
506      .trim()
507      .split(/\s+/)
508      .filter((word) => word !== '')
509    if (verb === undefined) return { text: await setMode($, null, defaultMode) }
510    if (isMode(verb) && number === undefined) return { text: await setMode($, verb, defaultMode) }
511    if (verb === 'show' && rest.length === 0) return { text: await show($, number) }
512    return { text: USAGE_TEXT }
513  })
514
515  on('session.end', async ($, e, next) => {
516    await forgetSession($)
517    return next(e)
518  })
519
520  on('tool.call', async ($, e, next) => {
521    const id = e.tool_use_id
522    if (e.agentId !== undefined) return next(e)
523    const input = inputOf(e)
524    const isTimed =
525      (e.tool === 'Bash' || drawsGenericRow(e.tool)) && input.run_in_background !== true
526    let startedAt: number
527    let timing: string | null
528    let ticker: Timer | null
529    try {
530      startedAt = await $.clock.now()
531      timing = isTimed ? timingKey(await generationOf($), id) : null
532      ticker = timing === null ? null : await startTicker($, timing, startedAt)
533    } catch (error) {
534      logFailure($, `no time for ${id}`, error)
535      return next(e)
536    }
537    let answer: Answer
538    try {
539      answer = await next(e)
540    } finally {
541      ticker?.cancel()
542    }
543    await recordCall($, {
544      facts: { tool_use_id: id, tool: e.tool, input, answer },
545      startedAt,
546      timing,
547    })
548    return answer
549  })
550
551  on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
552    if (!shouldUnfold(e.props)) return next(e)
553    let isOn = false
554    try {
555      const { value: mode = defaultMode } = await $.state.get(MODE)
556      isOn = mode === 'on'
557    } catch (error) {
558      logFailure($, 'the engine folds the group', error)
559    }
560    return next(isOn ? { ...e, props: { ...e.props, isExpanded: true } } : e)
561  })
562
563  on('ui.render', { component: ['ToolUse', 'ToolResult'] }, async ($, e, next) => {
564    const beneath = await next(e)
565    if (!isEngineOwnRow(beneath)) return beneath
566    let drawn: RenderElement | null = null
567    try {
568      if (await isSimple($, e.props.tool_use_id, defaultMode)) {
569        const look = {
570          elements: $.ui.resolve(e),
571          hasToolMarker: e.surface === 'terminal',
572          columns: e.viewport?.columns ?? DEFAULT_COLUMNS,
573        }
574        drawn =
575          e.component === 'ToolUse'
576            ? await useDrawing($, e.props, look)
577            : await resultDrawing($, e.props, look)
578      }
579    } catch (error) {
580      logFailure($, `the engine draws ${e.props.tool_use_id}`, error)
581    }
582    return drawn ?? beneath
583  })
584}
585
hooks/command.ts 100 lines
1const LABEL_LENGTH = 60
2const DIRECTORY_CHANGES = new Set(['cd', 'pushd', 'popd'])
3const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/
4const TWO_CHARACTER_SEPARATORS = new Set(['&&', '||'])
5const ONE_CHARACTER_SEPARATORS = new Set([';', '|', '\n'])
6
7type Quote = '"' | "'" | '`'
8type Scan = { quote: Quote | null; depth: number; isEscaped: boolean }
9
10const QUOTES: ReadonlySet<string> = new Set(['"', "'", '`'])
11
12function isQuote(character: string): character is Quote {
13  return QUOTES.has(character)
14}
15
16function isQuiet(scan: Scan): boolean {
17  return scan.quote === null && scan.depth === 0 && !scan.isEscaped
18}
19
20function step(scan: Scan, character: string, following: string): void {
21  if (scan.isEscaped) {
22    scan.isEscaped = false
23  } else if (character === '\\' && scan.quote !== "'") {
24    scan.isEscaped = true
25  } else if (scan.quote !== null) {
26    if (character === scan.quote) scan.quote = null
27  } else if (isQuote(character)) {
28    scan.quote = character
29  } else if (character === '$' && following === '(') {
30    scan.depth += 1
31  } else if (character === ')' && scan.depth > 0) {
32    scan.depth -= 1
33  }
34}
35
36export function segments(command: string): string[] {
37  const found: string[] = []
38  const scan: Scan = { quote: null, depth: 0, isEscaped: false }
39  let start = 0
40  let index = 0
41  while (index < command.length) {
42    const character = command.charAt(index)
43    const pair = command.slice(index, index + 2)
44    if (isQuiet(scan) && TWO_CHARACTER_SEPARATORS.has(pair)) {
45      found.push(command.slice(start, index))
46      index += 2
47      start = index
48      continue
49    }
50    if (isQuiet(scan) && ONE_CHARACTER_SEPARATORS.has(character)) {
51      found.push(command.slice(start, index))
52      index += 1
53      start = index
54      continue
55    }
56    step(scan, character, command.charAt(index + 1))
57    index += 1
58  }
59  found.push(command.slice(start))
60  return found.map((segment) => segment.replace(/\s+/g, ' ').trim()).filter((s) => s !== '')
61}
62
63function words(segment: string): string[] {
64  return segment.split(' ').filter((word) => !ASSIGNMENT.test(word))
65}
66
67function unquoted(word: string): string {
68  return word.replace(/^(['"])(.*)\1$/, '$2')
69}
70
71function baseName(word: string): string {
72  return (
73    word
74      .split('/')
75      .filter((part) => part !== '')
76      .at(-1) ?? word
77  )
78}
79
80export function programOf(command: string): string {
81  const firstWords = segments(command)
82    .map((segment) => words(segment)[0])
83    .filter((word): word is string => word !== undefined)
84    .map((word) => baseName(unquoted(word)))
85  return firstWords.find((word) => !DIRECTORY_CHANGES.has(word)) ?? firstWords[0] ?? ''
86}
87
88export function cutLabel(text: string, length = LABEL_LENGTH): string {
89  const graphemes = Array.from(new Intl.Segmenter().segment(text), (part) => part.segment)
90  if (graphemes.length <= length) return text
91  return `${graphemes.slice(0, length).join('').trimEnd()}…`
92}
93
94export function commandLabel(command: string): string {
95  const [first = '', ...rest] = segments(command)
96  const label = cutLabel(first)
97  if (rest.length === 0 || label.endsWith('…')) return label
98  return `${label} …`
99}
100
hooks/detail.ts 137 lines
1import type { SimpleViewCall, SimpleViewDiffGap } from '../types'
2import { isRichTool } from './generic'
3import { contentLines, diffGap, hunksOf, isRecord } from './output'
4
5export const KEPT_CALLS = 50
6export const PART_LIMIT = 8000
7
8type Answer = { result?: unknown; text?: string; deny?: string; isError?: true }
9
10export function capped(text: string, limit = PART_LIMIT): string {
11  if (text.length <= limit) return text
12  const left = text.length - limit
13  return `${text.slice(0, limit)}\n[simple-view kept the first ${String(limit)} characters; ${String(left)} more were cut]`
14}
15
16function hunkText(hunks: ReturnType<typeof hunksOf>): string[] {
17  return (hunks ?? []).flatMap((hunk) => [
18    `@@ -${String(hunk.oldStart)},${String(hunk.oldLines)} +${String(hunk.newStart)},${String(hunk.newLines)} @@`,
19    ...hunk.lines,
20  ])
21}
22
23function fileDiff(path: string, hunks: ReturnType<typeof hunksOf>): string[] {
24  const body = hunkText(hunks)
25  return body.length === 0 ? [] : [`--- ${path}`, `+++ ${path}`, ...body]
26}
27
28function createdDiff(path: string, content: string): string[] {
29  const lines = contentLines(content)
30  return [
31    '--- /dev/null',
32    `+++ ${path}`,
33    `@@ -0,0 +1,${String(lines.length)} @@`,
34    ...lines.map((line) => `+${line}`),
35  ]
36}
37
38export function diffText(result: unknown): string {
39  if (!isRecord(result)) return ''
40  if (typeof result.filePath === 'string') {
41    const hunks = hunksOf(result.structuredPatch)
42    if (hunks?.length === 0 && result.type === 'create' && typeof result.content === 'string') {
43      return createdDiff(result.filePath, result.content).join('\n')
44    }
45    return fileDiff(result.filePath, hunks).join('\n')
46  }
47  const diff = result.bashEditDiff
48  if (!isRecord(diff) || !Array.isArray(diff.files)) return ''
49  const lines = diff.files.flatMap((file: unknown) =>
50    isRecord(file) && typeof file.filePath === 'string'
51      ? fileDiff(file.filePath, hunksOf(file.hunks))
52      : [],
53  )
54  if (typeof diff.moreFiles === 'number' && diff.moreFiles > 0) {
55    lines.push(`(${String(diff.moreFiles)} more changed files have no diff here)`)
56  }
57  return lines.join('\n')
58}
59
60function savedNote(result: unknown): string {
61  if (!isRecord(result) || typeof result.persistedOutputPath !== 'string') return ''
62  return `Full output saved to ${result.persistedOutputPath}\n\n`
63}
64
65function outputText(answer: Answer): string {
66  if (answer.deny !== undefined) return `Refused: ${answer.deny}`
67  if (answer.text !== undefined) return `${savedNote(answer.result)}${answer.text}`
68  if (typeof answer.result === 'string') return answer.result
69  return JSON.stringify(answer.result ?? null, null, 2)
70}
71
72export type CallFacts = {
73  generation: number
74  seq: number
75  tool_use_id: string
76  tool: string
77  input: Record<string, unknown>
78  answer: Answer
79  elapsedMs: number
80}
81
82export function callRecord(facts: CallFacts): SimpleViewCall {
83  const gap = isRichTool(facts.tool) ? diffGap(facts.tool, facts.answer.result) : 'unreported'
84  return {
85    generation: facts.generation,
86    seq: facts.seq,
87    tool_use_id: facts.tool_use_id,
88    tool: facts.tool,
89    input: capped(JSON.stringify(facts.input, null, 2)),
90    output: capped(outputText(facts.answer)),
91    diff: gap === null ? capped(diffText(facts.answer.result)) : '',
92    diffGap: gap,
93    isErrored: facts.answer.deny !== undefined || facts.answer.isError === true,
94    elapsedMs: facts.elapsedMs,
95  }
96}
97
98export function slotOf(seq: number): string {
99  return String(seq % KEPT_CALLS)
100}
101
102function fenced(language: string, text: string): string {
103  const longest = Math.max(2, ...Array.from(text.matchAll(/`+/g), (run) => run[0].length))
104  const fence = '`'.repeat(longest + 1)
105  return `${fence}${language}\n${text}\n${fence}`
106}
107
108export function elapsedText(ms: number): string {
109  if (ms < 10_000) return `${(ms / 1000).toFixed(1)}s`
110  const seconds = Math.round(ms / 1000)
111  if (seconds < 60) return `${String(seconds)}s`
112  return `${String(Math.floor(seconds / 60))}m ${String(seconds % 60).padStart(2, '0')}s`
113}
114
115const GAP_HEADINGS: Readonly<Record<SimpleViewDiffGap, string>> = {
116  unreported: 'File diff: not reported by the engine.',
117  untracked: 'File diff: not tracked by the engine.',
118}
119
120function diffHeading(call: SimpleViewCall): string {
121  if (call.diffGap !== null) return GAP_HEADINGS[call.diffGap]
122  return call.diff === '' ? 'File diff: none.' : 'File diff:'
123}
124
125export function showText(call: SimpleViewCall, back: number, kept: number): string {
126  const ending = call.isErrored ? 'errored' : 'answered'
127  return [
128    `Call ${String(back)} of the last ${String(kept)} (1 is the last): ${call.tool}, ${ending}, ${elapsedText(call.elapsedMs)}`,
129    'Input:',
130    fenced('json', call.input),
131    'Output:',
132    fenced('text', call.output),
133    diffHeading(call),
134    ...(call.diff === '' ? [] : [fenced('diff', call.diff)]),
135  ].join('\n\n')
136}
137
hooks/fold.ts 208 lines
1import type { RenderElement, RenderSurface } from 'claude-code'
2import type { SimpleViewFold } from '../types'
3import { EXIT_PREFIX, isRecord } from './output'
4import type { RowLook } from './row'
5import { graphemesOf, isEmoji } from './width'
6
7export const OPEN_LINES = 20
8export const DRAWN_CHARACTERS_AT_MOST = 60_000
9const TAB_STOP = 8
10const RESULT_INDENT = 2
11const RULE = '─'
12// eslint-disable-next-line no-control-regex -- an ANSI colour code starts with the escape character
13const COLOR_CODE = /\u001b\[[0-9;:]*m/g
14const HIDDEN_CHARACTER = /(?!\t)[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu
15const EMOJI_JOINER = /^[\u200D\u{E0020}-\u{E007F}]$/u
16const LEADING_BLANK_LINES = /^(?:[ \t]*\r?\n)+/
17
18const COPY_REFUSALS: Readonly<Record<'no-surface' | 'no-clipboard' | 'refused', string>> = {
19  'no-surface': 'no screen is attached to this session',
20  'no-clipboard': 'the clipboard took nothing. The text may be too long for this terminal',
21  refused: 'another plugin refused the copy',
22}
23
24export function copyRefusalText(reason: keyof typeof COPY_REFUSALS): string {
25  return `Not copied: ${COPY_REFUSALS[reason]}.`
26}
27
28export type CallOutput = { text: string; lines: string[]; savedTo: string | null }
29
30export type FoldActions = {
31  fold: (next: SimpleViewFold) => void
32  copy?: (surface: RenderSurface) => void
33}
34
35function escapedUnits(text: string): string {
36  return Array.from(
37    { length: text.length },
38    (_, index) => `\\u${text.charCodeAt(index).toString(16).padStart(4, '0')}`,
39  ).join('')
40}
41
42function shownGrapheme(grapheme: string): string {
43  const keepsJoiners = isEmoji(grapheme)
44  return grapheme.replace(HIDDEN_CHARACTER, (found) =>
45    keepsJoiners && EMOJI_JOINER.test(found) ? found : escapedUnits(found),
46  )
47}
48
49function shownWithTabs(line: string): string {
50  let shown = ''
51  let column = 0
52  for (const { grapheme, cells } of graphemesOf(line)) {
53    if (grapheme === '\t') {
54      const tabCells = TAB_STOP - (column % TAB_STOP)
55      shown += ' '.repeat(tabCells)
56      column += tabCells
57      continue
58    }
59    const drawn = shownGrapheme(grapheme)
60    shown += drawn
61    column +=
62      drawn === grapheme ? cells : graphemesOf(drawn).reduce((sum, part) => sum + part.cells, 0)
63  }
64  return shown
65}
66
67export function shownLine(line: string): string {
68  const overwritten = line.replace(COLOR_CODE, '').split('\r').at(-1) ?? ''
69  return shownWithTabs(overwritten)
70}
71
72function outputOf(copied: string, drawn: string, savedTo: string | null): CallOutput | null {
73  const kept = drawn.trimEnd()
74  if (kept === '' && savedTo === null) return null
75  return { text: copied, lines: kept === '' ? [] : kept.split(/\r?\n/), savedTo }
76}
77
78function stdoutThenStderr(stdout: string, stderr: string): string {
79  const isBreakNeeded = stdout !== '' && stderr !== '' && !stdout.endsWith('\n')
80  return `${stdout}${isBreakNeeded ? '\n' : ''}${stderr}`
81}
82
83export function callOutput(output: unknown, isErrored: boolean): CallOutput | null {
84  if (isErrored) {
85    if (typeof output !== 'string') return null
86    const found = EXIT_PREFIX.exec(output)
87    if (found === null) return null
88    const errorOutput = output.slice(found[0].length).replace(LEADING_BLANK_LINES, '')
89    return outputOf(errorOutput, errorOutput, null)
90  }
91  if (!isRecord(output) || typeof output.stdout !== 'string') return null
92  const stderr = typeof output.stderr === 'string' ? output.stderr : ''
93  const drawn = [output.stdout.trimEnd(), stderr.trimEnd()].filter((part) => part !== '').join('\n')
94  const savedTo = typeof output.persistedOutputPath === 'string' ? output.persistedOutputPath : null
95  return outputOf(stdoutThenStderr(output.stdout, stderr), drawn, savedTo)
96}
97
98export function plural(count: number, word: string): string {
99  return `${String(count)} ${word}${count === 1 ? '' : 's'}`
100}
101
102export function foldButtons(
103  look: RowLook,
104  fold: SimpleViewFold,
105  actions: FoldActions,
106): RenderElement {
107  const { Box, Button } = look.elements
108  return Box({
109    flexDirection: 'row',
110    gap: 1,
111    children: [
112      Button({
113        key: 'fold',
114        label: fold === 'folded' ? 'more' : 'less',
115        dimColor: true,
116        onPress: () => {
117          actions.fold(fold === 'folded' ? 'open' : 'folded')
118        },
119      }),
120      actions.copy === undefined
121        ? null
122        : Button({
123            key: 'copy',
124            label: 'copy',
125            dimColor: true,
126            onPress: (press) => {
127              actions.copy?.(press.surface)
128            },
129          }),
130    ],
131  })
132}
133
134function drawnLines(lines: readonly string[], fold: 'open' | 'all'): string[] {
135  if (fold === 'open') return lines.slice(0, OPEN_LINES).map(shownLine)
136  const drawn: string[] = []
137  let characters = 0
138  for (const line of lines) {
139    const shown = shownLine(line)
140    characters += shown.length + 1
141    if (characters > DRAWN_CHARACTERS_AT_MOST) break
142    drawn.push(shown)
143  }
144  return drawn
145}
146
147function noteLines(output: CallOutput, fold: 'open' | 'all', drawn: number): string[] {
148  const left = output.lines.length - drawn
149  const notes: string[] = []
150  if (fold === 'open' && left > 0) notes.push('…')
151  if (fold === 'all' && left > 0) {
152    notes.push(`… ${plural(left, 'more line')} not drawn. Copy takes all of them.`)
153  }
154  if (output.savedTo !== null) {
155    notes.push(`The full output is in ${shownLine(output.savedTo)}. Copy takes all of it.`)
156  }
157  return notes
158}
159
160export function outputBlock(
161  look: RowLook,
162  output: CallOutput,
163  fold: 'open' | 'all',
164  actions: FoldActions,
165): RenderElement {
166  const { Box, Text, Button } = look.elements
167  const drawn = drawnLines(output.lines, fold)
168  const textLine = (text: string, index: number, key: string) =>
169    Box({
170      key: `${key}-${String(index)}`,
171      children: Text({ dimColor: true, wrap: 'truncate-end', children: text === '' ? ' ' : text }),
172    })
173  const hasAllButton = fold === 'open' && output.lines.length > OPEN_LINES
174  const indent = look.hasToolMarker ? RESULT_INDENT : 0
175  const divider = (key: string) =>
176    Box({
177      key,
178      children: Text({
179        dimColor: true,
180        wrap: 'truncate-end',
181        children: RULE.repeat(Math.max(look.columns - indent, 1)),
182      }),
183    })
184  return Box({
185    flexDirection: 'column',
186    paddingLeft: indent,
187    children: [
188      divider('opened-top'),
189      ...drawn.map((text, index) => textLine(text, index, 'line')),
190      ...noteLines(output, fold, drawn.length).map((text, index) => textLine(text, index, 'note')),
191      hasAllButton
192        ? Box({
193            key: 'all-lines',
194            children: Button({
195              key: 'all',
196              label: `all ${String(output.lines.length)} lines`,
197              dimColor: true,
198              onPress: () => {
199                actions.fold('all')
200              },
201            }),
202          })
203        : null,
204      divider('opened-bottom'),
205    ],
206  })
207}
208
hooks/generic.ts 93 lines
1import { shownLine } from './fold'
2import { FILE_TOOLS, isRecord } from './output'
3import { READING_TOOLS } from './reading'
4
5const RICH_TOOLS: ReadonlySet<string> = new Set(['Bash', ...FILE_TOOLS, ...READING_TOOLS])
6
7const ENGINE_ROW_TOOLS: ReadonlySet<string> = new Set([
8  'AskUserQuestion',
9  'EnterPlanMode',
10  'ExitPlanMode',
11  'ProposeGoal',
12  'TodoWrite',
13  'SendUserMessage',
14  'SendUserFile',
15  'PushNotification',
16  'ReportFindings',
17  'propose_skills',
18  'PublishPlugin',
19  'SuggestPluginInstall',
20  'SuggestSkills',
21  'SuggestConnectors',
22  'OfferChromeSetup',
23  'ShowOnboardingRolePicker',
24  'request_computer',
25])
26
27const ENGINE_HIDDEN_TOOLS: ReadonlySet<string> = new Set(['ToolSearch'])
28
29const SUMMARY_FIELDS = [
30  'title',
31  'subject',
32  'description',
33  'summary',
34  'url',
35  'query',
36  'pattern',
37  'skill',
38  'command',
39  'file_path',
40  'filePath',
41  'notebook_path',
42  'path',
43  'uri',
44  'prompt',
45  'message',
46  'name',
47] as const
48
49const MCP_PREFIX = 'mcp__'
50const MCP_SEPARATOR = '__'
51const SUMMARY_SOURCE_LIMIT = 2000
52
53export function isRichTool(tool: string): boolean {
54  return RICH_TOOLS.has(tool)
55}
56
57export function isHiddenByEngine(tool: string): boolean {
58  return ENGINE_HIDDEN_TOOLS.has(tool)
59}
60
61export function drawsGenericRow(tool: string): boolean {
62  return !RICH_TOOLS.has(tool) && !ENGINE_ROW_TOOLS.has(tool) && !ENGINE_HIDDEN_TOOLS.has(tool)
63}
64
65export function toolLabel(tool: string): string {
66  if (!tool.startsWith(MCP_PREFIX)) return shownLine(tool)
67  const named = tool.slice(MCP_PREFIX.length)
68  const split = named.indexOf(MCP_SEPARATOR)
69  if (split <= 0 || split + MCP_SEPARATOR.length >= named.length) return shownLine(tool)
70  const server = named.slice(0, split)
71  const name = named.slice(split + MCP_SEPARATOR.length)
72  return `${shownLine(server)} · ${shownLine(name)}`
73}
74
75function oneLine(value: unknown): string {
76  if (typeof value !== 'string') return ''
77  const head = Array.from(value).slice(0, SUMMARY_SOURCE_LIMIT).join('')
78  return shownLine(head.replace(/\s+/g, ' ').trim())
79}
80
81export function inputSummary(input: unknown): string {
82  if (!isRecord(input)) return ''
83  for (const field of SUMMARY_FIELDS) {
84    const named = oneLine(input[field])
85    if (named !== '') return named
86  }
87  for (const value of Object.values(input)) {
88    const first = oneLine(value)
89    if (first !== '') return first
90  }
91  return ''
92}
93
hooks/output.ts 170 lines
1import type { SimpleViewDiffGap } from '../types'
2
3export const EXIT_PREFIX = /^Error: Exit code (\d+)[^\n]*(?:\n|$)/
4
5export const FILE_TOOLS: ReadonlySet<string> = new Set(['Edit', 'Write'])
6
7export type Totals = { added: number; removed: number }
8
9export type StderrSummary = { lines: number; first: string }
10
11export type BashEnd =
12  | {
13      kind: 'done'
14      lines: number
15      interpretation: string | null
16      stderr: StderrSummary | null
17      savedTo: string | null
18    }
19  | { kind: 'exit'; code: number; line: string }
20
21export type FileChange = { path: string; verb: 'Updated' | 'Created' | 'Deleted'; totals: Totals }
22
23export type BashChanges =
24  | { kind: 'tracked'; files: FileChange[]; moreFiles: number }
25  | { kind: 'untracked' }
26  | { kind: 'unreported' }
27
28export type FileEdit = { path: string; totals: Totals | null }
29
30type Hunk = {
31  oldStart: number
32  oldLines: number
33  newStart: number
34  newLines: number
35  lines: string[]
36}
37
38export function isRecord(value: unknown): value is Record<string, unknown> {
39  return typeof value === 'object' && value !== null && !Array.isArray(value)
40}
41
42function isHunk(value: unknown): value is Hunk {
43  return (
44    isRecord(value) &&
45    typeof value.oldStart === 'number' &&
46    typeof value.oldLines === 'number' &&
47    typeof value.newStart === 'number' &&
48    typeof value.newLines === 'number' &&
49    Array.isArray(value.lines) &&
50    value.lines.every((line) => typeof line === 'string')
51  )
52}
53
54export function hunksOf(value: unknown): Hunk[] | null {
55  if (!Array.isArray(value) || !value.every(isHunk)) return null
56  return value
57}
58
59export function totalsOf(hunks: readonly Hunk[]): Totals {
60  const lines = hunks.flatMap((hunk) => hunk.lines)
61  return {
62    added: lines.filter((line) => line.startsWith('+')).length,
63    removed: lines.filter((line) => line.startsWith('-')).length,
64  }
65}
66
67export function lineCount(text: string): number {
68  const kept = text.trimEnd()
69  return kept === '' ? 0 : kept.split(/\r?\n/).length
70}
71
72export function contentLines(content: string): string[] {
73  return content === '' ? [] : content.replace(/\r?\n$/, '').split(/\r?\n/)
74}
75
76function firstNonEmptyLine(text: string): string {
77  return (
78    text
79      .split(/\r?\n/)
80      .map((line) => line.trim())
81      .find((line) => line !== '') ?? ''
82  )
83}
84
85function stderrSummary(stderr: unknown): StderrSummary | null {
86  if (typeof stderr !== 'string' || stderr.trim() === '') return null
87  return { lines: lineCount(stderr.trim()), first: firstNonEmptyLine(stderr) }
88}
89
90export function bashEnd(output: unknown, isErrored: boolean): BashEnd | null {
91  if (isErrored) {
92    if (typeof output !== 'string') return null
93    const found = EXIT_PREFIX.exec(output)
94    if (found?.[1] === undefined) return null
95    return {
96      kind: 'exit',
97      code: Number(found[1]),
98      line: firstNonEmptyLine(output.slice(found[0].length)),
99    }
100  }
101  if (!isRecord(output) || typeof output.stdout !== 'string') return null
102  if (output.interrupted !== false || output.isImage === true) return null
103  if (output.backgroundTaskId !== undefined) return null
104  const { returnCodeInterpretation: interpretation, persistedOutputPath: savedTo } = output
105  return {
106    kind: 'done',
107    lines: lineCount(output.stdout),
108    interpretation: typeof interpretation === 'string' ? interpretation : null,
109    stderr: stderrSummary(output.stderr),
110    savedTo: typeof savedTo === 'string' ? savedTo : null,
111  }
112}
113
114function fileChange(value: unknown): FileChange | null {
115  if (!isRecord(value) || typeof value.filePath !== 'string') return null
116  const hunks = hunksOf(value.hunks)
117  if (hunks === null) return null
118  const verb = value.created === true ? 'Created' : value.deleted === true ? 'Deleted' : 'Updated'
119  return { path: value.filePath, verb, totals: totalsOf(hunks) }
120}
121
122export function bashChanges(output: unknown): BashChanges | null {
123  if (!isRecord(output)) return null
124  const diff = output.bashEditDiff
125  if (diff === undefined) return { kind: 'unreported' }
126  if (!isRecord(diff)) return null
127  if (diff.unavailable === true || diff.skipped === true) return { kind: 'untracked' }
128  if (!Array.isArray(diff.files) || typeof diff.moreFiles !== 'number') return null
129  const files = diff.files.map(fileChange)
130  if (!files.every((file) => file !== null)) return null
131  return { kind: 'tracked', files, moreFiles: diff.moreFiles }
132}
133
134export function diffGap(tool: string, output: unknown): SimpleViewDiffGap | null {
135  if (tool !== 'Bash') return null
136  const changes = bashChanges(output)
137  if (changes === null) return 'unreported'
138  return changes.kind === 'tracked' ? null : changes.kind
139}
140
141function writeTotals(output: Record<string, unknown>, hunks: readonly Hunk[]): Totals | null {
142  if (typeof output.content !== 'string') return null
143  if (hunks.length > 0) return totalsOf(hunks)
144  if (output.type === 'create') return { added: contentLines(output.content).length, removed: 0 }
145  if (output.originalFile === output.content) return { added: 0, removed: 0 }
146  return null
147}
148
149export function fileEdit(tool: string, output: unknown): FileEdit | null {
150  if (!isRecord(output) || typeof output.filePath !== 'string') return null
151  if (output.staged === true) return null
152  const hunks = hunksOf(output.structuredPatch)
153  if (hunks === null) return null
154  if (tool === 'Edit') {
155    return { path: output.filePath, totals: hunks.length > 0 ? totalsOf(hunks) : null }
156  }
157  if (tool === 'Write') return { path: output.filePath, totals: writeTotals(output, hunks) }
158  return null
159}
160
161export function shownPath(path: string, root: string): string {
162  const base = root.replace(/[\\/]+$/, '')
163  if (base !== '' && path.replace(/[\\/]+$/, '') === base) return '.'
164  const separator = path.charAt(base.length)
165  if (base !== '' && path.startsWith(base) && (separator === '/' || separator === '\\')) {
166    return path.slice(base.length + 1)
167  }
168  return path
169}
170
hooks/reading.ts 104 lines
1import { isRecord, shownPath } from './output'
2
3export const READING_TOOLS: ReadonlySet<string> = new Set(['Read', 'Grep', 'Glob'])
4
5type Noun = { one: string; many: string }
6
7const LINES: Noun = { one: 'line', many: 'lines' }
8const FILES: Noun = { one: 'file', many: 'files' }
9const MATCHES: Noun = { one: 'match', many: 'matches' }
10
11function isCount(value: unknown): value is number {
12  return typeof value === 'number' && Number.isInteger(value) && value >= 0
13}
14
15function counted(count: number, noun: Noun): string {
16  return `${String(count)} ${count === 1 ? noun.one : noun.many}`
17}
18
19function shownOfTotal(shown: number, total: unknown, noun: Noun): string {
20  if (!isCount(total) || total <= shown) return counted(shown, noun)
21  return `${String(shown)} of ${counted(total, noun)}`
22}
23
24function readCount(output: unknown): string | null {
25  if (!isRecord(output) || output.type !== 'text' || !isRecord(output.file)) return null
26  const { numLines, startLine, totalLines } = output.file
27  if (!isCount(numLines) || !isCount(startLine) || !isCount(totalLines)) return null
28  const isWholeFile = startLine <= 1 && numLines >= totalLines
29  if (isWholeFile || numLines === 0) return counted(numLines, LINES)
30  const lastLine = startLine + numLines - 1
31  return `lines ${String(startLine)}-${String(lastLine)} of ${String(totalLines)}`
32}
33
34function grepCount(output: unknown): string | null {
35  if (!isRecord(output)) return null
36  switch (output.mode) {
37    case 'content':
38      return isCount(output.numLines)
39        ? shownOfTotal(output.numLines, output.totalLines, LINES)
40        : null
41    case 'count':
42      return isCount(output.numMatches) ? counted(output.numMatches, MATCHES) : null
43    case 'files_with_matches':
44      return isCount(output.numFiles)
45        ? shownOfTotal(output.numFiles, output.totalFiles, FILES)
46        : null
47    default:
48      return null
49  }
50}
51
52function globCount(output: unknown): string | null {
53  if (!isRecord(output) || !isCount(output.numFiles) || typeof output.truncated !== 'boolean') {
54    return null
55  }
56  const total = isCount(output.totalMatches) ? output.totalMatches : output.numFiles
57  const isFloor =
58    output.countIsComplete === false || (output.truncated && output.totalMatches === undefined)
59  return isFloor ? `${String(total)}+ ${FILES.many}` : counted(total, FILES)
60}
61
62export function readingCount(tool: string, output: unknown): string | null {
63  switch (tool) {
64    case 'Read':
65      return readCount(output)
66    case 'Grep':
67      return grepCount(output)
68    case 'Glob':
69      return globCount(output)
70    default:
71      return null
72  }
73}
74
75function searchTarget(pattern: string, input: Record<string, unknown>, root: string): string[] {
76  if (typeof input.path !== 'string') return [pattern]
77  return [pattern, `in ${shownPath(input.path, root)}`]
78}
79
80export function streamingTarget(tool: string, input: unknown, root: string): string[] | null {
81  if (!isRecord(input)) return null
82  const named = tool === 'Read' ? input.file_path : input.pattern
83  if (named !== undefined && typeof named !== 'string') return null
84  if (tool === 'Read') return named === undefined ? [] : [shownPath(named, root)]
85  if (input.path !== undefined && typeof input.path !== 'string') return null
86  if (named === undefined) return []
87  return searchTarget(tool === 'Grep' ? `"${named}"` : named, input, root)
88}
89
90export function readingTarget(
91  tool: string,
92  input: unknown,
93  output: unknown,
94  root: string,
95): string[] | null {
96  if (tool === 'Read') {
97    if (!isRecord(output) || !isRecord(output.file)) return null
98    const { filePath } = output.file
99    return typeof filePath === 'string' ? [shownPath(filePath, root)] : null
100  }
101  const target = streamingTarget(tool, input, root)
102  return target === null || target.length === 0 ? null : target
103}
104
hooks/row.ts 245 lines
1import type { Elements, RenderElement, RenderSurface, ThemeKey } from 'claude-code'
2import { elapsedText } from './detail'
3import type { BashEnd, FileChange, StderrSummary, Totals } from './output'
4import { graphemesOf } from './width'
5
6type RowElements = Pick<Elements[RenderSurface], 'Box' | 'Text' | 'Button'>
7type CellStyle = Omit<Parameters<RowElements['Text']>[0], 'children'>
8type Cell = { text: string; style?: CellStyle; canShrink?: boolean; keptCells?: number }
9
10export type RowLook = { elements: RowElements; hasToolMarker: boolean; columns: number }
11
12export type BashState = { kind: 'pending' } | { kind: 'running' } | BashEnd
13
14export type BashView = {
15  label: string
16  program: string
17  state: BashState
18  elapsedMs: number | null
19}
20
21const LABEL_KEPT_CELLS = 40
22const PENDING_TEXT = '…'
23const TIME_SHOWN_FROM_MS = 1000
24
25function cell(
26  { Box, Text }: RowElements,
27  { text, style = {}, canShrink = false, keptCells }: Cell,
28) {
29  return Box({
30    flexShrink: canShrink ? 1 : 0,
31    ...(keptCells === undefined ? {} : { minWidth: keptCells }),
32    children: Text({ ...style, children: text }),
33  })
34}
35
36function cellsOf(text: string): number {
37  return graphemesOf(text).reduce((sum, part) => sum + part.cells, 0)
38}
39
40function trailing(elements: RowElements, actions: RenderElement | null): RenderElement[] {
41  if (actions === null) return []
42  return [
43    elements.Box({ flexGrow: 1, minWidth: 2 }),
44    elements.Box({ flexShrink: 0, children: actions }),
45  ]
46}
47
48function line(
49  look: RowLook,
50  key: string,
51  marker: ThemeKey,
52  cells: Cell[],
53  actions: RenderElement | null = null,
54): RenderElement {
55  const { elements } = look
56  const columns = elements.Box({
57    flexDirection: 'row',
58    flexShrink: 1,
59    gap: 2,
60    children: cells.filter((part) => part.text !== '').map((part) => cell(elements, part)),
61  })
62  const parts = [columns, ...trailing(elements, actions)]
63  if (!look.hasToolMarker) return elements.Box({ key, flexDirection: 'row', children: parts })
64  const dot = elements.Box({
65    flexShrink: 0,
66    marginRight: 1,
67    children: elements.Text({ color: marker, children: '●' }),
68  })
69  return elements.Box({ key, flexDirection: 'row', children: [dot, ...parts] })
70}
71
72function plural(count: number, word: string): string {
73  return `${String(count)} ${word}${count === 1 ? '' : 's'}`
74}
75
76function stderrCells(stderr: StderrSummary | null): Cell[] {
77  if (stderr === null) return []
78  return [
79    { text: plural(stderr.lines, 'stderr line'), style: { dimColor: true } },
80    { text: stderr.first, style: { dimColor: true, wrap: 'truncate-end' }, canShrink: true },
81  ]
82}
83
84function stateCells(state: BashState): Cell[] {
85  switch (state.kind) {
86    case 'pending':
87      return [{ text: PENDING_TEXT, style: { dimColor: true } }]
88    case 'running':
89      return [{ text: 'running', style: { dimColor: true } }]
90    case 'done':
91      return [
92        state.interpretation === null
93          ? { text: 'exit 0', style: { color: 'success' } }
94          : { text: state.interpretation, style: { dimColor: true } },
95        {
96          text: state.savedTo === null ? plural(state.lines, 'line') : 'output saved to a file',
97          style: { dimColor: true },
98        },
99        ...stderrCells(state.stderr),
100      ]
101    case 'exit':
102      return [
103        { text: `exit ${String(state.code)}`, style: { color: 'error' } },
104        { text: state.line, style: { color: 'error', wrap: 'truncate-end' }, canShrink: true },
105      ]
106  }
107}
108
109function hasCutText(state: BashState): boolean {
110  return state.kind === 'exit' ? state.line !== '' : state.kind === 'done' && state.stderr !== null
111}
112
113function timeText(elapsedMs: number | null): string {
114  if (elapsedMs === null || elapsedMs < TIME_SHOWN_FROM_MS) return ''
115  return elapsedText(elapsedMs)
116}
117
118const MARKERS: Readonly<Record<BashState['kind'], ThemeKey>> = {
119  pending: 'subtle',
120  running: 'subtle',
121  done: 'success',
122  exit: 'error',
123}
124
125export function bashRow(
126  look: RowLook,
127  view: BashView,
128  actions: RenderElement | null = null,
129): RenderElement {
130  return line(
131    look,
132    'row',
133    MARKERS[view.state.kind],
134    [
135      {
136        text: view.label,
137        style: { wrap: 'truncate-end' },
138        canShrink: true,
139        keptCells: hasCutText(view.state)
140          ? Math.min(cellsOf(view.label), LABEL_KEPT_CELLS)
141          : undefined,
142      },
143      { text: view.program, style: { dimColor: true } },
144      ...stateCells(view.state),
145      { text: timeText(view.elapsedMs), style: { dimColor: true } },
146    ],
147    actions,
148  )
149}
150
151export function totalsText({ added, removed }: Totals): string {
152  return `+${String(added)} -${String(removed)}`
153}
154
155export function fileRow(
156  look: RowLook,
157  tool: string,
158  path: string,
159  totals: Totals | null,
160): RenderElement {
161  return line(look, 'row', 'success', [
162    { text: tool },
163    { text: path, style: { wrap: 'truncate-end' }, canShrink: true },
164    { text: totals === null ? '' : totalsText(totals), style: { dimColor: true } },
165  ])
166}
167
168export function readingRow(
169  look: RowLook,
170  tool: string,
171  target: readonly string[],
172  count: string | null,
173): RenderElement {
174  return line(look, 'row', count === null ? 'subtle' : 'success', [
175    { text: tool },
176    ...target.map((text) => ({ text, style: { wrap: 'truncate-end' as const }, canShrink: true })),
177    { text: count ?? PENDING_TEXT, style: { dimColor: true } },
178  ])
179}
180
181export type GenericState = 'pending' | 'running' | 'done' | 'error'
182
183export type GenericView = {
184  label: string
185  summary: string
186  state: GenericState
187  lines: number | null
188  elapsedMs: number | null
189}
190
191const GENERIC_STATES: Readonly<Record<GenericState, { marker: ThemeKey; cell: Cell }>> = {
192  pending: { marker: 'subtle', cell: { text: PENDING_TEXT, style: { dimColor: true } } },
193  running: { marker: 'subtle', cell: { text: 'running', style: { dimColor: true } } },
194  done: { marker: 'success', cell: { text: 'done', style: { color: 'success' } } },
195  error: { marker: 'error', cell: { text: 'error', style: { color: 'error' } } },
196}
197
198export function genericRow(look: RowLook, view: GenericView): RenderElement {
199  const { marker, cell: stateCell } = GENERIC_STATES[view.state]
200  return line(look, 'row', marker, [
201    { text: view.label },
202    { text: view.summary, style: { wrap: 'truncate-end' }, canShrink: true },
203    stateCell,
204    {
205      text: view.state === 'done' && view.lines !== null ? plural(view.lines, 'line') : '',
206      style: { dimColor: true },
207    },
208    { text: view.state === 'pending' ? '' : timeText(view.elapsedMs), style: { dimColor: true } },
209  ])
210}
211
212export type ChangeLines = { files: readonly FileChange[]; moreFiles: number } | null
213
214const RESULT_INDENT = 2
215
216type ChangeLine = { text: string; isDim: boolean }
217
218function changeLines(changes: ChangeLines): ChangeLine[] {
219  if (changes === null) {
220    return [{ text: 'File changes were not tracked for this call', isDim: true }]
221  }
222  const lines = changes.files.map((file) => ({
223    text: `${file.verb} ${file.path} (${totalsText(file.totals)})`,
224    isDim: false,
225  }))
226  if (changes.moreFiles > 0) {
227    lines.push({ text: `and ${plural(changes.moreFiles, 'more changed file')}`, isDim: true })
228  }
229  return lines
230}
231
232export function changesBlock(look: RowLook, changes: ChangeLines): RenderElement {
233  const { Box, Text } = look.elements
234  return Box({
235    flexDirection: 'column',
236    paddingLeft: look.hasToolMarker ? RESULT_INDENT : 0,
237    children: changeLines(changes).map((line, index) =>
238      Box({
239        key: `change-${String(index)}`,
240        children: Text({ dimColor: line.isDim, wrap: 'truncate-end', children: line.text }),
241      }),
242    ),
243  })
244}
245
hooks/width.ts 28 lines
1const GRAPHEMES = new Intl.Segmenter(undefined, { granularity: 'grapheme' })
2
3const ZERO_WIDTH = /^[\p{Mn}\p{Me}\p{Cf}]/u
4
5const EMOJI_PRESENTATION = /\p{Emoji_Presentation}/u
6
7const EMOJI_BY_SELECTOR = /^\p{Emoji}.*\uFE0F/u
8
9const EAST_ASIAN_WIDE =
10  /^[ᄀ-ᅟ⺀-〾ぁ-㏿㐀-䶿一-鿿ꀀ-꓏ꥠ-꥿가-힣豈-﫿︐-︙︰-﹯＀-⦆¢-₩\u{16FE0}-\u{18CFF}\u{1B000}-\u{1B2FF}\u{1F200}-\u{1F2FF}\u{20000}-\u{2FFFD}\u{30000}-\u{3FFFD}]/u
11
12export function isEmoji(grapheme: string): boolean {
13  return EMOJI_PRESENTATION.test(grapheme) || EMOJI_BY_SELECTOR.test(grapheme)
14}
15
16function cellsOf(grapheme: string): number {
17  if (isEmoji(grapheme)) return 2
18  if (ZERO_WIDTH.test(grapheme)) return 0
19  return EAST_ASIAN_WIDE.test(grapheme) ? 2 : 1
20}
21
22export function graphemesOf(text: string): { grapheme: string; cells: number }[] {
23  return Array.from(GRAPHEMES.segment(text), ({ segment }) => ({
24    grapheme: segment,
25    cells: cellsOf(segment),
26  }))
27}
28
types/index.d.ts 40 lines
1export type SimpleViewMode = 'on' | 'off'
2
3export type SimpleViewTiming = {
4  startedAt: number
5  elapsedMs: number
6  isRunning: boolean
7}
8
9export type SimpleViewDiffGap = 'unreported' | 'untracked'
10
11export type SimpleViewFold = 'folded' | 'open' | 'all'
12
13export type SimpleViewCall = {
14  generation: number
15  seq: number
16  tool_use_id: string
17  tool: string
18  input: string
19  output: string
20  diff: string
21  diffGap: SimpleViewDiffGap | null
22  isErrored: boolean
23  elapsedMs: number
24}
25
26declare module 'claude-code' {
27  interface PluginState {
28    'handily-simple-view': {
29      mode: SimpleViewMode
30      generation: number
31      timing: StateFamily<SimpleViewTiming>
32      resultLines: StateFamily<number>
33      count: number
34      calls: StateFamily<SimpleViewCall>
35      folds: StateFamily<SimpleViewFold>
36      ready: { root: string }
37    }
38  }
39}
40