SLOPSHOPPER

ledger-widget

What a project has cost across every session, from any folder or worktree in it: measured as each turn ends, and read back from the sessions Claude Code saved

newpanebandspinnercommandprocess
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · ledger-widget
› 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 › /ledger-widget ⎿ ledger-widget: Ledger on; /widgets places it. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

Claude Code Widgets

Small cards that sit under the Claude Code prompt, or docked beside the transcript in fullscreen. Each widget is its own mod, toggled with a slash command.

It started with a few useful ones (context, usage, file tree) and then got carried away: there are now 95 widgets, from git status and a turn timer to a pixel crab, a dungeon crawl and Tetris.

Try every widget in its own little terminal on the demo page: the real widget code runs in the browser against a simulated session, so you can type its slash commands, run a turn and play the games. It is a static page in docs/, published to GitHub Pages on every push to main that changes it; opening docs/index.html from a checkout works too.

Install

Add the marketplace, then install the layout plugin and whichever widgets you want:

/plugin marketplace add oMaN-Rod/claude-code-widgets
/plugin install widgets@claude-code-widgets
/plugin install context-widget@claude-code-widgets

Every widget needs widgets, the layout plugin that places the cards.

Requires a Claude Code version with mod (function hook) support. The mod API is early access and may change between releases.

Widgets

Layout

Required by every widget.

PluginCommandWhat it shows
widgets`/widgets [side\above\below\close\<columns>\width <widget> <columns\reset>]`Places the cards: below the prompt, above it, or docked beside the transcript in fullscreen

Session

What Claude is doing and what it is costing.

PluginCommandWhat it shows
context-widget`/context-widget [auto\detailed\grid\top\bar\line]`The context window as a stacked bar, one colour per /context category
usage-widget/usage-widgetA bar per rate-limit window, time to reset, session cost
timer-widget`/timer-widget [on\off\clear]`The running turn's elapsed time, plus last, average and longest turn and a sparkline
activity-widget`/activity-widget [on\off\clear]`The latest tool calls with their duration and whether they failed
tasks-widget`/tasks-widget [on\off\clear]`The task list Claude is working through, with a progress bar
checks-widget`/checks-widget [on\off\clear]`The latest test, lint and build runs: pass or fail, duration and how long ago
timeline-widget`/timeline-widget [on\off]`The turn as a chart: one bar per tool call on a time axis, parallel calls stacked
board-widget`/board-widget [on\off\clear]`A status board Claude writes itself through a pin tool: goal, findings and open questions
forecast-widget`/forecast-widget [on\off\clear]`Context growth per turn as a chart, with the turns left before compaction; warns once when three or fewer are left
guard-widget`/guard-widget [on\off\clear]`Permission checks this session: allowed, asked and denied, with what you keep being asked about
stream-widget`/stream-widget [on\off]`A live tokens-per-second gauge and sparkline while Claude is writing (estimated from text length)
sessions-widget/relay <number> <message>, `/sessions-widget [on\off]`Every Claude Code session open on this machine: folder, branch, working or waiting and for how long; /relay 1 <message> sends a line to one
collision-widget`/collision-widget [on\off\clear]`Stops an edit to a file another Claude Code session on this machine changed since this one last read it, and has Claude read it again first
sieve-widget`/sieve-widget [on\off]`A compaction that keeps every word you and Claude said and folds only the old tool traffic, with no summary and no tokens spent
redact-widget`/redact-widget [on\off\clear]`Replaces API keys, tokens, private keys and passwords in command output and file reads before Claude sees them
notebook-widget`/notebook-widget [on\off\show\drop <number>\clear]`Gives Claude a jot tool for writing down what its future self should know about this project, and reads the notes back next session
footnotes-widget`/footnotes-widget [on\off\show\clear]`Checks every file path, cited line and code symbol in Claude's last reply against the working tree, with no model call, and flags the ones that are not there
witness-widget`/witness-widget [on\off\show\clear]`Every line of hidden context the other widgets add to your prompts, word for word, with a running size
queue-widget`/queue-widget [on\off\add <prompt>\until <command\off>\start\drop <number>\report\clear]`A queue of prompts that run back to back while you are away, a gate command each must pass before the next starts, and a report of how each one ended
done-widget`/done-widget [on\off\add <criterion>\drop <number>\show\clear]`A definition of done you write once: Claude ticks each item with evidence through its tick tool, and is pulled up when it says done with items open
trial-widget`/trial-widget [on\off\test <widget>\clear]`A fair test of another widget: sessions alternate with it on and off, and the card compares how many turns end clean
aside-widget`/aside-widget [on\off\ask <question>\clear]`Ask a side question about the conversation, even mid-turn, and get the answer on a card without adding a turn to the transcript
tap-widget`/tap-widget [on\off\list [word]\add <server> <tool> [json] [anyway]\run <n>\show <n>\drop <n>\clear]`One line per tool of your connected MCP servers, called by the widget on a clock with no model: pull requests, errors, the next meeting
margin-widget`/margin-widget [on\off\mark [remark]\drop <n>\send\clear]`Mark passages of Claude's reply with the mouse, write a remark against each, and send them back as one quoted prompt
loupe-widget`/loupe-widget [on\off\look [text]\copy]`Select a hash, path, name, timestamp or colour in the transcript with the mouse and the card says what it is, with no model call
strays-widget`/strays-widget [on\off\stop <port>\forget <port>\clear]`Servers this session started that still hold a port, with age and turn, one verb to stop one, and the survivors shown when the next session opens
premise-widget`/premise-widget [on\off\show\fix <n>\clear]`Quotes thinking-summary sentences that name a gap and a choice made anyway, unless the reply flags it, and starts your correction; no model call; needs "showThinkingSummaries": true in settings.json
earpiece-widget`/earpiece-widget [on\off], /whisper <number> <note>`Every running subagent with the tool it is on and its last sentence, and /whisper slips one of them a note without stopping the turn
pen-widget`/pen-widget [on\off\show\clear]`The file, edit or command Claude is writing right now, drawn line by line as the tool call's arguments stream in, before the tool runs
outage-widget`/outage-widget [on\off\check\clear]`When a push or install fails on the network, checks the provider's status page and says whether GitHub, npm, PyPI or crates.io reports an incident
landmarks-widget`/landmarks-widget [on\off\list\go <n>\clear]`A numbered table of contents for the session, built as it happens from prompts, first edits, checks turning red or green, commits and questions; press a line to scroll the transcript to it
seen-widget`/seen-widget [on\off\show\open [n]\clear]`The pictures Claude looked at this session, image files it read and screenshots that came back from tools, drawn as Claude received them and opened full size with one command
amendments-widget`/amendments-widget [on\off\show [n]\clear]`What changed in the system prompt and the built-in tool descriptions Claude Code gives Claude since the version you last ran, with the before and after one command away
skimmed-widget`/skimmed-widget [on\off\show\clear]`The caveats in Claude's replies that left your screen while Claude was still writing and have not been back, quoted in full; it never claims that what was on screen was read
attic-widget`/attic-widget [on\off\show\keep <tool>\stow <tool>\clear]`Counts which tools Claude calls in this project, puts the unused ones behind ToolSearch, lists the daily ones up front, and reports how many schema tokens each request no longer carries
rehearsal-widget`/rehearsal-widget [on\off\show\forget <n>\clear]`Which of the commands and edits Claude has made in this project would stop for permission or be refused right now, asked of the engine's own permission check without running anything
aim-widget`/aim-widget [on\off\prod <word>\unprod <word>\show\clear]`Where a command lands outside this folder: the kube context, cloud profile, Terraform workspace or database it is aimed at, named in the permission dialog
earshot-widget`/earshot-widget [on\off\last\clear]`Whether Claude has got the message you typed while it was working: how late a request first carried it, and what Claude changed before it heard you

Project and git

The state of the working tree.

PluginCommandWhat it shows
file-tree-widget/file-tree-widgetThe project directory; folders expand on click
git-widget/git-widgetBranch, ahead/behind, staged, changed and untracked counts, and the last commit
changes-widget`/changes-widget [on\off\clear]`Files edited this session, most recent first, with an edit count each
commits-widget/commits-widgetThe commits made since the session started
todos-widget/todos-widgetTODO, FIXME, HACK and XXX comments in tracked files, counted and listed
diff-widget`/diff-widget [on\off\clear]`The last edit as a syntax-highlighted diff
watch-widget`/watch-widget [on\off\run\stop], /watch <command>`/watch bun test reruns the command after every edit: a pass or fail light and the last failing lines
map-widget`/map-widget [on\off\clear]`A pixel map of the tracked files, lit blue where Claude has read and green where it has edited
stakes-widget`/stakes-widget [on\off\clear]`What a yes would lose, measured from git and written under the permission dialog for a destructive command
ledger-widget`/ledger-widget [on\off\scan\show\clear]`What a project has cost across every session, from any folder or worktree in it: measured as each turn ends, and read back from the sessions Claude Code saved
squiggle-widget`/squiggle-widget [on\off\check [text]]`Underlines file names that do not exist, as you type them in the prompt box, and paints the ones that do green
critic-widget`/critic-widget [on\off\review\tell\clear]`A second pair of eyes: a separate model reads the uncommitted diff and lists only real defects, which you can hand to Claude
customs-widget`/customs-widget [on\off\show\trust <name>\clear]`Looks up every package Claude installs on npm or PyPI before the command runs, and holds the install for a yes when the name is missing or under 30 days old. Scoped names and installs that name a registry, or sit beside a project .npmrc that does, are not looked up; user-level and environment registry settings, bunfig.toml, .yarnrc.yml and pip and uv config files are not seen
provenance-widget`/provenance-widget [on\off\scan\look [<path>:<line>]\copy\clear]`The conversation behind a line of code: for lines Claude is about to edit, or a path:line you ask about, the prompt you typed before they were written and the command that resumes that session
green-widget`/green-widget [on\off\tell\clear]`What changed in the working tree since each test, lint or build command last passed, measured against a hidden git snapshot taken at that moment and handed to Claude on request

Time and focus

Clocks, timers and reminders that do not depend on the session.

PluginCommandWhat it shows
pomodoro-widget`/pomodoro-widget [on\off\start\break\stop\<minutes>]`A focus timer with a countdown, a progress bar and a count of finished sessions
countdown-widget`/countdown-widget [on\off\clear], /countdown <HH:MM\<n>m\<n>h> [label]`Time left to a deadline you set, with a progress bar and a toast when it arrives
clocks-widget`/clocks-widget [on\off\add <zone>\remove <zone>\clear]`Your local time beside the time zones you add, such as Asia/Tokyo
notes-widget`/notes-widget [on\off\clear], /note <text\done <n>>`Pinned notes kept across sessions; /note <text> adds one, /note done <n> removes it
coffee-widget`/coffee-widget [on\off\refill\<minutes>]`A cup that empties over 90 minutes and nudges you to take a break

Scenes

Pixel art that reacts to turns, tool calls, checks and context usage.

PluginCommandWhat it shows
pet-widget`/pet-widget [on\off\<mood>]`Clawd, a pixel crab: works during a turn, dizzy when a tool call fails, happy when tests pass. Earns XP and levels up across sessions, wears a hat once badges-widget has awarded a badge, and with two sessions open stays in the one you last prompted. Remembers each project and greets you with how long you were away and whether the checks were red
aquarium-widget`/aquarium-widget [on\off\demo]`A fish for every running tool call and agent
skyline-widget`/skyline-widget [on\off\demo\clear]`One building per turn, one floor per tool call
train-widget`/train-widget [on\off]`A locomotive pulling one wagon per tool call this turn, coloured by tool
garden-widget`/garden-widget [on\off\reset]`A plant: a leaf per tool call, a flower when checks pass, wilting when a call fails
campfire-widget`/campfire-widget [on\off\stoke]`A campfire that burns higher with tool calls and dies down to embers when idle
constellation-widget`/constellation-widget [on\off\clear]`A star per turn, joined into a constellation that gets a name after nine
fireworks-widget`/fireworks-widget [on\off\demo]`A night sky that sets off fireworks when checks pass, and a dud when they fail
invaders-widget`/invaders-widget [on\off\demo\clear]`An invader arrives for every failing check; passing checks shoot them down
weather-widget`/weather-widget [on\off\live\<percent>]`Clear sky when context has room, a storm near compaction
boss-widget`/boss-widget [on\off]`Context usage as a boss health bar; compaction defeats it and starts the next level
sky-widget`/sky-widget [on\off]`The sky at your local time: sun by day, moon by night, more stars the longer the session runs
world-widget`/world-widget [on\off\clear]`One scene for everything: sky by the clock, weather by context, a tower per turn, a train of tool calls and a wandering crab
quest-widget`/quest-widget [on\off\reset]`The session as a dungeon crawl: a room per turn, a monster per tool call, loot when checks pass; the hero is kept across sessions
race-widget`/race-widget [on\off\clear]`Parallel subagents as cars on a track, one stride per tool call, with a podium as they finish
moon-widget`/moon-widget [on\off\north\south]`The real moon right now, drawn for your hemisphere, with a countdown to the next full moon and what it means for your deploy

Visualizers

Abstract pictures driven by tool activity.

PluginCommandWhat it shows
mosaic-widget`/mosaic-widget [on\off\clear]`One tile per tool call, coloured by tool; failures are red
sorting-widget`/sorting-widget [on\off\step]`A bar chart being sorted, one swap per tool call
equalizer-widget`/equalizer-widget [on\off]`Level meters that jump with each tool call and fall back to rest
rain-widget`/rain-widget [on\off]`Falling code rain that speeds up the busier the turn gets
orbit-widget`/orbit-widget [on\off]`A small solar system; the planets speed up while tool calls run
life-widget`/life-widget [on\off\reset]`Conway's Game of Life; every tool call drops a glider
donut-widget`/donut-widget [on\off]`The spinning 3D donut; it spins faster while tool calls run
pipes-widget`/pipes-widget [on\off]`The pipes screensaver; it grows while the session is idle and pauses while Claude works
maze-widget`/maze-widget [on\off\new]`A first-person walk through a maze seeded by the project folder
marquee-widget`/marquee-widget [on\off\clear\<text>]`An LED ticker scrolling session events; any other text posts your own headline

Games

Snake, 2048 and Tetris play themselves until you click the board and take the keys.

PluginCommandWhat it shows
snake-widget`/snake-widget [on\off]`Snake; it plays itself until you take the keys
2048-widget`/2048-widget [on\off]`2048; it plays itself until you take the keys
tetris-widget`/tetris-widget [on\off]`Tetris; it plays itself until you take the keys
minesweeper-widget`/minesweeper-widget [on\off]`Minesweeper: click to reveal, right-click or f to flag, r to restart
breakout-widget`/breakout-widget [on\off\reset]`A self-playing brick breaker; every tool call adds a row of bricks
typer-widget`/typer-widget [on\off]`A typing game: words from your own file names fall, and you type them before they land

Just for fun

PluginCommandWhat it shows
fortune-widget`/fortune-widget [on\off\next]`A one-line fortune that changes with every turn
8ball-widget`/8ball-widget [on\off], /8ball <question>`/8ball <question> gives an answer of doubtful reliability
badges-widget`/badges-widget [on\off\reset]`Achievements earned across sessions, with a toast when one unlocks
sigil-widget`/sigil-widget [on\off\clear]`A pixel emblem generated from this session's activity, beside a gallery of the ones from earlier sessions
sound-widget`/sound-widget [on\off\mute\test]`A note per tool call, a chord when checks pass, a buzz on failure, with a piano roll (audio plays on macOS only)

Placement, which widgets are on, and view modes are saved and restored in every session.

Notes

  • /widgets width pet 60 sets how wide one widget's card may grow (the default is 40 columns); /widgets width pet reset puts it back.
  • /widgets side docks the cards beside the transcript only in the fullscreen layout (/tui fullscreen). In the default layout it falls back to below the prompt.
  • The pixel art is drawn with terminal block characters and shows in the terminal only.
  • sound-widget plays audio on macOS only; elsewhere it stays silent and just draws the piano roll.
  • board-widget registers a pin tool that Claude can call, so its description is part of the context while the board is on.
  • watch-widget runs your command through sh -c, falling back to cmd /c.
  • Taking over a game, and playing Minesweeper at all, needs a mouse click on the board, which the fullscreen layout reports.

Develop

Each plugin under plugins/ is a mod: a manifest, a hooks module and its tests.

claude --plugin-dir plugins            # load every plugin from this checkout
claude plugin validate plugins/<name>  # check a manifest and hooks module
claude plugin test plugins/<name>      # run its tests

Plugin storage ($.store) is read once per session, so a widget that has to see other live sessions keeps a file under its own folder instead ($.plugin.root).

Plugins cannot import from one another, so widgets shares card stacking and the pixel renderer as $.widgets (plugins/widgets/hooks/kit.tsx), which every widget calls.

Demo page

docs/ is the demo page. bun run site/build.ts bundles every widget's hooks module into docs/mods.js and writes docs/catalog.js from the tables above, so a new widget appears on the page once it has a row here. docs/engine.js is a small stand-in for the mod engine (state, store, clock, commands, a made-up project and a scripted turn), and docs/view.js draws the card trees. bun run site/smoke.ts boots every widget in that engine and runs a turn; a widget that needs an engine call the stand-in lacks shows up there. docs/widgets.js holds recordings from the real interface, shown only if a widget fails to start.

The Widget Factory

New widgets are made by the Widget Factory in factory/: a crew of Claude Code agents that takes each widget through ideation, design, build, inspection and shipping, with a different agent inspecting than built it. Clone the repository and you can run your own:

https://github.com/user-attachments/assets/6833eb82-8b2e-4b4c-80ca-4194d48d10e7

bun run --cwd factory setup   # checks what you need and prepares the floor
bun run --cwd factory floor   # the factory floor in your browser
bun run --cwd factory line    # opens a Claude Code session that runs the line

https://github.com/user-attachments/assets/d0953871-4935-4fa9-8ab3-f58b51739a17

factory/README.md explains the stations, the crew, the widget standard and how to contribute a widget.

License

MIT

Source 3 files
hooks/register.tsx 419 lines
1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, Register, RenderElement, RenderSurface } from 'claude-code'
3import type { WidgetsPlace } from 'widgets'
4
5import { fit, folder, plural } from './lib'
6
7type Tags = Pick<Elements[RenderSurface], 'Box' | 'Text'>
8type Entry = { usd: number | null; at: number; size: number; isOurs: boolean }
9type Sessions = Record<string, Entry>
10type View = { key: string; name: string; roots: string[]; id: string; sessions: Sessions; scannedAt: number; fault: boolean }
11type Kept = { sessions: Sessions; scannedAt: number }
12type Book = { projects: Record<string, unknown> }
13type Saved = { id: string; path: string; size: number; mtimeMs: number; isExact: boolean }
14type Tally = { isEmpty: boolean; total: number; counted: number; since: number | null; unpriced: number; long: number; mine: number }
15
16const PANE = 'widgets'
17const CARD_COLUMNS = 40
18const LONG_COLUMNS = 36
19const USAGE = 'Usage: /ledger-widget [on|off|scan|show|clear]'
20const OFF = 'Ledger is off.'
21const FILE = 'ledger.json'
22const GIT_MS = 3000
23const MAX_READ = 3_500_000
24const MAX_SCAN = 40_000_000
25const WORKTREE = 'worktree '
26const COST = '"type":"cost-state"'
27const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] as const
28const EMPTY = ['Nothing counted yet.', "Each turn's cost is added here.", "/ledger-widget scan adds this project's saved sessions."] as const
29const BLANK: View = { key: '', name: '', roots: [], id: '', sessions: {}, scannedAt: 0, fault: false }
30const site = { plugin: 'widgets', key: 'site' } as const
31const widths = { plugin: 'widgets', key: 'widths' } as const
32const isOn = atom({ plugin: 'ledger-widget', key: 'isOn' } as const, false)
33const view = atom({ plugin: 'ledger-widget', key: 'view' } as const, BLANK)
34
35const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
36
37const isAmount = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value) && value >= 0
38
39const parsed = (line: string): Record<string, unknown> | undefined => {
40  try {
41    const value: unknown = JSON.parse(line)
42
43    return isRecord(value) ? value : undefined
44  } catch {
45    return undefined
46  }
47}
48
49const bookOf = (text: string): Book => {
50  const projects = parsed(text)?.projects
51
52  return { projects: isRecord(projects) ? projects : {} }
53}
54
55const keptOf = (book: Book, key: string): Kept => {
56  const raw = book.projects[key]
57  if (!isRecord(raw) || !isRecord(raw.sessions)) return { sessions: {}, scannedAt: 0 }
58
59  const sessions: Sessions = {}
60  for (const [id, entry] of Object.entries(raw.sessions)) {
61    if (!isRecord(entry)) continue
62    const { usd, at, size, isOurs } = entry
63    if ((usd === null || isAmount(usd)) && isAmount(at) && isAmount(size) && typeof isOurs === 'boolean') sessions[id] = { usd, at, size, isOurs }
64  }
65
66  return { sessions, scannedAt: isAmount(raw.scannedAt) ? raw.scannedAt : 0 }
67}
68
69const enc = (path: string): string => path.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase()
70
71const isWithin = (cwd: string, roots: readonly string[]): boolean =>
72  roots.some(root => folder(cwd) === folder(root) || folder(cwd).startsWith(`${folder(root)}/`))
73
74const money = (usd: number): string => {
75  const cents = Math.round(usd * 100) / 100
76
77  return cents < 100 ? `$${cents.toFixed(2)}` : `$${String(Math.round(usd)).replace(/\B(?=(\d{3})+$)/g, ',')}`
78}
79
80const dated = (at: number): string => {
81  const day = new Date(at)
82
83  return `${day.getDate()} ${MONTHS[day.getMonth()]} ${day.getFullYear()}`
84}
85
86const tallied = ({ sessions, id }: View): Tally => {
87  const ours = Object.values(sessions).filter(entry => entry.isOurs)
88  const counted = ours.flatMap(({ usd, at }) => (usd === null ? [] : [{ usd, at }]))
89  const blank = ours.filter(entry => entry.usd === null)
90  const long = blank.filter(entry => entry.size > MAX_READ).length
91
92  return {
93    isEmpty: ours.length === 0,
94    total: counted.reduce((sum, entry) => sum + entry.usd, 0),
95    counted: counted.length,
96    since: counted.reduce<number | null>((least, entry) => (least === null || entry.at < least ? entry.at : least), null),
97    unpriced: blank.length - long,
98    long,
99    mine: sessions[id]?.usd ?? 0,
100  }
101}
102
103const summary = (held: View): string => {
104  const { total, counted, since, unpriced, long } = tallied(held)
105  const priced = since === null ? `Nothing counted yet for ${held.name}.` : `${money(total)} over ${plural(counted, 'session')} since ${dated(since)}.`
106
107  return `${priced}${unpriced > 0 ? ` ${unpriced} without a cost record.` : ''}${long > 0 ? ` ${long} too long to read.` : ''}`
108}
109
110const savedOf = (text: string, fallback: number): { cwd: string | undefined; start: number; usd: number | undefined } => {
111  const lines = text.split('\n')
112  let first: Record<string, unknown> | undefined
113  for (const line of lines) {
114    const row = line.includes('"cwd"') ? parsed(line) : undefined
115    if (typeof row?.cwd !== 'string') continue
116    first = row
117    break
118  }
119  let usd: number | undefined
120  for (let at = lines.length - 1; at >= 0 && usd === undefined; at -= 1) {
121    const cost = lines[at]?.includes(COST) === true ? parsed(lines[at] ?? '')?.totalCostUSD : undefined
122    if (isAmount(cost)) usd = cost
123  }
124  const start = typeof first?.timestamp === 'string' ? Date.parse(first.timestamp) : Number.NaN
125
126  return { cwd: typeof first?.cwd === 'string' ? first.cwd : undefined, start: isAmount(start) ? start : fallback, usd }
127}
128
129const load = async ($: EngineInterface): Promise<Book> => bookOf(await $.fs.read(`${$.plugin.root}/${FILE}`).catch(() => ''))
130
131const save = async ($: EngineInterface, projects: Record<string, unknown>): Promise<void> => {
132  await $.fs.write(`${$.plugin.root}/${FILE}`, JSON.stringify({ projects })).catch(() => undefined)
133}
134
135const refresh = async ($: EngineInterface): Promise<View> => {
136  const book = await load($)
137
138  return update($, view, held => ({ ...(held ?? BLANK), ...keptOf(book, (held ?? BLANK).key) }))
139}
140
141const open = async ($: EngineInterface): Promise<void> => {
142  if ((await read($, view)).key === '') {
143    const root = await $.session.root()
144    const listed = await $.process
145      .run(['git', '--no-optional-locks', 'worktree', 'list', '--porcelain'], { cwd: root, timeoutMs: GIT_MS })
146      .catch(() => undefined)
147    const found =
148      listed === undefined || listed.exitCode !== 0 || listed.isStdoutTruncated
149        ? []
150        : listed.stdout
151            .split('\n')
152            .filter(line => line.startsWith(WORKTREE))
153            .map(line => line.slice(WORKTREE.length).replace(/\r$/, ''))
154            .filter(path => path !== '')
155    const roots = found.length > 0 ? found : [root]
156    const main = roots[0] ?? root
157    const id = await $.session.id().catch(() => '')
158    const name = main.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || main
159    await update($, view, held => ({ ...(held ?? BLANK), key: folder(main) || main, name, roots, id }))
160  }
161  await refresh($)
162}
163
164const measure = async ($: EngineInterface): Promise<void> => {
165  const { key, id } = await read($, view)
166  if (key === '' || id === '') return
167
168  const usd = (await $.session.usage().catch(() => undefined))?.cost?.usd
169  if (!isAmount(usd)) return
170
171  const now = await $.clock.now()
172  const book = await load($)
173  const { sessions, scannedAt } = keptOf(book, key)
174  const kept = sessions[id]
175  const entry: Entry = { usd: Math.max(kept?.usd ?? 0, usd), at: kept?.at ?? now, size: kept?.size ?? 0, isOurs: true }
176  const next = { sessions: { ...sessions, [id]: entry }, scannedAt }
177  await save($, { ...book.projects, [key]: next })
178  await update($, view, held => ({ ...(held ?? BLANK), ...next }))
179}
180
181const failed = async ($: EngineInterface, text: string): Promise<string> => {
182  await update($, view, held => ({ ...(held ?? BLANK), fault: true }))
183
184  return text
185}
186
187const scan = async ($: EngineInterface): Promise<string> => {
188  const { key, name, roots } = await read($, view)
189  const config = await $.env.get('CLAUDE_CONFIG_DIR').catch(() => undefined)
190  const home = config || (await $.env.get('HOME').catch(() => undefined)) || (await $.env.get('USERPROFILE').catch(() => undefined))
191  if (!home) return failed($, 'Could not find where sessions are saved.')
192
193  const base = config ? `${config}/projects` : `${home}/.claude/projects`
194  const folders = await $.fs.list(base).catch(() => undefined)
195  if (folders === undefined) return failed($, `Could not read ${base}.`)
196
197  const now = await $.clock.now()
198  const book = await load($)
199  const sessions = { ...keptOf(book, key).sessions }
200  const names = roots.map(enc)
201  const fresh: Saved[] = []
202  for (const entry of folders) {
203    const lower = entry.name.toLowerCase()
204    const isExact = names.includes(lower)
205    if (entry.kind === 'file' || !(isExact || names.some(start => lower.startsWith(`${start}-`)))) continue
206
207    const files = await $.fs.list(`${base}/${entry.name}`).catch(() => [])
208    for (const file of files) {
209      if (file.kind !== 'file' || !file.name.endsWith('.jsonl')) continue
210      const id = file.name.slice(0, -'.jsonl'.length)
211      const kept = sessions[id]
212      if (kept?.size === file.size) continue
213      if (file.size <= MAX_READ) fresh.push({ id, path: `${base}/${entry.name}/${file.name}`, size: file.size, mtimeMs: file.mtimeMs, isExact })
214      else if (isExact) sessions[id] = { usd: kept?.usd ?? null, at: kept?.at ?? file.mtimeMs, size: file.size, isOurs: true }
215    }
216  }
217
218  fresh.sort((one, other) => other.mtimeMs - one.mtimeMs)
219  let spent = 0
220  let count = 0
221  let reached = 0
222  for (const { id, path, size, mtimeMs } of fresh) {
223    if (reached > 0 && spent + size > MAX_SCAN) break
224    reached += 1
225    spent += size
226    const text = await $.fs.read(path).catch(() => undefined)
227    if (text === undefined) continue
228
229    count += 1
230    const kept = sessions[id]
231    const { cwd, start, usd } = savedOf(text, mtimeMs)
232    if (cwd !== undefined && isWithin(cwd, roots)) {
233      sessions[id] = { usd: usd === undefined ? (kept?.usd ?? null) : Math.max(kept?.usd ?? 0, usd), at: Math.min(kept?.at ?? start, start), size, isOurs: true }
234    } else {
235      sessions[id] = kept?.isOurs === true ? { ...kept, size } : { usd: null, at: mtimeMs, size, isOurs: false }
236    }
237  }
238
239  const next = { sessions, scannedAt: now }
240  await save($, { ...book.projects, [key]: next })
241  const held = await update($, view, old => ({ ...(old ?? BLANK), ...next, fault: false }))
242  const waiting = fresh.length - reached
243
244  return [`Read ${plural(count, 'saved session')} of ${name}.`, summary(held), ...(waiting > 0 ? [`${waiting} more to read: run scan again.`] : [])].join('\n')
245}
246
247const tell = async ($: EngineInterface): Promise<string> => {
248  const held = await refresh($)
249
250  return [
251    `${held.name} (${held.roots[0] ?? ''})`,
252    summary(held),
253    `This session: ${money(tallied(held).mine)}`,
254    ...(held.scannedAt === 0 ? ['Saved sessions not read yet: /ledger-widget scan'] : []),
255  ].join('\n')
256}
257
258const wipe = async ($: EngineInterface): Promise<string> => {
259  const { key, name } = await read($, view)
260  const book = await load($)
261  await save($, Object.fromEntries(Object.entries(book.projects).filter(([other]) => other !== key)))
262  await update($, view, held => ({ ...(held ?? BLANK), sessions: {}, scannedAt: 0 }))
263
264  return `Ledger cleared for ${name}.`
265}
266
267const wrapped = (sentence: string, inner: number): string[] =>
268  sentence.split(' ').reduce<string[]>((rows, word) => {
269    const last = rows.at(-1)
270
271    return last !== undefined && last.length + 1 + word.length <= inner ? [...rows.slice(0, -1), `${last} ${word}`] : [...rows, word]
272  }, [])
273
274const paired =(left: string, rights: readonly string[], inner: number): { gap: string; right: string } => {
275  const right = rights.find(wanted => left.length + 1 + wanted.length <= inner) ?? ''
276
277  return { gap: ' '.repeat(Math.max(0, inner - left.length - right.length)), right }
278}
279
280const show = async (
281  $: EngineInterface,
282  { Box, Text }: Tags,
283  beneath: RenderElement,
284  place: WidgetsPlace,
285  columns: number,
286): Promise<RenderElement> => {
287  if (!(await read($, isOn))) return beneath
288  if ((await $.state.get(site)).value !== place) return beneath
289
290  const width = fit((await $.state.get(widths)).value?.['ledger-widget'] ?? CARD_COLUMNS, columns)
291  const inner = width - 4
292  const isLong = inner >= LONG_COLUMNS
293  const held = await read($, view)
294  const { isEmpty, total, counted, since, unpriced, long, mine } = tallied(held)
295  const count = plural(counted, 'session')
296  const top = paired(money(total), [count], inner)
297  const spent = `this session ${money(mine)}`
298  const from = paired(spent, since === null ? [] : [`since ${dated(since)}`, dated(since)], inner)
299  const fault = held.fault && (
300    <Text color="yellow" wrap="truncate-end">
301      {isLong ? 'Saved sessions could not be read' : 'scan failed'}
302    </Text>
303  )
304
305  return $.widgets.card({
306    beneath,
307    width,
308    title: 'Ledger',
309    note: held.name,
310    body: isEmpty ? (
311      <Box flexDirection="column">
312        {EMPTY.flatMap((sentence, at) => wrapped(sentence, inner).map(row => ({ row, isDim: at > 0 }))).map(({ row, isDim }, at) => (
313          <Text key={`empty-${at + 1}`} dimColor={isDim} wrap="truncate-end">
314            {row}
315          </Text>
316        ))}
317        {fault}
318      </Box>
319    ) : (
320      <Box flexDirection="column">
321        {isLong ? (
322          <Text wrap="truncate-end">
323            <Text bold>{money(total)}</Text>
324            {top.gap}
325            <Text dimColor>{top.right}</Text>
326          </Text>
327        ) : (
328          <Text bold wrap="truncate-end">
329            {money(total)}
330          </Text>
331        )}
332        {!isLong && (
333          <Text wrap="truncate-end">
334            {count}
335          </Text>
336        )}
337        {isLong ? (
338          <Text wrap="truncate-end">
339            {spent}
340            {from.gap}
341            <Text dimColor>{from.right}</Text>
342          </Text>
343        ) : (
344          <Text wrap="truncate-end">
345            now {money(mine)}
346          </Text>
347        )}
348        {unpriced > 0 && (
349          <Text dimColor wrap="truncate-end">
350            {isLong ? `${unpriced} without a cost record` : `${unpriced} no record`}
351          </Text>
352        )}
353        {long > 0 && (
354          <Text dimColor wrap="truncate-end">
355            {isLong ? `${long} too long to read` : `${long} too long`}
356          </Text>
357        )}
358        {fault ||
359          (held.scannedAt === 0 && (
360            <Text dimColor wrap="truncate-end">
361              {isLong ? '/ledger-widget scan adds saved ones' : 'scan adds more'}
362            </Text>
363          ))}
364      </Box>
365    ),
366  })
367}
368
369export const register: Register = on => {
370  on('session.start', async ($, e, next) => {
371    await $.command.register({
372      name: 'ledger-widget',
373      description: 'Toggle the Ledger card, or scan, show or clear what the project has cost',
374      argumentHint: '[on|off|scan|show|clear]',
375    })
376    if ((await $.store.get('isOn')) === true) {
377      await update($, isOn, () => true)
378      await open($)
379    }
380
381    return next(e)
382  })
383
384  on('command.run', { command: 'ledger-widget' }, async ($, e) => {
385    const arg = e.args.trim().toLowerCase()
386    if (arg === 'scan' || arg === 'show' || arg === 'clear') {
387      if (!(await read($, isOn))) return { text: OFF }
388
389      return { text: await (arg === 'scan' ? scan($) : arg === 'show' ? tell($) : wipe($)) }
390    }
391    if (arg !== '' && arg !== 'on' && arg !== 'off') return { text: USAGE }
392
393    const isShown = await update($, isOn, shown => (arg === '' ? !(shown ?? false) : arg === 'on'))
394    await $.store.set('isOn', isShown)
395    if (isShown) await open($)
396
397    return { text: isShown ? 'Ledger on; /widgets places it.' : 'Ledger off.' }
398  })
399
400  on('turn.complete', async ($, e, next) => {
401    const done = await next(e)
402    if (e.agentId === undefined && (await read($, isOn))) await measure($)
403
404    return done
405  })
406
407  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) =>
408    show($, $.ui.resolve(e), await next(e), 'side', e.props.bodyColumns),
409  )
410
411  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) =>
412    e.props.hasSurvey ? next(e) : show($, $.ui.resolve(e), await next(e), 'above', e.props.bodyColumns),
413  )
414
415  on('ui.render', { component: 'PromptHint' }, async ($, e, next) =>
416    show($, $.ui.resolve(e), await next(e), 'below', e.viewport?.columns ?? 80),
417  )
418}
419
hooks/lib.ts 45 lines
1const MIN_CARD = 20
2const BARS = '▁▂▃▄▅▆▇█'
3
4export const fit = (wanted: number, columns: number): number => Math.min(wanted, Math.max(MIN_CARD, columns))
5
6export const plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? '' : 's'}`
7
8export const span = (ms: number): string => {
9  const seconds = Math.max(0, Math.round(ms / 1000))
10  if (seconds < 60) return `${seconds}s`
11  const minutes = Math.floor(seconds / 60)
12  if (minutes < 60) return `${minutes}m ${String(seconds % 60).padStart(2, '0')}s`
13  const hours = Math.floor(minutes / 60)
14  if (hours < 24) return `${hours}h ${String(minutes % 60).padStart(2, '0')}m`
15
16  return `${Math.floor(hours / 24)}d ${hours % 24}h`
17}
18
19export const spark = (values: readonly number[], width: number): string => {
20  const shown = width > 0 ? values.slice(-width) : []
21  const top = Math.max(...shown, 0)
22
23  return shown
24    .map(value => (top <= 0 ? BARS[0] : BARS[Math.min(BARS.length - 1, Math.round((Math.max(0, value) / top) * (BARS.length - 1)))]))
25    .join('')
26}
27
28export const hash = (text: string): number => {
29  let held = 2166136261
30  for (const letter of text) held = Math.imul(held ^ (letter.codePointAt(0) ?? 0), 16777619)
31
32  return held >>> 0
33}
34
35export const shade = (color: number, factor: number): number =>
36  (Math.round((color >> 16) * factor) << 16) |
37  (Math.round(((color >> 8) & 255) * factor) << 8) |
38  Math.round((color & 255) * factor)
39
40export const folder = (path: string): string => {
41  const flat = path.replaceAll('\\', '/').replace(/\/+$/, '')
42
43  return /^[a-z]:/i.test(flat) ? flat.toLowerCase() : flat
44}
45
types/index.d.ts 19 lines
1export type LedgerSwitch = boolean
2
3declare module 'claude-code' {
4  interface PluginState {
5    'ledger-widget': {
6      isOn: LedgerSwitch
7      view: {
8        key: string
9        name: string
10        roots: string[]
11        id: string
12        sessions: Record<string, { usd: number | null; at: number; size: number; isOurs: boolean }>
13        scannedAt: number
14        fault: boolean
15      }
16    }
17  }
18}
19