Your Claude usage limit, as a one-line torch bar above the prompt that fades as you use it.

Your Claude usage limit, as a one-line torch bar above the prompt that fades as you use it.
src/register.tsx 222 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionRateLimit, Timer } from 'claude-code'
3
4import type { TorchDemo, TorchLook, TorchView } from '../types'
5import { DEFAULT_THRESHOLDS, formatClock, formatCountdown, lookFor } from './logic.ts'
6import type { Thresholds } from './logic.ts'
7import * as text from './text.ts'
8import type { WindowLeft } from './text.ts'
9
10const demo = atom({ plugin: 'usage-torch', key: 'demo' } as const, null)
11const view = atom({ plugin: 'usage-torch', key: 'view' } as const, null)
12const countdown = atom({ plugin: 'usage-torch', key: 'countdown' } as const, '')
13
14const BAR_CELLS = 10
15// The bar takes the flame's color for the state: bright, low, out.
16const BAR_COLORS: Record<TorchLook, string> = { awake: '#EF9F27', tired: '#D85A30', sleep: '#888780' }
17const DEMOS: readonly TorchDemo[] = ['awake', 'tired', 'sleep']
18const DEMO_PERCENT_LEFT: Record<TorchLook, number> = { awake: 82, tired: 18, sleep: 0 }
19const DEMO_RESET_MS = 12 * 60_000 + 30_000
20const TICK_MS = 1000
21// From this width the torch sits beside the band beneath it; narrower, that band goes on a line of its own.
22const SIDE_BY_SIDE_COLUMNS = 110
23
24// Module state: a reload starts it over, the host keeps what the drawing reads in $.state.
25let thresholds: Thresholds = DEFAULT_THRESHOLDS
26// The last real reading: the window closest to its limit, and what is left of every window.
27let real: { percentUsed: number; resetsAt: number | null; kind: string | null; windows: WindowLeft[] } | null = null
28// Whether a measurement came in: before one, the band shows a waiting line.
29let measured = false
30let timer: Timer | undefined
31
32const viewFor = (
33 look: TorchLook,
34 percentLeft: number,
35 resetsAt: number | null,
36 kind: string | null = null,
37 windows: WindowLeft[] | null = null,
38): TorchView => ({ look, percentLeft, resetsAt, kind, windows })
39
40const clockOf = (resetsAt: number | null): string =>
41 resetsAt === null ? '' : formatClock(resetsAt, -new Date(resetsAt).getTimezoneOffset())
42
43const barOf = (percentLeft: number): string => {
44 const lit = Math.round((Math.min(100, Math.max(0, percentLeft)) / 100) * BAR_CELLS)
45 return '▰'.repeat(lit) + '▱'.repeat(BAR_CELLS - lit)
46}
47
48function realView(): TorchView | null {
49 if (real === null) return null
50 const percentLeft = leftOf(real.percentUsed)
51 return viewFor(lookFor(real.percentUsed, thresholds), percentLeft, real.resetsAt, real.kind, real.windows)
52}
53
54// Before the first measurement the band waits; after one with no windows (no subscription) it hides.
55function shownView(): TorchView | null {
56 return realView() ?? (measured ? null : { ...viewFor('awake', 100, null), isPending: true })
57}
58
59const leftOf = (percentUsed: number): number => Math.max(0, Math.round(100 - percentUsed))
60
61// The 5-hour window reads first, then the weekly one, then any other in the order reported.
62const WINDOW_ORDER = ['five_hour', 'seven_day']
63const rankOf = (kind: string): number => {
64 const i = WINDOW_ORDER.indexOf(kind)
65 return i === -1 ? WINDOW_ORDER.length : i
66}
67
68// The window that binds first: the most used of those the last response reported.
69function readingOf(limits: readonly SessionRateLimit[]) {
70 if (limits.length === 0) return null
71 const w = limits.reduce((a, b) => (b.percentUsed > a.percentUsed ? b : a))
72 const resetsAt = w.resetsAt === undefined ? null : Date.parse(w.resetsAt)
73 const windows = [...limits]
74 .sort((a, b) => rankOf(a.kind) - rankOf(b.kind))
75 .map(l => ({ kind: l.kind, percentLeft: leftOf(l.percentUsed) }))
76 return { percentUsed: w.percentUsed, resetsAt: Number.isNaN(resetsAt) ? null : resetsAt, kind: w.kind, windows }
77}
78
79// Draws the real reading unless a demo holds the band; leaving sleep says the torch relit.
80async function showReal($: EngineInterface) {
81 if ((await read($, demo)) !== null) return
82 const now = await $.clock.now()
83 const next = shownView()
84 const cur = await read($, view)
85 if (next?.look === 'sleep' && next.resetsAt !== null) {
86 const left = formatCountdown(next.resetsAt - now)
87 await update($, countdown, () => left)
88 }
89 await update($, view, () => next)
90 if (cur?.look === 'sleep' && next !== null && next.look !== 'sleep') $.ui.toast(text.WAKE_TOAST)
91}
92
93// Once a second while asleep: the countdown ticks, and the window's reset is noticed here,
94// since no turn runs while the limit is hit.
95async function step($: EngineInterface) {
96 const v = await read($, view)
97 if (v !== null && v.look === 'sleep' && v.resetsAt !== null) {
98 const now = await $.clock.now()
99 if (now >= v.resetsAt && real !== null && (await read($, demo)) === null) {
100 const kind = real.kind
101 const windows = real.windows.map(w => (w.kind === kind ? { ...w, percentLeft: 100 } : w))
102 real = { percentUsed: 0, resetsAt: null, kind, windows }
103 await showReal($)
104 } else {
105 const left = formatCountdown(v.resetsAt - now)
106 if (left !== (await read($, countdown))) await update($, countdown, () => left)
107 }
108 }
109
110 timer = $.clock.after(TICK_MS, () => void step($))
111}
112
113export const register: Register = (on, options) => {
114 const { tiredBelowPercent, sleepAtPercentUsed } = options
115 thresholds = {
116 tiredBelowPercent: typeof tiredBelowPercent === 'number' ? tiredBelowPercent : DEFAULT_THRESHOLDS.tiredBelowPercent,
117 sleepAtPercentUsed: typeof sleepAtPercentUsed === 'number' ? sleepAtPercentUsed : DEFAULT_THRESHOLDS.sleepAtPercentUsed,
118 }
119
120 on('session.start', async ($, e, next) => {
121 await $.command.register({
122 name: 'torch',
123 description: text.COMMAND_DESCRIPTION,
124 argumentHint: text.COMMAND_HINT,
125 })
126 timer?.cancel()
127 void step($)
128
129 const result = await next(e)
130 real = readingOf((await $.session.usage()).rateLimits)
131 await showReal($)
132 return result
133 })
134
135 // Every measurement counts: the first one with no windows is what hides the waiting band.
136 on('session.measure', async ($, e, next) => {
137 measured = true
138 real = readingOf(e.rateLimits)
139 await showReal($)
140 return next(e)
141 })
142
143 on('command.run', { command: 'torch' }, async ($, e) => {
144 const [sub, arg] = e.args.trim().split(/\s+/)
145
146 if (sub === 'demo' && arg === 'off') {
147 await update($, demo, () => null)
148 await update($, view, () => null)
149 await showReal($)
150 return { text: text.DEMO_OFF }
151 }
152
153 // A bare /torch reports the figures, like /torch status.
154 if (sub === undefined || sub === '' || sub === 'status') {
155 const v = await read($, view)
156 if (v === null || v.isPending === true) return { text: text.NO_READING }
157 return { text: `Usage Torch: ${text.usageLine(v.percentLeft, v.kind, clockOf(v.resetsAt), v.windows)}` }
158 }
159
160 const chosen = DEMOS.find(d => d === arg)
161 if (sub === 'demo' && chosen !== undefined) {
162 const now = await $.clock.now()
163 const resetsAt = chosen === 'sleep' ? now + DEMO_RESET_MS : null
164 await update($, demo, () => chosen)
165 await update($, countdown, () => (resetsAt === null ? '' : formatCountdown(resetsAt - now)))
166 await update($, view, () => viewFor(chosen, DEMO_PERCENT_LEFT[chosen], resetsAt))
167 return { text: text.DEMO_ON(chosen) }
168 }
169
170 return { text: text.USAGE }
171 })
172
173 // The torch draws its line and keeps what the plugins beneath draw beside it, so it shares the
174 // spot above the prompt (with context-band, say) instead of taking it.
175 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
176 if (e.props.hasSurvey) return next(e)
177 const v = await read($, view)
178 if (v === null) return next(e)
179 const below = await next(e)
180
181 const clock = clockOf(v.resetsAt)
182 const usage = v.isPending === true ? text.WAITING : text.usageLine(v.percentLeft, v.kind, clock, v.windows)
183
184 if (e.surface !== 'terminal') {
185 const { Box, Text } = $.ui.resolve(e)
186 const head = v.isPending === true ? 'Usage Torch' : text.oneLine(v.percentLeft)
187 return (
188 <Box flexDirection="column">
189 <Text dimColor>{`${head} · ${usage}`}</Text>
190 {below}
191 </Box>
192 )
193 }
194
195 const { Box, Text } = $.ui.resolve(e)
196 const isOut = v.look === 'sleep'
197 const isResting = isOut && v.resetsAt !== null
198 const left = isResting ? await read($, countdown) : ''
199
200 const line = (
201 <Box flexDirection="row" gap={1}>
202 <Text color={BAR_COLORS[v.look]} bold>
203 {text.LABEL}
204 </Text>
205 {v.isPending !== true && <Text color={BAR_COLORS[v.look]}>{barOf(v.percentLeft)}</Text>}
206 <Text wrap="truncate-end" dimColor>
207 {isOut
208 ? [text.OUT_OF_LIGHT, isResting ? `${left} · ${text.relightsAt(clock)}` : ''].filter(Boolean).join(' · ')
209 : usage}
210 </Text>
211 </Box>
212 )
213
214 return (
215 <Box flexDirection={e.props.bodyColumns >= SIDE_BY_SIDE_COLUMNS ? 'row' : 'column'} columnGap={3}>
216 {line}
217 {below}
218 </Box>
219 )
220 })
221}
222src/logic.ts 31 lines1// Pure rules: usage to state, countdown text.
2
3export type Look = 'awake' | 'tired' | 'sleep'
4
5export type Thresholds = { tiredBelowPercent: number; sleepAtPercentUsed: number }
6
7export const DEFAULT_THRESHOLDS: Thresholds = { tiredBelowPercent: 30, sleepAtPercentUsed: 100 }
8
9/** The state for a window's fill: asleep at the limit, tired below the threshold left. */
10export function lookFor(percentUsed: number, t: Thresholds = DEFAULT_THRESHOLDS): Look {
11 if (percentUsed >= t.sleepAtPercentUsed) return 'sleep'
12 if (100 - percentUsed < t.tiredBelowPercent) return 'tired'
13 return 'awake'
14}
15
16const pad = (n: number): string => String(n).padStart(2, '0')
17
18/** Time left as h:mm from an hour up, m:ss below; never 0:00 while time remains. */
19export function formatCountdown(ms: number): string {
20 const total = Math.max(0, Math.ceil(ms / 1000))
21 if (total >= 3600) return `${Math.floor(total / 3600)}:${pad(Math.floor((total % 3600) / 60))}`
22 return `${Math.floor(total / 60)}:${pad(total % 60)}`
23}
24
25/** A wall clock time as HH:MM, given the local offset in minutes east of UTC. */
26export function formatClock(epochMs: number, offsetMinutes: number): string {
27 const minutes = Math.floor((epochMs + offsetMinutes * 60_000) / 60_000)
28 const day = ((minutes % 1440) + 1440) % 1440
29 return `${pad(Math.floor(day / 60))}:${pad(day % 60)}`
30}
31src/text.ts 45 lines1// Every string the mod shows. English only; no em dashes (a test holds this).
2
3export const relightsAt = (clock: string): string => `Relights at ${clock}`
4export const WAKE_TOAST = 'Torch relit'
5export const oneLine = (percentLeft: number): string => `Usage Torch ${percentLeft}%`
6
7const WINDOW_NAMES: Readonly<Record<string, string>> = {
8 five_hour: '5-hour limit',
9 seven_day: 'weekly limit',
10 spend_limit: 'spend limit',
11}
12export const windowName = (kind: string): string => WINDOW_NAMES[kind] ?? kind.replace(/_/g, ' ')
13
14const SHORT_NAMES: Readonly<Record<string, string>> = { five_hour: '5h', seven_day: 'week', spend_limit: 'spend' }
15const shortName = (kind: string): string => SHORT_NAMES[kind] ?? kind.replace(/_/g, ' ')
16
17export type WindowLeft = { kind: string; percentLeft: number }
18
19/** The figures in one line: what is left side by side when there are several windows, and when it refills. */
20// `kind` and `windows` may be missing on a view an older version of the mod left in the session's state.
21export function usageLine(
22 percentLeft: number,
23 kind: string | null | undefined,
24 clock: string,
25 windows?: readonly WindowLeft[] | null,
26): string {
27 const parts =
28 windows != null && windows.length > 1
29 ? windows.map(w => `${shortName(w.kind)} ${w.percentLeft}%`)
30 : [`${percentLeft}% left`, ...(typeof kind === 'string' ? [windowName(kind)] : [])]
31 if (clock !== '') parts.push(`resets ${clock}`)
32 return parts.join(' · ')
33}
34
35export const LABEL = 'Torch'
36export const OUT_OF_LIGHT = 'out of light'
37
38export const COMMAND_DESCRIPTION = 'Show Usage Torch figures, or simulate a state'
39export const COMMAND_HINT = '[status|demo awake|tired|sleep|off]'
40export const DEMO_ON = (look: string): string => `Usage Torch demo: ${look}. Real usage is ignored until /torch demo off.`
41export const DEMO_OFF = 'Usage Torch demo off.'
42export const USAGE = 'Usage: /torch status, /torch demo awake|tired|sleep, /torch demo off'
43export const WAITING = 'Usage shows after the first reply'
44export const NO_READING = 'Usage Torch has no usage reading yet. It arrives with the first reply.'
45types/index.d.ts 27 lines1export type TorchLook = 'awake' | 'tired' | 'sleep'
2
3export type TorchDemo = TorchLook
4
5/** What the band shows: the state and the window it reads. */
6export type TorchView = {
7 look: TorchLook
8 percentLeft: number
9 resetsAt: number | null
10 /** The rate-limit window shown (`five_hour`, `seven_day`); null in a demo. */
11 kind: string | null
12 /** What is left of every window the last reading reported, 5-hour first; null in a demo. */
13 windows?: { kind: string; percentLeft: number }[] | null
14 /** True while the session has had no reading yet: the band shows, waiting for figures. */
15 isPending?: boolean
16}
17
18declare module 'claude-code' {
19 interface PluginState {
20 'usage-torch': {
21 demo: TorchDemo | null
22 view: TorchView | null
23 countdown: string
24 }
25 }
26}
27