SLOPSHOPPER

limits-meter

Session (5 h) and weekly usage limits as small progress bars with reset countdowns, plus whether the prompt cache is still warm and for how long and the…

spinnercommandstatustimer
v0.6.0MITupdated 2026-10-22marcelmatula/claude-mods/limits-meter
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · limits-meter
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /limits ⎿ limits-meter: Limits meter hidden. /limits brings it back. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

limits-meter

A Claude Code mod that shows your usage limits for the current session (5 h) and the week as small progress bars with a percentage and the time left until each resets, whether the session's prompt cache is still warm and for how long, and the session's name once you have given it one. They sit on a centred row at the bottom of the screen, under the prompt's hint line; in the Claude desktop app they show as text in the prompt's footer. /limits hides or shows them, and the choice is remembered.

Part of claude-mods, Marcel's Claude Code marketplace (marcel-mods).

limits-meter under the Claude Code prompt: the session's name, flaky-test-fix, in bold, then Session 38 % in green, resetting in 2:31, Week 82 % in red, resetting in 3 days 4 hours, and the prompt cache warm for about 4 more minutes, centred on the row below the hint line

Each bar is green below 50 %, yellow from 50 % and red from 80 %, in your theme's colours. The screenshot is the mod running in a 120-column terminal with sample readings, in a session named flaky-test-fix.

After each percentage, ↻ and a dim countdown give the time left until that window resets:

WindowCountdownReads
Session↻2:312 hours 31 minutes
Week↻3d 4h3 days 4 hours; in its last day hours and minutes, as ↻17:05

It counts down at the start of every minute, without waiting for a response, and rounds up, so it never reads 0:00 before the reset. Each countdown keeps the same width, so the row doesn't shift as it ticks over.

The prompt cache

After the two windows, a third item says whether the session's prompt cache is still warm. Claude Code sends the conversation with every request, and the API keeps it in a prompt cache for a few minutes, so the next response reads it from there, cheaper and faster. Each response starts that time over; once it runs out with no response, the cache is cold and the next response pays for the whole conversation again.

ShowsMeans
Cache █████▋ warm ↓4mthe cache was used within its lifetime; about 4 minutes are left until it is cold
Cache with an empty bar, coldits lifetime has run out; the next response re-sends the whole conversation
nothingthe session has had no response yet, or its conversation was just compacted, cleared or resumed

The bar empties as the cache cools, and takes the limits' colours turned round: green while more than half of the lifetime is left, yellow from the half-way point, red in the last fifth. ↓ marks the time until it is cold, as ↻ marks the time until a window resets. It counts down at the start of every minute and rounds up like the other countdowns, but goes cold at the moment its lifetime ends, not up to a minute later.

How long it lasts. Claude Code doesn't tell a mod how long the account's cache lasts: 5 minutes, or an hour on accounts that have the longer one. The cacheTtl option says which, 5m (the default) or 1h. Installing the mod asks for it, and afterwards it is a row in /config.

It is an estimate. The mod can't see the cache, only that a response ended, so:

  • It counts from the end of the latest response. The cache was last used when that response began, so the countdown can read the length of that response too long.
  • While a turn is running, the terminal row shows the cache as warm with no countdown, since every request of the turn uses it. The desktop app's text can't tell that a turn is running, so for a turn longer than the lifetime it may read cold until the turn ends.
  • It doesn't see anything else that drops the cache, such as switching model with /model, or caching being turned off for the session.
  • It holds for the main conversation; a subagent has a cache of its own, which isn't shown.

Unlike the limits, the cache belongs to one session's conversation, so nothing about it is shared between sessions.

The session's name

Once you name a session, with /rename <name> or by starting it with claude --name <name>, the row starts with that name in bold, set off from the meters: limits work Session ███ 38% ↻2:31 Week ….

  • It is the name you gave the session. Claude Code also titles a session by itself, but it doesn't tell a mod that title, so a session you haven't named shows no name.
  • Claude Code tells a mod the name only when a session starts and with each prompt you send. So a name the session starts with, from --name or a session you resume, shows from the start or at the latest with your first prompt, and after /rename the new name shows with your next prompt.
  • Where an organization manages Claude Code, the two hooks that bring the name run only for plugins the organization lists in its managed settings, so a limits-meter you install yourself shows no name there. The meters work as usual.
  • A name longer than 24 characters is cut short with …. On a narrower terminal it gets shorter still, down to 8 characters, before the meters lose any detail. When not even that fits beside the meters' bars, the row goes on without it.
  • It counts a character to a cell, so a name in wide characters, such as Chinese, Japanese or emoji, puts the row a little off centre.
  • Before the session has any figures, the name is the row on its own. /limits hides it with the rest of the row.
  • The desktop app shows the session's name itself, so the figures in its footer leave it out.

Install

Type this at the prompt of a Claude Code terminal session:

/plugin install limits-meter --marketplace marcelmatula/claude-mods

Answer y to add the marketplace, then pick a scope (user scope loads it in every session). It asks how long your prompt cache lasts, 5m or 1h; see The prompt cache. The mod is active in that session at once; the meters show as soon as it has a reading, at the latest after the next response.

Or in two steps:

/plugin marketplace add marcelmatula/claude-mods
/plugin install limits-meter@marcel-mods

Showing and hiding

TypeWhat happens
/limitshides the meter row if it's showing, shows it if it's hidden
/limits offhides it
/limits onshows it

Claude Code's own hint line stays as it is either way. The cache item is part of the row, so /limits hides and shows it with the windows. The choice is remembered across sessions, so a hidden meter stays hidden until you turn it back on.

In the Claude desktop app

The desktop app's Code tab draws no hint line under its prompt, so the meter row can't show there. Instead the figures appear as text in the prompt's footer, beside the model's name:

limits-meter  Session 61% ↻0:42 · Week 75% ↻2d 21h · Cache warm ↓4m

They work as the row does: the same countdowns, moved on every minute, and /limits hides and shows them. They appear once the app has connected to the session, within a minute of opening it. A mod installed from a terminal at user scope, as under Install, loads in the desktop app's local sessions too.

What to expect

  • The figures are the ones Claude Code receives with each response, so the mod makes no requests of its own. They update whenever a window moves by a whole point.
  • Your limits are shared by all your sessions, but each session gets figures only with its own responses. So every session saves the newest figures it gets, and the others pick them up within a minute: a session you left idle while working in another one catches up by itself.
  • When a window's reset time passes while the session sits idle, its meter drops to 0 % within a minute, without waiting for the next response. Its countdown goes then, and comes back once a response brings the next window's reset time.
  • The meters stay through /clear and /resume, and so does a hidden meter's choice.
  • The limits are on a Claude subscription only. A new session shows the newest figures another session saved straight away; with none saved, the row appears after its first response. A session on an API key has no rate-limit windows, so its windows go after its first response, and the cache item stays: with no windows, the row is the cache alone.
  • It adds one line at the bottom. While Claude Code shows a notice on the hint line (for example "Context left until auto-compact"), the notice moves to its own line under the meters.
  • On a narrow terminal the labels shorten to 5h and 7d and the bars get shorter. The cache item goes below about 70 columns, the windows then keeping their full labels down to about 60; the countdowns go below about 47 columns, and the row is hidden below about 20. These widths are for a session with no name; a name takes room of its own, as The session's name says.

What it can access

A mod runs inside Claude Code's plugin sandbox and can reach the outside only through $ calls. On Claude Code 2.1.294 the sandbox gives a mod no way to make web requests, load modules, reach the process or run code from a string, and the validator refuses disguised $ access, so its list of hooks and calls covers everything a mod can do. For limits-meter that list is:

HooksWhen they run
session.startonce when a session starts
session.measurewhen Claude Code's usage figures change, which includes the end of each response
session.endwhen a session ends, to notice /clear and /resume
ui.render on PromptHintwhen the line under the prompt is drawn
classic.SessionStartwhen a session starts, including after /clear and /resume, to read the session's name
classic.UserPromptSubmitwhen you send a prompt, to read the session's name again after a /rename
command.run on limitswhen you run /limits
$ callsWhat for
$.session.usagereads the rate-limit figures
$.state.get, $.state.setkeeps those figures for the session, with the time the countdowns count from, when the session's own figures arrived, when the prompt cache was last used, and the session's name, in the mod's own state
$.clock.now, $.clock.afterat the start of every minute moves the countdowns on and checks whether a window's reset time has passed or the figures changed; at the moment the cache's lifetime ends marks it cold; fills the meters in again just after /clear or /resume
$.ui.resolvegets the elements it draws with
$.session.surfacestells a session in the desktop app, which draws on no terminal, from a terminal session
$.ui.statusshows the figures as text in the desktop app's prompt footer
$.command.register, $.command.listadds the /limits command, and adds it again if the session no longer lists it
$.store.get, $.store.setkeeps the shown or hidden choice between sessions, and passes the newest figures between your open sessions

It saves two things in the mod's own small store, which Claude Code keeps in your Claude Code configuration folder: the shown or hidden choice, and the newest usage figures (each window's percentage and reset time, and when they arrived). The cache item is not saved there. It needs no access of its own: it uses the session.measure hook the windows already use, learns only that a response ended (the context window moved and has a reading), and never looks at token counts, prompts or responses. The session's name is not saved there either, nor shared with other sessions. Beyond that it reads and writes no files, runs no shell commands and makes no network requests.

The two classic. hooks run on Claude Code's settings hook events SessionStart and UserPromptSubmit, the only places Claude Code hands a mod the session's name. The UserPromptSubmit hook receives each prompt you send, as any hook on that event does, but reads only the session's name from it: it never looks at the prompt's text, and passes every prompt on as it came, never blocking, changing or keeping one. The mod has no hooks on Claude's tool calls, and its one command hook answers /limits.

Check this yourself from a clone of the repo, in the hooks: and calls: lines:

claude plugin validate limits-meter

capabilities.json holds the same list. CI fails if the mod's hooks or $ calls ever go beyond it, so any new kind of access has to show up as a change to that file.

Privacy

limits-meter collects nothing about you and sends nothing anywhere: it makes no network requests, and its author receives no data of any kind. The usage figures it shows come from Claude Code itself.

On your computer it keeps two things in its own store, in your Claude Code configuration folder: whether you have hidden the row, and the newest usage figures (each window's percentage and reset time, and when they arrived). The session's name and when the prompt cache was last used stay in the session's state, not in that store, and are not shared with other sessions. It never reads the text of your prompts or of Claude's responses, your files or your token counts. What it can access lists every hook and call it has.

How it works

hooks/register.tsx is a plugin of function hooks:

  • session.start reads the current windows with $.session.usage().
  • session.measure keeps them up to date as responses arrive, and saves them with the time they arrived in $.store for the other sessions. It also marks the prompt cache as used when it reports the context window moving with a reading, which a response does; a compaction moves it with none, which clears the mark. A timer set for the end of the cache's lifetime marks it cold at that moment, and sets itself again if a response moved the end later.
  • A timer started in session.start runs at the start of every minute. It records the time, which the countdowns count from, reads the figures again and sets a window whose reset time has passed to 0 %, since Claude Code sends the new figure only with the next response. It takes the figures another session saved when they are newer than the session's own.
  • classic.SessionStart and classic.UserPromptSubmit hooks take the session's name from the session_title that Claude Code gives those settings hook events, and keep it in the session's state, which redraws the row. Neither changes the event.
  • /clear and /resume empty the mod's session state and start no new session.start. A session.end hook sees them and, a moment later, reads the saved choice and the figures back in, and writes the name the latest SessionStart brought, which may have come before the state was emptied.
  • A ui.render hook on the PromptHint site draws Claude Code's own hint line unchanged and adds the meter row below it, led by the session's name when it has one, unless the meter is hidden. It works each countdown out from a window's reset time, or the cache's last use plus its lifetime, and the recorded time; while a turn is running (the hint's isWorking) it shows the cache as warm with no countdown.
  • In a session that draws on no terminal (the desktop app), the minute check, each new reading, the end of the cache's lifetime and /limits also set the mod's status entry with $.ui.status: the same figures as one line of text. A terminal session sets none.
  • /limits is registered in session.start and answered by a command.run hook. The minute check registers it again when the session no longer lists it, as happened in a desktop app session the mod was updated under; should a load of the mod come without a session.start, its first reading registers the command and starts the minute check. It flips the hidden setting in the session's state, which redraws the row at once, and saves it with $.store. The next session.start reads it back.

Built and tested on Claude Code 2.1.294. The function-hooks plugin API is early access and may change between releases.

Development

From this folder:

claude plugin validate .
claude plugin test .
claude --plugin-dir .

License

MIT. See LICENSE.

Source 2 files
hooks/register.tsx 678 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionRateLimit } from 'claude-code'
3
4import type { Limit, Reading } from '../types'
5
6const limits = atom({ plugin: 'limits-meter', key: 'limits' } as const, [])
7const isHidden = atom({ plugin: 'limits-meter', key: 'isHidden' } as const, false)
8// The time the countdowns count from: the latest minute check or reading, 0 before one.
9const time = atom({ plugin: 'limits-meter', key: 'time' } as const, 0)
10// When this session's own engine last brought figures, 0 before it has.
11const measuredAt = atom({ plugin: 'limits-meter', key: 'measuredAt' } as const, 0)
12// When this session's prompt cache was last used: the end of its latest response, 0 before
13// one. Unlike the limits it is not shared, the cache belonging to the session's own prompt.
14const cachedAt = atom({ plugin: 'limits-meter', key: 'cachedAt' } as const, 0)
15// The session's name, as /rename or --name set it; '' while it has none.
16const sessionName = atom({ plugin: 'limits-meter', key: 'name' } as const, '')
17
18// $.store key that keeps the shown/hidden choice across sessions.
19const HIDDEN_KEY = 'isHidden'
20// $.store key of the newest figures any session got, with when it got them. The limits are
21// the account's, but each session's engine learns them only from its own responses.
22const READING_KEY = 'reading'
23
24// How often the meters check the engine's figures and the time: an idle session gets no
25// responses to notice a reset by, nothing else refills the state if it was emptied, and
26// the countdowns move on a minute.
27const CHECK_MS = 60_000
28
29// How long after /clear or /resume the state is filled in again. The engine empties it
30// within a few milliseconds of session.end.
31const REFILL_DELAY_MS = 250
32
33// `left` is the most cells a window's countdown takes: "5:00" and "6d 23h". Each one is
34// padded to it, so the centred row doesn't shift as the countdowns tick over.
35const WINDOWS = [
36  { kind: 'five_hour', label: 'Session', short: '5h', left: 4 },
37  { kind: 'seven_day', label: 'Week', short: '7d', left: 6 },
38] as const
39
40const MINUTE_MS = 60_000
41
42// How long the prompt cache stays warm after it is used. Claude Code does not tell a mod
43// which applies to the account, so the `cacheTtl` option says.
44const CACHE_TTLS = { '5m': 5 * MINUTE_MS, '1h': 60 * MINUTE_MS } as const
45const CACHE_LABEL = 'Cache'
46// The cache gets colder from the moment it is used, and a countdown to that is not a
47// reset: this marks the time left until it is cold, not until a window starts again.
48const CACHE_MARK = '↓'
49
50const EIGHTHS = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉']
51const SEPARATOR = '   '
52// Marks a countdown as the time until the window starts again, not a time of day.
53const RESET_MARK = '↻'
54const TRACK = 'subtle'
55// The hint line's rows start two columns in from the terminal's edge.
56const INDENT = 2
57
58// The session's name leads the row, cut with an ellipsis to at most NAME_CELLS cells. On a
59// row too narrow for it, it gives up cells down to NAME_MIN_CELLS before the meters lose
60// detail, and goes only when no tier with bars leaves it that many.
61const NAME_CELLS = 24
62const NAME_MIN_CELLS = 8
63const ELLIPSIS = '…'
64
65type Tier = { labels: 'long' | 'short'; bar: number; countdowns: boolean; cache: boolean }
66
67// From the most detailed down; the first that fits is drawn. The tiers without the cache
68// are the row as it was before the cache came, so a row too narrow for the cache keeps
69// whatever the windows alone could. The cache stays as long as the short labels let it fit,
70// which is longer than the long labels would, and goes before the countdowns do.
71const TIERS: Tier[] = [
72  { labels: 'long', bar: 8, countdowns: true, cache: true },
73  { labels: 'short', bar: 5, countdowns: true, cache: true },
74  { labels: 'long', bar: 8, countdowns: true, cache: false },
75  { labels: 'short', bar: 5, countdowns: true, cache: false },
76  { labels: 'short', bar: 5, countdowns: false, cache: false },
77  { labels: 'short', bar: 0, countdowns: false, cache: false },
78]
79
80// One item of the row, whatever it measures. `fill` is how much of the bar is filled, as
81// a percentage; `value` is what follows the bar, a percentage or a word, in up to 4 cells.
82type Meter = {
83  label: string
84  fill: number
85  color: string
86  value: string
87  isDim: boolean
88  countdown: string | undefined
89}
90
91// The prompt cache as of some moment: warm with the percentage of its lifetime left and,
92// while the time is running, the time left; or cold. Absent before the session's first
93// response.
94type Cache = { isWarm: boolean; remaining: number; untilCold: string | undefined }
95
96const known = (list: readonly SessionRateLimit[]): Limit[] =>
97  list
98    .filter(one => WINDOWS.some(w => w.kind === one.kind))
99    .map(({ kind, percentUsed, resetsAt }) =>
100      resetsAt === undefined ? { kind, percentUsed } : { kind, percentUsed, resetsAt },
101    )
102
103const hasReset = (one: Limit, now: number) =>
104  one.resetsAt !== undefined && Date.parse(one.resetsAt) <= now
105
106// A window starts again at 0% when its reset time passes, but Claude Code sends the new
107// figure only with the next response, so until then the mod resets it itself.
108const current = (list: readonly Limit[], now: number): Limit[] =>
109  list.map(one => (hasReset(one, now) ? { kind: one.kind, percentUsed: 0 } : one))
110
111const colorFor = (percent: number) =>
112  percent >= 80 ? 'error' : percent >= 50 ? 'warning' : 'success'
113
114const percentText = (percent: number) => `${Math.round(percent)}%`
115
116// Each value counts as 4 cells. What a shorter one lacks goes at the end of its meter, so
117// it sits one cell from its bar and one space from its countdown whatever its digits, and
118// the row keeps its width.
119const VALUE_CELLS = 4
120const valuePad = (meter: Meter) => ' '.repeat(Math.max(0, VALUE_CELLS - meter.value.length))
121
122// The time left until a reset, rounded up to the minute so that it never reads 0:00
123// before the reset: "2:31" under a day, "3d 4h" from a day on.
124const leftText = (ms: number) => {
125  const minutes = Math.ceil(ms / 60_000)
126  if (minutes < 24 * 60) {
127    return `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, '0')}`
128  }
129
130  return `${Math.floor(minutes / (24 * 60))}d ${Math.floor((minutes % (24 * 60)) / 60)}h`
131}
132
133// What the meters show at `now`: each known window's percentage and, while its reset is
134// still ahead, the time left until it.
135const readingsAt = (list: readonly Limit[], now: number) => {
136  const shown = current(list, now)
137
138  return WINDOWS.flatMap(w => {
139    const one = shown.find(l => l.kind === w.kind)
140    if (one === undefined) {
141      return []
142    }
143
144    const left = one.resetsAt === undefined ? NaN : Date.parse(one.resetsAt) - now
145
146    return [{ ...w, percent: one.percentUsed, untilReset: now > 0 && left > 0 ? leftText(left) : undefined }]
147  })
148}
149
150// The cache's lifetime, which the `cacheTtl` option sets when the module loads.
151let cacheMs: number = CACHE_TTLS['5m']
152
153// The time left until the cache is cold, rounded up to the minute like the windows'
154// countdowns: "4m", and "60m" on the hour's lifetime.
155const cacheLeftText = (ms: number) => `${Math.ceil(ms / MINUTE_MS)}m`
156
157// Most cells that text takes, which the countdown is padded to.
158const cacheLeftWidth = () => `${cacheMs / MINUTE_MS}m`.length
159
160// The cache as of `now`, given when it was last used. A turn that is running keeps it warm
161// with every request it makes, so while one is, there is no time to count down. Absent
162// before the session's first response, and wherever the time is not known.
163const cacheAt = (touched: number, now: number, isWorking: boolean): Cache | undefined => {
164  if (touched === 0 || now === 0) {
165    return undefined
166  }
167
168  if (isWorking) {
169    return { isWarm: true, remaining: 100, untilCold: undefined }
170  }
171
172  const left = touched + cacheMs - now
173
174  return left > 0
175    ? { isWarm: true, remaining: Math.min(100, (left * 100) / cacheMs), untilCold: cacheLeftText(left) }
176    : { isWarm: false, remaining: 0, untilCold: undefined }
177}
178
179// The figures as one line of text: "Session 61% ↻0:42 · Week 75% ↻2d 21h · Cache warm ↓4m".
180// It leaves out the session's name, which the desktop app shows itself.
181const statusText = (list: readonly Limit[], now: number, touched: number) => {
182  const parts = readingsAt(list, now).map(
183    r => `${r.label} ${Math.round(r.percent)}%${r.untilReset === undefined ? '' : ` ${RESET_MARK}${r.untilReset}`}`,
184  )
185  const cache = cacheAt(touched, now, false)
186  if (cache !== undefined) {
187    parts.push(
188      `${CACHE_LABEL} ${cache.isWarm ? 'warm' : 'cold'}${cache.untilCold === undefined ? '' : ` ${CACHE_MARK}${cache.untilCold}`}`,
189    )
190  }
191
192  return parts.length === 0 ? undefined : parts.join(' · ')
193}
194
195// The meters a tier draws for the windows' readings.
196const windowMeter = (r: ReturnType<typeof readingsAt>[number], tier: Tier): Meter => ({
197  label: tier.labels === 'long' ? r.label : r.short,
198  fill: r.percent,
199  color: colorFor(r.percent),
200  value: percentText(r.percent),
201  isDim: false,
202  countdown:
203    tier.countdowns && r.untilReset !== undefined ? ` ${RESET_MARK}${r.untilReset.padEnd(r.left)}` : undefined,
204})
205
206// The cache as a meter: a bar that empties as the cache cools, in the limits' colours turned
207// round (green with most of the lifetime left), and "warm" or "cold" where their percentage is.
208const cacheMeter = (cache: Cache, tier: Tier): Meter => ({
209  label: CACHE_LABEL,
210  fill: cache.remaining,
211  color: colorFor(100 - cache.remaining),
212  value: cache.isWarm ? 'warm' : 'cold',
213  isDim: !cache.isWarm,
214  countdown:
215    tier.countdowns && cache.untilCold !== undefined
216      ? ` ${CACHE_MARK}${cache.untilCold.padEnd(cacheLeftWidth())}`
217      : undefined,
218})
219
220// Cells one meter takes: "label ", the bar and a space, the value in its 4 cells, then the
221// countdown with its space and mark.
222const meterWidth = (tier: Tier, meter: Meter) =>
223  meter.label.length + 1 + (tier.bar > 0 ? tier.bar + 1 : 0) + VALUE_CELLS + (meter.countdown?.length ?? 0)
224
225// Cells a text takes, a character to a cell: a name in wide characters (CJK, emoji) takes
226// more than this says, which moves the row off centre.
227const cellsOf = (text: string) => [...text].length
228
229// The text in at most `cells` cells, cut with an ellipsis when it is longer.
230const clip = (text: string, cells: number) =>
231  cellsOf(text) <= cells ? text : `${[...text].slice(0, cells - 1).join('').trimEnd()}${ELLIPSIS}`
232
233const isLimit = (one: unknown): one is Limit => {
234  if (typeof one !== 'object' || one === null) return false
235  const { kind, percentUsed, resetsAt } = one as Record<string, unknown>
236
237  return (
238    typeof kind === 'string' &&
239    typeof percentUsed === 'number' &&
240    (resetsAt === undefined || typeof resetsAt === 'string')
241  )
242}
243
244const isReading = (value: unknown): value is Reading => {
245  if (typeof value !== 'object' || value === null) return false
246  const { at, limits } = value as Record<string, unknown>
247
248  return typeof at === 'number' && Array.isArray(limits) && limits.every(isLimit)
249}
250
251// The reading a session saved last, or undefined when there is none the mod can read.
252async function savedReading($: EngineInterface): Promise<Reading | undefined> {
253  try {
254    const value = await $.store.get(READING_KEY)
255    return isReading(value) ? value : undefined
256  } catch {
257    return undefined
258  }
259}
260
261// The time, then the newest figures with any window past its reset time at 0%: the
262// engine's, or the reading another session saved when that is newer. The time is written
263// every time, which moves the countdowns on; the figures only when they differ from the
264// state's, since a write redraws the meters.
265async function refresh($: EngineInterface) {
266  const now = await $.clock.now()
267  await update($, time, () => now)
268  const usage = await $.session.usage()
269  const own = known(usage.rateLimits)
270  // Responses with no windows mean the session is off a subscription (on an API key), so
271  // the figures another session saved are not its limits.
272  const isOffSubscription = own.length === 0 && (usage.cost?.usd ?? 0) > 0
273  const saved = isOffSubscription ? undefined : await savedReading($)
274  const newest = saved !== undefined && saved.at > (await read($, measuredAt)) ? saved.limits : own
275  const fresh = current(newest, now)
276  if (JSON.stringify(fresh) !== JSON.stringify(await read($, limits))) {
277    await update($, limits, () => fresh)
278  }
279
280  await showStatus($)
281}
282
283// The text the status entry was last set to, so it is set again only when it changes.
284let statusShown: string | undefined
285
286// The desktop app draws no hint line, but it does draw a plugin's status entry, small in
287// the prompt's footer. So a session that draws on no terminal shows the figures there as
288// text, and a terminal session, which has the meter row, sets none.
289async function showStatus($: EngineInterface) {
290  try {
291    const surfaces = await $.session.surfaces()
292    const isOffTerminal = surfaces.length > 0 && !surfaces.includes('terminal')
293    const text =
294      isOffTerminal && !(await read($, isHidden))
295        ? statusText(await read($, limits), await read($, time), await read($, cachedAt))
296        : undefined
297    if (text !== statusShown) {
298      statusShown = text
299      $.ui.status(text)
300    }
301  } catch {
302    // The next minute check tries again.
303  }
304}
305
306// The name the classic hooks last brought to this load of the module, undefined before
307// they have. A reload starts it over while the state keeps the name it had.
308let nameSeen: string | undefined
309
310// Keeps the session's name as Claude Code handed it to a settings hook, no name included,
311// so a session that lost its name loses it from the row.
312async function nameSession($: EngineInterface, title: string | undefined) {
313  const name = title?.trim() ?? ''
314  nameSeen = name
315  try {
316    if (name !== (await read($, sessionName))) {
317      await update($, sessionName, () => name)
318    }
319  } catch {
320    // The next prompt brings it again.
321  }
322}
323
324// Fills the state a session starts from: the saved shown/hidden choice, the session's name
325// and the figures.
326async function fill($: EngineInterface) {
327  try {
328    const stored = await $.store.get(HIDDEN_KEY)
329    await update($, isHidden, () => stored === true)
330  } catch {
331    // No stored choice: the meters show.
332  }
333
334  // /clear and /resume empty the state just after the SessionStart that names the session
335  // they start may have run, so the name it brought is written again.
336  const name = nameSeen
337  if (name !== undefined) {
338    try {
339      await update($, sessionName, () => name)
340    } catch {
341      // The next prompt brings it again.
342    }
343  }
344
345  try {
346    await refresh($)
347  } catch {
348    // No reading yet, from this session or a saved one; session.measure fills it in
349    // after the next response.
350  }
351}
352
353// Runs the minute check at the start of each minute, so the countdowns turn over with the
354// clock's minutes. Each wait is measured from the time again, which keeps it on the minute,
355// and is set before the check runs, so a check that never finishes doesn't stop the next.
356async function checkOnTheMinute($: EngineInterface) {
357  const now = await $.clock.now().catch(() => 0)
358  $.clock.after(CHECK_MS - (now % CHECK_MS), async () => {
359    void checkOnTheMinute($)
360    try {
361      await refresh($)
362    } catch {
363      // The next check tries again.
364    }
365
366    await keepCommand($)
367  })
368}
369
370// Whether a timer is waiting for the cache to go cold. The minute check would show it up to
371// a minute late, so one timer waits for the moment itself. A response in the meantime moves
372// that moment later, and the timer, finding it so, waits again: one is enough.
373let isWatchingCache = false
374
375function watchCache($: EngineInterface, wait: number) {
376  if (isWatchingCache) {
377    return
378  }
379
380  isWatchingCache = true
381  $.clock.after(wait, async () => {
382    isWatchingCache = false
383    try {
384      const touched = await read($, cachedAt)
385      const now = await $.clock.now()
386      if (touched === 0) {
387        return
388      }
389
390      const left = touched + cacheMs - now
391      if (left > 0) {
392        watchCache($, left)
393        return
394      }
395
396      await update($, time, () => now)
397      await showStatus($)
398    } catch {
399      // The next minute check shows it.
400    }
401  })
402}
403
404// A response ended: the cache was used just before, so its time starts over. Anything else
405// that moves the context window without a response (a compaction, which leaves the window
406// with no reading) starts a different prompt, which the old cache does not serve.
407async function useCache($: EngineInterface, hasResponse: boolean) {
408  if (!hasResponse) {
409    await update($, cachedAt, () => 0)
410    return
411  }
412
413  const now = await $.clock.now()
414  await update($, time, () => now)
415  await update($, cachedAt, () => now)
416  watchCache($, cacheMs)
417}
418
419// Whether this load of the module runs the minute check. session.start starts it, and
420// one follows every load of the module; should a load come without one, the next reading
421// starts it, and adds /limits.
422let isChecking = false
423
424async function startChecking($: EngineInterface) {
425  if (!isChecking) {
426    isChecking = true
427    await checkOnTheMinute($)
428  }
429}
430
431const COMMAND = { name: 'limits', description: 'Show or hide the usage limits meter', argumentHint: 'on|off' }
432
433// Adds /limits, replacing any registration the session already has.
434async function registerCommand($: EngineInterface) {
435  try {
436    await $.command.register(COMMAND)
437  } catch {
438    // Without the command the meters still work; they just can't be hidden.
439  }
440}
441
442// Adds /limits again when the session no longer lists it: a desktop app session that
443// was running when the mod was updated lost it.
444async function keepCommand($: EngineInterface) {
445  try {
446    if (!(await $.command.list()).some(c => c.name === COMMAND.name)) {
447      await registerCommand($)
448    }
449  } catch {
450    // The next check looks again.
451  }
452}
453
454// What `/limits <args>` asks for: show, hide, flip, or undefined for anything else.
455const wanted = (args: string, hidden: boolean): boolean | undefined => {
456  const word = args.trim().toLowerCase()
457  if (word === '') return !hidden
458  if (word === 'off') return true
459  if (word === 'on') return false
460  return undefined
461}
462
463export const register: Register = (on, options) => {
464  cacheMs = CACHE_TTLS[options.cacheTtl === '1h' ? '1h' : '5m']
465
466  on('session.start', async ($, e, next) => {
467    await registerCommand($)
468    await fill($)
469    await startChecking($)
470
471    return next(e)
472  })
473
474  // /clear and /resume empty the session's state and run no session.start after it, while
475  // the engine keeps its figures, so the meters would stay away until a window moved.
476  on('session.end', async ($, e, next) => {
477    if (e.reason === 'clear' || e.reason === 'resume') {
478      $.clock.after(REFILL_DELAY_MS, () => void fill($))
479    }
480
481    return next(e)
482  })
483
484  // Claude Code tells a mod the session's name only through these two settings hook events:
485  // at the start (a --name, or the name of a session resumed), and with each prompt, which
486  // brings a /rename. Nothing else of either is read, and both go on as they came.
487  on('classic.SessionStart', async ($, e, next) => {
488    await nameSession($, e.session_title)
489    return next(e)
490  })
491
492  on('classic.UserPromptSubmit', async ($, e, next) => {
493    await nameSession($, e.session_title)
494    return next(e)
495  })
496
497  on('session.measure', async ($, e, next) => {
498    if (!isChecking) {
499      await registerCommand($)
500      await startChecking($)
501    }
502
503    // The window's fill moves with every response, and has no reading yet after a compaction.
504    const isContextMoved = e.changed.includes('context')
505    if (isContextMoved) {
506      await useCache($, e.context.tokens !== undefined)
507    }
508
509    if (e.changed.includes('rateLimits')) {
510      const now = await $.clock.now()
511      const reading = known(e.rateLimits)
512      await update($, time, () => now)
513      await update($, measuredAt, () => now)
514      await update($, limits, () => current(reading, now))
515      await showStatus($)
516
517      // Saved for the other sessions, which pick it up at their next minute check. A
518      // reading with no windows (no subscription) would empty their meters.
519      if (reading.length > 0) {
520        try {
521          await $.store.set(READING_KEY, { at: now, limits: reading } satisfies Reading)
522        } catch {
523          // The other sessions keep the reading they have.
524        }
525      }
526    } else if (isContextMoved) {
527      await showStatus($)
528    }
529
530    return next(e)
531  })
532
533  on('command.run', { command: 'limits' }, async ($, e) => {
534    const hidden = await read($, isHidden)
535    // A plugin's own $.command.run can leave args out; typed commands carry "".
536    const hide = wanted(e.args ?? '', hidden)
537    if (hide === undefined) {
538      return { text: 'Usage: /limits shows or hides the limits meter; /limits on and /limits off set it.' }
539    }
540
541    await update($, isHidden, () => hide)
542    await showStatus($)
543    try {
544      await $.store.set(HIDDEN_KEY, hide)
545    } catch {
546      return { text: `Limits meter ${hide ? 'hidden' : 'shown'} for this session; the choice could not be saved for later ones.` }
547    }
548
549    if (hide) {
550      return { text: 'Limits meter hidden. /limits brings it back.' }
551    }
552
553    try {
554      await refresh($)
555    } catch {
556      // Answer from the figures the state has.
557    }
558
559    if ((await read($, limits)).length === 0) {
560      return {
561        text: 'Limits meter shown, but there are no usage figures yet. Claude Code gets them with its next response (on a Claude subscription).',
562      }
563    }
564
565    return { text: 'Limits meter shown.' }
566  })
567
568  on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
569    const engine = await next(e)
570    if (await read($, isHidden)) {
571      return engine
572    }
573
574    const name = await read($, sessionName)
575    const list = await read($, limits)
576    const touched = await read($, cachedAt)
577    if (list.length === 0 && touched === 0 && name === '') {
578      return engine
579    }
580
581    // Read only when there are figures or a cache, so the minute's time redraws nothing
582    // otherwise.
583    const now = list.length === 0 && touched === 0 ? 0 : await read($, time)
584    const windows = readingsAt(list, now)
585    const cache = cacheAt(touched, now, e.props.isWorking)
586
587    if (windows.length === 0 && cache === undefined && name === '') {
588      return engine
589    }
590
591    // The most detailed tier that fits between the indents: first the tiers with bars led
592    // by the name, then each tier as it was without it.
593    const columns = e.viewport?.columns ?? 80
594    const room = columns - 2 * INDENT
595    const tiers = [
596      ...(name === '' ? [] : TIERS.filter(t => t.bar > 0).map(tier => ({ tier, hasName: true }))),
597      ...TIERS.map(tier => ({ tier, hasName: false })),
598    ]
599    const layout = tiers.map(({ tier, hasName }) => {
600      const meters: Meter[] = [
601        ...windows.map(r => windowMeter(r, tier)),
602        ...(tier.cache && cache !== undefined ? [cacheMeter(cache, tier)] : []),
603      ]
604      const metersWidth =
605        meters.reduce((sum, m) => sum + meterWidth(tier, m), 0) +
606        SEPARATOR.length * Math.max(0, meters.length - 1)
607      const nameRoom = Math.min(NAME_CELLS, room - metersWidth - (meters.length > 0 ? SEPARATOR.length : 0))
608      const shownName =
609        hasName && nameRoom >= Math.min(cellsOf(name), NAME_MIN_CELLS) ? clip(name, nameRoom) : undefined
610      const nameWidth = shownName === undefined ? 0 : cellsOf(shownName) + (meters.length > 0 ? SEPARATOR.length : 0)
611
612      return { tier, meters, shownName, hasName, width: nameWidth + metersWidth }
613    }).find(l => (l.hasName ? l.shownName !== undefined : l.meters.length > 0) && l.width <= room)
614
615    if (layout === undefined) {
616      return engine
617    }
618
619    const { Box, Text } = $.ui.resolve(e)
620
621    const bar = (percent: number, cells: number, color: string) => {
622      const eighths = Math.round((Math.min(100, Math.max(0, percent)) / 100) * cells * 8)
623      const full = Math.floor(eighths / 8)
624      const partial = EIGHTHS[eighths % 8] ?? ''
625      const empty = cells - full - (partial === '' ? 0 : 1)
626
627      return (
628        <Box flexDirection="row" marginRight={1}>
629          {[
630            ...(full > 0 ? [<Text color={color}>{'█'.repeat(full)}</Text>] : []),
631            ...(partial !== '' ? [<Text color={color} backgroundColor={TRACK}>{partial}</Text>] : []),
632            ...(empty > 0 ? [<Text backgroundColor={TRACK}>{' '.repeat(empty)}</Text>] : []),
633          ]}
634        </Box>
635      )
636    }
637
638    // The session's name, bold, set off from the meters as they are from each other.
639    const lead =
640      layout.shownName === undefined
641        ? []
642        : [
643            <Text bold>{layout.shownName}</Text>,
644            ...(layout.meters.length > 0 ? [<Text dimColor>{SEPARATOR}</Text>] : []),
645          ]
646
647    // The engine's line is a full-width row (hint left, notices right) that paints
648    // over anything placed on it, and a Box around it may not size it. So it stays
649    // as it is, and the meters take the row under it, centred on the terminal.
650    return (
651      <Box flexDirection="column">
652        {engine}
653        <Box flexDirection="row" marginLeft={Math.max(0, Math.floor((columns - layout.width) / 2) - INDENT)}>
654          {lead}
655          {layout.meters.map((meter, index) => (
656            <Box flexDirection="row">
657              {[
658                ...(index > 0 ? [<Text dimColor>{SEPARATOR}</Text>] : []),
659                <Text dimColor>{`${meter.label} `}</Text>,
660                ...(layout.tier.bar > 0 ? [bar(meter.fill, layout.tier.bar, meter.color)] : []),
661                meter.isDim ? (
662                  <Text dimColor>{meter.value}</Text>
663                ) : (
664                  <Text color={meter.color} bold>
665                    {meter.value}
666                  </Text>
667                ),
668                ...(meter.countdown !== undefined ? [<Text dimColor>{meter.countdown}</Text>] : []),
669                ...(valuePad(meter) !== '' ? [<Text>{valuePad(meter)}</Text>] : []),
670              ]}
671            </Box>
672          ))}
673        </Box>
674      </Box>
675    )
676  })
677}
678
types/index.d.ts 18 lines
1export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
2
3// A session's figures as saved for the others: `at` is when its engine got them.
4export type Reading = { at: number; limits: Limit[] }
5
6declare module 'claude-code' {
7  interface PluginState {
8    'limits-meter': {
9      limits: Limit[]
10      isHidden: boolean
11      time: number
12      measuredAt: number
13      cachedAt: number
14      name: string
15    }
16  }
17}
18