Mods Toolbox - Function-hook mods (Claude Code 2.1.291+): Clean View, a calm checklist above the prompt for non-technical users that hides tool calls, diffs…

Function-hook mods that change how Claude Code looks while it works:
They ship together because the dock's helpers report through Clean View's report_progress tool, and the Status Line Dock's Agents block shows the Agent Dock's helper count.
Claude Code 2.1.291 or newer. Mods use the function-hook plugin API, which is early access, so a later Claude Code release may change it.
claude plugin marketplace add rube-de/cc-skills
claude plugin install mods-toolbox@rube-cc-skills
Or at the prompt: /plugin install mods-toolbox --marketplace rube-de/cc-skills.
Coming from clean-view: this plugin used to be called clean-view. Run claude plugin uninstall clean-view@rube-cc-skills before installing it, or both copies register /simple, /dock and the tools twice. Clean View on/off, Team Size and helper model start back at their defaults.
A calm, friendly Claude Code for people who aren't technical. While Claude works, tool calls, file diffs and command output are hidden, and one checklist above the prompt shows the plan, what's happening now and how far along it is.
Build my landing page · 1m 12s
✓ Read your brand notes ██████████ Done
▶ Build the pricing section ██████░░░░ 60%
○ Add the contact form ░░░░░░░░░░ Next
○ Polish the footer ░░░░░░░░░░ Up next
Claude's written replies stay visible. Permission prompts and questions stay visible too, and switch the header to Needs you.
Clean View starts on. Use the Clean View switch in the Toolbox, or type:
| Command | Effect |
|---|---|
/simple | Flip it |
/simple on | Turn it on |
/simple off | Turn it off: every hidden row comes back |
Both work while Claude is busy, and the choice is remembered after a restart.
| Area | Behaviour |
|---|---|
| Plan first | Claude is asked to lay out 2 to 8 plain-English steps (plan_steps) before anything else, and other tools are refused until it has. A to-do list (TodoWrite, TaskCreate) also counts as a plan. Subagents are never gated. Off while Clean View is off. |
| Progress | Claude reports progress per step (report_progress); 100% checks a step off and starts the next. While Clean View is off, both tools stay registered but Claude's own calls change nothing, and plan_steps waits behind ToolSearch. report_progress stays in front because helpers' reports still reach the Agent Dock. |
| Job name | While Clean View is on, each new request sends one small Haiku call, at low effort, to name the job in 2 to 6 words. |
| Hidden rows | ToolUse, ToolResult and ToolGroup rows, and the "run in background" hint. |
| States | Working (also while background helpers are still out: · waiting for 3 helpers to finish), Needs you (permission prompt, question, waiting for your reply), Stuck (you said no, repeated failures, API errors in one plain sentence), Stopped (Esc), All done (shrinks to one line after 5 seconds). |
Pick a Team Size and every request you send is split across exactly that many helper agents running in parallel, each shown as its own card in a pane called Agent Dock.
◆ A G E N T D O C K ● L I V E
────────────────────────────────────────────────────────────────────────────
T E A M S I Z E ╭ 1 3 5 10 20 [50] 100 │ Custom ╮
Splits each request across 50 helpers · 20 at a time · Fast & Cheap
M I S S I O N Research bakery pricing 45% 1:12
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
● 20 working ○ 10 queued ✓ 20 done ✕ 0 stuck
| Command | Effect |
|---|---|
/dock | Open the dock, or fold it. While helpers run, a folded dock shows a badge under the prompt (20 working · 10 queued · 20 done); an idle one shows nothing |
/dock 10 | Set the Team Size (1 to 100) and open the dock |
| Agent Dock | The Toolbox's Launch entry opens it too |
CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS (default 20) instead of queueing it. The dock holds those calls until a slot frees up. "At a time" is the lower of that limit and CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY (default 10). Set both to 20 in the env block of your user settings for waves of 20.report_progress at about 25, 50, 75 and 100%, and each card's meter follows its own helper.Status line count: the Status Line Dock's Agents block shows ◇ N agents while helpers run. The dock writes the live count to ~/.claude/agent-dock/agents-now/<session id>.json (under $CLAUDE_CONFIG_DIR when set) and removes the file when they finish or the session ends.
Every face is a colored two-letter badge. Past 12 helpers the cards shrink to one-line tiles so 50 or 100 still fit. The animation clock runs only while a request is live, so the idle seats are a still row with no twinkle.
Cost: at size 50 every request becomes 50 agents. Keep the size at 1 unless you mean it.
Builds Claude Code's status line from blocks, with a live preview, and installs it for every project or for this one. Open it with ◆ Status Line Dock in the Toolbox's Launch section, or /status-dock. It takes the band above the prompt, full width, right above the real status line, so it shows in the terminal and the desktop app but not in VS Code or on mobile, which don't draw the band:
╭────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ◆ S T A T U S L I N E D O C K Global · installed · 2 lines · 9 blocks ✕ │
│ Mode Replace [Extend] Scope [Global] This project Icons [Glyph] Emoji None │
│ Keeps ~/.claude/statusline.sh │
│ ── B L O C K S ─────────────────────────────────────────────────────────────────────────────── │
│ Line 1 Folder Branch [Model] Effort │
│ Line 2 Context Cost Lines changed Session time Agents │
│ Off Version Style Rate limits Prompt cache Skill │
│ ── P R E V I E W ────────────────────────────────────────────── at 180 columns · nothing drops │
│ 📁 ~/code/app 🌿 main ✗ 🤖 Opus 5.5 │
│ ⌂ ~/code/app ⎇ main ✗ ◆ Opus 5.5 ◎ high │
│ ███░░░░░░░ 34% $0.53 +42 -18 ◷ 2m15s ◇ 3 agents │
│ h: ← l: → k: ↑ j: ↓ o: on/off i: icons a: Apply u: Uninstall │
│ click the Dock, then the keys · other keys go to the prompt │
╰────────────────────────────────────────────────────────────────────────────────────────────────╯
.../oasis/flexvaults-service), Branch (✗ while there are uncommitted changes, checked only in the repo the session started in, since git status runs programs a repo's own config names), Model (with the context size short, as Opus 5.5(1M)), Effort, Version, Style (the output style), Context (bar and % used), Cost, Lines changed, Session time, Rate limits (5-hour and 7-day, each with the time to its reset, as 5h 23% ↺2h10m), Prompt cache (cache 47m while warm, the time until it expires, amber in the last sixth of its TTL; cache cold once it lapsed), Agents (the Agent Dock's helpers working right now) and Skill (the skill this conversation ran last, typed as /name or called by Claude, by its full name such as council:review-plan: bright while that turn runs, gray after; a helper's skills don't count). A block Claude Code has no figure for yet is left out of the line.ctrl+x tab, hands it the keys, starting on the selected block, so Enter there only selects it. Esc, or any key the Dock doesn't use, hands them back to the prompt, and that key is typed there. Tab to a block and Enter, or a click, selects it; one that is Off is turned on too, at the end of the last line in use. Then h and l move it along its line, k and j move it between Line 1, Line 2 and Off, o turns it off or on, i cycles the icons (Glyph, Emoji, None, also chips to click), a applies, r reverts edits not applied yet and u uninstalls. Letters only: a digit typed into an empty prompt would press a band button.statusLine in your user settings.json; This project sets it in .claude/settings.local.json, with a reminder to keep that out of git. Each scope has its own Layout, and a project's starts from the global one. In Extend, a project with no status line of its own keeps following the one it inherits, read on every refresh, so a later change there still shows. When that is the Dock's own global line, the project keeps what the global Layout keeps instead, so no block shows twice.statusLine block, in the file's own indentation, writes through a settings file that is a symlink into a dotfiles repo, and sets refreshInterval to 2 seconds unless yours is already 1 or 2. Once installed, Apply saves only the Layout, and the status line picks it up at its next refresh.statusLine block back exactly as the install found it (or takes it out, or deletes the settings file the install created), and deletes ~/.claude/mods-toolbox/ once no scope uses it. With no record of the install on this machine, as with a settings file from another machine's dotfiles, it takes the Dock's line out. A status line you changed by hand since is left alone.~/.claude/mods-toolbox/skill-now/<session id>.json, writes it again at the end of each turn, and removes it when the session ends or /clear starts a new one. A file no turn has touched for a day goes at the next session start; if its session is still open, the file comes back at that session's next turn end.jq (macOS 15 ships /usr/bin/jq); without it the status line reads status line needs jq. The renderer and Layouts live in ~/.claude/mods-toolbox/ (under $CLAUDE_CONFIG_DIR when set), so the status line keeps working if the plugin goes; use Uninstall first to take it out. A settings file shared through a dotfiles repo gets the renderer on another machine at that machine's next session; open the Dock there and Apply to write its Layout. ADR 0001 says why it's a shell script.Coming from /mods-toolbox:dock-setup: that skill is gone. Open the Dock and Install: it unwraps the add-on, and deletes it once no other project's settings run it.
◆ Toolbox ▾ at the right of the prompt footer, or /toolbox, opens one popup above the prompt with Claude's model and effort and both mods' settings:
╭────────────────────────────────────────────────────────────────╮
│ ◆ T O O L B O X Opus 5.5 · 1M · high ✕ │
│ ── M O D E L C O N F I G ─────────────────────────────────── │
│ ◇ Model saved as default Haiku Sonnet [Opus] Fable │
│ ◇ Effort thinking depth Low Medium [High] XHigh Max │
│ ○ Ultracode workflows on every task ○ On ● Off │
│ ── S E T T I N G S ─────────────────────────────────────────── │
│ ● Clean View simple checklist ● On ○ Off │
│ ◇ Team size per request 1 3 [5] 10 20 50 100 Custom │
│ ◇ Helpers model they use Fast & Cheap Same as me │
│ ── L A U N C H ─────────────────────────────────────────────── │
│ ◆ Agent Dock team of 5 │
│ ◆ Status Line Dock 2 lines · 9 blocks │
╰────────────────────────────────────────────────────────────────╯
/model and /effort does: for this chat now, and saved as your default for new sessions (in your user settings.json; effort per model). Claude Code runs those commands only when Claude isn't working, so a pick made mid-task shows in gold with ◷ switches when Claude is done working. Each switch adds the command's one-line confirmation to the chat./config model row lists, and keeps 1M context when the chat is on it. The row is left out when your organization locks the model./effort ultracode on or off: dynamic workflows on every task, which Claude Code reports as for this session only. No API reads it, so the row starts at Off and follows the toggle and a typed /effort ultracode. If Claude Code refuses it, as on a plan without Ultracode, the refusal shows as a toast and the row goes for the rest of the session. A mistyped /effort ultracode leaves the row as it was.settings.json, so a session started with --effort shows the real level after its first answer. Each model has its own effort, so after a model switch the row shows the new model's from settings.json (its own level, else the general one), the way Claude Code picks it./model or /effort, or the /config model row, moves the popup too.· step 2 of 3) above it./simple and /dock, saved the same way. Team Size above 20 asks first, in gold, inside the popup./simple and /dock; the Status Line Dock has no command-only form, so set the status line up from the terminal or the desktop app.The checklist lives in $.state under the mods-toolbox key, typed in types/index.d.ts: cleanViewEnabled, checklist and tick, the dock's dockTeamSize, dockMission and the rest beside them, the Toolbox's bandView ('toolbox', 'statusLineDock' or null), chatModel (the session's model id) and chatEffort (its effort as last seen), and the Status Line Dock's statusLineSetup. List mods-toolbox under dependencies in your mod's plugin.json to get the types laid beside it.
claude --plugin-dir plugins/mods-toolbox # run it from this checkout
claude plugin validate plugins/mods-toolbox
claude plugin test plugins/mods-toolbox
bun test plugins/mods-toolbox/renderer # the status line renderer, run as a real shell script
hooks/register.tsx is the entry point: it calls registerToolbox(on) from hooks/toolbox.tsx first, then registerStatusLineDock(on) from hooks/status-line-dock.tsx, so both band hooks sit outside Clean View's, then registerChatPicks(on) from hooks/chat-picks.tsx, which runs /model and /effort for the popup's model config rows and keeps the effort last seen, then registerDock(on) from hooks/dock.tsx, so the dock's hook on a helper's report_progress runs before Clean View's, then registerCleanView(on) from hooks/clean-view.tsx. The engine follows $ only into functions of the same file, so the Toolbox draws its controls and Clean View, the dock and the chat picks answer their keys in their own ui.press and ui.input hooks; each file reads the shared values through its own atom on the same literal key. While the popup is open the Toolbox lays out the band: Clean View steps aside, and the checklist is drawn through the same $-free hooks/checklist-view.tsx both use, beside the popup or folded above it. The band's layout math is in hooks/toolbox-logic.ts, and the model names and /model arguments in hooks/chat-picks-logic.ts. Every step name goes through hooks/clean-name.ts, and both mods take percents and durations from hooks/progress.ts. The dock's logic that needs no $ (sizes, names, instruction texts, counts, meters) lives in hooks/dock-logic.ts so tests call it directly, and the Status Line Dock's (Layout edits, what the settings files hold, install and uninstall changes, the preview's input, colors to styled runs) in hooks/status-line-logic.ts. The status line itself is renderer/statusline.sh and renderer/statusline.jq; claude plugin test can't spawn a shell, so renderer/statusline.spec.ts runs under bun test, under sh and dash. Claude Code writes the API types into .claude-plugin/types/ (gitignored) when it loads the plugin, and tsconfig.json extends them, so tsc -p plugins/mods-toolbox works after one load.
hooks/register.tsx 20 lines1import type { Register } from 'claude-code'
2
3import { registerChatPicks } from './chat-picks'
4import { registerCleanView } from './clean-view'
5import { registerDock } from './dock'
6import { registerStatusLineDock } from './status-line-dock'
7import { registerToolbox } from './toolbox'
8
9// Registrations nest first-outermost. The Toolbox and the Status Line Dock wrap
10// the band Clean View draws, and the dock's hook on a helper's report_progress
11// runs before Clean View's catch-all answers it. The chat picks only answer
12// their own keys and watch Stop and /effort, so where they sit doesn't matter.
13export const register: Register = on => {
14 registerToolbox(on)
15 registerStatusLineDock(on)
16 registerChatPicks(on)
17 registerDock(on)
18 registerCleanView(on)
19}
20hooks/chat-picks.tsx 205 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On } from 'claude-code'
3
4import type { ChatEffort } from '../types'
5import {
6 FAMILIES,
7 effortFromSettings,
8 effortTaken,
9 familyOf,
10 isEffort,
11 modelArgs,
12 refusal,
13 ultracodeAsked,
14 ultracodeTaken,
15} from './chat-picks-logic'
16
17type Engine = EngineInterface
18
19// The Toolbox's model config rows switch the model, effort and Ultracode the
20// way typing /model and /effort does: once Claude is free, and in an
21// interactive session the model and effort are saved as the default for new
22// sessions too. The model is read back from the engine after every change; no
23// API reads the effort or Ultracode, so the last ones seen are kept here.
24const optionsAtom = atom({ plugin: 'mods-toolbox', key: 'chatModelOptions' } as const, null)
25const modelAtom = atom({ plugin: 'mods-toolbox', key: 'chatModel' } as const, null)
26const effortAtom = atom({ plugin: 'mods-toolbox', key: 'chatEffort' } as const, null)
27const modelPendingAtom = atom({ plugin: 'mods-toolbox', key: 'chatModelPending' } as const, null)
28const effortPendingAtom = atom({ plugin: 'mods-toolbox', key: 'chatEffortPending' } as const, null)
29const ultracodeAtom = atom({ plugin: 'mods-toolbox', key: 'chatUltracode' } as const, 'off')
30const ultracodePendingAtom = atom({ plugin: 'mods-toolbox', key: 'chatUltracodePending' } as const, null)
31
32const KEY = /^chat-(model|effort|ultracode)-(.+)$/
33
34/** Answers the Toolbox's `chat-*` presses and keeps the model, effort and Ultracode it draws current. */
35export function registerChatPicks(on: On) {
36 // Clean View holds the bare session.start, the dock its cwd matcher and the
37 // Toolbox its surface one.
38 on('session.start', { isInteractive: true }, async ($, e, next) => {
39 // A reload drops the runs a pick was waiting on, so nothing stays pending.
40 await update($, modelPendingAtom, () => null)
41 await update($, effortPendingAtom, () => null)
42 await update($, ultracodePendingAtom, () => null)
43 try {
44 await loadPicks($)
45 } catch {
46 // Without the /config row the model row stays out; effort shows once a turn ends.
47 }
48
49 return next(e)
50 })
51
52 // Every main turn's Stop carries the effort it ran at; the dock holds the bare hook.
53 on('classic.Stop', { cwd: /^/ }, async ($, e, next) => {
54 const level = e.effort?.level
55 if (e.agent_id === undefined && isEffort(level)) {
56 await update($, effortAtom, current => (current === level ? current : level)).catch(() => undefined)
57 }
58
59 return next(e)
60 })
61
62 // The person's /model and /config's model row move the chat too, not only the Toolbox.
63 on('command.run', { command: 'model' }, async ($, e, next) => {
64 const before = await read($, modelAtom)
65 const ran = await next(e)
66 await followModel($, before)
67
68 return ran
69 })
70
71 on('config.set', { key: 'model' }, async ($, e, next) => {
72 const before = await read($, modelAtom)
73 const set = await next(e)
74 await followModel($, before)
75
76 return set
77 })
78
79 // The person's own /effort moves the popup too.
80 on('command.run', { command: 'effort' }, async ($, e, next) => {
81 const ran = await next(e)
82 const ultracode = ultracodeAsked(e.args)
83 if (ultracode !== null) {
84 // A refusal means this plan has no Ultracode, so the row goes for the session.
85 const state = ultracodeTaken(ran.text) ? (ultracode ? 'on' : 'off') : 'unavailable'
86 await update($, ultracodeAtom, () => state)
87
88 return ran
89 }
90 const wanted = e.args.trim().toLowerCase()
91 if (wanted === 'auto') {
92 await update($, effortAtom, () => null)
93 } else if (isEffort(wanted) && effortTaken(ran.text)) {
94 await update($, effortAtom, () => wanted)
95 }
96
97 return ran
98 })
99
100 on('ui.press', { plugin: 'mods-toolbox', component: 'AbovePrompt', element: KEY }, async ($, e) => {
101 const [, kind, value = ''] = KEY.exec(e.element) ?? []
102 // Detached: /model and /effort wait until Claude is free, and the press should not.
103 $.clock.after(1, () => {
104 void (kind === 'model' ? switchModel($, value) : kind === 'effort' ? switchEffort($, value) : switchUltracode($, value))
105 })
106
107 return { element: e.element }
108 })
109}
110
111async function loadPicks($: Engine) {
112 const row = (await $.config.list()).find(candidate => candidate.key === 'model')
113 const options = row === undefined || row.isLocked ? [] : [...(row.options ?? [])]
114 await update($, optionsAtom, () => options)
115 const model = await refreshModel($)
116 // A reload keeps what a turn already showed; the settings only fill an empty start.
117 if (model !== null && (await read($, effortAtom)) === null) {
118 const effort = effortFromSettings(await $.settings.read(), model)
119 await update($, effortAtom, current => current ?? effort)
120 }
121}
122
123async function refreshModel($: Engine): Promise<string | null> {
124 try {
125 const model = await $.session.model()
126 await update($, modelAtom, current => (current === model ? current : model))
127
128 return model
129 } catch {
130 return null
131 }
132}
133
134// Each model keeps its own effort, so after a switch the last one seen no longer
135// holds: the new model's comes from settings, as Claude Code takes it.
136async function followModel($: Engine, before: string | null): Promise<string | null> {
137 const model = await refreshModel($)
138 if (model !== null && model !== before) {
139 const effort = await $.settings.read().then(
140 settings => effortFromSettings(settings, model),
141 () => null,
142 )
143 await update($, effortAtom, () => effort)
144 }
145
146 return model
147}
148
149async function switchModel($: Engine, family: string) {
150 const known = FAMILIES.find(candidate => candidate === family)
151 if (known === undefined) {
152 return
153 }
154 await update($, modelPendingAtom, () => known)
155 try {
156 const current = (await read($, modelAtom)) ?? (await $.session.model())
157 const ran = await $.command.run({ command: 'model', args: modelArgs(known, current, (await read($, optionsAtom)) ?? []) })
158 const model = await followModel($, current)
159 if (model === null || familyOf(model) !== known) {
160 $.ui.toast(refusal(ran.text, 'The model could not switch. Try /model.'))
161 }
162 } catch {
163 $.ui.toast('The model could not switch. Try /model.')
164 }
165 await update($, modelPendingAtom, current => (current === known ? null : current))
166}
167
168async function switchEffort($: Engine, level: string) {
169 if (!isEffort(level)) {
170 return
171 }
172 const wanted: ChatEffort = level
173 await update($, effortPendingAtom, () => wanted)
174 try {
175 const ran = await $.command.run({ command: 'effort', args: wanted })
176 if (effortTaken(ran.text)) {
177 await update($, effortAtom, () => wanted)
178 } else {
179 $.ui.toast(refusal(ran.text, 'The effort could not change. Try /effort.'))
180 }
181 } catch {
182 $.ui.toast('The effort could not change. Try /effort.')
183 }
184 await update($, effortPendingAtom, current => (current === wanted ? null : current))
185}
186
187async function switchUltracode($: Engine, value: string) {
188 if (value !== 'on' && value !== 'off') {
189 return
190 }
191 await update($, ultracodePendingAtom, () => value)
192 try {
193 const ran = await $.command.run({ command: 'effort', args: `ultracode ${value}` })
194 if (ultracodeTaken(ran.text)) {
195 await update($, ultracodeAtom, () => value)
196 } else {
197 await update($, ultracodeAtom, () => 'unavailable')
198 $.ui.toast(refusal(ran.text, 'Ultracode could not switch. Try /effort ultracode.'))
199 }
200 } catch {
201 $.ui.toast('Ultracode could not switch. Try /effort ultracode.')
202 }
203 await update($, ultracodePendingAtom, current => (current === value ? null : current))
204}
205hooks/clean-view.tsx 790 lines1import { atom, read, update } from 'claude-code'
2import type {
3 EngineInterface,
4 On,
5 RenderInput,
6 Timer,
7 ToolCallInput,
8 ToolCallResult,
9 TurnCompleteInput,
10} from 'claude-code'
11
12import type { CleanViewChecklist, CleanViewTask } from '../types'
13import { API_TROUBLE, WAITING_FOR_REPLY, checklistView, isAnimated } from './checklist-view'
14import { cleanName } from './clean-name'
15import { ACTIVE_STATUSES } from './dock-logic'
16import { clampPercent } from './progress'
17
18type Engine = EngineInterface
19type Checklist = CleanViewChecklist
20
21const enabledAtom = atom({ plugin: 'mods-toolbox', key: 'cleanViewEnabled' } as const, true)
22const checklistAtom = atom({ plugin: 'mods-toolbox', key: 'checklist' } as const, null)
23const tickAtom = atom({ plugin: 'mods-toolbox', key: 'tick' } as const, 0)
24// The Toolbox's: while its popup or the Status Line Dock is up, that draws the checklist.
25const bandViewAtom = atom({ plugin: 'mods-toolbox', key: 'bandView' } as const, null)
26
27const STORE_KEY = 'cleanViewEnabled'
28const ALWAYS_ALLOWED = new Set([
29 'ToolSearch',
30 'TodoWrite',
31 'TaskCreate',
32 'TaskUpdate',
33 'AskUserQuestion',
34])
35
36const FRAME_MS = 250
37const COLLAPSE_AFTER_MS = 5000
38const FAILURES_BEFORE_STUCK = 3
39const MAX_STEPS = 8
40const HELPER_CHECK_MS = 5000
41// Checks in a row that find no helper out before the job stops waiting, so the
42// turn their reports start has time to begin.
43const QUIET_CHECKS = 2
44
45const DEFAULT_TITLE = 'Working on your request'
46const NEEDS_OK = 'Claude needs your OK to continue'
47const HAS_QUESTION = 'Claude has a question for you'
48const SAID_NO = 'you said no to a step, so Claude paused'
49const KEEPS_FAILING = 'a step keeps failing, Claude is trying another way'
50const REFUSED = "Claude couldn't help with that request"
51const OFF_NOTE = 'Clean View is off, so there is no checklist to update. Carry on without it.'
52
53// The words Claude Code hands the model when the person rejects a permission prompt.
54const PERSON_SAID_NO = /doesn't want to proceed|tool use was rejected/i
55
56function gateMessage(): string {
57 return (
58 `Clean View: call ${tools.plan} first to lay out the steps of this request ` +
59 `(if it is deferred, load it with ToolSearch "select:${tools.plan},${tools.progress}"), then try again.`
60 )
61}
62
63function guide(): string {
64 return [
65 '# Clean View',
66 'The person sees a short checklist of your steps instead of your tool calls, so keep it accurate and friendly.',
67 `- For every request, even a quick question, call ${tools.plan} first with every step of the job, 2 to 8 in order. If it is deferred, load it with ToolSearch ("select:${tools.plan},${tools.progress}"). Other tools are refused until a plan exists. If this session has TodoWrite or TaskCreate, your to-do list can serve as the plan instead.`,
68 `- Call ${tools.progress} with the step's name and a percent as real progress happens, and with 100 the moment a step is finished.`,
69 '- Write every step name in plain English a non-technical person understands: under 40 characters, starting with a verb, like "Build the pricing section".',
70 '- Never put file paths, file names, commands, code or tool names in a step name.',
71 ].join('\n')
72}
73
74const TITLE_PROMPT =
75 'Name this request in 2 to 6 plain words a non-technical person understands, starting with a verb, ' +
76 'like "Build my landing page". No file names, code or punctuation. Reply with the name only.\n\nRequest:\n'
77
78// Timers and per-turn flags live with the module: a reload drops them and
79// session.start puts the timers back from the checklist.
80// The engine names the two tools when it registers them (mcp__<plugin>__<name>);
81// these defaults hold until it has.
82let tools = { plan: 'mcp__mods-toolbox__plan_steps', progress: 'mcp__mods-toolbox__report_progress' }
83let ticker: Timer | null = null
84let collapseTimer: Timer | null = null
85let helperWatch: Timer | null = null
86let quietChecks = 0
87let areToolsReady = false
88let isExpansionPending = false
89let lastApiTrouble: string | null = null
90
91/** The dock tells helpers to call these by the names the engine gave them. */
92export function cleanViewTools(): { plan: string; progress: string } {
93 return tools
94}
95
96export function registerCleanView(on: On) {
97 on('session.start', async ($, e, next) => {
98 const saved = await $.store.get(STORE_KEY)
99 await update($, enabledAtom, () => saved !== false)
100
101 const job = await read($, checklistAtom)
102 syncTicker($, job)
103 syncHelperWatch($, job)
104 scheduleCollapse($, job, await $.clock.now())
105
106 await $.command.register({
107 name: 'simple',
108 description: 'Turn Clean View on or off',
109 argumentHint: 'on|off',
110 immediate: true,
111 })
112 // The plan-first gate only stands once Claude can call plan_steps.
113 areToolsReady = await registerTools($).then(
114 names => {
115 tools = names
116 return true
117 },
118 () => false,
119 )
120
121 return next(e)
122 })
123
124 on('command.run', { command: 'simple' }, async ($, e) => {
125 const wanted = e.args.trim().toLowerCase()
126 if (wanted !== '' && wanted !== 'on' && wanted !== 'off') {
127 return { text: 'Type /simple on, /simple off, or just /simple to switch.' }
128 }
129 const isOn = await setEnabled($, wanted === '' ? 'toggle' : wanted === 'on')
130
131 return { text: isOn ? 'Clean View is on.' : 'Clean View is off.' }
132 })
133
134 // While off, plan_steps waits behind ToolSearch so its "before anything else" doesn't nudge Claude.
135 // report_progress stays in front: the dock's helpers call it whether Clean View is on or not.
136 on('tool.describe', async ($, e, next) => {
137 const described = await next(e)
138 const tool = String(e.tool)
139 if (!isOwnTool(tool)) {
140 return described
141 }
142
143 return { ...described, isDeferred: tool === tools.plan && !(await read($, enabledAtom)) }
144 })
145
146 on('prompt.compose', async ($, e, next) => {
147 const composed = await next(e)
148 if (!(await read($, enabledAtom))) {
149 return composed
150 }
151
152 return { sections: [...composed.sections, { id: 'clean-view:guide', text: guide(), scope: 'session' }] }
153 })
154
155 on('classic.UserPromptExpansion', ($, e, next) => {
156 isExpansionPending = true
157
158 return next(e)
159 })
160
161 on('turn.start', async ($, e, next) => {
162 const isCommand = isExpansionPending || e.text.trimStart().startsWith('/')
163 isExpansionPending = false
164 lastApiTrouble = null
165 if (isCommand || e.text.trim() === '') {
166 return next(e)
167 }
168 // While off there is no job to show, so no checklist to keep and no title to ask Haiku for.
169 if (!(await read($, enabledAtom))) {
170 await change($, () => null)
171 return next(e)
172 }
173
174 const now = await $.clock.now()
175 // The person's answer, or the helpers' reports, carry the same job on.
176 const job = await change($, current =>
177 current !== null && (isWaitingOnPerson(current) || isWaitingOnHelpers(current))
178 ? { ...working(current), turnId: e.turnId, failedInARow: 0, finishedAt: null, isCollapsed: false, waitingOnHelpers: 0 }
179 : newJob(e.turnId, e.turnId, now),
180 )
181 if (job?.jobId === e.turnId) {
182 nameJob($, e.turnId, e.text)
183 }
184
185 return next(e)
186 })
187
188 on('tool.call', async ($, e, next) => {
189 const tool = String(e.tool)
190 if (isOwnTool(tool)) {
191 // While off there is no checklist, so a stray call has nothing to update.
192 if (!(await read($, enabledAtom))) {
193 return { result: OFF_NOTE }
194 }
195 return tool === tools.plan ? planSteps($, e) : reportProgress($, e)
196 }
197 if (e.agentId !== undefined) {
198 return next(e)
199 }
200
201 const job = await read($, checklistAtom)
202 const needsPlan = areToolsReady && isTurnRunning(job) && job.planSource === null
203 if (needsPlan && !ALWAYS_ALLOWED.has(tool) && (await read($, enabledAtom))) {
204 return { deny: gateMessage() }
205 }
206
207 await change($, current => {
208 if (!isTurnRunning(current)) {
209 return current
210 }
211 if (tool === 'AskUserQuestion') {
212 return { ...current, phase: 'needsYou', needsYouReason: HAS_QUESTION, stuckReason: null }
213 }
214
215 return current.phase === 'needsYou' ? working(current) : current
216 })
217
218 const ran = await next(e)
219 if (ran.deny === undefined) {
220 await change($, current => (isTurnRunning(current) ? afterTool(current, e, ran) : current))
221 }
222
223 return ran
224 })
225
226 on('classic.Notification', async ($, e, next) => {
227 const kind = e.notification_type
228 const reason = /permission/i.test(kind) ? NEEDS_OK : /elicitation|question/i.test(kind) ? HAS_QUESTION : null
229 if (reason !== null) {
230 await needsYou($, reason)
231 }
232
233 return next(e)
234 })
235
236 on('classic.PermissionRequest', async ($, e, next) => {
237 await needsYou($, NEEDS_OK)
238
239 return next(e)
240 })
241
242 on('classic.StopFailure', async ($, e, next) => {
243 if (e.agent_id === undefined) {
244 const trouble = describeApiTrouble(e.error, e.error_details ?? '')
245 lastApiTrouble = trouble
246 // Whichever of this and turn.complete lands first, the plain reason wins.
247 await change($, job =>
248 job?.phase === 'stuck' && job.stuckReason === API_TROUBLE ? { ...job, stuckReason: trouble } : job,
249 )
250 }
251
252 return next(e)
253 })
254
255 on('turn.complete', async ($, e, next) => {
256 if (e.agentId !== undefined) {
257 return next(e)
258 }
259 const now = await $.clock.now()
260 const trouble = lastApiTrouble
261 const helpers = isTurnRunning(await read($, checklistAtom)) ? ((await runningHelpers($)) ?? 0) : 0
262 const job = await change($, current =>
263 isTurnRunning(current) ? finished(current, e, now, trouble, helpers) : current,
264 )
265 scheduleCollapse($, job, now)
266
267 return next(e)
268 })
269
270 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
271 if (!(await read($, enabledAtom))) {
272 return next(e)
273 }
274 const { Box } = $.ui.resolve(e)
275
276 return <Box display="none" />
277 })
278
279 on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
280 if (!(await read($, enabledAtom))) {
281 return next(e)
282 }
283 const { Box } = $.ui.resolve(e)
284
285 return <Box display="none" />
286 })
287
288 on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
289 if (!(await read($, enabledAtom))) {
290 return next(e)
291 }
292 const { Box } = $.ui.resolve(e)
293
294 return <Box display="none" />
295 })
296
297 on('ui.render', { component: 'ToolProgress' }, async ($, e, next) =>
298 (await read($, enabledAtom)) ? next({ ...e, props: { ...e.props, hint: '' } }) : next(e),
299 )
300
301 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
302 if (e.props.hasSurvey || (await read($, bandViewAtom)) !== null) {
303 return next(e)
304 }
305 // The band is shared with other mods: Clean View sits on top of whatever the hooks beneath draw.
306 const { Box } = $.ui.resolve(e)
307 const band = await drawChecklist($, e)
308 const below = await next(e)
309
310 return (
311 <Box flexDirection="column">
312 {band}
313 {below}
314 </Box>
315 )
316 })
317
318 // The Toolbox popup draws the switch; flipping it is Clean View's own business.
319 on('ui.press', { plugin: 'mods-toolbox', component: 'AbovePrompt', element: /^cv-(on|off)$/ }, async ($, e) => {
320 try {
321 await setEnabled($, e.element === 'cv-on')
322 } catch {
323 $.ui.toast('Clean View could not switch. Try /simple.')
324 }
325
326 return { element: e.element }
327 })
328}
329
330// Nothing while Clean View is off or idle.
331async function drawChecklist($: Engine, e: RenderInput<'AbovePrompt'>) {
332 const job = (await read($, enabledAtom)) ? await read($, checklistAtom) : null
333 if (job === null) {
334 return null
335 }
336 const { Box, Text } = $.ui.resolve(e)
337 const frame = isAnimated(job.phase) ? await read($, tickAtom) : 0
338
339 return checklistView(Box, Text, job, { columns: e.props.bodyColumns, isFolded: false, now: await $.clock.now(), frame })
340}
341
342async function registerTools($: Engine) {
343 const plan = await $.tool.register({
344 name: 'plan_steps',
345 description:
346 'Lay out every step of the current job before doing anything else: 2 to 8 short names in order, ' +
347 'in plain English, each under 40 characters and starting with a verb. No file names, paths, commands or code. ' +
348 'The first step starts right away.',
349 inputSchema: {
350 type: 'object',
351 properties: {
352 steps: {
353 type: 'array',
354 items: { type: 'string' },
355 minItems: 2,
356 maxItems: MAX_STEPS,
357 description: 'The steps in order, like "Build the pricing section"',
358 },
359 },
360 required: ['steps'],
361 additionalProperties: false,
362 },
363 })
364 const progress = await $.tool.register({
365 name: 'report_progress',
366 description:
367 'Report progress on a step of the plan: its name as planned and a percent from 0 to 100. ' +
368 'Report 100 the moment a step is finished; that checks it off and starts the next one.',
369 inputSchema: {
370 type: 'object',
371 properties: {
372 task: { type: 'string', description: 'The step name, as planned' },
373 percent: { type: 'number', minimum: 0, maximum: 100 },
374 },
375 required: ['task', 'percent'],
376 additionalProperties: false,
377 },
378 })
379
380 return { plan: plan.tool, progress: progress.tool }
381}
382
383async function planSteps($: Engine, e: ToolCallInput): Promise<ToolCallResult> {
384 const steps = stringList(argsOf(e).steps).slice(0, MAX_STEPS).map(cleanName)
385 if (steps.length < 2) {
386 return { deny: 'plan_steps needs "steps": a list of 2 to 8 short step names.' }
387 }
388 const answer = { result: `Planned ${steps.length} steps. The first one has started.` }
389 // A subagent's plan is its own business; the checklist follows the main agent.
390 if (e.agentId !== undefined) {
391 return answer
392 }
393
394 const now = await $.clock.now()
395 const job = await change($, current => {
396 // No job yet (a slash command's turn, say): start one; turn.complete still ends it.
397 const base = isTurnRunning(current) ? current : newJob(`plan-${now}`, 'untracked', now)
398
399 return {
400 ...working(base),
401 planSource: 'steps',
402 tasks: steps.map((name, index) => newTask(`step-${index + 1}`, name, index === 0 ? 'active' : 'upcoming')),
403 }
404 })
405 if (job?.jobId === `plan-${now}`) {
406 nameJob($, job.jobId, steps.join('; '))
407 }
408
409 return answer
410}
411
412async function reportProgress($: Engine, e: ToolCallInput): Promise<ToolCallResult> {
413 const args = argsOf(e)
414 const percent = clampPercent(args.percent)
415 if (e.agentId === undefined && typeof args.task === 'string') {
416 const name = args.task
417 await change($, current => (isTurnRunning(current) ? progressed(current, name, percent) : current))
418 }
419
420 return { result: `Progress noted: ${percent}%.` }
421}
422
423async function setEnabled($: Engine, wanted: boolean | 'toggle'): Promise<boolean> {
424 const wasOn = await read($, enabledAtom)
425 const isOn = await update($, enabledAtom, current => (wanted === 'toggle' ? !current : wanted))
426 // The engine keeps tool.describe's answer for the session; asking again moves plan_steps.
427 // Only on a real change, since each ask spends the prompt cache.
428 if (isOn !== wasOn) {
429 $.ui.invalidate('tool.describe')
430 }
431 await $.store.set(STORE_KEY, isOn)
432 $.ui.toast(isOn ? 'Clean View is on: you see the plan, not the details' : 'Clean View is off: every detail is showing')
433
434 return isOn
435}
436
437async function needsYou($: Engine, reason: string) {
438 await change($, job =>
439 isTurnRunning(job) ? { ...job, phase: 'needsYou', needsYouReason: reason, stuckReason: null } : job,
440 )
441}
442
443async function change($: Engine, fn: (job: Checklist | null) => Checklist | null): Promise<Checklist | null> {
444 const job = await update($, checklistAtom, fn)
445 syncTicker($, job)
446 syncHelperWatch($, job)
447
448 return job
449}
450
451// Between turns the helpers' count follows the engine, and a job whose helpers
452// all left without a report starting a turn ends the way a turn without them
453// would, so it never waits for good.
454function syncHelperWatch($: Engine, job: Checklist | null) {
455 const shouldWatch = job !== null && isWaitingOnHelpers(job)
456 if (shouldWatch && helperWatch === null) {
457 quietChecks = 0
458 helperWatch = $.clock.every(HELPER_CHECK_MS, () => {
459 void recheckHelpers($)
460 })
461 } else if (!shouldWatch && helperWatch !== null) {
462 helperWatch.cancel()
463 helperWatch = null
464 }
465}
466
467async function recheckHelpers($: Engine) {
468 const helpers = await runningHelpers($)
469 if (helpers === null) {
470 return
471 }
472 quietChecks = helpers === 0 ? quietChecks + 1 : 0
473 const now = await $.clock.now()
474 const job = await change($, current => {
475 if (current === null || !isWaitingOnHelpers(current)) {
476 return current
477 }
478 if (helpers > 0) {
479 return helpers === current.waitingOnHelpers ? current : { ...current, waitingOnHelpers: helpers }
480 }
481
482 return quietChecks < QUIET_CHECKS ? current : settled(current, now)
483 })
484 scheduleCollapse($, job, now)
485}
486
487// Helpers the engine still runs for this session; null when it can't say.
488async function runningHelpers($: Engine): Promise<number | null> {
489 try {
490 return (await $.agent.list()).filter(agent => ACTIVE_STATUSES.has(agent.status)).length
491 } catch {
492 return null
493 }
494}
495
496function syncTicker($: Engine, job: Checklist | null) {
497 const shouldTick = job !== null && isAnimated(job.phase)
498 if (shouldTick && ticker === null) {
499 ticker = $.clock.every(FRAME_MS, () => {
500 void update($, tickAtom, frame => frame + 1)
501 })
502 } else if (!shouldTick && ticker !== null) {
503 ticker.cancel()
504 ticker = null
505 }
506}
507
508function scheduleCollapse($: Engine, job: Checklist | null, now: number) {
509 collapseTimer?.cancel()
510 collapseTimer = null
511 if (job === null || job.phase !== 'done' || job.isCollapsed || job.finishedAt === null) {
512 return
513 }
514 const { jobId } = job
515 const wait = Math.max(1, job.finishedAt + COLLAPSE_AFTER_MS - now)
516 collapseTimer = $.clock.after(wait, () => {
517 void update($, checklistAtom, current =>
518 current?.jobId === jobId && current.phase === 'done' ? { ...current, isCollapsed: true } : current,
519 )
520 })
521}
522
523// Started from a timer so the request is not tied to the turn.start dispatch.
524function nameJob($: Engine, jobId: string, request: string) {
525 $.clock.after(1, () => {
526 void askForTitle($, jobId, request)
527 })
528}
529
530async function askForTitle($: Engine, jobId: string, request: string) {
531 try {
532 const reply = await $.model.complete({
533 model: 'haiku',
534 effort: 'low',
535 maxTokens: 30,
536 timeoutMs: 20_000,
537 prompt: TITLE_PROMPT + request.slice(0, 2000),
538 })
539 if (!reply.isAnswered) {
540 return
541 }
542 const words = reply.text.replace(/[^\p{L}\p{N}\s'’-]/gu, ' ').trim().split(/\s+/).filter(Boolean)
543 if (words.length < 2) {
544 return
545 }
546 const title = cleanName(words.slice(0, 6).join(' '))
547 await update($, checklistAtom, job => (job?.jobId === jobId ? { ...job, title } : job))
548 } catch {
549 // The placeholder title stays; naming is a nicety.
550 }
551}
552
553function newJob(jobId: string, turnId: string, now: number): Checklist {
554 return {
555 jobId,
556 title: DEFAULT_TITLE,
557 phase: 'working',
558 tasks: [newTask('placeholder-1', 'Understand your request', 'active'), newTask('placeholder-2', 'Plan the steps', 'upcoming')],
559 planSource: null,
560 needsYouReason: null,
561 stuckReason: null,
562 failedInARow: 0,
563 turnId,
564 waitingOnHelpers: 0,
565 startedAt: now,
566 finishedAt: null,
567 isCollapsed: false,
568 }
569}
570
571function newTask(id: string, name: string, status: CleanViewTask['status']): CleanViewTask {
572 return { id, name, status, percent: status === 'done' ? 100 : 0, hasReported: false }
573}
574
575function working(job: Checklist): Checklist {
576 return { ...job, phase: 'working', needsYouReason: null, stuckReason: null }
577}
578
579function progressed(job: Checklist, rawName: string, percent: number): Checklist {
580 const name = cleanName(rawName)
581 const tasks = job.planSource === null ? [] : job.tasks
582 let index = tasks.findIndex(task => task.name.toLowerCase() === name.toLowerCase())
583 let list = tasks
584 if (index < 0) {
585 const active = tasks.findIndex(task => task.status === 'active')
586 index = active < 0 ? tasks.length : active
587 list = [...tasks.slice(0, index), newTask(`added-${tasks.length + 1}`, name, 'upcoming'), ...tasks.slice(index)]
588 }
589 const isFinished = percent >= 100
590 const reported = list.map((task, at): CleanViewTask => {
591 if (at < index) {
592 return { ...task, status: 'done', percent: 100 }
593 }
594 if (at === index) {
595 return { ...task, status: isFinished ? 'done' : 'active', percent, hasReported: true }
596 }
597
598 return task.status === 'active' ? { ...task, status: 'upcoming' } : task
599 })
600
601 return { ...working(job), tasks: withOneActive(reported) }
602}
603
604function afterTool(job: Checklist, e: ToolCallInput, ran: ToolCallResult): Checklist {
605 if (ran.isError === true) {
606 if (PERSON_SAID_NO.test(ran.text ?? '')) {
607 return { ...job, phase: 'stuck', stuckReason: SAID_NO, needsYouReason: null, failedInARow: 0 }
608 }
609 const failedInARow = job.failedInARow + 1
610 if (failedInARow >= FAILURES_BEFORE_STUCK) {
611 return { ...job, failedInARow, phase: 'stuck', stuckReason: KEEPS_FAILING, needsYouReason: null }
612 }
613
614 return { ...(job.phase === 'needsYou' ? working(job) : job), failedInARow }
615 }
616
617 // A success clears both Stuck and Needs you.
618 const next = { ...working(job), failedInARow: 0 }
619 if (e.tool === 'TodoWrite') {
620 return fromTodos(next, e.todos)
621 }
622 if (e.tool === 'TaskCreate') {
623 const id = createdTaskId(ran.result)
624
625 return id === null ? next : withCreatedTask(next, id, e.subject)
626 }
627 if (e.tool === 'TaskUpdate') {
628 return withUpdatedTask(next, e.taskId, e.status, e.subject)
629 }
630
631 return next
632}
633
634const TODO_STATUS = { completed: 'done', in_progress: 'active', pending: 'upcoming' } as const
635
636function fromTodos(
637 job: Checklist,
638 todos: ReadonlyArray<{ content: string; status: keyof typeof TODO_STATUS }>,
639): Checklist {
640 const tasks = todos.map((todo, index) => {
641 const id = `todo-${index + 1}`
642 const name = cleanName(todo.content)
643 const status = TODO_STATUS[todo.status] ?? 'upcoming'
644 const before = job.tasks.find(task => task.name === name && task.status === 'active')
645
646 return status === 'active' && before !== undefined ? { ...before, id } : newTask(id, name, status)
647 })
648
649 return { ...job, planSource: 'todos', tasks: withOneActive(tasks) }
650}
651
652function withCreatedTask(job: Checklist, id: string, subject: string): Checklist {
653 const tasks = job.planSource === 'tasks' ? job.tasks : []
654
655 return { ...job, planSource: 'tasks', tasks: withOneActive([...tasks, newTask(`task-${id}`, cleanName(subject), 'upcoming')]) }
656}
657
658function withUpdatedTask(
659 job: Checklist,
660 taskId: string,
661 status: keyof typeof TODO_STATUS | 'deleted' | undefined,
662 subject: string | undefined,
663): Checklist {
664 const id = `task-${taskId}`
665 if (job.planSource !== 'tasks' || !job.tasks.some(task => task.id === id)) {
666 return job
667 }
668 if (status === 'deleted') {
669 return { ...job, tasks: withOneActive(job.tasks.filter(task => task.id !== id)) }
670 }
671 const next = status === undefined ? undefined : TODO_STATUS[status]
672 const tasks = job.tasks.map((task): CleanViewTask => {
673 if (task.id !== id) {
674 return next === 'active' && task.status === 'active' ? { ...task, status: 'upcoming' } : task
675 }
676 const renamed = subject === undefined ? task : { ...task, name: cleanName(subject) }
677
678 return next === undefined ? renamed : { ...renamed, status: next, percent: next === 'done' ? 100 : renamed.percent }
679 })
680
681 return { ...job, tasks: withOneActive(tasks) }
682}
683
684function withOneActive(tasks: CleanViewTask[]): CleanViewTask[] {
685 if (tasks.some(task => task.status === 'active')) {
686 return tasks
687 }
688 const next = tasks.findIndex(task => task.status === 'upcoming')
689
690 return next < 0 ? tasks : tasks.map((task, index) => (index === next ? { ...task, status: 'active' } : task))
691}
692
693function finished(job: Checklist, e: TurnCompleteInput, now: number, trouble: string | null, helpers: number): Checklist {
694 const ended: Checklist = { ...job, turnId: null, needsYouReason: null, waitingOnHelpers: 0 }
695 if (e.reason === 'error') {
696 return { ...ended, phase: 'stuck', stuckReason: trouble ?? API_TROUBLE }
697 }
698 if (e.reason === 'refusal') {
699 return { ...ended, phase: 'stuck', stuckReason: REFUSED }
700 }
701 // Saying no to a permission prompt also ends the turn; the no is the news.
702 if (job.phase === 'stuck' && job.stuckReason === SAID_NO) {
703 return ended
704 }
705 if (e.reason === 'aborted') {
706 return { ...ended, phase: 'stopped', stuckReason: null, finishedAt: now }
707 }
708 // Claude ends its turn while background helpers run, and goes on when they
709 // report: it is not waiting for the person.
710 if (helpers > 0) {
711 return { ...ended, phase: 'working', stuckReason: null, waitingOnHelpers: helpers }
712 }
713
714 return settled(ended, now)
715}
716
717// A job with no turn and no helper left: unfinished steps wait for the person.
718function settled(job: Checklist, now: number): Checklist {
719 const ended: Checklist = { ...job, waitingOnHelpers: 0 }
720 if (job.planSource !== null && job.tasks.some(task => task.status !== 'done')) {
721 return { ...ended, phase: 'needsYou', stuckReason: null, needsYouReason: WAITING_FOR_REPLY }
722 }
723
724 return {
725 ...ended,
726 phase: 'done',
727 stuckReason: null,
728 finishedAt: now,
729 tasks: job.tasks.map(task => ({ ...task, status: 'done', percent: 100 })),
730 }
731}
732
733function describeApiTrouble(kind: string, details: string): string {
734 if (/too long|context window|too many tokens/i.test(details)) {
735 return 'this chat got too long, type /compact and try again'
736 }
737 if (/network|connection|socket|econn|enotfound|fetch failed|offline/i.test(details)) {
738 return 'the internet connection dropped'
739 }
740 switch (kind) {
741 case 'rate_limit':
742 return 'you hit your usage limit, try again a little later'
743 case 'overloaded':
744 case 'server_error':
745 return "Claude's servers are busy, try again in a minute"
746 case 'authentication_failed':
747 case 'oauth_org_not_allowed':
748 case 'cloud_credential_error':
749 return "you're signed out, type /login"
750 case 'billing_error':
751 case 'account_on_hold':
752 case 'verification_required':
753 return 'your account needs attention, check your plan'
754 default:
755 return API_TROUBLE
756 }
757}
758
759function isOwnTool(tool: string): boolean {
760 return tool === tools.plan || tool === tools.progress
761}
762
763function isTurnRunning(job: Checklist | null): job is Checklist {
764 return job !== null && job.turnId !== null
765}
766
767function isWaitingOnHelpers(job: Checklist): boolean {
768 return job.turnId === null && job.waitingOnHelpers > 0
769}
770
771function isWaitingOnPerson(job: Checklist): boolean {
772 const isPaused = job.phase === 'needsYou' || job.phase === 'stuck'
773
774 return isPaused && job.planSource !== null && job.tasks.some(task => task.status !== 'done')
775}
776
777function argsOf(e: ToolCallInput): Record<string, unknown> {
778 return e as unknown as Record<string, unknown>
779}
780
781function stringList(value: unknown): string[] {
782 return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string' && item.trim() !== '') : []
783}
784
785function createdTaskId(result: unknown): string | null {
786 const id = (result as { task?: { id?: unknown } } | null | undefined)?.task?.id
787
788 return typeof id === 'string' || typeof id === 'number' ? String(id) : null
789}
790hooks/dock.tsx 1001 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On, RenderInput, Timer, ToolCallResult } from 'claude-code'
3
4import type { DockCard, DockHelperModel, DockMission } from '../types'
5import { cleanViewTools } from './clean-view'
6import {
7 ACTIVE_STATUSES,
8 BADGE_COLORS,
9 BAD_CUSTOM,
10 BIG_TEAM_QUESTION,
11 CORAL,
12 CUSTOM_PLACEHOLDER,
13 CUSTOM_QUESTION,
14 GOLD,
15 GREEN,
16 HAIRLINE,
17 HELPERS_SKIP_PLAN,
18 INK,
19 MUTED,
20 RED,
21 SIZES,
22 SIZE_HELP,
23 STOPPED,
24 TILES_AFTER,
25 TOO_NARROW,
26 afterMainTurn,
27 atATime,
28 badgeText,
29 capMessage,
30 cardTime,
31 cardsPerRow,
32 closedOut,
33 confirmMessage,
34 countDir,
35 countFile,
36 countPath,
37 counts,
38 ended,
39 formatClock,
40 hasActiveHelper,
41 helperNote,
42 infoLine,
43 isBigTeam,
44 isFinished,
45 isLive,
46 jobName,
47 meter,
48 missionBar,
49 missionPercent,
50 mix,
51 newMission,
52 nudgeText,
53 parseSize,
54 reconciled,
55 reported,
56 restoreHelperModel,
57 restoreSize,
58 rows,
59 seats,
60 spaced,
61 standingBy,
62 started,
63 summary,
64 teamInstruction,
65 tilesPerRow,
66 withAgent,
67 withCard,
68 withQueued,
69 withoutCard,
70} from './dock-logic'
71import type { MeterPart } from './dock-logic'
72import { clampPercent } from './progress'
73
74type Engine = EngineInterface
75
76const PANE = 'agent-dock'
77const DOCK_COLUMNS = 78
78const FRAME_MS = 200
79const TILE_WIDTH = 17
80const SIZE_KEY = 'dock.teamSize'
81const MODEL_KEY = 'dock.helperModel'
82const FALLBACK_JOB = 'Helpers at work'
83// Prompts a person sent; a background task's notification is not a new request.
84const PERSON_ORIGINS = new Set(['composer', 'bridge', 'sdk'])
85
86const sizeRef = { plugin: 'mods-toolbox', key: 'dockTeamSize' } as const
87const sizeAtom = atom(sizeRef, 1)
88const modelAtom = atom({ plugin: 'mods-toolbox', key: 'dockHelperModel' } as const, 'fast')
89const pendingAtom = atom({ plugin: 'mods-toolbox', key: 'dockPendingSize' } as const, null)
90const customAtom = atom({ plugin: 'mods-toolbox', key: 'dockIsCustomOpen' } as const, false)
91const foldedAtom = atom({ plugin: 'mods-toolbox', key: 'dockIsFolded' } as const, false)
92const missionAtom = atom({ plugin: 'mods-toolbox', key: 'dockMission' } as const, null)
93const tickAtom = atom({ plugin: 'mods-toolbox', key: 'dockTick' } as const, 0)
94
95// Module state a reload may drop: session.start puts the clock and limits back.
96let ticker: Timer | null = null
97let atOnce = atATime(undefined, undefined)
98let lastJob: string | null = null
99let shownStatus: string | undefined | null = null
100let missionCount = 0
101// Agent calls let out of the hold whose subagent the engine has not listed yet.
102const launching = new Set<string>()
103// The live count the status line reads: where it goes, what was last written, in order.
104let countFolder: string | null = null
105let writtenPath: string | null = null
106let writtenKey: string | null = null
107let countQueue: Promise<void> = Promise.resolve()
108
109export function registerDock(on: On) {
110 on('session.start', { cwd: /^/ }, async ($, e, next) => {
111 try {
112 // A reload keeps this session's size; only a new session reads the store.
113 const { value: current } = await $.state.get(sizeRef)
114 if (current === undefined) {
115 const [savedSize, savedModel] = await Promise.all([$.store.get(SIZE_KEY), $.store.get(MODEL_KEY)])
116 await update($, sizeAtom, () => restoreSize(savedSize))
117 await update($, modelAtom, () => restoreHelperModel(savedModel))
118 }
119 atOnce = await readLimits($)
120 countFolder = await readCountFolder($)
121 await sweepCountFiles($)
122 syncTicker($, await read($, missionAtom))
123 await $.command.register({
124 name: 'dock',
125 description: 'Show or fold the Agent Dock, or set its Team Size (1 to 100)',
126 argumentHint: '[team size]',
127 immediate: true,
128 })
129 } catch {
130 // The dock stays at its defaults; Clean View carries on either way.
131 }
132
133 return next(e)
134 })
135
136 // No awaits here: the answer goes back at once and the pane opens after.
137 on('command.run', { command: 'dock' }, ($, e) => {
138 try {
139 const wanted = e.args.trim()
140 if (wanted === '') {
141 void toggleDock($)
142 return { text: 'Agent Dock toggled. Type /dock again to switch back.' }
143 }
144 const size = parseSize(wanted)
145 if (size === null) {
146 return { text: SIZE_HELP }
147 }
148 void (async () => {
149 try {
150 await chooseSize($, size)
151 await showDock($)
152 } catch {
153 $.ui.toast('The Agent Dock could not open. Try /dock again.')
154 }
155 })()
156
157 return { text: isBigTeam(size) ? confirmMessage(size) : `Team Size is ${size}.` }
158 } catch {
159 return { text: 'The Agent Dock could not answer. Try /dock again.' }
160 }
161 })
162
163 on('prompt.submit', async ($, e, next) => {
164 let context: string | null = null
165 try {
166 const text = e.text.trim()
167 const isRequest = PERSON_ORIGINS.has(e.origin.kind) && text !== '' && !text.startsWith('/')
168 let current = isRequest ? await read($, missionAtom) : null
169 // Idle with a mission still open and no helper of it running: its finish
170 // was missed, so close it rather than leave this request unsplit.
171 if (isLive(current) && e.turnId === undefined) {
172 const statuses = await agentStatuses($)
173 if (statuses !== null && !hasActiveHelper(current, statuses)) {
174 const now = await $.clock.now()
175 current = await change($, mission => (isLive(mission) ? closedOut(mission, statuses, now) : mission))
176 }
177 }
178 if (isRequest && !isLive(current)) {
179 const job = jobName(text)
180 lastJob = job
181 const size = await read($, sizeAtom)
182 const now = await $.clock.now()
183 // At size 1 Claude decides: a mission starts with its first helper.
184 const mission = size > 1 ? newMission(`mission-${now}-${++missionCount}`, job, size, now) : null
185 await change($, () => mission)
186 if (size > 1) {
187 const { progress, plan } = cleanViewTools()
188 context = teamInstruction(size, progress, plan)
189 }
190 }
191 } catch {
192 context = null
193 }
194
195 return context === null ? next(e) : next({ ...e, context: [...(e.context ?? []), context] })
196 })
197
198 // Cards show queued as soon as Claude writes the Agent calls.
199 on('session.append', { door: 'response' }, async ($, e, next) => {
200 if (e.agentId === undefined) {
201 try {
202 const calls = agentCalls(e.message.content)
203 if (calls.length > 0) {
204 const fresh = await missionFor($)
205 await change($, current => {
206 const mission = isLive(current) ? current : fresh
207 return withQueued(mission, calls, mission.size > 1 ? mission.size : null)
208 })
209 }
210 } catch {
211 // Cards still appear once the calls start.
212 }
213 }
214
215 return next(e)
216 })
217
218 on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
219 if (e.agentId !== undefined) {
220 return next(e)
221 }
222 const id = e.tool_use_id
223 const admitted = await admit($, id, e.description).catch(() => ({ size: 1, deny: null }))
224 if (admitted.deny !== null) {
225 return { deny: admitted.deny }
226 }
227 if (admitted.size > 1) {
228 const isStopped = await waitForSlot($, id, next.signal).catch(() => false)
229 if (isStopped) {
230 await finish($, id, 'stuck').catch(() => undefined)
231 return { deny: STOPPED }
232 }
233 }
234 await startCard($, id).catch(() => undefined)
235
236 let ran: ToolCallResult
237 try {
238 ran = await next(e)
239 } finally {
240 launching.delete(id)
241 }
242 await afterCall($, id, ran).catch(() => undefined)
243
244 return ran
245 })
246
247 // Helpers report on their own card; Clean View's checklist follows the main agent.
248 on('tool.call', { tool: /__(report_progress|plan_steps)$/ }, async ($, e, next) => {
249 const agentId = e.agentId
250 const tools = cleanViewTools()
251 if (agentId === undefined || (e.tool !== tools.progress && e.tool !== tools.plan)) {
252 return next(e)
253 }
254 if (e.tool === tools.plan) {
255 return { result: HELPERS_SKIP_PLAN }
256 }
257 const percent = clampPercent((e as unknown as { percent?: unknown }).percent)
258 await change($, mission => (mission === null ? mission : withAgent(mission, agentId, card => reported(card, percent)))).catch(
259 () => undefined,
260 )
261
262 return { result: `Progress noted: ${percent}%.` }
263 })
264
265 on('agent.spawn', async ($, e, next) => {
266 if (e.parentAgentId !== undefined || e.workflow !== undefined) {
267 return next(e)
268 }
269 let input = e
270 try {
271 const mission = await read($, missionAtom)
272 const isHelper = mission !== null && mission.size > 1 && mission.cards.some(card => card.id === e.tool_use_id)
273 if (isHelper) {
274 const model = await read($, modelAtom)
275 const { progress, plan } = cleanViewTools()
276 input = {
277 ...e,
278 ...(model === 'fast' && e.model === undefined && !e.fork ? { model: 'haiku' } : {}),
279 ...(e.prompt.includes(progress) ? {} : { prompt: `${e.prompt}\n\n${helperNote(progress, plan)}` }),
280 }
281 }
282 } catch {
283 input = e
284 }
285
286 const spawned = await next(input)
287 launching.delete(e.tool_use_id)
288 const agentId = 'agentId' in spawned ? spawned.agentId : undefined
289 if (agentId !== undefined) {
290 await change($, mission =>
291 mission === null ? mission : withCard(mission, e.tool_use_id, card => ({ ...card, agentId, isBackground: e.background })),
292 ).catch(() => undefined)
293 }
294
295 return spawned
296 })
297
298 on('turn.complete', { turnId: /^/ }, async ($, e, next) => {
299 try {
300 const now = await $.clock.now()
301 const agentId = e.agentId
302 if (agentId !== undefined) {
303 const status = e.reason === 'answer' ? 'done' : 'stuck'
304 await change($, mission => (mission === null ? mission : withAgent(mission, agentId, card => ended(card, status, now))))
305 } else {
306 const statuses = (await agentStatuses($)) ?? new Map<string, string>()
307 await change($, mission =>
308 isLive(mission) ? afterMainTurn(reconciled(mission, statuses, now), e.reason === 'aborted', now) : mission,
309 )
310 }
311 } catch {
312 // A missed finish is picked up at the next main turn's end.
313 }
314
315 return next(e)
316 })
317
318 // One follow-up per request when Claude used fewer helpers than the team size.
319 on('classic.Stop', async ($, e, next) => {
320 const answered = await next(e)
321 if (answered.block !== undefined) {
322 return answered
323 }
324 try {
325 const nudge: { text: string | null } = { text: null }
326 await change($, mission => {
327 nudge.text = null
328 if (!isLive(mission) || mission.size <= 1 || mission.hasNudged || mission.cards.length >= mission.size) {
329 return mission
330 }
331 nudge.text = nudgeText(mission.cards.length, mission.size)
332 return { ...mission, hasNudged: true }
333 })
334 if (nudge.text !== null) {
335 return { ...answered, block: nudge.text }
336 }
337 } catch {
338 // No nudge this time.
339 }
340
341 return answered
342 })
343
344 on('session.end', async ($, e, next) => {
345 if (writtenPath !== null) {
346 await removeFile($, writtenPath)
347 writtenPath = null
348 writtenKey = null
349 }
350
351 return next(e)
352 })
353
354 on('ui.close', { id: PANE }, async ($, e, next) => {
355 const closed = await next(e)
356 await fold($, true).catch(() => undefined)
357
358 return closed
359 })
360
361 on('ui.render', { component: 'Pane', requestId: PANE }, ($, e) => drawDock($, e))
362
363 // The Toolbox popup draws Team Size, the helper model and the Agent Dock with
364 // the pane's own keys; their presses are the dock's to answer.
365 on('ui.press', { plugin: 'mods-toolbox', component: 'AbovePrompt', element: /^(size-|model-|big-|custom-|toolbox-dock$)/ }, async ($, e, next) => {
366 try {
367 const size = e.element.startsWith('size-') ? parseSize(e.element.slice('size-'.length)) : null
368 if (e.element === 'toolbox-dock') {
369 await showDock($)
370 // The popup's own press closes it, so the dock gets the room.
371 return next(e)
372 }
373 if (size !== null) {
374 await chooseSize($, size)
375 } else if (e.element === 'size-custom' || e.element === 'custom-cancel') {
376 await setCustomOpen($, e.element === 'size-custom')
377 } else if (e.element === 'model-fast' || e.element === 'model-same') {
378 await pickModel($, e.element === 'model-fast' ? 'fast' : 'same')
379 } else if (e.element === 'big-continue') {
380 await confirmBigTeam($)
381 } else if (e.element === 'big-cancel') {
382 await cancelBigTeam($)
383 }
384 } catch {
385 $.ui.toast('The Agent Dock could not take that. Try /dock.')
386 }
387
388 return { element: e.element }
389 })
390
391 on('ui.input', { plugin: 'mods-toolbox', component: 'AbovePrompt', element: 'custom-size' }, async ($, e) => {
392 if (e.kind === 'submit') {
393 await submitCustom($, e.value).catch(() => $.ui.toast(BAD_CUSTOM))
394 }
395
396 return { element: e.element, value: e.value }
397 })
398}
399
400async function readCountFolder($: Engine): Promise<string | null> {
401 try {
402 return countDir(await $.env.get('CLAUDE_CONFIG_DIR'), await $.env.get('HOME'))
403 } catch {
404 return null
405 }
406}
407
408// Count files a crashed session left behind; a live one is rewritten as it changes.
409async function sweepCountFiles($: Engine) {
410 try {
411 if (countFolder !== null && (await $.fs.exists(countFolder))) {
412 await $.process.run(['find', countFolder, '-type', 'f', '-name', '*.json', '-mmin', '+1440', '-delete'])
413 }
414 } catch {
415 // Leftovers are harmless: each status line reads its own session's file.
416 }
417}
418
419async function removeFile($: Engine, path: string) {
420 try {
421 await $.process.run(['rm', '-f', path])
422 } catch {
423 // Its session is over, so no status line reads it again.
424 }
425}
426
427// Writes are chained so an older count never lands after a newer one.
428function publishCount($: Engine): Promise<void> {
429 countQueue = countQueue.then(() => writeCount($)).catch(() => undefined)
430
431 return countQueue
432}
433
434async function writeCount($: Engine) {
435 if (countFolder === null) {
436 return
437 }
438 const file = countFile(await read($, missionAtom), await $.clock.now())
439 if (file === null) {
440 if (writtenPath !== null) {
441 const stale = writtenPath
442 writtenPath = null
443 writtenKey = null
444 await removeFile($, stale)
445 }
446 return
447 }
448 // A /clear goes on under a new session id, so the path can move mid-mission.
449 const path = countPath(countFolder, await $.session.id())
450 const key = `${path}|${file.working}|${file.queued}|${file.done}|${file.stuck}`
451 if (key === writtenKey) {
452 return
453 }
454 if (writtenPath !== null && writtenPath !== path) {
455 await removeFile($, writtenPath)
456 }
457 writtenPath = path
458 writtenKey = key
459 await $.fs.write(path, JSON.stringify(file))
460}
461
462async function readLimits($: Engine): Promise<number> {
463 try {
464 const subagents = await $.env.get('CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS')
465 const tools = await $.env.get('CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY')
466
467 return atATime(subagents, tools)
468 } catch {
469 return atATime(undefined, undefined)
470 }
471}
472
473function agentCalls(content: readonly unknown[]): Array<{ id: string; description: string }> {
474 const calls: Array<{ id: string; description: string }> = []
475 for (const block of content as ReadonlyArray<{ type?: unknown; id?: unknown; name?: unknown; input?: unknown }>) {
476 if (block.type === 'tool_use' && block.name === 'Agent' && typeof block.id === 'string') {
477 const description = (block.input as { description?: unknown } | undefined)?.description
478 calls.push({ id: block.id, description: typeof description === 'string' ? description : 'Helper' })
479 }
480 }
481
482 return calls
483}
484
485// Helpers no person's request asked the dock to split (a slash command's, a
486// skill's, a later notification turn's) are drawn but never capped, held,
487// moved to Haiku or nudged: such a mission runs at size 1.
488async function missionFor($: Engine): Promise<DockMission> {
489 const now = await $.clock.now()
490
491 return newMission(`mission-${now}-${++missionCount}`, lastJob ?? FALLBACK_JOB, 1, now)
492}
493
494// Gives the call a card, or refuses it once the request has its team.
495async function admit($: Engine, id: string, description: string): Promise<{ size: number; deny: string | null }> {
496 const fresh = await missionFor($)
497 const verdict: { size: number; deny: string | null } = { size: 1, deny: null }
498 await change($, current => {
499 const mission = isLive(current) ? current : fresh
500 verdict.size = mission.size
501 verdict.deny = null
502 if (mission.cards.some(card => card.id === id)) {
503 return mission
504 }
505 if (mission.size > 1 && mission.cards.length >= mission.size) {
506 verdict.deny = capMessage(mission.size)
507 return current
508 }
509
510 return withQueued(mission, [{ id, description }], null)
511 })
512
513 return verdict
514}
515
516// Claude Code refuses an Agent call past its limit instead of queueing it, so
517// the dock holds the call here. A process sleep is a `$` call, which the
518// hook's ten-second budget does not count; `$.clock.sleep` would.
519async function waitForSlot($: Engine, id: string, signal: AbortSignal): Promise<boolean> {
520 for (;;) {
521 if (signal.aborted) {
522 return true
523 }
524 const listed = await activeAgents($)
525 const mission = await read($, missionAtom)
526 const working = mission?.cards.filter(card => card.status === 'working' && !launching.has(card.id)).length ?? 0
527 // Checked and taken in one step, so two held calls never take one slot.
528 if ((listed ?? working) + launching.size < atOnce) {
529 launching.add(id)
530 return false
531 }
532 await $.process.run(['/bin/sleep', '1'])
533 }
534}
535
536async function activeAgents($: Engine): Promise<number | null> {
537 try {
538 return (await $.agent.list()).filter(agent => ACTIVE_STATUSES.has(agent.status)).length
539 } catch {
540 return null
541 }
542}
543
544async function agentStatuses($: Engine): Promise<Map<string, string> | null> {
545 try {
546 return new Map((await $.agent.list()).map(agent => [agent.id, agent.status]))
547 } catch {
548 return null
549 }
550}
551
552async function startCard($: Engine, id: string) {
553 const now = await $.clock.now()
554 await change($, mission => (mission === null ? mission : withCard(mission, id, card => started(card, now))))
555}
556
557async function finish($: Engine, id: string, status: 'done' | 'stuck') {
558 const now = await $.clock.now()
559 await change($, mission => (mission === null ? mission : withCard(mission, id, card => ended(card, status, now))))
560}
561
562// A background helper finishes with its own turn.complete; a foreground one,
563// or one whose spawn the dock never saw, finishes when its call returns.
564async function afterCall($: Engine, id: string, ran: ToolCallResult) {
565 if (ran.deny !== undefined) {
566 await change($, mission => (mission === null ? mission : withoutCard(mission, id)))
567 return
568 }
569 if (ran.isError === true) {
570 await finish($, id, 'stuck')
571 return
572 }
573 const card = (await read($, missionAtom))?.cards.find(one => one.id === id)
574 if (card?.isBackground !== true || card.agentId === null) {
575 await finish($, id, 'done')
576 }
577}
578
579async function change($: Engine, fn: (mission: DockMission | null) => DockMission | null): Promise<DockMission | null> {
580 const mission = await update($, missionAtom, fn)
581 syncTicker($, mission)
582 await refreshBadge($, mission)
583 await publishCount($)
584
585 return mission
586}
587
588// One clock, and only while a mission is live.
589function syncTicker($: Engine, mission: DockMission | null) {
590 const shouldTick = isLive(mission)
591 if (shouldTick && ticker === null) {
592 ticker = $.clock.every(FRAME_MS, () => {
593 void update($, tickAtom, frame => frame + 1)
594 })
595 } else if (!shouldTick && ticker !== null) {
596 ticker.cancel()
597 ticker = null
598 }
599}
600
601async function refreshBadge($: Engine, known?: DockMission | null) {
602 const isFolded = await read($, foldedAtom)
603 const mission = known === undefined ? await read($, missionAtom) : known
604 const text = isFolded ? badgeText(mission) : undefined
605 if (text !== shownStatus) {
606 shownStatus = text
607 $.ui.status(text)
608 }
609}
610
611async function fold($: Engine, isFolded: boolean) {
612 await update($, foldedAtom, () => isFolded)
613 await refreshBadge($)
614}
615
616async function isDockOpen($: Engine): Promise<boolean> {
617 return (await $.ui.panes()).some(pane => pane.id === PANE)
618}
619
620async function toggleDock($: Engine) {
621 try {
622 if (await isDockOpen($)) {
623 await $.ui.close({ id: PANE })
624 await fold($, true)
625 } else {
626 await showDock($)
627 }
628 } catch {
629 $.ui.toast('The Agent Dock could not open. Try /dock again.')
630 }
631}
632
633// Opened from a command or a press, so it seats at any width; `columns` docks
634// it beside the transcript in fullscreen.
635async function showDock($: Engine) {
636 const opened = await $.ui.open({ id: PANE, title: 'Agent Dock', columns: DOCK_COLUMNS })
637 if (opened.isPlaced) {
638 await fold($, false)
639 } else {
640 $.ui.toast(TOO_NARROW)
641 await fold($, true)
642 }
643}
644
645async function chooseSize($: Engine, size: number) {
646 await update($, customAtom, () => false)
647 if (isBigTeam(size)) {
648 await update($, pendingAtom, () => size)
649 return
650 }
651 await commitSize($, size)
652}
653
654async function commitSize($: Engine, size: number) {
655 await update($, pendingAtom, () => null)
656 await update($, sizeAtom, () => size)
657 await $.store.set(SIZE_KEY, size)
658}
659
660async function confirmBigTeam($: Engine) {
661 const pending = await read($, pendingAtom)
662 if (pending !== null) {
663 await commitSize($, pending)
664 }
665}
666
667async function cancelBigTeam($: Engine) {
668 await update($, pendingAtom, () => null)
669}
670
671async function setCustomOpen($: Engine, isOpen: boolean) {
672 await update($, customAtom, () => isOpen)
673}
674
675async function submitCustom($: Engine, text: string) {
676 const size = parseSize(text)
677 if (size === null) {
678 $.ui.toast(BAD_CUSTOM)
679 return
680 }
681 await chooseSize($, size)
682}
683
684async function pickModel($: Engine, model: DockHelperModel) {
685 await update($, modelAtom, () => model)
686 await $.store.set(MODEL_KEY, model)
687}
688
689type Elements = ReturnType<Engine['ui']['resolve']>
690type TextElement = Elements['Text']
691
692async function drawCustomSize($: Engine, e: RenderInput<'Pane'>) {
693 if (!(await read($, customAtom))) {
694 return null
695 }
696 const { Box, Text, Button } = $.ui.resolve(e)
697
698 return (
699 <Box borderStyle="round" borderColor={CORAL} paddingX={1} flexDirection="row" gap={2}>
700 {e.surface === 'mobile' ? (
701 <Text>Type /dock and a number from 1 to 100</Text>
702 ) : (
703 (() => {
704 const { Input } = $.ui.resolve(e)
705 return (
706 <Input
707 key="custom-size"
708 label={CUSTOM_QUESTION}
709 placeholder={CUSTOM_PLACEHOLDER}
710 submitLabel="set"
711 autoFocus
712 onSubmit={value => submitCustom($, value)}
713 />
714 )
715 })()
716 )}
717 <Button key="custom-cancel" plain label="Cancel" onPress={() => setCustomOpen($, false)} />
718 </Box>
719 )
720}
721
722async function drawBigTeamConfirm($: Engine, e: RenderInput<'Pane'>) {
723 const pending = await read($, pendingAtom)
724 if (pending === null) {
725 return null
726 }
727 const { Box, Text, Button } = $.ui.resolve(e)
728
729 return (
730 <Box borderStyle="round" borderColor={GOLD} paddingX={1} flexDirection="column">
731 <Text color={GOLD}>{BIG_TEAM_QUESTION}</Text>
732 <Box flexDirection="row" gap={2}>
733 <Button key="big-continue" variant="primary" autoFocus label={`Continue with ${pending}`} onPress={() => confirmBigTeam($)} />
734 <Button key="big-cancel" label="Cancel" onPress={() => cancelBigTeam($)} />
735 </Box>
736 </Box>
737 )
738}
739
740async function drawDock($: Engine, e: RenderInput<'Pane'>) {
741 const { Box, Text, Button } = $.ui.resolve(e)
742 const columns = Math.max(24, e.props.bodyColumns)
743 const [size, model, mission, customBox, confirmBox] = await Promise.all([
744 read($, sizeAtom),
745 read($, modelAtom),
746 read($, missionAtom),
747 drawCustomSize($, e),
748 drawBigTeamConfirm($, e),
749 ])
750 const now = await $.clock.now()
751 // Only a live mission reads the clock, so nothing redraws while idle.
752 const frame = isLive(mission) ? await read($, tickAtom) : 0
753
754 const chip = (label: string) => (
755 <Text backgroundColor={CORAL} color={INK} bold>
756 {label}
757 </Text>
758 )
759 const isPreset = (SIZES as readonly number[]).includes(size)
760
761 return (
762 <Box flexDirection="column">
763 <Box flexDirection="row" justifyContent="space-between">
764 <Text>
765 <Text color={CORAL}>{'◆ '}</Text>
766 {wordmark(Text)}
767 </Text>
768 {liveMark(Text, mission, frame)}
769 </Box>
770 <Text color={HAIRLINE}>{'─'.repeat(columns)}</Text>
771
772 <Box flexDirection="row" flexWrap="wrap">
773 <Text color={MUTED}>{`${spaced('TEAM SIZE')} `}</Text>
774 <Text color={HAIRLINE}>{'╭ '}</Text>
775 {SIZES.map(option =>
776 option === size ? (
777 chip(` ${option} `)
778 ) : (
779 <Button key={`size-${option}`} plain label={` ${option} `} onPress={() => chooseSize($, option)} />
780 ),
781 )}
782 <Text color={HAIRLINE}>{' │ '}</Text>
783 {isPreset ? null : chip(` ${size} `)}
784 <Button key="size-custom" plain label=" Custom " onPress={() => setCustomOpen($, true)} />
785 <Text color={HAIRLINE}>{' ╮'}</Text>
786 </Box>
787 <Text color={MUTED} wrap="truncate-end">
788 {infoLine(size, atOnce, model)}
789 </Text>
790 <Box flexDirection="row">
791 <Text color={MUTED}>{'Helper agents '}</Text>
792 {model === 'fast' ? chip(' Fast & Cheap ') : <Button key="model-fast" plain label=" Fast & Cheap " onPress={() => pickModel($, 'fast')} />}
793 <Text> </Text>
794 {model === 'same' ? chip(' Same as me ') : <Button key="model-same" plain label=" Same as me " onPress={() => pickModel($, 'same')} />}
795 </Box>
796 {customBox}
797 {confirmBox}
798 <Text> </Text>
799 {mission === null ? idle(Box, Text, size) : drawMission($, e, mission, columns, now, frame)}
800 </Box>
801 )
802}
803
804function wordmark(Text: TextElement) {
805 const letters = [...spaced('AGENT DOCK')]
806 const last = Math.max(1, letters.length - 1)
807
808 return letters.map((letter, index) => (
809 <Text color={mix(CORAL, GOLD, index / last)} bold>
810 {letter}
811 </Text>
812 ))
813}
814
815function liveMark(Text: TextElement, mission: DockMission | null, frame: number) {
816 if (mission === null) {
817 return <Text color={MUTED}>{spaced('STANDING BY')}</Text>
818 }
819 if (mission.finishedAt !== null) {
820 return <Text color={GREEN}>{spaced('COMPLETE')}</Text>
821 }
822
823 // A slow blink: bright for three frames, soft for two.
824 return (
825 <Text color={frame % 5 < 3 ? GREEN : '#1F7A45'} bold>
826 {`● ${spaced('LIVE')}`}
827 </Text>
828 )
829}
830
831function idle(Box: Elements['Box'], Text: TextElement, size: number) {
832 const [standing, hint] = standingBy(size)
833
834 return (
835 <Box flexDirection="column">
836 <Text>
837 {seats(size).map((seat, index) => (
838 <Text color={seat.color} dimColor={seat.isSoft}>
839 {index === 0 ? '●' : ' ●'}
840 </Text>
841 ))}
842 </Text>
843 <Text bold>{standing}</Text>
844 <Text color={MUTED}>{hint}</Text>
845 </Box>
846 )
847}
848
849function drawMission($: Engine, e: RenderInput<'Pane'>, mission: DockMission, columns: number, now: number, frame: number) {
850 const { Box, Text } = $.ui.resolve(e)
851 const tally = counts(mission.cards)
852 const elapsed = `${missionPercent(mission.cards)}% ${formatClock((mission.finishedAt ?? now) - mission.startedAt)}`
853 const isAllBack = mission.cards.length > 0 && mission.cards.every(card => isFinished(card.status))
854 const useTiles = mission.cards.length > TILES_AFTER
855
856 return (
857 <Box flexDirection="column">
858 <Box flexDirection="row" justifyContent="space-between">
859 <Box width={Math.max(8, columns - elapsed.length - 2)}>
860 <Text wrap="truncate-end">
861 <Text color={MUTED}>{`${spaced('MISSION')} `}</Text>
862 <Text bold>{mission.job}</Text>
863 </Text>
864 </Box>
865 <Text bold>{elapsed}</Text>
866 </Box>
867 <Text>{parts(Text, missionBar(mission.cards, columns, frame))}</Text>
868 <Box flexDirection="row" gap={4}>
869 <Text color={GREEN}>{`● ${tally.working} working`}</Text>
870 <Text color={MUTED}>{`○ ${tally.queued} queued`}</Text>
871 <Text color={GOLD}>{`✓ ${tally.done} done`}</Text>
872 <Text color={tally.stuck > 0 ? RED : MUTED}>{`✕ ${tally.stuck} stuck`}</Text>
873 </Box>
874 {mission.finishedAt !== null ? (
875 <Box borderStyle="round" borderColor={GREEN} paddingX={1}>
876 <Text>
877 <Text color={GREEN}>{'✓ '}</Text>
878 {summary(mission)}
879 </Text>
880 </Box>
881 ) : mission.cards.length === 0 ? (
882 <Text color={MUTED}>{`Claude is splitting the work across ${mission.size} helpers…`}</Text>
883 ) : isAllBack ? (
884 <Text color={MUTED}>Every helper is back. Claude is combining their work…</Text>
885 ) : null}
886 <Text> </Text>
887 {useTiles ? tiles($, e, mission.cards, columns, frame) : cards($, e, mission.cards, columns, now, frame)}
888 </Box>
889 )
890}
891
892function cards($: Engine, e: RenderInput<'Pane'>, list: readonly DockCard[], columns: number, now: number, frame: number) {
893 const { Box, Text } = $.ui.resolve(e)
894 const perRow = cardsPerRow(columns)
895 const width = Math.floor((columns - (perRow - 1)) / perRow)
896 const inner = width - 4
897
898 return (
899 <Box flexDirection="column">
900 {rows(list, perRow).map(row => (
901 <Box flexDirection="row" gap={1}>
902 {row.map(card => {
903 const isQueued = card.status === 'queued'
904 const time = cardTime(card, now)
905 const label = percentLabel(card).padStart(5)
906 return (
907 <Box
908 key={`card-${card.id}`}
909 width={width}
910 flexDirection="column"
911 borderStyle="round"
912 borderColor={card.status === 'stuck' ? RED : HAIRLINE}
913 hover={{ borderColor: CORAL }}
914 paddingX={1}
915 >
916 <Box flexDirection="row">
917 {face(Text, card)}
918 <Text> </Text>
919 <Box width={Math.max(4, inner - 6 - time.length)}>
920 <Text wrap="truncate-end" bold={card.status === 'working'} dimColor={isQueued}>
921 {card.task}
922 </Text>
923 </Box>
924 <Text> </Text>
925 <Text color={MUTED} dimColor={isQueued}>
926 {time}
927 </Text>
928 </Box>
929 <Text>
930 {' '}
931 {parts(Text, meter(card, Math.max(1, inner - 10), frame))}
932 <Text dimColor={isQueued} color={card.status === 'stuck' ? RED : undefined}>
933 {label}
934 </Text>
935 </Text>
936 </Box>
937 )
938 })}
939 </Box>
940 ))}
941 </Box>
942 )
943}
944
945// Past twelve helpers each one is a one-line tile, so 50 or 100 still fit.
946function tiles($: Engine, e: RenderInput<'Pane'>, list: readonly DockCard[], columns: number, frame: number) {
947 const { Box, Text } = $.ui.resolve(e)
948 const perRow = tilesPerRow(columns, TILE_WIDTH)
949
950 return (
951 <Box flexDirection="column">
952 {rows(list, perRow).map(row => (
953 <Box flexDirection="row" gap={1}>
954 {row.map(card => (
955 <Box key={`tile-${card.id}`} width={TILE_WIDTH} flexDirection="row">
956 {face(Text, card)}
957 <Text> </Text>
958 <Text>{parts(Text, meter(card, TILE_WIDTH - 10, frame))}</Text>
959 <Text dimColor={card.status === 'queued'} color={card.status === 'stuck' ? RED : undefined}>
960 {percentLabel(card).padStart(5)}
961 </Text>
962 </Box>
963 ))}
964 </Box>
965 ))}
966 </Box>
967 )
968}
969
970// The terminal draws no headshots here, so every face is a two-letter badge.
971function face(Text: TextElement, card: DockCard) {
972 return (
973 <Text
974 backgroundColor={BADGE_COLORS[card.colorIndex] ?? CORAL}
975 color={INK}
976 bold
977 dimColor={card.status === 'queued'}
978 hover={{ backgroundColor: CORAL }}
979 >
980 {` ${card.initials} `}
981 </Text>
982 )
983}
984
985function percentLabel(card: DockCard): string {
986 switch (card.status) {
987 case 'queued':
988 return '—'
989 case 'stuck':
990 return '✕'
991 case 'done':
992 return '100%'
993 case 'working':
994 return card.hasReported ? `${card.percent}%` : '…'
995 }
996}
997
998function parts(Text: TextElement, list: MeterPart[]) {
999 return list.map(part => <Text color={part.color}>{part.text}</Text>)
1000}
1001hooks/status-line-dock.tsx 887 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On, RenderInput, RenderNode, Timer } from 'claude-code'
3
4import type { StatusLineBlockId, StatusLineLayout, StatusLineRun, StatusLineScope, StatusLineSetup } from '../types'
5import { checklistView, isAnimated } from './checklist-view'
6import { CORAL, GOLD, HAIRLINE, INK, MUTED, counts, spaced } from './dock-logic'
7import {
8 ICON_NAMES,
9 ICON_STYLES,
10 agentDockRecord,
11 blockName,
12 installPlan,
13 isOff,
14 layoutFile,
15 layoutSummary,
16 layoutText,
17 moveAcross,
18 moveAlong,
19 nextIcons,
20 parseRecords,
21 parseSettings,
22 pathsFor,
23 previewFrom,
24 previewInput,
25 recordsText,
26 rows,
27 sameLayout,
28 sessionFile,
29 setupFrom,
30 startingLayout,
31 statusLineCommand,
32 toggleBlock,
33 turnOn,
34 uninstallPlan,
35 withoutAgentDockRecord,
36} from './status-line-logic'
37import type { Paths } from './status-line-logic'
38
39type Engine = EngineInterface
40type Elements = ReturnType<Engine['ui']['resolve']>
41
42const bandViewAtom = atom({ plugin: 'mods-toolbox', key: 'bandView' } as const, null)
43const setupAtom = atom({ plugin: 'mods-toolbox', key: 'statusLineSetup' } as const, null)
44const scopeAtom = atom({ plugin: 'mods-toolbox', key: 'statusLineScope' } as const, 'global')
45const draftsAtom = atom({ plugin: 'mods-toolbox', key: 'statusLineDrafts' } as const, { global: null, project: null })
46const selectedAtom = atom({ plugin: 'mods-toolbox', key: 'statusLineSelected' } as const, null)
47const confirmAtom = atom({ plugin: 'mods-toolbox', key: 'statusLineConfirm' } as const, null)
48const previewAtom = atom({ plugin: 'mods-toolbox', key: 'statusLinePreview' } as const, null)
49const skillAtom = atom({ plugin: 'mods-toolbox', key: 'statusLineSkill' } as const, null)
50// Clean View's, the Agent Dock's and the chat picks' values, read on the keys their files write.
51const cleanViewAtom = atom({ plugin: 'mods-toolbox', key: 'cleanViewEnabled' } as const, true)
52const checklistAtom = atom({ plugin: 'mods-toolbox', key: 'checklist' } as const, null)
53const tickAtom = atom({ plugin: 'mods-toolbox', key: 'tick' } as const, 0)
54const missionAtom = atom({ plugin: 'mods-toolbox', key: 'dockMission' } as const, null)
55const chatModelAtom = atom({ plugin: 'mods-toolbox', key: 'chatModel' } as const, null)
56const chatEffortAtom = atom({ plugin: 'mods-toolbox', key: 'chatEffort' } as const, null)
57
58const PREVIEW_MS = 2000
59const RUN_TIMEOUT_MS = 2000
60const LABEL_WIDTH = 9
61const ROW_LABELS = ['Line 1', 'Line 2', 'Off']
62const SCOPE_NAMES: Record<StatusLineScope, string> = { global: 'Global', project: 'This project' }
63// Any key no button takes, like Esc, hands the keyboard back to the prompt.
64const KEYS_HINT = 'click the Dock, then the keys · other keys go to the prompt'
65const CAPTURE_MAX_MINUTES = '+1440'
66
67// Module state a reload may drop: session.start and the next open put it back.
68let previewTimer: Timer | null = null
69let isPreviewRunning = false
70let isPreviewAgain = false
71// The terminal's width as the band last measured it, until the renderer has reported Claude Code's own.
72let terminalColumns = 0
73// One grant per /command or Skill call of the main conversation in flight, for
74// the skill it asked for: the first skill.prompt of that skill takes it, so two
75// calls out at once each take their own. Used once, since a forked skill's call
76// stays in flight while its subagent runs skills of its own.
77const skillGrants: Array<{ skill: string; isUsed: boolean }> = []
78// The skill file the status line reads: where it went, and its writes in order.
79let skillPath: string | null = null
80let skillQueue: Promise<void> = Promise.resolve()
81
82export function registerStatusLineDock(on: On) {
83 // Clean View holds the bare session.start, the dock { cwd: /^/ }, the Toolbox
84 // a surface matcher and the chat picks isInteractive; every cwd holds a slash.
85 on('session.start', { cwd: /\// }, async ($, e, next) => {
86 try {
87 await $.command.register({
88 name: 'status-dock',
89 description: 'Open or close the Status Line Dock: build the status line from blocks, with a preview',
90 immediate: true,
91 })
92 } catch {
93 // The Toolbox's Launch entry still opens it.
94 }
95 try {
96 const where = await currentPaths($)
97 const setup = await loadSetup($, where)
98 await keepRendererCurrent($, where, setup)
99 await sweepDayOld($, where.captures)
100 await sweepDayOld($, where.skills)
101 if ((await read($, bandViewAtom)) === 'statusLineDock') {
102 syncPreviewTimer($, true)
103 }
104 } catch {
105 // The Dock reads the files again when it opens.
106 }
107
108 return next(e)
109 })
110
111 on('command.run', { command: 'status-dock' }, async $ => {
112 if ((await read($, bandViewAtom)) === 'statusLineDock') {
113 await closeDock($)
114 return { text: 'Status Line Dock closed.' }
115 }
116 await openDock($).catch(() => $.ui.toast('The Status Line Dock could not open. Try /status-dock again.'))
117
118 return { text: 'Status Line Dock open above the prompt.' }
119 })
120
121 // The Toolbox draws the Launch entry; opening the Dock is this file's to do.
122 on('ui.press', { plugin: 'mods-toolbox', component: 'AbovePrompt', element: 'toolbox-status-line' }, async ($, e) => {
123 await openDock($).catch(() => $.ui.toast('The Status Line Dock could not open. Try /status-dock.'))
124
125 return { element: e.element }
126 })
127
128 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
129 if (e.props.hasSurvey || (await read($, bandViewAtom)) !== 'statusLineDock') {
130 return next(e)
131 }
132 terminalColumns = e.viewport?.columns ?? e.props.bodyColumns + 5
133 const { Box } = $.ui.resolve(e)
134 const [checklist, dock, below] = await Promise.all([drawChecklist($, e), drawDock($, e), next(e)])
135
136 // The engine refuses its own band rows under a sized Box, so they stay below.
137 return (
138 <Box flexDirection="column">
139 {checklist}
140 {dock}
141 {below}
142 </Box>
143 )
144 })
145
146 // The Skill block. A skill typed as /name expands inside its command.run, and
147 // one Claude calls inside its tool.call; skill.prompt alone can't tell either
148 // from a subagent's call or preload, so it counts only with a caller's grant.
149 on('command.run', async ($, e, next) => {
150 const grant = { skill: e.command, isUsed: false }
151 skillGrants.push(grant)
152 try {
153 return await next(e)
154 } finally {
155 skillGrants.splice(skillGrants.indexOf(grant), 1)
156 }
157 })
158
159 on('tool.call', { tool: 'Skill' }, async ($, e, next) => {
160 if (e.agentId !== undefined) {
161 return next(e)
162 }
163 const grant = { skill: e.skill.replace(/^\//, ''), isUsed: false }
164 skillGrants.push(grant)
165 try {
166 return await next(e)
167 } finally {
168 skillGrants.splice(skillGrants.indexOf(grant), 1)
169 }
170 })
171
172 on('skill.prompt', async ($, e, next) => {
173 // The Skill tool may ask for `review-plan` where the engine resolves `council:review-plan`.
174 const grant = skillGrants.findLast(open => !open.isUsed && (e.skill === open.skill || e.skill.endsWith(`:${open.skill}`)))
175 if (grant !== undefined) {
176 grant.isUsed = true
177 }
178 const expanded = await next(e)
179 if (grant !== undefined) {
180 try {
181 await update($, skillAtom, () => ({ name: e.skill, isRunning: true }))
182 await publishSkill($)
183 } catch {
184 // The block keeps the skill before this one.
185 }
186 }
187
188 return expanded
189 })
190
191 // Written at every turn's end, not only when the skill stops running: an active
192 // session's file stays fresh for the day-old sweep, and one an uninstall or
193 // sweep took comes back.
194 on('turn.complete', { reason: /^/ }, async ($, e, next) => {
195 if (e.agentId === undefined) {
196 try {
197 const skill = await read($, skillAtom)
198 if (skill !== null) {
199 await update($, skillAtom, () => ({ ...skill, isRunning: false }))
200 await publishSkill($)
201 }
202 } catch {
203 // It stays as it was until the next turn's end.
204 }
205 }
206
207 return next(e)
208 })
209
210 // After a /clear or a resume the process goes on under a new session id with
211 // no session.start, so the skill goes with the conversation that ran it.
212 on('session.end', { reason: /^/ }, async ($, e, next) => {
213 try {
214 await update($, skillAtom, () => null)
215 await publishSkill($)
216 } catch {
217 // A day later the sweep takes it.
218 }
219
220 return next(e)
221 })
222}
223
224async function openDock($: Engine) {
225 await update($, bandViewAtom, () => 'statusLineDock')
226 const setup = await loadSetup($, await currentPaths($))
227 // The Dock opens on the scope in force here.
228 if (setup.project.isInstalled) {
229 await update($, scopeAtom, () => 'project')
230 }
231 syncPreviewTimer($, true)
232 await refreshPreview($)
233}
234
235async function closeDock($: Engine) {
236 await update($, bandViewAtom, current => (current === 'statusLineDock' ? null : current))
237 await update($, confirmAtom, () => null)
238 syncPreviewTimer($, false)
239}
240
241// --- Files ------------------------------------------------------------------
242
243async function currentPaths($: Engine): Promise<Paths> {
244 const [configDir, home, root] = await Promise.all([$.env.get('CLAUDE_CONFIG_DIR'), $.env.get('HOME'), $.session.root()])
245
246 return pathsFor(configDir, home ?? '', root)
247}
248
249async function readText($: Engine, path: string): Promise<string | null> {
250 try {
251 return (await $.fs.exists(path)) ? await $.fs.read(path) : null
252 } catch {
253 return null
254 }
255}
256
257async function loadSetup($: Engine, where: Paths): Promise<StatusLineSetup> {
258 const [policy, user, project, local, globalLayout, projectLayout, records] = await Promise.all([
259 $.settings.read({ source: 'policy' }).catch(() => ({})),
260 readText($, where.userSettings),
261 readText($, where.projectSettings),
262 readText($, where.localSettings),
263 readText($, layoutFile(where, 'global')),
264 readText($, layoutFile(where, 'project')),
265 readText($, where.records),
266 ])
267 const setup = setupFrom({
268 paths: where,
269 user,
270 project,
271 local,
272 globalLayout,
273 projectLayout,
274 records,
275 isLocked: statusLineCommand(policy) !== null,
276 })
277 await update($, setupAtom, () => setup)
278
279 return setup
280}
281
282async function remove($: Engine, ...targets: string[]) {
283 await $.process.run(['rm', '-rf', ...targets]).catch(() => undefined)
284}
285
286// Settings files point at the copy under the config folder, since the plugin's
287// own folder carries its version. Each session puts the shipped one there while
288// any install or settings file uses it, so an update reaches every status line
289// and a settings file from another machine's dotfiles finds its renderer here.
290async function keepRendererCurrent($: Engine, where: Paths, setup: StatusLineSetup, isInstalling = false) {
291 const records = parseRecords(await readText($, where.records))
292 const isUsed = Object.keys(records).length > 0 || setup.global.isInstalled || setup.project.isInstalled
293 if (!isInstalling && !isUsed) {
294 return
295 }
296 for (const [shipped, copy] of [
297 [`${$.plugin.root}/renderer/statusline.sh`, where.renderer],
298 [`${$.plugin.root}/renderer/statusline.jq`, where.rendererJq],
299 ] as const) {
300 const text = await $.fs.read(shipped)
301 if ((await readText($, copy)) !== text) {
302 await $.fs.write(copy, text)
303 }
304 }
305}
306
307// Per-session files (the renderer's inputs, the skills) of sessions that ended a day ago or more.
308async function sweepDayOld($: Engine, folder: string) {
309 if (await $.fs.exists(folder).catch(() => false)) {
310 await $.process.run(['find', folder, '-type', 'f', '-name', '*.json', '-mmin', CAPTURE_MAX_MINUTES, '-delete']).catch(() => undefined)
311 }
312}
313
314// --- The skill file ---------------------------------------------------------
315
316// Writes are chained so an older skill never lands after a newer one.
317function publishSkill($: Engine): Promise<void> {
318 skillQueue = skillQueue.then(() => writeSkill($)).catch(() => undefined)
319
320 return skillQueue
321}
322
323// Only while an install runs the renderer: an uninstall takes the whole folder,
324// and a skill after it must not bring the folder back.
325async function writeSkill($: Engine) {
326 const where = await currentPaths($)
327 const skill = await read($, skillAtom)
328 if (skill === null || !(await $.fs.exists(where.renderer).catch(() => false))) {
329 await dropSkillFile($)
330 return
331 }
332 // A /clear goes on under a new session id, so the path can move.
333 const path = sessionFile(where.skills, await $.session.id())
334 if (skillPath !== null && skillPath !== path) {
335 await remove($, skillPath)
336 }
337 skillPath = path
338 await $.fs.write(path, JSON.stringify(skill))
339}
340
341async function dropSkillFile($: Engine) {
342 if (skillPath === null) {
343 return
344 }
345 const stale = skillPath
346 skillPath = null
347 await remove($, stale)
348}
349
350// --- Editing ----------------------------------------------------------------
351
352type Editing = {
353 setup: StatusLineSetup
354 scope: StatusLineScope
355 saved: StatusLineLayout
356 layout: StatusLineLayout
357 hasChanges: boolean
358}
359
360async function editing($: Engine): Promise<Editing | null> {
361 const setup = await read($, setupAtom)
362 if (setup === null) {
363 return null
364 }
365 const scope = await read($, scopeAtom)
366 const saved = startingLayout(setup, scope)
367 const draft = (await read($, draftsAtom))[scope]
368 const layout = draft ?? saved
369
370 return { setup, scope, saved, layout, hasChanges: draft !== null && !sameLayout(draft, saved) }
371}
372
373async function edit($: Engine, change: (layout: StatusLineLayout, selected: StatusLineBlockId) => StatusLineLayout) {
374 const current = await editing($)
375 if (current === null) {
376 return
377 }
378 const selected = (await read($, selectedAtom)) ?? rows(current.layout).flat()[0]
379 if (selected === undefined) {
380 return
381 }
382 await update($, selectedAtom, () => selected)
383 const changed = change(current.layout, selected)
384 await update($, draftsAtom, drafts => ({ ...drafts, [current.scope]: sameLayout(changed, current.saved) ? null : changed }))
385 void refreshPreview($)
386}
387
388async function select($: Engine, id: StatusLineBlockId) {
389 await update($, selectedAtom, () => id)
390}
391
392// A click selects a block; one that is off is turned on too.
393async function pick($: Engine, id: StatusLineBlockId) {
394 await select($, id)
395 const current = await editing($)
396 if (current !== null && isOff(current.layout, id)) {
397 await edit($, now => turnOn(now, id))
398 }
399}
400
401async function chooseScope($: Engine, scope: StatusLineScope) {
402 await update($, scopeAtom, () => scope)
403 await update($, confirmAtom, () => null)
404 void refreshPreview($)
405}
406
407async function revert($: Engine) {
408 const scope = await read($, scopeAtom)
409 await update($, draftsAtom, drafts => ({ ...drafts, [scope]: null }))
410 await update($, confirmAtom, () => null)
411 void refreshPreview($)
412}
413
414// Installed, Apply saves the Layout the renderer reads; otherwise it asks first.
415async function apply($: Engine) {
416 const current = await editing($)
417 if (current === null || current.setup.isLocked || current.setup[current.scope].problem !== null) {
418 return
419 }
420 const state = current.setup[current.scope]
421 if (!state.isInstalled) {
422 await update($, confirmAtom, () => 'install')
423 return
424 }
425 await $.fs.write(state.layoutFile, layoutText(current.layout))
426 await update($, draftsAtom, drafts => ({ ...drafts, [current.scope]: null }))
427 await loadSetup($, await currentPaths($))
428 $.ui.toast('Status line updated.')
429}
430
431async function install($: Engine) {
432 const current = await editing($)
433 await update($, confirmAtom, () => null)
434 if (current === null) {
435 return
436 }
437 const where = await currentPaths($)
438 const state = current.setup[current.scope]
439 const [settingsText, recordsFile, agentDockText] = await Promise.all([
440 readText($, state.file),
441 readText($, where.records),
442 readText($, where.agentDockRecords),
443 ])
444 const records = parseRecords(recordsFile)
445 const plan = installPlan({
446 scope: current.scope,
447 state,
448 settingsText,
449 draft: current.layout,
450 command: state.command,
451 existing: records[state.file],
452 agentDockValue: agentDockRecord(agentDockText, state.file),
453 })
454 if ('problem' in plan) {
455 $.ui.toast(plan.problem)
456 return
457 }
458
459 await keepRendererCurrent($, where, current.setup, true)
460 await $.fs.write(state.layoutFile, layoutText(plan.layout))
461 await $.fs.write(where.records, recordsText({ ...records, [plan.file]: plan.record }))
462 // Written last: the status line only switches once its renderer and Layout are there.
463 await $.fs.write(plan.file, plan.text)
464 if (plan.wasAgentDock) {
465 await retireAgentDockLine($, where, agentDockText, plan.file)
466 }
467
468 await update($, draftsAtom, drafts => ({ ...drafts, [current.scope]: null }))
469 await loadSetup($, where)
470 // A skill run before the install shows from the first refresh.
471 await publishSkill($)
472 await refreshPreview($)
473 $.ui.toast(`Status line set in ${plan.file}.`)
474 if (plan.createsFile && current.scope === 'project' && !(await isGitIgnored($, where.root, plan.file))) {
475 $.ui.toast('Keep .claude/settings.local.json out of git: add it to .gitignore.')
476 }
477}
478
479// The Agent Dock's add-on stays while any settings file it lists still runs it.
480async function retireAgentDockLine($: Engine, where: Paths, text: string | null, file: string) {
481 const rest = withoutAgentDockRecord(text, file)
482 if (rest !== '') {
483 await $.fs.write(where.agentDockRecords, rest)
484 return
485 }
486 await remove($, where.agentDockRecords, where.agentDockAddon)
487}
488
489async function isGitIgnored($: Engine, root: string, file: string): Promise<boolean> {
490 const ran = await $.process.run(['git', '-C', root, 'check-ignore', '-q', file]).catch(() => null)
491
492 return ran === null || ran.exitCode === 0
493}
494
495async function uninstall($: Engine) {
496 await update($, confirmAtom, () => null)
497 const current = await editing($)
498 if (current === null) {
499 return
500 }
501 const where = await currentPaths($)
502 const state = current.setup[current.scope]
503 const records = parseRecords(await readText($, where.records))
504 const record = records[state.file]
505 const plan = uninstallPlan(await readText($, state.file), state.file, record)
506 if ('problem' in plan) {
507 $.ui.toast(plan.problem)
508 return
509 }
510 if (plan.text === null) {
511 await remove($, state.file)
512 } else if (plan.text !== undefined) {
513 await $.fs.write(state.file, plan.text)
514 }
515
516 const { [state.file]: _gone, ...rest } = records
517 const other = current.setup[current.scope === 'global' ? 'project' : 'global']
518 if (Object.keys(rest).length === 0 && !other.isInstalled) {
519 // Nothing runs the renderer any more: everything the installs put under the config folder goes.
520 await remove($, `${where.config}/mods-toolbox`)
521 } else {
522 await remove($, state.layoutFile)
523 if (record !== undefined) {
524 await $.fs.write(where.records, recordsText(rest))
525 }
526 }
527
528 await update($, draftsAtom, drafts => ({ ...drafts, [current.scope]: null }))
529 await loadSetup($, where)
530 await refreshPreview($)
531 $.ui.toast(
532 plan.text === undefined
533 ? `The status line in ${state.file} is no longer this Dock's, so it stays.`
534 : record === undefined
535 ? `Status line taken out of ${state.file}.`
536 : `Status line in ${state.file} put back as it was.`,
537 )
538}
539
540// --- Preview ----------------------------------------------------------------
541
542function syncPreviewTimer($: Engine, isOpen: boolean) {
543 if (isOpen && previewTimer === null) {
544 previewTimer = $.clock.every(PREVIEW_MS, () => {
545 void refreshPreview($)
546 })
547 } else if (!isOpen && previewTimer !== null) {
548 previewTimer.cancel()
549 previewTimer = null
550 }
551}
552
553// One run at a time; an edit during a run asks for one more after it.
554async function refreshPreview($: Engine) {
555 if (isPreviewRunning) {
556 isPreviewAgain = true
557 return
558 }
559 isPreviewRunning = true
560 try {
561 if ((await read($, bandViewAtom)) !== 'statusLineDock') {
562 syncPreviewTimer($, false)
563 return
564 }
565 await runPreview($)
566 } catch {
567 // The next tick tries again.
568 } finally {
569 isPreviewRunning = false
570 }
571 if (isPreviewAgain) {
572 isPreviewAgain = false
573 await refreshPreview($)
574 }
575}
576
577async function runPreview($: Engine) {
578 const current = await editing($)
579 if (current === null) {
580 return
581 }
582 const where = await currentPaths($)
583 const sessionId = await $.session.id()
584 const capturedText = await readText($, sessionFile(where.captures, sessionId))
585 const captured = parseSettings(capturedText, 'last input').settings
586 const [cwd, model, version, effort, settings, usage, mission, skill] = await Promise.all([
587 $.session.cwd(),
588 read($, chatModelAtom).then(known => known ?? $.session.model().catch(() => null)),
589 $.session.version().then(
590 found => found.version,
591 () => null,
592 ),
593 read($, chatEffortAtom),
594 $.settings.read().catch(() => ({}) as Record<string, unknown>),
595 $.session.usage().catch(() => null),
596 read($, missionAtom),
597 read($, skillAtom),
598 ])
599 const { input, samples, agents, skill: shownSkill } = previewInput({
600 captured,
601 sessionId,
602 cwd,
603 root: where.root,
604 modelId: model,
605 version,
606 effort,
607 outputStyle: typeof settings.outputStyle === 'string' ? settings.outputStyle : null,
608 usage,
609 now: await $.clock.now(),
610 agents: counts(mission?.cards ?? []).working,
611 skill,
612 })
613 const capturedColumns = captured?.columns
614 const columns = typeof capturedColumns === 'number' && capturedColumns > 0 ? capturedColumns : terminalColumns > 0 ? terminalColumns : 120
615
616 const ran = await $.process
617 .run(['sh', `${$.plugin.root}/renderer/statusline.sh`], {
618 stdin: JSON.stringify(input),
619 cwd,
620 timeoutMs: RUN_TIMEOUT_MS,
621 env: {
622 MODS_TOOLBOX_LAYOUT: JSON.stringify(current.layout),
623 MODS_TOOLBOX_PREVIEW: '1',
624 MODS_TOOLBOX_AGENTS: String(agents),
625 MODS_TOOLBOX_SKILL: JSON.stringify(shownSkill),
626 COLUMNS: String(columns),
627 },
628 })
629 .catch(() => null)
630 const on = new Set(current.layout.lines.flat())
631 const preview = previewFrom(ran?.stdout ?? '', columns, samples.filter(id => on.has(id)))
632 const shown = ran === null ? { ...preview, error: 'The preview took too long. It tries again in a moment.' } : preview
633 await update($, previewAtom, before => (JSON.stringify(before) === JSON.stringify(shown) ? before : shown))
634}
635
636// --- Drawing ----------------------------------------------------------------
637
638async function drawChecklist($: Engine, e: RenderInput<'AbovePrompt'>) {
639 const job = (await read($, cleanViewAtom)) ? await read($, checklistAtom) : null
640 if (job === null) {
641 return null
642 }
643 const { Box, Text } = $.ui.resolve(e)
644 const frame = isAnimated(job.phase) ? await read($, tickAtom) : 0
645
646 return checklistView(Box, Text, job, { columns: e.props.bodyColumns, isFolded: true, now: await $.clock.now(), frame })
647}
648
649function runs(Text: Elements['Text'], line: StatusLineRun[]) {
650 return line.map(({ text, ...style }) => <Text {...style}>{text}</Text>)
651}
652
653async function drawDock($: Engine, e: RenderInput<'AbovePrompt'>) {
654 const { Box, Text, Button } = $.ui.resolve(e)
655 const width = Math.max(30, e.props.bodyColumns)
656 const inner = width - 4
657 const [current, selected, confirm, preview] = await Promise.all([
658 editing($),
659 read($, selectedAtom),
660 read($, confirmAtom),
661 read($, previewAtom),
662 ])
663
664 const close = <Button key="sl-close" plain role="dismiss" label="✕" onPress={() => closeDock($)} />
665 const header = (meta: RenderNode) => (
666 <Box flexDirection="row" justifyContent="space-between">
667 <Text color={CORAL} bold>
668 {`◆ ${spaced('STATUS LINE DOCK')}`}
669 </Text>
670 <Box flexDirection="row" gap={2}>
671 {meta}
672 {close}
673 </Box>
674 </Box>
675 )
676 if (current === null) {
677 return (
678 <Box width={width} flexDirection="column" borderStyle="round" borderColor={HAIRLINE} paddingX={1}>
679 {header(<Text color={MUTED}>reading your settings…</Text>)}
680 </Box>
681 )
682 }
683
684 const { setup, scope, layout, hasChanges } = current
685 const state = setup[scope]
686 const isBlocked = setup.isLocked || state.problem !== null
687 const meta = [SCOPE_NAMES[scope], state.isInstalled ? 'installed' : 'not installed'].join(' · ')
688
689 const chip = (key: string, label: string, isOn: boolean, onPress: () => unknown) =>
690 isOn ? (
691 <Text backgroundColor={CORAL} color={INK} bold>
692 {label}
693 </Text>
694 ) : (
695 <Button key={key} plain label={label} onPress={onPress} />
696 )
697 const rule = (title: string, tail = '') => {
698 const label = spaced(title)
699 const rest = Math.max(0, inner - label.length - tail.length - 5)
700 return (
701 <Text>
702 <Text color={HAIRLINE}>{'── '}</Text>
703 <Text color={MUTED}>{label}</Text>
704 <Text color={HAIRLINE}>{` ${'─'.repeat(rest)} `}</Text>
705 <Text color={MUTED}>{tail}</Text>
706 </Text>
707 )
708 }
709
710 const modes = [
711 chip('sl-mode-replace', ' Replace ', layout.mode === 'replace', () => edit($, now => ({ ...now, mode: 'replace' }))),
712 ...(layout.base === null
713 ? []
714 : [chip('sl-mode-extend', ' Extend ', layout.mode === 'extend', () => edit($, now => ({ ...now, mode: 'extend' })))]),
715 ]
716 const scopes = (['global', 'project'] as const).map(name =>
717 chip(`sl-scope-${name}`, ` ${SCOPE_NAMES[name]} `, scope === name, () => chooseScope($, name)),
718 )
719 const icons = ICON_STYLES.map(style =>
720 chip(`sl-icons-${style}`, ` ${ICON_NAMES[style]} `, layout.icons === style, () => edit($, now => ({ ...now, icons: style }))),
721 )
722 const settingsRow = (
723 <Box flexDirection="row" flexWrap="wrap" gap={3}>
724 <Box flexDirection="row">
725 <Box width={LABEL_WIDTH}>
726 <Text bold>Mode</Text>
727 </Box>
728 {modes}
729 </Box>
730 <Box flexDirection="row">
731 <Text bold>{'Scope '}</Text>
732 {scopes}
733 </Box>
734 <Box flexDirection="row">
735 <Text bold>{'Icons '}</Text>
736 {icons}
737 </Box>
738 </Box>
739 )
740
741 // Where the focus ring starts when the band takes the keys: the block the keys
742 // act on, where Enter only selects, rather than the ✕ first in the band. The
743 // first drawn of several wins, so it yields to the confirm box's Continue.
744 const ringStart = confirm === null ? (selected ?? rows(layout).flat()[0]) : undefined
745 const blockRows = rows(layout).map((ids, index) => (
746 <Box flexDirection="row" flexWrap="wrap">
747 <Box width={LABEL_WIDTH}>
748 <Text bold={index < 2} color={index < 2 ? undefined : MUTED}>
749 {ROW_LABELS[index] ?? ''}
750 </Text>
751 </Box>
752 {ids.length === 0 ? <Text color={MUTED}>{index < 2 ? 'empty' : 'every block is on'}</Text> : null}
753 {ids.map(id =>
754 // Inverse, apart from the coral of a chosen Mode or Scope.
755 id === selected ? (
756 <Button key={`sl-block-${id}`} plain autoFocus={id === ringStart || undefined} onPress={() => pick($, id)}>
757 <Text inverse bold>{` ${blockName(id)} `}</Text>
758 </Button>
759 ) : (
760 <Button
761 key={`sl-block-${id}`}
762 plain
763 autoFocus={id === ringStart || undefined}
764 dimColor={index === 2}
765 label={` ${blockName(id)} `}
766 onPress={() => pick($, id)}
767 />
768 ),
769 )}
770 </Box>
771 ))
772
773 const keptBase =
774 layout.mode !== 'extend' || layout.base === null ? null : (
775 <Text color={MUTED} wrap="truncate-end">
776 {layout.base.kind === 'command' ? `Keeps ${layout.base.command}` : `Keeps the status line ${layout.base.path} sets`}
777 </Text>
778 )
779
780 const notices = [
781 setup.isLocked ? "Your organization sets the status line, so it can't be changed here." : null,
782 state.problem,
783 scope === 'global' && setup.inForce !== null && setup.inForce.source !== 'user'
784 ? `This project's ${setup.inForce.source === 'local' ? '.claude/settings.local.json' : '.claude/settings.json'} sets its own status line, so the global one doesn't show here.`
785 : null,
786 ].filter((notice): notice is string => notice !== null)
787
788 const confirmBox =
789 confirm === null ? null : (
790 <Box borderStyle="round" borderColor={GOLD} paddingX={1} flexDirection="column">
791 {confirm === 'install' ? (
792 <Box flexDirection="column">
793 <Text color={GOLD}>{`Set the status line in ${state.file}?`}</Text>
794 <Text color={MUTED} wrap="truncate-end">
795 {`now ${setup.inForce === null ? 'none' : setup.inForce.command}`}
796 </Text>
797 <Text color={MUTED} wrap="truncate-end">
798 {`new ${state.command}`}
799 </Text>
800 </Box>
801 ) : (
802 <Box flexDirection="column">
803 <Text color={GOLD}>
804 {state.isRecorded ? `Put back the status line ${state.file} had before the Dock?` : `Take the Dock's status line out of ${state.file}?`}
805 </Text>
806 {state.restores === null ? null : (
807 <Text color={MUTED} wrap="truncate-end">
808 {`back to ${state.restores}`}
809 </Text>
810 )}
811 </Box>
812 )}
813 <Box flexDirection="row" gap={2}>
814 <Button
815 key="sl-confirm"
816 variant="primary"
817 autoFocus
818 label="Continue"
819 onPress={() => (confirm === 'install' ? install($) : uninstall($))}
820 />
821 <Button key="sl-cancel" label="Cancel" onPress={() => update($, confirmAtom, () => null)} />
822 </Box>
823 </Box>
824 )
825
826 const dropped = preview === null || preview.dropped.length === 0 ? 'nothing drops' : `drops: ${preview.dropped.map(blockName).join(', ')}`
827 const previewTail = preview === null ? '' : `at ${preview.columns} columns · ${dropped}`
828 const previewRows =
829 preview === null ? (
830 <Text color={MUTED}>drawing…</Text>
831 ) : preview.error !== null ? (
832 <Text color={MUTED}>{preview.error}</Text>
833 ) : (
834 <Box flexDirection="column">
835 {(layout.mode === 'extend' ? preview.base : []).map(line => (
836 <Text wrap="truncate-end">{runs(Text, line)}</Text>
837 ))}
838 {preview.lines.length === 0 ? <Text color={MUTED}>Turn a block on to see it here.</Text> : null}
839 {preview.lines.map(line => (
840 <Text wrap="truncate-end">{runs(Text, line)}</Text>
841 ))}
842 {preview.samples.length === 0 ? null : (
843 <Text color={MUTED} wrap="truncate-end">{`◌ sample figures until Claude Code has them: ${preview.samples.map(blockName).join(', ')}`}</Text>
844 )}
845 </Box>
846 )
847
848 const key = (name: string, hotkey: string, label: string, onPress: () => unknown) => (
849 <Button key={name} plain hotkey={hotkey} label={label} onPress={onPress} />
850 )
851 const toolbar = (
852 <Box flexDirection="row" justifyContent="space-between" flexWrap="wrap">
853 <Box flexDirection="row" gap={2}>
854 {key('sl-left', 'h', '←', () => edit($, (now, id) => moveAlong(now, id, -1)))}
855 {key('sl-right', 'l', '→', () => edit($, (now, id) => moveAlong(now, id, 1)))}
856 {key('sl-up', 'k', '↑', () => edit($, (now, id) => moveAcross(now, id, -1)))}
857 {key('sl-down', 'j', '↓', () => edit($, (now, id) => moveAcross(now, id, 1)))}
858 {key('sl-toggle', 'o', 'on/off', () => edit($, (now, id) => toggleBlock(now, id)))}
859 {key('sl-icons', 'i', 'icons', () => edit($, now => nextIcons(now)))}
860 {isBlocked ? null : key('sl-apply', 'a', state.isInstalled ? 'Apply' : 'Install', () => apply($))}
861 {hasChanges ? key('sl-revert', 'r', 'Revert', () => revert($)) : null}
862 {state.isInstalled && !setup.isLocked ? key('sl-uninstall', 'u', 'Uninstall', () => update($, confirmAtom, () => 'uninstall')) : null}
863 </Box>
864 <Text color={MUTED}>{KEYS_HINT}</Text>
865 </Box>
866 )
867
868 return (
869 <Box width={width} flexDirection="column" borderStyle="round" borderColor={HAIRLINE} paddingX={1}>
870 {header(
871 <Text color={hasChanges ? GOLD : MUTED}>{hasChanges ? `${meta} · unapplied changes` : `${meta} · ${layoutSummary(layout)}`}</Text>,
872 )}
873 {settingsRow}
874 {keptBase}
875 {rule('BLOCKS')}
876 {blockRows}
877 {rule('PREVIEW', previewTail)}
878 {previewRows}
879 {notices.map(notice => (
880 <Text color={GOLD}>{notice}</Text>
881 ))}
882 {confirmBox}
883 {toolbar}
884 </Box>
885 )
886}
887hooks/toolbox.tsx 362 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On, RenderInput, RenderNode } from 'claude-code'
3
4import type { BandView, StatusLineSetup } from '../types'
5import { EFFORTS, familyOf, modelLabel, offeredFamilies } from './chat-picks-logic'
6import { checklistView, isAnimated } from './checklist-view'
7import {
8 BIG_TEAM_QUESTION,
9 CORAL,
10 CUSTOM_PLACEHOLDER,
11 CUSTOM_QUESTION,
12 GOLD,
13 GREEN,
14 HAIRLINE,
15 INK,
16 MUTED,
17 SIZES,
18 spaced,
19} from './dock-logic'
20import { layoutSummary } from './status-line-logic'
21import { BAND_GAP, bandLayout } from './toolbox-logic'
22import type { BandLayout } from './toolbox-logic'
23
24type Engine = EngineInterface
25
26// The band shows the popup or the Status Line Dock, never both.
27const bandViewAtom = atom({ plugin: 'mods-toolbox', key: 'bandView' } as const, null)
28// Clean View's and the dock's values, read on the same keys their files write.
29const cleanViewAtom = atom({ plugin: 'mods-toolbox', key: 'cleanViewEnabled' } as const, true)
30const checklistAtom = atom({ plugin: 'mods-toolbox', key: 'checklist' } as const, null)
31const tickAtom = atom({ plugin: 'mods-toolbox', key: 'tick' } as const, 0)
32const sizeAtom = atom({ plugin: 'mods-toolbox', key: 'dockTeamSize' } as const, 1)
33const modelAtom = atom({ plugin: 'mods-toolbox', key: 'dockHelperModel' } as const, 'fast')
34const pendingAtom = atom({ plugin: 'mods-toolbox', key: 'dockPendingSize' } as const, null)
35const customAtom = atom({ plugin: 'mods-toolbox', key: 'dockIsCustomOpen' } as const, false)
36// The model config rows' values (model and effort), written by chat-picks.tsx.
37const chatOptionsAtom = atom({ plugin: 'mods-toolbox', key: 'chatModelOptions' } as const, null)
38const chatModelAtom = atom({ plugin: 'mods-toolbox', key: 'chatModel' } as const, null)
39const chatEffortAtom = atom({ plugin: 'mods-toolbox', key: 'chatEffort' } as const, null)
40const chatModelPendingAtom = atom({ plugin: 'mods-toolbox', key: 'chatModelPending' } as const, null)
41const chatEffortPendingAtom = atom({ plugin: 'mods-toolbox', key: 'chatEffortPending' } as const, null)
42const chatUltracodeAtom = atom({ plugin: 'mods-toolbox', key: 'chatUltracode' } as const, 'off')
43const chatUltracodePendingAtom = atom({ plugin: 'mods-toolbox', key: 'chatUltracodePending' } as const, null)
44// The Status Line Dock's, for its Launch entry.
45const statusLineSetupAtom = atom({ plugin: 'mods-toolbox', key: 'statusLineSetup' } as const, null)
46
47const NAME_WIDTH = 14
48
49type Option = { label: string; node: RenderNode }
50
51// The engine follows `$` only into this file, so the popup draws the controls
52// and Clean View, the dock and the chat picks answer their own keys in their
53// `ui.press` and `ui.input` hooks; by the time a press would reach this closure
54// it is answered.
55const answeredByOwner = () => undefined
56
57const toggleView = (view: BandView | null): BandView | null => (view === 'toolbox' ? null : 'toolbox')
58
59export function registerToolbox(on: On) {
60 // Clean View holds the bare session.start and the dock its cwd matcher.
61 on('session.start', { surface: /^/ }, async ($, e, next) => {
62 try {
63 await $.command.register({
64 name: 'toolbox',
65 description: "Open or close the Toolbox: Claude's model and effort, Clean View, Team Size, helper model, the Agent Dock and the Status Line Dock",
66 immediate: true,
67 })
68 } catch {
69 // The footer button still opens it.
70 }
71
72 return next(e)
73 })
74
75 on('command.run', { command: 'toolbox' }, async $ => {
76 const view = await update($, bandViewAtom, toggleView)
77
78 return { text: view === 'toolbox' ? 'Toolbox open above the prompt.' : 'Toolbox closed.' }
79 })
80
81 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
82 const below = await next(e)
83 const { Box, Button, Text } = $.ui.resolve(e)
84 const isOpen = (await read($, bandViewAtom)) === 'toolbox'
85
86 return (
87 <Box flexDirection="row" gap={1}>
88 {below}
89 <Button key="toolbox-button" plain onPress={() => update($, bandViewAtom, toggleView)}>
90 <Text color={CORAL}>◆</Text>
91 {` Toolbox ${isOpen ? '▴' : '▾'}`}
92 </Button>
93 </Box>
94 )
95 })
96
97 // While the popup is open the band is laid out here: Clean View steps aside
98 // and the checklist is drawn beside the popup, or folded above it. `next` then
99 // brings only other mods' rows and the engine's own, which the engine refuses
100 // under a sized Box, so they go below, never in the row. The popup always sits
101 // at the right edge, with or without a checklist beside it.
102 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
103 if (e.props.hasSurvey || (await read($, bandViewAtom)) !== 'toolbox') {
104 return next(e)
105 }
106 const { Box } = $.ui.resolve(e)
107 const layout = bandLayout(e.props.bodyColumns)
108 const [checklist, popup, below] = await Promise.all([
109 drawChecklist($, e, layout),
110 drawPopup($, e, layout.popupWidth),
111 next(e),
112 ])
113 const pinned = (
114 <Box flexDirection="row" justifyContent="flex-end">
115 {popup}
116 </Box>
117 )
118 const top =
119 checklist === null ? (
120 pinned
121 ) : layout.isSideBySide ? (
122 <Box flexDirection="row" justifyContent="flex-end" alignItems="flex-end" gap={BAND_GAP}>
123 <Box width={layout.checklistColumns}>{checklist}</Box>
124 {popup}
125 </Box>
126 ) : (
127 <Box flexDirection="column">
128 {checklist}
129 {pinned}
130 </Box>
131 )
132
133 return (
134 <Box flexDirection="column">
135 {top}
136 {below}
137 </Box>
138 )
139 })
140}
141
142async function drawChecklist($: Engine, e: RenderInput<'AbovePrompt'>, layout: BandLayout) {
143 const job = (await read($, cleanViewAtom)) ? await read($, checklistAtom) : null
144 if (job === null) {
145 return null
146 }
147 const { Box, Text } = $.ui.resolve(e)
148 const frame = isAnimated(job.phase) ? await read($, tickAtom) : 0
149
150 return checklistView(Box, Text, job, {
151 columns: layout.checklistColumns,
152 isFolded: !layout.isSideBySide,
153 now: await $.clock.now(),
154 frame,
155 })
156}
157
158async function drawPopup($: Engine, e: RenderInput<'AbovePrompt'>, width: number) {
159 const { Box, Text, Button } = $.ui.resolve(e)
160 const inner = Math.max(1, width - 4)
161 const [
162 isCleanView,
163 size,
164 model,
165 pending,
166 isCustomOpen,
167 chatOptions,
168 chatModel,
169 effort,
170 modelPending,
171 effortPending,
172 ultracode,
173 ultracodePending,
174 statusLineSetup,
175 ] = await Promise.all([
176 read($, cleanViewAtom),
177 read($, sizeAtom),
178 read($, modelAtom),
179 read($, pendingAtom),
180 read($, customAtom),
181 read($, chatOptionsAtom),
182 read($, chatModelAtom),
183 read($, chatEffortAtom),
184 read($, chatModelPendingAtom),
185 read($, chatEffortPendingAtom),
186 read($, chatUltracodeAtom),
187 read($, chatUltracodePendingAtom),
188 read($, statusLineSetupAtom),
189 ])
190 // chat-picks.tsx keeps the model read back; asking the engine covers a start it missed.
191 const modelId = chatModel ?? (await $.session.model().catch(() => ''))
192
193 const chip = (label: string, background: string, color?: string): Option => ({
194 label,
195 node: (
196 <Text backgroundColor={background} color={color} bold>
197 {label}
198 </Text>
199 ),
200 })
201 const pick = (key: string, label: string): Option => ({
202 label,
203 node: <Button key={key} plain label={label} onPress={answeredByOwner} />,
204 })
205
206 const rule = (title: string) => {
207 const label = spaced(title)
208
209 return (
210 <Text>
211 <Text color={HAIRLINE}>{'── '}</Text>
212 <Text color={MUTED}>{label}</Text>
213 <Text color={HAIRLINE}>{` ${'─'.repeat(Math.max(0, inner - label.length - 4))}`}</Text>
214 </Text>
215 )
216 }
217
218 // The hint shows only where it fits whole; the options keep their room.
219 const row = (mark: RenderNode, name: string, hint: string, options: Option[]) => {
220 const optionsWidth = options.reduce((sum, option) => sum + option.label.length, 0)
221 const hasHint = inner - 2 - NAME_WIDTH - optionsWidth - 1 >= hint.length
222
223 return (
224 <Box flexDirection="row" justifyContent="space-between">
225 <Box flexDirection="row">
226 <Box width={2}>{mark}</Box>
227 <Box width={NAME_WIDTH}>
228 <Text bold>{name}</Text>
229 </Box>
230 {hasHint ? <Text color={MUTED}>{hint}</Text> : null}
231 </Box>
232 <Box flexDirection="row" flexWrap="wrap">
233 {options.map(option => option.node)}
234 </Box>
235 </Box>
236 )
237 }
238
239 // On and Off: the filled dot follows the chosen side, as on a radio button,
240 // and a side waiting for its command to run shows in gold.
241 const onOff = (keyPrefix: string, isOn: boolean, pendingSide: 'on' | 'off' | null = null): Option[] => {
242 const side = (value: 'on' | 'off', label: string, background: string): Option =>
243 pendingSide === value
244 ? chip(` ● ${label} `, GOLD, INK)
245 : pendingSide === null && isOn === (value === 'on')
246 ? chip(` ● ${label} `, background, value === 'on' ? INK : undefined)
247 : pick(`${keyPrefix}-${value}`, ` ○ ${label} `)
248
249 return [side('on', 'On', GREEN), side('off', 'Off', HAIRLINE)]
250 }
251 const cleanView = onOff('cv', isCleanView)
252 const isPreset = (SIZES as readonly number[]).includes(size)
253 const sizes = [
254 ...SIZES.map(option => (option === size ? chip(` ${option} `, CORAL, INK) : pick(`size-${option}`, ` ${option} `))),
255 ...(isPreset ? [] : [chip(` ${size} `, CORAL, INK)]),
256 pick('size-custom', ' Custom '),
257 ]
258 const helpers = [
259 model === 'fast' ? chip(' Fast & Cheap ', CORAL, INK) : pick('model-fast', ' Fast & Cheap '),
260 model === 'same' ? chip(' Same as me ', CORAL, INK) : pick('model-same', ' Same as me '),
261 ]
262
263 // A pick waiting for /model or /effort shows in gold until it has run.
264 const choice = (key: string, label: string, isChosen: boolean, isPending: boolean): Option =>
265 isPending ? chip(label, GOLD, INK) : isChosen ? chip(label, CORAL, INK) : pick(key, label)
266 const titled = (word: string) => ` ${word.charAt(0).toUpperCase()}${word.slice(1)} `
267 const shownFamily = modelPending ?? familyOf(modelId)
268 const models = offeredFamilies(chatOptions ?? undefined).map(family =>
269 choice(`chat-model-${family}`, titled(family), family === shownFamily, family === modelPending),
270 )
271 const efforts = EFFORTS.map(level =>
272 choice(`chat-effort-${level}`, titled(level === 'xhigh' ? 'XHigh' : level), level === (effortPending ?? effort), level === effortPending),
273 )
274 const isUltracodeOn = ultracode === 'on'
275 const ultracodes = onOff('chat-ultracode', isUltracodeOn, ultracodePending)
276 const isWaiting = e.props.isWorking && (modelPending !== null || effortPending !== null || ultracodePending !== null)
277 const meta = [modelId === '' ? null : modelLabel(modelId), effort, isUltracodeOn ? 'ultracode' : null]
278 .filter(Boolean)
279 .join(' · ')
280
281 // The engine raises AbovePrompt on the terminal and desktop alone, so the
282 // popup never shows on mobile or VS Code; the surface check only narrows the
283 // element table to one that has Input.
284 let customBox: RenderNode | null = null
285 if (isCustomOpen && e.surface !== 'mobile' && e.surface !== 'vscode') {
286 const { Input } = $.ui.resolve(e)
287 customBox = (
288 <Box borderStyle="round" borderColor={CORAL} paddingX={1} flexDirection="row" gap={2}>
289 <Input
290 key="custom-size"
291 label={CUSTOM_QUESTION}
292 placeholder={CUSTOM_PLACEHOLDER}
293 submitLabel="set"
294 autoFocus
295 onSubmit={answeredByOwner}
296 />
297 <Button key="custom-cancel" plain label="Cancel" onPress={answeredByOwner} />
298 </Box>
299 )
300 }
301
302 const confirmBox =
303 pending === null ? null : (
304 <Box borderStyle="round" borderColor={GOLD} paddingX={1} flexDirection="column">
305 <Text color={GOLD}>{BIG_TEAM_QUESTION}</Text>
306 <Box flexDirection="row" gap={2}>
307 <Button key="big-continue" variant="primary" autoFocus label={`Continue with ${pending}`} onPress={answeredByOwner} />
308 <Button key="big-cancel" label="Cancel" onPress={answeredByOwner} />
309 </Box>
310 </Box>
311 )
312
313 return (
314 <Box width={width} flexDirection="column" borderStyle="round" borderColor={HAIRLINE} paddingX={1}>
315 <Box flexDirection="row" justifyContent="space-between">
316 <Text color={CORAL} bold>
317 {`◆ ${spaced('TOOLBOX')}`}
318 </Text>
319 <Box flexDirection="row" gap={2}>
320 {meta === '' ? null : <Text color={MUTED}>{meta}</Text>}
321 <Button key="toolbox-close" plain role="dismiss" label="✕" onPress={() => update($, bandViewAtom, () => null)} />
322 </Box>
323 </Box>
324 {rule('MODEL CONFIG')}
325 {models.length === 0 ? null : row(<Text color={MUTED}>◇</Text>, 'Model', 'saved as default', models)}
326 {row(<Text color={MUTED}>◇</Text>, 'Effort', 'thinking depth', efforts)}
327 {ultracode === 'unavailable'
328 ? null
329 : row(<Text color={isUltracodeOn ? GREEN : MUTED}>{isUltracodeOn ? '●' : '○'}</Text>, 'Ultracode', 'workflows on every task', ultracodes)}
330 {isWaiting ? <Text color={GOLD}>{'◷ switches when Claude is done working'}</Text> : null}
331 {rule('SETTINGS')}
332 {row(<Text color={isCleanView ? GREEN : MUTED}>{isCleanView ? '●' : '○'}</Text>, 'Clean View', 'simple checklist', cleanView)}
333 {row(<Text color={MUTED}>◇</Text>, 'Team size', 'per request', sizes)}
334 {customBox}
335 {confirmBox}
336 {row(<Text color={MUTED}>◇</Text>, 'Helpers', 'model they use', helpers)}
337 {rule('LAUNCH')}
338 <Box flexDirection="column">
339 {/* The dock opens itself, then lets the press through to close the popup. */}
340 <Button key="toolbox-dock" plain onPress={() => update($, bandViewAtom, () => null)}>
341 <Text color={CORAL}>◆</Text>
342 {' Agent Dock '}
343 <Text color={MUTED}>{`team of ${size}`}</Text>
344 </Button>
345 {/* The Status Line Dock takes the band over from the popup. */}
346 <Button key="toolbox-status-line" plain onPress={answeredByOwner}>
347 <Text color={CORAL}>◆</Text>
348 {' Status Line Dock '}
349 <Text color={MUTED}>{statusLineNote(statusLineSetup)}</Text>
350 </Button>
351 </Box>
352 </Box>
353 )
354}
355
356// The Layout in force here, or that there is none yet.
357function statusLineNote(setup: StatusLineSetup | null): string {
358 const installed = setup === null ? null : setup.project.isInstalled ? setup.project : setup.global.isInstalled ? setup.global : null
359
360 return installed === null || installed.layout === null ? 'not set up' : layoutSummary(installed.layout)
361}
362hooks/chat-picks-logic.ts 112 lines1import type { ChatEffort } from '../types'
2
3// What the Toolbox's model config rows need with no `$`: which model families
4// to offer, how to name the one running, and what /model and /effort take.
5
6export const FAMILIES = ['haiku', 'sonnet', 'opus', 'fable'] as const
7export type Family = (typeof FAMILIES)[number]
8
9export const EFFORTS: readonly ChatEffort[] = ['low', 'medium', 'high', 'xhigh', 'max']
10type Effort = ChatEffort
11
12const LONG_CONTEXT = '[1m]'
13
14/** A level /effort takes and a turn reports; `auto` and `ultracode` are not levels. */
15export function isEffort(value: unknown): value is Effort {
16 return typeof value === 'string' && (EFFORTS as readonly string[]).includes(value)
17}
18
19/** The families the `/config` model row offers, in the Toolbox's order; none when there is no row. */
20export function offeredFamilies(options: readonly string[] | undefined): Family[] {
21 if (options === undefined) {
22 return []
23 }
24
25 return FAMILIES.filter(family => options.includes(family))
26}
27
28/** "claude-opus-5-5[1m]" → opus; null for a model outside the four families. */
29export function familyOf(modelId: string): Family | null {
30 const match = /^claude-([a-z]+)-/.exec(modelId)
31 const family = match?.[1]
32
33 return FAMILIES.find(known => known === family) ?? null
34}
35
36/** "claude-opus-5-5[1m]" → "Opus 5.5 · 1M"; the id itself when it reads otherwise. */
37export function modelLabel(modelId: string): string {
38 const match = /^claude-([a-z]+)-(\d+)(?:-(\d+))?/.exec(modelId)
39 if (match === null) {
40 return modelId
41 }
42 const [, family = '', major, minor] = match
43 const name = `${family.charAt(0).toUpperCase()}${family.slice(1)} ${minor === undefined ? major : `${major}.${minor}`}`
44
45 return modelId.endsWith(LONG_CONTEXT) ? `${name} · 1M` : name
46}
47
48/** What /model takes for a family: the 1M-context alias when the chat runs on one and the row offers it. */
49export function modelArgs(family: Family, currentModelId: string, options: readonly string[]): string {
50 const longAlias = `${family}${LONG_CONTEXT}`
51
52 return currentModelId.endsWith(LONG_CONTEXT) && options.includes(longAlias) ? longAlias : family
53}
54
55const TOAST_MAX = 80
56
57/** A command's refusal as a toast: its first line with words, clipped; the fallback when it said nothing. */
58export function refusal(text: string | undefined, fallback: string): string {
59 const line = (text ?? '').split('\n').map(part => part.trim()).find(part => part !== '') ?? ''
60 if (line === '') {
61 return fallback
62 }
63
64 return line.length > TOAST_MAX ? `${line.slice(0, TOAST_MAX - 1)}…` : line
65}
66
67/**
68 * Whether /effort took the level, judged by what its run answered. An
69 * interactive run hands back no text, its line goes to the chat, so only
70 * words that are not the confirmation count as a refusal.
71 */
72export function effortTaken(text: string | undefined): boolean {
73 return text === undefined || text.trim() === '' || /effort level to/i.test(text)
74}
75
76/**
77 * `/effort ultracode [on|off]` as asked: true for on (bare turns it on), false
78 * for off, null for any other /effort. Claude Code refuses anything else, such
79 * as `ultracode onn`, as an invalid argument, which says nothing about the plan.
80 */
81export function ultracodeAsked(args: string): boolean | null {
82 const [first, second, ...rest] = args.trim().toLowerCase().split(/\s+/)
83 if (first !== 'ultracode' || rest.length > 0) {
84 return null
85 }
86 if (second === undefined || second === 'on') {
87 return true
88 }
89
90 return second === 'off' ? false : null
91}
92
93/** Whether `/effort ultracode` took, judged as effortTaken is. */
94export function ultracodeTaken(text: string | undefined): boolean {
95 return text === undefined || text.trim() === '' || /ultracode (on|off)/i.test(text)
96}
97
98/** The effort settings.json gives this model before any turn says otherwise. */
99export function effortFromSettings(settings: Readonly<Record<string, unknown>>, modelId: string): Effort | null {
100 const base = modelId.replace(LONG_CONTEXT, '')
101 const perModel = settings.modelSettings
102 const own =
103 typeof perModel === 'object' && perModel !== null
104 ? (perModel as Record<string, { effortLevel?: unknown } | undefined>)[base]?.effortLevel
105 : undefined
106 if (isEffort(own)) {
107 return own
108 }
109
110 return isEffort(settings.effortLevel) ? settings.effortLevel : null
111}
112hooks/checklist-view.tsx 159 lines1import type { EngineInterface, RenderNode } from 'claude-code'
2
3import type { CleanViewChecklist, CleanViewPhase, CleanViewTask } from '../types'
4import { MAX_NAME_LENGTH } from './clean-name'
5import { formatDuration } from './progress'
6
7// The checklist as drawn, with no `$`: Clean View draws it in the band, and the
8// Toolbox draws it beside its popup while that is open.
9
10type Elements = ReturnType<EngineInterface['ui']['resolve']>
11type TextElement = Elements['Text']
12
13const METER_CELLS = 10
14
15export const WAITING_FOR_REPLY = 'Claude is waiting for your reply'
16export const API_TROUBLE = 'something went wrong talking to Claude, try again'
17
18export type ChecklistFrame = {
19 columns: number
20 // Above the Toolbox popup only the header shows, with the step it is on.
21 isFolded: boolean
22 now: number
23 frame: number
24}
25
26export function isAnimated(phase: CleanViewPhase): boolean {
27 return phase === 'working' || phase === 'needsYou'
28}
29
30export function checklistView(
31 Box: Elements['Box'],
32 Text: TextElement,
33 job: CleanViewChecklist,
34 { columns, isFolded, now, frame }: ChecklistFrame,
35) {
36 const header = (
37 <Box width={Math.max(1, columns)}>
38 <Text wrap="truncate-end">
39 {headline(Text, job, now)}
40 {isFolded ? stepOf(job) : null}
41 </Text>
42 </Box>
43 )
44 if (job.isCollapsed || isFolded) {
45 return header
46 }
47
48 // mark (2) + name + gap (1) + meter (10) + gap (2) + label (7)
49 const nameWidth = Math.min(MAX_NAME_LENGTH + 1, Math.max(6, columns - 22))
50 const firstUpcoming = job.tasks.findIndex(task => task.status === 'upcoming')
51
52 return (
53 <Box flexDirection="column">
54 {header}
55 {job.tasks.map((task, index) => (
56 <Box key={`row-${task.id}`} flexDirection="row">
57 <Box width={2}>{mark(Text, task, job.phase)}</Box>
58 <Box width={nameWidth}>
59 <Text wrap="truncate-end" bold={task.status === 'active'} dimColor={task.status !== 'active'}>
60 {task.name}
61 </Text>
62 </Box>
63 <Text> </Text>
64 {meter(Text, task, job.phase, frame)}
65 <Text> </Text>
66 <Text dimColor={task.status !== 'active'}>{statusLabel(task, index === firstUpcoming)}</Text>
67 </Box>
68 ))}
69 </Box>
70 )
71}
72
73function headline(Text: TextElement, job: CleanViewChecklist, now: number): RenderNode[] {
74 switch (job.phase) {
75 case 'working':
76 return [<Text bold>{job.title}</Text>, ` · ${formatDuration(now - job.startedAt)}`, waitingFor(job.waitingOnHelpers)]
77 case 'needsYou':
78 return [
79 <Text backgroundColor="warning" color="inverseText" bold>
80 {' Needs you '}
81 </Text>,
82 ` ${job.needsYouReason ?? WAITING_FOR_REPLY}`,
83 ]
84 case 'stuck':
85 return [<Text color="warning">⚠ Stuck:</Text>, ` ${job.stuckReason ?? API_TROUBLE}`]
86 case 'stopped':
87 return [<Text color="warning">■ Stopped</Text>, ` · ${job.title} · you pressed Esc`]
88 case 'done':
89 return [
90 <Text color="success">✓ All done</Text>,
91 ` · ${job.title} · took ${formatDuration((job.finishedAt ?? now) - job.startedAt)}`,
92 ]
93 }
94}
95
96// Claude's turn ended but its background helpers are still out; it goes on
97// when they report.
98function waitingFor(helpers: number | undefined): string {
99 if (helpers === undefined || helpers <= 0) {
100 return ''
101 }
102
103 return ` · waiting for ${helpers === 1 ? '1 helper' : `${helpers} helpers`} to finish`
104}
105
106function mark(Text: TextElement, task: CleanViewTask, phase: CleanViewPhase) {
107 if (task.status === 'done') {
108 return <Text color="success">✓</Text>
109 }
110 if (task.status === 'upcoming') {
111 return <Text dimColor>○</Text>
112 }
113
114 return <Text bold>{phase === 'needsYou' ? '‖' : '▶'}</Text>
115}
116
117function meter(Text: TextElement, task: CleanViewTask, phase: CleanViewPhase, frame: number) {
118 if (task.status === 'done') {
119 return <Text color="success">{'█'.repeat(METER_CELLS)}</Text>
120 }
121 if (task.status === 'upcoming') {
122 return <Text dimColor>{'░'.repeat(METER_CELLS)}</Text>
123 }
124 if (task.hasReported || !isAnimated(phase)) {
125 const filled = Math.round(task.percent / 10)
126
127 return <Text>{'█'.repeat(filled) + '░'.repeat(METER_CELLS - filled)}</Text>
128 }
129 // No percent yet: a three-cell block sweeps across the meter.
130 const start = (frame % (METER_CELLS + 3)) - 3
131 let cells = ''
132 for (let cell = 0; cell < METER_CELLS; cell++) {
133 cells += cell >= start && cell < start + 3 ? '█' : '░'
134 }
135
136 return <Text>{cells}</Text>
137}
138
139// " · step 2 of 3", while a real plan is under way.
140function stepOf(job: CleanViewChecklist): string | null {
141 const active = job.tasks.findIndex(task => task.status === 'active')
142 if (job.planSource === null || job.phase === 'done' || active < 0) {
143 return null
144 }
145
146 return ` · step ${active + 1} of ${job.tasks.length}`
147}
148
149function statusLabel(task: CleanViewTask, isNext: boolean): string {
150 if (task.status === 'done') {
151 return 'Done'
152 }
153 if (task.status === 'active') {
154 return task.hasReported ? `${task.percent}%` : 'Working'
155 }
156
157 return isNext ? 'Next' : 'Up next'
158}
159hooks/clean-name.ts 48 lines1export const MAX_NAME_LENGTH = 40
2
3const FALLBACK_NAME = 'Working on it'
4
5const CODE_EXTENSIONS = [
6 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'mts', 'cts', 'py', 'rb', 'go', 'rs',
7 'java', 'kt', 'swift', 'c', 'cc', 'cpp', 'h', 'hpp', 'cs', 'php', 'sh', 'bash',
8 'zsh', 'ps1', 'sql', 'json', 'yaml', 'yml', 'toml', 'ini', 'xml', 'html', 'htm',
9 'css', 'scss', 'sass', 'less', 'vue', 'svelte', 'md', 'mdx', 'lock', 'env',
10 'sol', 'lua', 'dart', 'scala', 'ex', 'exs', 'hs', 'tf', 'gradle', 'ipynb',
11]
12
13const BACKTICK_CODE = /`[^`]*`/g
14const WITH_SLASH = /\S*[/\\]\S*/g
15const FILE_NAME = new RegExp(`[\\w.-]*\\.(?:${CODE_EXTENSIONS.join('|')})(?![\\w.])`, 'gi')
16const EMPTY_BRACKETS = /\(\s*\)|\[\s*\]|\{\s*\}/g
17const EDGE_PUNCTUATION = /^[\s,;:–—-]+|[\s,;:–—-]+$/g
18
19// One cleaner for every name the checklist shows: no code, paths or file
20// names, at most 40 characters, never empty.
21export function cleanName(raw: string): string {
22 const name = raw
23 .replace(BACKTICK_CODE, ' ')
24 .replace(/`/g, ' ')
25 .replace(WITH_SLASH, ' ')
26 .replace(FILE_NAME, ' ')
27 .replace(EMPTY_BRACKETS, ' ')
28 .replace(/\s+/g, ' ')
29 .replace(/\s+([,.;:!?])/g, '$1')
30 .replace(EDGE_PUNCTUATION, '')
31
32 if (name === '') {
33 return FALLBACK_NAME
34 }
35
36 const capitalised = name[0]!.toUpperCase() + name.slice(1)
37
38 return capitalised.length <= MAX_NAME_LENGTH ? capitalised : shorten(capitalised)
39}
40
41function shorten(name: string): string {
42 const room = name.slice(0, MAX_NAME_LENGTH - 1)
43 const lastSpace = room.lastIndexOf(' ')
44 const cut = lastSpace > 0 ? room.slice(0, lastSpace) : room
45
46 return cut.replace(EDGE_PUNCTUATION, '') + '…'
47}
48hooks/dock-logic.ts 503 lines1import type { DockCard, DockCardStatus, DockHelperModel, DockMission } from '../types'
2import { cleanName } from './clean-name'
3import { formatDuration } from './progress'
4
5export const SIZES = [1, 3, 5, 10, 20, 50, 100] as const
6export const MAX_SIZE = 100
7export const BIG_TEAM = 20
8export const MAX_SEATS = 25
9export const TILES_AFTER = 12
10
11// What Claude Code runs at once when nothing in settings says otherwise.
12export const DEFAULT_SUBAGENT_LIMIT = 20
13export const DEFAULT_TOOL_LIMIT = 10
14
15export const SIZE_HELP = 'Team Size is a whole number from 1 to 100, e.g. /dock 10.'
16export const BAD_CUSTOM = 'Type a whole number from 1 to 100'
17export const STOPPED = 'Stopped before this helper started.'
18export const HELPERS_SKIP_PLAN = 'Helpers skip the plan. Just call report_progress as you work.'
19export const TOO_NARROW = 'The window is too narrow to show the Agent Dock. Widen it or watch the status bar.'
20// The dock's pane and the Toolbox popup ask the same way.
21export const BIG_TEAM_QUESTION = 'Big team: this uses your plan quickly. Continue?'
22export const CUSTOM_QUESTION = 'How many helpers? '
23export const CUSTOM_PLACEHOLDER = '1 to 100'
24
25export const CORAL = '#FF7A66'
26export const GOLD = '#F2C14E'
27export const GREEN = '#4ADE80'
28export const GREEN_LIGHT = '#BBF7D0'
29export const RED = '#F87171'
30export const MUTED = '#8B90A0'
31export const HAIRLINE = '#3A3F4B'
32export const INK = '#16181D'
33
34// Muted, not a rainbow: each helper's badge cycles through these.
35export const BADGE_COLORS = ['#E07A5F', '#F2CC8F', '#81B29A', '#7FA7C9', '#B5A1D6', '#E5989B', '#9CC5A1', '#D4A373']
36
37export function parseSize(text: string): number | null {
38 const trimmed = text.trim()
39 if (!/^\d+$/.test(trimmed)) {
40 return null
41 }
42 const size = Number(trimmed)
43
44 return size >= 1 && size <= MAX_SIZE ? size : null
45}
46
47/** A big team never carries over: a new session starts it at 1. */
48export function restoreSize(saved: unknown): number {
49 return typeof saved === 'number' && Number.isInteger(saved) && saved >= 1 && saved <= BIG_TEAM ? saved : 1
50}
51
52export function isBigTeam(size: number): boolean {
53 return size > BIG_TEAM
54}
55
56export function restoreHelperModel(saved: unknown): DockHelperModel {
57 return saved === 'same' ? 'same' : 'fast'
58}
59
60export function parseLimit(raw: string | undefined, fallback: number): number {
61 const limit = Number(raw)
62
63 return Number.isInteger(limit) && limit > 0 ? limit : fallback
64}
65
66/** Helpers running at once: Claude Code refuses an Agent call past either limit. */
67export function atATime(subagentLimit: string | undefined, toolLimit: string | undefined): number {
68 return Math.min(parseLimit(subagentLimit, DEFAULT_SUBAGENT_LIMIT), parseLimit(toolLimit, DEFAULT_TOOL_LIMIT))
69}
70
71export function jobName(request: string): string {
72 const firstLine = request.trim().split('\n')[0] ?? ''
73 const clause = firstLine.split(/[.;!?](?:\s|$)|,\s|\s[–—-]\s/)[0] ?? firstLine
74
75 return cleanName(clause)
76}
77
78export function taskName(description: string): string {
79 return cleanName(description)
80}
81
82/** "Price check: Panera" → PA, "Read the docs" → RT. */
83export function initials(task: string): string {
84 const subject = task.includes(':') ? task.slice(task.indexOf(':') + 1) : task
85 const words = subject.match(/[\p{L}\p{N}]+/gu) ?? task.match(/[\p{L}\p{N}]+/gu) ?? []
86 const [first, second] = words
87 if (first === undefined) {
88 return '··'
89 }
90 if (second === undefined) {
91 return first.slice(0, 2).toUpperCase().padEnd(2, '·')
92 }
93
94 return (first[0]! + second[0]!).toUpperCase()
95}
96
97export function helperNote(progressTool: string, planTool: string): string {
98 return (
99 `As you work, call ${progressTool} with your task name and a percent at about 25, 50, 75 and 100. ` +
100 `Do not call ${planTool}.`
101 )
102}
103
104export function teamInstruction(size: number, progressTool: string, planTool: string): string {
105 return [
106 `Agent Dock: Team Size is ${size}.`,
107 `- Split this request into exactly ${size} independent pieces and launch one helper (the Agent tool) per piece, all ${size} in one message so they run in parallel.`,
108 '- Find a real split, one helper per item (per store, per task, per file, per section). Never argue that it can\'t be split and never pad with useless work.',
109 '- Give each helper a short plain-English description of 3 to 5 words, e.g. "Price check: Panera".',
110 `- In each helper's prompt add: "${helperNote(progressTool, planTool)}"`,
111 '- When they finish, combine their results into one answer.',
112 ].join('\n')
113}
114
115export function nudgeText(used: number, size: number): string {
116 return (
117 `You used ${used} of ${size} helpers. Split the remaining work across the other ${size - used}, ` +
118 'one helper per piece, all in parallel.'
119 )
120}
121
122export function capMessage(size: number): string {
123 return `Team Size is ${size}: this request already has ${size} helpers. Finish with the helpers you have.`
124}
125
126export function confirmMessage(size: number): string {
127 return `Confirm the team of ${size} in the Agent Dock.`
128}
129
130export function infoLine(size: number, atOnce: number, model: DockHelperModel): string {
131 const split = size === 1 ? 'Claude decides how many helpers' : `Splits each request across ${size} helpers`
132 const running = `${size === 1 ? atOnce : Math.min(size, atOnce)} at a time`
133 const helpers = size > 1 && model === 'fast' ? 'Fast & Cheap' : 'Same model as you'
134
135 return [split, running, helpers].join(' · ')
136}
137
138export type DockCounts = { working: number; queued: number; done: number; stuck: number; total: number }
139
140export function counts(cards: readonly DockCard[]): DockCounts {
141 const tally: DockCounts = { working: 0, queued: 0, done: 0, stuck: 0, total: cards.length }
142 for (const card of cards) {
143 tally[card.status] += 1
144 }
145
146 return tally
147}
148
149export function isFinished(status: DockCardStatus): boolean {
150 return status === 'done' || status === 'stuck'
151}
152
153/** A stuck helper is over too, so it counts as a full share of the bar. */
154export function missionPercent(cards: readonly DockCard[]): number {
155 if (cards.length === 0) {
156 return 0
157 }
158 const sum = cards.reduce((total, card) => total + (isFinished(card.status) ? 100 : card.percent), 0)
159
160 return Math.round(sum / cards.length)
161}
162
163export function isLive(mission: DockMission | null): mission is DockMission {
164 return mission !== null && mission.finishedAt === null
165}
166
167/**
168 * Only while a helper works or waits, as for the count file: an idle team needs
169 * no line under the prompt, and the engine draws every mod status line with a
170 * warning glyph.
171 */
172export function badgeText(mission: DockMission | null): string | undefined {
173 const tally = counts(mission?.cards ?? [])
174 if (tally.working + tally.queued === 0) {
175 return undefined
176 }
177 const parts = [`${tally.working} working`, `${tally.queued} queued`, `${tally.done} done`]
178 if (tally.stuck > 0) {
179 parts.push(`${tally.stuck} stuck`)
180 }
181
182 return parts.join(' · ')
183}
184
185export type CountFile = { working: number; queued: number; done: number; stuck: number; job: string; updatedAt: number }
186
187/** What the status line reads for this session; null while no helper runs. */
188export function countFile(mission: DockMission | null, now: number): CountFile | null {
189 if (mission === null) {
190 return null
191 }
192 const tally = counts(mission.cards)
193 if (tally.working + tally.queued === 0) {
194 return null
195 }
196
197 return { working: tally.working, queued: tally.queued, done: tally.done, stuck: tally.stuck, job: mission.job, updatedAt: now }
198}
199
200/** The global folder the status line reads, beside Claude Code's own settings. */
201export function countDir(configDir: string | undefined, home: string | undefined): string | null {
202 const base = configDir !== undefined && configDir !== '' ? configDir : home !== undefined && home !== '' ? `${home}/.claude` : null
203
204 return base === null ? null : `${base.replace(/\/+$/, '')}/agent-dock/agents-now`
205}
206
207export function countPath(dir: string, sessionId: string): string {
208 return `${dir}/${sessionId.replace(/[^A-Za-z0-9._-]/g, '_')}.json`
209}
210
211/** 72_000 → "1:12" */
212export function formatClock(ms: number): string {
213 const seconds = Math.max(0, Math.floor(ms / 1000))
214 const minutes = Math.floor(seconds / 60)
215
216 return `${minutes}:${String(seconds % 60).padStart(2, '0')}`
217}
218
219export function summary(mission: DockMission): string {
220 const total = mission.cards.length
221 const stuck = counts(mission.cards).stuck
222 const took = formatDuration((mission.finishedAt ?? mission.startedAt) - mission.startedAt)
223 const line = `${total} ${total === 1 ? 'agent' : 'agents'} finished ${mission.job} in ${took}`
224
225 return stuck > 0 ? `${line} (${stuck} got stuck)` : line
226}
227
228export function cardTime(card: DockCard, now: number): string {
229 if (card.startedAt === null) {
230 return '0:00'
231 }
232
233 return formatClock((card.finishedAt ?? now) - card.startedAt)
234}
235
236export function newMission(id: string, job: string, size: number, now: number): DockMission {
237 return { id, job, size, cards: [], hasNudged: false, startedAt: now, finishedAt: null }
238}
239
240export function newCard(id: string, description: string, index: number): DockCard {
241 const task = taskName(description)
242
243 return {
244 id,
245 task,
246 initials: initials(task),
247 colorIndex: index % BADGE_COLORS.length,
248 status: 'queued',
249 percent: 0,
250 hasReported: false,
251 agentId: null,
252 isBackground: null,
253 startedAt: null,
254 finishedAt: null,
255 }
256}
257
258/** At a team size above 1 no card is drawn past the size: those calls are refused. */
259export function withQueued(
260 mission: DockMission,
261 calls: ReadonlyArray<{ id: string; description: string }>,
262 cap: number | null,
263): DockMission {
264 const cards = [...mission.cards]
265 for (const call of calls) {
266 if (cards.some(card => card.id === call.id) || (cap !== null && cards.length >= cap)) {
267 continue
268 }
269 cards.push(newCard(call.id, call.description, cards.length))
270 }
271
272 return { ...mission, cards }
273}
274
275export function withCard(mission: DockMission, id: string, change: (card: DockCard) => DockCard): DockMission {
276 return { ...mission, cards: mission.cards.map(card => (card.id === id ? change(card) : card)) }
277}
278
279export function withAgent(mission: DockMission, agentId: string, change: (card: DockCard) => DockCard): DockMission {
280 return { ...mission, cards: mission.cards.map(card => (card.agentId === agentId ? change(card) : card)) }
281}
282
283/** Helpers the engine reports finished whose own turn.complete never reached the dock. */
284export function reconciled(mission: DockMission, statuses: ReadonlyMap<string, string>, now: number): DockMission {
285 const cards = mission.cards.map(card => {
286 const status = card.status === 'working' && card.agentId !== null ? statuses.get(card.agentId) : undefined
287 if (status === 'completed') {
288 return ended(card, 'done', now)
289 }
290
291 return status === 'failed' || status === 'killed' ? ended(card, 'stuck', now) : card
292 })
293
294 return { ...mission, cards }
295}
296
297// The agent statuses that hold one of Claude Code's subagent slots.
298export const ACTIVE_STATUSES = new Set(['running', 'pending', 'waiting'])
299
300export function hasActiveHelper(mission: DockMission, statuses: ReadonlyMap<string, string>): boolean {
301 return mission.cards.some(card => !isFinished(card.status) && card.agentId !== null && ACTIVE_STATUSES.has(statuses.get(card.agentId) ?? ''))
302}
303
304/**
305 * Closes a mission the engine has no helper running for, so a missed finish
306 * never leaves the next request unsplit. A helper that started and is gone
307 * counts as done; one that never started counts as stuck.
308 */
309export function closedOut(mission: DockMission, statuses: ReadonlyMap<string, string>, now: number): DockMission | null {
310 const settled = reconciled(mission, statuses, now)
311 const cards = settled.cards.map(card =>
312 isFinished(card.status) ? card : ended(card, card.status === 'working' && card.agentId !== null ? 'done' : 'stuck', now),
313 )
314
315 return cards.length === 0 ? null : { ...settled, cards, finishedAt: now }
316}
317
318export function withoutCard(mission: DockMission, id: string): DockMission {
319 return { ...mission, cards: mission.cards.filter(card => card.id !== id) }
320}
321
322export function started(card: DockCard, now: number): DockCard {
323 return card.status === 'queued' ? { ...card, status: 'working', startedAt: now } : card
324}
325
326export function ended(card: DockCard, status: 'done' | 'stuck', now: number): DockCard {
327 if (isFinished(card.status)) {
328 return card
329 }
330
331 return { ...card, status, percent: status === 'done' ? 100 : card.percent, startedAt: card.startedAt ?? now, finishedAt: now }
332}
333
334export function reported(card: DockCard, percent: number): DockCard {
335 return isFinished(card.status) ? card : { ...card, percent, hasReported: true }
336}
337
338/**
339 * The main turn ended: a mission whose helpers have all finished is complete,
340 * and one that never launched a helper goes back to standing by.
341 */
342export function afterMainTurn(mission: DockMission, isAborted: boolean, now: number): DockMission | null {
343 const cards = isAborted ? mission.cards.map(card => (card.status === 'queued' ? ended(card, 'stuck', now) : card)) : mission.cards
344 if (cards.length === 0) {
345 return null
346 }
347
348 return cards.every(card => isFinished(card.status)) ? { ...mission, cards, finishedAt: now } : { ...mission, cards }
349}
350
351export function spaced(text: string): string {
352 return text
353 .split(' ')
354 .map(word => [...word].join(' '))
355 .join(' ')
356}
357
358/** A color run along a gradient: `cells` cells split into up to `steps` runs. */
359export function gradientRuns(cells: number, from: string, to: string, steps = 8): Array<{ cells: number; color: string }> {
360 if (cells <= 0) {
361 return []
362 }
363 const runs = Math.min(steps, cells)
364 const out: Array<{ cells: number; color: string }> = []
365 let used = 0
366 for (let run = 0; run < runs; run++) {
367 const end = Math.round(((run + 1) * cells) / runs)
368 out.push({ cells: end - used, color: mix(from, to, runs === 1 ? 0 : run / (runs - 1)) })
369 used = end
370 }
371
372 return out
373}
374
375export function mix(from: string, to: string, at: number): string {
376 const a = rgb(from)
377 const b = rgb(to)
378 const channel = (index: number) =>
379 Math.round(a[index]! + (b[index]! - a[index]!) * at)
380 .toString(16)
381 .padStart(2, '0')
382
383 return `#${channel(0)}${channel(1)}${channel(2)}`
384}
385
386function rgb(hex: string): [number, number, number] {
387 const value = parseInt(hex.slice(1), 16)
388
389 return [(value >> 16) & 255, (value >> 8) & 255, value & 255]
390}
391
392export type MeterPart = { text: string; color: string }
393
394/**
395 * Cells of one meter: done in coral to gold, a reported percent in green, a
396 * three-cell sweep while a helper has not reported yet, a hairline queued.
397 */
398export function meter(card: DockCard, cells: number, frame: number): MeterPart[] {
399 if (cells <= 0) {
400 return []
401 }
402 if (card.status === 'queued') {
403 return [{ text: '─'.repeat(cells), color: HAIRLINE }]
404 }
405 if (card.status === 'done') {
406 return gradientRuns(cells, CORAL, GOLD, 4).map(run => ({ text: '━'.repeat(run.cells), color: run.color }))
407 }
408 if (card.status === 'stuck') {
409 const filled = Math.max(1, Math.round((card.percent / 100) * cells))
410 return [
411 { text: '━'.repeat(filled), color: RED },
412 { text: '─'.repeat(cells - filled), color: HAIRLINE },
413 ]
414 }
415 if (!card.hasReported) {
416 const width = Math.min(3, cells)
417 const start = (frame % (cells + width)) - width
418 const parts: MeterPart[] = []
419 for (let cell = 0; cell < cells; cell++) {
420 const isLit = cell >= start && cell < start + width
421 parts.push({ text: isLit ? '━' : '─', color: isLit ? GREEN : HAIRLINE })
422 }
423 return merge(parts)
424 }
425 const filled = Math.round((card.percent / 100) * cells)
426
427 return merge([
428 { text: '━'.repeat(filled), color: GREEN },
429 { text: '─'.repeat(cells - filled), color: HAIRLINE },
430 ])
431}
432
433/**
434 * The mission bar: finished helpers sweep coral to gold, working ones
435 * shimmer green, the rest is a hairline.
436 */
437export function missionBar(cards: readonly DockCard[], cells: number, frame: number): MeterPart[] {
438 if (cells <= 0) {
439 return []
440 }
441 const tally = counts(cards)
442 const total = Math.max(1, tally.total)
443 const finished = Math.round(((tally.done + tally.stuck) / total) * cells)
444 const working = Math.min(cells - finished, Math.round((tally.working / total) * cells))
445 const parts: MeterPart[] = gradientRuns(finished, CORAL, GOLD).map(run => ({ text: '━'.repeat(run.cells), color: run.color }))
446 const glint = working > 0 ? frame % working : -1
447 for (let cell = 0; cell < working; cell++) {
448 parts.push({ text: '━', color: cell === glint ? GREEN_LIGHT : GREEN })
449 }
450 parts.push({ text: '─'.repeat(cells - finished - working), color: HAIRLINE })
451
452 return merge(parts.filter(part => part.text !== ''))
453}
454
455function merge(parts: MeterPart[]): MeterPart[] {
456 const out: MeterPart[] = []
457 for (const part of parts) {
458 const last = out[out.length - 1]
459 if (last !== undefined && last.color === part.color) {
460 last.text += part.text
461 } else if (part.text !== '') {
462 out.push({ ...part })
463 }
464 }
465
466 return out
467}
468
469export function cardsPerRow(columns: number): number {
470 return columns >= 98 ? 3 : columns >= 64 ? 2 : 1
471}
472
473export function tilesPerRow(columns: number, tileWidth: number): number {
474 return Math.max(1, Math.floor((columns + 1) / (tileWidth + 1)))
475}
476
477export function rows<T>(items: readonly T[], perRow: number): T[][] {
478 const out: T[][] = []
479 for (let at = 0; at < items.length; at += perRow) {
480 out.push(items.slice(at, at + perRow))
481 }
482
483 return out
484}
485
486/**
487 * The idle row: one seat per team member, up to 25, in a fixed shimmer of
488 * bright and soft seats (no clock runs while idle).
489 */
490export function seats(size: number): Array<{ color: string; isSoft: boolean }> {
491 return Array.from({ length: Math.min(size, MAX_SEATS) }, (_, index) => ({
492 color: BADGE_COLORS[index % BADGE_COLORS.length]!,
493 isSoft: (index * 7) % 5 < 2,
494 }))
495}
496
497export function standingBy(size: number): [string, string] {
498 return [
499 `Your team of ${size} is standing by`,
500 size === 1 ? 'Send a request and Claude decides how many helpers to use.' : `Send a request and it splits across ${size} helpers.`,
501 ]
502}
503hooks/progress.ts 23 lines1// Shared by Clean View and the Agent Dock, so a percent and a duration read
2// the same on every surface.
3
4export function clampPercent(value: unknown): number {
5 const percent = Number(value)
6
7 return Number.isFinite(percent) ? Math.round(Math.min(100, Math.max(0, percent))) : 0
8}
9
10// 134_000 → "2m 14s"
11export function formatDuration(ms: number): string {
12 const seconds = Math.max(0, Math.floor(ms / 1000))
13 if (seconds < 60) {
14 return `${seconds}s`
15 }
16 const minutes = Math.floor(seconds / 60)
17 if (minutes < 60) {
18 return `${minutes}m ${seconds % 60}s`
19 }
20
21 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
22}
23hooks/status-line-logic.ts 975 lines1import type {
2 ChatEffort,
3 StatusLineBase,
4 StatusLineBlockId,
5 StatusLineIcons,
6 StatusLineLayout,
7 StatusLineMode,
8 StatusLinePreview,
9 StatusLineRun,
10 StatusLineScope,
11 StatusLineScopeState,
12 StatusLineSetup,
13 StatusLineSkill,
14} from '../types'
15import { modelLabel } from './chat-picks-logic'
16
17// What the Status Line Dock needs with no `$`: the blocks, Layout edits, what
18// the settings files hold, the install and uninstall changes, the preview's
19// input, and the renderer's colors turned into styled runs.
20
21export const BLOCKS: ReadonlyArray<{ id: StatusLineBlockId; name: string }> = [
22 { id: 'folder', name: 'Folder' },
23 { id: 'branch', name: 'Branch' },
24 { id: 'model', name: 'Model' },
25 { id: 'effort', name: 'Effort' },
26 { id: 'version', name: 'Version' },
27 { id: 'style', name: 'Style' },
28 { id: 'context', name: 'Context' },
29 { id: 'cost', name: 'Cost' },
30 { id: 'lines', name: 'Lines changed' },
31 { id: 'time', name: 'Session time' },
32 { id: 'limits', name: 'Rate limits' },
33 { id: 'cache', name: 'Prompt cache' },
34 { id: 'agents', name: 'Agents' },
35 { id: 'skill', name: 'Skill' },
36]
37
38export const LINE_COUNT = 2
39export const ICON_STYLES: readonly StatusLineIcons[] = ['glyph', 'emoji', 'none']
40export const ICON_NAMES: Record<StatusLineIcons, string> = { glyph: 'Glyph', emoji: 'Emoji', none: 'None' }
41
42const DEFAULT_LINES: readonly StatusLineBlockId[][] = [
43 ['folder', 'branch', 'model', 'effort'],
44 ['context', 'cost', 'lines', 'time', 'agents'],
45]
46
47// Every command this renderer runs as ends with these, wherever the config folder is.
48const RENDERER_NAME = 'mods-toolbox/statusline.sh'
49const AGENT_DOCK_ADDON = /^(\S*agent-dock\/statusline\.sh)(?:\s+'((?:[^']|'\\'')*)')?\s*$/
50const REFRESH_SECONDS = 2
51
52export function isBlockId(value: unknown): value is StatusLineBlockId {
53 return BLOCKS.some(block => block.id === value)
54}
55
56export function blockName(id: StatusLineBlockId): string {
57 return BLOCKS.find(block => block.id === id)?.name ?? id
58}
59
60/** A first Layout: Extend when there is a status line to keep, Replace when there is none. */
61export function defaultLayout(base: StatusLineBase | null): StatusLineLayout {
62 return {
63 version: 1,
64 mode: base === null ? 'replace' : 'extend',
65 icons: 'glyph',
66 lines: DEFAULT_LINES.map(line => [...line]),
67 base,
68 }
69}
70
71function isRecord(value: unknown): value is Record<string, unknown> {
72 return typeof value === 'object' && value !== null && !Array.isArray(value)
73}
74
75function parseBase(value: unknown): StatusLineBase | null {
76 if (!isRecord(value)) {
77 return null
78 }
79 if (value.kind === 'command' && typeof value.command === 'string' && value.command.trim() !== '') {
80 return { kind: 'command', command: value.command }
81 }
82 if (value.kind === 'file' && typeof value.path === 'string' && value.path !== '') {
83 return { kind: 'file', path: value.path }
84 }
85
86 return null
87}
88
89/** A Layout file's text as the Dock edits it; null when it is not one. Unknown and repeated blocks are dropped. */
90export function parseLayout(text: string | null): StatusLineLayout | null {
91 if (text === null) {
92 return null
93 }
94 let value: unknown
95 try {
96 value = JSON.parse(text)
97 } catch {
98 return null
99 }
100 if (!isRecord(value) || !Array.isArray(value.lines)) {
101 return null
102 }
103 const seen = new Set<StatusLineBlockId>()
104 const lines = Array.from({ length: LINE_COUNT }, (_, index) => {
105 const line = (value as { lines: unknown[] }).lines[index]
106 return (Array.isArray(line) ? line : []).filter((id): id is StatusLineBlockId => {
107 if (!isBlockId(id) || seen.has(id)) {
108 return false
109 }
110 seen.add(id)
111 return true
112 })
113 })
114 const mode: StatusLineMode = value.mode === 'extend' ? 'extend' : 'replace'
115 const icons = ICON_STYLES.find(style => style === value.icons) ?? 'glyph'
116
117 return { version: 1, mode, icons, lines, base: parseBase(value.base) }
118}
119
120export function layoutText(layout: StatusLineLayout): string {
121 return `${JSON.stringify(layout, null, 2)}\n`
122}
123
124export function sameLayout(a: StatusLineLayout, b: StatusLineLayout): boolean {
125 return JSON.stringify(a) === JSON.stringify(b)
126}
127
128/** "2 lines · 9 blocks" */
129export function layoutSummary(layout: StatusLineLayout): string {
130 const lines = layout.lines.filter(line => line.length > 0).length
131 const blocks = layout.lines.reduce((sum, line) => sum + line.length, 0)
132
133 return `${lines} line${lines === 1 ? '' : 's'} · ${blocks} block${blocks === 1 ? '' : 's'}`
134}
135
136/** Line 1, line 2, then the blocks that are off, in the catalog's order. */
137export function rows(layout: StatusLineLayout): StatusLineBlockId[][] {
138 const on = new Set(layout.lines.flat())
139
140 return [...layout.lines.map(line => [...line]), BLOCKS.map(block => block.id).filter(id => !on.has(id))]
141}
142
143function rowOf(layout: StatusLineLayout, id: StatusLineBlockId): number {
144 const index = layout.lines.findIndex(line => line.includes(id))
145
146 return index === -1 ? LINE_COUNT : index
147}
148
149/** One place left or right within its line; the off row keeps the catalog's order. */
150export function moveAlong(layout: StatusLineLayout, id: StatusLineBlockId, step: -1 | 1): StatusLineLayout {
151 const row = rowOf(layout, id)
152 const line = layout.lines[row]
153 if (line === undefined) {
154 return layout
155 }
156 const from = line.indexOf(id)
157 const to = from + step
158 if (to < 0 || to >= line.length) {
159 return layout
160 }
161 const moved = [...line]
162 moved.splice(from, 1)
163 moved.splice(to, 0, id)
164
165 return { ...layout, lines: layout.lines.map((other, index) => (index === row ? moved : other)) }
166}
167
168/** Up or down a row: line 1, line 2, off. It lands at the end of a line. */
169export function moveAcross(layout: StatusLineLayout, id: StatusLineBlockId, step: -1 | 1): StatusLineLayout {
170 const from = rowOf(layout, id)
171 const to = Math.min(LINE_COUNT, Math.max(0, from + step))
172 if (to === from) {
173 return layout
174 }
175
176 return {
177 ...layout,
178 lines: layout.lines.map((line, index) => {
179 const without = line.filter(other => other !== id)
180 return index === to ? [...without, id] : without
181 }),
182 }
183}
184
185export function isOff(layout: StatusLineLayout, id: StatusLineBlockId): boolean {
186 return rowOf(layout, id) === LINE_COUNT
187}
188
189/** On at the end of the last line in use, where the status line ends; line 1 when none is. */
190export function turnOn(layout: StatusLineLayout, id: StatusLineBlockId): StatusLineLayout {
191 if (!isOff(layout, id)) {
192 return layout
193 }
194 const last = layout.lines.reduce((found, line, index) => (line.length > 0 ? index : found), 0)
195
196 return { ...layout, lines: layout.lines.map((line, index) => (index === last ? [...line, id] : line)) }
197}
198
199export function turnOff(layout: StatusLineLayout, id: StatusLineBlockId): StatusLineLayout {
200 return isOff(layout, id) ? layout : { ...layout, lines: layout.lines.map(line => line.filter(other => other !== id)) }
201}
202
203export function toggleBlock(layout: StatusLineLayout, id: StatusLineBlockId): StatusLineLayout {
204 return isOff(layout, id) ? turnOn(layout, id) : turnOff(layout, id)
205}
206
207export function nextIcons(layout: StatusLineLayout): StatusLineLayout {
208 const index = ICON_STYLES.indexOf(layout.icons)
209
210 return { ...layout, icons: ICON_STYLES[(index + 1) % ICON_STYLES.length] ?? 'glyph' }
211}
212
213// --- Files and commands -----------------------------------------------------
214
215export type Paths = {
216 config: string
217 home: string
218 root: string
219 userSettings: string
220 projectSettings: string
221 localSettings: string
222 renderer: string
223 rendererJq: string
224 records: string
225 agentDockRecords: string
226 agentDockAddon: string
227 captures: string
228 skills: string
229}
230
231/** Claude Code's config folder ($CLAUDE_CONFIG_DIR, else ~/.claude) and every file the Dock reads or writes. */
232export function pathsFor(configDir: string | undefined, home: string, root: string): Paths {
233 const config = (configDir !== undefined && configDir !== '' ? configDir : `${home}/.claude`).replace(/\/+$/, '')
234 const own = `${config}/mods-toolbox`
235
236 return {
237 config,
238 home,
239 root,
240 userSettings: `${config}/settings.json`,
241 projectSettings: `${root}/.claude/settings.json`,
242 localSettings: `${root}/.claude/settings.local.json`,
243 renderer: `${own}/statusline.sh`,
244 rendererJq: `${own}/statusline.jq`,
245 records: `${own}/installs.json`,
246 agentDockRecords: `${config}/agent-dock/installs`,
247 agentDockAddon: `${config}/agent-dock/statusline.sh`,
248 captures: `${own}/last-input`,
249 skills: `${own}/skill-now`,
250 }
251}
252
253/** A session's file in a per-session folder, named the way the renderer names it. */
254export function sessionFile(dir: string, sessionId: string): string {
255 return `${dir}/${sessionId.replace(/[^A-Za-z0-9._-]/g, '_')}.json`
256}
257
258// 32-bit FNV-1a, so two project paths that read alike once cleaned keep apart.
259function hash(text: string): string {
260 let value = 0x811c9dc5
261 for (let index = 0; index < text.length; index++) {
262 value ^= text.charCodeAt(index)
263 value = Math.imul(value, 0x01000193) >>> 0
264 }
265
266 return value.toString(16).padStart(8, '0')
267}
268
269export function layoutFile(paths: Paths, scope: StatusLineScope): string {
270 const folder = `${paths.config}/mods-toolbox/layouts`
271 if (scope === 'global') {
272 return `${folder}/global.json`
273 }
274 const name = paths.root.replace(/[^A-Za-z0-9._-]/g, '_').replace(/^_+/, '').slice(-80)
275
276 return `${folder}/project-${name}-${hash(paths.root)}.json`
277}
278
279export function shellQuote(word: string): string {
280 return /^[A-Za-z0-9_@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`
281}
282
283// Under the home folder a path is written with ~, so a settings file kept in a
284// dotfiles repository works on every machine it is used on.
285function shellPath(path: string, home: string): string {
286 if (home !== '' && path.startsWith(`${home}/`)) {
287 const rest = path.slice(home.length + 1)
288 if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(rest)) {
289 return `~/${rest}`
290 }
291 }
292
293 return shellQuote(path)
294}
295
296/** The status line command for one scope's Layout. */
297export function rendererCommand(paths: Paths, scope: StatusLineScope): string {
298 return `sh ${shellPath(paths.renderer, paths.home)} ${shellPath(layoutFile(paths, scope), paths.home)}`
299}
300
301export function isOwnCommand(command: string | null): boolean {
302 return command !== null && command.includes(RENDERER_NAME)
303}
304
305/** The Agent Dock add-on wraps a person's command as `statusline.sh '<command>'`; this is that command, if any. */
306export function unwrapAgentDock(command: string): { isWrapped: boolean; base: string | null } {
307 const match = AGENT_DOCK_ADDON.exec(command.trim())
308 if (match === null) {
309 return { isWrapped: false, base: null }
310 }
311 const quoted = match[2]
312
313 return { isWrapped: true, base: quoted === undefined ? null : quoted.replace(/'\\''/g, "'") }
314}
315
316type Parsed = { settings: Record<string, unknown> | null; problem: string | null }
317
318/** A settings file as JSON; null settings when there is no file, a problem when it is not plain JSON (comments, say). */
319export function parseSettings(text: string | null, path: string): Parsed {
320 if (text === null) {
321 return { settings: null, problem: null }
322 }
323 try {
324 const value: unknown = JSON.parse(text)
325 return isRecord(value) ? { settings: value, problem: null } : { settings: null, problem: `${path} is not a JSON object` }
326 } catch {
327 return { settings: null, problem: `${path} is not plain JSON, so it is left alone` }
328 }
329}
330
331export function statusLineCommand(settings: Record<string, unknown> | null): string | null {
332 const statusLine = settings?.statusLine
333 if (!isRecord(statusLine) || typeof statusLine.command !== 'string' || statusLine.command.trim() === '') {
334 return null
335 }
336
337 return statusLine.command
338}
339
340// What Extend keeps of a command a settings file holds: the person's own
341// command, unwrapped from the Agent Dock add-on, or nothing for our own.
342function keptCommand(command: string): StatusLineBase | null {
343 if (isOwnCommand(command)) {
344 return null
345 }
346 const { isWrapped, base } = unwrapAgentDock(command)
347 const kept = isWrapped ? base : command
348
349 return kept === null ? null : { kind: 'command', command: kept }
350}
351
352export type SetupFiles = {
353 paths: Paths
354 user: string | null
355 project: string | null
356 local: string | null
357 globalLayout: string | null
358 projectLayout: string | null
359 records: string | null
360 isLocked: boolean
361}
362
363// What an uninstall puts back, as the confirm says it; null when the scope isn't installed.
364function restoreText(isInstalled: boolean, record: InstallRecord | undefined, inherited: string | null): string | null {
365 if (!isInstalled) {
366 return null
367 }
368 const before = record?.before ?? null
369 if (isRecord(before) && typeof before.command === 'string' && before.command.trim() !== '') {
370 return before.command
371 }
372 if (before !== null) {
373 return 'its statusLine block as it was'
374 }
375 const none = inherited === null ? 'no status line' : `no status line of its own, so ${inherited} shows again`
376
377 return record === undefined ? `${none}: there is no record here of the one before` : none
378}
379
380/** What the settings files and Layouts hold, read the way Claude Code picks a status line. */
381export function setupFrom(files: SetupFiles): StatusLineSetup {
382 const { paths } = files
383 const user = parseSettings(files.user, paths.userSettings)
384 const project = parseSettings(files.project, paths.projectSettings)
385 const local = parseSettings(files.local, paths.localSettings)
386 const commands = {
387 local: statusLineCommand(local.settings),
388 project: statusLineCommand(project.settings),
389 user: statusLineCommand(user.settings),
390 }
391 const source = (['local', 'project', 'user'] as const).find(name => commands[name] !== null)
392 const inForce = source === undefined ? null : { source, command: commands[source] ?? '' }
393
394 const globalLayout = parseLayout(files.globalLayout)
395 const projectLayout = parseLayout(files.projectLayout)
396 const isGlobalInstalled = isOwnCommand(commands.user)
397 const isProjectInstalled = isOwnCommand(commands.local)
398 const globalBase = isGlobalInstalled ? (globalLayout?.base ?? null) : commands.user === null ? null : keptCommand(commands.user)
399
400 // A project with no status line of its own follows the file it inherits
401 // from, so a later change there still shows. A file that runs this Dock's
402 // line is not followed, or its blocks would show twice: the project keeps
403 // what the global Layout keeps.
404 const inheritedBase = (): StatusLineBase | null => {
405 if (commands.project !== null) {
406 return isOwnCommand(commands.project) ? null : { kind: 'file', path: paths.projectSettings }
407 }
408 if (commands.user !== null) {
409 return isGlobalInstalled ? globalBase : { kind: 'file', path: paths.userSettings }
410 }
411 return null
412 }
413 const projectBase = isProjectInstalled
414 ? (projectLayout?.base ?? null)
415 : commands.local !== null
416 ? keptCommand(commands.local)
417 : inheritedBase()
418
419 const records = parseRecords(files.records)
420 const inherited = commands.project !== null ? 'the one in .claude/settings.json' : commands.user !== null ? 'the global one' : null
421
422 const scope = (
423 scopeName: StatusLineScope,
424 file: string,
425 isInstalled: boolean,
426 layout: StatusLineLayout | null,
427 base: StatusLineBase | null,
428 problem: string | null,
429 ): StatusLineScopeState => ({
430 file,
431 layoutFile: layoutFile(paths, scopeName),
432 command: rendererCommand(paths, scopeName),
433 isInstalled,
434 layout,
435 base,
436 restores: restoreText(isInstalled, records[file], scopeName === 'project' ? inherited : null),
437 isRecorded: records[file] !== undefined,
438 problem,
439 })
440
441 return {
442 isLocked: files.isLocked,
443 inForce,
444 global: scope('global', paths.userSettings, isGlobalInstalled, globalLayout, globalBase, user.problem),
445 project: scope('project', paths.localSettings, isProjectInstalled, projectLayout, projectBase, local.problem),
446 }
447}
448
449/** The Layout the Dock opens on for a scope: its saved one, the global one for a new project, else the default. */
450export function startingLayout(setup: StatusLineSetup, scope: StatusLineScope): StatusLineLayout {
451 const own = setup[scope]
452 const saved = own.layout ?? (scope === 'project' ? setup.global.layout : null)
453 if (saved === null) {
454 return defaultLayout(own.base)
455 }
456
457 return own.isInstalled ? saved : { ...saved, base: own.base, mode: own.base === null ? 'replace' : saved.mode }
458}
459
460// --- Install and uninstall --------------------------------------------------
461
462/** What an install found, so an uninstall puts back exactly that. */
463export type InstallRecord = {
464 scope: StatusLineScope
465 layoutFile: string
466 // The statusLine block before the install; null when there was none.
467 before: unknown
468 createdFile: boolean
469}
470
471export type InstallRecords = Record<string, InstallRecord>
472
473export function parseRecords(text: string | null): InstallRecords {
474 if (text === null) {
475 return {}
476 }
477 try {
478 const value: unknown = JSON.parse(text)
479 const installs = isRecord(value) && isRecord(value.installs) ? value.installs : {}
480 const records: InstallRecords = {}
481 for (const [file, record] of Object.entries(installs)) {
482 if (isRecord(record) && (record.scope === 'global' || record.scope === 'project') && typeof record.layoutFile === 'string') {
483 records[file] = {
484 scope: record.scope,
485 layoutFile: record.layoutFile,
486 before: record.before ?? null,
487 createdFile: record.createdFile === true,
488 }
489 }
490 }
491 return records
492 } catch {
493 return {}
494 }
495}
496
497export function recordsText(records: InstallRecords): string {
498 return `${JSON.stringify({ version: 1, installs: records }, null, 2)}\n`
499}
500
501// The file's own indent and final newline, so a rewrite changes only the statusLine lines.
502function formatLike(value: Record<string, unknown>, original: string | null): string {
503 const indent = original === null ? ' ' : (/^([ \t]+)"/m.exec(original)?.[1] ?? ' ')
504 const isNewlineEnded = original === null || original.endsWith('\n')
505
506 return `${JSON.stringify(value, null, indent)}${isNewlineEnded ? '\n' : ''}`
507}
508
509/** The line the Agent Dock's setup kept for a settings file in agent-dock/installs: a number, none, new, new-file, unknown; null when absent. */
510export function agentDockRecord(text: string | null, file: string): string | null {
511 for (const line of (text ?? '').split('\n')) {
512 const [path, value] = line.split('\t')
513 if (path === file) {
514 return value === undefined || value === '' ? 'unknown' : value
515 }
516 }
517
518 return null
519}
520
521export function withoutAgentDockRecord(text: string | null, file: string): string {
522 return (text ?? '')
523 .split('\n')
524 .filter(line => line !== '' && line.split('\t')[0] !== file)
525 .map(line => `${line}\n`)
526 .join('')
527}
528
529export type InstallPlan = {
530 file: string
531 text: string
532 createsFile: boolean
533 oldCommand: string | null
534 newCommand: string
535 layout: StatusLineLayout
536 record: InstallRecord
537 // The file was the Agent Dock add-on's: its line in agent-dock/installs goes.
538 wasAgentDock: boolean
539}
540
541type InstallArgs = {
542 scope: StatusLineScope
543 state: StatusLineScopeState
544 settingsText: string | null
545 draft: StatusLineLayout
546 command: string
547 existing: InstallRecord | undefined
548 agentDockValue: string | null
549}
550
551// What the file held before, as the Agent Dock's own uninstall would have put it back.
552function beforeAgentDock(statusLine: Record<string, unknown>, base: string | null, recorded: string | null): { before: unknown; createdFile: boolean } {
553 if (recorded === 'new' || base === null) {
554 return { before: null, createdFile: recorded === 'new-file' }
555 }
556 if (recorded === 'new-file') {
557 return { before: null, createdFile: true }
558 }
559 const { refreshInterval, ...rest } = statusLine
560 if (recorded === 'none') {
561 return { before: { ...rest, command: base }, createdFile: false }
562 }
563 if (recorded !== null && /^\d+$/.test(recorded)) {
564 return { before: { ...rest, command: base, refreshInterval: Number(recorded) }, createdFile: false }
565 }
566
567 return { before: { ...rest, command: base, ...(refreshInterval === undefined ? {} : { refreshInterval }) }, createdFile: false }
568}
569
570/** The settings file's new text and what to remember, or why it can't be changed. */
571export function installPlan({ scope, state, settingsText, draft, command, existing, agentDockValue }: InstallArgs): InstallPlan | { problem: string } {
572 const parsed = parseSettings(settingsText, state.file)
573 if (parsed.problem !== null) {
574 return { problem: parsed.problem }
575 }
576 const settings = parsed.settings ?? {}
577 const current = settings.statusLine
578 const statusLine = isRecord(current) ? current : {}
579 const oldCommand = statusLineCommand(settings)
580 const wrapped = oldCommand === null ? { isWrapped: false, base: null } : unwrapAgentDock(oldCommand)
581
582 const found =
583 current === undefined
584 ? { before: null, createdFile: settingsText === null }
585 : isOwnCommand(oldCommand)
586 ? { before: existing?.before ?? null, createdFile: existing?.createdFile ?? false }
587 : wrapped.isWrapped
588 ? beforeAgentDock(statusLine, wrapped.base, agentDockValue)
589 : { before: current, createdFile: false }
590
591 const interval = statusLine.refreshInterval
592 const next: Record<string, unknown> = {
593 ...statusLine,
594 type: 'command',
595 command,
596 refreshInterval: typeof interval === 'number' && interval >= 1 && interval <= REFRESH_SECONDS ? interval : REFRESH_SECONDS,
597 }
598
599 return {
600 file: state.file,
601 text: formatLike({ ...settings, statusLine: next }, settingsText),
602 createsFile: settingsText === null,
603 oldCommand,
604 newCommand: command,
605 layout: { ...draft, base: state.base },
606 record: { scope, layoutFile: state.layoutFile, before: found.before, createdFile: found.createdFile },
607 wasAgentDock: wrapped.isWrapped,
608 }
609}
610
611export type UninstallPlan = {
612 // The settings file's new text; null to delete the file the install created; undefined to leave it alone.
613 text: string | null | undefined
614}
615
616/**
617 * Puts back what the install found. With no record of the install, as when the
618 * settings file came from another machine's dotfiles, the statusLine block just
619 * goes. A status line someone changed since is theirs, and stays.
620 */
621export function uninstallPlan(settingsText: string | null, file: string, record: InstallRecord | undefined): UninstallPlan | { problem: string } {
622 const parsed = parseSettings(settingsText, file)
623 if (parsed.problem !== null) {
624 return { problem: parsed.problem }
625 }
626 if (parsed.settings === null || !isOwnCommand(statusLineCommand(parsed.settings))) {
627 return { text: undefined }
628 }
629 const { statusLine: _ours, ...rest } = parsed.settings
630 const before = record?.before ?? null
631 const restored = before === null ? rest : { ...parsed.settings, statusLine: before }
632 if (record?.createdFile === true && Object.keys(restored).length === 0) {
633 return { text: null }
634 }
635
636 return { text: formatLike(restored, settingsText) }
637}
638
639// --- Preview ----------------------------------------------------------------
640
641export type PreviewFacts = {
642 // The last input Claude Code gave the installed renderer, for this session.
643 captured: Record<string, unknown> | null
644 sessionId: string
645 cwd: string
646 // The folder the session started in: the renderer runs git status only in its repo.
647 root: string
648 modelId: string | null
649 version: string | null
650 effort: ChatEffort | null
651 outputStyle: string | null
652 usage: {
653 startedAt: number
654 context: { percent?: number }
655 rateLimits: ReadonlyArray<{ kind: string; percentUsed: number; resetsAt?: string }>
656 cost?: { usd: number }
657 } | null
658 now: number
659 agents: number
660 skill: StatusLineSkill | null
661}
662
663const SAMPLE = {
664 model: 'Opus 5.5',
665 effort: 'high',
666 version: '2.1.0',
667 style: 'default',
668 context: 34,
669 cost: 0.42,
670 added: 42,
671 removed: 18,
672 durationMs: 754_000,
673 fiveHour: 23,
674 sevenDay: 41,
675 // Seconds from now; the half minute keeps the countdown on its figure between refreshes.
676 fiveHourResets: 2 * 3600 + 10 * 60 + 30,
677 sevenDayResets: 3 * 86_400 + 4 * 3600 + 30,
678 cacheExpires: 47 * 60 + 30,
679 agents: 3,
680 skill: { name: 'code-review', isRunning: true },
681}
682
683function at(value: unknown, ...keys: string[]): unknown {
684 let current = value
685 for (const key of keys) {
686 current = isRecord(current) ? current[key] : undefined
687 }
688
689 return current
690}
691
692const isMissing = (value: unknown) => value === undefined || value === null || value === ''
693
694// The name Claude Code's own status line input carries, "Opus 5.5 (1M context)", which the renderer shortens.
695function displayName(modelId: string): string {
696 const isLong = modelId.endsWith('[1m]')
697 const name = modelLabel(isLong ? modelId.slice(0, -'[1m]'.length) : modelId)
698
699 return isLong ? `${name} (1M context)` : name
700}
701
702/** The stdin the preview's renderer gets: this session's real figures, and samples for the blocks that have none yet. */
703export function previewInput(facts: PreviewFacts): {
704 input: Record<string, unknown>
705 samples: StatusLineBlockId[]
706 agents: number
707 skill: StatusLineSkill
708} {
709 const nowSeconds = Math.floor(facts.now / 1000)
710 // A window as the status line input has it: resets_at in epoch seconds.
711 const rateWindow = (kind: string) => {
712 const limit = facts.usage?.rateLimits.find(found => found.kind === kind)
713 if (limit === undefined) {
714 return {}
715 }
716 const resets = limit.resetsAt === undefined ? Number.NaN : Date.parse(limit.resetsAt)
717 return {
718 [kind]: { used_percentage: limit.percentUsed, ...(Number.isFinite(resets) ? { resets_at: Math.floor(resets / 1000) } : {}) },
719 }
720 }
721 const built: Record<string, unknown> = {
722 session_id: facts.sessionId,
723 cwd: facts.cwd,
724 workspace: { current_dir: facts.cwd, project_dir: facts.root },
725 ...(facts.modelId === null ? {} : { model: { id: facts.modelId, display_name: displayName(facts.modelId) } }),
726 ...(facts.version === null ? {} : { version: facts.version }),
727 ...(facts.effort === null ? {} : { effort: { level: facts.effort } }),
728 ...(facts.outputStyle === null ? {} : { output_style: { name: facts.outputStyle } }),
729 cost: {
730 ...(facts.usage?.cost === undefined ? {} : { total_cost_usd: facts.usage.cost.usd }),
731 ...(facts.usage === null ? {} : { total_duration_ms: Math.max(0, facts.now - facts.usage.startedAt) }),
732 },
733 context_window: facts.usage?.context.percent === undefined ? {} : { used_percentage: facts.usage.context.percent },
734 rate_limits: { ...rateWindow('five_hour'), ...rateWindow('seven_day') },
735 }
736 const { columns: _columns, ...captured } = facts.captured ?? {}
737 const real = facts.captured === null ? built : captured
738
739 const samples: StatusLineBlockId[] = []
740 const fill = (id: StatusLineBlockId, isEmpty: boolean, patch: Record<string, unknown>) => {
741 if (isEmpty) {
742 samples.push(id)
743 Object.assign(real, merge(real, patch))
744 }
745 }
746 fill('model', isMissing(at(real, 'model', 'display_name')) && isMissing(at(real, 'model', 'id')), { model: { display_name: SAMPLE.model } })
747 fill('effort', isMissing(at(real, 'effort', 'level')), { effort: { level: SAMPLE.effort } })
748 fill('version', isMissing(at(real, 'version')), { version: SAMPLE.version })
749 fill('style', isMissing(at(real, 'output_style', 'name')), { output_style: { name: SAMPLE.style } })
750 fill('context', isMissing(at(real, 'context_window', 'used_percentage')), { context_window: { used_percentage: SAMPLE.context } })
751 fill('cost', isMissing(at(real, 'cost', 'total_cost_usd')), { cost: { total_cost_usd: SAMPLE.cost } })
752 fill('lines', !at(real, 'cost', 'total_lines_added') && !at(real, 'cost', 'total_lines_removed'), {
753 cost: { total_lines_added: SAMPLE.added, total_lines_removed: SAMPLE.removed },
754 })
755 fill('time', !at(real, 'cost', 'total_duration_ms'), { cost: { total_duration_ms: SAMPLE.durationMs } })
756 fill('limits', isMissing(at(real, 'rate_limits', 'five_hour')) && isMissing(at(real, 'rate_limits', 'seven_day')), {
757 rate_limits: {
758 five_hour: { used_percentage: SAMPLE.fiveHour, resets_at: nowSeconds + SAMPLE.fiveHourResets },
759 seven_day: { used_percentage: SAMPLE.sevenDay, resets_at: nowSeconds + SAMPLE.sevenDayResets },
760 },
761 })
762 fill('cache', isMissing(at(real, 'prompt_cache', 'expires_at')), {
763 prompt_cache: { caching_observed: true, warm: true, ttl: '1h', expires_at: nowSeconds + SAMPLE.cacheExpires },
764 })
765 const agents = facts.agents > 0 ? facts.agents : SAMPLE.agents
766 if (facts.agents <= 0) {
767 samples.push('agents')
768 }
769 if (facts.skill === null) {
770 samples.push('skill')
771 }
772
773 return { input: real, samples, agents, skill: facts.skill ?? SAMPLE.skill }
774}
775
776function merge(target: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown> {
777 const merged: Record<string, unknown> = { ...target }
778 for (const [key, value] of Object.entries(patch)) {
779 const current = merged[key]
780 merged[key] = isRecord(current) && isRecord(value) ? merge(current, value) : value
781 }
782
783 return merged
784}
785
786/** The renderer's preview JSON as the Dock draws it, or why there is none. */
787export function previewFrom(stdout: string, columns: number, samples: StatusLineBlockId[]): StatusLinePreview {
788 try {
789 const value: unknown = JSON.parse(stdout)
790 if (!isRecord(value) || !Array.isArray(value.lines)) {
791 throw new Error('not a preview')
792 }
793 const texts = (list: unknown) => (Array.isArray(list) ? list.filter((line): line is string => typeof line === 'string') : [])
794
795 return {
796 base: texts(value.base).flatMap(line => styledLines(line)),
797 lines: texts(value.lines).flatMap(line => styledLines(line)),
798 dropped: (Array.isArray(value.dropped) ? value.dropped : []).filter(isBlockId),
799 samples,
800 columns,
801 error: null,
802 }
803 } catch {
804 const said = stdout.split('\n').find(line => line.trim() !== '')
805
806 return { base: [], lines: [], dropped: [], samples, columns, error: said === undefined ? 'The preview could not run.' : stripControls(said) }
807 }
808}
809
810// --- ANSI colors to styled runs ---------------------------------------------
811
812// The xterm palette: the 16 named colors, a 6×6×6 cube, then 24 grays.
813const NAMED = [
814 '#000000', '#cd0000', '#00cd00', '#cdcd00', '#0000ee', '#cd00cd', '#00cdcd', '#e5e5e5',
815 '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff',
816]
817const CUBE = [0, 95, 135, 175, 215, 255]
818
819const hex = (red: number, green: number, blue: number) =>
820 `#${[red, green, blue].map(part => Math.max(0, Math.min(255, part)).toString(16).padStart(2, '0')).join('')}`
821
822export function paletteColor(index: number): string | undefined {
823 if (!Number.isInteger(index) || index < 0 || index > 255) {
824 return undefined
825 }
826 if (index < 16) {
827 return NAMED[index]
828 }
829 if (index < 232) {
830 const cube = index - 16
831 return hex(CUBE[Math.floor(cube / 36)] ?? 0, CUBE[Math.floor(cube / 6) % 6] ?? 0, CUBE[cube % 6] ?? 0)
832 }
833 const gray = 8 + (index - 232) * 10
834
835 return hex(gray, gray, gray)
836}
837
838type Style = Omit<StatusLineRun, 'text'>
839
840// An extended color (38;5;n or 38;2;r;g;b) from the parameters after 38 or 48; how many it used.
841function extendedColor(params: number[], from: number): { color: string | undefined; used: number } {
842 if (params[from] === 5) {
843 return { color: paletteColor(params[from + 1] ?? -1), used: 2 }
844 }
845 if (params[from] === 2) {
846 return { color: hex(params[from + 1] ?? 0, params[from + 2] ?? 0, params[from + 3] ?? 0), used: 4 }
847 }
848
849 return { color: undefined, used: 0 }
850}
851
852function applySgr(style: Style, params: number[]): Style {
853 let next: Style = { ...style }
854 const list = params.length === 0 ? [0] : params
855 for (let index = 0; index < list.length; index++) {
856 const code = list[index] ?? 0
857 if (code === 0) {
858 next = {}
859 } else if (code === 1) {
860 next.bold = true
861 } else if (code === 2) {
862 next.dimColor = true
863 } else if (code === 3) {
864 next.italic = true
865 } else if (code === 4) {
866 next.underline = true
867 } else if (code === 7) {
868 next.inverse = true
869 } else if (code === 9) {
870 next.strikethrough = true
871 } else if (code === 22) {
872 delete next.bold
873 delete next.dimColor
874 } else if (code === 23) {
875 delete next.italic
876 } else if (code === 24) {
877 delete next.underline
878 } else if (code === 27) {
879 delete next.inverse
880 } else if (code === 29) {
881 delete next.strikethrough
882 } else if (code >= 30 && code <= 37) {
883 next.color = NAMED[code - 30]
884 } else if (code >= 90 && code <= 97) {
885 next.color = NAMED[code - 90 + 8]
886 } else if (code === 39) {
887 delete next.color
888 } else if (code >= 40 && code <= 47) {
889 next.backgroundColor = NAMED[code - 40]
890 } else if (code >= 100 && code <= 107) {
891 next.backgroundColor = NAMED[code - 100 + 8]
892 } else if (code === 49) {
893 delete next.backgroundColor
894 } else if (code === 38 || code === 48) {
895 const { color, used } = extendedColor(list, index + 1)
896 if (color !== undefined) {
897 next[code === 38 ? 'color' : 'backgroundColor'] = color
898 }
899 index += used
900 }
901 }
902
903 return next
904}
905
906/**
907 * Terminal output as lines of styled runs. Colors and text styles become
908 * props; every other escape sequence and control character is dropped, since
909 * one left in a Text refuses the whole band.
910 */
911export function styledLines(text: string): StatusLineRun[][] {
912 return text.split('\n').map(line => {
913 const runs: StatusLineRun[] = []
914 let style: Style = {}
915 let chunk = ''
916 const flush = () => {
917 if (chunk !== '') {
918 const last = runs[runs.length - 1]
919 if (last !== undefined && JSON.stringify({ ...last, text: '' }) === JSON.stringify({ ...style, text: '' })) {
920 last.text += chunk
921 } else {
922 runs.push({ text: chunk, ...style })
923 }
924 chunk = ''
925 }
926 }
927 for (let index = 0; index < line.length; index++) {
928 const char = line[index] ?? ''
929 const code = char.charCodeAt(0)
930 if (char === '\u001b') {
931 const kind = line[index + 1]
932 if (kind === '[') {
933 let end = index + 2
934 while (end < line.length && !/[@-~]/.test(line[end] ?? '')) {
935 end++
936 }
937 if (line[end] === 'm') {
938 flush()
939 const params = line
940 .slice(index + 2, end)
941 .split(/[;:]/)
942 .map(part => (part === '' ? 0 : Number(part)))
943 style = applySgr(style, params.every(Number.isFinite) ? params : [])
944 }
945 index = end
946 } else if (kind === ']') {
947 // An OSC (a link, a title) runs to BEL or ESC \.
948 let end = index + 2
949 while (end < line.length && line[end] !== '\u0007' && !(line[end] === '\u001b' && line[end + 1] === '\\')) {
950 end++
951 }
952 index = line[end] === '\u001b' ? end + 1 : end
953 } else {
954 index++
955 }
956 } else if (char === '\t') {
957 chunk += ' '
958 } else if (code < 0x20 || code === 0x7f || (code >= 0x80 && code <= 0x9f)) {
959 // Dropped: a control character refuses the tree.
960 } else {
961 chunk += char
962 }
963 }
964 flush()
965
966 return runs
967 })
968}
969
970export function stripControls(text: string): string {
971 return styledLines(text)
972 .map(line => line.map(run => run.text).join(''))
973 .join(' ')
974}
975