A status line on its own band above the prompt: model, folder and branch, context, 5h/7d limits and cache, wrapping instead of cutting. Off by default…

A status line on its own band above the prompt: context percent and tokens, the 5h and 7d rate limits with a reset countdown, a cache dot (ok / over), then model, folder and branch. Nothing is ever cut or dropped on a narrow terminal: each item is kept whole and wraps onto a further row. No progress bars, numbers only. The engine's own hint row under the prompt (mode label, esc to interrupt, its background-task pill) is left to the engine; this mod no longer draws a ⎿ pill row. The engine's [-] collapses the band like any other.
It is off by default. Turn it on with:
/statusline on
/statusline off turns it off./statusline with no argument opens its settings pane (On / Off).statusLine out of settings.json and keeps a copy in settings.json.statusline.bak; turning it off puts it back. If settings.json is not valid JSON, nothing is written.Works on its own, or together with the optional menu mod: then the menu lists "Status line" and shows this page in its pane, and a ◆ mods button appears at the end of the last row of the band (on a row of its own when it does not fit).
◆ mods button has no hotkey: click it, or use the menu command./plugin marketplace add danielmalka/malka-claude-mods
/plugin install statusline@malka-claude-mods
Turn it off first, so your previous statusLine is restored:
/statusline off
/plugin uninstall statusline@malka-claude-mods
Backup files stay next to settings.json (settings.json.statusline.bak, and settings.json.statusline.prev.bak if a saved line was superseded); delete them if you no longer need them.
Type declarations in .claude-plugin/types/ are generated by Claude Code when the mod loads (not committed); the mod's own state contract is types/index.d.ts, and types/menu.d.ts vendors the menu mod's contract (apiVersion 1). Then claude plugin test plugins/statusline and tsc -p plugins/statusline.
Uma linha de status em faixa própria acima do prompt: contexto (porcentagem e tokens), limites de 5h e 7d com contagem regressiva até o reset, ponto de cache (ok / over) e, por fim, modelo, pasta e branch. Nada é cortado nem descartado em terminal estreito: cada item fica inteiro e quebra para outra linha. Sem barras de progresso, só números. A linha de dicas do engine (modo, esc to interrupt, pílula de tarefas em segundo plano) fica por conta do engine; este mod não desenha mais a linha ⎿ pílula. O [-] do engine recolhe a faixa como qualquer outra.
Vem desligada. Para ligar: /statusline on. /statusline off desliga; /statusline sem argumento abre o painel de configuração (On / Off). Ao ligar, o seu statusLine do settings.json é guardado em settings.json.statusline.bak e volta ao desligar. Independente de ligar/desligar, mostra um aviso (toast) uma vez por sessão quando o contexto passa de 60% ("consider /compact") e de novo aos 80% ("time to /compact"). Funciona sozinha ou com o mod opcional menu (que a lista e mostra a página no seu painel, com um botão ◆ mods no fim da última linha da faixa).
Limites conhecidos: a faixa mede a largura do texto por caracteres, então caracteres largos (CJK, emoji) no nome da pasta, da branch ou do modelo podem fazer uma linha parecer mais larga do que o calculado; em terminais muito estreitos (cerca de 20 colunas ou menos) a faixa pode chegar a 5 linhas e o engine a rola; o botão ◆ mods não tem tecla de atalho (clique, ou use o comando do menu).
Instalar: /plugin marketplace add danielmalka/malka-claude-mods e depois /plugin install statusline@malka-claude-mods. Desinstalar: rode /statusline off antes (para restaurar o seu statusLine) e então /plugin uninstall statusline@malka-claude-mods.
hooks/register.tsx 262 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type {} from '../types/menu'
5import type { MenuEntry, StatusSnapshot } from '../types'
6import { configDir, moveStatusLine, parseSettings, type Settings } from './settings'
7import { checkContext, resetContextToasts } from './context-toasts'
8import { LIMIT_LABELS } from './status'
9import { statusBand, statusPage } from './status-line'
10
11const isOnAtom = atom({ plugin: 'statusline', key: 'isOn' } as const, false)
12const snapshotAtom = atom({ plugin: 'statusline', key: 'snapshot' } as const, null)
13const lastResponseAt = atom({ plugin: 'statusline', key: 'lastResponseAt' } as const, null)
14const clockAtom = atom({ plugin: 'statusline', key: 'clock' } as const, 0)
15// Foreign refs: the optional `menu` mod owns them (apiVersion 1); undefined = no menu.
16const menuPanel = { plugin: 'menu', key: 'panel' } as const
17const menuPresent = { plugin: 'menu', key: 'present' } as const
18const menuEntryRef = { plugin: 'statusline', key: 'menuEntry' } as const
19
20const PANE = 'statusline-settings'
21const MENU_PANE = 'mods-menu'
22const BRANCH_MS = 5_000
23const TICK_MS = 15_000
24
25// ~/.claude/settings.json ----------------------------------------------------------------
26// Parsed first, so an invalid file is never overwritten; the first change keeps the original text in settings.json.statusline.bak.
27
28async function settingsPath($: EngineInterface) {
29 const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'))
30 return `${configDir(await $.env.get('CLAUDE_CONFIG_DIR'), home)}/settings.json`
31}
32
33// Moves and mode changes run one at a time: two quick presses cannot interleave their file writes.
34let queue: Promise<unknown> = Promise.resolve()
35function serial<T>(job: () => Promise<T>): Promise<T> {
36 const result = queue.then(job)
37 queue = result.catch(() => undefined)
38 return result
39}
40
41// On: the user's own statusLine is kept (plugin store and the .bak) and taken out of settings.json; off puts it back.
42// The latest statusLine the user set wins; a saved one it supersedes is appended to settings.json.statusline.prev.bak
43// ({ history: [{ statusLine, at }] }, never truncated).
44async function moveNow($: EngineInterface, isOn: boolean) {
45 const path = await settingsPath($)
46 const existed = await $.fs.exists(path)
47 const text = existed ? ((await $.fs.read(path)) as string) : '{}'
48 const settings: Settings = parseSettings(text)
49 const saved = (await $.store.get('savedStatusLine')) as { statusLine: unknown } | undefined
50 const moved = moveStatusLine(settings, isOn, saved)
51 if (moved === undefined) return
52 // the safe copies first, the settings.json write last: a failure never loses the user's value
53 if (moved.prev !== undefined) {
54 const prevPath = `${path}.statusline.prev.bak`
55 const old = (await $.fs.exists(prevPath)) ? parseSettings((await $.fs.read(prevPath)) as string) : {}
56 const history: { statusLine: unknown; at: string }[] = Array.isArray(old.history) ? old.history : []
57 if (JSON.stringify(history[history.length - 1]?.statusLine) !== JSON.stringify(moved.prev)) {
58 history.push({ statusLine: moved.prev, at: new Date(await $.clock.now()).toISOString() })
59 await $.fs.write(prevPath, `${JSON.stringify({ history }, null, 2)}\n`)
60 }
61 $.ui.toast(`Your earlier saved statusLine was kept in ${prevPath} (${history.length} ${history.length === 1 ? 'entry' : 'entries'})`)
62 }
63 if (moved.save !== undefined) await $.store.set('savedStatusLine', moved.save)
64 const backup = `${path}.statusline.bak`
65 if (existed && !(await $.fs.exists(backup))) await $.fs.write(backup, text)
66 if (moved.next !== settings) await $.fs.write(path, `${JSON.stringify(moved.next, null, 2)}\n`)
67 if (moved.drop) await $.store.delete('savedStatusLine')
68}
69
70const moveUserStatusLine = ($: EngineInterface, isOn: boolean) => serial(() => moveNow($, isOn))
71
72// Status data ---------------------------------------------------------------------------
73
74// The git branch is looked up at most once per BRANCH_MS (and when the folder changes).
75let branchAt = 0
76let branchCwd = ''
77let branch = ''
78let ticker: Timer | undefined
79
80async function refreshStatus($: EngineInterface, force = false) {
81 const [model, cwd, usage] = await Promise.all([$.session.model(), $.session.cwd(), $.session.usage()])
82 if (force || cwd !== branchCwd || Date.now() - branchAt >= BRANCH_MS) {
83 branchAt = Date.now()
84 branchCwd = cwd
85 branch = ''
86 try {
87 const ran = await $.process.run(['git', '-C', cwd, 'branch', '--show-current'])
88 if (ran.exitCode === 0) branch = ran.stdout.trim()
89 } catch {}
90 }
91 const snapshot: StatusSnapshot = {
92 model,
93 dir: cwd.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || cwd,
94 branch,
95 ctxPercent: usage.context.percent ?? null,
96 ctxTokens: usage.context.tokens ?? null,
97 ctxWindow: usage.context.window,
98 limits: usage.rateLimits
99 .filter(l => LIMIT_LABELS[l.kind] !== undefined)
100 .map(l => ({
101 label: LIMIT_LABELS[l.kind]!,
102 percent: Math.round(l.percentUsed),
103 resetsAt: l.resetsAt === undefined ? null : Date.parse(l.resetsAt),
104 })),
105 }
106 // nothing drawn changed: no write, no redraw
107 if (JSON.stringify(await read($, snapshotAtom)) !== JSON.stringify(snapshot)) await update($, snapshotAtom, () => snapshot)
108}
109
110const writeEntry = ($: EngineInterface, isOn: boolean) => {
111 const entry: MenuEntry = { apiVersion: 1, title: 'Status line', summary: isOn ? 'on' : 'off', order: 1 }
112 return $.state.set(menuEntryRef, entry)
113}
114
115function runTicker($: EngineInterface, isOn: boolean) {
116 ticker?.cancel()
117 ticker = undefined
118 if (!isOn) return
119 try {
120 ticker = $.clock.every(TICK_MS, () => {
121 void update($, clockAtom, () => Date.now())
122 void refreshStatus($).catch(() => undefined) // branch lookups are throttled by BRANCH_MS
123 })
124 } catch {}
125}
126
127async function setOnNow($: EngineInterface, isOn: boolean) {
128 // The mode is persisted before the move: a crash in between is repaired at the next session start.
129 const was = (await $.store.get('isOn')) === true
130 await $.store.set('isOn', isOn)
131 try {
132 await moveNow($, isOn)
133 } catch (error) {
134 await $.store.set('isOn', was)
135 throw error
136 }
137 // summary 'on' implies the footer is ours: turning on flips the mode first, turning off writes the entry first
138 if (isOn) await update($, isOnAtom, () => true)
139 await writeEntry($, isOn)
140 if (!isOn) await update($, isOnAtom, () => false)
141 runTicker($, isOn)
142 if (isOn) {
143 await update($, clockAtom, () => Date.now())
144 await refreshStatus($, true)
145 }
146}
147
148const setOn = ($: EngineInterface, isOn: boolean) => serial(() => setOnNow($, isOn))
149
150// The menu mod handles these presses itself (ui.press on this plugin's key); the closure only keeps the Button pressable.
151const noop = () => undefined
152
153const tell = ($: EngineInterface) => (error: unknown) => $.ui.toast(`Status line: ${String(error)}`)
154
155async function page($: EngineInterface, e: any, hasBack: boolean) {
156 return statusPage($.ui.resolve(e), {
157 isOn: await read($, isOnAtom),
158 hasBack,
159 onSet: v => setOn($, v).catch(tell($)),
160 onBack: noop,
161 })
162}
163
164export const register: Register = on => {
165 on('session.start', async ($, e, next) => {
166 resetContextToasts()
167 void checkContext($)
168 // Default off: only a stored "on" turns it on.
169 const isOn = (await $.store.get('isOn')) === true
170 await update($, isOnAtom, () => isOn)
171 await writeEntry($, isOn)
172 await update($, clockAtom, () => Date.now())
173 runTicker($, isOn)
174 // a statusLine back in settings.json (edited while off the mod's watch) must not draw under our row
175 // off with a saved value: a crash left it unrestored (or a newer statusLine supersedes it)
176 if (isOn || (await $.store.get('savedStatusLine')) !== undefined) await moveUserStatusLine($, isOn).catch(tell($))
177 if (isOn) await refreshStatus($, true).catch(() => undefined)
178 await $.command
179 .register({ name: 'statusline', description: 'Turn the status line on or off, or open its settings', argumentHint: '[on|off]' })
180 .catch(() => undefined)
181 return next(e)
182 })
183
184 on('command.run', { command: 'statusline' }, async ($, e) => {
185 const arg = e.args.trim().toLowerCase()
186 if (arg === 'on' || arg === 'off') {
187 try {
188 await setOn($, arg === 'on')
189 return { text: `Status line is ${arg}.` }
190 } catch (error) {
191 return { text: `Status line could not be turned ${arg}: ${String(error)}` }
192 }
193 }
194 await $.ui.open({ id: PANE, title: 'Status line', focus: true, closeOnEscape: true, rows: 14, columns: 56 })
195 return { text: 'Status line settings are open.' }
196 })
197
198 on('ui.render', { component: 'Pane', requestId: PANE }, ($, e) => page($, e, false))
199
200 // Inside the menu's pane (apiVersion 1): drawn only when the menu is on this panel.
201 on('ui.render', { component: 'Pane', requestId: MENU_PANE }, async ($, e, next) => {
202 const { value } = await $.state.get(menuPanel)
203 if (value !== 'statusline') return next(e)
204 return page($, e, true)
205 })
206
207 // The status band: its own rows under whatever the hooks beneath draw above the prompt. The engine's mode-label /
208 // hint row (PromptHint) is no longer ours. The engine's [-] can collapse the band; that is accepted.
209 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
210 if (e.props.hasSurvey || !(await read($, isOnAtom))) return next(e)
211 const snapshot = await read($, snapshotAtom)
212 const { value: hasMenu } = await $.state.get(menuPresent)
213 const ui = $.ui.resolve(e)
214 const label = '◆ mods'
215 const button = hasMenu === true ? <ui.Button key="mods-open" plain label={label} onPress={noop} /> : undefined
216 // No snapshot yet (or it keeps failing): only the button, so it never vanishes.
217 if (snapshot === null && button === undefined) return next(e)
218 const under = await next(e)
219 return (
220 <ui.Box flexDirection="column">
221 {under}
222 {snapshot === null ? (
223 <ui.Box justifyContent="flex-end">{button}</ui.Box>
224 ) : (
225 statusBand(ui, {
226 snapshot,
227 clock: await read($, clockAtom),
228 lastResponseAt: await read($, lastResponseAt),
229 columns: Math.max(1, e.props.bodyColumns ?? 80),
230 label: button === undefined ? '' : label,
231 button,
232 })
233 )}
234 </ui.Box>
235 )
236 })
237
238 on('turn.complete', async ($, e, next) => {
239 const r = await next(e)
240 void checkContext($)
241 return r
242 })
243
244 // fire-and-forget: reading usage never delays the spawn
245 on('agent.spawn', ($, e, next) => {
246 void checkContext($)
247 return next(e)
248 })
249
250 // The main loop's responses keep the prompt cache warm; subagents' do not.
251 on('turn.step', async function* ($, e, next) {
252 const answered = yield* next(e)
253 if (e.agentId === undefined && answered.usage !== null && (await read($, isOnAtom).catch(() => false))) {
254 const at = Date.now()
255 await update($, lastResponseAt, () => at).catch(() => undefined)
256 await update($, clockAtom, () => at).catch(() => undefined)
257 void refreshStatus($).catch(() => undefined)
258 }
259 return answered
260 })
261}
262hooks/settings.ts 36 lines1// ~/.claude/settings.json edits on a parsed object: other keys are kept; an invalid file throws before anything is written.
2export type Settings = Record<string, any>
3
4export function parseSettings(text: string): Settings {
5 const s = JSON.parse(text)
6 if (!s || typeof s !== 'object' || Array.isArray(s)) throw new Error('settings.json is not a JSON object')
7 return s
8}
9
10const ABSOLUTE = /^(\/|[A-Za-z]:[\\/]|\\\\)/
11
12// CLAUDE_CONFIG_DIR when it is an absolute path, else <home>/.claude; never a relative path.
13export function configDir(configDirEnv: string | undefined, home: string | undefined): string {
14 const dir = configDirEnv && ABSOLUTE.test(configDirEnv) ? configDirEnv : home ? `${home}/.claude` : ''
15 if (!ABSOLUTE.test(dir)) throw new Error('no absolute CLAUDE_CONFIG_DIR, HOME or USERPROFILE: settings.json not touched')
16 return dir.replaceAll('\\', '/').replace(/\/+$/, '')
17}
18
19const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
20
21// The user's latest explicit statusLine wins; a saved value it supersedes is returned as `prev` so the caller keeps it.
22// On: a live statusLine leaves the file and is saved. Off: a live one stays and the stale saved one is dropped;
23// else the saved one comes back. `drop` = delete the saved value afterwards. undefined when nothing changes.
24export function moveStatusLine(s: Settings, isOn: boolean, saved: { statusLine: unknown } | undefined) {
25 const live = s.statusLine
26 const prev = saved !== undefined && live !== undefined && !same(saved.statusLine, live) ? saved.statusLine : undefined
27 if (isOn) {
28 if (live === undefined) return undefined
29 const { statusLine, ...next } = s
30 return { next, save: { statusLine }, prev, drop: false }
31 }
32 if (saved === undefined) return undefined
33 if (live !== undefined) return { next: s, save: undefined, prev, drop: true }
34 return { next: { ...s, statusLine: saved.statusLine }, save: undefined, prev: undefined, drop: true }
35}
36hooks/context-toasts.ts 31 lines1import type { EngineInterface } from 'claude-code'
2
3const THRESHOLDS = [60, 80] as const
4const MESSAGES: Record<number, (p: number) => string> = {
5 60: p => `Context at ${p}% - consider /compact at the next pause`,
6 80: p => `Context at ${p}% - time to /compact`,
7}
8
9// Thresholds already warned this session (module-level; session.start clears it).
10// One session per plugin instance; a plugin reload re-warns once.
11const warned = new Set<number>()
12
13export const resetContextToasts = () => warned.clear()
14
15// Fail-open: any error is swallowed. Independent of the status line on/off.
16export async function checkContext($: EngineInterface): Promise<void> {
17 try {
18 const percent = (await $.session.usage()).context.percent
19 if (typeof percent !== 'number') return
20 // a reading crossing several thresholds at once shows only the highest; lower ones count as warned
21 const crossed = THRESHOLDS.filter(t => percent >= t)
22 const top = crossed[crossed.length - 1]
23 if (top === undefined) return
24 const isNew = !warned.has(top)
25 for (const t of crossed) warned.add(t)
26 if (isNew) $.ui.toast(MESSAGES[top]!(Math.round(percent)))
27 } catch {
28 // ignore
29 }
30}
31hooks/status.ts 94 lines1// The status line's arithmetic. Pure; drawing is in status-line.tsx, data gathering in register.tsx.
2export const STATUS_GREEN = '#22c55e'
3export const STATUS_YELLOW = '#eab308'
4export const STATUS_RED = '#ef4444'
5export const STATUS_CYAN = '#22d3ee'
6
7// Claude Code's main-thread prompt cache lives for an hour on a subscription.
8export const CACHE_TTL_MS = 60 * 60 * 1000
9
10export const colorFor = (percent: number): string =>
11 percent >= 90 ? STATUS_RED : percent >= 70 ? STATUS_YELLOW : STATUS_GREEN
12
13export const fmtTokens = (n: number): string => {
14 if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
15 if (n >= 1000) return `${Math.round(n / 1000)}k`
16 return String(n)
17}
18
19// Short countdown: 45s, 12m, 4h38m, 5d18h.
20export const fmtDuration = (ms: number): string => {
21 const secs = Math.max(0, Math.floor(ms / 1000))
22 if (secs < 60) return `${secs}s`
23 const m = Math.floor(secs / 60)
24 if (m < 60) return `${m}m`
25 const h = Math.floor(m / 60)
26 if (h < 24) return `${h}h${String(m % 60).padStart(2, '0')}m`
27 return `${Math.floor(h / 24)}d${String(h % 24).padStart(2, '0')}h`
28}
29
30// "ok" while the last response is younger than the cache, "over" after; null before the first response.
31export const cacheState = (lastResponseAt: number | null, now: number): 'ok' | 'over' | null =>
32 lastResponseAt === null ? null : now - lastResponseAt < CACHE_TTL_MS ? 'ok' : 'over'
33
34export const LIMIT_LABELS: Record<string, string> = { five_hour: '5h', seven_day: '7d' }
35
36// Layout. The band is made of atomic segments, in priority order: ctx, 5h, 7d, cache, then the head
37// (model · folder · branch). A segment is never split or dropped; a row that cannot hold the next one wraps.
38export type Segment = { key: string; text: string }
39
40export type StatusParts = {
41 ctxText: string // `41% 82k/200k`
42 limits: readonly { label: string; percentText: string; resetText: string }[]
43 cacheText: string // '' = no cache segment
44 head: string
45}
46
47// The same strings the band draws. Text only: the status line never draws progress bars.
48export const segmentTexts = (d: StatusParts): Segment[] => {
49 return [
50 { key: 'ctx', text: `ctx ${d.ctxText}` },
51 ...d.limits.map(l => ({ key: `limit-${l.label}`, text: `${l.label} ${l.percentText}${l.resetText}` })),
52 ...(d.cacheText === '' ? [] : [{ key: 'cache', text: d.cacheText }]),
53 { key: 'head', text: d.head },
54 ]
55}
56
57export const SEP_WIDTH = 5 // ` │ `, drawn only between two segments of one row
58const BUTTON_GAP = 1
59
60// Indices per row, greedy, in order. Every index appears once; one wider than the row stays alone (its Text wraps).
61// The button joins the last row when gap + button fits, else it takes a row of its own.
62export function layoutRows(widths: readonly number[], columns: number, sep: number, button: number): { rows: number[][]; buttonJoins: boolean } {
63 const rows: number[][] = []
64 let used = 0
65 widths.forEach((w, i) => {
66 const row = rows[rows.length - 1]
67 if (row !== undefined && used + sep + w <= columns) {
68 row.push(i)
69 used += sep + w
70 } else {
71 rows.push([i])
72 used = w
73 }
74 })
75 return { rows, buttonJoins: button > 0 && rows.length > 0 && used + BUTTON_GAP + button <= columns }
76}
77
78export const rowCount = (l: { rows: unknown[]; buttonJoins: boolean }, button: number): number =>
79 l.rows.length + (button > 0 && !l.buttonJoins ? 1 : 0)
80
81// Resets and head are never dropped.
82export function pickLayout(d: StatusParts, columns: number, button: number) {
83 const segments = segmentTexts(d)
84 return { segments, ...layoutRows(segments.map(s => [...s.text].length), columns, SEP_WIDTH, button) }
85}
86
87// `claude-opus-5-5` as `Opus 5.5`; a name that is not a Claude model id stays as it is.
88export function prettyModel(id: string): string {
89 const match = id.match(/^claude-([a-z]+)-(\d+)(?:-(\d+))?/i)
90 if (match === null) return id
91 const [, family = '', major = '', minor] = match
92 return `${family.charAt(0).toUpperCase()}${family.slice(1)} ${major}${minor === undefined ? '' : `.${minor}`}`
93}
94hooks/status-line.tsx 124 lines1import type { StatusSnapshot } from '../types'
2import { cacheState, colorFor, fmtDuration, fmtTokens, pickLayout, prettyModel, STATUS_CYAN, STATUS_GREEN, STATUS_RED } from './status'
3
4type Ui = { Box: any; Text: any; Button: any }
5
6// The status band: ctx, 5h/7d and cache, then model · folder · branch, as atomic segments that wrap onto further rows
7// (never cut, never dropped); the optional button joins the last row or sits right-aligned on its own.
8export function statusBand(
9 { Box, Text }: Ui,
10 p: {
11 snapshot: StatusSnapshot
12 clock: number
13 lastResponseAt: number | null
14 columns: number
15 label: string // text of the button, '' when there is none
16 button: unknown // undefined when there is none
17 },
18) {
19 const { snapshot, clock } = p
20 const cache = cacheState(p.lastResponseAt, clock)
21 const ctxPercent = Math.round(snapshot.ctxPercent ?? 0)
22 const ctxTokens =
23 snapshot.ctxTokens === null ? '' : ` ${fmtTokens(snapshot.ctxTokens)}${snapshot.ctxWindow ? `/${fmtTokens(snapshot.ctxWindow)}` : ''}`
24 const limits = snapshot.limits.map(l => ({
25 ...l,
26 percentText: `${l.percent}%`,
27 resetText: l.resetsAt === null ? '' : ` (resets ${fmtDuration(l.resetsAt - clock)})`,
28 }))
29 const model = prettyModel(snapshot.model)
30 const head = `${model} · ${snapshot.dir}${snapshot.branch === '' ? '' : ` · ${snapshot.branch}`}`
31 const buttonWidth = p.button === undefined ? 0 : [...p.label].length
32 const { segments, rows, buttonJoins } = pickLayout(
33 { ctxText: `${ctxPercent}%${ctxTokens}`, limits, cacheText: cache === null ? '' : `● cache ${cache}`, head },
34 p.columns,
35 buttonWidth,
36 )
37
38 const drawn: Record<string, unknown> = {
39 ctx: (
40 <Text key="seg-ctx">
41 <Text>ctx </Text>
42 <Text bold color={colorFor(ctxPercent)}>{`${ctxPercent}%`}</Text>
43 <Text dimColor>{ctxTokens}</Text>
44 </Text>
45 ),
46 head: (
47 <Text key="seg-head">
48 <Text color={STATUS_CYAN}>{model}</Text>
49 <Text dimColor> · </Text>
50 <Text>{snapshot.dir}</Text>
51 {snapshot.branch !== '' && <Text dimColor> · </Text>}
52 {snapshot.branch !== '' && <Text color={STATUS_GREEN}>{snapshot.branch}</Text>}
53 </Text>
54 ),
55 }
56 for (const l of limits)
57 drawn[`limit-${l.label}`] = (
58 <Text key={`seg-limit-${l.label}`}>
59 <Text>{l.label} </Text>
60 <Text bold color={colorFor(l.percent)}>{l.percentText}</Text>
61 <Text dimColor>{l.resetText}</Text>
62 </Text>
63 )
64 if (cache !== null)
65 drawn.cache = (
66 <Text key="seg-cache">
67 <Text color={cache === 'ok' ? STATUS_GREEN : STATUS_RED}>●</Text>
68 <Text dimColor> cache {cache}</Text>
69 </Text>
70 )
71
72 const lastRow = rows.length - 1
73 return (
74 <Box flexDirection="column">
75 {rows.map((row, r) => {
76 const cells = row.flatMap((i, n) => [
77 ...(n === 0 ? [] : [<Text key={`sep-${r}-${n}`} dimColor>{' │ '}</Text>]),
78 drawn[segments[i]!.key],
79 ])
80 return (
81 <Box key={`row-${r}`} justifyContent="space-between" gap={1}>
82 <Box>{cells}</Box>
83 {r === lastRow && buttonJoins ? p.button : null}
84 </Box>
85 )
86 })}
87 {p.button !== undefined && !buttonJoins && (
88 <Box key="row-button" justifyContent="flex-end">
89 {p.button}
90 </Box>
91 )}
92 </Box>
93 )
94}
95
96// The settings page: On/Off. In the menu's pane it carries a back button (key mods-back), whose press the menu handles.
97export function statusPage({ Box, Text, Button }: Ui, p: { isOn: boolean; hasBack: boolean; onSet: (v: boolean) => unknown; onBack: () => unknown }) {
98 const option = (key: string, label: string, isOn: boolean, onPress: () => unknown) => (
99 <Box key={`row-${key}`} gap={1}>
100 <Button key={key} plain label={`${isOn ? '●' : '○'} ${label}`} dimColor={!isOn} onPress={onPress} />
101 </Box>
102 )
103 return (
104 <Box flexDirection="column" paddingX={1}>
105 <Box justifyContent="space-between">
106 <Text bold color="claude">
107 ◆ Status line
108 </Text>
109 {p.hasBack && <Button key="mods-back" plain dimColor hotkey="b" label="← back" onPress={p.onBack} />}
110 </Box>
111 <Text dimColor>Model, folder and branch, then context, 5h and 7d limits and cache.</Text>
112 <Box marginTop={1}>
113 <Text bold>Status line</Text>
114 </Box>
115 {option('status-on', 'On', p.isOn, () => p.onSet(true))}
116 {option('status-off', 'Off', !p.isOn, () => p.onSet(false))}
117 <Text dimColor>On takes your own statusLine out of settings.json; Off puts it back.</Text>
118 <Box marginTop={1}>
119 <Text dimColor>↑↓ move · enter select · esc close</Text>
120 </Box>
121 </Box>
122 )
123}
124types/index.d.ts 27 lines1export type StatusRateLimit = { label: string; percent: number; resetsAt: number | null }
2
3export type StatusSnapshot = {
4 model: string
5 dir: string
6 branch: string
7 ctxPercent: number | null
8 ctxTokens: number | null
9 ctxWindow: number | null
10 limits: StatusRateLimit[]
11}
12
13// Menu contract, apiVersion 1: an optional `menu` mod lists this entry.
14export type MenuEntry = { apiVersion: 1; title: string; summary: string; order: number }
15
16declare module 'claude-code' {
17 interface PluginState {
18 statusline: {
19 menuEntry: MenuEntry
20 isOn: boolean
21 snapshot: StatusSnapshot | null
22 lastResponseAt: number | null
23 clock: number
24 }
25 }
26}
27