SLOPSHOPPER

Context Band

How full the context window is, as a one-line bar above the prompt, so you know when to /compact or /clear.

bandcommandtoast
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · context-band
› 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 › /ctx ⎿ context-band: Context Band: 49% · 97k of 200k window Context ▰▰▰▰▰▱▱▱▱▱ 49% · 97k/200k ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
Context ▰▰▰▰▰▱▱▱▱▱ 49% · 97k/200k ⟨Claude Code's own drawing⟩
README

Context Band

How full the context window is, as a one-line bar above the prompt, so you know when to /compact or /clear.

Context ▰▰▰▰▰▰▰▰▱▱ 82% · 137k/167k · time to /compact
  • Updates after every reply from the figures the status line reads; no /context needed.
  • The share counts toward where auto-compaction runs, so 100% is the point Claude Code compacts on its own. With auto-compaction off it counts against the whole window.
  • Teal while calm, amber from 50% or 100k tokens, red from 75% or 150k tokens, whichever comes first. The token thresholds matter on large windows, where quality drops long before the share looks high. All four are options; a token threshold of 0 turns it off.
  • One toast when a reply crosses into red: /compact to summarize, /clear to start fresh.
  • Sits beside the usage torch when the terminal is wide, on its own line when it is narrow.
  • /ctx prints the figures; /ctx demo calm|warm|hot previews a level, /ctx demo off ends it.

Install

claude plugin marketplace add hicrandn/claude-mods
claude plugin install context-band@hicran-mods
Source 4 files
src/register.tsx 176 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionContextUsage } from 'claude-code'
3
4import type { ContextDemo, ContextLevel, ContextView } from '../types'
5import { DEFAULT_THRESHOLDS, levelFor, limitOf, percentOf } from './logic.ts'
6import type { Thresholds } from './logic.ts'
7import * as text from './text.ts'
8
9const demo = atom({ plugin: 'context-band', key: 'demo' } as const, null)
10const view = atom({ plugin: 'context-band', key: 'view' } as const, null)
11
12const BAR_CELLS = 10
13// Calm teal, warming amber, red once it is time to compact.
14const BAR_COLORS: Record<ContextLevel, string> = { calm: '#5DCAA5', warm: '#EF9F27', hot: '#D85A30' }
15const DEMOS: readonly ContextDemo[] = ['calm', 'warm', 'hot']
16const DEMO_PERCENT: Record<ContextLevel, number> = { calm: 24, warm: 58, hot: 86 }
17const DEMO_WINDOW = 200_000
18// From this width the band sits beside the one beneath it; narrower, it goes on a line of its own.
19const SIDE_BY_SIDE_COLUMNS = 110
20
21// Module state: a reload starts it over, the host keeps what the drawing reads in $.state.
22let thresholds: Thresholds = DEFAULT_THRESHOLDS
23// The last real reading; null before the live window's first reply.
24let real: { tokens: number; window: number } | null = null
25// Where auto-compaction runs for a window (null: it is off), asked once per window size.
26let autoCompact: { window: number; at: number | null } | null = null
27// Whether the last reading was hot: crossing into hot raises the toast once.
28let wasHot = false
29
30function readingOf(context: SessionContextUsage) {
31  if (context.tokens === undefined) return null
32  return { tokens: context.tokens, window: context.window }
33}
34
35// The threshold comes with the context breakdown, which the summary form estimates locally and
36// sends nothing for. It moves only with the window (a model switch), so it is asked again then.
37// Where no breakdown comes back the fill counts against the whole window, as the status line does,
38// and the next reply asks again.
39async function autoCompactAt($: EngineInterface, window: number): Promise<number | null> {
40  if (autoCompact?.window === window) return autoCompact.at
41  let breakdown
42  try {
43    breakdown = (await $.session.usage({ breakdown: 'summary' })).context.breakdown
44  } catch {
45    return null
46  }
47  if (breakdown === undefined) return null
48  const at = breakdown.isAutoCompactEnabled ? (breakdown.autoCompactThreshold ?? null) : null
49  autoCompact = { window, at }
50  return at
51}
52
53function shownView(window: number, at: number | null): ContextView {
54  const limit = limitOf(window, at)
55  const isAutoCompact = limit !== window
56  if (real === null) return { level: 'calm', percent: 0, tokens: 0, limit, window, isAutoCompact, isPending: true }
57  const percent = percentOf(real.tokens, limit)
58  return { level: levelFor(percent, real.tokens, thresholds), percent, tokens: real.tokens, limit, window, isAutoCompact }
59}
60
61// Draws the real reading unless a demo holds the band; crossing into hot says what to do.
62async function showReal($: EngineInterface, context: SessionContextUsage, mayToast: boolean) {
63  real = readingOf(context)
64  const next = shownView(context.window, await autoCompactAt($, context.window))
65  const isHot = next.isPending !== true && next.level === 'hot'
66  if (mayToast && isHot && !wasHot) $.ui.toast(text.HOT_TOAST(next.tokens))
67  wasHot = isHot
68  if ((await read($, demo)) !== null) return
69  await update($, view, () => next)
70}
71
72const barOf = (percent: number): string => {
73  const lit = Math.round((Math.min(100, Math.max(0, percent)) / 100) * BAR_CELLS)
74  return '▰'.repeat(lit) + '▱'.repeat(BAR_CELLS - lit)
75}
76
77export const register: Register = (on, options) => {
78  const numberOr = (value: unknown, fallback: number): number => (typeof value === 'number' ? value : fallback)
79  thresholds = {
80    warnAtPercent: numberOr(options.warnAtPercent, DEFAULT_THRESHOLDS.warnAtPercent),
81    compactAtPercent: numberOr(options.compactAtPercent, DEFAULT_THRESHOLDS.compactAtPercent),
82    warnAtTokens: numberOr(options.warnAtTokens, DEFAULT_THRESHOLDS.warnAtTokens),
83    compactAtTokens: numberOr(options.compactAtTokens, DEFAULT_THRESHOLDS.compactAtTokens),
84  }
85
86  on('session.start', async ($, e, next) => {
87    await $.command.register({
88      name: 'ctx',
89      description: text.COMMAND_DESCRIPTION,
90      argumentHint: text.COMMAND_HINT,
91    })
92    const result = await next(e)
93    // No toast on a start or reload: only a reply that crosses the line raises it.
94    await showReal($, (await $.session.usage()).context, false)
95    return result
96  })
97
98  on('session.measure', async ($, e, next) => {
99    if (e.changed.includes('context')) await showReal($, e.context, true)
100    return next(e)
101  })
102
103  on('command.run', { command: 'ctx' }, async ($, e) => {
104    const [sub, arg] = e.args.trim().split(/\s+/)
105
106    if (sub === 'demo' && arg === 'off') {
107      await update($, demo, () => null)
108      const window = real?.window ?? DEMO_WINDOW
109      await update($, view, () => shownView(window, autoCompact?.window === window ? autoCompact.at : null))
110      return { text: text.DEMO_OFF }
111    }
112
113    // A bare /ctx reports the figures, like /ctx status.
114    if (sub === undefined || sub === '' || sub === 'status') {
115      const v = await read($, view)
116      if (v === null || v.isPending === true) return { text: text.NO_READING }
117      return { text: `Context Band: ${text.statusLine(v.percent, v.tokens, v.limit, v.window, v.isAutoCompact)}` }
118    }
119
120    const chosen = DEMOS.find(d => d === arg)
121    if (sub === 'demo' && chosen !== undefined) {
122      const percent = DEMO_PERCENT[chosen]
123      const tokens = Math.round((percent / 100) * DEMO_WINDOW)
124      await update($, demo, () => chosen)
125      await update($, view, () => ({ level: chosen, percent, tokens, limit: DEMO_WINDOW, window: DEMO_WINDOW, isAutoCompact: false }))
126      return { text: text.DEMO_ON(chosen) }
127    }
128
129    return { text: text.USAGE }
130  })
131
132  // The band draws its line and keeps what the plugins beneath draw beside it, so it shares the
133  // spot above the prompt (with usage-torch, say) instead of taking it.
134  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
135    if (e.props.hasSurvey) return next(e)
136    const v = await read($, view)
137    // A view 0.1.0 left in the session's state has no limit: pass until session.start redraws it.
138    if (v === null || typeof v.limit !== 'number') return next(e)
139    const below = await next(e)
140
141    const fill = v.isPending === true ? text.WAITING : text.fillLine(v.percent, v.tokens, v.limit)
142
143    if (e.surface !== 'terminal') {
144      const { Box, Text } = $.ui.resolve(e)
145      const head = v.isPending === true ? text.LABEL : text.oneLine(v.percent)
146      return (
147        <Box flexDirection="column">
148          <Text dimColor>{`${head} · ${fill}`}</Text>
149          {below}
150        </Box>
151      )
152    }
153
154    const { Box, Text } = $.ui.resolve(e)
155    const isWide = e.props.bodyColumns >= SIDE_BY_SIDE_COLUMNS
156    const color = BAR_COLORS[v.level]
157    const line = (
158      <Box flexDirection="row" gap={1} flexShrink={0}>
159        <Text color={color} bold>
160          {text.LABEL}
161        </Text>
162        {v.isPending !== true && <Text color={color}>{barOf(v.percent)}</Text>}
163        <Text dimColor>{fill}</Text>
164        {v.isPending !== true && v.level === 'hot' && <Text color={color}>{`· ${text.HOT_HINT}`}</Text>}
165      </Box>
166    )
167
168    return (
169      <Box flexDirection={isWide ? 'row' : 'column'} columnGap={3}>
170        {line}
171        {below}
172      </Box>
173    )
174  })
175}
176
src/logic.ts 49 lines
1// Pure rules: fill to level, token counts to short text.
2
3export type Level = 'calm' | 'warm' | 'hot'
4
5/** A level starts at whichever comes first: its share of the limit, or its token count (0 turns that off). */
6export type Thresholds = {
7  warnAtPercent: number
8  compactAtPercent: number
9  warnAtTokens: number
10  compactAtTokens: number
11}
12
13export const DEFAULT_THRESHOLDS: Thresholds = {
14  warnAtPercent: 50,
15  compactAtPercent: 75,
16  warnAtTokens: 100_000,
17  compactAtTokens: 150_000,
18}
19
20const reached = (tokens: number, at: number): boolean => at > 0 && tokens >= at
21
22/** The level for a fill: hot from either compact threshold, warm from either warn one. */
23export function levelFor(percent: number, tokens = 0, t: Thresholds = DEFAULT_THRESHOLDS): Level {
24  if (percent >= t.compactAtPercent || reached(tokens, t.compactAtTokens)) return 'hot'
25  if (percent >= t.warnAtPercent || reached(tokens, t.warnAtTokens)) return 'warm'
26  return 'calm'
27}
28
29/** The fill as a whole percent, 0 to 100. */
30export function percentOf(tokens: number, limit: number): number {
31  if (limit <= 0) return 0
32  return Math.min(100, Math.max(0, Math.round((tokens / limit) * 100)))
33}
34
35/** What the fill counts against: the point auto-compaction runs at, else the whole window. */
36export function limitOf(window: number, autoCompactAt: number | null): number {
37  return autoCompactAt !== null && autoCompactAt > 0 && autoCompactAt < window ? autoCompactAt : window
38}
39
40/** A token count in a few characters: 950, 12k, 124k, 1.2M. */
41export function formatTokens(n: number): string {
42  if (n >= 1_000_000) {
43    const m = Math.round(n / 100_000) / 10
44    return `${Number.isInteger(m) ? m : m.toFixed(1)}M`
45  }
46  if (n >= 1000) return `${Math.round(n / 1000)}k`
47  return String(Math.max(0, Math.round(n)))
48}
49
src/text.ts 30 lines
1// Every string the mod shows. English only; no em dashes (a test holds this).
2
3import { formatTokens } from './logic.ts'
4
5export const LABEL = 'Context'
6
7/** The figures in one line: the fill and the tokens against the limit. */
8export const fillLine = (percent: number, tokens: number, limit: number): string =>
9  `${percent}% · ${formatTokens(tokens)}/${formatTokens(limit)}`
10
11/** The figures in full, for /ctx: what the limit is and the whole window beside it. */
12export const statusLine = (percent: number, tokens: number, limit: number, window: number, isAutoCompact: boolean): string =>
13  isAutoCompact
14    ? `${percent}% · ${formatTokens(tokens)} of ${formatTokens(limit)} before auto-compact (window ${formatTokens(window)})`
15    : `${percent}% · ${formatTokens(tokens)} of ${formatTokens(limit)} window`
16
17export const HOT_HINT = 'time to /compact'
18export const WAITING = 'fills after the first reply'
19export const oneLine = (percent: number): string => `Context ${percent}%`
20
21export const HOT_TOAST = (tokens: number): string =>
22  `Context at ${formatTokens(tokens)}: /compact to summarize or /clear to start fresh`
23
24export const COMMAND_DESCRIPTION = 'Show Context Band figures, or simulate a level'
25export const COMMAND_HINT = '[status|demo calm|warm|hot|off]'
26export const DEMO_ON = (level: string): string => `Context Band demo: ${level}. Real figures are ignored until /ctx demo off.`
27export const DEMO_OFF = 'Context Band demo off.'
28export const USAGE = 'Usage: /ctx status, /ctx demo calm|warm|hot, /ctx demo off'
29export const NO_READING = 'Context Band has no reading yet. It arrives with the first reply.'
30
types/index.d.ts 30 lines
1export type ContextLevel = 'calm' | 'warm' | 'hot'
2
3export type ContextDemo = ContextLevel
4
5/** What the band shows: how far the last reply's input has come toward compaction. */
6export type ContextView = {
7  level: ContextLevel
8  /** Whole percent of `limit` in use, 0 to 100. */
9  percent: number
10  /** Input tokens of the last reply. */
11  tokens: number
12  /** What the fill counts against: where auto-compaction runs, else the model's whole window. */
13  limit: number
14  /** The model's whole context window, in tokens. */
15  window: number
16  /** True when `limit` is the auto-compaction point. */
17  isAutoCompact: boolean
18  /** True before the live window's first reply (a new session, right after /clear or /compact). */
19  isPending?: boolean
20}
21
22declare module 'claude-code' {
23  interface PluginState {
24    'context-band': {
25      demo: ContextDemo | null
26      view: ContextView | null
27    }
28  }
29}
30