A status row under the prompt (mode, model, effort, 5h / 7d / context usage, cache warmth), with the turn's time and live tokens while working

Mods for Claude Code. Each mod has one job and works on its own: none imports, reads or calls another. They are sorted by where they run:
| Folder | What goes there |
|---|---|
mods/cli | Mods for the Claude Code CLI (the terminal) only |
mods/desktop | Mods for the Claude Code desktop app only (none yet) |
mods/both | Mods that work in both, with a behaviour for each |
| Mod | Runs in | Its job |
|---|---|---|
mods/both/statusdeck | CLI and desktop | Live stats: a status row under the prompt in the CLI, a status band above the prompt in the desktop app |
mods/cli/prettier | CLI | The layout and colours of the whole chat: prompts, replies, code, tool rows, the spinner |
mods/cli/hark | CLI | Voice input: speak your prompt, transcribed on your own computer |
The two kinds load differently:
~/.claude/mods and named in the CLAUDE_CODE_PLUGIN_DIRS environment variable, set in your shell's profile. Only a claude started from that shell sees it, so the desktop app never loads them.CLAUDE_CODE_PLUGIN_DIRS can't reach it. mods/both is a plugin marketplace; install from it once and the mod loads in the CLI and the desktop app alike.Restart Claude Code (and the desktop app) after installing.
git clone https://github.com/MoizAsif616/claude-code-utilities.git
# CLI mods: copied to ~/.claude/mods and named in your PowerShell profile (terminal only)
New-Item -ItemType Directory -Force "$env:USERPROFILE\.claude\mods" | Out-Null
Copy-Item -Recurse -Force .\claude-code-utilities\mods\cli\* "$env:USERPROFILE\.claude\mods\"
Add-Content $PROFILE '$env:CLAUDE_CODE_PLUGIN_DIRS = "$env:USERPROFILE\.claude\mods\prettier;$env:USERPROFILE\.claude\mods\hark"'
# Mods for both: installed as plugins from the mods/both marketplace
claude plugin marketplace add .\claude-code-utilities\mods\both
claude plugin install statusdeck@claude-code-utilities --scope user
Open a new PowerShell window before starting claude, and check the variable:
echo $env:CLAUDE_CODE_PLUGIN_DIRS # must start with ...\mods\prettier
Don't set CLAUDE_CODE_PLUGIN_DIRS as a Windows user environment variable: every program sees those, the desktop app included, so the CLI mods would load there too.
git clone https://github.com/MoizAsif616/claude-code-utilities.git
mkdir -p ~/.claude/mods
cp -r claude-code-utilities/mods/cli/* ~/.claude/mods/
echo 'export CLAUDE_CODE_PLUGIN_DIRS="$HOME/.claude/mods/prettier:$HOME/.claude/mods/hark"' >> ~/.bashrc
claude plugin marketplace add ./claude-code-utilities/mods/both
claude plugin install statusdeck@claude-code-utilities --scope user
Open a new shell (or source ~/.bashrc) before starting claude.
git clone https://github.com/MoizAsif616/claude-code-utilities.git
mkdir -p ~/.claude/mods
cp -R claude-code-utilities/mods/cli/* ~/.claude/mods/
echo 'export CLAUDE_CODE_PLUGIN_DIRS="$HOME/.claude/mods/prettier:$HOME/.claude/mods/hark"' >> ~/.zshrc
claude plugin marketplace add ./claude-code-utilities/mods/both
claude plugin install statusdeck@claude-code-utilities --scope user
Open a new shell (or source ~/.zshrc) before starting claude.
A plugin installed from a folder is read from that folder: keep the clone where it is, and an edit there reaches Claude Code after /reload-plugins.
The three mods never draw the same thing, so their order doesn't matter (;-separated on Windows, : on Linux and macOS in CLAUDE_CODE_PLUGIN_DIRS). The install commands list prettier first.
The one row hark shares is the one above the prompt: statusdeck draws its panes chips there in the CLI (only with the panes mod), and whichever of the two loads first shows when both have something to draw. hark also doesn't affect prettier's times: it keeps each prompt as it was finally sent, so the time under a prompt you sent while recording is right.
One mod with two looks: a status row under the prompt in the CLI, and a status band above the prompt in the desktop app. Each draws only where it belongs.
The row under the prompt, with every colour in it:
⚡ and a countdown while the prompt cache is warm, ❄ once it has gone cold.A band right above the prompt, in the app's theme colours, so it reads in light and dark mode. The bar under the prompt is left to the app: it draws a mod's content there only as plain text.
❄ when cold.☰ at the right end, or /statusdeck-context): check or uncheck skills and MCP tools. After Apply, whatever is unchecked is hidden from Claude and refused if Claude calls it anyway. The desktop app's own ccd_* tools can't be turned off. Pending changes apply on their own at the next /clear or /compact.The desktop band is adapted from the deskdeck mod; the 5-hour and 7-day pills are left out of it.
The cache lifetime (1h on a Claude subscription, 5m with an API key) is a plugin option: /plugin configure statusdeck@claude-code-utilities in a terminal session.
statusdeck doesn't draw the spinner; prettier does.
The layout and colours of the chat. What it changes:
▸ 14 more lines. Beside the time, 14:32 ⧉ (same grey): a click on ⧉ copies that prompt's text and nothing else, and it reads a green ✓ for 3.5 seconds.python, or code when unlabeled) and ⧉ Copy at the right, which copies only the code and reads Copied! for 3.5 seconds. A panel is as wide as its longest line, never wider than the reply.+12 −3 (green and red) after an edit's row. While a reply is being written each diff shows whole at 75% of the terminal; once it is done, each edited or created file is one row, ▸ Edit hooks/app.ts +12 −3, that opens to its diff on a click.▸ Ran 2 commands · 1.2s. A click opens it: each call on a filled block with the whole command and its output (up to 40 lines). A click on any block, or on the row, closes it.✗ Bash failed, as wide as the error and no wider than the reply. Once the reply is done the call is one row, ▸ Edit app.ts · ✗ failed (✗ failed in red), that opens to its frame on a click. Declining a permission prompt is not a failure.⚙ Background task · completed · 2m 2s), not as your pill.39s · ▸ 2 tools, how long it took (dim) and how many tools it used (purple). A click on the count lists each call: ✓ Bash npm test · 1.2s.⠋ and Claude Code's word, or the tool running now: ⠋ ▸ running Bash….Everything compact toggles on a click: ▸ is closed, ▾ is open. Clicks only reach mods in Claude Code's fullscreen (alternate-screen) layout. On the normal screen these rows stay compact, edit diffs and errors stay whole (there would be no way to reopen them), the Copy buttons are hidden, and a folded prompt or message says ctrl+o. ctrl+o is Claude Code's own transcript view: it shows tool calls, outputs and long prompts in full; press it again to go back.
| Command | Settings (defaults) |
|---|---|
/prettier | lists the commands; on, off (layout and colours together), reset (every setting back to its default) |
/prettier-prompt | width 70 (% of the terminal), lines 6 (shown before folding), time on |
/prettier-response | width 85 (% of the terminal; also the most a code panel or red frame takes), fold on (fold runs of reads, searches and commands) |
/prettier-code | width 75 (% of the terminal, for diffs) |
Each command on its own lists its settings and what they do. Change one or several at once: /prettier-prompt width 60 lines 4. Settings are kept across sessions. A wrong name or value says what's allowed.
● <mod>: ... lines Claude Code prints when a mod loads, reloads or fails are Claude Code's own; no mod can restyle them.More detail is in mods/cli/prettier/README.md.
Voice input for the prompt. You speak, and the words appear in the input box as you talk. Speech is turned into text by a model running on your own computer: no account, no API key, and your voice never leaves the machine. The only network use is downloading a model once.
● Record button on the right. While recording: a ■ Stop button, a timer and level bars that move with your voice and stay flat in silence.● Record and talk; the text fills the input live, after anything you had already typed. Click ■ Stop to keep the text and edit it, or press Enter to stop and send in one go. With nothing said, the input is left as it was./hark-models opens a list of speech models with their languages, download size, RAM, speed and accuracy. Pick one, confirm, and it downloads (in the background if you like, with a red ✕ to cancel). Voice input switches to it as soon as it has loaded.
✓ marks the model in use.■ Stop to the text appearing, for example 0.4 s.| Model | Languages | Download | Notes |
|---|---|---|---|
| Moonshine Tiny / Base | English | 30 / 111 MB | Smallest and quickest; Base is a good first choice |
| Kroko Live | English | 57 MB | Words appear as you say them; no punctuation |
| Parakeet 110M | English | 108 MB | Very accurate for its size |
| Parakeet 0.6B v2 / v3 | English / 25 European | about 485 MB | Best accuracy that is still fast on a CPU |
| SenseVoice Small | Chinese, Cantonese, English, Japanese, Korean | 163 MB | For East Asian languages |
| Whisper Small, Large v3, Large v3 Turbo | 99 | 0.5 to 3 GB | Most languages; the large ones are slow on a CPU |
| Distil-Whisper Large | English | 1.5 GB | Near large-model accuracy, faster |
| Command | What it does |
|---|---|
/hark | Turns voice input on or off; /hark on and /hark off also work. With no model yet, it opens the list |
/hark-models | Choose, download, switch or delete a speech model |
PATH (python3, python or py). hark makes its own Python environment in ~/.claude/hark and installs what it needs there, nothing system-wide. It uses uv when installed; otherwise Python's own venv, which on Ubuntu/Debian needs sudo apt install python3-venv.sudo apt install libportaudio2 (Fedora: sudo dnf install portaudio, Arch: sudo pacman -S portaudio). Windows and macOS have it built in.Everything hark downloads lives in ~/.claude/hark. Delete that folder to remove it all.
Pull the latest changes, then copy the CLI mods again and update statusdeck:
cd claude-code-utilities && git pull
cp -R mods/cli/* ~/.claude/mods/
claude plugin update statusdeck@claude-code-utilities
On Windows, run git pull and repeat the Copy-Item line from the install section. The profile line only needs adding once. In a running session, /reload-plugins picks up the new statusdeck.
types/ and tests/ folders inside each mod are for development and aren't needed to run the mods.hooks/register.tsx 764 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionRateLimit, Timer } from 'claude-code'
3
4import type { Cache, Clock, Controls, Run, Usage, Window } from '../types'
5import {
6 deskAfterCompact,
7 deskBand,
8 deskEnd,
9 deskMeasure,
10 deskSessionStart,
11 deskStepCounted,
12 deskStepEnd,
13 deskStepPending,
14 deskTurnComplete,
15 deskTurnStart,
16 registerDesk,
17} from './desk'
18
19const usageAtom = atom({ plugin: 'statusdeck', key: 'usage' } as const, {
20 fiveHour: null,
21 week: null,
22 context: null,
23} as Usage)
24const runAtom = atom({ plugin: 'statusdeck', key: 'run' } as const, {
25 isWorking: false,
26 startedAt: 0,
27 now: 0,
28 tokens: 0,
29} as Run)
30const controlsAtom = atom({ plugin: 'statusdeck', key: 'controls' } as const, {
31 effort: null,
32 model: null,
33} as Controls)
34const cacheAtom = atom({ plugin: 'statusdeck', key: 'cache' } as const, {
35 touchedAt: null,
36} as Cache)
37const clockAtom = atom({ plugin: 'statusdeck', key: 'clock' } as const, { now: 0 } as Clock)
38const panesSummary = { plugin: 'panes', key: 'summary' } as const
39
40// Palette shared with prettier and panes.
41const PILL_BG = '#202C34'
42const PILL_LABEL = '#D4DCE2'
43const PILL_TIMER = '#A7B3BD'
44const CACHE_TIME = '#A7B3BD'
45// The colour of a percentage used, blended channel by channel between stops.
46const USED_STOPS = [
47 { at: 0, color: '#8BD5F5' },
48 { at: 50, color: '#9FDFB5' },
49 { at: 70, color: '#FFD080' },
50 { at: 85, color: '#FF9E64' },
51 { at: 100, color: '#FF6B6B' },
52]
53// Blank cells between the parts of the status row.
54const MODE_GAP = 2
55const PILL_GAP = 1
56// The footer's left pad, the two blanks the engine keeps between the hint and
57// the slot, and one more for the slot's lead: a pill row this much narrower
58// than the terminal still fits on one line.
59const FOOTER_SLACK = 5
60
61// The hint's mode, model and effort in cells, as last drawn, so the status
62// pills know how much of the row is left to them.
63let hintCells = 0
64// While a mode is on the engine draws its own label and " · " before the hint
65// ("⏵⏵ auto mode on · "), and names no mode a hook can read: room for the
66// longest of the shift+tab cycle's, "⏵⏵ accept edits on · ".
67const ENGINE_MODE_CELLS = 21
68// Whether the engine draws that label: the idle hint says ("(shift+tab to
69// cycle)" with a mode on, "? for shortcuts" without), and a working turn's
70// hint ("esc to interrupt") keeps what it said last.
71let isEngineModeOn = false
72const ORANGE = '#F97316'
73const PURPLE = '#A855F7'
74const PURPLE_LIGHT = '#C4B5FD'
75const GREEN = '#22C55E'
76const ICE = '#7DD3FC'
77const WARM_ICON = '⚡'
78const COLD_ICON = '❄'
79const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
80const TICK_MS = 160
81const POLL_MS = 1000
82const COUNT_MS = 3000
83const IDLE_CLOCK_MS = 30000
84
85// A coloured glyph and a short word, no background block: the mode at a glance
86// in a few cells.
87const MODES = [
88 { re: /plan mode/i, label: 'Plan', glyph: '◐', color: '#A78BFA' },
89 { re: /accept edits/i, label: 'Accept edits', glyph: '◉', color: '#4ADE80' },
90 { re: /bypass permissions/i, label: 'Bypass', glyph: '◆', color: '#F87171' },
91 { re: /auto mode/i, label: 'Auto', glyph: '◎', color: '#FBBF24' },
92 { re: /don'?t ask/i, label: "Don't ask", glyph: '◇', color: '#9CA3AF' },
93 { re: /manual mode/i, label: 'Manual', glyph: '○', color: '#94A3B8' },
94]
95// A mode this list does not know yet ("review mode on") still reads as one
96// word, in a neutral colour.
97function modeOf(text: string): (typeof MODES)[number] | undefined {
98 const known = MODES.find(m => m.re.test(text))
99 if (known !== undefined) return known
100 const name = /([a-z][a-z']*(?: [a-z][a-z']*)?) mode on/i.exec(text)?.[1]
101 if (name === undefined) return undefined
102 const label = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase()
103 return { re: new RegExp(name, 'i'), label, glyph: '●', color: '#94A3B8' }
104}
105
106function hex(color: string): number[] {
107 const n = parseInt(color.slice(1), 16)
108 return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
109}
110
111function mix(a: string, b: string, t: number): string {
112 const [ar = 0, ag = 0, ab = 0] = hex(a)
113 const [br = 0, bg = 0, bb = 0] = hex(b)
114 const part = (x: number, y: number) =>
115 Math.round(x + (y - x) * t)
116 .toString(16)
117 .padStart(2, '0')
118 return `#${part(ar, br)}${part(ag, bg)}${part(ab, bb)}`
119}
120
121function usedColor(percent: number): string {
122 const p = Math.min(100, Math.max(0, percent))
123 const i = USED_STOPS.findIndex(stop => stop.at >= p)
124 const hi = USED_STOPS[Math.max(1, i)]!
125 const lo = USED_STOPS[Math.max(1, i) - 1]!
126 return mix(lo.color, hi.color, (p - lo.at) / (hi.at - lo.at))
127}
128
129function countdown(resetsAt: string | null, now: number): string {
130 if (resetsAt === null) return ''
131 const ms = Date.parse(resetsAt) - now
132 if (!(ms > 0)) return ''
133 const minutes = Math.floor(ms / 60000)
134 const days = Math.floor(minutes / 1440)
135 const hours = Math.floor((minutes % 1440) / 60)
136 if (days > 0) return `${days}d${hours}h`
137 if (hours > 0) return `${hours}h${String(minutes % 60).padStart(2, '0')}m`
138 return `${minutes}m`
139}
140
141// Minutes while there is room to spare, m:ss for the last five.
142function warmth(ms: number): string {
143 if (ms >= 300000) return `${Math.ceil(ms / 60000)}m`
144 const s = Math.max(0, Math.ceil(ms / 1000))
145 return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
146}
147
148function elapsed(ms: number): string {
149 const s = Math.max(0, Math.floor(ms / 1000))
150 return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
151}
152
153function compact(n: number): string {
154 return n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n)
155}
156
157function prettyModel(id: string | null): string {
158 if (id === null) return '…'
159 const m = /(opus|sonnet|haiku|fable)-(\d+)(?:-(\d{1,2}))?(?!\d)/i.exec(id)
160 if (m === null) return id
161 const name = (m[1] ?? '').charAt(0).toUpperCase() + (m[1] ?? '').slice(1).toLowerCase()
162 return m[3] === undefined ? `${name} ${m[2]}` : `${name} ${m[2]}.${m[3]}`
163}
164
165function toWindow(limit: SessionRateLimit | undefined): Window | null {
166 return limit === undefined ? null : { percent: limit.percentUsed, resetsAt: limit.resetsAt ?? null }
167}
168
169// A window whose reset has passed holds nothing worth showing.
170function fresh(w: Window | null, now: number): Window | null {
171 if (w === null || w.resetsAt === null) return w
172 return Date.parse(w.resetsAt) > now ? w : null
173}
174
175// Before the first response of a session the engine has no reading yet
176// (rateLimits empty, no context fill), so a reading only replaces what it has.
177// While the window is counted as /context counts it, that count owns ctx: the
178// engine's figure is the last response's, stale after a /compact or /clear.
179function usageFrom(
180 prev: Usage,
181 context: { percent?: number } | undefined,
182 rateLimits: readonly SessionRateLimit[] | undefined,
183): Usage {
184 const limits = rateLimits ?? []
185 return {
186 fiveHour: toWindow(limits.find(l => l.kind === 'five_hour')) ?? prev.fiveHour,
187 week: toWindow(limits.find(l => l.kind === 'seven_day')) ?? prev.week,
188 context: isCounted ? prev.context : (context?.percent ?? prev.context),
189 }
190}
191
192// The rate-limit windows are the account's, so the last reading carries over
193// to the next session until a response brings a new one.
194async function saveUsage($: EngineInterface, usage: Usage): Promise<void> {
195 if (usage.fiveHour === null && usage.week === null) return
196 await $.store.set('limits', { fiveHour: usage.fiveHour, week: usage.week })
197}
198
199async function storedUsage($: EngineInterface, now: number): Promise<Usage> {
200 const held = (await $.store.get('limits')) as Partial<Usage> | undefined
201 return {
202 fiveHour: fresh(held?.fiveHour ?? null, now),
203 week: fresh(held?.week ?? null, now),
204 context: null,
205 }
206}
207
208async function refreshUsage($: EngineInterface): Promise<void> {
209 const { context, rateLimits } = await $.session.usage()
210 const prev = await read($, usageAtom)
211 const next = usageFrom(prev, context, rateLimits)
212 if (JSON.stringify(next) === JSON.stringify(prev)) return
213 await update($, usageAtom, () => next)
214 await saveUsage($, next)
215}
216
217// The window counted locally, as /context counts it (no request sent), so ctx
218// shows the figure /context shows: right after a /compact or /clear too, when
219// the engine has no fill until the next response. A count that fails leaves
220// ctx to the engine's figure.
221async function recountContext($: EngineInterface): Promise<void> {
222 lastCountAt = await $.clock.now()
223 const { context } = await $.session.usage({ breakdown: 'summary' })
224 const b = context.breakdown
225 const max = b?.rawMaxTokens ?? context.window
226 const percent =
227 b === undefined
228 ? null
229 : typeof b.percentage === 'number'
230 ? b.percentage
231 : max > 0
232 ? Math.round((b.totalTokens / max) * 100)
233 : null
234 isCounted = percent !== null
235 if (percent === null) return
236 if ((await read($, usageAtom)).context === percent) return
237 await update($, usageAtom, u => ({ ...u, context: percent }))
238}
239
240// "claude-opus-5-5[1m]", "claude-opus-5-5-20261001" and "opus" all name one model.
241function baseModel(id: string): string {
242 return id
243 .toLowerCase()
244 .replace(/\[.*?\]/g, '')
245 .replace(/-\d{8}$/, '')
246 .trim()
247}
248
249// This build keeps the effort per model, in settings.modelSettings[<model id>].
250function effortFor(settings: Record<string, unknown>, model: string): string | null {
251 const perModel = settings['modelSettings']
252 const want = baseModel(model)
253 if (want !== '' && perModel !== null && typeof perModel === 'object') {
254 const entries = Object.entries(perModel as Record<string, unknown>)
255 const exact = entries.filter(([name]) => baseModel(name) === want)
256 const loose = entries.filter(([name]) => {
257 const have = baseModel(name)
258 return have !== want && (have.includes(want) || want.includes(have))
259 })
260 for (const [, value] of [...exact, ...loose]) {
261 const level = (value as { effortLevel?: unknown } | null)?.effortLevel
262 if (typeof level === 'string') return level
263 }
264 }
265 const level = settings['effortLevel']
266 return typeof level === 'string' ? level : null
267}
268
269// One failing step (the engine not ready yet at launch) must not stop the rest.
270async function safely(work: () => Promise<unknown>): Promise<void> {
271 try {
272 await work()
273 } catch {
274 // The next poll tries again.
275 }
276}
277
278let ticker: Timer | undefined
279let poll: Timer | undefined
280let tokensDone = 0
281let ttlMs = 3600000
282// Whether the last local count of the window worked, and when it ran.
283let isCounted = false
284let lastCountAt = 0
285// What the settings said at the last poll; a poll only moves the label when
286// this changes, so a session-only /effort max is not flipped back.
287let seenKey = ''
288// Each model keeps a cache of its own: switching away and back (/model, or a
289// view whose model differs) brings back the one it left.
290const touchedByModel = new Map<string, number>()
291const pending = new Map<string, number>()
292
293function live(): number {
294 return tokensDone + [...pending.values()].reduce((a, b) => a + b, 0)
295}
296
297async function tick($: EngineInterface): Promise<void> {
298 const now = await $.clock.now()
299 const tokens = live()
300 await update($, runAtom, r => ({ ...r, now, tokens }))
301}
302
303function startTicker($: EngineInterface): void {
304 ticker?.cancel()
305 ticker = $.clock.every(TICK_MS, () => void tick($))
306}
307
308function stopTicker(): void {
309 ticker?.cancel()
310 ticker = undefined
311}
312
313// Writes only on a change, so the slow poll redraws nothing while idle.
314async function refreshControls($: EngineInterface, effort?: string): Promise<void> {
315 const model = await $.session.model()
316 const settings = (await $.settings.read()) as Record<string, unknown>
317 const level = effortFor(settings, model)
318 const key = `${model}|${level}`
319 const isChanged = key !== seenKey
320 // A miss (model or settings not ready at launch) is not remembered, so the
321 // next poll fills the label in rather than leaving "…".
322 if (level !== null && model !== '') seenKey = key
323 const current = await read($, controlsAtom)
324 const next = {
325 model: model !== '' ? model : current.model,
326 effort: effort ?? (level !== null && (isChanged || current.effort === null) ? level : current.effort),
327 }
328 // "claude-opus-5-5" and "claude-opus-5-5[1m]" share one cache.
329 const was = current.model === null ? '' : baseModel(current.model)
330 const now = next.model === null ? '' : baseModel(next.model)
331 if (was !== '' && now !== '' && was !== now) {
332 const { touchedAt } = await read($, cacheAtom)
333 if (touchedAt !== null) touchedByModel.set(was, touchedAt)
334 await update($, cacheAtom, () => ({ touchedAt: touchedByModel.get(now) ?? null }))
335 }
336 if (next.model === current.model && next.effort === current.effort) return
337 await update($, controlsAtom, () => next)
338}
339
340// Keeps the countdowns moving: every second while the cache is warm, else rarely.
341async function pulse($: EngineInterface): Promise<void> {
342 const now = await $.clock.now()
343 const { touchedAt } = await read($, cacheAtom)
344 const clock = await read($, clockAtom)
345 const isWarm = touchedAt !== null && touchedAt + ttlMs > now
346 const isJustCold = touchedAt !== null && !isWarm && clock.now < touchedAt + ttlMs
347 if (isWarm || isJustCold || now - clock.now >= IDLE_CLOCK_MS) {
348 await update($, clockAtom, () => ({ now }))
349 }
350 await safely(() => refreshControls($))
351 // The plain usage call is free and writes only on a change: catches the
352 // first reading of a session, and any measurement missed.
353 await safely(() => refreshUsage($))
354 // The local count every few seconds, so ctx never trails /context.
355 if (now - lastCountAt >= COUNT_MS) await safely(() => recountContext($))
356}
357
358function startPoll($: EngineInterface): void {
359 poll?.cancel()
360 poll = $.clock.every(POLL_MS, () => void safely(() => pulse($)))
361}
362
363async function pickEffort($: EngineInterface): Promise<void> {
364 try {
365 await $.command.run({ command: 'effort' })
366 } catch {
367 $.ui.toast('Could not open the effort picker; type /effort')
368 }
369 await refreshControls($)
370}
371
372// A chip opens that pane of the panes mod, beside the conversation or inline.
373async function openPane($: EngineInterface, id: string): Promise<void> {
374 try {
375 await $.command.run({ command: 'panes', args: id })
376 } catch {
377 $.ui.toast(`Could not open the pane; type /panes ${id}`)
378 }
379}
380
381async function pickModel($: EngineInterface): Promise<void> {
382 try {
383 await $.command.run({ command: 'model' })
384 } catch {
385 $.ui.toast('Could not open the model picker; type /model')
386 }
387 await refreshControls($)
388}
389
390export const register: Register = (on, options) => {
391 // The desktop app draws deskdeck's band above the prompt (./desk); every
392 // hook below that draws leaves the desktop to it and to the app's own footer.
393 registerDesk(on, options)
394
395 ttlMs = (options as Record<string, unknown>)['cacheTtl'] === '5m' ? 300000 : 3600000
396
397 // At launch the engine may not have the model, settings or a usage reading
398 // yet: the poll starts first and each step stands alone, so a miss here is
399 // filled in a second later instead of leaving the row blank.
400 on('session.start', async ($, e, next) => {
401 startPoll($)
402 await safely(async () => {
403 const started = await $.clock.now()
404 await update($, clockAtom, () => ({ now: started }))
405 const held = await storedUsage($, started)
406 await update($, usageAtom, u => ({
407 fiveHour: u.fiveHour ?? held.fiveHour,
408 week: u.week ?? held.week,
409 context: u.context,
410 }))
411 })
412 await safely(() => refreshUsage($))
413 await safely(() => refreshControls($))
414 await safely(async () => {
415 if ((await read($, runAtom)).isWorking) startTicker($)
416 })
417 await safely(() => deskSessionStart($))
418 return next(e)
419 })
420
421 on('session.measure', async ($, e, next) => {
422 const measured = usageFrom(await read($, usageAtom), e.context, e.rateLimits)
423 await update($, usageAtom, () => measured)
424 await safely(() => saveUsage($, measured))
425 // The live window's fill moves after each main-thread response: a request
426 // that went out over the cached prefix, so the cache was just refreshed.
427 if (e.changed.includes('context') && (e.context.tokens ?? 0) > 0) {
428 const now = await $.clock.now()
429 const { touchedAt } = await read($, cacheAtom)
430 if (touchedAt === null || now - touchedAt > 2000) {
431 await update($, cacheAtom, () => ({ touchedAt: now }))
432 }
433 await safely(() => recountContext($))
434 }
435 await safely(() => deskMeasure($, e))
436 return next(e)
437 })
438
439 // A /clear starts an empty window with nothing cached.
440 on('session.end', async ($, e, next) => {
441 if (e.reason === 'clear') {
442 touchedByModel.clear()
443 await update($, cacheAtom, () => ({ touchedAt: null }))
444 await update($, usageAtom, u => ({ ...u, context: null }))
445 // The next poll counts the new window.
446 lastCountAt = 0
447 }
448 await safely(() => deskEnd($, e))
449 return next(e)
450 })
451
452 // The summarizer's request reads the cached system prompt and tools, which
453 // the next request reuses: the cache stays warm from that moment, and the
454 // window's fill drops to the summary's.
455 on('session.compact', async ($, e, next) => {
456 const done = await next(e)
457 if (e.agentId === undefined && done.skip === undefined && e.trigger !== 'precompute') {
458 const now = await $.clock.now()
459 await update($, cacheAtom, () => ({ touchedAt: now }))
460 await safely(() => recountContext($))
461 }
462 await safely(() => deskAfterCompact($, e, done))
463 return done
464 })
465
466 on('turn.start', async ($, e, next) => {
467 if (e.agentId === undefined) {
468 tokensDone = 0
469 pending.clear()
470 const now = await $.clock.now()
471 await update($, runAtom, r => ({ ...r, isWorking: true, startedAt: now, now, tokens: 0 }))
472 startTicker($)
473 }
474 await safely(() => deskTurnStart($, e))
475 return next(e)
476 })
477
478 on('turn.complete', async ($, e, next) => {
479 if (e.agentId === undefined) {
480 stopTicker()
481 pending.clear()
482 await update($, runAtom, r => ({ ...r, isWorking: false }))
483 await safely(() => refreshControls($))
484 }
485 await safely(() => deskTurnComplete($, e))
486 return next(e)
487 })
488
489 // Counts the turn's output tokens as they stream (an estimate while text
490 // arrives, the API's own count when a response ends), follows the effort the
491 // turn really runs at, and stamps the cache each main-thread request touches.
492 on('turn.step', async function* ($, e, next) {
493 const isMain = e.agentId === undefined
494 const startedAt = await $.clock.now()
495 if (isMain && typeof e.effort === 'string') {
496 const effort = e.effort
497 if ((await read($, controlsAtom)).effort !== effort) {
498 await update($, controlsAtom, c => ({ ...c, effort }))
499 }
500 }
501 const id = `${e.agentId ?? 'main'}:${e.turnId}:${e.index}`
502 let chars = 0
503 let counted = false
504 let isStamped = false
505 const stamp = async (usage: { cache_read_input_tokens: number; cache_creation_input_tokens: number } | null) => {
506 if (!isMain || isStamped || usage === null) return
507 if (usage.cache_read_input_tokens + usage.cache_creation_input_tokens <= 0) return
508 isStamped = true
509 await update($, cacheAtom, () => ({ touchedAt: startedAt }))
510 }
511 const stream = next(e)
512 try {
513 let step = await stream.next()
514 while (step.done !== true) {
515 const chunk = step.value
516 if (chunk.kind === 'text' || chunk.kind === 'thinking') chars += chunk.text.length
517 else if (chunk.kind === 'input') chars += chunk.json.length
518 else if (chunk.kind === 'stop' && chunk.usage !== null) {
519 tokensDone += chunk.usage.output_tokens
520 deskStepCounted(chunk.usage.output_tokens)
521 counted = true
522 await stamp(chunk.usage)
523 }
524 pending.set(id, counted ? 0 : Math.round(chars / 4))
525 deskStepPending(id, counted ? 0 : Math.round(chars / 4))
526 yield chunk
527 step = await stream.next()
528 }
529 const result = step.value
530 if (result !== undefined) await stamp(result.usage)
531 return result
532 } finally {
533 if (!counted) {
534 tokensDone += Math.round(chars / 4)
535 deskStepCounted(Math.round(chars / 4))
536 }
537 pending.delete(id)
538 deskStepEnd(id)
539 }
540 })
541
542 on('command.run', { command: 'effort' }, async ($, e, next) => {
543 const ran = await next(e)
544 const typed = e.args.trim().toLowerCase()
545 await refreshControls($, EFFORTS.includes(typed) ? typed : undefined)
546 return ran
547 }).catch(($, e, next) => next(e))
548
549 on('command.run', { command: 'model' }, async ($, e, next) => {
550 const ran = await next(e)
551 await refreshControls($)
552 return ran
553 }).catch(($, e, next) => next(e))
554
555 // The band above the prompt: only the panes chips, so without them it draws
556 // nothing and takes no row.
557 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
558 if (e.surface === 'desktop') return deskBand($, e, next)
559 if (e.props.hasSurvey) return next(e)
560
561 const { Box, Button, Text } = $.ui.resolve(e)
562 const { value: panes } = await $.state.get(panesSummary)
563
564 // While the panes panel is off screen, its news folds into one quiet row.
565 const chips = (p: NonNullable<typeof panes>) => {
566 const items = []
567 if (p.branch !== null) {
568 items.push(
569 <Button key="chip-git" plain onPress={() => openPane($, 'git')}>
570 <Text color={PURPLE} bold>{`⎇ ${p.branch}`}</Text>
571 {p.ahead > 0 && <Text color={PURPLE_LIGHT}>{` ↑${p.ahead}`}</Text>}
572 {p.behind > 0 && <Text color={ORANGE}>{` ↓${p.behind}`}</Text>}
573 {p.changed > 0 && <Text dimColor>{` · ${p.changed} changed`}</Text>}
574 </Button>,
575 )
576 }
577 if (p.edited > 0) {
578 items.push(
579 <Button key="chip-files" plain onPress={() => openPane($, 'files')}>
580 <Text color={ORANGE}>◆</Text>
581 <Text>{` ${p.edited} edited`}</Text>
582 </Button>,
583 )
584 }
585 if (p.total > 0) {
586 items.push(
587 <Button key="chip-tasks" plain onPress={() => openPane($, 'tasks')}>
588 <Text color={GREEN}>✓</Text>
589 <Text>{` ${p.done}/${p.total} tasks`}</Text>
590 </Button>,
591 )
592 }
593 if (items.length === 0) return null
594 return (
595 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
596 {items}
597 </Box>
598 )
599 }
600
601 const chipRow = panes !== undefined && !panes.isPanelShown ? chips(panes) : null
602 return chipRow ?? next(e)
603 })
604
605 // The footer row under the prompt is the engine's: its own mode text, then
606 // " · " and the hint at the left, the SessionMode slot at the far right,
607 // which it moves to a row of its own, still flush right, when the two do not
608 // fit side by side. So the hint draws the mode, model and effort, the slot
609 // draws the pills and the cache, and neither asks for more width than its
610 // words: a part that did would squeeze the engine's mode text until it ran
611 // into the model ("auto mode onOpus") and its " ·" fell to a row of its own.
612
613 // The 5h, 7d and ctx pills and the cache time. None of the engine's mode
614 // labels draw, nor the " · " it sets before them.
615 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
616 if (e.surface === 'desktop') return next(e)
617 const { Box, Text } = $.ui.resolve(e)
618 // A blank of fixed width that never shrinks, so on a narrow terminal the
619 // words keep their spacing and wrap whole instead of running together.
620 const gap = (key: string, cells: number) => <Box key={key} width={cells} flexShrink={0} />
621 const usage = await read($, usageAtom)
622 const cache = await read($, cacheAtom)
623 const clock = await read($, clockAtom)
624 const now = clock.now > 0 ? clock.now : await $.clock.now()
625
626 const remaining = cache.touchedAt === null ? 0 : cache.touchedAt + ttlMs - now
627 const isWarm = remaining > 0
628 const cacheText = isWarm ? warmth(remaining) : 'cold'
629 const percentText = (p: number | null) => (p === null ? '–' : `${Math.round(p)}%`)
630
631 const allPills = [
632 usage.fiveHour === null
633 ? null
634 : { key: '5h', name: '5h', percent: usage.fiveHour.percent, reset: countdown(usage.fiveHour.resetsAt, now) },
635 usage.week === null
636 ? null
637 : { key: '7d', name: '7d', percent: usage.week.percent, reset: countdown(usage.week.resetsAt, now) },
638 { key: 'ctx', name: 'ctx', percent: usage.context, reset: '' },
639 ].filter(p => p !== null)
640
641 // The left half's width, as the hint last drew it, with the run's time and
642 // tokens counted fresh so they never trail a tick.
643 const run = await read($, runAtom)
644 const runCells = run.isWorking
645 ? MODE_GAP + `⏱ ${elapsed(run.now - run.startedAt)}`.length + 1 + `↓ ${compact(run.tokens)} tok`.length
646 : 0
647 const columns = e.viewport?.columns ?? 80
648 const pillCells = (p: (typeof allPills)[number]) =>
649 p.name.length + 2 + percentText(p.percent).length + (p.reset === '' ? 1 : p.reset.length + 2) + PILL_GAP
650 const cacheCells = (isWarm ? 2 : 1) + 1 + cacheText.length
651 // So the row stays one line: 7d goes first, then ctx, then 5h, then the
652 // cache; each comes back, in reverse, once there is room again.
653 let pills = allPills
654 let showCache = true
655 const fits = () =>
656 hintCells + runCells + pills.reduce((n, p) => n + pillCells(p), 0) + (showCache ? cacheCells : 0) + FOOTER_SLACK <= columns
657 for (const key of ['7d', 'ctx', '5h']) {
658 if (fits()) break
659 pills = pills.filter(p => p.key !== key)
660 }
661 if (!fits()) showCache = false
662
663 // Each pill sets its own background on every piece, so nothing bleeds past
664 // its closing pad.
665 const pill = (p: (typeof pills)[number]) => (
666 <Box key={p.key} flexDirection="row" flexShrink={0}>
667 <Text backgroundColor={PILL_BG} color={PILL_LABEL} bold>
668 {` ${p.name} `}
669 </Text>
670 <Text backgroundColor={PILL_BG} color={p.percent === null ? PILL_TIMER : usedColor(p.percent)} bold>
671 {percentText(p.percent)}
672 </Text>
673 <Text backgroundColor={PILL_BG} color={PILL_TIMER}>
674 {p.reset === '' ? ' ' : ` ${p.reset} `}
675 </Text>
676 </Box>
677 )
678
679 const parts = [
680 ...pills.map(p => (
681 <Box key={`gap-${p.key}`} flexDirection="row" flexShrink={0}>
682 {pill(p)}
683 {gap(`gap-after-${p.key}`, PILL_GAP)}
684 </Box>
685 )),
686 showCache && (
687 <Box key="cache" flexDirection="row" flexShrink={0}>
688 <Text color={isWarm ? ORANGE : ICE}>{isWarm ? WARM_ICON : COLD_ICON}</Text>
689 <Text color={CACHE_TIME}>{` ${cacheText}`}</Text>
690 </Box>
691 ),
692 ]
693
694 // Cells the group takes on one line (⚡ is two wide, ❄ one).
695 const cells = pills.reduce((n, p) => n + pillCells(p), 0) + (showCache ? cacheCells : 0)
696 // A row of exactly its words while it fits the terminal; only narrower
697 // than that does it wrap, flush right, on the row the engine gives it.
698 const isOneLine = cells + FOOTER_SLACK <= columns
699 return isOneLine ? (
700 <Box key="right" flexDirection="row" flexShrink={0}>
701 {parts}
702 </Box>
703 ) : (
704 <Box key="right" flexDirection="row" flexWrap="wrap" justifyContent="flex-end">
705 {parts}
706 </Box>
707 )
708 })
709
710 // The mode, model and effort, after the engine's own mode text; while a turn
711 // runs, its time and live output tokens follow the effort.
712 on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
713 if (e.surface === 'desktop') return next(e)
714 const { Box, Button, Text } = $.ui.resolve(e)
715 // A blank of fixed width that never shrinks, so on a narrow terminal the
716 // words keep their spacing and wrap whole instead of running together.
717 const gap = (key: string, cells: number) => <Box key={key} width={cells} flexShrink={0} />
718 const controls = await read($, controlsAtom)
719 const run = await read($, runAtom)
720 const mode = modeOf(e.props.hint)
721 const model = prettyModel(controls.model)
722 const effort = controls.effort ?? '…'
723 if (/shift\+tab/i.test(e.props.hint)) isEngineModeOn = mode === undefined
724 else if (/\? for shortcuts/i.test(e.props.hint)) isEngineModeOn = false
725 const engineModeCells = isEngineModeOn ? ENGINE_MODE_CELLS : 0
726 hintCells =
727 engineModeCells + (mode === undefined ? 0 : `${mode.glyph} ${mode.label}`.length + MODE_GAP) + model.length + 1 + effort.length
728
729 return (
730 <Box key="left" flexDirection="row" flexShrink={0}>
731 {mode !== undefined && (
732 <Box key="mode" flexShrink={0}>
733 <Text color={mode.color} bold>
734 {`${mode.glyph} ${mode.label}`}
735 </Text>
736 </Box>
737 )}
738 {mode !== undefined && gap('gap-mode', MODE_GAP)}
739 <Box key="model-effort" flexDirection="row" flexShrink={0}>
740 <Button key="model" plain onPress={() => pickModel($)}>
741 <Text color={ORANGE} bold>
742 {model}
743 </Text>
744 </Button>
745 {gap('gap-effort', 1)}
746 <Button key="effort" plain onPress={() => pickEffort($)}>
747 <Text color={ORANGE} bold>
748 {effort}
749 </Text>
750 </Button>
751 </Box>
752 {run.isWorking && gap('gap-run', MODE_GAP)}
753 {run.isWorking && (
754 <Box key="run" flexDirection="row" flexShrink={0}>
755 <Text color={PURPLE_LIGHT}>{`⏱ ${elapsed(run.now - run.startedAt)}`}</Text>
756 {gap('gap-tokens', 1)}
757 <Text color={PURPLE_LIGHT}>{`↓ ${compact(run.tokens)} tok`}</Text>
758 </Box>
759 )}
760 </Box>
761 )
762 })
763}
764hooks/desk.tsx 985 lines1import { atom, read, update } from 'claude-code'
2import type {
3 Args,
4 Color,
5 EngineInterface,
6 EventResult,
7 Register,
8 RenderChildren,
9 RenderInput,
10 SessionRateLimit,
11 Timer,
12} from 'claude-code'
13
14import type { Cache, Catalog, Choice, Choices, Clock, ContextTool, DeskRun as Run, DeskUsage as Usage, Git, Mood, MoodState, Window } from '../types'
15import { CLAWD_HEIGHT, CLAWD_WIDTH, clawd } from './clawd'
16import {
17 isLockedTool,
18 parseSkills,
19 serverOf,
20 shortTool,
21 withoutFunctions,
22 withoutNames,
23 withoutServers,
24 withoutSkills,
25} from './context'
26import { parseGit } from './git'
27
28// statusdeck's desktop band, ported from deskdeck, right above the prompt: Clawd and the turn's timer at
29// the left; the git, 5h, 7d, ctx and cache pills at the right, each a rounded
30// outline on no fill of its own, in theme colours only. The app frames this band itself
31// (padding, rounded corners, a faint tint), which no prop reaches; it draws
32// mod trees in the bar under the prompt for its cloud sessions only, as of
33// app 2.37337. Every other surface (the CLI, VS Code, mobile) gets the
34// engine's own band.
35
36const usageAtom = atom({ plugin: 'statusdeck', key: 'deskUsage' } as const, {
37 fiveHour: null,
38 week: null,
39 context: null,
40 tokens: null,
41 window: null,
42} as Usage)
43const cacheAtom = atom({ plugin: 'statusdeck', key: 'deskCache' } as const, { touchedAt: null } as Cache)
44const clockAtom = atom({ plugin: 'statusdeck', key: 'deskClock' } as const, { now: 0 } as Clock)
45const moodAtom = atom({ plugin: 'statusdeck', key: 'mood' } as const, { mood: 'idle', since: 0 } as MoodState)
46const runAtom = atom({ plugin: 'statusdeck', key: 'deskRun' } as const, { isWorking: false, startedAt: 0, tokens: 0 } as Run)
47const gitAtom = atom({ plugin: 'statusdeck', key: 'git' } as const, null as Git)
48const catalogAtom = atom({ plugin: 'statusdeck', key: 'catalog' } as const, { skills: [], tools: [] } as Catalog)
49const NONE: Choice = { skills: [], tools: [] }
50const choicesAtom = atom({ plugin: 'statusdeck', key: 'choices' } as const, { applied: NONE, draft: NONE } as Choices)
51const expandedAtom = atom({ plugin: 'statusdeck', key: 'expanded' } as const, [] as string[])
52
53const CONTEXT_PANE = 'statusdeck-context'
54
55
56// Theme colours by name, which the app resolves to its own light or dark
57// value; a hex colour would stay one colour in both themes.
58const COLD: Color = 'error'
59const RUN: Color = 'suggestion'
60// The warm cache's time, by the sixth of its lifetime left (ten minutes each
61// on the 1h cache): from the brightest green down to red.
62const CACHE_BANDS: Color[] = ['error', 'diffRemoved', 'claude', 'warning', 'diffAdded', 'success']
63// The colour of a percentage used, by the first band it falls under.
64const USED_BANDS: { below: number; color: Color }[] = [
65 { below: 50, color: 'suggestion' },
66 { below: 70, color: 'success' },
67 { below: 85, color: 'warning' },
68 { below: Infinity, color: 'error' },
69]
70// The context gauge's colour by the tenth of the window filled: a distinct
71// theme colour per tenth, from the accent blue through green, yellow and the
72// brand orange to red, each resolved by the app for light or dark.
73const CONTEXT_BANDS: Color[] = [
74 'suggestion',
75 'success',
76 'diffAdded',
77 'diffAddedWord',
78 'warning',
79 'claudeShimmer',
80 'claude',
81 'diffRemoved',
82 'diffRemovedWord',
83 'error',
84]
85// From here a toast suggests /compact once.
86const CONTEXT_WARN = 85
87
88// When the bar runs out of room, parts go in this order, and come back in
89// reverse once there is room again. Clawd and the running turn's pill never go.
90const DROP_ORDER = ['7d', 'cache', 'git', '5h', 'ctx']
91// Blank cells between parts, and room kept for whatever the app draws itself.
92const GAP = 1
93const SLACK = 4
94// The context disc: 1.9 cells across by 0.8 of a line down, about the
95// height of the percentage's digits, which reads as a circle.
96const GAUGE_WIDTH = 1.9
97const GAUGE_HEIGHT = 0.8
98// A pill's border and padding, in cells, and Clawd's track.
99const PILL_CHROME = 4
100const CLAWD_CELLS = 10
101// Below this the band has not been measured yet (the desktop starts it at 1):
102// everything draws, so the band shows and gets its real width.
103const MEASURED_COLUMNS = 8
104const MAX_BRANCH = 18
105// How long Clawd celebrates a finished turn, droops after a stopped one, and
106// stays idle before he falls asleep.
107const DONE_MS = 5000
108const STOPPED_MS = 3000
109const SLEEP_MS = 300000
110
111const POLL_MS = 1000
112const COUNT_MS = 3000
113const GIT_MS = 5000
114const IDLE_CLOCK_MS = 30000
115// Tools whose run may change the working tree, so the git pill reads it again.
116const WRITERS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Bash'])
117
118function usedColor(percent: number): Color {
119 return USED_BANDS.find(band => percent < band.below)?.color ?? 'error'
120}
121
122// The largest unit alone ("3h", "4d", "42m"), and the finer units after it
123// ("47m", "3h 12m"), shown on hover.
124function countdown(resetsAt: string | null, now: number): { short: string; more: string } {
125 if (resetsAt === null) return { short: '', more: '' }
126 const ms = Date.parse(resetsAt) - now
127 if (!(ms > 0)) return { short: '', more: '' }
128 const minutes = Math.floor(ms / 60000)
129 const days = Math.floor(minutes / 1440)
130 const hours = Math.floor((minutes % 1440) / 60)
131 const mins = minutes % 60
132 if (days > 0) return { short: `${days}d`, more: `${hours}h ${mins}m` }
133 if (hours > 0) return { short: `${hours}h`, more: `${mins}m` }
134 return { short: `${mins}m`, more: '' }
135}
136
137function tenth(percent: number): number {
138 return Math.max(0, Math.min(9, Math.floor(percent / 10)))
139}
140
141function contextColor(percent: number): Color {
142 return CONTEXT_BANDS[tenth(percent)] ?? 'error'
143}
144
145function cacheColor(remaining: number): Color {
146 const band = Math.min(CACHE_BANDS.length - 1, Math.floor((remaining / ttlMs) * CACHE_BANDS.length))
147 return CACHE_BANDS[Math.max(0, band)] ?? 'error'
148}
149
150// Minutes while there is room to spare, m:ss for the last five.
151function warmth(ms: number): string {
152 if (ms >= 300000) return `${Math.ceil(ms / 60000)}m`
153 const s = Math.max(0, Math.ceil(ms / 1000))
154 return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
155}
156
157function elapsed(ms: number): string {
158 const s = Math.max(0, Math.floor(ms / 1000))
159 return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
160}
161
162function compact(n: number): string {
163 return n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n)
164}
165
166function shorten(text: string, max: number): string {
167 return text.length <= max ? text : `${text.slice(0, max - 1)}…`
168}
169
170// "claude-opus-5-5[1m]", "claude-opus-5-5-20261001" and "opus" all name one model.
171function baseModel(id: string): string {
172 return id
173 .toLowerCase()
174 .replace(/\[.*?\]/g, '')
175 .replace(/-\d{8}$/, '')
176 .trim()
177}
178
179function toWindow(limit: SessionRateLimit | undefined): Window | null {
180 return limit === undefined ? null : { percent: limit.percentUsed, resetsAt: limit.resetsAt ?? null }
181}
182
183// A window whose reset has passed holds nothing worth showing.
184function fresh(w: Window | null, now: number): Window | null {
185 if (w === null || w.resetsAt === null) return w
186 return Date.parse(w.resetsAt) > now ? w : null
187}
188
189// One failing step (the engine not ready yet at launch) must not stop the rest.
190async function safely(work: () => Promise<unknown>): Promise<void> {
191 try {
192 await work()
193 } catch {
194 // The next poll tries again.
195 }
196}
197
198let poll: Timer | undefined
199let settle: Timer | undefined
200let ttlMs = 3600000
201// Whether the last local count of the window worked, and when it ran.
202let isCounted = false
203let lastCountAt = 0
204let lastGitAt = 0
205// The model at the last poll: each model keeps a cache of its own.
206let lastModel = ''
207// Whether the context warning was already toasted at this fill.
208let isContextWarned = false
209// The turn's output tokens: those of finished responses, and the estimates of
210// responses still streaming, by step.
211let tokensDone = 0
212const pending = new Map<string, number>()
213
214function liveTokens(): number {
215 return tokensDone + [...pending.values()].reduce((a, b) => a + b, 0)
216}
217
218function usageFrom(
219 prev: Usage,
220 context: { percent?: number; tokens?: number; window?: number } | undefined,
221 rateLimits: readonly SessionRateLimit[] | undefined,
222): Usage {
223 const limits = rateLimits ?? []
224 return {
225 fiveHour: toWindow(limits.find(l => l.kind === 'five_hour')) ?? prev.fiveHour,
226 week: toWindow(limits.find(l => l.kind === 'seven_day')) ?? prev.week,
227 context: isCounted ? prev.context : (context?.percent ?? prev.context),
228 tokens: isCounted ? prev.tokens : (context?.tokens ?? prev.tokens),
229 window: isCounted ? prev.window : (context?.window ?? prev.window),
230 }
231}
232
233// The rate-limit windows are the account's, so the last reading carries over
234// to the next session until a response brings a new one.
235async function saveUsage($: EngineInterface, usage: Usage): Promise<void> {
236 if (usage.fiveHour === null && usage.week === null) return
237 await $.store.set('limits', { fiveHour: usage.fiveHour, week: usage.week })
238}
239
240// Once per crossing: the fill has to drop back under the line to warn again.
241async function warnContext($: EngineInterface): Promise<void> {
242 const { context } = await read($, usageAtom)
243 const isOver = context !== null && context >= CONTEXT_WARN
244 if (isOver && !isContextWarned) {
245 $.ui.toast(`Context ${Math.round(context)}% full: run /compact to free it`)
246 }
247 isContextWarned = isOver
248}
249
250async function refreshUsage($: EngineInterface): Promise<void> {
251 const { context, rateLimits } = await $.session.usage()
252 const prev = await read($, usageAtom)
253 const next = usageFrom(prev, context, rateLimits)
254 if (JSON.stringify(next) === JSON.stringify(prev)) return
255 await update($, usageAtom, () => next)
256 await saveUsage($, next)
257 await warnContext($)
258}
259
260// The window counted locally, as /context counts it (no request sent), so ctx
261// is right after a /compact or /clear too.
262async function recountContext($: EngineInterface): Promise<void> {
263 lastCountAt = await $.clock.now()
264 const { context } = await $.session.usage({ breakdown: 'summary' })
265 const b = context.breakdown
266 const max = b?.rawMaxTokens ?? context.window
267 const percent =
268 b === undefined
269 ? null
270 : typeof b.percentage === 'number'
271 ? b.percentage
272 : max > 0
273 ? Math.round((b.totalTokens / max) * 100)
274 : null
275 isCounted = percent !== null
276 if (percent === null || b === undefined) return
277 const tokens = b.totalTokens
278 const held = await read($, usageAtom)
279 if (held.context === percent && held.tokens === tokens && held.window === max) return
280 await update($, usageAtom, u => ({ ...u, context: percent, tokens, window: max }))
281 await warnContext($)
282}
283
284async function refreshGit($: EngineInterface): Promise<void> {
285 lastGitAt = await $.clock.now()
286 // Null outside a repository, or where git is missing.
287 const { exitCode, stdout } = await $.process.run(['git', 'status', '--porcelain=v1', '--branch', '--untracked-files=normal'], {
288 timeoutMs: 5000,
289 })
290 const git = exitCode === 0 ? parseGit(stdout) : null
291 if (JSON.stringify(git) === JSON.stringify(await read($, gitAtom))) return
292 await update($, gitAtom, () => git)
293}
294
295// A switch of model starts its cache cold.
296async function followModel($: EngineInterface): Promise<void> {
297 const model = baseModel(await $.session.model())
298 if (model === '') return
299 if (lastModel !== '' && model !== lastModel) await update($, cacheAtom, () => ({ touchedAt: null }))
300 lastModel = model
301}
302
303// A mood that passes (done, stopped) settles back to idle after its while,
304// unless another mood has taken over by then.
305async function setMood($: EngineInterface, mood: Mood): Promise<void> {
306 settle?.cancel()
307 settle = undefined
308 const since = await $.clock.now()
309 const current = await read($, moodAtom)
310 if (current.mood !== mood) await update($, moodAtom, () => ({ mood, since }))
311 const lasts = mood === 'done' ? DONE_MS : mood === 'stopped' ? STOPPED_MS : null
312 if (lasts === null) return
313 settle = $.clock.after(lasts, () => {
314 void safely(async () => {
315 if ((await read($, moodAtom)).mood === mood) await setMood($, 'idle')
316 })
317 })
318}
319
320async function pulse($: EngineInterface): Promise<void> {
321 const now = await $.clock.now()
322 const mood = await read($, moodAtom)
323 if (mood.mood === 'idle' && mood.since > 0 && now - mood.since >= SLEEP_MS) await setMood($, 'sleep')
324 const run = await read($, runAtom)
325 const { touchedAt } = await read($, cacheAtom)
326 const clock = await read($, clockAtom)
327 const isWarm = touchedAt !== null && touchedAt + ttlMs > now
328 const isJustCold = touchedAt !== null && !isWarm && clock.now < touchedAt + ttlMs
329 // Every second while a turn runs (its timer) or the cache counts down.
330 if (run.isWorking || isWarm || isJustCold || now - clock.now >= IDLE_CLOCK_MS) {
331 await update($, clockAtom, () => ({ now }))
332 }
333 if (run.isWorking && run.tokens !== liveTokens()) {
334 const tokens = liveTokens()
335 await update($, runAtom, r => ({ ...r, tokens }))
336 }
337 await safely(() => followModel($))
338 await safely(() => refreshUsage($))
339 if (now - lastCountAt >= COUNT_MS) await safely(() => recountContext($))
340 if (now - lastGitAt >= GIT_MS) await safely(() => refreshGit($))
341}
342
343
344
345// Whether this process is a session the desktop app started: the context
346// choices apply there alone, never in the CLI or VS Code.
347let isDesktop: boolean | undefined
348
349async function onDesktop($: EngineInterface): Promise<boolean> {
350 if (isDesktop === undefined) isDesktop = (await $.env.get('CLAUDE_CODE_ENTRYPOINT')) === 'claude-desktop'
351 return isDesktop
352}
353
354const sameChoice = (a: Choice, b: Choice) =>
355 JSON.stringify([...a.skills].sort()) === JSON.stringify([...b.skills].sort()) &&
356 JSON.stringify([...a.tools].sort()) === JSON.stringify([...b.tools].sort())
357
358function changeCount(c: Choices): number {
359 const diff = (x: string[], y: string[]) => x.filter(n => !y.includes(n)).length + y.filter(n => !x.includes(n)).length
360 return diff(c.applied.skills, c.draft.skills) + diff(c.applied.tools, c.draft.tools)
361}
362
363// Servers every one of whose tools is off: their instructions go too.
364function offServers(tools: readonly ContextTool[], off: readonly string[]): Set<string> {
365 const servers = new Set<string>()
366 for (const server of new Set(tools.map(t => t.server))) {
367 const own = tools.filter(t => t.server === server)
368 if (own.length > 0 && own.every(t => off.includes(t.name))) servers.add(server)
369 }
370 return servers
371}
372
373async function refreshTools($: EngineInterface): Promise<void> {
374 const tools = (await $.tool.list())
375 .filter(t => t.mcp)
376 .map(t => ({ name: t.name, description: t.description.split('\n')[0] ?? '', server: serverOf(t.name) ?? 'mcp' }))
377 .sort((a, b) => a.name.localeCompare(b.name))
378 const held = await read($, catalogAtom)
379 if (JSON.stringify(held.tools) !== JSON.stringify(tools)) await update($, catalogAtom, c => ({ ...c, tools }))
380}
381
382// What the model reads changes from the next request: the listings and the
383// tool schemas are computed again, which re-caches the conversation once.
384async function applyChoices($: EngineInterface): Promise<void> {
385 const { draft, applied } = await read($, choicesAtom)
386 if (sameChoice(draft, applied)) return
387 await update($, choicesAtom, c => ({ ...c, applied: c.draft }))
388 await $.store.set('context-off', draft)
389 $.ui.invalidate('prompt.attachment')
390 $.ui.invalidate('tool.describe')
391}
392
393async function toggle($: EngineInterface, kind: 'skills' | 'tools', names: readonly string[], isOff: boolean): Promise<void> {
394 await update($, choicesAtom, c => {
395 const rest = c.draft[kind].filter(n => !names.includes(n))
396 return { ...c, draft: { ...c.draft, [kind]: isOff ? [...rest, ...names] : rest } }
397 })
398}
399
400async function openContext($: EngineInterface): Promise<void> {
401 await safely(() => refreshTools($))
402 // The skill listing went out before the panel could read it: the next
403 // request asks for it again, unchanged while nothing is off, so no re-cache.
404 if ((await read($, catalogAtom)).skills.length === 0) $.ui.invalidate('prompt.attachment')
405 try {
406 await $.ui.open({ id: CONTEXT_PANE, title: 'Context' })
407 } catch {
408 $.ui.toast('Could not open the context panel')
409 }
410}
411
412
413export const registerDesk: Register = (on, options) => {
414 ttlMs = (options as Record<string, unknown>)['cacheTtl'] === '5m' ? 300000 : 3600000
415
416 // Only a session the desktop app started keeps the poll running: anywhere
417 // else nothing draws the bar, so there is nothing to keep fresh.
418
419
420 // A /clear starts an empty window with nothing cached.
421
422 // Clawd and the timer follow the main thread's turns: working while one
423 // runs, done or stopped when it ends, and needs-you while a prompt waits.
424
425
426 // Counts the turn's output tokens as they stream: an estimate while text
427 // arrives, the API's own count once a response ends.
428
429 // A verdict of "ask" means a permission prompt is about to wait on you.
430 on('tool.check', async ($, e, next) => {
431 const verdict = await next(e)
432 if (verdict.decision === 'ask') await safely(() => setMood($, 'attention'))
433 return verdict
434 }).catch(($, e, next) => next(e))
435
436 // A compaction re-caches the conversation anyway: pending choices go with it.
437
438 on('command.run', { command: 'statusdeck-context' }, async $ => {
439 await openContext($)
440 return { text: 'Context panel opened.' }
441 })
442
443 // The skills Claude is told about: the panel reads the full listing, the
444 // model reads it without the skills turned off.
445 on('prompt.attachment', { type: 'skill_listing' }, async ($, e, next) => {
446 const answer = await next(e)
447 if (answer.text === null || !(await onDesktop($))) return answer
448 const text = answer.text
449 await safely(async () => {
450 const skills = parseSkills(text)
451 if (skills.length > 0 && JSON.stringify((await read($, catalogAtom)).skills) !== JSON.stringify(skills)) {
452 await update($, catalogAtom, c => ({ ...c, skills }))
453 }
454 })
455 const off = new Set((await read($, choicesAtom)).applied.skills)
456 return { text: withoutSkills(text, off) }
457 }).catch(($, e, next) => next(e))
458
459 // The deferred tools Claude may load by name: none it is not to see.
460 on('prompt.attachment', { type: 'deferred_tools_delta' }, async ($, e, next) => {
461 const answer = await next(e)
462 if (answer.text === null || !(await onDesktop($))) return answer
463 const off = new Set((await read($, choicesAtom)).applied.tools)
464 return { text: withoutNames(answer.text, off) }
465 }).catch(($, e, next) => next(e))
466
467 // A tool turned off leaves the prompt's tool list for the deferred one,
468 // which in turn leaves it out: its schema reaches the model nowhere.
469 on('tool.describe', async ($, e, next) => {
470 const described = await next(e)
471 if (!(await onDesktop($))) return described
472 const { applied } = await read($, choicesAtom)
473 return applied.tools.includes(e.tool) ? { ...described, isDeferred: true } : described
474 }).catch(($, e, next) => next(e))
475
476 // The MCP instructions of a server whose every tool is off.
477 on('prompt.compose', async ($, e, next) => {
478 const composed = await next(e)
479 if (!(await onDesktop($))) return composed
480 const { applied } = await read($, choicesAtom)
481 const servers = offServers((await read($, catalogAtom)).tools, applied.tools)
482 if (servers.size === 0) return composed
483 return { sections: composed.sections.map(section => ({ ...section, text: withoutServers(section.text, servers) })) }
484 }).catch(($, e, next) => next(e))
485
486 // On the desktop a call to what is off is refused, and a tool search never
487 // surfaces it. A question to you waits like a prompt; once a call that
488 // waited is answered (allowed, denied or replied to), the turn is working
489 // again. A tool that may change the working tree has the git pill read it.
490 on('tool.call', async ($, e, next) => {
491 const applied = (await onDesktop($)) ? (await read($, choicesAtom)).applied : NONE
492 if (applied.tools.includes(e.tool)) return { deny: 'This tool is turned off in statusdeck.' }
493 // A tool's own arguments ride the event itself: the Skill tool's `skill`.
494 const skill = (e as { skill?: unknown }).skill
495 if (e.tool === 'Skill' && typeof skill === 'string' && applied.skills.includes(skill)) {
496 return { deny: 'This skill is turned off in statusdeck.' }
497 }
498 if (e.tool === 'AskUserQuestion') await safely(() => setMood($, 'attention'))
499 const result = await next(e)
500 await safely(async () => {
501 if ((await read($, moodAtom)).mood === 'attention') await setMood($, 'working')
502 })
503 if (WRITERS.has(e.tool) && (await onDesktop($))) await safely(() => refreshGit($))
504 if (e.tool === 'ToolSearch' && typeof result.result === 'string' && applied.tools.length > 0) {
505 return { ...result, result: withoutFunctions(result.result, new Set(applied.tools)) }
506 }
507 return result
508 }).catch(($, e, next) => next(e))
509
510
511 // The time and tokens line under each answer: the run pill shows both while
512 // the turn runs, so on the desktop the line draws nothing.
513 on('ui.render', { component: 'TurnDuration' }, async ($, e, next) => {
514 if (e.surface !== 'desktop') return next(e)
515 const { Box } = $.ui.resolve(e)
516 return <Box key="no-duration" />
517 })
518
519
520 // The context panel: every skill and MCP tool the session offers, a
521 // checkbox each; what is unchecked is hidden from Claude once applied.
522 on('ui.render', { component: 'Pane', requestId: CONTEXT_PANE }, async ($, e) => {
523 const { Box, Button, Text } = $.ui.resolve(e)
524 const catalog = await read($, catalogAtom)
525 const choices = await read($, choicesAtom)
526 const expanded = await read($, expandedAtom)
527 const cache = await read($, cacheAtom)
528 const clock = await read($, clockAtom)
529 const now = clock.now > 0 ? clock.now : await $.clock.now()
530 const width = Math.max(24, e.props.bodyColumns - 2)
531 const changes = changeCount(choices)
532 const offSkills = new Set(choices.draft.skills)
533 const offTools = new Set(choices.draft.tools)
534 const warmFor = cache.touchedAt === null ? 0 : cache.touchedAt + ttlMs - now
535
536 const box = (isOn: boolean | 'some', isLocked = false) => (
537 <Text key="box" color={isLocked ? undefined : isOn === false ? undefined : 'suggestion'} dimColor={isLocked || isOn === false}>
538 {isOn === 'some' ? '◩' : isOn ? '☑' : '☐'}
539 </Text>
540 )
541 const fit = (text: string, room: number) => (text.length <= room ? text : `${text.slice(0, Math.max(1, room - 1))}…`)
542 const heading = (key: string, title: string, note: string) => (
543 <Box key={key} flexDirection="row" justifyContent="space-between" marginTop={1}>
544 <Text key="title" bold>
545 {title}
546 </Text>
547 <Text key="note" dimColor>
548 {note}
549 </Text>
550 </Box>
551 )
552
553 const skillRows = catalog.skills.map(skill => {
554 const isOn = !offSkills.has(skill.name)
555 return (
556 <Button key={`skill:${skill.name}`} plain onPress={() => void toggle($, 'skills', [skill.name], isOn)}>
557 {box(isOn)}
558 <Text key="name">{` ${fit(skill.name, Math.floor(width / 2))}`}</Text>
559 <Text key="about" dimColor>
560 {` ${fit(skill.description, width - Math.min(skill.name.length, Math.floor(width / 2)) - 6)}`}
561 </Text>
562 </Button>
563 )
564 })
565
566 const servers = [...new Set(catalog.tools.map(t => t.server))]
567 const serverRows = servers.flatMap(server => {
568 const tools = catalog.tools.filter(t => t.server === server)
569 const isLocked = tools.every(t => isLockedTool(t.name))
570 const onCount = tools.filter(t => !offTools.has(t.name)).length
571 const state: boolean | 'some' = onCount === tools.length ? true : onCount === 0 ? false : 'some'
572 const isOpen = expanded.includes(server)
573 const head = (
574 <Box key={`server:${server}`} flexDirection="row" columnGap={1}>
575 {isLocked ? (
576 <Text key="locked" dimColor>
577 {`☑ ${fit(server, width - 22)}`}
578 </Text>
579 ) : (
580 <Button
581 key={`server-toggle:${server}`}
582 plain
583 onPress={() => void toggle($, 'tools', tools.filter(t => !isLockedTool(t.name)).map(t => t.name), state !== false)}
584 >
585 {box(state)}
586 <Text key="name">{` ${fit(server, width - 22)}`}</Text>
587 </Button>
588 )}
589 <Button
590 key={`server-open:${server}`}
591 plain
592 onPress={() => void update($, expandedAtom, list => (isOpen ? list.filter(s => s !== server) : [...list, server]))}
593 >
594 <Text key="count" dimColor>
595 {`${isLocked ? 'required · ' : ''}${onCount}/${tools.length} ${isOpen ? '▾' : '▸'}`}
596 </Text>
597 </Button>
598 </Box>
599 )
600 if (!isOpen) return [head]
601 return [
602 head,
603 ...tools.map(tool => {
604 const isOn = !offTools.has(tool.name)
605 const locked = isLockedTool(tool.name)
606 const label = ` ${fit(shortTool(tool.name), width - 6)}`
607 return locked ? (
608 <Box key={`tool:${tool.name}`} paddingLeft={3} flexDirection="row">
609 {box(true, true)}
610 <Text key="name" dimColor>
611 {label}
612 </Text>
613 </Box>
614 ) : (
615 <Box key={`tool:${tool.name}`} paddingLeft={3} flexDirection="row">
616 <Button key={`tool-toggle:${tool.name}`} plain onPress={() => void toggle($, 'tools', [tool.name], isOn)}>
617 {box(isOn)}
618 <Text key="name">{label}</Text>
619 </Button>
620 </Box>
621 )
622 }),
623 ]
624 })
625
626 const skillsOn = catalog.skills.filter(s => !offSkills.has(s.name)).length
627 const toolsOn = catalog.tools.filter(t => !offTools.has(t.name)).length
628
629 return (
630 <Box flexDirection="column" paddingX={1}>
631 <Text key="lead" dimColor>
632 Unchecked skills and tools are hidden from Claude.
633 </Text>
634 {changes > 0 ? (
635 <Box key="pending" flexDirection="column" marginTop={1} rowGap={0}>
636 <Text key="what" color="warning" bold>
637 {`${changes} change${changes === 1 ? '' : 's'} not applied`}
638 </Text>
639 <Text key="cost" dimColor>
640 {warmFor > 0
641 ? `Cache warm (${warmth(warmFor)}): applying re-caches the conversation once.`
642 : 'Cache cold: applying now costs nothing extra.'}
643 </Text>
644 <Text key="later" dimColor>
645 Or leave them: they apply on their own at the next /clear or /compact.
646 </Text>
647 <Box key="actions" flexDirection="row" columnGap={1} marginTop={1}>
648 <Button key="apply" label="Apply" variant="primary" onPress={() => void applyChoices($)} />
649 <Button
650 key="discard"
651 label="Discard"
652 onPress={() => void update($, choicesAtom, c => ({ ...c, draft: c.applied }))}
653 />
654 </Box>
655 </Box>
656 ) : null}
657 {heading('skills-head', 'Skills', catalog.skills.length === 0 ? '' : `${skillsOn} of ${catalog.skills.length} on`)}
658 {catalog.skills.length === 0 ? (
659 <Text key="no-skills" dimColor>
660 The skill list arrives with your next message.
661 </Text>
662 ) : (
663 <Box key="skills" flexDirection="column">
664 {skillRows}
665 </Box>
666 )}
667 {heading('tools-head', 'MCP tools', catalog.tools.length === 0 ? '' : `${toolsOn} of ${catalog.tools.length} on`)}
668 {catalog.tools.length === 0 ? (
669 <Text key="no-tools" dimColor>
670 No MCP tools in this session.
671 </Text>
672 ) : (
673 <Box key="servers" flexDirection="column">
674 {serverRows}
675 </Box>
676 )}
677 </Box>
678 )
679 })
680}
681
682// Each function below is the desktop's part of a hook register.tsx owns: a
683// plugin hooks an event once, so the CLI's hook calls these.
684export async function deskSessionStart($: EngineInterface): Promise<void> {
685 if (!(await onDesktop($))) return
686 poll?.cancel()
687 await safely(async () => {
688 const held = (await $.store.get('context-off')) as Choice | undefined
689 const applied = { skills: held?.skills ?? [], tools: held?.tools ?? [] }
690 await update($, choicesAtom, () => ({ applied, draft: applied }))
691 })
692 await safely(() => refreshTools($))
693 await safely(() =>
694 $.command.register({ name: 'statusdeck-context', description: 'Choose which skills and MCP tools Claude sees' }),
695 )
696 poll = $.clock.every(POLL_MS, () => void safely(() => pulse($)))
697 await safely(async () => {
698 const now = await $.clock.now()
699 await update($, clockAtom, () => ({ now }))
700 const held = (await $.store.get('limits')) as Partial<Usage> | undefined
701 await update($, usageAtom, u => ({
702 ...u,
703 fiveHour: u.fiveHour ?? fresh(held?.fiveHour ?? null, now),
704 week: u.week ?? fresh(held?.week ?? null, now),
705 }))
706 })
707 await safely(() => refreshUsage($))
708 await safely(() => followModel($))
709 await safely(() => refreshGit($))
710 await safely(() => setMood($, 'idle'))
711
712}
713
714export async function deskMeasure($: EngineInterface, e: Args<'session.measure'>): Promise<void> {
715 const measured = usageFrom(await read($, usageAtom), e.context, e.rateLimits)
716 await update($, usageAtom, () => measured)
717 await safely(() => saveUsage($, measured))
718 await safely(() => warnContext($))
719 // The window's fill moves after each main-thread response: a request that
720 // went out over the cached prefix, so the cache was just refreshed.
721 if (e.changed.includes('context') && (e.context.tokens ?? 0) > 0) {
722 const now = await $.clock.now()
723 await update($, cacheAtom, () => ({ touchedAt: now }))
724 await safely(() => recountContext($))
725 }
726
727}
728
729export async function deskEnd($: EngineInterface, e: Args<'session.end'>): Promise<void> {
730 if (e.reason === 'clear') {
731 // The cache starts over anyway: pending choices cost nothing now.
732 await safely(() => applyChoices($))
733 await update($, cacheAtom, () => ({ touchedAt: null }))
734 await update($, usageAtom, u => ({ ...u, context: null, tokens: null }))
735 lastCountAt = 0
736 }
737
738}
739
740export async function deskTurnStart($: EngineInterface, e: Args<'turn.start'>): Promise<void> {
741 if (e.agentId === undefined) {
742 tokensDone = 0
743 pending.clear()
744 const now = await $.clock.now()
745 await update($, runAtom, () => ({ isWorking: true, startedAt: now, tokens: 0 }))
746 await update($, clockAtom, () => ({ now }))
747 await safely(() => setMood($, 'working'))
748 }
749
750}
751
752export async function deskTurnComplete($: EngineInterface, e: Args<'turn.complete'>): Promise<void> {
753 if (e.agentId === undefined && (await onDesktop($))) {
754 pending.clear()
755 await update($, runAtom, r => ({ ...r, isWorking: false }))
756 await safely(() => setMood($, e.reason === 'answer' ? 'done' : 'stopped'))
757 await safely(() => refreshGit($))
758 }
759
760}
761
762export async function deskAfterCompact($: EngineInterface, e: Args<'session.compact'>, done: EventResult<'session.compact'>): Promise<void> {
763 if (e.agentId === undefined && done.skip === undefined) await safely(() => applyChoices($))
764
765}
766
767// The turn's output tokens, as register.tsx's turn.step counts them.
768export function deskStepPending(id: string, estimate: number): void {
769 pending.set(id, estimate)
770}
771
772export function deskStepCounted(tokens: number): void {
773 tokensDone += tokens
774}
775
776export function deskStepEnd(id: string): void {
777 pending.delete(id)
778}
779
780// The band above the prompt on the desktop.
781export async function deskBand($: EngineInterface, e: RenderInput<'AbovePrompt', 'desktop'>, next: (e: RenderInput<'AbovePrompt', 'desktop'>) => Promise<EventResult<'ui.render'>>): Promise<EventResult<'ui.render'>> {
782 if (e.props.hasSurvey) return next(e)
783 const { Box, Button, Svg, Text } = $.ui.resolve(e)
784 const { mood } = await read($, moodAtom)
785 const usage = await read($, usageAtom)
786 const cache = await read($, cacheAtom)
787 const run = await read($, runAtom)
788 const git = await read($, gitAtom)
789 const clock = await read($, clockAtom)
790 const now = clock.now > 0 ? clock.now : await $.clock.now()
791
792 const remaining = cache.touchedAt === null ? 0 : cache.touchedAt + ttlMs - now
793 const isWarm = remaining > 0
794 const cacheText = isWarm ? warmth(remaining) : '❄'
795 const percentText = (p: number | null) => (p === null ? '–' : `${Math.round(p)}%`)
796
797 // The 5h and 7d usage pills are left out of the desktop band for now.
798 const pills = [
799 { key: 'ctx', percent: usage.context, reset: { short: '', more: '' } },
800 ].filter(p => p !== null)
801 const runText = run.isWorking ? `⏱ ${elapsed(now - run.startedAt)} ↓ ${compact(run.tokens)}` : ''
802 const branch = git === null ? '' : shorten(git.branch, MAX_BRANCH)
803 const gitText = git === null ? '' : `⎇ ${branch}${git.files.length > 0 ? ` ±${git.files.length}` : ''}`
804
805 // Each part's width in cells, its border and padding included, so parts
806 // drop one by one as the band narrows.
807 const widths = new Map<string, number>()
808 widths.set('clawd', CLAWD_CELLS)
809 widths.set('open', 2)
810 if (run.isWorking) widths.set('run', runText.length + PILL_CHROME)
811 if (git !== null) widths.set('git', gitText.length + PILL_CHROME)
812 for (const p of pills) {
813 // The ctx pill's gauge is one cell where the others have their label.
814 const label = p.key === 'ctx' ? '●●' : p.key
815 const words = `${label} ${percentText(p.percent)}${p.reset.short === '' ? '' : ` ${p.reset.short}`}`
816 widths.set(p.key, words.length + PILL_CHROME)
817 }
818 widths.set('cache', cacheText.length + PILL_CHROME)
819
820 // Parts drop one by one only once the band has a real width; Clawd and
821 // the running turn's pill stay whatever the width, so the band always has
822 // something drawn in it.
823 const shown = new Set(widths.keys())
824 const columns = e.props.bodyColumns
825 const total = () => [...shown].reduce((n, k) => n + (widths.get(k) ?? 0) + GAP, 0) + SLACK
826 if (columns >= MEASURED_COLUMNS) {
827 for (const key of DROP_ORDER) {
828 if (total() <= columns) break
829 shown.delete(key)
830 }
831 }
832
833 // A softly rounded outline in the theme's own border colour, no fill, so
834 // the pills sit on the band as the app draws it in light and dark alike.
835 // Words a pill keeps for hover (`before`, `after`) stay hidden until the
836 // pointer is on it: revealed in place, with no hover fill of any kind.
837 const pill = (key: string, children: RenderChildren[], hover: { before?: string; after?: string } = {}) => {
838 const scope = `deskdeck-${key}`
839 const hidden = (side: string, words: string | undefined) =>
840 words !== undefined &&
841 words !== '' && (
842 <Box key={`${key}-${side}`} display="none" hover={{ scope, display: 'flex' }}>
843 <Text key="words" dimColor>
844 {words}
845 </Text>
846 </Box>
847 )
848 return (
849 <Box
850 key={key}
851 borderStyle="single"
852 paddingX={1}
853 paddingY={0}
854 flexDirection="row"
855 columnGap={1}
856 flexShrink={0}
857 hover={{ scope }}
858 >
859 {hidden('before', hover.before)}
860 {children}
861 {hidden('after', hover.after)}
862 </Box>
863 )
864 }
865 const drawing = clawd(mood)
866
867 return (
868 <Box key="deck" flexDirection="row" justifyContent="space-between" alignItems="center" columnGap={GAP} width="100%">
869 <Box key="left" flexDirection="row" alignItems="center" columnGap={GAP} flexShrink={0}>
870 {shown.has('clawd') && (
871 <Svg
872 key={`clawd-${mood}`}
873 source={drawing.source}
874 alt={drawing.alt}
875 width={CLAWD_WIDTH}
876 height={CLAWD_HEIGHT}
877 isInteractive
878 />
879 )}
880 </Box>
881 <Box key="pills" flexDirection="row" justifyContent="flex-end" alignItems="center" columnGap={GAP}>
882 {git !== null &&
883 shown.has('git') &&
884 pill(
885 'git',
886 [
887 <Text key="branch" dimColor>
888 {`⎇ ${branch}`}
889 </Text>,
890 git.files.length > 0 && (
891 <Text key="changed" color="warning" bold>
892 {`±${git.files.length}`}
893 </Text>
894 ),
895 ],
896 )}
897 {shown.has('run') &&
898 pill('run', [
899 <Text key="time" color={RUN}>
900 {`⏱ ${elapsed(now - run.startedAt)}`}
901 </Text>,
902 <Text key="tokens" dimColor>
903 {`↓ ${compact(run.tokens)}`}
904 </Text>,
905 ])}
906 {pills
907 .filter(p => shown.has(p.key) && p.key !== 'ctx')
908 .map(p =>
909 pill(
910 p.key,
911 [
912 <Text key="name" dimColor>
913 {p.key}
914 </Text>,
915 <Text key="percent" color={p.percent === null ? undefined : usedColor(p.percent)} bold>
916 {percentText(p.percent)}
917 </Text>,
918 p.reset.short !== '' && (
919 <Text key="reset" dimColor>
920 {p.reset.short}
921 </Text>
922 ),
923 ],
924 { after: p.reset.more },
925 ),
926 )}
927 {shown.has('ctx') &&
928 pill(
929 'ctx',
930 [
931 // A small disc, its corners rounded past its half so it is a
932 // circle the height of the text beside it, outlined and filled
933 // from the bottom by the tenth of the window used, in that
934 // tenth's theme colour; the disc clips the fill to its round.
935 <Box
936 key="gauge"
937 borderStyle="round"
938 borderColor={usage.context === null ? undefined : contextColor(usage.context)}
939 width={GAUGE_WIDTH}
940 height={GAUGE_HEIGHT}
941 padding={0}
942 overflow="hidden"
943 flexDirection="column"
944 justifyContent="flex-end"
945 alignSelf="center"
946 flexShrink={0}
947 >
948 {usage.context !== null && usage.context >= 1 && (
949 <Box
950 key="fill"
951 width="100%"
952 height={`${(tenth(usage.context) + 1) * 10}%`}
953 backgroundColor={contextColor(usage.context)}
954 />
955 )}
956 </Box>,
957 <Text key="percent" color={usage.context === null ? undefined : contextColor(usage.context)} bold>
958 {percentText(usage.context)}
959 </Text>,
960 ],
961 {
962 before: 'context',
963 after: usage.tokens === null || usage.window === null ? '' : `${compact(usage.tokens)} / ${compact(usage.window)}`,
964 },
965 )}
966 {shown.has('cache') &&
967 pill(
968 'cache',
969 [
970 <Text key="time" color={isWarm ? cacheColor(remaining) : COLD} bold={isWarm}>
971 {cacheText}
972 </Text>,
973 ],
974 isWarm ? { before: 'cache warm' } : { before: 'cache', after: 'cold' },
975 )}
976 <Button key="open-context" plain onPress={() => void openContext($)}>
977 <Text key="glyph" dimColor>
978 ☰
979 </Text>
980 </Button>
981 </Box>
982 </Box>
983 )
984}
985hooks/clawd.ts 118 lines1import type { Mood } from '../types'
2
3// Clawd, drawn in pixel units on a 48 by 19 track, one SVG per mood. The app
4// runs the SMIL loops itself, so the mod redraws only when the mood changes.
5// The body and eyes read on light and dark alike; the marks beside him (the
6// "!", the sparkles, the "z") are mid tones that do too.
7
8const BODY = '#D97757'
9const EYE = '#141413'
10const ALERT = '#D4A017'
11const SPARKLE = '#639922'
12const SLEEPY = '#888780'
13
14// 24 px tall, the band's own line, at the track's 48:19 proportion.
15export const CLAWD_WIDTH = 61
16export const CLAWD_HEIGHT = 24
17
18const svg = (body: string) =>
19 `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 19" width="${CLAWD_WIDTH}" height="${CLAWD_HEIGHT}" shape-rendering="crispEdges">${body}</svg>`
20
21const loop = (attr: string, values: string, dur: string, extra = '') =>
22 `<animate attributeName="${attr}" values="${values}" dur="${dur}" repeatCount="indefinite" ${extra}/>`
23
24const move = (values: string, dur: string, extra = '') =>
25 `<animateTransform attributeName="transform" type="translate" values="${values}" dur="${dur}" repeatCount="indefinite" additive="sum" ${extra}/>`
26
27const rect = (x: number, y: number, w: number, h: number, fill: string, inner = '') =>
28 `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="${fill}">${inner}</rect>`
29
30// Clawd's own box is x 0..16, y 3..15: a body 12 wide and 9 tall, arms at
31// its sides, eyes three tall, and legs three long beneath.
32const body = (armY = 6) =>
33 rect(2, 3, 12, 9, BODY) + rect(0, armY, 2, 3, BODY) + rect(14, armY, 2, 3, BODY)
34
35const legs = (anim = false) =>
36 [3, 5, 10, 12]
37 .map((x, i) => rect(x, 12, 1, 3, BODY, anim ? loop('height', i % 2 === 0 ? '3;1.5;3' : '1.5;3;1.5', '0.4s') : ''))
38 .join('')
39
40const blink = loop('height', '3;3;0.3;3', '4.5s', 'keyTimes="0;0.92;0.96;1"')
41const openEyes = (inner = '') => rect(5, 6, 1, 3, EYE, inner) + rect(10, 6, 1, 3, EYE, inner)
42const flatEyes = (y: number) => rect(4.5, y, 2, 0.7, EYE) + rect(9.5, y, 2, 0.7, EYE)
43
44// Set down so his feet sit on the track's floor, with room above for a hop.
45const at = (x: number, inner: string, motion = '') => `<g transform="translate(${x} 3)">${motion}${inner}</g>`
46
47const MOODS: Record<Mood, { alt: string; source: string }> = {
48 // Breathes and blinks; every so often shuffles a step to the side and back.
49 idle: {
50 alt: 'Clawd, idle',
51 source: svg(
52 at(
53 4,
54 `<g>${move('0 0;0 0.4;0 0', '3s')}${body()}${openEyes(blink)}</g>${legs()}`,
55 move('0 0;0 0;4 0;4 0;0 0;0 0', '12s', 'keyTimes="0;0.55;0.6;0.85;0.9;1"'),
56 ),
57 ),
58 },
59 // Walks the track and back, legs going, body bobbing, eyes leading the way.
60 working: {
61 alt: 'Clawd, working',
62 source: svg(
63 at(
64 0,
65 `<g>${move('0 0;0 -0.6;0 0', '0.4s')}${body()}<g>${move('1 0;-1 0', '5s', 'calcMode="discrete" keyTimes="0;0.5"')}${openEyes()}</g></g>${legs(true)}`,
66 move('0 0;32 0;0 0', '5s'),
67 ),
68 ),
69 },
70 // Hops in the middle with arms up and happy eyes; sparkles either side.
71 done: {
72 alt: 'Clawd, done',
73 source: svg(
74 at(
75 16,
76 `<g>${move('0 0;0 -3;0 0;0 0', '0.9s', 'keyTimes="0;0.18;0.36;1"')}${body(3)}<path d="M4.5 8.3 L5.5 6.8 L6.5 8.3 M9.5 8.3 L10.5 6.8 L11.5 8.3" stroke="${EYE}" stroke-width="0.8" fill="none"/>${legs()}</g>`,
77 move('0 0;1.5 0;0 0;-1.5 0;0 0', '1.8s'),
78 ) +
79 `<path d="M8 5 l0.7 1.4 l1.4 0.7 l-1.4 0.7 l-0.7 1.4 l-0.7 -1.4 l-1.4 -0.7 l1.4 -0.7 z" fill="${SPARKLE}">${loop('opacity', '0;1;0', '0.9s')}</path>` +
80 `<path d="M40 4 l0.7 1.4 l1.4 0.7 l-1.4 0.7 l-0.7 1.4 l-0.7 -1.4 l-1.4 -0.7 l1.4 -0.7 z" fill="${SPARKLE}">${loop('opacity', '1;0;1', '0.9s')}</path>`,
81 ),
82 },
83 // Wiggles side to side and bounces, one arm waving, eyes wide; "!" beside him.
84 attention: {
85 alt: 'Clawd, needs you',
86 source: svg(
87 at(
88 10,
89 `<g>${move('0 0;0 -1;0 0', '0.5s')}${rect(2, 3, 12, 9, BODY)}${rect(0, 6, 2, 3, BODY)}${rect(14, 2, 2, 3, BODY, loop('y', '2;7;2', '0.6s'))}${rect(5, 5, 1, 4, EYE)}${rect(10, 5, 1, 4, EYE)}</g>${legs()}`,
90 move('0 0;-1.5 0;0 0;1.5 0;0 0', '0.5s'),
91 ) + `<g>${move('0 0;0 -1;0 0', '0.5s')}${rect(31, 4, 1.8, 8, ALERT)}${rect(31, 13.6, 1.8, 2, ALERT)}</g>`,
92 ),
93 },
94 // Droops a step lower with flat eyes and lowered arms after a stop or error.
95 stopped: {
96 alt: 'Clawd, stopped',
97 source: svg(
98 at(
99 4,
100 `<g transform="translate(0 1)">${body(8)}${flatEyes(8)}</g>${legs()}`,
101 move('0 0;-1 0;1 0;0 0;0 0', '1.6s', 'keyTimes="0;0.08;0.16;0.24;1"'),
102 ),
103 ),
104 },
105 // Eyes shut, slow breath, a "z" drifting up and fading beside him.
106 sleep: {
107 alt: 'Clawd, asleep',
108 source: svg(
109 at(4, `<g>${move('0 0;0 0.5;0 0', '5s')}${body(8)}${flatEyes(8.2)}</g>${legs()}`) +
110 `<g>${move('0 0;2 -5', '3s')}<path d="M22 9 h3 l-3 3 h3" stroke="${SLEEPY}" stroke-width="0.8" fill="none">${loop('opacity', '1;0', '3s')}</path></g>`,
111 ),
112 },
113}
114
115export function clawd(mood: Mood): { alt: string; source: string } {
116 return MOODS[mood]
117}
118hooks/context.ts 85 lines1import type { ContextItem } from '../types'
2
3// Plain-text helpers for the context panel: reading the skill listing the
4// engine sends, and taking turned-off skills, tools and servers out of the
5// texts the model reads. None of them touches `$`.
6
7// MCP servers the desktop app itself runs on (its session, turn and window
8// plumbing): the app does not work without them, so they cannot be turned off.
9const LOCKED_SERVERS = /^ccd_/
10
11// "mcp__server__tool" names its server; a built-in tool names none.
12export function serverOf(tool: string): string | null {
13 const m = /^mcp__(.+?)__/.exec(tool)
14 return m?.[1] ?? null
15}
16
17export function shortTool(tool: string): string {
18 const server = serverOf(tool)
19 return server === null ? tool : tool.slice(`mcp__${server}__`.length)
20}
21
22export function isLockedTool(tool: string): boolean {
23 const server = serverOf(tool)
24 return server !== null && LOCKED_SERVERS.test(server)
25}
26
27// The listing is one "- name: description" entry per skill, a description
28// running on over the lines that follow until the next entry. A name holds
29// no spaces but may hold colons ("plugin:skill"), so it runs to the colon
30// and space that open the description.
31export function parseSkills(text: string): ContextItem[] {
32 const skills: ContextItem[] = []
33 for (const block of text.split(/^(?=- )/m)) {
34 const m = /^- (\S+): ([\s\S]*)$/.exec(block.trim())
35 if (m === null) continue
36 const description = (m[2] ?? '').split('\n')[0] ?? ''
37 skills.push({ name: m[1] ?? '', description: description.trim() })
38 }
39 return skills
40}
41
42export function withoutSkills(text: string, off: ReadonlySet<string>): string {
43 if (off.size === 0) return text
44 return text
45 .split(/^(?=- )/m)
46 .filter(block => {
47 const m = /^- (\S+): /.exec(block)
48 return m === null || !off.has(m[1] ?? '')
49 })
50 .join('')
51}
52
53// The deferred-tool notices list one tool name per line.
54export function withoutNames(text: string, off: ReadonlySet<string>): string {
55 if (off.size === 0) return text
56 return text
57 .split('\n')
58 .filter(line => !off.has(line.trim()))
59 .join('\n')
60}
61
62// The system prompt's MCP instructions: one "## server" block per server.
63export function withoutServers(text: string, off: ReadonlySet<string>): string {
64 if (off.size === 0 || !text.includes('# MCP Server Instructions')) return text
65 return text
66 .split(/^(?=## )/m)
67 .filter(block => {
68 const m = /^## (.+)$/m.exec(block)
69 return m === null || !block.startsWith('## ') || !off.has((m[1] ?? '').trim())
70 })
71 .join('')
72}
73
74// ToolSearch answers with one "<function>{...}</function>" line per tool.
75export function withoutFunctions(text: string, off: ReadonlySet<string>): string {
76 if (off.size === 0) return text
77 return text
78 .split('\n')
79 .filter(line => {
80 const m = /"name":\s*"([^"]+)"/.exec(line)
81 return m === null || !line.includes('<function>') || !off.has(m[1] ?? '')
82 })
83 .join('\n')
84}
85hooks/git.ts 18 lines1import type { Git } from '../types'
2
3// What `git status --porcelain=v1 --branch` prints: the "## branch...upstream
4// [ahead 1, behind 2]" header, then one "XY path" row per changed file.
5export function parseGit(stdout: string): NonNullable<Git> {
6 const [head = '', ...rows] = stdout.split('\n')
7 const line = head.replace(/^## (No commits yet on )?/, '')
8 const name = line.split('...')[0]?.split(' ')[0] ?? ''
9 const branch = name === '' || name === 'HEAD' ? 'detached' : name
10 const counts = /\[(.*)\]$/.exec(line)?.[1] ?? ''
11 const ahead = Number(/ahead (\d+)/.exec(counts)?.[1] ?? 0)
12 const behind = Number(/behind (\d+)/.exec(counts)?.[1] ?? 0)
13 const files = rows
14 .filter(row => row.length > 3)
15 .map(row => ({ status: row.slice(0, 2).trim() || '?', path: row.slice(3) }))
16 return { branch, ahead, behind, files }
17}
18types/index.d.ts 90 lines1export type Window = { percent: number; resetsAt: string | null }
2
3export type Usage = {
4 fiveHour: Window | null
5 week: Window | null
6 context: number | null
7}
8
9export type Run = {
10 isWorking: boolean
11 startedAt: number
12 now: number
13 tokens: number
14}
15
16export type Controls = {
17 effort: string | null
18 model: string | null
19}
20
21// When the main thread's prompt cache was last read or written (ms), or null
22// when it is cold or unknown.
23export type Cache = { touchedAt: number | null }
24
25// A coarse clock the band reads, so countdowns redraw without the turn ticker.
26export type Clock = { now: number }
27
28// What the panes mod publishes for the chips (its own contract owns it).
29export type PanesSummary = {
30 isPanelShown: boolean
31 branch: string | null
32 ahead: number
33 behind: number
34 changed: number
35 edited: number
36 done: number
37 total: number
38}
39
40// The desktop band (ported from deskdeck): its own usage, with the window's
41// tokens and size for the ctx pill's hover, and its own turn record.
42export type DeskUsage = {
43 fiveHour: Window | null
44 week: Window | null
45 context: number | null
46 tokens: number | null
47 window: number | null
48}
49export type DeskRun = { isWorking: boolean; startedAt: number; tokens: number }
50
51// What Clawd shows at the left of the band, and since when (ms).
52export type Mood = 'idle' | 'working' | 'done' | 'attention' | 'stopped' | 'sleep'
53export type MoodState = { mood: Mood; since: number }
54
55// The repository the session works in, or null outside one.
56export type GitFile = { status: string; path: string }
57export type Git = { branch: string; ahead: number; behind: number; files: GitFile[] } | null
58
59// One skill or tool the context panel lists.
60export type ContextItem = { name: string; description: string }
61export type ContextTool = ContextItem & { server: string }
62export type Catalog = { skills: ContextItem[]; tools: ContextTool[] }
63
64// What is turned off: as sent to the model (applied) and as the panel's
65// checkboxes stand (draft); a draft differing from applied waits for Apply.
66export type Choice = { skills: string[]; tools: string[] }
67export type Choices = { applied: Choice; draft: Choice }
68
69declare module 'claude-code' {
70 interface PluginState {
71 statusdeck: {
72 usage: Usage
73 run: Run
74 controls: Controls
75 cache: Cache
76 clock: Clock
77 deskUsage: DeskUsage
78 deskCache: Cache
79 deskClock: Clock
80 deskRun: DeskRun
81 mood: MoodState
82 git: Git
83 catalog: Catalog
84 choices: Choices
85 expanded: string[]
86 }
87 panes: { summary: PanesSummary }
88 }
89}
90