Status band above the prompt in the Claude Desktop app's Code tab: folder, git branch and state, session age, prompt count and cost, 5-hour and weekly plan…

One source of truth for my user-level Claude Code config. Local sessions and cloud sessions (desktop app, claude.ai/code) both read it.
Each folder that landed-dirs.txt names lands in ~/.claude. Both installers read that file, so a folder added there lands on every platform with no other change. Every other path stays in the clone. The mods install from the marketplace instead (decision mods-install-via-marketplace, mods install with no installer step).
| Path | Holds |
|---|---|
CLAUDE.md | Global working rules. A one-line @ import in ~/.claude/CLAUDE.md loads it. |
settings.json | Output style, env vars, hooks. It becomes ~/.claude/settings.json. |
landed-dirs.txt | The folders that both installers land. |
agents/ | The subagent roles, one file each. |
hooks/ | The guard, the watches, and the other hook scripts. |
lint/ | The Simplified Technical English linter, and the gates and checks that CI runs. |
skills/ | The shipped skills, one folder each. |
output-styles/ | The shiv-stylisms output style. |
ux/ | The house UX rules. |
bin/ | The command launchers: merge, verdict, ste-changed, claude-janitor. Also ios-ship, the shared tool that ships iOS apps from the Mac (see "Shipping iOS apps"), and shoot, which takes one screenshot per route, width and theme from a repo's .claude/shoot.json and prints one verdict line. |
janitor/ | The machine-wide sweep for orphaned worktrees, branches, and listeners. See janitor/GUIDE.md. |
merge/ | The code of the merge command. It runs from the clone, and nothing installs a copy. bin/merge starts it. |
actions/ | Composite GitHub Actions this repo publishes (stamp, ste-lint). Callers pin them by commit SHA. |
mods/, .claude-plugin/ | The vendored mods, and the marketplace file that lists them. |
githooks/ | Git hooks for a repo, such as main-ref. |
testing/ | A shared test helper, skip-locally-fail-in-ci.mjs. |
tools/ | mem-monitor.ps1, a manual Windows memory monitor. No installer lands it, and no hook runs it. |
decisions/, debts/, plans/ | The records: one file per ruling, known gap or deferred item, and plan. See debts/README.md. |
docs/ | The generated pages: records.md indexes the records, catalog.md lists hooks, mods and skills. |
.github/ | gates.yml, the CI that checks this repo, and this repo's stamp config. |
.claude/ | Instructions that load only in sessions on this repo. |
.gitattributes, .gitignore | The line-ending rules, and the files that git leaves out. |
.ste-lint-exclude | The pathspecs that the STE lint leaves out, such as pinned third-party prose. |
renovate.json | The Renovate config that updates pinned versions. |
install.sh, install.ps1 | The installers. The install*.test.ps1 files test them. |
git clone https://github.com/shivinate7/claude-settings C:\src\claude-settings
cd C:\src\claude-settings
powershell -ExecutionPolicy Bypass -File .\install.ps1
Needs Windows Developer Mode (Settings > System > For developers), or an admin shell, for real symlinks. Without it, the script copies the files and installs a git post-merge hook that re-copies them after every pull on main.
mkdir -p ~/Developer
git clone https://github.com/shivinate7/claude-settings ~/Developer/claude-settings
cd ~/Developer/claude-settings
bash install.sh
Everything is a real symlink. A git pull in the clone is the whole update.
claude --cloud)A cloud VM never sees your machine's ~/.claude. In claude.ai/code, set the environment's setup script to:
curl -fsSL https://raw.githubusercontent.com/shivinate7/claude-settings/main/install.sh | bash -s -- --cloud
Leave network access at Trusted, or add raw.githubusercontent.com, github.com, and codeload.github.com to a Custom list. The script also writes a SessionStart hook that re-runs itself, so each new or resumed session re-fetches the files even from a stale snapshot. To pin cloud sessions to one commit instead of main, replace /main/ in the URL with /<sha>/, or set CLAUDE_SETTINGS_REF=<sha> as an environment variable.
/context, in any session, lists ~/.claude/CLAUDE.md and the imported file under Memory files./status shows the shiv-stylisms output style.echo $CLAUDE_CODE_SUBAGENT_MODEL. Expect sonnet.~\.claude\claude-settings-install.log for a dated line from the last run. The line reads settings.json=<mode> agents/lint=<mode>. A mode is symlink, copy, or kept. kept means that a replace failed (a file lock, say) and nothing was copied, so the old files stay in place. copy+failed (agents/lint only) means that some files were copied and at least one replace failed; that file keeps its old copy. The run prints why. Run install.ps1 again after you close the lock.Edit a file here, commit, push, open a pull request against main. .github/workflows/gates.yml runs the guard fixture suite, its mutation harness, the STE lint, and the rest of the checks named in that file. Merge only when you say so, or under a repo grant, per CLAUDE.md.
Once merged:
SessionStart hook in settings.json fast-forwards local main and the live pin to origin/main when it can. It works in a detached child, so the session that starts it can load before the move ends. A session that starts after the child ends sees the move.post-merge git hook copies the changed files after your next git pull on main, and re-runs install.ps1 itself if install.ps1 changed.merge commandOne command merges a pull request in any repo that has opted in. It claims record numbers before the merge, waits for CI on the claim commit, reverts the claim if a step fails, and then merges. The repo's own opt-in is the merge block of its stamp config, see "The merge tool contract" in actions/stamp/README.md.
Run it from inside the repo, with gh, git, node and Python 3 on PATH:
merge <pr> preview: what it would claim and merge. Presses nothing.
merge <pr> --confirm [--session NAME] lock, claim, rebuild the records page, push, wait, merge, move the local main, clean up.
NAME shows in the lock to a waiting run.
merge --unlock [BRANCH] remove the merge lock on BRANCH (default: the default branch). Reads no lock state.
merge --dev ... run the checkout's own tree, not origin main
merge --help lists every flag except --dev.
bin/merge lands in ~/.claude/bin. On Windows, bin\merge.cmd lands there too, and starts bin\merge. The installers put ~/.claude/bin on PATH. The launcher holds no merge logic. It finds this clone through CLAUDE_SETTINGS_DIR, then the @ line in CLAUDE.md under CLAUDE_CONFIG_DIR (default ~/.claude). With neither, it clones the public repo into a temporary folder. The checkout must have origin set to shivinate7/claude-settings. Any other result stops before a pull request read. A repo's own wrapper, such as a make merge target, may hold the same lookup instead.origin main and runs from a temporary worktree at that SHA. It prints the SHA it ran. If it cannot prove fresh code, such as when offline, it prints a warning block and runs the code it has. --dev skips all of this and runs the checkout's own tree. Use it only to work on the tool.--unlock is for a dead holder only. A rerun on a branch that already holds its own claim resumes at the wait.confirm in merge/merge.py. The rulings are in these decisions:gh run watch)Exit codes:
| Code | Meaning |
|---|---|
| 0 | A preview ran, the lock was removed, or the merge landed and every after-step passed. |
| 1 | A refusal or a failed step. The message on stderr names it. A launcher stop also exits 1. |
| 1 | The merge landed, but the local main did not move or an afterMerge command failed. The merge stays. The printed line says so. |
| 2 | The arguments are wrong, such as both a pull request number and --unlock. |
Exit 1 has two causes. Read the output to tell them apart. A line that starts merge: #<pr> merged as means that the merge landed.
CLAUDE.md: edit the file. Wrap the sentence in a <!-- rule:<slug> --> anchor if you want lint/rule_audit.py to hold you to naming its enforcement (a guard rule, a gate, a CI step, or unmechanized or judgment plus a reason) in lint/rule_mechanisms.json. All the guard rules, gates, and their design rationale live as comments and numbered decisions inside hooks/guard.py and lint/. Read there, not here, for the full list.agents/<name>.md. A project can override it with a project-level .claude/agents/<name>.md carrying the same name. See agents/builder.md and agents/reviewer.md for the two shipped roles, and CLAUDE.md's Roles section for what each is for.lint/. A guard change: edit hooks/. Re-run the installer once locally so a new symlink exists.decisions/, named by slug. Claim its number only at merge, per CLAUDE.md ("never allocate a numbered record on a branch").debts/.python3 or python on PATH. Hook commands run under sh on Windows, so put Python on Git Bash's own PATH there. Python 3 ships with the Command Line Tools on macOS. When it is missing, run xcode-select --install. When Python is missing, the hook command exits silently, so a machine without it just runs without the gates.install.ps1 once, to replace the copies with real symlinks.~/.claude/CLAUDE.md or settings.json had content you wanted to keep. Both installers back up the old file as *.bak.<timestamp> before writing. Fold anything you want into the repo's own CLAUDE.md or settings.json, then commit.SessionStart hook the setup script installs re-fetches on every session, so this should self-heal. When it does not, check the environment's network access is not blocking the three hosts above.opus-grant-expires for the guarded override and its required expiry field.actions/ after this repository becomes private. Open Settings, then Actions, then General, then Access. Set "Accessible from repositories owned by the user".bin/ios-ship builds, signs and ships the owner's iOS apps from the Mac. It runs on macOS only, under /bin/bash 3.2. Each private app repo keeps only what differs, in tools/ios-ship.json. The account values live once, on the Mac.
The App Store Connect API key
.p8 file lives only on the Mac, at ~/.appstoreconnect/private_keys/AuthKey_<KEY_ID>.p8. Never commit it. This repo is public, so it holds no team ID, key ID, issuer ID or phone ID.~/.config/ios-ship/account.json, holds the key path and the IDs: team_id, device_udid, asc_key_path, asc_key_id, asc_issuer_id. It lives only on the Mac. The tool checks that the key file exists. It never reads the key file.The repo config. The top level holds repo_url (the install job clones it) and apps. It may also set an account key, as a variant for that repo. Each app holds name, scheme, bundle_id and project_dir. These keys are optional:
project_yml: the XcodeGen spec. Without it, the project is hand-written and XcodeGen does not run.product_name: the .app name when it differs from the scheme.prebuild: commands that run in the repo root before XcodeGen.trust_package_plugins: true adds -skipPackagePluginValidation and -skipMacroValidation to the build.configuration: Release (default) or Debug. The install job only.copy_in: a list of {from, to} secret files. The tool copies each into the tree for the build only, and removes the copy on every exit path. to must be git-ignored. A relative from resolves against the repo root of the config.after_archive: commands that check the archive. They run in the repo root with ARCHIVE set. A command that fails fails the app. The testflight job only.Each account value comes from the first of: an environment variable of the same name in capitals (TEAM_ID, DEVICE_UDID, ASC_KEY_PATH, ASC_KEY_ID, ASC_ISSUER_ID), the repo config, the account file. A value that is unset in all three is refused, and the refusal names both files and the variable. The tool has no built-in IDs.
Run it from inside the app repo: ios-ship testflight or ios-ship install. With no CONFIG, the tool uses tools/ios-ship.json at the git toplevel of the current folder. Outside a git repo, or with no such file, it exits 2. The app repos need no wrapper script. install refuses PHONE_APPS_JSON (exit 2): use --app and tools/ios-ship.json.
ios-ship testflight [CONFIG] [--app NAME]... [--export-only] archives each app as Release and uploads it to TestFlight. It refuses unless the tree is clean and HEAD is origin/main, just fetched. All apps share one build number. It stops at the first app that fails, and prints one verdict line. --export-only skips the main check, exports the .ipa files to a folder it prints, and deletes the .ipa of each app that has copy_in.ios-ship install [CONFIG] [--app NAME]... [--no-install] [--debug] [--force] builds each app in its own clone under ~/Library/Application Support/ios-adblock-reinstall and installs it on the phone. One app's failure does not stop the others. Exit 75 means that the phone was not reachable. --no-install stops after a build for generic iOS. An install that is more than 300 days old raises an overdue notice.--app NAME limits a run to the named apps. A name that is not in the config exits 2.settings.json carries a SessionStart hook. It exits at once in cloud sessions, and otherwise hands its work to a detached child and exits 0, so it never blocks a session. The session that starts it can load before the child ends; a session that starts after the child ends sees the move. The child finds the clone from the @ pointer in ~/.claude/CLAUDE.md (the pointer names the live pin, a worktree of the clone). One child runs at a time: it holds a lock directory in ~/.claude, and a start that finds the lock exits quietly. A lock a killed child left is cleared once it is stale. The child fetches origin/main and moves local main to it, fast-forward only. A tree that holds main is merged in place when it has no tracked change; otherwise the tree is left alone. The hook never stashes, resets or forces in your trees. When the pin is not at local main, the child runs merge/install_from_main.sh, which switches only the pin and never one with tracked changes. A failed fetch, move, skip or pin install writes one line to the install log, with its own reason. Cost, per session start or resume: one detached child and at most one network fetch. A local git fetch . runs only when main moves by ref because no tree holds it. The helper and the installer start only when the pin is not at local main. Files written: the lock directory, made and removed each time; install-log lines only on a failure, plus the start and end lines of the helper and of the installer when they run. The install log's reader is the owner; no hook reads it. Case 34 of merge/test_install_from_main.sh proves the no-move cost: no log line, no installer, one fetch.CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH=1 removes the Agent tool from every subagent, so only the main conversation fans out. A nested child's completion notice can misroute. This stalls the subagent that launched it (anthropics/claude-code#75043). A repo that needs nesting raises the depth in its own .claude/settings.json and records the risk in its CLAUDE.md.actions/ste-lint exists as a composite action. A caller repo can then lint only the lines a pull request changed, against the pull request base. It never pays down a whole document's old backlog on the first branch that touches it. See the diff-scope rationale in actions/ste-lint.janitor/GUIDE.md (decisions/the-janitor-is-one-machine-wide-sweep.md).No LICENSE file is in this repository yet. Until one is added, the default is "all rights reserved". Treat the content as personal configuration, not as licensed for reuse.
hooks/register.tsx 358 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, ModelUsage, ProcessRunResult, Register } from 'claude-code'
3
4import type { GitRead, Limit, Snapshot } from '../types'
5
6const snapshot = atom({ plugin: 'desktop-statusline', key: 'snap' } as const, null)
7const warned = atom({ plugin: 'desktop-statusline', key: 'warned' } as const, [])
8const lastTurn = atom({ plugin: 'desktop-statusline', key: 'lastTurn' } as const, null)
9const compactions = atom({ plugin: 'desktop-statusline', key: 'compactions' } as const, null)
10
11const gitRead = atom({ plugin: 'desktop-statusline', key: 'git' } as const, null)
12const gitTry = atom({ plugin: 'desktop-statusline', key: 'gitTry' } as const, null)
13
14const REFRESH_MS = 60_000 // the band's own snapshot (idle time, limit countdowns); it reads no git
15const GIT_IDLE_MS = 300_000 // an idle session reads git this often at most; a turn end and an attach read too
16const WARN_AT = [95, 80]
17const LABELS: Record<string, string> = { five_hour: '5-hour', seven_day: 'Weekly' }
18const LABEL_CELLS = 8
19const PERCENT_CELLS = 5
20const DETAIL_GAP = 2
21const METER_GAP = 3
22const AGENT_ROWS = 3
23// Desktop metrics in CSS px, measured from screenshots of the band: a Box `width` cell, one
24// column of `bodyColumns`, and an average glyph of the band's proportional font. Bars are SVG
25// in px, so the limits row is fitted in px, keeping 5% spare for the estimate.
26const CELL_PX = 15
27const COL_PX = 12.5
28const CHAR_PX = 13
29const SPARE = 0.95
30const MIN_BAR_PX = 60
31const MAX_BAR_PX = 180
32
33const label = (kind: string) => LABELS[kind] ?? kind.replace(/_/g, ' ')
34const tone = (percent: number) => (percent >= 95 ? 'error' : percent >= 80 ? 'warning' : undefined)
35
36const tokens = (n: number) =>
37 n >= 1_000_000 ? `${+(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : `${n}`
38
39// Drawn as an image, so it cannot follow the theme: a translucent track reads on light and dark.
40const bar = (percent: number, width: number) => {
41 const fill = percent >= 95 ? '#e5484d' : percent >= 80 ? '#e0a030' : '#2f7de1'
42 const filled = Math.round((Math.min(percent, 100) / 100) * width)
43 return (
44 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="8" viewBox="0 0 ${width} 8">` +
45 `<rect width="${width}" height="8" rx="4" fill="#808080" fill-opacity="0.3"/>` +
46 `<rect width="${filled}" height="8" rx="4" fill="${fill}"/></svg>`
47 )
48}
49
50const until = (iso: string, now: number) => {
51 const minutes = Math.max(0, Math.round((Date.parse(iso) - now) / 60_000))
52 if (minutes < 60) return `${minutes}m`
53 if (minutes < 1440) return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
54 return `${Math.floor(minutes / 1440)}d ${Math.floor((minutes % 1440) / 60)}h`
55}
56
57const elapsed = (ms: number) => {
58 const s = Math.round(ms / 1000)
59 if (s < 60) return `${s}s`
60 if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`
61 return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`
62}
63
64const ago = (ms: number) => {
65 const minutes = Math.floor(ms / 60_000)
66 if (minutes < 1) return '<1m'
67 if (minutes < 60) return `${minutes}m`
68 if (minutes < 1440) return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
69 return `${Math.floor(minutes / 1440)}d ${Math.floor((minutes % 1440) / 60)}h`
70}
71
72const cacheHit = (u: ModelUsage) => {
73 const input = u.input_tokens + u.cache_creation_input_tokens + u.cache_read_input_tokens
74 return input === 0 ? null : Math.round((u.cache_read_input_tokens / input) * 100)
75}
76
77const isOnDesktop = async ($: EngineInterface) => (await $.session.surfaces()).includes('desktop')
78
79// Each git command is written out in full at its call; this only reads the result.
80const output = async (run: Promise<ProcessRunResult>) => {
81 try {
82 const ran = await run
83 return ran.exitCode === 0 ? ran.stdout.trim() : null
84 } catch {
85 return null
86 }
87}
88
89const warn = async ($: EngineInterface, limits: Limit[], now: number) => {
90 const seen = await read($, warned)
91 const fresh: string[] = []
92
93 for (const limit of limits) {
94 const threshold = WARN_AT.find(t => limit.percent >= t)
95 const key = `${limit.kind}@${threshold}@${limit.resetsAt}`
96 if (threshold === undefined || seen.includes(key)) continue
97
98 fresh.push(key)
99 const resets = limit.resetsAt ? ` · resets in ${until(limit.resetsAt, now)}` : ''
100 $.ui.toast(`${label(limit.kind)} usage limit at ${limit.percent}%${resets}`, { timeoutMs: 8000 })
101 }
102
103 if (fresh.length > 0) await update($, warned, s => [...s, ...fresh].slice(-50))
104}
105
106// Reads git when asked to, on the first try, once more on the next tick after a first failure, or when the last
107// try is GIT_IDLE_MS old; otherwise the last good read stands. So repeated failures (a folder that is not a repo)
108// back off to the idle interval. A failed read is never stored: the band keeps the last good values.
109const refresh = async ($: EngineInterface, isGitDue = false) => {
110 if (!(await isOnDesktop($))) return
111
112 const [usage, cwd, now, agents, prompts] = await Promise.all([
113 $.session.usage(),
114 $.session.cwd(),
115 $.clock.now(),
116 $.agent.list(),
117 $.session.turns(),
118 ])
119 let git = await read($, gitRead)
120 const tried = await read($, gitTry)
121 if (isGitDue || tried === null || tried.fails === 1 || now - tried.at >= GIT_IDLE_MS) {
122 const [status, dirs] = await Promise.all([
123 output($.process.run(['git', 'status', '--porcelain=v2', '--branch'], { cwd, timeoutMs: 5000 })),
124 output($.process.run(['git', 'rev-parse', '--git-dir', '--git-common-dir'], { cwd, timeoutMs: 5000 })),
125 ])
126 const isFailed = status === null || dirs === null
127 await update($, gitTry, () => ({ at: now, fails: isFailed ? (tried?.fails ?? 0) + 1 : 0 }))
128 if (!isFailed) {
129 const lines = status.split('\n')
130 const head = lines.find(l => l.startsWith('# branch.head '))?.slice(14)
131 const ab = lines.find(l => l.startsWith('# branch.ab '))?.match(/\+(\d+) -(\d+)/)
132 const [gitDir, commonDir] = dirs.split('\n')
133 const fresh: GitRead = {
134 branch: head && head !== '(detached)' ? head : null,
135 isWorktree: gitDir !== commonDir,
136 ahead: Number(ab?.[1] ?? 0),
137 behind: Number(ab?.[2] ?? 0),
138 changed: lines.filter(l => l && !l.startsWith('#')).length,
139 }
140 git = fresh
141 await update($, gitRead, () => fresh)
142 }
143 }
144 const limits = usage.rateLimits.map(r => ({
145 kind: r.kind,
146 percent: r.percentUsed,
147 resetsAt: r.resetsAt ?? null,
148 }))
149 const snap: Snapshot = {
150 at: now,
151 startedAt: usage.startedAt,
152 prompts,
153 dir: cwd.split('/').pop() || cwd,
154 branch: git?.branch ?? null,
155 isWorktree: git?.isWorktree ?? false,
156 ahead: git?.ahead ?? 0,
157 behind: git?.behind ?? 0,
158 changed: git?.changed ?? 0,
159 costUsd: usage.cost?.usd ?? null,
160 limits,
161 agents: agents
162 .filter(a => a.status === 'running')
163 .map(a => ({ type: a.type, description: a.description })),
164 }
165
166 await update($, snapshot, () => snap)
167 await warn($, limits, now)
168}
169
170export const register: Register = (on, options) => {
171 // The main conversation's prompt-cache TTL (the `cache_ttl` option): 1 hour on a Claude
172 // subscription within plan usage, 5 minutes with pay-as-you-go API billing, a cloud provider or usage credits.
173 const cacheTtlMs = options.cache_ttl === '5m' ? 5 * 60_000 : 60 * 60_000
174
175 on('session.start', async ($, e, next) => {
176 const started = await next(e)
177 await refresh($, true)
178 $.clock.every(REFRESH_MS, () => void refresh($))
179
180 return started
181 })
182
183 on('session.attach', { surface: 'desktop' }, async ($, e, next) => {
184 const attached = await next(e)
185 await refresh($, true)
186
187 return attached
188 })
189
190 on('session.measure', async ($, e, next) => {
191 const measured = await next(e)
192 await refresh($)
193
194 return measured
195 })
196
197 on('turn.complete', async ($, e, next) => {
198 const completed = await next(e)
199 if (!e.agentId) {
200 const at = await $.clock.now()
201 await update($, lastTurn, () => ({
202 at,
203 durationMs: e.durationMs,
204 model: e.usage?.model ?? null,
205 cacheHit: e.usage ? cacheHit(e.usage) : null,
206 }))
207 }
208 await refresh($, true) // the one git read of this turn end: the session.measure after it reads none
209
210 return completed
211 })
212
213 // A spawned agent shows as running only once it has started; look again shortly after.
214 on('tool.call', { tool: 'Agent' }, ($, e, next) => {
215 $.clock.after(2000, () => void refresh($))
216
217 return next(e)
218 })
219
220 on('session.compact', async ($, e, next) => {
221 const result = await next(e)
222 if (e.trigger === 'precompute' || e.agentId || result.messages === undefined) return result
223
224 const { startedAt } = await $.session.usage()
225 await update($, compactions, c => ({
226 since: startedAt,
227 count: (c?.since === startedAt ? c.count : 0) + 1,
228 before: result.tokensBefore ?? null,
229 after: result.tokensAfter ?? null,
230 }))
231
232 return result
233 })
234
235 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
236 if (e.surface !== 'desktop' || e.props.hasSurvey) return next(e)
237
238 const snap = await read($, snapshot)
239 if (snap === null) return next(e)
240
241 const { Box, Svg, Text } = $.ui.resolve(e)
242
243 const meter = (name: string, percent: number | null, detail: string, barPx: number) => (
244 <Box flexDirection="row" alignItems="center">
245 <Box width={LABEL_CELLS} flexShrink={0}>
246 <Text>{name}</Text>
247 </Box>
248 {percent === null ? (
249 <Text dimColor>{'waiting for first response'}</Text>
250 ) : (
251 <Box flexDirection="row" alignItems="center" flexShrink={0}>
252 <Svg source={bar(percent, barPx)} alt={`${name} ${percent}% used`} width={barPx} height={8} />
253 <Box width={PERCENT_CELLS} justifyContent="flex-end">
254 <Text color={tone(percent)}>{`${percent}%`}</Text>
255 </Box>
256 </Box>
257 )}
258 <Box marginLeft={DETAIL_GAP} flexShrink={0}>
259 <Text dimColor>{detail}</Text>
260 </Box>
261 </Box>
262 )
263
264 // Fit the limit meters on one row: try "resets in 2h 8m", then "↻ 2h 8m", and stack them
265 // (the one case of 5 lines) only when even the short form leaves a bar under MIN_BAR_PX.
266 const availPx = e.props.bodyColumns * COL_PX * SPARE
267 const fixedPx = (LABEL_CELLS + PERCENT_CELLS + DETAIL_GAP) * CELL_PX
268 const n = Math.max(1, snap.limits.length)
269 const fit = (isLong: boolean) => {
270 const details = snap.limits.map(l => (l.resetsAt ? `${isLong ? 'resets in ' : '↻ '}${until(l.resetsAt, snap.at)}` : ''))
271 const textPx = details.reduce((sum, d) => sum + d.length * CHAR_PX, 0)
272 const barPx = Math.floor((availPx - n * fixedPx - (n - 1) * METER_GAP * CELL_PX - textPx) / n)
273 return { details, barPx: Math.min(MAX_BAR_PX, barPx) }
274 }
275 const long = fit(true)
276 const { details, barPx: sharedBar } = long.barPx >= MIN_BAR_PX ? long : fit(false)
277 const isStacked = sharedBar < MIN_BAR_PX
278 const longestPx = Math.max(0, ...details.map(d => d.length * CHAR_PX))
279 const limitBar = isStacked
280 ? Math.max(40, Math.min(MAX_BAR_PX, Math.floor(availPx - fixedPx - longestPx)))
281 : sharedBar
282
283 const where =
284 `📁 ${snap.dir}` +
285 (snap.branch === null ? '' : ` 🌿 ${snap.branch}${snap.isWorktree ? ' 🌳' : ''}`) +
286 `${snap.ahead ? ` ↑${snap.ahead}` : ''}${snap.behind ? ` ↓${snap.behind}` : ''}` +
287 `${snap.changed ? ` ● ${snap.changed} changed` : ''}`
288 const session =
289 `session ${ago(snap.at - snap.startedAt)} · ${snap.prompts} prompt${snap.prompts === 1 ? '' : 's'}` +
290 (snap.costUsd === null ? '' : ` · $${snap.costUsd.toFixed(2)}`)
291
292 // Bottom line parts: dim unless they need attention (warning) or are live (agents).
293 const activity: { text: string; emphasis?: 'warning' | 'live' }[] = []
294 const turn = await read($, lastTurn)
295 if (turn !== null && turn.at >= snap.startedAt) {
296 const idleMs = Math.max(0, snap.at - turn.at)
297 const isCold = idleMs >= cacheTtlMs
298 activity.push({ text: `Last turn ${elapsed(turn.durationMs)}${turn.model ? ` on ${turn.model}` : ''}` })
299 if (turn.cacheHit !== null) {
300 activity.push({ text: `cache ${turn.cacheHit}%`, emphasis: turn.cacheHit < 50 ? 'warning' : undefined })
301 }
302 if (!e.props.isWorking) {
303 activity.push({ text: `idle ${ago(idleMs)}${isCold ? ' (cache cold)' : ''}`, emphasis: isCold ? 'warning' : undefined })
304 }
305 }
306 const c = await read($, compactions)
307 if (c !== null && c.since === snap.startedAt) {
308 const sizes = c.before === null || c.after === null ? '' : ` (last ${tokens(c.before)} → ${tokens(c.after)})`
309 activity.push({ text: `compacted ${c.count}×${sizes}` })
310 }
311 // Running agents get rows of their own (description truncated, type kept), so a
312 // long description never runs off the "Last turn" line.
313 const agentRows = snap.agents.slice(0, AGENT_ROWS)
314 const moreAgents = snap.agents.length - agentRows.length
315
316 return (
317 <Box flexDirection="column">
318 <Box flexDirection="row" justifyContent="space-between" width="100%">
319 <Text wrap="truncate-end">{where}</Text>
320 <Box marginLeft={2} flexShrink={0}>
321 <Text dimColor>{session}</Text>
322 </Box>
323 </Box>
324 {snap.limits.length > 0 && (
325 <Box flexDirection={isStacked ? 'column' : 'row'} columnGap={METER_GAP}>
326 {snap.limits.map((l, i) => meter(label(l.kind), l.percent, details[i] ?? '', limitBar))}
327 </Box>
328 )}
329 {activity.length > 0 && (
330 <Box flexDirection="row">
331 {activity.map((a, i) => (
332 <Box flexDirection="row">
333 {i > 0 && <Text dimColor>{' · '}</Text>}
334 <Text
335 wrap="truncate-end"
336 color={a.emphasis === 'warning' ? 'warning' : undefined}
337 dimColor={a.emphasis === undefined}
338 >
339 {a.text}
340 </Text>
341 </Box>
342 ))}
343 </Box>
344 )}
345 {agentRows.map(a => (
346 <Box flexDirection="row" justifyContent="space-between" width="100%">
347 <Text wrap="truncate-end">{`⏳ ${a.description || a.type}`}</Text>
348 <Box marginLeft={2} flexShrink={0}>
349 <Text dimColor>{a.type.split(':').pop()}</Text>
350 </Box>
351 </Box>
352 ))}
353 {moreAgents > 0 && <Text dimColor>{` +${moreAgents} more agent${moreAgents > 1 ? 's' : ''} running`}</Text>}
354 </Box>
355 )
356 })
357}
358types/index.d.ts 43 lines1export type Limit = { kind: string; percent: number; resetsAt: string | null }
2
3export type Agent = { type: string; description: string }
4
5export type Snapshot = {
6 at: number
7 startedAt: number
8 prompts: number
9 dir: string
10 branch: string | null
11 isWorktree: boolean
12 ahead: number
13 behind: number
14 changed: number
15 costUsd: number | null
16 limits: Limit[]
17 agents: Agent[]
18}
19
20export type GitRead = Pick<Snapshot, 'branch' | 'isWorktree' | 'ahead' | 'behind' | 'changed'>
21
22export type TurnStat = {
23 at: number
24 durationMs: number
25 model: string | null
26 cacheHit: number | null
27}
28
29export type Compactions = { since: number; count: number; before: number | null; after: number | null }
30
31declare module 'claude-code' {
32 interface PluginState {
33 'desktop-statusline': {
34 snap: Snapshot | null
35 git: GitRead | null
36 gitTry: { at: number; fails: number } | null
37 warned: string[]
38 lastTurn: TurnStat | null
39 compactions: Compactions | null
40 }
41 }
42}
43