SLOPSHOPPER

ctui

A mod for Claude Code: a docked sidebar with git, context, limits, todo, skills, MCP and agent sections, plus agent and shell toasts and a /ctui settings menu…

panespinnerrowsguardcommandtoast
★ 1v1.0.3MITupdated 2026-10-24a1exk-dev/claude-tui/ctui
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · ctui
│ ┃ sidebar ✕ ╭────────────────────────────────────────────╮ │ ┃ ┃ │ ctui │ │ ┃ /work/app ┃ fix the failing │ ctui needs Claude Code 2.1.292 or later; │ │ ┃ ┃ │ this is 2.1.289 │ │ ┃ ┃ ╰────────────────────────────────────────────╯ │ ┃ ┃ │ ┃ ════════════════════════════════════════ │ ┃ ════════════ ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ ▣ client module ./press.tsx▣ client module ← Edit src/auth.ts │ ┃ ⏺ Bash(bun test) │ ┃ ━━━━━━━━━━━━━━━━━━━━━━──────────────── ⎿ 3 pass, 1 fail │ ┃ ─────── 49% │ ┃ 97,400 / 200k tokens ⟨Claude Code's own drawing⟩ │ ┃ │ ┃ ──────────────────────────────────────── ✻ Worked for 42s · done 4:20 PM │ ┃ ──────────── │ ┃ ▣ client module ./press.tsx▣ client module › /ctui │ ┃ ⎿ ctui: Can't open the ctui menu. Change ctui settings in /config │ ┃ 5h │ ┃ ━━━━━━━━━━━━────────────────────────── │ ┃ ─ 31% │ ┃ resets in 59m │ ┃ │ ┃ ──────────────────────────────────────── │ ┃ ──────────── ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · sidebar
/work/app ════════════════════════════════════════════════════ ▣ client module ./press.tsx▣ client module ./foldrow.tsx ━━━━━━━━━━━━━━━━━━━━━━─────────────────────── 49% 97,400 / 200k tokens ──────────────────────────────────────────────────── ▣ client module ./press.tsx▣ client module ./foldrow.tsx 5h ━━━━━━━━━━━━─────────────────────────── 31% resets in 59m ──────────────────────────────────────────────────── ▣ client module ./press.tsx▣ client module ./foldrow.tsx no task tools in this session ──────────────────────────────────────────────────── ▣ client module ./press.tsx▣ client module ./foldrow.tsx ↓ more claude cli: 2.1.289 │ ctui: local, inherit
Your message
┃ ┃ fix the failing auth test and add an audit log call ┃ ┃ ┃
Claude's reply
⟨Claude Code's own drawing⟩
Tool row
← Edit src/auth.ts
README

ctui

ctui is a mod for Claude Code: a plugin that changes how Claude Code looks and behaves. It docks a sidebar beside the transcript with git, context, limits, todo, skills, MCP, and agents-and-shells sections, and it restyles the lines under the prompt input. It also raises short toasts when a subagent or a background shell starts, finishes, or fails.

The sidebar with every section folded

The sidebar with every section expanded

Needs Claude Code 2.1.292 or later. Tested with 2.1.300.

Install

/plugin marketplace add a1exk-dev/claude-tui
/plugin install ctui@claude-tui

The sidebar docks only in fullscreen: set "tui": "fullscreen" in settings.json or start Claude Code with CLAUDE_CODE_NO_FLICKER=1, in a terminal 110 or more columns wide. Below that, or on the main screen, ctui draws no sidebar; the toasts and the restyled rows still show.

Examples

Follow a multi-step job in the todo section. Ask for several things at once, such as "rename a.txt to notes.txt, then create a README.md, then tell me how many lines each file has". With Task tools on (the default), Claude makes one task per outcome first, and the todo section lists them: a spinner on the one in progress, a check on each one done.

Watch background work. Ask Claude to run something in the background, such as "run npm test in the background", or to start a background subagent. A toast says it started ($ npm test started in background), a row under Agents & shells shows it running with its elapsed time, and a second toast says when it is done or failed.

Switch the sidebar's theme. Type /ctui, choose Themes, type part of a name to narrow the list, and press Enter on a theme. The sidebar takes its colors at once, and every new session keeps it.

Terminal setup

tmux. Inside tmux, Claude Code draws with the 256-color palette even when your terminal supports true color, so sidebar backgrounds and theme colors turn into the nearest grey. Turn true color back on in the env block of your user settings.json, then restart Claude Code:

{
  "env": {
    "CLAUDE_CODE_TMUX_TRUECOLOR": "1"
  }
}

Ghostty with a transparent background. With background-opacity below 1, Ghostty draws cells that have their own background color fully opaque, so the sidebar looks like a solid, lighter panel beside the see-through transcript. Add this to ~/.config/ghostty/config and reload Ghostty, so colored cells take the same opacity:

background-opacity-cells = true

Configuration

Every setting, the sidebar sections and their options, an example Claude Code theme with the colors ctui uses, and how to set the main background in your terminal are in the configuration docs.

Settings

/ctui opens ctui's settings menu at once, even while Claude is replying.

The Plugins screen of the /ctui menu

The Themes screen of the /ctui menu

  • Plugins lists the sidebar sections in their order: x turns the focused one on or off, k/j move it up or down (saved on the menu's next change, opening a plugin, Esc, close, /ctui or session end), and Enter opens its settings.
  • Themes lists inherit (the default, which follows your Claude Code theme) and every bundled theme by name, with a filter field: type to narrow the list, pick to switch.

Esc goes back one level, and closes the menu at the top. If another command already holds /ctui, ctui says so in a toast once per session; change its settings in /config instead. Each section and the toasts also have a row in /config. Settings are saved to your user settings.json, so a change applies to every session.

Task tools

The todo section shows Claude's task list. Claude Code gives Claude the Task tools (TaskCreate, TaskList, TaskUpdate) by default only on some models; Opus 5.x and Sonnet 5.x don't get them. So ctui turns them on for each session by setting CLAUDE_CODE_ENABLE_TODO_TOOLS=1, and subagents and anything the session starts inherit it. To turn this off, set Task tools to off under ctui in /config. ctui leaves the variable alone when you set it yourself, for example in the env block of settings.json.

Task tools also keeps TaskCreate and TaskUpdate (or TodoWrite) in Claude's prompt rather than deferred, adds a line to TaskCreate's or TodoWrite's description, and adds a short task-list section to Claude's prompt asking for one task per outcome, so Claude keeps a list for multi-step work on its own. That costs about 1.2k cached tokens per request. Turning Task tools off stops both, even when you set the variable yourself. A change fully reaches Claude from the next /clear or new session: Claude Code keeps the prompt a conversation started with.

While the sidebar is docked with Todo on, ctui runs Claude's own TaskCreate and TaskUpdate calls itself, so the list shows once, in the sidebar, and Claude Code's own list stays hidden.

Privacy and data

ctui makes no network calls, and nothing it reads leaves your machine. What ctui watches writes out every program it starts.

What ctui stores, and for how long:

  • Cost totals, only while Limits cost is on: for each session that ended this month, its dollar total and its transcript's size and modification time, in ctui's own store, a JSON file under Claude Code's configuration directory. The first scan in a new month deletes the earlier months' totals.
  • Settings you change in /ctui: ctui's own ctui.* settings, in your user settings.json.
  • Sidebar and menu state: folded sections, scroll, what each section lists, the turn footers' mode and model, and where you are in the /ctui menu. Claude Code holds these for the session only, ctui writes none of them to disk, and /clear empties them.

What ctui reads:

  • ~/.claude.json (or $CLAUDE_CONFIG_DIR/.claude.json), for the MCP section. That file also holds your sign-in and account data; ctui keeps only the names of your MCP servers (your own and this project's) and the project's list of servers you turned off, never a server's config, which can hold secrets.
  • The .mcp.json files from the working directory up, and the managed managed-mcp.json: server names only.
  • Your Claude Code settings, for which project MCP servers you approved and the model's effort, and the managed settings, for the names of managed MCP servers.
  • With the inherit theme and a custom Claude Code theme, that theme's file from ~/.claude/themes/, to tint the sidebar.
  • The session's messages: to rebuild the skills section when it starts empty (a new process, /clear or /resume), and, on a model with TodoWrite instead of the Task tools, to fill the todo section. ctui keeps only the names of the skills and commands used, whether each skill's folder is yours or the project's, and the last TodoWrite call's list.
  • This month's transcripts' cost lines, only while Limits cost is on, through the grep under What ctui watches.

What ctui watches

ctui runs as a mod in every Claude Code session where the plugin is enabled. It watches Bash tool calls and subagent events to show background shells and agents, Claude's task tool calls for the todo section, and which skills and commands the chat invokes, with Claude Code's skill and command lists, for the skills section. Once you turn on Limits cost in /config (it is off by default), and while the Limits cost row shows, it also searches this month's Claude Code transcripts under ~/.claude/projects (or $CLAUDE_CONFIG_DIR/projects) for their cost lines, reads only those lines, and keeps each session's dollar total to add up the month. Set Limits cost back to off to stop it. Privacy and data lists every file and message ctui reads, what it keeps from each, and for how long.

Some of its hooks run in every session. A submitted prompt and a finished turn give the hook only their permission mode, for the turn footer; a finished tool call gives it only the server the call came from (mcp_server), while the mcp section is on; and tool.call gives it the tool name, to count MCP calls in flight and refresh git. Each of these events passes on unchanged, and ctui keeps nothing else from them.

The programs ctui runs are these four, and nothing else:

  • git --no-optional-locks status --porcelain=v2 --branch
  • git --no-optional-locks stash list
  • git --no-optional-locks diff --numstat HEAD
  • grep -h -F '"type":"cost-state"' -- <transcripts>, where <transcripts> are this month's transcript files whose cost ctui hasn't read yet, while the Limits cost row shows

The three git commands, run in the working directory for the sidebar header, only read the repository, and take no lock on it. Every argument is fixed text or a file path, never your conversation or a file's text, and the output of all four stays inside ctui, on your machine.

ctui calls Claude Code's tools itself in two cases only: TaskList, to read the session's task list for the todo section, and, while the sidebar is docked with Todo on, the main conversation's TaskCreate and TaskUpdate calls, which it runs for Claude so Claude Code's own list stays hidden. A subagent's task calls pass on to Claude Code unchanged.

ctui changes two kinds of settings only: its own ctui.* settings, when you change one in /ctui, and CLAUDE_CODE_ENABLE_TODO_TOOLS, which it sets for the session while Task tools is on.

Its tool.describe hook changes what Claude reads about its tools in two ways. With Task tools on, it keeps the tools that start and update a task list (TaskCreate and TaskUpdate, or TodoWrite) in the prompt rather than deferred, and adds one line to TaskCreate's or TodoWrite's description asking Claude to make a list for a request with two or more outcomes. It also reads each MCP tool's server name, to name that server's row as /mcp does. With Task tools on, its prompt.compose hook adds a short section to Claude's prompt asking for one task per outcome a request names.

These hooks change what Claude Code draws or does:

  • Closing the sidebar. You can't close the sidebar yourself (ui.close); only ctui's own close passes.
  • Scrolling the sidebar. ctui takes the sidebar's scroll (ui.scroll) and moves its sections itself; Claude Code's own scroll never runs.
  • The /ctui menu. Its hidden hotkeys are denied focus, so the keyboard stays on the rows (ui.focus). Esc in a submenu goes back a level instead of closing the menu (ui.close); at the top, Esc closes it. A key press on a row (ui.press) and text in the Monthly cost field or the Themes filter (ui.input) pass on to Claude Code first; ctui then opens the screen, writes the ctui.* setting, moves a section in the order or filters the Themes they ask for.
  • Tool groups are drawn expanded, so each call shows as its own row.
  • Transcript rows are restyled: Claude's replies, your own prompts, the Read, Edit, Write and Bash rows, the line under the prompt (model · effort added) and each turn's footer (its mode and model added).
  • Task calls. While the sidebar is docked with Todo on, the main conversation's TaskCreate and TaskUpdate calls run as ctui's, as above; a subagent's pass on.
  • /ctui is answered by ctui.

These hooks read their event and pass it on unchanged:

  • A background Bash call's result: its command's first line, which shows in the toast and under Agents & shells.
  • A Workflow call's result: the run's id, name and transcriptDir, where ctui checks which run a background shell's agent belongs to. It looks only for that agent's transcript file, and reads none.
  • Task notifications (prompt.submit and session.append): their text is parsed for the task's id, status and summary, to end its row and raise its toast. Only tasks ctui already shows are matched.
  • A subagent's start and failure (agent.spawn, StopFailure): its type, description and error word. A TaskStop or TodoWrite result: the task's id, or the list.
  • An invoked skill or command: its name, its source, and the folder line its text opens with.
  • Each model step and /effort: the model and effort level, for the line under the prompt. A /cd: the new working directory.
  • A prompt you type: it reopens the sidebar when an earlier open waited for room.

Troubleshooting

No sidebar. The sidebar docks only in fullscreen ("tui": "fullscreen" in settings.json, or CLAUDE_CODE_NO_FLICKER=1) and in a terminal at least 110 columns wide; narrower, or on the main screen, ctui draws none. Claude Code docks a pane ctui opens on its own only from 144 columns: between 110 and 143, the sidebar opens with your first prompt, and from then on it docks from 110.

/ctui opens something else. Another plugin's command already holds /ctui, and ctui says so in a toast once per session. Change ctui's settings under ctui in /config instead.

The todo section says no task tools on this model. Task tools is off: turn it on under ctui in /config.

Some parts don't work under an organization's management. Where an organization manages Claude Code, Claude Code skips some of ctui's hooks; see Managed Claude Code below for what that turns off.

Known differences

Some parts of the design renders are Claude Code's own and stay as Claude Code draws them: the sidebar's frame and close button, the prompt box, the permission-mode pill, the main background, and the rows of tools other than Read, Edit, Write and Bash. See the full list.

Managed Claude Code. Where an organization manages Claude Code (managed settings, or a Team or Enterprise sign-in), Claude Code skips 7 of ctui's hooks. Then the skills section stays empty, Claude gets no task-list instruction, the turn footer drops its mode, MCP sources don't update after /cd or a finished call, and a failed agent shows no reason. claude plugin validate lists the skipped hooks.

Support

For help and bug reports, open an issue in GitHub Issues. Report a security problem privately through GitHub private vulnerability reporting, not in a public issue.

License

MIT. The Themes in themes/ are generated from the built-in theme palettes of Omarchy 4.0.4, also MIT-licensed; both notices are in LICENSE.

Source 36 files
hooks/register.tsx 1700 lines
1import type { EngineInterface, Register, RenderElement } from 'claude-code'
2
3import { plugins, sections } from '../plugins'
4import { type ClientPlaceholder, clientPlaceholders, placeholdersIn, withClients } from '../plugins/clients'
5import { colors } from '../plugins/colors'
6import type { SidebarUi } from '../plugins/plugin'
7import type { GitSnapshot, McpRow, Menu, SkillRow, Task, Todo, TodoItem, Turn, Usage } from '../types'
8import { build } from './build'
9import { type Config, isSettingKey, readConfig, type SettingKey } from './config'
10import { belowFloor, floorToast } from './floor'
11import { fitsPromptLine, formatReset, modelEffort, promptLabel, savedEffort } from './format'
12import { parseGit, tildify } from './git'
13import { type McpSources, mcpRows, segmentOf, serverName, serverOfTool, withBusy } from './mcp'
14import {
15  type Cached,
16  COST_PREFIX,
17  costKey,
18  lastCosts,
19  monthOf,
20  monthStart,
21  monthTotal,
22  showsCost,
23  staleTranscripts,
24  type Transcript,
25} from './month'
26import { grey, inheritGlass, themeFile } from './glass'
27import { addSkill, dirSource, type SkillHints, skillDirs, skillName, skillsFromMessages, sourceOf, stated } from './skills'
28import { deniedText, HOTKEYS, isMonthlyKey, KEYS, MENU_START, monthlyKey, type Setting, settingKey, settingRows, menuView, moveId, NO_CONFIG, PARENT, rowId, rowKey, takenBy, themeSlug, type ThemeName, topKey, type TopPick, topPick } from './menu'
29import { type Control, controlKey, foldRowKey, sidebar, type SidebarInput } from './sidebar'
30import { assistantMessage } from './skin/assistant'
31import { promptLabelRow } from './skin/prompt'
32import { hasToolRow, toolLine, toolRow } from './skin/tool'
33import { turnOf, turnWord } from './skin/turn'
34import { isOwnPrompt, userMessage } from './skin/user'
35import {
36  applyAgentList,
37  applyNotification,
38  dropEnded,
39  endTask,
40  enqueue,
41  failureReason,
42  firstLine,
43  parseTaskNotification,
44  startedToast,
45  type Toast,
46} from './tasks'
47
48const SIDEBAR = 'sidebar'
49const FOLDED = { plugin: 'ctui', key: 'folded' } as const
50const EXPANDED = { plugin: 'ctui', key: 'expanded' } as const
51const SCROLL = { plugin: 'ctui', key: 'scroll' } as const
52const GIT = { plugin: 'ctui', key: 'git' } as const
53const VERSIONS = { plugin: 'ctui', key: 'versions' } as const
54const USAGE = { plugin: 'ctui', key: 'usage' } as const
55const NOW = { plugin: 'ctui', key: 'now' } as const
56const MONTH = { plugin: 'ctui', key: 'month' } as const
57const MCP = { plugin: 'ctui', key: 'mcp' } as const
58const MCP_OBSERVED = { plugin: 'ctui', key: 'mcpObserved' } as const
59const TODO = { plugin: 'ctui', key: 'todo' } as const
60const SKILLS = { plugin: 'ctui', key: 'skills' } as const
61const ACTIVE_FORMS = { plugin: 'ctui', key: 'activeForms' } as const
62const TODO_ENV_SET = { plugin: 'ctui', key: 'todoEnvSet' } as const
63const TASKS = { plugin: 'ctui', key: 'tasks' } as const
64const MODEL = { plugin: 'ctui', key: 'model' } as const
65const EFFORT = { plugin: 'ctui', key: 'effort' } as const
66const TURNS = { plugin: 'ctui', key: 'turns' } as const
67const GLASS = { plugin: 'ctui', key: 'glass' } as const
68
69// The dock docks from 110 terminal columns; the Sidebar asks 42, or 53 from 160.
70const DOCK_COLUMNS = 110
71const GAP = 2 // columns between the transcript rows ctui draws and the docked Sidebar's rule
72const widthFor = (terminalColumns: number) => (terminalColumns >= 160 ? 53 : 42)
73
74// The `/ctui` menu's pane, its model, and whether this session already toasted a taken or refused `/ctui`.
75const MENU_PANE = 'ctui'
76const MENU = { plugin: 'ctui', key: 'menu' } as const
77const MENU_REFUSED = { plugin: 'ctui', key: 'menuRefused' } as const
78
79// Whether this session already toasted an engine below the support floor.
80const FLOOR_TOASTED = { plugin: 'ctui', key: 'floorToasted' } as const
81
82// The enterprise MCP file on Linux and macOS.
83const ENTERPRISE_MCP = ['/etc/claude-code/managed-mcp.json', '/Library/Application Support/ClaudeCode/managed-mcp.json']
84
85const GIT_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'Bash'])
86
87// What `/effort <args>` sets for the session.
88const EFFORT_LEVELS = new Set(['low', 'medium', 'high', 'xhigh', 'max'])
89
90// The month total rescans this often while the cost row shows.
91const SCAN_MS = 60_000
92
93// Toasts come at most this often: the engine drops one within 2 s of the last.
94const TOAST_GAP_MS = 2100
95
96// Module state: a reload starts a fresh environment.
97let tick: { cancel: () => void } | undefined
98let gitRunning = false
99let gitAgain = false // a refresh came while git ran: run once more after it
100let checking = false // a viewport check is queued
101let waiting = false // opened unasked and not placed: open again on the person's prompt
102let requested: number | undefined // the columns last asked for
103let maxScroll = 0 // the sections window's last offset, as last drawn
104let monthRunning = false
105let lastScan = -Infinity // when the month total last scanned
106let mcpRunning = false
107let mcpTimeout: number | undefined // MCP_TIMEOUT, read once
108// `.claude.json`'s disabled list and its user and local MCP server names.
109type ClaudeJson = { path: string; project: string; mtimeMs?: number; disabled: string[]; user: string[]; local: string[] }
110let claudeJson: ClaudeJson | undefined
111// The approved project, managed and enterprise MCP server names, read at start and on /cd.
112let mcpFiles: Pick<McpSources, 'project' | 'managed' | 'enterprise'> = { project: [], managed: [], enterprise: [] }
113// The sources tool runs reported, by segment, also kept in `$.state`: a reload
114// resets this, `/clear` and `/resume` empty that, and the servers outlive both.
115let mcpObserved: Record<string, string> = {}
116// Calls in flight per server segment, and every write of the MCP rows queued
117// behind the one before it (`writeMcpRows`). Module state, never `$.state`: a settings change reloads the mod
118// mid-session, so a call can start under one module and end under its
119// replacement, whose `finally` never runs. Here that reload drops the count
120// and the row settles at once — busy reads stale-cold for the rest of the
121// call and never stale-hot, where in `$.state` nothing would be left to
122// decrement it and the row would sweep forever.
123let mcpCalls: Record<string, number> = {}
124let mcpWrites: Promise<unknown> = Promise.resolve()
125let cwdMoved = false // since the last MCP tick: drop the old project's off rows
126let themeSeen: { path?: string; mtimeMs?: number } = {} // the active custom /theme file, last read
127let themeNames: ThemeName[] | undefined // every Theme's slug and name, read once
128const mcpNames: Record<string, string> = {} // segment → /mcp name, from `tool.describe`
129let todoRunning = false
130let todoAgain = false // a reload came while one ran: run once more after it
131let tasksChain: Promise<unknown> = Promise.resolve() // task updates, one at a time
132let carry: Record<string, Task> | undefined // running tasks across /clear and /resume
133let toasts: Toast[] = []
134let toasting = false
135let toastsOn = true // `agents_toasts`
136let lastToast = -Infinity
137let agentsRunning = false
138let themes: readonly string[] | undefined // the `theme` setting's options, read once
139let hint = '' // PromptHint's text, as the engine last drew it
140let dockColumns = 0 // the docked Sidebar's columns, its rule included; 0 while it isn't docked
141let savedLevel: { model: string; level: unknown } | undefined // modelSettings[model].effortLevel at the last poll
142let effortCarry: string | null | undefined // the session's effort across /clear and /resume
143let mode: string | undefined // the latest main-loop permission_mode
144let stepModel: string | undefined // the last main-loop turn.step's model
145let lastTurn: { turn: Turn; at: number } | undefined // the latest main-loop turn.complete's record
146const drawnFooters = new Set<string>() // TurnDuration instances drawn since load
147
148// A hook's answer from its own call: the result alone, so core maps it for this
149// call's tool_use_id. A deny or error passes through unchanged.
150async function ownCall<R extends { deny?: string; isError?: true; result?: unknown }>(call: Promise<R>): Promise<R> {
151  const ran = await call
152  return ran.deny !== undefined || ran.isError ? ran : ({ result: ran.result } as R)
153}
154
155// A run still going takes this refresh as one more run after it ends.
156async function refreshGit($: EngineInterface) {
157  if (gitRunning) {
158    gitAgain = true
159    return
160  }
161  gitRunning = true
162  try {
163    // Each command is written whole, so the directory's scan reads it as fixed
164    // text; `ctui/README.md` "What ctui watches" names all three.
165    const git: GitSnapshot = { path: tildify(await $.session.cwd(), await $.env.get('HOME')) }
166    const status = await $.process
167      .run(['git', '--no-optional-locks', 'status', '--porcelain=v2', '--branch'])
168      .catch(() => undefined)
169    if (status?.exitCode === 0) {
170      // On an unborn branch the numstat fails: it counts as 0.
171      const [stash, numstat] = await Promise.all([
172        $.process.run(['git', '--no-optional-locks', 'stash', 'list']).catch(() => undefined),
173        $.process.run(['git', '--no-optional-locks', 'diff', '--numstat', 'HEAD']).catch(() => undefined),
174      ])
175      const out = (result: typeof stash) => (result?.exitCode === 0 ? result.stdout : '')
176      git.repo = parseGit(status.stdout, out(stash), out(numstat))
177    }
178    const { value } = await $.state.get(GIT)
179    if (JSON.stringify(value) !== JSON.stringify(git)) await $.state.set(GIT, git)
180  } finally {
181    gitRunning = false
182  }
183  if (gitAgain) {
184    gitAgain = false
185    await refreshGit($)
186  }
187}
188
189// `/clear` and `/resume` empty `$.state` with no `session.start`: the Sidebar's
190// next draw and the tick refill it.
191async function refillVersions($: EngineInterface, slug: string) {
192  const { value } = await $.state.get(VERSIONS)
193  if (!value) await loadVersions($, slug)
194}
195
196// `slug` is the `theme` setting; the footer shows the Theme file's `name`, as `/theme` lists it.
197async function loadVersions($: EngineInterface, slug: string) {
198  const name =
199    slug === 'inherit' ? slug : String(JSON.parse(await $.fs.read(`${$.plugin.root}/themes/${slug}.json`)).name)
200  const versions = { ctui: build($.plugin.root), claude: (await $.session.version()).version, theme: name }
201  const { value } = await $.state.get(VERSIONS)
202  if (JSON.stringify(value) !== JSON.stringify(versions)) await $.state.set(VERSIONS, versions)
203}
204
205// The context and limits figures, from `$.session.usage()` or a `session.measure`.
206async function setUsage($: EngineInterface, { context, rateLimits, cost }: Usage) {
207  const usage: Usage = { context, rateLimits, ...(cost && { cost }) }
208  const { value } = await $.state.get(USAGE)
209  if (JSON.stringify(value) !== JSON.stringify(usage)) await $.state.set(USAGE, usage)
210}
211
212async function loadUsage($: EngineInterface) {
213  await setUsage($, await $.session.usage())
214}
215
216// `/clear` and `/resume` empty `$.state` with no `session.start`: the Sidebar's
217// next draw and the tick refill it.
218async function refillUsage($: EngineInterface) {
219  const { value } = await $.state.get(USAGE)
220  if (!value) await loadUsage($)
221}
222
223// The usage says whether the cost row shows: the month follows it.
224async function refillUsageAndMonth($: EngineInterface, monthCost: boolean, choice: Config['limits']['cost']) {
225  await refillUsage($)
226  if (monthCost) await refreshMonth($, choice)
227}
228
229// The session's first usage, then the `now` and month rows that read it, neither awaited.
230async function loadUsageAndMonth(
231  $: EngineInterface,
232  now: boolean,
233  monthCost: boolean,
234  choice: Config['limits']['cost'],
235) {
236  await loadUsage($)
237  if (now) void setNow($).catch(() => undefined)
238  if (monthCost) void refreshMonth($, choice).catch(() => undefined)
239}
240
241// `now` moves when a reset time shown would read differently.
242async function setNow($: EngineInterface) {
243  const usage = await $.state.get(USAGE)
244  const resets = usage.value?.rateLimits.flatMap((limit) => (limit.resetsAt ? [limit.resetsAt] : [])) ?? []
245  if (!resets.length) return
246  const now = await $.clock.now()
247  const { value } = await $.state.get(NOW)
248  if (value === undefined || resets.some((at) => formatReset(at, now) !== formatReset(at, value))) {
249    await $.state.set(NOW, now)
250  }
251}
252
253// Claude Code's config dir: `CLAUDE_CONFIG_DIR`, else `~/.claude`.
254const configDirOf = async ($: EngineInterface) =>
255  (await $.env.get('CLAUDE_CONFIG_DIR')) || `${await $.env.get('HOME')}/.claude`
256
257// The main transcripts written since `since`, the current session's left out:
258// `<config dir>/projects/<project>/<session id>.jsonl`.
259async function listTranscripts($: EngineInterface, since: number, current: string) {
260  const dir = await configDirOf($)
261  const projects = (await $.fs.list(`${dir}/projects`)).filter((entry) => entry.kind === 'dir')
262  const lists = await Promise.all(
263    projects.map(async ({ name }) => {
264      const path = `${dir}/projects/${name}`
265      return (await $.fs.list(path)).flatMap(({ name, kind, mtimeMs, size }): Transcript[] => {
266        const session = name.endsWith('.jsonl') ? name.slice(0, -'.jsonl'.length) : ''
267        return kind === 'file' && session && session !== current && mtimeMs >= since
268          ? [{ session, path: `${path}/${name}`, mtimeMs, size }]
269          : []
270      })
271    }),
272  )
273  return lists.flat()
274}
275
276// The ended sessions' cost this month (#147): each transcript's last
277// `cost-state`, cached per session in `$.store` so unchanged transcripts aren't
278// read again and totals outlive the 30-day transcript sweep. A failed scan
279// keeps the cached totals; the next one retries.
280async function scanMonth($: EngineInterface) {
281  if (monthRunning) return
282  monthRunning = true
283  try {
284    const [now, current] = await Promise.all([$.clock.now(), $.session.id()])
285    lastScan = now
286    const month = monthOf(now)
287    const prefix = costKey(month, '')
288    const keys = await $.store.keys()
289    const cached: Record<string, Cached> = {}
290    for (const key of keys) {
291      if (key.startsWith(prefix)) cached[key.slice(prefix.length)] = (await $.store.get(key)) as Cached
292      // Earlier months' totals go.
293      else if (key.startsWith(COST_PREFIX)) await $.store.delete(key).catch(() => undefined)
294    }
295    try {
296      const stale = staleTranscripts(await listTranscripts($, monthStart(now), current), cached)
297      if (stale.length) {
298        const grep = ['grep', '-h', '-F', '"type":"cost-state"', '--', ...stale.map((t) => t.path)]
299        const { exitCode, stdout, isStdoutTruncated } = await $.process.run(grep)
300        // 1 is no line found.
301        if (exitCode > 1 || isStdoutTruncated) throw new Error(`grep exited ${exitCode}`)
302        const costs = lastCosts(stdout)
303        for (const { session, mtimeMs, size } of stale) {
304          const entry = { usd: costs[session] ?? 0, mtimeMs, size }
305          await $.store.set(costKey(month, session), entry)
306          cached[session] = entry
307        }
308      }
309    } catch {
310      // Failed: the cached totals stand until the next scan.
311    }
312    const total = { month, session: current, usd: monthTotal(cached, current) }
313    const { value } = await $.state.get(MONTH)
314    if (JSON.stringify(value) !== JSON.stringify(total)) await $.state.set(MONTH, total)
315  } catch {
316    // The store can't be read: the last total stands.
317  } finally {
318    monthRunning = false
319  }
320}
321
322// Scans while the cost row shows: once the usage says it does, each SCAN_MS,
323// at the local month's turn, and when `/clear` or `/resume` changed the
324// session, a scan running across the switch included.
325async function refreshMonth($: EngineInterface, choice: Config['limits']['cost']) {
326  const [usage, total, now] = await Promise.all([$.state.get(USAGE), $.state.get(MONTH), $.clock.now()])
327  if (!showsCost(usage.value, choice)) return
328  const session = await $.session.id()
329  const value = total.value
330  if (!value || value.month !== monthOf(now) || value.session !== session || now - lastScan >= SCAN_MS) {
331    await scanMonth($)
332  }
333}
334
335// `.claude.json` keys a project by its git root, found by walking up from the cwd, else the cwd.
336async function projectOf($: EngineInterface) {
337  const cwd = await $.session.cwd()
338  for (let dir = cwd; dir; dir = dir.slice(0, dir.lastIndexOf('/'))) {
339    if (await $.fs.exists(`${dir}/.git`)) return dir
340  }
341  return cwd
342}
343
344// `projects[<project>].disabledMcpServers`, and the user (`mcpServers`) and
345// local (`projects[<project>].mcpServers`) server names, re-read when the
346// file's mtime changes. Claude Code keeps the file in CLAUDE_CONFIG_DIR when that is set.
347async function readClaudeJson($: EngineInterface) {
348  const dir = (await $.env.get('CLAUDE_CONFIG_DIR')) || (await $.env.get('HOME'))
349  claudeJson ??= { path: `${dir}/.claude.json`, project: await projectOf($), disabled: [], user: [], local: [] }
350  const file = claudeJson
351  const stat = await $.fs.stat(file.path).catch(() => undefined)
352  if (stat?.mtimeMs !== file.mtimeMs) {
353    try {
354      const json = stat ? JSON.parse(await $.fs.read(file.path)) : {}
355      const project = json.projects?.[file.project]
356      file.disabled = project?.disabledMcpServers ?? []
357      file.user = Object.keys(json.mcpServers ?? {})
358      file.local = Object.keys(project?.mcpServers ?? {})
359      file.mtimeMs = stat?.mtimeMs
360    } catch {
361      // Caught mid-write: the next tick reads it again.
362    }
363  }
364  return file
365}
366
367// The server names in an `{ mcpServers }` file, never their entries (they can hold secrets).
368async function serverNames($: EngineInterface, path: string) {
369  try {
370    return Object.keys(JSON.parse(await $.fs.read(path)).mcpServers ?? {})
371  } catch {
372    return [] // No such file.
373  }
374}
375
376// MEMORY.md "The `mcp` Sidebar plugin reads live tools and MCP config names;
377// it never probes": the approved project servers in `.mcp.json` from the cwd
378// up to (not including) `/`, the policy's `managedMcpServers`, and the
379// enterprise `managed-mcp.json`.
380async function readMcpFiles($: EngineInterface, cwd?: string) {
381  const [dir0, settings, policy] = await Promise.all([
382    cwd ?? $.session.cwd(),
383    $.settings.read() as Promise<Record<string, unknown>>,
384    $.settings.read({ source: 'policy' }) as Promise<Record<string, unknown>>,
385  ])
386  const dirs: string[] = []
387  for (let dir = dir0; dir; dir = dir.slice(0, dir.lastIndexOf('/'))) dirs.push(dir)
388  const listed = (key: string) => (Array.isArray(settings[key]) ? (settings[key] as string[]) : [])
389  const approved = (name: string) =>
390    !listed('disabledMcpjsonServers').includes(name) &&
391    (settings.enableAllProjectMcpServers === true || listed('enabledMcpjsonServers').includes(name))
392  const [project, enterprise] = await Promise.all([
393    Promise.all(dirs.map((dir) => serverNames($, `${dir}/.mcp.json`))),
394    Promise.all(ENTERPRISE_MCP.map((path) => serverNames($, path))),
395  ])
396  const managed = policy.managedMcpServers
397  mcpFiles = {
398    project: project.flat().filter(approved),
399    managed: managed && typeof managed === 'object' && !Array.isArray(managed) ? Object.keys(managed) : [],
400    enterprise: enterprise.flat(),
401  }
402}
403
404// A glass as Claude Code can draw it: under tmux without
405// `CLAUDE_CODE_TMUX_TRUECOLOR`, its 256-color test (MEMORY.md "Inside tmux,
406// Claude Code draws 256 colors…"), snapped to a grey.
407async function paintable($: EngineInterface, glass: string) {
408  const palette = (await $.env.get('TMUX')) && !(await $.env.get('CLAUDE_CODE_TMUX_TRUECOLOR'))
409  return palette ? grey(glass) : glass
410}
411
412// Under `inherit`, the glass of the active `/theme` when it's a user custom
413// theme with no dock color (Omarchy's), re-read when the theme or its file's
414// mtime changes: an Omarchy switch rewrites the file.
415async function refreshGlass($: EngineInterface) {
416  const row = (await $.config.list()).find((r) => r.key === 'theme')
417  const dir = await configDirOf($)
418  const path = themeFile(row?.value, dir)
419  const stat = path ? await $.fs.stat(path).catch(() => undefined) : undefined
420  // `/clear` and `/resume` empty `$.state` with no `session.start`: read again.
421  const { value } = await $.state.get(GLASS)
422  if (value !== undefined && path === themeSeen.path && stat?.mtimeMs === themeSeen.mtimeMs) return
423  let glass: string | null
424  try {
425    glass = (path && stat && inheritGlass(JSON.parse(await $.fs.read(path)).overrides ?? {})) || null
426  } catch {
427    return // Caught mid-write: the next tick reads it again.
428  }
429  if (glass) glass = await paintable($, glass)
430  themeSeen = { path, mtimeMs: stat?.mtimeMs }
431  // A state value is never undefined: null clears the paint.
432  if (value !== glass) await $.state.set(GLASS, glass)
433}
434
435// MEMORY.md "The `mcp` Sidebar plugin reads live tools and MCP config names; it never probes".
436async function refreshMcp($: EngineInterface) {
437  if (mcpRunning) return
438  mcpRunning = true
439  try {
440    mcpTimeout ??= Number(await $.env.get('MCP_TIMEOUT')) || 30_000
441    const timeoutMs = mcpTimeout // the closure below reads it after an await
442    const moved = cwdMoved
443    cwdMoved = false
444    const [tools, file, now, { value: observed = {} }] = await Promise.all([
445      $.tool.list(),
446      readClaudeJson($),
447      $.clock.now(),
448      $.state.get(MCP_OBSERVED),
449    ])
450    const sources = { ...mcpFiles, user: file.user, local: file.local, observed: { ...mcpObserved, ...observed } }
451    await writeMcpRows($, (rows) =>
452      mcpRows({
453        rows: moved ? rows.filter((row) => row.state !== 'off') : rows,
454        tools,
455        disabled: file.disabled,
456        names: mcpNames,
457        now,
458        timeoutMs,
459        sources,
460        busy: mcpCalls,
461      }),
462    )
463  } finally {
464    mcpRunning = false
465  }
466}
467
468// The one writer of the MCP rows: both the 1 s tick and the `tool.call`
469// bracket go through it, one write at a time. It reads the rows `$.state`
470// holds, hands them to `derive` (the tick's own rows, or the rows as they
471// stand), applies the in-flight count **here**, and compares against the rows
472// it read itself.
473//
474// Doing all of that inside the queued callback is what keeps the row honest.
475// A write that computed its rows earlier and set them later would put back the
476// count as it stood then: a release landing in between would be overwritten
477// and the row would keep sweeping until the next tick — up to a second of a
478// row that says working when nothing is. Busy may read stale-cold, never
479// stale-hot, and it settles at once.
480//
481// The busy flag reaches the Sidebar through these rows, so the row redraws and
482// the sweep starts as the call crosses the wire and stops the instant the last
483// one ends, without waiting for a tick.
484function writeMcpRows($: EngineInterface, derive?: (rows: readonly McpRow[]) => readonly McpRow[]) {
485  const write = mcpWrites.then(async () => {
486    const { value: rows = [] } = await $.state.get(MCP)
487    const busy = withBusy(derive ? derive(rows) : rows, mcpCalls)
488    if (JSON.stringify(busy) !== JSON.stringify(rows)) await $.state.set(MCP, busy)
489  })
490  mcpWrites = write.catch(() => undefined)
491  return write
492}
493
494// MEMORY.md "The `todo` Sidebar plugin turns the task tools on by default":
495// set the variable when it's unset, and unset it only when ctui set it.
496async function setTodoEnv($: EngineInterface, tools: boolean) {
497  const { value: ours } = await $.state.get(TODO_ENV_SET)
498  if (tools && (await $.env.get('CLAUDE_CODE_ENABLE_TODO_TOOLS')) === undefined) {
499    await $.env.set('CLAUDE_CODE_ENABLE_TODO_TOOLS', '1')
500    await $.state.set(TODO_ENV_SET, true)
501  } else if (!tools && ours) {
502    await $.env.set('CLAUDE_CODE_ENABLE_TODO_TOOLS', undefined)
503    await $.state.set(TODO_ENV_SET, false)
504  }
505}
506
507// The task tools `todo_tools` keeps out of ToolSearch; TaskList, TaskGet and TaskStop stay deferred.
508const PINNED_TASK_TOOLS = new Set(['TaskCreate', 'TaskUpdate', 'TodoWrite'])
509
510// The tools that start a list carry the 2+ outcomes rule in their own description, where
511// Sonnet 5.5 decides whether to call one: the section alone left it listing 6 of 9.
512const LIST_STARTERS = new Set(['TaskCreate', 'TodoWrite'])
513const LIST_RULE = 'Use this for any request with 2 or more outcomes the user named, even when one command or edit could do several of them; make the list before the first tool call. A request for one outcome gets no list.'
514
515// The `ctui:todo` section, as tested live in #220 and narrowed in #294, naming the
516// tools the request offers. It counts outcomes the user named, not the model's own
517// moves, because a weak model counted a one-line fix's read, edit and check as
518// three steps and Sonnet 5.5 read a three-outcome job as one piece (#358).
519const taskSection = (create: string, update: string) => `# Task list
520The user follows your progress in a task list shown beside the conversation. Count what the user asked for, not your own moves: reading, searching, editing and checking one change are not separate steps, so a request for one outcome — one file's edit, one command, one question answered — gets no list. A request for 2 or more outcomes the user named, even a short one (a rename, then a README, then a line count; several files or fixes; a delegated agent; a build and then its tests), gets one task per outcome as your first action, created with ${create} before reading files or delegating. Set each task in_progress with ${update} when you start it and completed as soon as it is done.`
521
522const TODO_STATUSES = new Set<string>(['pending', 'in_progress', 'completed'])
523
524const todoToolsOf = (names: readonly string[]): Todo['tools'] =>
525  names.includes('TaskList') ? 'task' : names.includes('TodoWrite') ? 'todowrite' : 'none'
526
527async function setTodo($: EngineInterface, todo: Todo) {
528  const { value } = await $.state.get(TODO)
529  if (JSON.stringify(value) !== JSON.stringify(todo)) await $.state.set(TODO, todo)
530}
531
532// The list as the session's task tools hold it (the map decision for #10).
533// `TaskList` covers a reload, `--resume` and compaction; it lacks `activeForm`,
534// kept from the TaskCreate/TaskUpdate inputs. `TodoWrite` takes the last call's
535// list from the transcript. A run still going takes this load as one more run.
536async function loadTodo($: EngineInterface) {
537  if (todoRunning) {
538    todoAgain = true
539    return
540  }
541  todoRunning = true
542  try {
543    const tools = todoToolsOf((await $.tool.list()).map((tool) => tool.name))
544    let items: TodoItem[] = []
545    if (tools === 'task') {
546      // TaskList throws when the tool isn't listed, as after a `/model` switch.
547      const listed = await $.tool.call({ tool: 'TaskList' }).catch(() => undefined)
548      if (!listed?.result || listed.isError) return
549      const { value: forms = {} } = await $.state.get(ACTIVE_FORMS)
550      // Rows leave out `deleted`, which 2.1.288's TaskList type doesn't list.
551      const shown = listed.result.tasks.filter(({ status }) => TODO_STATUSES.has(status))
552      items = shown.map(({ id, subject, status }) => ({
553        id,
554        subject,
555        status,
556        ...(forms[id] !== undefined && { activeForm: forms[id] }),
557      }))
558    } else if (tools === 'todowrite') {
559      const uses = (await $.session.messages()).flatMap((message) => message.toolUses)
560      const last = uses.findLast((use) => use.tool === 'TodoWrite' && !use.isError)
561      items = todoWriteItems(last?.input.todos)
562    }
563    await setTodo($, { tools, items })
564  } finally {
565    todoRunning = false
566  }
567  if (todoAgain) {
568    todoAgain = false
569    await loadTodo($)
570  }
571}
572
573// A TodoWrite list: its `todos` input, or its `newTodos` result.
574function todoWriteItems(todos: unknown): TodoItem[] {
575  if (!Array.isArray(todos)) return []
576  return todos.map(({ content, status, activeForm }) => ({ subject: content, status, activeForm }))
577}
578
579// Reloads the list when the session's task tools change: a `/model` switch,
580// or `/clear` and `/resume`, which empty `$.state`.
581async function refreshTodo($: EngineInterface) {
582  const [tools, { value }] = await Promise.all([$.tool.list(), $.state.get(TODO)])
583  if (todoToolsOf(tools.map((tool) => tool.name)) !== value?.tools) await loadTodo($)
584}
585
586// Keeps a Task's `activeForm`, which TaskList lacks.
587async function keepActiveForm($: EngineInterface, id: string, activeForm: string | undefined) {
588  if (activeForm === undefined) return
589  const { value = {} } = await $.state.get(ACTIVE_FORMS)
590  if (value[id] !== activeForm) await $.state.set(ACTIVE_FORMS, { ...value, [id]: activeForm })
591}
592
593// Applies `change` to the session's tasks, one change at a time. `change`
594// edits the copy it gets and returns the toasts its edits raise.
595function updateTasks(
596  $: EngineInterface,
597  change: (tasks: Record<string, Task>, now: number) => Toast[] | void | Promise<Toast[] | void>,
598) {
599  const run = tasksChain.then(async () => {
600    const [{ value = {} }, now] = await Promise.all([$.state.get(TASKS), $.clock.now()])
601    const tasks = { ...value }
602    const raised = (await change(tasks, now)) ?? []
603    if (JSON.stringify(tasks) !== JSON.stringify(value)) await $.state.set(TASKS, tasks)
604    for (const toast of raised) showToast($, toast)
605  })
606  tasksChain = run.catch(() => undefined)
607  return run
608}
609
610// One toast at most every TOAST_GAP_MS; an end goes ahead of waiting starts.
611// `always` skips the `agents_toasts` gate, for a toast that isn't a task's.
612function showToast($: EngineInterface, toast: Toast, always = false) {
613  if (!toastsOn && !always) return
614  toasts = enqueue(toasts, toast)
615  // A reload unloads the environment under a waiting toast: the new module starts its own queue.
616  if (!toasting) void drainToasts($).catch(() => undefined)
617}
618
619async function drainToasts($: EngineInterface) {
620  toasting = true
621  try {
622    while (toasts.length) {
623      const wait = lastToast + TOAST_GAP_MS - (await $.clock.now())
624      if (wait > 0) await $.clock.sleep(wait)
625      const [toast, ...rest] = toasts
626      toasts = rest
627      if (!toast) break
628      lastToast = await $.clock.now()
629      await $.ui.toast(toast.text)
630    }
631  } finally {
632    toasting = false
633  }
634}
635
636// Agent status from the list, which has no change event.
637async function refreshAgents($: EngineInterface) {
638  if (agentsRunning) return
639  agentsRunning = true
640  try {
641    const list = (await $.agent.list()).filter((agent) => agent.type !== 'teammate')
642    await updateTasks($, (tasks, now) => applyAgentList(tasks, list, now))
643  } finally {
644    agentsRunning = false
645  }
646}
647
648// The tick's share: merges the /clear carry, drops rows ended ENDED_MS ago,
649// and moves `now` while a row shows.
650async function tickTasks($: EngineInterface, timers: boolean) {
651  const carried = carry
652  carry = undefined
653  let shown = false
654  await updateTasks($, (tasks, now) => {
655    for (const task of Object.values(carried ?? {})) tasks[task.id] ??= task
656    dropEnded(tasks, now)
657    shown = Object.keys(tasks).length > 0
658  })
659  if (timers && shown) await $.state.set(NOW, await $.clock.now())
660}
661
662// The tick's agent refresh, then its task share.
663async function refreshAgentsAndTasks($: EngineInterface, timers: boolean) {
664  await refreshAgents($)
665  await tickTasks($, timers)
666}
667
668function onNotification($: EngineInterface, text: string) {
669  const note = parseTaskNotification(text)
670  if (note) return updateTasks($, (tasks, now) => applyNotification(tasks, note, now))
671}
672
673const textOf = (content: readonly { type: string; text?: string }[]) =>
674  content.map((block) => (block.type === 'text' ? (block.text ?? '') : '')).join('\n')
675
676// Folds or unfolds a section, or expands or caps its list.
677async function toggle($: EngineInterface, config: Config, { kind, id }: Control) {
678  if (kind === 'fold') {
679    const { value = {} } = await $.state.get(FOLDED)
680    await $.state.set(FOLDED, { ...value, [id]: !(value[id] ?? config[id].folded ?? false) })
681  } else {
682    const { value = {} } = await $.state.get(EXPANDED)
683    await $.state.set(EXPANDED, { ...value, [id]: !value[id] })
684  }
685}
686
687// The Sidebar's role colors and background: under `inherit` each role's theme
688// key and no background, else the selected Theme's overrides and its glass,
689// from `themes/<slug>.json`.
690async function themeLook($: EngineInterface, theme: string): Promise<Pick<SidebarInput, 'colors' | 'background'>> {
691  if (theme === 'inherit') return { colors: colors() }
692  const { overrides } = JSON.parse(await $.fs.read(`${$.plugin.root}/themes/${theme}.json`))
693  return { colors: colors(overrides), background: await paintable($, overrides.composerSidebarBackground) }
694}
695
696// The manifest's `theme` options: under `claude -p` no `/config` row lists them.
697async function themesOf($: EngineInterface) {
698  themes ??= JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)).userConfig.theme
699    .options as string[]
700  return themes
701}
702
703// `claude -p` and the SDK list no `ctui.theme` row, and `$.config.set` throws there.
704async function hasConfig($: EngineInterface) {
705  // A refused list reads as no settings: the person loses the menu for this
706  // `/ctui` and gets the fixed line that sends them to `/config`, not silence.
707  const rows = await $.config.list().catch(() => [])
708  return rows.some((row) => row.key === 'ctui.theme')
709}
710
711// MEMORY.md "`/ctui` is one instant menu; it survives each settings reload".
712// The name is global: a person's own `/ctui` or an earlier plugin's makes `register` throw.
713async function registerMenu($: EngineInterface) {
714  try {
715    await $.command.register({ name: 'ctui', description: 'ctui: Sidebar plugins and themes', immediate: true })
716  } catch (error) {
717    // Taken, or refused by another mod, the session has no `/ctui` until a
718    // settings reload registers it again: one toast sends the person to `/config`.
719    const refusal = error instanceof Error ? error.message : String(error)
720    if ((await $.state.get(MENU_REFUSED)).value) return
721    await $.state.set(MENU_REFUSED, true)
722    // A taken name reads `"/ctui" refused: …`, naming who holds it.
723    const text = refusal.includes('"/ctui" refused')
724      ? `/ctui is taken by ${takenBy(refusal)}; change ctui settings in /config`
725      : "Can't register /ctui; change ctui settings in /config"
726    showToast($, { id: 'menu-refused', end: true, text }, true)
727  }
728}
729
730// CONTEXT.md "Support floor": one toast per session on an older engine. On
731// 2.1.284 and older the hooks module never loads, so this reaches 2.1.285 to 2.1.291.
732async function checkFloor($: EngineInterface) {
733  const { version } = await $.session.version()
734  if (!belowFloor(version) || (await $.state.get(FLOOR_TOASTED)).value) return
735  await $.state.set(FLOOR_TOASTED, true)
736  showToast($, { id: 'floor', end: true, text: floorToast(version) }, true)
737}
738
739// Opens the menu with the keys: a first open, or one taking them back after Esc's deny.
740async function openMenu($: EngineInterface) {
741  // As wide as the Sidebar it docks over; inline ignores it, and fits the
742  // menu's content up to `rows`.
743  await $.ui.open({ id: MENU_PANE, title: 'Settings', focus: true, closeOnEscape: true, columns: requested ?? widthFor(DOCK_COLUMNS), rows: 24 })
744}
745
746async function menuOf($: EngineInterface): Promise<Menu> {
747  return (await $.state.get(MENU)).value ?? MENU_START
748}
749
750async function setMenu($: EngineInterface, menu: Menu) {
751  await $.state.set(MENU, menu)
752}
753
754// The order the Plugins screen moved and hasn't saved, as the `order` setting's text.
755// Each hook that saves it repeats its own `$.config.set({ key: 'ctui.order', … })`
756// on purpose: the directory reads a write only on the hook's own `$`, call by call.
757async function pendingOrder($: EngineInterface) {
758  return (await menuOf($)).pending?.join(',')
759}
760
761// After one menu write: a deny toasts its line (a menu pick has no command
762// row), through the queue even with `agents_toasts` off. A written or denied
763// order stops waiting; the rows keep it until the write lands, and the
764// reload's `session.start` then drops it.
765async function settleWrite($: EngineInterface, set: Setting, deny: string | undefined) {
766  if (deny !== undefined) showToast($, { id: 'menu-deny', end: true, text: deniedText(set, deny) }, true)
767  if (set.key === 'ctui.order') {
768    const { pending: _, ...menu } = await menuOf($)
769    await setMenu($, menu)
770  }
771  return deny === undefined
772}
773
774// Puts the menu's ring on `key` once the redraw has drawn it, as #160's spike
775// did: 50 ms on, or `ms` to follow another move.
776function focusLater($: EngineInterface, key: string, ms = 50) {
777  $.clock.after(ms, () => $.ui.focus({ requestId: MENU_PANE, key }).catch(() => undefined))
778}
779
780
781async function themeNamesOf($: EngineInterface) {
782  const slugs = await themesOf($)
783  themeNames ??= await Promise.all(
784    slugs.map(async (slug) =>
785      slug === 'inherit'
786        ? { slug, name: slug }
787        : { slug, name: String(JSON.parse(await $.fs.read(`${$.plugin.root}/themes/${slug}.json`)).name) },
788    ),
789  )
790  return themeNames
791}
792
793// MEMORY.md "The `skills` Sidebar plugin lists every `skill.prompt`": the
794// skill listing and the command list name each skill's source, and the config
795// dir tells a user skill's folder from a project one's.
796async function skillCatalog($: EngineInterface) {
797  const [usage, commands, configDir] = await Promise.all([$.session.usage({ breakdown: 'summary' }), $.command.list(), configDirOf($)])
798  return { listed: usage.context.breakdown?.skills?.skillFrontmatter ?? [], commands, configDir }
799}
800
801let skillsChain: Promise<unknown> = Promise.resolve() // one list write at a time
802
803// Runs `write` after the list's earlier writes, so a rebuild and a
804// `skill.prompt` never race.
805function writeSkills(write: () => Promise<void>) {
806  const run = skillsChain.then(write)
807  skillsChain = run.catch(() => undefined)
808  return run
809}
810
811// A `skill.prompt`'s skill, once; a skill already listed reads nothing more.
812function addSkills($: EngineInterface, name: string, text: string, hints: SkillHints) {
813  return writeSkills(async () => {
814    const { value = [] } = await $.state.get(SKILLS)
815    if (value.some((row) => row.name === name)) return
816    const { listed, commands, configDir } = await skillCatalog($)
817    const place = dirSource(skillDirs([text]).get(skillName(name)), configDir)
818    await $.state.set(SKILLS, [...addSkill(value, { name, source: sourceOf(name, listed, commands, { ...hints, place }) })])
819  })
820}
821
822// After `--resume` (a new process) and `/resume` or `/clear` (`$.state`
823// emptied), rebuild the list from the transcript's main rows; a reload keeps it.
824function refillSkills($: EngineInterface) {
825  return writeSkills(async () => {
826    if ((await $.state.get(SKILLS)).value) return
827    const [{ listed, commands, configDir }, messages] = await Promise.all([skillCatalog($), $.session.messages()])
828    const known = new Set([
829      ...listed.map((skill) => skill.name),
830      ...commands.filter((command) => command.source !== 'builtin').map((command) => command.name),
831    ])
832    const names = skillsFromMessages(messages, known)
833    const dirs = skillDirs(messages.map((message) => message.text))
834    let rows: readonly SkillRow[] = []
835    for (const name of names) {
836      const place = dirSource(dirs.get(skillName(name)), configDir)
837      rows = addSkill(rows, { name, source: sourceOf(name, listed, commands, { place }) })
838    }
839    await $.state.set(SKILLS, [...rows])
840  })
841}
842
843// MEMORY.md "The line under the prompt: `model · effort` is a `SessionMode`
844// label". The model follows `/model` within a tick. An unset effort is a new
845// session (or `/clear`, `/resume`): seed it. Later, a change in the current
846// model's saved level is a `/effort` picker save.
847async function refreshModel($: EngineInterface) {
848  const [model, settings, stored, effort] = await Promise.all([
849    $.session.model(),
850    $.settings.read(),
851    $.state.get(MODEL),
852    $.state.get(EFFORT),
853  ])
854  const level = modelEffort(settings, model)
855  const changed = savedLevel?.model === model && savedLevel.level !== level
856  savedLevel = { model, level }
857  if (effort.value === undefined) {
858    await setEffort($, effortCarry !== undefined ? effortCarry : (savedEffort(settings, model) ?? null))
859    effortCarry = undefined
860  } else if (changed && typeof level === 'string') {
861    await setEffort($, level)
862  }
863  if (stored.value !== model) await $.state.set(MODEL, model)
864}
865
866// A turn's footer draws within this long of its turn.complete.
867const FOOTER_MS = 2000
868
869async function addTurn($: EngineInterface, turn: Turn) {
870  const { value = [] } = await $.state.get(TURNS)
871  await $.state.set(TURNS, [...value, turn])
872}
873
874// The latest main-loop permission mode, for the turn footer.
875function noteMode(input: { agent_id?: string; permission_mode?: string }) {
876  if (input.agent_id === undefined && input.permission_mode) mode = input.permission_mode
877}
878
879// Redraws the line under the prompt on the next tick, never from a render.
880function redrawLater($: EngineInterface) {
881  $.clock.after(0, () => $.ui.invalidate('ui.render'))
882}
883
884async function setEffort($: EngineInterface, effort: string | null) {
885  const { value } = await $.state.get(EFFORT)
886  if (value !== effort) await $.state.set(EFFORT, effort)
887}
888
889// A change of the dock's columns redraws what fits around it.
890function setDock($: EngineInterface, dock: number) {
891  if (dock !== dockColumns) {
892    dockColumns = dock
893    redrawLater($)
894  }
895}
896
897async function openSidebar($: EngineInterface, columns: number) {
898  requested = columns
899  const opened = await $.ui.open({ id: SIDEBAR, title: 'Sidebar', columns })
900  waiting = !opened.isPlaced
901  if (waiting) setDock($, 0)
902}
903
904export const register: Register = (on, options) => {
905  const config = readConfig(options)
906  // The sections in the `order` setting's order; the Sidebar places the header and footer by slot.
907  const enabled = plugins
908    .filter((plugin) => config[plugin.id].enable)
909    .sort((a, b) => config.order.indexOf(a.id) - config.order.indexOf(b.id))
910  const needs = new Set(enabled.flatMap((plugin) => plugin.needs))
911  // Tasks feed the Sidebar section and the toasts.
912  const tracking = needs.has('tasks') || config.agents.toasts
913  toastsOn = config.agents.toasts
914  const inherit = config.theme === 'inherit'
915  let look: ReturnType<typeof themeLook> | undefined // read once per load: a `theme` change reloads
916
917  on('session.start', async ($, e, next) => {
918    void checkFloor($).catch(() => undefined)
919    void registerMenu($).catch(() => undefined)
920    // A written order stops waiting; one a reload from elsewhere (`/config`)
921    // left still waits for the menu's next write, Esc or close. A refused read
922    // reads as an empty menu, so the session still starts and ticks: a moved
923    // order never saved stays waiting, as that reload already leaves it.
924    const { pending, ...menu } = await menuOf($).catch(() => MENU_START)
925    if (pending?.join(',') === config.order.join(',')) await setMenu($, menu)
926    await setTodoEnv($, config.todo.tools)
927    // `tool.describe` answers are cached for the session: re-ask them, so the pin follows `todo_tools`.
928    $.ui.invalidate('tool.describe')
929    void refreshModel($).catch(() => undefined)
930    if (needs.has('todo')) void loadTodo($).catch(() => undefined)
931    if (needs.has('skills')) void refillSkills($).catch(() => undefined)
932    if (needs.has('git')) void refreshGit($).catch(() => undefined)
933    if (needs.has('mcp')) void readMcpFiles($).catch(() => undefined)
934    if (needs.has('versions')) void loadVersions($, config.theme).catch(() => undefined)
935    if (needs.has('usage')) void loadUsageAndMonth($, needs.has('now'), needs.has('monthCost'), config.limits.cost).catch(() => undefined)
936    if (inherit) void refreshGlass($).catch(() => undefined)
937    let ticks = 0
938    tick?.cancel()
939    tick = $.clock.every(1000, () => {
940      ticks++
941      void refreshModel($).catch(() => undefined)
942      if (ticks % 5 === 0 && needs.has('git')) void refreshGit($).catch(() => undefined)
943      if (needs.has('usage')) void refillUsageAndMonth($, needs.has('monthCost'), config.limits.cost).catch(() => undefined)
944      if (needs.has('versions')) void refillVersions($, config.theme).catch(() => undefined)
945      if (needs.has('mcp')) void refreshMcp($).catch(() => undefined)
946      if (needs.has('todo')) void refreshTodo($).catch(() => undefined)
947      if (needs.has('skills')) void refillSkills($).catch(() => undefined)
948      if (needs.has('now')) void setNow($).catch(() => undefined)
949      if (inherit) void refreshGlass($).catch(() => undefined)
950      if (tracking) void refreshAgentsAndTasks($, needs.has('now')).catch(() => undefined)
951    })
952    return next(e)
953  })
954
955  on('session.measure', async ($, e, next) => {
956    if (needs.has('usage')) await setUsage($, e)
957    if (needs.has('now')) await setNow($)
958    return next(e)
959  })
960
961  // Names a server's row as /mcp does, and with Task tools on keeps the tools
962  // that start and move a list in the prompt, so their own text nudges Claude to keep one.
963  on('tool.describe', async ($, e, next) => {
964    const [segment, name] = serverName(e.tool, e.provider.plugin) ?? []
965    if (segment && name) mcpNames[segment] = name
966    if (config.todo.tools && PINNED_TASK_TOOLS.has(e.tool)) {
967      const described = { ...(await next(e)), isDeferred: false }
968      return LIST_STARTERS.has(e.tool) ? { ...described, description: `${described.description}\n\n${LIST_RULE}` } : described
969    }
970    return next(e)
971  })
972
973  // With Task tools on, tells Claude the user follows a task list. Pure: it
974  // also runs for /context's measuring render.
975  on('prompt.compose', async ($, e, next) => {
976    const answer = await next(e)
977    if (!config.todo.tools) return answer
978    const text = e.tools.includes('TaskCreate')
979      ? taskSection('TaskCreate', 'TaskUpdate')
980      : e.tools.includes('TodoWrite')
981        ? taskSection('TodoWrite', 'TodoWrite')
982        : undefined
983    return text ? { sections: [...answer.sections, { id: 'ctui:todo', text, scope: 'session' }] } : answer
984  })
985
986  // After /cd the disabled list is another project's: re-derive its key, and
987  // drop the off rows the old list made. Observe only.
988  on('classic.CwdChanged', ($, e, next) => {
989    claudeJson = undefined
990    cwdMoved = true
991    // Another directory's servers of the same names may come from elsewhere.
992    mcpObserved = {}
993    if (needs.has('mcp')) {
994      void $.state.set(MCP_OBSERVED, {}).catch(() => undefined)
995      void readMcpFiles($, e.new_cwd).catch(() => undefined)
996    }
997    return next(e)
998  })
999
1000  // A run of a server's tool names its source; it corrects the guess. Observe only.
1001  on('classic.PostToolUse', async ($, e, next) => {
1002    if (needs.has('mcp') && e.mcp_server) {
1003      const { name, source } = e.mcp_server
1004      const server = segmentOf(name)
1005      mcpObserved = { ...mcpObserved, [server]: source }
1006      const { value = {} } = await $.state.get(MCP_OBSERVED)
1007      if (value[server] !== source) await $.state.set(MCP_OBSERVED, { ...value, [server]: source })
1008    }
1009    return next(e)
1010  })
1011
1012  on('tool.call', async ($, e, next) => {
1013    // A call to an MCP server is bracketed here — counted before `next`,
1014    // released in the `finally`, so an error and an abort both release it —
1015    // and its row sweeps while the count is above zero. The event carries no
1016    // provider, so the server comes from the tool name.
1017    const server = needs.has('mcp') ? serverOfTool(e.tool) : undefined
1018    if (server) {
1019      mcpCalls = { ...mcpCalls, [server]: (mcpCalls[server] ?? 0) + 1 }
1020      void writeMcpRows($).catch(() => undefined)
1021    }
1022    try {
1023      return await next(e)
1024    } finally {
1025      if (server) {
1026        mcpCalls = { ...mcpCalls, [server]: Math.max((mcpCalls[server] ?? 1) - 1, 0) }
1027        void writeMcpRows($).catch(() => undefined)
1028      }
1029      if (needs.has('git') && GIT_TOOLS.has(e.tool)) void refreshGit($).catch(() => undefined)
1030    }
1031  })
1032
1033  // While the Sidebar is docked with Todo on, a main-loop task call runs as ctui's
1034  // own `$.tool.call`: the tool's `set_expanded_view` progress never reaches the
1035  // REPL, so Claude Code's own list stays closed. It runs here, not in a hook of
1036  // its own, since ctui's own call skips ctui's `tool.call` hooks.
1037  const hidesList = (agentId: string | undefined) => agentId === undefined && dockColumns > 0 && needs.has('todo')
1038
1039  // A task tool's call reloads the list.
1040  on('tool.call', { tool: 'TaskCreate' }, async ($, e, next) => {
1041    const done = hidesList(e.agentId) ? await ownCall($.tool.call(e)) : await next(e)
1042    if (needs.has('todo') && done.result && !done.isError) {
1043      // Once ctui's own call has replaced `next`, nothing later may throw: the
1044      // engine would run the tool again. A refusal costs the row its activeForm.
1045      await keepActiveForm($, done.result.task.id, e.activeForm).catch(() => undefined)
1046      void loadTodo($).catch(() => undefined)
1047    }
1048    return done
1049  })
1050
1051  on('tool.call', { tool: 'TaskUpdate' }, async ($, e, next) => {
1052    const done = hidesList(e.agentId) ? await ownCall($.tool.call(e)) : await next(e)
1053    if (needs.has('todo') && done.result && !done.isError) {
1054      // Once ctui's own call has replaced `next`, nothing later may throw: the
1055      // engine would run the tool again. A refusal costs the row its activeForm.
1056      await keepActiveForm($, e.taskId, e.activeForm).catch(() => undefined)
1057      void loadTodo($).catch(() => undefined)
1058    }
1059    return done
1060  })
1061
1062  on('tool.call', { tool: 'TodoWrite' }, async ($, e, next) => {
1063    const done = await next(e)
1064    if (!needs.has('todo') || !done.result || done.isError) return done
1065    // Before the first load or after `/clear`, the tick's load replays the transcript.
1066    const { value } = await $.state.get(TODO)
1067    if (value?.tools === 'todowrite') {
1068      await setTodo($, { tools: 'todowrite', items: todoWriteItems(done.result.newTodos) })
1069    }
1070    return done
1071  })
1072
1073  // MEMORY.md "Agent and shell events go to toasts, the live list goes to the
1074  // sidebar", "Task ends come from notifications" and "A Workflow run is one
1075  // task row; teammates stay hidden". Every task hook observes only.
1076  on('agent.spawn', async ($, e, next) => {
1077    const done = await next(e)
1078    if (tracking && done.agentId && !e.isTeammate && !e.workflow) {
1079      const id = done.agentId
1080      await updateTasks($, (tasks, now) => {
1081        const task: Task = {
1082          id,
1083          kind: 'agent',
1084          type: e.subagentType,
1085          label: e.description,
1086          ...(e.parentAgentId && { parent: e.parentAgentId }),
1087          status: 'running',
1088          listed: 'running',
1089          startedAt: now,
1090        }
1091        tasks[id] = task
1092        return [startedToast(task)]
1093      })
1094    }
1095    return done
1096  })
1097
1098  // An agent dead on an API error: StopFailure comes before the list says `failed`.
1099  on('classic.StopFailure', async ($, e, next) => {
1100    const id = e.agent_id
1101    if (tracking && id) {
1102      await updateTasks($, (tasks) => {
1103        const task = tasks[id]
1104        if (task?.kind === 'agent') tasks[id] = { ...task, reason: failureReason(e.error) }
1105      })
1106    }
1107    return next(e)
1108  })
1109
1110  // A background shell: from the main loop, a held agent, or an agent of a
1111  // running Workflow run (nested quietly under the run whose transcripts hold it).
1112  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
1113    const done = await next(e)
1114    const id = done.isError ? undefined : done.result?.backgroundTaskId
1115    if (!tracking || !id) return done
1116    const agentId = e.agentId
1117    await updateTasks($, async (tasks, now) => {
1118      const label = firstLine(e.command)
1119      const shell: Task = { id, kind: 'shell', type: 'shell', label, status: 'running', startedAt: now }
1120      if (!agentId || tasks[agentId]) {
1121        tasks[id] = { ...shell, ...(agentId && { parent: agentId }) }
1122        return [startedToast(shell)]
1123      }
1124      for (const run of Object.values(tasks)) {
1125        if (run.kind !== 'workflow' || run.status !== 'running' || !run.transcriptDir) continue
1126        const found = await $.fs.stat(`${run.transcriptDir}/agent-${agentId}.jsonl`).catch(() => undefined)
1127        if (found) {
1128          tasks[id] = { ...shell, parent: run.id }
1129          return
1130        }
1131      }
1132    })
1133    return done
1134  })
1135
1136  on('tool.call', { tool: 'Workflow' }, async ($, e, next) => {
1137    const done = await next(e)
1138    const result = done.isError ? undefined : done.result
1139    if (tracking && result?.taskId) {
1140      const id = result.taskId
1141      await updateTasks($, (tasks, now) => {
1142        const task: Task = {
1143          id,
1144          kind: 'workflow',
1145          type: 'workflow',
1146          label: result.workflowName ?? 'workflow',
1147          ...(result.transcriptDir && { transcriptDir: result.transcriptDir }),
1148          status: 'running',
1149          startedAt: now,
1150        }
1151        tasks[id] = task
1152        return [startedToast(task)]
1153      })
1154    }
1155    return done
1156  })
1157
1158  // The model's TaskStop sends no notification: its result is the kill.
1159  on('tool.call', { tool: 'TaskStop' }, async ($, e, next) => {
1160    const done = await next(e)
1161    const id = done.isError ? undefined : done.result?.task_id
1162    if (tracking && id) {
1163      await updateTasks($, (tasks, now) => {
1164        const task = tasks[id]
1165        return task?.status === 'running' ? endTask(tasks, task, 'killed', now, true) : undefined
1166      })
1167    }
1168    return done
1169  })
1170
1171  on('prompt.submit', { origin: { kind: 'task-notification' } }, async ($, e, next) => {
1172    if (tracking) await onNotification($, e.text)
1173    return next(e)
1174  })
1175
1176  // A /tasks kill's notification comes only as this row, with the next prompt.
1177  on('session.append', { door: 'delivery', message: { name: 'queued_command' } }, async ($, e, next) => {
1178    if (tracking) await onNotification($, textOf(e.message.content))
1179    return next(e)
1180  })
1181
1182  // A subagent's shell reports its end into that subagent's loop, with no
1183  // `prompt.submit`. The main loop's door-`prompt` rows (the synthetic
1184  // `stopped` after /resume) carry no `agentId` and stay unread.
1185  on('session.append', { door: 'prompt', origin: { kind: 'task-notification' } }, async ($, e, next) => {
1186    if (tracking && e.agentId) await onNotification($, textOf(e.message.content))
1187    return next(e)
1188  })
1189
1190  // Every invocation, whoever made it: typed, the Skill tool (a subagent's
1191  // too), a fork, a preload, a markdown command. Observe only.
1192  on('skill.prompt', ($, e, next) => {
1193    if (needs.has('skills')) void addSkills($, e.skill, e.text, stated(e)).catch(() => undefined)
1194    return next(e)
1195  })
1196
1197  // /clear and /resume empty `$.state` while running work goes on: the tick
1198  // merges it into the new session.
1199  // An order the menu moved and never saved is written as the session ends,
1200  // but not on /clear or /resume: the write's reload would lose `carry` and
plugins/index.ts 20 lines
1import type { SidebarPlugin } from './plugin'
2
3import agents from './agents'
4import context from './context'
5import git from './git'
6import limits from './limits'
7import mcp from './mcp'
8import skills from './skills'
9import todo from './todo'
10import versions from './versions'
11
12// Static registry in default Sidebar order: validation rejects dynamic
13// import(). Keep folders and these imports equal, and an `<id>_enable` key in
14// plugin.json for each section; the git header and versions footer are always
15// on (scripts/check.ts checks).
16export const plugins: readonly SidebarPlugin[] = [git, context, limits, todo, skills, mcp, agents, versions]
17
18// The sections between the header and footer, the ones a person can turn off and reorder.
19export const sections = plugins.filter((plugin) => plugin.slot === 'section')
20
plugins/clients.ts 56 lines
1import type { RenderElement, RenderNode } from 'claude-code'
2
3import type { FoldRowProps } from '../hooks/foldrow'
4import type { PressProps } from '../hooks/press'
5import type { SidebarClients } from './plugin'
6import type { SpinnerProps } from '../hooks/spinner'
7
8// A Client placeholder: where a Sidebar `Client` goes, as plain data: which of
9// the three, its key, its width and its props. A Sidebar plugin leaves one in
10// its tree, and the Sidebar's render hook in register.tsx draws each as its
11// `Client`, the only place one is written (MEMORY.md "Sidebar plugins are
12// pure; only `register.tsx` touches `$`").
13export type ClientPlaceholder =
14  | { client: 'press'; key: string; props: PressProps }
15  | { client: 'foldRow'; key: string; width: number; props: FoldRowProps }
16  | { client: 'sweep'; key: string; props: SpinnerProps }
17
18// A placeholder in a tree: an empty Box that holds it until the hook draws its Client.
19type Holder = RenderElement & { clientPlaceholder: ClientPlaceholder }
20
21const holderOf = (clientPlaceholder: ClientPlaceholder): RenderElement => {
22  const holder: Holder = { type: 'Box', clientPlaceholder }
23  return holder
24}
25
26// The Sidebar's three Client draws, each returning its placeholder.
27export const clientPlaceholders: SidebarClients = {
28  press: (key, props) => holderOf({ client: 'press', key, props }),
29  foldRow: (key, width, props) => holderOf({ client: 'foldRow', key, width, props }),
30  sweep: (key, props) => holderOf({ client: 'sweep', key, props }),
31}
32
33// The placeholder `node` holds, if it holds one.
34export const placeholderOf = (node: RenderNode): ClientPlaceholder | undefined =>
35  typeof node === 'object' && 'clientPlaceholder' in node ? (node as Holder).clientPlaceholder : undefined
36
37// Every Client placeholder in `node`'s tree, at any depth, for the render hook
38// to build each one's `Client` in its own body.
39export const placeholdersIn = (node: RenderElement): ClientPlaceholder[] => {
40  const held = placeholderOf(node)
41  if (held) return [held]
42  if (!('children' in node) || !node.children) return []
43  return node.children.flatMap((child) => (typeof child === 'string' ? [] : placeholdersIn(child)))
44}
45
46// `node`'s tree with each placeholder swapped for the element the render hook
47// built for it. Keyed by the placeholder itself: two sections can leave the
48// same key (`spinner-1` from Todo and from MCP).
49export const withClients = (node: RenderElement, ready: ReadonlyMap<ClientPlaceholder, RenderElement>): RenderElement => {
50  const held = placeholderOf(node)
51  if (held) return ready.get(held) ?? node
52  if (!('children' in node) || !node.children) return node
53  const children = node.children.map((child) => (typeof child === 'string' ? child : withClients(child, ready)))
54  return { ...node, children } as RenderElement
55}
56
plugins/colors.ts 21 lines
1// The Sidebar's 7 color roles and the Claude Code theme key each draws with
2// (MEMORY.md "Sidebar colors inherit the Claude Code theme").
3const KEYS = {
4  main: 'text',
5  muted: 'inactive',
6  faint: 'subtle',
7  success: 'success',
8  warning: 'warning',
9  error: 'error',
10  accent: 'suggestion',
11} as const
12
13export type Role = keyof typeof KEYS
14export type Colors = Record<Role, string>
15
16// Each role's color: a selected Theme's override for its key, else the key
17// itself, which Claude Code resolves from the person's theme at draw time.
18// Under `inherit` there are no overrides.
19export const colors = (overrides: Readonly<Record<string, string>> = {}): Colors =>
20  Object.fromEntries(Object.entries(KEYS).map(([role, key]) => [role, overrides[key] ?? key])) as Colors
21
plugins/plugin.ts 61 lines
1import type { ElementTable, RenderElement, RenderNode } from 'claude-code'
2
3import type { SectionConfig } from '../hooks/config'
4import type { FoldRowProps } from '../hooks/foldrow'
5import type { PressProps } from '../hooks/press'
6import type { GitSnapshot, McpRow, SkillRow, Task, Todo, Usage, Versions } from '../types'
7import type { Colors } from './colors'
8import type { SpinnerProps } from '../hooks/spinner'
9
10export type SidebarId = 'git' | 'context' | 'limits' | 'todo' | 'skills' | 'mcp' | 'agents' | 'versions'
11
12// What register.tsx loads for the enabled plugins' `needs`.
13export type SidebarData = {
14  git?: GitSnapshot
15  usage?: Usage
16  monthCost?: number // the ended sessions' cost this month, without the live session's
17  now?: number
18  mcp?: McpRow[]
19  todo?: Todo
20  skills?: readonly SkillRow[]
21  tasks?: Record<string, Task>
22  versions?: Versions
23}
24
25// The Sidebar's `Client`s, each under its `key`: a fold arrow or list toggle
26// (`press.tsx`), a section's title row (`foldrow.tsx`) and a working row's
27// sweep (`spinner.tsx`). Each returns a Client placeholder (`clients.ts`)
28// that the Sidebar's render hook in register.tsx draws as its `Client`, the only
29// place one is written (MEMORY.md "Sidebar plugins are pure; only
30// `register.tsx` touches `$`").
31export type SidebarClients = {
32  press: (key: string, props: PressProps) => RenderElement
33  foldRow: (key: string, width: number, props: FoldRowProps) => RenderElement
34  sweep: (key: string, props: SpinnerProps) => RenderElement
35}
36
37// The Sidebar's elements, from the surfaces that draw a Client, and its Clients.
38export type SidebarUi = Pick<ElementTable<'terminal' | 'desktop'>, 'Box' | 'Text' | 'Button'> & SidebarClients
39
40// `width` is the row's width in cells. `colors` holds each role's color.
41type Draw<T> = (data: SidebarData, ui: SidebarUi, cfg: SectionConfig, width: number, colors: Colors) => T
42
43// A Sidebar plugin: pure, never receives `$`. register.tsx loads the data
44// each plugin `needs` and passes the element table from `$.ui.resolve(e)`.
45// Every color is a role from `colors`: a Text with no color draws in the
46// terminal's foreground, not the theme's.
47// `view` returns one node per row. A `section` gets a header row with a fold
48// button: `count` shows at its right while expanded, `summary` while folded.
49// A `list` section is capped at `cap` rows, 4 unless it sets its own.
50export type SidebarPlugin = {
51  id: SidebarId
52  title: string
53  slot: 'header' | 'section' | 'footer'
54  needs: readonly (keyof SidebarData)[]
55  list?: true
56  cap?: number
57  view: Draw<readonly RenderNode[]>
58  count?: Draw<RenderNode | undefined>
59  summary?: Draw<RenderNode | undefined>
60}
61
hooks/build.ts 6 lines
1// The version of ctui running.
2// Claude Code installs a plugin from a marketplace into
3// `plugins/cache/<marketplace>/<plugin>/<version>`, named by plugin.json's `version`;
4// any other folder is one `--plugin-dir` loaded.
5export const build = (root: string) => /[\\/]plugins[\\/]cache[\\/][^\\/]+[\\/][^\\/]+[\\/]([^\\/]+)$/.exec(root)?.[1] ?? 'local'
6
hooks/config.ts 82 lines
1import type { PluginOptions } from 'claude-code'
2
3import { plugins, sections } from '../plugins'
4import type { SidebarId } from '../plugins/plugin'
5import { MONTHLY_DEFAULT } from './monthly-default'
6
7// One Sidebar plugin's settings: `<id>_enable`, for a foldable one
8// `<id>_folded`, for `todo` `todo_tools`, and for `limits` `limits_cost` and
9// `limits_cost_monthly`.
10export type SectionConfig = { enable: boolean; folded?: boolean; tools?: boolean; cost?: CostChoice; monthly?: number }
11
12// ctui's `userConfig` keys, as `plugin.json` lists them.
13const SETTING_KEYS = [
14  'context_enable',
15  'context_folded',
16  'limits_enable',
17  'limits_folded',
18  'limits_cost',
19  'limits_cost_monthly',
20  'todo_enable',
21  'todo_folded',
22  'todo_tools',
23  'skills_enable',
24  'skills_folded',
25  'mcp_enable',
26  'mcp_folded',
27  'agents_enable',
28  'agents_folded',
29  'agents_toasts',
30  'order',
31  'theme',
32] as const
33export type SettingKey = (typeof SETTING_KEYS)[number]
34export const isSettingKey = (key: string): key is SettingKey => SETTING_KEYS.some((setting) => setting === key)
35
36// `auto` shows the Limits cost row off a plan; `on` and `off` override that.
37export type CostChoice = 'auto' | 'on' | 'off'
38
39export type Config = Record<SidebarId, SectionConfig> & {
40  agents: SectionConfig & { toasts: boolean }
41  limits: SectionConfig & { cost: CostChoice; monthly: number }
42  todo: SectionConfig & { tools: boolean }
43  theme: string
44  order: SidebarId[] // the section ids, every one once
45}
46
47// The `order` setting's section ids: unknown and repeated ids dropped,
48// missing ones appended in registry order.
49function sectionOrder(order: unknown): SidebarId[] {
50  const ids = sections.map((plugin) => plugin.id)
51  const listed = typeof order === 'string' ? order.split(',').map((id) => id.trim()) : []
52  return [...new Set([...listed, ...ids])].filter((id): id is SidebarId => ids.some((section) => section === id))
53}
54
55// Regroups the flat `userConfig` options (MEMORY.md "Plugin settings are flat
56// `userConfig` keys").
57export function readConfig(options: PluginOptions): Config {
58  const sections = {} as Record<SidebarId, SectionConfig>
59  for (const { id, slot } of plugins) {
60    const folded = options[`${id}_folded`]
61    sections[id] = {
62      // The git header and versions footer are always on.
63      enable: slot !== 'section' || options[`${id}_enable`] !== false,
64      ...(typeof folded === 'boolean' && { folded }),
65    }
66  }
67  return {
68    ...sections,
69    agents: { ...sections.agents, toasts: options.agents_toasts !== false },
70    limits: {
71      ...sections.limits,
72      // Unset, the cost row is off: showing it reads this month's transcripts.
73      cost: options.limits_cost === 'on' || options.limits_cost === 'auto' ? options.limits_cost : 'off',
74      // A non-number limit, possible only by hand-editing settings.json, reads as the default.
75      monthly: typeof options.limits_cost_monthly === 'number' ? options.limits_cost_monthly : MONTHLY_DEFAULT,
76    },
77    todo: { ...sections.todo, tools: options.todo_tools !== false },
78    theme: typeof options.theme === 'string' ? options.theme : 'inherit',
79    order: sectionOrder(options.order),
80  }
81}
82
hooks/floor.ts 19 lines
1// The support floor: the lowest Claude Code version ctui runs on (CONTEXT.md
2// "Support floor"). `node scripts/check.ts` ties it to README.md, ctui/README.md and
3// the types in vendor/claude-code-types-floor/.
4export const FLOOR = '2.1.292'
5
6const core = (version: string) => /^(\d+)\.(\d+)\.(\d+)/.exec(version)?.slice(1).map(Number)
7
8// Whether an engine version is older than the floor. A version not spelled
9// `x.y.z…` is taken as new enough: a wrong toast is worse than none.
10export function belowFloor(version: string): boolean {
11  const have = core(version)
12  const need = core(FLOOR)!
13  if (!have) return false
14  for (let i = 0; i < 3; i++) if (have[i] !== need[i]) return have[i]! < need[i]!
15  return false
16}
17
18export const floorToast = (version: string) => `ctui needs Claude Code ${FLOOR} or later; this is ${version}`
19
hooks/format.ts 95 lines
1// Pure formatters for the Sidebar's rows.
2
3const MINUTE = 60_000
4const HOUR = 60 * MINUTE
5const DAY = 24 * HOUR
6const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
7
8export type Level = 'success' | 'warning' | 'error'
9
10// The role of a bar's fill.
11export const level = (percent: number): Level => (percent < 50 ? 'success' : percent < 85 ? 'warning' : 'error')
12
13// `18,402`
14export const formatTokens = (tokens: number) => tokens.toLocaleString('en-US')
15
16// `200k`, `1M`
17export const formatWindow = (tokens: number) =>
18  tokens >= 1_000_000 ? `${+(tokens / 1_000_000).toFixed(1)}M` : `${Math.round(tokens / 1000)}k`
19
20// `0.21$`: the sign after the digits, as everywhere in the Limits section.
21export const formatUsd = (usd: number) => `${usd.toFixed(2)}$`
22
23// `62$`, in whole dollars.
24export const formatDollars = (usd: number) => `${Math.round(usd)}$`
25
26// `resets in 2h 17m`; past a day, `resets in 3d 4h, Mon 09:00` in local 24-hour time.
27export function formatReset(resetsAt: string, now: number): string {
28  const at = new Date(resetsAt)
29  const left = Math.max(at.getTime() - now, 0)
30  if (left <= DAY) {
31    const hours = Math.floor(left / HOUR)
32    const minutes = Math.floor((left % HOUR) / MINUTE)
33    return `resets in ${hours ? `${hours}h ` : ''}${minutes}m`
34  }
35  const pad = (n: number) => String(n).padStart(2, '0')
36  const clock = `${WEEKDAYS[at.getDay()]} ${pad(at.getHours())}:${pad(at.getMinutes())}`
37  return `resets in ${Math.floor(left / DAY)}d ${Math.floor((left % DAY) / HOUR)}h, ${clock}`
38}
39
40// A bar of `width` cells for `percent`: filled `━`, empty `─`. Past 100 it is full.
41export function bar(percent: number, width: number): { filled: string; empty: string } {
42  const cells = Math.max(width, 0)
43  const filled = Math.round((cells * Math.min(Math.max(percent, 0), 100)) / 100)
44  return { filled: '━'.repeat(filled), empty: '─'.repeat(cells - filled) }
45}
46
47// A percent right of a bar, at least 5 columns and always one space from it:
48// `   9%`, ` 100%`, ` 1133%`. The bar takes what is left of the row.
49export const formatPercent = (percent: number) => ` ${Math.round(percent)}%`.padStart(5)
50
51// `21s`, `1m 15s`, `15m 03s`, `1h 02m`.
52export function formatElapsed(ms: number): string {
53  const seconds = Math.floor(Math.max(ms, 0) / 1000)
54  const pad = (n: number) => String(n).padStart(2, '0')
55  if (seconds < 60) return `${seconds}s`
56  if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${pad(seconds % 60)}s`
57  return `${Math.floor(seconds / 3600)}h ${pad(Math.floor((seconds % 3600) / 60))}m`
58}
59
60// MEMORY.md "The turn footer": the mode as Claude Code's pill names it.
61const MODES: Record<string, string> = {
62  default: 'manual mode',
63  acceptEdits: 'accept edits',
64  plan: 'plan mode',
65  bypassPermissions: 'bypass permissions',
66  auto: 'auto mode',
67  dontAsk: "don't ask",
68}
69
70export const modeLabel = (mode: string) => MODES[mode] ?? mode
71
72// MEMORY.md "The line under the prompt": `claude-opus-5-5 · high effort`, or
73// the model alone when it takes no effort (`null`) or none is known.
74export const promptLabel = (model: string, effort: string | null | undefined) =>
75  effort ? `${model} · ${effort} effort` : model
76
77// The widest pill, `⏵⏵ bypass permissions on`.
78const PILL = 24
79
80// The label fits the line beside the pill and the hint, from `columns` wide.
81export const fitsPromptLine = (hint: string, label: string, columns: number) =>
82  2 + PILL + 1 + hint.length + 2 + label.length <= columns
83
84type Settings = Readonly<Record<string, unknown>>
85
86// `modelSettings[<model>].effortLevel`: the level `/effort` saved for the model.
87export const modelEffort = (settings: Settings, model: string): unknown =>
88  (settings.modelSettings as Record<string, { effortLevel?: unknown }> | undefined)?.[model]?.effortLevel
89
90// The effort a model starts a session with: its own saved level, else the global one.
91export function savedEffort(settings: Settings, model: string): string | undefined {
92  const level = modelEffort(settings, model) ?? settings.effortLevel
93  return typeof level === 'string' ? level : undefined
94}
95
hooks/git.ts 40 lines
1import type { GitRepo } from '../types'
2
3// Parses `git status --porcelain=v2 --branch`, `git stash list` and
4// `git diff --numstat HEAD` into the git header's repo rows.
5export function parseGit(status: string, stash: string, numstat: string): GitRepo {
6  const repo: GitRepo = { branch: '', staged: 0, modified: 0, untracked: 0, stashes: 0, added: 0, removed: 0 }
7  let oid = ''
8  for (const line of status.split('\n')) {
9    const [kind, field, value = ''] = line.split(' ')
10    if (kind === '#') {
11      if (field === 'branch.oid') oid = value
12      else if (field === 'branch.head') repo.branch = value
13      else if (field === 'branch.ab') {
14        repo.ahead = Number(value.slice(1))
15        repo.behind = Number(line.split(' ')[3]?.slice(1))
16      }
17    } else if (kind === '1' || kind === '2') {
18      if (field?.[0] !== '.') repo.staged++
19      if (field?.[1] !== '.') repo.modified++
20    } else if (kind === 'u') repo.modified++
21    else if (kind === '?') repo.untracked++
22  }
23  if (repo.branch === '(detached)') repo.branch = oid.slice(0, 7)
24  repo.stashes = stash.split('\n').filter(Boolean).length
25  for (const line of numstat.split('\n')) {
26    const [added, removed] = line.split('\t')
27    // Binary files read `-`: they count 0.
28    repo.added += Number(added) || 0
29    repo.removed += Number(removed) || 0
30  }
31  return repo
32}
33
34// The cwd with the home directory shown as `~`.
35export function tildify(cwd: string, home: string | undefined): string {
36  if (!home) return cwd
37  if (cwd === home) return '~'
38  return cwd.startsWith(`${home}/`) ? `~${cwd.slice(home.length)}` : cwd
39}
40
hooks/mcp.ts 110 lines
1import type { McpRow } from '../types'
2
3// What the `mcp` Sidebar plugin reads each tick (MEMORY.md "The `mcp` Sidebar
4// plugin reads live tools and MCP config names; it never probes").
5export type McpInput = {
6  rows: readonly McpRow[] // the previous tick's
7  tools: readonly { name: string; mcp: boolean }[] // `$.tool.list()`
8  disabled: readonly string[] // `disabledMcpServers`, as /mcp names them
9  names: Readonly<Record<string, string>> // segment → /mcp name, from `tool.describe`
10  now: number
11  timeoutMs: number // MCP_TIMEOUT
12  sources: McpSources
13  busy: Readonly<Record<string, number>> // calls in flight per segment, from register.tsx's module variable
14}
15
16// The `/mcp` names each config source holds (names only: an entry can hold
17// secrets), and the source a tool run reported for a server, by segment.
18export type McpSources = Record<(typeof SCOPES)[number], readonly string[]> & {
19  observed: Readonly<Record<string, string>> // `classic.PostToolUse` `mcp_server.source`
20}
21
22// Claude Code's own lookup order for a name's scope.
23const SCOPES = ['enterprise', 'managed', 'local', 'project', 'user'] as const
24
25export const NO_SOURCES: McpSources = { enterprise: [], managed: [], local: [], project: [], user: [], observed: {} }
26
27// The tools a server offers before its sign-in.
28const AUTH_TOOLS = new Set(['authenticate', 'complete_authentication'])
29
30// Busy over the rows as they stand: a row is busy while at least one call to
31// that server is in flight, and the flag goes the moment the count is back at
32// zero — no hold, no floor.
33// The row says nothing about how many are running.
34export const withBusy = (rows: readonly McpRow[], busy: Readonly<Record<string, number>>): McpRow[] =>
35  rows.map(({ busy: _was, ...row }) => ((busy[row.server] ?? 0) > 0 ? { ...row, busy: true } : row))
36
37// The server a `tool.call` names. That event carries no provider, so the
38// segment comes from the tool name the way the tick's rows do: the second
39// `__` segment of an `mcp__<server>__<tool>` name, and nothing for any other tool.
40export function serverOfTool(tool: string): string | undefined {
41  const [mcp, server, name] = tool.split('__')
42  return mcp === 'mcp' && server && name !== undefined ? server : undefined
43}
44
45// A /mcp name as it shows in tool names: `claude.ai Claude Docs` → `claude_ai_Claude_Docs`.
46export const segmentOf = (name: string) => name.replace(/[^A-Za-z0-9_-]/g, '_')
47
48// The server a `tool.describe` provider names, as its tool segment and /mcp
49// name: `mcp:<name>` for a configured server; `<plugin>@<marketplace>` for a
50// plugin's, whose /mcp name is `plugin:<plugin>:<server>`.
51export function serverName(tool: string, provider: string): [segment: string, name: string] | undefined {
52  const configured = /^mcp:(.+)$/.exec(provider)?.[1]
53  if (configured) return [segmentOf(configured), configured]
54  const [mcp, segment = ''] = tool.split('__')
55  const plugin = /^([^@]+)@/.exec(provider)?.[1]
56  const prefix = `plugin_${segmentOf(plugin ?? '')}_`
57  if (mcp === 'mcp' && plugin && segment.startsWith(prefix)) {
58    return [segment, `plugin:${plugin}:${segment.slice(prefix.length)}`]
59  }
60}
61
62// Where a server comes from: what a tool run reported, else `claude.ai` or the
63// plugin from its name, else the first config source holding it, else
64// `dynamic` (`--mcp-config`, which the mod can't read).
65function sourceOf(server: string, name: string | undefined, sources: McpSources) {
66  const plugin = /^plugin:([^:]+):/.exec(name ?? '')?.[1] ?? /^plugin_([^_]+)_/.exec(server)?.[1]
67  const observed = sources.observed[server]
68  if (observed) return observed === 'claudeai' ? 'claude.ai' : observed === 'plugin' && plugin ? plugin : observed
69  if (name?.startsWith('claude.ai ') || server.startsWith('claude_ai_')) return 'claude.ai'
70  if (plugin) return plugin
71  return SCOPES.find((scope) => sources[scope].some((held) => segmentOf(held) === server)) ?? 'dynamic'
72}
73
74const labelOf = (name: string) => name.replace(/^claude\.ai /, '').replace(/^plugin:[^:]+:/, '')
75const labelOfSegment = (segment: string) => segment.replace(/^claude_ai_/, '').replace(/^plugin_[^_]+_/, '')
76
77// The rows A–Z by label, off rows last: servers seen with tools this session
78// plus disabled ones. A listed server with no tools connects for `timeoutMs` from
79// the tick it lost them or left the disabled list, then reads down.
80export function mcpRows({ rows, tools, disabled, names, now, timeoutMs, sources, busy }: McpInput): McpRow[] {
81  const offered = new Map<string, string[]>()
82  for (const tool of tools) {
83    const [, server, name = ''] = tool.mcp ? tool.name.split('__') : []
84    if (server) offered.set(server, [...(offered.get(server) ?? []), name])
85  }
86  const off = new Map(disabled.map((name) => [segmentOf(name), name]))
87  const servers = [...new Set([...rows.map((row) => row.server), ...offered.keys(), ...off.keys()])]
88  const all: McpRow[] = servers.map((server) => {
89    const before = rows.find((row) => row.server === server)
90    const name = off.get(server) ?? names[server]
91    const label = name ? labelOf(name) : (before?.label ?? labelOfSegment(server))
92    const row = { server, label, source: sourceOf(server, name, sources) }
93    const toolNames = offered.get(server)
94    if (off.has(server)) return { ...row, state: 'off' }
95    if (toolNames?.length) {
96      return toolNames.every((tool) => AUTH_TOOLS.has(tool))
97        ? { ...row, state: 'auth' }
98        : { ...row, state: 'ok', tools: toolNames.length }
99    }
100    if (before?.state === 'down') return { ...row, state: 'down' }
101    const since = before?.state === 'connecting' ? (before.since ?? now) : now
102    return now - since >= timeoutMs ? { ...row, state: 'down' } : { ...row, state: 'connecting', since }
103  })
104  const sorted = all.sort(
105    (a, b) =>
106      +(a.state === 'off') - +(b.state === 'off') || a.label.localeCompare(b.label) || a.server.localeCompare(b.server),
107  )
108  return withBusy(sorted, busy)
109}
110
hooks/month.ts 62 lines
1import type { Usage } from '../types'
2import type { CostChoice } from './config'
3
4// The Limits cost row's month total: every session's last `cost-state` in its
5// transcript, counted in the local month the transcript was last written.
6
7// A session's total as last read from its transcript, kept in `$.store`.
8export type Cached = { usd: number; mtimeMs: number; size: number }
9
10// A main transcript, `<session id>.jsonl`, as `$.fs.list` gives it.
11export type Transcript = { session: string; path: string; mtimeMs: number; size: number }
12
13const pad = (n: number) => String(n).padStart(2, '0')
14
15// The local month, `2026-10`.
16export function monthOf(ms: number) {
17  const date = new Date(ms)
18  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}`
19}
20
21// Midnight local time on the 1st.
22export function monthStart(ms: number) {
23  const date = new Date(ms)
24  return new Date(date.getFullYear(), date.getMonth(), 1).getTime()
25}
26
27// One `$.store` key per session, so concurrent sessions write apart; the
28// month in it drops earlier months by name.
29export const COST_PREFIX = 'cost:'
30export const costKey = (month: string, session: string) => `${COST_PREFIX}${month}:${session}`
31
32// `totalCostUSD` from the last `cost-state` line per `sessionId` in grep's output.
33export function lastCosts(stdout: string) {
34  const costs: Record<string, number> = {}
35  for (const line of stdout.split('\n')) {
36    try {
37      const { sessionId, totalCostUSD } = JSON.parse(line)
38      if (typeof sessionId === 'string' && typeof totalCostUSD === 'number') costs[sessionId] = totalCostUSD
39    } catch {
40      // Empty, or caught mid-write.
41    }
42  }
43  return costs
44}
45
46// The transcripts to grep: new ones, and ones whose size or mtime moved.
47export const staleTranscripts = (transcripts: readonly Transcript[], cached: Readonly<Record<string, Cached>>) =>
48  transcripts.filter(({ session, mtimeMs, size }) => cached[session]?.mtimeMs !== mtimeMs || cached[session]?.size !== size)
49
50// The ended sessions' total: the current session counts by its live cost instead.
51export const monthTotal = (cached: Readonly<Record<string, Cached>>, current: string) =>
52  Object.entries(cached).reduce((sum, [session, { usd }]) => (session === current ? sum : sum + usd), 0)
53
54// A Claude plan reports a 5-hour or a weekly window; a gateway's `spend_limit`
55// alone isn't one.
56const onPlan = (usage: Usage) => usage.rateLimits.some(({ kind }) => kind === 'five_hour' || kind === 'seven_day')
57
58// Whether the cost row shows: unset is off, `auto` hides it on a plan, and it
59// needs a cost.
60export const showsCost = (usage: Usage | undefined, choice: CostChoice | undefined) =>
61  Boolean(usage?.cost && (choice === 'on' || (choice === 'auto' && !onPlan(usage))))
62