SLOPSHOPPER

plan-tracker

A live board of your approved plan: which steps are done, running, blocked or waiting on you.

panebandguardcommandtoastprompt
v0.8.0MITupdated 2026-10-18lijingwu2026/claude-code-plan-tracker
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · plan-tracker
│ ┃ Plans ✕ › fix the failing auth test and add an audit log call │ ┃ No PROGRESS.md yet: the route skill writes │ ┃ it when an approved plan starts. ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /plan-tracker │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Plans
No PROGRESS.md yet: the route skill writes it when an approved plan starts.
README

<img src="docs/cover.jpg" alt="plan-tracker, a Claude Code plugin: Your plan on one live board inside Claude Code: every task, who's on it, and what waits on you. Below, the board of a demo plan, Add CSV export, in progress, 3 of 8 tasks done." width="100%">

<sub>The board on the cover is a demo plan: adding CSV export to a report CLI, 3 of 8 tasks done.</sub>

<h3 align="center"> <a href="#get-started">Get started</a> | <a href="#where-it-runs">Where it runs</a> | <a href="#how-it-works">How it works</a> | <a href="#try-it">Try it</a> | <a href="#what-you-get">What you get</a> | <a href="#compared">Compared</a> | <a href="#limits">Limits</a> | <a href="#reference">Reference</a> </h3>

plan-tracker

Claude Code mod that puts your plan on one live board: every task, who's on it, and what waits on you.

Get started

Install plan-tracker and plan-orchestrator, the separate plugin that writes your plan's tasks to PROGRESS.md:

/plugin marketplace add lijingwu2026/claude-code-plan-orchestrator
/plugin install plan-orchestrator@plan-orchestrator
/plugin marketplace add lijingwu2026/claude-code-plan-tracker
/plugin install plan-tracker@plan-tracker
ToDo
See your planApprove a plan in plan mode. The band appears above your prompt, in every session of that project.
Open the boardPress the bar, or type /plan-tracker.
Pick a plan/plan-tracker lists your open plans, newest first, with a search field. Typing also finds done and canceled plans. This needs a board command that lists several plans. A plain PROGRESS.md has one plan, so it opens its board.
Use your own PROGRESS.mdCopy the table under Try it. plan-orchestrator is not needed.

Where it runs

PlaceStatusTested onScreenshot
Terminal (macOS)TestedClaude Code 2.1.301terminal
Claude Desktop app (macOS)TestedDesktop 2.31226.1, which runs Claude Code 2.1.295Desktop
VS Code extensionTested in CursorClaude Code extension 2.1.300; VS Code itself is not testedCursor

How it works

The route skill in plan-orchestrator writes your plan's tasks to PROGRESS.md and updates them as they run. plan-tracker reads that file and never writes it.

<img src="docs/how-it-works.svg" alt="Sequence: 1 you approve a plan; 2 the route skill writes one row per task, each with its goal; 3 plan-tracker reads that file; 4 it draws the band and the board; 5 rows change as tasks run and new work gets its own row; 6 a task waits on your check; 7 its card says needs you and its page shows the goal and latest note; 8 you check it and reply; 9 the route skill marks it Done; 10 a pop-up and chime, the bar fills; 11 when Claude hands the plan back, the route skill writes the Recap; 12 in the next session the band and board draw from the same file: state, done/total and recap." width="100%">

Try it

Save this as PROGRESS.md in your project root. The band appears within a few seconds, the board shows a card in Done, In Progress and Verify, and task 3 says ◆ needs you.

# Add CSV export

| task | status | executor | check | evidence |
|---|---|---|---|---|
| 1. Write the serializer | Done | subagent · Sonnet | script | 12 tests pass |
| 2. Add the export command | In Progress | main session · Opus | script | |
| 3. Review the file name wording | Needs Verification | main session · Opus | you | draft ready |

Change a status in the file and the board follows.

What you get

<img src="docs/demo.gif" alt="The plan-tracker demo: /plan-tracker opens the board, task 7 goes In Progress and then Done with a pop-up, then task 4, the last open one, goes Done and the band's bar turns to a rainbow." width="100%">

<sub>14 s. /plan-tracker opens the board, then the plan's PROGRESS.md changes: task 7 goes In Progress, then Done (a pop-up ✅ 7. Document the export flags · 1 left and a chime); then task 4, the last open one, goes Done (a pop-up, a chime, and the band's bar turns to a rainbow until the next prompt). The board reads the file every 1.5 s, so no one has to tell you a task moved. docs/demo.mp4 is the same with sound.</sub>

Band

<img src="docs/band-closed.png" alt="Claude Code with the board closed: only the one-line band above the prompt" width="100%">

<sub>The board is closed; the band is the one line above the prompt, in every session of the project.</sub>

  • Above your prompt: the state word (In progress, Waiting for you, Idle or Done), done out of total (3/8) and a bar. The plan reads In progress while Claude is working on it, even when no task is marked In Progress, and Waiting for you when the only tasks left wait on your check.
  • A task is done → a pop-up ✅ <task> · N left and, in the terminal, a chime.
  • You come back, or start a new session → the band shows the file's state; the board has Claude's last recap.

<table> <thead><tr><th width="480">Looks like</th><th>Part</th><th>Shows</th><th>Press</th></tr></thead> <tbody> <tr><td><img src="docs/parts/band-mascot.png" width="480" alt="Band, the mascot boxed"></td><td><b>Mascot</b></td><td>Moves while a task is running (In Progress or Verifying); stands still otherwise.</td><td>Opens or closes the board.</td></tr> <tr><td><img src="docs/parts/band-dot.png" width="480" alt="Band, the dot boxed"></td><td><b>Dot</b></td><td>The colour of the most urgent open task: red Blocked, yellow waiting for a check, blue In Progress, grey Todo; green when every task is Done. Red here: task 6 is blocked.</td><td>Opens or closes the board.</td></tr> <tr><td><img src="docs/parts/band-name.png" width="480" alt="Band, the plan name boxed"></td><td><b>Plan name</b></td><td>The plan's name, cut with <code>…</code> when the band is short of room.</td><td>One plan: opens or closes the board. Several plans: opens the plan list.</td></tr> <tr><td><img src="docs/parts/band-menu.png" width="480" alt="Band, the menu arrow boxed"></td><td><b><code>▾</code></b></td><td>Shown when there are several plans.</td><td>Opens the plan list under the band; pick a plan to show it.</td></tr> <tr><td><img src="docs/parts/band-state.png" width="480" alt="Band, the state word boxed"></td><td><b>State word</b></td><td><code>In progress</code>, <code>Stalled since …</code>, <code>Waiting for you since …</code>, <code>Idle since …</code> or <code>Done at …</code> (see the board's plan states). Left out when the band is short of room.</td><td>Opens or closes the board.</td></tr> <tr><td><img src="docs/parts/band-bar.png" width="480" alt="Band, the progress bar boxed"></td><td><b>Bar</b></td><td>Done tasks over all tasks but the Canceled ones, filled in green; a rainbow once the last task goes Done.</td><td>Opens or closes the board.</td></tr> <tr><td><img src="docs/parts/band-count.png" width="480" alt="Band, the count boxed"></td><td><b>Count</b></td><td>The same as a number: <code>2/8</code>.</td><td>Opens or closes the board.</td></tr> <tr><td><img src="docs/parts/band-planfile.png" width="480" alt="Band, Plan file boxed"></td><td><b><code>Plan file ›</code></b></td><td>Reads <code>‹ Board</code> while the plan file is open.</td><td>Opens the plan file in the board pane; <code>‹ Board</code> goes back.</td></tr> </tbody> </table>

<table> <thead><tr><th width="480">Looks like</th><th>State</th><th>When</th></tr></thead> <tbody> <tr><td><img src="docs/parts/band-whole.png" width="480" alt="Band, in progress"></td><td><b>In progress</b></td><td>A task is running, or Claude is working on the plan now. Red dot: one task is blocked.</td></tr> <tr><td><img src="docs/states/band-board-open.png" width="447" alt="Band beside the open board"></td><td><b>Board open</b></td><td>The board takes the right of the window, so the name is cut and the state word left out; the dot still carries the colour.</td></tr> <tr><td><img src="docs/states/band-waiting.png" width="480" alt="Band, waiting for you"></td><td><b>Waiting for you</b></td><td>Nothing is running and a task waits for your check, with you as its checker or its executor: <code>Waiting for you since 19:40</code>, in the <code>◆ needs you</code> colour.</td></tr> <tr><td><img src="docs/states/band-idle.png" width="447" alt="Band, idle"></td><td><b>Idle</b></td><td>Nothing is running and nothing waits on you: grey dot, still mascot.</td></tr> <tr><td><img src="docs/states/band-done.png" width="447" alt="Band, done"></td><td><b>Done</b></td><td>Every task is Done: green dot, full bar.</td></tr> <tr><td><img src="docs/states/band-rainbow.png" width="480" alt="Band with a rainbow bar"></td><td><b>Last task done</b></td><td>Right after the last open task goes Done: a pop-up and a chime, and the bar is a moving rainbow until your next prompt.</td></tr> <tr><td><img src="docs/states/band-plan-file.png" width="447" alt="Band while the plan file is open"></td><td><b>Plan file open</b></td><td><code>Plan file ›</code> becomes <code>‹ Board</code>.</td></tr> </tbody> </table>

Board

<img src="docs/board-in-progress.png" alt="Board while the plan is in progress" width="100%">

<sub>The board opens in a pane on the right; the band stays above the prompt. These board screens read the board from a command that lists two plans, so they show the plan's times and stalled tasks; a plain PROGRESS.md, as in the video, draws the same board without those. Tokens and cost are counted by plan-tracker itself, so either source shows them.</sub>

  • Claude adds a task → a card for it appears.
  • A task is blocked → its card sits red at the top of In Progress; open its page and the latest note says why.
  • You want to know who runs what → each open card is tagged with who has it: Opus, Sonnet, Haiku or you (in Verify, who checks it). A Done task's page says who did it and who checked it.

<table> <thead><tr><th width="480">Looks like</th><th>Part</th><th>Shows</th><th>Press</th></tr></thead> <tbody> <tr><td><img src="docs/parts/head-dot.png" width="391" alt="Header, the dot boxed"></td><td><b>Dot</b></td><td>As on the band: the most urgent open task's colour.</td><td>&mdash;</td></tr> <tr><td><img src="docs/parts/head-name.png" width="391" alt="Header, the plan name boxed"></td><td><b>Plan name</b></td><td>The plan's name, in bold.</td><td>Several plans: opens or closes the plan menu.</td></tr> <tr><td><img src="docs/parts/head-state.png" width="391" alt="Header, the state word boxed"></td><td><b>State word</b></td><td>The plan's state and its only time (see Plan states below).</td><td>&mdash;</td></tr> <tr><td><img src="docs/parts/head-count.png" width="391" alt="Header, the count boxed"></td><td><b>Count</b></td><td>Done tasks over all tasks but the Canceled ones.</td><td>&mdash;</td></tr> <tr><td><img src="docs/parts/head-menu.png" width="391" alt="Header, the menu arrow boxed"></td><td><b><code>▾</code></b></td><td>Shown when there are several plans; <code>▴</code> while the plan menu is open.</td><td>Opens or closes the plan menu.</td></tr> <tr><td><img src="docs/parts/head-planfile.png" width="372" alt="Header, Plan file boxed"></td><td><b><code>Plan file ›</code></b></td><td>The plan behind the board.</td><td>Opens the plan file page.</td></tr> <tr><td><img src="docs/parts/head-close.png" width="372" alt="Header, the close mark boxed"></td><td><b><code>✕</code></b></td><td>Closes the pane.</td><td>Closes the board; the band stays.</td></tr> <tr><td><img src="docs/parts/board-menu.png" width="480" alt="The plan menu open under the header"></td><td><b>Plan menu</b></td><td>This project's plans with state and count; the one shown is highlighted and marked <code>▶</code>.</td><td>A plan: shows its board.</td></tr> <tr><td><img src="docs/parts/board-figures.png" width="437" alt="Tokens and est. cost boxed"></td><td><b>Figures</b></td><td>Tokens and cost of the whole plan, counted by plan-tracker from each API request in every session that had it loaded, a plain <code>PROGRESS.md</code> included. <code>incl. $0.80 on the plan, not one task</code> under it names the part that no single task owns.</td><td>&mdash;</td></tr> <tr><td><img src="docs/parts/board-recap.png" width="480" alt="The recap boxed"></td><td><b>Recap</b></td><td>Claude's two or three sentences: what the plan is for, where it is, what is next or needed from you. <code>updated 12 min ago</code> when the board command gives its time.</td><td>&mdash;</td></tr> <tr><td><img src="docs/parts/board-lanes.png" width="480" alt="The four lane titles boxed"></td><td><b>Lanes</b></td><td>Todo, In Progress, Verify and Done, each with its count; In Progress adds <code>· 1 blocked</code>. Each lane lists its latest-updated task first; Blocked comes first in In Progress.</td><td>&mdash;</td></tr> <tr><td><img src="docs/parts/card-whole.png" width="242" alt="A task card boxed"></td><td><b>Card</b></td><td>One task. The border takes the task's colour (blue here: In Progress). A <code>progress</code> value draws a bar on the card, when the card is wide enough.</td><td>Opens its task page.</td></tr> <tr><td><img src="docs/parts/card-mascot.png" width="242" alt="Card, the mascot boxed"></td><td><b>Card mascot</b></td><td>Moves while the task runs; frozen when it is blocked or stalled; none on Todo and Done cards.</td><td>Opens its task page.</td></tr> <tr><td><img src="docs/parts/card-name.png" width="242" alt="Card, the task name boxed"></td><td><b>Task name</b></td><td>The whole name, wrapped; a marker before it when blocked (<code>⚑ Blocked ·</code>) or waiting for you (<code>◆ needs you ·</code>).</td><td>Opens its task page.</td></tr> <tr><td><img src="docs/parts/card-tag.png" width="242" alt="Card, the tag boxed"></td><td><b>Tag</b></td><td>Who does the task or takes it next: <code>Opus</code>, <code>Sonnet</code>, <code>Haiku</code> or <code>you</code>; in Verify, who checks it; grey <code>stalled</code> when no session is working on it; none on Done, and none when the task's <code>route</code> names neither a model nor you.</td><td>Opens its task page.</td></tr> <tr><td><img src="docs/parts/board-fold.png" width="261" alt="The fold button boxed"></td><td><b><code>+N more ▾</code></b></td><td>A lane holds more cards than it shows.</td><td>Unfolds the lane; <code>Show less ▴</code> folds it again.</td></tr> <tr><td><img src="docs/parts/board-list.png" width="480" alt="The plan list with its search field boxed"></td><td><b>Plan list</b></td><td><code>/plan-tracker</code> lists every plan, latest first, under a <code>Search plans</code> field: name, state, count and when it last changed. Needs a board command that lists several plans; a plain <code>PROGRESS.md</code> opens its board directly.</td><td>Typing filters; Enter or a press opens the plan.</td></tr> <tr><td><img src="docs/parts/board-planfile.png" width="480" alt="The plan file page boxed"></td><td><b>Plan file page</b></td><td>The plan file drawn as Markdown, under <code>‹ Back</code> and its file name. For a plain <code>PROGRESS.md</code> that is the file itself.</td><td><code>‹ Back</code> returns to the board.</td></tr> </tbody> </table>

Plan states

<table> <thead><tr><th width="480">Looks like</th><th>State</th><th>When</th></tr></thead> <tbody> <tr><td><img src="docs/states/plan-in-progress.png" width="480" alt="Plan header, In progress"></td><td><b>In progress</b></td><td>A task is In Progress or Verifying and not stalled, or Claude is working on the plan now: this session runs a turn or a background agent, and the plan is this session's (the one plan of a <code>PROGRESS.md</code>; with a board command, a plan sent with <code>in_session: true</code>). Agents a Workflow starts are not counted. No time.</td></tr> <tr><td><img src="docs/states/plan-stalled.png" width="480" alt="Plan header, Stalled"></td><td><b>Stalled</b></td><td>Every running task is stalled and this session is not working on the plan: your board command marks a task with <code>stalled_since</code>, meaning no session is working on it. A plain <code>PROGRESS.md</code> has no session data and never shows this. <code>Stalled since 19:23</code>, the newest <code>stalled_since</code>.</td></tr> <tr><td><img src="docs/states/plan-waiting.png" width="480" alt="Plan header, Waiting for you"></td><td><b>Waiting for you</b></td><td>Nothing is running and a Needs Verification task has you as its checker or its executor: <code>Waiting for you since 19:40</code>, the later of <code>idle_since</code> and when this session last stopped working (plain without either), in the <code>◆ needs you</code> colour.</td></tr> <tr><td><img src="docs/states/plan-idle.png" width="480" alt="Plan header, Idle"></td><td><b>Idle</b></td><td>Nothing is running and nothing waits on you, including a plan nothing has started: <code>Idle since 19:40</code>, the later of <code>idle_since</code> and when this session last stopped working (plain <code>Idle</code> without either).</td></tr> <tr><td><img src="docs/states/plan-done.png" width="480" alt="Plan header, Done"></td><td><b>Done</b></td><td>Every task is Done or Canceled (one at least Done), or your board command sends <code>finished</code>: <code>Done at 21:40</code>, from <code>finished</code>, else <code>updated</code> (plain <code>Done</code> with neither), with a green dot.</td></tr> </tbody> </table>

Card states

<table> <thead><tr><th width="301">Looks like</th><th>State</th><th>When</th></tr></thead> <tbody> <tr><td><img src="docs/states/card-running.png" width="301" alt="Task card, running"></td><td><b>Running</b></td><td>In Progress: the mascot moves; the tag is the model doing it.</td></tr> <tr><td><img src="docs/states/card-stalled.png" width="301" alt="Task card, stalled"></td><td><b>Stalled</b></td><td>In Progress, but no session is working on it: the mascot stands still and a grey <code>stalled 19:23</code> (<code>stalled Oct 11</code> from another day) replaces the tag; a card too narrow for the time shows the bare <code>stalled</code>.</td></tr> <tr><td><img src="docs/states/card-waiting-for-you.png" width="300" alt="Task card, waiting for you"></td><td><b>Waiting for you</b></td><td>You are its checker or its executor: <code>◆ needs you ·</code> before the name, tag <code>you</code>.</td></tr> <tr><td><img src="docs/states/card-waiting-for-check.png" width="300" alt="Task card, waiting for a check"></td><td><b>Waiting for a check</b></td><td>A model checks it: no marker; the tag is the checker's model. A script checks it: no tag.</td></tr> <tr><td><img src="docs/states/card-blocked.png" width="301" alt="Task card, blocked"></td><td><b>Blocked</b></td><td>Red, <code>⚑ Blocked ·</code> before the name, the mascot frozen; the tag is who runs it.</td></tr> <tr><td><img src="docs/states/card-todo.png" width="300" alt="Task card, to do"></td><td><b>Todo</b></td><td>No mascot; the tag is who will do it.</td></tr> <tr><td><img src="docs/states/card-done.png" width="300" alt="Task card, done"></td><td><b>Done</b></td><td>No tag; its page says who did it.</td></tr> </tbody> </table>

Narrow pane

<img src="docs/narrow.png" alt="Board in a narrow side pane" width="100%">

<sub>Below about 100 columns the lanes stack into one column and the recap wraps to the pane.</sub>

Task page

<img src="docs/task-done.png" alt="Task page of a Done task" width="100%">

<sub>Pressing a card opens its page in the board pane. A row is left out when there is nothing to show.</sub>

  • A task needs your review → its card says ◆ needs you; open its page for the goal and the latest note.

<table> <thead><tr><th width="480">Looks like</th><th>Part</th><th>Shows</th><th>Press</th></tr></thead> <tbody> <tr><td><img src="docs/parts/task-back.png" width="100" alt="Task page, Back"></td><td><b><code>‹ Back</code></b></td><td>&mdash;</td><td>Returns to the board.</td></tr> <tr><td><img src="docs/parts/task-title.png" width="275" alt="Task page, the title"></td><td><b>Title</b></td><td>The task's whole name; the square takes the status colour.</td><td>&mdash;</td></tr> <tr><td><img src="docs/parts/task-goal.png" width="480" alt="Task page, Goal row"></td><td><b>Goal</b></td><td>One sentence on what the task is for.</td><td>&mdash;</td></tr> <tr><td><img src="docs/parts/task-status.png" width="238" alt="Task page, Status row"></td><td><b>Status</b></td><td><code>To do</code>, <code>In progress</code>, <code>Waiting for your check</code>, <code>Waiting for a check</code>, <code>Being checked</code>, <code>⚑ Blocked</code> or <code>Done</code>, in its colour; a stalled task, with no session working on it, adds <code>· stalled since …</code>.</td><td>&mdash;</td></tr> <tr><td><img src="docs/parts/task-doneby.png" width="358" alt="Task page, Done by row"></td><td><b>Done by</b></td><td>Who runs it, with the model as a tag; <code>you</code> for your own tasks.</td><td>&mdash;</td></tr> <tr><td><img src="docs/parts/task-checkedby.png" width="257" alt="Task page, Checked by row"></td><td><b>Checked by</b></td><td>Who checked it, once the task is Done.</td><td>&mdash;</td></tr> <tr><td><i>Not in these shots</i></td><td><b>Progress</b></td><td>The <code>progress</code> bar.</td><td>&mdash;</td></tr> <tr><td><img src="docs/parts/task-note.png" width="321" alt="Task page, Latest note row"></td><td><b>Latest note</b></td><td>The newest note on the task. A file path in it is a link; a terminal without OSC 8 hyperlink support prints the address after the link.</td><td>A path opens the file.</td></tr> <tr><td><img src="docs/parts/task-blocked-because.png" width="468" alt="Task page, Blocked because row"></td><td><b>Blocked because</b></td><td>Takes the Latest note's place on a blocked task.</td><td>&mdash;</td></tr> <tr><td><i>Not in these shots</i></td><td><b>Tokens, cost</b></td><td>Above the table: what the subagents that worked on this task used. None for a task you run yourself.</td><td>&mdash;</td></tr> <tr><td><i>Not in these shots</i></td><td><b>Sessions</b></td><td>One line per session that worked on the task: when, where (<code>terminal</code>, <code>Desktop</code>, <code>VS Code extension</code>), and that session's tokens and cost. None for a task you run yourself.</td><td>&mdash;</td></tr> </tbody> </table>

Compared

Use plan-tracker alongside Claude Code's own views; each shows something different.

Claude Code'sIt showsplan-tracker adds
Agent map (Desktop, VS Code)This session's subagents, each with its status, time and tokensThe plan's tasks across sessions: who has each one and what waits on you
Background tasks (/tasks)Shells and subagents running in this session, cleared when Claude Code exitsWhich tasks are running, blocked or done, kept in a file after the session ends

Limits

  • Read-only for your board: it never writes PROGRESS.md.
  • Only sessions with plan-tracker loaded are counted.
  • Main-session work counts for the plan, not a task; a task shows figures only for a subagent whose brief names its row.
  • With a plain PROGRESS.md, a session's work counts for the plan only after that session has edited the file with Claude's file tools; a session that changes it another way (a shell command, an editor) counts for nothing; a session that edited it once and then works on something else still counts for the plan while a row is In Progress.
  • With board_command, counting needs the command's in_session and each row's exact task text.
  • Claude Code makes some requests the plugin never sees (prompt suggestions); their cost is spread over that interval's requests, or goes to unowned outside 0
Source 8 files
hooks/register.tsx 1812 lines
1/**
2 * The plan board for a terminal: a one-row band above the prompt (`● <plan> ▾ <bar> n/m  Plan file ›`: "▾" opens the plan
3 * list above the prompt, the bar opens or closes the board, "Plan file ›" opens the board on the plan file) and a pane with
4 * the plan dropdown, the plan line and four lanes (Todo, In Progress, Verify, Done) of bordered cards (press one for its page).
5 * Picking a plan in the band or in the pane switches both.
6 *
7 * The data is the board file (PROGRESS.md, read again every 1.5 s, so the board follows the file) or, with the setting
8 * `board_command`, that command's JSON; read on session.start, on each prompt, at each turn's start and end and each background
9 * agent's start and stop, after a Bash call that runs the command, and every 10 s while the pane is open; one run is in flight at a
10 * time, and none holds a prompt, a turn or a Bash result. While this session runs a turn or a background agent, its own plans (the
11 * board file's one plan; a command's plans marked `in_session: true`) read In progress. With a `board_command`, `/plan-tracker` opens the pane at once on the list of the plans not Done or Canceled, latest updated first, under a
12 * search field that has the keys, with no text, whatever the surface says (a Desktop client may not have attached yet), and reads the list again
13 * behind it; `/plan-tracker <words>` puts the words in the field, and opens the plan when the answer is in if they are its name or anchor or leave
14 * one row. Typing filters every plan in the mod; Enter or a press on a row opens that plan, as do the band and the plan menus. A command that lists
15 * no `matches` but two or more `plans` has them listed; one that prints a single plan, and a plain board file, open that plan's board. When the
16 * board cannot be drawn a toast says why. A PLAN-DONE block in a Bash result becomes a toast, a chime
17 * and a notice in the conversation, and one with `0 left` makes the band's bar a rainbow until the person's next prompt. With no
18 * `board_command`, a row of the board file that goes Done does the same, with no block: the file is the only source.
19 *
20 * The usage ledger: every model request of this session (`turn.step`, the main thread's and each subagent's) is counted to the plan row it
21 * worked on, or to the plan, or to nobody (`hooks/ledger.ts` says whose); the requests of one interval between two `session.measure`
22 * readings are scaled to the host's own cost; the whole ledger is written to `~/.claude/mods-logs/plan-tracker-usage/<session id>.json`
23 * after each main turn and at the session's end, never inside a request's chain. Every session's file is summed (`hooks/usage.ts`) into
24 * the figures the board draws, so a plain PROGRESS.md has them too.
25 */
26import { atom, read, update } from 'claude-code'
27import type { EngineInterface, Register, Timer, TurnUsage } from 'claude-code'
28
29import type { Live, PlanBoard, PlanEntry, PlanStatus } from '../types'
30import {
31  BAND_MASCOT_SPACE,
32  MASCOT,
33  bandPlanOf,
34  bandPose,
35  bandPoseIndex,
36  detailOf,
37  directPick,
38  FRAME_MS,
39  doneBlocks,
40  doneHeader,
41  failureText,
42  finishedAnchor,
43  isActive,
44  isComplete,
45  isOpen,
46  isRainbow,
47  isWorking,
48  listOf,
49  listedMatches,
50  localIso,
51  messageOf,
52  movement,
53  noBoardFile,
54  parseBoard,
55  parseProgress,
56  planOf,
57  planStateOf,
58  planStateText,
59  truncate,
60  settings,
61  applyOptions,
62  boardArgv,
63  commandMarkOf,
64  withWork,
65} from './board'
66import type { LaneKey, Work } from './board'
67import type { FileView } from './draw'
68import { drawBand, drawPane, drawPicker, holdsSomething, isProportionalSurface, listedMatchOf, listedOf } from './draw'
69import {
70  SCALE_INCLUDES_SUBAGENTS,
71  bookInto,
72  briefRow,
73  emptyLedger,
74  hasEntries,
75  keyPaths,
76  ledgerDir,
77  ledgerNames,
78  ledgerText,
79  mainOwner,
80  parseLedger,
81  requestUsd,
82  resolveAgent,
83  rowOwner,
84  scaleInterval,
85  settle,
86  tokensOf,
87} from './ledger'
88import type { AgentClaims, Claim, LedgerFile, Owner, Request } from './ledger'
89import { planKey, readLedgers, withUsage } from './usage'
90
91const COMMAND = 'plan-tracker'
92const PANE_ID = 'plan-tracker'
93const PANE_TITLE = 'Plans'
94const REFRESH_MS = 10_000
95const SCRIPT_TIMEOUT_MS = 30_000
96const DONE_SOUND = 'sounds/done.wav'
97const DONE_GAIN = 0.6
98const TOAST_COLUMNS = 70
99/**
100 * Opening the pane asks for the keyboard, so the arrows and PageUp/PageDown scroll it at once (a pane taller than its window
101 * scrolls only while focused; the wheel needs a fullscreen terminal), and for 60 rows, up to what the layout spares.
102 */
103const OPEN = { id: PANE_ID, title: PANE_TITLE, focus: true, rows: 60 } as const
104
105/** The tracker's last answer: a board, or the one line saying why there is none; null until the first answer. */
106const live = atom({ plugin: 'plan-tracker', key: 'live' } as const, null)
107/** The `--query` the refreshes pass: `*` while the pane lists the plans, else the plan opened from the list, the band or a plan menu, or the one that just finished. */
108const query = atom({ plugin: 'plan-tracker', key: 'query' } as const, '')
109/** The query that asks the board command for the list of every plan. */
110const ALL_PLANS = '*'
111/** Whether the pane shows the plan list: `/plan-tracker` turns it on, opening a plan turns it off. */
112const listing = atom({ plugin: 'plan-tracker', key: 'listing' } as const, false)
113/** The list's search field text; the list is filtered by it here, with no script run per key. */
114const search = atom({ plugin: 'plan-tracker', key: 'search' } as const, '')
115/** Every plan, from the last answer to the query `*`: the list is drawn from it at once while `/plan-tracker` reads a new one. */
116const allPlans = atom({ plugin: 'plan-tracker', key: 'allPlans' } as const, null)
117/** The anchor picked in the band or the pane; null until one is picked, when the tracker's own `selected` stands. */
118const selected = atom({ plugin: 'plan-tracker', key: 'selected' } as const, null)
119const card = atom({ plugin: 'plan-tracker', key: 'card' } as const, null)
120/** Whether the pane shows the plan file instead of the board. */
121const file = atom({ plugin: 'plan-tracker', key: 'file' } as const, false)
122/** The anchor of the plan a PLAN-DONE with 0 left finished; cleared by the person's next prompt. */
123const finished = atom({ plugin: 'plan-tracker', key: 'finished' } as const, null)
124/** The animation frame; advanced by the one timer, only while something on screen moves. */
125const frame = atom({ plugin: 'plan-tracker', key: 'frame' } as const, 0)
126/** Whether the pane's plan dropdown shows its list. */
127const menu = atom({ plugin: 'plan-tracker', key: 'menu' } as const, false)
128/** The lanes that show all their cards, as `<anchor>:<lane>`. */
129const expanded = atom({ plugin: 'plan-tracker', key: 'expanded' } as const, [])
130/** Whether the band's plan list shows. */
131const bandMenu = atom({ plugin: 'plan-tracker', key: 'bandMenu' } as const, false)
132/** What of this session is at work: a main turn running, and its background agents not yet ended. */
133const working = atom({ plugin: 'plan-tracker', key: 'working' } as const, { turn: false, agents: [] })
134/** When `working` last went from something to nothing; null until it has. */
135const stoppedAt = atom({ plugin: 'plan-tracker', key: 'stoppedAt' } as const, null)
136/** What the usage ledger keeps across a reload of the module (see `persistCarry`): the session, what is known of each subagent, the requests not yet in the file, the board files the session changed. */
137const carried = atom({ plugin: 'plan-tracker', key: 'usageCarry' } as const, { session: '', agents: {}, unwritten: [], edited: [] })
138
139/** The session's project root: where the board file and a relative path in a note are looked up. */
140async function projectRoot($: EngineInterface): Promise<string> {
141  if (settings.root === '') {
142    settings.root = (await $.session.root().catch(() => '')).replace(/\/+$/, '')
143  }
144
145  return settings.root
146}
147
148/** How a command runs: in the project root, with `CLAUDE_PROJECT_DIR` pointing at it. */
149async function commandInit($: EngineInterface, timeoutMs = SCRIPT_TIMEOUT_MS) {
150  const root = await projectRoot($)
151
152  return { cwd: root, env: { CLAUDE_PROJECT_DIR: root }, timeoutMs }
153}
154
155/** The board file's absolute path (`board_location`, relative to the project root). */
156const boardFile = (root: string): string => (settings.boardLocation.startsWith('/') ? settings.boardLocation : `${root}/${settings.boardLocation}`)
157
158// ---------------------------------------------------------------- the board: a command, or the board file
159
160/** The board file read as a board, or the one line saying why there is none. */
161async function readBoardFile($: EngineInterface): Promise<Live> {
162  if (settings.boardLocation.startsWith('command:')) {
163    return { error: 'plan-tracker: board_location is a "command:" board; set board_command to a command that prints the board as JSON' }
164  }
165
166  const file = boardFile(await projectRoot($))
167
168  if (!(await $.fs.exists(file).catch(() => false))) {
169    return noBoardFile(file)
170  }
171
172  try {
173    return parseProgress(await $.fs.read(file), file, file.split('/').at(-2) ?? 'Plan')
174  } catch (error) {
175    return { error: `plan-tracker: cannot read ${file}: ${messageOf(error)}` }
176  }
177}
178
179/** The board for `text`: `board_command`'s JSON when it is set, else the board file. */
180async function fetchBoard($: EngineInterface, text: string): Promise<Live> {
181  if (settings.boardCommand === '') {
182    return readBoardFile($)
183  }
184
185  try {
186    const { exitCode, stdout, stderr } = await $.process.run(boardArgv(await $.session.id(), text), await commandInit($))
187
188    return exitCode === 0 ? parseBoard(stdout) : { error: failureText(exitCode, stderr) }
189  } catch (error) {
190    return { error: `plan-tracker: could not run the board command: ${messageOf(error)}` }
191  }
192}
193
194/** The answer last written to `live`, as text; undefined until one is. */
195let shownJson: string | undefined
196
197/**
198 * The board command's (or the board file's) answer for `text` with the usage the ledgers hold (`withUsage`), the ledgers read while the
199 * board is. The plans the answer names are kept for the usage ledger's owners as soon as the board is in, without waiting for a ledger
200 * that is being read again. A board command's own `usage` keys are not read: the plugin counts by itself, so there is one source.
201 */
202async function fetchWithUsage($: EngineInterface, text: string): Promise<Live> {
203  const reading = readLedgers($).catch(async (error: unknown) => {
204    await log($, 'ledger', `the usage ledgers were not read: ${messageOf(error)}`)
205
206    return undefined
207  })
208  const answer = await fetchBoard($, text)
209
210  if (!('board' in answer)) {
211    return answer
212  }
213
214  trackerPlans = answer.board.plans
215
216  const ledgers = await reading
217
218  return ledgers === undefined ? answer : { board: withUsage(answer.board, ledgers, planKey) }
219}
220
221/** The run of the script under way, and the one rerun waiting behind it. */
222let inFlight: Promise<void> | undefined
223let queued: Promise<void> | undefined
224
225/** Runs the script once for the current query and stores its answer (an answer to `*` also as the list); the state write redraws the band and the pane. */
226async function refreshOnce($: EngineInterface) {
227  const asked = await read($, query)
228  const answer = await fetchWithUsage($, asked)
229  const text = JSON.stringify(answer)
230
231  if (asked === ALL_PLANS && 'board' in answer) {
232    const list = listOf(answer.board)
233
234    // Written only when it changed, as `live` is below: a write redraws, and a redraw hands the desktop's buttons new handles.
235    if (JSON.stringify(list) !== JSON.stringify(await read($, allPlans))) {
236      await update($, allPlans, () => list)
237    }
238  }
239
240  // A write redraws what read the value, even one that changes nothing, and a redraw hands the desktop's buttons new handles:
241  // an answer like the one shown is not written.
242  if (text === shownJson) {
243    return
244  }
245
246  await update($, live, () => answer)
247  shownJson = text
248
249  // Only the board file has no PLAN-DONE to say that a row went Done; a board command prints its own.
250  if (settings.boardCommand === '') {
251    await announceFileDone($, answer)
252  }
253}
254
255/** The status of each row of the board file at its last read, by task; undefined until the first read, which is the baseline. */
256let lastStatuses: Map<string, PlanStatus> | undefined
257
258/**
259 * A read of the board file that moved rows to Done: each is a toast and a notice, `✅ <task> · N left` (N: rows neither Done nor
260 * Canceled), the read as a whole one chime, and a read that leaves every row Done or Canceled turns the band to a rainbow until
261 * the person's next prompt. The first read, a row first seen already Done, and an error answer (the baseline stays) give nothing.
262 */
263async function announceFileDone($: EngineInterface, answer: Live) {
264  if (!('board' in answer)) {
265    return
266  }
267
268  const plan = answer.board.plans[0]
269  const before = lastStatuses
270
271  lastStatuses = new Map((plan?.rows ?? []).map(row => [row.task, row.status]))
272
273  if (plan !== undefined && plan.anchor === (await read($, finished)) && plan.rows.some(isOpen)) {
274    await unmarkFinished($, plan.anchor)
275  }
276
277  if (before === undefined || plan === undefined) {
278    return
279  }
280
281  const went = plan.rows.filter(row => row.status === 'Done' && before.has(row.task) && before.get(row.task) !== 'Done')
282  const left = plan.rows.filter(isOpen).length
283
284  for (const [at, row] of went.entries()) {
285    await notify($, row.task, String(left + went.length - 1 - at))
286  }
287
288  if (went.length > 0) {
289    await chime($)
290
291    if (isComplete(plan)) {
292      await markFinished($, plan.anchor)
293    }
294  }
295}
296
297/**
298 * Reads the tracker again. One run is in flight at a time: a call that comes meanwhile (the 10 s timer, a prompt, a Bash
299 * call) shares the one rerun that starts when it ends, which reads the query as it is by then. The promise ends with the
300 * run that answers the call.
301 */
302function refreshBoard($: EngineInterface): Promise<void> {
303  if (inFlight === undefined) {
304    const run = refreshOnce($).finally(() => {
305      if (inFlight === run) {
306        inFlight = undefined
307      }
308    })
309
310    inFlight = run
311
312    return run
313  }
314
315  queued ??= inFlight
316    .catch(() => undefined)
317    .then(() => {
318      queued = undefined
319
320      return refreshBoard($)
321    })
322
323  return queued
324}
325
326/** `refreshBoard` for a place that must not fail because the script did. */
327const refreshQuietly = ($: EngineInterface) => refreshBoard($).catch(() => undefined)
328
329const lastDrawn = new Map<string, { key: string; tree: unknown }>()
330
331/**
332 * The tree `build` makes for `data`, or the one made last time in `slot` when `data` is the same. Every Button and every link with a
333 * press gets a new handle when a render hook builds its tree, and the engine keeps only the latest tree's handles: a click that
334 * carries an earlier tree's handle is "ui_press not handled" and nothing happens. A render that draws what was drawn therefore hands
335 * back the tree it drew, whose handles are the ones the surface holds. `data` is every input of the drawing (JSON, closures left out).
336 */
337export function steadily<T>(slot: string, data: unknown, build: () => T): T {
338  const key = JSON.stringify(data)
339  const held = lastDrawn.get(slot)
340
341  if (held !== undefined && held.key === key) {
342    return held.tree as T
343  }
344
345  const tree = build()
346
347  lastDrawn.set(slot, { key, tree })
348
349  return tree
350}
351
352/** Starts a read of the tracker without waiting for it (a slow script must not hold a prompt or a Bash result), then redraws what moves. */
353function refreshInBackground($: EngineInterface) {
354  void refreshQuietly($)
355    .then(() => syncAnimation($))
356    .catch(() => undefined)
357}
358
359let refresh: Timer | undefined
360/** The poll of the board file: it runs for the whole session, so the band and the board follow the file without a command. */
361let watch: Timer | undefined
362
363/** How often the board file is read again (it is read whole and redrawn only when its content changed). */
364const WATCH_MS = 1_500
365
366function startWatch($: EngineInterface) {
367  if (settings.boardCommand === '') {
368    watch ??= $.clock.every(WATCH_MS, () => void refreshInBackground($))
369  }
370}
371
372function startRefresh($: EngineInterface) {
373  refresh ??= $.clock.every(REFRESH_MS, () => void refreshQuietly($))
374}
375
376function stopRefresh() {
377  refresh?.cancel()
378  refresh = undefined
379}
380
381// ---------------------------------------------------------------- what is shown
382
383/**
384 * The board the tracker last answered, with this session's work on its own plans (`withWork`), or undefined while there is none (no
385 * answer yet, or an error line). A drawing that reads it is redrawn when the work changes.
386 */
387async function boardOf($: EngineInterface): Promise<PlanBoard | undefined> {
388  const answer = await read($, live)
389
390  return answer !== null && 'board' in answer ? withWork(answer.board, await read($, working), await read($, stoppedAt)) : undefined
391}
392
393// ---------------------------------------------------------------- this session at work
394
395/**
396 * Changes what of this session is at work and redraws what reads it (the band too, with the pane closed); when that leaves nothing at
397 * work, `stoppedAt` becomes now. A change that changes nothing writes nothing.
398 */
399async function changeWork($: EngineInterface, change: (work: Work) => Work) {
400  const before = await read($, working)
401
402  if (JSON.stringify(change(before)) === JSON.stringify(before)) {
403    return
404  }
405
406  let was = before
407
408  await update($, working, current => {
409    was = current
410
411    return change(current)
412  })
413
414  if (isWorking(was) && !isWorking(await read($, working))) {
415    await update($, stoppedAt, () => localIso(Date.now()))
416  }
417
418  await syncAnimation($)
419}
420
421/** Ended agent states: `$.agent.list()` showing one of these, or not listing the agent at all, ends it here. */
422const ENDED = ['completed', 'failed', 'killed']
423
424/** Drops the background agents `$.agent.list()` shows ended or no longer lists. */
425async function pruneAgents($: EngineInterface) {
426  if ((await read($, working)).agents.length === 0) {
427    return
428  }
429
430  const running = new Set((await $.agent.list()).flatMap(agent => (ENDED.includes(agent.status) ? [] : [agent.id])))
431
432  await changeWork($, work => ({ ...work, agents: work.agents.filter(id => running.has(id)) }))
433}
434
435/** The plan picked (else the tracker's own choice). */
436async function shownPlan($: EngineInterface): Promise<PlanEntry | undefined> {
437  const board = await boardOf($)
438
439  return board === undefined ? undefined : planOf(board, await read($, selected))
440}
441
442/** The most characters of the plan file the pane draws (one drawing holds 100000 in all). */
443const FILE_CHARS = 90000
444
445/** The plan file's text for the pane, or why it cannot be read. */
446async function loadFile($: EngineInterface, plan: PlanEntry): Promise<FileView> {
447  try {
448    const text = await $.fs.read(plan.plan_file)
449
450    return { text: text.length > FILE_CHARS ? `${text.slice(0, FILE_CHARS)}\n\n… (cut here; open the file for the rest)` : text }
451  } catch (error) {
452    return { error: `cannot read ${plan.plan_file}: ${messageOf(error)}` }
453  }
454}
455
456// ---------------------------------------------------------------- the log, the toast and the chime
457
458/** One line of ~/.claude/mods-logs/plan-tracker.jsonl; `error` is null for a notice that was shown. `extra` adds fields after the four. */
459async function log($: EngineInterface, stage: string, error: string | null, extra: Record<string, unknown> = {}) {
460  try {
461    const home = await $.env.get('HOME')
462
463    if (home === undefined) {
464      return
465    }
466
467    const line = JSON.stringify({
468      ts: new Date().toISOString(),
469      session_id: await $.session.id().catch(() => ''),
470      stage,
471      error,
472      ...extra,
473    })
474
475    await $.process.run(['/bin/sh', '-c', 'mkdir -p "$1" && cat >> "$1/plan-tracker.jsonl"', 'sh', `${home}/.claude/mods-logs`], {
476      stdin: `${line}\n`,
477    })
478  } catch {
479    // The log is best effort: it must not break the Bash call it reports on.
480  }
481}
482
483/** Runs `work`; a throw is logged under `stage` and answers false. */
484async function attempt($: EngineInterface, stage: string, work: () => unknown): Promise<boolean> {
485  try {
486    await work()
487
488    return true
489  } catch (error) {
490    await log($, stage, messageOf(error))
491
492    return false
493  }
494}
495
496// ---------------------------------------------------------------- the usage ledger
497
498/** The plans the board last answered (`refreshOnce`), as they came: whose work a request is, is read from them. */
499let trackerPlans: readonly PlanEntry[] = []
500
501/** The board files this session, or one of its agents, has changed with a file tool: with a plain PROGRESS.md, such a session works the plan the file holds. */
502const edited = new Set<string>()
503
504/**
505 * The plans the owners read, each keyed as the ledgers key it (`planKey`: a plain PROGRESS.md's plan is `progress` in every project, so its
506 * key is the file) and marked this session's by what the board says (`in_session` of a board command) or, for a plain PROGRESS.md, by the
507 * session having changed the file. The band's In progress state keeps reading the plans as the board gave them.
508 */
509function ownerPlans(): PlanEntry[] {
510  return trackerPlans.map(plan => ({ ...plan, anchor: planKey(plan), in_session: settings.boardCommand === '' ? edited.has(plan.plan_file) : plan.in_session === true }))
511}
512
513/** The requests recorded since the last interval closed. `turn.step` pushes here without an `await`; a `session.measure` that moves the cost books them. */
514let pending: Request[] = []
515
516/**
517 * What is known of each subagent, by agent id: the rows it claimed (its brief's, each verified In Progress write of its own) and its
518 * parent. Whose its requests are is worked out from this and the tracker's latest answer each time (`resolveAgent`), never fixed at the spawn.
519 */
520const agents = new Map<string, AgentClaims>()
521
522/** The ledger as booked (closed intervals only); null until `ensureLedger` has read the file or started a new one. */
523let ledger: LedgerFile | null = null
524
525let loading: Promise<void> | undefined
526
527/** The host's `cost.usd` at the end of the last interval, or at load; null when not known. */
528let lastUsd: number | null = null
529
530/** Whether the next interval is the first since this board loaded: its requests are not scaled. */
531let isFirstInterval = true
532
533/** Whether the host keeps a cost ledger; once a reading shows it does not, nothing waits for an interval to close. */
534let hostHasCost = true
535
536/** Whether the ledger or the open interval changed since the file was written. */
537let isDirty = false
538
539/** The surface the session last drew on, which the file records. */
540let surfaceSeen = 'unknown'
541
542/** Whether this session's `usage-shape` line has been logged. */
543let isShapeLogged = false
544
545/** Whether the session's ledger file exists (read at load, or written since). A session with no entry of its own makes none: a headless run would leave one file per run. */
546let hasFile = false
547
548/** The file `ledger` is written to, chosen with it at load (`ensureLedger`); null before, or when no free name could be found. The two are always used together. */
549let ledgerFile: string | null = null
550
551/** How many of `pending` the file already holds (at table price), and the count of intervals closed: a write only counts requests of the interval it saw. */
552let writtenUpTo = 0
553let intervalNo = 0
554
555/** A write of the file that has not ended in this long is given up (logged), so the next write is not held behind it. */
556const WRITE_TIMEOUT_MS = 10_000
557
558/**
559 * Reads the session's ledger file, or starts a new ledger when there is none: a board that reloads mid-session adds to what it wrote
560 * before. A file that cannot be read as this session's ledger is left as it is (it may hold the session's earlier usage): the ledger is
561 * written to the next name of `ledgerNames`. Once per session; never throws.
562 */
563function ensureLedger($: EngineInterface): Promise<void> {
564  loading ??= (async () => {
565    let held: LedgerFile | undefined
566    let file: string | null = null
567    let session = ''
568
569    try {
570      session = await $.session.id()
571
572      const home = await $.env.get('HOME')
573      const dir = home === undefined || home === '' ? undefined : ledgerDir(home)
574
575      for (const name of dir === undefined || session === '' ? [] : ledgerNames(session)) {
576        const path = `${dir}/${name}`
577
578        if (!(await $.fs.exists(path))) {
579          file = path
580
581          break
582        }
583
584        try {
585          held = parseLedger(await $.fs.read(path), session)
586        } catch (error) {
587          await log($, 'ledger', `${path} not read: ${messageOf(error)}`)
588
589          continue
590        }
591
592        if (held !== undefined) {
593          file = path
594
595          break
596        }
597
598        await log($, 'ledger', `${path} not read: it is not a ledger of this session; it is left as it is and the ledger goes to another file`)
599      }
600
601      if (file === null && session !== '') {
602        await log($, 'ledger', 'no file name is free for this session\'s ledger: its usage is not written')
603      }
604    } catch (error) {
605      await log($, 'ledger', `ledger file not read: ${messageOf(error)}`)
606    }
607
608    if (session === '') {
609      loading = undefined
610
611      return
612    }
613
614    ledger = held ?? emptyLedger(session, surfaceSeen)
615    ledgerFile = file
616    hasFile = held !== undefined
617  })()
618
619  return loading
620}
621
622/** Loads the ledger, takes back what a reload left in the state, and reads the host's cost at this moment, which the first interval's change is counted from. */
623async function startLedger($: EngineInterface) {
624  await ensureLedger($)
625  await restoreCarry($)
626
627  const cost = (await $.session.usage()).cost?.usd
628
629  lastUsd ??= cost ?? null
630  hostHasCost = cost !== undefined
631}
632
633/** Forgets the session: the next one (after a `/clear` the same process goes on under a new id) starts a ledger of its own, with none of this one's plans. */
634function resetLedger($: EngineInterface) {
635  ledger = null
636  ledgerFile = null
637  loading = undefined
638  pending = []
639  writtenUpTo = 0
640  intervalNo += 1
641  trackerPlans = []
642  agents.clear()
643  edited.clear()
644  lastUsd = null
645  isFirstInterval = true
646  isDirty = false
647  isShapeLogged = false
648  hasFile = false
649  persistCarry($)
650}
651
652const isOwner = (value: unknown): value is Owner | null =>
653  value === null || (typeof value === 'object' && typeof (value as Owner).plan === 'string' && ((value as Owner).row === null || typeof (value as Owner).row === 'string'))
654
655const isCount = (value: unknown): boolean => typeof value === 'number' && Number.isFinite(value)
656
657/** A request read back from the state: the shape `recordRequest` writes, else it is dropped. */
658const isRequest = (value: unknown): value is Request => {
659  const one = value as Request | null
660  const tokens = one?.tokens
661
662  return (
663    typeof one === 'object' && one !== null && isOwner(one.owner) && (one.agentId === undefined || typeof one.agentId === 'string') && (one.wanted === undefined || isClaim(one.wanted)) &&
664    (one.usd === null || isCount(one.usd)) && isCount(one.at) && typeof tokens === 'object' && tokens !== null &&
665    [tokens.in, tokens.cached, tokens.cache_write, tokens.out].every(isCount)
666  )
667}
668
669/** The write of the carry in flight, and whether another was asked meanwhile. */
670let carrying: Promise<void> | undefined
671let isCarryAgain = false
672
673/**
674 * Keeps what is known of each subagent, the requests the file does not hold yet and the board files this session has changed in
675 * `usageCarry` (`$.state`), which a reload of the module outlives, so a worker still running keeps its row, its recent requests are not
676 * lost and the session still works its plan. Not awaited; one write at a time; a failure is ignored.
677 */
678function persistCarry($: EngineInterface) {
679  if (carrying !== undefined) {
680    isCarryAgain = true
681
682    return
683  }
684
685  carrying = (async () => {
686    try {
687      do {
688        isCarryAgain = false
689
690        const session = await $.session.id()
691
692        await update($, carried, () => JSON.parse(JSON.stringify({ session, agents: Object.fromEntries(agents), unwritten: pending.slice(writtenUpTo), edited: [...edited] })))
693      } while (isCarryAgain)
694    } catch {
695      // the carry is a convenience for a reload; the file is the record
696    } finally {
697      carrying = undefined
698    }
699  })()
700}
701
702const isClaim = (value: unknown): value is Claim => typeof value === 'object' && value !== null && typeof (value as Claim).task === 'string' && ((value as Claim).anchor === undefined || typeof (value as Claim).anchor === 'string')
703
704/** Takes back, after a reload, what the carry holds for this session: what is known of each subagent, the unwritten requests and the board files it changed. */
705async function restoreCarry($: EngineInterface) {
706  const held = await read($, carried)
707
708  if (held.session === '' || held.session !== (await $.session.id())) {
709    return
710  }
711
712  for (const [id, known] of Object.entries(held.agents)) {
713    const claims = Array.isArray(known?.claims) ? known.claims.filter(isClaim) : []
714
715    if (!agents.has(id)) {
716      agents.set(id, { claims, ...(typeof known?.parent === 'string' ? { parent: known.parent } : {}) })
717    }
718  }
719
720  if (pending.length === 0 && writtenUpTo === 0) {
721    pending = held.unwritten.filter(isRequest)
722    isDirty = isDirty || pending.length > 0
723  }
724
725  for (const path of held.edited) {
726    if (typeof path === 'string') {
727      edited.add(path)
728    }
729  }
730}
731
732/**
733 * Once per session, logs one `usage-shape` line with the key names of the first usage object `turn.step` reports, nested keys as dotted
734 * paths: it shows whether the runtime carries the 1-hour/5-minute split of cache writes. Not awaited; no value is logged.
735 */
736function noteUsageShape($: EngineInterface, usage: unknown) {
737  if (isShapeLogged || usage === null || usage === undefined) {
738    return
739  }
740
741  isShapeLogged = true
742  void log($, 'usage-shape', null, { kind: 'usage-shape', keys: keyPaths(usage) })
743}
744
745/** Whether `usage` holds the four counts and a model: a response that does not is not a request to count. */
746const isCounted = (usage: TurnUsage): boolean =>
747  typeof usage.model === 'string' &&
748  usage.model !== '<synthetic>' &&
749  [usage.input_tokens, usage.output_tokens, usage.cache_read_input_tokens, usage.cache_creation_input_tokens].every(count => typeof count === 'number' && Number.isFinite(count))
750
751/** Counts one response. No `await`, nothing that can reach the disk: it runs in the request's chain, after the response is whole. */
752function recordRequest($: EngineInterface, agentId: string | undefined, usage: TurnUsage | null) {
753  if (usage === null || !isCounted(usage)) {
754    return
755  }
756
757  const plans = ownerPlans()
758  const { owner, wanted } = agentId === undefined ? { owner: mainOwner(plans), wanted: undefined } : resolveAgent(agents, plans, agentId)
759
760  pending.push({ owner, agentId, ...(wanted === undefined ? {} : { wanted }), tokens: tokensOf(usage), usd: requestUsd(usage.model, usage, agentId === undefined), at: Date.now() })
761  isDirty = true
762  persistCarry($)
763}
764
765/** Looks up again, in the board's latest answer, the rows that the open interval's subagent requests claimed when the answer did not have them yet. */
766function settleOwners() {
767  pending = settle(pending, ownerPlans())
768}
769
770/**
771 * A spawned subagent: its brief's first line, `Tracker row: "<exact row text>"`, is its claim on a row, and `parentAgentId` says which
772 * subagent spawned it. Nothing is decided here: whose its requests are comes from these and the board's latest answer when they are
773 * recorded and booked (`resolveAgent`), because the row may be one made seconds before, which the board's last answer lacks. One
774 * `usage-owner` line says what was known and what it resolved to, so a live miss can be read from the log.
775 */
776function noteSpawn($: EngineInterface, agentId: string, prompt: string, parentAgentId: string | undefined) {
777  const task = briefRow(prompt)
778
779  const plans = ownerPlans()
780
781  agents.set(agentId, { claims: task === undefined ? [] : [{ task }], ...(parentAgentId === undefined ? {} : { parent: parentAgentId }) })
782  persistCarry($)
783  void log($, 'usage-owner', null, {
784    kind: 'usage-owner',
785    agent_id: agentId,
786    brief_row: task ?? null,
787    brief_matched: task !== undefined && rowOwner(plans, task) !== null,
788    parent: parentAgentId ?? null,
789    owner: resolveAgent(agents, plans, agentId).owner,
790    tracker_plans: plans.filter(one => one.in_session === true).length,
791  })
792}
793
794/** A file tool changed `path`: when it is the board file, the session works the plan the file holds, and the file is read again. */
795async function noteBoardChange($: EngineInterface, path: unknown) {
796  if (typeof path !== 'string' || path !== boardFile(await projectRoot($))) {
797    return
798  }
799
800  if (!edited.has(path)) {
801    edited.add(path)
802    persistCarry($)
803  }
804
805  refreshInBackground($)
806}
807
808/**
809 * The end of an interval: `session.measure` says the host's cost moved. The requests since the last interval are scaled to the host's
810 * change (`scaleInterval`) and booked into the ledger. Every measure, closing one or not, leaves one `usage-interval` line in the log:
811 * whether the host had a cost, the host's change, the table's sums for the main thread and for subagents, the counts, the factor.
812 */
813async function closeInterval($: EngineInterface, e: { cost?: { usd: number }; changed: readonly string[] }) {
814  await ensureLedger($)
815  settleOwners()
816
817  const usd = e.cost?.usd
818  const isClosing = usd !== undefined && e.changed.includes('cost')
819  const delta = usd === undefined || lastUsd === null ? null : usd - lastUsd
820  const interval = scaleInterval(pending, delta, { includesSubagents: SCALE_INCLUDES_SUBAGENTS, isFirst: isFirstInterval })
821  const probe = {
822    kind: 'usage-interval',
823    cost_present: usd !== undefined,
824    changed: e.changed,
825    is_first: isFirstInterval,
826    host_delta_usd: delta,
827    table_sum_main_usd: interval.tableMain,
828    table_sum_sub_usd: interval.tableSub,
829    requests_main: interval.requestsMain,
830    requests_sub: interval.requestsSub,
831    factor: interval.factor,
832    is_scaled: isClosing && interval.isScaled,
833  }
834
835  hostHasCost = usd !== undefined
836
837  if (isClosing && ledger !== null) {
838    ledger = { ...bookInto(ledger, interval.booked), measured_usd: usd }
839    pending = []
840    writtenUpTo = 0
841    intervalNo += 1
842    lastUsd = usd
843    isFirstInterval = false
844    isDirty = true
845    persistCarry($)
846    requestWrite($)
847  }
848
849  // A measure that moved only the rate limits (a cost on the host, unchanged) has nothing to say about the cost.
850  if (isClosing || usd === undefined) {
851    void log($, 'usage-interval', null, probe)
852  }
853}
854
855/** Writes the ledger file whole. False when nothing needed writing or the write failed (logged; the next write tries again). */
856async function writeLedger($: EngineInterface): Promise<boolean> {
857  if (!isDirty) {
858    return false
859  }
860
861  await ensureLedger($)
862
863  if (ledger === null || ledgerFile === null) {
864    return false
865  }
866
867  settleOwners()
868
869  // A host with no cost ledger never closes an interval: its requests are booked at the table price as they come.
870  if (!hostHasCost && pending.length > 0) {
871    ledger = bookInto(ledger, scaleInterval(pending, null, { includesSubagents: SCALE_INCLUDES_SUBAGENTS, isFirst: true }).booked)
872    pending = []
873    writtenUpTo = 0
874    intervalNo += 1
875    persistCarry($)
876  }
877
878  // No file for a session with no entry of its own (a headless run, a summarizer): it would only hold what nobody owns, and the tracker reads every file.
879  if (!hasFile && !hasEntries(ledger, pending)) {
880    return false
881  }
882
883  const surface = (await $.session.surfaces().catch(() => []))[0] ?? surfaceSeen
884
885  // From here to the write nothing is awaited: the ledger and the file it belongs to are taken together, so a session that ended meanwhile
886  // (a /clear) can never have its ledger written under the other session's name.
887  const file = ledgerFile
888  const held = ledger
889
890  if (held === null || file === null) {
891    return false
892  }
893
894  surfaceSeen = surface
895  ledger = { ...held, surface }
896  isDirty = false
897  settleOwners()
898
899  const seen = { upTo: pending.length, interval: intervalNo }
900  const text = ledgerText(ledger, pending, localIso(Date.now()))
901
902  try {
903    await writeBounded($, file, text)
904
905    if (ledgerFile === file) {
906      hasFile = true
907
908      // The file now holds the requests of the interval it was written from; what came after is still unwritten.
909      if (seen.interval === intervalNo) {
910        writtenUpTo = Math.max(writtenUpTo, seen.upTo)
911        persistCarry($)
912      }
913    }
914
915    return true
916  } catch (error) {
917    if (ledgerFile === file) {
918      isDirty = true
919    }
920
921    await log($, 'ledger', `${file} not written: ${messageOf(error)}`)
922
923    return false
924  }
925}
926
927/** `$.fs.write`, given up (rejected) when it has not ended in `WRITE_TIMEOUT_MS`: a write that hangs must not hold the writer for good. */
928function writeBounded($: EngineInterface, path: string, text: string): Promise<void> {
929  return new Promise((resolve, reject) => {
930    const timer = $.clock.after(WRITE_TIMEOUT_MS, () => reject(new Error(`the write did not end in ${WRITE_TIMEOUT_MS / 1000} s`)))
931
932    $.fs.write(path, text).then(resolve, reject).finally(() => timer.cancel())
933  })
934}
935
936/** The write in flight, and whether another was asked meanwhile. */
937let writing: Promise<void> | undefined
938let isWriteAgain = false
939
940/**
941 * Asks for the ledger to be written, without waiting for it: one write runs at a time, a request that comes meanwhile makes it write
942 * once more. When something was written the tracker is read again, once, so the board draws the new figures.
943 */
944function requestWrite($: EngineInterface) {
945  if (writing !== undefined) {
946    isWriteAgain = true
947
948    return
949  }
950
951  writing = (async () => {
952    let wrote = false
953
954    try {
955      do {
956        isWriteAgain = false
957        wrote = (await writeLedger($)) || wrote
958      } while (isWriteAgain)
959    } catch (error) {
960      await log($, 'ledger', messageOf(error))
961    } finally {
962      writing = undefined
963    }
964
965    if (wrote) {
966      refreshInBackground($)
967    }
968  })()
969}
970
971/** Shows one PLAN-DONE block as a toast and a notice in the conversation; whatever fails is logged, never thrown. */
972export async function announce($: EngineInterface, block: string) {
973  const done = doneHeader(block)
974
975  if (done === undefined) {
976    await log($, 'parse', `unreadable header: ${block.split('\n')[0] ?? ''}`)
977
978    return
979  }
980
981  await notify($, done.task, done.left, block)
982}
983
984/**
985 * The toast `✅ <task> · <left> left` (the task cut to the toast) and the notice in the conversation: `notice` as given, else the
986 * same line with the whole task. Whatever fails is logged, never thrown; a `sent` line says both were shown.
987 */
988async function notify($: EngineInterface, task: string, left: string, notice = `✅ ${task} · ${left} left`) {
989  const isToasted = await attempt($, 'toast', () => $.ui.toast(`✅ ${truncate(task, TOAST_COLUMNS)} · ${left} left`))
990  const isAppended = await attempt($, 'append', async () => {
991    const appended = await $.session.append({ message: { type: 'system', content: [{ type: 'text', text: notice }] } })
992
993    if (appended.deny !== undefined) {
994      throw new Error(`append refused: ${appended.deny}`)
995    }
996  })
997
998  if (isToasted && isAppended) {
999    await log($, 'sent', null)
1000  }
1001}
1002
1003/**
1004 * The chime, only where a person can hear it: a session with a terminal. A session with none (a `claude -p` run at night
1005 * loads mods too) stays silent, and a clip that cannot play never breaks anything.
1006 */
1007async function chime($: EngineInterface) {
1008  try {
1009    if ((await $.session.surfaces()).includes('terminal')) {
1010      await $.audio.play({ asset: DONE_SOUND }, { gain: DONE_GAIN })
1011    }
1012  } catch {
1013    // no screen to ask, or a clip that cannot play: the toast has been shown
1014  }
1015}
1016
1017// ---------------------------------------------------------------- the board, the band and what moves
1018
1019/**
1020 * Opens the board when it is not up, closes it when it is. While the pane lists the plans, the press leaves the list instead: the pane
1021 * shows the band's plan board, opened if it was closed, and the query becomes that plan's anchor.
1022 */
1023async function toggleBoard($: EngineInterface) {
1024  const isUp = (await $.ui.panes()).some(pane => pane.id === PANE_ID && pane.isPlaced)
1025
1026  if (await read($, listing)) {
1027    const plan = await shownPlan($)
1028
1029    await Promise.all([update($, listing, () => false), ...(plan === undefined ? [] : [update($, query, () => plan.anchor)])])
1030    await $.ui.open(OPEN)
1031  } else if (isUp) {
1032    await $.ui.close({ id: PANE_ID })
1033  } else {
1034    await $.ui.open(OPEN)
1035  }
1036
1037  await syncAnimation($)
1038}
1039
1040/**
1041 * Hands the keyboard to the pane if it is up. A click leaves the keys with the site it landed on (the band's Button holds
1042 * them), so a handler that changes what the pane shows asks again, which the pane takes; with the pane closed it opens nothing.
1043 * With `top`, the new view also starts at its first row (the window keeps its offset across views otherwise).
1044 */
1045async function refocus($: EngineInterface, top = false) {
1046  try {
1047    if ((await $.ui.panes()).some(pane => pane.id === PANE_ID && pane.isPlaced)) {
1048      await $.ui.open(OPEN)
1049
1050      if (top) {
1051        await $.ui.scroll({ to: 'start', in: PANE_ID })
1052      }
1053    }
1054  } catch {
1055    // a surface that cannot move the keys leaves them where they are
1056  }
1057}
1058
1059/** Opens the board (taking the keys) and shows the plan file in it. */
1060async function openFile($: EngineInterface) {
1061  await Promise.all([update($, file, () => true), update($, card, () => null), update($, menu, () => false), update($, bandMenu, () => false)])
1062
1063  await $.ui.open(OPEN)
1064  await $.ui.scroll({ to: 'start', in: PANE_ID }).catch(() => undefined)
1065  await syncAnimation($)
1066}
1067
1068/** Goes back to the board's lanes. The keys go to the pane. */
1069async function showBoard($: EngineInterface) {
1070  await Promise.all([update($, card, () => null), update($, file, () => false)])
1071  await syncAnimation($)
1072  await refocus($, true)
1073}
1074
1075/**
1076 * Picks a plan for the band and the board together: both lists close and the board shows its lanes; the pane leaves the plan list, and
1077 * the query becomes the anchor (else the refreshes would go on asking for every plan).
1078 */
1079async function pickPlan($: EngineInterface, anchor: string) {
1080  await Promise.all([
1081    update($, listing, () => false),
1082    update($, query, () => anchor),
1083    update($, selected, () => anchor),
1084    update($, card, () => null),
1085    update($, file, () => false),
1086    update($, menu, () => false),
1087    update($, bandMenu, () => false),
1088  ])
1089  await syncAnimation($)
1090  await refocus($, true)
1091}
1092
1093/**
1094 * Picks a plan of the pane's list: the plan may not be among the session's, so the query becomes its anchor (the tracker answers
1095 * with that plan's entry) as well as the plan shown. The pane leaves the list, lists close and the board shows its lanes, as in `pickPlan`.
1096 */
1097async function pickMatch($: EngineInterface, anchor: string) {
1098  await Promise.all([
1099    update($, listing, () => false),
1100    update($, query, () => anchor),
1101    update($, selected, () => anchor),
1102    update($, card, () => null),
1103    update($, file, () => false),
1104    update($, menu, () => false),
1105    update($, bandMenu, () => false),
1106  ])
1107  await refreshQuietly($)
1108  await syncAnimation($)
1109  await refocus($, true)
1110}
1111
1112/**
1113 * Whether anything on screen moves: the band (the rainbow of a complete plan, the mascot while the plan is at work) or the open
1114 * pane (the mascots while the plan is at work).
1115 */
1116async function animates($: EngineInterface): Promise<boolean> {
1117  const plan = await shownPlan($)
1118
1119  if (plan === undefined) {
1120    return false
1121  }
1122
1123  // Only a terminal moves by redraw: the desktop reads no frame (its sprite animates itself), so a timer would only write one.
1124  const surfaces = await $.session.surfaces().catch(() => null)
1125
1126  if (JSON.stringify(surfaces) !== loggedSurfaces) {
1127    loggedSurfaces = JSON.stringify(surfaces)
1128    void log($, 'timer', null, { surfaces })
1129  }
1130
1131  if (surfaces !== null && !surfaces.includes('terminal')) {
1132    return false
1133  }
1134
1135  const isPaneUp = (await $.ui.panes()).some(pane => pane.id === PANE_ID && pane.isPlaced && pane.isShown)
1136  const isBoard = detailOf(plan, await read($, card)) === null && !(await read($, file))
1137  const { band, pane } = movement(plan, { finished: await read($, finished), isPaneUp, isBoard })
1138
1139  return band || pane
1140}
1141
1142/** The state text the band last drew, by surface, as `<anchor> <text>`. */
1143const drawnStates = new Map<string, string>()
1144
1145/** Logs the state the band draws on `surface` when it differs from the one it drew last there: once per change, not per frame. */
1146function noteState($: EngineInterface, surface: string, plan: PlanEntry, text: string) {
1147  const key = `${plan.anchor} ${text}`
1148
1149  if (drawnStates.get(surface) !== key) {
1150    drawnStates.set(surface, key)
1151    void log($, 'state', null, { surface, plan: plan.anchor, state: planStateOf(plan), text })
1152  }
1153}
1154
1155/** The rows the pane last said it shows (`scroll.bodyRows`): logged with a lane press, for the Show less rule. */
1156let paneRows: number | undefined
1157
1158/** The surfaces last logged by `animates`, as text. */
1159let loggedSurfaces = ''
1160
1161/** Opens row `index` of `plan` on its page: the plan list shuts and the pane is focused at its top. */
1162async function openRow($: EngineInterface, plan: PlanEntry, index: number) {
1163  await Promise.all([update($, menu, () => false), update($, card, () => ({ anchor: plan.anchor, index }))])
1164  await syncAnimation($)
1165  await refocus($, true)
1166}
1167
1168/**
1169 * What a press on the Button (or answered link) keyed `element` does: the same actions as the drawings' `onPress` closures,
1170 * which call this too. It decides at once whether the key is the mod's (undefined if not) and returns the work, so a caller
1171 * can answer a press without waiting: the `ui.press` hook runs the work in the background, because opening a pane from
1172 * inside the press chain must not hold the chain.
1173 */
1174export function actionFor($: EngineInterface, element: string, surface: string): (() => Promise<unknown>) | undefined {
1175  const lane = /^lane:(.+):(?:more|less)$/.exec(element)?.[1]
1176  // A card: a line of the terminal's Buttons (`card:N`, `card:N:<line>`), or vscode's "Open ›" (`card:<anchor>:N`, ignored for another plan).
1177  const lineCard = /^card:(\d+)(?::\d+)?$/.exec(element)
1178  const linkCard = lineCard === null ? /^card:(.+):(\d+)$/.exec(element) : null
1179  const cardAt = lineCard?.[1] ?? linkCard?.[2]
1180
1181  if (cardAt !== undefined) {
1182    return async () => {
1183      const plan = await shownPlan($)
1184      const index = Number(cardAt)
1185
1186      if (plan !== undefined && (linkCard === null || linkCard[1] === plan.anchor) && plan.rows[index] !== undefined) {
1187        await openRow($, plan, index)
1188      }
1189    }
1190  }
1191
1192  if (element === 'band:bar' || element === 'band:head') {
1193    return () => toggleBoard($)
1194  }
1195
1196  if (element === 'band:plans') {
1197    return () => update($, bandMenu, isOpen => !isOpen)
1198  }
1199
1200  if (element === 'band:file' || element === 'plan-file') {
hooks/board.ts 1925 lines
1/**
2 * The pure part of the mod: how the board command is called and what it prints (the
3 * PLAN-DONE block, the `--json` board), how a status is colored, how wide a string is on
4 * screen, and what the band and the board show. Nothing here draws or touches `$`.
5 * It shows what the tracker records, and whether its own session is at work on its plans (`withWork`).
6 */
7import type { CardRef, PlanBoard, PlanEntry, PlanMatch, PlanRow, PlanStatus, PlanTotals, RowUsage, SessionUsage } from '../types'
8
9export const STATUSES: readonly PlanStatus[] = ['Todo', 'In Progress', 'Verifying', 'Needs Verification', 'Blocked', 'Done', 'Canceled']
10
11export type Style = { color: string; dimColor?: true }
12
13/**
14 * One color per status, as theme keys: every terminal theme defines them and
15 * they follow light and dark. The engine looks a bare name such as 'red' up in
16 * the theme too and finds nothing, so it would draw uncolored. No two statuses
17 * share a key (the v3 review found In Progress and Review resolving to one color).
18 */
19export const STYLE: Record<PlanStatus, Style> = {
20  Todo: { color: 'inactive' }, // gray
21  'In Progress': { color: 'suggestion' }, // blue
22  Verifying: { color: 'warning' }, // yellow, the Verify lane's colour
23  'Needs Verification': { color: 'warning' }, // yellow
24  Blocked: { color: 'error' }, // red
25  Done: { color: 'success' }, // green
26  Canceled: { color: 'inactive', dimColor: true }, // dim gray
27  Other: { color: 'permission' }, // a status the reader does not know
28}
29
30/** The color of a "needs you" marker: used by no status. */
31export const NEEDS_YOU_COLOR = 'merged'
32
33/**
34 * The color of a link, in the note of a task page: the theme's accent for suggestions, which reads on a dark and on a light
35 * theme (`remember` is a dark blue on a dark one).
36 */
37export const LINK_COLOR = 'suggestion'
38
39/** Most urgent first: what "worst" means for a plan. */
40const URGENCY: readonly PlanStatus[] = ['Blocked', 'Verifying', 'Needs Verification', 'In Progress', 'Other', 'Todo', 'Done', 'Canceled']
41
42export const isBlocked = (row: PlanRow): boolean => row.status === 'Blocked'
43
44/** Whether the row is still to do: not Done, not Canceled. */
45export const isOpen = (row: PlanRow): boolean => row.status !== 'Done' && row.status !== 'Canceled'
46
47export const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error))
48
49const isStatus = (value: unknown): value is PlanStatus => STATUSES.includes(value as PlanStatus)
50
51const asText = (value: unknown): string | undefined => (typeof value === 'string' && value !== '' ? value : undefined)
52
53const isNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value)
54
55const MATCH_STATES: readonly PlanMatch['state'][] = ['In progress', 'Idle', 'Done', 'Canceled']
56
57/**
58 * The plans the board command lists (`matches`): an entry of another shape is dropped; none left is no list. A plan waiting for the
59 * person keeps one of the four words and carries `waiting: true`.
60 */
61function matchesOf(value: unknown): PlanMatch[] | undefined {
62  const out = (Array.isArray(value) ? value : []).flatMap((one: Record<string, unknown> | null): PlanMatch[] => {
63    const anchor = asText(one?.anchor)
64    const name = asText(one?.name)
65    const state = MATCH_STATES.find(word => word === one?.state)
66    const done = one?.done
67    const total = one?.total
68    const updated = asText(one?.updated)
69
70    return anchor !== undefined && name !== undefined && state !== undefined && isNumber(done) && isNumber(total)
71      ? [{ anchor, name, state, done, total, ...(updated === undefined ? {} : { updated }), ...(one?.waiting === true ? { waiting: true as const } : {}) }]
72      : []
73  })
74
75  return out.length === 0 ? undefined : out
76}
77
78/** Lower case, with `- _ → : · /` as spaces, so `plan tracker` finds `plan-tracker`. */
79const normText = (text: string): string => text.toLowerCase().replace(/[-_→:·/]/g, ' ')
80
81/** The words of `text`, normalised. */
82const wordsOf = (text: string): string[] => normText(text).split(/\s+/).filter(word => word !== '')
83
84/** Whether a plan stays in the list for the search `text`: every word of it in the plan's name or anchor, in any order (no word: every plan). */
85export function isFound(plan: { anchor: string; name: string }, text: string): boolean {
86  const hay = `${normText(plan.name)} ${normText(plan.anchor)}`
87
88  return wordsOf(text).every(word => hay.includes(word))
89}
90
91/** The plans the list shows for the search `text`: with no words, every plan but the Done and Canceled ones; with words, every plan they find. */
92export function listedMatches<T extends { anchor: string; name: string; state: string }>(plans: readonly T[], text: string): T[] {
93  return wordsOf(text).length === 0 ? plans.filter(one => one.state !== 'Done' && one.state !== 'Canceled') : plans.filter(one => isFound(one, text))
94}
95
96/**
97 * The plan `/plan-tracker <words>` opens at once: the first whose name or anchor equals the words (normalised), else the only one
98 * the words leave in the list; undefined when they leave none or several, or are no words.
99 */
100export function directPick<T extends { anchor: string; name: string }>(plans: readonly T[], text: string): T | undefined {
101  const key = wordsOf(text).join(' ')
102
103  if (key === '') {
104    return undefined
105  }
106
107  const found = plans.filter(plan => isFound(plan, text))
108
109  return plans.find(plan => wordsOf(plan.name).join(' ') === key || wordsOf(plan.anchor).join(' ') === key) ?? (found.length === 1 ? found[0] : undefined)
110}
111
112/**
113 * The plans the list draws from the board command's answer to `*`: its `matches`; when it has none, its `plans` if there are two or more,
114 * latest `updated` first (a command that does not know `*` still lists the plans it prints); else none: one plan opens its board.
115 */
116export function listOf(board: PlanBoard): PlanMatch[] {
117  if (board.matches !== undefined) {
118    return board.matches
119  }
120
121  const at = (plan: { updated?: string }) => (Number.isNaN(Date.parse(plan.updated ?? '')) ? 0 : Date.parse(plan.updated ?? ''))
122
123  return board.plans.length < 2
124    ? []
125    : board.plans
126        .map((plan): PlanMatch => {
127          const state = planStateOf(plan)
128
129          return {
130            anchor: plan.anchor,
131            name: plan.name,
132            state: state === 'Stalled' ? 'In progress' : state === 'Waiting for you' ? 'Idle' : state,
133            ...(state === 'Waiting for you' ? { waiting: true as const } : {}),
134            ...countOf(plan),
135            ...(plan.updated === undefined ? {} : { updated: plan.updated }),
136          }
137        })
138        .sort((a, b) => at(b) - at(a))
139}
140
141/**
142 * The script's `--view --json` output as a board, or one line saying what is wrong with it. A field the tracker leaves null
143 * is dropped, so the drawing code reads an absent field, never a null.
144 */
145export function parseBoard(text: string): { board: PlanBoard } | { error: string } {
146  let data: unknown
147
148  try {
149    data = JSON.parse(text)
150  } catch (error) {
151    return { error: `plan-tracker: the board command did not print JSON: ${messageOf(error)}` }
152  }
153
154  const raw = data as { selected?: unknown; message?: unknown; plans?: unknown } | null
155  const isShaped =
156    Array.isArray(raw?.plans) &&
157    raw.plans.every(
158      (plan: { anchor?: unknown; rows?: unknown } | null) =>
159        typeof plan?.anchor === 'string' &&
160        Array.isArray(plan.rows) &&
161        plan.rows.every((row: { task?: unknown; status?: unknown } | null) => typeof row?.task === 'string' && isStatus(row.status)),
162    )
163
164  if (!isShaped) {
165    return { error: 'plan-tracker: the JSON of the board command has no plans[].rows[] with a task and a known status' }
166  }
167
168  const plans = (raw.plans as Record<string, unknown>[]).map((plan): PlanEntry => ({
169    anchor: plan.anchor as string,
170    name: asText(plan.name) ?? (plan.anchor as string),
171    goal: asText(plan.goal) ?? '',
172    plan_file: asText(plan.plan_file) ?? '',
173    ...(asText(plan.created) === undefined ? {} : { created: asText(plan.created) as string }),
174    ...(asText(plan.created_at) === undefined ? {} : { created_at: asText(plan.created_at) as string }),
175    ...(asText(plan.started) === undefined ? {} : { started: asText(plan.started) as string }),
176    ...(asText(plan.finished) === undefined ? {} : { finished: asText(plan.finished) as string }),
177    ...(asText(plan.updated) === undefined ? {} : { updated: asText(plan.updated) as string }),
178    ...(asText(plan.idle_since) === undefined ? {} : { idle_since: asText(plan.idle_since) as string }),
179    ...(asText(plan.recap) === undefined ? {} : { recap: asText(plan.recap) as string }),
180    ...(asText(plan.recap) === undefined || asText(plan.recap_updated) === undefined ? {} : { recap_updated: asText(plan.recap_updated) as string }),
181    ...(typeof plan.in_session === 'boolean' ? { in_session: plan.in_session } : {}),
182    rows: (plan.rows as Record<string, unknown>[]).map((row): PlanRow => {
183      const note = asText(row.note)
184      const route = asText(row.route)
185      const who = asText(row.who)
186      const goal = asText(row.goal)
187      const progress = asText(row.progress)
188      const started = asText(row.started)
189      const finished = asText(row.finished)
190      const stalledAt = asText(row.stalled_since)
191      const stalledSince = stalledAt === undefined || Number.isNaN(Date.parse(stalledAt)) ? undefined : stalledAt
192
193      return {
194        task: row.task as string,
195        status: row.status as PlanStatus,
196        updated: asText(row.updated) ?? null,
197        ...(note === undefined ? {} : { note }),
198        ...(route === undefined ? {} : { route }),
199        ...(who === undefined ? {} : { who }),
200        ...(goal === undefined ? {} : { goal }),
201        ...(progress === undefined ? {} : { progress }),
202        ...(started === undefined ? {} : { started }),
203        ...(finished === undefined ? {} : { finished }),
204        ...(stalledSince === undefined ? {} : { stalled_since: stalledSince }),
205      }
206    }),
207  }))
208
209  const message = asText(raw.message)
210  const matches = matchesOf((raw as { matches?: unknown }).matches)
211
212  return { board: { selected: asText(raw.selected) ?? null, message: message ?? null, plans, ...(matches === undefined ? {} : { matches }) } }
213}
214
215/** The plan the person picked, else the tracker's own choice, else the first. */
216export function planOf(board: PlanBoard, picked: string | null): PlanEntry | undefined {
217  return board.plans.find(plan => plan.anchor === picked) ?? board.plans.find(plan => plan.anchor === board.selected) ?? board.plans[0]
218}
219
220/** What decides the plan's color: its most urgent open row (Blocked, Verifying, Needs Verification, In Progress, Todo), green once none is left. */
221export function worstStatus(plan: PlanEntry): PlanStatus {
222  return URGENCY.find(status => status !== 'Done' && status !== 'Canceled' && plan.rows.some(row => row.status === status)) ?? 'Done'
223}
224
225/** Rows Done and rows to reach (every row but the Canceled): what `n/m` counts. A Canceled row is not shown anywhere. */
226export function countOf(plan: PlanEntry): { done: number; total: number } {
227  const canceled = plan.rows.filter(row => row.status === 'Canceled').length
228
229  return { done: plan.rows.filter(row => row.status === 'Done').length, total: plan.rows.length - canceled }
230}
231
232/** `5/12`. */
233export const countText = (plan: PlanEntry): string => `${countOf(plan).done}/${countOf(plan).total}`
234
235/**
236 * A plan's state word: `Done` once closed, `In progress` while a row runs or its session works on it, `Stalled` when every running row
237 * is stalled, `Waiting for you` when nothing runs and a row waits on the person's check, else `Idle`. There is no "Todo" state: a plan
238 * nobody started is Idle. `Canceled` (an abandoned plan) comes only from a board command's list.
239 */
240export type PlanState = 'In progress' | 'Stalled' | 'Waiting for you' | 'Idle' | 'Done' | 'Canceled'
241
242/** The state words, widest first, for aligning a column of them. */
243export const STATE_COLUMNS = 'In progress'.length
244
245/**
246 * One color per state: the In Progress lane's, gray like the Todo lane (Stalled and Idle), the "needs you" color (Waiting for you), the
247 * Done lane's, dim gray like a Canceled row.
248 */
249export const STATE_STYLE: Record<PlanState, Style> = {
250  'In progress': STYLE['In Progress'],
251  Stalled: STYLE.Todo,
252  'Waiting for you': { color: NEEDS_YOU_COLOR },
253  Idle: STYLE.Todo,
254  Done: STYLE.Done,
255  Canceled: STYLE.Canceled,
256}
257
258/**
259 * Done = the plan is closed (the tracker gave `finished`, or every row is Done or Canceled with one Done). In progress = open,
260 * with a row In Progress or Verifying that is not stalled, or its session at work (`working`). Stalled = open, not worked on, with
261 * running rows that are all stalled. Waiting for you = open, nothing running, and a Needs Verification row waits on the person
262 * (`needsYou`). Idle = open and nothing running (rows Todo, Needs Verification checked by another, or Blocked, or no row started).
263 */
264export function planStateOf(plan: PlanEntry): PlanState {
265  if (plan.finished !== undefined || isComplete(plan)) {
266    return 'Done'
267  }
268
269  if (isActive(plan)) {
270    return 'In progress'
271  }
272
273  return hasInProgress(plan) ? 'Stalled' : plan.rows.some(needsYou) ? 'Waiting for you' : 'Idle'
274}
275
276/** The later of two tracker times; either may be absent. */
277const laterOf = (a: string | undefined, b: string | undefined): string | undefined =>
278  a === undefined ? b : b === undefined ? a : Date.parse(b) > Date.parse(a) ? b : a
279
280/**
281 * The state word as the header, the band and the plan list write it, and the one place the board shows a plan's time: `Done at 21:40`
282 * (the plan's `finished`, else its `updated`), `Stalled since 19:23` (the newest `stalled_since` of its running rows), `Idle since 19:40`
283 * and `Waiting for you since 19:40` (the later of the plan's `idle_since` and `stopped_at`, when its session last stopped); a time on
284 * another day reads `Oct 11 19:23`. Plain `Done`, `Stalled`, `Idle` or `Waiting for you` when the time is not there or not a clock time
285 * (a `PROGRESS.md` has none until its session has stopped once); `In progress` is always the bare label. Colors follow the bare state
286 * (`planStateOf`); the room it takes is this text's.
287 */
288export function planStateText(plan: PlanEntry, now: number = Date.now()): string {
289  const state = planStateOf(plan)
290
291  if (state === 'Done') {
292    const at = [plan.finished, plan.updated].map(time => (time === undefined ? undefined : sinceText(time, now))).find(one => one !== undefined)
293
294    return at === undefined ? state : `Done at ${at}`
295  }
296
297  if (state === 'Stalled') {
298    const times = plan.rows.flatMap(row => (isStalled(row) ? [row.stalled_since as string] : []))
299    const newest = times.reduce((latest, one) => (Date.parse(one) > Date.parse(latest) ? one : latest))
300    const at = sinceText(newest, now)
301
302    return at === undefined ? state : `${state} since ${at}`
303  }
304
305  const since = state === 'Idle' || state === 'Waiting for you' ? laterOf(plan.idle_since, plan.stopped_at) : undefined
306  const at = since === undefined ? undefined : sinceText(since, now)
307
308  return at === undefined ? state : `${state} since ${at}`
309}
310
311// ---------------------------------------------------------------- width
312
313const WIDE: readonly (readonly [number, number])[] = [
314  [0x1100, 0x115f],
315  [0x231a, 0x231b],
316  [0x23e9, 0x23ec],
317  [0x2614, 0x2615],
318  [0x2705, 0x2705],
319  [0x270a, 0x270b],
320  [0x2728, 0x2728],
321  [0x274c, 0x274c],
322  [0x2753, 0x2755],
323  [0x2757, 0x2757],
324  [0x2795, 0x2797],
325  [0x2b1b, 0x2b1c],
326  [0x2b50, 0x2b50],
327  [0x2b55, 0x2b55],
328  [0x2e80, 0x303e],
329  [0x3041, 0x33ff],
330  [0x3400, 0x4dbf],
331  [0x4e00, 0x9fff],
332  [0xa000, 0xa4cf],
333  [0xac00, 0xd7a3],
334  [0xf900, 0xfaff],
335  [0xfe30, 0xfe6f],
336  [0xff00, 0xff60],
337  [0xffe0, 0xffe6],
338  [0x1f300, 0x1f64f],
339  [0x1f900, 0x1f9ff],
340  [0x20000, 0x3fffd],
341]
342
343const ZERO: readonly (readonly [number, number])[] = [
344  [0x0300, 0x036f],
345  [0x200b, 0x200f],
346  [0x20d0, 0x20ff],
347  [0xfe00, 0xfe0f],
348]
349
350const within = (ranges: readonly (readonly [number, number])[], cp: number) => ranges.some(([from, to]) => cp >= from && cp <= to)
351
352/** Columns one code point takes: 2 for CJK and emoji, 0 for marks and controls, else 1 (`■ ▸ · — ×` are 1). */
353export function charWidth(cp: number): 0 | 1 | 2 {
354  if (cp < 32 || (cp >= 0x7f && cp < 0xa0) || within(ZERO, cp)) {
355    return 0
356  }
357
358  return within(WIDE, cp) ? 2 : 1
359}
360
361export function displayWidth(text: string): number {
362  let width = 0
363
364  for (const char of text) {
365    width += charWidth(char.codePointAt(0) ?? 0)
366  }
367
368  return width
369}
370
371/** Characters a line does not start with (closing marks) and does not end with (opening marks). */
372const NO_START = ',。、;:!?)」』】》〉,.;:!?)]}'
373const NO_END = '(「『【《〈([{'
374
375/**
376 * Where `text` is broken when its first `cut` code units fit a line: the last space that fits, or the last boundary next
377 * to a wide (CJK) character, which has no spaces; else the cut itself. `skip` is the code units dropped at the break (the space).
378 */
379function breakOf(text: string, cut: number): { at: number; skip: number } {
380  let best = -1
381  let skip = 0
382  let prev = ''
383  let idx = 0
384
385  for (const char of text) {
386    if (idx > cut) {
387      break
388    }
389
390    if (char === ' ' && idx > 0) {
391      best = idx
392      skip = 1
393    } else if (idx > 0 && char !== ' ' && prev !== ' ' && prev !== '') {
394      const isWide = charWidth(char.codePointAt(0) ?? 0) === 2 || charWidth(prev.codePointAt(0) ?? 0) === 2
395
396      if (isWide && !NO_START.includes(char) && !NO_END.includes(prev)) {
397        best = idx
398        skip = 0
399      }
400    }
401
402    prev = char
403    idx += char.length
404  }
405
406  return best > 0 ? { at: best, skip } : { at: Math.max(cut, 1), skip: 0 }
407}
408
409/** `text` cut to at most `cols` columns; a cut ends in `…`. */
410export function truncate(text: string, cols: number): string {
411  if (cols <= 0) {
412    return ''
413  }
414
415  if (displayWidth(text) <= cols) {
416    return text
417  }
418
419  let kept = ''
420  let used = 0
421
422  for (const char of text) {
423    const width = charWidth(char.codePointAt(0) ?? 0)
424
425    if (used + width > cols - 1) {
426      break
427    }
428
429    kept += char
430    used += width
431  }
432
433  return `${kept}…`
434}
435
436/**
437 * `text` broken into lines of at most `cols` columns, at a space when the line has one and else wherever it fills (CJK
438 * has no spaces); a line never starts with a space. Fewer than 1 column leaves the text whole. With `maxLines`, the
439 * last line takes all that is left of the text, cut with a `…` when it does not fit.
440 */
441export function wrap(text: string, cols: number, maxLines = Infinity): string[] {
442  if (cols < 1) {
443    return [text]
444  }
445
446  const lines: string[] = []
447  let rest = text.trim()
448
449  while (displayWidth(rest) > cols) {
450    if (lines.length === maxLines - 1) {
451      return [...lines, truncate(rest, cols)]
452    }
453
454    let used = 0
455    let cut = 0
456
457    for (const char of rest) {
458      const width = charWidth(char.codePointAt(0) ?? 0)
459
460      if (used + width > cols) {
461        break
462      }
463
464      used += width
465      cut += char.length
466    }
467
468    const { at, skip } = breakOf(rest, cut)
469
470    lines.push(rest.slice(0, at))
471    rest = rest.slice(at + skip).trimStart()
472  }
473
474  return [...lines, rest]
475}
476
477// ---------------------------------------------------------------- band
478
479export const FILE_LABEL = 'Plan file ›'
480
481/** What the band's right end says while the board shows the plan file: the way back, which never scrolls away. */
482export const BOARD_LABEL = '‹ Board'
483
484/** Cells of the progress bar when the band has room. */
485export const BAR_COLUMNS = 12
486
487/** Columns the band's fixed parts take besides the name, the bar and the count: `● `, ` ▾`, two gaps, the space before the count, `Plan file ›`. */
488const BAND_FIXED = 2 + 2 + 2 + 1 + 2 + displayWidth(FILE_LABEL)
489
490/** Columns of name the band keeps before the bar starts to shrink. */
491const MIN_BAND_NAME = 8
492
493export type BandLine = { name: string; state: PlanState; /** The state word as written (`Stalled since 19:23`): the room it takes. */ stateText: string; filled: number; empty: number; count: string }
494
495/** Cells of a `width`-cell bar that are filled for `done` of `total`: at least 1 once started, all of them only when complete. */
496export function filledOf(done: number, total: number, width: number): number {
497  if (total <= 0 || done <= 0) {
498    return 0
499  }
500
501  return done >= total ? width : Math.min(width - 1, Math.max(1, Math.round((done / total) * width)))
502}
503
504/**
505 * The band's one row without the mascot, cut to `cols` columns: the name (cut first), the state word (never cut; its whole text, `Stalled
506 * since 19:23` and `Idle since 19:40` included, takes room from the name), the 12-cell bar (shrunk to 4 cells at the least, and only when
507 * the name would keep under 8 columns) and `done/total`. `now` decides whether a state time is today's.
508 */
509export function bandLine(plan: PlanEntry, cols: number, now: number = Date.now()): BandLine {
510  const { done, total } = countOf(plan)
511  const count = `${done}/${total}`
512  const state = planStateOf(plan)
513  const stateText = planStateText(plan, now)
514  // The state word is never cut: it takes a space and its width from the name's room.
515  const rest = cols - BAND_FIXED - displayWidth(count) - 1 - displayWidth(stateText)
516  // The bar keeps its 12 cells and the name is cut; only when less than 8 columns would be left for the name does the bar shrink.
517  const bar = Math.min(BAR_COLUMNS, Math.max(4, rest - MIN_BAND_NAME))
518  const filled = filledOf(done, total, bar)
519
520  return { name: truncate(plan.name, Math.max(4, rest - bar)), state, stateText, filled, empty: bar - filled, count }
521}
522
523/** What the terminal band draws in the room its column leaves (`bandFit`). */
524export type BandFit = {
525  name: string
526  state: PlanState
527  /** The state word as written (`Stalled since 19:23`). */
528  stateText: string
529  /** Whether the state word shows: it is dropped whole, never cut. */
530  hasState: boolean
531  filled: number
532  empty: number
533  count: string
534  /** Whether the right end ("Plan file ›") shows. */
535  hasFile: boolean
536  /** True when the row cannot hold even the name and the count: the progress takes a second row under it. */
537  isStacked: boolean
538}
539
540/** Columns of name the terminal band keeps before it drops anything else. */
541const MIN_FIT_NAME = 4
542
543/**
544 * The terminal band's parts for a row of `cols` columns after the mascot and its space. The name is cut first (to 4 columns at
545 * the least, the bar shrinking to 4 cells before the name goes under 8); then the state word (its whole text, `Stalled since 19:23`
546 * included) is dropped whole, then the right end, then the bar; when even the name and the count do not fit one row, the progress goes
547 * to a second row of `cols` plus the mascot's columns. Nothing is ever cut mid-word or left wider than `cols`. `now` decides whether
548 * a state time is today's.
549 */
550export function bandFit(plan: PlanEntry, cols: number, hasChoice: boolean, fileWidth: number, now: number = Date.now()): BandFit {
551  const { done, total } = countOf(plan)
552  const count = `${done}/${total}`
553  const state = planStateOf(plan)
554  const stateText = planStateText(plan, now)
555  const countCols = displayWidth(count)
556  const stateBit = 1 + displayWidth(stateText) + 2
557  // The columns of every part but the name and the bar's cells: the dot, the arrow, the state, the bar's trailing space, the count, the right end.
558  const fixed = (hasState: boolean, hasBar: boolean, hasFile: boolean) =>
559    2 + (hasChoice ? 2 : 0) + (hasState ? stateBit : 1) + (hasBar ? 1 : 0) + countCols + (hasFile ? 2 + fileWidth : 0)
560  const stages = [
561    { hasState: true, hasFile: true, hasBar: true },
562    { hasState: false, hasFile: true, hasBar: true },
563    { hasState: false, hasFile: false, hasBar: true },
564    { hasState: false, hasFile: false, hasBar: false },
565  ]
566
567  for (const stage of stages) {
568    const rest = cols - fixed(stage.hasState, stage.hasBar, stage.hasFile)
569
570    if (rest >= MIN_FIT_NAME + (stage.hasBar ? 4 : 0)) {
571      const bar = stage.hasBar ? Math.min(BAR_COLUMNS, Math.max(4, rest - MIN_BAND_NAME)) : 0
572      const filled = filledOf(done, total, bar)
573
574      return { name: truncate(plan.name, rest - bar), state, stateText, hasState: stage.hasState, filled, empty: bar - filled, count, hasFile: stage.hasFile, isStacked: false }
575    }
576  }
577
578  // Stacked: the first row keeps the dot, the name and the arrow; the second row (the whole frame width) the state, the bar and the count.
579  const wide = cols + BAND_MASCOT_SPACE
580  const second = (hasState: boolean) => wide - (hasState ? stateBit : 1) - 1 - countCols
581  const hasState = second(true) >= 4
582  const bar = Math.min(BAR_COLUMNS, second(hasState))
583  const barCells = bar >= 4 ? bar : 0
584  const filled = filledOf(done, total, barCells)
585  const name = truncate(plan.name, Math.max(1, cols - 2 - (hasChoice ? 2 : 0)))
586
587  return { name, state, stateText, hasState, filled, empty: barCells - filled, count, hasFile: false, isStacked: true }
588}
589
590/** A plan with nothing left to do: each row Done or Canceled, at least one of them Done (an all-Canceled plan was not completed). */
591export const isComplete = (plan: PlanEntry): boolean => plan.rows.every(row => !isOpen(row)) && plan.rows.some(row => row.status === 'Done')
592
593/** The plan as the band draws a plan just finished: every row Done, the Canceled ones as they were. */
594export const asFinished = (plan: PlanEntry): PlanEntry => ({
595  ...plan,
596  rows: plan.rows.map((row): PlanRow => (row.status === 'Canceled' ? row : { ...row, status: 'Done' })),
597})
598
599/** The plan the band draws: `plan` as it is, or as finished when `finished` names it (a PLAN-DONE with 0 left). */
600export const bandPlanOf = (plan: PlanEntry, finished: string | null): PlanEntry => (finished === plan.anchor ? asFinished(plan) : plan)
601
602/** Whether a row is running right now: In Progress, or being verified (a Blocked row is not: its mascot is frozen). */
603export const isRunning = (row: PlanRow): boolean => row.status === 'In Progress' || row.status === 'Verifying'
604
605/** Whether a row of the plan is running: In Progress or Verifying. */
606export const hasInProgress = (plan: PlanEntry): boolean => plan.rows.some(isRunning)
607
608/** Whether a running row is stalled: the board command says no session is working on it (`stalled_since`). */
609export const isStalled = (row: PlanRow): boolean => isRunning(row) && row.stalled_since !== undefined
610
611/** Whether a row of the plan is running and not stalled: what moves the cards' mascot. */
612export const hasWorking = (plan: PlanEntry): boolean => plan.rows.some(row => isRunning(row) && !isStalled(row))
613
614/** Whether the plan is at work: a running row that is not stalled, or its session working on it. What reads In progress and moves the band's mascot. */
615export const isActive = (plan: PlanEntry): boolean => hasWorking(plan) || plan.working === true
616
617/** What of this session is at work: a main turn, and the ids of its background agents not yet ended. */
618export type Work = { turn: boolean; agents: string[] }
619
620/** Whether any of it is at work. */
621export const isWorking = (work: Work): boolean => work.turn || work.agents.length > 0
622
623/** `ms` as an ISO time on this machine's clock with its offset, as the tracker writes times (`sinceText` prints its clock part as written). */
624export function localIso(ms: number): string {
625  const at = new Date(ms)
626  const pad = (n: number) => String(n).padStart(2, '0')
627  const offset = -at.getTimezoneOffset()
628
629  return `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}T${pad(at.getHours())}:${pad(at.getMinutes())}:${pad(at.getSeconds())}${offset < 0 ? '-' : '+'}${pad(Math.floor(Math.abs(offset) / 60))}:${pad(Math.abs(offset) % 60)}`
630}
631
632/** The board with this session's work on its own plans (`in_session: true`): `working` while it works, `stopped_at` once it has stopped. */
633export function withWork(board: PlanBoard, work: Work, stoppedAt: string | null): PlanBoard {
634  const isOn = isWorking(work)
635
636  if (!isOn && stoppedAt === null) {
637    return board
638  }
639
640  return {
641    ...board,
642    plans: board.plans.map(plan =>
643      plan.in_session !== true ? plan : { ...plan, ...(isOn ? { working: true as const } : {}), ...(stoppedAt === null ? {} : { stopped_at: stoppedAt }) },
644    ),
645  }
646}
647
648/** Rows of the plan still to do: not Done, not Canceled. */
649export const openCount = (plan: PlanEntry): number => plan.rows.filter(isOpen).length
650
651/** Rainbow hues, red to violet; raw hex, so they do not follow the theme. */
652export const RAINBOW: readonly string[] = ['#ff5555', '#ff9933', '#ffd633', '#55cc66', '#33b5e5', '#5577ff', '#aa66ee']
653
654/** The hue of band cell `cell` at animation frame `frame`: each frame moves the hues one cell along. */
655export const rainbowAt = (cell: number, frame: number): string => RAINBOW[(cell + frame) % RAINBOW.length] ?? '#ffffff'
656
657// ---------------------------------------------------------------- board
658
659/** A row on a lane; `index` is its place in the plan's `rows`, which names the card. */
660export type Card = { row: PlanRow; index: number }
661
662export type LaneKey = 'Todo' | 'In Progress' | 'Verify' | 'Done' | 'Other'
663
664/** `more` is how many cards the lane does not show; `moreLabel` the line that says so (`+2 more`, `+1 blocked · 12 running`). */
665export type Lane = { key: LaneKey; header: string; color: string; cards: Card[]; more: number; moreLabel: string }
666
667/** The overflow line of an expanded lane, which folds it back to its cap. */
668export const SHOW_LESS = 'Show less'
669
670/** The overflow button's label: the line, then ▴ to fold or ▾ to unfold (a Button draws the `[ ]` itself). */
671export const moreButton = (label: string): string => `${label} ${label === SHOW_LESS ? '▴' : '▾'}`
672
673/** Todo and Done show this many cards, then `+N more`. */
674export const CAPPED = 3
675
676/** In Progress shows this many cards, Blocked ones first, then a line counting the rest. */
677export const DOING_SHOWN = 5
678
679/** Blocked cards the In Progress lane shows at the most, so that running cards (the mascot) stay in view. */
680export const BLOCKED_SHOWN = 3
681
682/** Verify shows this many cards, then a line counting the rest and how many of them wait on her. */
683export const VERIFY_SHOWN = 5
684
685const timeOf = (row: PlanRow) => (row.updated === null ? 0 : Date.parse(row.updated) || 0)
686
687/**
688 * `cards` with the latest `updated` first; cards updated at the same moment keep the later row first. Cards none of which has a time
689 * (a plain PROGRESS.md) keep their file order, so a lane with no times is not reversed by the tie rule.
690 */
691const latestFirst = (cards: Card[]): Card[] =>
692  cards.some(card => timeOf(card.row) > 0) ? [...cards].sort((a, b) => timeOf(b.row) - timeOf(a.row) || b.index - a.index) : cards
693
694/**
695 * The four lanes of a plan, each listing its latest updated task first. Verifying and Needs Verification are Verify; Blocked stays on the
696 * In Progress lane (its card is red, first in the lane, 3 at the most while running cards fill the rest of 5); a Canceled row is no card
697 * and is counted nowhere. The groups of a lane keep their places and each is sorted inside: Blocked, then running in In Progress;
698 * verifying, then waiting on you, then other waiting in Verify. A lane whose cards have no times keeps file order.
699 * Todo and Done keep 3 cards (Done: the latest).
700 */
701export function lanesOf(plan: PlanEntry, expanded: readonly LaneKey[] = []): Lane[] {
702  const cards = plan.rows.map((row, index): Card => ({ row, index }))
703  const of = (...statuses: PlanStatus[]) => cards.filter(card => statuses.includes(card.row.status))
704  const todo = latestFirst(of('Todo'))
705  const blocked = latestFirst(of('Blocked'))
706  const running = latestFirst(of('In Progress'))
707  // Blocked cards first, but at most 3 unless there are too few running cards to fill the lane: a lane of red cards only
708  // reads "everything is stuck" when 12 of 18 are running.
709  const blockedShown = Math.min(blocked.length, Math.max(BLOCKED_SHOWN, DOING_SHOWN - running.length))
710  const runningShown = Math.min(running.length, DOING_SHOWN - blockedShown)
711  const isOpen = (key: LaneKey) => expanded.includes(key)
712  // An expanded lane shows every card in the same order: Blocked first in In Progress.
713  const doing = isOpen('In Progress') ? [...blocked, ...running] : [...blocked.slice(0, blockedShown), ...running.slice(0, runningShown)]
714  // What the collapsed lane hides; a lane that hides nothing has nothing to expand, whatever its state.
715  const hiddenBlocked = blocked.length - blockedShown
716  const hiddenRunning = running.length - runningShown
717  const isFoldable = (key: LaneKey, count: number) => isOpen(key) && count > 0
718  // Verify: rows being verified now first, then the ones waiting on her (◆ needs you), then the other waiting rows.
719  const verifying = latestFirst(of('Verifying'))
720  const waiting = latestFirst(of('Needs Verification'))
721  const verify = [...verifying, ...waiting.filter(card => needsYou(card.row)), ...waiting.filter(card => !needsYou(card.row))]
722  // What the collapsed Verify lane hides, and how many of those wait on her.
723  const hiddenVerify = verify.slice(VERIFY_SHOWN)
724  const hiddenAsks = hiddenVerify.filter(card => needsYou(card.row)).length
725  // Latest first; rows updated at the same moment keep the later row first.
726  const done = of('Done').sort((a, b) => timeOf(b.row) - timeOf(a.row) || b.index - a.index)
727
728  // `+3 blocked · 10 running`: the plus leads the line once; a part that is zero is left out.
729  const hidden = (...parts: [number, string][]) => {
730    const line = parts.filter(([count]) => count > 0).map(([count, word]) => `${count} ${word}`).join(' · ')
731
732    return line === '' ? '' : `+${line}`
733  }
734
735  // A status the markdown reader does not know has its own lane, after the four, only while a row has it; named for the status
736  // when the rows share one.
737  const other = of('Other')
738  const otherNames = [...new Set(other.map(card => card.row.statusText ?? 'Other'))]
739  const otherLane: Lane[] =
740    other.length === 0
741      ? []
742      : [
743          {
744            key: 'Other',
745            header: `${otherNames.length === 1 ? otherNames[0] : 'Other'} ${other.length}`,
746            color: STYLE.Other.color,
747            cards: isOpen('Other') ? other : other.slice(0, CAPPED),
748            more: isOpen('Other') ? 0 : Math.max(0, other.length - CAPPED),
749            moreLabel: isFoldable('Other', other.length - CAPPED) ? SHOW_LESS : isOpen('Other') ? '' : hidden([other.length - CAPPED, 'more']),
750          },
751        ]
752
753  return [
754    {
755      key: 'Todo',
756      header: `Todo ${todo.length}`,
757      color: STYLE.Todo.color,
758      cards: isOpen('Todo') ? todo : todo.slice(0, CAPPED),
759      more: isOpen('Todo') ? 0 : Math.max(0, todo.length - CAPPED),
760      moreLabel: isFoldable('Todo', todo.length - CAPPED) ? SHOW_LESS : isOpen('Todo') ? '' : hidden([todo.length - CAPPED, 'more']),
761    },
762    {
763      key: 'In Progress',
764      header: `In Progress ${blocked.length + running.length}${blocked.length > 0 ? ` · ${blocked.length} blocked` : ''}`,
765      color: STYLE['In Progress'].color,
766      cards: doing,
767      more: isOpen('In Progress') ? 0 : hiddenBlocked + hiddenRunning,
768      moreLabel: isFoldable('In Progress', hiddenBlocked + hiddenRunning)
769        ? SHOW_LESS
770        : isOpen('In Progress')
771          ? ''
772          : hidden([hiddenBlocked, 'blocked'], [hiddenRunning, 'running']),
773    },
774    {
775      key: 'Verify',
776      header: `Verify ${verify.length}${verifying.length > 0 ? ` · ${verifying.length} verifying` : ''}`,
777      color: STYLE['Needs Verification'].color,
778      cards: isOpen('Verify') ? verify : verify.slice(0, VERIFY_SHOWN),
779      more: isOpen('Verify') ? 0 : hiddenVerify.length,
780      moreLabel: isFoldable('Verify', hiddenVerify.length)
781        ? SHOW_LESS
782        : isOpen('Verify')
783          ? ''
784          : hidden([hiddenVerify.length, 'more'], [hiddenAsks, 'needs you']),
785    },
786    {
787      key: 'Done',
788      header: `Done ${done.length}`,
789      color: STYLE.Done.color,
790      cards: isOpen('Done') ? done : done.slice(0, CAPPED),
791      more: isOpen('Done') ? 0 : Math.max(0, done.length - CAPPED),
792      moreLabel: isFoldable('Done', done.length - CAPPED) ? SHOW_LESS : isOpen('Done') ? '' : hidden([done.length - CAPPED, 'more']),
793    },
794    ...otherLane,
795  ]
796}
797
798/** The pane lays the lanes side by side from this width, stacked below it. */
799export const SIDE_BY_SIDE_FROM = 100
800
801/** Columns between two lanes side by side: two, so a title that fills its lane does not read as one phrase with the next. */
802export const LANE_GAP = 2
803
804/** Columns one lane gets side by side: four lanes and the gaps between them. */
805export const laneWidth = (bodyColumns: number, count = 4) => Math.floor((bodyColumns - (count - 1) * LANE_GAP) / count)
806
807/** A card is a Box with a round border and one column of padding on each side: four columns in all. */
808export const BORDER_COLUMNS = 4
809
810/**
811 * Claude Code's mascot, the orange pixel creature, as a small sprite of block characters: 2 rows of `MASCOT_COLUMNS`
812 * columns, in two poses (the second has its arms up and its legs shifted).
813 */
814export type Pose = readonly [string, string]
815
816export const MASCOT: readonly [Pose, Pose] = [
817  ['▄█▜▛█▄', ' ▛▛▜▜ '],
818  ['▚█▜▛█▞', ' ▜▜▛▛ '],
819]
820
821/** The quadrants (upper left, upper right, lower left, lower right) each block character of the mascot fills. */
822const QUADRANTS: Readonly<Record<string, readonly [number, number, number, number]>> = {
823  '▄': [0, 0, 1, 1],
824  '█': [1, 1, 1, 1],
825  '▜': [1, 1, 0, 1],
826  '▛': [1, 1, 1, 0],
827  '▟': [0, 1, 1, 1],
828  '▙': [1, 0, 1, 1],
829  '▚': [1, 0, 0, 1],
830  '▞': [0, 1, 1, 0],
831}
832
833/** The colours of the mascot as raw hex, for a surface that draws it as a picture and cannot look up a theme key. */
834export const SPRITE_COLORS: Readonly<Record<string, string>> = { claude: '#D77757', error: '#E5484D' }
835
836/** The animation frame's period in ms: what the one timer ticks at, and so how long a pose lasts (`MASCOT_EVERY` frames). */
837export const FRAME_MS = 120
838
839/** The mascot's rows as an SVG pixel sprite: every block character is 2×2 sub-pixels, one `<rect>` for each one it fills. */
840export function spriteSvg(rows: readonly string[], color: string): { source: string; rects: number } {
841  const fill = SPRITE_COLORS[color] ?? color
842  const cols = Math.max(...rows.map(row => [...row].length))
843  const rects = spriteRects(rows)
844
845  const source = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${cols * 2} ${rows.length * 2}" preserveAspectRatio="none" shape-rendering="crispEdges"><g fill="${fill}">${rects.join('')}</g></svg>`
846
847  return { source, rects: rects.length }
848}
849
850/**
851 * Both poses in one SVG that switches between them by itself (SMIL `<animate>` on each group's opacity, discrete), a pose
852 * lasting what it lasts on the terminal: `MASCOT_EVERY` frames of `FRAME_MS`. The desktop animates this without a redraw, which
853 * would issue the buttons new handles. `rects` counts the rects of both poses.
854 */
855export function spriteSvgAnimated(poses: readonly [readonly string[], readonly string[]], color: string): { source: string; rects: number } {
856  const fill = SPRITE_COLORS[color] ?? color
857  const cols = Math.max(...poses[0].map(row => [...row].length))
858  const lists = poses.map(spriteRects)
859  const cycle = MASCOT_EVERY * FRAME_MS * 2
860
861  const group = (rects: string[], values: string) =>
862    `<g fill="${fill}" opacity="${values.split(';')[0]}">${rects.join('')}<animate attributeName="opacity" values="${values}" keyTimes="0;0.5" calcMode="discrete" dur="${cycle}ms" repeatCount="indefinite"/></g>`
863
864  const source = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${cols * 2} ${poses[0].length * 2}" preserveAspectRatio="none" shape-rendering="crispEdges">${group(lists[0] ?? [], '1;0')}${group(lists[1] ?? [], '0;1')}</svg>`
865
866  return { source, rects: lists.reduce((all, list) => all + list.length, 0) }
867}
868
869/** The `<rect>`s of a pose, one per filled sub-pixel. */
870function spriteRects(rows: readonly string[]): string[] {
871  const rects: string[] = []
872
873  rows.forEach((row, y) =>
874    [...row].forEach((char, x) =>
875      (QUADRANTS[char] ?? [0, 0, 0, 0]).forEach((isOn, at) => {
876        if (isOn === 1) {
877          rects.push(`<rect x="${x * 2 + (at % 2)}" y="${y * 2 + Math.floor(at / 2)}" width="1" height="1"/>`)
878        }
879      }),
880    ),
881  )
882
883  return rects
884}
885
886/** CSS pixels of the card's sprite (6 columns, 2 rows of text) and of the band's (5 columns, 1 row). */
887export const CARD_SPRITE_PX = { width: 36, height: 24 } as const
888export const BAND_SPRITE_PX = { width: 24, height: 16 } as const
889
890/** Cells the desktop gives the card's and the band's sprite beside it (a cell is about 8 px). */
891export const CARD_SPRITE_CELLS = 5
892export const BAND_SPRITE_CELLS = 4
893
894/** The desktop's solid bars: the Svg bar's size in CSS pixels, and the card's fixed width in cells (the Client region has no Svg). */
895export const BAR_PX = { width: 64, height: 6 } as const
896export const CARD_BAR_CELLS = 8
897
898/**
899 * A progress bar as an SVG: a rounded track and a rounded fill of `fraction` of it. With `colors` the fill is those colours in
900 * equal stripes (the band's rainbow), clipped to the same rounded shape.
901 */
902export function barSvg(fraction: number, color: string, colors?: readonly string[]): string {
903  const { width, height } = BAR_PX
904  const radius = height / 2
905  const part = Math.min(1, Math.max(0, fraction))
906  const fill = part === 0 ? 0 : Math.max(height, Math.round(width * part))
907  const stripe = colors === undefined ? 0 : fill / colors.length
908
909  const body =
910    fill === 0
911      ? ''
912      : colors === undefined
913        ? `<rect width="${fill}" height="${height}" rx="${radius}" fill="${color}"/>`
914        : `<clipPath id="f"><rect width="${fill}" height="${height}" rx="${radius}"/></clipPath><g clip-path="url(#f)">${colors.map((one, at) => `<rect x="${(at * stripe).toFixed(1)}" width="${(stripe + 0.5).toFixed(1)}" height="${height}" fill="${one}"/>`).join('')}</g>`
915
916  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"><rect width="${width}" height="${height}" rx="${radius}" fill="${TRACK_COLOR}"/>${body}</svg>`
917}
918
919/** Theme colours as hex, for a picture (an Svg cannot look a theme key up): the statuses' colours as the light theme has them. */
920export const HEX: Readonly<Record<string, string>> = {
921  inactive: '#8A8A85',
922  suggestion: '#3B6FD4',
923  warning: '#B7791F',
924  error: '#E5484D',
925  success: '#3C9D5A',
926  claude: '#D77757',
927}
928
929/** The empty part of a solid progress bar on the desktop: a light grey. */
930export const TRACK_COLOR = '#D9D6CC'
931
932export const MASCOT_COLUMNS = 6
933export const MASCOT_ROWS = 2
934
935/** Animation frames (ticks of the one timer) each pose lasts: 3 ticks of 120 ms, about 360 ms. */
936export const MASCOT_EVERY = 3
937
938/** The card mascot's two rows at animation frame `frame`. */
939export const mascotAt = (frame: number): Pose => MASCOT[Math.floor(frame / MASCOT_EVERY) % MASCOT.length] ?? MASCOT[0]
940
941/**
942 * The band's mascot: Claude Code's creature again, one row of `BAND_MASCOT_COLUMNS` columns, in two poses (arms down,
943 * arms up). The two-row `MASCOT` stays on the In Progress cards.
944 */
945export const BAND_MASCOT: readonly [string, string] = ['▜▟█▙▛', '▞▟█▙▚']
946
947export const BAND_MASCOT_COLUMNS = 5
948
949/** Columns the band's mascot and the space after it take. */
950export const BAND_MASCOT_SPACE = BAND_MASCOT_COLUMNS + 1
951
952/** The band's mascot at animation frame `frame`: the pose changes every `MASCOT_EVERY` ticks, as the cards' does. */
953export const bandMascotAt = (frame: number): string => BAND_MASCOT[Math.floor(frame / MASCOT_EVERY) % BAND_MASCOT.length] ?? BAND_MASCOT[0]
954
955/**
956 * The band mascot's pose: arms up and still when the plan is complete (the rainbow), moving while the plan is at work
957 * (`isActive`), else arms down and still.
958 */
959export const bandPose = (plan: PlanEntry, frame: number): string => BAND_MASCOT[bandPoseIndex(plan, frame)] ?? BAND_MASCOT[0]
960
961/** Which of the two poses the band's mascot is in: the same choice `bandPose` makes, as an index (the desktop draws the card sprite's pose of that index). */
962export const bandPoseIndex = (plan: PlanEntry, frame: number): 0 | 1 =>
963  isComplete(plan) ? 1 : isActive(plan) ? (Math.floor(frame / MASCOT_EVERY) % 2 === 0 ? 0 : 1) : 0
964
965/** Columns the mascot and the space after it take on a card. */
966export const MASCOT_SPACE = MASCOT_COLUMNS + 1
967
968/** Fewest columns of task name an In Progress card keeps beside the mascot; a narrower card has no mascot. */
969export const MIN_NAME_COLUMNS = 8
970
971/** Whether a card `cardWidth` wide has the mascot: its inside holds the mascot, a space and `MIN_NAME_COLUMNS`. */
972export const hasMascot = (cardWidth: number) => cardWidth - BORDER_COLUMNS >= MASCOT_SPACE + MIN_NAME_COLUMNS
973
974/** The index in `plan.rows` of the card whose page the pane shows, or null while it shows the board. */
975export const detailOf = (plan: PlanEntry, open: CardRef | null): number | null =>
976  open !== null && open.anchor === plan.anchor && plan.rows[open.index] !== undefined ? open.index : null
977
978/** Whether the band draws the rainbow: the plan is the one a PLAN-DONE with 0 left finished (until her next prompt) and has a Done row. */
979export const isRainbow = (plan: PlanEntry, finished: string | null): boolean => finished === plan.anchor && isComplete(bandPlanOf(plan, finished))
980
981/**
982 * What moves on screen: the band when it draws the rainbow of a finished plan or the plan is at work (`isActive`: its mascot), the
983 * pane's mascots while it is up with the board and the plan is at work. A complete plan nothing finished stands still.
984 */
985export function movement(plan: PlanEntry, view: { finished: string | null; isPaneUp: boolean; isBoard: boolean }): { band: boolean; pane: boolean } {
986  const drawn = bandPlanOf(plan, view.finished)
987
988  return {
989    band: isRainbow(plan, view.finished) || isActive(drawn),
990    pane: view.isPaneUp && view.isBoard && isActive(plan),
991  }
992}
993
994// ---------------------------------------------------------------- settings and file links
995
996/** What the person set in the plugin's settings (`userConfig`); `applyOptions` fills it when the module loads. */
997export const settings = { boardLocation: 'PROGRESS.md', boardCommand: '', yourName: '', root: '' }
998
999/** Reads the three settings out of the options the engine hands the module (a missing or blank one keeps its default). */
1000export function applyOptions(options: Readonly<Record<string, unknown>> | undefined): void {
1001  const text = (key: string, fallback: string) => {
1002    const value = options?.[key]
1003
1004    return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback
1005  }
1006
1007  settings.boardLocation = text('board_location', 'PROGRESS.md')
1008  settings.boardCommand = text('board_command', '')
1009  settings.yourName = text('your_name', '')
1010}
1011
1012/** Whether `name` is the person: `you` in any case, or their own name (the setting `your_name`, when set). */
1013export const isYou = (name: string | undefined): boolean => {
1014  const who = name?.trim().toLowerCase()
1015
1016  return who !== undefined && (who === 'you' || (settings.yourName !== '' && who === settings.yourName.toLowerCase()))
1017}
1018
1019/** The `file://` link of an absolute path; each segment is percent-encoded (spaces, `#`, CJK). */
1020const linkOf = (absolute: string) => `file://${absolute.split('/').map(encodeURIComponent).join('/')}`
1021
1022/**
1023 * The `file://` link of a file path in a note: `~/…` is under `home`, a path that starts with `/` is as it is and any other is relative to
1024 * the project root. null for a `~` path when the home directory is not known.
1025 */
1026export function fileHref(path: string, home: string | undefined): string | null {
1027  const absolute = absolutePath(path, home)
1028
1029  return absolute === null ? null : linkOf(absolute)
1030}
1031
1032/** The absolute path of a file path in a note: `~/…` is under `home` (null when not known), `/…` is as it is, any other is relative to the project root (null while that is not known). */
1033export function absolutePath(path: string, home: string | undefined): string | null {
1034  if (path === '~' || path.startsWith('~/')) {
1035    return home === undefined || home === '' ? null : `${home.replace(/\/+$/, '')}${path.slice(1)}`
1036  }
1037
1038  return path.startsWith('/') ? path : settings.root === '' ? null : `${settings.root.replace(/\/+$/, '')}/${path}`
1039}
1040
1041// ---------------------------------------------------------------- usage on the task page and the plan line
1042
1043/** `1.2M`, `48k`, `900`: a count in at most four characters of digits. */
1044export function compactCount(value: number): string {
1045  const trim = (n: number) => n.toFixed(1).replace(/\.0$/, '')
1046
1047  if (value >= 1_000_000) {
1048    return `${trim(value / 1_000_000)}M`
1049  }
1050
1051  return value >= 10_000 ? `${Math.round(value / 1000)}k` : value >= 1000 ? `${trim(value / 1000)}k` : String(Math.round(value))
1052}
1053
1054/** `$3.10`; `<$0.01` for an amount above nothing and under a cent, which `$0.00` would hide. */
1055export function costText(usd: number): string {
1056  return usd > 0 && usd < 0.005 ? '<$0.01' : `$${usd.toFixed(2)}`
1057}
1058
1059/** Every token a row or a plan used: input, cache reads, cache writes and output. */
1060const tokenTotal = (usage: RowUsage): number => usage.tokens_in + usage.tokens_cached + usage.tokens_cache_write + usage.tokens_out
1061
1062// ---------------------------------------------------------------- the plan line and the task page's lines
1063
1064/**
1065 * The dim label over a plan's recap: `Recap · updated 12 min ago`, from `recap_updated` (ISO, as the tracker wrote it).
1066 * Just `Recap` when there is no time, it is not an ISO time, or it lies ahead of `now`.
1067 */
1068export function recapLabel(plan: PlanEntry, now: number): string {
1069  const minutes = Math.floor((now - Date.parse(plan.recap_updated ?? '')) / 60_000)
1070
1071  if (!Number.isFinite(minutes) || minutes < 0) {
1072    return 'Recap'
1073  }
1074
1075  if (minutes < 1) {
1076    return 'Recap · updated just now'
1077  }
1078
1079  if (minutes < 60) {
1080    return `Recap · updated ${minutes} min ago`
1081  }
1082
1083  return minutes < 1440 ? `Recap · updated ${Math.floor(minutes / 60)} h ago` : `Recap · updated ${Math.floor(minutes / 1440)} d ago`
1084}
1085
1086const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
1087
1088const pad2 = (n: number): string => String(n).padStart(2, '0')
1089
1090/** `YYYY-MM-DDTHH:MM` of an instant on this machine's clock. */
1091function localMinute(ms: number): string {
1092  const at = new Date(ms)
1093
1094  return `${at.getFullYear()}-${pad2(at.getMonth() + 1)}-${pad2(at.getDate())}T${pad2(at.getHours())}:${pad2(at.getMinutes())}`
1095}
1096
1097/**
1098 * A tracker ISO time as the clock time when it is today (`19:23`) and as the day and the clock time on another day (`Oct 11 19:23`):
1099 * the one way the board writes a time (the plan's `updated`, the state word's `since`, a stalled task's tag and page). A time with an
1100 * offset reads as written, on its own clock, and "today" is `now` on that clock; a time ending in Z, or with no offset, reads on this
1101 * machine's clock. Undefined when the text is not an ISO time with a clock time.
1102 */
1103export function sinceText(iso: string, now: number): string | undefined {
1104  if (!/^\d{4}-\d\d-\d\dT\d\d:\d\d/.test(iso)) {
1105    return undefined
1106  }
1107
1108  const instant = /Z$/.test(iso) ? Date.parse(iso) : undefined
1109
1110  if (instant !== undefined && Number.isNaN(instant)) {
1111    return undefined
1112  }
1113
1114  const written = instant === undefined ? iso : localMinute(instant)
1115  const offset = /([+-])(\d\d):(\d\d)$/.exec(written)
1116  const today = offset === null ? localMinute(now).slice(0, 10) : new Date(now + (offset[1] === '-' ? -1 : 1) * (Number(offset[2]) * 60 + Number(offset[3])) * 60_000).toISOString().slice(0, 10)
1117  const time = written.slice(11, 16)
1118
1119  return written.slice(0, 10) === today ? time : `${MONTHS[Number(written.slice(5, 7)) - 1] ?? written.slice(5, 7)} ${Number(written.slice(8, 10))} ${time}`
1120}
1121
1122/**
1123 * One figure of the stats row: a big bold `value` over a small dim `label`. `drop` orders what a narrow pane gives up: the
1124 * lowest goes first.
1125 */
1126export type Stat = { value: string; label: string; drop: number }
1127
1128/** Columns between two stats of a row. */
1129export const STAT_GAP = 3
1130
1131/** What a stats row shows when the plan has not begun: no start or finish time, and no row has left Todo. */
1132export const NOT_STARTED = 'Not started yet'
1133
1134/**
1135 * Whether the plan has begun: it has a start or a finish time, or a row has left Todo (a Canceled row is ignored). The stats are drawn
1136 * for such a plan; a plan that has not begun reads `Not started yet` instead.
1137 */
1138const hasBegun = (plan: PlanEntry): boolean =>
1139  plan.started !== undefined || plan.finished !== undefined || plan.rows.some(row => row.status !== 'Todo' && row.status !== 'Canceled')
1140
1141/**
1142 * `Not started yet` for a plan that has not begun (no start or finish time, and every row Todo or Canceled), '' for any other plan,
1143 * whose header already says In progress, Idle or Done.
1144 */
1145export function notStartedText(plan: PlanEntry): string {
1146  return hasBegun(plan) ? '' : NOT_STARTED
1147}
1148
1149/** Columns a stat takes: the wider of its value and its label. */
1150const statCols = (stat: Stat): number => Math.max(displayWidth(stat.value), displayWidth(stat.label))
1151
1152/** `stats` as far as they fit `width` columns: the lowest `drop` goes first, the last one stays however narrow the pane. */
1153export function fitStats(stats: readonly Stat[], width: number): Stat[] {
1154  const kept = [...stats]
1155  const need = () => kept.reduce((all, stat) => all + statCols(stat), 0) + STAT_GAP * Math.max(0, kept.length - 1)
1156
1157  while (kept.length > 1 && need() > width) {
1158    const lowest = kept.reduce((low, stat) => (stat.drop < low.drop ? stat : low))
1159
1160    kept.splice(kept.indexOf(lowest), 1)
1161  }
1162
1163  return kept
1164}
1165
1166/** A stats row as two lines of text, each stat in a column as wide as the wider of its value and its label. */
1167export function statLines(stats: readonly Stat[]): { values: string; labels: string } {
1168  const cell = (text: string, stat: Stat) => `${text}${' '.repeat(statCols(stat) - displayWidth(text))}`
1169  const gap = ' '.repeat(STAT_GAP)
1170
1171  return { values: stats.map(stat => cell(stat.value, stat)).join(gap).trimEnd(), labels: stats.map(stat => cell(stat.label, stat)).join(gap).trimEnd() }
1172}
1173
1174/**
1175 * The tokens (every count) and the cost of `usage`, each a value over a label: nothing for no usage or no request counted, the cost
1176 * left out when it is nothing (requests of a model with no price). The tokens go first on a narrow row.
1177 */
1178const statsOfUsage = (usage: RowUsage | undefined): Stat[] =>
1179  usage === undefined || usage.requests <= 0
1180    ? []
1181    : [
1182        { value: compactCount(tokenTotal(usage)), label: 'tokens', drop: 2 },
1183        ...(usage.cost_usd > 0 ? [{ value: costText(usage.cost_usd), label: 'cost', drop: 3 }] : []),
1184      ]
1185
1186/**
1187 * The stats under the plan name: the plan's tokens (every count) and cost from its `usage_totals` (the plan's own share is inside them),
1188 * each a bold value over a dim label. No time: the plan's time is in the header (`planStateText`). With no request counted the plan has no
1189 * details line. Narrower than `width`: the tokens go first; the cost stays. Empty for a plan that has not begun (no start or finish time,
1190 * every row Todo or Canceled): it reads `Not started yet`. A plan under way with no start time draws the figures it has.
1191 */
1192export function planStatsOf(plan: PlanEntry, width: number): Stat[] {
1193  return hasBegun(plan) ? fitStats(statsOfUsage(plan.usage_totals), width) : []
1194}
1195
1196/** The line under the plan's stats that names the part of its total that no single task owns: `incl. $0.80 on the plan, not one task`; '' for none. */
1197export function planOwnText(totals: PlanTotals | undefined): string {
1198  const own = totals?.plan_own
1199
1200  if (own === undefined) {
hooks/draw.tsx 1397 lines
1/** The two drawings of the mod, as trees: the band above the prompt and the pane. */
2import type { BoxProps, ButtonProps, ClientProps, ElementConstructor, InputProps, LinkProps, MarkdownProps, RenderElement, RenderSurface, SvgProps, TextProps } from 'claude-code'
3
4import type { PlanEntry, PlanMatch, PlanRow } from '../types'
5import {
6  BAND_MASCOT_SPACE,
7  BAND_SPRITE_CELLS,
8  BAND_SPRITE_PX,
9  BAR_PX,
10  CARD_BAR_CELLS,
11  CARD_SPRITE_CELLS,
12  HEX,
13  barSvg,
14  countOf,
15  filledOf,
16  BORDER_COLUMNS,
17  BOARD_LABEL,
18  CARD_SPRITE_PX,
19  TRACK_COLOR,
20  spriteSvg,
21  spriteSvgAnimated,
22  CHIPS,
23  chipOf,
24  planStateText,
25  FILE_LABEL,
26  LINK_COLOR,
27  MASCOT,
28  MASCOT_COLUMNS,
29  NEEDS_YOU_COLOR,
30  SIDE_BY_SIDE_FROM,
31  STYLE,
32  bandFit,
33  bandLine,
34  cardRows,
35  checkerOf,
36  cardView,
37  countText,
38  STATE_COLUMNS,
39  STATE_STYLE,
40  fileHref,
41  planStatsOf,
42  planOwnText,
43  ledgerErrorText,
44  notStartedText,
45  recapLabel,
46  planStateOf,
47  progressOf,
48  sessionLineOf,
49  statusWords,
50  usageStatsOf,
51  fitStats,
52  statLines,
53  STAT_GAP,
54  whoLineOf,
55  displayWidth,
56  noteLinesOf,
57  isBlocked,
58  executorOf,
59  isYou,
60  isRunning,
61  isStalled,
62  LANE_GAP,
63  laneWidth,
64  lanesOf,
65  SHOW_LESS,
66  mascotAt,
67  moreButton,
68  overflowLabel,
69  piecesOf,
70  rainbowAt,
71  shortPath,
72  sinceText,
73  truncate,
74  wrap,
75  worstStatus,
76} from './board'
77import type { CardRow } from './card'
78import type { Card, Chip, Lane, LaneKey, PlanState, Pose, Progress, Stat } from './board'
79
80/** The elements both drawings use; every surface's table has them. */
81export type Kit = {
82  Box: ElementConstructor<BoxProps>
83  Text: ElementConstructor<TextProps>
84  Button: ElementConstructor<ButtonProps>
85  Link: ElementConstructor<LinkProps>
86  Markdown: ElementConstructor<MarkdownProps>
87  /** Absent on a surface with no `Client` (vscode, mobile): a card is then Buttons. */
88  Client?: ElementConstructor<ClientProps>
89  /** Only the remote surfaces (desktop, vscode, mobile) draw it. */
90  Svg?: ElementConstructor<SvgProps>
91  /** The list's search field; absent on mobile, which draws no field. */
92  Input?: ElementConstructor<InputProps>
93}
94
95/** Whether what the hooks below drew is more than an empty Box or Text. */
96export function holdsSomething(drawn: RenderElement | null | undefined): boolean {
97  if (!drawn) {
98    return false
99  }
100
101  return (drawn.type !== 'Box' && drawn.type !== 'Text') || drawn.children === undefined || drawn.children.length > 0
102}
103
104/** The surfaces with a proportional font, laid out with flex rather than padded with spaces: the desktop app and vscode. */
105export const isProportionalSurface = (surface: string): boolean => surface === 'desktop' || surface === 'vscode'
106
107/** vscode's card button: the card's text is not pressable there (no Client), so this opens the card's page. */
108export const CARD_OPEN_LABEL = 'Open ›'
109
110/** vscode lays the lanes side by side from this many columns: its proportional text fits a lane in a quarter of a narrower row. */
111export const QUIET_SIDE_BY_SIDE_FROM = 60
112
113/** The kit's Button, drawn dim when `isQuiet`: vscode draws a plain Button as a filled chip, a dim one as a quiet outline. */
114export function quietButton(kit: Kit, isQuiet: boolean): Kit['Button'] {
115  return isQuiet ? props => kit.Button({ ...props, dimColor: true }) : kit.Button
116}
117
118/** The kit with Ink's rule for rows when `isQuiet`: vscode wraps a row by default, so a row too wide drops its end to a new line instead of cutting the text set to cut. */
119export function inkRows(kit: Kit, isQuiet: boolean): Kit {
120  return isQuiet ? { ...kit, Box: props => kit.Box({ flexWrap: 'nowrap', ...props }) } : kit
121}
122
123/**
124 * Characters of proportional text that fit one column vscode reports. Cursor counts its columns by the width of "─", which is wide
125 * in its font: a pane of about 880 px reported 66 columns (about 13.3 px each), while ordinary text runs about 6.6 px a character,
126 * so about 2.0 characters fit a column. 1.8 leaves room for bold.
127 */
128export const VSCODE_CHARS_PER_COLUMN = 1.8
129
130/** The characters vscode's text has room for in `columns` reported columns: the budget its cuts by count use. */
131export const vscodeChars = (columns: number): number => Math.floor(columns * VSCODE_CHARS_PER_COLUMN)
132
133/** Characters per `ch` of width in vscode's text, kept under the measured ~1.33 so a wide name (or a CJK one, 2 per character) still fits
134 * its box: a plan list's name column sized in plain characters left a gap of about a third of the name before the state column. */
135export const VSCODE_CHARS_PER_CH = 1.2
136
137/** Characters the band's frame takes on vscode: its padding of 1 ch each side (ch is about one character there; the borders are 1 px). */
138const QUIET_FRAME_CHARS = 2
139
140/** A no-break space: vscode collapses or drops plain spaces at the ends of a text. */
141const NBSP = ' '
142
143/** Two no-break spaces: the gap a link's text keeps. */
144const GAP = `${NBSP}${NBSP}`
145
146/** Markdown's special characters escaped, so a name is drawn as written. */
147const escapeMarkdown = (text: string) => text.replace(/[\\`*_[\]<>~&]/g, '\\$&')
148
149/** Text a line cannot break: no-break spaces, and a word joiner between characters (a hyphen or an arrow is a break otherwise). */
150const unbreakable = (text: string) => Array.from(text.replace(/ /g, NBSP)).join('\u2060')
151
152/** The address of a vscode band link: the mod answers it by the Markdown's key (`ui.press`), and `.invalid` opens nowhere. */
153const bandHref = (key: string) => `https://plan-tracker.invalid/${key.split(':').join('/')}`
154
155/** The desktop's card bar: a fixed 8 cells whatever the total, filled in proportion to done/total. */
156const deskBar = (bar: Progress, color: string) => {
157  const filled = filledOf(bar.done, bar.total, CARD_BAR_CELLS)
158
159  return { filled, empty: CARD_BAR_CELLS - filled, color, track: TRACK_COLOR }
160}
161
162/** The fields of a card row's tag: its chip (the grey one of `stalled` and its time too), or none. */
163const tagFields = (word: string, pad: number): Pick<CardRow, 'tag' | 'tagPad' | 'tagBg' | 'tagFg' | 'tagBold'> => {
164  const chip: Chip | undefined = chipOf(word)
165
166  return word === '' || chip === undefined
167    ? { tag: '', tagPad: 0, tagBg: '', tagFg: '', tagBold: false }
168    : { tag: word, tagPad: pad, tagBg: chip.bg, tagFg: chip.fg, tagBold: chip.bold === true }
169}
170
171/** `text` padded with spaces on the right to `cols` columns. */
172const padTo = (text: string, cols: number) => `${text}${' '.repeat(Math.max(0, cols - displayWidth(text)))}`
173
174type BandArgs = {
175  /** The plan the band draws (as finished when a PLAN-DONE with 0 left named it). */
176  plan: PlanEntry
177  plans: readonly PlanEntry[]
178  /** Columns the row has after the mascot and its space. */
179  columns: number
180  /** What the hooks below drew, drawn under ours when it holds something. */
181  below: RenderElement | undefined
182  /** Whether the plan list shows under the row. */
183  isOpen: boolean
184  /** Whether the board is showing the plan file: the right end is then the way back to the board. */
185  isFile: boolean
186  /** With a frame the filled cells are the rainbow at that frame instead of the success color. */
187  frame: number | null
188  pose: string
189  /** The time a state word's `since` is compared with, to say today's time as a clock time and another day's with its day (`Date.now()`); a parameter so a test can pin it. */
190  now: number
191  /** The card sprite's pose the desktop draws instead of `pose`'s block characters. */
192  spritePose?: Pose
193  /** The desktop's sprite switches its poses by itself (a plan with a row In Progress), with no redraw. */
194  isMoving?: boolean
195  /** The desktop's proportional font: the mascot is drawn one Box per cell. */
196  isProportional?: boolean
197  /** Whether the surface draws a `Client` (terminal, desktop); a proportional surface without one (vscode) has links for its click targets. */
198  hasClient?: boolean
199  /** Rows the engine lets the band show whole (`e.props.maxRows`); a terminal band that does not fit them with its frame is drawn without it. */
200  maxRows?: number
201  onBar: () => void
202  onMenu: () => void
203  onPick: (anchor: string) => void
204  onFile: () => void
205  onBoard: () => void
206}
207
208type PlanListArgs = {
209  plans: readonly PlanEntry[]
210  /** The open plan: its row is marked ▶ and drawn inverse. */
211  plan: PlanEntry
212  /** The columns the list may take, its one margin column included. */
213  columns: number
214  /** `Date.now()`, for the state words' times. */
215  now: number
216  /** The list Box's key. */
217  listKey: string
218  /** What a row's Button key starts with; the anchor follows. */
219  pickKey: string
220  onPick: (anchor: string) => void
221  isQuiet: boolean
222}
223
224/**
225 * One row of a plan list: a plan of the session, or a plan of the board command's list. `state` picks the color; `stateText` is the word drawn
226 * (`Idle since 19:40`). `time` is when a listed plan was last updated (`19:40` today, `Oct 9 20:08` another day); a plan of the session has none.
227 */
228export type ListItem = { anchor: string; name: string; state: PlanState; stateText: string; count: string; time?: string }
229
230/**
231 * What the plan list draws of a plan of the session: the only part of the session's other plans the pane reads. The render hook
232 * compares these (not the whole plans) to tell whether a new answer of the tracker changes what it draws.
233 */
234export const listedOf = (plan: PlanEntry, now: number): ListItem => ({ anchor: plan.anchor, name: plan.name, state: planStateOf(plan), stateText: planStateText(plan, now), count: countText(plan) })
235
236type RowsArgs = {
237  items: readonly ListItem[]
238  /** The anchor of the open plan: its row is marked ▶ and drawn inverse; null for a list with no open plan. */
239  activeAnchor: string | null
240  columns: number
241  listKey: string
242  pickKey: string
243  onPick: (anchor: string) => void
244  /** vscode: each name is a quiet Button with its label only, and the columns are set apart by margins, not spaces. */
245  isQuiet?: boolean
246}
247
248/**
249 * The rows of a plan list: one per plan (`▶` for the open one, the name, its state text in the state's style, n/m, and a listed plan's
250 * time, dim), the open row inverse and bold. The state column is as wide as the widest text (`Stalled since Oct 11 19:23` is wider than
251 * `In progress`); with times the count column is padded so they line up. The name is cut first (to 1 column at the least); if even then the
252 * state text and the time have no room, they are dropped whole.
253 */
254function drawListRows(kit: Kit, { items, activeAnchor, columns, listKey, pickKey, onPick, isQuiet = false }: RowsArgs): RenderElement {
255  const { Box, Text } = kit
256  const Button = quietButton(kit, isQuiet)
257  // vscode's columns hold about two characters each: the names are cut to the characters it fits.
258  const room = (isQuiet ? vscodeChars(columns) : columns) - 1
259  const countCols = Math.max(0, ...items.map(one => displayWidth(one.count)))
260  const stateCols = Math.max(STATE_COLUMNS, ...items.map(one => displayWidth(one.stateText)))
261  const timeCols = Math.max(0, ...items.map(one => displayWidth(one.time ?? '')))
262  const nameRoom = (hasState: boolean) => room - 2 - 1 - countCols - (hasState ? stateCols + 2 + (timeCols > 0 ? timeCols + 2 : 0) : 0)
263  const hasState = nameRoom(true) >= 4
264  const names = items.map(one => truncate(one.name, Math.max(1, nameRoom(hasState))))
265  const nameCols = Math.max(0, ...names.map(displayWidth))
266
267  const option = (one: ListItem, at: number) => {
268    const isOn = one.anchor === activeAnchor
269    const text = `${isOn ? '▶' : ' '} ${padTo(names[at] ?? '', nameCols)}`
270
271    // vscode draws a Button's label alone (its children flattened, so the open row cannot be inverse) and drops a Text's trailing
272    // spaces: the open row is marked by the ▶ in its label alone, and each column is a Box of one fixed width in ch (about a character
273    // there), the name's holding its longest name, the ▶ and the Button's border, so the columns line up row to row.
274    if (isQuiet) {
275      const label = `${isOn ? `▶${NBSP}` : ''}${names[at] ?? ''}`
276
277      return (
278        <Box flexDirection="row">
279          <Box width={Math.ceil(nameCols / VSCODE_CHARS_PER_CH) + 5} flexShrink={0}>
280            <Button plain key={`${pickKey}${one.anchor}`} label={label} onPress={() => onPick(one.anchor)} />
281          </Box>
282          {hasState ? (
283            <Box marginLeft={2} width={stateCols} flexShrink={0}>
284              <Text {...STATE_STYLE[one.state]}>{one.stateText}</Text>
285            </Box>
286          ) : null}
287          <Box marginLeft={1} width={countCols} flexShrink={0}>
288            <Text color="suggestion">{one.count}</Text>
289          </Box>
290          {hasState && one.time !== undefined ? (
291            <Box marginLeft={2} flexShrink={0}>
292              <Text dimColor>{one.time}</Text>
293            </Box>
294          ) : null}
295        </Box>
296      )
297    }
298
299    return (
300      <Box flexDirection="row">
301        <Button plain key={`${pickKey}${one.anchor}`} label={text} onPress={() => onPick(one.anchor)}>
302          <Text {...(isOn ? { bold: true, inverse: true } : {})}>{text}</Text>
303        </Button>
304        {hasState ? <Text {...STATE_STYLE[one.state]} {...(isOn ? { inverse: true } : {})}>{`  ${padTo(one.stateText, stateCols)}`}</Text> : null}
305        <Text color="suggestion" {...(isOn ? { inverse: true } : {})}>{` ${timeCols > 0 ? padTo(one.count, countCols) : one.count}`}</Text>
306        {hasState && one.time !== undefined ? <Text dimColor>{`  ${one.time}`}</Text> : null}
307      </Box>
308    )
309  }
310
311  return (
312    <Box key={listKey} flexDirection="column" marginLeft={1}>
313      {items.map(option)}
314    </Box>
315  )
316}
317
318/** The plan list both the board's dropdown and the band's open: every plan of the session, the open one marked. */
319function drawPlanList(kit: Kit, { plans, plan, columns, now, listKey, pickKey, onPick, isQuiet }: PlanListArgs): RenderElement {
320  return drawListRows(kit, {
321    items: plans.map(one => listedOf(one, now)),
322    activeAnchor: plan.anchor,
323    columns,
324    listKey,
325    pickKey,
326    onPick,
327    isQuiet,
328  })
329}
330
331/**
332 * A plan of the board command's list as a row of it: the bare state word (Waiting for you for an Idle plan the command marks `waiting`),
333 * `n/m` and when it was last updated (`sinceText`).
334 */
335export const listedMatchOf = (one: PlanMatch, now: number): ListItem => {
336  const time = one.updated === undefined ? undefined : sinceText(one.updated, now)
337  const state = one.waiting === true && one.state === 'Idle' ? 'Waiting for you' : one.state
338
339  return { anchor: one.anchor, name: one.name, state, stateText: state, count: `${one.done}/${one.total}`, ...(time === undefined ? {} : { time }) }
340}
341
342type PickerArgs = {
343  /** The rows the search leaves, in the board command's order (latest first). */
344  rows: readonly ListItem[]
345  /** The search field's text. */
346  search: string
347  /** The line drawn when no row is left. */
348  empty: string
349  /** `e.props.bodyColumns` */
350  columns: number
351  /** The surface drawing: vscode gets Ink's rows and quiet label-only Buttons. */
352  surface: RenderSurface
353  onPick: (anchor: string) => void
354  onInput: (value: string) => void
355  onSubmit: (value: string) => void
356}
357
358/**
359 * What the pane shows while it lists the plans: the search field (`Search plans`), then the rows the search leaves as the plan list draws
360 * them, with no plan open (a press picks one: keys `match:<anchor>`), or the `empty` line when none is left. A surface with no `Input`
361 * (mobile) has the rows alone.
362 */
363export function drawPicker(given: Kit, { rows, search, empty, columns, surface, onPick, onInput, onSubmit }: PickerArgs): RenderElement {
364  // vscode: proportional with no Client.
365  const isQuiet = surface === 'vscode'
366  const kit = inkRows(given, isQuiet)
367  const { Box, Text, Input } = kit
368
369  return (
370    <Box key="matches" flexDirection="column">
371      {Input === undefined ? null : <Input key="search" placeholder="Search plans" value={search} autoFocus onInput={onInput} onSubmit={onSubmit} />}
372      {rows.length === 0
373        ? <Text dimColor>{empty}</Text>
374        : drawListRows(kit, { items: rows, activeAnchor: null, columns, listKey: 'matches:list', pickKey: 'match:', onPick, isQuiet })}
375    </Box>
376  )
377}
378
379/** Columns the band's frame takes from the row: two border columns and one padding column each side. */
380const FRAME_COLUMNS = 4
381
382type QuietBandArgs = {
383  plan: PlanEntry
384  hasChoice: boolean
385  /** Columns the row has after the mascot and its space, the frame included. */
386  columns: number
387  now: number
388  isFile: boolean
389  frame: number | null
390  spritePose?: Pose
391  isMoving: boolean
392  onBar: () => void
393  onMenu: () => void
394  onFile: () => void
395  onBoard: () => void
396}
397
398/**
399 * vscode's band row: no part of it can be an invisible click area there (no Client; Svg and Box take no press), so the click
400 * targets are pressable Markdown links (underlined, no border). The mascot, the dot (coloured), then the name: with one plan `<name>` keyed
401 * `band:head` (the board), with two plans or more `<name> ▾` keyed `band:plans` (the plan list); then `<state>  n/m` keyed `band:bar` (the
402 * board), which never shrinks; then the bar (a picture, no press) and "Plan file ›". The texts are cut by count to the room `bandFit` leaves,
403 * use no-break spaces, and sit in Boxes that clip what overflows, so the band is one line. A press is answered by its key (`actionFor`).
404 */
405function drawQuietBandRow(kit: Kit, a: QuietBandArgs): RenderElement {
406  const { Box, Text, Markdown } = kit
407  const Button = quietButton(kit, true)
408  const { color: dotColor, ...dotDim } = STYLE[worstStatus(a.plan)]
409  const fileLabel = a.isFile ? BOARD_LABEL : FILE_LABEL
410  // The whole row in characters, less the mascot's Box (its width in ch) and the frame: `columns` counts the mascot's space in reported columns.
411  const chars = vscodeChars(a.columns + BAND_MASCOT_SPACE) - BAND_SPRITE_CELLS - QUIET_FRAME_CHARS
412  const fit = bandFit(a.plan, chars, a.hasChoice, displayWidth(fileLabel), a.now)
413  const tail = `${fit.hasState ? `${fit.stateText}${GAP}` : ''}${fit.count}`
414  // The name may be cut at the row's edge; its ▾, the state and the count never shrink, so they stay whole as in the terminal.
415  const targets = [
416    a.hasChoice ? { key: 'band:plans', text: fit.name, press: a.onMenu, isFixed: false, mark: '▾' } : { key: 'band:head', text: fit.name, press: a.onBar, isFixed: false },
417    { key: 'band:bar', text: tail, press: a.onBar, isFixed: true },
418  ]
419  const { done, total } = countOf(a.plan)
420
421  // No height clamp: the Markdown's own root scrolls (overflow-y auto) when its line is taller than the Box, and Cursor shows that scrollbar.
422  // The text cannot break (`unbreakable`), so it stays one line; what does not fit is clipped at the Box's edge.
423  const target = ({ key, text, press, isFixed, mark }: { key: string; text: string; press: () => void; isFixed: boolean; mark?: string }) => {
424    const href = bandHref(key)
425    const link = (
426      <Box key={`${key}:box`} overflow="hidden" flexShrink={isFixed ? 0 : 1} minWidth={isFixed ? undefined : 0} marginRight={mark === undefined ? 1 : 0}>
427        <Markdown key={key} text={`[${escapeMarkdown(unbreakable(text))}](${href})`} pressableLinks={[href]} onLinkPress={press} />
428      </Box>
429    )
430
431    return mark === undefined
432      ? [link]
433      : [
434          link,
435          <Box key={`${key}:mark`} flexShrink={0} marginRight={1}>
436            <Text>{`${NBSP}${mark}`}</Text>
437          </Box>,
438        ]
439  }
440
441  // Centered: the bar picture is shorter than a line and would otherwise sit at the row's top.
442  return (
443    <Box key="bar" flexDirection="row" alignItems="center">
444      {kit.Svg === undefined ? null : (
445        <Box key="band:part:mascot" width={BAND_SPRITE_CELLS} flexShrink={0}>
446          <kit.Svg
447            source={(a.isMoving ? spriteSvgAnimated(MASCOT, 'claude') : spriteSvg(a.spritePose ?? MASCOT[0], 'claude')).source}
448            alt="Claude Code's mascot"
449            width={BAND_SPRITE_PX.width}
450            height={BAND_SPRITE_PX.height}
451          />
452        </Box>
453      )}
454      <Box key="band:part:dot" flexShrink={0}>
455        <Box marginRight={1}>
456          <Text color={dotColor} {...dotDim}>●</Text>
457        </Box>
458      </Box>
459      {targets.flatMap(target)}
460      {kit.Svg === undefined ? null : (
461        <Box key="band:solid" flexShrink={0} marginRight={1}>
462          <kit.Svg
463            source={barSvg(
464              total === 0 ? 0 : done / total,
465              HEX.success ?? '#3C9D5A',
466              a.frame === null ? undefined : Array.from({ length: Math.max(1, fit.filled) }, (_, at) => rainbowAt(at, a.frame ?? 0)),
467            )}
468            alt={`${fit.count} done`}
469            width={BAR_PX.width}
470            height={BAR_PX.height}
471          />
472        </Box>
473      )}
474      <Box key="band:part:rest" flexGrow={1} flexShrink={1} minWidth={2} />
475      {a.isFile ? (
476        <Button plain key="band:board" label={BOARD_LABEL} onPress={a.onBoard} />
477      ) : (
478        <Button plain key="band:file" label={FILE_LABEL} onPress={a.onFile} />
479      )}
480    </Box>
481  )
482}
483
484/**
485 * The band: ONE row inside a dim round frame, `<mascot> ● <name> ▾  <bar> n/m ........ Plan file ›`, then the plan list when it is open, then
486 * whatever the hooks below drew. A Button takes no color, so the colored parts are Text inside a plain Button: "name ▾"
487 * opens the list, the bar and the count toggle the board, "Plan file ›" opens the board on the plan file (and is "‹ Board"
488 * while it shows it).
489 */
490export function drawBand(given: Kit, args: BandArgs): RenderElement {
491  const kit = inkRows(given, args.isProportional === true && args.hasClient !== true)
492  const { Box, Text } = kit
493  const { plan, plans, columns, below, isOpen, isFile, frame, pose, now, spritePose, isMoving = false, isProportional = false, hasClient = false, maxRows = Number.POSITIVE_INFINITY, onBar, onMenu, onPick, onFile, onBoard } = args
494  // vscode (proportional, no Client) draws its native button as a filled chip; dim, it is a quiet outline.
495  const isQuiet = isProportional && !hasClient
496  const Button = quietButton(kit, isQuiet)
497  const line = bandLine(plan, columns, now)
498  const { color: stateColor } = STATE_STYLE[line.state]
499  const hasChoice = plans.length > 1
500  const { color: dotColor, ...dotDim } = STYLE[worstStatus(plan)]
501  const fileLabel = isFile ? BOARD_LABEL : FILE_LABEL
502  const fileButton = isFile ? (
503    <Button plain key="band:board" label={BOARD_LABEL} onPress={onBoard} />
504  ) : (
505    <Button plain key="band:file" label={FILE_LABEL} onPress={onFile} />
506  )
507
508  const filledCells = (count: number) =>
509    Array.from({ length: count }, (_, at) => <Text color={frame === null ? STYLE.Done.color : rainbowAt(at, frame)}>▰</Text>)
510
511  // The desktop: a Button holds only strings and Text, so a picture (the mascot, the bar) cannot be pressed. A region
512  // that posts `{ band: 'toggle' }` is laid over each such part (and the dot and the gap), so the whole band is a target. The
513  // name's and the plan file's buttons are drawn as before, and a region never covers them.
514  const Client = isProportional ? kit.Client : undefined
515
516  const zone = (key: string, child: RenderElement, fit: 'fixed' | 'grow' | 'shrink' = 'fixed') => {
517    const flex = fit === 'grow' ? { flexGrow: 1, flexShrink: 1 } : fit === 'shrink' ? { flexShrink: 1, minWidth: 0 } : { flexShrink: 0 }
518
519    return Client === undefined ? (
520      child
521    ) : (
522      <Box key={`band:zone:${key}`} position="relative" {...flex}>
523        {child}
524        <Box position="absolute" top={0} left={0} width="100%" height="100%">
525          <Client key={`band:zone:${key}:region`} module="./band.tsx" width="100%" height="100%" />
526        </Box>
527      </Box>
528    )
529  }
530
531  if (isQuiet) {
532    return (
533      <Box flexDirection="column">
534        <Box key="band:frame" flexDirection="column" borderStyle="round" borderDimColor paddingX={1}>
535          {drawQuietBandRow(kit, {
536            plan,
537            hasChoice,
538            columns,
539            now,
540            isFile,
541            frame,
542            ...(spritePose === undefined ? {} : { spritePose }),
543            isMoving,
544            onBar,
545            onMenu,
546            onFile,
547            onBoard,
548          })}
549        </Box>
550        {isOpen && hasChoice ? drawPlanList(kit, { plans, plan, columns: columns + BAND_MASCOT_SPACE, now, listKey: 'band:list', pickKey: 'band:plan:', onPick, isQuiet }) : null}
551        {holdsSomething(below) ? below : null}
552      </Box>
553    )
554  }
555
556  if (isProportional) {
557    // The name is whole: the row's Text cuts it by the room the panel leaves, not by a count of characters.
558    const name = <Text bold wrap="truncate">{plan.name}</Text>
559
560    return (
561      <Box flexDirection="column">
562        <Box key="band:frame" flexDirection="column" borderStyle="round" borderDimColor paddingX={1}>
563        <Box key="bar" flexDirection="row">
564          {kit.Svg !== undefined
565            ? zone(
566                'mascot',
567                <Box width={BAND_SPRITE_CELLS} flexShrink={0} alignSelf="center">
568                  <kit.Svg
569                    source={(isMoving ? spriteSvgAnimated(MASCOT, 'claude') : spriteSvg(spritePose ?? MASCOT[0], 'claude')).source}
570                    alt="Claude Code's mascot"
571                    width={BAND_SPRITE_PX.width}
572                    height={BAND_SPRITE_PX.height}
573                    {...(isMoving ? { isInteractive: true } : {})}
574                  />
575                </Box>,
576              )
577            : null}
578          {zone('dot', <Text color={dotColor} {...dotDim}>●{' '}</Text>)}
579          {hasChoice ? (
580            <Box key="band:name" flexShrink={1} minWidth={0}>
581              <Button plain key="band:plans" label={`${plan.name} ▾`} onPress={onMenu}>
582                {name}
583                <Text> ▾</Text>
584              </Button>
585            </Box>
586          ) : (
587            zone('name', name, 'shrink')
588          )}
589          {zone(
590            'gap',
591            <Box flexDirection="row">
592              <Text> </Text>
593              <Text color={stateColor}>{line.stateText}</Text>
594              <Text>{'  '}</Text>
595            </Box>,
596          )}
597          {kit.Svg === undefined
598            ? null
599            : zone(
600                'bar',
601                // The glyphs draw as slanted dashes in a proportional font: a thin rounded bar of one fixed width.
602                <Box key="band:solid" flexShrink={0} alignSelf="center" marginRight={1}>
603                  <kit.Svg
604                    source={barSvg(
605                      countOf(plan).total === 0 ? 0 : countOf(plan).done / countOf(plan).total,
606                      HEX.success ?? '#3C9D5A',
607                      frame === null ? undefined : Array.from({ length: Math.max(1, line.filled) }, (_, at) => rainbowAt(at, frame)),
608                    )}
609                    alt={`${line.count} done`}
610                    width={BAR_PX.width}
611                    height={BAR_PX.height}
612                  />
613                </Box>,
614              )}
615          <Button plain key="band:bar" label={` ${line.count}`} onPress={onBar}>
616            <Text>{` ${line.count}`}</Text>
617          </Button>
618          {zone('rest', <Box minWidth={2} />, 'grow')}
619          {fileButton}
620        </Box>
621        </Box>
622        {isOpen && hasChoice ? drawPlanList(kit, { plans, plan, columns: columns + BAND_MASCOT_SPACE, now, listKey: 'band:list', pickKey: 'band:plan:', onPick, isQuiet }) : null}
623        {holdsSomething(below) ? below : null}
624      </Box>
625    )
626  }
627
628  // The terminal: the mascot, the dot and (with one plan) the name are one Button; the bar, the count and the gap up to
629  // "Plan file ›" are another. Both toggle the board; the name's menu and the plan file keep their own buttons. The parts
630  // are fitted to the frame's inside (`bandFit`), so the row never runs past the column a docked pane leaves it.
631  // A pane open inline can leave the band two rows: then the frame (its two border rows) goes and the band is the one row it was before it.
632  const framedFit = bandFit(plan, columns - FRAME_COLUMNS, hasChoice, displayWidth(fileLabel), now)
633  const isFramed = maxRows >= (framedFit.isStacked ? 4 : 3)
634  const frameColumns = isFramed ? FRAME_COLUMNS : 0
635  const fit = isFramed ? framedFit : bandFit(plan, columns, hasChoice, displayWidth(fileLabel), now)
636  const headText = `${pose} ● ${hasChoice ? '' : fit.name}`
637  const nameWidth = hasChoice ? displayWidth(`${fit.name} ▾`) : 0
638  const bar = fit.filled + fit.empty
639  const barText = ` ${fit.hasState ? `${fit.stateText}  ` : ''}${bar > 0 ? `${'▰'.repeat(fit.filled)}${'▱'.repeat(fit.empty)} ` : ''}${fit.count}`
640  const used = displayWidth(headText) + nameWidth + displayWidth(barText) + (fit.hasFile ? displayWidth(fileLabel) : 0)
641  const filler = ' '.repeat(Math.max(0, columns + BAND_MASCOT_SPACE - frameColumns - used - (fit.hasFile ? 2 : 0)))
642
643  const progress = (
644    <Button plain key="band:bar" label={`${barText}${fit.isStacked ? '' : filler}`} onPress={onBar}>
645      <Text>{' '}</Text>
646      {fit.hasState ? <Text color={stateColor}>{fit.stateText}</Text> : null}
647      {fit.hasState ? <Text>{'  '}</Text> : null}
648      {bar > 0 ? filledCells(fit.filled) : null}
649      {bar > 0 ? <Text dimColor>{'▱'.repeat(fit.empty)}</Text> : null}
650      {bar > 0 ? <Text>{' '}</Text> : null}
651      <Text>{`${fit.count}${fit.isStacked ? '' : filler}`}</Text>
652    </Button>
653  )
654
655  return (
656    <Box flexDirection="column">
657      <Box key={isFramed ? 'band:frame' : 'band:plain'} flexDirection="column" {...(isFramed ? { borderStyle: 'round' as const, borderDimColor: true, paddingX: 1 } : {})}>
658        <Box key="bar" flexDirection="row">
659          <Button plain key="band:head" label={headText} onPress={onBar}>
660            <Text color="claude">{`${pose} `}</Text>
661            <Text color={dotColor} {...dotDim}>
662              ●{' '}
663            </Text>
664            {hasChoice ? null : <Text bold>{fit.name}</Text>}
665          </Button>
666          {hasChoice ? (
667            <Button plain key="band:plans" label={`${fit.name} ▾`} onPress={onMenu}>
668              <Text bold>{fit.name}</Text>
669              <Text> ▾</Text>
670            </Button>
671          ) : null}
672          {fit.isStacked ? <Box flexGrow={1} minWidth={0} /> : progress}
673          {fit.isStacked ? null : <Box flexGrow={1} minWidth={1} />}
674          {fit.hasFile ? fileButton : null}
675        </Box>
676        {fit.isStacked ? (
677          <Box key="bar:2" flexDirection="row">
678            {progress}
679            <Box flexGrow={1} minWidth={0} />
680          </Box>
681        ) : null}
682      </Box>
683      {isOpen && hasChoice ? drawPlanList(kit, { plans, plan, columns: columns + BAND_MASCOT_SPACE, now, listKey: 'band:list', pickKey: 'band:plan:', onPick, isQuiet }) : null}
684      {holdsSomething(below) ? below : null}
685    </Box>
686  )
687}
688
689type StatsArgs = {
690  stats: readonly Stat[]
691  isProportional: boolean
692  boxKey: string
693}
694
695/**
696 * A row of stats, each a bold value over a small dim label. The terminal has no font size: two lines of text, the values bold
697 * and the labels dim under them, each stat in a column as wide as the wider of the two. The desktop has no size prop either: a
698 * Box per stat, the value bold in the normal colour against its dim label.
699 */
700function drawStats(kit: Kit, { stats, isProportional, boxKey }: StatsArgs): RenderElement {
701  const { Box, Text } = kit
702
703  if (isProportional) {
704    return (
705      <Box key={boxKey} flexDirection="row" gap={STAT_GAP} marginTop={1}>
706        {stats.map(stat => (
707          <Box key={`${boxKey}:${stat.label}`} flexDirection="column" flexShrink={0}>
708            <Text bold wrap="truncate">
709              {stat.value}
710            </Text>
711            <Text dimColor wrap="truncate">
712              {stat.label}
713            </Text>
714          </Box>
715        ))}
716      </Box>
717    )
718  }
719
720  const { values, labels } = statLines(stats)
721
722  return (
723    <Box key={boxKey} flexDirection="column">
724      <Text bold wrap="truncate">
725        {values}
726      </Text>
727      <Text dimColor wrap="truncate">
728        {labels}
729      </Text>
730    </Box>
731  )
732}
733
734/** What the pane shows besides the board: the plan file's text, or why there is none. */
735export type FileView = { text: string } | { error: string }
736
737type PaneArgs = {
738  plans: readonly PlanEntry[]
739  plan: PlanEntry
740  /** `e.props.bodyColumns` */
741  columns: number
742  message: string | null
743  /** The ids of the sessions whose usage ledger could not be read (the board's `ledger_errors`); a line under the plan details says how many. */
744  ledgerErrors?: readonly string[]
745  /** The index in `plan.rows` of the card whose page replaces the board; null shows the board. */
746  detail: number | null
747  /** The plan file view replaces the board (and the page): its text, or why it cannot be read. */
748  file: FileView | null
749  /** The time a shown time (`updated`, a state word's `since`, a stalled mark) is compared with, to say today's as a clock time and another day's with its day (`Date.now()`); a parameter so a test can pin it. */
750  now: number
751  /** Rows the pane shows (`scroll.bodyRows`); undefined when the surface does not say. */
752  bodyRows?: number
753  /** The person's home directory, which a `~/` path in a note is under; undefined when not known. */
754  home: string | undefined
755  /** The animation frame the mascot is drawn at. */
756  frame: number
757  /** Whether the plan dropdown shows its list. */
758  isOpen: boolean
759  /** The lanes of the plan that show all their cards. */
760  expanded: readonly LaneKey[]
761  /** Whether the surface draws a `Client` (terminal, desktop): a card is then one, else Buttons. */
762  hasClient: boolean
763  /** The surface drawing: the desktop app has a proportional font, so it is laid out with flex, not padded with spaces. */
764  surface: RenderSurface
765  onMenu: () => void
766  onPick: (anchor: string) => void
767  onCard: (index: number) => void
768  onBack: () => void
769  onFile: () => void
770  onLane: (key: LaneKey) => void
771}
772
773/** Columns of plan name the pane's header keeps beside "Plan file ›"; a narrower room puts that button on a row of its own. */
774const MIN_HEAD_NAME = 8
775
776/** The pane: the plan dropdown, "Plan file ›" and the plan line on top, then the four lanes (or one card's page, or the plan file). */
777export function drawPane(given: Kit, args: PaneArgs): RenderElement {
778  const kit = inkRows(given, isProportionalSurface(args.surface) && args.hasClient !== true)
779  const { Box, Text, Markdown } = kit
780  // Only the terminal and the desktop draw a Client; another surface's table has the name but drops the element.
781  const Client = args.hasClient ? kit.Client : undefined
782  const { plans, plan, columns, message, detail, file, home, frame, isOpen, expanded, now } = args
783  const { onMenu, onPick, onCard, onBack, onFile, onLane, bodyRows } = args
784  const isProportional = isProportionalSurface(args.surface)
785  // vscode: proportional with no Client. Its buttons are quiet outlines, and its lanes sit side by side from a narrower pane, sized by share.
786  const isQuiet = isProportional && Client === undefined
787  const Button = quietButton(kit, isQuiet)
788  // A Client's props: the terminal's stay as they were.
789  const proportional = isProportional ? ({ isProportional: true } as const) : {}
790  // A proportional layout leaves a row between cards, which it has room for; the terminal's rows are dear.
791  const gapRows = isProportional ? 1 : 0
792  const isSideBySide = columns >= (isQuiet ? QUIET_SIDE_BY_SIDE_FROM : SIDE_BY_SIDE_FROM)
793  const laneCount = lanesOf(plan, expanded).length
794  const width = isSideBySide ? laneWidth(columns, laneCount) : columns
795  // The width a lane is drawn at: vscode's lanes share the row (24% each of four, 19% each of five with the Other lane), whatever its column count says.
796  const laneBoxWidth = isQuiet && isSideBySide ? `${Math.floor(96 / laneCount)}%` : width
797  // vscode's card is left to fill its lane: a width of 100% is the inside, and its border and padding would run into the gap.
798  const cardBoxWidth = isQuiet && isSideBySide ? undefined : width
799
800  const { color: dotColor, ...dotDim } = STYLE[worstStatus(plan)]
801  const hasChoice = plans.length > 1
802  const state = planStateOf(plan)
803  // The state text (`Idle since 19:40`) is drawn in the bare state's color; its width is what the header gives it.
804  const stateText = planStateText(plan, now)
805  const stats = planStatsOf(plan, columns)
806  const notStarted = notStartedText(plan)
807  // The state text and n/m are never cut: the name is shortened to leave them room. Beside "Plan file ›" the name has the old
808  // budget (two gaps and the ▾ besides the three; at least MIN_HEAD_NAME columns, else it would be cut to nothing). A name that
809  // does not fit beside it moves "Plan file ›" to a row of its own, and the first row gives the name what the other three leave.
810  // vscode's columns hold about two characters each: its header is fitted to the characters it fits.
811  const headColumns = isQuiet ? vscodeChars(columns) : columns
812  const countWidth = displayWidth(countText(plan))
813  const beside = headColumns - 20 - countWidth - 2 - displayWidth(stateText)
814  const isFileBelow = beside < Math.min(MIN_HEAD_NAME, displayWidth(plan.name))
815  const headName = truncate(plan.name, isFileBelow ? Math.max(2, headColumns - 6 - countWidth - displayWidth(stateText) - (hasChoice ? 2 : 0) - 1) : beside)
816
817  // vscode drops a Text's trailing spaces and draws a Button's label alone: the gaps are margins, the name's Button its label only, and the
818  // state and the count never shrink (else "In / progress"). The other surfaces draw the spaces as before.
819  const headRow = isQuiet ? (
820    <Box key={isFileBelow ? 'menu:row' : 'menu'} flexDirection="row">
821      <Box key="menu:dot" marginRight={1} flexShrink={0}>
822        <Text color={dotColor} {...dotDim}>●</Text>
823      </Box>
824      {hasChoice ? <Button plain key="menu:name" label={headName} onPress={onMenu} /> : <Text bold wrap="truncate">{headName}</Text>}
825      <Box key="menu:state" marginLeft={2} flexShrink={0}>
826        <Text color={STATE_STYLE[state].color}>{stateText}</Text>
827      </Box>
828      <Box key="menu:count" marginLeft={2} flexShrink={0}>
829        <Text color="suggestion">{countText(plan)}</Text>
830      </Box>
831      {hasChoice ? (
832        // vscode drops the label's leading space: a margin keeps the button off the count.
833        <Box key="menu:arrow:box" marginLeft={1} flexShrink={0}>
834          <Button plain key="menu:arrow" label={isOpen ? '▴' : '▾'} onPress={onMenu} />
835        </Box>
836      ) : null}
837      {isFileBelow ? null : <Box flexGrow={1} minWidth={2} />}
838      {isFileBelow ? null : <Button plain key="plan-file" label={FILE_LABEL} onPress={onFile} />}
839    </Box>
840  ) : (
841    <Box key={isFileBelow ? 'menu:row' : 'menu'} flexDirection="row">
842      <Text color={dotColor} {...dotDim}>
843        ●{' '}
844      </Text>
845      {hasChoice ? (
846        <Button plain key="menu:name" label={headName} onPress={onMenu}>
847          <Text bold>{headName}</Text>
848        </Button>
849      ) : (
850        <Text bold>{headName}</Text>
851      )}
852      <Text>{'  '}</Text>
853      <Text color={STATE_STYLE[state].color}>{stateText}</Text>
854      <Text>{'  '}</Text>
855      <Text color="suggestion">{countText(plan)}</Text>
856      {hasChoice ? <Button plain key="menu:arrow" label={isOpen ? ' ▴' : ' ▾'} onPress={onMenu} /> : null}
857      {isFileBelow ? null : <Box flexGrow={1} minWidth={2} />}
858      {isFileBelow ? null : <Button plain key="plan-file" label={FILE_LABEL} onPress={onFile} />}
859    </Box>
860  )
861
862  const header = isFileBelow ? (
863    <Box key="menu" flexDirection="column">
864      {headRow}
865      <Box flexDirection="row">
866        <Box flexGrow={1} />
867        <Button plain key="plan-file" label={FILE_LABEL} onPress={onFile} />
868      </Box>
869    </Box>
870  ) : (
871    headRow
872  )
873
874  // A card is its own bordered Box (the border takes 2 columns): every line of it is a Button, so a press anywhere opens
875  // its page. An In Progress card has the mascot beside its two lines; a Blocked card is red all through (border, text,
876  // tag) with the mascot frozen on one pose; the tag is right-aligned on the last line.
877  // Only the Buttons are pressable, and a Button inverts under the pointer, so the mascot is plain Text beside the Button of
878  // its row and never sits under that bar. The card shows its task name whole, wrapped; there is no hover box.
879  const card = ({ row, index }: Card) => {
880    const view = cardView(row, width, now)
881    const isDoing = isRunning(row)
882    const isStuck = isBlocked(row)
883    const { color } = STYLE[row.status]
884    const press = () => onCard(index)
885    const art = isStuck || isStalled(row) ? MASCOT[0] : mascotAt(frame)
886    // A proportional font draws block glyphs at its own shapes: the desktop draws the mascot as a picture beside the card's region.
887    const Svg = isProportional ? kit.Svg : undefined
888    const useSprite = Svg !== undefined && view.mascot && (Client !== undefined || isQuiet)
889    const markerColor = isStuck ? 'error' : NEEDS_YOU_COLOR
890
891    const parsed: CardRow[] = view.lines.map((line, at) => {
892      const isBar = at === view.barAt
893      const marker = !isBar && at === 0 && view.marker !== '' && line.startsWith(view.marker) ? view.marker : ''
894
895      return {
896        art: view.mascot && !useSprite ? `${art[at] ?? ' '.repeat(MASCOT_COLUMNS)} ` : '',
897        artColor: isStuck ? 'error' : 'claude',
898        marker,
899        markerColor,
900        name: isBar ? ` ${view.bar?.count ?? ''}` : line.slice(marker.length),
901        isRed: isStuck,
902        isBold: isDoing && !isBar,
903        ...(isBar && view.bar !== undefined ? { bar: isProportional ? deskBar(view.bar, color) : { filled: view.bar.filled, empty: view.bar.empty, color, track: TRACK_COLOR } } : {}),
904        ...tagFields(at === view.tagAt ? view.tag : '', view.pad),
905      }
906    })
907
908    const sprite =
909      useSprite && Svg !== undefined ? (
910        <Box width={CARD_SPRITE_CELLS} flexShrink={0}>
911          <Svg
912            source={(isDoing && !isStalled(row) ? spriteSvgAnimated(MASCOT, 'claude') : spriteSvg(art, isStuck ? 'error' : 'claude')).source}
913            alt="Claude Code's mascot"
914            width={CARD_SPRITE_PX.width}
915            height={CARD_SPRITE_PX.height}
916            {...(isDoing && !isStalled(row) ? { isInteractive: true } : {})}
917          />
918        </Box>
919      ) : null
920
921    // vscode (proportional, no Client): the task name as the desktop's card draws it (bold while running, red when blocked), the bar under
922    // it, and a last row with a quiet "Open ›" button (its key `card:<anchor>:N`) before the tag.
923    const linkBody = () => {
924      const barRow = parsed[view.barAt]
925      const tagRow = parsed[view.tagAt]
926      const chip =
927        tagRow === undefined || tagRow.tag === '' ? null : (
928          <Box key={`card:${index}:tag`} marginLeft={1} flexShrink={0}>
929            <Text color={tagRow.tagFg} backgroundColor={tagRow.tagBg} {...(tagRow.tagBold ? { bold: true } : {})}>{`${NBSP}${tagRow.tag}${NBSP}`}</Text>
930          </Box>
931        )
932
933      return (
934        <Box key={`card:${index}:body`} flexDirection="column" flexGrow={1} flexShrink={1} minWidth={0}>
935          <Text wrap="wrap">
936            {view.marker === '' ? null : <Text bold color={markerColor}>{view.marker}</Text>}
937            <Text {...(isStuck ? { color: 'error' } : {})} {...(isDoing ? { bold: true } : {})}>{row.task}</Text>
938          </Text>
939          {barRow?.bar === undefined ? null : (
940            <Box flexDirection="row">
941              {barRow.bar.filled === 0 ? null : <Box width={barRow.bar.filled} height={1} flexShrink={0} backgroundColor={barRow.bar.color} />}
942              {barRow.bar.empty === 0 ? null : <Box width={barRow.bar.empty} height={1} flexShrink={0} backgroundColor={barRow.bar.track} />}
943              <Text>{barRow.name}</Text>
944            </Box>
945          )}
946          <Box flexDirection="row">
947            <Box flexGrow={1} />
948            <Button plain key={`card:${plan.anchor}:${index}`} label={CARD_OPEN_LABEL} onPress={press} />
949            {chip}
950          </Box>
951        </Box>
952      )
953    }
954
955    // With a Client the rows are drawn by `card.tsx` in one region that posts a click and inverts under no pointer.
956    const lineRows = Client
957      ? [
958          sprite !== null ? (
959            <Box key={`card:${index}:sprite`} flexDirection="row" alignItems="center">
960              {sprite}
961              <Client
962                key={`card:${index}`}
963                module="./card.tsx"
964                width={Math.max(1, width - BORDER_COLUMNS - CARD_SPRITE_CELLS)}
965                height={parsed.length}
966                props={{ index, rows: parsed, ...proportional }}
967              />
968            </Box>
969          ) : (
970            <Client
971              key={`card:${index}`}
972              module="./card.tsx"
973              width={Math.max(1, width - BORDER_COLUMNS)}
974              height={parsed.length}
975              props={{ index, rows: parsed, ...proportional }}
976            />
977          ),
978        ]
979      : isQuiet
980        ? [
981            sprite !== null ? (
982              <Box key={`card:${index}:sprite`} flexDirection="row" alignItems="center">
983                {sprite}
984                {linkBody()}
985              </Box>
986            ) : (
987              linkBody()
988            ),
989          ]
990        : parsed.map((one, at) => {
991          const key = at === 0 ? `card:${index}` : `card:${index}:${at}`
992          const picture = view.mascot ? <Text color={one.artColor}>{one.art}</Text> : null
993          const button =
994            view.lines[at] === '' && one.tag === '' ? null : (
995              <Button plain key={key} label={`${view.lines[at] ?? ''}${one.tag === '' ? '' : ` ${one.tag} `}`} onPress={press}>
996                {one.marker === '' ? null : (
997                  <Text bold color={one.markerColor}>
998                    {one.marker}
999                  </Text>
1000                )}
1001                {one.bar === undefined ? null : (
1002                  <Text color={one.bar.color}>{'▰'.repeat(one.bar.filled)}</Text>
1003                )}
1004                {one.bar === undefined ? null : <Text dimColor>{'▱'.repeat(one.bar.empty)}</Text>}
1005                <Text {...(isStuck ? { color: 'error' } : {})} {...(isDoing && one.bar === undefined ? { bold: true } : {})}>
1006                  {one.name}
1007                </Text>
1008                {one.tag === '' ? null : (
1009                  <Text>
1010                    {' '.repeat(one.tagPad)}
1011                    <Text color={one.tagFg} backgroundColor={one.tagBg} {...(one.tagBold ? { bold: true } : {})}>{` ${one.tag} `}</Text>
1012                  </Text>
1013                )}
1014              </Button>
1015            )
1016
1017          return view.mascot ? (
1018            <Box key={`card:${index}:row${at}`} flexDirection="row">
1019              {picture}
1020              {button}
1021            </Box>
1022          ) : (
1023            button
1024          )
1025        })
1026
1027    return (
1028      <Box
1029        key={`cardbox:${index}`}
1030        {...(isProportional ? { hover: { borderStyle: 'bold', borderDimColor: false } } : {})}
1031        width={cardBoxWidth}
1032        flexDirection="column"
1033        borderStyle="round"
1034        // vscode writes the border as one `border: 1px solid var(--app-warning-foreground)`, a variable Cursor sets from
1035        // `--vscode-menu-foreground`; where that is undefined the whole border is dropped. The Verify card's outline is a hex there.
1036        borderColor={isQuiet && color === 'warning' ? (HEX.warning ?? color) : color}
1037        borderDimColor={!isDoing && !isStuck}
1038        paddingX={1}
1039      >
1040        {lineRows}
1041      </Box>
1042    )
1043  }
1044
1045  // The header row of an expanded lane has "Show less ▴" at its right end; a Button draws its own `[ ]`, two columns more.
1046  const lessLabel = moreButton(SHOW_LESS)
1047  const lessColumns = displayWidth(lessLabel) + 4
1048  // vscode sizes a lane by share, not by the cells this counts: its overflow Button is always the short form, whole.
1049  const laneLabel = (one: Lane) => (isQuiet ? (one.moreLabel === SHOW_LESS ? lessLabel : `+${one.more} more ▾`) : overflowLabel(one, width))
1050  // A lane header is cut to the characters its lane fits: on vscode about two to a column ("In Progress 2 · 1 blocked", not "In Progress 2 …").
1051  const headerRoom = (cols: number) => (isQuiet ? vscodeChars(cols) : cols)
1052
1053  const lane = (one: Lane) => {
1054    const isOpen = one.moreLabel === SHOW_LESS
1055    const hasLess = isOpen && width >= lessColumns + 12
1056    // The header's button folds the lane; the one at the bottom is kept only when the lane is taller than the pane shows
1057    // (the header has then scrolled away), or when the pane does not say how many rows it shows.
1058    const laneRows = 1 + one.cards.reduce((all, { row }) => all + cardRows(row, width, now) + gapRows, 0) + (one.cards.length === 0 ? 1 : 0) + 1
1059    const hasBottom = one.moreLabel !== '' && !(hasLess && bodyRows !== undefined && laneRows <= bodyRows)
1060
1061    return (
1062      <Box key={`lane:${one.key}`} flexDirection="column" width={laneBoxWidth} {...(gapRows === 0 ? {} : { gap: gapRows })}>
1063        {hasLess ? (
1064          <Box flexDirection="row">
1065            <Text bold color={one.color} wrap="truncate">
1066              {truncate(one.header, headerRoom(width - lessColumns - 1))}
1067            </Text>
1068            <Box flexGrow={1} minWidth={1} />
1069            <Button key={`lane:${one.key}:less`} label={lessLabel} onPress={() => onLane(one.key)} />
1070          </Box>
1071        ) : (
1072          <Text bold color={one.color} wrap="truncate">
1073            {truncate(one.header, headerRoom(width))}
1074          </Text>
1075        )}
1076        {one.cards.length === 0 ? <Text dimColor>—</Text> : null}
1077        {one.cards.map(card)}
1078        {!hasBottom ? null : (
1079          <Button key={`lane:${one.key}:more`} label={laneLabel(one)} onPress={() => onLane(one.key)} />
1080        )}
1081      </Box>
1082    )
1083  }
1084
1085  const row = detail === null ? undefined : plan.rows[detail]
1086
1087  if (file !== null) {
1088    return (
1089      <Box flexDirection="column">
1090        {message === null ? null : <Text dimColor>{message}</Text>}
1091        <Box key="file" flexDirection="column">
1092          <Button key="back" label="‹ Back" onPress={onBack} />
1093          <Text dimColor wrap="truncate">
1094            {shortPath(plan.plan_file, columns)}
1095          </Text>
1096          {'error' in file ? (
1097            <Text color="error" wrap="wrap">
1098              {file.error}
1099            </Text>
1100          ) : (
1101            <Box marginTop={1}>
1102              <Markdown text={file.text} />
1103            </Box>
1104          )}
1105        </Box>
1106      </Box>
1107    )
1108  }
1109
1110  return (
1111    <Box flexDirection="column">
1112      {message === null ? null : <Text dimColor>{message}</Text>}
1113      {row === undefined ? (
1114        <Box key="strip" flexDirection="column">
1115          {header}
1116          {isOpen && hasChoice ? drawPlanList(kit, { plans, plan, columns, now, listKey: 'menu:list', pickKey: 'plan:', onPick, isQuiet }) : null}
1117          {stats.length > 0 ? (
1118            drawStats(kit, { stats, isProportional, boxKey: 'plan-stats' })
1119          ) : notStarted === '' ? null : (
1120            <Box key="plan-stats">
1121              <Text dimColor wrap="truncate">
1122                {notStarted}
1123              </Text>
1124            </Box>
1125          )}
1126          {stats.length > 0 && planOwnText(plan.usage_totals) !== '' ? (
1127            <Box key="plan-own">
1128              <Text dimColor wrap="truncate">
1129                {planOwnText(plan.usage_totals)}
1130              </Text>
1131            </Box>
1132          ) : null}
1133          {ledgerErrorText(args.ledgerErrors) === '' ? null : (
1134            <Box key="ledger-errors">
1135              <Text dimColor wrap="truncate">
1136                {ledgerErrorText(args.ledgerErrors)}
1137              </Text>
1138            </Box>
1139          )}
1140          {plan.recap === undefined ? null : (
1141            <Box key="recap" flexDirection="column" marginTop={1}>
1142              <Text dimColor wrap="truncate">
1143                {recapLabel(plan, now)}
1144              </Text>
1145              <Text wrap="wrap">{plan.recap}</Text>
1146            </Box>
1147          )}
1148          {/* A row of ─ is `columns` cells long, but a proportional font draws ─ wider than a cell and the Text is cut to "…": the desktop gets the Markdown rule, which the surface draws as wide as the pane. */}
1149          <Box key="divider" marginTop={1} {...(isProportional ? { flexDirection: 'column' as const, width: '100%' } : {})}>
1150            {isProportional ? (
1151              <Markdown text="---" dimColor />
1152            ) : (
1153              <Text dimColor wrap="truncate">
1154                {'─'.repeat(columns)}
1155              </Text>
1156            )}
1157          </Box>
1158        </Box>
1159      ) : null}
1160      {row === undefined ? (
1161        <Box key="kanban" flexDirection={isSideBySide ? 'row' : 'column'} gap={isSideBySide ? LANE_GAP : 1} marginTop={1}>
1162          {lanesOf(plan, expanded).map(lane)}
1163        </Box>
1164      ) : (
1165        drawDetail(kit, { row, columns, home, onBack, isProportional, isQuiet, now })
1166      )}
1167    </Box>
1168  )
1169}
1170
1171type DetailArgs = Pick<PaneArgs, 'columns' | 'home' | 'onBack' | 'now'> & { row: PlanRow; isProportional: boolean; /** vscode: margins for spaces, quiet Buttons, note paths as plain text (a `file://` Link is dead there). */ isQuiet: boolean }
1172
1173/** Columns of the table's label cell, at the most (the longest label is "Blocked because"). */
1174const LABEL_COLUMNS = 15
1175
1176/** The narrowest value cell the table keeps before the label cell shrinks. */
1177const MIN_VALUE_COLUMNS = 12
1178
1179/** A piece of a cell's line: text, its colour, and the file link it opens, if any. */
1180type Part = { text: string; color?: string; bold?: boolean; dim?: true; href?: string | null; /** Drawn as this chip: the text padded one space each side. */ chip?: Chip; /** Drawn as a solid bar of Boxes (the desktop). */ bar?: { fraction: number; color: string } }
1181
1182/** One row of the table: the label and its lines, each a list of parts. */
1183type TableRow = { key: string; label: string; isRed?: boolean; lines: Part[][] }
1184
1185/** Columns a desktop cell wraps at: none, since its Box wraps the text itself. */
1186const UNWRAPPED_COLUMNS = 100_000
1187
1188const widthOf = (parts: readonly Part[]) => parts.reduce((all, part) => all + displayWidth(part.text) + (part.chip === undefined ? 0 : 2), 0)
1189
1190/** A cell of words with the chips `you`, `Opus`, `Sonnet` and `Haiku` kept: `main session · Sonnet`. */
1191const chipParts = (words: string): Part[] =>
1192  words.split(' · ').flatMap((word, at): Part[] => [...(at === 0 ? [] : [{ text: ' · ' }]), CHIPS[word] === undefined ? { text: word } : { text: word, chip: CHIPS[word] }])
1193
1194/**
1195 * One task's page: the task behind a square in its status color; a row of stats (tokens and cost: bold values over dim labels), left out
1196 * for a row no request was counted to and for her own rows; then a bordered table of labelled
1197 * rows, each left out when the tracker records nothing for it: Goal, Status (in words and its color), Done by (the tier a chip
1198 * and the executor, or the you chip), Checked by (once the row is Done), Progress (a bar), Sessions (one line per session that worked on
1199 * the row: when, where, tokens, cost), "Latest note" (the reason, on a Blocked row; its date, then one bulleted point per line, its file
1200 * paths links).
hooks/ledger.ts 415 lines
1/**
2 * The pure part of the usage ledger: what one API request costs by the price table, whose work a request is, how the requests of one
3 * interval between two `session.measure` readings are scaled to the host's own cost, and the file the plugin writes. Nothing here
4 * touches `$`; `register.tsx` records, books and writes.
5 */
6import type { PlanEntry, UsageTokens } from '../types'
7import { localIso } from './board'
8
9// ---------------------------------------------------------------- the price table
10
11/**
12 * USD per million tokens: (input, output, cache read, cache write 5m). A 1-hour cache write costs twice the input price (`requestUsd`).
13 * Source: platform.claude.com/docs/en/about-claude/pricing.md, fetched 2026-10-11.
14 */
15export const PRICES: Record<string, readonly [number, number, number, number]> = {
16  'claude-fable-5': [10.0, 50.0, 1.0, 12.5],
17  'claude-fable-5-1': [10.0, 50.0, 0.25, 12.5],
18  'claude-opus-5-5': [4.0, 20.0, 0.2, 5.0],
19  'claude-opus-5': [5.0, 25.0, 0.5, 6.25],
20  'claude-sonnet-5-5': [2.0, 10.0, 0.1, 2.5],
21  'claude-sonnet-5': [2.0, 10.0, 0.2, 2.5],
22  'claude-haiku-4-5': [1.0, 5.0, 0.1, 1.25],
23  'claude-haiku-4-5-20251001': [1.0, 5.0, 0.1, 1.25],
24}
25
26/** Priced by prompt size (input + cache read + cache write): [threshold, prices up to it, prices above it]. */
27export const TIERED_PRICES: Record<string, readonly [number, readonly [number, number, number, number], readonly [number, number, number, number]]> = {
28  'claude-haiku-5-5': [100_000, [0.1, 0.5, 0.01, 0.125], [0.5, 2.5, 0.05, 0.625]],
29}
30
31/**
32 * How long the cache writes of a main-thread request live when the runtime's usage gives no `cache_creation` split, which it does not
33 * (the `usage-shape` line of the probe on 2026-10-18 lists only the four counts and the model). The transcripts of both probes of that day
34 * show the main thread writing only 1-hour entries (66,863 and 67,813 tokens) and its subagents only 5-minute ones (75,934 and 47,692), so
35 * a main-thread write is priced as 1-hour (twice the input price) and a subagent's as 5-minute (the table's cache-write price). A split in
36 * the usage, when a runtime gives one, wins over this.
37 */
38export const MAIN_THREAD_CACHE_WRITE: '1h' | '5m' = '1h'
39
40/** The model the API reported (`TurnUsage.model`) as the table spells it: a `[1m]` suffix (the 1M-context variant) is priced as the base id. */
41export const normModel = (model: string): string => model.replace(/\[1m\]$/, '')
42
43/**
44 * The API's four counts of one response (`ModelUsage`). `cache_creation` is the runtime's split of the written tokens by lifetime
45 * (`ephemeral_1h_input_tokens`, `ephemeral_5m_input_tokens`); the d.ts type does not list it, so it is read defensively.
46 */
47export type ApiUsage = { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number; cache_creation?: unknown }
48
49export const tokensOf = (usage: ApiUsage): UsageTokens => ({
50  in: usage.input_tokens,
51  cached: usage.cache_read_input_tokens,
52  cache_write: usage.cache_creation_input_tokens,
53  out: usage.output_tokens,
54})
55
56const isCount = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value) && value >= 0
57
58/**
59 * The written tokens the runtime's split says are 1-hour ones (`cache_creation.ephemeral_1h_input_tokens`, at most all of them; 0 when only
60 * the 5-minute count is given); undefined when the usage carries no split (neither count is a number of tokens). What is not 1-hour is
61 * priced as a 5-minute write.
62 */
63function splitHourWrites(usage: ApiUsage): number | undefined {
64  const split = usage.cache_creation as { ephemeral_1h_input_tokens?: unknown; ephemeral_5m_input_tokens?: unknown } | null | undefined
65
66  if (typeof split !== 'object' || split === null || (!isCount(split.ephemeral_1h_input_tokens) && !isCount(split.ephemeral_5m_input_tokens))) {
67    return undefined
68  }
69
70  return isCount(split.ephemeral_1h_input_tokens) ? Math.min(split.ephemeral_1h_input_tokens, usage.cache_creation_input_tokens) : 0
71}
72
73/**
74 * What one response costs by the table, in USD; null for a model the table lacks (its tokens are still counted). A 1-hour cache write
75 * costs twice the input price, a 5-minute write the table's cache-write price. The usage's split says which; with no split the loop
76 * decides: a main-thread request's writes are `MAIN_THREAD_CACHE_WRITE`, a subagent's are 5-minute.
77 */
78export function requestUsd(model: string, usage: ApiUsage, isMainThread = false): number | null {
79  const id = normModel(model)
80  const tier = TIERED_PRICES[id]
81  const prompt = usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
82  const prices = PRICES[id] ?? (tier === undefined ? undefined : prompt <= tier[0] ? tier[1] : tier[2])
83
84  if (prices === undefined) {
85    return null
86  }
87
88  const [input, output, read, write] = prices
89  const hour = splitHourWrites(usage) ?? (isMainThread && MAIN_THREAD_CACHE_WRITE === '1h' ? usage.cache_creation_input_tokens : 0)
90
91  return (usage.input_tokens * input + usage.output_tokens * output + usage.cache_read_input_tokens * read + (usage.cache_creation_input_tokens - hour) * write + hour * 2 * input) / 1_000_000
92}
93
94const KEY_DEPTH = 4
95const KEY_LIMIT = 100
96
97/** The key names of an object, a nested key as a dotted path (`cache_creation.ephemeral_1h_input_tokens`): no value is read, an array is one key, and it stops at a depth and a count. */
98export function keyPaths(value: unknown, prefix = '', depth = 1): string[] {
99  if (typeof value !== 'object' || value === null || Array.isArray(value)) {
100    return []
101  }
102
103  const paths: string[] = []
104
105  for (const [key, inner] of Object.entries(value)) {
106    const path = prefix === '' ? key : `${prefix}.${key}`
107
108    paths.push(path, ...(depth < KEY_DEPTH ? keyPaths(inner, path, depth + 1) : []))
109
110    if (paths.length >= KEY_LIMIT) {
111      break
112    }
113  }
114
115  return paths.slice(0, KEY_LIMIT)
116}
117
118// ---------------------------------------------------------------- whose work a request is
119
120/** The plan (its ledger key) and the row (its exact task text) a request is counted to; `row: null` is the plan's own share. */
121export type Owner = { plan: string; row: string | null }
122
123/**
124 * The owner of the main thread's requests, from the plans the board last answered: the plan's own share (`row: null`) when exactly one
125 * of this session's plans has a row In Progress, whoever does the row; else nobody (null). The main thread's work is never a row's: a
126 * row is counted only the work of a subagent that was briefed for it (`briefRow`) or was spawned by one that was.
127 */
128export function mainOwner(plans: readonly PlanEntry[]): Owner | null {
129  const running = plans.filter(plan => plan.in_session === true && plan.rows.some(row => row.status === 'In Progress'))
130
131  return running.length === 1 ? { plan: (running[0] as PlanEntry).anchor, row: null } : null
132}
133
134/** The row `task` of this session's plans (those of `anchor` when given) as an owner; null when no plan has it, or several do. */
135export function rowOwner(plans: readonly PlanEntry[], task: string, anchor?: string): Owner | null {
136  const hits = plans.filter(plan => plan.in_session === true && (anchor === undefined || plan.anchor === anchor)).filter(plan => plan.rows.some(row => row.task === task))
137
138  return hits.length === 1 ? { plan: (hits[0] as PlanEntry).anchor, row: task } : null
139}
140
141/** What the plugin knows of a subagent: the row it claimed (its brief's) and the agent that spawned it. */
142export type AgentClaims = { claims: Claim[]; parent?: string }
143
144/**
145 * Whose work a subagent's request is, against the plans the tracker has now: the row of its latest claim that a row of this session's
146 * plans matches; else its parent's owner; else the main thread's owner. Nothing is frozen when the agent is spawned: a brief can name a
147 * row made seconds before, which the board's last answer may not have yet. `wanted` is its latest claim that no row matched, for
148 * `settle` to look up again once an answer holds it.
149 */
150export function resolveAgent(agents: ReadonlyMap<string, AgentClaims>, plans: readonly PlanEntry[], agentId: string, depth = 0): { owner: Owner | null; wanted?: Claim } {
151  const known = agents.get(agentId)
152  const claims = known?.claims ?? []
153
154  for (const claim of [...claims].reverse()) {
155    const owner = rowOwner(plans, claim.task, claim.anchor)
156
157    if (owner !== null) {
158      return { owner }
159    }
160  }
161
162  const wanted = claims.at(-1)
163  const up = known?.parent !== undefined && known.parent !== agentId && depth < 8 ? resolveAgent(agents, plans, known.parent, depth + 1) : undefined
164  const missing = wanted ?? up?.wanted
165
166  return { owner: up === undefined ? mainOwner(plans) : up.owner, ...(missing === undefined ? {} : { wanted: missing }) }
167}
168
169/** `requests` with each one's `wanted` row looked up again in `plans`: a request whose row the tracker now has is the row's, no longer the fallback's. */
170export function settle(requests: readonly Request[], plans: readonly PlanEntry[]): Request[] {
171  return requests.map(one => {
172    const owner = one.wanted === undefined ? null : rowOwner(plans, one.wanted.task, one.wanted.anchor)
173
174    if (owner === null) {
175      return one
176    }
177
178    const { wanted: _found, ...rest } = one
179
180    return { ...rest, owner }
181  })
182}
183
184/** The row text of a brief's first line, `Tracker row: "<exact row text>"`; undefined for a brief that does not start with it. */
185export function briefRow(prompt: string): string | undefined {
186  const first = prompt.split('\n').find(line => line.trim() !== '')
187
188  return /^\s*Tracker row:\s*"(.+)"\s*$/.exec(first ?? '')?.[1]
189}
190
191// ---------------------------------------------------------------- the interval
192
193/** Scaling is kept only inside these bounds: a host change far from the table's own sum means the requests do not match the host's. */
194export const SCALE_MIN = 0.8
195export const SCALE_MAX = 1.25
196
197/**
198 * Whether a subagent's requests are in the host's `cost.usd` (and so scaled with the main thread's). The probe decides it; true until it does.
199 * False: only the main thread's requests are scaled, a subagent's keep the table price.
200 */
201export const SCALE_INCLUDES_SUBAGENTS = true
202
203/** A row a subagent was briefed for: its exact text, and its plan's key when one is named. */
204export type Claim = { task: string; anchor?: string }
205
206/**
207 * One API response as the plugin records it: whose it is, which loop made it, its counts and table price, and when (ms). `wanted` is the
208 * row a subagent claimed that the tracker's answer did not have yet when this was recorded: the owner is then the fallback, and the row
209 * once an answer holds it (`settle`).
210 */
211export type Request = { owner: Owner | null; agentId: string | undefined; wanted?: Claim; tokens: UsageTokens; usd: number | null; at: number }
212
213/** A request with the cost it is booked at. */
214export type Booked = Request & { cost: number }
215
216export type Interval = {
217  booked: Booked[]
218  /** The host's change over the table's sum of the requests in scope; null when it cannot be worked out. */
219  factor: number | null
220  isScaled: boolean
221  tableMain: number
222  tableSub: number
223  requestsMain: number
224  requestsSub: number
225}
226
227const priced = (requests: readonly Request[]) => requests.reduce((sum, one) => sum + (one.usd ?? 0), 0)
228
229/**
230 * The requests of one interval booked at a cost. `deltaUsd` is the host's `cost.usd` change over the interval (null when there is no
231 * baseline); the requests in scope sum to it when the factor is inside `SCALE_MIN`..`SCALE_MAX`. Not scaled (no baseline, the first
232 * interval after a load, no priced request, a factor outside the bounds): each keeps its table price. A request with no price books 0.
233 * What the host spent that no request covers is not worked out here: the file derives it (`ledgerText`).
234 */
235export function scaleInterval(requests: readonly Request[], deltaUsd: number | null, options: { includesSubagents: boolean; isFirst: boolean }): Interval {
236  const main = requests.filter(one => one.agentId === undefined)
237  const sub = requests.filter(one => one.agentId !== undefined)
238  const inScope = (one: Request) => options.includesSubagents || one.agentId === undefined
239  const tableMain = priced(main)
240  const tableSub = priced(sub)
241  const tableScope = options.includesSubagents ? tableMain + tableSub : tableMain
242  const factor = deltaUsd === null || tableScope <= 0 ? null : deltaUsd / tableScope
243  const isScaled = factor !== null && !options.isFirst && factor >= SCALE_MIN && factor <= SCALE_MAX
244
245  return {
246    booked: requests.map(one => ({ ...one, cost: one.usd === null ? 0 : isScaled && inScope(one) ? one.usd * (factor as number) : one.usd })),
247    factor,
248    isScaled,
249    tableMain,
250    tableSub,
251    requestsMain: main.length,
252    requestsSub: sub.length,
253  }
254}
255
256// ---------------------------------------------------------------- the file
257
258export type LedgerEntry = { plan: string; row: string | null; first: string; last: string; tokens: UsageTokens; cost_usd: number; requests: number }
259
260export type Unowned = { tokens: UsageTokens; cost_usd: number; requests: number }
261
262/** `~/.claude/mods-logs/plan-tracker-usage/<session id>.json`. */
263export type LedgerFile = {
264  version: 1
265  session: string
266  /** Where the session drew: `terminal`, `desktop`, `vscode`, `mobile`, or `unknown` until a surface is known. */
267  surface: string
268  updated: string
269  /** The host's `cost.usd` at the last interval's end; null until one was read. */
270  measured_usd: number | null
271  entries: LedgerEntry[]
272  unowned: Unowned
273}
274
275const zeroTokens = (): UsageTokens => ({ in: 0, cached: 0, cache_write: 0, out: 0 })
276
277const addTokens = (to: UsageTokens, from: UsageTokens): UsageTokens => ({ in: to.in + from.in, cached: to.cached + from.cached, cache_write: to.cache_write + from.cache_write, out: to.out + from.out })
278
279/** Where every session's ledger is kept: `~/.claude/mods-logs/plan-tracker-usage`, apart from the plan board's own `usage` folder so the two never read each other's files. */
280export const ledgerDir = (home: string): string => `${home.replace(/\/+$/, '')}/.claude/mods-logs/plan-tracker-usage`
281
282/**
283 * The files a session's ledger may be written to, in the order the plugin tries them: its own `<id>.json`, then others of the same session
284 * id that the plugin sums too (it takes the session from the file's `session`, not its name). A file that cannot be read is left as it
285 * is and the next name is tried, so what it holds is never overwritten.
286 */
287export const ledgerNames = (session: string): string[] => [`${session}.json`, `${session}.recovered.json`, ...[2, 3, 4, 5].map(n => `${session}.recovered-${n}.json`)]
288
289export const emptyLedger = (session: string, surface = 'unknown'): LedgerFile => ({
290  version: 1,
291  session,
292  surface,
293  updated: '',
294  measured_usd: null,
295  entries: [],
296  unowned: { tokens: zeroTokens(), cost_usd: 0, requests: 0 },
297})
298
299const isNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value)
300
301const tokensFrom = (value: unknown): UsageTokens | undefined => {
302  const raw = value as Record<string, unknown> | null
303
304  return typeof raw === 'object' && raw !== null && isNumber(raw.in) && isNumber(raw.cached) && isNumber(raw.cache_write) && isNumber(raw.out)
305    ? { in: raw.in, cached: raw.cached, cache_write: raw.cache_write, out: raw.out }
306    : undefined
307}
308
309/** A ledger file's text as a ledger of `session`, or undefined when it is not one (unparsable, another version, another session, a damaged entry). */
310export function parseLedger(text: string, session: string): LedgerFile | undefined {
311  let data: unknown
312
313  try {
314    data = JSON.parse(text)
315  } catch {
316    return undefined
317  }
318
319  const raw = data as Record<string, unknown> | null
320  const unowned = raw?.unowned as Record<string, unknown> | null | undefined
321  const unownedTokens = tokensFrom(unowned?.tokens)
322
323  if (typeof raw !== 'object' || raw === null || raw.version !== 1 || raw.session !== session || !Array.isArray(raw.entries) || unownedTokens === undefined || !isNumber(unowned?.cost_usd) || !isNumber(unowned?.requests)) {
324    return undefined
325  }
326
327  const entries: LedgerEntry[] = []
328
329  for (const one of raw.entries as (Record<string, unknown> | null)[]) {
330    const tokens = tokensFrom(one?.tokens)
331
332    if (
333      tokens === undefined || typeof one?.plan !== 'string' || (one.row !== null && typeof one.row !== 'string') ||
334      typeof one.first !== 'string' || typeof one.last !== 'string' || !isNumber(one.cost_usd) || !isNumber(one.requests)
335    ) {
336      return undefined
337    }
338
339    entries.push({ plan: one.plan, row: one.row, first: one.first, last: one.last, tokens, cost_usd: one.cost_usd, requests: one.requests })
340  }
341
342  return {
343    version: 1,
344    session,
345    surface: typeof raw.surface === 'string' && raw.surface !== '' ? raw.surface : 'unknown',
346    updated: typeof raw.updated === 'string' ? raw.updated : '',
347    measured_usd: isNumber(raw.measured_usd) ? raw.measured_usd : null,
348    entries,
349    unowned: { tokens: unownedTokens, cost_usd: unowned.cost_usd as number, requests: unowned.requests as number },
350  }
351}
352
353const earlier = (a: string, b: string) => (Date.parse(b) < Date.parse(a) ? b : a)
354const later = (a: string, b: string) => (Date.parse(b) > Date.parse(a) ? b : a)
355
356/** `ledger` with `booked` added: each request to the entry of its row (or plan), a request with no owner to `unowned`. */
357export function bookInto(ledger: LedgerFile, booked: readonly Booked[]): LedgerFile {
358  const entries = ledger.entries.map(one => ({ ...one }))
359  let unowned = { ...ledger.unowned }
360
361  for (const one of booked) {
362    if (one.owner === null) {
363      unowned = { tokens: addTokens(unowned.tokens, one.tokens), cost_usd: unowned.cost_usd + one.cost, requests: unowned.requests + 1 }
364
365      continue
366    }
367
368    const { plan, row } = one.owner
369    const time = localIso(one.at)
370    const held = entries.find(entry => entry.plan === plan && entry.row === row)
371
372    if (held === undefined) {
373      entries.push({ plan, row, first: time, last: time, tokens: { ...one.tokens }, cost_usd: one.cost, requests: 1 })
374    } else {
375      held.first = earlier(held.first, time)
376      held.last = later(held.last, time)
377      held.tokens = addTokens(held.tokens, one.tokens)
378      held.cost_usd += one.cost
379      held.requests += 1
380    }
381  }
382
383  return { ...ledger, entries, unowned }
384}
385
386/** Whether the ledger, with the requests of the open interval, has an entry: one booked, or an open request that someone owns. A request nobody owns is not an entry. */
387export const hasEntries = (ledger: LedgerFile, open: readonly Request[]): boolean => ledger.entries.length > 0 || open.some(one => one.owner !== null)
388
389const roundUsd = (usd: number) => Math.round(usd * 1e6) / 1e6
390
391/**
392 * The ledger as the file holds it: `ledger` plus the requests of the interval still open at their table price (they are scaled when the
393 * interval closes), its cost rounded to a millionth of a dollar. Pretty-printed JSON.
394 *
395 * Entries and unowned never add up to more than the host measured. With a measurement (`measured_usd`), the cost nobody owns is what the
396 * host measured less the entries' (negative when the entries are over it), whatever the requests nobody owns cost by the table: a request the
397 * measurement already counted adds nothing on top. Without one (the host keeps no cost), it is the table price of those requests.
398 */
399export function ledgerText(ledger: LedgerFile, open: readonly Request[], updated: string): string {
400  const whole = bookInto(ledger, open.map(one => ({ ...one, cost: one.usd ?? 0 })))
401  const unownedCost = whole.measured_usd === null ? whole.unowned.cost_usd : whole.measured_usd - whole.entries.reduce((sum, one) => sum + one.cost_usd, 0)
402
403  return `${JSON.stringify(
404    {
405      ...whole,
406      updated,
407      measured_usd: whole.measured_usd === null ? null : roundUsd(whole.measured_usd),
408      entries: whole.entries.map(one => ({ ...one, cost_usd: roundUsd(one.cost_usd) })),
409      unowned: { ...whole.unowned, cost_usd: roundUsd(unownedCost) },
410    },
411    null,
412    2,
413  )}\n`
414}
415
hooks/usage.ts 176 lines
1/**
2 * What the plugin shows of the usage: every session's ledger file (`register.tsx` writes one per session) read from the ledger folder and
3 * summed per plan and row. A file is read again only when its size or modification time changed. A file that does not parse is read once
4 * more after 200 ms (a read can land mid-write); one that still fails is listed in `ledger_errors` and read again only when it changes.
5 */
6import type { EngineInterface } from 'claude-code'
7
8import type { PlanBoard, PlanEntry, PlanRow, RowUsage, SessionUsage, UsageTokens } from '../types'
9import { settings } from './board'
10import { ledgerDir, parseLedger } from './ledger'
11import type { LedgerFile } from './ledger'
12
13/**
14 * The key a plan is counted under in the ledgers. A plain PROGRESS.md names its one plan `progress` in every project, so its key is the
15 * file's absolute path; a board command's plan is the project root and its anchor, so two projects whose commands return the same anchor
16 * never mix.
17 */
18export const planKey = (plan: PlanEntry): string => (settings.boardCommand === '' ? plan.plan_file : `${settings.root}#${plan.anchor}`)
19
20/** How long a file that does not parse waits before its second read. */
21export const LEDGER_RETRY_MS = 200
22
23/** The ledgers read, and the ids of the sessions whose file could not be read. */
24export type Ledgers = { files: readonly LedgerFile[]; errors: readonly string[] }
25
26/** A file as it was last read: its size and modification time then, and its ledger, undefined when it would not parse. */
27type Held = { size: number; mtimeMs: number; ledger: LedgerFile | undefined }
28
29const held = new Map<string, Held>()
30
31/** The ledger in `path`, or undefined when it cannot be read or is no ledger. A file is the ledger of the session it names (`session`), else of its own name. */
32async function readOne($: EngineInterface, path: string, stem: string): Promise<LedgerFile | undefined> {
33  try {
34    const text = await $.fs.read(path)
35    const named = (JSON.parse(text) as { session?: unknown } | null)?.session
36
37    return parseLedger(text, typeof named === 'string' && named !== '' ? named : stem)
38  } catch {
39    return undefined
40  }
41}
42
43/** Reads every `*.json` of the ledger folder, those that changed since the last call only; the rest is kept in memory. A missing folder is no ledgers. */
44export async function readLedgers($: EngineInterface): Promise<Ledgers> {
45  const home = await $.env.get('HOME')
46  const dir = home === undefined || home === '' ? undefined : ledgerDir(home)
47  const listed = dir === undefined ? [] : await $.fs.list(dir).catch(() => [])
48  const files = listed.filter(one => one.kind === 'file' && one.name.endsWith('.json')).sort((a, b) => (a.name < b.name ? -1 : 1))
49  const pathOf = (name: string) => `${dir}/${name}`
50  const stemOf = (name: string) => name.slice(0, -'.json'.length)
51
52  for (const path of [...held.keys()]) {
53    if (!files.some(one => pathOf(one.name) === path)) {
54      held.delete(path)
55    }
56  }
57
58  // The size and time are those of the listing, taken before the read: a file rewritten meanwhile no longer matches them.
59  const changed = files.filter(one => {
60    const was = held.get(pathOf(one.name))
61
62    return was === undefined || was.size !== one.size || was.mtimeMs !== one.mtimeMs
63  })
64  const first = await Promise.all(changed.map(one => readOne($, pathOf(one.name), stemOf(one.name))))
65  const failed = changed.filter((_, at) => first[at] === undefined)
66  const again = new Map<string, LedgerFile | undefined>()
67
68  if (failed.length > 0) {
69    await $.clock.sleep(LEDGER_RETRY_MS)
70
71    for (const one of failed) {
72      again.set(one.name, await readOne($, pathOf(one.name), stemOf(one.name)))
73    }
74  }
75
76  changed.forEach((one, at) => held.set(pathOf(one.name), { size: one.size, mtimeMs: one.mtimeMs, ledger: first[at] ?? again.get(one.name) }))
77
78  const read = files.map(one => ({ name: one.name, ledger: held.get(pathOf(one.name))?.ledger }))
79
80  return {
81    files: read.flatMap(one => (one.ledger === undefined ? [] : [one.ledger])),
82    errors: read.flatMap(one => (one.ledger === undefined ? [stemOf(one.name)] : [])),
83  }
84}
85
86// ---------------------------------------------------------------- summing
87
88/** One session's sums for one plan and row: the earliest first and the latest last time, and the counts. */
89type Acc = { surface: string; first: string; last: string; tokens: UsageTokens; cost: number; requests: number }
90
91/** The sums by plan key and row text (null for the plan's own share), then by session id. */
92type Sums = Map<string, Map<string, Acc>>
93
94const slot = (key: string, row: string | null): string => JSON.stringify([key, row])
95
96const time = (iso: string): number => {
97  const ms = Date.parse(iso)
98
99  return Number.isNaN(ms) ? 0 : ms
100}
101
102function sumsOf(ledgers: readonly LedgerFile[]): Sums {
103  const sums: Sums = new Map()
104
105  for (const one of ledgers) {
106    for (const entry of one.entries) {
107      const bySession = sums.get(slot(entry.plan, entry.row)) ?? new Map<string, Acc>()
108      const acc = bySession.get(one.session) ?? { surface: one.surface, first: entry.first, last: entry.last, tokens: { in: 0, cached: 0, cache_write: 0, out: 0 }, cost: 0, requests: 0 }
109
110      if (time(entry.first) < time(acc.first)) {
111        acc.first = entry.first
112      }
113
114      if (time(entry.last) > time(acc.last)) {
115        acc.last = entry.last
116      }
117
118      acc.tokens = { in: acc.tokens.in + entry.tokens.in, cached: acc.tokens.cached + entry.tokens.cached, cache_write: acc.tokens.cache_write + entry.tokens.cache_write, out: acc.tokens.out + entry.tokens.out }
119      acc.cost += entry.cost_usd
120      acc.requests += entry.requests
121      bySession.set(one.session, acc)
122      sums.set(slot(entry.plan, entry.row), bySession)
123    }
124  }
125
126  return sums
127}
128
129const round = (usd: number): number => Math.round(usd * 1e6) / 1e6
130
131function usageOf(accs: readonly Acc[]): RowUsage {
132  return {
133    tokens_in: accs.reduce((sum, one) => sum + one.tokens.in, 0),
134    tokens_cached: accs.reduce((sum, one) => sum + one.tokens.cached, 0),
135    tokens_cache_write: accs.reduce((sum, one) => sum + one.tokens.cache_write, 0),
136    tokens_out: accs.reduce((sum, one) => sum + one.tokens.out, 0),
137    cost_usd: round(accs.reduce((sum, one) => sum + one.cost, 0)),
138    requests: accs.reduce((sum, one) => sum + one.requests, 0),
139  }
140}
141
142/** The row's sessions, by the time each first worked on it. */
143function sessionsOf(bySession: ReadonlyMap<string, Acc>): SessionUsage[] {
144  return [...bySession.entries()]
145    .sort(([a, one], [b, two]) => time(one.first) - time(two.first) || (a < b ? -1 : 1))
146    .map(([session, acc]) => ({ session, surface: acc.surface, first: acc.first, last: acc.last, tokens: acc.tokens, cost_usd: round(acc.cost) }))
147}
148
149/**
150 * `board` with the usage the ledgers hold: each row some entry names gets `usage` and `sessions_usage`; each plan `usage_totals` (its rows'
151 * and its own share, which is also given alone as `plan_own`; zeros when nothing was counted); the board `ledger_errors` when a file could
152 * not be read. `keyOf` gives the key a plan is counted under (its ledger entries' `plan`).
153 */
154export function withUsage(board: PlanBoard, ledgers: Ledgers, keyOf: (plan: PlanEntry) => string): PlanBoard {
155  const sums = sumsOf(ledgers.files)
156  const accsOf = (key: string, row: string | null): Acc[] => [...(sums.get(slot(key, row))?.values() ?? [])]
157
158  const plans = board.plans.map((plan): PlanEntry => {
159    const key = keyOf(plan)
160    const own = accsOf(key, null)
161    const ofRows = [...new Set(plan.rows.map(one => one.task))].flatMap(task => accsOf(key, task))
162
163    return {
164      ...plan,
165      usage_totals: { ...usageOf([...ofRows, ...own]), plan_own: usageOf(own) },
166      rows: plan.rows.map((one): PlanRow => {
167        const bySession = sums.get(slot(key, one.task))
168
169        return bySession === undefined || bySession.size === 0 ? one : { ...one, usage: usageOf([...bySession.values()]), sessions_usage: sessionsOf(bySession) }
170      }),
171    }
172  })
173
174  return { ...board, plans, ...(ledgers.errors.length === 0 ? {} : { ledger_errors: [...ledgers.errors] }) }
175}
176
hooks/card.tsx 127 lines
1/**
2 * The surface module of a card: the card's text rows, drawn in a Client region. A Button inverts under the pointer; a
3 * Client does not, so the card is clickable (a left button down and up inside the region posts `{ open }` to the
4 * plugin) without a bar over its rows or its mascot. A click also gives the region the keyboard, and Enter posts the same.
5 */
6import type { ClientModule } from 'claude-code'
7
8/** One text row of a card, as plain data. */
9export type CardRow = {
10  /** The mascot's row of block characters and its space, or ''. */
11  art: string
12  artColor: string
13  /** The marker (`⚑ Blocked · `, `◆ needs you · `) and its colour. */
14  marker: string
15  markerColor: string
16  name: string
17  isRed: boolean
18  isBold: boolean
19  /** The progress bar that starts the row (`name` is then its count), or undefined: filled cells in `color`, the empty ones dim. */
20  bar?: { filled: number; empty: number; color: string; track: string }
21  /** The word of the tag's chip, or ''; `tagPad` spaces go before it (the terminal aligns it right; a proportional font does it with a Box). */
22  tag: string
23  tagPad: number
24  tagBg: string
25  tagFg: string
26  tagBold: boolean
27}
28
29/**
30 * `isProportional` is a surface with a proportional font (the desktop app): the tag cannot be aligned with spaces there, so a row is
31 * the name in a Box that grows, then the tag.
32 */
33export type CardProps = { index: number; rows: CardRow[]; isProportional?: boolean }
34
35/** The local state: whether the left button went down in the card and has not come up yet. */
36type State = { isDown: boolean }
37
38const Card: ClientModule<CardProps, State> = (props, surface) => {
39  const { Box, Text } = surface.elements
40  const open = () => surface.post({ open: props.index })
41  const colour = (row: CardRow) => (row.isRed ? { color: 'error' } : {})
42
43  surface.onPointer(event => {
44    if (event.type === 'down' && event.button === 'left') {
45      surface.setState({ isDown: true })
46    }
47
48    if (event.type === 'up') {
49      const wasDown = surface.state?.isDown === true
50      // A click is the left button coming up in the card where it went down: letting go outside cancels it. A region
51      // not yet laid out reports 0 cells, and then nothing is outside.
52      const isInside = surface.columns === 0 || surface.rows === 0 || (event.x >= 0 && event.y >= 0 && event.x < surface.columns && event.y < surface.rows)
53
54      surface.setState({ isDown: false })
55
56      if (wasDown && event.button === 'left' && isInside) {
57        open()
58      }
59    }
60  })
61  surface.onKey(event => {
62    if (event.key === 'return') {
63      open()
64    }
65  })
66
67  const chip = (row: CardRow) => (
68    <Text color={row.tagFg} backgroundColor={row.tagBg} {...(row.tagBold ? { bold: true } : {})}>{` ${row.tag} `}</Text>
69  )
70
71  const name = (row: CardRow) =>
72    row.bar === undefined
73      ? row.name
74      : [
75          <Text color={row.bar.color}>{'▰'.repeat(row.bar.filled)}</Text>,
76          <Text dimColor>{'▱'.repeat(row.bar.empty)}</Text>,
77          row.name,
78        ]
79
80  return (
81    <Box flexDirection="column">
82      {props.rows.map(row => (
83        <Box flexDirection="row">
84          {row.art === '' ? null : <Text color={row.artColor}>{row.art}</Text>}
85          {row.marker === '' ? null : (
86            <Text bold color={row.markerColor}>
87              {row.marker}
88            </Text>
89          )}
90          {props.isProportional === true ? (
91            <Box flexGrow={1} flexDirection="row">
92              {
93                // The glyphs of a bar draw as slanted dashes in a proportional font: a solid bar of two Boxes instead.
94                row.bar === undefined ? null : (
95                  <Box flexShrink={0} flexDirection="row">
96                    {row.bar.filled === 0 ? null : <Box width={row.bar.filled} height={1} backgroundColor={row.bar.color} />}
97                    {row.bar.empty === 0 ? null : <Box width={row.bar.empty} height={1} backgroundColor={row.bar.track} />}
98                  </Box>
99                )
100              }
101              <Text {...colour(row)} {...(row.isBold ? { bold: true } : {})}>
102                {row.name}
103              </Text>
104            </Box>
105          ) : (
106            <Text {...colour(row)} {...(row.isBold ? { bold: true } : {})}>
107              {name(row)}
108            </Text>
109          )}
110          {row.tag === '' ? null : props.isProportional === true ? (
111            <Box marginLeft={1} flexShrink={0}>
112              {chip(row)}
113            </Box>
114          ) : (
115            <Text>
116              {' '.repeat(row.tagPad)}
117              {chip(row)}
118            </Text>
119          )}
120        </Box>
121      ))}
122    </Box>
123  )
124}
125
126export default Card
127
hooks/band.tsx 33 lines
1/**
2 * The desktop band's pressable overlay: an empty region laid over a part of the band that no Button can hold (the mascot and
3 * the bar are pictures). A left button down and up inside it posts `{ band: 'toggle' }` to the plugin, which toggles the
4 * board, as a press on the band does on the terminal. The posts reach the plugin by the instance, not by a button handle.
5 */
6import type { ClientModule } from 'claude-code'
7
8type State = { isDown: boolean }
9
10const BandZone: ClientModule<Record<string, never>, State> = (_props, surface) => {
11  const { Box } = surface.elements
12
13  surface.onPointer(event => {
14    if (event.type === 'down' && event.button === 'left') {
15      surface.setState({ isDown: true })
16    }
17
18    if (event.type === 'up') {
19      const wasDown = surface.state?.isDown === true
20
21      surface.setState({ isDown: false })
22
23      if (wasDown && event.button === 'left') {
24        surface.post({ band: 'toggle' })
25      }
26    }
27  })
28
29  return <Box />
30}
31
32export default BandZone
33
types/index.d.ts 208 lines
1/**
2 * The statuses a row can have, spelled as the tracker writes them (Blocked is a status here, not a flag), and `Other` for a
3 * status the PROGRESS.md reader does not know (its own text is in `statusText`).
4 */
5export type PlanStatus = 'Todo' | 'In Progress' | 'Verifying' | 'Needs Verification' | 'Blocked' | 'Done' | 'Canceled' | 'Other'
6
7/**
8 * One task of a plan, with only what the tracker records: `route` is `<split> × <executor> · <tier> — <why>` (absent when
9 * unrouted), `note` the row's latest free text (the reason, on a Blocked row), `updated` when it was last written.
10 * Absent fields are the tracker's null, dropped when the `--json` output is read.
11 */
12export type PlanRow = {
13  task: string
14  status: PlanStatus
15  /** The status as written in the board file, kept for a row whose status is `Other`. */
16  statusText?: string
17  note?: string
18  /** When the row was last written, ISO text; each lane lists the latest first. Null for none (a `PROGRESS.md` has none): a lane with no times keeps file order. */
19  updated: string | null
20  route?: string
21  /** The route's `<split> × <executor> · <tier>` or `unrouted`, as the tracker's `--json` gives it; used when there is no `route`. */
22  who?: string
23  /** Who checks the work, from the board file's `check` column (`script (grep)`, `you`, `subagent · Opus`); absent when the file has none. */
24  check?: string
25  /** One sentence on what the task is for; absent when not given. */
26  goal?: string
27  /** `n/m` steps done of total, as the agent reported it; absent until it has. */
28  progress?: string
29  /** When the row first went In Progress, and when it was finished (Done or Canceled); ISO text. Absent on rows written before these fields. */
30  started?: string
31  finished?: string
32  /**
33   * When the row last had a session working on it, ISO text: given by a board command for an In Progress or Verifying row that no session is working
34   * on. The card then shows a grey `stalled` tag with the time (`stalled 14:02`, or the day, `stalled Oct 11`, when it was not today) and its mascot
35   * stops, and the task page says `stalled since 14:02` (`stalled since Oct 11 14:02`). A `PROGRESS.md` never has it.
36   */
37  stalled_since?: string
38  /** What the API requests counted to this row cost, summed by the plugin from every session's usage ledger (`hooks/usage.ts`); absent for a row no ledger entry names. */
39  usage?: RowUsage
40  /** The same, one entry per session that worked on the row; absent with `usage`. */
41  sessions_usage?: SessionUsage[]
42}
43
44/** The four token counts of the usage ledger: uncached input, cache reads, cache writes, output. */
45export type UsageTokens = { in: number; cached: number; cache_write: number; out: number }
46
47/** What the API requests counted to a row or to a plan cost, as the plugin sums them over every session's ledger. */
48export type RowUsage = {
49  tokens_in: number
50  tokens_cached: number
51  tokens_cache_write: number
52  tokens_out: number
53  cost_usd: number
54  requests: number
55}
56
57/** One session's share of a row: when it first and last worked on it (ISO), where it ran (`surface`) and what it used. */
58export type SessionUsage = {
59  session: string
60  /** `terminal`, `desktop`, `vscode`, `mobile`, or `unknown`. */
61  surface: string
62  first: string
63  last: string
64  tokens: UsageTokens
65  cost_usd: number
66}
67
68/** What the plugin adds up over a plan: its rows' usage and the plan's own share (work no single task owns), already inside the total. */
69export type PlanTotals = RowUsage & { plan_own?: RowUsage }
70
71export type PlanEntry = {
72  anchor: string
73  name: string
74  goal: string
75  /** The absolute path of the plan file the "Plan file ›" view reads. */
76  plan_file: string
77  /** When the plan was registered: the date, and (plans made since 2026-10-11) the full ISO time. */
78  created?: string
79  created_at?: string
80  /** The earliest row `started`; the latest row `finished`, given only once the plan is closed (the header then reads `Done at 21:40`). */
81  started?: string
82  finished?: string
83  /**
84   * When the plan last changed, ISO text: the newest row `updated`. A closed plan with no `finished` reads `Done at 21:40` from it (`Done at Oct 11 21:40`
85   * on another day). A `PROGRESS.md` never has it.
86   */
87  updated?: string
88  /**
89   * Since when the plan has had no row In Progress or Verifying, ISO text: given by a board command for an idle plan. The state word then reads
90   * `Idle since 19:40` (`Idle since Oct 11 19:40`); without it, plain `Idle`.
91   */
92  idle_since?: string
93  /** Set by the plugin from the usage ledgers, never read from a board command's answer. */
94  usage_totals?: PlanTotals
95  /** Claude's 2–3 sentence summary of the plan (what it is for, where it is now, what is next or needed from the person), drawn under the plan line. Absent when none. */
96  recap?: string
97  /** When the recap was written, ISO text. Absent when the recap has no time (one read from PROGRESS.md has none). */
98  recap_updated?: string
99  /**
100   * Given by a board command: true for a plan this session works on, false for one added because the person picked or searched it. Only a
101   * plan with `in_session: true` reads In progress while this session works; a plan without the key keeps the state its rows give. A
102   * `PROGRESS.md` has one plan, which counts as this session's (true).
103   */
104  in_session?: boolean
105  /**
106   * Set by the mod, never by a board command, on a plan with `in_session: true`: `working` while this session runs a main turn or has a
107   * background agent not yet ended; `stopped_at` when that last stopped (ISO, this machine's clock and offset).
108   */
109  working?: true
110  stopped_at?: string
111  rows: PlanRow[]
112}
113
114/**
115 * One plan of the list `/plan-tracker` draws, as the board command lists it for the query `*`: a light line with the plan's state word
116 * (`Canceled` for an abandoned plan), `done` of `total` tasks, and when it was last updated (absent when no row has a time).
117 * `waiting` is true when nothing runs and a Needs Verification row waits on the person: the list draws it as Waiting for you.
118 */
119export type PlanMatch = {
120  anchor: string
121  name: string
122  state: 'In progress' | 'Idle' | 'Done' | 'Canceled'
123  done: number
124  total: number
125  updated?: string
126  waiting?: true
127}
128
129/**
130 * What the board command prints as JSON (or the board file, read as one), read: the plans of the session and the one the band and
131 * the board show. `matches` is the list of every plan, latest updated first, for the query `*`; without it the list is drawn from
132 * `plans` when there are two or more.
133 */
134export type PlanBoard = {
135  selected: string | null
136  message: string | null
137  plans: PlanEntry[]
138  matches?: PlanMatch[]
139  /** The ids of sessions whose usage ledger could not be read, set by the plugin; absent when every one was read. */
140  ledger_errors?: string[]
141}
142
143/** The plan (its ledger key) and the row (its exact text) a usage request is counted to; `row: null` is the plan's own share. */
144export type UsageOwner = { plan: string; row: string | null }
145
146/** A row a subagent claimed: its exact text, and its plan's key when one is named. */
147export type UsageClaim = { task: string; anchor?: string }
148
149/**
150 * One API request as the usage ledger holds it before it is booked: whose, which loop (`agentId`, absent for the main thread), its counts,
151 * its table price (null: no price) and when (ms). `wanted` is a claimed row the tracker did not have yet when it was recorded.
152 */
153export type UsageRequest = { owner: UsageOwner | null; agentId?: string; wanted?: UsageClaim; tokens: UsageTokens; usd: number | null; at: number }
154
155/**
156 * The usage ledger's state across a reload (`PluginState['plan-tracker'].usageCarry`): the session, what is known of each subagent (its
157 * claimed rows and its parent), the requests not yet in the file, and the board files this session has changed.
158 */
159export type UsageCarry = { session: string; agents: Record<string, { claims: UsageClaim[]; parent?: string }>; unwritten: UsageRequest[]; edited: string[] }
160
161/** The tracker's answer: a board, or one line saying why there is none. */
162export type Live = { board: PlanBoard } | { error: string }
163
164/** The card whose page the pane shows: a plan and the index of the row in its `rows`. */
165export type CardRef = { anchor: string; index: number }
166
167declare module 'claude-code' {
168  interface PluginState {
169    'plan-tracker': {
170      /** The tracker's last answer; null until the first one is in. */
171      live: Live | null
172      /** The `--query` the refreshes pass: `*` while the pane lists the plans, else the plan opened from the list, the band or the plan menu, or the one that just finished; '' for none. */
173      query: string
174      /** Whether the pane shows the plan list (set by `/plan-tracker`, cleared by opening a plan). */
175      listing: boolean
176      /** The text of the list's search field. */
177      search: string
178      /** Every plan, as the last answer to the query `*` listed them; null until one is in. The list is drawn from it while a new one is read. */
179      allPlans: PlanMatch[] | null
180      /** The anchor picked in the band or the pane; null until one is picked (the tracker's `selected` stands). */
181      selected: string | null
182      /** The card whose page replaces the board; null shows the board. */
183      card: CardRef | null
184      /** Whether the pane shows the plan file instead of the board. */
185      file: boolean
186      /** The anchor of the plan a PLAN-DONE with 0 left just finished, until the person's next prompt; null for none. */
187      finished: string | null
188      /** The animation frame, advanced by the one timer while something moves on screen. */
189      frame: number
190      /** Whether the pane's plan dropdown shows its list. */
191      menu: boolean
192      /** The lanes that show all their cards, as `<anchor>:<lane>`. */
193      expanded: string[]
194      /** Whether the band's plan list shows. */
195      bandMenu: boolean
196      /** What of this session is at work: a main turn running, and the ids of its background agents not yet ended. */
197      working: { turn: boolean; agents: string[] }
198      /** When `working` last went from something to nothing (ISO, this machine's clock and offset); null until it has. */
199      stoppedAt: string | null
200      /**
201       * What the usage ledger keeps across a reload of the module: the session it is for, whose work each subagent's requests are, the
202       * requests recorded since the last write of the file (those in the file are read back from it) and the board files this session has changed.
203       */
204      usageCarry: UsageCarry
205    }
206  }
207}
208