SLOPSHOPPER

context-bar-hiroshi

Fork do context-bar (hamzafer, MIT): a janela de contexto como barra empilhada acima do prompt, agora atualizada também depois de um /compact e enquanto a…

bandcommand
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · context-bar-hiroshi
› 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 › /context-bar ⎿ context-bar-hiroshi: Context bar hidden. /context-bar shows it again ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

git-band e filetree-hiroshi em ação no Claude Code

Acima, o git-band e o filetree-hiroshi numa sessão real: a faixa do git acompanha as alterações e o commit, e a árvore mostra onde o agente lê e escreve, com os diffs embaixo.

Instalar

claude plugin marketplace add MoriHiroshiDesu/hiroshi-claude-mods
claude plugin install <mod>@hiroshi-claude-mods --scope user

Depois, /reload-plugins ou reinicie o Claude Code. Para trazer versões novas, atualize o marketplace e depois os mods instalados:

claude plugin marketplace update hiroshi-claude-mods
claude plugin update <mod>@hiroshi-claude-mods

Sem o nome, claude plugin marketplace update atualiza todos os marketplaces registrados. Depois, /reload-plugins de novo.

Mods

ModO que faz
model-effortMostra o modelo e o effort da sessão, alinhados à direita do rodapé do prompt (sonnet 5.5 · high). Verde até sonnet e até high; vermelho de opus e de xhigh para cima.
git-bandUma linha acima do prompt em 4 colunas: branch ou worktree (↑↓), alterações não commitadas por cor, último commit e as linhas +/- dele. A opção columns escolhe quais colunas aparecem e em que ordem (guia).
context-bar-hiroshiFork do context-bar do hamzafer (MIT): a janela de contexto como barra empilhada acima do prompt, agora atualizada também depois de um /compact e enquanto a tarefa roda, sem esperar o fim do turno. /context-bar mostra ou esconde.
filetree-hiroshiÁrvore de arquivos da sessão num painel lateral, com o status git e as linhas +/- de cada arquivo, marcando onde o agente lê (azul) e escreve (laranja). Modo foco quando os arquivos estão longe na árvore (f) e, abaixo dela, os diffs de cada arquivo escrito (d oculta, c limpa). Um botão ⧉ abrir ao lado do nome, ao passar o mouse, abre o arquivo ou o diff no Zed ou no VS Code, só com o mouse. Com a opção icons (nerd), ícones de Nerd Fonts por tipo de arquivo e pasta, com ícones próprios para arquivos de IA e do Docker. Abre sozinho na primeira escrita; /filetree abre ou fecha. Detalhes no README do mod; as opções icons, editor e width estão no guia de configuração. Inspirado no claude-code-filetree do data-goblin (MIT).
footer-inlineLeva o status do tool-diet (⚠ 10 tools on demand) para o fim da linha do modo (auto mode on), em vez de uma linha só dele embaixo do prompt. Só mexe em status que contêm on demand; os de outros mods ficam como estão. Troque a regex INLINE em hooks/register.ts para mover outros.
Source 2 files
hooks/register.tsx 223 lines
1// Fork of hamzafer/claude-code-mods context-bar (MIT). Changes: refresh after a /compact reads the new window (session.append, doors compaction, command and notice); the bar grows while a turn runs (session.measure), not only when it ends.
2// Context Bar: what is filling my context window?
3//   Above the prompt, the window as one stacked bar, a color per category as /context
4//   draws them (system prompt, tools, MCP tools, memory files, skills, messages, free),
5//   with a legend of tokens and shares and where auto-compaction runs. It refreshes after
6//   each turn and while one runs. /context-bar shows or hides it, and the choice is kept across sessions.
7import { atom, read, update } from 'claude-code'
8import type { EngineInterface, Register } from 'claude-code'
9
10import type { Reading, Slice } from '../types'
11
12const MIN_WIDTH = 20 // narrower than this, the bar is not drawn
13const SPLIT = '   '
14// /context's theme gives several rows the same grey, so each used row gets its own color, in order.
15const PALETTE = ['#7aa2f7', '#7dcfff', '#bb9af7', '#9ece6a', '#e0af68', '#f7768e', '#73daca', '#ff9e64', '#c0caf5']
16const MESSAGES = '#d97757' // the row that grows, in the accent color
17const FREE = '#808080' // a mid grey thin line reads as empty on dark and light themes alike
18const BUFFER = '#808080'
19const GLYPH = { used: '█', free: '─', buffer: '░' } as const
20
21// Held by the host, so the bar survives a hot reload of this file.
22const reading = atom({ plugin: 'context-bar-hiroshi', key: 'reading' } as const, null as Reading | null)
23const isHidden = atom({ plugin: 'context-bar-hiroshi', key: 'isHidden' } as const, false)
24
25export const register: Register = on => {
26  on('session.start', async ($, e, next) => {
27    const r = await next(e)
28    measured = undefined
29    await $.command.register({ name: 'context-bar', description: 'Show or hide the context window bar above the prompt' }).catch(() => {}) // a name Claude Code already has is refused: start anyway
30    const hidden = (await $.store.get('isHidden').catch(() => undefined)) === true
31    await update($, isHidden, () => hidden)
32    void refresh($).catch(() => {})
33    return r
34  })
35
36  on('turn.complete', async ($, e, next) => {
37    const r = await next(e)
38    if (!e.agentId) await refresh($).catch(() => {}) // a subagent's turn fills its own window, not this one
39    return r
40  })
41
42  // The engine measures the session while a turn runs, not only when it ends: the bar follows the
43  // window as the task fills it. A measure that leaves the token count where the bar has it, or
44  // one that reports none, does not ask for the breakdown.
45  on('session.measure', async ($, e, next) => {
46    const r = await next(e)
47    const total = e.context?.tokens
48    if (typeof total === 'number' && total !== measured) {
49      measured = total
50      void refreshLive($)
51    }
52    return r
53  })
54
55  // A /compact empties the window without a turn ending. `session.compact` answers before the
56  // transcript is swapped, and a plugin that does its own compaction may skip the compaction row,
57  // so the rows a compaction leaves behind (its boundary, the command's record, the notice) are
58  // what we read after: by then the transcript is the new one.
59  on('session.append', async ($, e, next) => {
60    const r = await next(e)
61    if (!e.agentId && (e.door === 'compaction' || e.door === 'command' || e.door === 'notice')) await refresh($).catch(() => {})
62    return r
63  })
64
65  on('command.run', { command: 'context-bar' }, async $ => {
66    const hidden = await update($, isHidden, h => !h)
67    await $.store.set('isHidden', hidden).catch(() => {})
68    if (!hidden) await refresh($).catch(() => {})
69    return { text: hidden ? 'Context bar hidden. /context-bar shows it again' : 'Context bar on' }
70  })
71
72  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
73    const rest = await next(e) // what other mods and Claude Code draw here stays, drawn above the box so one-row mods stay visible
74    const r = await read($, reading)
75    if (e.props.hasSurvey || (await read($, isHidden)) || !r) return rest
76    const { Box, Text } = $.ui.resolve(e)
77    const inner = e.props.bodyColumns - 4 // the border and padding take 4 cells
78    if (inner < MIN_WIDTH) return rest
79
80    const head = `${tokens(r.total)} of ${tokens(r.window)}${r.compactsAt ? ` · compacts at ${tokens(r.compactsAt)}` : ''}`
81    const pct = ` ${r.percent}% `
82    const level = r.compactsAt ? r.total / r.compactsAt : r.total / r.window
83    return (
84      <Box flexDirection="column">
85        {rest}
86        <Box flexDirection="column" borderStyle="round" borderColor="inactive" paddingX={1}>
87          <Box flexDirection="row" justifyContent="space-between">
88            <Text wrap="truncate-end">
89              <Text color="#d97757">{'◆ '}</Text>
90              <Text bold>context</Text>
91            </Text>
92            <Text wrap="truncate-start">
93              <Text dimColor>{`${head} `}</Text>
94              <Text bold color="black" backgroundColor={level >= 0.9 ? 'red' : level >= 0.7 ? 'yellow' : 'green'}>{pct}</Text>
95            </Text>
96          </Box>
97          <Text>
98            {cells(r, inner).map(c => (
99              <Text color={c.color}>{c.text}</Text>
100            ))}
101          </Text>
102          {legend(r, inner).map(line => (
103            <Text wrap="truncate-end">
104              {line.map((s, i) => (
105                <Text>
106                  {i > 0 && <Text>{SPLIT}</Text>}
107                  <Text color={s.color}>{s.kind === 'used' ? '■ ' : `${GLYPH[s.kind]} `}</Text>
108                  <Text dimColor={s.kind !== 'used'}>{`${s.name} `}</Text>
109                  <Text bold={s.kind === 'used'}>{tokens(s.tokens)}</Text>
110                  {s.kind === 'used' && <Text dimColor>{` ${share(s.tokens, r.window)}`}</Text>}
111                </Text>
112              ))}
113            </Text>
114          ))}
115        </Box>
116      </Box>
117    )
118  })
119}
120
121// Measures arrive in bursts, and the breakdown takes a moment: one refresh runs at a time, and the
122// measures that come in meanwhile fold into a single one after it.
123let running = false
124let again = false
125let measured: number | undefined // the token count of the last measure that asked for a refresh
126async function refreshLive($: EngineInterface) {
127  if (running) {
128    again = true
129    return
130  }
131  running = true
132  try {
133    do {
134      again = false
135      await refresh($).catch(() => {})
136    } while (again)
137  } finally {
138    running = false
139  }
140}
141
142// Asks the engine for /context's breakdown, estimated locally (no token-count calls).
143async function refresh($: EngineInterface) {
144  if (await read($, isHidden)) return
145  const usage = await $.session.usage({ breakdown: 'summary' })
146  const b = usage.context.breakdown
147  if (!b || !(b.rawMaxTokens > 0)) return // no window to measure against
148  await update($, reading, () => toReading(b))
149}
150
151export function toReading(b: {
152  categories: { name: string; tokens: number; color: string; kind: string }[]
153  totalTokens: number
154  rawMaxTokens: number
155  percentage: number
156  autoCompactThreshold?: number
157  isAutoCompactEnabled: boolean
158}): Reading {
159  const slices: Slice[] = b.categories
160    .filter(c => c.kind !== 'deferred' && c.tokens > 0)
161    .map(c => ({ name: c.name.toLowerCase(), tokens: c.tokens, color: c.color, kind: c.kind as Slice['kind'] }))
162  const order = { used: 0, free: 1, buffer: 2 }
163  slices.sort((x, y) => order[x.kind] - order[y.kind]) // stable: used rows keep /context's order
164  let next = 0
165  for (const s of slices) {
166    s.color = s.kind === 'free' ? FREE : s.kind === 'buffer' ? BUFFER : s.name === 'messages' ? MESSAGES : PALETTE[next++ % PALETTE.length]!
167  }
168  return {
169    slices,
170    total: b.totalTokens,
171    window: b.rawMaxTokens,
172    percent: b.percentage,
173    compactsAt: b.isAutoCompactEnabled ? b.autoCompactThreshold : undefined,
174  }
175}
176
177// The bar as runs of cells: each slice gets its share of `width`, a used one at least one cell.
178export function cells(r: Reading, width: number) {
179  const sizes = r.slices.map(s => Math.max(s.kind === 'used' ? 1 : 0, Math.round((s.tokens / r.window) * width)))
180  // Rounding leaves the sum a few cells off: free space takes the difference first, then the largest slices.
181  let diff = width - sizes.reduce((a, n) => a + n, 0)
182  const isUsed = (i: number) => r.slices[i]!.kind === 'used'
183  const order = r.slices.map((_, i) => i).sort((a, b) => Number(isUsed(a)) - Number(isUsed(b)) || sizes[b]! - sizes[a]!)
184  for (const i of order) {
185    if (diff === 0) break
186    const size = Math.max(isUsed(i) ? 1 : 0, sizes[i]! + diff)
187    diff -= size - sizes[i]!
188    sizes[i] = size
189  }
190  return r.slices.map((s, i) => ({ color: s.color, kind: s.kind, text: GLYPH[s.kind].repeat(sizes[i]!) })).filter(c => c.text !== '')
191}
192
193// The legend, packed into lines no wider than `width`.
194export function legend(r: Reading, width: number) {
195  const lines: Slice[][] = [[]]
196  let used = 0
197  for (const s of r.slices) {
198    const size = 2 + s.name.length + 1 + tokens(s.tokens).length + (s.kind === 'used' ? 1 + share(s.tokens, r.window).length : 0)
199    const line = lines.at(-1)!
200    if (line.length > 0 && used + SPLIT.length + size > width) {
201      lines.push([s])
202      used = size
203    } else {
204      used += (line.length > 0 ? SPLIT.length : 0) + size
205      line.push(s)
206    }
207  }
208  return lines.filter(l => l.length > 0)
209}
210
211export function tokens(n: number) {
212  if (n >= 1_000_000) return `${+(n / 1_000_000).toFixed(n % 1_000_000 === 0 ? 0 : 1)}M`
213  if (n >= 10_000) return `${Math.round(n / 1000)}k`
214  if (n >= 1000) return `${+(n / 1000).toFixed(1)}k`
215  return String(n)
216}
217
218export function share(n: number, window: number) {
219  const p = (n / window) * 100
220  if (p > 0 && p < 0.1) return '<0.1%'
221  return `${p >= 10 ? Math.round(p) : +p.toFixed(1)}%`
222}
223
types/index.d.ts 16 lines
1export type Slice = { name: string; tokens: number; color: string; kind: 'used' | 'free' | 'buffer' }
2
3export type Reading = {
4  slices: Slice[]
5  total: number // tokens in use
6  window: number // the window measured against
7  percent: number
8  compactsAt?: number // where auto-compaction runs, when it is on
9}
10
11declare module 'claude-code' {
12  interface PluginState {
13    'context-bar-hiroshi': { reading: Reading | null; isHidden: boolean }
14  }
15}
16