SLOPSHOPPER

chudarin-context-mod

A Claude Code mod: a side panel that shows what fills your context window, what your plan limits look like, what each kind of action costs and what the…

paneguardcommandpromptprocesstimer
v1.2.1MITupdated 2026-10-26schudarin/chudarin-context-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · chudarin-context-mod
│ ┃ Context ✕ › fix the failing auth test and add an audit log call │ ┃ No data until the first reply. │ ⏺ 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 │ ⎿ chudarin-context-mod: Panel open. Esc or /ctx closes it. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Context
No data until the first reply.
README

<img alt="chudarin-context-mod: a context panel for Claude Code" src="assets/banner-light.svg" width="100%">

<a href="#-install"><img alt="Claude Code mod" src="https://img.shields.io/badge/Claude_Code-mod-D97757"></a> <a href="#-limits"><img alt="early access" src="https://img.shields.io/badge/mods_API-early_access-6B6B75"></a> <a href="LICENSE"><img alt="MIT license" src="https://img.shields.io/badge/license-MIT-2EA44F"></a>

A side panel for Claude Code that shows where your context goes. Type /ctx, and a panel opens next to the chat: how full the context is, how much of your plan limits is left, what fills the window, and what each kind of action costs.

I made it to learn how context works. /context gives a table of categories, and in a long session most of the window sits in one line called Messages. That line doesn't tell you whether it was the screenshots, the test output or the files Claude rewrote. The panel splits it open, and next to every item says in plain words what it is, why it's that big, and what you can do about it.

Русская версия

👀 What you see

The panel's home page

From top to bottom:

  • Context, 5-hour limit, weekly limit. Three meters, green, yellow or red. Under the context meter, roughly how many turns are left before auto-compaction at the current pace. Under the 5-hour meter, how long the limit lasts at the pace of the last hour. A line across the full width under the meters says how fast the context grows compared with your past sessions (🐌 🐈 🐇 🚀; it needs three sessions of five or more turns).
  • What fills the context. One bar for the whole window, split into four groups: tool work, Claude Code itself, your conversation, skills and rules. Click a group to open it.
  • A hint. One line, only when one item is big and you can do something about it: "Bash output took 61k. Ask Claude to run tests and go through long logs in a subagent: only the summary comes back." "Put in chat" puts a ready request in the prompt box after what you typed, or a command in place of it; you send it yourself. "Hide" hides it for the session. On the item page, "Don't show again" appears once you hide the advice or send it. Most of the advice comes from Anthropic's guide to reducing token usage.
  • Action costs. The average price of one screenshot, one file written, one Bash command, one skill. This is the part that teaches: you see which habits are expensive.
  • This session. How long it has run and how many messages you sent, how much of the 5-hour and weekly limits it used, what one message costs on average, and the compactions. A long session makes every message dearer, since each one sends the whole context again. The limits are shared, so sessions open side by side count too. If subagents ran: how many, how much they processed (new and from cache), and the three dearest with their biggest context and number of steps. Only a subagent's report reaches your context, so the rest of its work shows up only here.
  • Context load chart, folded. One column per turn, as tall as what that turn added, so a heavy turn stands out as a peak. Below it, the five biggest jumps with their cause (point at one to light its column), and every compaction.

Context load chart: the jump under the pointer lit on the chart and opened

Click a group to see its items, click an item to get its help page:

A groupAn item
Tool work, item by itemFetched pages: what it is, why so much, what to do

A narrow pane stacks the meters and puts each row on two lines: the name, then its figures under it.

The panel speaks English unless Claude Code's language setting is Russian.

📦 Install

You need Claude Code with mods. I built and tested it on Claude Code 2.1.300 in a terminal.

/plugin marketplace add schudarin/chudarin-design-skills
/plugin install chudarin-context-mod@chudarin

The first line adds my plugin catalog, chudarin. It also lists a design agent for Figma; you don't have to install it, the two are separate. Restart Claude Code after installing, then type /ctx.

🕹️ Using it

CommandWhat it does
/ctxOpens the panel. Again, or Esc while the panel has focus, closes it

Click a row to open it, ← Back to return. If clicks don't land, focus the panel first: click it or press ctrl+x tab.

In a fullscreen terminal wide enough, the panel docks beside the chat. Otherwise it opens above the prompt.

🔢 Where the numbers come from

  • Categories are the ones /context shows, from Claude Code's own estimate.
  • Messages are split by reading the conversation: tool results by tool, code Claude wrote, tool arguments, reminders Claude Code adds, loaded skills, your messages, Claude's replies, images. The split is estimated at about 4 characters per token, then scaled so the parts add up to the Messages total from /context.
  • Images count as 1.5k each. The conversation doesn't carry their size, so this is a guess.
  • This session adds up the rises of each limit's percent while the session runs, and counts the prompts you send (slash commands aside). The log is kept per session, survives a restart and claude --resume, and holds the last 30 sessions. It starts when the mod is installed; earlier history isn't counted.
  • Subagents are read from their transcripts next to the session's (<session>/subagents/agent-<id>.jsonl) through grep, which passes on only the reply lines, so a file of tens of MB is read line by line, not whole. The session's transcript path arrives with your first message, so the lines show after it. Agents a workflow ran aren't counted.
  • Limits come from your plan's rate-limit windows. With an API key there are none, and the limit meters don't show.

Nothing leaves your machine. The mod makes no network calls.

⚠️ Limits

  • Mods are an early-access part of Claude Code. An update can change the API and break the panel until I fix it.
  • Tested on macOS in a terminal and in the desktop app. VS Code and mobile aren't tested.
  • The subagent lines run grep, so it has to be on your PATH. They were checked only in a terminal.
  • Where an organization manages Claude Code, hooks on compaction don't run in plugins a person installs. The panel works, but the compaction lines in "This session" stay at zero.

🔄 Update and remove

claude plugin update chudarin-context-mod@chudarin      # newest version, restart to apply
claude plugin uninstall chudarin-context-mod@chudarin   # remove

🎨 Also by me

chudarin-design-skills: a design agent for Figma. A separate plugin in the same catalog.

📄 License

MIT, see LICENSE.

Source 8 files
hooks/register.tsx 1529 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, TextProps } from 'claude-code'
3
4import type { AgentRun, LimitTrack, Page, SessionLog, Snapshot, Step, Subagents } from '../types'
5import { GROUPS, actionPrices, buildEntries, groupLabel, groupTotals, insight } from './entries'
6import { HELP_IDS, helpFor } from './help'
7import { type Lang, langOf, UI } from './i18n'
8import { addCompact, addLimit, addPoint, addPrompt, addRequest, emptyLog, findResumed, pruneKeys, sessionKey } from './history'
9import { chartRows, clip, detail, detailsFor, fitCell, joinLines, lineSvg, nameWidth, priceGrid, sentenceCase, wrapLines, jumps, k, label, limitForecast, pace, resetLabel, speed, trackLimit, turnRises, usualRise, windowRows } from './model'
10import { addLine, descriptionOf, runOf, summarize } from './subagents'
11
12const log = atom({ plugin: 'chudarin-context-mod', key: 'log' } as const, null)
13const heaviest = atom({ plugin: 'chudarin-context-mod', key: 'heaviest' } as const, null)
14const snapshot = atom({ plugin: 'chudarin-context-mod', key: 'snapshot' } as const, null)
15const expanded = atom({ plugin: 'chudarin-context-mod', key: 'expanded' } as const, [])
16const page = atom({ plugin: 'chudarin-context-mod', key: 'page' } as const, { kind: 'home' } as Page)
17const lang = atom({ plugin: 'chudarin-context-mod', key: 'lang' } as const, 'en' as Lang)
18const usual = atom({ plugin: 'chudarin-context-mod', key: 'usual' } as const, null)
19const hidden = atom({ plugin: 'chudarin-context-mod', key: 'hidden' } as const, [])
20const sent = atom({ plugin: 'chudarin-context-mod', key: 'sent' } as const, [])
21const muted = atom({ plugin: 'chudarin-context-mod', key: 'muted' } as const, [])
22const limitTrack = atom({ plugin: 'chudarin-context-mod', key: 'limitTrack' } as const, null)
23const minute = atom({ plugin: 'chudarin-context-mod', key: 'minute' } as const, 0)
24const logId = atom({ plugin: 'chudarin-context-mod', key: 'logId' } as const, null)
25const transcript = atom({ plugin: 'chudarin-context-mod', key: 'transcript' } as const, null)
26// Store key for the 5-hour limit samples: the limit is shared by every session.
27const LIMIT = 'limit:five_hour'
28
29function isTrack(v: unknown): v is LimitTrack {
30  const t = v as LimitTrack | null
31  return !!t && typeof t.resetsAt === 'string' && Array.isArray(t.samples)
32}
33
34// One more sample of the 5-hour limit. The store is merged in, so every session adds to one track.
35async function sampleLimit($: EngineInterface, resetsAt: string, percent: number) {
36  const now = await $.clock.now()
37  // A window already over is an idle session's old figure: it must not start the track over.
38  if (Date.parse(resetsAt) <= now) return
39  const stored = await $.store.get(LIMIT).catch(() => undefined)
40  const own = await read($, limitTrack)
41  // The newest window wins; in the same window, the track with more samples.
42  const [base = null] = [stored, own]
43    .filter(isTrack)
44    .sort((a, b) => Date.parse(b.resetsAt) - Date.parse(a.resetsAt) || b.samples.length - a.samples.length)
45  if (base && Date.parse(resetsAt) < Date.parse(base.resetsAt)) return
46  const next = trackLimit(base, resetsAt, now, percent)
47  await update($, limitTrack, () => next)
48  await $.store.set(LIMIT, next).catch(err => $.ui.log(`chudarin-context-mod: limit samples not saved: ${String(err)}`))
49}
50// Store key for advice hidden for good: it outlives sessions.
51const MUTED = 'muted'
52
53// Marks advice as done once its request was sent or its command run: what counts is
54// what reached Claude, not what the panel put in the box.
55async function markDone($: EngineInterface, matches: (prompt: string) => boolean) {
56  // The first message after a /clear belongs to the new session: switch before marking.
57  await followSession($)
58  const ids = HELP_IDS.filter(id => (['ru', 'en'] as const).some(l => {
59    const p = helpFor(id, l).prompt
60    return p !== null && matches(p)
61  }))
62  if (ids.length === 0) return
63  const add = (prev: string[]) => [...prev, ...ids.filter(id => !prev.includes(id))]
64  await update($, sent, add)
65}
66
67const PANE = 'chudarin-context-mod'
68// Figures older than this get the "data is stale" line.
69const STALE_MS = 5 * 60_000
70// Session logs kept in the store; older ones are dropped.
71const KEEP_SESSIONS = 30
72// A session whose conversation was launched longer ago than this is a resumed one.
73const RESUMED_MS = 60_000
74// Store key for the last 5-hour and weekly figures: limits are the account's, not a session's.
75const LAST_LIMITS = 'limits:last'
76const CHART_ROWS = 6
77// Content narrower than this stacks each row that holds a name and figures into two lines:
78// the name, then the figures under it, indented 2.
79const COMPACT = 48
80// Lower blocks keep a gap between stacked rows; a dim dot marks the empty part of a meter.
81const BLOCK = '▆'
82const EMPTY = '·'
83
84type Level = 'ok' | 'warn' | 'bad'
85const LEVEL_COLOR: Record<Level, 'success' | 'warning' | 'error'> = { ok: 'success', warn: 'warning', bad: 'error' }
86// The same levels, and the chart's 'suggestion', as fixed colors for vector graphics: an Svg is drawn
87// isolated and knows no theme. Each holds at least 3:1 on #ffffff, #f5f5f0, #eeeeee, #282828,
88// #1a1a19 and #000000.
89const LEVEL_HEX: Record<Level, string> = { ok: '#2b8a3e', warn: '#b87400', bad: '#d6333a' }
90const CHART_HEX = '#5769f7'
91
92// The desktop's layout (and every surface but the terminal's): the host's font, spacing in the
93// host's steps, columns as fixed-width Boxes in cells, graphics as Svg sized in pixels.
94// Columns, in cells: tokens or a delta, a share, a count, a turn, a chevron or mark, the chart's axis,
95// a group page's bar.
96const D_NUM = 6
97const D_PCT = 5
98const D_COUNT = 5
99const D_TURN = 8
100const D_MARK = 1
101const D_AXIS = 4
102const D_BAR = 10
103// Svg heights in pixels: a tile's meter, the stacked bar, a group page's bar.
104const PX_METER = 6
105const PX_STACK = 10
106const PX_BAR = 6
107// The chart's height in rows. Its columns are Boxes, not Svg: a hover restyles a Box, never what an
108// Svg draws, and a lit column must turn the accent color whole.
109const D_CHART_ROWS = 6
110// The chart spreads its turns over the first of these slot counts they fit in, so a few turns don't
111// draw fat columns, and a turn is a whole percent of the width (the engine takes whole percents only).
112const CHART_SLOTS = [20, 25, 50, 100] as const
113
114function levelOf(percent: number, warn: number, bad: number): Level {
115  return percent > bad ? 'bad' : percent >= warn ? 'warn' : 'ok'
116}
117
118// Split a width among values in proportion, at least one cell for any value above zero.
119function widths(values: readonly number[], width: number): number[] {
120  const sum = values.reduce((a, b) => a + b, 0)
121  if (sum <= 0) return values.map(() => 0)
122  const out = values.map(v => (v > 0 ? Math.max(1, Math.round((v / sum) * width)) : 0))
123  let extra = out.reduce((a, b) => a + b, 0) - width
124  while (extra > 0) {
125    const i = out.indexOf(Math.max(...out))
126    out[i]! -= 1
127    extra -= 1
128  }
129  return out
130}
131
132// Load session `id`'s log, or start one (`launch`: the conversation's first launch, when known).
133// What was sent or hidden belonged to the session before.
134async function loadSession($: EngineInterface, id: string, launch?: number): Promise<SessionLog | undefined> {
135  // An unreadable store starts an empty log, as a missing one does.
136  const stored = (await $.store.get(sessionKey(id)).catch(() => undefined)) as SessionLog | undefined
137  const now = await $.clock.now()
138  // Logs from older versions lack newer fields; the empty log fills them in.
139  await update($, log, () => (stored ? { ...emptyLog(stored.startedAt), ...stored } : emptyLog(now, launch)))
140  await update($, hidden, () => [])
141  await update($, sent, () => [])
142  await update($, logId, () => id)
143  return stored
144}
145
146// /clear and a resume inside the process go on under a new session id, and no session.start
147// fires: the first write after one loads the new id's log.
148async function followSession($: EngineInterface): Promise<string> {
149  const id = await $.session.id()
150  if ((await read($, logId)) !== id) await loadSession($, id)
151  return id
152}
153
154// Change the session log in the panel's state and persist it, so a restart or `claude --resume` keeps it.
155async function saveLog($: EngineInterface, change: (l: SessionLog) => SessionLog) {
156  const id = await followSession($)
157  const now = await $.clock.now()
158  let next: SessionLog | null = null
159  await update($, log, prev => (next = change(prev ?? emptyLog(now))))
160  if (next) await $.store.set(sessionKey(id), next)
161}
162
163// Claude Code's `language` setting decides the panel's language.
164async function readLang($: EngineInterface): Promise<Lang> {
165  const settings = await $.settings.read().catch(() => ({}) as Record<string, unknown>)
166  return langOf(settings.language)
167}
168
169type LastLimit = { percentUsed: number; resetsAt?: string }
170function isLastLimits(v: unknown): v is Record<string, LastLimit> {
171  return !!v && typeof v === 'object' && !Array.isArray(v) &&
172    Object.values(v).every(x => !!x && typeof (x as LastLimit).percentUsed === 'number')
173}
174
175// Each subagent transcript read, by path, with the mtime and size it had: a file is read again only
176// once it changes, so a finished agent is read once.
177const agentRuns = new Map<string, { stamp: string; run: AgentRun }>()
178
179// One subagent's transcript can run to tens of MB, past what $.fs.read takes: grep streams only the
180// reply lines, and they are summed line by line as they come.
181async function readRun($: EngineInterface, dir: string, id: string): Promise<AgentRun> {
182  const meta = await $.fs.read(`${dir}/${id}.meta.json`).then(t => JSON.parse(t) as unknown).catch(() => null)
183  const steps = new Map()
184  let rest = ''
185  for await (const { stream, text } of $.process.spawn({ argv: ['grep', '-F', '"type":"assistant"', `${dir}/${id}.jsonl`] })) {
186    if (stream !== 'stdout') continue
187    const lines = (rest + text).split('\n')
188    rest = lines.pop() ?? ''
189    for (const line of lines) addLine(steps, line)
190  }
191  addLine(steps, rest)
192  return runOf(descriptionOf(meta, id), steps)
193}
194
195// The session's subagents, from their transcripts beside the session's: <session>/subagents/agent-<id>.jsonl.
196// Agents a workflow ran (subagents/workflows/) are not counted.
197async function readSubagents($: EngineInterface): Promise<Subagents | null> {
198  const main = await read($, transcript)
199  if (!main) return null
200  const dir = `${main.replace(/\.jsonl$/, '')}/subagents`
201  const runs: AgentRun[] = []
202  for (const f of await $.fs.list(dir).catch(() => [])) {
203    const id = /^(agent-.+)\.jsonl$/.exec(f.name)?.[1]
204    if (f.kind !== 'file' || !id) continue
205    const path = `${dir}/${f.name}`
206    const stamp = `${f.mtimeMs}:${f.size}`
207    let known = agentRuns.get(path)
208    if (known?.stamp !== stamp) {
209      // An agent that can't be read now is left out and tried again on the next refresh.
210      const run = await readRun($, dir, id).catch(err => void $.ui.log(`chudarin-context-mod: ${f.name} not read: ${String(err)}`, { to: 'debug' }))
211      if (!run) continue
212      known = { stamp, run }
213      agentRuns.set(path, known)
214    }
215    runs.push(known.run)
216  }
217  return summarize(runs)
218}
219
220async function refresh($: EngineInterface) {
221  const l = await readLang($)
222  await update($, lang, () => l)
223  const usage = await $.session.usage({ breakdown: 'summary' })
224  const b = usage.context.breakdown
225  if (!b) return
226  const messages = await $.session.messages({ as: 'api' })
227  const categories = windowRows(b.categories)
228  const entries = buildEntries(categories, detailsFor(b), messages, l)
229  const fresh = usage.rateLimits.map(r => ({ kind: r.kind, percentUsed: r.percentUsed, resetsAt: r.resetsAt }))
230  // Limit figures come with model replies (the last API response's); right after a start, or in an
231  // idle refresh, there are none. Limits are the account's: the last figures any session read are
232  // kept in the store, and the session log is the fallback. A reset time that has passed shows as reset.
233  const stored = await $.store.get(LAST_LIMITS).catch(() => undefined)
234  const last: Record<string, LastLimit> = isLastLimits(stored) ? stored : {}
235  const logged = (await read($, log))?.limits ?? {}
236  const next0: Record<string, LastLimit> = { ...last }
237  const kept: { kind: string; percentUsed: number; resetsAt?: string }[] = []
238  for (const kind of ['five_hour', 'seven_day'] as const) {
239    const r = fresh.find(x => x.kind.includes(kind) && !/fable/i.test(x.kind))
240    if (r) next0[kind] = { percentUsed: r.percentUsed, ...(r.resetsAt ? { resetsAt: r.resetsAt } : {}) }
241    else if (last[kind]) kept.push({ kind, ...last[kind]! })
242    else if (logged[kind]) kept.push({ kind, percentUsed: logged[kind]!.last, resetsAt: logged[kind]!.resetsAt })
243  }
244  if (JSON.stringify(next0) !== JSON.stringify(last))
245    await $.store.set(LAST_LIMITS, next0).catch(err => $.ui.log(`chudarin-context-mod: limits not saved: ${String(err)}`))
246  const next: Snapshot = {
247    lang: l,
248    at: await $.clock.now(),
249    entries,
250    prices: actionPrices(messages, l),
251    limits: [...fresh, ...kept],
252    threshold: b.isAutoCompactEnabled && b.autoCompactThreshold ? b.autoCompactThreshold : usage.context.window,
253    window: usage.context.window,
254    used: entries.reduce((n, e) => n + e.tokens, 0),
255    subagents: await readSubagents($),
256  }
257  await update($, snapshot, () => next)
258  const five = usage.rateLimits.find(r => /five_hour/.test(r.kind) && !/fable/i.test(r.kind))
259  if (five?.resetsAt) await sampleLimit($, five.resetsAt, five.percentUsed)
260  // What this session spent of each limit; the log is a nice-to-have, a failure must not stop the refresh.
261  const week = usage.rateLimits.find(r => /seven_day/.test(r.kind) && !/fable/i.test(r.kind))
262  for (const [kind, r] of [['five_hour', five], ['seven_day', week]] as const)
263    if (r?.resetsAt) {
264      const { resetsAt, percentUsed } = r
265      await saveLog($, l => addLimit(l, kind, resetsAt, percentUsed)).catch(err => $.ui.log(`chudarin-context-mod: limit not logged: ${String(err)}`))
266    }
267}
268
269export const register: Register = on => {
270  on('session.start', async ($, e, next) => {
271    const r = await next(e)
272    const t0 = UI[await readLang($)]
273    await $.command.register({ name: 'ctx', description: t0.cmdPanel })
274    // Pick up this session's log (after a restart or `claude --resume`), or start one.
275    const id = await $.session.id()
276    const { context, startedAt: launch } = await $.session.usage()
277    const now = await $.clock.now()
278    let stored = await loadSession($, id, launch)
279    // Every other session's log: the usual pace, and the one a resumed conversation may have left.
280    const others: (readonly [string, SessionLog])[] = []
281    for (const key of await $.store.keys())
282      if (key.startsWith('session:') && key !== sessionKey(id)) {
283        const other = (await $.store.get(key)) as SessionLog | undefined
284        if (other) others.push([key, other])
285      }
286    // A conversation launched well before this process (the desktop app after a restart) can come back
287    // under a new session id; its first launch is still `usage.startedAt`, so its log is found by that.
288    const resumed = !stored && now - launch > RESUMED_MS ? findResumed(others, launch) : null
289    const adopted = others.find(([key]) => key === resumed)?.[1]
290    if (adopted) {
291      stored = adopted
292      await update($, log, () => ({ ...emptyLog(adopted.startedAt), ...adopted, launchedAt: launch }))
293    }
294    // The store keeps its keys in insertion order and pruning drops the oldest: this session's log goes
295    // to the end now, so a long conversation resumed after many short ones is not the one dropped.
296    if (stored) {
297      const current = await read($, log)
298      await $.store.delete(sessionKey(id)).catch(() => undefined)
299      if (current) await $.store.set(sessionKey(id), current)
300    }
301    for (const key of pruneKeys(await $.store.keys(), KEEP_SESSIONS)) await $.store.delete(key)
302    await update($, usual, () => usualRise(others.map(([, l]) => l)))
303    // Only a list of ids counts; anything else in the store is ignored.
304    const rawMuted = await $.store.get(MUTED)
305    const mutedBefore = Array.isArray(rawMuted) ? rawMuted.filter((x): x is string => typeof x === 'string') : []
306    await update($, muted, () => mutedBefore)
307    if (context.tokens !== undefined && !stored?.points.length) {
308      const tokens = context.tokens
309      await saveLog($, l => addPoint(l, tokens, null))
310    }
311    // A failed read must not keep the minute clock below from starting.
312    await refresh($).catch(err => $.ui.log(`chudarin-context-mod: refresh failed: ${String(err)}`))
313    // A minute clock for the session's life. The pane reads `minute`, so each write redraws it:
314    // an idle session still shows a passed reset time and, after five minutes, that its figures
315    // are stale. Redraw only; reading the data again here would keep it from ever looking stale.
316    $.clock.every(60_000, () => {
317      void $.clock
318        .now()
319        .then(at => update($, minute, () => at))
320        .catch(err => $.ui.log(`chudarin-context-mod: minute clock failed: ${String(err)}`))
321    })
322    return r
323  })
324
325  // Any slash command, built-in ones included: running /mcp or /effort counts as done.
326  on('command.run', async ($, e, next) => {
327    const r = await next(e)
328    await markDone($, p => p === `/${e.command}`).catch(err => $.ui.log(`chudarin-context-mod: ${String(err)}`))
329    return r
330  }).catch(($, e, next) => next(e))
331
332  on('command.run', { command: 'ctx' }, async $ => {
333    const t = UI[await read($, lang)]
334    const panes = await $.ui.panes()
335    if (panes.some(p => p.id === PANE)) {
336      await $.ui.close({ id: PANE })
337      return { text: t.panelClosed }
338    }
339    await update($, page, () => ({ kind: 'home' }) as Page)
340    await refresh($).catch(err => $.ui.log(`chudarin-context-mod: refresh failed: ${String(err)}`))
341    await $.ui.open({ id: PANE, title: t.paneTitle, focus: true, closeOnEscape: true })
342    return { text: t.panelOpened }
343  })
344
345  on('prompt.submit', async ($, e, next) => {
346    await update($, heaviest, () => null)
347    await markDone($, p => !p.startsWith('/') && e.text.includes(p))
348    if (!e.command && !e.isMeta) await saveLog($, addPrompt).catch(err => $.ui.log(`chudarin-context-mod: prompt not logged: ${String(err)}`))
349    return next(e)
350  }).catch(($, e, next) => next(e))
351
352  // Only the classic events carry the transcript's path; /clear and a resume change it.
353  on('classic.UserPromptSubmit', async ($, e, next) => {
354    await update($, transcript, () => e.transcript_path)
355    return next(e)
356  }).catch(($, e, next) => next(e))
357
358  on('tool.call', async ($, e, next) => {
359    const r = await next(e)
360    // Rough estimate: ~4 characters per token.
361    const tokens = Math.round((r.text?.length ?? 0) / 4)
362    const step: Step = { label: label(e as Record<string, unknown>), tokens, detail: detail(e as Record<string, unknown>) }
363    await update($, heaviest, prev => (prev && prev.tokens >= tokens ? prev : step))
364    return r
365  }).catch(($, e, next) => next(e))
366
367  // Every model request of the main conversation: what it read and wrote.
368  on('turn.step', async function* ($, e, next) {
369    const r = yield* next(e)
370    const usage = r?.usage
371    if (!e.agentId && usage) await saveLog($, l => addRequest(l, usage))
372    return r
373  })
374
375  on('session.compact', async ($, e, next) => {
376    const r = await next(e)
377    const isMain = !e.agentId && e.trigger !== 'precompute'
378    if (isMain && r.skip === undefined) {
379      const { tokensBefore, tokensAfter } = r
380      if (tokensBefore !== undefined && tokensAfter !== undefined)
381        await saveLog($, l => addCompact(l, e.trigger, tokensBefore, tokensAfter))
382    }
383    return r
384  }).catch(($, e, next) => next(e))
385
386  on('session.measure', async ($, e, next) => {
387    const tokens = e.context.tokens
388    if (tokens !== undefined) {
389      const step = await read($, heaviest)
390      const cause = step?.label ?? null
391      // The log is a nice-to-have: a failure here must not stop the panel's refresh.
392      await saveLog($, l => addPoint(l, tokens, cause, step?.detail ?? null)).catch(err => $.ui.log(`chudarin-context-mod: log not saved: ${String(err)}`))
393    }
394    await refresh($)
395    return next(e)
396  })
397
398  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
399    try {
400      const elements = $.ui.resolve(e)
401      const { Box, Button, Text: HostText } = elements
402      // The terminal's tree keeps `mono` on every Text, as it was drawn before the desktop got its
403      // own layout; the terminal ignores it.
404      const Text: typeof HostText = props => HostText({ mono: true, ...props })
405      // Everywhere but the terminal: the desktop layout, in the host's own font.
406      const gui = e.surface !== 'terminal'
407      // Meters, bars and the chart as vector graphics where the surface draws Svg. An Svg is a leaf
408      // that takes no hover and can't sit in a Button: a Box around it carries the hover group.
409      const Svg = gui && 'Svg' in elements ? elements.Svg : null
410      // A figure in a table column: a fixed width in cells, right-aligned, digits of one width.
411      const figure = (text: string, width: number, style: TextProps = {}) => (
412        <Box width={width} flexShrink={0} justifyContent="flex-end">
413          <HostText tabular {...style}>
414            {text}
415          </HostText>
416        </Box>
417      )
418      // A fixed-width cell for a chevron, a mark or a dot, so the rows' edges line up; dim unless
419      // given a color.
420      const markCell = (mark: string | null, style: TextProps = {}) => (
421        <Box width={D_MARK} flexShrink={0}>
422          {mark !== null && <HostText {...(style.color ? style : { dimColor: true, ...style })}>{mark}</HostText>}
423        </Box>
424      )
425      // A page title or a section title, with a figure at the far end that moves under it when the
426      // pane is too narrow for both.
427      const heading = (title: string, note: string | null, size: 'heading' | 'body' = 'body') => (
428        <Box flexDirection="row" flexWrap="wrap" justifyContent="space-between" alignItems="flex-end" columnGap="md">
429          <HostText size={size} weight="semibold">
430            {title}
431          </HostText>
432          {note !== null && (
433            <HostText size="caption" dimColor>
434              {note}
435            </HostText>
436          )}
437        </Box>
438      )
439      // The back link, a line of its own at the top of a page: a link, dim at rest and full under the
440      // pointer or the focus (the Button's own `dimColor`). `ring` is the key that takes the focus on
441      // the page it leads to, the row the person came from.
442      const backLink = (to: Page, ring: string) => <Button key="back" plain dimColor label={t.back} onPress={go(to, ring)} />
443      // Actions are the host's own buttons, with chrome: `plain` would draw them as bare text. "Put in
444      // chat" is the screen's one primary action; the rest are secondary.
445      const action = (key: string, text: string, onPress: () => unknown, variant: 'primary' | 'secondary' = 'secondary') => (
446        <Button key={key} variant={variant} label={text} onPress={() => void onPress()} />
447      )
448      // Every read at once: one wait per redraw instead of one per read (a resize redraws
449      // on each step). Reading `minute` subscribes the pane to the minute clock.
450      const [snap, language, session, open, where, , now, mutedIds, done, hiddenIds, track, usualPace] = await Promise.all([
451        read($, snapshot),
452        read($, lang),
453        read($, log),
454        read($, expanded),
455        read($, page),
456        read($, minute),
457        $.clock.now(),
458        read($, muted),
459        read($, sent),
460        read($, hidden),
461        read($, limitTrack),
462        read($, usual),
463      ])
464      const t = UI[language]
465      if (!snap)
466        return gui ? (
467          <Box padding="md">
468            <HostText dimColor>{t.noData}</HostText>
469          </Box>
470        ) : (
471          <Text dimColor>{t.noData}</Text>
472        )
473
474      const points = session?.points ?? []
475      const fiveSpent = session?.limits?.five_hour?.spent ?? null
476      const weekSpent = session?.limits?.seven_day?.spent ?? null
477      const agents = snap.subagents
478      // Each agent's figures, in a column as wide as the longest: they start in one place.
479      const agentNotes = agents?.top.map(r => t.agentPeak(k(r.peak), r.steps)) ?? []
480      const NOTE_W = Math.max(0, ...agentNotes.map(n => n.length))
481      // Two empty columns on each side of every page; the grid fits inside them.
482      const PAD = 2
483      // The real width, however narrow: content wider than the pane wraps and breaks the grid.
484      const W = Math.max(16, e.props.bodyColumns - 2 * PAD)
485      const compact = W < COMPACT
486      // One grid for every list: name, tokens, share, then a bar or a chevron.
487      const NAME = nameWidth(W)
488      const NUM = 7
489      const PCT = 6
490      // An empty row where column labels used to be: keeps the rhythm without the words.
491      const columnsHead = <Text> </Text>
492      // Two empty rows between the home page's main blocks.
493      const sectionGap = (
494        <Box flexDirection="column">
495          <Text> </Text>
496          <Text> </Text>
497        </Box>
498      )
499      // A press that changes the page removes the Button that held the focus. On the desktop the ring
500      // goes to the new page's first stop (`ring`, else its back link), so the pane keeps the keyboard
501      // and the next click presses at once. The terminal's ring stays the engine's, as before.
502      // Not awaited: the ring waits for the next drawing. What came of it goes to the debug log only.
503      const go = (to: Page, ring = 'back') => async () => {
504        await update($, page, () => to)
505        if (gui)
506          void $.ui.focus({ requestId: PANE, key: ring }).then(
507            r => $.ui.log(`chudarin-context-mod: focus to ${ring}: ${r.deny ?? 'moved'}`, { to: 'debug' }),
508            err => $.ui.log(`chudarin-context-mod: focus to ${ring}: ${String(err)}`, { to: 'debug' }),
509          )
510      }
511      const pctOfUsed = (n: number) => (snap.used ? `${Math.round((n / snap.used) * 100)}%` : '')
512      const ofUsed = (n: number) => t.ofUsed(k(n), pctOfUsed(n))
513      const total = points[points.length - 1]?.tokens ?? snap.used
514
515      const back = (to: Page) => (
516        <Box flexDirection="column">
517          <Button key="back" plain label={t.back} onPress={go(to)}>
518            <Text dimColor>{t.back}</Text>
519          </Button>
520          <Text> </Text>
521        </Box>
522      )
523      // A narrow pane's title whose figure doesn't fit beside it: the figure goes under it.
524      const titleOver = (title: string, figure: string) => (
525        <Box flexDirection="column">
526          <Text bold>{title.toUpperCase()}</Text>
527          <Text dimColor>{`  ${figure}`}</Text>
528        </Box>
529      )
530      // A title with a figure on the right; `edge` is the column the figure ends at.
531      const titleRow = (title: string, right: string, edge = W) =>
532        compact && title.length + 1 + right.length > edge ? (
533          titleOver(title, right)
534        ) : (
535          <Text>
536            <Text bold>{title.toUpperCase()}</Text>
537            <Text dimColor>{right.padStart(Math.max(1, edge - title.length))}</Text>
538          </Text>
539        )
540      // A title with a note right after it, for a note that reads with the title.
541      const titleNote = (title: string, note: string) =>
542        compact && title.length + 2 + note.length > W ? (
543          titleOver(title, note)
544        ) : (
545          <Text>
546            <Text bold>{title.toUpperCase()}</Text>
547            <Text dimColor>{`  ${note}`}</Text>
548          </Text>
549        )
550
551      // "Don't show again" is for good and kept in the store; there is no way back.
552      const setMuted = async (change: (prev: string[]) => string[]) => {
553        const next = await update($, muted, change)
554        await $.store.set(MUTED, next).catch(err => $.ui.log(`chudarin-context-mod: hidden advice not saved: ${String(err)}`))
555      }
556      // Adds the request after whatever the person has typed; a command takes the draft's place,
557      // since it runs only on its own. The hint stays until it is sent.
558      const putInChat = (h: { id: string; prompt: string | null }) => async () => {
559        if (!h.prompt) return
560        const after = !h.prompt.startsWith('/') && (await $.prompt.read()).text.trim() !== ''
561        await $.prompt.fill({ text: after ? ` ${h.prompt}` : h.prompt, mode: after ? 'append' : 'replace' })
562      }
563      // Hidden for this session; after a /clear, for the new one.
564      const hide = (id: string) => async () => {
565        await followSession($)
566        await update($, hidden, prev => [...prev, id])
567      }
568      // Muted for good, sent to Claude this session, hidden by the person this session, or shown.
569      const stateOf = (id: string) =>
570        mutedIds.includes(id) ? 'muted' : done.includes(id) ? 'sent' : hiddenIds.includes(id) ? 'hidden' : 'shown'
571
572      // ---- entry page: what it is, why so much, what to do ----
573      if (where.kind === 'entry') {
574        const entry = snap.entries.find(x => x.id === where.id)
575        const help = helpFor(where.id, snap.lang)
576        const parent: Page = { kind: 'group', id: entry?.group ?? help.group }
577        if (gui && !entry)
578          return (
579            <Box flexDirection="column" padding="md" gap="lg">
580              {backLink(parent, 'back')}
581              <HostText dimColor>{t.entryGone}</HostText>
582            </Box>
583          )
584        if (!entry)
585          return (
586            <Box flexDirection="column" paddingX={PAD}>
587              {back(parent)}
588              <Text dimColor>{t.entryGone}</Text>
589            </Box>
590          )
591        const average = entry.count ? Math.round(entry.tokens / entry.count) : 0
592        const state = stateOf(entry.id)
593        if (gui) {
594          // A section of the page: its title, then what it says, rows `xs` apart.
595          const part = (title: string, body: ReturnType<typeof HostText>[]) => (
596            <Box flexDirection="column" gap="sm">
597              <HostText weight="semibold">{title}</HostText>
598              <Box flexDirection="column" gap="xs">
599                {body}
600              </Box>
601            </Box>
602          )
603          return (
604            <Box flexDirection="column" padding="md" gap="lg">
605              {backLink(parent, `entry-${entry.id}`)}
606              {heading(entry.label, ofUsed(entry.tokens), 'heading')}
607              {part(t.whatIs, [<HostText>{help.what}</HostText>])}
608              {part(t.whySoMuch, [
609                <HostText>{entry.count > 1 ? t.times(entry.count, k(average)) : t.once}</HostText>,
610                ...(entry.top.length > 0
611                  ? [
612                      <HostText size="caption" dimColor>
613                        {t.heaviest}
614                      </HostText>,
615                    ]
616                  : []),
617                ...entry.top.map(c => (
618                  <Box flexDirection="row" alignItems="flex-start" columnGap="sm">
619                    {figure(`+${k(c.tokens)}`, D_NUM)}
620                    <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
621                      <HostText>{c.label}</HostText>
622                    </Box>
623                  </Box>
624                )),
625              ])}
626              {/* advice hidden for good leaves no trace here either */}
627              {state !== 'muted' &&
628                part(t.whatToDo, [
629                  // hidden this session: the mark below stands in for the advice
630                  ...(state !== 'hidden' ? [<HostText>{help.todo ?? t.nothingToDo}</HostText>] : []),
631                  // one row of actions; what it holds depends on the advice's state
632                  ...(help.todo
633                    ? [
634                        <Box flexDirection="row" flexWrap="wrap" alignItems="flex-end" columnGap="md" rowGap="xs">
635                          {state === 'sent' && <HostText dimColor>{help.prompt?.startsWith('/') ? t.hintRan : t.hintSent}</HostText>}
636                          {state === 'hidden' && <HostText dimColor>{t.adviceHidden}</HostText>}
637                          {state === 'shown' && help.prompt && action('entry-fill', t.hintFill, putInChat({ id: entry.id, prompt: help.prompt }), 'primary')}
638                          {state === 'shown'
639                            ? action('entry-hide', t.hideAdvice, hide(entry.id))
640                            : action('entry-mute', t.neverShow, () => setMuted(prev => [...prev, entry.id]))}
641                        </Box>,
642                      ]
643                    : []),
644                ])}
645            </Box>
646          )
647        }
648        return (
649          <Box flexDirection="column" paddingX={PAD}>
650            {back(parent)}
651            {titleRow(entry.label, ofUsed(entry.tokens))}
652            <Text> </Text>
653            <Text bold>{t.whatIs}</Text>
654            <Box paddingLeft={2}>
655              <Text>{help.what}</Text>
656            </Box>
657            <Text> </Text>
658            <Text bold>{t.whySoMuch}</Text>
659            <Box paddingLeft={2} flexDirection="column">
660              <Text>{entry.count > 1 ? t.times(entry.count, k(average)) : t.once}</Text>
661              {entry.top.length > 0 && <Text dimColor>{t.heaviest}</Text>}
662              {entry.top.map(c => (
663                <Text wrap="truncate-end">
664                  {`+${k(c.tokens)}`.padStart(7)}
665                  {'  '}
666                  {c.label}
667                </Text>
668              ))}
669            </Box>
670            {/* advice hidden for good leaves no trace here either */}
671            {state !== 'muted' && (
672              <Box flexDirection="column">
673                <Text> </Text>
674                <Text bold>{t.whatToDo}</Text>
675                <Box paddingLeft={2} flexDirection="column">
676              {/* hidden this session: the mark below stands in for the advice */}
677              {state !== 'hidden' && <Text>{help.todo ?? t.nothingToDo}</Text>}
678              {/* one row of actions; what it holds depends on the advice's state */}
679              {help.todo && (
680                <Box flexDirection="row">
681                  {state === 'sent' && <Text dimColor>{help.prompt?.startsWith('/') ? t.hintRan : t.hintSent}</Text>}
682                  {state === 'hidden' && <Text dimColor>{t.adviceHidden}</Text>}
683                  {state === 'shown' && help.prompt && (
684                    <Button key="entry-fill" plain label={t.hintFill} onPress={putInChat({ id: entry.id, prompt: help.prompt })}>
685                      <Text color="claude">{t.hintFill}</Text>
686                    </Button>
687                  )}
688                  {(state !== 'shown' || help.prompt) && <Text>{'   '}</Text>}
689                  {state === 'shown' ? (
690                    <Button key="entry-hide" plain label={t.hideAdvice} onPress={hide(entry.id)}>
691                      <Text dimColor>{t.hideAdvice}</Text>
692                    </Button>
693                  ) : (
694                    <Button key="entry-mute" plain label={t.neverShow} onPress={() => setMuted(prev => [...prev, entry.id])}>
695                      <Text color="claude">{t.neverShow}</Text>
696                    </Button>
697                  )}
698                </Box>
699              )}
700                </Box>
701              </Box>
702            )}
703          </Box>
704        )
705      }
706
707      // ---- group page: its entries ----
708      if (where.kind === 'group') {
709        const group = GROUPS.find(g => g.id === where.id) ?? GROUPS[0]!
710        const list = snap.entries.filter(x => x.group === group.id)
711        const sum = list.reduce((n, x) => n + x.tokens, 0)
712        const max = Math.max(0, ...list.map(x => x.tokens))
713        // The name column in cells: the row less tokens, share, the bar where it shows, the chevron and
714        // a cell for each gap.
715        const groupName = Math.max(8, W - D_NUM - D_PCT - D_MARK - 4 - (compact ? 0 : D_BAR + 1))
716        if (gui)
717          return (
718            <Box flexDirection="column" padding="md" gap="lg">
719              {backLink({ kind: 'home' }, `group-${group.id}`)}
720              {heading(groupLabel(group.id, snap.lang), ofUsed(sum), 'heading')}
721              {list.length === 0 && <HostText dimColor>{t.emptyGroup}</HostText>}
722              {/* name | tokens | share | bar | chevron; a narrow pane leaves the bar out, the figures say it */}
723              <Box flexDirection="column" gap="xs">
724                {list.map(x => (
725                  <Box key={`row-${x.id}`} flexDirection="row" alignItems="flex-start" columnGap="sm">
726                    {/* the name may shrink below its text and is cut to its column, so the figures stay put */}
727                    <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
728                      <Button key={`entry-${x.id}`} plain label={x.label} onPress={go({ kind: 'entry', id: x.id })}>
729                        <HostText wrap="truncate-end">{clip(x.label, groupName)}</HostText>
730                      </Button>
731                    </Box>
732                    {figure(k(x.tokens), D_NUM)}
733                    {figure(pctOfUsed(x.tokens), D_PCT, { dimColor: true })}
734                    {!compact && Svg && (
735                      <Box width={D_BAR} flexShrink={0} alignSelf="center">
736                        <Svg source={lineSvg(max > 0 ? x.tokens / max : 0, group.color)} alt={`${x.label} ${k(x.tokens)}`} height={PX_BAR} />
737                      </Box>
738                    )}
739                    {markCell('›')}
740                  </Box>
741                ))}
742              </Box>
743            </Box>
744          )
745        // Group rows also hold a bar: the name leaves it four cells, and in a pane too narrow even
746        // for that the bar goes.
747        const NAME_G = nameWidth(W, 4)
748        const barW = Math.max(0, W - NAME_G - NUM - PCT - 4)
749        const bar = (tokens: number, width: number) =>
750          BLOCK.repeat(max > 0 ? Math.min(width, Math.max(1, Math.round((tokens / max) * width))) : 0)
751        // A narrow pane: the figures under the name, each row's bar starting at the same column.
752        const figures = (tokens: number) => `  ${k(tokens)} · ${pctOfUsed(tokens)}`
753        const FIG = Math.max(0, ...list.map(x => figures(x.tokens).length)) + 2
754        return (
755          <Box flexDirection="column" paddingX={PAD}>
756            {back({ kind: 'home' })}
757            {titleRow(groupLabel(group.id, snap.lang), ofUsed(sum))}
758            <Text> </Text>
759            {columnsHead}
760            {list.length === 0 && <Text dimColor>{t.emptyGroup}</Text>}
761            {list.map(x => {
762              const open = go({ kind: 'entry', id: x.id })
763              if (compact)
764                return (
765                  <Box key={`row-${x.id}`} flexDirection="column">
766                    <Box flexDirection="row">
767                      <Button key={`entry-${x.id}`} plain label={x.label} onPress={open}>
768                        {clip(x.label, W - 2)}
769                      </Button>
770                      <Text dimColor> ▸</Text>
771                    </Box>
772                    <Text>
773                      {`  ${k(x.tokens)}`}
774                      <Text dimColor>{` · ${pctOfUsed(x.tokens)}`.padEnd(FIG - 2 - k(x.tokens).length)}</Text>
775                      <Text color={group.color}>{bar(x.tokens, Math.max(0, W - FIG))}</Text>
776                    </Text>
777                  </Box>
778                )
779              // Only the name is the button: the pointer inverts a button, and an inverted bar breaks.
780              const name = clip(x.label, NAME_G - 1)
781              return (
782                <Box key={`row-${x.id}`} flexDirection="row">
783                  <Button key={`entry-${x.id}`} plain label={x.label} onPress={open}>
784                    {name}
785                  </Button>
786                  <Text>
787                    {' '.repeat(NAME_G - name.length)}
788                    {k(x.tokens).padStart(NUM)}
789                    <Text dimColor>{pctOfUsed(x.tokens).padStart(PCT)}</Text>
790                    {'  '}
791                    <Text color={group.color}>{bar(x.tokens, barW).padEnd(barW)}</Text>
792                    <Text dimColor> ▸</Text>
793                  </Text>
794                </Box>
795              )
796            })}
797          </Box>
798        )
799      }
800
801      // ---- home ----
802      const v = pace(points)
803      const fill = snap.window ? (total / snap.window) * 100 : 0
804      // Past the threshold there is nothing left to count.
805      const turnsLeft = v.recent > 0 && total < snap.threshold ? Math.floor((snap.threshold - total) / v.recent) : null
806      // Limit figures arrive with model replies. In an idle session the reset time can pass while the
807      // percent stays old: then the window has started over, so the limit shows as reset.
808      const limit = (re: RegExp) => {
809        const l = snap.limits.find(x => re.test(x.kind) && !/fable/i.test(x.kind))
810        const passed = !!l?.resetsAt && Date.parse(l.resetsAt) <= now
811        return l && { ...l, percentUsed: passed ? 0 : l.percentUsed, passed }
812      }
813      const limitLine = (l: { resetsAt?: string | null; passed: boolean }) =>
814        !l.resetsAt ? '' : l.passed ? t.wasReset(resetLabel(l.resetsAt, now)) : t.resets(resetLabel(l.resetsAt, now))
815      const five = limit(/five_hour/)
816      const forecast =
817        five?.resetsAt && !five.passed && track?.resetsAt === five.resetsAt
818          ? limitForecast(track, now, Date.parse(five.resetsAt))
819          : null
820      const fiveForecast = forecast === null ? '' : forecast === 'untilReset' ? t.limitUntilReset : t.limitLeft(forecast.minutes)
821      const week = limit(/seven_day/)
822      const tiles = [
823        {
824          title: t.tileContext,
825          percent: fill,
826          level: levelOf((total / snap.threshold) * 100, 50, 80),
827          lines: [t.ofWindow(k(total), k(snap.window)), turnsLeft !== null ? t.turnsLeft(turnsLeft) : ''],
828        },
829        ...(five
830          ? [
831              {
832                title: t.tile5h,
833                percent: five.percentUsed,
834                level: levelOf(five.percentUsed, 70, 90),
835                lines: [limitLine(five), fiveForecast],
836              },
837            ]
838          : []),
839        ...(week
840          ? [
841              {
842                title: t.tileWeek,
843                percent: week.percentUsed,
844                level: levelOf(week.percentUsed, 70, 90),
845                lines: [limitLine(week), ''],
846              },
847            ]
848          : []),
849      ]
850      const gap = 2
851      const colW = Math.floor((W - gap * (tiles.length - 1)) / tiles.length)
852      // Never wider than its column: in a very narrow pane the meter takes the whole of it.
853      const meterW = Math.min(colW, Math.max(6, colW - 2))
854      // Each tile's text is cut to its column; the gap between columns always stays.
855      const cell = (text: string, i: number) => fitCell(text, colW) + (i < tiles.length - 1 ? ' '.repeat(gap) : '')
856
857      const groups = groupTotals(snap.entries, snap.lang)
858      const usedGroups = groups.filter(g => g.tokens > 0)
859      const stack = widths(
860        usedGroups.map(g => g.tokens),
861        W - (usedGroups.length - 1),
862      )
863      const hint = insight(snap.entries, snap.used, snap.lang, [...hiddenIds, ...done, ...mutedIds])
864      const tempo = speed(points, usualPace)
865      const prices = snap.prices.slice(0, 6)
866      const grid = priceGrid(W)
867      const priceRows = Math.ceil(prices.length / grid.columns)
868      const toggle = (id: string) => () =>
869        update($, expanded, prev => (prev.includes(id) ? prev.filter(n => n !== id) : [...prev, id]))
870      const isOpen = (id: string) => open.includes(id)
871      // One column per turn: what that turn added, so a heavy turn stands out as a peak.
872      const shown = points.slice(-Math.max(10, W - 8) - 1)
873      const rises = turnRises(shown)
874      // One point is the context at start: nothing to chart until a second one (or a compaction).
875      const chartable = points.length >= 2 || (session?.compacts.length ?? 0) > 0
876      const chartMax = Math.max(0, ...rises)
877      // The five biggest jumps, listed below the chart; each one's column joins its hover group.
878      const peaks = jumps(shown, 5)
879      const peakAt = new Map(peaks.map((j, n) => [shown.findIndex(p => p.turn === j.turn) - 1, n + 1]))
880      // A chart row split so each peak's cell joins its hover group: pointing at a jump in the
881      // list lights its column, and pointing at the column lights the jump. The surface does the
882      // lighting; no hook runs.
883      const chartLine = (line: string) => {
884        const parts: ReturnType<typeof Text>[] = []
885        let run = ''
886        const flush = () => {
887          if (run) parts.push(<Text color="suggestion">{run}</Text>)
888          run = ''
889        }
890        for (let c = 0; c < line.length; c++) {
891          const n = peakAt.get(c)
892          if (n === undefined) {
893            run += line[c]
894            continue
895          }
896          flush()
897          parts.push(
898            <Text color="suggestion" hover={{ scope: `peak-${n}`, color: 'claude', bold: true }}>
899              {line[c]}
900            </Text>,
901          )
902        }
903        flush()
904        return parts
905      }
906
907      if (gui) {
908        const stale = now - (snap.at ?? now) >= STALE_MS
909        // The chart's slots: one a turn, so a few turns draw slim columns at the left and the empty
910        // slots are the turns to come. Past 100 turns a slot's width is rounded where it ends.
911        const slots = CHART_SLOTS.find(n => n >= rises.length) ?? rises.length
912        const slotWidth = (from: number) => `${Math.round(((from + 1) / slots) * 100) - Math.round((from / slots) * 100)}%`
913        // A column's height: its share of the biggest rise, a whole percent, at least 1 when above zero.
914        const columnHeight = (rise: number) =>
915          chartMax > 0 && rise > 0 ? Math.max(1, Math.round((Math.min(rise, chartMax) / chartMax) * 100)) : 0
916        // The stacked bar's pieces in whole percents that add up to 100.
917        const piece = widths(
918          usedGroups.map(g => g.tokens),
919          100,
920        )
921        // A jump's caption column, in cells: the row less the delta, the turn, the mark and the gaps.
922        const captionCells = Math.max(8, W - D_NUM - D_TURN - D_MARK - 3)
923        return (
924          <Box flexDirection="column" padding="md" gap="xl">
925            {/* three cards side by side; a narrow pane stacks them */}
926            <Box flexDirection="column" gap="sm">
927              <Box flexDirection={compact ? 'column' : 'row'} gap="md">
928                {tiles.map(tile => (
929                  <Box
930                    flexDirection="column"
931                    flexGrow={1}
932                    flexShrink={1}
933                    {...(compact ? {} : { width: `${Math.floor(100 / tiles.length)}%` })}
934                    borderStyle="round"
935                    borderDimColor
936                    padding="md"
937                    gap="xs"
938                  >
939                    <HostText size="caption" dimColor>
940                      {sentenceCase(tile.title)}
941                    </HostText>
942                    {/* the level's color only once it asks for attention; the meter always carries it */}
943                    <HostText size="title" weight="semibold" tabular {...(tile.level === 'ok' ? {} : { color: LEVEL_COLOR[tile.level] })}>
944                      {`${Math.round(tile.percent)}%`}
945                    </HostText>
946                    {Svg && (
947                      <Svg
948                        source={lineSvg(tile.percent / 100, LEVEL_HEX[tile.level], { track: true })}
949                        alt={`${sentenceCase(tile.title)} ${Math.round(tile.percent)}%`}
950                        height={PX_METER}
951                      />
952                    )}
953                    {tile.lines.filter(Boolean).map(l => (
954                      <HostText size="caption" dimColor>
955                        {l}
956                      </HostText>
957                    ))}
958                  </Box>
959                ))}
960              </Box>
961              {tempo && <HostText>{t.speed(tempo.kind, tempo.ratio)}</HostText>}
962            </Box>
963
964            {/* what fills the window: the title over the tokens column with the total */}
965            <Box flexDirection="column" gap="sm">
966              <Box flexDirection="row" alignItems="flex-end" columnGap="sm">
967                <Box flexGrow={1} flexShrink={1}>
968                  <HostText weight="semibold">{t.whatFills}</HostText>
969                </Box>
970                {figure(k(snap.used), D_NUM, { dimColor: true })}
971                <Box width={D_PCT} flexShrink={0} />
972                {markCell(null)}
973              </Box>
974              {/* A bar piece and its legend row share a hover group: pointing at either lights both.
975                  The piece is drawn translucent over a Box that takes the group's color when lit. */}
976              {Svg && (
977                <Box flexDirection="row" columnGap="xs">
978                  {usedGroups.map((g, i) => (
979                    <Box
980                      width={`${piece[i] ?? 0}%`}
981                      flexShrink={1}
982                      hover={{ scope: `group-${g.id}`, backgroundColor: g.color }}
983                    >
984                      <Svg source={lineSvg(1, g.color, { opacity: 0.7 })} alt={`${g.label} ${k(g.tokens)}`} height={PX_STACK} />
985                    </Box>
986                  ))}
987                </Box>
988              )}
989              {/* dot | name | tokens | share | chevron */}
990              <Box flexDirection="column" gap="xs">
991                {usedGroups.map(g => {
992                  const lit = { scope: `group-${g.id}`, bold: true } as const
993                  return (
994                    <Box key={`row-${g.id}`} flexDirection="row" alignItems="flex-start" columnGap="sm">
995                      {markCell('●', { color: g.color, hover: lit })}
996                      <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
997                        <Button key={`group-${g.id}`} plain label={g.label} hover={lit} onPress={go({ kind: 'group', id: g.id })}>
998                          <HostText wrap="truncate-end">{clip(g.label, Math.max(8, W - D_MARK - D_NUM - D_PCT - D_MARK - 4))}</HostText>
999                        </Button>
1000                      </Box>
1001                      {figure(k(g.tokens), D_NUM, { hover: lit })}
1002                      {figure(pctOfUsed(g.tokens), D_PCT, { dimColor: true, hover: lit })}
1003                      {markCell('›', { hover: lit })}
1004                    </Box>
1005                  )
1006                })}
1007              </Box>
1008              {/* the arrow on the hint's first line; the buttons under the text */}
1009              {hint && (
1010                <Box flexDirection="row" alignItems="flex-start" columnGap="sm" marginTop="sm">
1011                  {/* the arrow in the text color: the primary button is the screen's one accent */}
1012                  <HostText weight="semibold">→</HostText>
1013                  <Box flexDirection="column" flexShrink={1} gap="sm">
1014                    <HostText>{hint.text}</HostText>
1015                    <Box flexDirection="row" flexWrap="wrap" columnGap="md" rowGap="xs">
1016                      {hint.prompt && action('hint-fill', t.hintFill, putInChat(hint), 'primary')}
1017                      {/* the entry page's label: one name for one action on this surface */}
1018                      {action('hint-hide', t.hideAdvice, hide(hint.id))}
1019                    </Box>
1020                  </Box>
1021                </Box>
1022              )}
1023            </Box>
1024
1025            {/* what one action costs: name | average | how many times */}
1026            <Box flexDirection="column" gap="sm">
1027              <HostText weight="semibold">{t.prices}</HostText>
1028              {prices.length === 0 && <HostText dimColor>{t.noActions}</HostText>}
1029              {prices.length > 0 && (
1030                <Box flexDirection="column" gap="xs">
1031                  {prices.map(p => (
1032                    <Box flexDirection="row" alignItems="flex-start" columnGap="sm">
1033                      <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
1034                        <HostText>{p.name}</HostText>
1035                      </Box>
1036                      {figure(k(p.average), D_NUM)}
1037                      {figure(`×${p.count}`, D_COUNT, { dimColor: true })}
1038                      {/* an empty chevron cell: the figures end where the context table's do */}
1039                      {markCell(null)}
1040                    </Box>
1041                  ))}
1042                </Box>
1043              )}
1044            </Box>
1045
1046            {/* the whole session, compactions included */}
1047            {session && session.requests > 0 && (
1048              <Box flexDirection="column" gap="sm">
1049                <Box flexDirection="row" flexWrap="wrap" alignItems="flex-end" columnGap="sm">
1050                  <HostText weight="semibold">{t.session}</HostText>
1051                  <HostText size="caption" dimColor>
1052                    {t.since(resetLabel(new Date(session.startedAt).toISOString(), now))}
1053                  </HostText>
1054                </Box>
1055                <Box flexDirection="column" gap="xs">
1056                  <HostText>{t.sessionRuns(Math.max(0, Math.round((now - session.startedAt) / 60_000)), session.prompts ?? 0)}</HostText>
1057                  {fiveSpent !== null && <HostText>{t.sessionSpent(fiveSpent, weekSpent)}</HostText>}
1058                  {fiveSpent !== null && fiveSpent > 0 && (session.prompts ?? 0) > 0 && (
1059                    <HostText>{t.perMessage(fiveSpent / (session.prompts ?? 1))}</HostText>
1060                  )}
1061                  <HostText>
1062                    {t.compactsLine(session.compacts.length, k(session.compacts.reduce((n, c) => n + Math.max(0, c.before - c.after), 0)))}
1063                  </HostText>
1064                  {/* subagents: their reports alone reach the context, so what they processed shows here */}
1065                  {agents && [
1066                    <HostText>{t.agents(agents.count, k(agents.fresh + agents.cached))}</HostText>,
1067                    <HostText>{t.agentsSplit(k(agents.fresh), k(agents.cached))}</HostText>,
1068                    ...agents.top.map((r, i) => (
1069                      <Box flexDirection="row" alignItems="flex-start" columnGap="sm">
1070                        <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
1071                          <HostText>{r.description}</HostText>
1072                        </Box>
1073                        <Box width={NOTE_W} flexShrink={0}>
1074                          <HostText dimColor tabular>
1075                            {agentNotes[i]}
1076                          </HostText>
1077                        </Box>
1078                      </Box>
1079                    )),
1080                  ]}
1081                </Box>
1082              </Box>
1083            )}
1084
1085            {/* folded: the chart, its jumps and the compactions; once there is something to chart */}
1086            {chartable && (
1087            <Box flexDirection="column" gap="sm">
1088              <Button key="block-dynamics" plain label={t.growth} onPress={toggle('block:dynamics')}>
1089                <HostText weight="semibold">{`${isOpen('block:dynamics') ? '▾' : '▸'} ${t.growth}`}</HostText>
1090              </Button>
1091              {isOpen('block:dynamics') && (
1092                <Box flexDirection="column" gap="sm">
1093                  {/* the axis (the biggest rise on top, 0 at the bottom), then the plot */}
1094                  <Box flexDirection="row" alignItems="stretch" columnGap="sm">
1095                    <Box width={D_AXIS} flexShrink={0} flexDirection="column" justifyContent="space-between" alignItems="flex-end">
1096                      <HostText size="caption" dimColor tabular>
1097                        {k(chartMax)}
1098                      </HostText>
1099                      <HostText size="caption" dimColor tabular>
1100                        0
1101                      </HostText>
1102                    </Box>
1103                    {/* one slot a turn; a column is a colored Box, and a peak's column joins its hover
1104                        group, so the jump list and the chart light each other */}
1105                    <Box flexDirection="row" flexGrow={1} flexShrink={1} minWidth={0} height={D_CHART_ROWS}>
1106                      {rises.map((rise, c) => {
1107                        const peak = peakAt.get(c)
1108                        // not `h`: that name is the JSX factory
1109                        const tall = columnHeight(rise)
1110                        return (
1111                          <Box width={slotWidth(c)} flexShrink={0} flexDirection="column" justifyContent="flex-end" alignItems="center">
1112                            {tall > 0 && (
1113                              <Box
1114                                width="60%"
1115                                height={`${tall}%`}
1116                                backgroundColor={CHART_HEX}
1117                                {...(peak !== undefined ? { hover: { scope: `peak-${peak}`, backgroundColor: 'claude' } } : {})}
1118                              />
1119                            )}
1120                          </Box>
1121                        )
1122                      })}
1123                    </Box>
1124                  </Box>
1125                  {shown.length > 2 && (
1126                    <Box flexDirection="row" columnGap="sm">
1127                      <Box width={D_AXIS} flexShrink={0} />
1128                      <HostText size="caption" dimColor>
1129                        {t.turnRange(shown[1]!.turn, shown[shown.length - 1]!.turn)}
1130                      </HostText>
1131                    </Box>
1132                  )}
1133                  {/* delta | turn | caption | mark. A jump with more to read opens on a press. */}
1134                  <Box flexDirection="column" gap="xs" marginTop="sm">
1135                    {peaks.map((j, n) => {
1136                      const caption = j.cause ?? t.conversation
1137                      const full = j.detail ?? caption
1138                      const opens = full !== caption || caption.length > captionCells
1139                      const line = clip(caption, captionCells)
1140                      const hover = { scope: `peak-${n + 1}`, color: 'claude' } as const
1141                      const isOpenJump = isOpen(`jump:${j.turn}`)
1142                      // Opened: what the line doesn't already say. The label caption in full is not repeated.
1143                      const rest = line === caption && full.startsWith(caption) ? full.slice(caption.length).replace(/^[:\s]+/, '') : full
1144                      return (
1145                        <Box flexDirection="column" gap="xs">
1146                          <Box flexDirection="row" alignItems="flex-start" columnGap="sm">
1147                            {figure(`+${k(j.delta)}`, D_NUM, { hover })}
1148                            <Box width={D_TURN} flexShrink={0}>
1149                              <HostText dimColor hover={hover}>
1150                                {t.turn(j.turn)}
1151                              </HostText>
1152                            </Box>
1153                            <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
1154                              {opens ? (
1155                                <Button key={`jump-${j.turn}`} plain label={caption} hover={hover} onPress={toggle(`jump:${j.turn}`)}>
1156                                  <HostText>{line}</HostText>
1157                                </Button>
1158                              ) : (
1159                                <HostText hover={hover}>{line}</HostText>
1160                              )}
1161                            </Box>
1162                            {markCell(opens ? (isOpenJump ? '▾' : '▸') : null, { hover })}
1163                          </Box>
1164                          {isOpenJump && (
1165                            <Box flexDirection="row" columnGap="sm">
1166                              <Box width={D_NUM} flexShrink={0} />
1167                              <Box width={D_TURN} flexShrink={0} />
1168                              <Box flexGrow={1} flexShrink={1}>
1169                                <HostText size="caption" dimColor>
1170                                  {rest || full}
1171                                </HostText>
1172                              </Box>
1173                            </Box>
1174                          )}
1175                        </Box>
1176                      )
1177                    })}
1178                    {(session?.compacts ?? []).map(c => (
1179                      <Box flexDirection="row" alignItems="flex-start" columnGap="sm">
1180                        {figure(`−${k(Math.max(0, c.before - c.after))}`, D_NUM)}
1181                        <Box width={D_TURN} flexShrink={0}>
1182                          <HostText dimColor>{t.turn(c.turn)}</HostText>
1183                        </Box>
1184                        <Box flexGrow={1} flexShrink={1}>
1185                          <HostText>
1186                            {t.compactLine(c.trigger === 'manual' ? t.manual : c.trigger === 'auto' ? t.auto : t.plugin, k(c.before), k(c.after))}
1187                          </HostText>
1188                        </Box>
1189                      </Box>
1190                    ))}
1191                  </Box>
1192                </Box>
1193              )}
1194            </Box>
1195            )}
1196
1197            {/* only once the figures are five minutes old; limits move only when a reply comes in */}
1198            {stale && (
1199              <Box flexDirection="row" flexWrap="wrap" alignItems="flex-end" columnGap="sm">
1200                <HostText size="caption" dimColor>
hooks/entries.ts 241 lines
1// Turns /context categories and the conversation into the dashboard's groups and entries.
2import type { Category, GroupId, Item } from '../types'
3
4import { helpFor } from './help'
5import { type Lang, type Strings, UI } from './i18n'
6import { IMAGE_TOKENS, type Message, k, kind, label } from './model'
7
8type Call = { label: string; tokens: number }
9type Entry = { id: string; label: string; group: GroupId; tokens: number; count: number; top: Call[] }
10type GroupTotal = { id: GroupId; label: string; color: string; tokens: number }
11type Price = { name: string; count: number; average: number }
12
13// Fixed order: a group keeps its color whatever its size. Blue, orange, aqua, violet from the
14// dataviz categorical palette, aqua and violet a step darker so one set works on any terminal:
15// checked with the dataviz validator on #000000, #1a1a19, #282828, #eeeeee, #f5f5f0 and #ffffff,
16// every check passing on each. Yellow is skipped: it means "warning" on the meters.
17export const GROUPS: readonly { id: GroupId; text: keyof Strings; color: string }[] = [
18  { id: 'tools', text: 'groupTools', color: '#3987e5' },
19  { id: 'service', text: 'groupService', color: '#d95926' },
20  { id: 'chat', text: 'groupChat', color: '#178f66' },
21  { id: 'rules', text: 'groupRules', color: '#7a6ce4' },
22]
23
24export function groupLabel(id: GroupId, lang: Lang): string {
25  const g = GROUPS.find(x => x.id === id) ?? GROUPS[0]!
26  return UI[lang][g.text] as string
27}
28
29const TOP_CALLS = 5
30const CODE_TOOLS = new Set(['Write', 'Edit', 'NotebookEdit', 'MultiEdit'])
31const SKILL_BODY = /^Base directory for this skill: (\S+)/
32
33type Block = { type: string; [field: string]: unknown }
34
35function textOf(content: unknown): { chars: number; images: number } {
36  if (typeof content === 'string') return { chars: content.length, images: 0 }
37  if (!Array.isArray(content)) return { chars: 0, images: 0 }
38  let chars = 0
39  let images = 0
40  for (const b of content as Block[]) {
41    if (b.type === 'text' && typeof b.text === 'string') chars += b.text.length
42    if (b.type === 'image') images += 1
43  }
44  return { chars, images }
45}
46
47type Piece = { id: string; tokens: number; call: string | null; action: string | null; callId: string | null }
48
49// Every piece of the conversation, tagged with its entry id, the call it belongs to and the action kind.
50function pieces(messages: readonly Message[]): Piece[] {
51  const out: Piece[] = []
52  const calls = new Map<string, { name: string; label: string }>()
53  for (const m of messages) {
54    for (const b of m.content) {
55      if (m.role === 'assistant') {
56        if (b.type === 'text' && typeof b.text === 'string')
57          out.push({ id: 'assistant', tokens: b.text.length / 4, call: null, action: null, callId: null })
58        if (b.type === 'thinking' && typeof b.thinking === 'string')
59          out.push({ id: 'thinking', tokens: b.thinking.length / 4, call: null, action: null, callId: null })
60        if (b.type === 'tool_use' && typeof b.id === 'string' && typeof b.name === 'string') {
61          const input = (b.input ?? {}) as Record<string, unknown>
62          const name = b.name
63          const callLabel = label({ ...input, tool: name })
64          calls.set(b.id, { name, label: callLabel })
65          out.push({
66            id: CODE_TOOLS.has(name) ? 'code' : 'args',
67            tokens: JSON.stringify(input).length / 4,
68            call: callLabel,
69            action: name,
70            callId: b.id,
71          })
72        }
73        continue
74      }
75      if (b.type === 'tool_result') {
76        const call = typeof b.tool_use_id === 'string' ? calls.get(b.tool_use_id) : undefined
77        const { chars, images } = textOf(b.content)
78        // A Skill call answers with one line; its body arrives as its own row below.
79        const id = call?.name === 'Skill' ? 'args' : `result:${kind(call?.name ?? 'tool')}`
80        out.push({
81          id,
82          tokens: chars / 4,
83          call: call?.label ?? null,
84          action: call?.name ?? null,
85          callId: typeof b.tool_use_id === 'string' ? b.tool_use_id : null,
86        })
87        for (let i = 0; i < images; i++)
88          out.push({ id: 'images', tokens: IMAGE_TOKENS, call: null, action: 'image', callId: null })
89      } else if (b.type === 'text' && typeof b.text === 'string') {
90        const text = b.text.trimStart()
91        const skill = SKILL_BODY.exec(text)
92        if (skill) {
93          const name = skill[1]!.split('/').filter(Boolean).pop() ?? 'skill'
94          out.push({ id: 'skills-loaded', tokens: text.length / 4, call: name, action: 'skill', callId: null })
95        } else if (text.startsWith('<system-reminder>')) {
96          out.push({ id: 'reminders', tokens: text.length / 4, call: null, action: null, callId: null })
97        } else {
98          out.push({ id: 'user', tokens: text.length / 4, call: null, action: null, callId: null })
99        }
100      } else if (b.type === 'image') {
101        out.push({ id: 'images', tokens: IMAGE_TOKENS, call: null, action: 'image', callId: null })
102      }
103    }
104  }
105  return out
106}
107
108// All entries: categories from /context, with Messages replaced by the parts of the conversation.
109export function buildEntries(
110  categories: readonly Category[],
111  details: Record<string, Item[]>,
112  messages: readonly Message[],
113  lang: Lang,
114): Entry[] {
115  const entries: Entry[] = []
116  for (const c of categories) {
117    if (c.isFree || /^messages/i.test(c.name) || c.tokens <= 0) continue
118    const id = `cat:${c.name}`
119    const help = helpFor(id, lang)
120    const list = details[c.name] ?? []
121    entries.push({
122      id,
123      label: help.label,
124      group: help.group,
125      tokens: c.tokens,
126      count: list.length,
127      top: list.slice(0, TOP_CALLS).map(i => ({ label: i.name, tokens: i.tokens })),
128    })
129  }
130
131  const sums = new Map<string, { tokens: number; count: number; calls: Map<string, number> }>()
132  for (const p of pieces(messages)) {
133    const s = sums.get(p.id) ?? { tokens: 0, count: 0, calls: new Map<string, number>() }
134    s.tokens += p.tokens
135    s.count += 1
136    if (p.call) s.calls.set(p.call, (s.calls.get(p.call) ?? 0) + p.tokens)
137    sums.set(p.id, s)
138  }
139  const raw = [...sums.values()].reduce((n, s) => n + s.tokens, 0)
140  const measured = categories.find(c => /^messages/i.test(c.name))?.tokens ?? 0
141  const scale = raw > 0 && measured > 0 ? measured / raw : 1
142
143  for (const [id, s] of sums) {
144    const tokens = Math.round(s.tokens * scale)
145    if (tokens <= 0) continue
146    const help = helpFor(id, lang)
147    entries.push({
148      id,
149      label: help.label,
150      group: help.group,
151      tokens,
152      count: s.count,
153      top: [...s.calls]
154        .map(([callLabel, t]) => ({ label: callLabel, tokens: Math.round(t * scale) }))
155        .sort((a, b) => b.tokens - a.tokens)
156        .slice(0, TOP_CALLS),
157    })
158  }
159  return entries.sort((a, b) => b.tokens - a.tokens)
160}
161
162export function groupTotals(entries: readonly Entry[], lang: Lang): GroupTotal[] {
163  return GROUPS.map(g => ({
164    id: g.id,
165    label: groupLabel(g.id, lang),
166    color: g.color,
167    tokens: entries.filter(e => e.group === g.id).reduce((n, e) => n + e.tokens, 0),
168  }))
169}
170
171const ACTION_TEXT: Record<string, keyof Strings> = {
172  Write: 'actWrite',
173  Edit: 'actEdit',
174  MultiEdit: 'actEdit',
175  NotebookEdit: 'actNotebook',
176  Read: 'actRead',
177  Bash: 'actBash',
178  WebSearch: 'actWebSearch',
179  WebFetch: 'actWebFetch',
180  Grep: 'actSearch',
181  Glob: 'actSearch',
182  Agent: 'actAgent',
183  image: 'actImage',
184  skill: 'actSkill',
185}
186
187function actionName(action: string, lang: Lang): string | null {
188  if (action === 'Skill' || action === 'AskUserQuestion' || action === 'ToolSearch') return null
189  if (action.startsWith('mcp__')) return kind(action)
190  const text = ACTION_TEXT[action]
191  return text ? (UI[lang][text] as string) : action
192}
193
194// Average price of one action: what I sent plus what came back, in estimated tokens.
195export function actionPrices(messages: readonly Message[], lang: Lang): Price[] {
196  const perCall = new Map<string, { action: string; tokens: number }>()
197  const single: { action: string; tokens: number }[] = []
198  for (const p of pieces(messages)) {
199    if (!p.action) continue
200    if (p.callId) {
201      const c = perCall.get(p.callId) ?? { action: p.action, tokens: 0 }
202      c.tokens += p.tokens
203      perCall.set(p.callId, c)
204    } else {
205      single.push({ action: p.action, tokens: p.tokens })
206    }
207  }
208  const sums = new Map<string, { count: number; tokens: number }>()
209  for (const { action, tokens } of [...perCall.values(), ...single]) {
210    const name = actionName(action, lang)
211    if (!name) continue
212    const s = sums.get(name) ?? { count: 0, tokens: 0 }
213    sums.set(name, { count: s.count + 1, tokens: s.tokens + tokens })
214  }
215  return [...sums]
216    .map(([name, s]) => ({ name, count: s.count, average: Math.round(s.tokens / s.count) }))
217    .filter(p => p.average > 0)
218    .sort((a, b) => b.average - a.average)
219}
220
221// One line worth acting on, or nothing.
222type Hint = { id: string; text: string; prompt: string | null }
223
224// The biggest entry with advice, if it holds over a tenth of the used context.
225// `hidden`: advice the person sent, ran, hid or muted.
226export function insight(
227  entries: readonly Entry[],
228  used: number,
229  lang: Lang,
230  hidden: readonly string[] = [],
231): Hint | null {
232  for (const e of entries) {
233    const help = helpFor(e.id, lang)
234    if (!help.todo || hidden.includes(e.id)) continue
235    if (used > 0 && e.tokens / used > 0.1)
236      return { id: e.id, text: `${e.label} ${help.took} ${k(e.tokens)}. ${help.todo}`, prompt: help.prompt }
237    return null
238  }
239  return null
240}
241
hooks/help.ts 342 lines
1// Plain-language names and help for every kind of entry the dashboard shows, in Russian and English.
2import type { GroupId } from '../types'
3
4import type { Lang } from './i18n'
5
6type Text = {
7  label: string
8  what: string
9  // What the person can do about it; null when nothing can be done.
10  todo: string | null
11  // What the hint's button puts in the prompt box: a request to Claude or a command.
12  prompt?: string
13}
14
15type Help = Omit<Text, 'prompt'> & {
16  prompt: string | null
17  group: GroupId
18  // The insight sentence: "<label> <took> <tokens>. <todo>"
19  took: string
20}
21
22type Entry = {
23  group: GroupId
24  // Past-tense Russian verb agreeing with the label.
25  took: 'занял' | 'заняла' | 'заняли' | 'заняло'
26  ru: Text
27  en: Text
28}
29
30const WEB_RU = 'Дальше ищи в интернете и читай страницы в субагенте, в чат возвращай только итог.'
31const WEB_EN = 'From now on, search the web and read pages in a subagent, and bring back only the summary.'
32
33const HELP: Record<string, Entry> = {
34  'result:Bash': {
35    group: 'tools',
36    took: 'занял',
37    ru: {
38      label: 'Вывод команд Bash',
39      what: 'Всё, что напечатали команды, которые запускал Claude: тесты, сборка, поиск, git. Вывод остаётся в контексте до конца сессии.',
40      todo: 'Проси Claude запускать тесты и разбирать длинные логи в субагенте: в чат вернётся только итог.',
41      prompt: 'Дальше запускай тесты и разбирай длинные логи в субагенте, в чат возвращай только итог.',
42    },
43    en: {
44      label: 'Bash output',
45      what: 'Everything the commands Claude ran printed: tests, builds, searches, git. The output stays in the context until the session ends.',
46      todo: 'Ask Claude to run tests and go through long logs in a subagent: only the summary comes back.',
47      prompt: 'From now on, run tests and go through long logs in a subagent, and bring back only the summary.',
48    },
49  },
50  'result:Read': {
51    group: 'tools',
52    took: 'заняли',
53    ru: {
54      label: 'Прочитанные файлы',
55      what: 'Содержимое файлов, которые прочитал Claude. Файл остаётся в контексте целиком, даже если нужна была пара строк.',
56      todo: 'Называй в задаче файл и функцию: чем точнее просьба, тем меньше Claude читает.',
57    },
58    en: {
59      label: 'Files read',
60      what: 'The contents of files Claude read. A whole file stays in the context even when only a few lines were needed.',
61      todo: 'Name the file and function in your request: the more precise it is, the less Claude reads.',
62    },
63  },
64  'result:WebSearch': {
65    group: 'tools',
66    took: 'занял',
67    ru: { label: 'Поиск в вебе', what: 'Результаты поиска в интернете: заголовки, ссылки, выдержки.', todo: 'Проси Claude искать в интернете и читать страницы в субагенте: в чат вернётся только итог.', prompt: WEB_RU },
68    en: { label: 'Web search', what: 'Web search results: titles, links, snippets.', todo: 'Ask Claude to search the web and read pages in a subagent: only the summary comes back.', prompt: WEB_EN },
69  },
70  'result:WebFetch': {
71    group: 'tools',
72    took: 'заняли',
73    ru: {
74      label: 'Загруженные страницы',
75      what: 'Веб-страницы, которые Claude загрузил и пересказал в текст.',
76      todo: 'Проси Claude искать в интернете и читать страницы в субагенте: в чат вернётся только итог.',
77      prompt: WEB_RU,
78    },
79    en: {
80      label: 'Fetched pages',
81      what: 'Web pages Claude fetched and turned into text.',
82      todo: 'Ask Claude to search the web and read pages in a subagent: only the summary comes back.',
83      prompt: WEB_EN,
84    },
85  },
86  'result:Grep': {
87    group: 'tools',
88    took: 'занял',
89    ru: { label: 'Поиск по файлам', what: 'Найденные строки и пути файлов.', todo: 'Называй в задаче файл и функцию: чем точнее просьба, тем меньше Claude читает.' },
90    en: { label: 'File search', what: 'Matching lines and file paths.', todo: 'Name the file and function in your request: the more precise it is, the less Claude reads.' },
91  },
92  'result:Glob': {
93    group: 'tools',
94    took: 'заняли',
95    ru: { label: 'Списки файлов', what: 'Пути файлов, найденные по шаблону.', todo: 'Называй в задаче файл и функцию: чем точнее просьба, тем меньше Claude читает.' },
96    en: { label: 'File lists', what: 'File paths matched by a pattern.', todo: 'Name the file and function in your request: the more precise it is, the less Claude reads.' },
97  },
98  'result:Agent': {
99    group: 'tools',
100    took: 'заняли',
101    ru: {
102      label: 'Отчёты субагентов',
103      what: 'Итоговые отчёты субагентов. Их собственная работа в этот контекст не попадает, только отчёт.',
104      todo: null,
105    },
106    en: {
107      label: 'Subagent reports',
108      what: "Final reports from subagents. Their own work stays out of this context; only the report comes back.",
109      todo: null,
110    },
111  },
112  'result:AskUserQuestion': {
113    group: 'chat',
114    took: 'заняли',
115    ru: { label: 'Твои ответы на вопросы', what: 'Варианты и ответы из вопросов, которые задавал Claude.', todo: null },
116    en: { label: 'Your answers to questions', what: 'Options and answers from the questions Claude asked.', todo: null },
117  },
118  'result:ToolSearch': {
119    group: 'service',
120    took: 'заняли',
121    ru: { label: 'Подгруженные схемы', what: 'Описания инструментов, которые Claude подгрузил по ходу работы.', todo: null },
122    en: { label: 'Loaded tool schemas', what: 'Descriptions of tools Claude loaded along the way.', todo: null },
123  },
124  code: {
125    group: 'tools',
126    took: 'занял',
127    ru: {
128      label: 'Код, который написал Claude',
129      what: 'Содержимое файлов, которые Claude создал или поправил через Write и Edit. Текст уходит целиком и остаётся в контексте.',
130      todo: null,
131    },
132    en: {
133      label: 'Code Claude wrote',
134      what: 'The contents of files Claude created or changed with Write and Edit. The text is sent in full and stays in the context.',
135      todo: null,
136    },
137  },
138  args: {
139    group: 'tools',
140    took: 'заняли',
141    ru: { label: 'Аргументы вызовов', what: 'Команды, запросы и параметры, с которыми Claude вызывал инструменты.', todo: null },
142    en: { label: 'Tool call arguments', what: 'Commands, queries and parameters Claude passed to tools.', todo: null },
143  },
144  reminders: {
145    group: 'service',
146    took: 'заняли',
147    ru: {
148      label: 'Служебные вставки',
149      what: 'Сообщения, которые Claude Code сам добавляет в разговор: список скиллов, изменения в файлах, состояние задач, подсказки хуков. Чем длиннее сессия, тем их больше.',
150      todo: null,
151    },
152    en: {
153      label: 'System reminders',
154      what: 'Messages Claude Code adds to the conversation on its own: the skill list, file changes, task state, hook notes. The longer the session, the more of them.',
155      todo: null,
156    },
157  },
158  'skills-loaded': {
159    group: 'rules',
160    took: 'заняли',
161    ru: {
162      label: 'Загруженные скиллы',
163      what: 'Полный текст скиллов, которые вызвал Claude. Скилл остаётся в контексте до конца сессии.',
164      todo: null,
165    },
166    en: {
167      label: 'Loaded skills',
168      what: 'The full text of skills Claude invoked. A skill stays in the context until the session ends.',
169      todo: null,
170    },
171  },
172  images: {
173    group: 'chat',
174    took: 'заняли',
175    ru: {
176      label: 'Скриншоты и картинки',
177      what: 'Картинки, которые ты прислал или вернули инструменты. Вес оценён грубо: 1.5k за штуку.',
178      todo: null,
179    },
180    en: {
181      label: 'Screenshots and images',
182      what: 'Images you sent or tools returned. The weight is a rough guess: 1.5k each.',
183      todo: null,
184    },
185  },
186  user: {
187    group: 'chat',
188    took: 'заняли',
189    ru: { label: 'Твои сообщения', what: 'Всё, что ты написал или вставил в чат.', todo: null },
190    en: { label: 'Your messages', what: 'Everything you typed or pasted into the chat.', todo: null },
191  },
192  assistant: {
193    group: 'chat',
194    took: 'заняли',
195    ru: { label: 'Ответы Claude', what: 'Текст ответов Claude тебе.', todo: null },
196    en: { label: "Claude's replies", what: "The text of Claude's replies to you.", todo: null },
197  },
198  thinking: {
199    group: 'chat',
200    took: 'заняли',
201    ru: { label: 'Рассуждения Claude', what: 'Рассуждения Claude перед ответом, которые возвращаются в контекст.', todo: 'На простых задачах снижай /effort: рассуждений станет меньше.', prompt: '/effort' },
202    en: { label: "Claude's thinking", what: 'Reasoning before a reply that goes back into the context.', todo: 'Lower /effort on simple tasks: Claude will reason less.', prompt: '/effort' },
203  },
204  'cat:System prompt': {
205    group: 'service',
206    took: 'занял',
207    ru: { label: 'Системный промпт', what: 'Базовые инструкции Claude Code. Есть в каждой сессии, уменьшить нельзя.', todo: null },
208    en: { label: 'System prompt', what: "Claude Code's base instructions. Present in every session; it cannot be reduced.", todo: null },
209  },
210  'cat:System tools': {
211    group: 'service',
212    took: 'заняли',
213    ru: {
214      label: 'Схемы встроенных инструментов',
215      what: 'Описания Bash, Read, Edit и других встроенных инструментов. Отправляются с каждым запросом.',
216      todo: null,
217    },
218    en: {
219      label: 'Built-in tool schemas',
220      what: 'Descriptions of Bash, Read, Edit and the other built-in tools. Sent with every request.',
221      todo: null,
222    },
223  },
224  'cat:MCP tools': {
225    group: 'service',
226    took: 'заняли',
227    ru: {
228      label: 'Схемы MCP-инструментов',
229      what: 'Описания подгруженных инструментов MCP-серверов.',
230      todo: 'Отключи ненужные серверы в /mcp. Где есть CLI вроде gh, он не занимает контекст описаниями инструментов.',
231      prompt: '/mcp',
232    },
233    en: { label: 'MCP tool schemas', what: 'Descriptions of loaded MCP server tools.', todo: "Turn off servers you don't use in /mcp. Where a CLI like gh exists, it adds no tool descriptions to the context.",
234      prompt: '/mcp',
235    },
236  },
237  'cat:MCP server instructions': {
238    group: 'service',
239    took: 'заняли',
240    ru: {
241      label: 'Инструкции MCP-серверов',
242      what: 'Правила, которые MCP-серверы добавляют в начало сессии.',
243      todo: 'Отключи ненужные серверы в /mcp. Где есть CLI вроде gh, он не занимает контекст описаниями инструментов.',
244      prompt: '/mcp',
245    },
246    en: {
247      label: 'MCP server instructions',
248      what: 'Rules MCP servers add at the start of a session.',
249      todo: "Turn off servers you don't use in /mcp. Where a CLI like gh exists, it adds no tool descriptions to the context.",
250      prompt: '/mcp',
251    },
252  },
253  'cat:Custom agents': {
254    group: 'rules',
255    took: 'заняли',
256    ru: { label: 'Описания агентов', what: 'Описания твоих агентов из .claude/agents, чтобы Claude знал, кого можно позвать.', todo: null },
257    en: { label: 'Agent descriptions', what: 'Descriptions of your agents from .claude/agents, so Claude knows whom it can call.', todo: null },
258  },
259  'cat:Memory files': {
260    group: 'rules',
261    took: 'заняли',
262    ru: {
263      label: 'CLAUDE.md и память',
264      what: 'Твои файлы инструкций: CLAUDE.md и индекс памяти. Загружаются в каждую сессию.',
265      todo: 'Держи CLAUDE.md до 200 строк, инструкции для отдельных процессов перенеси в скиллы: они загружаются, только когда нужны.',
266      prompt: 'Сократи CLAUDE.md до 200 строк: инструкции для отдельных процессов вынеси в скиллы.',
267    },
268    en: {
269      label: 'CLAUDE.md and memory',
270      what: 'Your instruction files: CLAUDE.md and the memory index. Loaded into every session.',
271      todo: 'Keep CLAUDE.md under 200 lines; move instructions for specific workflows into skills, which load only when needed.',
272      prompt: 'Trim CLAUDE.md to under 200 lines: move instructions for specific workflows into skills.',
273    },
274  },
275  'cat:Skills': {
276    group: 'rules',
277    took: 'занял',
278    ru: {
279      label: 'Список скиллов',
280      what: 'Короткие описания всех установленных скиллов, чтобы Claude знал, какие есть.',
281      todo: 'Удали скиллы, которыми не пользуешься.',
282    },
283    en: {
284      label: 'Skill list',
285      what: 'Short descriptions of every installed skill, so Claude knows what is there.',
286      todo: "Remove skills you don't use.",
287    },
288  },
289}
290
291export const HELP_IDS = Object.keys(HELP)
292
293const flat = (e: Entry, lang: Lang): Help => ({
294  ...e[lang],
295  prompt: e[lang].prompt ?? null,
296  group: e.group,
297  took: lang === 'ru' ? e.took : 'took',
298})
299
300export function helpFor(id: string, lang: Lang): Help {
301  const known = HELP[id]
302  if (known) return flat(known, lang)
303  if (id.startsWith('result:MCP ')) {
304    const server = id.slice('result:MCP '.length)
305    return flat(
306      {
307        group: 'tools',
308        took: 'заняли',
309        ru: {
310          label: `Ответы MCP ${server}`,
311          what: `Данные, которые вернул MCP-сервер ${server}.`,
312          todo: null,
313        },
314        en: { label: `MCP ${server} replies`, what: `Data the ${server} MCP server returned.`, todo: null },
315      },
316      lang,
317    )
318  }
319  if (id.startsWith('result:')) {
320    const tool = id.slice('result:'.length)
321    return flat(
322      {
323        group: 'tools',
324        took: 'заняли',
325        ru: { label: `Результаты ${tool}`, what: `Ответы инструмента ${tool}.`, todo: null },
326        en: { label: `${tool} results`, what: `What the ${tool} tool returned.`, todo: null },
327      },
328      lang,
329    )
330  }
331  const name = id.startsWith('cat:') ? id.slice('cat:'.length) : id
332  return flat(
333    {
334      group: 'service',
335      took: 'заняла',
336      ru: { label: name, what: 'Часть контекста, которую /context считает отдельной категорией.', todo: null },
337      en: { label: name, what: 'A part of the context that /context counts as its own category.', todo: null },
338    },
339    lang,
340  )
341}
342
hooks/i18n.ts 196 lines
1// Interface strings in Russian and English. The language follows Claude Code's `language` setting.
2
3import type { SpeedKind } from './model'
4
5export type Lang = 'ru' | 'en'
6
7const ICON: Record<SpeedKind, string> = { snail: '🐌', cat: '🐈', rabbit: '🐇', rocket: '🚀' }
8// Minutes, rounded for a forecast: to 5 under an hour, to 10 above.
9const roundMinutes = (m: number) => (m < 60 ? Math.max(5, Math.round(m / 5) * 5) : Math.round(m / 10) * 10)
10const duration = (m: number, h: string, min: string) => {
11  const r = roundMinutes(m)
12  const hours = Math.floor(r / 60)
13  const rest = r % 60
14  return [hours ? `${hours} ${h}` : '', rest ? `${rest} ${min}` : ''].filter(Boolean).join(' ')
15}
16// Time a session has run: "2 h 30 min", "40 min", "2 h".
17const elapsed = (m: number, h: string, min: string) => {
18  const hours = Math.floor(m / 60)
19  const rest = m % 60
20  return [hours ? `${hours} ${h}` : '', rest || !hours ? `${rest} ${min}` : ''].filter(Boolean).join(' ')
21}
22// A percent to one decimal, without a trailing .0.
23const percent = (x: number, comma: boolean) => {
24  const s = String(Math.round(x * 10) / 10)
25  return comma ? s.replace('.', ',') : s
26}
27// Russian noun form for a count: 1 сообщение, 2 сообщения, 5 сообщений.
28const plural = (n: number, one: string, few: string, many: string) =>
29  n % 10 === 1 && n % 100 !== 11 ? one : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 12 || n % 100 > 14) ? few : many
30// How many times faster or slower, to one decimal: 1.74 → 1.7, 0.5 → 2.
31const times = (ratio: number) => Math.round((ratio >= 1 ? ratio : 1 / ratio) * 10) / 10
32
33export function langOf(setting: unknown): Lang {
34  return typeof setting === 'string' && /^(ru|russian|русск)/i.test(setting.trim()) ? 'ru' : 'en'
35}
36
37const ru = {
38  cmdPanel: 'Панель: что съедает контекст',
39  panelClosed: 'Панель контекста закрыта.',
40  panelOpened: 'Панель открыта. Esc или /ctx закрывает.',
41  paneTitle: 'Контекст',
42  noData: 'Нет данных до первого ответа.',
43  back: '← Назад',
44  entryGone: 'Этого пункта сейчас нет в контексте.',
45  whatIs: 'Что это',
46  whySoMuch: 'Почему столько',
47  times: (n: number, avg: string) => `${n} ${plural(n, 'раз', 'раза', 'раз')}, в среднем ${avg} за раз`,
48  once: '1 раз',
49  heaviest: 'Самые тяжёлые:',
50  whatToDo: 'Что делать',
51  nothingToDo: 'Ничего: это постоянная часть работы Claude Code.',
52  emptyGroup: 'Здесь пока пусто.',
53  ofUsed: (tokens: string, pct: string) => `${tokens} · ${pct} занятого`,
54  tileContext: 'КОНТЕКСТ',
55  tile5h: 'ЛИМИТ 5 Ч',
56  tileWeek: 'ЛИМИТ НЕДЕЛЯ',
57  ofWindow: (used: string, window: string) => `${used} из ${window}`,
58  turnsLeft: (n: number) => `хватит на ~${n} ходов`,
59  limitLeft: (minutes: number) => (minutes <= 0 ? 'лимит на исходе' : `хватит на ~${duration(minutes, 'ч', 'мин')}`),
60  limitUntilReset: 'хватит до сброса',
61  hintFill: 'Вставить в чат',
62  hintHide: 'Скрыть',
63  hintSent: '✓ Отправлено Claude',
64  adviceHidden: '✓ Совет скрыт',
65  hideAdvice: 'Скрыть совет',
66  neverShow: 'Не показывать снова',
67  hintRan: '✓ Команда запущена',
68  speed: (kind: SpeedKind, ratio: number) => {
69    if (kind === 'cat') return `${ICON.cat} контекст растёт как обычно`
70    const x = times(ratio)
71    const word = Number.isInteger(x) && x >= 5 ? 'раз' : 'раза'
72    return `${ICON[kind]} контекст растёт в ${String(x).replace('.', ',')} ${word} ${kind === 'snail' ? 'медленнее' : 'быстрее'} обычного`
73  },
74  resets: (at: string) => `сброс ${at}`,
75  wasReset: (at: string) => `сбросился в ${at}`,
76  stale: (at: string) => `Данные устарели, последнее обновление в ${at}`,
77  refresh: 'Обновить',
78  whatFills: 'Чем занят контекст',
79  prices: 'Стоимость действий',
80  noActions: 'Пока нет действий.',
81  session: 'За сессию',
82  since: (at: string) => `с ${at}`,
83  sessionRuns: (minutes: number, prompts: number) =>
84    `Идёт ${elapsed(minutes, 'ч', 'мин')}, ${prompts} ${plural(prompts, 'твоё сообщение', 'твоих сообщения', 'твоих сообщений')}`,
85  sessionSpent: (five: number, week: number | null) =>
86    `Съела ${percent(five, true)}% лимита на 5 часов${week === null ? '' : ` и ${percent(week, true)}% недельного`}`,
87  perMessage: (pct: number) => `Одно сообщение в среднем: ${percent(pct, true)}% лимита на 5 часов`,
88  compactsLine: (n: number, dropped: string) => (n === 0 ? 'Компактов не было' : `Компактов: ${n}, сбросили ${dropped}`),
89  agents: (n: number, total: string) => `Субагентов: ${n}, обработали ${total}`,
90  agentsSplit: (fresh: string, cached: string) => `Новых ${fresh}, из кеша ${cached}`,
91  agentPeak: (peak: string, steps: number) => `пик ${peak} · ${steps} ${plural(steps, 'шаг', 'шага', 'шагов')}`,
92  growth: 'График загрузки контекста',
93  turnRange: (from: number, to: number) => `ход ${from} → ход ${to}`,
94  turn: (n: number) => `ход ${n}`,
95  conversation: 'переписка',
96  compactLine: (how: string, before: string, after: string) => `компакт ${how}: ${before} → ${after}`,
97  manual: 'вручную',
98  auto: 'автоматически',
99  plugin: 'плагином',
100  groupTools: 'Работа инструментов',
101  groupService: 'Служебное Claude Code',
102  groupChat: 'Наш разговор',
103  groupRules: 'Скиллы и правила',
104  actWrite: 'Записать файл',
105  actEdit: 'Правка файла',
106  actNotebook: 'Правка ноутбука',
107  actRead: 'Прочитать файл',
108  actBash: 'Команда в Bash',
109  actWebSearch: 'Поиск в вебе',
110  actWebFetch: 'Загрузить страницу',
111  actSearch: 'Поиск по файлам',
112  actAgent: 'Субагент',
113  actImage: 'Скриншот',
114  actSkill: 'Скилл',
115}
116
117const en: typeof ru = {
118  cmdPanel: 'Panel: what fills your context',
119  panelClosed: 'Context panel closed.',
120  panelOpened: 'Panel open. Esc or /ctx closes it.',
121  paneTitle: 'Context',
122  noData: 'No data until the first reply.',
123  back: '← Back',
124  entryGone: 'This item is not in the context right now.',
125  whatIs: 'What it is',
126  whySoMuch: 'Why so much',
127  times: (n, avg) => `${n} times, ${avg} each on average`,
128  once: 'once',
129  heaviest: 'Heaviest:',
130  whatToDo: 'What to do',
131  nothingToDo: 'Nothing: this is a fixed part of how Claude Code works.',
132  emptyGroup: 'Nothing here yet.',
133  ofUsed: (tokens, pct) => `${tokens} · ${pct} of used`,
134  tileContext: 'CONTEXT',
135  tile5h: '5-HOUR LIMIT',
136  tileWeek: 'WEEKLY LIMIT',
137  ofWindow: (used, window) => `${used} of ${window}`,
138  turnsLeft: n => `about ${n} turns left`,
139  limitLeft: minutes => (minutes <= 0 ? 'about to run out' : `about ${duration(minutes, 'h', 'min')} left`),
140  limitUntilReset: 'lasts until reset',
141  hintFill: 'Put in chat',
142  hintHide: 'Hide',
143  hintSent: '✓ Sent to Claude',
144  adviceHidden: '✓ Advice hidden',
145  hideAdvice: 'Hide advice',
146  neverShow: "Don't show again",
147  hintRan: '✓ Command run',
148  speed: (kind, ratio) =>
149    kind === 'cat'
150      ? `${ICON.cat} context grows at your usual pace`
151      : `${ICON[kind]} context grows ${times(ratio)}× ${kind === 'snail' ? 'slower' : 'faster'} than usual`,
152  resets: at => `resets ${at}`,
153  wasReset: at => `reset at ${at}`,
154  stale: at => `Data is stale, last updated at ${at}`,
155  refresh: 'Refresh',
156  whatFills: 'What fills the context',
157  prices: 'Action costs',
158  noActions: 'No actions yet.',
159  session: 'This session',
160  since: at => `since ${at}`,
161  sessionRuns: (minutes, prompts) => `Running ${elapsed(minutes, 'h', 'min')}, ${prompts} ${prompts === 1 ? 'message' : 'messages'} from you`,
162  sessionSpent: (five, week) =>
163    `Used ${percent(five, false)}% of the 5-hour limit${week === null ? '' : ` and ${percent(week, false)}% of the weekly one`}`,
164  perMessage: pct => `One message on average: ${percent(pct, false)}% of the 5-hour limit`,
165  compactsLine: (n, dropped) => (n === 0 ? 'No compactions' : `Compactions: ${n}, dropped ${dropped}`),
166  agents: (n, total) => `Subagents: ${n}, processed ${total}`,
167  agentsSplit: (fresh, cached) => `New ${fresh}, from cache ${cached}`,
168  agentPeak: (peak, steps) => `peak ${peak} · ${steps} ${steps === 1 ? 'step' : 'steps'}`,
169  growth: 'Context load chart',
170  turnRange: (from, to) => `turn ${from} → turn ${to}`,
171  turn: n => `turn ${n}`,
172  conversation: 'conversation',
173  compactLine: (how, before, after) => `${how} compaction: ${before} → ${after}`,
174  manual: 'manual',
175  auto: 'automatic',
176  plugin: 'plugin',
177  groupTools: 'Tool work',
178  groupService: 'Claude Code itself',
179  groupChat: 'Our conversation',
180  groupRules: 'Skills and rules',
181  actWrite: 'Write a file',
182  actEdit: 'Edit a file',
183  actNotebook: 'Edit a notebook',
184  actRead: 'Read a file',
185  actBash: 'Bash command',
186  actWebSearch: 'Web search',
187  actWebFetch: 'Fetch a page',
188  actSearch: 'Search files',
189  actAgent: 'Subagent',
190  actImage: 'Screenshot',
191  actSkill: 'Skill',
192}
193
194export const UI: Record<Lang, typeof ru> = { ru, en }
195export type Strings = typeof ru
196
hooks/history.ts 81 lines
1// The session log: what the model read and wrote, the context after each turn and every
2// compaction. Kept in $.store per session, so it survives a restart or --resume.
3import type { SessionLog } from '../types'
4
5const MAX_POINTS = 300
6
7// `launchedAt`: the conversation's first launch (`usage.startedAt`), kept so a resume under a new
8// session id can find this log again.
9export function emptyLog(startedAt: number, launchedAt?: number): SessionLog {
10  return {
11    startedAt,
12    ...(launchedAt !== undefined ? { launchedAt } : {}),
13    requests: 0, read: 0, cached: 0, written: 0, points: [], compacts: [], prompts: 0, limits: {},
14  }
15}
16
17// The log a conversation launched at `launch` and resumed under a new session id left: the one that
18// kept that launch time, else (a log from before launch times were kept) the one that started within
19// a minute of it. Two candidates, or none: null.
20export function findResumed(logs: readonly (readonly [string, SessionLog])[], launch: number): string | null {
21  const exact = logs.filter(([, l]) => l.launchedAt === launch)
22  if (exact.length > 0) return exact.length === 1 ? exact[0]![0] : null
23  const near = logs.filter(([, l]) => l.launchedAt === undefined && Math.abs(l.startedAt - launch) <= 60_000)
24  return near.length === 1 ? near[0]![0] : null
25}
26
27export function sessionKey(id: string): string {
28  return `session:${id}`
29}
30
31type Usage = {
32  input_tokens: number
33  cache_read_input_tokens: number
34  cache_creation_input_tokens: number
35  output_tokens: number
36}
37
38// One model request: everything it read (fresh, cached and newly cached) and what it wrote.
39export function addRequest(log: SessionLog, u: Usage): SessionLog {
40  return {
41    ...log,
42    requests: log.requests + 1,
43    read: log.read + u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens,
44    cached: log.cached + u.cache_read_input_tokens,
45    written: log.written + u.output_tokens,
46  }
47}
48
49// The context size after a turn, with the heaviest step of that turn as its likely cause.
50export function addPoint(log: SessionLog, tokens: number, cause: string | null, detail: string | null = null): SessionLog {
51  const last = log.points[log.points.length - 1]
52  if (last?.tokens === tokens) return log
53  const point = { tokens, turn: (last?.turn ?? 0) + 1, cause, detail }
54  return { ...log, points: [...log.points, point].slice(-MAX_POINTS) }
55}
56
57// One more prompt from the person. Logs written before this field count from zero.
58export function addPrompt(log: SessionLog): SessionLog {
59  return { ...log, prompts: (log.prompts ?? 0) + 1 }
60}
61
62// A plan limit's percent now. Rises in the same window add up; after a reset the percent
63// starts from zero, so all of it counts.
64export function addLimit(log: SessionLog, kind: string, resetsAt: string, percent: number): SessionLog {
65  const limits = log.limits ?? {}
66  const prev = limits[kind]
67  const spent = !prev ? 0 : prev.resetsAt === resetsAt ? prev.spent + Math.max(0, percent - prev.last) : prev.spent + percent
68  return { ...log, limits: { ...limits, [kind]: { resetsAt, last: percent, spent } } }
69}
70
71export function addCompact(log: SessionLog, trigger: string, before: number, after: number): SessionLog {
72  const turn = log.points[log.points.length - 1]?.turn ?? 0
73  return { ...log, compacts: [...log.compacts, { turn, trigger, before, after }] }
74}
75
76// Session keys to drop so that only the newest `keep` remain (the store holds them in insertion order).
77export function pruneKeys(keys: readonly string[], keep: number): string[] {
78  const sessions = keys.filter(k => k.startsWith('session:'))
79  return sessions.slice(0, Math.max(0, sessions.length - keep))
80}
81
hooks/model.ts 285 lines
1// Formatting and small maths shared by the panel: no engine calls and no words here.
2import type { Category, Item, LimitTrack, Point } from '../types'
3
4const BARS = '▁▂▃▄▅▆▇█'
5const EIGHTHS = ' ▁▂▃▄▅▆▇█'
6// A flat guess per image: the transcript does not carry their pixel size.
7export const IMAGE_TOKENS = 1500
8
9type Block = { type: string; [field: string]: unknown }
10export type Message = { role: 'user' | 'assistant'; content: readonly Block[] }
11
12export function k(tokens: number): string {
13  if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
14  if (tokens >= 9_950) return `${Math.round(tokens / 1000)}k`
15  if (tokens >= 1000) return `${(tokens / 1000).toFixed(1).replace(/\.0$/, '')}k`
16  return String(tokens)
17}
18
19// Cut a text to max characters on a word boundary, ending with an ellipsis.
20export function shorten(text: string, max: number): string {
21  if (text.length <= max) return text
22  const cut = text.slice(0, max - 1)
23  const space = cut.lastIndexOf(' ')
24  return `${(space > max / 2 ? cut.slice(0, space) : cut).trimEnd()}…`
25}
26
27// The whole call, for a jump opened in the panel: description, full command or path, capped.
28export function detail(e: Record<string, unknown>): string {
29  const tool = String(e.tool)
30  const short = tool.startsWith('mcp__') ? tool.split('__').slice(1).join(':') : tool
31  const str = (v: unknown) => (typeof v === 'string' ? v : '')
32  const main = str(e.file_path) || str(e.skill) || str(e.command) || str(e.query) || str(e.url) || str(e.pattern)
33  const desc = str(e.description)
34  const arg = desc && main && desc !== main ? `${desc}: ${main}` : desc || main
35  return shorten(arg ? `${short} ${arg}` : short, 400)
36}
37
38// Text broken into lines of at most `width`: on spaces, and a word longer than a line is split.
39export function wrapLines(text: string, width: number): string[] {
40  const out: string[] = []
41  let line = ''
42  for (const word of text.split(/\s+/).filter(Boolean)) {
43    let w = word
44    while (w.length > width) {
45      if (line) out.push(line)
46      line = ''
47      out.push(w.slice(0, width))
48      w = w.slice(width)
49    }
50    if (!line) line = w
51    else if (line.length + 1 + w.length <= width) line += ` ${w}`
52    else {
53      out.push(line)
54      line = w
55    }
56  }
57  if (line) out.push(line)
58  return out
59}
60
61// Parts joined with " · " and wrapped to `width`; the dot stays with the part before it, so a
62// line never starts with it. Empty parts are left out.
63export function joinLines(parts: readonly string[], width: number): string[] {
64  // A character no text holds keeps each dot glued to the word before it while wrapping.
65  const GLUE = '\u0001'
66  return wrapLines(parts.filter(Boolean).join(`${GLUE}· `), width).map(l => l.split(GLUE).join(' '))
67}
68
69// A name cut to its column with an ellipsis; a short one is left as it is.
70export function clip(text: string, width: number): string {
71  return text.length > width ? `${text.slice(0, Math.max(0, width - 1))}…` : text
72}
73
74// A text in exactly `width` cells: padded, or cut with an ellipsis so it never runs into the next.
75export function fitCell(text: string, width: number): string {
76  return text.length > width ? `${text.slice(0, Math.max(0, width - 1))}…` : text.padEnd(width)
77}
78
79// Action prices: one column when the pane is narrow, two when wide, each at most 36 cells so a
80// number stays next to its name.
81export function priceGrid(width: number): { columns: 1 | 2; width: number } {
82  return width < 60 ? { columns: 1, width: Math.min(width, 40) } : { columns: 2, width: Math.min(36, Math.floor((width - 4) / 2)) }
83}
84
85// Name column for group and entry lists: what is left after tokens, share, the chevron and,
86// on a group page, `bar` cells for the bar.
87export function nameWidth(width: number, bar = 0): number {
88  return Math.min(30, Math.max(12, width - 17 - bar))
89}
90
91// Group name for a tool: built-in tools by name, MCP tools by server.
92export function kind(tool: string): string {
93  return tool.startsWith('mcp__') ? `MCP ${server(tool.split('__')[1] ?? '')}` : tool
94}
95
96// An MCP server's name for a label: a UUID in it shows as its first 8 characters, which tell
97// servers apart; the whole text (detail) keeps it in full.
98const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi
99export function server(name: string): string {
100  return name.replace(UUID, id => id.slice(0, 8))
101}
102
103// Short name for a tool call: tool plus its main argument.
104export function label(e: Record<string, unknown>): string {
105  const tool = String(e.tool)
106  const short = tool.startsWith('mcp__') ? server(tool.split('__').slice(1).join(':')) : tool
107  const arg =
108    (typeof e.file_path === 'string' && e.file_path.split('/').pop()) ||
109    (typeof e.skill === 'string' && e.skill) ||
110    (typeof e.description === 'string' && e.description) ||
111    (typeof e.command === 'string' && e.command.split(/\s+/).slice(0, 2).join(' ')) ||
112    (typeof e.query === 'string' && e.query) ||
113    (typeof e.url === 'string' && e.url) ||
114    (typeof e.pattern === 'string' && e.pattern) ||
115    ''
116  return arg ? `${short} ${shorten(arg, 45)}` : short
117}
118
119// A column chart from zero, one column per value, top row first; each cell in eighths.
120export function chartRows(values: readonly number[], height: number): string[] {
121  const max = Math.max(0, ...values)
122  return Array.from({ length: height }, (_, i) => {
123    const row = height - 1 - i
124    return values
125      .map(v => {
126        const level = max > 0 ? Math.round((v / max) * height * 8) : 0
127        return EIGHTHS[Math.min(8, Math.max(0, level - row * 8))]
128      })
129      .join('')
130  })
131}
132
133// The empty part of a meter: a translucent grey reads on light and dark backgrounds alike.
134const TRACK = 'fill="#808080" fill-opacity="0.25"'
135const num = (x: number) => String(Math.round(x * 100) / 100)
136
137// The desktop's graphics. Its layout is not a cell grid, so the markup is wide and stretched
138// (preserveAspectRatio none) and the element is drawn with no width: it fills its slot, and the
139// caller sets the height in pixels. Square ends: rounded corners would stretch with the strip.
140const WIDE = 1000
141
142// A strip filled to `fraction` (0 to 1) in `color`; with `track`, the rest faint. A share above zero
143// shows at least a sliver. `opacity` below 1 lets a lit background show through the fill.
144export function lineSvg(fraction: number, color: string, opts: { track?: boolean; opacity?: number } = {}): string {
145  const h = 10
146  const f = Math.min(1, Math.max(0, fraction))
147  const filled = f > 0 ? Math.min(WIDE, Math.max(WIDE / 200, f * WIDE)) : 0
148  const alpha = opts.opacity !== undefined && opts.opacity < 1 ? ` fill-opacity="${opts.opacity}"` : ''
149  const bg = opts.track ? `<rect x="0" y="0" width="${WIDE}" height="${h}" ${TRACK}/>` : ''
150  const fg = filled > 0 ? `<rect x="0" y="0" width="${num(filled)}" height="${h}" fill="${color}"${alpha}/>` : ''
151  return `<svg xmlns="http://www.w3.org/2000/svg" width="${WIDE}" height="${h}" viewBox="0 0 ${WIDE} ${h}" preserveAspectRatio="none">${bg}${fg}</svg>`
152}
153
154// A title set in capitals for the terminal, as a sentence: "5-HOUR LIMIT" → "5-hour limit".
155export function sentenceCase(text: string): string {
156  return text === text.toUpperCase() ? text.charAt(0) + text.slice(1).toLowerCase() : text
157}
158
159const two = (n: number) => String(n).padStart(2, '0')
160
161// Local time: HH:MM today, otherwise DD.MM HH:MM.
162export function resetLabel(iso: string, now: number): string {
163  const at = new Date(iso)
164  const today = new Date(now)
165  const time = `${two(at.getHours())}:${two(at.getMinutes())}`
166  const isToday =
167    at.getFullYear() === today.getFullYear() && at.getMonth() === today.getMonth() && at.getDate() === today.getDate()
168  return isToday ? time : `${two(at.getDate())}.${two(at.getMonth() + 1)} ${time}`
169}
170
171// Average rise per turn: over the last five turns and over all of them.
172export function pace(points: readonly Point[]): { recent: number; overall: number } {
173  const rises: number[] = []
174  for (let i = 1; i < points.length; i++) rises.push(Math.max(0, points[i]!.tokens - points[i - 1]!.tokens))
175  const mean = (xs: number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0)
176  return { recent: mean(rises.slice(-5)), overall: mean(rises) }
177}
178
179// How much the context grew each turn; drops (compactions) are left out.
180function rises(points: readonly { tokens: number }[]): number[] {
181  const out: number[] = []
182  for (let i = 1; i < points.length; i++) {
183    const d = points[i]!.tokens - points[i - 1]!.tokens
184    if (d > 0) out.push(d)
185  }
186  return out
187}
188
189function median(xs: readonly number[]): number {
190  const s = [...xs].sort((a, b) => a - b)
191  const mid = Math.floor(s.length / 2)
192  return s.length % 2 ? s[mid]! : (s[mid - 1]! + s[mid]!) / 2
193}
194
195// The usual rise per turn: the median, over past sessions, of each one's median rise.
196// Medians, so one session full of screenshots doesn't set the norm.
197export function usualRise(logs: readonly { points: readonly { tokens: number }[] }[]): number | null {
198  const perSession = logs.map(l => rises(l.points)).filter(r => r.length >= 5).map(median)
199  return perSession.length >= 3 ? median(perSession) : null
200}
201
202export type SpeedKind = 'snail' | 'cat' | 'rabbit' | 'rocket'
203
204// The last few turns against the usual pace.
205export function speed(points: readonly Point[], usual: number | null): { kind: SpeedKind; ratio: number } | null {
206  const recent = rises(points).slice(-5)
207  if (!usual || recent.length < 3) return null
208  const ratio = Math.round((median(recent) / usual) * 100) / 100
209  const kind: SpeedKind = ratio < 0.67 ? 'snail' : ratio < 1.5 ? 'cat' : ratio < 2 ? 'rabbit' : 'rocket'
210  return { kind, ratio }
211}
212
213const LIMIT_SAMPLES = 300
214const MINUTE = 60_000
215
216// Samples of one limit window; a new reset time starts a new track.
217export function trackLimit(track: LimitTrack | null, resetsAt: string, at: number, percent: number): LimitTrack {
218  const samples = track?.resetsAt === resetsAt ? track.samples : []
219  return { resetsAt, samples: [...samples, { at, percent }].slice(-LIMIT_SAMPLES) }
220}
221
222// When the limit runs out at the pace of the last hour; 'untilReset' when it lasts until the reset.
223// Null until there are at least ten minutes of samples in that hour.
224export function limitForecast(track: LimitTrack, now: number, resetsAt: number): { minutes: number } | 'untilReset' | null {
225  const recent = track.samples.filter(s => s.at >= now - 60 * MINUTE)
226  const first = recent[0]
227  const last = recent[recent.length - 1]
228  if (!first || !last || now - first.at < 10 * MINUTE) return null
229  const perMinute = (last.percent - first.percent) / ((now - first.at) / MINUTE)
230  if (perMinute <= 0) return 'untilReset'
231  const minutes = Math.round((100 - last.percent) / perMinute)
232  return now + minutes * MINUTE >= resetsAt ? 'untilReset' : { minutes }
233}
234
235// What each turn added to the context, oldest first; a compaction's drop counts as nothing.
236export function turnRises(points: readonly { tokens: number }[]): number[] {
237  return points.slice(1).map((p, i) => Math.max(0, p.tokens - points[i]!.tokens))
238}
239
240// The biggest rises from one turn to the next, with what likely caused them.
241type Jump = { delta: number; turn: number; cause: string | null; detail: string | null }
242
243export function jumps(points: readonly Point[], n: number): Jump[] {
244  const out: Jump[] = []
245  for (let i = 1; i < points.length; i++) {
246    const delta = points[i]!.tokens - points[i - 1]!.tokens
247    if (delta > 0) out.push({ delta, turn: points[i]!.turn, cause: points[i]!.cause, detail: points[i]!.detail ?? null })
248  }
249  return out.sort((a, b) => b.delta - a.delta).slice(0, n)
250}
251
252// The /context rows that sit in the window: used content by size, then free space.
253export function windowRows(
254  rows: readonly { name: string; tokens: number; kind: string; color: string }[],
255): Category[] {
256  const used = rows.filter(r => r.kind === 'used').sort((a, b) => b.tokens - a.tokens)
257  const free = rows.filter(r => r.kind === 'free')
258  return [...used, ...free].map(({ name, tokens, color, kind }) => ({ name, tokens, color, isFree: kind === 'free' }))
259}
260
261type BreakdownLists = {
262  categories: readonly { name: string; tokens: number }[]
263  skills?: { skillFrontmatter: readonly { name: string; tokens: number }[] }
264  memoryFiles: readonly { path: string; tokens: number }[]
265  mcpTools: readonly { name: string; serverName: string; tokens: number; isLoaded: boolean }[]
266  agents: readonly { agentType: string; tokens: number }[]
267}
268
269// Per-item lists for the /context categories that have them, keyed by the category's name.
270export function detailsFor(b: BreakdownLists): Record<string, Item[]> {
271  const lists: [RegExp, () => Item[]][] = [
272    [/skill/i, () => (b.skills?.skillFrontmatter ?? []).map(s => ({ name: s.name, tokens: s.tokens }))],
273    [/memory/i, () => b.memoryFiles.map(f => ({ name: f.path.split('/').slice(-2).join('/'), tokens: f.tokens }))],
274    [/mcp tools/i, () => b.mcpTools.filter(t => t.isLoaded).map(t => ({ name: `${server(t.serverName)}: ${t.name}`, tokens: t.tokens }))],
275    [/agent/i, () => b.agents.map(a => ({ name: a.agentType, tokens: a.tokens }))],
276  ]
277  const out: Record<string, Item[]> = {}
278  for (const { name } of b.categories) {
279    const match = lists.find(([re]) => re.test(name))
280    const items = match ? match[1]() : []
281    if (items.length > 0) out[name] = [...items].sort((x, y) => y.tokens - x.tokens)
282  }
283  return out
284}
285
hooks/subagents.ts 62 lines
1// What the session's subagents processed, read from their transcripts (<session>/subagents/agent-<id>.jsonl).
2import type { AgentRun, Subagents } from '../types'
3
4type Usage = {
5  input_tokens: number
6  cache_read_input_tokens: number
7  cache_creation_input_tokens: number
8  output_tokens: number
9}
10
11// One transcript line into the steps so far, by message id. A reply is written as several lines, one
12// per block, each with the same id; the last carries the final output count, so it wins. Anything
13// else, a line cut short by a running agent included, counts for nothing.
14export function addLine(steps: Map<string, Usage>, line: string): void {
15  if (!line.includes('"assistant"')) return
16  let o: { type?: string; message?: { id?: string; usage?: Partial<Usage> } }
17  try {
18    o = JSON.parse(line)
19  } catch {
20    return
21  }
22  const u = o.message?.usage
23  if (o.type !== 'assistant' || !o.message?.id || !u) return
24  steps.set(o.message.id, {
25    input_tokens: u.input_tokens ?? 0,
26    cache_read_input_tokens: u.cache_read_input_tokens ?? 0,
27    cache_creation_input_tokens: u.cache_creation_input_tokens ?? 0,
28    output_tokens: u.output_tokens ?? 0,
29  })
30}
31
32// A step's context is everything it read: input, cache read and cache write.
33export function runOf(description: string, steps: ReadonlyMap<string, Usage>): AgentRun {
34  const run = { description, steps: steps.size, peak: 0, fresh: 0, cached: 0 }
35  for (const u of steps.values()) {
36    run.peak = Math.max(run.peak, u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens)
37    run.fresh += u.input_tokens + u.cache_creation_input_tokens + u.output_tokens
38    run.cached += u.cache_read_input_tokens
39  }
40  return run
41}
42
43// Dearest by everything processed, new and cached.
44export function summarize(runs: readonly AgentRun[]): Subagents | null {
45  if (runs.length === 0) return null
46  const top = [...runs].sort((a, b) => b.fresh + b.cached - (a.fresh + a.cached)).slice(0, 3)
47  return {
48    count: runs.length,
49    fresh: runs.reduce((n, r) => n + r.fresh, 0),
50    cached: runs.reduce((n, r) => n + r.cached, 0),
51    top,
52  }
53}
54
55// From agent-<id>.meta.json: the Agent call's task, else the agent type, else the file name. The model
56// writes the task, so control characters (an escape sequence for the terminal) become spaces.
57export function descriptionOf(meta: unknown, fallback: string): string {
58  const m = (meta ?? {}) as { description?: unknown; agentType?: unknown }
59  const clean = (v: unknown) => (typeof v === 'string' ? v.replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ').trim() : '')
60  return clean(m.description) || clean(m.agentType) || fallback
61}
62
types/index.d.ts 93 lines
1export type Step = { label: string; tokens: number; detail?: string }
2export type Category = { name: string; tokens: number; color: string; isFree: boolean }
3export type Item = { name: string; tokens: number }
4// `detail`: the cause's whole text (full command, full path), for a jump opened in the panel.
5export type Point = { tokens: number; turn: number; cause: string | null; detail?: string | null }
6export type Compact = { turn: number; trigger: string; before: number; after: number }
7// Samples of one rate-limit window, keyed by its reset time.
8export type LimitTrack = { resetsAt: string; samples: { at: number; percent: number }[] }
9
10// One session's running totals, kept in $.store under `session:<id>`.
11export type SessionLog = {
12  startedAt: number
13  // The conversation's first launch (`usage.startedAt`), when the log was started knowing it.
14  launchedAt?: number
15  requests: number
16  // Everything the model read across requests: fresh, cached and newly cached input.
17  read: number
18  cached: number
19  written: number
20  points: Point[]
21  compacts: Compact[]
22  // Prompts the person sent (slash commands left out).
23  prompts: number
24  // What this session spent of each plan limit, by kind (five_hour, seven_day).
25  limits: Record<string, LimitSpend>
26}
27
28// One plan limit as the session saw it: the last percent and how much it has added up.
29export type LimitSpend = { resetsAt: string; last: number; spent: number }
30
31// One subagent, read from its transcript: its task, its model requests (steps), the biggest
32// context one step read, what was new (input, cache write, output) and what came from cache.
33export type AgentRun = { description: string; steps: number; peak: number; fresh: number; cached: number }
34
35// The session's subagents: how many ran, what they processed, the three dearest.
36export type Subagents = { count: number; fresh: number; cached: number; top: AgentRun[] }
37
38export type GroupId = 'tools' | 'service' | 'chat' | 'rules'
39
40// Everything the pane reads, refreshed after each turn.
41export type Snapshot = {
42  lang: 'ru' | 'en'
43  // When it was read, for the "updated at" line.
44  at: number
45  entries: {
46    id: string
47    label: string
48    group: GroupId
49    tokens: number
50    count: number
51    top: { label: string; tokens: number }[]
52  }[]
53  prices: { name: string; count: number; average: number }[]
54  limits: { kind: string; percentUsed: number; resetsAt?: string }[]
55  // Where auto-compaction starts, or the whole window when it is off.
56  threshold: number
57  window: number
58  used: number
59  // Null until the session's transcript is known, or when no subagent has run.
60  subagents: Subagents | null
61}
62
63export type Page = { kind: 'home' } | { kind: 'group'; id: string } | { kind: 'entry'; id: string }
64
65declare module 'claude-code' {
66  interface PluginState {
67    'chudarin-context-mod': {
68      log: SessionLog | null
69      heaviest: Step | null
70      snapshot: Snapshot | null
71      expanded: string[]
72      page: Page
73      lang: 'ru' | 'en'
74      // The usual context rise per turn over past sessions; null until there are enough.
75      usual: number | null
76      // Advice the person hid this session, by entry id.
77      hidden: string[]
78      // Advice sent to Claude or run as a command this session, by entry id.
79      sent: string[]
80      // Advice the person hid for good, by entry id; kept in $.store under `muted`.
81      muted: string[]
82      // Samples of the 5-hour limit in its current window, for the forecast; kept in $.store.
83      limitTrack: LimitTrack | null
84      // Written once a minute; the pane reads it, so the write redraws an open pane.
85      minute: number
86      // The session id that log, sent and hidden belong to; /clear and a resume change it.
87      logId: string | null
88      // The session's transcript path, from the last prompt; its subagents' transcripts lie beside it.
89      transcript: string | null
90    }
91  }
92}
93