SLOPSHOPPER

aitools

Subscription usage, API-equivalent cost and context bar above the prompt

panebandrowsguardcommandtoast
★ 1v0.9.8no licenseupdated 2026-10-20pkkid/claude-aitools/plugins/aitools
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · aitools
│ ┃ Background tasks ✕ › fix the failing auth test╭───────────────────────────────────────╮ │ ┃ Showing: All │ aitools │ │ ┃ Hide after: Never ⏺ Read(src/auth.ts) │ Handoff brief copied to the clipboard │ │ ┃ ⎿ Read 6 lines ╰───────────────────────────────────────╯ │ ┃ Background tasks will appear here when ⏺ Bash(bun test) │ ┃ started. ⎿ 3 pass, 1 fail │ │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /aitools │ ⎿ aitools: aitools bar hidden. Run /aitools to show it. │ │ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ aitools: Task View, Clean View

Draws

Pane · Background tasks
Showing: All Hide after: Never Background tasks will appear here when started.
Pane · Branches
Branches: Local + remote Show: All Git didn't list any worktrees.
Pane · handoff
Writing the handoff brief…
Pane · aitools-settings
What the AI Tools ribbons show. Changes save right away. Yours, in every project: ~/.claude/aitools.json Not in a GitHub repository Global Settings May be overridden by project settings ● Show title AI Tools at the start of the bar ● Threshold colors Yellow from 70%, red from 90%; a cache a ● Show project row A second row: repo, board, issue and too ○ Statusline file Written each turn, as the CLI's status l ~/.claude/statusline.json Meters 5-hour ● Percent ● Reset 5h 42%, 1h12m Weekly ● Percent ● Reset wk 18%, Thu Context ● Percent ● Tokens ctx 31% 62k/200k Tokens ● Thread ● Last turn tok 1.3M (+48k) Cache ● Time left ● Cold cost cache 42m, $0. Thread cost ● Thread ● Last turn ● Weekly share thread $3.12 (+$0.41) ~2.1% wk Month ● Cost month $184.20 Burn rate ● Warning limit ~3:40pm Project Settings Saved for each project Its settings show in a GitHub repository.
Pane · project
Reading the board…
Pane · notes
Loading the note…
README

aitools

A one-row bar above the prompt showing how close your Claude subscription is to its limits, and what the work would cost at Anthropic API list prices.

AI Tools    5h 42%, 1h12m    wk 18%, Thu    ctx 31% 62k/200k    tok 1.3M (+48k)    cache 42m, $0.50    thread $3.12 (+$0.41)    month $184.20    limit ~3:40pm   [🛠] [⁝]
SegmentMeaning
ClawdThe mascot, at the start of the bar in the desktop Code tab only (see below)
AI ToolsA dim title naming the bar
5h 42%, 1h12m5-hour usage window: percent used, time until it resets
wk 18%, ThuWeekly window: percent used, the day it resets (hours when under a day)
ctx 31% 62k/200kContext window fill: percent and tokens used / window size
tok 1.3M (+48k)Tokens: this thread's total this month (its helpers' included) and the last turn's, counting input, output and prompt-cache reads and writes
cache 42mHow long the prompt cache should stay warm: Claude Code writes the main conversation's cache with a 1-hour TTL, restarted by every request. Amber under 10 minutes, cache cold once expired. An estimate from request times; the API does not report cache state, and Anthropic may evict early
cache 42m, $0.50What a cold cache costs the next message: the whole context written to the cache again at the model's 1-hour cache-write price (list prices, ~ for a model priced by its family), where a warm cache reads it for a small fraction of that. Shown after the cache time (cache 42m, $0.50, or cache cold, $0.50 once it has lapsed), or as cache $0.50 with cache warmth off. It's an upper bound: the context figure includes the last reply
thread $3.12This session's cost at API prices
(+$0.41)What the last turn cost (last $0.41 when thread cost is hidden)
~2.1% wk (+0.03%)Thread cost %: the thread's and the last turn's estimated share of your weekly allowance (see below)
month $184.20This calendar month's Claude Code usage at API prices, across all sessions on this machine
limit ~3:40pmAt your pace over the last hour, when the 5-hour window would run out; shown only if before it resets

Labels are dim and values a lighter grey; usage and context values turn yellow at 70% and red at 90%. A value not known yet shows -; until the first response of a session the bar shows the figures from your previous session.

Show or hide the bar

/aitools toggles the whole bar (buttons included); /aitools on and /aitools off set it. The choice holds across sessions. /handoff works either way.

Settings

Press ⁝ (opts in the terminal) to open the AI Tool Settings pane; press it again, or the pane's own close mark, to close it. Opening it closes the 🛠 menu. Clawd stands at its top left in a hard hat, cranking a cog (on the desktop), beside the files the settings are saved in. Every option, or every meter with its options, gets a row, in two sections:

Global Settings  May be overridden by project settings
● Show mascot       Clawd, acting out what Claude is doing
● Clawd reactions   He reacts to what you say: blushing at praise, mad at swearing
● Show title        AI Tools at the start of the bar
● Threshold colors  Yellow from 70%, red from 90%; a cache about to go cold
● Show project row  A second row: repo, board, issue and tools, in every project
○ Statusline file   Written each turn, as the CLI's status line does: ~/.claude/statusline.json
Meters
  5-hour            ● Percent  ● Reset  5h 42%, 1h12m
  Weekly            ● Percent  ● Reset  wk 18%, Thu
  Context           ● Percent  ● Tokens  ctx 31% 62k/200k
  Tokens            ● Thread  ● Last turn  tok 1.3M (+48k)
  Cache             ● Time left  ● Cold cost  cache 42m, $0.50
  Thread cost       ● Thread  ● Last turn  ● Weekly share
                    thread $3.12 (+$0.41) ~2.1% wk
  Month             ● Cost  month $184.20
  Burn rate         ● Warning  limit ~3:40pm

Project Settings  Saved for vowelit only
● Show project row  The row in vowelit
  Name              [Vowelit                                   ]
                    In place of the repo's name
● Board             Its open items on the row, and the Project pane
  Board URL         [https://github.com/users/pkkid/projects/1 ]
  Tools             Server · Test · Docs. Edit project.tools in the file.

Global Settings holds the bar's display options. First the bar's own: show mascot and Clawd reactions (offered on the desktop only), show title, threshold colors, show project row (in every project) and statusline file. Then each meter in the bar is one row, its options beside its name and a sample of it after them, all under Meters in the order the bar shows them: 5-hour, weekly, context, tokens, cache, thread cost, month and burn rate. A meter shows while any of its options is on. The 🛠 button always shows.

Statusline file (off by default) writes ~/.claude/statusline.json after each turn, in the shape of the JSON the CLI hands a statusLine command, so a program outside Claude (a desktop meter such as Conky) can read the 5-hour and weekly limits even from the desktop app, which runs no status line command. Fields the mod has no figure for are left out (prompt_cache, effort, output_style and the like). Each write goes to a private temp file that is then renamed over the old one, as a status line command would, so a reader never sees half a file and sessions writing at once each land whole; the last one wins, and the limits are the account's, so its reading is the newest.

Global Settings are saved for all your projects, in your settings file. Project Settings are saved for the project, in its own file, and show only in a GitHub repository: Show project row (whether the row shows here, when the global one is on too), the name it shows, and its board (off, or its URL). Each heading says where its settings go. Type a name or URL and press Enter to save it; an empty field goes back to the repository's name or the board looked up for it, and a URL that isn't a GitHub Project's is refused with a line saying why. These are written to the project file (see Project row); its tools are edited in the file itself.

Changes show in the bar right away and are saved across sessions. An option that is off does no work in the background: the transcript scan runs only for monthly cost, thread tokens or thread cost %; the cost lookups only for the cost options; the mascot follows nothing while hidden. (Request times are kept either way: /keepwarm needs them.) Turned back on, an option catches up at once, except the burn-rate warning, which needs fresh samples (a few responses) to project from. Hiding the bar with /aitools off stops all of it.

The settings file

Everything the mod's controls change is saved to ~/.claude/aitools.json ($CLAUDE_CONFIG_DIR/aitools.json when that is set): the display options (the project row among them), /aitools on|off, the view, and the Background tasks and Branches panes' picks. The first run writes every setting into it, taking over what earlier versions kept in the mod's own store, so the file lists everything there is to change. Edit it by hand and the bar follows within 30 seconds, when ⁝ opens, or at once when Claude edits it. A file that isn't valid JSON is left alone: the settings stay as they were, and one dim line in the chat says what's wrong.

{
  "bar": {
    "hidden": false,
    "show": { "mascot": true, "label": true, "projectRow": true, "fiveHour": true, "cacheWarmth": true, "coldCost": true, "...": true }
  },
  "view": { "tasks": false, "clean": false },
  "subagents": { "showing": "all", "hideAfter": "never" },
  "branches": { "where": "both", "show": "all" }
}

A write reads the file again first and changes only its own keys, so anything else in it stays. The display options are always written here; a project's own .claude/aitools.json gets only what you set under Project Settings (see Project row).

Mascot

In the desktop Code tab, Clawd, Claude Code's mascot, stands at the start of the bar (48 × 20 px) and acts out what Claude is doing. He is drawn in flat shapes with eased motion, and a change of pose plays a short transition first: he walks over to his laptop or terminal, sits down to sleep, jolts awake, or throws an arm up as a thought lands.

PoseWhen
WavingA new session starts (a few seconds)
CatchingYou send a prompt: it flies up from the prompt box and he catches it (a few seconds)
ThinkingThe reply streams thinking: dots pulse in a thought bubble, then a lightbulb as he acts
TypingA turn is running and no tool below is: tapping at a laptop, code typing out on its screen
ReadingRead, or a shell command that reads a file (cat, head, tail): reading a sheet of paper
WritingEdit or Write: lines writing themselves onto a page as a pencil follows
SearchingA shell command that searches (grep, rg, find): sweeping a magnifying glass over files
TerminalAny other shell command: typing at a little terminal, Enter, output scrolling in
GlobeA web search or fetch: pointing at a spinning globe
RocketA git commit or git push succeeds: a rocket lifts off and he cheers (a few seconds)
Mini ClawdThe chat sends off a subagent: a mini Clawd pops out of him and runs off (a few seconds)
PackingThe conversation compacts: a messy stack of pages squashed into a box
CoffeeA turn running past 3 minutes: a sip now and then; past 9 minutes he wipes his brow instead
WaitingAn AskUserQuestion dialog is open: tapping a foot, a cursor blinking in his bubble
PuzzledA reply ends with a question mark. Your next prompt settles it
CelebratingA turn finishes with an answer (a few seconds, then Standing)
StoppingYou interrupt a turn: he skids to a halt, hands up (a few seconds)
OopsA tool call fails or is refused, or a turn fails (a few seconds)
StandingNothing is running: breathing, blinking, glancing around. Once a minute a small moment: a glance at the prompt, a stretch, a hop, a butterfly
SleepingStanding idle for 5 minutes, with a yawn in the last one; your next prompt wakes him

He is SVG, so he never shows in the terminal, and Mascot in the settings pane (on by default) is offered on the desktop only.

Reactions

Say something to him and he reacts in place of catching your prompt, then types as usual. The mod reads your prompt against a list of phrases (no model, no tokens): a long prompt only at its first and last 12 words, skipping code, quotes, pasted text and links; slash commands never.

You sayHe
A compliment: "good job", "you're the best", "Perfect!"Blushes, a heart floating up
"love you", "<3", "call me"Winks with a phone to his head, hearts floating off it
Scolding, swearing, or a prompt in all capitalsTurns red and stomps, steam and an anger mark
"take a break", "go take a nap"Yawns; once the turn ends, naps in a hammock until your next prompt
"good night", "calling it a day"Waves; once the turn ends, falls asleep
"do a barrel roll", "do a flip"Leaps and spins
"high five", "we did it"Snaps a claw up to meet your hand
"\*pats Clawd\*", "good boy"Squishes under a head pat, then hearts
"thanks"Takes a bow
"lol", "haha"Laughs, tears of joy flying
"are you sure?", "that's wrong", "oops"Scratches his head sheepishly
"dance", "yay", "🎉"Dances, music notes floating up
"hi", "good morning", "bye"Waves
"ship it", "lgtm"Launches the rocket

A reaction said in passing (thanks, hello, a compliment) plays at most once every 5 minutes; one asked for outright (a barrel roll, a break, a dance) plays every time. Clawd reactions in the settings pane turns them off.

Handoff

/handoff asks the current conversation for a brief (goal, current state, decisions, open tasks, key files, next step), prints it in the chat as formatted text, and copies the raw markdown to the clipboard. Paste it into a new session to continue there. The brief is a command output row, so the current session's model reads it too.

The 🛠 button opens a row above the bar with Handoff, Notes, Tasks, Branches, Project (in a GitHub repository), Task View and Clean View, right-aligned; press it again to close the row without picking. Handoff writes the same brief into a Handoff brief pane, drawn as formatted text with a Copy button; nothing is copied until you press it, and the brief stays out of the chat (so the current session's model does not read it).

Keep the cache warm

Stepping away for longer than an hour lets the prompt cache lapse, and the next message pays to write the whole context again (the dollar figure after the cache time on the bar). /keepwarm holds it warm while you are gone: 5 minutes before the cache's hour is up, it sends one small request over the conversation, which reads the cache and restarts its hour.

/keepwarm             keep warm for 6 hours
/keepwarm 90m         for a time of your own (also 2h30m, 10h)
/keepwarm status      time left, the next ping, and what the last ping read and cost
/keepwarm off         stop
/keepwarm help        these lines

While it runs, a ☼ shows left of 🛠 (tools in the terminal), right of ? when that shows.

  • A ping is $.model.fork: the conversation exactly as Claude last sent it, plus "Reply with the single word: warm". It reads the cached context (about $0.01 for 62k tokens on Opus 5.5), and nothing joins the conversation.
  • No ping while Claude is working (its own requests keep the cache warm), before the session's first request, after compaction until the next request, or when the cache would stay warm past the window's end anyway.
  • A cache that has already lapsed is never pinged: that would pay the full write every hour. Pings start again after your next message.
  • Each ping's readback is checked. If it read nothing, or wrote a tenth of what it read or more, the cache was already gone, and keepwarm stops. A failed ping (an API error, an interruption, an empty reply) stops it too. Either way a dim line in the chat and /keepwarm status say why.
  • The window belongs to this session and is kept across a restart of it, until its time is up.
  • Claude Code must be left running, and the main cache must have the 1-hour lifetime: subscription use has it by default; API-key and cloud-provider sessions need promptCacheTtl set to "1h".

The logic follows cache-tax's keepwarm, pinging 5 minutes before the hour where cache-tax pings after 50 idle minutes.

Ask as choices

When Claude ends an answer with questions for you in plain text, /askme asks them again as pop-up questions with clickable options. Claude's recommended option comes first, marked "(Recommended)", and each option says what picking it means. Yes-or-no confirmations come four to a question, and you can always type your own answer under "Other". Anything typed after the command is passed along as a note, as in /askme only the M2 ones. After you answer, Claude sums up the decisions and carries on.

You don't have to type the command: when Claude's last answer asks you something and it hasn't already used the pop-up for that request, a ? button appears just left of 🛠 (tools in the terminal). It goes away once you send your next prompt. Pressing it sends /askme straight away. If it can't, because Claude is still working or the prompt was refused, it puts /askme in the prompt box for you to send. Anything you had typed there stays, after the command, and goes along as its note. Only a question mark right after a word counts: a bare ?, or one inside code or a link, doesn't.

Notes

Notes in the 🛠 menu opens a Notes pane with one text box for a single scratch note. It is kept in .claude/notes.md under the project root, a plain Markdown file you can open anywhere else too, and saved as you type. Copy, at the end of the line above the box, copies the note to the clipboard. Add .claude/notes.md to the project's .gitignore if it should stay out of git.

Click in the box to type. Enter starts a new line, the arrows, Home and End move the cursor (Ctrl+A and Ctrl+E too), Page Up and Page Down move ten rows, and Backspace and Delete remove. Escape hands the keys back to the prompt. There is no selection or undo. Pasting works in the terminal but not in the desktop app, where a mod cannot read the clipboard; paste into .claude/notes.md in another editor and reopen the pane instead. The pane stays open until you close it, and comes back after the mod reloads. Where a surface cannot draw the box (VS Code, the mobile app), the pane says where the note is kept instead.

Task View and Clean View

Two views from the 🛠 menu, each turned on and off on its own: Task View draws Claude's work as a checklist in the bar, and Clean View hides Claude's work in the chat, leaving its final replies. In the menu a ● marks a view that is on and a ○ one that is off; picking one turns it on or off. The choices hold across sessions (view.tasks and view.clean in the settings file; a file from when the views were one choice reads "task" as Task View and "clean" as both).

While a view is on, its name shows in the status line under the prompt (both, comma separated). /taskview and /cleanview do the same as the menu from the prompt: no argument toggles that view, on turns it on and off turns it off.

The checklist sits between the bar's top row and the project row (an open menu still shows above the bar): done steps marked with a green ✓, the step in progress with a blue ●, steps not started with a dim ○. Its title row starts with ▾, which folds the list to that row for the session (▸ opens it again), and ends with how many steps are done and ×, which closes the list until your next prompt; Claude updating it meanwhile leaves it closed.

▾ Adding dark mode                                                3 of 5 ×
✓ Read the theme code                                       100% ▰▰▰▰▰▰
✓ Add the color tokens                                      100% ▰▰▰▰▰▰
● Wire up the toggle                                         40% ▰▰▱▱▱▱
○ Update tests                                                0% ▱▱▱▱▱▱
○ Run checks                                                  0% ▱▱▱▱▱▱

Each step has a bar: full once done, empty until it starts, and for the step in progress Claude's own estimate of how far along it is, which moves each time Claude updates the checklist (the note asks for about every quarter of a step).

  • Task View shows the checklist and leaves the chat as it is (only the checklist tool's own rows are hidden).
  • Clean View hides every tool call and everything Claude writes while it works; only the final reply of each finished request stays. It hides tool calls and in-progress replies already in the chat too. With Task View on as well, the checklist is what shows the work meanwhile.

While Task View is on, each prompt you send carries a hidden note asking Claude to plan the work as plain-language steps and report them through the mod's checklist tool (mcp__aitools__checklist), updating it as each step starts and finishes. The mod answers that tool itself, before Claude Code's permission check, so it should not ask for permission. Each new prompt starts a fresh checklist; once every step is done and Claude stops, it folds to one line, ✓ Done: <title> (<n> steps), with a × at its right end that closes it. A quick question that needs no work gets no checklist.

While Clean View is on, each prompt also carries a note asking Claude not to narrate between steps and to put what you need in a brief final reply. Clean View recognizes a final reply as the last thing Claude wrote before your next prompt. It reads them from the conversation when the mod loads (so replies from before a reload or restart still show) and adds each new one as a request finishes.

Background tasks

While any background task runs, the project row counts them (1 bg task, 3 bg tasks); pressing it opens the Background tasks pane. Tasks in the 🛠 menu opens it too (where there is no project row), and /tasks opens it, or closes it if open; the pane's own close mark closes it. It stays open until you close it, and comes back after the mod reloads.

On the desktop, Clawd stands left of the pane's option rows with a mini Clawd stacked on his head for each task running in the list (the stack stops growing at four), and sleeps in quiet grey when none is. The header line under the options sits beside him too. The terminal has no picture.

Every subagent, workflow agent and monitor of the session gets a line, whether the pane is open or not, one per line with its type:

  • Subagent: a subagent Claude starts with its Agent tool (foreground or background).
  • Workflow: an agent of a workflow Claude starts, named after the workflow (review-changes · agent 3, since a workflow's agents have no names of their own).
  • Monitor: a monitor watching a command's output or a socket: its description, then what it watches.

Shell commands run in the background get no line: Claude Code offers no way to ask whether one is still running, so a line whose end notice was missed would stay running for good. Claude Code lists them itself.

The ones running come first (oldest first), then the finished ones, the most recently finished first. Marks are Task View's: a blue ● running, a ✓ done, a red × failed, and a dim × stopped (killed by you or Claude). A running task's name is a lighter grey, followed in dim grey by what it is doing (a subagent's latest tool call, Reading bar.tsx, or what a monitor watches) and its running time. A line's name and what it is doing take the room the pane's width leaves, cut with … at the edge. A finished line is all dim (but a failed one's ×): no bar, just how long it ran and how long ago it finished, 0:09 (3m ago).

Showing: [All] Subagents  Workflows  Monitors
Hide after: [Never] 1h  15m  5m  Immediate

2 running · 1 done
● Subagent Research business licenses · Reading the city site          40% ▰▰▱▱▱▱  1:20
● Monitor  Wait for the dev server · curl localhost:3000                             4:02
✓ Subagent Draft the floor plan                                          0:56 (3m ago)

In each option row the choice in effect is drawn at full strength (shown as […] above); the others are dim, and pressing one picks it. They are the same compact buttons as the bar's.

Tasks run as Claude Code normally runs them: the pane only watches, adding no note to your prompts, changing no model and putting nothing in the status line. Tracking costs no tokens: the lines are kept in memory for the session.

  • A task's end is what Claude Code's own notice of it says (completed, failed, killed), whether the notice arrives as a prompt of its own or inside a running turn, the main chat's or the subagent's that started it. A subagent whose end was missed is settled when Claude next replies; a monitor whose closing notice never comes ends a minute past its deadline.
  • Only while the pane is open, every subagent Claude starts with its Agent tool has its prompt ask it to report how far along it is through the mod's agent_progress tool (mcp__aitools__agent_progress); once it does, its line shows its percent (its own estimate) and a bar. Workflow agents, monitors, and subagents started while the pane was closed are not asked, so they show no bar.
  • Showing: All (the default) lists every line; Subagents, **Workflows*
Source 30 files
hooks/register.tsx 3194 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Events, Register, Timer } from 'claude-code'
3
4import {
5  PROGRESS_SPEC,
6  PROGRESS_TOOL_ID,
7  SUBAGENT_NOTE,
8  DEFAULT_HIDE_AFTER,
9  DOCK_PANE,
10  DOCK_TITLE,
11  KIND_LABELS,
12  activityText,
13  addCard,
14  clip,
15  finishCard,
16  isRunning,
17  kindOf,
18  newRun,
19  noteActivity,
20  noticeEnd,
21  parseTaskNotices,
22  runningCount,
23  renderDock,
24  reportProgress,
25  workflowName,
26} from '../src/agentdock'
27import type { EndStatus } from '../src/agentdock'
28import { CACHE_TTL, renderBar } from '../src/bar'
29import { BOARD_QUERY, BOARD_REFRESH_MS, PROJECT_PANE, filterCounts, parseBoardItems, parseBoardUrl, renderBoard } from '../src/board'
30import { price } from '../src/pricing'
31import {
32  CHECKLIST_SPEC,
33  CHECKLIST_TOOL_ID,
34  VIEW_NAMES,
35  addFinal,
36  finalReplies,
37  isFinalReply,
38  nextToggle,
39  parseChecklist,
40  renderChecklist,
41  viewNote,
42} from '../src/checklist'
43import { FAINT_TEXT, RED } from '../src/palette'
44import { EMPTY_BURN, addSample, project } from '../src/burnrate'
45import type { BurnState } from '../src/burnrate'
46import { HANDOFF_PROMPT, handoffOutput, paneMarkdown } from '../src/handoff'
47import { ASK_TOOL, askmeText, asksQuestions, isAskableIn } from '../src/askme'
48import { CONFIG_FILE, STORED_KEYS, configText, migrated, parseConfig, personalFrom, withPersonal } from '../src/config'
49import type { Json, Personal, StoredSettings } from '../src/config'
50import {
51  LOG_KEEP,
52  expand,
53  issueInBranch,
54  issueInPrompt,
55  logPaneId,
56  parseGithubRemote,
57  projectFrom,
58  renderProjectRow,
59  splitOutput,
60} from '../src/project'
61import type { ToolVars } from '../src/project'
62import {
63  KEEPWARM_HELP,
64  KEEPWARM_LEAD_MS,
65  KEEPWARM_PROMPT,
66  coldPingText,
67  failureText,
68  isWarmReadback,
69  keepWarmStatus,
70  parseKeepWarm,
71  pingDelay,
72} from '../src/keepwarm'
73import {
74  IDLE_MOMENTS,
75  IDLE_MOMENT_MS,
76  LONG_TURN_MOMENT_MS,
77  LONG_TURN_MS,
78  MASCOT_START,
79  ONE_SHOT_MS,
80  SLEEP_AFTER_MS,
81  TOOL_POSES,
82  commandPose,
83  endsWithQuestion,
84  introMs,
85  isQuestionOpenIn,
86  isShipCommand,
87  mascotDrawing,
88} from '../src/mascot'
89import { mayReact, reactionTo } from '../src/reactions'
90import type { Reaction } from '../src/reactions'
91import {
92  AFTER_TOOL_MS,
93  BRANCHES_PANE,
94  BRANCHES_TITLE,
95  CHANGING_TOOLS,
96  FIRST_PARENT_DEPTH,
97  REFRESH_MS,
98  SWEEP_MS,
99  baseName,
100  countBranches,
101  countChanged,
102  findForks,
103  firstLine,
104  isCleanable,
105  isDeletable,
106  joinBranches,
107  parseCommitTimes,
108  parseParents,
109  parsePrs,
110  parseRefs,
111  parseRuns,
112  parseShortstat,
113  parseTreeStats,
114  parseWorktreeList,
115  refFormat,
116  removedText,
117  renderBranches,
118} from '../src/branches'
119import type { CheckoutFacts, Fork, PrFacts, Removal, WorktreeEntry } from '../src/branches'
120import { DEFAULT_SETTINGS, nextHidden, normalizeSettings } from '../src/settings'
121import { SETTINGS_PANE, SETTINGS_TITLE, boardProblem, homeRelative, renderSettings, withProject } from '../src/settingspane'
122import type { ProjectChange } from '../src/settingspane'
123import { STATUSLINE_FILE, STATUSLINE_WRITE, projectSlug, statusline } from '../src/statusline'
124import { scanMonth, sessionTokens, sessionUsd, usageTokens } from '../src/transcripts'
125import type { ScanCache, ScanIO } from '../src/transcripts'
126import type { BoardData, Branch, BranchTarget, BranchesShow, BranchesWhere, CiState, GithubRepo, ProjectTool, ToolListener, ToolRun } from '../types'
127import type { AgentCard, AgentKind, AgentRun, AgentShowing, Brief, HideAfter, LimitWindow, MascotPose, MascotState, Snapshot, ToggleKey } from '../types'
128
129// The engine follows `$` only into functions declared in this file, so every
130// function that touches `$` lives here; src/ holds the pure units.
131
132const snapshot = atom({ plugin: 'aitools', key: 'snapshot' } as const, null)
133const month = atom({ plugin: 'aitools', key: 'month' } as const, { usd: 0, isEstimate: false, status: 'loading' })
134const projection = atom({ plugin: 'aitools', key: 'projection' } as const, null)
135const settings = atom({ plugin: 'aitools', key: 'settings' } as const, DEFAULT_SETTINGS)
136const isHidden = atom({ plugin: 'aitools', key: 'isHidden' } as const, false)
137const isSettingsOpen = atom({ plugin: 'aitools', key: 'isSettingsOpen' } as const, false)
138const cacheAt = atom({ plugin: 'aitools', key: 'cacheAt' } as const, null)
139const turnBaseline = atom({ plugin: 'aitools', key: 'turnBaseline' } as const, null)
140const tick = atom({ plugin: 'aitools', key: 'tick' } as const, 0)
141const isHandingOff = atom({ plugin: 'aitools', key: 'isHandingOff' } as const, false)
142const isToolsOpen = atom({ plugin: 'aitools', key: 'isToolsOpen' } as const, false)
143const brief = atom({ plugin: 'aitools', key: 'brief' } as const, null)
144const isTaskView = atom({ plugin: 'aitools', key: 'isTaskView' } as const, false)
145const isCleanView = atom({ plugin: 'aitools', key: 'isCleanView' } as const, false)
146const checklist = atom({ plugin: 'aitools', key: 'checklist' } as const, null)
147const isChecklistCollapsed = atom({ plugin: 'aitools', key: 'isChecklistCollapsed' } as const, false)
148const isChecklistClosed = atom({ plugin: 'aitools', key: 'isChecklistClosed' } as const, false)
149const finals = atom({ plugin: 'aitools', key: 'finals' } as const, [])
150const isDockOpen = atom({ plugin: 'aitools', key: 'isDockOpen' } as const, false)
151const agentShowing = atom({ plugin: 'aitools', key: 'agentShowing' } as const, 'all')
152const hideAfter = atom({ plugin: 'aitools', key: 'hideAfter' } as const, DEFAULT_HIDE_AFTER)
153const agentRun = atom({ plugin: 'aitools', key: 'agentRun' } as const, null)
154const runningTasks = atom({ plugin: 'aitools', key: 'runningTasks' } as const, 0)
155const branchCount = atom({ plugin: 'aitools', key: 'branchCount' } as const, null)
156const dockTick = atom({ plugin: 'aitools', key: 'dockTick' } as const, 0)
157const mascot = atom({ plugin: 'aitools', key: 'mascot' } as const, MASCOT_START)
158const asking = atom({ plugin: 'aitools', key: 'asking' } as const, 0)
159const isQuestionOpen = atom({ plugin: 'aitools', key: 'isQuestionOpen' } as const, false)
160const isAskable = atom({ plugin: 'aitools', key: 'isAskable' } as const, false)
161const mainModel = atom({ plugin: 'aitools', key: 'mainModel' } as const, null)
162const keepWarm = atom({ plugin: 'aitools', key: 'keepWarm' } as const, null)
163const githubRepo = atom({ plugin: 'aitools', key: 'githubRepo' } as const, null)
164const projectConfig = atom({ plugin: 'aitools', key: 'projectConfig' } as const, null)
165const boardUrl = atom({ plugin: 'aitools', key: 'boardUrl' } as const, null)
166const promptIssue = atom({ plugin: 'aitools', key: 'promptIssue' } as const, null)
167const toolRuns = atom({ plugin: 'aitools', key: 'toolRuns' } as const, {})
168const toolListeners = atom({ plugin: 'aitools', key: 'toolListeners' } as const, {})
169const toolLogs = atom({ plugin: 'aitools', key: 'toolLogs' } as const, {})
170const keepWarmStopped = atom({ plugin: 'aitools', key: 'keepWarmStopped' } as const, null)
171const isNotesOpen = atom({ plugin: 'aitools', key: 'isNotesOpen' } as const, false)
172const notes = atom({ plugin: 'aitools', key: 'notes' } as const, null)
173const isBranchesOpen = atom({ plugin: 'aitools', key: 'isBranchesOpen' } as const, false)
174const branchList = atom({ plugin: 'aitools', key: 'branches' } as const, null)
175const branchAction = atom({ plugin: 'aitools', key: 'branchAction' } as const, null)
176const branchesWhere = atom({ plugin: 'aitools', key: 'branchesWhere' } as const, 'both' as BranchesWhere)
177const branchesShow = atom({ plugin: 'aitools', key: 'branchesShow' } as const, 'all' as BranchesShow)
178const isBoardOpen = atom({ plugin: 'aitools', key: 'isBoardOpen' } as const, false)
179const board = atom({ plugin: 'aitools', key: 'board' } as const, { status: 'loading' })
180const boardFilter = atom({ plugin: 'aitools', key: 'boardFilter' } as const, 'open')
181const isBoardReading = atom({ plugin: 'aitools', key: 'isBoardReading' } as const, false)
182const settingsNote = atom({ plugin: 'aitools', key: 'settingsNote' } as const, null)
183
184const HANDOFF_PANE = 'handoff'
185const NOTES_PANE = 'notes'
186/** The note's file, under the session's project root. */
187const NOTES_FILE = '.claude/notes.md'
188/** The editor's key in the Notes pane. */
189const NOTES_EDITOR = 'notes-editor'
190
191/** Prompt origins that are the person's own words; anything else (a subagent's report, a notice) is not a new request. */
192const PERSON_ORIGINS: ReadonlySet<string> = new Set(['composer', 'bridge', 'sdk'])
193/** How many Background tasks trace lines the store keeps. */
194const TRACE_KEEP = 60
195/** The mod's own tools: reporting progress is not work the mascot reacts to. */
196const QUIET_TOOLS: ReadonlySet<string> = new Set([CHECKLIST_TOOL_ID, PROGRESS_TOOL_ID])
197/** How long a subagent's first model request waits for its own start to be recorded, at most. */
198const SPAWN_WAIT_MS = 2000
199/** How long past its deadline a monitor's line waits for its own closing notice before it is ended anyway. */
200const MONITOR_GRACE_MS = 60_000
201
202/** Subagent starts in flight, which a subagent's first model request may wait on before its line exists. */
203const startsInFlight = new Set<Promise<void>>()
204/** Subagent loops already looked at: each gets a line once, or is passed over once (a fork, the pane closed). */
205const seenAgents = new Set<string>()
206/** Subagents with a running line, which shows their latest tool call. */
207const trackedAgents = new Set<string>()
208/** The last workflow the main chat started, and how many of its agents have a line: what workflow agents are called. */
209let lastWorkflow: string | null = null
210let workflowAgents = 0
211/** The poses of the main chat's tool calls in flight (TOOL_POSES), oldest first: the mascot shows the latest. */
212let toolPoses: MascotPose[] = []
213/** Whether a main-chat turn is running: where the mascot stands when he is turned on mid-session. */
214let isTurnRunning = false
215/** When the running turn started, and when it last played a long turn's moment. */
216let turnStartedAt = 0
217let longMomentAt = 0
218/** When the mascot last played an idle moment, and how many he has played: they come in turn. */
219let idleMomentAt = 0
220let idleMoments = 0
221/** Whether the next turn answers the person's own prompt: it starts with the mascot catching it. */
222let isPromptPending = false
223/** The reaction the person's prompt drew (reactions.ts), played as the turn it starts begins. */
224let pendingReaction: Reaction | null = null
225/** Where the mascot settles when the running turn ends, if its prompt's reaction says: the hammock, or asleep. */
226let settleAfter: MascotPose | null = null
227/** When each reaction last played, by name: one said in passing waits out a cooldown. */
228const reactedAt = new Map<string, number>()
229/** Whether Claude has opened the question pop-up since the person's last prompt: then the bar offers no ? button. */
230let isAskedThisRequest = false
231/** /keepwarm's one pending timer: its next ping, or its end when no ping is due before then. */
232let keepWarmTimer: Timer | null = null
233/** The once-a-second timer that redraws running times: running only while the Background tasks pane is open. */
234let dockTimer: Timer | null = null
235/** The model tools registered so far: each is offered to the model only once its feature is first turned on. */
236const registeredTools = new Set<string>()
237/** The note's writes, one after another, so the last text typed is the one left on disk. */
238let notesSaving: Promise<void> = Promise.resolve()
239/** The note as it stands: as loaded, then as the editor last posted it. What Copy copies. */
240let latestNotes = ''
241/** Trace writes run one after another, so lines written at once are all kept. */
242let traceQueue: Promise<void> = Promise.resolve()
243/** The Branches pane's regular read, every REFRESH_MS: running only while it is open. */
244let branchTimer: Timer | null = null
245/** The fetch and GitHub read under way, if any: one at a time, and the pane reads git again once it is in. */
246let branchNews: Promise<void> | null = null
247/** The read in flight, and whether another (with GitHub's or not) waits for it to finish. */
248let branchReading: Promise<void> | null = null
249let branchQueued: { withGithub: boolean } | null = null
250/** The branch merges are measured against, found once each time the pane opens. */
251let branchBase: string | null = null
252/** The base the project row's branch count leaves out, found once per main checkout. */
253let countBase: { main: string; base: string } | null = null
254/** Lines added and removed since the base, by `<base commit>:<branch commit>`: a branch's are read once per commit. */
255let branchStats = new Map<string, { added: number; removed: number }>()
256/** GitHub's word, as last read: pull requests by branch and CI by commit. Dropped when the pane closes. */
257let githubPrs = new Map<string, PrFacts[]>()
258let githubRuns = new Map<string, CiState>()
259/**
260 * The board's next read, BOARD_REFRESH_MS after the last; armed only while the Project pane is open or the project row
261 * shows its open count.
262 */
263let boardTimer: Timer | null = null
264/** The board read in flight: a read asked for meanwhile is dropped, since this one brings the same. */
265let boardReading: Promise<void> | null = null
266
267const encoder = new TextEncoder()
268const TICK_MS = 30_000
269/** Cache times older than this are dropped from the per-session store. */
270const CACHE_KEEP_MS = 2 * 60 * 60_000
271/** Blank rows between the chat and the bar on the terminal, so the last of a reply does not run into it. */
272const TERMINAL_TOP_MARGIN = 1
273
274/** The latest scan, kept here too so a store write that fails costs nothing but persistence. */
275let memoryCache: ScanCache | null = null
276let isScanning = false
277let isScanPending = false
278let hasLoggedScanError = false
279
280function errorText(err: unknown): string {
281  return err instanceof Error ? err.message : String(err)
282}
283
284/** Whether a bar option is on and the bar shown: work that only feeds the bar is skipped otherwise. */
285async function isShown($: EngineInterface, keys: ToggleKey | readonly ToggleKey[]): Promise<boolean> {
286  if (await read($, isHidden)) {
287    return false
288  }
289  const current = normalizeSettings(await read($, settings))
290
291  return (typeof keys === 'string' ? [keys] : keys).some(key => current[key])
292}
293
294/** The options whose figures come from the transcript scan: the month's cost, the thread's tokens, the week's share. */
295const SCAN_KEYS: readonly ToggleKey[] = ['monthlyCost', 'threadTokens', 'threadPercent']
296/** The options that show the session's cost. */
297const COST_KEYS: readonly ToggleKey[] = ['threadCost', 'lastTurnCost', 'threadPercent']
298
299/** Whether the mascot is drawn anywhere: its option on, the bar shown, and a surface that draws SVG attached. */
300async function isMascotOn($: EngineInterface): Promise<boolean> {
301  if (!(await isShown($, 'mascot'))) {
302    return false
303  }
304
305  return (await $.session.surfaces().catch(() => [])).some(surface => surface !== 'terminal')
306}
307
308/** Offers one of the mod's tools to the model, the first time its feature is turned on in this load. */
309async function registerTool($: EngineInterface, spec: Parameters<EngineInterface['tool']['register']>[0]): Promise<void> {
310  if (registeredTools.has(spec.name)) {
311    return
312  }
313  registeredTools.add(spec.name)
314  await $.tool.register(spec).catch(err => {
315    registeredTools.delete(spec.name)
316    $.ui.log(`aitools: ${spec.name} tool not registered: ${errorText(err)}`)
317  })
318}
319
320function toWindow(limit: { percentUsed: number; resetsAt?: string } | undefined): LimitWindow | undefined {
321  return limit && { percentUsed: limit.percentUsed, resetsAt: limit.resetsAt }
322}
323
324
325function scanIO($: EngineInterface): ScanIO {
326  return {
327    list: dir => $.fs.list(dir),
328    readBytes: async path => encoder.encode(await $.fs.read(path)),
329    async tail(path, offset) {
330      const run = await $.process.run(['tail', '-c', `+${offset + 1}`, path])
331      if (run.exitCode !== 0) {
332        throw new Error(`tail exited ${run.exitCode}`)
333      }
334
335      return { bytes: encoder.encode(run.stdout), isTruncated: run.isStdoutTruncated }
336    },
337  }
338}
339
340async function projectsRoot($: EngineInterface): Promise<string> {
341  return `${await configDir($)}/projects`
342}
343
344async function readCache($: EngineInterface): Promise<ScanCache | null> {
345  return memoryCache ?? ((await $.store.get('scanCache')) as ScanCache | undefined) ?? null
346}
347
348async function scan($: EngineInterface): Promise<void> {
349  if (isScanning) {
350    isScanPending = true
351    return
352  }
353  isScanning = true
354  try {
355    do {
356      isScanPending = false
357      const next = await scanMonth(scanIO($), await projectsRoot($), await readCache($), await $.clock.now())
358      memoryCache = next
359      await $.store.set('scanCache', next).catch((err: unknown) => logScanError($, err))
360      await update($, month, () => ({ usd: next.usd, isEstimate: next.isEstimate, status: 'ready' as const, hours: next.hours }))
361      const threadTokens = sessionTokens(next, await $.session.id())
362      if (threadTokens !== undefined) {
363        await update($, snapshot, snap => ({ ...(snap ?? {}), threadTokens }))
364      }
365    } while (isScanPending)
366  } catch (err) {
367    await update($, month, m => ({ ...m, usd: m?.usd ?? 0, isEstimate: m?.isEstimate ?? false, status: 'error' as const }))
368    logScanError($, err)
369  } finally {
370    isScanning = false
371  }
372}
373
374function logScanError($: EngineInterface, err: unknown): void {
375  if (!hasLoggedScanError) {
376    hasLoggedScanError = true
377    $.ui.log(`aitools: monthly cost scan failed: ${errorText(err)}`)
378  }
379}
380
381type CacheTimes = Record<string, number>
382
383async function rememberCacheAt($: EngineInterface, at: number): Promise<void> {
384  const sessionId = await $.session.id()
385  const stored = ((await $.store.get('cacheAt')) as CacheTimes | undefined) ?? {}
386  const kept = Object.fromEntries(Object.entries(stored).filter(([, t]) => at - t < CACHE_KEEP_MS))
387  await $.store.set('cacheAt', { ...kept, [sessionId]: at })
388}
389
390async function restoreCacheAt($: EngineInterface): Promise<void> {
391  const stored = ((await $.store.get('cacheAt')) as CacheTimes | undefined) ?? {}
392  const at = stored[await $.session.id()]
393  if (at !== undefined) {
394    await update($, cacheAt, () => at)
395  }
396}
397
398/** Scans the transcripts soon, if any option showing their figures is on. */
399function startScan($: EngineInterface): void {
400  $.clock.after(0, () => void scanIfShown($))
401}
402
403async function scanIfShown($: EngineInterface): Promise<void> {
404  if (await isShown($, SCAN_KEYS)) {
405    await scan($)
406  }
407}
408
409/** Asks a fork of this conversation for the brief: the brief, or the failure's text. Null while one is already running. */
410async function writeBrief($: EngineInterface): Promise<Brief | null> {
411  if (await read($, isHandingOff)) {
412    return null
413  }
414  await update($, isHandingOff, () => true)
415  try {
416    const reply = await $.model.fork({ prompt: HANDOFF_PROMPT })
417    if (!reply.isAnswered) {
418      const reason = reply.reason === 'nothing-to-fork' ? 'nothing to hand off yet' : reply.reason
419      return { status: 'error', text: `Handoff failed: ${reason}` }
420    }
421
422    return { status: 'ready', text: reply.text.trim() }
423  } catch (err) {
424    return { status: 'error', text: `Handoff failed: ${errorText(err)}` }
425  } finally {
426    await update($, isHandingOff, () => false)
427  }
428}
429
430/** /handoff: copies the brief and toasts the outcome. Returns the chat row's text. */
431async function handoff($: EngineInterface): Promise<string> {
432  const written = await writeBrief($)
433  if (written === null) {
434    return 'Handoff already in progress.'
435  }
436  if (written.status === 'error') {
437    $.ui.toast(written.text)
438    return written.text
439  }
440  const copied = await $.ui.copy({ text: written.text })
441  $.ui.toast(copied.isCopied ? 'Handoff brief copied to the clipboard' : 'Handoff brief ready (copy failed)')
442
443  return handoffOutput(written.text)
444}
445
446/** Where the note is kept: `.claude/notes.md` under the session's project root. */
447async function notesPath($: EngineInterface): Promise<string> {
448  return `${(await $.session.root()).replace(/[\\/]$/, '')}/${NOTES_FILE}`
449}
450
451/**
452 * Reads the note for the pane, once any write still going has landed: none yet is an empty note; a file that is there
453 * but cannot be read is an error, so the editor never writes over it.
454 */
455async function loadNotes($: EngineInterface): Promise<void> {
456  await update($, notes, () => null)
457  await notesSaving
458  const path = await notesPath($)
459  let loaded: { text: string } | { error: string }
460  if (!(await $.fs.exists(path).catch(() => false))) {
461    loaded = { text: '' }
462  } else {
463    loaded = await $.fs.read(path).then(
464      text => (typeof text === 'string' ? { text } : { error: `${NOTES_FILE} is not text.` }),
465      (err: unknown) => ({ error: `Could not read ${NOTES_FILE}: ${errorText(err)}` }),
466    )
467  }
468  latestNotes = 'text' in loaded ? loaded.text : ''
469  await update($, notes, () => loaded)
470}
471
472/** The 🛠 menu's Notes: opens the Notes pane on the note as saved, its keys handed to the editor. */
473async function openNotes($: EngineInterface): Promise<void> {
474  await update($, isToolsOpen, () => false)
475  await update($, isNotesOpen, () => true)
476  await $.ui.open({ id: NOTES_PANE, title: 'Notes', focus: true })
477  await loadNotes($)
478  await $.ui.focus({ requestId: NOTES_PANE, key: NOTES_EDITOR }).catch(() => undefined)
479}
480
481/** Saves the note as the editor posted it, after any write before it. */
482function saveNotes($: EngineInterface, text: string): void {
483  latestNotes = text
484  notesSaving = notesSaving
485    .then(async () => $.fs.write(await notesPath($), text))
486    .catch((err: unknown) => $.ui.log(`aitools: could not save ${NOTES_FILE}: ${errorText(err)}`))
487}
488
489/** The Notes pane's Copy: the note as it stands, to the clipboard of the surface pressed on. */
490async function copyNotes($: EngineInterface, surface: Parameters<EngineInterface['ui']['copy']>[0]['surface']): Promise<void> {
491  const copied = await $.ui.copy({ text: latestNotes, surface })
492  $.ui.toast(copied.isCopied ? 'Note copied to the clipboard' : 'Copy failed')
493}
494
495/** The 🛠 menu's Handoff: writes the brief into the handoff pane, which has its own Copy button. */
496async function showHandoff($: EngineInterface): Promise<void> {
497  await update($, isToolsOpen, () => false)
498  if (await read($, isHandingOff)) {
499    $.ui.toast('Handoff already in progress.')
500    return
501  }
502  await update($, brief, () => ({ status: 'writing', text: '' }))
503  await $.ui.open({ id: HANDOFF_PANE, title: 'Handoff brief' })
504  const written = await writeBrief($)
505  if (written !== null) {
506    await update($, brief, () => written)
507  }
508}
509
510/** Copies the handoff pane's brief on the surface the press came from, and says whether it took. */
511async function copyBrief($: EngineInterface, surface: Parameters<EngineInterface['ui']['copy']>[0]['surface']): Promise<void> {
512  const shown = await read($, brief)
513  if (shown?.status !== 'ready') {
514    return
515  }
516  const copied = await $.ui.copy({ text: shown.text, surface })
517  $.ui.toast(copied.isCopied ? 'Handoff brief copied to the clipboard' : 'Copy failed')
518}
519
520async function toggleSetting($: EngineInterface, key: keyof typeof DEFAULT_SETTINGS): Promise<void> {
521  const changed = await update($, settings, s => {
522    const was = normalizeSettings(s)
523
524    return { ...was, [key]: !was[key] }
525  })
526  await savePersonal($, { settings: normalizeSettings(changed) })
527  if (normalizeSettings(changed)[key]) {
528    await catchUp($, key)
529  }
530  if (key === 'projectRow') {
531    // Its servers' ports, and its board's items, are read only while the row shows.
532    syncListenerPoll($)
533    syncBoardReads($)
534  }
535}
536
537/**
538 * Brings a feature up to date once it is turned on, or the whole bar once it is shown again (`key` absent): the work
539 * skipped while it was off.
540 */
541async function catchUp($: EngineInterface, key?: ToggleKey): Promise<void> {
542  startScan($)
543  if ((key === undefined || COST_KEYS.includes(key)) && (await isShown($, COST_KEYS))) {
544    const cost = (await $.session.usage()).cost?.usd
545    if (cost !== undefined) {
546      await update($, snapshot, snap => ({ ...(snap ?? {}), threadUsd: cost }))
547    }
548  }
549  if ((key === undefined || key === 'mascot') && (await isMascotOn($))) {
550    await syncMascot($)
551  }
552  if (key === 'statuslineFile') {
553    await writeStatusline($)
554  }
555}
556/** Whether a tool's row is hidden: every one under Clean View, the checklist's own under Task View (the band shows it). */
557async function isToolRowHidden($: EngineInterface, tool: string): Promise<boolean> {
558  return (await read($, isCleanView)) || ((await read($, isTaskView)) && tool === CHECKLIST_TOOL_ID)
559}
560
561/** Whether a view is on. */
562async function isViewOn($: EngineInterface, view: 'task' | 'clean'): Promise<boolean> {
563  return view === 'task' ? read($, isTaskView) : read($, isCleanView)
564}
565
566/** Turns one view on or off, on its own: saves it for later sessions and closes the 🛠 menu. */
567async function setView($: EngineInterface, view: 'task' | 'clean', isOn: boolean): Promise<void> {
568  await update($, isToolsOpen, () => false)
569  if (view === 'task') {
570    await update($, isTaskView, () => isOn)
571  } else {
572    await update($, isCleanView, () => isOn)
573  }
574  await savePersonal($, view === 'task' ? { taskView: isOn } : { cleanView: isOn })
575  await showStatus($)
576  await startViews($)
577}
578
579/** The 🛠 menu's Task View and Clean View: each turns its view on or off. */
580async function toggleView($: EngineInterface, view: 'task' | 'clean'): Promise<void> {
581  await setView($, view, !(await isViewOn($, view)))
582}
583
584/**
585 * What the views need once on: for Task View the checklist tool offered to the model, for Clean View the final
586 * replies so far (only kept while it is on).
587 */
588async function startViews($: EngineInterface): Promise<void> {
589  if (await read($, isTaskView)) {
590    await registerTool($, CHECKLIST_SPEC)
591  }
592  if (await read($, isCleanView)) {
593    const earlier = finalReplies(await $.session.messages().catch(() => []))
594    await update($, finals, list => earlier.reduce((acc, text) => addFinal(acc, text), list))
595  }
596}
597
598/** The status line under the prompt: the views that are on, comma separated; cleared when none. */
599async function showStatus($: EngineInterface): Promise<void> {
600  const on = [(await read($, isTaskView)) ? VIEW_NAMES.task : '', (await read($, isCleanView)) ? VIEW_NAMES.clean : ''].filter(Boolean)
601  $.ui.status(on.length > 0 ? on.join(', ') : undefined)
602}
603
604/** /taskview and /cleanview: toggles the view, or sets it with on/off, and says how it stands now. */
605async function viewCommand($: EngineInterface, view: 'task' | 'clean', args: string): Promise<{ text: string }> {
606  const name = VIEW_NAMES[view]
607  const isOn = nextToggle(await isViewOn($, view), args)
608  if (isOn === null) {
609    return { text: `Usage: /${view}view [on|off] (no argument toggles ${name})` }
610  }
611  await setView($, view, isOn)
612
613  return { text: `${name} ${isOn ? 'on' : 'off'}.` }
614}
615
616/** Redraws the dock's running times each second; with nothing running any more, the timer stops. */
617async function bumpDockTick($: EngineInterface): Promise<void> {
618  if (isRunning(await read($, agentRun))) {
619    await update($, dockTick, n => n + 1)
620  } else {
621    dockTimer?.cancel()
622    dockTimer = null
623  }
624}
625
626/** Starts the once-a-second redraw while the pane is open and a subagent runs; it stops itself once none does. */
627async function startDockTimer($: EngineInterface): Promise<void> {
628  if (dockTimer === null && (await read($, isDockOpen)) && isRunning(await read($, agentRun))) {
629    dockTimer = $.clock.every(1000, () => void bumpDockTick($))
630  }
631}
632
633/** Opens or closes the Background tasks pane; tasks are tracked either way. */
634async function setDockOpen($: EngineInterface, isOpen: boolean): Promise<void> {
635  await update($, isDockOpen, () => isOpen)
636  if (isOpen) {
637    await $.ui.open({ id: DOCK_PANE, title: DOCK_TITLE })
638  } else {
639    await $.ui.close({ id: DOCK_PANE })
640  }
641  await syncDock($)
642  await showStatus($)
643}
644
645/**
646 * Runs the pane's work only while it is open: its once-a-second redraw timer while a subagent runs, and the progress
647 * tool its subagents report through.
648 */
649async function syncDock($: EngineInterface): Promise<void> {
650  if (!(await read($, isDockOpen))) {
651    dockTimer?.cancel()
652    dockTimer = null
653    return
654  }
655  await startDockTimer($)
656  await registerTool($, PROGRESS_SPEC)
657}
658
659/** /subagents: opens the pane if closed, closes it if open. */
660async function toggleDock($: EngineInterface): Promise<boolean> {
661  const isOpen = !(await read($, isDockOpen))
662  await setDockOpen($, isOpen)
663
664  return isOpen
665}
666
667/** The 🛠 menu's Tasks: opens the Background tasks pane (its own close mark closes it), and closes the menu. */
668async function openDock($: EngineInterface): Promise<void> {
669  await update($, isToolsOpen, () => false)
670  await setDockOpen($, true)
671}
672
673/** The pane's Showing pick, saved for later sessions. */
674async function setShowing($: EngineInterface, showing: AgentShowing): Promise<void> {
675  await update($, agentShowing, () => showing)
676  await savePersonal($, { showing })
677}
678
679/** The pane's Hide after pick, saved for later sessions. */
680async function setHideAfter($: EngineInterface, minutes: HideAfter): Promise<void> {
681  await update($, hideAfter, () => minutes)
682  await savePersonal($, { hideAfter: minutes })
683}
684
685/** Appends one line to the Background tasks pane trace in the store, the newest TRACE_KEEP kept, one write after another. */
686function traceDock($: EngineInterface, line: string): Promise<void> {
687  traceQueue = traceQueue.then(() => appendTrace($, line)).catch(() => undefined)
688
689  return traceQueue
690}
691
692/** Reads the trace, adds one timed line and writes it back; only ever run through traceDock's queue. */
693async function appendTrace($: EngineInterface, line: string): Promise<void> {
694  const at = new Date(await $.clock.now()).toISOString().slice(11, 19)
695  const trace = ((await $.store.get('dockTrace')) as string[] | undefined) ?? []
696  await $.store.set('dockTrace', [...trace, `${at} ${line}`].slice(-TRACE_KEEP))
697}
698
699/** Waits for `work`, or `ms` at most, whichever comes first. */
700function waitAtMost($: EngineInterface, work: Promise<unknown>, ms: number): Promise<void> {
701  return new Promise(resolve => {
702    $.clock.after(ms, () => resolve())
703    void work.then(() => resolve(), () => resolve())
704  })
705}
706
707/**
708 * Changes the tasks, and the running count the project row shows with them: the row redraws only when the count
709 * changes, not on every line's activity.
710 */
711async function updateRun($: EngineInterface, change: (run: AgentRun | null) => AgentRun | null): Promise<void> {
712  await update($, agentRun, change)
713  const count = runningCount(await read($, agentRun))
714  if ((await read($, runningTasks)) !== count) {
715    await update($, runningTasks, () => count)
716  }
717}
718
719/** Marks a task finished: its line turns done, failed or stopped and moves down to the top of the finished ones. */
720async function endTask($: EngineInterface, id: string, status: EndStatus): Promise<void> {
721  trackedAgents.delete(id)
722  const now = await $.clock.now()
723  await updateRun($, run => (run === null ? run : finishCard(run, id, status, now)))
724}
725
726/** Finishes the line of every task a notice in `text` says has ended. */
727async function endNoticedTasks($: EngineInterface, text: string): Promise<void> {
728  for (const notice of parseTaskNotices(text)) {
729    const status = noticeEnd(notice)
730    if (status !== null) await endTask($, notice.id, status)
731  }
732}
733
734/** Gives a task a line, once; a subagent's or workflow agent's line follows its tool calls. */
735async function trackTask(
736  $: EngineInterface,
737  id: string,
738  task: string,
739  kind: AgentKind,
740  extra: Pick<AgentCard, 'doing' | 'expiresAt'> = {},
741): Promise<void> {
742  seenAgents.add(id)
743  if (kind === 'subagent' || kind === 'workflow') trackedAgents.add(id)
744  const now = await $.clock.now()
745  await updateRun($, r => addCard(r ?? newRun(now), id, task, now, kind, extra))
746  await startDockTimer($)
747}
748
749/**
750 * A subagent loop the pane has no line for yet, at its first model request: one the engine lists (started before the
751 * pane opened, or by another plugin) gets its own description; one it does not list is a workflow's agent while a
752 * workflow has been started, else the engine's own fork, which is passed over.
753 */
754async function noticeAgent($: EngineInterface, id: string): Promise<void> {
755  seenAgents.add(id)
756  if (await read($, isHandingOff)) {
757    return
758  }
759  const listed = (await $.agent.list().catch(() => [])).find(a => a.id === id)
760  if (listed !== undefined) {
761    await trackTask($, id, listed.description, 'subagent')
762  } else if (lastWorkflow !== null) {
763    workflowAgents += 1
764    await trackTask($, id, `${lastWorkflow} · agent ${workflowAgents}`, 'workflow')
765  }
766}
767
768/**
769 * Finishes any line whose task is over though its finish was never heard: a subagent the engine no longer has
770 * running, a monitor past its deadline.
771 */
772async function settleCards($: EngineInterface): Promise<void> {
773  const run = await read($, agentRun)
774  if (!isRunning(run)) {
775    return
776  }
777  const now = await $.clock.now()
778  for (const card of run?.cards.filter(c => c.status === 'running' && c.expiresAt !== undefined && c.expiresAt <= now) ?? []) {
779    await endTask($, card.id, 'done')
780  }
781  const agents = await $.agent.list().catch(() => null)
782  if (agents === null) {
783    return
784  }
785  // A subagent the engine no longer lists has finished too; only one listed as running or pending is still at work. A
786  // workflow's agents are never listed, nor are monitors: their own finish is the only word on them.
787  for (const card of run?.cards.filter(c => c.status === 'running' && kindOf(c) === 'subagent') ?? []) {
788    const status = agents.find(a => a.id === card.id)?.status ?? 'gone'
789    if (status !== 'running' && status !== 'pending') {
790      await traceDock($, `settled ${card.task}: ${status}`)
791      await endTask($, card.id, status === 'failed' ? 'failed' : status === 'killed' ? 'stopped' : 'done')
792    }
793  }
794}
795
796
797/**
798 * Starts a subagent as Claude Code would, given a line in the pane; while the pane is open it is also asked to report
799 * its progress there. Its start counts as in flight, so its first request finds the line rather than racing it.
800 */
801async function startSubagent(
802  $: EngineInterface,
803  e: Parameters<Events['agent.spawn']>[1],
804  next: Parameters<Events['agent.spawn']>[2],
805): Promise<Awaited<ReturnType<Events['agent.spawn']>>> {
806  const note = (await read($, isDockOpen)) ? SUBAGENT_NOTE : ''
807  let settle = () => {}
808  const inFlight = new Promise<void>(resolve => (settle = resolve))
809  startsInFlight.add(inFlight)
810  try {
811    const started = await next({ ...e, prompt: e.prompt + note })
812    if (started.agentId !== undefined) {
813      await trackTask($, started.agentId, e.description, 'subagent')
814    }
815
816    return started
817  } finally {
818    startsInFlight.delete(inFlight)
819    settle()
820  }
821}
822
823/** Standing idle and the small moments he plays there: time spent across them counts toward falling asleep. */
824const isIdling = (pose: MascotPose) => pose === 'idle' || pose === 'yawn' || IDLE_MOMENTS.includes(pose)
825
826/**
827 * Shows `pose`, playing its transition from the pose before first; `rest` is the pose a moment pose (ONE_SHOT_MS)
828 * gives way to. Showing the pose already up only changes what it gives way to. `isSoft` lets a moment playing finish
829 * first: `pose` then becomes what it gives way to.
830 */
831async function showMascot($: EngineInterface, pose: MascotPose, rest: MascotPose = pose, isSoft = false): Promise<void> {
832  if (!(await isMascotOn($))) {
833    return
834  }
835  const now = await $.clock.now()
836  // Checked inside the update, so two calls at once (parallel tool calls) change the pose once.
837  let isChanged = false
838  const shown = await update($, mascot, m => {
839    if (isSoft && m.pose !== pose && ONE_SHOT_MS[m.pose] !== undefined) {
840      return { ...m, rest: pose }
841    }
842    isChanged = m.pose !== pose
843    const since = isIdling(pose) && isIdling(m.pose) ? m.since : now
844    return isChanged ? { pose, rest, from: m.pose, change: m.change + 1, seq: m.seq + 1, since } : { ...m, rest }
845  })
846  if (!isChanged) {
847    return
848  }
849  const { change } = shown
850  // Once the intro has played the source drops it, so a redraw can only ever restart the loop.
851  const intro = introMs(pose, shown.from)
852  $.clock.after(intro, () => void settleMascot($, change))
853  const hold = ONE_SHOT_MS[pose]
854  if (hold !== undefined) {
855    $.clock.after(intro + hold, () => void endMoment($, change))
856  }
857}
858
859/** Drops the played intro from the mascot's source, unless the pose changed since. */
860async function settleMascot($: EngineInterface, change: number): Promise<void> {
861  await update($, mascot, m => (m.change === change && m.from !== null ? { ...m, from: null, seq: m.seq + 1 } : m))
862}
863
864/** A moment pose that is still up gives way to the pose underneath it. */
865async function endMoment($: EngineInterface, change: number): Promise<void> {
866  const shown = await read($, mascot)
867  if (shown.change === change) {
868    await showMascot($, shown.rest)
869  }
870}
871
872/**
873 * The pose underneath when no turn runs: waiting while a question dialog is open, puzzled while an answer's question
874 * waits on the person, standing otherwise.
875 */
876async function restingPose($: EngineInterface): Promise<MascotPose> {
877  if ((await read($, asking)) > 0) {
878    return 'waiting'
879  }
880  return (await read($, isQuestionOpen)) ? 'puzzled' : 'idle'
881}
882
883/** The pose underneath right now: typing through a turn, else at rest. */
884async function underneath($: EngineInterface): Promise<MascotPose> {
885  return isTurnRunning ? 'working' : await restingPose($)
886}
887
888/**
889 * Where the mascot should be when he is turned on: his poses were not followed while he was off, so the question
890 * left open is read back from the conversation.
891 */
892async function syncMascot($: EngineInterface): Promise<void> {
893  const isAsked = isQuestionOpenIn(await $.session.messages().catch(() => []))
894  await update($, isQuestionOpen, () => isAsked)
895  await showMascot($, await underneath($))
896}
897
898/**
899 * Passes the main chat's response through, the mascot following it: thinking while it streams thinking, typing again
900 * once it writes or calls a tool. Only a change of kind moves him, and a moment playing finishes first.
901 */
902async function* followStream<C extends { kind: string }, R>($: EngineInterface, stream: AsyncGenerator<C, R>): AsyncGenerator<C, R> {
903  let kind = ''
904  try {
905    for (;;) {
906      const piece = await stream.next()
907      if (piece.done) {
908        return piece.value
909      }
910      if (piece.value.kind !== kind && piece.value.kind !== 'engine') {
911        kind = piece.value.kind
912        if (kind === 'thinking' && toolPoses.length === 0 && (await read($, asking)) === 0) {
913          await showMascot($, 'thinking', 'working', true)
914        } else if (kind !== 'thinking' && (await read($, mascot)).pose === 'thinking') {
915          await showMascot($, 'working', 'working', true)
916        } else if (kind !== 'thinking' && (await read($, mascot)).rest === 'thinking') {
917          await update($, mascot, (m): MascotState => ({ ...m, rest: 'working' }))
918        }
919      }
920      yield piece.value
921    }
922  } finally {
923    await stream.return(undefined as R)
924  }
925}
926
927/** Standing idle long enough, the mascot sits down and falls asleep; the person's next prompt wakes him. */
928async function checkSleep($: EngineInterface): Promise<void> {
929  const shown = await read($, mascot)
930  if (shown.pose === 'idle' && (await $.clock.now()) - shown.since >= SLEEP_AFTER_MS && (await isMascotOn($))) {
931    await showMascot($, 'sleeping')
932  }
933}
934
935/**
936 * Now and then a moment: standing idle, the next idle moment in turn (a yawn in his last minute awake); typing
937 * through a long turn, a sip of coffee, or past three times as long a wipe of his brow.
938 */
939async function checkMoment($: EngineInterface): Promise<void> {
940  const shown = await read($, mascot)
941  const now = await $.clock.now()
942  if (shown.pose === 'idle') {
943    const idleFor = now - shown.since
944    if (idleFor >= IDLE_MOMENT_MS && now - idleMomentAt >= IDLE_MOMENT_MS && (await isMascotOn($))) {
945      idleMomentAt = now
946      const moment = idleFor >= SLEEP_AFTER_MS - IDLE_MOMENT_MS ? 'yawn' : IDLE_MOMENTS[idleMoments++ % IDLE_MOMENTS.length]!
947      await showMascot($, moment, 'idle')
948    }
949  } else if (shown.pose === 'working' && isTurnRunning) {
950    const runFor = now - turnStartedAt
951    if (runFor >= LONG_TURN_MS && now - longMomentAt >= LONG_TURN_MOMENT_MS && (await isMascotOn($))) {
952      longMomentAt = now
953      await showMascot($, runFor >= LONG_TURN_MS * 3 ? 'brow' : 'coffee', 'working')
954    }
955  }
956}
957
958/** Draws nothing in a transcript row's place: how Clean View hides tool calls and in-progress replies. */
959function drawNothing($: EngineInterface, e: Parameters<EngineInterface['ui']['resolve']>[0]) {
960  const { Box } = $.ui.resolve(e)
961
962  return <Box key="aitools-hidden" display="none" />
963}
964
965/** Opens or closes the 🛠 menu above the bar. */
966async function toggleMenu($: EngineInterface): Promise<void> {
967  await update($, isToolsOpen, open => !open)
968}
969
970/** ⁝: opens the AI Tool Settings pane, both files read first so it shows them as they stand, or closes it. */
971async function toggleSettingsPane($: EngineInterface): Promise<void> {
972  await update($, isToolsOpen, () => false)
973  if (await read($, isSettingsOpen)) {
974    await update($, isSettingsOpen, () => false)
975    await $.ui.close({ id: SETTINGS_PANE })
976    return
977  }
978  await reloadConfigs($)
979  await update($, settingsNote, () => null)
980  await update($, isSettingsOpen, () => true)
981  await $.ui.open({ id: SETTINGS_PANE, title: SETTINGS_TITLE })
982}
983
984/**
985 * The settings pane's project fields, written to the project file the row reads (the checkout's when there is none
986 * yet), keeping everything else in it; then read back, so the row and the pane follow. A refused URL or a file that
987 * can't be read or written says why in the pane instead.
988 */
989async function saveProject($: EngineInterface, change: ProjectChange): Promise<void> {
990  const repo = await read($, githubRepo)
991  if (repo === null) {
992    return
993  }
994  const fail = (text: string) => update($, settingsNote, () => ({ text, isError: true }))
995  const problem = typeof change.board === 'string' ? boardProblem(change.board) : null
996  if (problem !== null) {
997    await fail(problem)
998    return
999  }
1000  const path = projectPath ?? `${repo.checkout}/.claude/${CONFIG_FILE}`
1001  const text = await readText($, path)
1002  let raw: Json = {}
1003  if (text !== null) {
1004    const parsed = parseConfig(text)
1005    if ('error' in parsed) {
1006      await fail(`${path} isn't valid JSON (${parsed.error}), so it was left as it is.`)
1007      return
1008    }
1009    raw = parsed.value
1010  }
1011  try {
1012    await $.fs.write(path, configText(withProject(raw, change)))
1013  } catch (err) {
1014    await fail(`Couldn't save ${path}: ${errorText(err)}`)
1015    return
1016  }
1017  await update($, settingsNote, () => null)
1018  await loadProject($)
1019}
1020
1021/** Every 30 s: countdowns redraw while the bar shows; the mascot may fall asleep. */
1022async function onTick($: EngineInterface): Promise<void> {
1023  if (!(await read($, isHidden))) {
1024    await update($, tick, n => (n ?? 0) + 1)
1025  }
1026  await checkSleep($)
1027  await checkMoment($)
1028  // The config files may have been edited by hand, and the branch changed in a terminal.
1029  await reloadConfigs($)
1030  await refreshRepo($)
1031}
1032
1033/** The mascot drawing last built: it only changes with the pose, so redraws of the bar reuse it. */
1034let lastMascot: { state: MascotState; drawing: ReturnType<typeof mascotDrawing> } | null = null
1035
1036function drawMascot(state: MascotState): ReturnType<typeof mascotDrawing> {
1037  if (lastMascot?.state.pose !== state.pose || lastMascot.state.from !== state.from || lastMascot.state.seq !== state.seq) {
1038    lastMascot = { state, drawing: mascotDrawing(state) }
1039  }
1040
1041  return lastMascot.drawing
1042}
1043
1044/** Where a session's /keepwarm window is kept, so a restart of the session picks it up again. */
1045const keepWarmKey = (sessionId: string) => `keepWarm:${sessionId}`
1046
1047/**
1048 * Sets /keepwarm's one timer: its next ping, KEEPWARM_LEAD_MS before the cache lapses, or, with no ping due (no request
1049 * yet, the cache already cold, or warm past the window), the window's end. Run again after every main turn and ping.
1050 */
1051async function armKeepWarm($: EngineInterface): Promise<void> {
1052  keepWarmTimer?.cancel()
1053  keepWarmTimer = null
1054  const kw = await read($, keepWarm)
1055  if (kw === null) {
1056    return
1057  }
1058  const now = await $.clock.now()
1059  if (now >= kw.until) {
1060    await stopKeepWarm($, null)
1061    return
1062  }
1063  const delay = pingDelay(now, await read($, cacheAt), kw.until)
1064  keepWarmTimer =
1065    delay === null
1066      ? $.clock.after(kw.until - now, () => void armKeepWarm($))
1067      : $.clock.after(delay, () => void pingCache($))
1068}
1069
1070/** Ends /keepwarm: on time or turned off (`why` null), or early, with the reason /keepwarm status gives. */
1071async function stopKeepWarm($: EngineInterface, why: string | null): Promise<void> {
1072  keepWarmTimer?.cancel()
1073  keepWarmTimer = null
1074  await update($, keepWarm, () => null)
1075  await update($, keepWarmStopped, () => why)
1076  await $.store.delete(keepWarmKey(await $.session.id())).catch(() => undefined)
1077  if (why !== null) {
1078    $.ui.log(`aitools: keepwarm stopped: ${why}`)
1079  }
1080}
1081
1082/**
1083 * One keepwarm ping: a request over the conversation as the main thread last sent it (`$.model.fork`), which the API
1084 * serves from the cache, restarting its hour. Its readback must show a read of the prefix; anything else stops the
1085 * window, since the cache is gone and pinging on would pay a write every hour.
1086 */
1087async function pingCache($: EngineInterface): Promise<void> {
1088  keepWarmTimer = null
1089  const kw = await read($, keepWarm)
1090  const at = await read($, cacheAt)
1091  const now = await $.clock.now()
1092  // A turn's own requests keep the cache warm, and its end sets the timer again; a request since the timer was set
1093  // has moved the ping later.
1094  if (kw === null || isTurnRunning || at === null || now < at + CACHE_TTL - KEEPWARM_LEAD_MS - 1000) {
1095    if (!isTurnRunning) await armKeepWarm($)
1096    return
1097  }
1098  if (now >= kw.until || now >= at + CACHE_TTL) {
1099    await armKeepWarm($)
1100    return
1101  }
1102  let reply: Awaited<ReturnType<EngineInterface['model']['fork']>>
1103  try {
1104    reply = await $.model.fork({ prompt: KEEPWARM_PROMPT })
1105  } catch (err) {
1106    await stopKeepWarm($, `the ping failed: ${errorText(err)}`)
1107    return
1108  }
1109  if (!reply.isAnswered) {
1110    await stopKeepWarm($, failureText(reply.reason, 'status' in reply ? reply.status : null))
1111    return
1112  }
1113  if (!isWarmReadback(reply.usage)) {
1114    await stopKeepWarm($, coldPingText(reply.usage))
1115    return
1116  }
1117  const model = await read($, mainModel)
1118  const cost = model === null ? null : price(model, reply.usage)
1119  const pinged = await $.clock.now()
1120  const receipt = { at: pinged, read: reply.usage.cache_read_input_tokens, usd: cost?.usd ?? null, isEstimate: cost?.isEstimate ?? false }
1121  await update($, cacheAt, () => pinged)
1122  await rememberCacheAt($, pinged).catch(() => undefined)
1123  await update($, keepWarm, k => (k === null ? k : { ...k, lastPing: receipt }))
1124  await armKeepWarm($)
1125}
1126
1127/** `/keepwarm [6h|90m|off|status]`: starts (6 hours bare), ends or reports keeping the cache warm. */
1128async function keepWarmCommand($: EngineInterface, args: string): Promise<{ text: string }> {
1129  const asked = parseKeepWarm(args)
1130  if (asked === null || asked.kind === 'help') {
1131    return { text: KEEPWARM_HELP }
1132  }
1133  if (asked.kind === 'stop') {
1134    const wasOn = (await read($, keepWarm)) !== null
1135    await stopKeepWarm($, null)
1136    return { text: wasOn ? 'Keepwarm stopped: the cache lapses an hour after the last request.' : 'Keepwarm is already off.' }
1137  }
1138  // One reading of the clock, so `/keepwarm 5h` reports 5h0m, not the 4h59m a later reading would floor to.
1139  const now = await $.clock.now()
1140  if (asked.kind === 'start') {
1141    const until = now + asked.ms
1142    await update($, keepWarm, () => ({ until, lastPing: null }))
1143    await update($, keepWarmStopped, () => null)
1144    await $.store.set(keepWarmKey(await $.session.id()), until)
1145    await armKeepWarm($)
1146  }
1147
1148  return { text: keepWarmStatus(await read($, keepWarm), await read($, keepWarmStopped), await read($, cacheAt), now) }
1149}
1150
1151/** On load: a window this session saved (before a restart) comes back, and the timer is set again either way. */
1152async function restoreKeepWarm($: EngineInterface): Promise<void> {
1153  if ((await read($, keepWarm)) === null) {
1154    const saved = await $.store.get(keepWarmKey(await $.session.id()))
1155    if (typeof saved === 'number' && saved > (await $.clock.now())) {
1156      await update($, keepWarm, () => ({ until: saved, lastPing: null }))
1157    }
1158  }
1159  await armKeepWarm($)
1160}
1161
1162/**
1163 * The bar's ? button: /askme's prompt sent as the person's, or, while a turn runs or when the prompt cannot be sent,
1164 * `/askme` put in the prompt box ahead of any draft (which then rides along as its note) to send by hand. When the box
1165 * cannot take it either, the button stays.
1166 */
1167async function askFromBar($: EngineInterface, isWorking: boolean): Promise<void> {
1168  await update($, isAskable, () => false)
1169  if (!isWorking) {
1170    const sent = await $.prompt.submit({ text: askmeText(''), asUser: true }).catch(() => null)
1171    if (sent !== null && sent.drop === undefined) {
1172      return
1173    }
1174  }
1175  const draft = (await $.prompt.read()).text.trim()
1176  const filled = await $.prompt.fill({ text: draft === '' ? '/askme' : `/askme ${draft}` }).catch(() => null)
1177  if (!filled?.isFilled) {
1178    await update($, isAskable, () => true)
1179  }
1180}
1181
1182/** The bar, with the 🛠 or ⁝ menu above it while one is open, for the AbovePrompt band. */
1183async function drawBar($: EngineInterface, el: Parameters<typeof renderBar>[0], isWorking: boolean) {
1184  await read($, tick)
1185  const current = normalizeSettings(await read($, settings))
1186
1187  const view = {
1188    snapshot: await read($, snapshot),
1189    month: await read($, month),
1190    projection: await read($, projection),
1191    cacheAt: await read($, cacheAt),
1192    model: await read($, mainModel),
1193    settings: current,
1194    now: await $.clock.now(),
1195  }
1196  const flags = {
1197    isWorking,
1198    isHandingOff: await read($, isHandingOff),
1199    isToolsOpen: await read($, isToolsOpen),
1200    isAskable: await read($, isAskable),
src/agentdock.tsx 407 lines
1import type { Elements } from 'claude-code'
2
3import type { AgentCard, AgentKind, AgentRun, AgentShowing, HideAfter } from '../types'
4import { progressBar } from './checklist'
5import { renderPick } from './picks'
6import { NOTE_SHRINK, ago, elapsed } from './format'
7import { BLUE, DOING_TEXT, FAINT_TEXT, RED } from './palette'
8import { TOTEM_HEIGHT, TOTEM_WIDTH, totemAlt, totemSvg } from './totem'
9
10/** How many finished tasks the pane keeps listing, newest first out of view last. */
11export const FINISHED_KEEP = 50
12/** The Showing picks, in order: every kind, then each kind on its own. */
13export const SHOWING_PICKS = ['all', 'subagent', 'workflow', 'monitor'] as const
14export const SHOWING_LABELS = {
15  all: 'All',
16  subagent: 'Subagents',
17  workflow: 'Workflows',
18  monitor: 'Monitors',
19} as const
20/** What the pane says while the Showing pick leaves it no lines. */
21export const EMPTY_LABELS = {
22  all: 'Background tasks will appear here when started.',
23  subagent: 'Subagents will appear here when started.',
24  workflow: 'Workflow agents will appear here when started.',
25  monitor: 'Monitors will appear here when started.',
26} as const
27/** Each line's type column. */
28export const KIND_LABELS = { subagent: 'Subagent', workflow: 'Workflow', monitor: 'Monitor' } as const
29/** The type column's width: its longest label and a space. */
30const KIND_WIDTH = 9
31/** The Hide after picks: never, then the longest wait to the shortest, in minutes. */
32export const HIDE_AFTER = ['never', 60, 15, 5, 0] as const
33export const DEFAULT_HIDE_AFTER: HideAfter = 'never'
34
35export function hideAfterLabel(minutes: HideAfter): string {
36  if (minutes === 'never') return 'Never'
37  if (minutes === 0) return 'Immediate'
38
39  return minutes % 60 === 0 ? `${minutes / 60}h` : `${minutes}m`
40}
41
42export function isShowing(value: unknown): value is AgentShowing {
43  return SHOWING_PICKS.some(pick => pick === value)
44}
45
46export function isHideAfter(value: unknown): value is HideAfter {
47  return HIDE_AFTER.some(m => m === value)
48}
49
50/** The lines the pane's picks leave: those of the kind Showing picks, and finished ones until Hide after's time is up. */
51export function visibleCards(
52  cards: readonly AgentCard[],
53  view: { showing: AgentShowing; hideAfter: HideAfter; now: number },
54): AgentCard[] {
55  return cards.filter(
56    c =>
57      (view.showing === 'all' || kindOf(c) === view.showing) &&
58      (c.status === 'running' || view.hideAfter === 'never' || view.now - (c.endedAt ?? view.now) < view.hideAfter * 60_000),
59  )
60}
61
62export const PROGRESS_TOOL = 'agent_progress'
63export const PROGRESS_TOOL_ID = 'mcp__aitools__agent_progress'
64export const DOCK_PANE = 'tasks'
65export const DOCK_TITLE = 'Background tasks'
66
67/** A line's kind; lines from before kinds existed were all subagents. */
68export function kindOf(card: AgentCard): AgentKind {
69  return card.kind ?? 'subagent'
70}
71
72export const PROGRESS_SPEC = {
73  name: PROGRESS_TOOL,
74  description:
75    'For a subagent listed in the Subagents pane: reports what you are doing and how far along your task is, shown on ' +
76    'your line in the pane. Call it when you start, about every quarter of your work, and at 100 when done.',
77  inputSchema: {
78    type: 'object',
79    properties: {
80      doing: { type: 'string', description: 'What you are doing now, in a few plain words' },
81      percent: { type: 'number', minimum: 0, maximum: 100, description: 'Your estimate of how far along your task is' },
82    },
83    required: ['doing', 'percent'],
84  },
85}
86
87/** How a subagent is asked to report, so its line can show a percent and bar. */
88const REPORT_ASK =
89  `Report progress with ${PROGRESS_TOOL_ID}: call it when you start with a few words on what you are doing and ` +
90  'percent 0, again about every quarter of your work, and with percent 100 when you finish.)'
91
92/** What a subagent's prompt gains while the pane is open, so its line can show progress. */
93export const SUBAGENT_NOTE = `\n\n(Your work shows as a line in the person's Subagents pane. ${REPORT_ASK}`
94
95export function newRun(now: number): AgentRun {
96  return { startedAt: now, cards: [] }
97}
98
99/** The run with a started task's line, once; `extra` adds what its kind knows from the start (a note, a deadline). */
100export function addCard(
101  run: AgentRun,
102  id: string,
103  task: string,
104  now: number,
105  kind: AgentKind = 'subagent',
106  extra: Pick<AgentCard, 'doing' | 'expiresAt'> = {},
107): AgentRun {
108  if (run.cards.some(c => c.id === id)) {
109    return run
110  }
111  const card: AgentCard = { id, task, kind, ...extra, status: 'running', startedAt: now }
112
113  return { ...run, cards: [...run.cards, card] }
114}
115
116/** The run with a subagent's latest activity on its line. */
117export function noteActivity(run: AgentRun, id: string, doing: string): AgentRun {
118  return { ...run, cards: run.cards.map(c => (c.id === id ? { ...c, doing } : c)) }
119}
120
121/** The last part of a path: what a line names a file by. */
122function baseName(path: unknown): string {
123  return typeof path === 'string' ? (path.split('/').filter(Boolean).at(-1) ?? path) : ''
124}
125
126/** Text on one line, cut to `n` characters with `…`; anything but a string is empty. */
127export function clip(text: unknown, n = 40): string {
128  const one = typeof text === 'string' ? text.replace(/\s+/g, ' ').trim() : ''
129  return one.length > n ? `${one.slice(0, n - 1)}…` : one
130}
131
132/** A short line on what a tool call does, for a subagent's line: `Reading bar.tsx`, `Running npm test`. */
133export function activityText(tool: string, input: Record<string, unknown>): string {
134  switch (tool) {
135    case 'Read':
136      return `Reading ${baseName(input.file_path)}`
137    case 'Edit':
138    case 'MultiEdit':
139    case 'NotebookEdit':
140      return `Editing ${baseName(input.file_path ?? input.notebook_path)}`
141    case 'Write':
142      return `Writing ${baseName(input.file_path)}`
143    case 'Bash':
144      return `Running ${clip(input.command)}`
145    case 'Grep':
146      return `Searching for ${clip(input.pattern, 30)}`
147    case 'Glob':
148      return `Finding ${clip(input.pattern, 30)}`
149    case 'WebFetch':
150      return `Fetching ${clip(typeof input.url === 'string' ? input.url.replace(/^https?:\/\//, '') : '', 30)}`
151    case 'WebSearch':
152      return `Searching the web for ${clip(input.query, 30)}`
153    case 'Agent':
154      return `Starting ${clip(input.description, 30) || 'a subagent'}`
155    default:
156      return `Using ${tool.replace(/^mcp__[^_]+__/, '')}`
157  }
158}
159
160/** A workflow's name, for its agents' lines: the tool's `name`, else its script's `meta` name. */
161export function workflowName(input: Record<string, unknown>): string {
162  if (typeof input.name === 'string' && input.name) {
163    return input.name
164  }
165  const script = typeof input.script === 'string' ? input.script : ''
166
167  return /\bname\s*:\s*['"`]([^'"`]+)['"`]/.exec(script)?.[1] ?? 'workflow'
168}
169
170/** One background task's notice, as the chat receives it: its id, and its status or event when it gives one. */
171export type TaskNotice = { id: string; status?: string; event?: string }
172
173/** The task notices in a prompt's text: `<task-notification>` blocks, each naming its task. */
174export function parseTaskNotices(text: string): TaskNotice[] {
175  const notices: TaskNotice[] = []
176  for (const [, body = ''] of text.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)) {
177    const tag = (name: string) => new RegExp(`<${name}>([\\s\\S]*?)</${name}>`).exec(body)?.[1]?.trim()
178    const id = tag('task-id')
179    if (id) notices.push({ id, status: tag('status'), event: tag('event') })
180  }
181
182  return notices
183}
184
185/**
186 * How a notice says its task ended, or null when it does not (a monitor's ordinary event): a status of completed,
187 * failed, or killed or stopped; a monitor's own closing event (`[Monitor expired after 30m ...]`).
188 */
189export function noticeEnd(notice: TaskNotice): EndStatus | null {
190  switch (notice.status) {
191    case 'completed':
192      return 'done'
193    case 'failed':
194      return 'failed'
195    case 'killed':
196    case 'stopped':
197      return 'stopped'
198  }
199
200  return notice.event?.startsWith('[Monitor ') ? 'done' : null
201}
202
203/** The run with one subagent's reported progress; a percent is rounded and held to 0 to 100. */
204export function reportProgress(run: AgentRun, id: string, doing: string, percent: number): AgentRun {
205  const pct = Math.min(100, Math.max(0, Math.round(Number.isFinite(percent) ? percent : 0)))
206
207  const report = (c: AgentCard): AgentCard => ({ ...c, doing: doing.trim() || c.doing, percent: pct })
208
209  return { ...run, cards: run.cards.map(c => (c.id === id ? report(c) : c)) }
210}
211
212/** How a finished task ended. */
213export type EndStatus = Exclude<AgentCard['status'], 'running'>
214
215/** The run with a task finished, as `status` says; a line already finished keeps how it ended. */
216export function finishCard(run: AgentRun, id: string, status: EndStatus, now: number): AgentRun {
217  if (!run.cards.some(c => c.id === id && c.status === 'running')) {
218    return run
219  }
220  const cards = run.cards.map((c): AgentCard => (c.id === id ? { ...c, status, endedAt: now } : c))
221  // Finished lines stay for the session, the newest FINISHED_KEEP of them.
222  const finished = cards.filter(c => c.status !== 'running').sort((a, b) => (b.endedAt ?? 0) - (a.endedAt ?? 0))
223  const dropped = new Set(finished.slice(FINISHED_KEEP).map(c => c.id))
224
225  return { ...run, cards: cards.filter(c => !dropped.has(c.id)) }
226}
227
228export function isRunning(run: AgentRun | null): boolean {
229  return run !== null && run.cards.some(c => c.status === 'running')
230}
231
232/** How many tasks are running: what the project row's button counts. */
233export function runningCount(run: AgentRun | null): number {
234  return run?.cards.filter(c => c.status === 'running').length ?? 0
235}
236
237/** The project row's button: `1 bg task`, `5 bg tasks` (background tasks, as Claude Code calls them). */
238export function tasksLabel(n: number): string {
239  return n === 1 ? '1 bg task' : `${n} bg tasks`
240}
241
242/** The pane's header line: the non-zero counts. */
243export function headerText(run: AgentRun | null): string {
244  const cards = run?.cards ?? []
245  const counts: [number, string][] = [
246    [cards.filter(c => c.status === 'running').length, 'running'],
247    [cards.filter(c => c.status === 'done').length, 'done'],
248    [cards.filter(c => c.status === 'failed').length, 'failed'],
249    [cards.filter(c => c.status === 'stopped').length, 'stopped'],
250  ]
251
252  return counts.filter(([n]) => n > 0).map(([n, label]) => `${n} ${label}`).join(' · ')
253}
254
255/** `Svg` only where the surface draws it (the desktop): the totem shows there alone. */
256type El = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'> & { Svg?: Elements['desktop']['Svg'] }
257
258const QUIET = { plain: true, dimColor: true } as const
259/** Task View's marks: ● running in blue, ✓ done (dim, as the rest of a finished line); × failed (red) or stopped. */
260const CARD_MARKS = { running: '●', done: '✓', failed: '×', stopped: '×' } as const
261
262/** The run's lines in order: running ones (oldest first), then finished ones, the most recently finished first. */
263export function orderedCards(run: AgentRun): AgentCard[] {
264  const running = run.cards.filter(c => c.status === 'running').sort((a, b) => a.startedAt - b.startedAt)
265  const finished = run.cards.filter(c => c.status !== 'running').sort((a, b) => (b.endedAt ?? 0) - (a.endedAt ?? 0))
266
267  return [...running, ...finished]
268}
269
270/**
271 * The Background tasks pane: controls on top, then the header (or what will appear when nothing is listed) and a
272 * line per task. Where SVG is drawn, the totem stands left of the controls, the header beside it too.
273 */
274export function renderDock(
275  el: El,
276  dock: {
277    showing: AgentShowing
278    hideAfter: HideAfter
279    run: AgentRun | null
280    now: number
281  },
282  on: {
283    setShowing(showing: AgentShowing): void
284    setHideAfter(minutes: HideAfter): void
285  },
286) {
287  const { Box, Text, Svg } = el
288  const { showing, run, now } = dock
289  const shown = run === null ? null : { ...run, cards: visibleCards(run.cards, { ...dock, now }) }
290  const isEmpty = shown === null || shown.cards.length === 0
291  const running = shown?.cards.filter(c => c.status === 'running').length ?? 0
292
293  return (
294    <Box flexDirection="column">
295      <Box flexDirection="row">
296        {Svg && (
297          <Box key="totem" flexShrink={0} marginRight={2}>
298            <Svg source={totemSvg(running)} alt={totemAlt(running)} width={TOTEM_WIDTH} height={TOTEM_HEIGHT} />
299          </Box>
300        )}
301        <Box flexDirection="column" flexShrink={1} gap={1}>
302          {renderControls(el, dock, on)}
303          <Text dimColor>{isEmpty ? EMPTY_LABELS[showing] : headerText(shown)}</Text>
304        </Box>
305      </Box>
306      {/* A blank line under the header, then the tasks running and the finished ones, the latest first. */}
307      {shown !== null && shown.cards.length > 0 && (
308        <Box flexDirection="column" marginTop={1}>
309          {orderedCards(shown).map(card => renderCard(el, card, now))}
310        </Box>
311      )}
312    </Box>
313  )
314}
315
316/** The pane's two option rows: Showing and Hide after. */
317function renderControls(
318  el: El,
319  dock: { showing: AgentShowing; hideAfter: HideAfter },
320  on: {
321    setShowing(showing: AgentShowing): void
322    setHideAfter(minutes: HideAfter): void
323  },
324) {
325  const { Box, Text } = el
326  const { showing, hideAfter } = dock
327
328  return (
329    <Box flexDirection="column">
330      <Box flexDirection="row" columnGap={1}>
331        <Text dimColor>Showing:</Text>
332        {SHOWING_PICKS.map(pick => (
333          renderPick(el, `showing-${pick}`, SHOWING_LABELS[pick], showing === pick, () => on.setShowing(pick))
334        ))}
335      </Box>
336      <Box flexDirection="row" columnGap={1}>
337        <Text dimColor>Hide after:</Text>
338        {HIDE_AFTER.map(minutes => (
339          renderPick(el, `hide-${minutes}`, hideAfterLabel(minutes), hideAfter === minutes, () => on.setHideAfter(minutes))
340        ))}
341      </Box>
342    </Box>
343  )
344}
345
346/**
347 * One task's row: its mark, its type column, then its name. Running: a blue ●, the name in the half-dim grey and what
348 * it is doing faint, then (once a subagent reports progress) its percent and bar, and its time so far. Finished: all
349 * faint (a failed one's × red), and its time with how long ago it finished: `0:09 (3m ago)`.
350 */
351function renderCard(el: El, card: AgentCard, now: number) {
352  const { Box, Text } = el
353  const time = elapsed((card.endedAt ?? now) - card.startedAt)
354  if (card.status !== 'running') {
355    return (
356      <Box key={`agent-${card.id}`} flexDirection="row" justifyContent="space-between">
357        <Box flexDirection="row" flexShrink={1} minWidth={0} overflow="hidden">
358          <Text color={card.status === 'failed' ? RED : FAINT_TEXT}>{`${CARD_MARKS[card.status]} `}</Text>
359          <Text color={FAINT_TEXT}>{KIND_LABELS[kindOf(card)].padEnd(KIND_WIDTH)}</Text>
360          <Box flexShrink={1} minWidth={0} overflow="hidden">
361            <Text color={FAINT_TEXT} wrap="truncate-end">
362              {card.task}
363            </Text>
364          </Box>
365        </Box>
366        <Text color={FAINT_TEXT}>{` ${time} (${ago(now - (card.endedAt ?? now))})`}</Text>
367      </Box>
368    )
369  }
370  const percent = card.percent ?? 0
371  const bar = progressBar(percent)
372  const isMeasured = card.percent !== undefined
373
374  return (
375    <Box key={`agent-${card.id}`} flexDirection="row" justifyContent="space-between">
376      <Box flexDirection="row" flexShrink={1} minWidth={0} overflow="hidden">
377        <Text color={BLUE}>{`${CARD_MARKS.running} `}</Text>
378        <Text dimColor>{KIND_LABELS[kindOf(card)].padEnd(KIND_WIDTH)}</Text>
379        <Box flexShrink={1} minWidth={0} overflow="hidden">
380          <Text color={DOING_TEXT} wrap="truncate-end">
381            {card.task}
382          </Text>
383        </Box>
384        {card.doing && (
385          <Box flexShrink={NOTE_SHRINK} minWidth={0} overflow="hidden">
386            <Text color={FAINT_TEXT} wrap="truncate-end">
387              {` · ${card.doing}`}
388            </Text>
389          </Box>
390        )}
391      </Box>
392      <Box flexDirection="row" flexShrink={0}>
393        {isMeasured ? (
394          <Box flexDirection="row">
395            <Text dimColor>{` ${String(percent).padStart(3)}% `}</Text>
396            <Text color={BLUE}>{bar.filled}</Text>
397            <Text dimColor>{bar.empty}</Text>
398          </Box>
399        ) : (
400          <Text>{' '.repeat(6 + bar.filled.length + bar.empty.length)}</Text>
401        )}
402        <Text dimColor>{` ${time.padStart(5)}`}</Text>
403      </Box>
404    </Box>
405  )
406}
407
src/bar.tsx 360 lines
1import type { Elements, RenderChildren } from 'claude-code'
2
3import { clockTime, duration, tokens, usd, weeklyReset } from './format'
4import { coldCacheUsd } from './pricing'
5import { usdSince } from './transcripts'
6import { VIEW_NAMES } from './checklist'
7import type { renderChecklist } from './checklist'
8import { MASCOT_HEIGHT, MASCOT_WIDTH } from './mascot'
9import { DOING_TEXT, RED, YELLOW } from './palette'
10import type { LimitWindow, MonthTotal, Settings, Snapshot } from '../types'
11
12export type View = {
13  snapshot: Snapshot | null
14  month: MonthTotal
15  projection: number | null
16  /** Start of the last main-thread model request, or null before one. */
17  cacheAt: number | null
18  /** The main chat's model, or null before its first request. */
19  model: string | null
20  settings: Settings
21  now: number
22}
23
24export type Tone = 'warn' | 'danger' | undefined
25
26/** One metric: `text` is the whole of it, `label` the leading word(s) naming it, drawn dimmer than the value after. */
27export type Segment = { key: string; label: string; text: string; tone?: Tone }
28
29export const SEPARATOR = '    '
30/** Names the mod at the start of the bar; the `label` toggle hides it. */
31export const LABEL = 'AI Tools'
32
33/** Claude Code writes the main conversation's prompt cache with the 1-hour TTL; each request restarts it. */
34export const CACHE_TTL = 60 * 60_000
35
36/** The bar's marker while /keepwarm runs: a sun with rays (U+263C), which has no color-emoji form. */
37export const KEEPWARM_MARK = '\u263C'
38
39const DASH = '-'
40const MIN = 60_000
41const CACHE_WARN = 10 * MIN
42const TONE_COLORS = { warn: YELLOW, danger: RED } as const
43/** Values in the checklist's half-dim grey: brighter than their dim labels, quieter than full text. */
44const VALUE_COLOR = DOING_TEXT
45
46export function toneFor(pct: number | undefined, settings: Settings): Tone {
47  if (!settings.thresholdColors || pct === undefined) {
48    return undefined
49  }
50
51  return pct >= 90 ? 'danger' : pct >= 70 ? 'warn' : undefined
52}
53
54/** What a cold cache costs the next request over a warm one, priced at the chat's model; null while unknown. */
55function coldCost(view: View): string | null {
56  const tokens = view.snapshot?.context?.tokens
57  const cost = tokens === undefined || view.model === null ? null : coldCacheUsd(view.model, tokens)
58
59  return cost === null ? null : usd(cost.usd, cost.isEstimate)
60}
61
62/**
63 * The cache segment: how long the cache stays warm, then (with Cold-cache cost on) what letting it lapse costs:
64 * `cache 42m, $0.50`, `cache cold, $0.50`. Cold-cache cost alone reads `cache $0.50`.
65 */
66function cacheSegment(view: View): Segment | null {
67  const { cacheAt, now, settings } = view
68  const cold = settings.coldCost ? coldCost(view) : null
69  if (!settings.cacheWarmth) {
70    return cold === null ? null : { key: 'cache', label: 'cache', text: `cache ${cold}` }
71  }
72  if (cacheAt === null) {
73    return { key: 'cache', label: 'cache', text: `cache ${DASH}${cold === null ? '' : `, ${cold}`}` }
74  }
75  const left = cacheAt + CACHE_TTL - now
76  const tone: Tone = !settings.thresholdColors ? undefined : left <= 0 ? 'danger' : left < CACHE_WARN ? 'warn' : undefined
77  const warmth = left <= 0 ? 'cache cold' : `cache ${Math.max(1, Math.ceil(left / MIN))}m`
78  const text = cold === null ? warmth : `${warmth}, ${cold}`
79
80  return { key: 'cache', label: 'cache', text, tone }
81}
82
83function monthText(month: MonthTotal): string {
84  if (month.status === 'loading') {
85    return 'month …'
86  }
87
88  return month.status === 'error' ? 'month ?' : `month ${usd(month.usd, month.isEstimate)}`
89}
90
91const WEEK_MS = 7 * 24 * 60 * 60_000
92
93/**
94 * What 1% of the weekly allowance costs at API prices, estimated: this machine's spend since the weekly window opened
95 * (its reset time less 7 days) over the weekly percent used. Null until both are known and above zero.
96 */
97export function usdPerWeeklyPercent(snapshot: Snapshot | null, month: MonthTotal): number | null {
98  const weekly = snapshot?.weekly
99  if (!weekly?.resetsAt || !(weekly.percentUsed > 0) || month.hours === undefined) {
100    return null
101  }
102  const spent = usdSince(month.hours, Date.parse(weekly.resetsAt) - WEEK_MS)
103
104  return spent > 0 ? spent / weekly.percentUsed : null
105}
106
107/** A share of the weekly allowance, with as many decimals as small shares need: `12%`, `2.1%`, `0.04%`, `<0.01%`. */
108export function percentText(pct: number): string {
109  if (pct < 0.01) {
110    return '<0.01%'
111  }
112
113  return `${pct >= 10 ? Math.round(pct) : pct >= 1 ? pct.toFixed(1) : pct.toFixed(2)}%`
114}
115
116/** The thread segment: its cost and the last turn's, each followed by its estimated share of the week when asked. */
117function threadSegment(view: View): Segment | null {
118  const { snapshot, settings: on } = view
119  const thread = snapshot?.threadUsd
120  const last = snapshot?.lastTurnUsd
121  const perPercent = on.threadPercent ? usdPerWeeklyPercent(snapshot, view.month) : null
122  const share = (spent: number | undefined) =>
123    perPercent === null || spent === undefined ? null : `~${percentText(spent / perPercent)}`
124  const threadShare = share(thread)
125  const lastShare = on.lastTurnCost ? share(last) : null
126
127  if (on.threadCost) {
128    const turn = on.lastTurnCost && last !== undefined ? ` (+${usd(last)})` : ''
129    const pct = threadShare === null ? '' : ` ${threadShare} wk${lastShare === null ? '' : ` (+${lastShare.slice(1)})`}`
130    return { key: 'thread', label: 'thread', text: `thread ${thread === undefined ? DASH : usd(thread)}${turn}${pct}` }
131  }
132  if (on.lastTurnCost) {
133    return { key: 'thread', label: 'last', text: `last ${last === undefined ? DASH : usd(last)}${lastShare === null ? '' : ` ${lastShare} wk`}` }
134  }
135  if (threadShare !== null) {
136    return { key: 'thread', label: 'thread', text: `thread ${threadShare} wk` }
137  }
138
139  return null
140}
141
142/** The token segment: the thread's total and the last turn's in parentheses, as the cost segment shows dollars. */
143function tokenSegment(snapshot: Snapshot | null, on: Settings): Segment {
144  const count = (n: number | undefined) => (n === undefined ? DASH : tokens(n))
145  if (on.threadTokens) {
146    const turn = on.lastTurnTokens && snapshot?.lastTurnTokens !== undefined ? ` (+${tokens(snapshot.lastTurnTokens)})` : ''
147    return { key: 'tokens', label: 'tok', text: `tok ${count(snapshot?.threadTokens)}${turn}` }
148  }
149
150  return { key: 'tokens', label: 'last tok', text: `last tok ${count(snapshot?.lastTurnTokens)}` }
151}
152
153export function segments(view: View): Segment[] {
154  const { snapshot, settings: on, now } = view
155  const segs: Segment[] = []
156  const fiveHour = snapshot?.fiveHour
157  const weekly = snapshot?.weekly
158  const context = snapshot?.context
159  const pct = (n: number | undefined) => (n === undefined ? DASH : `${Math.round(n)}%`)
160
161  // A limit's meter shows while its percent or its reset is on: `5h 42%, 1h12m`, `5h 42%`, `5h 1h12m`.
162  const limit = (window: LimitWindow | undefined, showPct: boolean, showReset: boolean, reset: (at: string) => string) => {
163    const parts = showPct ? [pct(window?.percentUsed)] : []
164    if (showReset && window?.resetsAt) parts.push(reset(window.resetsAt))
165    return parts.length > 0 ? parts.join(', ') : DASH
166  }
167  if (on.fiveHour || on.fiveHourReset) {
168    const text = limit(fiveHour, on.fiveHour, on.fiveHourReset, at => duration(Date.parse(at) - now))
169    segs.push({ key: 'fiveHour', label: '5h', text: `5h ${text}`, tone: toneFor(fiveHour?.percentUsed, on) })
170  }
171  if (on.weekly || on.weeklyReset) {
172    const text = limit(weekly, on.weekly, on.weeklyReset, at => weeklyReset(at, now))
173    segs.push({ key: 'weekly', label: 'wk', text: `wk ${text}`, tone: toneFor(weekly?.percentUsed, on) })
174  }
175  if (on.contextPercent || on.contextTokens) {
176    const parts: string[] = []
177    if (on.contextPercent) {
178      parts.push(pct(context?.percent))
179    }
180    if (on.contextTokens && context?.tokens !== undefined) {
181      parts.push(`${tokens(context.tokens)}/${tokens(context.window)}`)
182    } else if (on.contextTokens && !on.contextPercent) {
183      parts.push(DASH)
184    }
185    segs.push({ key: 'context', label: 'ctx', text: `ctx ${parts.join(' ')}`, tone: toneFor(context?.percent, on) })
186  }
187  if (on.threadTokens || on.lastTurnTokens) {
188    segs.push(tokenSegment(snapshot, on))
189  }
190  const cacheSeg = cacheSegment(view)
191  if (cacheSeg !== null) {
192    segs.push(cacheSeg)
193  }
194  const threadSeg = threadSegment(view)
195  if (threadSeg !== null) {
196    segs.push(threadSeg)
197  }
198  if (on.monthlyCost) {
199    segs.push({ key: 'month', label: 'month', text: monthText(view.month) })
200  }
201  if (on.burnRate && view.projection !== null) {
202    segs.push({ key: 'burn', label: 'limit', text: `limit ~${clockTime(view.projection)}` })
203  }
204
205  return segs
206}
207
208/** `Svg` only where the surface draws it (the desktop): the mascot and its option show there alone. */
209type El = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'> & { Svg?: Elements['desktop']['Svg'] }
210
211/** The 🛠 menu's view options, each turned on or off on its own. */
212const VIEWS = [
213  { view: 'task', label: VIEW_NAMES.task },
214  { view: 'clean', label: VIEW_NAMES.clean },
215] as const
216
217/** Quiet buttons, matching the other bands: dim text and no outline at rest, full strength under the pointer. */
218const QUIET = { plain: true, dimColor: true } as const
219
220/**
221 * The two menu buttons' labels. The terminal gets words: it lays a bare 🛠 out one column wide but paints it two,
222 * which pushes ⁝ under the icon's right half and both presses onto the icon.
223 */
224const MENU_LABELS = {
225  desktop: { tools: '🛠', settings: '⁝' },
226  terminal: { tools: 'tools', settings: 'opts' },
227} as const
228
229/** Room between neighboring buttons: the desktop's native chrome parts them, the terminal's plain words need spaces. */
230const BUTTON_GAP = { desktop: 0, terminal: 2 } as const
231
232export function renderBar(
233  el: El,
234  view: View,
235  flags: {
236    isWorking: boolean
237    isHandingOff: boolean
238    isToolsOpen: boolean
239    /** Whether Claude's last reply asks something it never put to the person as pop-up choices. */
240    isAskable: boolean
241    /** Whether /keepwarm is keeping the cache warm: the bar shows its marker. */
242    isKeepingWarm: boolean
243    isTaskView: boolean
244    isCleanView: boolean
245    /** Whether the session works in a GitHub repository: the 🛠 menu offers its Project pane. */
246    hasRepo: boolean
247    /** The mascot's drawing as it stands now. */
248    mascot: { source: string; alt: string } | null
249  },
250  on: {
251    toggleTools(): void
252    askme(): void
253    handoff(): void
254    openNotes(): void
255    toggleView(view: 'task' | 'clean'): void
256    openDock(): void
257    openBranches(): void
258    openProject(): void
259    /** ⁝: opens or closes the AI Tool Settings pane. */
260    toggleSettings(): void
261  },
262  /** The checklist, drawn between the bar and the project row; null while Task View is off or there is none. */
263  checklist: ReturnType<typeof renderChecklist> = null,
264  /** The project row, drawn right under the bar; null outside a GitHub repository. */
265  projectRow: RenderChildren | null = null,
266) {
267  const { Box, Text, Button, Svg } = el
268  const isHandoffIdle = !flags.isWorking && !flags.isHandingOff
269  const segs = segments(view)
270
271  const art = Svg && view.settings.mascot ? flags.mascot : null
272  const labels = Svg ? MENU_LABELS.desktop : MENU_LABELS.terminal
273  const gap = Svg ? BUTTON_GAP.desktop : BUTTON_GAP.terminal
274
275  // Segments wrap onto further rows when the band is narrow; the mascot and the buttons keep their places at the ends.
276  // Beside the mascot the row centers on him; without him the buttons stay on the first row of text.
277  const bar = (
278    <Box flexDirection="row" justifyContent="space-between" {...(art ? { alignItems: 'center' as const } : {})}>
279      {Svg && art && (
280        <Box key="mascot-art" flexShrink={0} marginRight={1}>
281          <Svg source={art.source} alt={art.alt} width={MASCOT_WIDTH} height={MASCOT_HEIGHT} />
282        </Box>
283      )}
284      <Box flexDirection="row" flexWrap="wrap" flexGrow={1} flexShrink={1}>
285        {view.settings.label && (
286          <Text key="label" dimColor>
287            {LABEL}
288            {segs.length > 0 ? SEPARATOR : ''}
289          </Text>
290        )}
291        {segs.map((s, i) => (
292          // Label and value in one row, so a narrow band wraps between metrics, never inside one.
293          <Box key={`segment-${s.key}`} flexDirection="row">
294            <Text dimColor>{`${s.label} `}</Text>
295            <Text color={s.tone ? TONE_COLORS[s.tone] : VALUE_COLOR}>
296              {s.text.slice(s.label.length + 1)}
297              {i < segs.length - 1 ? SEPARATOR : ''}
298            </Text>
299          </Box>
300        ))}
301      </Box>
302      <Box flexDirection="row" gap={gap} flexShrink={0}>
303        {flags.isAskable && <Button key="askme" label="?" {...QUIET} onPress={() => on.askme()} />}
304        {flags.isKeepingWarm && (
305          // On the desktop, room from ? only: the tools button's own chrome parts it from the mark.
306          <Box key="keepwarm" paddingLeft={Svg ? 1 : 0}>
307            <Text color={VALUE_COLOR}>{KEEPWARM_MARK}</Text>
308          </Box>
309        )}
310        <Button key="tools" label={labels.tools} {...QUIET} onPress={() => on.toggleTools()} />
311        <Button key="settings" label={labels.settings} {...QUIET} onPress={() => on.toggleSettings()} />
312      </Box>
313    </Box>
314  )
315
316  let menu = null
317  if (flags.isToolsOpen) {
318    menu = (
319      <Box flexDirection="row" justifyContent="flex-end" gap={gap}>
320        <Button
321          key="handoff"
322          label={flags.isHandingOff ? 'Handoff…' : 'Handoff'}
323          {...QUIET}
324          onPress={() => isHandoffIdle && on.handoff()}
325        />
326        <Button key="notes" label="Notes" {...QUIET} onPress={() => on.openNotes()} />
327        <Button key="tasks" label="Tasks" {...QUIET} onPress={() => on.openDock()} />
328        <Button key="branches" label="Branches" {...QUIET} onPress={() => on.openBranches()} />
329        {flags.hasRepo && <Button key="project" label="Project" {...QUIET} onPress={() => on.openProject()} />}
330        {VIEWS.map(v => {
331          const isOn = v.view === 'task' ? flags.isTaskView : flags.isCleanView
332
333          return <Button key={v.view} label={`${isOn ? '●' : '○'} ${v.label}`} {...QUIET} onPress={() => on.toggleView(v.view)} />
334        })}
335      </Box>
336    )
337  }
338  // The checklist sits between the bar and the project row. On the desktop the rows get a gap between them; the
339  // terminal keeps the bar and the project row on consecutive lines, with a blank line around the checklist.
340  const bars =
341    checklist === null && projectRow === null ? bar : (
342      <Box flexDirection="column" gap={Svg || checklist !== null ? 1 : 0}>
343        {bar}
344        {checklist}
345        {projectRow}
346      </Box>
347    )
348  if (!menu) {
349    return bars
350  }
351
352  // The open 🛠 menu sits above the bar, so the bar itself never shifts.
353  return (
354    <Box flexDirection="column" gap={1}>
355      {menu}
356      {bars}
357    </Box>
358  )
359}
360
src/board.tsx 388 lines
1/**
2 * The Project pane: the GitHub Project board's items, each with its id, title, Status and pull request, read with one
3 * GraphQL query at most every BOARD_REFRESH_MS while the pane is open or the project row shows the open count. A header links to the board and filters the
4 * items to the open ones, the done ones or all; where SVG is drawn, Clawd stacks task blocks at the top left.
5 */
6
7import type { Elements, RenderChildren } from 'claude-code'
8
9import { BLUE, DOING_TEXT, FAINT_TEXT, GREEN, RED, YELLOW } from './palette'
10import { TOWER_HEIGHT, TOWER_WIDTH, towerAlt, towerSvg } from './tower'
11import { age } from './branches'
12import type { BoardData, BoardFilter, BoardItem, BoardState, TowerMode } from '../types'
13
14export const PROJECT_PANE = 'project'
15
16/** How often the open pane reads the board, and how long a read stays fresh across closing and reopening it. */
17export const BOARD_REFRESH_MS = 5 * 60_000
18
19/** How many items a read keeps: GitHub's most for one page. */
20export const BOARD_PAGE = 100
21
22/** The Status names that mean done, as the board filter and isDone both read them. */
23export const DONE_STATUSES = ['Done', 'Closed', 'Complete', 'Completed', 'Finished', 'Shipped', 'Merged'] as const
24
25/** How far back a read looks for done items: the most recently changed are the ones worth listing. */
26export const DONE_WINDOW_DAYS = 30
27
28const ITEM_FIELDS =
29  'type updatedAt status:fieldValueByName(name:"Status"){... on ProjectV2ItemFieldSingleSelectValue{name}} ' +
30  'content{... on DraftIssue{title} ... on Issue{number title url state repository{nameWithOwner} ' +
31  'closedByPullRequestsReferences(first:3,includeClosedPrs:true){nodes{number url state}}} ' +
32  '... on PullRequest{number title url state repository{nameWithOwner}}}'
33
34/**
35 * The board in one query: its item count, its Status columns in order, up to BOARD_PAGE items not in a done column,
36 * and up to BOARD_PAGE done ones changed in the last DONE_WINDOW_DAYS days. GitHub sorts items only by their position
37 * on the board, so the query picks them by filter and the read sorts them (sortItems). `repositoryOwner` takes a
38 * user's login or an organization's, so either kind of board is one query.
39 */
40export const BOARD_QUERY =
41  'query($login:String!,$number:Int!){repositoryOwner(login:$login){... on ProjectV2Owner{projectV2(number:$number){' +
42  'title url all:items(first:0){totalCount} ' +
43  'field(name:"Status"){... on ProjectV2SingleSelectField{options{name}}} ' +
44  `open:items(first:${BOARD_PAGE},query:"-status:${DONE_STATUSES.join(',')}"){totalCount nodes{${ITEM_FIELDS}}} ` +
45  `done:items(first:${BOARD_PAGE},query:"status:${DONE_STATUSES.join(',')} updated:>@today-${DONE_WINDOW_DAYS}d"){nodes{${ITEM_FIELDS}}}` +
46  '}}}}'
47
48/** A Project board's owner and number from its URL: `https://github.com/users/<login>/projects/<n>`, or `/orgs/`. */
49export function parseBoardUrl(url: string): { login: string; number: number } | null {
50  const match = /^https?:\/\/github\.com\/(?:users|orgs)\/([^/\s]+)\/projects\/(\d+)(?:[/?#]|$)/.exec(url.trim())
51
52  return match?.[1] && match[2] ? { login: match[1], number: Number(match[2]) } : null
53}
54
55type Pr = { number: number; url: string; state: string }
56
57/** The pull request an issue links to, of those that close it: an open one first, then a merged one, newest first. */
58export function pickPr(prs: readonly Pr[]): { number: number; url: string } | null {
59  const rank = (pr: Pr) => (pr.state === 'OPEN' ? 0 : pr.state === 'MERGED' ? 1 : 2)
60  const best = [...prs].sort((a, b) => rank(a) - rank(b) || b.number - a.number)[0]
61
62  return best ? { number: best.number, url: best.url } : null
63}
64
65const STATES: ReadonlySet<string> = new Set(['OPEN', 'CLOSED', 'MERGED'])
66
67/** One item from the query's answer; null for one it cannot show (content the person may not read). */
68function toItem(node: unknown): BoardItem | null {
69  const n = (node ?? {}) as { type?: unknown; updatedAt?: unknown; status?: { name?: unknown } | null; content?: Record<string, unknown> | null }
70  const content = n.content ?? {}
71  const title = typeof content.title === 'string' ? content.title : null
72  if (title === null) {
73    return null
74  }
75  const status = typeof n.status?.name === 'string' ? n.status.name : null
76  const updated = typeof n.updatedAt === 'string' ? Date.parse(n.updatedAt) : Number.NaN
77  const updatedAt = Number.isFinite(updated) ? updated : null
78  if (n.type === 'DRAFT_ISSUE') {
79    return { kind: 'draft', number: null, repo: null, title, url: null, state: null, status, pr: null, updatedAt }
80  }
81  const number = typeof content.number === 'number' ? content.number : null
82  const url = typeof content.url === 'string' ? content.url : null
83  if (number === null || url === null) {
84    return null
85  }
86  const repo = (content.repository as { nameWithOwner?: unknown } | undefined)?.nameWithOwner
87  const state = typeof content.state === 'string' && STATES.has(content.state) ? (content.state as BoardItem['state']) : null
88  const isPr = n.type === 'PULL_REQUEST'
89  const closing = (content.closedByPullRequestsReferences as { nodes?: unknown } | undefined)?.nodes
90  const prs = Array.isArray(closing)
91    ? closing.filter((p): p is Pr => typeof p?.number === 'number' && typeof p?.url === 'string' && typeof p?.state === 'string')
92    : []
93
94  return {
95    kind: isPr ? 'pr' : 'issue',
96    number,
97    repo: typeof repo === 'string' ? repo : null,
98    title,
99    url,
100    state,
101    status,
102    pr: isPr ? { number, url } : pickPr(prs),
103    updatedAt,
104  }
105}
106
107/**
108 * The items as the pane lists them: open ones before done ones, open ones by their Status column against the board's
109 * order (`columns`), furthest along first, so Blocked, In Review, In Progress, then Todo; done ones in the board's order.
110 * One with no Status, or a column the board no longer has, goes after them; then the most recently changed first.
111 */
112export function sortItems(items: readonly BoardItem[], columns: readonly string[]): BoardItem[] {
113  const column = (item: BoardItem) => {
114    const at = item.status === null ? -1 : columns.indexOf(item.status)
115    if (at < 0) return columns.length
116    return isDone(item) ? at : columns.length - 1 - at
117  }
118
119  return [...items].sort(
120    (a, b) => Number(isDone(a)) - Number(isDone(b)) || column(a) - column(b) || (b.updatedAt ?? 0) - (a.updatedAt ?? 0),
121  )
122}
123
124/** The query's answer as the pane shows it, or why it holds no board. */
125export function parseBoardItems(json: string): { data: BoardData } | { error: string } {
126  let raw: unknown
127  try {
128    raw = JSON.parse(json)
129  } catch {
130    return { error: "GitHub's answer wasn't JSON" }
131  }
132  type Items = { totalCount?: unknown; nodes?: unknown } | null | undefined
133  const answer = raw as { data?: { repositoryOwner?: { projectV2?: unknown } | null }; errors?: { message?: unknown }[] }
134  const project = answer.data?.repositoryOwner?.projectV2 as
135    | { title?: unknown; url?: unknown; all?: Items; open?: Items; done?: Items; field?: { options?: unknown } | null }
136    | null
137    | undefined
138  if (!project) {
139    const message = answer.errors?.find(e => typeof e.message === 'string')?.message
140    return { error: typeof message === 'string' ? message : 'GitHub found no such Project board' }
141  }
142  const read = (list: Items) => (Array.isArray(list?.nodes) ? list.nodes : []).map(toItem).filter((item): item is BoardItem => item !== null)
143  const open = read(project.open)
144  const done = read(project.done)
145  const options = Array.isArray(project.field?.options) ? project.field.options : []
146  const columns = options.map(o => (o as { name?: unknown })?.name).filter((name): name is string => typeof name === 'string')
147  const items = sortItems([...open, ...done], columns).slice(0, BOARD_PAGE)
148  // The open filter also brings items with no Status whose issue is closed: they count as done.
149  const openCount = typeof project.open?.totalCount === 'number' ? project.open.totalCount - open.filter(isDone).length : undefined
150
151  return {
152    data: {
153      title: typeof project.title === 'string' ? project.title : 'Project',
154      url: typeof project.url === 'string' ? project.url : '',
155      total: typeof project.all?.totalCount === 'number' ? project.all.totalCount : items.length,
156      open: openCount,
157      items,
158    },
159  }
160}
161
162const DONE_STATUS = new RegExp(`^(${DONE_STATUSES.join('|')})$`, 'i')
163
164/** Whether an item counts as done: its Status says so, or with no Status, its issue or pull request is closed. */
165export function isDone(item: BoardItem): boolean {
166  if (item.status !== null) {
167    return DONE_STATUS.test(item.status.trim())
168  }
169
170  return item.state === 'CLOSED' || item.state === 'MERGED'
171}
172
173export function filterItems(items: readonly BoardItem[], filter: BoardFilter): BoardItem[] {
174  return filter === 'all' ? [...items] : items.filter(item => isDone(item) === (filter === 'done'))
175}
176
177export function filterCounts(items: readonly BoardItem[]): Record<BoardFilter, number> {
178  const done = items.filter(isDone).length
179
180  return { open: items.length - done, done, all: items.length }
181}
182
183/** An item's id: `#12` in the session's repository, `name#12` in another, `draft` for a draft. */
184export function itemId(item: BoardItem, repo: string | null): string {
185  if (item.number === null) {
186    return 'draft'
187  }
188  if (item.repo === null || repo === null || item.repo.toLowerCase() === repo.toLowerCase()) {
189    return `#${item.number}`
190  }
191
192  return `${item.repo.split('/').pop()}#${item.number}`
193}
194
195/** A Status's dot and color, read from its name: filled for one under way or finished, hollow for one not started. */
196export function statusMark(status: string | null): { dot: string; color: string } {
197  const s = status?.trim().toLowerCase() ?? ''
198  if (s === '') return { dot: '○', color: FAINT_TEXT }
199  if (DONE_STATUS.test(s)) return { dot: '●', color: GREEN }
200  if (/block/.test(s)) return { dot: '●', color: RED }
201  if (/review/.test(s)) return { dot: '●', color: BLUE }
202  if (/progress|doing|active|working|started/.test(s)) return { dot: '●', color: YELLOW }
203  if (/todo|to do|backlog|ready|new|triage|planned|later/.test(s)) return { dot: '○', color: FAINT_TEXT }
204
205  return { dot: '●', color: DOING_TEXT }
206}
207
208/** The status column's text: its dot and name, a long name cut to fit STATUS_MAX cells. */
209export function statusText(status: string | null): string {
210  const chars = Array.from(`${statusMark(status).dot} ${status?.trim() || '-'}`)
211
212  return chars.length > STATUS_MAX ? `${chars.slice(0, STATUS_MAX - 1).join('')}…` : chars.join('')
213}
214
215/** Clawd's mood: puzzled with no board to show, asleep with nothing open, else stacking. */
216export function towerMode(board: BoardState): TowerMode {
217  if (board.status === 'none' || board.status === 'error') return 'puzzled'
218  if (board.status === 'loading') return 'building'
219
220  return filterCounts(board.data.items).open === 0 ? 'resting' : 'building'
221}
222
223/** The header's faint note: how many items (and how many a read fetched, when fewer), and how long since the read. */
224export function metaText(data: BoardData, at: number, now: number): string {
225  const count =
226    data.total > data.items.length ? `${data.items.length} of ${data.total} items` : `${data.total} ${data.total === 1 ? 'item' : 'items'}`
227  const ago = age(now - at)
228
229  return `${count} · updated ${ago === 'now' ? 'just now' : `${ago} ago`}`
230}
231
232const FILTERS: readonly { filter: BoardFilter; label: string; empty: string }[] = [
233  { filter: 'open', label: 'Open', empty: 'Nothing open on the board.' },
234  { filter: 'done', label: 'Done', empty: 'Nothing done yet.' },
235  { filter: 'all', label: 'All', empty: 'The board is empty.' },
236]
237
238/**
239 * The id column's width in cells at least: room for a five-digit `#12345`, and the slack the desktop's id button needs
240 * around its label. A longer id (another repository's `name#12`) widens it.
241 */
242export const ID_WIDTH = 8
243/** The PR column's width in cells: room for `PR #12345`. */
244export const PR_WIDTH = 10
245/** The most cells the status column's text takes; a longer Status is cut. */
246export const STATUS_MAX = 16
247
248/** `Svg` only where the surface draws it (the desktop): Clawd shows there alone. */
249type El = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'> & { Svg?: Elements['desktop']['Svg'] }
250
251/** Quiet buttons, as the bar's own: dim text and no outline at rest, full strength under the pointer. */
252const QUIET = { plain: true, dimColor: true } as const
253
254export type BoardView = {
255  board: BoardState
256  filter: BoardFilter
257  isReading: boolean
258  /** The session's repository as `owner/name`: its own items' ids leave the name off. */
259  repo: string | null
260  now: number
261}
262
263type BoardActions = { open(url: string): void; setFilter(filter: BoardFilter): void; refresh(): void }
264
265/**
266 * The pane: the board's name, Open in GitHub and a faint note on one line, the filters and Refresh on the next, Clawd
267 * to their left; then a line per item in fixed-width columns.
268 */
269export function renderBoard(el: El, view: BoardView, on: BoardActions) {
270  const { Box, Text, Button, Svg } = el
271  const { board } = view
272  const ready = board.status === 'ready' ? board : null
273
274  let header: RenderChildren
275  if (board.status === 'none') {
276    header = <Text key="none" color={FAINT_TEXT}>This repository has no GitHub Project board. Set project.board in .claude/aitools.json.</Text>
277  } else if (board.status === 'loading') {
278    header = <Text key="loading" color={FAINT_TEXT}>Reading the board…</Text>
279  } else if (board.status === 'error') {
280    header = (
281      <Box key="error" flexDirection="column">
282        <Text color={FAINT_TEXT}>{`Couldn't read the board: ${board.text}`}</Text>
283        <Box marginTop={1}>{refreshButton(el, view, on)}</Box>
284      </Box>
285    )
286  } else {
287    const counts = filterCounts(board.data.items)
288    const url = board.data.url
289    header = (
290      <Box key="header" flexDirection="column">
291        <Box flexDirection="row" columnGap={2} flexWrap="wrap">
292          <Text key="title" color={DOING_TEXT}>{board.data.title}</Text>
293          {url && <Button key="open" label="Open in GitHub" {...QUIET} onPress={() => on.open(url)} />}
294          <Text key="meta" color={FAINT_TEXT}>{metaText(board.data, board.at, view.now)}</Text>
295        </Box>
296        <Box flexDirection="row" columnGap={2} flexWrap="wrap" marginTop={1}>
297          {FILTERS.map(f => (
298            <Button
299              key={`filter-${f.filter}`}
300              label={`${view.filter === f.filter ? '●' : '○'} ${f.label} ${counts[f.filter]}`}
301              {...QUIET}
302              onPress={() => on.setFilter(f.filter)}
303            />
304          ))}
305          {refreshButton(el, view, on)}
306        </Box>
307        {board.error && <Text key="stale" color={FAINT_TEXT}>{`Couldn't read the board again: ${board.error}`}</Text>}
308      </Box>
309    )
310  }
311
312  const items = ready ? filterItems(ready.data.items, view.filter) : []
313  const mode = towerMode(board)
314
315  return (
316    <Box flexDirection="column">
317      <Box flexDirection="row">
318        {Svg && (
319          <Box key="tower" flexShrink={0} marginRight={2}>
320            <Svg source={towerSvg(mode)} alt={towerAlt(mode)} width={TOWER_WIDTH} height={TOWER_HEIGHT} />
321          </Box>
322        )}
323        <Box flexDirection="column" flexShrink={1}>
324          {header}
325        </Box>
326      </Box>
327      {ready && (
328        <Box flexDirection="column" marginTop={1}>
329          {items.length === 0 ? (
330            <Text key="empty" color={FAINT_TEXT}>{FILTERS.find(f => f.filter === view.filter)?.empty}</Text>
331          ) : (
332            renderRows(el, items, view, on)
333          )}
334        </Box>
335      )}
336    </Box>
337  )
338}
339
340/** Refresh, or what it is doing while a read runs. */
341function refreshButton(el: El, view: BoardView, on: BoardActions) {
342  const { Text, Button } = el
343
344  return view.isReading ? (
345    <Text key="refresh" color={FAINT_TEXT}>Refreshing…</Text>
346  ) : (
347    <Button key="refresh" label="Refresh" {...QUIET} onPress={() => on.refresh()} />
348  )
349}
350
351/**
352 * One line per item: its id (opening it) and title on the left, its status and pull request on the right. The id and
353 * status columns are as wide as their widest entry, so every line lines up.
354 */
355function renderRows(el: El, items: readonly BoardItem[], view: BoardView, on: BoardActions) {
356  const { Box, Text, Button } = el
357  const ids = items.map(item => itemId(item, view.repo))
358  const idWidth = Math.max(ID_WIDTH, ...ids.map(id => Array.from(id).length + 2))
359  const statusWidth = Math.max(...items.map(item => Array.from(statusText(item.status)).length)) + 1
360  const cell = (key: string, width: number, child: RenderChildren) => (
361    <Box key={key} width={width} flexShrink={0} flexDirection="row">
362      {child}
363    </Box>
364  )
365
366  return items.map((item, i) => {
367    const id = ids[i] ?? ''
368    const { url, pr } = item
369
370    return (
371      <Box key={`item-${url ?? `draft-${i}`}`} flexDirection="row" justifyContent="space-between">
372        <Box flexDirection="row" flexShrink={1} minWidth={0} overflow="hidden">
373          {cell('id', idWidth, url === null ? <Text color={FAINT_TEXT}>{id}</Text> : <Button key={`id-${i}`} label={id} {...QUIET} onPress={() => on.open(url)} />)}
374          <Box flexShrink={1} minWidth={0} overflow="hidden">
375            <Text color={isDone(item) ? FAINT_TEXT : DOING_TEXT} wrap="truncate-end">
376              {item.title}
377            </Text>
378          </Box>
379        </Box>
380        <Box flexDirection="row" flexShrink={0} marginLeft={2}>
381          {cell('status', statusWidth, <Text color={statusMark(item.status).color}>{statusText(item.status)}</Text>)}
382          {cell('pr', PR_WIDTH, pr === null ? null : <Button key={`pr-${i}`} label={`PR #${pr.number}`} {...QUIET} onPress={() => on.open(pr.url)} />)}
383        </Box>
384      </Box>
385    )
386  })
387}
388
src/pricing.ts 100 lines
1// API list prices in $ per million tokens, as of 2026-09-25.
2// Cache writes are 1.25x input for the 5-minute TTL and 2x input for the 1-hour TTL.
3
4export type Rates = { input: number; output: number; cacheWrite5m: number; cacheWrite1h: number; cacheRead: number }
5
6export type TokenUsage = {
7  input_tokens?: number
8  output_tokens?: number
9  cache_read_input_tokens?: number
10  cache_creation_input_tokens?: number
11  cache_creation?: { ephemeral_5m_input_tokens?: number; ephemeral_1h_input_tokens?: number }
12}
13
14function rates(input: number, output: number, cacheRead: number): Rates {
15  return { input, output, cacheWrite5m: input * 1.25, cacheWrite1h: input * 2, cacheRead }
16}
17
18const FABLE_5_1 = rates(10, 50, 0.25)
19const FABLE_5 = rates(10, 50, 1)
20const OPUS_5_5 = rates(4, 20, 0.2)
21const OPUS_5 = rates(5, 25, 0.5)
22const OPUS_4_1 = rates(15, 75, 1.5)
23const SONNET_5 = rates(2, 10, 0.2)
24const SONNET_4 = rates(3, 15, 0.3)
25const HAIKU_4_5 = rates(1, 5, 0.1)
26
27const TABLE: Record<string, Rates> = {
28  'claude-fable-5-1': FABLE_5_1,
29  'claude-mythos-5-1': FABLE_5_1,
30  'claude-fable-5': FABLE_5,
31  'claude-mythos-5': FABLE_5,
32  'claude-opus-5-5': OPUS_5_5,
33  'claude-opus-5': OPUS_5,
34  'claude-opus-4-8': OPUS_5,
35  'claude-opus-4-7': OPUS_5,
36  'claude-opus-4-6': OPUS_5,
37  'claude-opus-4-5': OPUS_5,
38  'claude-opus-4-1': OPUS_4_1,
39  'claude-opus-4': OPUS_4_1,
40  'claude-sonnet-5-5': SONNET_5,
41  'claude-sonnet-5': SONNET_5,
42  'claude-sonnet-4-6': SONNET_4,
43  'claude-sonnet-4-5': SONNET_4,
44  'claude-sonnet-4': SONNET_4,
45  'claude-haiku-4-5': HAIKU_4_5,
46}
47
48const FAMILIES: [RegExp, Rates][] = [
49  [/fable|mythos/, FABLE_5_1],
50  [/opus/, OPUS_5_5],
51  [/sonnet/, SONNET_5],
52  [/haiku/, HAIKU_4_5],
53]
54
55function ratesFor(model: string): { rates: Rates | null; isEstimate: boolean } {
56  const exact = TABLE[model.replace(/-\d{8}$/, '')]
57  if (exact) {
58    return { rates: exact, isEstimate: false }
59  }
60  const family = FAMILIES.find(([pattern]) => pattern.test(model))
61
62  return { rates: family?.[1] ?? null, isEstimate: true }
63}
64
65/**
66 * What a cold cache costs the next request: `tokens` of context written afresh at the 1-hour write rate, as cache-tax
67 * prices it (a warm one reads them at the cache-read rate). Null for a model with no known rates.
68 */
69export function coldCacheUsd(model: string, tokens: number): { usd: number; isEstimate: boolean } | null {
70  const { rates, isEstimate } = ratesFor(model)
71
72  return rates === null ? null : { usd: (tokens * rates.cacheWrite1h) / 1_000_000, isEstimate }
73}
74
75export function price(model: string, usage: TokenUsage): { usd: number; isEstimate: boolean } {
76  const input = usage.input_tokens ?? 0
77  const output = usage.output_tokens ?? 0
78  const cacheRead = usage.cache_read_input_tokens ?? 0
79  const cacheWrite = usage.cache_creation_input_tokens ?? 0
80  if (input + output + cacheRead + cacheWrite === 0) {
81    return { usd: 0, isEstimate: false }
82  }
83
84  const { rates, isEstimate } = ratesFor(model)
85  if (!rates) {
86    return { usd: 0, isEstimate: true }
87  }
88  const split = usage.cache_creation
89  const write1h = split ? (split.ephemeral_1h_input_tokens ?? 0) : 0
90  const write5m = split ? (split.ephemeral_5m_input_tokens ?? 0) : cacheWrite
91  const perMillion =
92    input * rates.input +
93    output * rates.output +
94    cacheRead * rates.cacheRead +
95    write5m * rates.cacheWrite5m +
96    write1h * rates.cacheWrite1h
97
98  return { usd: perMillion / 1_000_000, isEstimate }
99}
100
src/checklist.tsx 265 lines
1import type { Elements } from 'claude-code'
2
3import type { Checklist, ChecklistItem } from '../types'
4import { BLUE, DOING_TEXT, GREEN } from './palette'
5
6/** The checklist tool's short name; the model calls it as `mcp__aitools__checklist`. */
7export const CHECKLIST_TOOL = 'checklist'
8export const CHECKLIST_TOOL_ID = 'mcp__aitools__checklist'
9
10const STATUSES = ['todo', 'doing', 'done'] as const
11
12export const CHECKLIST_SPEC = {
13  name: CHECKLIST_TOOL,
14  description:
15    'Shows the person your plan and progress as a checklist above their prompt. Use it only when a system note says ' +
16    'progress reporting is on. Send the whole list every call: a short title for the task and each step in plain ' +
17    'language (an outcome, never a tool name, file path or code).',
18  inputSchema: {
19    type: 'object',
20    properties: {
21      title: { type: 'string', description: 'What the task is, in a few words' },
22      items: {
23        type: 'array',
24        items: {
25          type: 'object',
26          properties: {
27            text: { type: 'string', description: 'One step, in plain language' },
28            status: { type: 'string', enum: [...STATUSES] },
29            percent: {
30              type: 'number',
31              minimum: 0,
32              maximum: 100,
33              description: 'For the step in progress: your estimate of how far along it is',
34            },
35          },
36          required: ['text', 'status'],
37        },
38      },
39    },
40    required: ['title', 'items'],
41  },
42}
43
44const TASK_NOTE =
45  `Progress reporting is on: the person follows your work through a checklist drawn from ${CHECKLIST_TOOL_ID}. ` +
46  'If the request needs more than a quick answer, call it before you start with a short title and your plan as ' +
47  '3 to 8 plain-language steps (outcomes, not tool names or code). Call it again with the whole list each time a ' +
48  'step starts (status "doing") or finishes ("done"), with one step doing at a time; add, drop or reword steps when ' +
49  'the plan changes. Give the step in progress a percent, your estimate of how far along it is, and send the list ' +
50  'again as it moves (roughly every quarter of the step) so its progress bar keeps up. Mark every step done before ' +
51  'your final reply. Skip the checklist for a quick question that needs no work.'
52
53/** Clean View's note: what the person sees besides the final reply depends on whether Task View is on too. */
54function cleanNote(isTaskView: boolean): string {
55  const sees = isTaskView ? 'only the checklist and your final reply' : 'only your final reply'
56
57  return (
58    `Clean View is on: the person sees ${sees}, not your tool calls or anything you write before it. Do not ` +
59    'narrate between steps; put what they need in a brief final reply.'
60  )
61}
62
63/** The views' names as the menu, the commands and their replies spell them. */
64export const VIEW_NAMES = { task: 'Task View', clean: 'Clean View' } as const
65
66/**
67 * Whether a view is on after `/taskview` or `/cleanview` with `args`: no argument toggles it, `on` and `off` set it;
68 * null for anything else. Each view is on or off on its own.
69 */
70export function nextToggle(isOn: boolean, args: string): boolean | null {
71  const word = args.trim().toLowerCase()
72
73  return word === '' ? !isOn : word === 'on' ? true : word === 'off' ? false : null
74}
75
76/** The hidden note a prompt carries while a view is on; null with neither. */
77export function viewNote(views: { isTaskView: boolean; isCleanView: boolean }): string | null {
78  const notes = [views.isTaskView ? TASK_NOTE : '', views.isCleanView ? cleanNote(views.isTaskView) : ''].filter(Boolean)
79
80  return notes.length === 0 ? null : notes.join(' ')
81}
82
83/** The checklist tool's input as a Checklist, or the reason it is not one. */
84export function parseChecklist(input: unknown): Checklist | string {
85  const given = input !== null && typeof input === 'object' ? (input as Record<string, unknown>) : {}
86  const title = typeof given.title === 'string' ? given.title.trim() : ''
87  if (!title) {
88    return 'title must be a non-empty string'
89  }
90  if (!Array.isArray(given.items)) {
91    return 'items must be an array of { text, status }'
92  }
93  const items: ChecklistItem[] = []
94  for (const raw of given.items as unknown[]) {
95    const item = raw !== null && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}
96    const text = typeof item.text === 'string' ? item.text.trim() : ''
97    const status = STATUSES.find(s => s === item.status)
98    if (!text || !status) {
99      return 'each item needs a non-empty text and a status of todo, doing or done'
100    }
101    const isPercent = typeof item.percent === 'number' && Number.isFinite(item.percent)
102    const percent = isPercent ? clampPercent(item.percent as number) : undefined
103    items.push(percent === undefined ? { text, status } : { text, status, percent })
104  }
105
106  return { title, items }
107}
108
109function clampPercent(n: number): number {
110  return Math.min(100, Math.max(0, Math.round(n)))
111}
112
113/** How far along a step's bar is: full once done, empty before it starts, the model's estimate in between. */
114export function stepPercent(item: ChecklistItem): number {
115  return item.status === 'done' ? 100 : item.status === 'todo' ? 0 : (item.percent ?? 0)
116}
117
118/** Cells in a step's progress bar. */
119export const BAR_CELLS = 6
120
121/** A step's progress bar: filled cells for the share done, light cells for the rest. */
122export function progressBar(percent: number, cells = BAR_CELLS): { filled: string; empty: string } {
123  const n = Math.round((clampPercent(percent) / 100) * cells)
124
125  return { filled: '▰'.repeat(n), empty: '▱'.repeat(cells - n) }
126}
127
128/** Whether Clean View shows an assistant text block: only one that is part of a finished turn's final reply. */
129export function isFinalReply(text: string, finals: readonly string[]): boolean {
130  const block = text.trim()
131
132  return block.length > 0 && finals.some(final => final.includes(block))
133}
134
135/** How many final replies Clean View keeps to match against. */
136export const FINALS_KEEP = 200
137
138/** Keeps the newest finals, so the list Clean View matches against stays small. */
139export function addFinal(finals: readonly string[], answer: string, keep = FINALS_KEEP): string[] {
140  const text = answer.trim()
141
142  return text && !finals.includes(text) ? [...finals, text].slice(-keep) : [...finals]
143}
144
145export type Row = { role: 'user' | 'assistant'; text: string; toolResults?: readonly unknown[] }
146
147/**
148 * Each request's final reply in a conversation: the last assistant text before the next prompt the person sent (a
149 * user row carrying text and no tool results), and the conversation's last assistant text. Read when the mod loads,
150 * so replies from turns that ended before it (a reload, a restart) still show in Clean View.
151 */
152export function finalReplies(rows: readonly Row[]): string[] {
153  const finals: string[] = []
154  let last = ''
155  for (const row of rows) {
156    if (row.role === 'assistant') {
157      last = row.text.trim() || last
158    } else if (row.text.trim() && !row.toolResults?.length) {
159      if (last) finals.push(last)
160      last = ''
161    }
162  }
163  if (last) finals.push(last)
164
165  return finals
166}
167
168type El = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'>
169
170const MARKS = { done: '✓', doing: '●', todo: '○' } as const
171/** Done marks green, the step in progress blue; steps not started stay dim. */
172const MARK_COLORS = { done: GREEN, doing: BLUE, todo: undefined } as const
173
174/** How far the steps sit in from the title row's fold mark, so they read as the title's. */
175export const STEP_INDENT = 2
176
177/** The collapse toggle's marks: ▸ folded to the title row, ▾ open. */
178export const FOLD_MARKS = { collapsed: '▸', expanded: '▾' } as const
179
180/**
181 * The checklist in the band: a title row (▸ or ▾ to fold it, the title, how many steps are done, × to close it), then
182 * the steps while work goes on, indented under the title; one line once every step is done. Folded, only the title
183 * row shows. `markGap` is the room between the fold mark and the title: the desktop's button chrome parts them already,
184 * the terminal's plain mark needs a space.
185 */
186export function renderChecklist(
187  el: El,
188  list: Checklist | null,
189  isWorking: boolean,
190  view: { isCollapsed: boolean; markGap: number },
191  on: { toggle(): void; close(): void },
192) {
193  const { isCollapsed } = view
194  const { Box, Text, Button } = el
195  if (list === null) {
196    return null
197  }
198  const done = list.items.filter(i => i.status === 'done').length
199  if (!isWorking && list.items.length > 0 && done === list.items.length) {
200    const steps = `${list.items.length} step${list.items.length === 1 ? '' : 's'}`
201    return (
202      <Box flexDirection="row" justifyContent="space-between">
203        <Box flexDirection="row" flexShrink={1}>
204          <Text color={MARK_COLORS.done}>{`${MARKS.done} `}</Text>
205          <Text dimColor wrap="truncate-end">{`Done: ${list.title} (${steps})`}</Text>
206        </Box>
207        <Button key="checklist-close" label="×" plain dimColor onPress={() => on.close()} />
208      </Box>
209    )
210  }
211  const titleRow = (
212    <Box key="checklist-title" flexDirection="row" justifyContent="space-between">
213      <Box flexDirection="row" flexShrink={1} minWidth={0} columnGap={view.markGap}>
214        <Button
215          key="checklist-fold"
216          label={isCollapsed ? FOLD_MARKS.collapsed : FOLD_MARKS.expanded}
217          plain
218          dimColor
219          onPress={() => on.toggle()}
220        />
221        <Box flexShrink={1} minWidth={0}>
222          <Text color={DOING_TEXT} wrap="truncate-end">{list.title}</Text>
223        </Box>
224      </Box>
225      <Box flexDirection="row" flexShrink={0} columnGap={1}>
226        <Text dimColor>{`${done} of ${list.items.length}`}</Text>
227        <Button key="checklist-close" label="×" plain dimColor onPress={() => on.close()} />
228      </Box>
229    </Box>
230  )
231  if (isCollapsed) {
232    return titleRow
233  }
234
235  return (
236    <Box flexDirection="column">
237      {titleRow}
238      {list.items.map((item, i) => {
239        const percent = stepPercent(item)
240        const bar = progressBar(percent)
241
242        return (
243          <Box key={`item-${i}`} flexDirection="row" justifyContent="space-between" paddingLeft={STEP_INDENT}>
244            <Box flexDirection="row" flexShrink={1}>
245              <Text color={MARK_COLORS[item.status]} dimColor={item.status === 'todo'}>{`${MARKS[item.status]} `}</Text>
246              <Text
247                color={item.status === 'doing' ? DOING_TEXT : undefined}
248                dimColor={item.status !== 'doing'}
249                wrap="truncate-end"
250              >
251                {item.text}
252              </Text>
253            </Box>
254            <Box flexDirection="row" flexShrink={0}>
255              <Text key="pct" dimColor>{`${String(percent).padStart(3)}% `}</Text>
256              <Text key="filled" color={MARK_COLORS[item.status]} dimColor={item.status !== 'doing'}>{bar.filled}</Text>
257              <Text key="empty" dimColor>{bar.empty}</Text>
258            </Box>
259          </Box>
260        )
261      })}
262    </Box>
263  )
264}
265
src/palette.ts 76 lines
1/**
2 * The Gruvbox palette (github.com/morhetz/gruvbox), the mods' source for text colors. Pick from here rather than a
3 * named terminal color or a hex of your own: the panes and bars draw on a dark background, so text takes the dark
4 * mode's foreground tones and BRIGHT accents. NEUTRAL and FADED are kept for the odd mark that needs less glare.
5 *
6 * Pictures (Clawd and his props) keep their own colors; this is for text.
7 */
8
9/** Dark mode's backgrounds, darkest first. */
10export const BG = {
11  bg0_h: '#1d2021',
12  bg0: '#282828',
13  bg0_s: '#32302f',
14  bg1: '#3c3836',
15  bg2: '#504945',
16  bg3: '#665c54',
17  bg4: '#7c6f64',
18} as const
19
20/** Dark mode's foregrounds, dimmest first; `gray` sits between the backgrounds and these. */
21export const FG = {
22  gray: '#928374',
23  fg4: '#a89984',
24  fg3: '#bdae93',
25  fg2: '#d5c4a1',
26  fg1: '#ebdbb2',
27  fg0: '#fbf1c7',
28} as const
29
30/** Dark mode's accents: the ones to use for text. */
31export const BRIGHT = {
32  red: '#fb4934',
33  green: '#b8bb26',
34  yellow: '#fabd2f',
35  blue: '#83a598',
36  purple: '#d3869b',
37  aqua: '#8ec07c',
38  orange: '#fe8019',
39} as const
40
41/** The accents' middle shades, shared by both modes. */
42export const NEUTRAL = {
43  red: '#cc241d',
44  green: '#98971a',
45  yellow: '#d79921',
46  blue: '#458588',
47  purple: '#b16286',
48  aqua: '#689d6a',
49  orange: '#d65d0e',
50} as const
51
52/** Light mode's accents, darkest: for text on a light background. */
53export const FADED = {
54  red: '#9d0006',
55  green: '#79740e',
56  yellow: '#b57614',
57  blue: '#076678',
58  purple: '#8f3f71',
59  aqua: '#427b58',
60  orange: '#af3a03',
61} as const
62
63// ---- the roles the mods use, named once ----
64
65export const RED = BRIGHT.red
66export const GREEN = BRIGHT.green
67export const YELLOW = BRIGHT.yellow
68export const BLUE = BRIGHT.blue
69/** Text that stands out without glaring: the step in progress, a pane's title. */
70export const DOING_TEXT = FG.fg3
71/**
72 * Faint text, as faint as the bar's dim labels: the desktop draws `dimColor` in a pane nearly as light as DOING_TEXT,
73 * so pane text that must read faint uses this instead.
74 */
75export const FAINT_TEXT = FG.gray
76
src/burnrate.ts 46 lines
1const MIN = 60_000
2const WINDOW = 60 * MIN
3const MIN_SPAN = 10 * MIN
4
5export type Sample = { t: number; pct: number }
6
7export type BurnState = { resetsAt: string | null; samples: Sample[] }
8
9export const EMPTY_BURN: BurnState = { resetsAt: null, samples: [] }
10
11export function addSample(s: BurnState, t: number, pct: number, resetsAt?: string): BurnState {
12  const window = resetsAt ?? null
13  const samples = window === s.resetsAt ? s.samples : []
14  if (samples.at(-1)?.pct === pct) {
15    return { resetsAt: window, samples }
16  }
17
18  return { resetsAt: window, samples: [...samples, { t, pct }].filter(x => x.t >= t - WINDOW) }
19}
20
21/** When the 5-hour window hits 100% at the recent pace, or null when that is not before the reset. */
22export function project(s: BurnState, now: number): number | null {
23  const samples = s.samples.filter(x => x.t >= now - WINDOW)
24  const first = samples[0]
25  const last = samples.at(-1)
26  if (!first || !last || samples.length < 2 || last.t - first.t < MIN_SPAN) {
27    return null
28  }
29
30  const meanT = samples.reduce((sum, x) => sum + x.t, 0) / samples.length
31  const meanP = samples.reduce((sum, x) => sum + x.pct, 0) / samples.length
32  const covariance = samples.reduce((sum, x) => sum + (x.t - meanT) * (x.pct - meanP), 0)
33  const variance = samples.reduce((sum, x) => sum + (x.t - meanT) ** 2, 0)
34  const slope = covariance / variance
35  if (!(slope > 0)) {
36    return null
37  }
38
39  const eta = Math.round(now + (100 - last.pct) / slope)
40  if (s.resetsAt && eta >= Date.parse(s.resetsAt)) {
41    return null
42  }
43
44  return eta
45}
46
src/handoff.ts 24 lines
1export const HANDOFF_PROMPT =
2  'Write a handoff brief so a fresh session with no memory of this conversation can continue the work. ' +
3  'Use markdown with exactly these sections: ## Goal, ## Current state, ## Decisions made, ## Open tasks, ' +
4  '## Key files, ## Next step. Be specific: name files, functions, commands and unresolved questions. ' +
5  'Output only the brief.'
6
7/**
8 * The chat row for a brief, which the chat renders as markdown. The title line comes first because the engine
9 * prefixes the row with the plugin's name, which would otherwise swallow the first heading.
10 */
11export function handoffOutput(brief: string): string {
12  return `Handoff brief\n\n${brief}`
13}
14
15/** The most a Markdown element draws; a longer brief is cut in the pane, while Copy still takes all of it. */
16export const MARKDOWN_MAX = 10_000
17
18const CUT_NOTE = '\n\n_(Cut to fit the pane; Copy takes the whole brief.)_'
19
20/** The brief as the handoff pane draws it, cut to fit the Markdown element's limit. */
21export function paneMarkdown(brief: string): string {
22  return brief.length <= MARKDOWN_MAX ? brief : brief.slice(0, MARKDOWN_MAX - CUT_NOTE.length) + CUT_NOTE
23}
24
src/askme.ts 64 lines
1/**
2 * /askme: asks Claude to put the questions from its last answer to the person as pop-up choices, each with a
3 * recommendation, instead of leaving them as prose to answer by typing.
4 */
5
6export const ASKME_PROMPT =
7  'Look at your previous response and find every question or decision you left for me. Ask them again with the ' +
8  'AskUserQuestion tool instead of in prose.\n' +
9  '- One question per decision. Make each question self-contained: the pop-up hides your earlier response, so ' +
10  'say in a sentence what it is about.\n' +
11  '- Give 2 to 4 concrete options. Put the one you recommend first and end its label with "(Recommended)". Each ' +
12  "option's description says what choosing it means or costs, in one line.\n" +
13  '- Group plain confirm-or-reverse items four to a multiSelect question: "Which of these should change? Select ' +
14  'none to confirm all."\n' +
15  '- Ask at most 4 questions per call, most important first, and keep calling until every question has an ' +
16  'answer. Follow up on any answer given as "Other" before treating it as decided.\n' +
17  'Then list the decisions in one short summary and carry on with the work they unblock. If your previous ' +
18  'response left no questions, say so in one line and stop.'
19
20/** The prompt for `/askme [extra]`: the extra words, when given, ride along as the person's own note. */
21export function askmeText(args: string): string {
22  const extra = args.trim()
23  return extra === '' ? ASKME_PROMPT : `${ASKME_PROMPT}\n\nAlso: ${extra}`
24}
25
26/** The tool that puts questions to the person as pop-up choices. */
27export const ASK_TOOL = 'AskUserQuestion'
28
29/**
30 * Whether a reply asks the person something: a question mark that ends a sentence, right after a word (closing marks
31 * between are fine), anywhere outside a code block. A bare one (the button's own **?**) or one inside a URL (`?q=`) or
32 * a code block asks nothing; a code span counts as a word, so "Use `x`?" still asks.
33 */
34export function asksQuestions(text: string): boolean {
35  const prose = text.replace(/```[\s\S]*?(```|$)/g, '').replace(/`[^`\n]*`/g, 'code')
36  return /[\p{L}\p{N}][*_"')\]]*\?[*_"')\]]*(\s|$)/u.test(prose)
37}
38
39/** A conversation row as `$.session.messages()` gives it, as much of it as is read here. */
40type AskRow = { role: 'user' | 'assistant'; text: string; toolUses?: readonly { tool: string }[]; toolResults?: readonly unknown[] }
41
42/**
43 * Whether the conversation, as the mod finds it on load, is worth an /askme: since the person's last prompt Claude
44 * never opened the question pop-up, and its last reply asks something.
45 */
46export function isAskableIn(rows: readonly AskRow[]): boolean {
47  let reply: string | null = null
48  for (const row of [...rows].reverse()) {
49    if (row.role === 'user' && row.text.trim() && !row.toolResults?.length) {
50      break
51    }
52    if (row.role === 'assistant') {
53      if (row.toolUses?.some(u => u.tool === ASK_TOOL)) {
54        return false
55      }
56      if (reply === null && row.text.trim()) {
57        reply = row.text
58      }
59    }
60  }
61
62  return reply !== null && asksQuestions(reply)
63}
64
src/config.ts 199 lines
1/**
2 * aitools.json: the mod's settings as files the person can read and edit.
3 *
4 * `~/.claude/aitools.json` (under CLAUDE_CONFIG_DIR when set) holds the person's own settings: what the bar shows
5 * (the project row among it),
6 * the views, the Background tasks and Branches panes' picks. Everything the mod's own controls change is written here, never to a
7 * project's file. `<repo>/.claude/aitools.json` holds only the `project` section (src/project.tsx reads it).
8 *
9 * Both files are JSON. A write reads the file again first and changes only the keys it sets, so hand edits and keys
10 * the mod does not know are kept.
11 */
12
13import { DEFAULT_HIDE_AFTER, isHideAfter, isShowing } from './agentdock'
14import { DEFAULT_SHOW, DEFAULT_WHERE, isBranchesShow, isBranchesWhere } from './branches'
15import { DEFAULT_SETTINGS, LEGACY_KEYS, normalizeSettings } from './settings'
16import type { AgentShowing, BranchesShow, BranchesWhere, HideAfter, Settings } from '../types'
17
18/** The file's name, in the Claude config folder and in a project's `.claude` folder. */
19export const CONFIG_FILE = 'aitools.json'
20
21/** A JSON object as read from a file: whatever it holds, typed loosely until normalized. */
22export type Json = Record<string, unknown>
23
24/** The person's settings, as the mod uses them. */
25export type Personal = {
26  settings: Settings
27  /** `/aitools off`: the whole bar hidden. */
28  isHidden: boolean
29  /** Task View and Clean View, each on or off on its own. */
30  taskView: boolean
31  cleanView: boolean
32  showing: AgentShowing
33  hideAfter: HideAfter
34  branchesWhere: BranchesWhere
35  branchesShow: BranchesShow
36}
37
38export const PERSONAL_DEFAULTS: Personal = {
39  settings: DEFAULT_SETTINGS,
40  isHidden: false,
41  taskView: false,
42  cleanView: false,
43  showing: 'all',
44  hideAfter: DEFAULT_HIDE_AFTER,
45  branchesWhere: DEFAULT_WHERE,
46  branchesShow: DEFAULT_SHOW,
47}
48
49/** A file's text as JSON: an object, or why it is not one. */
50export function parseConfig(text: string): { value: Json } | { error: string } {
51  let value: unknown
52  try {
53    value = JSON.parse(text)
54  } catch (err) {
55    return { error: err instanceof Error ? err.message : String(err) }
56  }
57  if (value === null || typeof value !== 'object' || Array.isArray(value)) {
58    return { error: 'the file must hold one JSON object' }
59  }
60
61  return { value: value as Json }
62}
63
64/** The text a config is written as: two-space JSON and a final newline. */
65export function configText(raw: Json): string {
66  return `${JSON.stringify(raw, null, 2)}\n`
67}
68
69/** The object under `key`, or an empty one when there is none. */
70export function objectAt(raw: Json, key: string): Json {
71  const value = raw[key]
72  return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : {}
73}
74
75/** The person's settings in a global file, each one the file leaves out or gets wrong at its default. */
76export function personalFrom(raw: Json): Personal {
77  const bar = objectAt(raw, 'bar')
78  const subagents = objectAt(raw, 'subagents')
79  const branches = objectAt(raw, 'branches')
80  // `view` was one word before the views were apart: `task`, or `clean`, which brought the checklist with it.
81  const legacy = raw.view
82  const view = objectAt(raw, 'view')
83
84  return {
85    settings: normalizeSettings(objectAt(bar, 'show')),
86    isHidden: bar.hidden === true,
87    taskView: legacy === 'task' || legacy === 'clean' || view.tasks === true,
88    cleanView: legacy === 'clean' || view.clean === true,
89    showing: isShowing(subagents.showing) ? subagents.showing : PERSONAL_DEFAULTS.showing,
90    hideAfter: isHideAfter(subagents.hideAfter) ? subagents.hideAfter : PERSONAL_DEFAULTS.hideAfter,
91    branchesWhere: isBranchesWhere(branches.where) ? branches.where : PERSONAL_DEFAULTS.branchesWhere,
92    branchesShow: isBranchesShow(branches.show) ? branches.show : PERSONAL_DEFAULTS.branchesShow,
93  }
94}
95
96/** Where each setting sits in the file. */
97const PATHS: { [K in keyof Personal]: readonly [string, ...string[]] } = {
98  settings: ['bar', 'show'],
99  isHidden: ['bar', 'hidden'],
100  taskView: ['view', 'tasks'],
101  cleanView: ['view', 'clean'],
102  showing: ['subagents', 'showing'],
103  hideAfter: ['subagents', 'hideAfter'],
104  branchesWhere: ['branches', 'where'],
105  branchesShow: ['branches', 'show'],
106}
107
108function setAt(raw: Json, path: readonly string[], value: unknown): Json {
109  const [key, ...rest] = path
110  if (key === undefined) {
111    return raw
112  }
113
114  return { ...raw, [key]: rest.length === 0 ? value : setAt(objectAt(raw, key), rest, value) }
115}
116
117function hasAt(raw: Json, path: readonly string[]): boolean {
118  const [key, ...rest] = path
119  if (key === undefined || !(key in raw)) {
120    return false
121  }
122
123  return rest.length === 0 || hasAt(objectAt(raw, key), rest)
124}
125
126/** The file with `change` written into it; every other key, the person's own included, kept as it was. */
127export function withPersonal(raw: Json, change: Partial<Personal>): Json {
128  let next = raw
129  for (const key of Object.keys(change) as (keyof Personal)[]) {
130    const value = key === 'settings' ? { ...objectAt(objectAt(raw, 'bar'), 'show'), ...change.settings } : change[key]
131    next = setAt(next, PATHS[key], value)
132  }
133
134  return next
135}
136
137/** Settings the mod no longer has: dropped from the file when it is next filled in. */
138const RETIRED_PATHS = [
139  ['subagents', 'team'],
140  ['subagents', 'helpers'],
141] as const
142
143/** The file without the setting at `path`; the file as it was when it has none. */
144function withoutAt(raw: Json, path: readonly string[]): Json {
145  const [key, ...rest] = path
146  if (key === undefined || !hasAt(raw, path)) {
147    return raw
148  }
149  if (rest.length === 0) {
150    const { [key]: _, ...kept } = raw
151    return kept
152  }
153
154  return { ...raw, [key]: withoutAt(objectAt(raw, key), rest) }
155}
156
157/** The settings the mod kept in its store before the file existed, under their old keys. */
158export type StoredSettings = Partial<Record<(typeof STORED_KEYS)[number], unknown>>
159
160/** The old store keys the migration reads, and clears once the file holds them. */
161export const STORED_KEYS = ['settings', 'isHidden', 'viewMode', 'agentTeam', 'agentHelpers', 'agentShowing', 'agentHideAfter'] as const
162
163/**
164 * The file with every setting it lacks filled in: from the store where the mod kept it before, else its default, so
165 * the file shows every setting there is, and with any setting the mod no longer has removed. What the file already
166 * holds wins.
167 */
168export function migrated(raw: Json, stored: StoredSettings): Json {
169  const old = personalFrom({
170    bar: { show: stored.settings, hidden: stored.isHidden },
171    view: stored.viewMode,
172    subagents: { showing: stored.agentShowing, hideAfter: stored.agentHideAfter },
173  })
174  let next = RETIRED_PATHS.reduce(withoutAt, raw)
175  if (typeof next.view === 'string') {
176    // The one-word view of before, as the two it stands for.
177    const was = personalFrom(next)
178    next = { ...next, view: { tasks: was.taskView, clean: was.cleanView } }
179  }
180  for (const key of Object.keys(PATHS) as (keyof Personal)[]) {
181    if (key === 'settings') {
182      // Each display option on its own, so one added in a later version joins a file that has the rest.
183      // An option that took over an older one's job starts from the file's pick for the older one.
184      const show = objectAt(objectAt(next, 'bar'), 'show')
185      const fromFile = normalizeSettings(show)
186      const missing = Object.fromEntries(
187        Object.entries(old.settings)
188          .filter(([k]) => !(k in show))
189          .map(([k, v]) => [k, (LEGACY_KEYS[k as keyof typeof LEGACY_KEYS] ?? '') in show ? fromFile[k as keyof typeof fromFile] : v]),
190      )
191      if (Object.keys(missing).length > 0) next = setAt(next, PATHS.settings, { ...show, ...missing })
192    } else if (!hasAt(next, PATHS[key])) {
193      next = setAt(next, PATHS[key], old[key])
194    }
195  }
196
197  return next
198}
199
src/project.tsx 314 lines
1/**
2 * The project row: a second line under the bar for the GitHub repository the session works in. On the left the
3 * repository's name (opening it in the browser), how many items are open on its GitHub Project board (opening the
4 * Project pane), how many branches it has besides the base (opening the Branches pane), how many background tasks run
5 * (opening their pane) and the issue the session is about (opening in the browser); on
6 * the right the tools the project's own `.claude/aitools.json` defines (links, servers, commands). Outside a GitHub
7 * repository the row is not drawn.
8 */
9
10import type { Elements } from 'claude-code'
11
12import { tasksLabel } from './agentdock'
13import { objectAt } from './config'
14import type { Json } from './config'
15import { DOING_TEXT, FAINT_TEXT, GREEN, RED, YELLOW } from './palette'
16import type { GithubRepo, ProjectConfig, ProjectTool, ToolListener, ToolRun } from '../types'
17
18/** A GitHub repository from a git remote URL: `https://github.com/o/r(.git)`, `git@github.com:o/r.git`, `ssh://…`. */
19export function parseGithubRemote(url: string): { owner: string; name: string } | null {
20  const match = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com(?::\d+)?\/)([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/.exec(url.trim())
21
22  return match?.[1] && match[2] ? { owner: match[1], name: match[2] } : null
23}
24
25/** Context the engine joins into a prompt's text, which can name unrelated issues and pull requests. */
26const REMINDER = /<system-reminder>[\s\S]*?<\/system-reminder>/g
27/** An issue a prompt names: its URL or `#<number>`; the first one counts. */
28const PROMPT_ISSUE = /\/issues\/(\d+)|(?:^|[^\w&])#(\d+)\b/
29
30/** The issue a prompt names, as vowelit's devserver mod reads it; null when it names none. */
31export function issueInPrompt(text: string): number | null {
32  const match = PROMPT_ISSUE.exec(text.replace(REMINDER, ''))
33  const n = match?.[1] ?? match?.[2]
34
35  return n === undefined ? null : Number(n)
36}
37
38/**
39 * The issue a branch is named for: a number opening the name or a segment after `/`, alone or before a `-`
40 * (`feat/123-login`, `123-fix`, `issue-123`, `gh-123`). A date (`2026-10-10-notes`) or a version (`v2`) is none.
41 */
42export function issueInBranch(branch: string): number | null {
43  for (const segment of branch.split('/')) {
44    const match = /^(?:(?:issue|issues|gh|bug|fix)-)?(\d+)(?:-|$)/i.exec(segment)
45    if (match?.[1] && !/^\d{4}-\d{2}-\d{2}/.test(segment)) {
46      return Number(match[1])
47    }
48  }
49
50  return null
51}
52
53/** The values a tool's command or link may name in braces. */
54export type ToolVars = { checkout: string; main: string; branch: string; repo: string; owner: string; name: string; issue: string; port: string }
55
56/** `text` with each `{name}` it names replaced; a name it does not know is left as written. */
57export function expand(text: string, vars: ToolVars): string {
58  return text.replace(/\{(\w+)\}/g, (whole, key: string) => (key in vars ? vars[key as keyof ToolVars] : whole))
59}
60
61/** A command as the file gives it: an argument list, or a string run by `sh -c`. */
62function argvOf(value: unknown): string[] | null {
63  if (typeof value === 'string' && value.trim()) return ['sh', '-c', value]
64  if (Array.isArray(value) && value.length > 0 && value.every(v => typeof v === 'string')) return value as string[]
65
66  return null
67}
68
69const slug = (text: string) => text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'tool'
70
71/**
72 * The project section of a project's file, its problems listed rather than thrown: a tool it cannot use is left out
73 * with a line saying why, so one mistake does not take the rest of the row down.
74 */
75export function projectFrom(raw: Json): ProjectConfig {
76  const project = objectAt(raw, 'project')
77  const problems: string[] = []
78  const tools: ProjectTool[] = []
79  const ids = new Set<string>()
80  const list = project.tools === undefined ? [] : Array.isArray(project.tools) ? project.tools : null
81  if (list === null) problems.push('project.tools must be a list')
82  for (const [i, entry] of (list ?? []).entries()) {
83    const where = `project.tools[${i}]`
84    const t = entry !== null && typeof entry === 'object' && !Array.isArray(entry) ? (entry as Json) : null
85    const label = typeof t?.label === 'string' && t.label.trim() ? t.label.trim() : null
86    if (t === null || label === null) {
87      problems.push(`${where} needs a "label"`)
88      continue
89    }
90    let id = typeof t.id === 'string' && t.id.trim() ? slug(t.id) : slug(label)
91    while (ids.has(id)) id = `${id}-${i}`
92    ids.add(id)
93    if (t.type === 'link') {
94      if (typeof t.url !== 'string' || !t.url.trim()) {
95        problems.push(`${where} ("${label}") needs a "url"`)
96        continue
97      }
98      tools.push({ type: 'link', id, label, url: t.url.trim() })
99    } else if (t.type === 'command') {
100      const run = argvOf(t.run)
101      if (run === null) {
102        problems.push(`${where} ("${label}") needs a "run" command: a string, or a list of arguments`)
103        continue
104      }
105      tools.push({ type: 'command', id, label, run, ...(typeof t.cwd === 'string' ? { cwd: t.cwd } : {}) })
106    } else if (t.type === 'server') {
107      const start = argvOf(t.start)
108      if (start === null) {
109        problems.push(`${where} ("${label}") needs a "start" command: a string, or a list of arguments`)
110        continue
111      }
112      const stop = t.stop === undefined ? null : argvOf(t.stop)
113      if (t.stop !== undefined && stop === null) problems.push(`${where} ("${label}"): "stop" must be a string or a list of arguments`)
114      const port = typeof t.port === 'number' && Number.isInteger(t.port) && t.port > 0 && t.port < 65536 ? t.port : null
115      if (t.port !== undefined && port === null) problems.push(`${where} ("${label}"): "port" must be a port number`)
116      let ready: string | null = null
117      if (typeof t.ready === 'string') {
118        try {
119          new RegExp(t.ready)
120          ready = t.ready
121        } catch {
122          problems.push(`${where} ("${label}"): "ready" is not a valid regular expression`)
123        }
124      }
125      tools.push({
126        type: 'server',
127        id,
128        label,
129        start,
130        ...(stop === null ? {} : { stop }),
131        ...(port === null ? {} : { port }),
132        ...(ready === null ? {} : { ready }),
133        ...(typeof t.cwd === 'string' ? { cwd: t.cwd } : {}),
134      })
135    } else {
136      problems.push(`${where} ("${label}"): "type" must be "link", "command" or "server"`)
137    }
138  }
139  const board = project.board === false ? false : typeof project.board === 'string' && project.board.trim() ? project.board.trim() : undefined
140  if (project.board !== undefined && board === undefined) problems.push('project.board must be a URL, or false to hide it')
141
142  return {
143    isEnabled: project.enabled !== false,
144    ...(typeof project.name === 'string' && project.name.trim() ? { name: project.name.trim() } : {}),
145    ...(board === undefined ? {} : { board }),
146    tools,
147    problems,
148  }
149}
150
151/** A server's status line: a dot in its state's color and the words, which open its log. */
152export function serverStatus(run: ToolRun | undefined, listener: ToolListener | null | undefined): { dot: string; text: string; color?: string } {
153  const phase = run?.phase ?? 'idle'
154  const branch = run?.branch ?? ''
155  if (phase === 'stopping') return { dot: '○', text: branch ? `Stopping ${branch}…` : 'Stopping…', color: YELLOW }
156  if (phase === 'starting') return { dot: '○', text: branch ? `Starting ${branch}…` : 'Starting…', color: YELLOW }
157  if (phase === 'ready') return { dot: '●', text: branch ? `Running ${branch}` : 'Running', color: GREEN }
158  if (listener) return { dot: '●', text: `Running ${listener.label}`, color: GREEN }
159  if (phase === 'running') return { dot: '●', text: branch ? `Running ${branch}` : 'Running', color: GREEN }
160  if (phase === 'exited') {
161    // Exiting with code 0, or on the stop signal a Stop sends, is a clean end: dim like Stopped, not red.
162    const isClean = /^(code 0|SIGTERM|SIGINT)$/.test(run?.detail ?? '')
163    return { dot: '○', text: `Exited${run?.detail ? ` (${run.detail})` : ''}`, ...(isClean ? {} : { color: RED }) }
164  }
165  if (phase === 'failed') return { dot: '○', text: `Failed${run?.detail ? `: ${run.detail}` : ''}`, color: RED }
166
167  return { dot: '○', text: 'Stopped' }
168}
169
170/** Whether a server counts as up: this session's run, or anything listening on its port. */
171export function isServerUp(run: ToolRun | undefined, listener: ToolListener | null | undefined): boolean {
172  return listener != null || run?.phase === 'starting' || run?.phase === 'ready' || run?.phase === 'running'
173}
174
175/** A command tool's dot: yellow while it runs, green once it passed, red once it failed; none before it ran. */
176export function commandDot(run: ToolRun | undefined): { dot: string; color: string } | null {
177  if (run?.phase === 'running') return { dot: '●', color: YELLOW }
178  if (run?.phase === 'passed') return { dot: '●', color: GREEN }
179  if (run?.phase === 'failed' || run?.phase === 'exited') return { dot: '●', color: RED }
180
181  return null
182}
183
184type El = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'>
185
186/** Quiet buttons, as the bar's own: dim text and no outline at rest, full strength under the pointer. */
187const QUIET = { plain: true, dimColor: true } as const
188
189/** What the row draws: the repository, its links, and each tool with how it stands. */
190export type RowView = {
191  repo: GithubRepo
192  name: string
193  boardUrl: string | null
194  /** The issue the session is about, by number: a button opens it on GitHub. */
195  issue: number | null
196  tools: readonly ProjectTool[]
197  runs: Readonly<Record<string, ToolRun>>
198  listeners: Readonly<Record<string, ToolListener | null>>
199  /** How many items are open on the board, null before it is read: a button after the name opens the Project pane. */
200  openItems: number | null
201  /** How many branches the repository has besides the base, null before a read: a button opens the Branches pane. */
202  branches: number | null
203  /** How many background tasks are running: a button after the branches' opens their pane while any is. */
204  tasks: number
205  /** Room between neighboring buttons: the desktop's own chrome parts them, the terminal needs spaces. */
206  gap: number
207}
208
209/** The board button's label: `1 project item`, `32 project items`. */
210export function itemsLabel(n: number): string {
211  return `${n} project ${n === 1 ? 'item' : 'items'}`
212}
213
214/** The branches button's label: `1 branch`, `5 branches`. */
215export function branchesLabel(n: number): string {
216  return `${n} ${n === 1 ? 'branch' : 'branches'}`
217}
218
219export function renderProjectRow(
220  el: El,
221  view: RowView,
222  on: {
223    open(url: string): void
224    startServer(id: string): void
225    stopServer(id: string): void
226    toggleLog(id: string): void
227    runCommand(id: string): void
228    openTasks(): void
229    openBoard(): void
230    openBranches(): void
231  },
232) {
233  const { Box, Text, Button } = el
234  const { repo, gap } = view
235
236  return (
237    <Box flexDirection="row" justifyContent="space-between" width="100%">
238      <Box key="project-left" flexDirection="row" gap={gap} flexShrink={1} alignItems="center">
239        <Button key="project-name" label={view.name} {...QUIET} onPress={() => on.open(repo.url)} />
240        {view.boardUrl !== null && view.openItems !== null && view.openItems > 0 && (
241          <Button key="project-board" label={itemsLabel(view.openItems)} {...QUIET} onPress={() => on.openBoard()} />
242        )}
243        {view.branches !== null && view.branches > 0 && (
244          <Button key="project-branches" label={branchesLabel(view.branches)} {...QUIET} onPress={() => on.openBranches()} />
245        )}
246        {view.tasks > 0 && <Button key="project-tasks" label={tasksLabel(view.tasks)} {...QUIET} onPress={() => on.openTasks()} />}
247        {view.issue !== null && (
248          <Button key="project-issue" label={`#${view.issue}`} {...QUIET} onPress={() => on.open(`${repo.url}/issues/${view.issue}`)} />
249        )}
250      </Box>
251      <Box key="project-tools" flexDirection="row" gap={gap} flexShrink={0} alignItems="center">
252        {view.tools.map(tool => {
253          if (tool.type === 'link') {
254            return <Button key={`tool-${tool.id}`} label={tool.label} {...QUIET} onPress={() => on.open(tool.url)} />
255          }
256          const run = view.runs[tool.id]
257          if (tool.type === 'command') {
258            const dot = commandDot(run)
259            return (
260              <Box key={`tool-${tool.id}`} flexDirection="row" alignItems="center">
261                {dot && <Text color={dot.color}>{`${dot.dot} `}</Text>}
262                <Button
263                  key={`tool-${tool.id}-run`}
264                  label={run?.phase === 'running' ? `${tool.label}…` : tool.label}
265                  {...QUIET}
266                  onPress={() => (run?.phase === 'running' ? on.toggleLog(tool.id) : on.runCommand(tool.id))}
267                />
268              </Box>
269            )
270          }
271          const listener = view.listeners[tool.id]
272          const status = serverStatus(run, listener)
273          const isUp = isServerUp(run, listener)
274          const isBusy = run?.phase === 'starting' || run?.phase === 'stopping'
275          return (
276            <Box key={`tool-${tool.id}`} flexDirection="row" gap={gap} alignItems="center">
277              <Box key={`tool-${tool.id}-status`} flexDirection="row" alignItems="center">
278                <Text color={status.color ?? FAINT_TEXT}>{`${status.dot} `}</Text>
279                <Button key={`tool-${tool.id}-log`} label={status.text} {...QUIET} onPress={() => on.toggleLog(tool.id)} />
280              </Box>
281              {isBusy ? (
282                <Text key={`tool-${tool.id}-busy`} color={DOING_TEXT}>{isUp ? `Stop ${tool.label}` : `Start ${tool.label}`}</Text>
283              ) : isUp ? (
284                <Button key={`tool-${tool.id}-stop`} label={`Stop ${tool.label}`} {...QUIET} onPress={() => on.stopServer(tool.id)} />
285              ) : (
286                <Button key={`tool-${tool.id}-start`} label={`Start ${tool.label}`} {...QUIET} onPress={() => on.startServer(tool.id)} />
287              )}
288            </Box>
289          )
290        })}
291      </Box>
292    </Box>
293  )
294}
295
296/** A tool's log pane id. */
297export const logPaneId = (id: string) => `aitools-log-${id}`
298
299/** How many lines a tool's log keeps. */
300export const LOG_KEEP = 2000
301
302const ANSI = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07]*\x07/g
303
304/**
305 * A chunk of output cut into whole lines, colors stripped and a carriage return taken as a redraw of the line: the
306 * lines it finished, and the unfinished rest, which the next chunk continues.
307 */
308export function splitOutput(rest: string, text: string): { lines: string[]; rest: string } {
309  const parts = (rest + text.replace(ANSI, '')).split('\n')
310  const tail = parts.pop() ?? ''
311
312  return { lines: parts.map(part => part.slice(part.lastIndexOf('\r') + 1)), rest: tail }
313}
314