ccbar — a quiet status band above the prompt, drawn natively by Claude Code's function hooks: the model and its effort, the repository (GitHub owner/name and…

ccbar is a quiet status band above the prompt, drawn natively by Claude Code's function hooks. Nothing runs outside the session: no statusLine command, no polling process.
Opus 5.5 xhigh · emaballarin/ccplugins ⎇ main (+12 −3) · ██████░░░░░░░░░░░░░░░░░▒ 246k/1M (25%) · Tok Σ 2.4M · Session 9% (4h 21m) · Weekly 27% (2d 3h 7m)
Here █ stands for the used window, ░ for the free track and ▒ for the auto-compaction reserve; the band draws all three as coloured cells, not as these glyphs. Groups are joined by one faint · and packed into rows by measured width; the rate-limit windows (Session, Weekly, and Spend behind a gateway) form one group, joined by a closer ·, so they always wrap together. On a narrower terminal the bar first shrinks from 24 to 16 cells (and further below 36 columns); only then does the band wrap, always between whole groups. Wrapped rows hang under the first row's second segment, unless the indent would cost a row or leave a group too wide for the room beside it: then the whole band wraps flush left. Below about 45 columns the joined limits no longer fit a row and are cut off at its end.
/plugin marketplace add emaballarin/ccplugins
/plugin install ccbar@ccplugins
claude --debug).git, and sh, tail, head, wc and tr (Linux, macOS; head -c is GNU and BSD, not POSIX). Without git the repository group is absent; without the others the token total is.ccbar coexists with a statusLine command such as ccstatusline: that one draws under the prompt, ccbar above it.
Two, in /config (stored under pluginConfigs in settings):
tokens, new by default). new counts new tokens, as described under What it shows. metered adds the cache reads the transcripts record, each response still counted once. It still differs from ccstatusline's Total, which counts each transcript line of a response but reads the main transcript only. Changing it rescans the transcript.links, off by default) draws the GitHub owner/name as a link to the repository and the branch as a link to its tree/<branch> page. Turn it on only where Claude Code itself detects OSC 8 hyperlinks: if the links in its replies are clickable, it does. Where it does not, each link prints its URL after its text and pushes the rest of the band off the row (see Design notes). Konsole and foot draw OSC 8 but are not detected; FORCE_HYPERLINK=1 in the environment makes Claude Code treat a terminal as capable.| Group | Example | Definition |
|---|---|---|
| Model | Opus 5.5 xhigh | The main loop's model by name. The effort level follows while extended thinking is on, and nothing follows while it is off. |
| Repository | emaballarin/ccplugins ⎇ main (+12 −3) | GitHub owner/name from the origin remote (nothing for other hosts), the branch (@<sha> when detached), and inserted/deleted lines from git diff-files --shortstat plus git diff-index --cached --shortstat against HEAD (the empty tree before the first commit), which never touch the index. (+0 −0) is a clean tree; when git cannot read the tree the counter is left out, never shown as clean. Untracked files are not counted. With links on (see Settings), owner/name links to the GitHub repository and the branch to its tree/<branch> page; a detached @<sha> is not linked. |
| Context | ██████░░░░░░░░░░░░░░░░░▒ 246k/1M (25%) | Input tokens the last API response was answered over (uncached, cache write and cache read) against the model's window. The percentage is Claude Code's own; its colour measures load against the auto-compaction point, not against the window. |
| Session tokens | Tok Σ 2.4M | New tokens: uncached input + cache write + output over every API response of the session, subagents included, counted once per response, at the largest value any of its transcript lines records. Cache reads, the conversation re-sent with every request, are left out unless tokens is metered (see Settings). A cache write after the cache has expired (after 5 minutes or an hour idle, depending on the cache lifetime in use) counts the rewritten history again. Subagent transcripts record their responses only as streaming lines, with the output count at the last update written, so a subagent's output tokens can read low; its input and cache-write counts are complete. |
| Rate limits | Session 9% (4h 21m) · Weekly 27% (2d 3h 7m) | Session is the five-hour window, Weekly the seven-day one: usage as the last API response reported it, and the time to reset, to the minute. Behind a Claude gateway, Spend shows the spend limit, which can pass 100%. Absent off a subscription. |
Every colour is a Claude Code theme key, so the band follows the light or dark theme. The swatches below describe the default dark theme.
| Colour | Theme key | Means | Used for |
|---|---|---|---|
| clay | claude | identity: which model | the model name |
| lavender | permission | a mode setting | the effort level |
| green → amber → red | success → warning → error | load against a cap: below 60%, below 85%, from 85% | context %, Session %, Weekly % |
| diff green / diff red | diffAddedWord / diffRemovedWord | lines added / removed (dim when zero) | (+12 −3) |
| default | — | a plain value | used tokens, the Tok Σ count, repository name, branch |
| light grey | inactive | labels, units, secondary figures | /1M, Tok Σ, Session, Weekly, countdowns, the owner |
| dark grey | subtle | structure | the · separators |
The bar spans the model's whole window, left to right. Its used part has the exact length the API reported. That part is split between the /context categories, in /context's order and in /context's own colours, so the bar reads like a one-row /context. The split is Claude Code's local estimate (breakdown: "summary"), recomputed after every main-loop turn. Category boundaries are drawn to an eighth of a cell.
| Colour (dark theme) | Theme key | /context category |
|---|---|---|
| mid grey | promptBorder | System prompt |
| light grey | inactive | System tools |
| cyan | cyan_FOR_SUBAGENTS_ONLY | MCP tools |
| green | green_FOR_SUBAGENTS_ONLY | MCP server instructions |
| lavender | permission | Custom agents |
| clay | claude | Memory files |
| amber | warning | Skills |
| violet | purple_FOR_SUBAGENTS_ONLY | Messages |
| darkest grey | userMessageBackground | Free space |
| dark grey | subtle | Auto-compaction reserve: compaction runs where it starts |
Deferred tool schemas are loaded on demand and sit outside the window, so the bar leaves them out, as /context's grid does. Until the first breakdown arrives, the used part is drawn in light grey (inactive).
| Trigger | Refreshes |
|---|---|
| Session start, main-loop turn end | everything, including the /context category split |
| Subagent turn end | the session-token total |
| Every 60 s | everything but the category split, so countdowns and limits stay current |
Each source also keeps a minimum gap, so a burst of events folds into one run:
| Source | Gap |
|---|---|
| in-process reads | 5 s |
| transcript tally | 10 s |
| git | 15 s |
/context category split | 30 s |
An idle minute costs a few in-process calls, plus four git processes inside a repository (five before its first commit). One sh process is added only if the transcript has grown since the last read. Before a session's first response its transcript does not exist yet; if it is not where the session root says, every project folder is searched for it at most once in 5 minutes.
statusLine command draws. That area is not one of the function-hook drawing sites. The nearest site under the prompt, PromptHint, is mounted below Claude Code's mode-and-hint row (⏵⏵ auto mode on), so it would draw one row lower than a status line does. The band above the prompt is the native place left. If the under-prompt route is ever taken, the tree must keep core's { type: "engine" } element, which is what next(e) returns. With that element in place, Claude Code keeps its own hint row live and only adds the plugin's rows. Without it, the plugin "stands in", and Claude Code swaps its row for a static dim copy of the hint.Tok Σ counts by default, and why it is far below ccstatusline's Total. Within one API response the usage fields do not overlap: uncached input, cache write and cache read split the prompt, and output comes on top. Across responses they do: every request re-sends the whole conversation, mostly as cache reads, so a sum that includes them counts the history once per request. On the session measured, cache reads were 97.9% of the metered 115.7M tokens, against 2.4M new; they are also billed at about a tenth of the input price, so the metered sum says little about cost or limits (the Session and Weekly percentages say that). By default ccbar counts new tokens only; tokens: metered adds the cache reads. ccstatusline 2.2.30 counts cache reads and, besides, sums every transcript line: a session transcript writes one line per content block, each repeating its response's full usage, which puts it a further 2.1–2.3× over on the sessions measured. ccbar counts each message.id once, at the largest value its lines record for each count, and adds only the rise when a later line raises it. Finished main-loop responses repeat the same counts on every line, so this equals counting each once. Subagent responses are written only as streaming lines (stop_reason null) that are never closed: counting only finished lines would miss about nine in ten of them.$.fs.read and $.process.run both stop at 4 MiB, but transcripts grow far past that. ccbar keeps a byte cursor per file (main transcript and each subagent's) and reads only the new whole lines, in 2 MiB ranges. A line longer than a range is stepped over by byte counts (wc), never by decoded text, which cannot say how many bytes a split character held; a response on such a line goes uncounted. A range that reads empty or reports an error is an error, never a skip. A reload rescans from the start.Stop hook input, which is the level actually used, after any downgrade for the model. Before the first turn ends it falls back to the effortLevel setting. Whether thinking is on comes from the /config row thinking.Link elements: an OSC 8 hyperlink on the terminal, an anchor on desktop. In the fullscreen terminal a plain click may be taken by Claude Code itself; a ctrl- or alt-click opens the link. A terminal Claude Code does not credit with OSC 8 (Apple Terminal, xterm, Konsole, foot, screen, tmux before 3.4) draws each link's text followed by its URL in dim. The band measures text only, so the two URLs (about 90 columns) push the row's end off: at 160 columns the context bar, tokens and rate limits are lost. That is why links is off by default. The branch link is built from the local branch name and does not check that it exists on GitHub: an unpushed branch opens a 404.session.start, turn.complete and classic.Stop observe and pass on; ui.render draws the band and gives way to surveys. Nothing touches tool calls or prompts. The transcript gets one dim notice line per distinct error, and nothing else.Load the working copy with claude --plugin-dir plugins/ccbar. Claude Code then lays this build's API typings under .claude-plugin/types/ (git-ignored); tsconfig.json extends them. Edits hot-reload at each turn end.
claude plugin validate plugins/ccbar
claude plugin test plugins/ccbar
tsc -p plugins/ccbar
These checks need Claude Code itself and are not part of the repository's CI, which is Python-only: run all three before a release. One rule the validator enforces trips most first attempts. $ is never stored, passed to a function of your own, or returned; it is only ever spelled $.noun.method(…) where it is called. The state helpers read and update are the exception. That is why the refreshers are closures inside the session.start hook.
hooks/register.tsx 393 lines1/** ccbar: a quiet status band above the prompt, fed by background refreshers and drawn from one snapshot. */
2import { atom, read, update } from "claude-code";
3import type { Register } from "claude-code";
4
5import type { CcbarContext, CcbarSnapshot } from "../types";
6import type { Run } from "./band";
7import { layout, linkSpans } from "./band";
8import type { Counts, Cursor } from "./lib";
9import { drainLines, parseGithub, parseShortstat, prettyModel, tallyTranscript } from "./lib";
10
11const EMPTY: CcbarSnapshot = {
12 model: null,
13 thinking: null,
14 repo: null,
15 context: null,
16 total: null,
17 limits: [],
18 now: 0,
19};
20const snap = atom({ plugin: "ccbar", key: "snap" } as const, EMPTY, { shape: "v3" });
21
22/** Idle cadence; turn ends refresh on their own, and each refresher keeps its own minimum gap. */
23const TICK_MS = 60_000;
24const GAP_MS = { cheap: 5_000, tokens: 10_000, git: 15_000, breakdown: 30_000 };
25/** How often a session whose transcript is not where its root says may rescan every project folder for it. */
26const RESCAN_MS = 5 * 60_000;
27const CHUNK_BYTES = 2 * 1024 * 1024;
28/**
29 * Columns taken off `bodyColumns` before packing: the 2 of left padding, plus 4 for the `[-]` mark. Claude Code 2.1.288
30 * hands the full width; 2.1.289 already takes the mark's five off, where the 4 only make the band wrap a little early.
31 */
32const EDGE_COLUMNS = 6;
33/** Reads a byte range of a file (`$1` from 1, `$2` the path, `$3` the length). */
34const READ_RANGE = 'tail -c "+$1" -- "$2" | head -c "$3"';
35/** Measures the same range: the bytes through its first newline, then how many newlines it holds. */
36const PROBE_RANGE =
37 'r() { tail -c "+$1" -- "$2" | head -c "$3"; }; ' +
38 'printf "%s %s\\n" "$(r "$1" "$2" "$3" | head -n 1 | wc -c)" "$(r "$1" "$2" "$3" | tr -dc "\\n" | wc -c)"';
39
40/** Runs `task` one at a time; a call that lands mid-run schedules one more run instead of overlapping. */
41function singleFlight(task: () => Promise<void>): () => Promise<void> {
42 let running: Promise<void> | null = null;
43 let again = false;
44 return () => {
45 if (running) {
46 again = true;
47 return running;
48 }
49 running = (async () => {
50 do {
51 again = false;
52 await task();
53 } while (again);
54 })().finally(() => {
55 running = null;
56 });
57 return running;
58 };
59}
60
61type Jobs = { all: (withBreakdown: boolean) => void; tokens: () => void; mode: () => void };
62
63export const register: Register = (on, options) => {
64 /** Off unless switched on: where a terminal lacks OSC 8 a link prints its URL and pushes the band off its row. */
65 const links = options.links === true;
66 /** `Tok Σ` counts new tokens unless set to `metered`, which adds the cache reads. */
67 const metered = options.tokens === "metered";
68 // Set by session.start: the refreshers close over that hook's `$`, which is never stored or passed.
69 let jobs: Jobs | null = null;
70 // The effort the last main-loop turn ran at, after any downgrade for the model (classic.Stop):
71 // undefined before any turn ends, null after one ran on a model that takes no effort.
72 let observedEffort: string | null | undefined = undefined;
73
74 on("session.start", async ($, e, next) => {
75 const started = await next(e);
76 const reported = new Set<string>();
77
78 // Transcript cursors live in the module: a reload rescans from the start, rebuilding `seen`.
79 const cursors = new Map<string, Cursor>();
80 const seen = new Map<string, Counts>();
81 let total = 0;
82 let located: { dir: string; id: string } | null = null;
83 let scanned: { id: string; at: number } | null = null;
84
85 const report = (where: string, err: unknown): void => {
86 const text = `ccbar: ${where}: ${err instanceof Error ? err.message : String(err)}`;
87 $.ui.log(text, { to: "debug" });
88 if (!reported.has(text)) {
89 reported.add(text);
90 $.ui.log(text);
91 }
92 };
93
94 /** Applies `change` to the snapshot at write time, writing (and so redrawing) only when it changes something. */
95 const patchWith = async (change: (s: CcbarSnapshot) => CcbarSnapshot): Promise<void> => {
96 const current = await read($, snap);
97 if (JSON.stringify(change(current)) === JSON.stringify(current)) return;
98 await update($, snap, change);
99 };
100 const patch = (fields: Partial<CcbarSnapshot>): Promise<void> => patchWith((s) => ({ ...s, ...fields }));
101
102 /** One at a time and at most once per `gapMs`; calls inside the gap fold into one trailing run. */
103 const paced = (where: string, gapMs: number, task: () => Promise<void>): (() => Promise<void>) => {
104 const run = singleFlight(() => task().catch((err: unknown) => report(where, err)));
105 let last = Number.NEGATIVE_INFINITY;
106 let waiting = false;
107 const call = async (): Promise<void> => {
108 if (waiting) return;
109 waiting = true;
110 let now: number;
111 try {
112 now = await $.clock.now();
113 const wait = last + gapMs - now;
114 if (wait > 0) {
115 $.clock.after(wait, () => {
116 waiting = false;
117 void call();
118 });
119 return;
120 }
121 } catch (err: unknown) {
122 // A refresher whose pacing fails stays callable rather than going quiet for the session.
123 waiting = false;
124 report(where, err);
125 return;
126 }
127 waiting = false;
128 last = now;
129 await run();
130 };
131 return call;
132 };
133
134 const refreshModel = async (): Promise<void> => {
135 await patch({ model: prettyModel(await $.session.model()) });
136 };
137
138 const refreshMode = async (): Promise<void> => {
139 const row = (await $.config.list()).find((r) => r.key === "thinking");
140 if (row?.value !== true) {
141 await patch({ thinking: null });
142 return;
143 }
144 const configured = (await $.settings.read()).effortLevel;
145 await patch({
146 thinking: {
147 effort:
148 observedEffort !== undefined ? observedEffort
149 : typeof configured === "string" ? configured
150 : null,
151 },
152 });
153 };
154
155 // Plumbing only: `git diff` may refresh the index and take its lock, colliding with a commit in flight.
156 const refreshGit = async (): Promise<void> => {
157 const repo = await $.session.repo();
158 if (!repo) {
159 await patch({ repo: null });
160 return;
161 }
162 const [branch, head] = await Promise.all([
163 $.process.run(["git", "branch", "--show-current"]),
164 $.process.run(["git", "rev-parse", "--verify", "-q", "HEAD"]),
165 ]);
166 // A repository with no commit yet diffs the index against the empty tree.
167 const base =
168 head.exitCode === 0 ?
169 "HEAD"
170 : (await $.process.run(["git", "hash-object", "-t", "tree", "/dev/null"])).stdout.trim();
171 const [unstaged, staged] = await Promise.all([
172 $.process.run(["git", "diff-files", "--shortstat"]),
173 $.process.run(["git", "diff-index", "--cached", "--shortstat", base]),
174 ]);
175 let name = branch.exitCode === 0 ? branch.stdout.trim() : "";
176 if (!name && head.exitCode === 0) name = `@${head.stdout.trim().slice(0, 7)}`;
177 // A failed read is no clean tree: without both counts the counter is left out.
178 const counted = base !== "" && unstaged.exitCode === 0 && staged.exitCode === 0;
179 const a = parseShortstat(unstaged.stdout);
180 const b = parseShortstat(staged.stdout);
181 const github = parseGithub(repo.remote);
182 await patch({
183 repo: {
184 owner: github?.owner ?? null,
185 name: github?.name ?? null,
186 branch: name,
187 changes: counted ? { added: a.added + b.added, removed: a.removed + b.removed } : null,
188 },
189 });
190 };
191
192 /** The live figures and the limits; the category split and the compaction point are left as they are. */
193 const refreshUsage = async (): Promise<void> => {
194 const usage = await $.session.usage();
195 const figures = {
196 tokens: usage.context.tokens ?? null,
197 window: usage.context.window,
198 percent: usage.context.percent ?? null,
199 };
200 const limits = usage.rateLimits.map((r) => ({
201 kind: r.kind,
202 percent: r.percentUsed,
203 resetsAt: r.resetsAt ?? null,
204 }));
205 await patchWith((s) => ({
206 ...s,
207 context: { segments: [], threshold: null, ...s.context, ...figures },
208 limits,
209 }));
210 };
211
212 /** The /context category split and the compaction point; the live figures are left to `refreshUsage`. */
213 const refreshBreakdown = async (): Promise<void> => {
214 const usage = await $.session.usage({ breakdown: "summary" });
215 const b = usage.context.breakdown;
216 if (!b) return;
217 const split = {
218 threshold: b.autoCompactThreshold ?? null,
219 segments: b.categories
220 .filter((c) => c.kind === "used")
221 .map((c) => ({ color: c.color, tokens: c.tokens })),
222 };
223 const fresh: CcbarContext = {
224 tokens: usage.context.tokens ?? null,
225 window: usage.context.window,
226 percent: usage.context.percent ?? null,
227 ...split,
228 };
229 await patchWith((s) => ({ ...s, context: s.context ? { ...s.context, ...split } : fresh }));
230 };
231
232 /** Finds `<config>/projects/<slug>` holding `<session id>.jsonl`; resets the tally when the id changes (/clear). */
233 const locate = async (): Promise<{ dir: string; id: string } | null> => {
234 const id = await $.session.id();
235 if (located?.id === id) return located;
236 if (located !== null || (scanned !== null && scanned.id !== id)) {
237 cursors.clear();
238 seen.clear();
239 total = 0;
240 located = null;
241 }
242 const home = await $.env.get("HOME");
243 const config = (await $.env.get("CLAUDE_CONFIG_DIR")) ?? (home ? `${home}/.claude` : null);
244 if (!config) return null;
245 const projects = `${config}/projects`;
246 const guess = `${projects}/${(await $.session.root()).replace(/[^a-zA-Z0-9]/g, "-")}`;
247 if (await $.fs.exists(`${guess}/${id}.jsonl`)) {
248 located = { dir: guess, id };
249 return located;
250 }
251 // Before the first response there is no transcript yet: scan every project folder only now and then.
252 const now = await $.clock.now();
253 if (scanned?.id === id && now - scanned.at < RESCAN_MS) return null;
254 scanned = { id, at: now };
255 for (const entry of await $.fs.list(projects)) {
256 if (entry.kind === "dir" && (await $.fs.exists(`${projects}/${entry.name}/${id}.jsonl`))) {
257 located = { dir: `${projects}/${entry.name}`, id };
258 return located;
259 }
260 }
261 return null;
262 };
263
264 const runRange = async (script: string, path: string, offset: number, length: number): Promise<string> => {
265 const run = await $.process.run(["sh", "-c", script, "ccbar", String(offset + 1), path, String(length)]);
266 // The pipe reports `head`'s status alone, so `tail`'s stderr carries its failures; "Broken pipe" is no
267 // failure but `tail` cut off by `head`, which it says aloud where SIGPIPE is ignored.
268 const errors = run.stderr
269 .split("\n")
270 .filter((l) => l.trim() !== "" && !/broken pipe/i.test(l))
271 .join("; ");
272 if (run.exitCode !== 0 || errors !== "") {
273 throw new Error(`reading ${path}: ${errors || `exit ${run.exitCode}`}`);
274 }
275 return run.stdout;
276 };
277
278 /** Tallies a JSONL file's new whole lines from its cursor, in ranges under the 4 MiB read limits. */
279 const drain = async (path: string): Promise<void> => {
280 const { size } = await $.fs.stat(path);
281 const cursor = cursors.get(path) ?? { offset: 0, skipping: false };
282 cursors.set(path, cursor);
283 await drainLines(
284 cursor,
285 size,
286 CHUNK_BYTES,
287 (offset, length) => runRange(READ_RANGE, path, offset, length),
288 async (offset, length) => {
289 const [first = NaN, newlines = NaN] = (await runRange(PROBE_RANGE, path, offset, length))
290 .trim()
291 .split(/\s+/)
292 .map(Number);
293 if (!Number.isInteger(first) || !Number.isInteger(newlines)) throw new Error(`probing ${path}`);
294 return { first, newlines };
295 },
296 (lines) => {
297 total += tallyTranscript(lines, seen, metered);
298 }
299 );
300 };
301
302 const refreshTotal = async (): Promise<void> => {
303 const where = await locate();
304 if (!where) {
305 await patch({ total: null });
306 return;
307 }
308 const paths = [`${where.dir}/${where.id}.jsonl`];
309 const subagents = `${where.dir}/${where.id}/subagents`;
310 if (await $.fs.exists(subagents)) {
311 for (const entry of await $.fs.list(subagents)) {
312 if (entry.kind === "file" && /^agent-.+\.jsonl$/.test(entry.name)) {
313 paths.push(`${subagents}/${entry.name}`);
314 }
315 }
316 }
317 for (const path of paths) await drain(path);
318 await patch({ total });
319 };
320
321 const tick = async (): Promise<void> => {
322 await patch({ now: await $.clock.now() });
323 };
324
325 const clock = paced("clock", 0, tick);
326 const model = paced("model", GAP_MS.cheap, refreshModel);
327 const mode = paced("thinking", GAP_MS.cheap, refreshMode);
328 const usage = paced("usage", GAP_MS.cheap, refreshUsage);
329 const breakdown = paced("context", GAP_MS.breakdown, refreshBreakdown);
330 const git = paced("git", GAP_MS.git, refreshGit);
331 const tokens = paced("tokens", GAP_MS.tokens, refreshTotal);
332
333 jobs = {
334 all: (withBreakdown) => {
335 void clock();
336 void model();
337 void mode();
338 void usage();
339 if (withBreakdown) void breakdown();
340 void git();
341 void tokens();
342 },
343 tokens: () => void tokens(),
344 mode: () => void mode(),
345 };
346
347 $.clock.after(0, () => jobs?.all(true));
348 $.clock.every(TICK_MS, () => jobs?.all(false));
349 return started;
350 });
351
352 on("turn.complete", async ($, e, next) => {
353 const done = await next(e);
354 // A main-loop turn may have moved everything; a subagent's only the token tally.
355 $.clock.after(0, () => (e.agentId === undefined ? jobs?.all(true) : jobs?.tokens()));
356 return done;
357 });
358
359 on("classic.Stop", async ($, e, next) => {
360 const result = await next(e);
361 const effort = e.effort?.level || null;
362 if (effort !== observedEffort) {
363 observedEffort = effort;
364 $.clock.after(0, () => jobs?.mode());
365 }
366 return result;
367 });
368
369 on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
370 if (e.props.hasSurvey) return next(e);
371 const s = await read($, snap);
372 if (!s.model && !s.context) return next(e);
373 const { Box, Text, Link } = $.ui.resolve(e);
374 const rows = layout(s, Math.max(20, e.props.bodyColumns - EDGE_COLUMNS));
375 const run = (r: Run) => (
376 <Text color={r.color} backgroundColor={r.bg} bold={r.bold}>
377 {r.text}
378 </Text>
379 );
380 return (
381 <Box flexDirection="column" paddingLeft={2} marginTop={2}>
382 {rows.map((row) => (
383 <Text wrap="truncate-end">
384 {linkSpans(row).map((span) =>
385 links && span[0]?.href ? <Link href={span[0].href}>{span.map(run)}</Link> : span.map(run)
386 )}
387 </Text>
388 ))}
389 </Box>
390 );
391 });
392};
393hooks/band.ts 164 lines1/** The band's layout as plain data: coloured runs, grouped, packed into rows under a width. */
2import type { CcbarSnapshot } from "../types";
3import { contextPieces, formatCountdown, formatTokens, layBar, limitLabel } from "./lib";
4
5/** A stretch of text in one style; colours are theme keys, and `href` makes it a link. */
6export type Run = { text: string; color?: string; bg?: string; bold?: boolean; href?: string };
7
8/** Runs that stay together on one row. */
9export type Group = Run[];
10
11/** What sits between two groups on a row. */
12export const SEPARATOR: Run = { text: " · ", color: "subtle" };
13
14/** The closer join inside a group of figures of one kind: the rate-limit windows (Session, Weekly, Spend). */
15export const TIGHT: Run = { text: " · ", color: "subtle" };
16
17/** Theme keys by meaning: one colour, one sense. */
18export const COLOR = {
19 identity: "claude",
20 mode: "permission",
21 label: "inactive",
22 added: "diffAddedWord",
23 removed: "diffRemovedWord",
24} as const;
25
26const BAR = { fill: "inactive", track: "userMessageBackground", reserve: "subtle" };
27
28/** Load against a cap: green below 60%, yellow below 85%, red from there. */
29export function loadColor(percent: number): string {
30 if (percent >= 85) return "error";
31 if (percent >= 60) return "warning";
32 return "success";
33}
34
35/** Columns a run list takes; every glyph the band draws is one cell wide. */
36export function width(runs: Run[]): number {
37 return runs.reduce((sum, r) => sum + [...r.text].length, 0);
38}
39
40/**
41 * Packs groups into rows no wider than `columns`, `SEPARATOR` between neighbours on a row. Rows after
42 * the first start `indent` columns in, and have that much less room.
43 */
44export function pack(groups: Group[], columns: number, indent = 0): Run[][] {
45 const rows: Run[][] = [];
46 let row: Run[] = [];
47 for (const group of groups) {
48 const room = rows.length === 0 ? columns : columns - indent;
49 const joined = row.length > 0 ? [...row, SEPARATOR, ...group] : group;
50 if (row.length > 0 && width(joined) > room) {
51 rows.push(row);
52 row = [...group];
53 } else {
54 row = joined;
55 }
56 }
57 if (row.length > 0) rows.push(row);
58 return indent > 0 ? rows.map((r, i) => (i === 0 ? r : [{ text: " ".repeat(indent) }, ...r])) : rows;
59}
60
61/** A row cut into spans: consecutive runs that share a link stay together, every other run stands alone. */
62export function linkSpans(row: Run[]): Run[][] {
63 const spans: Run[][] = [];
64 for (const r of row) {
65 const last = spans.at(-1);
66 if (r.href && last?.[0]?.href === r.href) last.push(r);
67 else spans.push([r]);
68 }
69 return spans;
70}
71
72/** The band's groups in reading order: model, repository, context, tokens, then the rate limits together. */
73export function groups(s: CcbarSnapshot, barWidth: number): Group[] {
74 const out: Group[] = [];
75 if (s.model) {
76 const effort = s.thinking?.effort;
77 out.push([
78 { text: s.model, color: COLOR.identity, bold: true },
79 ...(effort ? [{ text: ` ${effort}`, color: COLOR.mode }] : []),
80 ]);
81 }
82 if (s.repo) {
83 const r = s.repo;
84 const group: Run[] = [];
85 // On GitHub, owner/name opens the repository and the branch its tree; a detached `@<sha>` is no branch.
86 const home =
87 r.owner && r.name ?
88 `https://github.com/${encodeURIComponent(r.owner)}/${encodeURIComponent(r.name)}`
89 : undefined;
90 const tree =
91 home && r.branch && !/^@[0-9a-f]{7}$/.test(r.branch) ?
92 `${home}/tree/${r.branch.split("/").map(encodeURIComponent).join("/")}`
93 : undefined;
94 if (r.owner && r.name)
95 group.push({ text: `${r.owner}/`, color: COLOR.label, href: home }, { text: r.name, href: home });
96 if (r.branch)
97 group.push({ text: group.length > 0 ? " ⎇ " : "⎇ ", color: COLOR.label }, { text: r.branch, href: tree });
98 // Drawn whenever git could read the tree: a quiet (+0 −0) says it is clean.
99 if (r.changes) {
100 const { added, removed } = r.changes;
101 group.push(
102 { text: group.length > 0 ? " (" : "(", color: COLOR.label },
103 { text: `+${added}`, color: added > 0 ? COLOR.added : COLOR.label },
104 { text: " ", color: COLOR.label },
105 { text: `−${removed}`, color: removed > 0 ? COLOR.removed : COLOR.label },
106 { text: ")", color: COLOR.label }
107 );
108 }
109 if (group.length > 0) out.push(group);
110 }
111 if (s.context) {
112 const c = s.context;
113 const used = c.tokens;
114 const cells = layBar(contextPieces(c, barWidth, BAR), barWidth);
115 const group: Run[] = cells.map((cell) => ({ text: cell.ch, color: cell.fg, bg: cell.bg }));
116 group.push(
117 { text: ` ${used === null ? "–" : formatTokens(used)}` },
118 { text: `/${formatTokens(c.window)}`, color: COLOR.label }
119 );
120 if (c.percent !== null && used !== null) {
121 const load = (used / (c.threshold ?? c.window)) * 100;
122 group.push(
123 { text: " (", color: COLOR.label },
124 { text: `${c.percent}%`, color: loadColor(load) },
125 { text: ")", color: COLOR.label }
126 );
127 }
128 out.push(group);
129 }
130 if (s.total) out.push([{ text: "Tok Σ ", color: COLOR.label }, { text: formatTokens(s.total) }]);
131 // The rate-limit windows wrap as one group: a row never splits Session from Weekly.
132 const limits: Run[] = [];
133 for (const l of s.limits) {
134 if (limits.length > 0) limits.push(TIGHT);
135 limits.push(
136 { text: `${limitLabel(l.kind)} `, color: COLOR.label },
137 { text: `${l.percent}%`, color: loadColor(l.percent) }
138 );
139 if (l.resetsAt && s.now) {
140 limits.push({ text: ` (${formatCountdown(Date.parse(l.resetsAt) - s.now)})`, color: COLOR.label });
141 }
142 }
143 if (limits.length > 0) out.push(limits);
144 return out;
145}
146
147/**
148 * Rows for `columns`: one row with a 24-cell bar, else one with 16, else wrapped rows with up to 16 (fewer
149 * below 36 columns). Wrapped rows hang under the first row's second segment, unless the indent would cost a
150 * row or leave a group too wide for the room beside it: then the whole band wraps flush left.
151 */
152export function layout(s: CcbarSnapshot, columns: number): Run[][] {
153 for (const bar of [24, 16]) {
154 const rows = pack(groups(s, bar), columns);
155 if (rows.length <= 1) return rows;
156 }
157 const wrapped = groups(s, Math.max(6, Math.min(16, columns - 20)));
158 const first = wrapped[0];
159 const flat = pack(wrapped, columns);
160 const hanging = first ? pack(wrapped, columns, width(first) + width([SEPARATOR])) : [];
161 const fits = hanging.length > 0 && hanging.length <= flat.length && hanging.every((r) => width(r) <= columns);
162 return fits ? hanging : flat;
163}
164hooks/lib.ts 255 lines1/** Pure helpers for ccbar: formatting, git and transcript parsing, and the context bar's layout. */
2
3/** A run of one colour along the bar, in eighths of a cell. */
4export type BarPiece = { color: string; units: number };
5
6/** One terminal cell of the bar: a left-aligned eighths block in `fg` over `bg`, or a blank in `bg`. */
7export type BarCell = { ch: string; fg: string | undefined; bg: string };
8
9/** Theme keys the bar draws its non-category runs in. */
10export type BarColors = { fill: string; track: string; reserve: string };
11
12const EIGHTHS = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"];
13
14const trimZero = (s: string): string => s.replace(/\.0$/, "");
15
16/** Formats a token count compactly: 940, 9.4k, 49k, 1M, 3.9M. */
17export function formatTokens(n: number): string {
18 if (n < 1000) return String(Math.round(n));
19 if (n < 9950) return `${trimZero((n / 1000).toFixed(1))}k`;
20 if (n < 999_500) return `${Math.round(n / 1000)}k`;
21 return `${trimZero((n / 1e6).toFixed(1))}M`;
22}
23
24/** Formats a duration down to the minute: `2d 3h 7m`, `4h 54m`, `12m`. */
25export function formatCountdown(ms: number): string {
26 const minutes = Math.max(0, Math.floor(ms / 60_000));
27 const d = Math.floor(minutes / 1440);
28 const h = Math.floor((minutes % 1440) / 60);
29 const m = minutes % 60;
30 if (d > 0) return `${d}d ${h}h ${m}m`;
31 if (h > 0) return `${h}h ${m}m`;
32 return `${m}m`;
33}
34
35/** Turns a model id (`claude-opus-5-5[1m]`) into its name (`Opus 5.5`); other spellings pass through. */
36export function prettyModel(raw: string): string {
37 const id = /claude-([a-z]+)-(\d{1,2})(?:-(\d{1,2}))?(?!\d)/i.exec(raw);
38 if (id?.[1] && id[2]) {
39 const family = id[1].charAt(0).toUpperCase() + id[1].slice(1).toLowerCase();
40 return id[3] ? `${family} ${id[2]}.${id[3]}` : `${family} ${id[2]}`;
41 }
42 return raw.replace(/\s*\[1m\]\s*$/i, "").trim();
43}
44
45/** Reads `owner/name` off a GitHub remote URL (https, ssh or scp-like); null for any other host. */
46export function parseGithub(remote: string | null): { owner: string; name: string } | null {
47 if (!remote) return null;
48 const m =
49 /^(?:git@github\.com:|ssh:\/\/git@github\.com(?::\d+)?\/|https?:\/\/(?:[^@/]+@)?github\.com\/|git:\/\/github\.com\/)([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/.exec(
50 remote.trim()
51 );
52 return m?.[1] && m[2] ? { owner: m[1], name: m[2] } : null;
53}
54
55/** Reads inserted and deleted line counts off `git diff --shortstat` output. */
56export function parseShortstat(text: string): { added: number; removed: number } {
57 const added = /(\d+) insertions?\(\+\)/.exec(text)?.[1];
58 const removed = /(\d+) deletions?\(-\)/.exec(text)?.[1];
59 return { added: added ? Number(added) : 0, removed: removed ? Number(removed) : 0 };
60}
61
62const count = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
63
64type TranscriptLine = {
65 message?: { id?: unknown; usage?: Record<string, unknown> };
66};
67
68/** A response's counts so far (uncached input, output, cache write, cache read): the largest each of its lines has recorded. */
69export type Counts = readonly [number, number, number, number];
70
71/**
72 * Adds the new tokens in whole JSONL lines to a per-response tally, and returns by how much the total grew.
73 *
74 * New tokens are a request's uncached input, its cache writes and its output; cache reads are the
75 * conversation re-sent with every request and are left out, so the total grows by what each request
76 * added, not by the history it carried again. A response is written as several lines (one per
77 * content block), each repeating its usage, so a response counts once, at the largest value any of
78 * its lines records for each count. A finished main-loop response repeats the same counts on every
79 * line; a subagent's is written only as streaming lines (`stop_reason` null) that are never closed,
80 * and the largest they record is the best there is. A later line that raises a response's counts
81 * adds only the rise, so lines read in separate passes still count once. `metered` adds the cache
82 * reads too, each response still counted once.
83 */
84export function tallyTranscript(text: string, seen: Map<string, Counts>, metered = false): number {
85 let added = 0;
86 for (const line of text.split("\n")) {
87 if (!line.includes('"usage"')) continue;
88 let parsed: TranscriptLine;
89 try {
90 parsed = JSON.parse(line) as TranscriptLine;
91 } catch {
92 continue;
93 }
94 const message = parsed.message;
95 const usage = message?.usage;
96 if (!message || !usage || typeof message.id !== "string") continue;
97 const previous = seen.get(message.id) ?? [0, 0, 0, 0];
98 const merged: Counts = [
99 Math.max(previous[0], count(usage.input_tokens)),
100 Math.max(previous[1], count(usage.output_tokens)),
101 Math.max(previous[2], count(usage.cache_creation_input_tokens)),
102 Math.max(previous[3], count(usage.cache_read_input_tokens)),
103 ];
104 const sum = (c: Counts): number => c[0] + c[1] + c[2] + (metered ? c[3] : 0);
105 added += sum(merged) - sum(previous);
106 seen.set(message.id, merged);
107 }
108 return added;
109}
110
111/** Where a read of an append-only JSONL file stands: the byte offset of the next unread byte, and whether it lies inside a line longer than a chunk. */
112export type Cursor = { offset: number; skipping: boolean };
113
114/** Reads at most `length` bytes of the file from byte `offset`, as UTF-8 text. */
115export type ReadRange = (offset: number, length: number) => Promise<string>;
116
117/** Measures at most `length` bytes from byte `offset`: the bytes through the first newline (all of them without one), and how many newlines there are. */
118export type ProbeRange = (offset: number, length: number) => Promise<{ first: number; newlines: number }>;
119
120/**
121 * Advances `cursor` over a file of `size` bytes, handing each run of whole new lines to `take`.
122 *
123 * A range read in text starts on a line boundary and is cut after its last newline, so the text
124 * re-encodes to its exact byte length. A line longer than `chunk` is stepped over by byte counts
125 * alone (`probe`), never by decoded text, which cannot say how many bytes a split character held.
126 * An empty read before the end of the file is an error, not a skip.
127 */
128export async function drainLines(
129 cursor: Cursor,
130 size: number,
131 chunk: number,
132 read: ReadRange,
133 probe: ProbeRange,
134 take: (lines: string) => void
135): Promise<void> {
136 if (size < cursor.offset) {
137 cursor.offset = 0;
138 cursor.skipping = false;
139 }
140 while (cursor.offset < size) {
141 if (cursor.skipping) {
142 const { first, newlines } = await probe(cursor.offset, chunk);
143 if (newlines === 0) {
144 // Still inside the over-long line; at the end of the file it is still being written.
145 if (cursor.offset + chunk >= size) return;
146 cursor.offset += chunk;
147 continue;
148 }
149 cursor.offset += first;
150 cursor.skipping = false;
151 continue;
152 }
153 const text = await read(cursor.offset, chunk);
154 if (text === "") throw new Error(`no bytes at offset ${cursor.offset} of ${size}`);
155 const cut = text.lastIndexOf("\n");
156 if (cut < 0) {
157 // A partial last line waits for its end; a full chunk with no newline is an over-long line.
158 if (cursor.offset + chunk >= size) return;
159 cursor.skipping = true;
160 continue;
161 }
162 const lines = text.slice(0, cut + 1);
163 cursor.offset += new TextEncoder().encode(lines).length;
164 take(lines);
165 }
166}
167
168/**
169 * Splits a bar of `width` cells into coloured runs: the used window by category, the free window,
170 * then the auto-compaction reserve at the end.
171 *
172 * The used length is exact (`tokens` over `window`); the categories share it in proportion to
173 * their estimates, by largest remainder. Without categories the used run takes `colors.fill`.
174 */
175export function contextPieces(
176 ctx: {
177 tokens: number | null;
178 window: number;
179 threshold: number | null;
180 segments: { color: string; tokens: number }[];
181 },
182 width: number,
183 colors: BarColors
184): BarPiece[] {
185 const total = width * 8;
186 const toUnits = (tokens: number): number => Math.round(Math.min(1, tokens / ctx.window) * total);
187 const used = ctx.tokens && ctx.tokens > 0 ? Math.max(1, toUnits(ctx.tokens)) : 0;
188 const reserveStart = ctx.threshold !== null && ctx.threshold < ctx.window ? toUnits(ctx.threshold) : total;
189
190 const pieces: BarPiece[] = [];
191 const segments = ctx.segments.filter((s) => s.tokens > 0);
192 const estimated = segments.reduce((sum, s) => sum + s.tokens, 0);
193 if (used > 0 && estimated > 0) {
194 const exact = segments.map((s) => (s.tokens / estimated) * used);
195 const units = exact.map(Math.floor);
196 let left = used - units.reduce((a, b) => a + b, 0);
197 const byRemainder = exact.map((x, i) => ({ i, r: x - Math.floor(x) })).sort((a, b) => b.r - a.r);
198 for (const { i } of byRemainder) {
199 if (left <= 0) break;
200 units[i] = (units[i] ?? 0) + 1;
201 left -= 1;
202 }
203 segments.forEach((s, i) => pieces.push({ color: s.color, units: units[i] ?? 0 }));
204 } else if (used > 0) {
205 pieces.push({ color: colors.fill, units: used });
206 }
207 const free = Math.max(0, reserveStart - used);
208 pieces.push({ color: colors.track, units: free });
209 pieces.push({ color: colors.reserve, units: total - used - free });
210 return pieces.filter((p) => p.units > 0);
211}
212
213/**
214 * Lays runs into cells. A cell inside one run is a blank on that colour; a cell where runs meet
215 * draws the first as a left eighths block over the largest of the rest, so a boundary keeps
216 * eighth-cell precision with two colours per cell.
217 */
218export function layBar(pieces: BarPiece[], width: number): BarCell[] {
219 const queue = pieces.map((p) => ({ ...p }));
220 const fallback = pieces.at(-1)?.color ?? "subtle";
221 const cells: BarCell[] = [];
222 for (let c = 0; c < width; c++) {
223 const parts: BarPiece[] = [];
224 let room = 8;
225 while (room > 0 && queue.length > 0) {
226 const head = queue[0];
227 if (!head) break;
228 const take = Math.min(head.units, room);
229 const last = parts.at(-1);
230 if (last && last.color === head.color) last.units += take;
231 else if (take > 0) parts.push({ color: head.color, units: take });
232 head.units -= take;
233 room -= take;
234 if (head.units <= 0) queue.shift();
235 }
236 const first = parts[0];
237 if (!first || parts.length === 1) {
238 cells.push({ ch: " ", fg: undefined, bg: first?.color ?? fallback });
239 continue;
240 }
241 const rest = parts.slice(1).reduce((a, b) => (b.units > a.units ? b : a));
242 cells.push({ ch: EIGHTHS[first.units] ?? " ", fg: first.color, bg: rest.color });
243 }
244 return cells;
245}
246
247/** A rate-limit window's label, as Claude's usage pages name it: `Session`, `Weekly`, `Spend`, else its kind. */
248export function limitLabel(kind: string): string {
249 if (kind === "five_hour") return "Session";
250 if (kind === "seven_day") return "Weekly";
251 if (kind === "spend_limit") return "Spend";
252 const words = kind.replace(/_/g, " ");
253 return words.charAt(0).toUpperCase() + words.slice(1);
254}
255types/index.d.ts 53 lines1/** The figures the band draws, gathered by background refreshers. */
2export type CcbarSnapshot = {
3 /** The main loop's model, prettified (`Opus 5.5`). */
4 model: string | null;
5 /** Extended thinking: null when off; on, the effort level when one is known. */
6 thinking: { effort: string | null } | null;
7 /** The working copy's repository; null outside one. */
8 repo: CcbarRepo | null;
9 /** The live context window; null before the first refresh. */
10 context: CcbarContext | null;
11 /** Tokens over every API response of the session, subagents included: new ones (uncached input, cache writes, output), plus cache reads under `tokens: metered`. */
12 total: number | null;
13 /** The account's rate-limit windows, as the last API response reported them. */
14 limits: CcbarLimit[];
15 /** The clock at the last tick, that reset countdowns are drawn against. */
16 now: number;
17};
18
19/** Repository identity and working-tree change counts. */
20export type CcbarRepo = {
21 /** GitHub owner and name; null for a remote elsewhere or none. */
22 owner: string | null;
23 name: string | null;
24 /** The branch, or `@<short sha>` when detached; empty when unknown. */
25 branch: string;
26 /** Inserted and deleted lines, staged and unstaged together; null when git could not read them. */
27 changes: { added: number; removed: number } | null;
28};
29
30/** Context-window occupancy: exact totals, with the category split estimated. */
31export type CcbarContext = {
32 tokens: number | null;
33 window: number;
34 percent: number | null;
35 /** Where auto-compaction runs, in tokens; null when it is off. */
36 threshold: number | null;
37 /** The `used` rows of the /context breakdown, in its order, by theme colour. */
38 segments: { color: string; tokens: number }[];
39};
40
41/** One rate-limit window. */
42export type CcbarLimit = {
43 kind: string;
44 percent: number;
45 resetsAt: string | null;
46};
47
48declare module "claude-code" {
49 interface PluginState {
50 ccbar: { snap: Shaped<CcbarSnapshot> };
51 }
52}
53