SLOPSHOPPER

usage-panel

The usage panel in a sidebar inside Claude Code: this session, today, the last 30 days, projects, top sessions, the day's costliest turns with why each was…

panebandspinnercommandtoastprocess
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · usage-panel
│ ┃ Usage ✕ › fix the failing auth test and add an audit log call │ ┃ [ Hide ] │ ┃ Usage ⏺ Read(src/auth.ts) │ ┃ Starting the usage panel for this session… ⎿ Read 6 lines │ ┃ The first figures take up to a minute: ⏺ Update(src/auth.ts) │ ┃ ccusage reads every transcript once. ⎿ 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 │ │ › /usage-panel │ │ ⟨Claude Code's own drawing⟩ [ Show usage sidebar ] ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
⟨Claude Code's own drawing⟩ [ Show usage sidebar ]
Pane · Usage · while holding a tool call
[ Hide ] Usage Starting the usage panel for this session… The first figures take up to a minute: ccusage reads every transcript once.
README

Claude Code Cost Sidebar

A live cost and usage panel for Claude Code.

[!TIP]

⚡ One-line setup: let Claude Code install it

Copy this line (the button at its right) and paste it into a terminal on a Mac:

claude "$(curl -fsSL https://raw.githubusercontent.com/andrewbakercloudscale/claude-code-cost-sidebar/main/SETUP_PROMPT.md)"

Claude Code opens with the setup prompt: it checks what is needed, installs, verifies, and tells you what it changed. No sudo. The prompt it runs is SETUP_PROMPT.md; already in a session, paste that file's text instead.

Or install it yourself. Paste this into a terminal on a Mac:

D="$HOME/claude-code-cost-sidebar"
if [ -d "$D/.git" ]; then git -C "$D" pull --ff-only; else git clone https://github.com/andrewbakercloudscale/claude-code-cost-sidebar.git "$D"; fi \
  && bash "$D/claude-panel-setup.sh"

Then start a new Claude Code session and the sidebar opens by itself. It needs Claude Code 2.1.287 or later, git, jq and Node.js (Requirements). Keep the ~/claude-code-cost-sidebar folder: the sidebar is installed from it. Pasting the same lines again updates it.

Uninstall. One paste removes everything setup installed, then the folder:

curl -fsSL https://raw.githubusercontent.com/andrewbakercloudscale/claude-code-cost-sidebar/main/claude-panel-uninstall.sh | bash \
  && rm -rf "$HOME/claude-code-cost-sidebar"

What it removes, and a dry run that only lists it, are under Uninstall.

Live, always-visible cost and token tracking for Claude Code, as a mod: a sidebar Claude Code itself draws beside the transcript, so you can watch what a coding agent is actually costing you, turn by turn, instead of finding out at the end of the month.

<table> <tr> <td valign="top"><img src="docs/sidebar-top.png" alt="The top of the usage sidebar: this session's model, cost and burn rate, its context as one bar by part against Claude Burst's compaction limit, graphs of context, cost and cache per turn, the turn table with a pauseless compaction's Started and Finished rows, this Mac's proxy state and licence, and Plan Utilisation: how much of the 5-hour and weekly limits is used" width="400"></td> <td valign="top"><img src="docs/sidebar-scrolled.png" alt="The usage sidebar scrolled down: today against a typical day by hour and the 5h block, sessions today and the day's costliest turns, the last 30 days by day and by model, and spend by project" width="400"></td> </tr> <tr> <td align="center"><sub>What a session opens with</sub></td> <td align="center"><sub>Scrolled down</sub></td> </tr> </table>

<sub>Every figure in the screenshots is made up. They are drawn by the mod's own code from invented numbers (docs/render-screenshots.mjs); the whole sidebar in one picture is docs/usage-sidebar.png.</sub>

This came out of a simple problem: AI coding agents burn tokens and money per turn, per session, per day, and none of that is visible while you're working. You only find out later, from a dashboard or an invoice, by which point the expensive session is long over and you've learned nothing you can act on. This repo is the fix: a live panel that sits next to your session and updates every few seconds.

Companion tool: Claude Burst. A local gateway for Claude Code (subscription-first routing with failover, pauseless compaction, session coordination, a dashboard). Each works without the other. Together, the sidebar shows the context Burst really sends, how much of your plan's 5-hour and weekly limits is used (with a warning as one gets close), and marks every pauseless compaction as it happens: see Pauseless compaction.

What needs Claude Burst, and is left out without it:

  • the limit rows in Plan Utilisation and the warning as a limit gets close;
  • the Pauseless Compaction, Compaction Strategies and Overflow to Secondary savings tables;
  • the context bar by part, the compaction line on it, and Uncompacted Size with compacting… beside it while a compaction runs;
  • Proxy State, the dashboard button and the * Async Compaction ... * rows in Turns.

Everything else (the session, its turns, today, the week, projects) is read from Claude Code's own transcripts.

The same panel for OpenCode lives in opencode-cost-usage-panel: the two were one repo until they were split apart, which is why the design notes here and there cross-reference each other.

Full write-up and motivation: AI coding costs are guesswork without this: instrumenting OpenCode and Claude Code

What you get

The sidebar: a Claude Code mod (2.1.287 and later)

A mod is a Claude Code plugin that draws inside the session. On a Claude Code that loads mods, setup installs the usage-panel mod (mods/usage-panel), and every new session opens the panel as a sidebar docked to the right of the transcript. Nothing is typed into your terminal, no Accessibility permission is needed and it works in any terminal: Claude Code draws it. Before the mod, the panel was a Ghostty split that a launcher opened by typing keystrokes; that split is still here for older versions (see The panel).

Each section is its own card, most specific first: this session, its turns, this Mac, Plan Utilisation, Pauseless Compaction (with Claude Burst), today across your sessions, sessions today, the last 30 days, your projects. The sidebar scrolls, so the lower cards are a scroll away, and each can be hidden or moved. Reading the sidebar goes through every card.

Command
/show-cost-panelShow the sidebar in this session, beside the transcript.
/hide-cost-panelHide it in this session. New sessions still open it; /usage-panel unpin stops that.
/usage-panelOpen the sidebar (or focus it). Esc puts you back in the prompt.
/usage-panel unpinStop it opening by itself in new sessions.
/usage-panel pinOpen it in every new session again (the default).
/usage-panel hide <section> / show <section>Hide a section, or bring it back. Sections: session, turns, mac, plan, savings, today, sessions, days, projects.
/usage-panel up / down / top / bottom <section>Move a section. The layout is kept for every new session.
/usage-panel sections / resetShow the current order (hidden ones in brackets), or go back to the default.
v (in the sidebar)With Claude Burst installed: open its dashboard, or its support console when the dashboard is down. The same button is in the This Mac card to click.

The sidebar has a Hide button at its top right, which does what /hide-cost-panel does. While it is closed there are two ways back, neither of them in a session that never had a sidebar (the pin is off and nothing opened it):

  • The line under the prompt ends with /show-cost-panel for the usage sidebar. It is text, not a button (that line takes only plain dim text from a mod), so type the command. On a narrow terminal Claude Code cuts it where the row ends.
  • A Show usage sidebar button sits in the band above the prompt and opens the sidebar beside the session. Claude Code lets that band be folded to one line (plugin panel hidden · ctrl+x ctrl+a or click to show, by its [-] or ctrl+x ctrl+a), and the button goes with it, which is why the line under the prompt says the same.

<img src="docs/sidebar-hidden.png" alt="The sidebar hidden, twice. With the band above the prompt open: a Show usage sidebar button over the prompt. With it folded away: the line plugin panel hidden, ctrl+x ctrl+a or click to show. In both the line under the prompt ends with /show-cost-panel for the usage sidebar" width="760">

<sub>Illustration: Claude Code draws the band, the prompt and the line under it; this is a copy of how they look.</sub>

The numbers are the panel's own, not a second implementation: for each session the mod starts ccusage-panel.sh without a terminal (PANEL_HEADLESS=1, via ~/.local/bin/ccusage-panel-mod-start), and it runs its usual two refresh tiers and writes what it would have drawn, as numbers, to ~/.cache/ccusage-panel-cache/mod/<session id>.json. The mod reads that file every 5 seconds. When the session ends the mod stops saying it is there, and the headless panel exits by itself 90 seconds later. The floating alerts over Ghostty still come from it.

While the mod is installed the Ghostty split below stands aside. Set CLAUDE_PANEL_SPLIT=true in the options file to have the split as well, or CLAUDE_PANEL_MOD=no bash claude-panel-setup.sh to install without the mod.

Reading the sidebar

Every dollar figure is tokens counted on this Mac, priced at pay-as-you-go API rates. On a Pro or Max plan that is a measure of use, not a bill. The top line of the sidebar reads live · 14:19, the time the figures were last written; it turns to a red stopped 4m ago when they are more than 3 minutes old.

Colours mean the same thing everywhere: green is normal, yellow is raised, red is high, purple is far out of range, and cyan marks "this one" (this session, this hour, today, this project).

Session

<img src="docs/card-session.png" alt="The Session card" width="460">

On screenWhat it is
*e7d21 · my-appThe last five characters of the session id, and the folder it runs in.
Opus 5.5The model of the latest turn, read from the transcript.
$14.62What this session has cost so far, coloured against your 7-day average session.
$3.10/hrThis session's burn rate.
149 turnsReplies from the model so far.
2.4× avgThis session against your 7-day average session, shown once it has reached half of it.
ctx bar and 86k/1M 9%How full the context is, against the model's whole window. With Claude Burst this is the context Burst really sends, and a thin red line with an arrow (▕◀) on the bar shows where Burst compacts (Auto Compact at 300k underneath), asked from Burst for the folder the session runs in (GetAutoCompactionThreshold), and marked (Intelligent) when Burst's Intelligent Compaction Mode chose it for that repository; that limit is your setting, not the room there is. The label turns yellow as it nears the line (at Burst's warning level) and red past it. Without Burst, see below.
The coloured parts and their keyWith Burst, what the context is made of, largest first: messages, tool results, system tools, MCP tools, memory files (CLAUDE.md and the like), the system prompt. Light grey is Free: the room left in the window. What is used takes its true share of the bar, so a part smaller than one cell is in the key but not on the bar.
Uncompacted Size: 320kClaude Code's own history, which Burst's compaction never shrinks. The gap to the ctx figure is what Burst saves on every turn. Always shown. Green: nothing compacted yet, it is the ctx figure (within a tenth). Yellow: Burst sends a summary and Claude Code holds more than a tenth above it. Red: it holds 300k or more beside a summary, so opening the session again (--resume, --continue) compacts Claude Code's own copy with Burst's summary, in the background and without a summary request; with Hand Burst's summary to Claude Code turned off on Burst's dashboard it stays yellow.
growthContext size, one bar per turn, oldest on the left. Blue, then yellow past 40% of the model's window and red past 70%. A cyan bar is a turn where the context fell to under 60% of the turn before: a compaction.
$/turnCost, one bar per turn. Yellow is over 2× the median turn, red over 4×. The cyan bar is the turn after a compaction (the same turn as the cyan drop in growth): it wrote the smaller context to the cache once, so it costs more by design and is never shown as a warning or reported as a costly turn.
Lines starting ↗ ◇ ▲ ◴ $ !Insights, at most three, only when there is something to say: how many turns until Burst compacts (or, without Burst, until the context turns amber) at the current growth, the median turn, a turn that cost over 4× the median, a session over 3× your average, a cache hit rate under 85%. ◴ is a turn made dear by a pause: it came more than five minutes after the one before, read under half its input from the cache (the cache had expired) and cost at least twice the median. It reads Turn 212 came after a 26m pause and read 4% from cache: $0.90 against a $0.05 median.
A line starting ▤With Claude Burst, one more: it names the part that is half or more of a context of 100k and up, e.g. Tool results are 65% of the context sent.
A limit Burst learned, and a history worth compacting

<table> <tr> <td valign="top"><img src="docs/card-session-intelligent.png" alt="The top of the sidebar with its Hide button, and a Session card whose limit reads Auto Compact at 240k (Intelligent) in cyan" width="400"></td> <td valign="top"><img src="docs/card-session-held.png" alt="A Session card with Uncompacted Size: 539k in red and compacting… beside it" width="400"></td> </tr> <tr> <td align="center"><sub><code>(Intelligent)</code>: Burst chose this limit for the repository</sub></td> <td align="center"><sub><code>compacting…</code>, while a compaction runs</sub></td> </tr> </table>

compacting… is beside Uncompacted Size while a compaction of this session's history is running, from the moment it starts until it stands or is skipped, and at no other time. There is no button: Claude Burst's burst-session mod compacts Claude Code's own history by itself once it holds 800k, with the summary Burst already wrote (no summary request, no pause), and /compact-async-full does it by hand at any size. A sidebar that drew a button from 500k, with a band crossing its label, read as a compaction always running (removed in mod 1.20.0).

The context bar without Claude Burst

<img src="docs/card-session-no-burst.png" alt="The Session card without Claude Burst: the ctx bar at 522k, 52% of a 1M window, in amber, ticks named expensive from 400k and wasteful from 700k, and a line saying it is getting expensive, with /compact and /clear" width="460">

Nothing compacts for you, so the bar is a traffic light on the transcript's own context, and it tells you when to act.

Context, as a share of the model's windowOn a 1M windowColourWhat the card says
Under 40%under 400kGreenNothing, or Grows 3k/turn: amber (400k) in ~40 turns.
40% to 70%400k to 700kAmberGetting expensive: every turn re-sends 522k. /compact, or /clear at a break in the work.
Over 70%over 700kRedWasteful: every turn re-sends 760k. /compact now, or /clear and start fresh.
  • The window is the model's, read from the transcript, so on a 200k model the same lines sit at 80k and 140k.
  • The two ticks on the bar are those lines, named underneath in tokens: expensive from 400k, wasteful from 700k.
  • Why it matters: every turn sends the whole context again. Cached, that is cheap per token but not free, and one pause that lets the cache expire re-bills all of it at full price.

Turns

<img src="docs/card-turns.png" alt="The Turns card: the per-turn table with a pauseless compaction's rows" width="460">

The last 12 turns of this session, newest first. Beside the heading, both across every session: Avg API: $0.12 is today's average cost per turn (one turn is one API reply: today's turns and what they cost, read from today's transcripts), and All: $4.10/hr is the burn rate of the current 5h block.

ColumnWhat it is
TurnThe turn's number in this session.
ModelThe model that answered, per turn, from the transcript. A * after it means the turn was served by Claude Burst's secondary provider; its cache and cost cells then show -- and the gateway's own figure, or ?.
CostThat turn at the model's published rates, cache reads and writes included. ? is a model with no known price.
InputThe whole context sent for that turn (input plus cache reads and writes). Coloured by how full the model's window is: yellow past 30%, red past 50%, purple past 70%. When it shrank by a fifth or more the whole row is blue: a compaction. When it rose by far more than the turn wrote, a * Replayed in full: 102k sent again * row follows: Claude Code sent its whole conversation again, which it does when Anthropic no longer holds the thread (after a pause, say).
CacheThe share of that turn's input read from the prompt cache. Green from 95%, red below, purple below 90%. A low figure straight after a compaction is expected.

<img src="docs/card-turns-replayed.png" alt="The Turns card with turn 118 at 323k, over a row reading Replayed in full: 105k sent again" width="460">

<sub>A turn that sent the whole conversation again.</sub>

A turn that added far more than the session's average, or one past 50% of the window, has its whole row coloured. The * Async Compaction ... * rows are Claude Burst's: see Pauseless compaction.

This Mac

<img src="docs/card-mac.png" alt="The This Mac card" width="460">

On screenWhat it is
Proxy StateWith Claude Burst: where requests are going. PRIMARY (oauth) in green is your subscription; SECONDARY (...) in yellow is the overflow provider; NOT IN USE in red means Burst is installed but out of the path. Absent without Burst.
LicenseThe plan Claude Code is signed in with, or API key when it is metered.
⚠ rowsWith Burst, each of its standing problems (yellow is a warning, red an error), and ⚡ Burst dashboard not answering when it is down.
[ Open Claude Burst dashboard ↗ ]A button: click it, or press v with the sidebar focused.
Red ! rowsThe panel's own errors (a ccusage call that failed, a model it has no price for), so a figure that is missing is explained.

This card sits third so a problem is not under a screen of charts.

Plan Utilisation

<img src="docs/card-plan.png" alt="The Plan Utilisation card: the 5-hour limit at 82% in yellow, the weekly limit at 58% with the week's time at 64% under it, which projects used each limit, the month's use at API rates beside the plan's price, and when the 5-hour limit will be reached at this pace" width="460">

How close you are to your plan's limits. Anthropic states the figures itself, in headers on every reply; Claude Burst keeps the latest and the sidebar reads them from its dashboard every 15 seconds. They are Anthropic's numbers, not an estimate from token counts.

On screenWhat it is
Max (20x)The plan Claude Code is signed in with.
5h bar, 82% resets 16:17 (1h58m)The share of the 5-hour limit used, and when the window resets. Green, yellow from 80%, red from 95%. Any use at all fills at least one cell. In a narrow sidebar the bar moves to a row of its own under the figures, the full width of the card.
weekly bar, plan utilised: 58% resets Thu 02:00The same for the 7-day limit. Any other window Anthropic reports (a per-model weekly limit, for one) gets a row of its own.
time bar, 64% 6 pts under paceUnder the weekly limit, how much of its week has gone by, so the two bars read against each other: a weekly bar shorter than the time bar is use the week can carry. The figure beside it is the gap in points. Green while the limit is at or under the week's time (and up to 9 points over), yellow from 10 points over, red from 25.
$132 at API rates this month ($200 plan)What this month's use would have cost pay-as-you-go, beside the plan's flat price. Shown for Pro ($20), Max 5x ($100) and Max 20x ($200).
What used the weekly limitThe limit's reading shared out by project: the three projects that spent most since the window opened, and the rest as other, each with its part of the limit in points (a project at 31% of a limit that reads 58% used a little over half of what is gone). This session's project is in cyan and each other project has a colour of its own, the same in both blocks. One block for the 5-hour limit and one for the weekly.
Lines starting ↗ !↗: at the pace of this window so far, the limit is reached before it resets, with when and by how much. !: a limit is used up, and when it comes back.

What used a limit is an estimate. Anthropic says how much of a limit is used, not what used it, and does not publish how it weighs tokens against a limit. The sidebar shares the reading out by each project's cost at API rates in Claude Burst's log over the same window, which is the nearest public measure. Read it as "which project", not as a figure to the point.

A warning before you hit a limit. When a limit passes 80%, and again at 95%, the mod raises a toast in the session: 🟡 Plan limit: 81% of the 5h limit used, resets 16:17 (1h58m), with a yellow mark at 80% and a red one (🔴) at 95%. Once per level and window, in every open session, so it is not repeated each minute.

A warning when one day eats the week. On the weekly limit, a day's fair share is a seventh (14%). When one day uses two days' worth (29%), one toast says so: 🟡 Plan pace: 30% of the weekly limit used today, over 2 days' share (29%). 60% used, resets Tue 04:00. Once a day, from whichever session sees it first. The day starts at the first reading after midnight, so use before any session was open that day is not counted.

<img src="docs/toast-limit.png" alt="The toast: usage-panel, a yellow mark, Plan limit: 82% of the 5h limit used, resets 16:17 (1h58m)" width="380">

<sub>Claude Code draws the toast; this picture copies its look.</sub>

  • The limit rows and the toast need Claude Burst: it is what sees Anthropic's replies. Without it the card shows the plan and the month's use only.
  • There are two limits, 5 hours and 7 days. Anthropic reports no monthly one, so there is no monthly row or warning.
  • A reading is from the last reply on this Mac, in any session, so it is as fresh as your last turn anywhere. The last one is kept, so a session that has not had a reply yet still shows it. A window that has reset is dropped until a reply reports the new one.
  • On an API key there is no plan and no card.

Pauseless Compaction

<img src="docs/card-savings.png" alt="The Pauseless Compaction card: $105 saved over the last 30 days from 38 compactions, then a table with a column for the 30 days and one for the last 7: compactions, what was not re-sent, the summaries, the cache rewrites, net savings, the saving per compaction and its share of all spend" width="460">

What Claude Burst's pauseless compaction has saved, across every session on this Mac. Shown only with Burst, once it has compacted something. The figures are Burst's own, read from its dashboard once a minute.

A table, not a chart: one column for Burst's window and, where that is longer than a week, one for the last 7 days (summed from Burst's daily figures). Burst's window is 30 days from 0.20.12; with an older Burst it is 7 days and the table has one column.

On screenWhat it is
30 days, 7 daysThe column headings: the window Burst keeps these figures over, and the last 7 days of it.
$105 savedThe net saving over the window: blue when compaction has paid for itself, red (lost) when it has not yet.

| Blue and re

Source 1 files
hooks/register.js 1953 lines
1// The usage panel in a sidebar inside Claude Code.
2//
3// The numbers are the panel's own: ccusage-panel.sh runs headless for this
4// session (started by ccusage-panel-mod-start) and writes everything it would
5// have drawn in its Ghostty split, as numbers, to
6// ~/.cache/ccusage-panel-cache/mod/<session id>.json. This mod reads that file
7// and draws it: the same figures and traffic lights, plus graphs and insights.
8// Nothing is computed twice and no keystrokes are typed anywhere.
9//
10// With Claude Burst on this Mac (the panel's JSON names its dashboard), the
11// session's one ctx bar is Burst's: the context it really sends, by part,
12// against its compaction limit. Burst's standing problems sit in This Mac.
13//
14// Also with Burst: Plan Utilisation, the share of the plan's 5-hour and weekly
15// limits used, from the limit headers on Anthropic's replies (Burst keeps the
16// latest for about a minute), with a toast when a limit is close.
17//
18// /usage-panel opens or focuses the sidebar; /usage-panel pin opens it in
19// every new session (the default), /usage-panel unpin stops that. (/usage
20// itself is Claude Code's own.)
21
22const PANE = 'usage'
23const COMMAND = 'usage-panel'
24const SHOW_COMMAND = 'show-cost-panel'
25const HIDE_COMMAND = 'hide-cost-panel'
26const COLUMNS = 58 // the sidebar's width to start with; dragging it wins
27const READ_MS = 5000 // the panel writes every 10s; reading at 5s halves the lag
28const FEED_MS = 30000 // keeps the headless panel alive; it stops after 90s without
29const STALE_S = 180 // older than this, the feed has stopped
30const LIMITS_MS = 15000 // the plan's limits: Burst keeps only its last 20 replies
31const EXTRA_MS = 60000 // Burst's slower figures
32const LIMITS_KEY = 'limits'
33// The context without Claude Burst, as a share of the model's window: green
34// under 40%, amber to 70%, red beyond (400k and 700k of a 1M window). Every
35// turn re-sends the whole context, so past these it is time to /compact or
36// /clear by hand.
37const CTX_AMBER = 0.4
38const CTX_RED = 0.7
39const LIMIT_WARN = 0.8 // a toast when a plan limit passes this, and again at
40const LIMIT_ALARM = 0.95
41const DAY_KEY = 'weekday' // the store's key for today's share of the weekly limit, shared by every session
42const PAUSE = 300 // seconds idle after which the prompt cache has expired
43const DAY_SHARES = 2 // a toast when one day uses this many days' worth of the weekly limit
44const PIN_KEY = 'pinned'
45const LAYOUT_KEY = 'layout'
46// The sidebar's sections, most specific first. This Mac (proxy state,
47// licence, Burst's standing problems, its dashboard button) is third, under
48// the turn table: a problem there must not sit below a screen of charts.
49// Plan Utilisation is next: how close the plan's limits are. Then, with
50// Claude Burst, what its pauseless compaction has saved.
51export const SECTIONS = ['session', 'turns', 'mac', 'plan', 'savings', 'today', 'sessions', 'days', 'projects']
52
53let sid = ''
54let home = ''
55let cwd = ''
56let data = null // the panel's last mod/<sid>.json
57let raw = ''
58let paneBg = '' // the terminal's background beside the pane, from Ghostty Dock; '' leaves Claude Code's
59let feedError = ''
60let pinned = true
61// The sidebar has been open in this session: where it is then closed, a
62// button above the prompt brings it back. A session that never had it (the
63// pin is off) is left without one.
64let wanted = false
65// The sidebar is drawn: kept here as it opens and closes, since the button
66// is drawn from it and a drawing asks the engine nothing.
67let up = false
68// It was opened and waits undrawn, on a terminal too narrow for a sidebar
69// nobody asked for: it is up once it is first drawn.
70let waiting = false
71let compacting = false // a compaction of this session's history is running
72let layout = null // { order, hidden } as the person left it
73let burst = null // { down, mod }: Burst's /api/mod answer; null without Burst
74let burstRaw = ''
75let limits = null // [{ key, util, reset }]: the plan's limits, as Anthropic last reported them
76let extra = null // { saved, secondary, warn, comp, auto }: Burst's slower figures, the percent of its limit it warns at, and this folder's compaction limit
77const warned = {} // limit window and reset time -> the level already toasted
78
79// A stored layout made whole: unknown names dropped, sections added since
80// it was saved put back in their default place.
81export function layoutOf(l) {
82  const order = (l && Array.isArray(l.order) ? l.order : []).filter((x) => SECTIONS.includes(x))
83  for (const x of SECTIONS) {
84    if (order.includes(x)) continue
85    const before = SECTIONS.slice(0, SECTIONS.indexOf(x)).reverse().find((y) => order.includes(y))
86    order.splice(before ? order.indexOf(before) + 1 : 0, 0, x)
87  }
88  const hidden = (l && Array.isArray(l.hidden) ? l.hidden : []).filter((x) => SECTIONS.includes(x))
89  return { order, hidden: [...new Set(hidden)] }
90}
91
92// "/usage-panel hide today", "show", "up", "down", "top", "bottom", "reset":
93// the new layout, or a string saying what was wrong.
94export function relayout(l, verb, name) {
95  const lay = layoutOf(l)
96  if (verb === 'reset') return layoutOf(null)
97  if (!SECTIONS.includes(name)) return 'Sections: ' + SECTIONS.join(', ')
98  const i = lay.order.indexOf(name)
99  const move = (j) => { lay.order.splice(i, 1); lay.order.splice(Math.max(0, Math.min(lay.order.length, j)), 0, name) }
100  if (verb === 'hide') lay.hidden = [...new Set([...lay.hidden, name])]
101  else if (verb === 'show') lay.hidden = lay.hidden.filter((x) => x !== name)
102  else if (verb === 'up') move(i - 1)
103  else if (verb === 'down') move(i + 1)
104  else if (verb === 'top') move(0)
105  else if (verb === 'bottom') move(SECTIONS.length)
106  return lay
107}
108
109export function register(on) {
110  on('session.start', async ($, e, next) => {
111    sid = await $.session.id()
112    home = (await $.env.get('HOME')) || ''
113    cwd = (e && e.cwd) || (await $.session.cwd()) || home
114    try {
115      layout = (await $.store.get(LAYOUT_KEY)) || null
116    } catch (err) {
117      // No stored layout: the default.
118    }
119    try {
120      const v = await $.store.get(PIN_KEY)
121      if (v === false) pinned = false
122    } catch (err) {
123      // No stored choice yet: pinned.
124    }
125    await feed($)
126    await read($)
127    await readBackground($)
128    await readBurst($)
129    await readLimits($)
130    await readExtras($)
131    $.clock.every(FEED_MS, async () => { await feed($) })
132    $.clock.every(LIMITS_MS, async () => { if (await readLimits($)) $.ui.invalidate('ui.render') })
133    $.clock.every(EXTRA_MS, async () => { if (await readExtras($)) $.ui.invalidate('ui.render') })
134    $.clock.every(READ_MS, async () => {
135      const changed = await read($)
136      const bg = await readBackground($)
137      if ((await readBurst($)) || changed || bg) $.ui.invalidate('ui.render')
138    })
139    try {
140      await $.command.register({ name: COMMAND, description: 'The usage sidebar: open it; pin / unpin; hide, show, up, down, top, bottom <section>; sections; reset', immediate: true })
141    } catch (err) {
142      $.ui.log('could not add /' + COMMAND + ': ' + err)
143    }
144    // The two things people look for first, under names that say them.
145    try {
146      await $.command.register({ name: SHOW_COMMAND, description: 'Show the cost and usage sidebar in this session', immediate: true })
147      await $.command.register({ name: HIDE_COMMAND, description: 'Hide the cost and usage sidebar in this session', immediate: true })
148    } catch (err) {
149      $.ui.log('could not add /' + SHOW_COMMAND + ' and /' + HIDE_COMMAND + ': ' + err)
150    }
151    if (pinned) {
152      wanted = true
153      try {
154        up = seat(await $.ui.open({ id: PANE, title: 'Usage', columns: COLUMNS }))
155      } catch (err) {
156        $.ui.log('could not open the usage sidebar: ' + err)
157      }
158    }
159    return next(e)
160  })
161
162  // A compaction of the main conversation, from the moment it starts until
163  // it stands or is skipped: "compacting…" beside Uncompacted Size for that
164  // long and no longer. Burst's hand-off at 800k (burst-session) comes
165  // through here as Claude Code's /compact. A precompute installs nothing,
166  // and a subagent's is its own transcript.
167  on('session.compact', async ($, e, next) => {
168    if (e.trigger === 'precompute' || e.agentId) return next(e)
169    compacting = true
170    $.ui.invalidate('ui.render')
171    try {
172      return await next(e)
173    } finally {
174      compacting = false
175      $.ui.invalidate('ui.render')
176    }
177  })
178
179  // Closed by the person's own close mark or key too: the button above the
180  // prompt is drawn from whether the sidebar is up.
181  // The close itself is never held up by it.
182  on('ui.close', ($, e, next) => {
183    const out = next(e)
184    if (e && e.id === PANE) {
185      Promise.resolve(out).then(() => {
186        up = false
187        waiting = false
188        $.ui.invalidate('ui.render')
189      }).catch(() => {})
190    }
191    return out
192  })
193
194  // The way back, on the line under the prompt: the band above it can be
195  // folded away by the person, and the button below with it.
196  on('ui.render', { component: 'PromptHint' }, ($, e, next) => {
197    if (!wanted || up) return next(e)
198    const before = e.props && e.props.tail ? e.props.tail + ' · ' : ''
199    return next({ ...e, props: { ...e.props, tail: before + '/' + SHOW_COMMAND + ' for the usage sidebar' } })
200  })
201
202  // While the sidebar is closed, or waits undrawn on a terminal too narrow
203  // for one nobody asked for: one button, under whatever else is there.
204  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
205    const theirs = await next(e)
206    if (!wanted || up || (e.props && e.props.hasSurvey)) return theirs
207    const { Box, Button } = $.ui.resolve(e)
208    const ours = Box({ flexDirection: 'row', children: [Button({ key: 'usage-show', label: 'Show usage sidebar', onPress: () => showPane($) })] })
209    return theirs ? Box({ flexDirection: 'column', children: [theirs, ours] }) : ours
210  })
211
212  on('command.run', { command: SHOW_COMMAND }, async ($) => {
213    await showPane($)
214    return {}
215  })
216
217  on('command.run', { command: HIDE_COMMAND }, async ($) => {
218    await hidePane($)
219    return {}
220  })
221
222  on('command.run', { command: COMMAND }, async ($, e) => {
223    const arg = String((e && e.args) || '').trim().toLowerCase()
224    if (arg === 'pin' || arg === 'unpin') {
225      pinned = arg === 'pin'
226      try { await $.store.set(PIN_KEY, pinned) } catch (err) { $.ui.log('could not save the pin: ' + err) }
227      $.ui.toast(pinned ? 'Usage panel opens in every new session' : 'Usage panel opens only with /' + COMMAND)
228      if (pinned) await showPane($)
229      return {}
230    }
231    const [verb, name] = arg.split(/\s+/)
232    if (['hide', 'show', 'up', 'down', 'top', 'bottom', 'reset'].includes(verb)) {
233      const next = relayout(layout, verb, name)
234      if (typeof next === 'string') {
235        $.ui.toast(next)
236        return {}
237      }
238      layout = next
239      try { await $.store.set(LAYOUT_KEY, layout) } catch (err) { $.ui.log('could not save the layout: ' + err) }
240      $.ui.invalidate('ui.render')
241      return {}
242    }
243    if (verb === 'sections') {
244      const lay = layoutOf(layout)
245      $.ui.toast(lay.order.map((x) => (lay.hidden.includes(x) ? '(' + x + ')' : x)).join(' · '))
246      return {}
247    }
248    wanted = true
249    up = seat(await $.ui.open({ id: PANE, title: 'Usage', columns: COLUMNS, focus: true, closeOnEscape: true }))
250    $.ui.invalidate('ui.render')
251    return {}
252  })
253
254  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
255    if (e.requestId !== PANE) return next(e)
256    // One that waited for a wider terminal has its place.
257    if (waiting) {
258      waiting = false
259      up = true
260      $.ui.invalidate('ui.render')
261    }
262    const { Box, Text, Button } = $.ui.resolve(e)
263    const width = Math.max(30, Math.min(100, (e.props && e.props.bodyColumns) || (e.viewport && e.viewport.columns) || 50))
264    const now = Math.floor((await $.clock.now()) / 1000)
265    const extras = []
266    // Claude Burst's dashboard, as the pane's [View] was: the dashboard when
267    // it answers, else Burst's support console, which is up when it is not.
268    const b = data && data.burst
269    if (b && b.dashboard) {
270      extras.push(Button({
271        // Not plain: Claude Code draws it as a button, so it reads as one.
272        key: 'burst', label: 'Open Claude Burst dashboard ↗', hotkey: 'v',
273        onPress: async () => {
274          let url = b.dashboard
275          try {
276            const r = await $.http.fetch(b.dashboard)
277            if (!r.ok && b.console) url = b.console
278          } catch (err) {
279            if (b.console) url = b.console
280          }
281          try { await $.process.run(['open', url]) } catch (err) { $.ui.toast('🔴 Could not open ' + url) }
282        },
283      }))
284    }
285    // Beside Uncompacted Size while a compaction runs, and only then.
286    const busy = compacting ? Text({ color: 'yellow', bold: true, children: [COMPACTING] }) : null
287    const rows = panel(Box, Text, data, width, now, feedError, layout, extras, burst, limits, extra, busy)
288    // At the top right, where a close mark is looked for. The button above
289    // the prompt brings the sidebar back.
290    const top = Box({ flexDirection: 'row', justifyContent: 'flex-end', children: [Button({ key: 'usage-hide', label: 'Hide', role: 'dismiss', onPress: () => hidePane($) })] })
291    return Box({ flexDirection: 'column', flexGrow: 1, backgroundColor: paneBg || undefined, children: [top, ...rows] })
292  })
293}
294
295// Opens the sidebar beside the session, where a new session opens it: no
296// focus taken. The button above the prompt goes as it does.
297async function showPane($) {
298  wanted = true
299  try { up = seat(await $.ui.open({ id: PANE, title: 'Usage', columns: COLUMNS })) } catch (err) { $.ui.toast('🔴 Could not open the usage sidebar') }
300  $.ui.invalidate('ui.render')
301}
302
303export const COMPACTING = 'compacting…'
304
305// Whether the sidebar is drawn, from what $.ui.open answered: not when it
306// waits undrawn, on a terminal too narrow for one nobody asked for.
307function seat(opened) {
308  waiting = !!(opened && opened.isPlaced === false)
309  return !waiting
310}
311
312// Closes it, for this session only: /usage-panel unpin stops it opening in
313// new ones.
314async function hidePane($) {
315  // Hidden by hand, so it was had: the button above the prompt is the way back.
316  wanted = true
317  try {
318    await $.ui.close({ id: PANE })
319    up = false
320    waiting = false
321  } catch (err) {
322    $.ui.log('could not close the usage sidebar: ' + err)
323  }
324  $.ui.invalidate('ui.render')
325}
326
327// Starts the headless panel when it is not running, and says this session
328// still wants it.
329async function feed($) {
330  if (!sid || !home) return
331  try {
332    const r = await $.process.run([home + '/.local/bin/ccusage-panel-mod-start', sid, cwd], { timeoutMs: 10000 })
333    feedError = r.exitCode === 0 ? '' : String(r.stderr || 'ccusage-panel-mod-start exited ' + r.exitCode).trim()
334  } catch (err) {
335    feedError = 'ccusage-panel-mod-start: ' + err
336  }
337}
338
339// True when the file changed.
340async function read($) {
341  if (!sid || !home) return false
342  let text = ''
343  try {
344    text = await $.fs.read(home + '/.cache/ccusage-panel-cache/mod/' + sid + '.json')
345  } catch (err) {
346    return false
347  }
348  if (text === raw) return false
349  raw = text
350  try {
351    data = JSON.parse(text)
352  } catch (err) {
353    return false
354  }
355  return true
356}
357
358// Claude Code fills a pane with its theme's own grey, which matches no
359// terminal but a plain dark one: beside a Ghostty Dock session in a light
360// theme, or one coloured from its row, the sidebar was a grey block. The Dock
361// writes each session's terminal background, and the pane is painted in it.
362// True when it changed.
363async function readBackground($) {
364  if (!sid || !home) return false
365  let bg = ''
366  try {
367    bg = String(await $.fs.read(home + '/.local/state/ghostty-dock/backgrounds/' + sid)).trim()
368  } catch (err) {
369    bg = ''
370  }
371  if (!/^#[0-9a-f]{6}$/i.test(bg)) bg = ''
372  if (bg === paneBg) return false
373  paneBg = bg
374  return true
375}
376
377// Burst's own account of this session, from its dashboard. True when what
378// the sidebar draws of it changed. Alerts are not asked for (since = now):
379// they are the burst-session mod's to show.
380async function readBurst($) {
381  const b = data && data.burst
382  if (!b || !b.dashboard || !sid) {
383    const had = burst !== null
384    burst = null
385    burstRaw = ''
386    return had
387  }
388  let next = { down: true, mod: null }
389  try {
390    const since = Math.floor((await $.clock.now()) / 1000)
391    const r = await $.http.fetch(b.dashboard.replace(/\/+$/, '') + '/api/mod?session=' + encodeURIComponent(sid) + '&since=' + since)
392    if (r.ok) {
393      const m = JSON.parse(r.text)
394      next = { down: false, mod: { route: m.route, overflow: m.overflow, primary_failing: m.primary_failing, session: m.session, problems: m.problems, handoff: await handoffOn($) } }
395    }
396  } catch (err) {
397    // Not answering, or not Burst's answer: drawn as down.
398  }
399  const text = JSON.stringify(next)
400  if (text === burstRaw) return false
401  burstRaw = text
402  burst = next
403  return true
404}
405
406// Whether Burst's mod hands Burst's summary to Claude Code: on unless the
407// dashboard's option is off. Read from Burst's own file, as its mod does;
408// /api/mod does not carry it.
409async function handoffOn($) {
410  try {
411    return JSON.parse(await $.fs.read(home + '/.config/claude-burst/mod.json')).handoff !== false
412  } catch (err) {
413    return true
414  }
415}
416
417// The plan's limits: the limit headers on Anthropic's latest reply. Burst
418// keeps the headers of its last 20 replies of any kind, heartbeats included,
419// so a model reply is in the list for about a minute and less with several
420// sessions open. Hence every 15 seconds, and the last reading is kept in the
421// store: a session that has not had a reply yet, or missed one, shows the
422// reading another session took. True when what the sidebar draws changed.
423// A limit that has passed 80% or 95% is toasted, once per level and window.
424async function readLimits($) {
425  const b = data && data.burst
426  if (!b || !b.dashboard || !sid) {
427    const had = limits !== null
428    limits = null
429    return had
430  }
431  const before = JSON.stringify(limits)
432  const now = Math.floor((await $.clock.now()) / 1000)
433  let found = null
434  try {
435    const r = await $.http.fetch(b.dashboard.replace(/\/+$/, '') + '/api/responses')
436    if (r.ok) found = limitsOf(JSON.parse(r.text))
437  } catch (err) {
438    found = null
439  }
440  if (found) {
441    limits = found
442    if (JSON.stringify(found) !== before) {
443      try { await $.store.set(LIMITS_KEY, found) } catch (err) { $.ui.log('could not save the plan limits: ' + err) }
444    }
445    const week = found.find((l) => l.key === '7d' && l.reset > now)
446    if (week) await dayPace($, week, now)
447  } else if (limits === null) {
448    try {
449      const kept = await $.store.get(LIMITS_KEY)
450      if (Array.isArray(kept) && kept.every((l) => l && typeof l.key === 'string' && typeof l.util === 'number')) limits = kept
451    } catch (err) {
452      limits = null
453    }
454  }
455  for (const l of limits || []) {
456    if (!(l.reset > now)) continue
457    const level = l.util >= LIMIT_ALARM ? 2 : l.util >= LIMIT_WARN ? 1 : 0
458    const key = l.key + ':' + l.reset
459    if (level > (warned[key] || 0)) {
460      warned[key] = level
461      limitToast($, l, now)
462    }
463  }
464  return JSON.stringify(limits) !== before
465}
466
467// Burst's slower figures, once a minute: what compaction has saved this
468// session, and what went to the secondary today. True when they changed.
469async function readExtras($) {
470  const b = data && data.burst
471  if (!b || !b.dashboard || !sid) {
472    const had = extra !== null
473    extra = null
474    return had
475  }
476  const base = b.dashboard.replace(/\/+$/, '')
477  const get = async (path) => {
478    try {
479      const r = await $.http.fetch(base + path)
480      return r.ok ? JSON.parse(r.text) : null
481    } catch (err) {
482      return null
483    }
484  }
485  const before = JSON.stringify(extra)
486  const now = Math.floor((await $.clock.now()) / 1000)
487  const state = await get('/api/state')
488  const next = { saved: null, secondary: null, warn: 0, comp: null, auto: null, over: null, by: null, week: null }
489  // Where Burst compacts sessions in this folder: one fixed size, the
490  // person's own for the repository, or the one Intelligent Compaction Mode
491  // has learned for it.
492  const at = cwd ? await get('/api/GetAutoCompactionThreshold?folder=' + encodeURIComponent(cwd)) : null
493  if (at && typeof at.threshold === 'number' && typeof at.source === 'string') {
494    const f = at.failures || {}
495    next.auto = { at: at.threshold, source: at.source, fixed: at.fixed || 0, target: at.target || 0, delay: at.delay_minutes || 0, buffer: at.buffer_percent || 0, lost: (f.unpaid || 0) + (f.summary_failed || 0) + (f.unused || 0), attempts: f.attempts || 0 }
496  }
497  const cfg = state && state.context && state.context.compaction
498  if (cfg && cfg.warn_at_percent > 0) next.warn = cfg.warn_at_percent
499  const iso = (sec) => new Date(sec * 1000).toISOString().slice(0, 19) + 'Z'
500  const stats = state && state.context && state.context.compaction_stats
501  const mine = ((stats && stats.sessions) || []).filter((x) => x && x.session === sid)
502  // Every session Burst has compacted, over its window (30 days; 7 before
503  // Burst 0.20.12).
504  if (stats && stats.compactions > 0) {
505    next.comp = {
506      days: (state.context.window_days > 0 && state.context.window_days) || 7,
507      n: stats.compactions, saved: stats.saved_usd || 0, summary: stats.summary_usd || 0, rewrite: stats.rewrite_usd || 0,
508      net: stats.net_usd || 0, tokens: stats.tokens_not_resent || 0, before: stats.largest_before || 0, after: stats.largest_after || 0,
509      daily: (Array.isArray(stats.daily) ? stats.daily : []).filter((x) => x && typeof x.date === 'string').map((x) => ({ d: x.date, net: x.net_usd || 0, n: x.compactions || 0, saved: x.saved_usd || 0, summary: x.summary_usd || 0, rewrite: x.rewrite_usd || 0 })),
510    }
511  }
512  // The same requests replayed three ways: Claude Code alone (compacts at
513  // default_at), a fixed Compact at (fixed_at), and Burst as it ran. Context
514  // cost only: cache reads plus what the compactions cost.
515  const strat = state && state.context && state.context.compaction_strategies
516  const way = (x) => ({ usd: (x && x.usd) || 0, n: (x && x.compactions) || 0 })
517  if (strat && strat.default && strat.fixed && strat.actual && strat.requests > 0) {
518    next.strat = {
519      days: (state.context.window_days > 0 && state.context.window_days) || 7,
520      defaultAt: strat.default_at || 0, fixedAt: strat.fixed_at || 0,
521      def: way(strat.default), fixed: way(strat.fixed), actual: way(strat.actual),
522      // The cheapest of every fixed size Burst replayed (newer Bursts only).
523      best: strat.cheapest && strat.cheapest.at > 0 && strat.cheapest.usd > 0 ? { at: strat.cheapest.at, ...way(strat.cheapest) } : null,
524      // The replay checked against the bill, since the sizes in force went
525      // on record: what it predicted they would cost, and what they did.
526      // Not under 200 requests, where one compaction is most of the bill.
527      track: strat.track && strat.track.requests >= 200 && strat.track.planned && strat.track.planned.usd > 0
528        ? { since: String(strat.track.since || ''), planned: way(strat.track.planned), actual: way(strat.track.actual), fixed: way(strat.track.fixed) } : null,
529      daily: (Array.isArray(strat.daily) ? strat.daily : []).filter((x) => x && typeof x.date === 'string').map((x) => {
530        const d = way(x.default), f = way(x.fixed), a = way(x.actual)
531        return { d: x.date, defUsd: d.usd, defN: d.n, fixedUsd: f.usd, fixedN: f.n, actualUsd: a.usd, actualN: a.n }
532      }),
533    }
534  }
535  // What the secondary's requests would have cost at the price of the model
536  // Claude Code asked for, against what the secondary charged.
537  const over = state && state.context && state.context.overflow_stats
538  if (over && over.requests > 0) {
539    next.over = {
540      days: (state.context.window_days > 0 && state.context.window_days) || 7,
541      n: over.requests, priced: over.priced || 0, list: over.list_usd || 0, paid: over.paid_usd || 0, saved: over.saved_usd || 0,
542      daily: (Array.isArray(over.daily) ? over.daily : []).filter((x) => x && typeof x.date === 'string').map((x) => ({ d: x.date, net: x.saved_usd || 0, n: x.requests || 0, list: x.list_usd || 0, paid: x.paid_usd || 0 })),
543    }
544  }
545  // What was spent over the same days, every provider, to say what share of
546  // it each saving is.
547  // The same for the last 7 of them where the window is longer.
548  const days = (next.comp && next.comp.daily) || (next.over && next.over.daily) || []
549  const spentSince = async (day) => {
550    const all = day ? await get('/api/usage?range=custom&limit=1&from=' + day.d + '&to=' + iso(now)) : null
551    return ((all && all.by_provider) || []).reduce((a, x) => a + ((x && x.usd) || 0), 0)
552  }
553  const spent = await spentSince(days[0])
554  if (spent > 0) next.spent = spent
555  if (days.length > 7) {
556    const spent7 = await spentSince(days[days.length - 7])
557    if (spent7 > 0) next.spent7 = spent7
558  }
559  if (mine.length > 0) next.saved = { net: mine.reduce((a, x) => a + (x.net_usd || 0), 0), n: mine.reduce((a, x) => a + (x.compactions || 0), 0) }
560  if (state && state.today && state.today.SecondaryRequests > 0) {
561    const day = new Date(now * 1000)
562    const p2 = (n) => String(n).padStart(2, '0')
563    const ymd = day.getFullYear() + '-' + p2(day.getMonth() + 1) + '-' + p2(day.getDate())
564    const usage = await get('/api/usage?range=custom&limit=1&from=' + ymd + '&to=' + ymd + 'T23:59')
565    const others = ((usage && usage.by_provider) || []).filter((x) => x && x.key !== 'anthropic' && x.requests > 0)
566    if (others.length > 0) next.secondary = { requests: others.reduce((a, x) => a + x.requests, 0), usd: others.reduce((a, x) => a + (x.usd || 0), 0), names: others.map((x) => x.key) }
567  }
568  // What used each of the plan's limits, by project: Anthropic's spend in
569  // Burst's log since the window opened. Only the plain windows (5h, 7d): a
570  // per-model one is a part of the weekly.
571  const byRepo = (u) => {
572    const rows = ((u && u.by_repo) || []).filter((x) => x && x.usd > 0).map((x) => ({ name: x.key || 'no folder', usd: x.usd })).sort((a, b) => b.usd - a.usd)
573    return rows.length > 0 ? { rows: rows.slice(0, 8), total: rows.reduce((a, x) => a + x.usd, 0) } : null
574  }
575  for (const l of limits || []) {
576    const len = windowSeconds(l.key)
577    if (!/^\d+[hd]$/.test(l.key) || !len || !(l.reset > now) || !(l.util > 0)) continue
578    const found = byRepo(await get('/api/usage?range=custom&limit=1&provider=anthropic&from=' + iso(l.reset - len) + '&to=' + iso(now)))
579    if (found) next.by = { ...(next.by || {}), [l.key]: found }
580  }
581  // And the last 7 days by project, to say when the project that leads the
582  // 30 days is no longer the one that leads the week. With the names Burst
583  // knows, so a project it names differently is not taken for a new one.
584  const week = await get('/api/usage?range=7d&limit=1&provider=anthropic')
585  const found = byRepo(week)
586  if (found) next.week = { ...found, repos: ((week.options && week.options.repos) || []).filter((x) => typeof x === 'string') }
587  extra = next.saved || next.secondary || next.warn || next.comp || next.strat || next.auto || next.over || next.by || next.week ? next : null
588  return JSON.stringify(extra) !== before
589}
590
591// The warning for a limit that is close: longer on screen from 95%.
592function limitToast($, l, now) {
593  // A toast is one colour, the engine's: the level is a coloured mark in
594  // the text, yellow at the warning and red at the alarm.
595  $.ui.toast((l.util >= LIMIT_ALARM ? '🔴 ' : '🟡 ') + 'Plan limit: ' + Math.round(l.util * 100) + '% of the ' + limitName(l.key) + ' limit used, resets ' + when(l.reset, now), { timeoutMs: l.util >= LIMIT_ALARM ? 30000 : 15000 })
596}
597
598// The plan's limits from Burst's list of recent replies: the newest reply
599// that carries Anthropic's utilisation headers, one row per window (5h, 7d,
600// and any other it names), shortest window first. null when none does.
601export function limitsOf(responses) {
602  if (!Array.isArray(responses)) return null
603  const rows = responses.filter((r) => r && r.headers && typeof r.headers === 'object')
604    .sort((a, b) => String(b.time || '').localeCompare(String(a.time || '')))
605  for (const r of rows) {
606    const out = []
607    for (const [name, v] of Object.entries(r.headers)) {
608      const m = /^anthropic-ratelimit-unified-(.+)-utilization$/.exec(name)
609      if (!m || m[1].startsWith('grace')) continue
610      const util = Number(v)
611      if (isNaN(util)) continue
612      out.push({ key: m[1], util, reset: Number(r.headers['anthropic-ratelimit-unified-' + m[1] + '-reset']) || 0 })
613    }
614    if (out.length > 0) return out.sort((a, b) => windowSeconds(a.key) - windowSeconds(b.key) || a.key.localeCompare(b.key))
615  }
616  return null
617}
618
619// "5h" is 18000, "7d" and "7d-opus" 604800; 0 when the name says no length.
620function windowSeconds(key) {
621  const m = /^(\d+)([hd])/.exec(key)
622  return m ? Number(m[1]) * (m[2] === 'h' ? 3600 : 86400) : 0
623}
624
625// "5h", "weekly", "weekly opus".
626// How much of the weekly limit today has used, kept in the store so every
627// session counts the same day once: the first reading of the day is where
628// the day starts (yesterday's last, when there is one in the same week), and
629// what was used before a reset in the middle of the day is carried over.
630// One toast a day, from whichever session sees it first, when the day has
631// used DAY_SHARES days' worth: a week at that pace runs out days early.
632async function dayPace($, l, now) {
633  const t = new Date(now * 1000)
634  const day = t.getFullYear() + '-' + (t.getMonth() + 1) + '-' + t.getDate()
635  let s = null
636  try { s = await $.store.get(DAY_KEY) } catch (err) { s = null }
637  const ok = s && typeof s.day === 'string' && typeof s.base === 'number' && typeof s.last === 'number' && typeof s.reset === 'number'
638  const before = JSON.stringify(s)
639  const sameWeek = ok && Math.abs(l.reset - s.reset) < 3600
640  if (!ok || s.day !== day) s = { day, base: sameWeek ? s.last : l.util, reset: l.reset, carried: 0, last: l.util, warned: false }
641  else if (!sameWeek) s = { ...s, carried: s.carried + Math.max(0, s.last - s.base), base: 0, reset: l.reset }
642  s.last = l.util
643  const used = (s.carried || 0) + Math.max(0, l.util - s.base)
644  if (!s.warned && used >= DAY_SHARES / 7) {
645    s.warned = true
646    $.ui.toast('🟡 Plan pace: ' + Math.round(used * 100) + '% of the weekly limit used today, over ' + DAY_SHARES + " days' share (" + Math.round((DAY_SHARES * 100) / 7) + '%). ' + Math.round(l.util * 100) + '% used, resets ' + when(l.reset, now), { timeoutMs: 30000 })
647  }
648  if (JSON.stringify(s) !== before) {
649    try { await $.store.set(DAY_KEY, s) } catch (err) { $.ui.log("could not save today's share of the weekly limit: " + err) }
650  }
651}
652
653function limitName(key) {
654  return key.replace(/^7d/, 'weekly').replace(/[-_]+/g, ' ')
655}
656
657// A time ahead: "16:00 (1h41m)" today, "Thu 02:00" on another day.
658function when(epoch, now) {
659  const t = new Date(epoch * 1000)
660  const same = t.toDateString() === new Date(now * 1000).toDateString()
661  return same ? clock(epoch) + ' (' + hm((epoch - now) / 60) + ')' : DAYS[t.getDay()] + ' ' + clock(epoch)
662}
663const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
664
665// The plan on the panel's License row, and what it costs a month where that
666// is a published flat price. null for an API key, or no row.
667export function planOf(summary) {
668  const line = parseAnsi(summary || '').map((l) => l.text).find((t) => /License:/.test(t))
669  if (!line) return null
670  const label = line.replace(/^.*License:\s*/, '').trim()
671  if (!label || /^API key/.test(label)) return null
672  const price = /^Max \(20x\)/.test(label) ? 200 : /^Max \(5x\)/.test(label) ? 100 : /^Pro\b/.test(label) ? 20 : 0
673  return { label, price }
674}
675
676// ---- the sidebar -------------------------------------------------------------
677
678const TIER = { green: 'green', yellow: 'yellow', red: 'red', purple: 'magenta', cyan: 'cyan' }
679const ACCENT = 'cyan'
680const BLOCKS = ' ▁▂▃▄▅▆▇█'
681
682export function panel(Box, Text, d, width, now, feedError, layout, extras = [], burst = null, limits = null, extra = null, busy = null) {
683  const T = (children, props = {}) => Text({ ...props, children: Array.isArray(children) ? children : [children] })
684  const rows = []
685  if (!d) {
686    rows.push(T('Usage', { bold: true, color: ACCENT }))
687    rows.push(T('Starting the usage panel for this session…', { dimColor: true }))
688    rows.push(T('The first figures take up to a minute: ccusage reads every transcript once.', { dimColor: true, wrap: 'wrap' }))
689    if (feedError) rows.push(T(feedError, { color: 'red', wrap: 'wrap' }))
690    return rows
691  }
692  const W = width
693  const age = Math.max(0, now - (d.at || now))
694  const stale = age > STALE_S
695
696  // Header
697  rows.push(Box({
698    flexDirection: 'row', justifyContent: 'space-between', children: [
699      T('◆ Usage', { bold: true, color: ACCENT }),
700      T(stale ? 'stopped ' + ago(age) : 'live · ' + clock(d.at), { color: stale ? 'red' : undefined, dimColor: !stale }),
701    ],
702  }))
703  if (feedError) rows.push(T(feedError, { color: 'red', wrap: 'wrap' }))
704
705  // Most specific first: this session, then today across sessions, then the
706  // last 30 days, then this Mac's set-up. Each block's insights sit under it.
707  // The order, and which are shown, is the person's (see layoutOf).
708  const tips = insights(d, now, limits, extra, burst)
709  const notes = (scope) => tips.filter((t) => t.scope === scope).map((t) =>
710    Box({ flexDirection: 'row', children: [T((t.icon || '•') + ' ', { color: TIER[t.tier] || ACCENT }), T(t.text, { wrap: 'wrap' })] }))
711  // Each section is a card: a rounded border, its heading inside, so where
712  // one ends and the next starts is plain. The border and padding take 4.
713  const IW = Math.max(26, W - 4)
714  const draw = {
715    session: () => [...sessionSection(Box, T, d, IW, burst, extra && extra.warn, busy), ...notes('session'), ...notes('burst')],
716    mac: () => {
717      const foot = [...footer(Box, T, d), ...burstRows(Box, T, burst), ...extras]
718      return foot.length > 0 ? [heading(T, 'This Mac'), ...foot] : []
719    },
720    turns: () => turnsTable(T, d),
721    plan: () => {
722      const body = planSection(Box, T, d, IW, now, limits, extra)
723      return body.length > 0 ? [...body, ...notes('plan')] : []
724    },
725    savings: () => {
726      const out = []
727      for (const part of [savingsSection(Box, T, IW, extra), strategiesSection(Box, T, IW, extra), overflowSection(Box, T, IW, extra)]) {
728        if (part.length === 0) continue
729        if (out.length > 0) out.push(T(' '))
730        out.push(...part)
731      }
732      return out
733    },
734    today: () => [...todaySection(Box, T, d, IW, now), ...notes('today')],
735    sessions: () => topSection(Box, T, d, IW),
736    days: () => daysSection(Box, T, d, IW),
737    projects: () => [...projectsSection(Box, T, d, IW), ...notes('general')],
738  }
739  const lay = layoutOf(layout)
740  for (const id of lay.order) {
741    if (lay.hidden.includes(id)) continue
742    const body = draw[id]()
743    if (body.length > 0) rows.push(card(Box, id, body))
744  }
745  if (lay.hidden.length > 0) rows.push(T('Hidden: ' + lay.hidden.join(', ') + ' (/' + 'usage-panel show <name>)', { dimColor: true, wrap: 'wrap' }))
746  return rows
747}
748
749function card(Box, key, children) {
750  return Box({ key, flexDirection: 'column', borderStyle: 'round', borderColor: 'gray', borderDimColor: true, paddingLeft: 1, paddingRight: 1, children })
751}
752
753// A card's title, bold, with a short dim note after it.
754function heading(T, title, note) {
755  return T([T(title, { bold: true, color: ACCENT }), note ? T('  ' + note, { dimColor: true }) : ''], { wrap: 'truncate-end' })
756}
757
758// A smaller heading inside a card, for one chart of several: in bold, under
759// a blank row, so the charts do not run into each other.
760function sub(Box, T, title, note) {
761  return Box({ flexDirection: 'row', marginTop: 1, children: [T([T(title, { bold: true, color: ACCENT }), note ? T('  ' + note, { dimColor: true }) : ''], { wrap: 'truncate-end' })] })
762}
763
764// A colour for each bar in a chart of projects or sessions, by its place.
765// Cyan is this session's and grey the rest's, so neither is here.
766const SHARE_COLOURS = ['blue', 'green', 'yellow', 'magenta']
767function colourer() {
768  const seen = new Map()
769  return (name) => {
770    if (!seen.has(name)) seen.set(name, SHARE_COLOURS[seen.size % SHARE_COLOURS.length])
771    return seen.get(name)
772  }
773}
774
775// ---- this session
776
777function sessionSection(Box, T, d, W, burst, warnPct, busy) {
778  const s = d.session || {}
779  // A long folder loses its start, not its end: the end is what tells two
780  // repos apart.
781  const id = d.sid ? '*' + d.sid.slice(-5) : ''
782  const room = W - 'Session:'.length - 2 - (id ? id.length + 3 : 0)
783  const out = [heading(T, 'Session:', [id, s.folder ? cut(s.folder, Math.max(4, room)) : ''].filter(Boolean).join(' · '))]
784  // Before the first reply the panel knows no model ("Unknown") and prices
785  // nothing ($0): say so rather than draw that as a reading.
786  const turnsSoFar = (d.turns && d.turns.turns) || []
787  const sent = burst && !burst.down && burst.mod && burst.mod.session && burst.mod.session.context > 0 ? burst.mod.session : null
788  if (turnsSoFar.length === 0 && !(s.ctx > 0) && !sent) {
789    out.push(T('No reply yet: the figures start with the first one.', { dimColor: true, wrap: 'wrap' }))
790    return out
791  }
792  const turns = (d.turns && d.turns.turns) || []
793  const n = turns.length > 0 ? turns[turns.length - 1][0] : 0
794  out.push(T([
795    T(s.model || 'model unknown', { color: TIER[s.model_tier], bold: true }),
796    T('  '),
797    T(s.cost == null ? '--' : money(s.cost, 2), { bold: true, color: TIER[s.tier] }),
798    T(s.rate == null ? '' : '  ' + money(s.rate, 2) + '/hr', { color: TIER[s.rate_tier] }),
799    T(n ? '  ' + n + (n === 1 ? ' turn' : ' turns') : '', { dimColor: true }),
800    s.avg_session > 0 && s.cost != null && s.cost >= s.avg_session * 0.5 ? T('  ' + ratio(s.cost / s.avg_session) + ' avg', { dimColor: true }) : '',
801  ], { wrap: 'truncate-end' }))
802
803  // One context bar. With Claude Burst it is Burst's: what is really sent
804  // (after Burst's own compaction, which Claude Code's figure does not know
805  // about), by part, against the model's window, with Burst's warning and
806  // compaction lines marked. Otherwise the
807  // panel's gauge against the model's window, its colour thresholds as ticks.
808  if (sent) {
809    out.push(...sentBar(Box, T, sent, W, s.win || 0, warnPct, busy))
810    if (s.compacting) out.push(T('  ⟳ a summary is ready: the next prompt compacts', { color: 'cyan' }))
811    else if (sent.state === 'warning') out.push(T('! Close to the limit: ' + limitLabel(sent) + '.', { color: 'yellow', wrap: 'wrap' }))
812    // "compacted" is not said: it stays for the rest of the session and the
813    // bar, the growth chart and the turn table already show it.
814    else if (sent.state && sent.state !== 'ok' && sent.state !== 'compacted') out.push(T('⟳ ' + sent.state, { color: 'cyan', wrap: 'wrap' }))
815  } else if (s.ctx > 0 && s.win > 0) {
816    const pct = (s.ctx * 100) / s.win
817    const label = k(s.ctx) + '/' + k(s.win) + ' ' + Math.round(pct) + '%'
818    const barW = Math.max(6, W - 8 - label.length)
819    const c = pct >= CTX_RED * 100 ? 'red' : pct >= CTX_AMBER * 100 ? 'yellow' : 'green'
820    out.push(Box({
821      flexDirection: 'row', columnGap: 1, children: [
822        T('ctx   ', { dimColor: true }),
823        gauge(T, pct, barW, c, [CTX_AMBER * 100, CTX_RED * 100]),
824        T(label, { color: c }),
825      ],
826    }))
827    // What the two ticks are, in this model's tokens.
828    out.push(Box({
829      flexDirection: 'row', flexWrap: 'wrap', columnGap: 2, children: [
830        T([T('│ ', { color: 'yellow' }), T('expensive from ' + k(s.win * CTX_AMBER), { dimColor: true })]),
831        T([T('│ ', { color: 'red' }), T('wasteful from ' + k(s.win * CTX_RED), { dimColor: true })]),
832      ],
833    }))
834    if (s.compacting) out.push(T('  ⟳ a summary is ready: the next prompt compacts', { color: 'cyan' }))
835  }
836
837  // Context per turn, with compactions marked; cost per turn underneath.
838  if (turns.length >= 3) {
839    const cols = Math.max(10, W - 7)
840    const shown = turns.slice(-cols)
841    const ctxs = shown.map((t) => t[1])
842    const drops = new Set()
843    for (let i = 1; i < shown.length; i++) if (shown[i][1] < shown[i - 1][1] * 0.6) drops.add(i)
844    const win = s.win || 0
845    const ctxColour = (v) => (!win ? 'blue' : v >= win * CTX_RED ? 'red' : v >= win * CTX_AMBER ? 'yellow' : 'blue')
846    out.push(Box({
847      flexDirection: 'row', columnGap: 1, marginTop: 1, children: [
848        T('growth', { dimColor: true }),
849        spark(T, ctxs, (v, i) => (drops.has(i) ? 'cyan' : ctxColour(v)), 0),
850      ],
851    }))
852    const costs = shown.map((t) => (t[4] == null ? 0 : t[4]))
853    const med = median(costs.filter((c) => c > 0))
854    // A row's bars reach the cell's foot and the next row's reach its head,
855    // so stacked directly they read as one shape: a blank row between each.
856    // The turn after a compaction writes the new context to the cache once,
857    // so it costs more by design: cyan like its drop above, never red.
858    out.push(Box({
859      flexDirection: 'row', columnGap: 1, marginTop: 1, children: [
860        T('$/turn', { dimColor: true }),
861        spark(T, costs, (v, i) => (drops.has(i) ? 'cyan' : med > 0 && v > med * 4 ? 'red' : med > 0 && v > med * 2 ? 'yellow' : 'green'), 0),
862      ],
863    }))
864  }
865  return out
866}
867
868// ---- Claude Burst: this session's context as its gateway sends it
869
870// One colour per part, in the gateway's order.
871const PART_COLOURS = {
872  'System prompt': 'ansi256(244)', // mid grey: 237 vanished into a dark terminal
873  'System tools': 'cyan',
874  'MCP tools': 'magenta',
875  'Memory files': 'yellow',
876  'Messages': 'blue',
877  'Tool results': 'green',
878}
879
880// What is left of the bar: light grey, lighter than the system prompt's
881// mid grey and a colour no part has. White glared beside the parts.
882const FREE_COLOUR = 'ansi256(250)'
883
884// Where Burst compacts this session: what GetAutoCompactionThreshold says
885// for this folder, and until it has answered, what the session's own
886// figures carry.
887function compactAt(s) {
888  const a = extra && extra.auto
889  if (a && a.at > 0) return a.at
890  return s && s.compact_at > 0 ? s.compact_at : 0
891}
892
893// Whether the limit is one Intelligent Compaction Mode learned for this
894// repository, not the fixed setting: by GetAutoCompactionThreshold, and
895// until it has answered, by the session's own figures. A learned limit
896// that is the fixed one is the fixed one: Intelligent Compaction Mode goes
897// back to it when compacting sooner does not pay, and "Auto Compact at
898// 300k (Intelligent)" then named a size nobody learned.
899function learnedLimit(s) {
900  const a = extra && extra.auto
901  if (a) return a.source === 'learned' && a.at > 0 && !(a.fixed > 0 && a.at >= a.fixed)
902  return !!(s && s.learned)
903}
904
905// "Auto Compact at 300k", the fixed limit and a learned one alike: a
906// learned one is told apart by its colour and the word beside it.
907function limitLabel(s) {
908  return 'Auto Compact at ' + k(compactAt(s))
909}
910
911// What stands beside the limit when it is learned: Burst's Intelligent
912// Compaction Mode chose it. '' for the fixed one.
913function limitNote(s) {
914  return learnedLimit(s) ? '(Intelligent)' : ''
915}
916
917// The context Burst sends for this session as a stacked bar against the
918// model's window, with a line where Burst compacts (the limit is a setting,
919// not the room there is), a legend under it, and
920// what Claude Code itself still holds when that is more. Without a window
921// the bar is against the compaction limit alone.
922function sentBar(Box, T, s, W, win, warnPct, busy) {
923  const limit = compactAt(s)
924  const warn = limit ? Math.round((limit * (warnPct > 0 && warnPct < 100 ? warnPct : 80)) / 100) : 0
925  const whole = win > limit && win >= s.context
926  const scale = whole ? win : Math.max(limit, s.context)
927  const pct = Math.round((s.context * 100) / scale)
928  const label = k(s.context) + (whole || limit ? '/' + k(scale) + ' ' + pct + '%' : '')
929  const colour = limit && s.context >= limit ? 'red' : warn && s.context >= warn ? 'yellow' : undefined
930  // Largest first, bar and legend alike: what to cut is read off the left.
931  const parts = (s.parts || []).filter((p) => p.tokens > 0).sort((a, b) => b.tokens - a.tokens)
932  const barW = Math.max(6, W - 8 - label.length)
933  const free = scale - s.context
934  let bar
935  {
936    // What is used takes its true share of the bar, so it meets the two
937    // lines where it should; the parts share that, the smallest giving way
938    // when there are more parts than cells (the legend still names them).
939    const used = free > 0 ? Math.max(1, Math.min(barW - 1, Math.round((s.context * barW) / scale))) : barW
940    // Before Burst has the breakdown by part the used share is one block,
941    // on the same bar: the room left and the limit's line look the same.
942    const onBar = parts.length > 0 ? parts.slice(0, used) : [{ tokens: s.context }]
943    const widths = share(onBar.map((p) => p.tokens), used)
944    const cells = []
945    onBar.forEach((p, i) => { for (let n = 0; n < widths[i]; n++) cells.push(['█', p.name ? PART_COLOURS[p.name] : colour || 'blue']) })
946    while (cells.length < barW) cells.push(['█', FREE_COLOUR])
947    // The two lines, over whatever is in that cell: still there once passed.
948    if (whole) {
949      const at = (tokens) => Math.max(1, Math.min(barW - 1, Math.round((tokens * barW) / scale)))
950      const stop = at(limit)
951      // A thin red line with an arrow pointing at it, each drawn on the
952      // colour of the cell it stands in: on the terminal's own background
953      // the line had a dark gap on both sides and cut the bar in two.
954      // The line is on the right edge of the cell before the limit, so it
955      // stands at the limit itself and touches the arrow's cell.
956      if (stop < cells.length) {
957        if (stop > 0) cells[stop - 1] = ['▕', 'red', cells[stop - 1][1]]
958        cells[stop] = ['◀', 'red', cells[stop][1]]
959      }
960    }
961    const segs = []
962    for (const [ch, c, bg] of cells) {
963      const last = segs[segs.length - 1]
964      if (last && last.ch === ch && last.c === c && last.bg === bg) last.text += ch
965      else segs.push({ ch, c, bg, text: ch })
966    }
967    bar = T(segs.map((g) => T(g.text, g.bg ? { color: g.c, backgroundColor: g.bg } : { color: g.c })))
968  }
969  const out = [Box({ flexDirection: 'row', columnGap: 1, children: [T('ctx   ', { dimColor: true }), bar, T(label, { color: colour })] })]
970  if (parts.length > 0) {
971    const key = parts.map((p) => [PART_COLOURS[p.name], p.name + ' ' + k(p.tokens)])
972    // The rest of the bar is room left, in the window or before Burst
973    // compacts: named, last.
974    if (free > 0) key.push([FREE_COLOUR, 'Free ' + k(free)])
975    out.push(Box({
976      flexDirection: 'row', flexWrap: 'wrap', columnGap: 2, children: key.map(([c, text]) =>
977        T([T('■ ', { color: c }), T(text, { dimColor: true })])),
978    }))
979  }
980  if (whole) {
981    out.push(Box({
982      flexDirection: 'row', flexWrap: 'wrap', columnGap: 1, children: [
983        T([T('▕◀ ', { color: 'red' }), T(limitLabel(s), learnedLimit(s) ? { color: 'cyan' } : { dimColor: true })]),
984        ...(limitNote(s) ? [T(limitNote(s), { dimColor: true })] : []),
985      ],
986    }))
987  }
988  // Claude Code's own history, which Burst's compaction never shrinks.
989  // Always said: before the two part it is what Burst sends, and a line that
990  // came and went read as a figure gone missing. Its colour is how far the
991  // two have parted, and what a restart will do about it.
992  const held = Math.max(s.raw || 0, s.context || 0)
993  if (held > 0) {
994    const size = T('Uncompacted Size: ' + k(held), { color: heldColour(s, held) })
995    if (busy) out.push(Box({ flexDirection: 'row', flexWrap: 'wrap', columnGap: 2, children: [size, busy] }))
996    else out.push(size)
997  }
998  return out
999}
1000
1001// `width` cells shared out in proportion, every amount above zero getting at
1002// least one: a part too small for a cell, or the last of the room left, is
1003// still on the bar. What that costs comes off the widest.
1004export function share(amounts, width) {
1005  const total = amounts.reduce((a, b) => a + b, 0)
1006  if (!(total > 0) || width <= 0) return amounts.map(() => 0)
1007  const ideal = amounts.map((a) => (a * width) / total)
1008  const out = ideal.map((x, i) => (amounts[i] > 0 ? Math.max(1, Math.round(x)) : 0))
1009  let sum = out.reduce((a, b) => a + b, 0)
1010  while (sum > width) {
1011    const i = out.indexOf(Math.max(...out))
1012    if (out[i] <= 1) break
1013    out[i]--
1014    sum--
1015  }
1016  while (sum < width) {
1017    let best = 0
1018    out.forEach((_, i) => { if (ideal[i] - out[i] > ideal[best] - out[best]) best = i })
1019    out[best]++
1020    sum++
1021  }
1022  return out
1023}
1024
1025// Where Burst's mod (burst-session, HANDOFF_AT) compacts a session opened
1026// again with the summary Burst already wrote.
1027const HANDOFF_AT = 300000
1028
1029// The colour of Uncompacted Size. Green: Claude Code holds what Burst sends,
1030// nothing has been compacted. Yellow: Burst sends a summary and Claude Code
1031// holds more than a tenth above it. Red: it holds enough that opening the
1032// session again (--resume, --continue) compacts Claude Code's own copy with
1033// that summary, unless the hand-off is turned off on Burst's dashboard.
1034function heldColour(s, held) {
1035  if (!(held > (s.context || 0) * 1.1)) return 'green'
1036  const handoff = !(burst && burst.mod && burst.mod.handoff === false)
1037  return handoff && held >= HANDOFF_AT ? 'red' : 'yellow'
1038}
1039
1040// Burst's rows for This Mac, under the panel's Proxy State: a dashboard that
1041// is not answering, and each problem still standing.
1042function burstRows(Box, T, burst) {
1043  if (!burst) return []
1044  if (burst.down || !burst.mod) return [T('⚡ Burst dashboard not answering', { color: 'red', bold: true, wrap: 'wrap' })]
1045  return (burst.mod.problems || []).map((p) => {
1046    const c = p.severity === 'error' ? 'red' : 'yellow'
1047    return Box({ flexDirection: 'row', children: [T('⚠ ', { color: c }), T(p.title, { color: c, bold: true, wrap: 'wrap' })] })
1048  })
1049}
1050
1051// ---- plan utilisation: the plan's limits, and what the month's use is worth
1052
1053function planSection(Box, T, d, W, now, limits, extra) {
1054  const plan = planOf(d.summary)
1055  const rows = (limits || []).filter((l) => l.reset > now)
1056  const hasBurst = !!(d.burst && d.burst.dashboard)
1057  if (rows.length === 0 && !plan) return []
1058  const out = [heading(T, 'Plan Utilisation', plan ? plan.label : '')]
1059  // Each limit, and under the weekly one how much of its week has gone.
1060  const shown = []
1061  for (const l of rows) {
1062    const pct = Math.round(l.util * 100)
1063    // The weekly row says what its figure is, with the week's time under it.
1064    shown.push({ name: limitName(l.key), pct, label: (l.key === '7d' ? 'plan utilised: ' + pct + '%' : lpad(pct + '%', 4)) + '  resets ' + when(l.reset, now), c: pct >= LIMIT_ALARM * 100 ? 'red' : pct >= LIMIT_WARN * 100 ? 'yellow' : 'green', any: l.util > 0 })
1065    if (l.key === '7d') shown.push(weekGone(l, now))
1066  }
1067  const nameW = Math.max(0, ...shown.map((r) => r.name.length))
1068  // One bar width for every row, so the bars can be compared.
1069  const labelW = Math.max(0, ...shown.map((r) => r.label.length))
1070  // Beside its figures where there is room for a bar worth reading; in a
1071  // narrow sidebar the bar has a row of its own, the card's whole width, and
1072  // the figures no longer wrap under it.
1073  const beside = W - nameW - 2 - labelW
1074  const stacked = beside < LIMIT_BAR_MIN
1075  for (const [i, r] of shown.entries()) {
1076    const name = T(pad(r.name, nameW), { dimColor: !stacked, bold: stacked })
1077    const label = T(r.label, { color: r.c === 'green' ? undefined : r.c, wrap: 'truncate-end' })
1078    // Any use at all is a cell on the bar: 4% of a short one rounded to none.
1079    const bar = (w) => gauge(T, r.any ? Math.max(r.pct, 100 / w) : 0, w, r.c, [])
1080    if (stacked) {
1081      // The week's time sits right under the weekly bar it is read against.
1082      out.push(Box({ flexDirection: 'row', columnGap: 1, marginTop: i > 0 && !r.pace ? 1 : 0, children: [name, label] }))
1083      out.push(bar(W))
1084    } else {
1085      out.push(Box({ flexDirection: 'row', columnGap: 1, children: [name, bar(Math.max(6, beside)), label] }))
1086    }
1087  }
1088  out.push(...limitShares(Box, T, d, W, rows, extra))
1089  if (rows.length === 0) {
1090    out.push(T(hasBurst ? 'No limit reading yet: it comes with the next reply.' : 'How much of the limits is used comes from Claude Burst, which reads it off Anthropic\'s replies.', { dimColor: true, wrap: 'wrap' }))
1091  }
1092  // What the flat price buys: the month's use at pay-as-you-go rates.
1093  if (plan && plan.price > 0 && d.month > 0) {
1094    out.push(Box({
1095      flexDirection: 'row', marginTop: out.length > 1 ? 1 : 0, children: [T([
1096        T(money(d.month), { bold: true }),
1097        // The shorter wording where the longer would wrap.
1098        T((money(d.month) + ' at API rates this month (' + money(plan.price) + ' plan)').length <= W ? ' at API rates this month (' + money(plan.price) + ' plan)' : ' this month at API rates vs ' + money(plan.price), { dimColor: true }),
1099      ], { wrap: 'wrap' })],
1100    }))
1101  }
1102  return out
1103}
1104
1105// How far ahead of the week's time the weekly limit may run, in points,
1106// before its row turns yellow, and red.
1107const PACE_WARN = 10
1108const PACE_ALARM = 25
1109
1110// The share of the weekly window that has gone by, as a row under the
1111// weekly limit: green while the limit is used no faster than the week
1112// passes, yellow from PACE_WARN points ahead of it, red from PACE_ALARM.
1113export function weekGone(l, now) {
1114  const gone = Math.min(1, Math.max(0, 1 - (l.reset - now) / windowSeconds(l.key)))
1115  const pct = Math.round(gone * 100)
1116  const over = Math.round(l.util * 100) - pct
1117  return {
1118    name: 'time', pct, pace: true, any: gone > 0,
1119    label: lpad(pct + '%', 4) + '  ' + (over > 0 ? over + ' pts over pace' : over < 0 ? -over + ' pts under pace' : 'on pace'),
1120    c: over >= PACE_ALARM ? 'red' : over >= PACE_WARN ? 'yellow' : 'green',
1121  }
1122}
1123
1124// The narrowest bar a limit is drawn with beside its figures: under this it
1125// has a row of its own.
1126const LIMIT_BAR_MIN = 16
1127
1128// What used each limit, by project: the limit's reading shared out by each
1129// project's cost at API rates since the window opened. An estimate, and
1130// said to be: Anthropic does not publish how it weighs tokens against a
1131// limit. The three largest and the rest, this session's project in cyan.
1132function limitShares(Box, T, d, W, rows, extra) {
1133  const out = []
1134  const here = (d.session && d.session.folder) || ''
1135  // The same project the same colour in both charts.
1136  const colourOf = colourer()
1137  for (const l of rows) {
1138    const by = extra && extra.by && extra.by[l.key]
1139    if (!by || !(by.total > 0)) continue
1140    const top = by.rows.slice(0, 3)
1141    const rest = by.total - top.reduce((a, x) => a + x.usd, 0)
1142    const list = rest / by.total >= 0.005 ? [...top, { name: 'other', usd: rest, other: true }] : top
1143    const nameW = Math.min(20, Math.max(...list.map((x) => x.name.length)))
1144    const barW = Math.max(4, W - nameW - 6)
1145    // The note gives way before the heading does.
1146    const title = 'What used the ' + limitName(l.key) + ' limit'
1147    const note = title.length + 14 <= W ? 'est. by cost' : title.length + 6 <= W ? 'est.' : ''
1148    out.push(sub(Box, T, title, note))
1149    for (const x of list) {
1150      const pts = (x.usd / by.total) * l.util * 100
1151      const n = Math.max(1, Math.round((x.usd / top[0].usd) * barW))
1152      const mine = !x.other && x.name === here
1153      out.push(Box({
1154        flexDirection: 'row', columnGap: 1, children: [
1155          T(pad(cut(x.name, nameW), nameW), { bold: mine, color: mine ? ACCENT : undefined, dimColor: !!x.other }),
1156          T('█'.repeat(Math.min(n, barW)) + ' '.repeat(Math.max(0, barW - n)), { color: mine ? ACCENT : x.other ? 'gray' : colourOf(x.name) }),
1157          T(lpad(pts < 1 ? '<1%' : Math.round(pts) + '%', 4)),
1158        ],
1159      }))
1160    }
1161  }
1162  return out
1163}
1164
1165// ---- pauseless compaction: what Claude Burst's compaction has saved
1166
1167// Each turn after a compaction sends the summary in place of the history;
1168// the saving is what those turns would have cost with the history still in,
1169// less what the summaries cost to write and the one cache rewrite each
1170// compaction causes. Burst works it out; this draws it.
1171function savingsSection(Box, T, W, extra) {
1172  const c = extra && extra.comp
1173  if (!c || !(c.n > 0)) return []
1174  const out = [heading(T, 'Pauseless Compaction')]
1175  out.push(T([
1176    T(money(Math.abs(c.net)), { bold: true, color: c.net >= 0 ? GAIN : 'red' }),
1177    T(c.net >= 0 ? ' saved' : ' lost', { color: c.net >= 0 ? GAIN : 'red' }),
1178    T('  ' + c.n + (c.n === 1 ? ' compaction' : ' compactions'), { dimColor: true }),
1179  ], { wrap: 'truncate-end' }))
1180  const w = lastWeek(c.daily, c.days)
1181  out.push(...figures(Box, T, c.days, !!w, [
1182    ['Compactions', String(c.n), w && String(w.n)],
1183    ['Not re-sent', money(c.saved, 2), w && money(w.saved, 2), true],
1184    ['Summaries', money(-c.summary, 2), w && money(-w.summary, 2)],
1185    ['Cache rewrites', money(-c.rewrite, 2), w && money(-w.rewrite, 2)],
1186    ['Net savings', money(c.net, 2), w && money(w.net, 2), true],
1187    ['Each', c.n > 0 ? money(c.net / c.n, 2) : '', w && w.n > 0 ? money(w.net / w.n, 2) : '', true],
1188    ['Bill cut by', ofSpend(c.net, extra.spent), w ? ofSpend(w.net, extra.spent7) : '', true],
1189  ]))
1190  out.push(T(' '))
1191  if (c.tokens > 0) {
1192    // On one row where it fits; in a narrow sidebar the largest has its own.
1193    const sent = big(c.tokens) + ' tokens not re-sent'
1194    const largest = c.before > c.after && c.after > 0 ? 'largest ' + k(c.before) + ' → ' + k(c.after) : ''
1195    const one = largest ? sent + ', ' + largest : sent
1196    for (const line of one.length <= W || !largest ? [one] : [sent, 'Largest ' + largest.slice(8)]) out.push(T(line, { dimColor: true, wrap: 'truncate-end' }))
1197  }
1198  const mine = extra.saved
1199  if (mine && mine.n > 0) {
1200    const one = mine.n === 1