SLOPSHOPPER

hud

One line above the prompt: context fill, rate-limit windows, a cache chip (кеш 59:48, m:ss) while the prompt cache is warm, and the buttons Handoff, Compact…

bandcommandtoasttimer
v0.6.10no licenseupdated 2026-10-20oleksandrkodua/qa-mods/hud
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · hud
› 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 › /hud ⎿ hud: Ліміти: ⎿ hud: 5 год 31% ⎿ hud: Витрати сесії: $0.42 ⎿ hud: Кеш: ≈ 59:59 (оцінка: остання відповідь + 60 хв) Контекст 49% · 5г 31% [ ⏱ ] · кеш 59:59 [ Handoff ] [ Compact ] [ Clear ] [ Прогрес ] ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
Контекст 49% · 5г 31% [ ⏱ ] · кеш 59:59 [ Handoff ] [ Compact ] [ Clear ] [ Прогрес ] ⟨Claude Code's own drawing⟩
README

qa-mods

Fourteen Claude Code mods, packaged as one plugin marketplace (qa-mods). Made for a manual QA workflow: guard rails around risky commands, evidence for what was tested, and a status band above the prompt.

Install

Run in your own Terminal (a sandboxed Claude session cannot write ~/.claude).

claude plugin marketplace add oleksandrkodua/qa-mods
claude plugin install hud@qa-mods

Replace hud with any plugin from the table.

To install everything from a local clone, or to set up a fresh machine, see INSTALL.md and install-pack.sh.

Plugins

PluginWhat it does
sandbox-guardDenies writes to protected Claude config paths and hands back a Terminal command
remote-gateAsks before git push and wrangler --remote, showing folder, branch, remote and the commits that will go out
blast-radiusShows what a risky Bash command will touch before it runs
retry-analyzerDetects repeated identical failing tool calls and tells Claude to change strategy
secret-redactorMasks tokens and keys in tool output
evidence-saverSaves screenshots from tool results to a folder you pick
replay-theater/replay: step through the session's file edits one by one
verification-guardChecks claims like "tests pass" against tool calls that actually ran
handoffOffers /handoff as the context fills up; fills the prompt box with a HANDOFF.md prompt
notifyA toast and a macOS notification when a long command or turn finishes
quick-actionsCompact and Clear buttons, each asks to confirm first
hudContext fill and rate-limit windows above the prompt, a кеш 59:48 chip (m:ss) while the prompt cache is warm, five buttons, and /hud with the figures as text
next-steps-ukFork of next-steps (MIT, Thariq Shihipar): suggested next prompts are always in Ukrainian. Install instead of next-steps
plan-progressFork of plan-progress 0.7.6 (zycck, MIT): live progress bars above the prompt. Install instead of plan-progress@zycck-mods

Tests

claude plugin test hud                                              # from the repo root
cd hud && node --test tests/format.test.mjs tests/handoff-prompt.test.mjs

A bare node --test also picks up register.test.ts, which only runs under claude plugin test.

License

No license file for the original mods yet. The two forks keep their upstream MIT notices: next-steps-uk/NOTICE.md and plan-progress/NOTICE.md (plus plan-progress/LICENSE.upstream).

Source 3 files
hooks/register.tsx 247 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { Limit } from '../types'
5
6import { bandLabel, bandPlaceholders, cacheChip, cacheLeft, isReset, limitLabel, report, tone, untilReset } from './format'
7
8const limits = atom({ plugin: 'hud', key: 'limits' } as const, [])
9const usd = atom({ plugin: 'hud', key: 'usd' } as const, null)
10const stale = atom({ plugin: 'hud', key: 'stale' } as const, false)
11const lastReplyAt = atom({ plugin: 'hud', key: 'lastReplyAt' } as const, 0)
12const tick = atom({ plugin: 'hud', key: 'tick' } as const, 0)
13const ctx = atom({ plugin: 'hud', key: 'ctx' } as const, -1)
14const showTimes = atom({ plugin: 'hud', key: 'showTimes' } as const, false)
15
16const ASK: Record<string, string> = {
17  compact: 'Стиснути розмову? Її буде замінено підсумком, щоб звільнити контекст; подробиці втрачаються.',
18  clear: 'Очистити всю розмову? Почнеться з порожнього контексту, це неможливо скасувати.',
19}
20const CHOICES = ['Підтвердити', 'Скасувати']
21
22// The same text as HANDOFF_PROMPT in handoff/hooks/logic.ts (a test keeps the two equal): the button fills the
23// box itself, so no command runs and the chat gets no `/handoff` bubble. It is the command of the active-memory plugin.
24export const HANDOFF_PROMPT = `/active-memory:amhandoff`
25
26const COLOR = { ok: '#30A46C', warn: '#E09A1E', hot: '#FF1F1F' } as const
27
28/**
29 * HUD: one line above the prompt: context fill, rate-limit windows and a `кеш 59:48` chip (m:ss, ticking every second) while the prompt-cache
30 * countdown runs (cost is left out so the five buttons fit a narrow window; `/hud` still reports it), then the buttons (handoff,
31 * Compact, Clear, Progress), and /hud with the figures as text
32 * (VS Code does not draw the band). The Handoff button fills the prompt box itself (no command runs); the Progress
33 * button runs a command another mod registers (`progress`); a missing mod just makes it do nothing. Compact and Clear ask first (confirm /
34 * cancel) and then run the real command: it is done here because the engine refuses `command.run` from inside a
35 * `command.run` hook, so a command of another mod could not do it.
36 * The band stacks with other mods' bands: the hook asks the hooks beneath (`next`) first
37 * and adds its own line above the result.
38 */
39export const register: Register = (on, options) => {
40  const ttl = Number(options?.cacheTtlMinutes) > 0 ? Number(options.cacheTtlMinutes) : 60
41  const warnAt = Number(options?.warnPercent) > 0 ? Number(options.warnPercent) : 80
42  const redAt = Number(options?.redPercent) > 0 ? Number(options.redPercent) : 85
43  const ctxWarn = Number(options?.ctxWarnPercent) > 0 ? Number(options.ctxWarnPercent) : 50
44  const ctxRed = Number(options?.ctxRedPercent) > 0 ? Number(options.ctxRedPercent) : 80
45  const alarmed = new Set<string>()
46  const warned = new Set<string>()
47  let stop: (() => void) | null = null
48  let lastReply = 0
49
50  on('session.start', async ($, e, next) => {
51    // a name already taken must not break the mod
52    await $.command.register({ name: 'hud', description: 'Show rate limits, session cost and the prompt-cache countdown as text' }).catch(() => undefined)
53
54    // The windows belong to the account, not the session: show the last ones seen until a reply
55    // refreshes them, so the band is not empty for the whole first turn.
56    try {
57      const now = await $.clock.now()
58      // no reading yet (or the call failing) is the same as an empty one: fall back to the saved windows
59      const fresh = (await $.session.usage().catch(() => ({ rateLimits: [] as Limit[] }))).rateLimits
60
61      if (fresh.length > 0) {
62        await update($, limits, () => fresh.map(l => ({ kind: l.kind, percentUsed: l.percentUsed, resetsAt: l.resetsAt })))
63      } else {
64        const saved = (await $.store.get('limits')) as { savedAt: number; limits: Limit[] } | undefined
65        const usable = (saved?.limits ?? []).filter(l => (l.resetsAt ? Date.parse(l.resetsAt) > now : now - (saved?.savedAt ?? 0) < 6 * 3600000))
66
67        if (usable.length > 0) {
68          await update($, limits, () => usable)
69          await update($, stale, () => true)
70        }
71      }
72    } catch {
73      // a missing reading only leaves the band empty until the first reply
74    }
75
76    return next(e)
77  })
78
79  on('session.measure', async ($, e, next) => {
80    const now = await $.clock.now()
81
82    // an empty reading (no reply yet, or not a subscription) must not wipe the saved windows
83    if (e.rateLimits.length > 0) {
84      const fresh = e.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed, resetsAt: l.resetsAt }))
85
86      await update($, limits, () => fresh)
87      await update($, stale, () => false)
88      await $.store.set('limits', { savedAt: now, limits: fresh }).catch(() => undefined)
89    }
90    await update($, usd, () => e.cost?.usd ?? null)
91    await update($, ctx, () => Math.round(e.context.percent ?? 0))
92
93    // a turn finished (context or cost moved): that response refreshed the prompt cache
94    if (e.changed.includes('context') || e.changed.includes('cost')) {
95      lastReply = now
96      await update($, lastReplyAt, () => now)
97    }
98
99    for (const l of e.rateLimits) {
100      if (l.percentUsed >= warnAt && !warned.has(l.kind)) {
101        warned.add(l.kind)
102        $.ui.toast(`HUD: ліміт ${limitLabel(l.kind)} використано на ${Math.round(l.percentUsed)}%`)
103      } else if (l.percentUsed < warnAt) {
104        warned.delete(l.kind)
105      }
106
107      if (l.percentUsed >= redAt && !alarmed.has(l.kind)) {
108        alarmed.add(l.kind)
109        $.ui.toast(`HUD: ліміт ${limitLabel(l.kind)} майже вичерпано, ${Math.round(l.percentUsed)}%`)
110      } else if (l.percentUsed < redAt) {
111        alarmed.delete(l.kind)
112      }
113    }
114
115    // one-second redraw only while a cache countdown is running
116    if (stop === null && lastReply > 0) {
117      stop = $.clock.every(1000, () => {
118        void (async () => {
119          await update($, tick, n => n + 1)
120
121          if (cacheLeft(lastReply, ttl, await $.clock.now()) === 0) {
122            stop?.()
123            stop = null
124          }
125        })()
126      })
127    }
128
129    return next(e)
130  })
131
132  on('command.run', { command: 'hud' }, async $ => ({
133    text: report({
134      limits: await read($, limits),
135      usd: await read($, usd),
136      lastReplyAt: await read($, lastReplyAt),
137      ttlMinutes: ttl,
138      now: await $.clock.now(),
139      warnAt,
140      redAt,
141      stale: await read($, stale),
142    }),
143  }))
144
145  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
146    const below = await next(e)
147    const list = await read($, limits)
148    const fill = await read($, ctx)
149    const times = await read($, showTimes)
150
151    if (e.props.hasSurvey) return below
152
153    await read($, tick)
154
155    const now = await $.clock.now()
156    const { Box, Text, Button } = $.ui.resolve(e)
157    const run = (command: string) => () => void $.command.run({ command }).catch(() => undefined)
158    // fills an empty box with the command; a slash command only works at the start, so a typed draft is kept and the command is copied
159    const fillHandoff = () =>
160      void (async () => {
161        const draft = await $.prompt.read().catch(() => ({ text: '' }))
162        const hasDraft = String(draft?.text ?? '').trim() !== ''
163        const filled = hasDraft ? { isFilled: false } : await $.prompt.fill({ text: HANDOFF_PROMPT, mode: 'replace' }).catch(() => ({ isFilled: false }))
164
165        if (filled.isFilled) {
166          $.ui.toast('Команда в полі вводу. Натисни Enter.')
167
168          return
169        }
170
171        const copied = await $.ui.copy({ text: HANDOFF_PROMPT }).catch(() => ({ isCopied: false }))
172
173        $.ui.toast(
174          copied.isCopied
175            ? `${hasDraft ? 'У полі є твій текст' : 'Поле вводу зараз не заповнити'}: команду ${HANDOFF_PROMPT} скопійовано, встав її сам.`
176            : `${hasDraft ? 'У полі є твій текст' : 'Поле вводу зараз не заповнити'}: введи ${HANDOFF_PROMPT} сам.`,
177        )
178      })()
179    const confirmRun = (command: 'compact' | 'clear') => () =>
180      void (async () => {
181        const answer = await $.ui.ask(ASK[command]!, CHOICES).catch(() => CHOICES[1])
182
183        if (answer === CHOICES[0]) {
184          // Compact is a model call (about 40 s) and the host shows nothing meanwhile; /clear waits in the queue behind it
185          $.ui.toast(command === 'compact' ? 'Стиснення запущено: це може тривати до хвилини, чекай.' : 'Очищення запущено.')
186          await $.command.run({ command }).catch(() => undefined)
187        } else {
188          $.ui.toast(`${command === 'compact' ? 'Стиснення' : 'Очищення'} скасовано: нічого не змінено.`)
189        }
190      })()
191    const dot = (k: string) => (
192      <Text key={`dot-${k}`} dimColor>
193        ·
194      </Text>
195    )
196
197    const chip = cacheChip(await read($, lastReplyAt), ttl, now)
198    const parts = [
199      fill < 0 ? (
200        <Text key="ctx" dimColor>Контекст —</Text>
201      ) : fill >= ctxWarn ? (
202        <Text key="ctx" color={fill >= ctxRed ? COLOR.hot : COLOR.warn}>{`Контекст ${fill}%`}</Text>
203      ) : (
204        <Text key="ctx" dimColor>{`Контекст ${fill}%`}</Text>
205      ),
206      ...(list.length === 0
207        ? [
208            <Box key="limits" flexDirection="row" alignItems="center" gap={1}>
209              {bandPlaceholders().flatMap((t, i) => [...(i > 0 ? [dot(`p${i}`)] : []), <Text key={`ph-${i}`} dimColor>{t}</Text>])}
210            </Box>,
211          ]
212        : [
213            <Box key="limits" flexDirection="row" alignItems="center" gap={1}>
214              {list.flatMap((l, i) => [
215                ...(i > 0 ? [dot(`l${i}`)] : []),
216                isReset(l.resetsAt, now) ? (
217                  <Text key={`limit-${l.kind}`} dimColor>{`${bandLabel(l.kind)} скинуто`}</Text>
218                ) : (
219                  <Text key={`limit-${l.kind}`}>
220                    <Text dimColor>{`${bandLabel(l.kind)} `}</Text>
221                    <Text color={COLOR[tone(l.percentUsed, warnAt, redAt)]} bold={l.percentUsed >= redAt}>
222                      {times ? untilReset(l.resetsAt, now) || '—' : `${Math.round(l.percentUsed)}%`}
223                    </Text>
224                  </Text>
225                ),
226              ])}
227              <Button key="b-times" label={times ? '%' : '⏱'} onPress={() => void update($, showTimes, v => !v)} />
228            </Box>,
229          ]),
230      ...(chip ? [<Text key="cache" dimColor>{chip}</Text>] : []),
231    ]
232
233    return (
234      <Box flexDirection="column">
235        <Box flexDirection="row" flexWrap="wrap" alignItems="center" gap={1}>
236          {parts.flatMap((p, i) => (i === 0 ? [p] : [dot(String(i)), p]))}
237          <Button key="b-handoff" label="Handoff" onPress={fillHandoff} />
238          <Button key="b-compact" label="Compact" onPress={confirmRun('compact')} />
239          <Button key="b-clear" label="Clear" onPress={confirmRun('clear')} />
240          <Button key="b-progress" label="Прогрес" onPress={run('progress')} />
241        </Box>
242        {below}
243      </Box>
244    )
245  })
246}
247
hooks/format.ts 103 lines
1import type { Limit } from '../types'
2
3
4const LABEL: Record<string, string> = { five_hour: '5 год', seven_day: '7 дн', spend_limit: 'ліміт витрат' }
5
6export const limitLabel = (kind: string) => LABEL[kind] ?? kind
7
8/** The band's one-line labels: 5г, 7д. */
9export const bandLabel = (kind: string) => ({ five_hour: '5г', seven_day: '7д' })[kind] ?? limitLabel(kind)
10
11/** The band's placeholders while no limits have arrived yet (no reply in the session): "5г —", "7д —". */
12export const bandPlaceholders = (): string[] => ['five_hour', 'seven_day'].map(k => `${bandLabel(k)} —`)
13
14/** `m:ss` for under an hour, `h:mm:ss` from an hour up; never negative. */
15export function countdown(ms: number): string {
16  const total = Math.max(0, Math.floor(ms / 1000))
17  const h = Math.floor(total / 3600)
18  const m = Math.floor((total % 3600) / 60)
19  const s = total % 60
20  const two = (n: number) => String(n).padStart(2, '0')
21
22  return h > 0 ? `${h}:${two(m)}:${two(s)}` : `${m}:${two(s)}`
23}
24
25/** "1г 07х" style time until a reset; empty when unknown or already passed. */
26export function untilReset(resetsAt: string | undefined, now: number): string {
27  if (!resetsAt) return ''
28
29  const ms = Date.parse(resetsAt) - now
30
31  if (!Number.isFinite(ms) || ms <= 0) return ''
32
33  const mins = Math.round(ms / 60000)
34  const d = Math.floor(mins / 1440)
35  const h = Math.floor((mins % 1440) / 60)
36  const m = mins % 60
37
38  if (d > 0) return `${d}д ${h}г`
39
40  return h > 0 ? `${h}г ${String(m).padStart(2, '0')}х` : `${m}х`
41}
42
43/** True when the window's reset time has passed: the saved percent belongs to a window that no longer exists. */
44export function isReset(resetsAt: string | undefined, now: number): boolean {
45  if (!resetsAt) return false
46
47  const ms = Date.parse(resetsAt)
48
49  return Number.isFinite(ms) && ms <= now
50}
51
52export type Tone = 'ok' | 'warn' | 'hot'
53
54export const tone = (percent: number, warnAt: number, redAt = 85): Tone => (percent >= redAt ? 'hot' : percent >= warnAt ? 'warn' : 'ok')
55
56export const money = (usd: number) => `$${usd.toFixed(2)}`
57
58/** Cache time left: the last reply plus the TTL. null before the first reply. */
59export function cacheLeft(lastReplyAt: number, ttlMinutes: number, now: number): number | null {
60  if (!lastReplyAt) return null
61
62  return Math.max(0, lastReplyAt + ttlMinutes * 60000 - now)
63}
64
65/** The band's cache chip: "кеш 59:48", minutes:seconds counting down; empty before the first reply and once it has expired. */
66export function cacheChip(lastReplyAt: number, ttlMinutes: number, now: number): string {
67  const left = cacheLeft(lastReplyAt, ttlMinutes, now)
68
69  const total = Math.floor((left ?? 0) / 1000)
70
71  if (!total) return ''
72
73  return `кеш ${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`
74}
75
76/** The same figures as plain text, for /hud (the only place VS Code can show them). */
77export function report(args: { limits: Limit[]; usd: number | null; lastReplyAt: number; ttlMinutes: number; now: number; warnAt: number; redAt?: number; stale?: boolean }): string {
78  const { limits, usd, lastReplyAt, ttlMinutes, now, warnAt, redAt = 85, stale } = args
79  const lines = [stale ? 'Ліміти (збережені з минулої сесії, оновляться після першої відповіді):' : 'Ліміти:']
80
81  if (limits.length === 0) lines.push('  даних немає (їх віддає лише підписка, і лише після першої відповіді)')
82
83  for (const l of limits) {
84    if (isReset(l.resetsAt, now)) {
85      lines.push(`  ${limitLabel(l.kind).padEnd(8)} скинуто (було ${Math.round(l.percentUsed)}%, нове значення прийде з наступною відповіддю)`)
86      continue
87    }
88
89    const reset = untilReset(l.resetsAt, now)
90    const flag = l.percentUsed >= redAt ? `  ‼ понад ${redAt}%` : l.percentUsed >= warnAt ? `  ⚠ понад ${warnAt}%` : ''
91
92    lines.push(`  ${limitLabel(l.kind).padEnd(8)} ${String(Math.round(l.percentUsed)).padStart(3)}%${reset ? `  (скидання через ${reset})` : ''}${flag}`)
93  }
94
95  lines.push(`Витрати сесії: ${usd === null ? 'невідомо' : money(usd)}`)
96
97  const left = cacheLeft(lastReplyAt, ttlMinutes, now)
98
99  lines.push(`Кеш: ${left === null ? 'ще немає відповіді' : left === 0 ? 'прострочений' : `≈ ${countdown(left)} (оцінка: остання відповідь + ${ttlMinutes} хв)`}`)
100
101  return lines.join('\n')
102}
103
types/index.d.ts 21 lines
1export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
2
3declare module 'claude-code' {
4  interface PluginState {
5    hud: {
6      limits: Limit[]
7      usd: number | null
8      // true while the limits shown were saved by an earlier session and no reply has refreshed them
9      stale: boolean
10      // epoch ms of the last finished turn; 0 before the first
11      lastReplyAt: number
12      // bumped every second while the cache countdown runs
13      tick: number
14      // context fill, percent, from the last measurement; -1 before the first
15      ctx: number
16      // the limit windows show the time to their reset instead of the percent
17      showTimes: boolean
18    }
19  }
20}
21