Claude Code mod: one line above the prompt with the context window fill (weather, with a compact button beside it), the subscription quota left (5-hour and…

A Claude Code mod (needs Claude Code 2.1.288 or later; tested on 2.1.288 and 2.1.291). It draws one line above the prompt, in the terminal and in the desktop Code tab:

In the terminal, with language set to en:
☂ Showers 54% (108k/200k) │ 5h ████████▊░ 88% wk ███████▋░░ 77% │ main ● [5 uncommitted] · ↑2 unpushed [Hide]
Claude Code only; Codex has no mods.
⟲ compact button sits beside the weather (☂ Showers 60% (120k/200k) ⟲ compact), at any fill./compact as if you had typed it, so it works the same in the terminal and in the desktop app, and the command shows in the transcript. The band shows ⟳ Compacting… until it ends.autoCompactThreshold of the /context breakdown, estimated locally, no request). Measured, it is the window less 33k, so the toast comes at 117k of 200k (58.5%) and 917k of 1M. With auto-compaction off, the window itself is the limit.session.measure's rateLimits), shown the moment a window moves a whole point;https://api.anthropic.com/api/oauth/usage, so use from other sessions shows too. It is fetched through $.http.fetch with the session's own credential ($.session.authorize(); the token never reaches the mod): at session start, when a turn ends (at most once a minute) and otherwise every 3 minutes. A failure or a 429 doubles the wait, up to 15 minutes.$.store, which every session reads, so open sessions share one fetch and none overwrites another's backoff.not on GitHub. It shows no upstream instead when a remote already has a branch of that name (pushed without -u), or when the repo's remotes are all off GitHub.git --no-optional-locks, so it never takes the index lock from your own git commands.$.process is CLI only), the line shows the context part alone.Commit the uncommitted changes (in the band's language) as your prompt, so the session starts the commit (queued until the current turn ends).Hide collapses the line to a small ▸ ctx/git button; press it to bring the line back.The band's own words (wk, uncommitted, clean, not on GitHub, unpushed, the prompt the uncommitted button sends, and the toasts) follow the language you use. The weather names and the short labels (5h, Hide, compact) stay English.
The plugin's language option picks the language, auto by default:
auto, in the desktop Code tab, follows the Claude desktop app's display language. It is read from locale in the app's own ~/Library/Application Support/Claude/config.json: an internal file, not a documented interface, which also holds the app's sign-in cache, so the mod reads it again only when its modification time moves and keeps nothing but locale.auto, in the terminal (and in the desktop when the app's language cannot be read), follows Claude Code's own language setting (the language Claude replies in), then the locale (LC_ALL, LC_MESSAGES, LANG). With neither, it is English.ja or en fixes Japanese or English on every surface.Japanese and English are written into the mod. Any other language is translated from English the first time it appears, by one small model call (haiku, through the session's own client, so it counts against your usage). Until it lands, the band shows English; it then switches within seconds. The translation is kept in the plugin's $.store per language and reused by every session, and translated again only when the English words change. A translation that loses a {placeholder}, runs too long for the band, or is not well-formed is thrown away, and that language then stays in English in every session, with no further call, until the English words change.
A switch shows without a new session: a change of Claude Code's language in /config at once, any other change within 3 seconds.
Change the option in the /config panel, where it is a picker of auto, ja and en; the value is saved under pluginConfigs in ~/.claude/settings.json.
In a Claude Code session (2.1.288 or later):
/plugin install context-git-band --marketplace mlabo-org/context-git-band
Or from your shell:
claude plugin marketplace add mlabo-org/context-git-band
claude plugin install context-git-band@context-git-band
Then start a new session. In the desktop app, you can also add the marketplace and install from + > Plugins.
To try a local copy for one session without installing it:
claude --plugin-dir /path/to/context-git-band
claude plugin validate ~/plugins/context-git-band
claude plugin test ~/plugins/context-git-band
The weather metaphor and its five levels come from the Token Weather example in Getting started with Claude Code mods on the Anthropic blog. The code here is written independently and does not include that example's code.
hooks/register.tsx 682 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionRateLimit } from 'claude-code'
3
4import type { GitInfo, QuotaReading, QuotaWindow, Words } from '../types'
5
6const git = atom({ plugin: 'context-git-band', key: 'git' } as const, null)
7const isHidden = atom({ plugin: 'context-git-band', key: 'isHidden' } as const, false)
8const isCompacting = atom({ plugin: 'context-git-band', key: 'isCompacting' } as const, false)
9
10// Tokens at which a toast says that auto-compaction is near
11const compactAt = atom({ plugin: 'context-git-band', key: 'compactAt' } as const, null)
12
13// Claude Code compacts on its own at its threshold (the window less 33k as measured:
14// 167k of 200k, 967k of 1M). The toast comes this many tokens earlier, so one or two
15// heavy turns still fit before the automatic one runs mid-task.
16const COMPACT_MARGIN_TOKENS = 50_000
17
18// The context window's fill as weather, with the guide's thresholds
19const weather = (percent: number) => {
20 if (percent >= 90) return { icon: '↯', label: 'Compact Soon', color: 'red' }
21 if (percent >= 75) return { icon: '☇', label: 'Storm', color: 'red' }
22 if (percent >= 50) return { icon: '☂', label: 'Showers', color: 'yellow' }
23 if (percent >= 25) return { icon: '☁', label: 'Cloudy', color: 'cyan' }
24 return { icon: '☀', label: 'Clear', color: 'green' }
25}
26
27const kilo = (n: number) => `${Math.round(n / 1000)}k`
28
29
30// The language the band's words are in, as a key (`ja`, `en`, `fr`, `zh-tw`, or a
31// language name): Claude Code's (every surface), and the desktop app's display
32// language, which the desktop Code tab prefers
33const language = atom({ plugin: 'context-git-band', key: 'language' } as const, null)
34const appLanguage = atom({ plugin: 'context-git-band', key: 'appLanguage' } as const, null)
35// Tables translated from EN, by language key
36const translations = atom({ plugin: 'context-git-band', key: 'translations' } as const, null)
37
38// How often a change of either is picked up
39const LANGUAGE_CHECK_MS = 3_000
40
41// The band's own words as templates; `{name}` is filled in. Japanese and English
42// are written here; any other language is translated from English once (see
43// ensureWords). The weather names and the short labels (Hide, compact) stay English.
44const EN: Words = {
45 week: 'wk',
46 quotaAlt: '{label} {remaining}% left',
47 uncommitted: '{count} uncommitted',
48 commitPrompt: 'Commit the uncommitted changes',
49 clean: '✔ clean',
50 noUpstream: 'no upstream',
51 notOnGitHub: 'not on GitHub',
52 unpushed: '↑{count} unpushed',
53 compactSoon: 'Context {used}/{window}: compact soon',
54 compactFailed: 'compact could not run now',
55}
56
57const JA: Words = {
58 week: '週',
59 quotaAlt: '{label} 残{remaining}%',
60 uncommitted: '{count} 未コミット',
61 commitPrompt: '未コミットの変更をコミットして',
62 clean: '✔ クリーン',
63 noUpstream: 'upstreamなし',
64 notOnGitHub: 'GitHub未公開',
65 unpushed: '↑{count} 未push',
66 compactSoon: 'コンテキスト {used}/{window}:そろそろ compact',
67 compactFailed: '今は compact できません',
68}
69
70const WRITTEN: Record<string, Words> = { en: EN, ja: JA }
71
72const fill = (template: string, vars: Record<string, string | number>) =>
73 template.replace(/\{(\w+)\}/g, (whole, name: string) => (name in vars ? String(vars[name]) : whole))
74
75const wordsFor = (key: string | null, translated: Record<string, Words> | null) =>
76 (key === null ? undefined : (WRITTEN[key] ?? translated?.[key])) ?? EN
77
78const quotaColor = (remaining: number) => (remaining <= 10 ? 'red' : remaining <= 25 ? 'yellow' : 'green')
79
80// A gauge of the remaining percent, 10 cells, each split into eighths
81const METER_CELLS = 10
82const EIGHTHS = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉']
83
84const meterText = (remaining: number) => {
85 const eighths = Math.round((remaining / 100) * METER_CELLS * 8)
86 const full = Math.floor(eighths / 8)
87 const partial = EIGHTHS[eighths % 8] ?? ''
88 const filled = '█'.repeat(full) + partial
89 return { filled, empty: '░'.repeat(METER_CELLS - full - (partial === '' ? 0 : 1)) }
90}
91
92// The desktop draws the gauge as a rounded bar; colors read on light and dark
93const SVG_COLORS: Record<string, string> = { green: '#2ea043', yellow: '#d29922', red: '#e5534b' }
94const METER_WIDTH = 64
95const METER_HEIGHT = 8
96
97const meterSvg = (remaining: number) => {
98 const fill = Math.round((remaining / 100) * METER_WIDTH)
99 const r = METER_HEIGHT / 2
100 return (
101 `<svg xmlns="http://www.w3.org/2000/svg" width="${METER_WIDTH}" height="${METER_HEIGHT}" viewBox="0 0 ${METER_WIDTH} ${METER_HEIGHT}">` +
102 `<clipPath id="c"><rect width="${METER_WIDTH}" height="${METER_HEIGHT}" rx="${r}"/></clipPath>` +
103 `<g clip-path="url(#c)"><rect width="${METER_WIDTH}" height="${METER_HEIGHT}" fill="#8b949e" fill-opacity="0.3"/>` +
104 `<rect width="${fill}" height="${METER_HEIGHT}" fill="${SVG_COLORS[quotaColor(remaining)]}"/></g></svg>`
105 )
106}
107
108// `git status --porcelain=v1 -b`: first line is the branch, the rest are changed files
109const parseStatus = (stdout: string): GitInfo => {
110 const [head = '', ...rest] = stdout.split('\n').filter(line => line !== '')
111 const branchLine = head.replace(/^## /, '')
112 const name = branchLine.split('...')[0] ?? branchLine
113 const hasUpstream = branchLine.includes('...')
114 const ahead = /ahead (\d+)/.exec(branchLine)
115 const behind = /behind (\d+)/.exec(branchLine)
116
117 return {
118 branch: name.startsWith('No commits yet on ') ? name.slice(18) : name,
119 dirty: rest.length,
120 ahead: hasUpstream ? (ahead ? Number(ahead[1]) : 0) : null,
121 behind: behind ? Number(behind[1]) : 0,
122 notOnGitHub: false,
123 }
124}
125
126// `git remote -v` lists no remote, or a remote on GitHub
127const mayGoToGitHub = (remotes: string) => {
128 const urls = remotes.split('\n').filter(line => line.trim() !== '')
129 return urls.length === 0 || urls.some(line => line.includes('github.com'))
130}
131
132// `git for-each-ref --format=%(refname:lstrip=3) refs/remotes` names a branch
133// of this name on a remote, as when it was pushed without setting an upstream
134const isOnRemote = (refs: string, branch: string) => refs.split('\n').includes(branch)
135
136const EDITING_TOOLS = ['Bash', 'Edit', 'Write', 'NotebookEdit']
137
138let lastRefresh = 0
139
140// Reads git into the shared value; a folder that is not a repo, or a host
141// that cannot run commands, leaves the band showing the context part alone.
142async function refreshGit($: EngineInterface, force: boolean) {
143 const now = await $.clock.now()
144 if (!force && now - lastRefresh < 2000) return
145 lastRefresh = now
146
147 try {
148 const { exitCode, stdout } = await $.process.run(['git', '--no-optional-locks', 'status', '--porcelain=v1', '-b'], {
149 timeoutMs: 5000,
150 })
151 const info = exitCode === 0 ? parseStatus(stdout) : null
152 if (info !== null && info.ahead === null) {
153 const remotes = await $.process.run(['git', 'remote', '-v'], { timeoutMs: 5000 })
154 if (remotes.exitCode === 0 && mayGoToGitHub(remotes.stdout)) {
155 const refs = await $.process.run(
156 ['git', 'for-each-ref', '--format=%(refname:lstrip=3)', 'refs/remotes'],
157 { timeoutMs: 5000 },
158 )
159 info.notOnGitHub = refs.exitCode === 0 && !isOnRemote(refs.stdout, info.branch)
160 }
161 }
162 await update($, git, () => info)
163 } catch {
164 await update($, git, () => null)
165 }
166}
167
168// The subscription's 5-hour and weekly windows, from two sources:
169// - this session's API responses, pushed by `session.measure` (instant, this session's use only)
170// - the account usage endpoint (undocumented), polled (every session's use)
171// The newer reading wins. Polls are shared across sessions through `$.store`,
172// so any number of open sessions makes the requests of one.
173
174const quota = atom({ plugin: 'context-git-band', key: 'quota' } as const, null)
175
176// Undocumented and may change; it answers 429 to aggressive polling
177const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
178const OAUTH_BETA = 'oauth-2025-04-20'
179const POLL_GAP_MS = 180_000
180const EVENT_GAP_MS = 60_000
181const CHECK_EVERY_MS = 30_000
182const MAX_BACKOFF_MS = 900_000
183// How long a session that started a request keeps the others from starting one
184const CLAIM_MS = 15_000
185
186const KINDS = ['five_hour', 'seven_day']
187
188// Two store keys, so no writer overwrites the other's part: the newest reading
189// (this session's responses and every poll write it) and the poll's own
190// bookkeeping (only a poll writes it)
191const READING_KEY = 'quota:reading'
192const POLL_KEY = 'quota:poll'
193
194type Poll = { fetchedAt: number; failures: number; nextAt: number; claim: { until: number; token: string } | null }
195
196const NO_POLL: Poll = { fetchedAt: 0, failures: 0, nextAt: 0, claim: null }
197
198const loadPoll = async ($: EngineInterface): Promise<Poll> => {
199 const value = await $.store.get(POLL_KEY)
200 return typeof value === 'object' && value !== null ? { ...NO_POLL, ...(value as Partial<Poll>) } : { ...NO_POLL }
201}
202
203const loadReading = async ($: EngineInterface): Promise<QuotaReading | null> => {
204 const value = (await $.store.get(READING_KEY)) as QuotaReading | undefined
205 return value !== undefined && Array.isArray(value.windows) && typeof value.at === 'number' ? value : null
206}
207
208const isNewer = (next: QuotaReading, current: QuotaReading | null | undefined) =>
209 current === null || current === undefined || next.at > current.at
210
211const adopt = ($: EngineInterface, reading: QuotaReading) =>
212 update($, quota, current => (isNewer(reading, current) ? reading : current))
213
214// Shares a reading unless the store already holds a newer one
215async function shareReading($: EngineInterface, reading: QuotaReading) {
216 if (isNewer(reading, await loadReading($))) await $.store.set(READING_KEY, reading)
217}
218
219// A reading from this session's own API responses: shown at once and shared
220async function takeLive($: EngineInterface, rateLimits: SessionRateLimit[]) {
221 const windows: QuotaWindow[] = rateLimits
222 .filter(limit => KINDS.includes(limit.kind))
223 .map(({ kind, percentUsed, resetsAt }) => ({ kind, percentUsed, resetsAt }))
224 if (windows.length === 0) return
225 const reading = { windows, at: await $.clock.now() }
226 await adopt($, reading)
227 await shareReading($, reading)
228}
229
230type UsageWindow = { utilization?: number | null; resets_at?: string | null } | null | undefined
231
232const parseUsage = (text: string, at: number): QuotaReading | null => {
233 const body = JSON.parse(text) as Record<string, UsageWindow>
234 const windows = KINDS.flatMap(kind => {
235 const window = body[kind]
236 return typeof window?.utilization === 'number'
237 ? [{ kind, percentUsed: window.utilization, resetsAt: window.resets_at ?? undefined }]
238 : []
239 })
240 return windows.length === 0 ? null : { windows, at }
241}
242
243let isPolling = false
244
245// Takes what another session shared, then polls when `gapMs` has passed since
246// the last poll and no backoff or other session's request stands in the way.
247// The store has no compare-and-set: a session writes a claim with its own token
248// and goes ahead only if that token reads back, which narrows (not closes) the
249// window in which two sessions both poll.
250async function syncQuota($: EngineInterface, gapMs: number) {
251 const shared = await loadReading($)
252 if (shared !== null) await adopt($, shared)
253 if (isPolling) return
254 isPolling = true
255 try {
256 const poll = await loadPoll($)
257 const now = await $.clock.now()
258 if (now < poll.nextAt || (poll.claim !== null && now < poll.claim.until) || now - poll.fetchedAt < gapMs) return
259
260 // A subscription signs in with a bearer token; an API key has no such quota
261 const auth = await $.session.authorize()
262 if (auth === null || auth.kind !== 'bearer') return
263
264 const token = `${now}-${Math.random().toString(36).slice(2)}`
265 await $.store.set(POLL_KEY, { ...poll, claim: { until: now + CLAIM_MS, token } })
266 if ((await loadPoll($)).claim?.token !== token) return
267
268 let reading: QuotaReading | null = null
269 try {
270 const response = await $.http.fetch(USAGE_URL, {
271 auth: auth.handle,
272 headers: { 'anthropic-beta': OAUTH_BETA, Accept: 'application/json' },
273 })
274 if (response.ok) reading = parseUsage(response.text, now)
275 } catch {
276 reading = null
277 }
278
279 const latest = await loadPoll($)
280 if (reading === null) {
281 const failures = latest.failures + 1
282 await $.store.set(POLL_KEY, {
283 failures,
284 fetchedAt: now,
285 nextAt: now + Math.min(POLL_GAP_MS * 2 ** (failures - 1), MAX_BACKOFF_MS),
286 claim: null,
287 })
288 return
289 }
290 await $.store.set(POLL_KEY, { fetchedAt: now, failures: 0, nextAt: 0, claim: null })
291 await shareReading($, reading)
292 await adopt($, reading)
293 } finally {
294 isPolling = false
295 }
296}
297
298const remainingOf = (reading: QuotaReading | null) =>
299 (reading?.windows ?? []).map(({ kind, percentUsed }) => ({
300 kind,
301 remaining: Math.max(0, Math.min(100, Math.round(100 - percentUsed))),
302 }))
303
304// Runs `/compact` as if typed: the one way to compact that every host takes (the
305// desktop app's session refuses `$.session.compact`). It is queued until the session is
306// idle. The module flag is set before any await, so a second press does nothing.
307let isCompactRunning = false
308
309async function compactNow($: EngineInterface) {
310 if (isCompactRunning) return
311 isCompactRunning = true
312 try {
313 await update($, isCompacting, () => true)
314 let note: string | undefined
315 try {
316 await $.command.run({ command: 'compact' })
317 } catch (error) {
318 // The engine's own reason goes with it: why it refused is not the band's to guess
319 const reason = error instanceof Error ? error.message : String(error)
320 note = `${(await toastWords($)).compactFailed} (${reason})`
321 }
322 if (note !== undefined) $.ui.toast(note)
323 } finally {
324 isCompactRunning = false
325 await update($, isCompacting, () => false)
326 }
327}
328
329// The engine's own threshold, read off the /context breakdown (estimated
330// locally, no request); with auto-compaction off the window is the limit
331async function refreshCompactAt($: EngineInterface) {
332 const { context } = await $.session.usage({ breakdown: 'summary' })
333 const limit = context.breakdown?.autoCompactThreshold ?? context.window
334 await update($, compactAt, () => Math.max(0, limit - COMPACT_MARGIN_TOKENS))
335}
336
337let hasWarned = false
338
339// A language as a key: `ja` and `en` for the written tables, else a lowercased
340// locale tag (`fr`, `pt-br`, `zh-tw`, `sr-latin`) or language name (`french`);
341// null when it names no language (`C`, `POSIX`, a bare `UTF-8`)
342const languageKey = (raw: string): string | null => {
343 const lowered = raw.trim().toLowerCase()
344 // A locale's modifier names its script (sr_RS@latin); its encoding names nothing
345 const modifier = /@([a-z]+)/.exec(lowered)?.[1]
346 const text = lowered.replace(/[.@].*$/, '').replace(/_/g, '-')
347 if (text === '' || text === 'c' || text === 'posix' || /^utf-?8$/.test(text)) return null
348 if (/^(japanese|日本語)/.test(text) || /^ja(?:$|-)/.test(text)) return 'ja'
349 if (/^english/.test(text) || /^en(?:$|-)/.test(text)) return 'en'
350 const tag = /^([a-z]{2,3})(?:-([a-z0-9]+))?$/.exec(text)
351 if (tag === null) return text
352 const [, base = text, region] = tag
353 // Keep what changes the written language: zh-tw/zh-hant, pt-br, a script modifier
354 if (modifier !== undefined) return `${base}-${modifier}`
355 return region !== undefined && (base === 'zh' || base === 'pt') ? `${base}-${region}` : base
356}
357
358// `auto` follows Claude Code's own `language` setting (the language Claude replies
359// in), then the locale variables; English with nothing to go by
360async function claudeLanguage($: EngineInterface): Promise<string> {
361 const { language: replyLanguage } = (await $.settings.read()) as { language?: unknown }
362 const fromSetting = typeof replyLanguage === 'string' ? languageKey(replyLanguage) : null
363 if (fromSetting !== null) return fromSetting
364 const locale = (await $.env.get('LC_ALL')) || (await $.env.get('LC_MESSAGES')) || (await $.env.get('LANG')) || ''
365 return languageKey(locale) ?? 'en'
366}
367
368// The desktop app keeps its display language as `locale` in its own config.json,
369// an internal file that also holds its sign-in cache: read again only when its
370// mtime moves, and nothing but `locale` kept. Null where there is no such app.
371let appConfigMtime = -1
372
373async function readAppLanguage($: EngineInterface): Promise<string | null | undefined> {
374 const home = await $.env.get('HOME')
375 if (home === undefined) return null
376 const path = `${home}/Library/Application Support/Claude/config.json`
377 try {
378 const { mtimeMs } = await $.fs.stat(path)
379 if (mtimeMs === appConfigMtime) return undefined
380 appConfigMtime = mtimeMs
381 const { locale } = JSON.parse(String(await $.fs.read(path))) as { locale?: unknown }
382 return typeof locale === 'string' ? languageKey(locale) : null
383 } catch {
384 return null
385 }
386}
387
388// A translated table is kept in the store per language, stamped with the English
389// it came from, so a change of EN translates again
390const hashText = (text: string) => {
391 let hash = 5381
392 for (let i = 0; i < text.length; i += 1) hash = ((hash * 33) ^ text.charCodeAt(i)) >>> 0
393 return hash.toString(36)
394}
395const EN_VERSION = hashText(JSON.stringify(EN))
396const TRANSLATE_CLAIM_MS = 60_000
397const translating = new Set<string>()
398
399const placeholders = (template: string) => (template.match(/\{\w+\}/g) ?? []).sort().join()
400
401// A translation is taken whole or not at all: every key, every placeholder, one
402// line each, and no longer than the band can hold
403const checkWords = (value: unknown): Words | null => {
404 if (typeof value !== 'object' || value === null) return null
405 const table = value as Record<string, unknown>
406 for (const key of Object.keys(EN) as (keyof Words)[]) {
407 const text = table[key]
408 if (typeof text !== 'string' || text.trim() === '' || /[\n\[\]]/.test(text)) return null
409 if (placeholders(text) !== placeholders(EN[key])) return null
410 if (text.length > Math.max(24, EN[key].length * 2.5)) return null
411 }
412 return Object.fromEntries((Object.keys(EN) as (keyof Words)[]).map(key => [key, String(table[key])])) as Words
413}
414
415// A language's table as kept: its words, or `failed` when its translation did not
416// hold, which keeps that language in English
417type StoredWords = { version: string; words?: Words; failed?: true }
418
419// Makes the table for `key` ready: written, already translated, kept in the
420// store, or translated now by one small model call (the band shows English
421// until it lands). A failure fixes English for that language, in every session,
422// until the English words change; nothing is tried again before then.
423async function ensureWords($: EngineInterface, key: string | null) {
424 if (key === null || key in WRITTEN || translating.has(key)) return
425 translating.add(key)
426 let claimKey: string | undefined
427 let isDone = false
428 const storeKey = `words:${key}`
429 try {
430 if ((await read($, translations))?.[key] !== undefined) return
431 const stored = (await $.store.get(storeKey)) as Partial<StoredWords> | undefined
432 if (stored?.version === EN_VERSION && stored.failed === true) return
433 const kept = stored?.version === EN_VERSION ? checkWords(stored.words) : null
434 if (kept !== null) {
435 await update($, translations, current => ({ ...current, [key]: kept }))
436 return
437 }
438 const now = await $.clock.now()
439 const claim = `translating:${key}`
440 if (Number((await $.store.get(claim)) ?? 0) > now) return
441 await $.store.set(claim, now + TRANSLATE_CLAIM_MS)
442 claimKey = claim
443 const result = await $.model.complete({
444 model: 'haiku',
445 system: 'You translate the user interface strings of a one-line status bar in a developer tool.',
446 prompt:
447 `Translate the values of this JSON object into the language "${key}" (a language name or a locale tag). ` +
448 'Keep every key. Keep each {placeholder} exactly as written. Keep the ✔ and ↑ marks, and keep 5h, GitHub, ' +
449 'upstream, push and compact as they are. Make each value as short as a status bar needs. ' +
450 'Answer with the JSON object only.\n\n' +
451 JSON.stringify(EN),
452 maxTokens: 1024,
453 timeoutMs: 30_000,
454 })
455 if (!result.isAnswered) return
456 const json = /\{[\s\S]*\}/.exec(result.text)?.[0]
457 const words = json === undefined ? null : checkWords(JSON.parse(json))
458 if (words === null) return
459 await $.store.set(storeKey, { version: EN_VERSION, words })
460 await update($, translations, current => ({ ...current, [key]: words }))
461 isDone = true
462 } catch {
463 // English stays
464 } finally {
465 translating.delete(key)
466 if (claimKey !== undefined) {
467 await $.store.delete(claimKey).catch(() => undefined)
468 if (!isDone) await $.store.set(storeKey, { version: EN_VERSION, failed: true }).catch(() => undefined)
469 }
470 }
471}
472
473// Settles both languages and makes their tables ready; `ja` or `en` in the
474// option fixes them on every surface
475async function refreshLanguage($: EngineInterface, option: unknown) {
476 if (option === 'ja' || option === 'en') {
477 await update($, language, () => option)
478 await update($, appLanguage, () => null)
479 return
480 }
481 const claude = await claudeLanguage($)
482 await update($, language, current => (current === claude ? current : claude))
483 const app = await readAppLanguage($)
484 if (app !== undefined) await update($, appLanguage, current => (current === app ? current : app))
485 void ensureWords($, claude)
486 void ensureWords($, await read($, appLanguage))
487}
488
489// Toasts follow the band's rule: the desktop app's language only when the
490// session draws on the desktop alone, Claude Code's otherwise
491async function toastWords($: EngineInterface) {
492 const surfaces = await $.session.surfaces()
493 const isDesktopOnly = surfaces.length > 0 && surfaces.every(surface => surface === 'desktop')
494 const app = isDesktopOnly ? await read($, appLanguage) : null
495 return wordsFor(app ?? (await read($, language)), await read($, translations))
496}
497
498export const register: Register = (on, options) => {
499
500 on('session.start', async ($, e, next) => {
501 // A reload in the middle of a compaction leaves the flag behind
502 await update($, isCompacting, () => false)
503 await refreshLanguage($, options.language)
504 $.clock.every(LANGUAGE_CHECK_MS, () => void refreshLanguage($, options.language).catch(() => undefined))
505 await refreshGit($, true)
506 // A reload drops the old timer with the old module
507 $.clock.every(CHECK_EVERY_MS, () => void syncQuota($, POLL_GAP_MS).catch(() => undefined))
508 void syncQuota($, EVENT_GAP_MS).catch(() => undefined)
509 await refreshCompactAt($)
510
511 return next(e)
512 })
513
514 // A `/config` change of Claude Code's language shows at once
515 on('config.set', async ($, e, next) => {
516 const result = await next(e)
517 await refreshLanguage($, options.language).catch(() => undefined)
518
519 return result
520 }).catch(($, e, next) => next(e))
521
522 // Git is read in the background, so a prompt or a tool result never waits on it
523 on('prompt.submit', ($, e, next) => {
524 void refreshGit($, false).catch(() => undefined)
525
526 return next(e)
527 }).catch(($, e, next) => next(e))
528
529 on('tool.call', async ($, e, next) => {
530 const result = await next(e)
531 if (EDITING_TOOLS.includes(e.tool)) void refreshGit($, false).catch(() => undefined)
532
533 return result
534 }).catch(($, e, next) => next(e))
535
536 on('session.measure', async ($, e, next) => {
537 if (e.changed.includes('rateLimits')) await takeLive($, e.rateLimits)
538
539 return next(e)
540 })
541
542 on('turn.complete', async ($, e, next) => {
543 await refreshGit($, true)
544 void syncQuota($, EVENT_GAP_MS).catch(() => undefined)
545
546 await refreshCompactAt($)
547 const { context } = await $.session.usage()
548 const at = await read($, compactAt)
549 const tokens = context.tokens ?? 0
550 if (at !== null && tokens >= at && !hasWarned) {
551 hasWarned = true
552 $.ui.toast(fill((await toastWords($)).compactSoon, { used: kilo(tokens), window: kilo(context.window) }))
553 } else if (at !== null && tokens < at) {
554 hasWarned = false
555 }
556
557 return next(e)
558 })
559
560 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
561 if (e.props.hasSurvey) {
562 return next(e)
563 }
564
565 const elements = $.ui.resolve(e)
566 const claude = await read($, language)
567 const app = e.surface === 'desktop' ? await read($, appLanguage) : null
568 const t = wordsFor(app ?? claude, await read($, translations))
569 const { Box, Button, Text } = elements
570 const Svg = e.surface === 'desktop' && 'Svg' in elements ? elements.Svg : undefined
571
572 // Hidden: leave one small button that brings the band back
573 if (await read($, isHidden)) {
574 const beneath = await next(e)
575
576 return (
577 <Box flexDirection="column">
578 <Box>
579 <Button key="show" label="▸ ctx/git" onPress={() => update($, isHidden, () => false)} />
580 </Box>
581 {beneath ?? null}
582 </Box>
583 )
584 }
585
586 const { context } = await $.session.usage()
587 const info = await read($, git)
588 const quotas = remainingOf(await read($, quota)).map(q => ({ ...q, label: q.kind === 'seven_day' ? t.week : q.kind === 'five_hour' ? '5h' : q.kind }))
589
590 const hasContext = context.percent !== undefined
591 const w = weather(context.percent ?? 0)
592 const compacting = await read($, isCompacting)
593 const canCompact = hasContext && !e.props.isWorking && !compacting
594 const tokensText =
595 hasContext && context.tokens !== undefined ? ` (${kilo(context.tokens)}/${kilo(context.window)})` : ''
596 // The band is one site shared by every plugin: keep what the ones beneath draw
597 const below = await next(e)
598
599 return (
600 <Box flexDirection="column">
601 <Box>
602 {compacting ? (
603 <Text color="cyan">⟳ Compacting… </Text>
604 ) : hasContext ? (
605 <Box>
606 <Text color={w.color}>
607 {w.icon} {w.label} {context.percent}%{' '}
608 </Text>
609 {tokensText === '' ? null : <Text dimColor>{tokensText.trim()} </Text>}
610 {canCompact ? (
611 <Box>
612 <Button key="compact" label="⟲ compact" onPress={() => void compactNow($)} />
613 <Text> </Text>
614 </Box>
615 ) : null}
616 </Box>
617 ) : (
618 <Text dimColor>ctx -- </Text>
619 )}
620 {quotas.length === 0 ? null : (
621 <Box>
622 <Text dimColor>│ </Text>
623 {quotas.map(q => {
624 const color = quotaColor(q.remaining)
625 const meter = meterText(q.remaining)
626 return (
627 <Box key={q.label}>
628 <Text>{q.label} </Text>
629 {Svg === undefined ? (
630 <Text>
631 <Text color={color}>{meter.filled}</Text>
632 <Text dimColor>{meter.empty}</Text>
633 </Text>
634 ) : (
635 <Svg
636 source={meterSvg(q.remaining)}
637 alt={fill(t.quotaAlt, { label: q.label, remaining: q.remaining })}
638 width={METER_WIDTH}
639 height={METER_HEIGHT}
640 />
641 )}
642 <Text color={color}> {q.remaining}% </Text>
643 </Box>
644 )
645 })}
646 </Box>
647 )}
648 {info === null ? null : (
649 <Box>
650 <Text dimColor>│ </Text>
651 <Text bold>{info.branch}</Text>
652 {info.dirty > 0 ? (
653 <Box>
654 <Text color="yellow"> ● </Text>
655 <Button
656 key="commit"
657 label={fill(t.uncommitted, { count: info.dirty })}
658 onPress={() => void $.prompt.submit({ text: t.commitPrompt, asUser: true })}
659 />
660 </Box>
661 ) : (
662 <Text color="green"> {t.clean}</Text>
663 )}
664 <Text>
665 {info.ahead === null ? (
666 <Text dimColor>{info.notOnGitHub ? ` · ${t.notOnGitHub}` : ` · ${t.noUpstream}`}</Text>
667 ) : info.ahead > 0 ? (
668 <Text color="yellow"> · {fill(t.unpushed, { count: info.ahead })}</Text>
669 ) : null}
670 {info.behind > 0 ? <Text color="cyan"> · ↓{info.behind}</Text> : null}
671 <Text> </Text>
672 </Text>
673 </Box>
674 )}
675 <Button key="hide" label="Hide" onPress={() => update($, isHidden, () => true)} />
676 </Box>
677 {below ?? null}
678 </Box>
679 )
680 })
681}
682types/index.d.ts 40 lines1export type GitInfo = {
2 branch: string
3 dirty: number
4 ahead: number | null
5 behind: number
6 notOnGitHub: boolean
7}
8
9export type QuotaWindow = {
10 kind: string
11 percentUsed: number
12 resetsAt?: string
13}
14
15export type QuotaReading = {
16 windows: QuotaWindow[]
17 at: number
18}
19
20// The band's own words, as templates with {placeholders}
21export type Words = {
22 week: string
23 quotaAlt: string
24 uncommitted: string
25 commitPrompt: string
26 clean: string
27 noUpstream: string
28 notOnGitHub: string
29 unpushed: string
30 compactSoon: string
31 compactSkipped: string
32 compactFailed: string
33}
34
35declare module 'claude-code' {
36 interface PluginState {
37 'context-git-band': { git: GitInfo | null; isHidden: boolean; isCompacting: boolean; compactAt: number | null; language: string | null; appLanguage: string | null; translations: Record<string, Words> | null; quota: QuotaReading | null }
38 }
39}
40