SLOPSHOPPER

sidebar

Docked session sidebar: model, usage, session, workspace, CI and tasks

paneguardcommandtoastprocessnetwork
★ 2v0.6.2no licenseupdated 2026-10-21pthexton/claude-sidebar-mod/sidebar
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · sidebar
│ ┃ sidebar ✕ › fix the failing auth test and add an audi╭───────────────────────╮ │ ┃ ── Model ── │ sidebar │ │ ┃ claude-opus-5-5 ⏺ Read(src/auth.ts) │ CI: not a git branch. │ │ ┃ ctx █████░░░░░░░ 49% ⎿ Read 6 lines ╰───────────────────────╯ │ ┃ 5h ███░░░░░░░░░ 31% 0:00 ⏺ Update(src/auth.ts) ╭───────────────────────╮ │ ┃ ⎿ Added 2 lines, removed 1 line │ sidebar │ │ ┃ ── Session ── ⏺ Bash(bun test) │ CI: not a git branch. │ │ ┃ cost $0.38* ⎿ 3 pass, 1 fail ╰───────────────────────╯ │ ┃ time 30m 0s │ ┃ api 0s ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ sid [ copy ] │ ┃ preview-session ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ ── Workspace ── › /sidebar │ ┃ repo app ⎿ sidebar: Sidebar closed. /sidebar opens it again. │ ┃ cwd /work/app │ ┃ │ ┃ ── Cost ── │ ┃ * 9% discount off list prices │ ┃ list $0.42 │ ┃ Change it in /config: Billing discount (%) │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · sidebar
── Model ── claude-opus-5-5 ctx █████░░░░░░░ 49% 5h ███░░░░░░░░░ 31% 0:00 ── Session ── cost $0.38* time 30m 0s api 0s sid [ copy ] preview-session ── Workspace ── repo app cwd /work/app ── Cost ── * 9% discount off list prices list $0.42 Change it in /config: Billing discount (%)
README

claude-sidebar-mod

A Claude Code plugin marketplace with three plugins, installed separately:

  • sidebar: a pane docked beside the transcript that shows the session's model, usage, workspace, CI and tasks. It replaces a multi-line status line, so the prompt box stays in one place.
  • pr-overview: /pr-overview lists the open PRs in the current repo that you're involved in, marks the ones with activity you haven't seen, and opens one in the browser. See PR overview.
  • rose-pine: Rosé Pine colour themes for Claude Code itself. See Rosé Pine themes.

The rest of this page is about the sidebar until those sections. What changed in each version is in CHANGELOG.md.

It's built on Claude Code's function-hooks plugin API, which is early access and may change between releases.

Install

At a Claude Code prompt:

/plugin install sidebar --marketplace pthexton/claude-sidebar-mod

Answer y to add the marketplace, then pick a scope (user scope loads it in every session).

From a local clone instead:

git clone https://github.com/pthexton/claude-sidebar-mod.git
claude plugin marketplace add /path/to/claude-sidebar-mod
claude plugin install sidebar@pt-mods --scope user

A marketplace added from a folder is read from that folder, so edits there reach new sessions without reinstalling (/reload-plugins for running ones).

Required setup

The sidebar only docks beside the transcript in the fullscreen layout. Add to ~/.claude/settings.json:

{ "tui": "fullscreen" }

(or run /tui and pick fullscreen). The pane opens by itself at 144 terminal columns or wider. Below that, run /sidebar to open it (from 110 columns). Drag its edge to resize it; Claude Code remembers the width.

Sections, and what each needs

SectionShowsNeeds
Modelmodel, context bar, 5h / 7d rate-limit bars (subscriptions only), prompt-cache chipnothing; see the two optional extras below for a fuller cache chip
Sessioncost, elapsed time, API time, effort, session id with a copy buttonnothing
Workspacerepo (and (wt) in a worktree), cwd, project root, branch, added dirsgit on PATH; added dirs need the status line feed
CIthe branch's PR, check counts, merge conflicts with the base (in red, with a toast when they first appear), failing and pending checks, refresh and open-PR buttons. Re-checked every 5 minutes once CI has finished, since the base can move ongh, signed in (gh auth login). Hidden when there's no PR or gh can't answer
TasksClaude's own task list (TodoWrite, TaskCreate, TaskUpdate) for the main conversationnothing
Costthe billing discount in use, the session cost at list price, and where to change the discount; with £ shown, the exchange rate in use. Hidden when the discount is 0 and £ is offnothing

Billing discount

Costs are shown after a discount off Anthropic's published prices, 9% by default. That applies to the session cost (Claude Code's own figure, scaled) and to the cache rebuild cost. Both are marked *, and the Cost section at the bottom shows the discount and the session cost at list price.

To change it, open /config and set Billing discount (%) under the sidebar plugin. Set it to 0 to see list prices; the Cost section then disappears.

Pounds (£)

To see costs in pounds as well as dollars, open /config and switch on GBP rate (£) under the sidebar plugin, or run /gbp (run it again to switch £ off). It's off by default. Dollars stay first, since Anthropic bills in dollars: the session cost reads $1.12* £0.85* (both starred while the billing discount is on), and the cache chip adds £ when the pane is wide enough for it.

The rate is the European Central Bank's daily reference rate, fetched from Frankfurter (free, no key) and shared by every session. The ECB publishes it once a working day, at about 3pm UK time. The saved rate is fetched again once it's 6 hours old, so that's at most 4 small requests a day, and each session checks hourly, so one left open all day picks up the new rate. The Cost section shows the rate in use and its date: £ rate: 0.7549 (ECB, 13th Oct). If the fetch fails, the last rate fetched is kept and it's tried again an hour later, once for all sessions; with no rate saved, no £ figure is shown. Nothing is fetched while the setting is off.

Commands: /sidebar shows or hides the pane (its close mark ignores clicks, so a stray one can't close it), /gbp switches £ on or off, /ci-refresh fetches CI now, /open-pr opens the PR in your browser (open on macOS, xdg-open on Linux, rundll32 url.dll,FileProtocolHandler on Windows).

Optional extras

Status line feed: fast mode, real cache TTL, added dirs

Mods can't read some of what Claude Code gives a status line command. sidebar/statusline-feed.sh is a status line command that saves that input per session to ~/.claude/state/statusline/<session_id>.json for the sidebar, and prints nothing, so no status line is drawn under the prompt. It needs jq. Point your status line at it in ~/.claude/settings.json:

{
  "statusLine": { "type": "command", "command": "/path/to/claude-sidebar-mod/sidebar/statusline-feed.sh" }
}

On Windows, use sidebar/statusline-feed.ps1 instead, which needs neither bash nor jq. Use forward slashes in the path, since Claude Code runs status line commands through Git Bash when it's installed:

{
  "statusLine": { "type": "command", "command": "powershell.exe -NoProfile -ExecutionPolicy Bypass -File \"C:/path/to/claude-sidebar-mod/sidebar/statusline-feed.ps1\"" }
}

There's only one status line, so this replaces any you already have. To keep another tool's status line too, pass its program with -Then (both feeds take it): the feed saves the input first, then hands the same input to that program and prints what it prints. Starting PowerShell can take a second or more, and Claude Code cancels a status line run that's still going when the next update is due, so a long-running -Then program may not finish during a busy turn.

Orca users need nothing extra. Orca installs a status line of its own, for its usage display. In an Orca terminal, the feed hands the same input to Orca's status line script (~/.orca/agent-hooks/claude-statusline.cmd on Windows, claude-statusline.sh elsewhere) when it's installed, as Orca's own status line would. Outside Orca terminals, it doesn't. Orca installs that script only while the status line is empty or Orca's own, so if you set up the feed before installing Orca, there's no script to hand on to, and Orca gets its usage figures another way. Orca's script passes the input to Orca only when it holds rate limits (rate_limits), which Claude Code gives the status line for claude.ai Pro and Max subscribers and behind a Claude apps gateway with spend limits; for other accounts it sends Orca nothing, feed or no feed. Don't name Orca's script in your status line, with -Then or otherwise: Orca takes a status line that names its script as its own, and replaces it with Orca's next time Orca starts, which turns the feed off. If that's happened, point the status line at the feed again.

With it, the sidebar shows:

  • a red FAST MODE ON line (and a toast) when fast mode is on, since it bills at a higher rate;
  • the cache chip's real TTL, expiry and rebuild size;
  • effort from the start of the session;
  • elapsed time and API time including time before a resume;
  • added dirs.

Without it, fast mode comes from the fastMode setting, and the cache chip assumes a 1-hour TTL from the last response. Either way, after a --resume the cache chip stays hidden until the first reply.

Pricing file: cache rebuild cost in dollars

The cache chip always shows the rebuild size in tokens. To also show what a cold cache would cost to rebuild (↻$0.37 (45.9k), yellow from $1, red from $5), create ~/.claude/state/model-pricing.tsv. Without it, or for a model it doesn't list, no dollar figure is shown. The figure has the billing discount taken off.

It's tab separated, USD per million tokens, one row per model. Lines starting with # and the header row are skipped:

model_id	input	write_5m	write_1h	cache_read	output	fast_input
claude-opus-5-5	4	5	8	0.2	20	8
claude-haiku-4-5	1	1.25	2	0.1	5
  • model_id is matched by longest prefix, so dated or suffixed ids (claude-haiku-4-5-20251001, claude-opus-5-5[1m]) find their row.
  • write_5m / write_1h are the cache-write prices for each TTL.
  • fast_input is the fast-mode input price, or empty for a model without fast mode. In fast mode the write price is scaled by fast_input / input.
  • cache_read and output aren't used yet, but keep the columns in that order.

Take the figures from Anthropic's pricing page, and update them when prices change.

Keys for CI

Claude Code can't bind function keys, but it can bind chords to the CI commands. In ~/.claude/keybindings.json:

{
  "bindings": [
    {
      "context": "Chat",
      "bindings": { "ctrl+x r": "command:ci-refresh", "ctrl+x o": "command:open-pr" }
    }
  ]
}

To use F5 / F6 anyway, have your terminal send those chords: in Ghostty, keybind = f5=text:\x18r and keybind = f6=text:\x18o; in macOS Terminal, Settings > Profiles > Keyboard, Send Text \030r and \030o.

PR overview

/pr-overview opens a pane listing the open pull requests in the session's repo that you're involved in, most recently updated first. Run it again, or press Escape, to close it. Install:

/plugin install pr-overview --marketplace pthexton/claude-sidebar-mod

It needs gh, logged in (gh auth login). The repo is the one gh picks for the session's folder.

acme/app  updated 09:12  [ refresh ]
● #123  Fix token refresh on expiry            ✓  2h
  #118  Add Orca handover                      ✗ conflict  1d
  • Involved means you opened it, commented on or reviewed it, were asked to review it, wrote one of its commits, or were @-mentioned in it. Team review requests don't count. GitHub's search finds them, however many PRs the repo has open, except commits pushed to someone else's PR: for those it checks the last 50 commits of the 50 most recently updated open PRs. Closed and merged PRs are never listed.
  • ● marks a PR with activity since you last opened it from the list, or one you haven't opened from it yet. Your own activity (your comment, review or push) doesn't mark it. The marks are shared by every session, and a PR's entry is dropped once it's closed or merged.
  • CI is the last commit's checks: ✓ passing, ✗ failing, … running, blank with no checks. conflict shows when GitHub reports a merge conflict. Drafts are dim.
  • Keys: Tab moves between PRs, Enter opens one (gh pr view --web), r refreshes, Escape closes.
  • It refreshes when opened, then every 30 minutes while it's open. Change that in /config: Refresh interval (minutes).

Rosé Pine themes

Three Claude Code themes built from the official Rosé Pine palette: Rosé Pine, Rosé Pine Moon (both dark) and Rosé Pine Dawn (light). Install:

/plugin install rose-pine --marketplace pthexton/claude-sidebar-mod

then pick one in /theme, where it's marked as from rose-pine. To tweak one, edit it in /theme (Ctrl+E): Claude Code saves your edit as a copy in ~/.claude/themes/, since plugin themes are read-only.

The colours follow Rosé Pine's role guide: rose is the accent, love marks errors and removed lines, gold warnings and fast mode, foam success and added lines, iris permissions and merges, and the highlight shades the prompt border, selection and your messages.

They colour the terminal UI only. The desktop app's Code tab keeps its own colours, and so does your terminal: for the sidebar's colours (which use the terminal's ANSI palette) to match, give the terminal the Rosé Pine theme as well (Ghostty: theme = Rose Pine).

rose-pine/themes/*.json is generated: change rose-pine/build.rb and run ruby rose-pine/build.rb.

Developing

claude plugin validate rose-pine
claude plugin validate sidebar
claude plugin test sidebar

claude plugin test runs the mod's tests, but its test sandbox can't start programs, so the status line feeds have their own: bash sidebar/tests/statusline-feed.test.sh (macOS and Linux, needs jq) and powershell -NoProfile -ExecutionPolicy Bypass -File sidebar\tests\statusline-feed.test.ps1 (Windows). GitHub runs them on Linux, macOS and Windows whenever a feed or its tests change (.github/workflows/statusline-feed.yml).

Claude Code writes the API types into sidebar/.claude-plugin/types/ when it loads the mod (git ignores them), after which npx -p typescript@5 tsc -p sidebar type-checks it. To run a working copy for one session without installing it: claude --plugin-dir sidebar.

Source 10 files
hooks/register.tsx 859 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionMeasureInput, SessionUsage } from 'claude-code'
3
4import type { CiCheck, CiStatus, RateWindow, TaskLine, Usage, Workspace } from '../types'
5import {
6  hasConflict,
7  isNoPrError,
8  isPrCreated,
9  notableChecks,
10  parseChecks,
11  parsePr,
12  shouldFetch,
13  summarize,
14} from './ci'
15import { FEED_DIR, parseFeed, resolveCache } from './feed'
16import { FX_CHECK_MS, FX_URL, cacheAmount, fmtGbp, fmtRateLine, isRateStale, isRecentTry, parseRate, toRate } from './fx'
17import { isOwnedBy } from './owner'
18import { baseName, homeDir } from './paths'
19import { costColor, discounted, parsePricing, recacheCost, toDiscount } from './pricing'
20import { elapsedText, isKnownStart } from './session'
21import {
22  applyTaskCreate,
23  applyTaskUpdate,
24  applyTodoWrite,
25  isTaskDim,
26  taskColor,
27  taskIcon,
28} from './tasks'
29
30// A session sidebar: Model, Session, Workspace, CI and Tasks sections in a
31// pane docked beside the fullscreen transcript. See README.md for what each
32// section needs.
33
34const PANE = 'sidebar'
35const PANE_COLUMNS = 40
36
37// The prompt cache TTL isn't exposed to mods: the status line feed carries
38// the real one, and without it this session's 1h TTL is assumed.
39const CACHE_TTL = '1h'
40
41const usage = atom({ plugin: 'sidebar', key: 'usage' } as const, null)
42const lastStep = atom({ plugin: 'sidebar', key: 'lastStep' } as const, null)
43const apiMs = atom({ plugin: 'sidebar', key: 'apiMs' } as const, 0)
44const workspace = atom({ plugin: 'sidebar', key: 'workspace' } as const, null)
45const now = atom({ plugin: 'sidebar', key: 'now' } as const, 0)
46const pricing = atom({ plugin: 'sidebar', key: 'pricing' } as const, [])
47const claudeTasks = atom({ plugin: 'sidebar', key: 'claudeTasks' } as const, [])
48const ci = atom({ plugin: 'sidebar', key: 'ci' } as const, null)
49const isCiFetching = atom({ plugin: 'sidebar', key: 'isCiFetching' } as const, false)
50const isFastMode = atom({ plugin: 'sidebar', key: 'isFastMode' } as const, false)
51const feed = atom({ plugin: 'sidebar', key: 'feed' } as const, null)
52// A change made in /config this session; null until then, when the module's
53// own options (read as it loaded) are the setting.
54const discountChange = atom({ plugin: 'sidebar', key: 'discountChange' } as const, null)
55const gbpRate = atom({ plugin: 'sidebar', key: 'gbpRate' } as const, null)
56const gbpChange = atom({ plugin: 'sidebar', key: 'gbpChange' } as const, null)
57
58// statusline-feed.sh rewrites its file whenever the status line updates.
59const FEED_POLL_MS = 2000
60
61// How often the CI refresh policy is checked; shouldFetch decides whether
62// that tick actually calls gh.
63const CI_TICK_MS = 15_000
64// Bindable in ~/.claude/keybindings.json as command:ci-refresh and
65// command:open-pr (README.md suggests ctrl+x r / ctrl+x o). Function keys
66// can't be bound: the keybinding matcher has no names for them.
67const CMD_CI_REFRESH = 'ci-refresh'
68const CMD_OPEN_PR = 'open-pr'
69const CMD_GBP = 'gbp'
70
71// Per-model prices, optional (format in README.md). Missing or unreadable
72// means the cache chip shows the rebuild size in tokens and no dollar cost.
73const PRICING_FILE = '.claude/state/model-pricing.tsv'
74
75const refreshPricing = async ($: EngineInterface, home: string | undefined) => {
76  if (home === undefined) return
77  try {
78    const rows = parsePricing(await $.fs.read(`${home}/${PRICING_FILE}`))
79    await update($, pricing, () => rows)
80  } catch {
81    // Keep whatever was loaded before.
82  }
83}
84
85// The USD to GBP rate, kept in $.store so every session shares each fetch,
86// with when one was last tried, so a failing fetch isn't retried by every
87// session. A failed fetch keeps the saved rate; with none saved, no £ is shown.
88const GBP_STORE_KEY = 'gbpRate'
89const GBP_TRIED_KEY = 'gbpRateTriedAt'
90
91const refreshGbpRate = async ($: EngineInterface) => {
92  const saved = toRate(await $.store.get(GBP_STORE_KEY))
93  if (saved !== undefined) await update($, gbpRate, () => saved)
94  const at = await $.clock.now()
95  if (!isRateStale(saved, at) || isRecentTry(await $.store.get(GBP_TRIED_KEY), at)) return
96  try {
97    await $.store.set(GBP_TRIED_KEY, at)
98    const res = await $.http.fetch(FX_URL)
99    const fresh = res.ok ? parseRate(res.text, at) : undefined
100    if (fresh === undefined) return
101    await $.store.set(GBP_STORE_KEY, fresh)
102    await update($, gbpRate, () => fresh)
103  } catch {
104    // Offline or refused: keep whatever was saved.
105  }
106}
107
108const toUsage = (u: SessionUsage | SessionMeasureInput, startedAt: number): Usage => ({
109  contextPercent: u.context.percent,
110  rateLimits: u.rateLimits.map(r => ({ kind: r.kind, percentUsed: r.percentUsed, resetsAt: r.resetsAt })),
111  costUsd: u.cost?.usd,
112  startedAt,
113})
114
115// When the session started, epoch ms: the one stored, else the engine's, else
116// the mod's first sight of it; 0 while none is known (drawn as '-', and the
117// next usage reading tries again).
118const sessionStartedAt = async ($: EngineInterface, known: number | undefined) => {
119  if (isKnownStart(known)) return known
120  try {
121    const reported = (await $.session.usage()).startedAt
122    if (isKnownStart(reported)) return reported
123    return await $.clock.now()
124  } catch {
125    return 0
126  }
127}
128
129// The sidebar's state belongs to a session. /clear (and /new, its alias)
130// carries the process on under a new one, which starts with that state empty
131// and gets no session.start: the model shows "?" and Workspace, CI and the
132// session id vanish until a turn ends. The tick sees the missing workspace and
133// fills it in again, with the rest session.start would have read.
134let isRefilling = false
135const refillIfEmpty = async ($: EngineInterface) => {
136  if (isRefilling || (await read($, workspace)) !== null) return
137  isRefilling = true
138  try {
139    await refreshWorkspace($)
140    if ((await read($, usage)) === null) {
141      const u = await $.session.usage()
142      const startedAt = await sessionStartedAt($, u.startedAt)
143      await update($, usage, () => toUsage(u, startedAt))
144    }
145    await refreshFeed($)
146    await refreshFastMode($)
147    $.clock.after(0, () => void refreshCi($, false))
148  } catch {
149    // Try again on the next tick.
150  } finally {
151    isRefilling = false
152  }
153}
154
155const git = async ($: EngineInterface, cwd: string, args: string[]) => {
156  try {
157    const r = await $.process.run(['git', '-C', cwd, ...args], { timeoutMs: 5000 })
158    return r.exitCode === 0 ? r.stdout.trim() : undefined
159  } catch {
160    return undefined
161  }
162}
163
164const refreshWorkspace = async ($: EngineInterface) => {
165  const cwd = await $.session.cwd()
166  const [sessionId, model, root, repo, homeVar, userProfile] = await Promise.all([
167    $.session.id(),
168    $.session.model(),
169    $.session.root(),
170    $.session.repo(),
171    $.env.get('HOME'),
172    $.env.get('USERPROFILE'),
173  ])
174  const home = homeDir(homeVar, userProfile)
175  let branch: string | undefined
176  let isWorktree = false
177  let commitSha: string | undefined
178  if (repo !== null) {
179    branch = await git($, cwd, ['branch', '--show-current'])
180    commitSha = await git($, cwd, ['rev-parse', 'HEAD'])
181    const dirs = await git($, cwd, ['rev-parse', '--path-format=absolute', '--git-dir', '--git-common-dir'])
182    const [gitDir, commonDir] = (dirs ?? '').split('\n')
183    isWorktree = gitDir !== undefined && commonDir !== undefined && gitDir !== commonDir
184  }
185  const repoName = repo === null ? undefined : baseName(repo.root)
186  const ws: Workspace = { sessionId, model, cwd, root, branch, commitSha, isWorktree, repoName, isGit: repo !== null, home }
187  await update($, workspace, () => ws)
188  await refreshPricing($, home)
189  return ws
190}
191
192// The model alone, without the git calls: cheap enough for the 1s tick, which
193// catches a switch no hook announces (the picker, /config, an auto fallback).
194const refreshModel = async ($: EngineInterface) => {
195  const [model, ws] = await Promise.all([$.session.model(), read($, workspace)])
196  if (ws !== null && ws.model !== model) await update($, workspace, () => ({ ...ws, model }))
197}
198
199// Fast mode bills at a higher per-token rate, so turning on gets a toast.
200const setFastMode = async ($: EngineInterface, isOn: boolean) => {
201  if (isOn === (await read($, isFastMode))) return
202  await update($, isFastMode, () => isOn)
203  if (isOn) $.ui.toast('⚡ Fast mode is ON: higher per-token cost. /fast turns it off.', { timeoutMs: 10_000 })
204}
205
206// The mod API has no fast-mode flag. The status line feed carries the
207// session's real state; without a feed, fall back to the `fastMode` setting
208// /fast persists (a session-only toggle may never reach settings).
209const refreshFastMode = async ($: EngineInterface) => {
210  const fromFeed = (await read($, feed))?.isFastMode
211  if (fromFeed !== undefined) return setFastMode($, fromFeed)
212  try {
213    await setFastMode($, (await $.settings.read()).fastMode === true)
214  } catch {
215    // Settings unreadable: leave it as it was.
216  }
217}
218
219const refreshFeed = async ($: EngineInterface) => {
220  const ws = await read($, workspace)
221  if (ws === null || ws.home === undefined) return
222  const path = `${ws.home}/${FEED_DIR}/${ws.sessionId}.json`
223  let text: string
224  let savedAt: number | undefined
225  try {
226    text = await $.fs.read(path)
227  } catch {
228    return // No feed (statusline-feed.sh isn't the status line): fallbacks apply.
229  }
230  try {
231    savedAt = (await $.fs.stat(path)).mtimeMs
232  } catch {
233    savedAt = undefined
234  }
235  const parsed = parseFeed(text, savedAt)
236  if (parsed === null) return
237  await update($, feed, () => parsed)
238  if (parsed.isFastMode !== undefined) await setFastMode($, parsed.isFastMode)
239}
240
241const gh = ($: EngineInterface, cwd: string, args: string[]) =>
242  $.process.run(['gh', ...args], { cwd, timeoutMs: 30_000 })
243
244// Fetches the branch's PR and checks with gh. `force` skips the refresh
245// policy (a manual refresh, a PR just created); otherwise shouldFetch decides.
246const refreshCi = async ($: EngineInterface, force: boolean): Promise<CiStatus | null> => {
247  const ws = await read($, workspace)
248  if (ws === null || !ws.isGit || ws.branch === undefined || ws.branch === '') {
249    await update($, ci, () => null)
250    return null
251  }
252  const branch = ws.branch
253  const commitSha = ws.commitSha ?? ''
254  const prev = await read($, ci)
255  const at = await $.clock.now()
256  if (!force && !shouldFetch(prev, branch, commitSha, at)) return prev
257  if (await read($, isCiFetching)) return prev
258
259  await update($, isCiFetching, () => true)
260  try {
261    const view = await gh($, ws.cwd, ['pr', 'view', '--json', 'number,title,url,createdAt,mergeable'])
262    let status: CiStatus
263    if (view.exitCode !== 0) {
264      status = isNoPrError(view.stderr)
265        ? { branch, commitSha, pr: null, checks: [], fetchedAt: at }
266        : {
267            ...(prev ?? { branch, commitSha, pr: null, checks: [] }),
268            fetchedAt: at,
269            error: view.stderr.trim().split('\n')[0] ?? 'gh pr view failed',
270          }
271    } else {
272      const pr = parsePr(view.stdout)
273      const checks =
274        pr === null ? [] : parseChecks((await gh($, ws.cwd, ['pr', 'checks', '--json', 'bucket,name,workflow'])).stdout)
275      status = { branch, commitSha, pr, checks, fetchedAt: await $.clock.now() }
276    }
277    await update($, ci, () => status)
278    // Newly conflicting needs attention; the pane keeps showing it after.
279    if (status.pr !== null && hasConflict(status.pr) && !hasConflict(prev?.pr)) {
280      $.ui.toast(`PR #${status.pr.number} has merge conflicts to resolve`, { timeoutMs: 10_000 })
281    }
282    return status
283  } catch (err) {
284    const message = err instanceof Error ? err.message : String(err)
285    await update($, ci, old => (old === null || old === undefined ? null : { ...old, error: message }))
286    return prev
287  } finally {
288    await update($, isCiFetching, () => false)
289  }
290}
291
292const ciSummaryText = (status: CiStatus | null) => {
293  if (status === null) return 'CI: not a git branch.'
294  if (status.error !== undefined) return `CI: ${status.error}`
295  if (status.pr === null) return `CI: no PR for ${status.branch}.`
296  const s = summarize(status.checks)
297  const conflict = hasConflict(status.pr) ? ', merge conflicts' : ''
298  return `CI #${status.pr.number}: ${s.pass} pass, ${s.fail} fail, ${s.pending} pending${conflict}`
299}
300
301const ciRefreshAction = async ($: EngineInterface) => {
302  $.ui.toast('Refreshing CI…', { timeoutMs: 2000 })
303  $.ui.toast(ciSummaryText(await refreshCi($, true)))
304}
305
306const openPrAction = async ($: EngineInterface) => {
307  let status = await read($, ci)
308  if (!status?.pr) status = await refreshCi($, true)
309  const pr = status?.pr
310  if (pr === null || pr === undefined) {
311    $.ui.toast(ciSummaryText(status))
312    return
313  }
314  // macOS has `open`; Linux desktops have `xdg-open`; Windows has rundll32's
315  // URL handler (explorer.exe opens it too, but exits 1 when it succeeds).
316  let isOpened = false
317  for (const opener of [['open'], ['xdg-open'], ['rundll32', 'url.dll,FileProtocolHandler']]) {
318    try {
319      isOpened = (await $.process.run([...opener, pr.url], { timeoutMs: 5000 })).exitCode === 0
320    } catch {
321      isOpened = false
322    }
323    if (isOpened) break
324  }
325  $.ui.toast(isOpened ? `Opening PR #${pr.number}` : `Couldn't open ${pr.url}`)
326}
327
328// ---- formatting ---------------------------------------------------------
329
330const barColor = (pct: number) => (pct >= 90 ? 'red' : pct >= 70 ? 'yellow' : 'green')
331
332// 9 -> "9%", 7.5 -> "7.5%".
333const fmtPercent = (pct: number) => `${Number(pct.toFixed(2))}%`
334
335const fmtDuration = (ms: number) => {
336  const total = Math.max(0, Math.floor(ms / 1000))
337  const d = Math.floor(total / 86400)
338  const h = Math.floor((total % 86400) / 3600)
339  const m = Math.floor((total % 3600) / 60)
340  const s = total % 60
341  let out = ''
342  if (d > 0) out += `${d}d `
343  if (d > 0 || h > 0) out += `${h}h `
344  if (d > 0 || h > 0 || m > 0) out += `${m}m `
345  return `${out}${s}s`
346}
347
348const fmtRemaining = (resetsAt: string | undefined, at: number) => {
349  if (resetsAt === undefined) return '-'
350  const secs = Math.floor((Date.parse(resetsAt) - at) / 1000)
351  if (!(secs > 0)) return '0:00'
352  return `${Math.floor(secs / 3600)}:${String(Math.floor((secs % 3600) / 60)).padStart(2, '0')}`
353}
354
355const fmtTokens = (n: number) =>
356  n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n)
357
358const shortPath = (p: string, home: string | undefined, max: number) => {
359  const tilde = home !== undefined && p.startsWith(home) ? `~${p.slice(home.length)}` : p
360  return tilde.length > max ? `…${tilde.slice(-(max - 1))}` : tilde
361}
362
363const effortColor = (effort: string) =>
364  ({ max: 'magenta', xhigh: 'magenta', high: 'cyan', medium: 'blue', low: 'gray' })[effort] ?? 'white'
365
366const windowLabel = (kind: string) => ({ five_hour: '5h', seven_day: '7d' })[kind] ?? kind
367
368// ---- hooks --------------------------------------------------------------
369
370export const register: Register = (on, options) => {
371  const discountOption = toDiscount(options.discountPercent)
372  const gbpOption = options.showGbp === true
373
374  // The discount and GBP rate (£) rows in /config: show a change at once, whether
375  // or not the engine reloads the module with the new options.
376  on('config.set', async ($, e, next) => {
377    const set = await next(e)
378    const isOurs = set.deny === undefined && isOwnedBy(e.provider.plugin, 'sidebar')
379    if (isOurs && e.key.endsWith('.discountPercent')) {
380      await update($, discountChange, () => toDiscount(set.value))
381    }
382    if (isOurs && e.key.endsWith('.showGbp')) {
383      const isOn = set.value === true
384      await update($, gbpChange, () => isOn)
385      if (isOn) await refreshGbpRate($)
386    }
387
388    return set
389  })
390
391  on('session.start', async ($, e, next) => {
392    // The £ rate first, off the start-up path, so nothing below holds it up
393    // or stops it; then hourly, so a session left open picks up the day's
394    // new rate. Nothing is fetched while GBP rate (£) is off.
395    const refreshGbpIfOn = async () => {
396      if ((await read($, gbpChange)) ?? gbpOption) await refreshGbpRate($)
397    }
398    $.clock.after(0, () => void refreshGbpIfOn())
399    $.clock.every(FX_CHECK_MS, () => void refreshGbpIfOn())
400
401    await $.command.register({ name: 'sidebar', description: 'Show or hide the session sidebar pane' })
402    await $.command.register({ name: CMD_GBP, description: 'Show or hide £ beside $ costs in the sidebar' })
403
404    const u = await $.session.usage()
405    const startedAt = await sessionStartedAt($, u.startedAt)
406    await update($, usage, () => toUsage(u, startedAt))
407    const tick = async () => {
408      const t = await $.clock.now()
409      await update($, now, () => t)
410      await refreshModel($)
411    }
412    await tick()
413    await refreshWorkspace($)
414    await refreshFeed($)
415    await refreshFastMode($)
416
417    // Drives the elapsed time and the cache countdown between events.
418    $.clock.every(1000, () => void tick().then(() => refillIfEmpty($)))
419    $.clock.every(FEED_POLL_MS, () => void refreshFeed($))
420
421    // CI: first fetch off the start-up path (gh takes a second or two), then
422    // the refresh policy on every tick.
423    await $.command.register({ name: CMD_CI_REFRESH, description: 'Refresh the sidebar CI status now (ctrl+x r)' })
424    await $.command.register({ name: CMD_OPEN_PR, description: "Open this branch's PR in the browser (ctrl+x o)" })
425    $.clock.after(0, () => void refreshCi($, false))
426    $.clock.every(CI_TICK_MS, () => void refreshCi($, false))
427
428    void $.ui.open({ id: PANE, title: 'Session', columns: PANE_COLUMNS })
429
430    return next(e)
431  })
432
433  // /sidebar toggles the pane: the one way to close it, since the close mark
434  // is ignored (below).
435  on('command.run', { command: 'sidebar' }, async $ => {
436    if ((await $.ui.panes()).some(pane => pane.id === PANE)) {
437      await $.ui.close({ id: PANE })
438      return { text: 'Sidebar closed. /sidebar opens it again.' }
439    }
440    const opened = await $.ui.open({ id: PANE, title: 'Session', columns: PANE_COLUMNS })
441
442    return { text: opened.isPlaced ? 'Sidebar opened.' : `Sidebar not placed: ${opened.reason}` }
443  })
444
445  // /gbp flips the GBP rate (£) setting, saved as if changed in /config. This
446  // plugin's own config.set hook doesn't see its own change, so the pane is
447  // told here.
448  on('command.run', { command: CMD_GBP }, async $ => {
449    const isOn = !((await read($, gbpChange)) ?? gbpOption)
450    // Where there's no /config to save to (claude -p), there's no row: say so
451    // plainly. Any other refusal gives its own reason.
452    let deny: string | undefined
453    try {
454      // The owner can carry a source: `claude --plugin-dir` lists sidebar@inline.
455      const row = (await $.config.list()).find(r => isOwnedBy(r.provider.plugin, 'sidebar') && r.key.endsWith('.showGbp'))
456      if (row === undefined) return { text: "£ not changed: the setting can't be saved here (claude -p has no /config)." }
457      deny = (await $.config.set({ key: row.key, value: isOn })).deny
458    } catch (err) {
459      deny = err instanceof Error ? err.message : String(err)
460    }
461    if (deny !== undefined) return { text: `£ not changed: ${deny}` }
462    await update($, gbpChange, () => isOn)
463    if (!isOn) return { text: `£ off. /${CMD_GBP} turns it on.` }
464    await refreshGbpRate($)
465    const fx = await read($, gbpRate)
466
467    return {
468      text: fx === null
469        ? `£ on. £ rate not fetched yet. /${CMD_GBP} turns it off.`
470        : `£ on. ${fmtRateLine(fx)}. /${CMD_GBP} turns it off.`,
471    }
472  })
473
474  // ctrl+x r / ctrl+x o (and the pane's buttons). Answering with no text means a key
475  // press adds nothing to the conversation; the toast is the feedback.
476  on('command.run', { command: CMD_CI_REFRESH }, async $ => {
477    await ciRefreshAction($)
478
479    return {}
480  })
481
482  // The built-in /fast: re-read the setting as soon as it has toggled.
483  on('command.run', { command: 'fast' }, async ($, e, next) => {
484    const ran = await next(e)
485    await refreshFastMode($)
486
487    return ran
488  })
489
490  // The built-in /model: show the new model as soon as the command returns.
491  on('command.run', { command: 'model' }, async ($, e, next) => {
492    const ran = await next(e)
493    await refreshModel($)
494
495    return ran
496  })
497
498  on('command.run', { command: CMD_OPEN_PR }, async $ => {
499    await openPrAction($)
500
501    return {}
502  })
503
504  // A stray click on the pane's close mark (or its close key) keeps it open.
505  // Answering without next() refuses the close; the plugin's own close and an
506  // unload still go through.
507  on('ui.close', ($, e, next) => {
508    if (e.id === PANE && e.origin.kind === 'person') return { value: undefined }
509
510    return next(e)
511  })
512
513  on('session.measure', async ($, e, next) => {
514    const startedAt = await sessionStartedAt($, (await read($, usage))?.startedAt)
515    await update($, usage, () => toUsage(e, startedAt))
516
517    return next(e)
518  })
519
520  // Every main-loop model request: time it for "api", and keep its token
521  // footprint and effort for the cache and effort chips.
522  on('turn.step', async function* ($, e, next) {
523    const startedAt = await $.clock.now()
524    const result = yield* next(e)
525    if (e.agentId !== undefined) return result
526
527    const at = await $.clock.now()
528    await update($, apiMs, ms => ms + (at - startedAt))
529    if (result.usage !== null) {
530      const u = result.usage
531      const contextTokens =
532        u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens + u.output_tokens
533      const effort = e.effort === undefined ? undefined : String(e.effort)
534      await update($, lastStep, () => ({ at, contextTokens, effort, model: u.model }))
535    }
536
537    return result
538  })
539
540  // Branch, model and cwd can all move during a turn.
541  on('turn.complete', async ($, e, next) => {
542    if (e.agentId === undefined) {
543      await refreshWorkspace($)
544      await refreshFastMode($)
545      // A commit or branch switch this turn is a reason to fetch; off the
546      // turn's end so gh never delays it.
547      $.clock.after(0, () => void refreshCi($, false))
548    }
549
550    return next(e)
551  })
552
553  // A PR Claude just opened: fetch at once rather than wait for the no-PR poll.
554  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
555    const ran = await next(e)
556    if (ran.deny === undefined && ran.isError !== true && isPrCreated(e.command, ran.result.stdout)) {
557      $.clock.after(0, () => void refreshCi($, true))
558    }
559
560    return ran
561  })
562
563  // Claude's own task tools, main loop only (a subagent's list is its own).
564  on('tool.call', { tool: 'TodoWrite' }, async ($, e, next) => {
565    const ran = await next(e)
566    if (e.agentId === undefined && ran.deny === undefined && ran.isError !== true) {
567      await update($, claudeTasks, () => applyTodoWrite(e.todos))
568    }
569
570    return ran
571  })
572
573  on('tool.call', { tool: 'TaskCreate' }, async ($, e, next) => {
574    const ran = await next(e)
575    if (e.agentId === undefined && ran.deny === undefined && ran.isError !== true) {
576      const { id, subject } = ran.result.task
577      await update($, claudeTasks, list => applyTaskCreate(list, id, subject))
578    }
579
580    return ran
581  })
582
583  on('tool.call', { tool: 'TaskUpdate' }, async ($, e, next) => {
584    const ran = await next(e)
585    if (e.agentId === undefined && ran.deny === undefined && ran.isError !== true && ran.result.success) {
586      await update($, claudeTasks, list => applyTaskUpdate(list, e))
587    }
588
589    return ran
590  })
591
592  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
593    const { Box, Button, Text } = $.ui.resolve(e)
594    const [u, step, api, ws, at, prices, claude, ciStatus, isFetching, isFast, fed, changed, fx, gbpChanged] = await Promise.all([
595      read($, usage),
596      read($, lastStep),
597      read($, apiMs),
598      read($, workspace),
599      read($, now),
600      read($, pricing),
601      read($, claudeTasks),
602      read($, ci),
603      read($, isCiFetching),
604      read($, isFastMode),
605      read($, feed),
606      read($, discountChange),
607      read($, gbpRate),
608      read($, gbpChange),
609    ])
610    const discount = changed ?? discountOption
611    const isGbp = gbpChanged ?? gbpOption
612    // The rate to show £ at; undefined when GBP rate (£) is off or none is fetched.
613    const rate = isGbp ? fx?.rate : undefined
614    // £ after a $ figure, starred like it when the discount is off it.
615    const Gbp = ({ usd, isDiscounted = false }: { usd: number; isDiscounted?: boolean }) =>
616      rate === undefined ? null : (
617        <Text>
618          <Text color="yellow"> {fmtGbp(usd, rate)}</Text>
619          {isDiscounted && <Text dimColor>*</Text>}
620        </Text>
621      )
622    const listCost = u?.costUsd ?? 0
623    const home = ws?.home
624    const effort = fed?.effort ?? step?.effort
625    const pathWidth = Math.max(16, e.props.bodyColumns - 6)
626
627    const Bar = ({ pct, width }: { pct: number; width: number }) => {
628      const filled = Math.min(width, Math.floor((pct * width) / 100))
629      return (
630        <Text>
631          <Text color={barColor(pct)}>{'█'.repeat(filled)}{'░'.repeat(width - filled)}</Text> {Math.round(pct)}%
632        </Text>
633      )
634    }
635
636    const Heading = ({ color, children }: { color: string; children: string }) => (
637      <Text bold color={color}>── {children} ──</Text>
638    )
639
640    const cacheChip = () => {
641      const view = resolveCache(fed, step, CACHE_TTL)
642      const model = step?.model ?? ws?.model
643      if (view === null || model === undefined) return null
644      const { tokens, ttl } = view
645      const left = view.expiresAt - at
646      const toks = fmtTokens(tokens)
647      const listPrice = recacheCost(prices, model, tokens, ttl, isFast)
648      const cost = listPrice === undefined ? undefined : discounted(listPrice, discount)
649      const label = left > 0 ? `cache warm ${Math.floor(left / 60000)}m ↻` : 'cache cold ↻'
650      const amount = cacheAmount({
651        cost,
652        isDiscounted: discount > 0,
653        toks,
654        rate,
655        room: e.props.bodyColumns - label.length,
656      })
657      return left > 0 ? (
658        <Text>
659          <Text dimColor>cache </Text>
660          <Text color="green">warm</Text> <Text dimColor>{Math.floor(left / 60000)}m</Text>{' '}
661          <Text color={cost === undefined ? 'gray' : costColor(cost)}>↻{amount}</Text>
662        </Text>
663      ) : (
664        <Text>
665          <Text dimColor>cache </Text>
666          <Text color="red">cold ↻{amount}</Text>
667        </Text>
668      )
669    }
670
671    const taskRow = (t: TaskLine) => (
672      <Text wrap="truncate-end" color={taskColor(t.status)} dimColor={isTaskDim(t.status)}>
673        {taskIcon(t.status)} {t.title}
674      </Text>
675    )
676
677    const checkRow = (c: CiCheck) => (
678      <Text wrap="truncate-end">
679        {'  '}
680        <Text color={c.bucket === 'fail' ? 'red' : 'yellow'}>{c.bucket === 'fail' ? '✗' : '◔'}</Text> {c.name}
681        {c.workflow !== undefined && c.workflow !== c.name && <Text dimColor> ({c.workflow})</Text>}
682      </Text>
683    )
684
685    const ciSection = () => {
686      if (ciStatus === null || ciStatus.pr === null) return null
687      const pr = ciStatus.pr
688      const s = summarize(ciStatus.checks)
689      return (
690        <Box flexDirection="column">
691          <Text> </Text>
692          <Heading color="green">CI</Heading>
693          <Text wrap="truncate-end">
694            <Text dimColor>#{pr.number}</Text> {pr.title}
695          </Text>
696          <Text>
697            {s.pass > 0 && <Text color="green">✓ {s.pass}  </Text>}
698            {s.fail > 0 && <Text color="red">✗ {s.fail}  </Text>}
699            {s.pending > 0 && <Text color="yellow">◔ {s.pending}  </Text>}
700            {s.cancel > 0 && <Text color="yellow">⊘ {s.cancel}  </Text>}
701            {s.skip > 0 && <Text dimColor>⊝ {s.skip}</Text>}
702            {ciStatus.checks.length === 0 && <Text dimColor>no checks yet</Text>}
703          </Text>
704          {hasConflict(pr) && (
705            <Text bold color="red" wrap="truncate-end">
706              ✗ merge conflicts: resolve to merge
707            </Text>
708          )}
709          {pr.mergeable === 'MERGEABLE' && <Text dimColor>✓ no merge conflicts</Text>}
710          {pr.mergeable === 'UNKNOWN' && <Text dimColor>◔ checking for merge conflicts</Text>}
711          {notableChecks(ciStatus.checks).map(checkRow)}
712          {ciStatus.error !== undefined && (
713            <Text color="red" wrap="truncate-end">! {ciStatus.error}</Text>
714          )}
715          <Text dimColor>
716            {isFetching ? 'refreshing…' : `checked ${fmtDuration(at - ciStatus.fetchedAt)} ago`}
717          </Text>
718          <Box flexDirection="row">
719            <Button key="ci-refresh" label="refresh" onPress={() => void ciRefreshAction($)} />
720            <Text> </Text>
721            <Button key="open-pr" label="open PR" onPress={() => void openPrAction($)} />
722          </Box>
723          <Box flexDirection="row">
724            <Text dimColor>^X r refresh  ^X o open PR</Text>
725          </Box>
726        </Box>
727      )
728    }
729
730    const rateRow = (r: RateWindow) => (
731      <Text>
732        <Text dimColor>{windowLabel(r.kind).padEnd(5)}</Text>
733        <Bar pct={r.percentUsed} width={12} /> <Text dimColor>{fmtRemaining(r.resetsAt, at)}</Text>
734      </Text>
735    )
736
737    return (
738      <Box flexDirection="column">
739        <Heading color="magenta">Model</Heading>
740        <Text color="cyan">{ws?.model ?? step?.model ?? '?'}</Text>
741        {isFast && (
742          <Text bold color="red" wrap="truncate-end">
743            ⚡ FAST MODE ON: /fast to turn off
744          </Text>
745        )}
746        <Text>
747          <Text dimColor>ctx  </Text>
748          <Bar pct={u?.contextPercent ?? 0} width={12} />
749        </Text>
750        {(u?.rateLimits ?? []).map(rateRow)}
751        {cacheChip()}
752
753        <Text> </Text>
754        <Heading color="yellow">Session</Heading>
755        <Text>
756          <Text dimColor>cost  </Text>
757          <Text color="yellow">${discounted(listCost, discount).toFixed(2)}</Text>
758          {discount > 0 && <Text dimColor>*</Text>}
759          <Gbp usd={discounted(listCost, discount)} isDiscounted={discount > 0} />
760        </Text>
761        <Text>
762          <Text dimColor>time  </Text>
763          {elapsedText(isKnownStart(fed?.startedAt) ? fed.startedAt : u?.startedAt, at, fmtDuration)}
764        </Text>
765        <Text>
766          <Text dimColor>api   </Text>
767          {fmtDuration(fed?.apiDurationMs ?? api)}
768        </Text>
769        {effort !== undefined && (
770          <Text>
771            <Text dimColor>eff   </Text>
772            <Text color={effortColor(effort)}>{effort}</Text>
773            {isFast && <Text color="yellow"> ⚡</Text>}
774          </Text>
775        )}
776        {ws !== null && (
777          <Box flexDirection="column">
778            <Box flexDirection="row">
779              <Text dimColor>sid   </Text>
780              <Button
781                key="copy-sid"
782                label="copy"
783                onPress={press => void $.ui.copy({ text: ws.sessionId, surface: press.surface })}
784              />
785            </Box>
786            <Text wrap="truncate-end">{ws.sessionId}</Text>
787          </Box>
788        )}
789
790        {ws !== null && (
791          <Box flexDirection="column">
792            <Text> </Text>
793            <Heading color="blue">Workspace</Heading>
794            {ws.repoName !== undefined && (
795              <Text>
796                <Text dimColor>repo  </Text>
797                {ws.repoName}
798                {ws.isWorktree && <Text dimColor> (wt)</Text>}
799              </Text>
800            )}
801            <Text>
802              <Text dimColor>cwd   </Text>
803              {shortPath(ws.cwd, home, pathWidth)}
804            </Text>
805            {ws.root !== ws.cwd && (
806              <Text>
807                <Text dimColor>proj  </Text>
808                {shortPath(ws.root, home, pathWidth)}
809              </Text>
810            )}
811            {ws.branch !== undefined && ws.branch !== '' && (
812              <Text>
813                <Text dimColor>br    </Text>
814                {ws.branch}
815              </Text>
816            )}
817            {(fed?.addedDirs.length ?? 0) > 0 && <Text dimColor>added:</Text>}
818            {(fed?.addedDirs ?? []).map(d => (
819              <Text wrap="truncate-start">  {shortPath(d, home, e.props.bodyColumns - 2)}</Text>
820            ))}
821          </Box>
822        )}
823
824        {ciSection()}
825
826        {claude.length > 0 && (
827          <Box flexDirection="column">
828            <Text> </Text>
829            <Heading color="cyan">Tasks</Heading>
830            {claude.map(taskRow)}
831          </Box>
832        )}
833
834        {(discount > 0 || isGbp) && (
835          <Box flexDirection="column">
836            <Text> </Text>
837            <Heading color="yellow">Cost</Heading>
838            {discount > 0 && (
839              <Box flexDirection="column">
840                <Text wrap="truncate-end">* {fmtPercent(discount)} discount off list prices</Text>
841                <Text>
842                  <Text dimColor>list  </Text>${listCost.toFixed(2)}
843                  <Gbp usd={listCost} />
844                </Text>
845                <Text dimColor wrap="wrap">Change it in /config: Billing discount (%)</Text>
846              </Box>
847            )}
848            {isGbp && (
849              <Text dimColor wrap="wrap">
850                {fx === null ? '£ rate not fetched yet' : fmtRateLine(fx)}
851              </Text>
852            )}
853          </Box>
854        )}
855      </Box>
856    )
857  })
858}
859
hooks/ci.ts 87 lines
1import type { CiCheck, CiPr, CiStatus } from '../types'
2
3// The branch's PR and checks, from gh, and when to fetch them again. The mod
4// runs gh itself on a timer, so there is no cache file or lock.
5
6export const parsePr = (json: string): CiPr | null => {
7  try {
8    const pr: unknown = JSON.parse(json)
9    if (typeof pr !== 'object' || pr === null) return null
10    const { number, title, url, createdAt, mergeable } = pr as Record<string, unknown>
11    return typeof number === 'number' && typeof title === 'string' && typeof url === 'string'
12      ? {
13          number,
14          title,
15          url,
16          createdAt: typeof createdAt === 'string' ? createdAt : undefined,
17          mergeable: typeof mergeable === 'string' ? mergeable : undefined,
18        }
19      : null
20  } catch {
21    return null
22  }
23}
24
25// `gh pr checks` exits non-zero while checks fail or pend, so its stdout is
26// read whatever the exit code.
27export const parseChecks = (json: string): CiCheck[] => {
28  try {
29    const rows: unknown = JSON.parse(json)
30    if (!Array.isArray(rows)) return []
31    return rows.flatMap(r =>
32      typeof r?.bucket === 'string' && typeof r?.name === 'string'
33        ? [{ bucket: r.bucket, name: r.name, workflow: typeof r.workflow === 'string' && r.workflow !== '' ? r.workflow : undefined }]
34        : [],
35    )
36  } catch {
37    return []
38  }
39}
40
41// gh's way of saying the branch has no PR: an expected state, not an error.
42export const isNoPrError = (stderr: string) => /no (open )?pull requests? (found|associated)/i.test(stderr)
43
44// When to fetch again:
45//   nothing fetched for this branch -> now
46//   local commit moved              -> now (CI reports on another sha)
47//   any check pending               -> every 60s
48//   no PR                           -> every 300s (one may be opened elsewhere)
49//   GitHub still working out merge  -> every 30s (mergeable UNKNOWN)
50//   PR under 10 min old, no checks  -> every 30s (workflows still registering)
51//   otherwise                       -> every 300s (the base can move on and
52//                                      conflict with no local change)
53export const shouldFetch = (ci: CiStatus | null, branch: string, commitSha: string, now: number) => {
54  if (ci === null || ci.branch !== branch) return true
55  if (commitSha !== '' && ci.commitSha !== commitSha) return true
56  const age = now - ci.fetchedAt
57  if (ci.checks.some(c => c.bucket === 'pending')) return age >= 60_000
58  if (ci.pr === null) return age >= 300_000
59  if (ci.pr.mergeable === 'UNKNOWN') return age >= 30_000
60  if (ci.checks.length === 0) {
61    const prAge = ci.pr.createdAt === undefined ? Infinity : now - Date.parse(ci.pr.createdAt)
62    if (prAge < 600_000) return age >= 30_000
63  }
64  return age >= 300_000
65}
66
67// The PR can't merge until its conflicts with the base are resolved.
68export const hasConflict = (pr: CiPr | null | undefined) => pr?.mergeable === 'CONFLICTING'
69
70export type CiSummary = { pass: number; fail: number; pending: number; cancel: number; skip: number }
71
72export const summarize = (checks: readonly CiCheck[]): CiSummary => ({
73  pass: checks.filter(c => c.bucket === 'pass').length,
74  fail: checks.filter(c => c.bucket === 'fail').length,
75  pending: checks.filter(c => c.bucket === 'pending').length,
76  cancel: checks.filter(c => c.bucket === 'cancel').length,
77  skip: checks.filter(c => c.bucket === 'skipping').length,
78})
79
80// The checks worth naming: failures and in-flight jobs, at most six.
81export const notableChecks = (checks: readonly CiCheck[]) =>
82  checks.filter(c => c.bucket === 'fail' || c.bucket === 'pending').slice(0, 6)
83
84// A Bash call that really opened a PR prints its URL (a --dry-run or --help doesn't).
85export const isPrCreated = (command: string, stdout: string) =>
86  command.includes('gh pr create') && /https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/.test(stdout)
87
hooks/feed.ts 69 lines
1import type { Feed, LastStep } from '../types'
2
3// The status line JSON statusline-feed.sh saves per session, at
4// ~/.claude/state/statusline/<session_id>.json.
5export const FEED_DIR = '.claude/state/statusline'
6
7const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined)
8
9// savedAt, the file's modified time, dates the JSON's durations.
10export const parseFeed = (json: string, savedAt?: number): Feed | null => {
11  let raw: unknown
12  try {
13    raw = JSON.parse(json)
14  } catch {
15    return null
16  }
17  if (typeof raw !== 'object' || raw === null) return null
18  const j = raw as {
19    fast_mode?: unknown
20    effort?: { level?: unknown }
21    prompt_cache?: { ttl?: unknown; warm?: unknown; expires_at?: unknown; recache_tokens_if_cold?: unknown }
22    workspace?: { added_dirs?: unknown }
23    cost?: { total_api_duration_ms?: unknown; total_duration_ms?: unknown }
24  }
25  const cache = j.prompt_cache ?? {}
26  const durationMs = num(j.cost?.total_duration_ms)
27  const expiresAt = num(cache.expires_at)
28  const dirs = j.workspace?.added_dirs
29  return {
30    isFastMode: typeof j.fast_mode === 'boolean' ? j.fast_mode : undefined,
31    cacheTtl: cache.ttl === '5m' || cache.ttl === '1h' ? cache.ttl : undefined,
32    isCacheWarm: typeof cache.warm === 'boolean' ? cache.warm : undefined,
33    // The status line gives seconds.
34    cacheExpiresAt: expiresAt === undefined ? undefined : expiresAt * 1000,
35    recacheTokens: num(cache.recache_tokens_if_cold),
36    effort: typeof j.effort?.level === 'string' ? j.effort.level : undefined,
37    apiDurationMs: num(j.cost?.total_api_duration_ms),
38    // Claude Code's session duration counts time before a resume, so the
39    // start it implies is the real one; dated from the save, it stays right
40    // between status line updates.
41    startedAt: savedAt === undefined || durationMs === undefined ? undefined : savedAt - durationMs,
42    addedDirs: Array.isArray(dirs) ? dirs.filter((d): d is string => typeof d === 'string') : [],
43  }
44}
45
46const TTL_MS = { '5m': 5 * 60_000, '1h': 60 * 60_000 } as const
47
48export type CacheView = { tokens: number; expiresAt: number; ttl: '5m' | '1h' }
49
50// What the cache chip shows, from the best source there is:
51//   1. the status line's prompt_cache;
52//   2. this process's last main-loop response, plus the TTL.
53// Null when neither has a figure: a fresh session before its first reply, or
54// a resumed one before this process's first request (prompt_cache is null
55// then, and mods can't hook SessionStart, which has the resume figures).
56export const resolveCache = (
57  feed: Feed | null,
58  step: LastStep | null,
59  assumedTtl: '5m' | '1h',
60): CacheView | null => {
61  const ttl = feed?.cacheTtl ?? assumedTtl
62  if (feed?.recacheTokens !== undefined && feed.cacheExpiresAt !== undefined) {
63    // A cold cache reads as expired now, whatever expires_at says.
64    return { tokens: feed.recacheTokens, expiresAt: feed.isCacheWarm === false ? 0 : feed.cacheExpiresAt, ttl }
65  }
66  if (step !== null) return { tokens: step.contextTokens, expiresAt: step.at + TTL_MS[ttl], ttl }
67  return null
68}
69
hooks/fx.ts 95 lines
1import type { GbpRate } from '../types'
2
3// The European Central Bank's daily reference rate, via Frankfurter: free,
4// no key. It's published once a working day, about 3pm UK time, so a rate
5// is fetched again once it's 6 hours old: at most 4 small requests a day.
6// Each session checks hourly, which reads the saved rate and fetches only
7// when it's due, and a failed try waits an hour, across all sessions.
8export const FX_URL = 'https://api.frankfurter.dev/v1/latest?from=USD&to=GBP'
9const HOUR_MS = 60 * 60 * 1000
10export const FX_MAX_AGE_MS = 6 * HOUR_MS
11export const FX_CHECK_MS = HOUR_MS
12export const FX_RETRY_MS = HOUR_MS
13
14const isRate = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value) && value > 0
15
16// Frankfurter's answer, {"date":"2026-10-13","rates":{"GBP":0.75492},...},
17// as a rate; anything else undefined, so a bad reply never shows £.
18export const parseRate = (text: string, fetchedAt: number): GbpRate | undefined => {
19  try {
20    const body = JSON.parse(text)
21    const rate = body?.rates?.GBP
22    const date = body?.date
23    return isRate(rate) && typeof date === 'string' ? { rate, date, fetchedAt } : undefined
24  } catch {
25    return undefined
26  }
27}
28
29// A saved rate as read back from $.store, or undefined when it isn't one.
30export const toRate = (value: unknown): GbpRate | undefined => {
31  const v = value as Partial<GbpRate> | null | undefined
32  return v != null && isRate(v.rate) && typeof v.date === 'string' && typeof v.fetchedAt === 'number'
33    ? { rate: v.rate, date: v.date, fetchedAt: v.fetchedAt }
34    : undefined
35}
36
37export const isRateStale = (saved: unknown, at: number) => {
38  const rate = toRate(saved)
39  if (rate === undefined) return true
40  // A fetch "in the future" means the clock moved back: fetch again.
41  const age = at - rate.fetchedAt
42  return age < 0 || age >= FX_MAX_AGE_MS
43}
44
45// Whether a fetch was tried (by this or another session) too recently to try
46// again. A try "in the future" means the clock moved back: try again.
47export const isRecentTry = (triedAt: unknown, at: number) => {
48  if (typeof triedAt !== 'number') return false
49  const age = at - triedAt
50  return age >= 0 && age < FX_RETRY_MS
51}
52
53export const fmtGbp = (usd: number, rate: number) => `£${(usd * rate).toFixed(2)}`
54
55const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
56
57// 1st, 2nd, 3rd, 4th ... 11th, 12th, 13th ... 21st, 22nd, 23rd ... 31st.
58const ordinal = (day: number) => {
59  const isTeen = day >= 11 && day <= 13
60  const suffix = isTeen ? 'th' : ({ 1: 'st', 2: 'nd', 3: 'rd' } as Record<number, string>)[day % 10] ?? 'th'
61  return `${day}${suffix}`
62}
63
64// "2026-10-13" -> "13th Oct"; anything else as given.
65export const fmtRateDate = (date: string) => {
66  const m = /^\d{4}-(\d{2})-(\d{2})$/.exec(date)
67  const month = m ? MONTHS[Number(m[1]) - 1] : undefined
68  return m && month ? `${ordinal(Number(m[2]))} ${month}` : date
69}
70
71// The rate as the Cost section and /gbp give it: "£ rate: 0.7538 (ECB, 14th Oct)".
72export const fmtRateLine = (fx: GbpRate) => `£ rate: ${fx.rate.toFixed(4)} (ECB, ${fmtRateDate(fx.date)})`
73
74// The cache chip's figure: the rebuild cost ($, with £ when there's a rate
75// and room for it on the line) and its size in tokens; tokens alone when
76// there's no cost. `room` is the columns left after the chip's label.
77export const cacheAmount = ({
78  cost,
79  isDiscounted,
80  toks,
81  rate,
82  room,
83}: {
84  cost: number | undefined
85  isDiscounted: boolean
86  toks: string
87  rate: number | undefined
88  room: number
89}) => {
90  if (cost === undefined) return toks
91  const usd = `$${cost.toFixed(2)}${isDiscounted ? '*' : ''}`
92  const withGbp = rate === undefined ? undefined : `${usd} ${fmtGbp(cost, rate)}${isDiscounted ? '*' : ''} (${toks})`
93  return withGbp !== undefined && withGbp.length <= room ? withGbp : `${usd} (${toks})`
94}
95
hooks/owner.ts 6 lines
1// Whether a /config row's owner (`provider.plugin`) is this plugin. The owner
2// carries where the plugin came from: `sidebar@pt-mods` installed from a
3// marketplace, `sidebar@inline` under `claude --plugin-dir`; tests use the
4// bare name.
5export const isOwnedBy = (owner: string, plugin: string) => owner === plugin || owner.startsWith(`${plugin}@`)
6
hooks/paths.ts 6 lines
1// Windows has no HOME by default; USERPROFILE is its home folder.
2export const homeDir = (home: string | undefined, userProfile: string | undefined) => home || userProfile
3
4// The last part of a path, split on either separator: Windows paths use `\`.
5export const baseName = (path: string) => path.split(/[\\/]/).at(-1)
6
hooks/pricing.ts 49 lines
1import type { Price } from '../types'
2
3// Reads ~/.claude/state/model-pricing.tsv (optional; see README.md), tab
4// separated, USD per million tokens:
5//   model_id, input, write_5m, write_1h, cache_read, output, fast_input
6export const parsePricing = (tsv: string): Price[] =>
7  tsv.split('\n').flatMap(line => {
8    if (line.startsWith('#') || line.startsWith('model_id')) return []
9    const [id, inp, w5, w1, , , fast] = line.split('\t')
10    const input = Number(inp)
11    const write5m = Number(w5)
12    const write1h = Number(w1)
13    if (!id || ![input, write5m, write1h].every(Number.isFinite)) return []
14    const fastInput = fast === undefined || fast.trim() === '' ? undefined : Number(fast)
15    return [{ id, input, write5m, write1h, fastInput: Number.isFinite(fastInput) ? fastInput : undefined }]
16  })
17
18// Dollar cost of re-writing the cache if the next submit lands cold. The
19// model matches by longest id prefix, so dated or suffixed ids resolve
20// ("claude-haiku-4-5-20251001", "claude-opus-5-5[1m]"). In fast mode the
21// cache-write multiplier stacks on the fast input price, so the write rate
22// scales by fast_input / input.
23export const recacheCost = (
24  prices: Price[],
25  model: string,
26  tokens: number,
27  ttl: '5m' | '1h',
28  isFast = false,
29) => {
30  const id = model.replace(/\[.*$/, '')
31  const best = prices
32    .filter(p => id === p.id || id.startsWith(`${p.id}-`))
33    .sort((a, b) => b.id.length - a.id.length)[0]
34  if (best === undefined) return undefined
35  const write = ttl === '1h' ? best.write1h : best.write5m
36  const rate = isFast && best.fastInput !== undefined && best.input > 0 ? (write * best.fastInput) / best.input : write
37  return (tokens * rate) / 1_000_000
38}
39
40// The discountPercent setting as a usable rate: 0 to 100, anything else 0.
41export const toDiscount = (value: unknown) =>
42  typeof value === 'number' && Number.isFinite(value) ? Math.min(100, Math.max(0, value)) : 0
43
44// A list-price figure (Claude Code's session cost, a rebuild estimate) after
45// the billing discount.
46export const discounted = (usd: number, percent: number) => usd * (1 - percent / 100)
47
48export const costColor =(usd: number) => (usd >= 5 ? 'red' : usd >= 1 ? 'yellow' : 'gray')
49
hooks/session.ts 9 lines
1// A session start time worth timing from, epoch ms. A usage reading can land
2// before session.start has stored one, and a resumed session can report 0;
3// timed from 0, the elapsed time reads as the years since 1970.
4export const isKnownStart = (t: number | undefined): t is number => t !== undefined && t > 0
5
6// The elapsed time, or '-' while the start isn't known.
7export const elapsedText = (startedAt: number | undefined, now: number, fmt: (ms: number) => string) =>
8  isKnownStart(startedAt) && now >= startedAt ? fmt(now - startedAt) : '-'
9
hooks/tasks.ts 34 lines
1import type { TaskLine } from '../types'
2
3// Claude's own task tools, replayed from their tool calls: the mod has no
4// way to ask for the list, so it keeps its own copy.
5
6// TodoWrite sends the whole list every time.
7export const applyTodoWrite = (todos: readonly { content: string; status: string }[]): TaskLine[] =>
8  todos.map((t, i) => ({ id: String(i), title: t.content, status: t.status }))
9
10export const applyTaskCreate = (list: TaskLine[], id: string, subject: string): TaskLine[] => [
11  ...list.filter(t => t.id !== id),
12  { id, title: subject, status: 'pending' },
13]
14
15export const applyTaskUpdate = (
16  list: TaskLine[],
17  change: { taskId: string; subject?: string; status?: string },
18): TaskLine[] =>
19  change.status === 'deleted'
20    ? list.filter(t => t.id !== change.taskId)
21    : list.map(t =>
22        t.id === change.taskId
23          ? { ...t, title: change.subject ?? t.title, status: change.status ?? t.status }
24          : t,
25      )
26
27export const taskIcon = (status: string) =>
28  ({ completed: '✓', in_progress: '→', blocked: '✗', cancelled: '–' })[status] ?? ' '
29
30export const taskColor = (status: string) =>
31  ({ in_progress: 'green', blocked: 'red' })[status]
32
33export const isTaskDim = (status: string) => status === 'completed' || status === 'cancelled'
34
types/index.d.ts 111 lines
1export type RateWindow = { kind: string; percentUsed: number; resetsAt?: string }
2
3// What session.measure / $.session.usage() last reported.
4export type Usage = {
5  contextPercent?: number
6  rateLimits: RateWindow[]
7  costUsd?: number
8  startedAt: number
9}
10
11// The main loop's most recent model response, for the prompt-cache chip.
12export type LastStep = {
13  at: number
14  // Tokens the next request re-sends (and re-writes if the cache went cold).
15  contextTokens: number
16  effort?: string
17  model: string
18}
19
20// One row of ~/.claude/state/model-pricing.tsv, USD per million tokens.
21// fastInput is absent for a model with no fast mode.
22export type Price = { id: string; input: number; write5m: number; write1h: number; fastInput?: number }
23
24// One row of the Tasks section: pending, in_progress or completed.
25export type TaskLine = { id: string; title: string; status: string }
26
27// What statusline-feed.sh saved from the status line's JSON for this session:
28// the facts the mod API doesn't expose. Each is absent when the JSON had none.
29export type Feed = {
30  isFastMode?: boolean
31  cacheTtl?: '5m' | '1h'
32  isCacheWarm?: boolean
33  // Epoch milliseconds.
34  cacheExpiresAt?: number
35  recacheTokens?: number
36  effort?: string
37  // The session's API time, resumed sessions included.
38  apiDurationMs?: number
39  // When the session started, epoch ms, resumed sessions included.
40  startedAt?: number
41  addedDirs: string[]
42}
43
44// gh pr checks' bucket: pass, fail, pending, skipping, cancel.
45export type CiCheck = { bucket: string; name: string; workflow?: string }
46
47export type CiPr = {
48  number: number
49  title: string
50  url: string
51  createdAt?: string
52  // gh's mergeable: MERGEABLE, CONFLICTING, or UNKNOWN while GitHub works it out.
53  mergeable?: string
54}
55
56// The branch's PR and its checks, fetched straight from gh by the mod.
57export type CiStatus = {
58  branch: string
59  commitSha: string
60  pr: CiPr | null
61  checks: CiCheck[]
62  fetchedAt: number
63  // Set when the last fetch failed (auth, network); the data is the last good one.
64  error?: string
65}
66
67export type Workspace = {
68  sessionId: string
69  model: string
70  cwd: string
71  root: string
72  branch?: string
73  commitSha?: string
74  isWorktree: boolean
75  repoName?: string
76  isGit: boolean
77  home?: string
78}
79
80// USD to GBP, from the ECB's daily rate: `date` is the rate's own day,
81// `fetchedAt` when it was fetched (epoch ms).
82export type GbpRate = {
83  rate: number
84  date: string
85  fetchedAt: number
86}
87
88declare module 'claude-code' {
89  interface PluginState {
90    sidebar: {
91      usage: Usage | null
92      lastStep: LastStep | null
93      apiMs: number
94      workspace: Workspace | null
95      pricing: Price[]
96      claudeTasks: TaskLine[]
97      ci: CiStatus | null
98      isCiFetching: boolean
99      isFastMode: boolean
100      feed: Feed | null
101      // The billing discount, percent, once changed in /config this session.
102      discountChange: number | null
103      // The USD to GBP rate in use; null until one is fetched or read back.
104      gbpRate: GbpRate | null
105      // The GBP rate (£) setting, once changed in /config this session.
106      gbpChange: boolean | null
107      now: number
108    }
109  }
110}
111