SLOPSHOPPER

workbench

Your current task above the prompt and a Workbench side pane: the task and its work items, what Claude is reading and editing, git status, file search and a…

panebandguardcommandtoaststatus
v0.1.36MITupdated 2026-10-19eascendco/workbench
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · workbench
│ ┃ Workbench ✕ › fix the failing auth test and add an audit log call │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ │ ⏺ Read(src/auth.ts) │ ┃ │ ▼ Task │ ⎿ Read 6 lines │ ┃ │ No tasks here yet. /task new <title> │ ⏺ Update(src/auth.ts) │ ┃ │ starts one. │ ⎿ Added 2 lines, removed 1 line │ ┃ │ │ ⏺ Bash(bun test) │ ┃ ╰──────────────────────────────────────────╯ ⎿ 3 pass, 1 fail │ ┃ │ ┃ ╭──────────────────────────────────────────╮ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ │ │ ┃ │ ▶ Files │ ✻ Worked for 42s · done 4:20 PM │ ┃ │ │ │ ┃ ╰──────────────────────────────────────────╯ › /task │ ┃ ⎿ workbench: No tasks here yet. `/task new <title>` starts one: a │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ │ │ ┃ │ ▶ In Flight │ │ ┃ │ │ │ ┃ ╰──────────────────────────────────────────╯ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Workbench
╭──────────────────────────────────────────────────────────╮ │ │ │ ▼ Task │ │ No tasks here yet. /task new <title> starts one. │ │ │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ │ │ ▶ Files │ │ │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ │ │ ▶ In Flight │ │ │ ╰──────────────────────────────────────────────────────────╯
README

Workbench

A Claude Code mod that keeps your work in view while Claude works. A band above the prompt shows your current task and its progress. A side pane holds three boxes:

  • Tasks: the current task, its work items and what's up next, kept as plain markdown files in your project.
  • Files: what Claude is reading or editing right now, your branch and uncommitted changes, every file Claude touched and a file tree.
  • In Flight: every Claude Code session on your machine and whether it's working, waiting for you or done; then this session's model, context and cost, every permission check, your subagents and a log.

No accounts, no services, no network calls.

Works with claude-skins: the pane takes your skin's colors and follows macOS light and dark. See Works with skins.

The band above the prompt: the task, the item in progress and a progress bar

<img src="media/pane.png" alt="The Workbench pane: Tasks with work items and Up next, Files with Right now, Claude touched and the file tree, and In Flight collapsed with its session counts" width="420">

<sub>Mockups drawn with the mod's own drawing code and sample data.</sub>

Install

Needs Claude Code 2.1.287 or later, in a terminal or the desktop app's Code tab.

/plugin marketplace add eascendco/workbench
/plugin install workbench@eascend

Start a new session and the pane opens. Then start your first task:

/task new Seven-day forecast

The pane

Three boxes, each collapsing to one row with its arrow, icon or title. Tasks starts open, Files and In Flight closed, and the pane remembers what you left. The arrow at the end of the band opens and closes the pane. In the desktop app the pane draws icons; in a terminal it uses plain text.

Tasks

Your current task and what's left on it. See How tasks work for the files behind it.

<img src="media/tasks.png" alt="The Tasks box with numbered parts: current task, in progress, work items, add work item and Up next" width="420">

  1. Current task. Its title, project and dates, and a progress bar in the color of the current stage, with the percent and how many items are done.
  2. In progress. The items you're working on now. Done marks one finished.
  3. Work items. Every item with its stage. Click an item's square to move it along: draft, to do, in progress, done. The small arrow folds the list.
  4. Add work item. Type a title, or stage: title to pick the stage.
  5. Up next. The next three open tasks by date. Press one to work on it instead; the task you left moves into Up next.

Files

What Claude is doing in your project, and the project itself.

<img src="media/files.png" alt="The Files box with numbered parts: right now, branch and changes, find a file, tree buttons, Claude touched and all files" width="420">

  1. Right now. What Claude is doing this turn: reading or editing a file, running a command, searching, or thinking. Between turns it shows the last file Claude touched.
  2. Branch and changes. Your git branch and how many files aren't committed, with the key for the dots below.
  3. Find a file. Searches every file in the project as you type. Enter opens the first match in the tree.
  4. Tree buttons. Refresh, collapse all, show sizes, go up a folder, go back to the project, show or hide hidden files.
  5. Claude touched. The last five files Claude read or edited this session, with their folder and whether it's reading or edited them.
  6. All files. The project tree. Dots mark files Claude read (purple) or edited (orange) and files not yet committed (yellow). A folder shows the dots of what's inside it.

While Claude works, the file it's reading or editing shimmers in the tree and in Claude touched, a band of light sweeping across its name (purple reading, orange editing). Files edited this turn stay lit in orange until your next prompt. A closed folder holding one takes the same color on its icon.

In Flight

What Claude and its subagents are doing right now, adapted from claude-flightdeck by Stephen Casella (MIT). It only watches: it never blocks or changes a tool call.

<img src="media/inflight.png" alt="The In Flight box expanded, with numbered panels: main model, sessions on this machine, architect, permission gate, agents, the turn and the session log" width="420">

  1. Main. The model, whether it's working, effort, permission mode and requests so far. The context gauge (⟲ counts compactions), the session's cost and your 5-hour and 7-day limits.
  2. Sessions. Every Claude Code session running on your machine (desktop app, VS Code, terminal): waiting first, then working, then done, each with its title, folder, where it runs and how long it's been in that state. A waiting session says what it waits for (input needed, dialog open). Collapsed, the box's header still counts them: In Flight · 1 waiting · 2 working · 1 done. It reads the registry Claude Code keeps in ~/.claude/sessions every 3 seconds and checks each process is still running with ps, so closed sessions drop off (macOS and Linux).
  3. Architect. Shows up once Claude consults an advisor or architect agent: each consult on a timeline, when it happened (before a plan, after repeated errors, before done; inferred), and the last advice.
  4. Gate. One square per permission check. Green was allowed by your settings, blue by the auto-mode classifier or you, amber is waiting for you, red ✗ was denied; checks inside subagents are dimmed. file, shell and other open the last five checks of that kind, with credentials masked.
  5. Agents. One row per subagent, newest first, six at most: status, task and a running clock, with type, context and steps under it. Each row stays on one line however narrow the pane. Press ▸ to see its last tool calls and the start of its answer.
  6. Turn. The turn in progress with its clock, edits and errors, or a receipt for the last one with its cost.
  7. Session log. Prompts, spawns, consults, edits, errors and denials as they happen.

Panels with nothing to show take no room, and Reset clears the box. It reads its data only while open.

How tasks work

Each task is one file in plans/ at your project root. /task new <title> writes one for you:

---
task: seven-day-forecast
project: weather-app
short: weather-app
title: Seven-day forecast
date: 2026-10-08
end: 2026-10-08
status: open
---

# Seven-day forecast

## Work items

- [x] Pick an API `spec`
- [~] Forecast screen `build`
  Seven days, with the hourly view behind a tap.
- [ ] Offline cache `build`
- [?] Release build `ship`
  • [ ] to do, [~] in progress, [x] done, [?] a draft waiting for your approval.
  • The word in backticks is the stage: spec, design, build, track, test or ship.
  • Indented lines under an item are its details.
  • The current task is the earliest open plan by date, unless you switched to another with /task switch or from Up next. The switch is kept per project across sessions, and once that task is done or parked the earliest open plan is current again. The next three are Up next. Set status: parked or status: superseded to keep a plan on disk without showing it.
  • When every item is done, the plan's status becomes done and the next task moves up.
  • Anything else in the file, like a ## Notes section, is kept as you wrote it.

Claude gets a work_items tool to create tasks, add items and update their status. Ask it to "break this task down" and it adds draft items for you to approve.

Commands

CommandWhat it does
/taskThe current task, its work items and Up next
/task new <title>Start a task
/task <n>One work item with its details
/task start <n>, /task done <n>, /task reopen <n>Change an item's status
/task approve [n]Approve one draft, or all of them
/task add [stage:] title -- detailsAdd a work item
/task breakAsk Claude to draft the work items
`/task switch [n \key \words]`Work on another open task: its Up next number, its task key or words of its title. With nothing after it, lists them. /task switch back returns to the earliest by date. A task with no work items yet is broken down first, as /task break does
/task paneOpen the side pane. In a folder with no plans the band shows "Workbench ❯" while the pane is closed, to reopen it
/task <anything else>Ask Claude, with the task and its plan file attached

Settings

In /config, under Workbench:

  • Plans folder: the folder name for plan files. Default plans.
  • Open the pane at start: on or off.
  • Band above the prompt: on or off.
  • Match macOS light and dark: on keeps Claude Code's theme on light or dark to match macOS, checked every 5 seconds (a daltonized or ANSI variant keeps its kind). off leaves the theme alone. Does nothing off macOS.

Works with skins

Workbench works with claude-skins by hellosverre, which restyles the Claude Code transcript. With a skin on, the pane takes its colors from your active skin, light or dark. Without one, the pane uses its own colors.

To add skins:

/plugin marketplace add hellosverre/claude-skins
/plugin install skins@hellosverre-mods

Skins pick light or dark from Claude Code's theme setting, which the desktop app doesn't change when macOS switches. The Match macOS setting above keeps that setting in step, so the transcript and the pane switch with your Mac, no restart needed.

What it reads

Your plan files, folder listings for the tree, and git status for the branch and changes. In Flight reads the session's own events (tool calls and their permission verdicts, subagent steps, context and cost) and keeps short summaries for the session only. Sessions reads Claude Code's own session registry in ~/.claude/sessions (each session's title, folder and status) and runs ps to check those processes are alive. It reads no other file contents beyond the plan files, makes no network calls, and stores nothing outside your project. Run claude plugin validate on this folder to see every call it makes.

Turn it off

Disable it in /plugin under Installed, or:

claude plugin disable workbench@eascend

License

MIT. Made by eascend. The In Flight box is adapted from claude-flightdeck, MIT, Copyright (c) 2026 Stephen Casella; its notice is in hooks/deck.ts.

Source 11 files
hooks/register.tsx 1557 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Hook, Register } from 'claude-code'
3
4import type { DevEntry, Entry, Files, Git, Group, PaneUi, Snap, Touch, Activity, WorkbenchUi, WorkItem } from '../types'
5import type { BarIn } from './draw'
6import { ACCENT, bandBarSvg, bandTitleSvg, DOING, DONE, MUTED, paneBarSvg, STAGE_COLOR } from './draw'
7import { activeItem, byStatus, themeFor, clip, counts, localDate, newId, nextStatus, parseAdd, STAGES, TITLE_MAX, withStages } from './logic'
8import type { Plan, PlanFront } from './plans'
9import { allDone, devEntryOf, findOpen, newPlanText, newTaskKey, parsePlan, plansDirName, setFront, setItems, snapshotOfPlans } from './plans'
10import {
11  absOf, addTouch, badge, baseOf, extOf, FILE_TOOLS, foldersTo, humanSize, isDirty, join,
12  inkOf, paletteOf, parentOf, parseStatus, relDir, rowsOf, search, THEME_KEY,
13} from './bench'
14import type { SkinCustom, SkinPrefs, Slot } from './bench'
15import type { DeckAgent, DeckArchitect, DeckCheck, DeckLogLine, DeckLoop, DeckReceipt, DeckSession, DeckView } from '../types'
16import {
17  adviceLine, afterCall, applyStep, bucketOf, cardTitle, DEFAULT_ARCHITECT, DEFAULT_GATE, DEFAULT_MAIN, DEFAULT_ROSTER, DEFAULT_TURN,
18  DEFAULT_USAGE, DEFAULT_VIEW, describeInput, EDIT_TOOLS, endConsult, fmtDuration, handbackOf, listOf, momentOf, normalize,
19  normalizeCard, normalizeGate, normalizeLog, noteTool, promptLine, receiptOf, recordCheck, RESET, settleCheck, shorten, startConsult, stepLoop,
20  alivePids, parseSessionFile, sessionsLine, sessionsOf,
21} from './deck'
22import type { SessionFile } from './deck'
23import type { DeckData } from './deck'
24import { deckKids, deckTitle } from './deck-view'
25import { caps, fileTag, hero, icon, pill, rule } from './icons'
26import type { IconName, Ink } from './icons'
27
28const TOOL = 'work_items'
29const TOOL_FULL = 'mcp__workbench__work_items'
30/** Item and task titles in lists are cut here. */
31const ROW_CHARS = 30
32
33const snapAtom = atom({ plugin: 'workbench', key: 'snap' } as const, { status: 'idle', shorts: [], prev: [], next: [] } as Snap)
34const uiAtom = atom({ plugin: 'workbench', key: 'ui' } as const, { showPrev: false } as PaneUi)
35
36type $ = EngineInterface
37
38/* ── the Workbench: the side pane (task box and file box) ── */
39
40const PANE = 'workbench'
41const TITLE = 'Workbench'
42
43const filesAtom = atom({ plugin: 'workbench', key: 'files' } as const, {
44  root: '', project: '', expanded: [], dirs: {}, showSizes: false, showHidden: false, query: '', all: [],
45} as Files)
46const gitAtom = atom({ plugin: 'workbench', key: 'git' } as const, { isRepo: false, branch: '', top: '', dirty: [] } as Git)
47const touchedAtom = atom({ plugin: 'workbench', key: 'touched' } as const, [] as Touch[])
48const activityAtom = atom({ plugin: 'workbench', key: 'activity' } as const, { busy: false } as Activity)
49const benchAtom = atom({ plugin: 'workbench', key: 'bench' } as const, { itemsOpen: true } as WorkbenchUi)
50
51// The skin /skin has on. Skins is optional (not a dependency): its refs are cast because its
52// contract is not laid here, and with it off the pane uses its own colors.
53const SKIN_PREFS = { plugin: 'skins', key: 'prefs' } as const
54const SKIN_CUSTOM = { plugin: 'skins', key: 'custom' } as const
55const SKIN_LIGHT = { plugin: 'skins', key: 'isLight' } as const
56
57const quiet = <T,>(p: Promise<T>) => p.catch(() => undefined)
58/** The label of a blank button laid over a drawn icon: two em spaces. Plain spaces collapse to one on the desktop, which left only the icon's left edge clickable. */
59const COVER = '\u2003\u2003'
60
61/* ── files ── */
62
63async function listDir($: $, dir: string): Promise<Entry[]> {
64  const list = await $.fs.list(dir)
65  const out: Entry[] = []
66  for (const x of list) {
67    let isDir = x.kind === 'dir'
68    if (x.isLink) isDir = (await quiet($.fs.stat(join(dir, x.name))))?.kind === 'dir'
69    out.push({ name: x.name, dir: isDir, size: x.size })
70  }
71  return out
72}
73
74async function loadDirs($: $, dirs: readonly string[]) {
75  const got: Record<string, Entry[]> = {}
76  for (const d of dirs) got[d] = (await quiet(listDir($, d))) ?? []
77  await update($, filesAtom, f => ({ ...f, dirs: { ...f.dirs, ...got } }))
78}
79
80async function setRoot($: $, root: string) {
81  await update($, filesAtom, f => ({ ...f, root, expanded: [], dirs: {}, query: '', all: [] }))
82  await loadDirs($, [root])
83  await refreshGit($)
84}
85
86async function refreshFiles($: $) {
87  const f = await read($, filesAtom)
88  await update($, filesAtom, x => ({ ...x, dirs: {}, all: [] }))
89  await loadDirs($, [f.root, ...f.expanded])
90  if (f.query) await loadAll($)
91  await refreshGit($)
92}
93
94async function toggleDir($: $, path: string) {
95  const f = await read($, filesAtom)
96  const isOpen = f.expanded.includes(path)
97  await update($, filesAtom, x => ({ ...x, expanded: isOpen ? x.expanded.filter(p => p !== path) : [...x.expanded, path] }))
98  if (!isOpen && !f.dirs[path]) await loadDirs($, [path])
99}
100
101/** Every file under root, for search: git's list in a repo, else a bounded walk. */
102async function loadAll($: $) {
103  const { root } = await read($, filesAtom)
104  const r = await quiet($.process.run(['git', '-C', root, 'ls-files', '-co', '--exclude-standard', '-z'], { timeoutMs: 10000 }))
105  let all: string[] = []
106  if (r && r.exitCode === 0) all = r.stdout.split('\0').filter(Boolean)
107  else {
108    const queue: [string, number][] = [[root, 0]]
109    while (queue.length && all.length < 5000) {
110      const [dir, depth] = queue.shift()!
111      for (const en of (await quiet(listDir($, dir))) ?? []) {
112        const p = join(dir, en.name)
113        if (en.dir) depth < 5 && en.name !== '.git' && en.name !== 'node_modules' && queue.push([p, depth + 1])
114        else all.push(p.slice(root.length + 1))
115      }
116    }
117  }
118  await update($, filesAtom, f => ({ ...f, all }))
119}
120
121async function reveal($: $, path: string) {
122  const f = await read($, filesAtom)
123  const folders = foldersTo(path, f.root)
124  await update($, filesAtom, x => ({ ...x, query: '', expanded: [...new Set([...x.expanded, ...folders])] }))
125  await loadDirs($, folders.filter(d => !f.dirs[d]))
126}
127
128async function refreshGit($: $) {
129  const { root } = await read($, filesAtom)
130  const head = await quiet($.process.run(['git', '-C', root, 'rev-parse', '--show-toplevel', '--abbrev-ref', 'HEAD'], { timeoutMs: 5000 }))
131  if (!head || head.exitCode !== 0) return void (await update($, gitAtom, () => ({ isRepo: false, branch: '', top: '', dirty: [] })))
132  const [top = root, branch = ''] = head.stdout.trim().split('\n')
133  const st = await quiet($.process.run(['git', '-C', top, 'status', '--porcelain=v1', '-z', '-uall'], { timeoutMs: 10000 }))
134  const dirty = st && st.exitCode === 0 ? parseStatus(st.stdout, top) : []
135  await update($, gitAtom, () => ({ isRepo: true, branch, top, dirty }))
136}
137
138/* ── work items, written by the plan writer below ── */
139
140async function save($: $, key: string, fn: (e: DevEntry) => DevEntry) {
141  const msg = await writeEntry($, key, fn).catch((err: Error) => String(err.message ?? err))
142  if (msg !== 'Saved') void $.ui.toast(msg)
143}
144
145const setStatus = ($: $, key: string, id: string, status: WorkItem['status']) =>
146  save($, key, x => ({ ...x, items: x.items.map(i => (i.id === id ? { ...i, status } : i)) }))
147
148/* ── drawing ── */
149
150const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
151const shortDate = (d: string) => `${MONTHS[Number(d.slice(5, 7)) - 1] ?? ''} ${Number(d.slice(8, 10))}`
152
153async function paletteNow($: $) {
154  const prefs = (await quiet($.state.get(SKIN_PREFS as never)))?.value as SkinPrefs
155  const custom = (await quiet($.state.get(SKIN_CUSTOM as never)))?.value as SkinCustom
156  const isLight = (await quiet($.state.get(SKIN_LIGHT as never)))?.value as boolean | undefined
157  return paletteOf(prefs, custom, isLight)
158}
159
160async function openPane($: $) {
161  await $.ui.open({ id: PANE, title: TITLE })
162}
163
164/** Set once the pane has drawn in this session. Until then the first prompt opens it again: a resumed
165 *  session can start before the desktop can take a pane, and the open at start is lost. */
166let paneSeen = false
167let paneRetried = false
168
169/** The band's chevron and `/task pane`. */
170async function togglePane($: $) {
171  const isUp = (await $.ui.panes()).some(p => p.id === PANE)
172  if (isUp) await $.ui.close({ id: PANE })
173  else await openPane($)
174}
175
176/** At session start: the tree on the session's folder, and the pane opens unless the setting says no. */
177async function startWorkbench($: $) {
178  const cwd = await $.session.cwd()
179  await update($, filesAtom, f => ({ ...f, project: cwd }))
180  void setRoot($, cwd)
181  // The sections as last left, from the store.
182  const sections = sectionsOf(await quiet($.store.get(SECTIONS)))
183  await update($, benchAtom, u => ({ ...u, sections }))
184  if (settings.openPane) void openPane($)
185}
186
187/** After each turn: commits and checkouts happen in Bash, so the branch line catches up. */
188/** Which Workbench sections are open, kept across sessions: Tasks open, Files and In Flight collapsed until changed. */
189const SECTIONS = 'sections'
190type Sections = { tasks: boolean; files: boolean; deck: boolean }
191const sectionsOf = (v: unknown): Sections => ({ tasks: true, files: false, deck: false, ...(v && typeof v === 'object' ? (v as Partial<Sections>) : {}) })
192async function toggleSection($: $, k: keyof Sections) {
193  const ui = await update($, benchAtom, u => {
194    const cur = sectionsOf(u.sections)
195    return { ...u, sections: { ...cur, [k]: !cur[k] } }
196  })
197  await quiet($.store.set(SECTIONS, ui.sections))
198}
199
200/* ── the In Flight card: its state, read and drawn here; its hooks are further down ── */
201
202const mainAtom = atom({ plugin: 'workbench', key: 'deckMain' } as const, DEFAULT_MAIN)
203const usageAtom = atom({ plugin: 'workbench', key: 'deckUsage' } as const, DEFAULT_USAGE)
204const archAtom = atom({ plugin: 'workbench', key: 'deckArchitect' } as const, DEFAULT_ARCHITECT)
205const gateAtom = atom({ plugin: 'workbench', key: 'deckGate' } as const, DEFAULT_GATE)
206const agentsAtom = atom({ plugin: 'workbench', key: 'deckAgents' } as const, [] as DeckAgent[])
207const loopsAtom = atom({ plugin: 'workbench', key: 'deckLoops' } as const, [] as DeckLoop[])
208const logAtom = atom({ plugin: 'workbench', key: 'deckLog' } as const, [] as DeckLogLine[])
209const turnAtom = atom({ plugin: 'workbench', key: 'deckTurn' } as const, DEFAULT_TURN)
210const receiptAtom = atom({ plugin: 'workbench', key: 'deckReceipt' } as const, null as DeckReceipt | null)
211const viewAtom = atom({ plugin: 'workbench', key: 'deckView' } as const, DEFAULT_VIEW)
212const rosterAtom = atom({ plugin: 'workbench', key: 'deckRoster' } as const, DEFAULT_ROSTER)
213const sessionsAtom = atom({ plugin: 'workbench', key: 'deckSessions' } as const, [] as DeckSession[])
214
215/** How often the Sessions panel rereads the registry. Read even while In Flight is collapsed: its header counts them. */
216const SESSIONS_MS = 3000
217
218/** Every Claude Code session running on this machine, from the registry under `~/.claude/sessions`; written only when it changed. */
219async function pollSessions($: $) {
220  const home = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${(await $.env.get('HOME')) ?? ''}/.claude`
221  const dir = `${home}/sessions`
222  const names = (await $.fs.list(dir)).filter(f => f.kind === 'file' && /^\d+\.json$/.test(f.name)).map(f => f.name)
223  const files = (await Promise.all(names.map(n => quiet($.fs.read(`${dir}/${n}`)).then(t => (t ? parseSessionFile(t) : null)))))
224    .filter((f): f is SessionFile => f !== null)
225  const pids = files.map(f => f.pid)
226  const ps = pids.length ? await quiet($.process.run(['ps', '-o', 'pid=,comm=', '-p', pids.join(',')], { timeoutMs: 5000 })) : undefined
227  const list = sessionsOf(files, alivePids(ps?.stdout ?? ''), (await quiet($.session.id())) ?? '')
228  const was = await read($, sessionsAtom)
229  if (JSON.stringify(was) !== JSON.stringify(list)) await update($, sessionsAtom, () => list)
230}
231
232async function watchSessions($: $) {
233  await quiet(pollSessions($))
234  $.clock.every(SESSIONS_MS, () => quiet(pollSessions($)))
235}
236
237async function readDeck($: $): Promise<DeckData> {
238  const [main, usage, arch, gate, cards, loops, log, turn, receipt, view, sessions, now] = await Promise.all([
239    getMain($), getUsage($), getArch($), getGate($), getCards($), getLoops($), getLog($), getTurn($), read($, receiptAtom), getView($),
240    getSessions($), $.clock.now(),
241  ])
242  return { main, usage, arch, gate, cards, loops, log, turn, receipt, view, sessions, now }
243}
244
245/** The card's Reset: agents, checks, consults, log and the turn clear; cost, rate limits and compactions stay. */
246async function resetDeck($: $) {
247  await update($, mainAtom, RESET.main)
248  await update($, archAtom, () => DEFAULT_ARCHITECT)
249  await update($, gateAtom, () => DEFAULT_GATE)
250  await update($, agentsAtom, () => [])
251  await update($, loopsAtom, () => [])
252  await update($, logAtom, () => [])
253  await update($, turnAtom, () => DEFAULT_TURN)
254  await update($, receiptAtom, () => null)
255  await update($, viewAtom, () => DEFAULT_VIEW)
256  await update($, usageAtom, RESET.usage)
257}
258
259const afterTurnWorkbench = ($: $) => {
260  void quiet(refreshGit($))
261  // The turn is over: Right now goes back to idle.
262  void quiet(update($, activityAtom, a => ({ ...a, busy: false })))
263}
264
265
266/* ── Plan files: the source of truth, read from disk ── */
267
268/** The plans folder this session works in, and the plans read from it last. */
269let plansDir: string | undefined
270let plans: Plan[] = []
271
272/** The settings from /config (the manifest's userConfig), read when the module loads. */
273const settings = { plansDir: 'plans', openPane: true, band: true, followMacos: true }
274
275/** The nearest plans folder at or above the session's folder, stopping at the home folder. */
276async function findPlansDir($: $) {
277  const home = ((await $.env.get('HOME')) ?? '').replace(/\/+$/, '')
278  let dir = (await $.session.cwd()).replace(/\/+$/, '')
279  while (dir && dir !== home && dir !== '/') {
280    if (await $.fs.exists(`${dir}/${settings.plansDir}`)) return `${dir}/${settings.plansDir}`
281    dir = dir.slice(0, dir.lastIndexOf('/'))
282  }
283  return undefined
284}
285
286async function loadPlans($: $) {
287  plansDir = await findPlansDir($)
288  return (plans = plansDir ? await loadPlansIn($, plansDir) : [])
289}
290
291/** The task picked as current in each project, by project folder; kept across sessions. Without one, the earliest open plan. */
292const PICKS = 'picks'
293const picksOf = async ($: $): Promise<Record<string, string>> => {
294  const v = await quiet($.store.get(PICKS))
295  return v && typeof v === 'object' ? (v as Record<string, string>) : {}
296}
297
298/** Makes `key` this project's current task; undefined, or the earliest open plan, goes back to following the dates.
299 * A task with no work items yet is broken down first: Claude is asked to draft them. Returns whether it was. */
300async function switchTask($: $, key: string | undefined) {
301  await loadPlans($)
302  if (!plansDir) return false
303  const folder = plansDir.slice(0, -settings.plansDir.length - 1)
304  const earliest = snapshotOfPlans(plans, folder).cur?.key
305  const picks = await picksOf($)
306  if (!key || key === earliest) delete picks[folder]
307  else picks[folder] = key
308  await quiet($.store.set(PICKS, picks))
309  const cur = (await refresh($)).cur
310  if (!cur || cur.items.length) return false
311  submitLater($, breakPrompt(cur))
312  return true
313}
314
315async function refresh($: $) {
316  try {
317    await loadPlans($)
318    const folder = plansDir ? plansDir.slice(0, -settings.plansDir.length - 1) : ''
319    const snap: Snap = plansDir
320      ? snapshotOfPlans(plans, folder, (await picksOf($))[folder])
321      : { status: 'none', shorts: [], prev: [], next: [] }
322    await update($, snapAtom, () => snap)
323    return snap
324  } catch (err) {
325    const snap: Snap = { status: 'error', message: String((err as Error).message ?? err), shorts: [], prev: [], next: [] }
326    await update($, snapAtom, () => snap)
327    return snap
328  }
329}
330
331/** Applies `fn` to one plan's work items and writes the file; a plan with every item done is marked done. */
332async function writeEntry($: $, key: string, fn: (e: DevEntry) => DevEntry): Promise<string> {
333  await loadPlans($)
334  const plan = plans.find(p => p.task === key)
335  if (!plan) return `Not saved: no plan file for ${key}`
336  const entry = withStages(fn(devEntryOf(plan)))
337  let text = setItems(plan.text, entry.items)
338  if (allDone(entry.items) && plan.status !== 'done') text = setFront(text, { ...plan, status: 'done' })
339  await $.fs.write(plan.file, text)
340  await refresh($)
341  return 'Saved'
342}
343
344/** `/task new <title>` and the tool's "create": a new plan file, today's date unless one is given. */
345async function createTask($: $, title: string, date?: string): Promise<string> {
346  const t = title.trim()
347  if (!t) return 'Give the task a title: /task new <title>'
348  await loadPlans($)
349  const dir = plansDir ?? `${(await $.session.cwd()).replace(/\/+$/, '')}/${settings.plansDir}`
350  const project = baseOf(dir.slice(0, -settings.plansDir.length - 1)) || 'project'
351  const key = newTaskKey(t, plans.map(p => p.task))
352  const day = date && /^\d{4}-\d{2}-\d{2}$/.test(date) ? date : localDate()
353  const front: PlanFront = { task: key, project, short: project, title: t, date: day, end: day, status: 'open' }
354  const file = `${dir}/${key}.md`
355  await $.fs.write(file, newPlanText(front, []))
356  await refresh($)
357  return `Created ${file} (task ${key})`
358}
359
360async function loadPlansIn($: $, dir: string) {
361  const files = (await $.fs.list(dir)).filter(f => f.kind === 'file' && f.name.endsWith('.md'))
362  const read = await Promise.all(files.map(async f => parsePlan(await $.fs.read(`${dir}/${f.name}`), `${dir}/${f.name}`)))
363  return read.filter((p): p is Plan => !!p)
364}
365
366/* ── shared view values ── */
367
368const dateShort = (d: string) => new Date(d + 'T00:00:00').toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
369const md = (d: string) => d.slice(5).replace('-', '/')
370const when = (g: Group) => (g.start === g.end ? md(g.start) : `${md(g.start)}→${md(g.end)}`)
371const openDate = (g: Group) => g.parts.find(p => p.status !== 'done')?.date ?? g.start
372const box = (s: WorkItem['status']) => ({ draft: '[?]', todo: '[ ]', doing: '[~]', done: '[x]' })[s]
373const GLYPH: Record<WorkItem['status'], string> = { draft: '◌', todo: '□', doing: '◧', done: '■' }
374
375function barIn(g: Group): BarIn {
376  const c = counts(g.items)
377  const n = byStatus(g.items)
378  const now = activeItem(g.items.filter(i => i.status !== 'done'))
379  const finished = c.total > 0 && c.done === c.total
380  const pill = finished ? 'done' : !g.items.length ? 'break down' : !c.total ? `${n.draft} draft${n.draft === 1 ? '' : 's'}` : (now?.stage ?? 'build')
381  // The bar takes the current stage's color, as the pane's stage tags do.
382  return { done: c.done, doing: n.doing, total: c.total, pill, finished, color: now ? STAGE_COLOR[now.stage] : undefined }
383}
384
385/** The item the band names: in progress, else the next one to do. */
386const inHand = (g: Group) => activeItem(g.items.filter(i => i.status === 'doing' || i.status === 'todo'))
387
388function breakPrompt(g: Group) {
389  return [
390    `Break the current dev task into work items.`,
391    `Task: "${g.title}" (${g.short}, ${when(g)}, key ${g.key}). Its plan file: ${g.file ?? 'none yet'}.`,
392    g.items.length ? `Existing items: ${g.items.map(i => `${i.stage}: ${i.title}`).join('; ')}.` : '',
393    `Read the project's docs and code as needed. Use only the stages that apply, from: ${STAGES.join(', ')} (track = analytics or monitoring for the feature).`,
394    `Each item is one concrete, checkable step; 3 to 10 items. Titles are short labels of 2 to 5 words, at most ${ROW_CHARS} characters, no sentences and no trailing period (good: "Auth screen", "Seed demo data"). Put the what, why and done-when in "details", one or two sentences.`,
395    `Then call the ${TOOL} tool with action "add", task "${g.key}" and draft true, and show me the list.`,
396  ]
397    .filter(Boolean)
398    .join('\n')
399}
400
401const NONE = 'No tasks here yet. `/task new <title>` starts one: a plan file in `' + 'plans/` that you, /task and Claude all edit.'
402
403const USAGE = [
404  '`/task` the task, its work items and Up next',
405  '`/task <n>` one item with its details',
406  '`/task start <n>` · `/task done <n>` · `/task reopen <n>`',
407  '`/task approve [n]` approve one draft, or all',
408  '`/task add [stage:] title -- details`',
409  '`/task break` ask Claude to draft the work items',
410  '`/task switch [n | task | words]` work on another open task; `/task switch back` returns to the earliest by date',
411  '`/task pane` open the side pane',
412  '`/task new <title>` start a task: a plan file in the plans folder',
413  '`/task refresh` re-read the plan files',
414  '`/task <anything else>` ask Claude, with the task and its items attached',
415].join('\n')
416const textBar = (b: BarIn, width = 20) => {
417  const f = b.total ? Math.round((width * b.done) / b.total) : 0
418  return '█'.repeat(f) + '░'.repeat(width - f)
419}
420
421/** What `/task` prints: the pane as markdown, for the terminal where the pane is out of sight. */
422function textView(snap: Snap, selected?: string) {
423  const cur = snap.cur!
424  const bar = barIn(cur)
425  const pct = bar.total ? Math.round((bar.done / bar.total) * 100) : 0
426  const act = activeItem(cur.items, selected)
427  const head = [
428    `**${cur.title}**`,
429    `${cur.short} · ${dateShort(openDate(cur))}${cur.size ? ' · ' + cur.size : ''}${cur.stages.length ? ' · ' + cur.stages.join(' → ') : ''}`,
430    bar.total ? `\`${textBar(bar)}\` ${bar.pill} · ${pct}%` : '',
431  ].filter(Boolean)
432  const now = act ? ['', `**${act.status === 'doing' ? 'In progress' : act.status === 'draft' ? 'Draft' : act.status === 'done' ? 'Done' : 'Up first'}: ${act.title}** · ${act.stage}`, act.details ?? '_No details yet._'] : []
433  const items = cur.items.length
434    ? ['', '**Work items**', ...cur.items.map((i, k) => `${k + 1}. ${GLYPH[i.status]} ${clip(i.title, ROW_CHARS)} · ${i.stage}${i.status === 'draft' ? ' · draft' : ''}`)]
435    : ['', '**Work items**', 'Not broken down yet: `/task break`']
436  const next = snap.next.length ? ['', '**Up next** (`/task switch <n>` to work on one)', ...snap.next.map((g, k) => `${k + 1}. ${g.key} ${clip(g.title, ROW_CHARS)} · ${dateShort(openDate(g))}`)] : []
437  return [...head, ...now, ...items, ...next].join('\n')
438}
439
440/** Sends a prompt once the command has finished: a command holds its turn, so submitting inside it is refused. */
441function submitLater($: $, text: string) {
442  $.clock.after(300, () => void $.prompt.submit({ text }))
443}
444
445/** `/task <words>`: the person's request, with the task and its plan file, for Claude to act on. */
446function workPrompt(snap: Snap, request: string) {
447  const g = snap.cur!
448  const items = g.items.map((i, k) => `${k + 1}. [${i.status}] ${i.stage}: ${i.title}${i.details ? `: ${i.details}` : ''}`)
449  return [
450    request,
451    '',
452    `Current task: "${g.title}" (${g.short}, key ${g.key}). Its plan file: ${g.file ?? 'none yet'}.`,
453    items.length ? `Work items:\n${items.join('\n')}` : 'It has no work items yet: break it down first with the work_items tool (action "add", draft true).',
454    snap.next.length ? `Up next after it: ${snap.next.map(x => x.title).join('; ')}.` : '',
455    `As you work, keep the plan file current: mark an item [~] when you start it and [x] when it is finished (or use the ${TOOL} tool). Add notes under the item or in the file's Notes section.`,
456  ]
457    .filter(Boolean)
458    .join('\n')
459}
460
461/** What `/task <n>` prints: one item whole. */
462function itemView(it: WorkItem, n: number) {
463  const state = { draft: 'draft', todo: 'to do', doing: 'in progress', done: 'done' }[it.status]
464  return [`**${n}. ${it.title}**`, `${it.stage} · ${state}`, '', it.details ?? '_No details yet._'].join('\n')
465}
466
467/** After each turn: Claude may have edited a plan file, so re-read it. */
468const afterTurn: Hook<'turn.complete'> = async ($, e, next) => {
469  const r = await next(e)
470  await quiet(deckTurnDone($, e))
471  afterTurnWorkbench($)
472  if (plansDir) await refresh($)
473  return r
474}
475
476/** `/task` and `/workbench:task`: the view, one item, or a change to an item. */
477async function taskCommand($: $, e: { args?: string }) {
478  const args = (e.args ?? '').trim()
479  const [verb = '', ...rest] = args.split(/\s+/)
480  if (verb === 'new') return { text: await createTask($, rest.join(' ')) }
481  const fresh = !args || verb === 'refresh' || verb === 'pane'
482  const snap = fresh || (await read($, snapAtom)).status !== 'ready' ? await refresh($) : await read($, snapAtom)
483  if (verb === 'pane') await openPane($)
484  if (snap.status === 'none') return { text: NONE }
485  if (snap.status === 'error') return { text: 'Could not read the plans: ' + snap.message }
486  const cur = snap.cur
487  if (!cur) return { text: 'No open tasks here. `/task new <title>` starts one.' }
488  const ui = await read($, uiAtom)
489  if (fresh) return { text: textView(snap, ui.selected) }
490
491  const nth = (v?: string) => cur.items[Number(v) - 1]
492  const missing = (v?: string) => ({ text: `No item ${v ?? ''}. ${cur.items.map((i, k) => `${k + 1} ${i.title}`).join(' · ')}` })
493  if (/^\d+$/.test(verb)) {
494    const it = nth(verb)
495    if (!it) return missing(verb)
496    await update($, uiAtom, u => ({ ...u, selected: it.id }))
497    return { text: itemView(it, Number(verb)) }
498  }
499  if (verb === 'break') {
500    submitLater($, breakPrompt(cur))
501    return { text: `Asking Claude to draft work items for "${cur.title}".` }
502  }
503  if (verb === 'add') {
504    const { stage, title, details } = parseAdd(rest.join(' '), ui.stage ?? cur.stages[0] ?? 'build')
505    if (!title) return { text: 'Usage: /task add [stage:] title -- details' }
506    const msg = await writeEntry($, cur.key, x => ({ ...x, items: [...x.items, { id: newId(), title, stage, status: 'todo', ...(details ? { details } : {}) }] }))
507    return { text: `${msg}: ${stage}: ${title}` }
508  }
509  if (verb === 'approve') {
510    const it = rest[0] ? nth(rest[0]) : undefined
511    if (rest[0] && !it) return missing(rest[0])
512    const n = it ? 1 : cur.items.filter(i => i.status === 'draft').length
513    if (!n) return { text: 'No drafts to approve.' }
514    const msg = await writeEntry($, cur.key, x => ({ ...x, items: x.items.map(i => (i.status === 'draft' && (!it || i.id === it.id) ? { ...i, status: 'todo' } : i)) }))
515    return { text: `${msg}: approved ${it ? it.title : `${n} draft${n === 1 ? '' : 's'}`}` }
516  }
517  const to = ({ start: 'doing', done: 'done', reopen: 'todo' } as const)[verb as 'start' | 'done' | 'reopen']
518  if (to) {
519    const it = nth(rest[0])
520    if (!it) return missing(rest[0])
521    const msg = await writeEntry($, cur.key, x => ({ ...x, items: x.items.map(i => (i.id === it.id ? { ...i, status: to } : i)) }))
522    return { text: `${msg}: ${it.title} → ${to}` }
523  }
524  if (verb === 'help') return { text: USAGE }
525  if (verb === 'switch') {
526    const arg = rest.join(' ')
527    const list = snap.next.map((g, k) => `${k + 1} ${g.key} ${g.title}`).join(' · ')
528    if (!arg) return { text: `Working on ${cur.key} ${cur.title}. Switch to: ${list || 'nothing else open'}. Use /task switch <n>, a task key or words of its title.` }
529    const breaking = ' It has no work items yet, so Claude breaks it down first.'
530    if (arg === 'back') {
531      const broke = await switchTask($, undefined)
532      const s2 = await read($, snapAtom)
533      return { text: `Back to the earliest open task: ${s2.cur?.key} ${s2.cur?.title}.${broke ? breaking : ''}` }
534    }
535    const to = findOpen(plans, snap, arg)
536    if (!to) return { text: `No open task matches "${arg}". Switch to: ${list}` }
537    const broke = await switchTask($, to.task)
538    return { text: `Now working on ${to.task} ${to.title}.${broke ? breaking : ''}` }
539  }
540  // Anything else is a request in words: hand it to Claude with the task and every item's details.
541  submitLater($, workPrompt(snap, args))
542  return { text: textView(snap, ui.selected) }
543}
544
545/* ── In Flight's hooks: they watch the session and keep the card's state; each passes its event on unchanged ── */
546
547/** Agent types and server tools that count as the on-call architect. */
548const ARCHITECT = /advisor|architect/i
549
550type ServerBlock = { type: string; id?: string; name?: string; tool_use_id?: string }
551
552// Every read goes through these, so a value saved under an older shape still reads after a reload.
553const getMain = async ($: $) => normalize(DEFAULT_MAIN, await read($, mainAtom))
554const getUsage = async ($: $) => normalize(DEFAULT_USAGE, await read($, usageAtom))
555async function getArch($: $): Promise<DeckArchitect> {
556  const a = normalize(DEFAULT_ARCHITECT, await read($, archAtom))
557  return { ...a, consults: listOf(a.consults), ids: listOf(a.ids), seen: listOf(a.seen) }
558}
559const getGate = async ($: $) => normalizeGate(await read($, gateAtom))
560const getCards = async ($: $) => listOf<unknown>(await read($, agentsAtom)).map(normalizeCard)
561const getLoops = async ($: $) => listOf<DeckLoop>(await read($, loopsAtom))
562const getLog = async ($: $) => normalizeLog(await read($, logAtom))
563const getTurn = async ($: $) => normalize(DEFAULT_TURN, await read($, turnAtom))
564const getView = async ($: $): Promise<DeckView> => normalize(DEFAULT_VIEW, await read($, viewAtom))
565const getSessions = async ($: $) => listOf<DeckSession>(await read($, sessionsAtom))
566const getRoster = async ($: $) => ({ architectTypes: listOf<string>(normalize(DEFAULT_ROSTER, await read($, rosterAtom)).architectTypes) })
567
568async function say($: $, who: string, text: string, kind: DeckLogLine['kind'] = 'info', agentId: string | null = null) {
569  const line: DeckLogLine = { at: await $.clock.now(), who, text, kind, agentId }
570  await update($, logAtom, list => [...normalizeLog(list), line].slice(-60))
571}
572
573async function whoIs($: $, agentId: string | undefined) {
574  if (!agentId) return 'main'
575  const card = (await getCards($)).find(c => c.id === agentId)
576  return card ? shorten(cardTitle(card), 14) : 'agent'
577}
578
579async function consultStarted($: $, id: string, via: string) {
580  const moment = momentOf(await getTurn($))
581  const at = await $.clock.now()
582  await update($, archAtom, a => startConsult(normalize(DEFAULT_ARCHITECT, a), { id, at, moment, via }))
583  if (moment === 'before done') await update($, turnAtom, x => ({ ...normalize(DEFAULT_TURN, x), isReviewing: true }))
584  await say($, 'architect', `${moment} · ${via}`, 'consult')
585}
586
587async function consultEnded($: $, advice: string | null, id?: string) {
588  const at = await $.clock.now()
589  const first = advice?.split('\n').find(l => l.trim()) ?? null
590  const text = first ? shorten(first.replace(/^[#>*\s-]+/, ''), 160) : null
591  await update($, archAtom, a => endConsult(normalize(DEFAULT_ARCHITECT, a), at, text, id))
592  await update($, turnAtom, t => ({ ...normalize(DEFAULT_TURN, t), isReviewing: false }))
593  await say($, 'architect', text ? `advice: ${shorten(text, 60)}` : 'advice returned', 'consult')
594}
595
596async function noteAdvice($: $, advice: string) {
597  await update($, archAtom, x => ({ ...normalize(DEFAULT_ARCHITECT, x), lastAdvice: advice }))
598  await say($, 'architect', `advice: ${shorten(advice, 60)}`, 'consult')
599}
600
601const isArchitectType = async ($: $, type: string) => ARCHITECT.test(type) || (await getRoster($)).architectTypes.includes(type)
602
603/** The session's cost read fresh, not from the last measurement: the receipt subtracts two of these. */
604const costNow = async ($: $) => (await $.session.usage().catch(() => null))?.cost?.usd ?? null
605
606async function noteMode($: $, mode: string | undefined) {
607  if (mode) await update($, mainAtom, m => (normalize(DEFAULT_MAIN, m).mode === mode ? normalize(DEFAULT_MAIN, m) : { ...normalize(DEFAULT_MAIN, m), mode }))
608}
609
610/* ── hooks: each passes its event on unchanged ── */
611
612// tool.check carries no loop id; the tool.call around it does, keyed by the call's id.
613const callLoop = new Map<string, string | null>()
614type CallIn = Parameters<Hook<'tool.call'>>[1]
615type CallOut = Awaited<ReturnType<Hook<'tool.call'>>>
616type TurnIn = Parameters<Hook<'turn.complete'>>[1]
617
618/** After a tool call: settle its permission check, note it on its agent's card, log edits, errors and refusals. */
619async function noteCall($: $, e: CallIn, ran: CallOut) {
620  const didRun = ran.deny === undefined
621  // Settle this call's pending ask, if it had one; skip the write (and the redraw) otherwise.
622  const g0 = await getGate($)
623  if (settleCheck(g0, e.tool_use_id, didRun) !== g0) await update($, gateAtom, g => settleCheck(normalizeGate(g), e.tool_use_id, didRun))
624  // A background agent hands its report back through this tool; an architect's report is its advice.
625  if (String(e.tool) === 'SubagentHandback') {
626    const message = (e as unknown as { message?: unknown }).message
627    const a = e.agentId ? await getArch($) : null
628    if (a && e.agentId && a.ids.includes(e.agentId) && typeof message === 'string') {
629      const advice = adviceLine(message)
630      if (advice && advice !== a.lastAdvice) await noteAdvice($, advice)
631    }
632    return
633  }
634  if (e.tool === 'Agent') return
635  const hasFailed = didRun && ran.isError === true
636  const isEdit = !hasFailed && didRun && EDIT_TOOLS.has(e.tool)
637  const t0 = await getTurn($)
638  if (isEdit || hasFailed || (!e.agentId && t0.errorStreak > 0))
639    await update($, turnAtom, t => afterCall(normalize(DEFAULT_TURN, t), { inSubagent: Boolean(e.agentId), hasFailed, isEdit }))
640  const text = shorten(describeInput(e.tool, e), 64)
641  if (e.agentId) {
642    const id = e.agentId
643    await update($, agentsAtom, list =>
644      listOf<unknown>(list)
645        .map(normalizeCard)
646        .map(c => (c.id === id ? noteTool(c, { tool: e.tool, text, isError: hasFailed || ran.deny !== undefined }) : c)),
647    )
648  }
649  // The log keeps what is worth a glance: refusals, errors and edits; the rest is on the cards.
650  if (ran.deny !== undefined) await say($, await whoIs($, e.agentId), `${text}  denied`, 'error', e.agentId ?? null)
651  else if (hasFailed) await say($, await whoIs($, e.agentId), `${text}  ✗`, 'error', e.agentId ?? null)
652  else if (isEdit) await say($, await whoIs($, e.agentId), text, 'info', e.agentId ?? null)
653}
654
655/** In Flight at session start: the first usage reading. A host without usage just starts without it. */
656async function deckStart($: $) {
657  const u = await $.session.usage().catch(() => null)
658  if (u)
659    await update($, usageAtom, x => ({
660      ...normalize(DEFAULT_USAGE, x),
661      pct: u.context.percent ?? null,
662      tokens: u.context.tokens ?? null,
663      window: u.context.window,
664      costUsd: u.cost?.usd ?? null,
665      limits: u.rateLimits.map(r => ({ kind: r.kind, pct: r.percentUsed })),
666    }))
667}
668
669/** In Flight around a tool call: it runs the call, then notes it; nothing after the call may throw into it. */
670async function deckToolCall($: $, e: CallIn, next: (e: CallIn) => Promise<CallOut>): Promise<CallOut> {
671  callLoop.set(e.tool_use_id, e.agentId ?? null)
672  const ran = await next(e).finally(() => callLoop.delete(e.tool_use_id))
673  await noteCall($, e, ran).catch(() => undefined)
674  return ran
675}
676
677/** In Flight after a turn, the main loop's or an agent's: the receipt, or the agent's card done. */
678async function deckTurnDone($: $, e: TurnIn) {
679  const id = e.agentId
680  const now = await $.clock.now()
681  if (!id) {
682    const [t, cards, cost] = await Promise.all([getTurn($), getCards($), costNow($)])
683    const r = receiptOf(t, { durationMs: e.durationMs, agentsSince: cards.filter(c => c.spawnedAt >= t.startedAt).length, costNow: cost, reason: e.reason })
684    await update($, receiptAtom, () => r)
685    await update($, mainAtom, m => ({ ...normalize(DEFAULT_MAIN, m), isRunning: false }))
686    return
687  }
688  if ((await getArch($)).ids.includes(id)) {
689    await consultEnded($, e.answer, id)
690    return
691  }
692  const cards = await getCards($)
693  if (cards.some(c => c.id === id)) {
694    const status = e.reason === 'answer' ? 'done' : e.reason === 'aborted' ? 'stopped' : 'failed'
695    await update($, agentsAtom, list =>
696      listOf<unknown>(list)
697        .map(normalizeCard)
698        .map(c => (c.id === id ? { ...c, status, endedAt: now, answer: shorten(e.answer, 400) } : c)),
699    )
700    const card = cards.find(c => c.id === id)
701    await say($, await whoIs($, id), status === 'done' ? `done · ${card ? fmtDuration(now - card.spawnedAt) : ''}` : status, status === 'done' ? 'done' : 'error', id)
702  } else {
703    await update($, loopsAtom, l => listOf<DeckLoop>(l).map(x => (x.id === id ? { ...x, isDone: true, lastAt: now } : x)))
704  }
705}
706
707// The desktop app follows macOS appearance, but mods only see Claude Code's `theme` setting.
708// Keeping it on light or dark to match lets skins and the pane redraw for the right background.
709async function syncAppearance($: EngineInterface): Promise<void> {
710  const { stdout } = await $.process.run(['defaults', 'read', '-g', 'AppleInterfaceStyle'], { timeoutMs: 5000 })
711  const current = (await $.config.list()).find(row => row.key === 'theme')?.value
712  const want = themeFor(current, stdout)
713
714  if (current !== want) {
715    await $.config.set({ key: 'theme', value: want })
716    // Skins re-reads the theme inside that set and still sees the old one; setting it again
717    // a moment later makes it read the new one.
718    await $.clock.sleep(1000)
719    await $.config.set({ key: 'theme', value: want })
720  }
721}
722
723// The first sync fails off macOS (no `defaults`), and then nothing keeps checking.
724async function followAppearance($: EngineInterface): Promise<void> {
725  await syncAppearance($)
726  $.clock.every(5000, () => quiet(syncAppearance($)))
727}
728
729export const register: Register = (on, options) => {
730  settings.plansDir = plansDirName(options.plans_dir)
731  settings.openPane = options.open_pane !== 'off'
732  settings.band = options.band !== 'off'
733  settings.followMacos = options.follow_macos !== 'off'
734
735  // In Flight: the events only it watches. session.start, tool.call and turn.complete go through the Workbench's own hooks.
736  on('session.end', async ($, e, next) => {
737    if (e.reason === 'clear') await resetDeck($)
738    return next(e)
739  })
740
741  on('classic.UserPromptSubmit', async ($, e, next) => {
742    await noteMode($, e.permission_mode)
743    return next(e)
744  })
745
746  on('agent.offer', async ($, e, next) => {
747    const offered = await next(e)
748    if (ARCHITECT.test(e.agent))
749      await update($, rosterAtom, r => {
750        const x = { architectTypes: listOf<string>(normalize(DEFAULT_ROSTER, r).architectTypes) }
751        return x.architectTypes.includes(e.agent) ? x : { architectTypes: [...x.architectTypes, e.agent].slice(-20) }
752      })
753    return offered
754  })
755
756  on('turn.start', async ($, e, next) => {
757    const [now, cost] = await Promise.all([$.clock.now(), costNow($)])
758    await update($, turnAtom, () => ({ ...DEFAULT_TURN, startedAt: now, costAtStart: cost }))
759    await update($, mainAtom, m => ({ ...normalize(DEFAULT_MAIN, m), isRunning: true }))
760    // A background architect's report reaches the main loop as the text opening this turn. The
761    // SubagentHandback tool call (in tool.call) normally carries it first; this is the fallback.
762    const back = e.text ? handbackOf(e.text) : null
763    const a = back ? await getArch($) : null
764    if (back && a && a.ids.includes(back.from)) {
765      const advice = adviceLine(back.body)
766      if (advice && advice !== a.lastAdvice) await noteAdvice($, advice)
767    } else if (e.text) {
768      const p = promptLine(e.text)
769      await say($, p.who, p.text)
770    }
771    return next(e)
772  })
773
774  on('turn.step', async function* ($, e, next) {
775    // The main loop's model is known when its request starts; a long first request shouldn't read "-".
776    if (!e.agentId) {
777      await update($, mainAtom, m => {
778        const x = normalize(DEFAULT_MAIN, m)
779        return { ...x, model: e.model, effort: String(e.effort ?? x.effort), steps: x.steps + 1 }
780      })
781      return yield* next(e)
782    }
783    const result = yield* next(e)
784    const id = e.agentId
785    const [cards, a] = await Promise.all([getCards($), getArch($)])
786    if (cards.some(c => c.id === id)) {
787      const step = { model: e.model, usage: result.usage, stopReason: result.stopReason }
788      await update($, agentsAtom, list => listOf<unknown>(list).map(normalizeCard).map(c => (c.id === id ? applyStep(c, step) : c)))
789      if (result.stopReason === 'max_tokens') await say($, await whoIs($, id), 'hit max_tokens', 'error', id)
790    } else if (!a.ids.includes(id)) {
791      const now = await $.clock.now()
792      await update($, loopsAtom, l => stepLoop(listOf<DeckLoop>(l), id, now))
793    }
794    return result
795  })
796
797  on('session.measure', async ($, e, next) => {
798    await update($, usageAtom, x => ({
799      ...normalize(DEFAULT_USAGE, x),
800      pct: e.context.percent ?? null,
801      tokens: e.context.tokens ?? null,
802      window: e.context.window,
803      costUsd: e.cost?.usd ?? null,
804      limits: e.rateLimits.map(r => ({ kind: r.kind, pct: r.percentUsed })),
805    }))
806    return next(e)
807  })
808
809  on('session.compact', async ($, e, next) => {
810    const done = await next(e)
811    if (!e.agentId && e.trigger !== 'precompute') {
812      const now = await $.clock.now()
813      await update($, usageAtom, x => {
814        const u = normalize(DEFAULT_USAGE, x)
815        return { ...u, compactions: u.compactions + 1, lastCompactAt: now }
816      })
817      await say($, 'main', `context compacted (${e.trigger})`)
818    }
819    return done
820  })
821
822  on('tool.check', async ($, e, next) => {
823    const verdict = await next(e)
824    if (e.tool_use_id) {
825      const check: DeckCheck = {
826        id: e.tool_use_id,
827        tool: e.tool,
828        bucket: bucketOf(e.tool),
829        verdict: verdict.decision === 'allow' ? 'rule' : verdict.decision,
830        inSubagent: Boolean(callLoop.get(e.tool_use_id)),
831        detail: shorten(describeInput(e.tool, e.input), 90),
832        at: await $.clock.now(),
833      }
834      await update($, gateAtom, g => recordCheck(normalizeGate(g), check))
835      if (verdict.decision === 'deny') await say($, 'gate', `denied by rule · ${check.detail}`, 'error')
836    }
837    return verdict
838  })
839
840  // A server-side review tool never reaches tool.call: it shows only in the assistant's rows.
841  on('session.append', async ($, e, next) => {
842    if (!e.agentId && e.message.type === 'assistant') {
843      const a = await getArch($)
844      // Consults this row opened: their result may be in the same row, after the stale read above.
845      const opened = new Set<string>()
846      for (const block of e.message.content as unknown as readonly ServerBlock[]) {
847        if (block.type === 'server_tool_use' && block.name && block.id && ARCHITECT.test(block.name)) {
848          if (a.seen.includes(block.id)) continue
849          const id = block.id
850          await update($, archAtom, x => {
851            const y = normalize(DEFAULT_ARCHITECT, x)
852            return { ...y, seen: [...listOf<string>(y.seen), id].slice(-60) }
853          })
854          opened.add(id)
855          await consultStarted($, id, `${block.name} tool`)
856        } else if (block.type.endsWith('_tool_result') && block.tool_use_id) {
857          const id = block.tool_use_id
858          const isOpen = opened.has(id) || (await getArch($)).consults.some(c => c.id === id && c.endAt === null)
859          if (isOpen) await consultEnded($, null, id)
860        }
861      }
862    }
863    return next(e)
864  })
865
866  on('agent.spawn', async ($, e, next) => {
867    const started = await next(e)
868    if (!e.parentAgentId) await noteMode($, e.permissionMode)
869    if (started.deny !== undefined || !started.agentId) return started
870    const id = started.agentId
871    if (await isArchitectType($, e.subagentType)) {
872      await update($, archAtom, a => {
873        const x = normalize(DEFAULT_ARCHITECT, a)
874        return { ...x, ids: [...listOf<string>(x.ids), id].slice(-40) }
875      })
876      await update($, loopsAtom, l => listOf<DeckLoop>(l).filter(x => x.id !== id))
877      await consultStarted($, id, e.subagentType.split(':').pop() ?? 'agent')
878      return started
879    }
880    const card: DeckAgent = { ...normalizeCard({}), id, type: e.name ?? e.subagentType, model: started.model, description: e.description, spawnedAt: await $.clock.now() }
881    await update($, agentsAtom, list => [...listOf<unknown>(list).map(normalizeCard), card].slice(-24))
882    await update($, loopsAtom, l => listOf<DeckLoop>(l).filter(x => x.id !== id))
883    await say($, shorten(cardTitle(card), 12), `spawned · ${card.type}`, 'info', id)
884    return started
885  })
886
887
888  on('session.start', async ($, e, next) => {
889    await $.command.register({
890      name: 'task',
891      description: 'The current task from the plans folder, its work items and details. /task new <title> starts one, /task <n> shows an item',
892      argumentHint: '[new <title> | <n> | start|done|reopen <n> | approve [n] | add <stage>: <title> -- <details> | break | pane]',
893    })
894    await $.tool.register({
895      name: TOOL,
896      description:
897        'Reads and updates tasks and their work items: one markdown plan file per task in the plans folder at the project root. ' +
898        'action "create" starts a task (title, optional date YYYY-MM-DD); "list" shows the task and its numbered items; "add" adds items; "status" sets item n to todo, doing or done; ' +
899        '"edit" changes item n\'s title, details or stage. ' +
900        `Titles are short labels of 2 to 5 words (at most ${ROW_CHARS} characters, refused past ${TITLE_MAX}), never sentences; ` +
901        'put the explanation in details. Mark an item doing when you start it and done when it is finished. ' +
902        'You may also edit the plan file directly: "- [ ] Title `stage`" with the details indented below; [~] in progress, [x] done, [?] draft.',
903      inputSchema: {
904        type: 'object',
905        properties: {
906          action: { type: 'string', enum: ['create', 'list', 'add', 'status', 'edit'] },
907          task: { type: 'string', description: 'Task key; defaults to the current task' },
908          items: {
909            type: 'array',
910            description: 'For add',
911            items: {
912              type: 'object',
913              properties: {
914                title: { type: 'string', maxLength: TITLE_MAX, description: 'Short label, 2 to 5 words, e.g. "Auth screen"' },
915                stage: { type: 'string', enum: STAGES },
916                details: { type: 'string', description: 'What to do and when it counts as done, 1 to 2 sentences' },
917              },
918              required: ['title', 'stage'],
919            },
920          },
921          draft: { type: 'boolean', description: 'For add: true marks items for the person to approve (default true)' },
922          n: { type: 'number', description: 'For status and edit: item number from list, 1-based' },
923          status: { type: 'string', enum: ['todo', 'doing', 'done'] },
924          title: { type: 'string', description: 'For create: the task title. For edit: the item title (a short label)' },
925          date: { type: 'string', description: 'For create: the day it starts, YYYY-MM-DD; today when absent' },
926          details: { type: 'string', description: 'For edit' },
927          stage: { type: 'string', enum: STAGES, description: 'For edit' },
928        },
929        required: ['action'],
930      },
931      isDeferred: false,
932    })
933    const r = await next(e)
934    void $.ui.status(undefined)
935    void quiet(deckStart($))
936    void startWorkbench($)
937    if (settings.followMacos) void quiet(followAppearance($))
938    void quiet(watchSessions($))
939    void refresh($)
940    return r
941  })
942
943  // `task` is registered at start; `workbench:task` is commands/task.md, which the app lists before a session starts.
944  on('turn.complete', afterTurn)
945
946  on('command.run', { command: 'task' }, taskCommand)
947  on('command.run', { command: 'workbench:task' }, taskCommand)
948
949  on('tool.call', { tool: TOOL_FULL }, async ($, e) => {
950    const input = e as unknown as {
951      action: 'create' | 'list' | 'add' | 'status' | 'edit'
952      date?: string
953      task?: string
954      items?: { title: string; stage: string; details?: string }[]
955      draft?: boolean
956      n?: number
957      status?: 'todo' | 'doing' | 'done'
958      title?: string
959      details?: string
960      stage?: string
961    }
962    if (input.action === 'create') return { result: await createTask($, input.title ?? '', input.date) }
963    let snap = await read($, snapAtom)
964    if (snap.status !== 'ready') snap = await refresh($)
965    if (snap.status !== 'ready') return { result: snap.status === 'none' ? NONE : 'Plans unavailable: ' + snap.message }
966    const pool = [snap.cur, ...snap.next, ...snap.prev].filter(Boolean) as Group[]
967    const g = input.task ? pool.find(x => x.key === input.task) : snap.cur
968    if (!g) return { result: `No task ${input.task ?? '(current)'} here. Tasks: ${pool.map(x => `${x.key} ${x.title}`).join('; ')}` }
969    const tooLong = (t?: string) => !!t && t.trim().length > TITLE_MAX
970
971    if (input.action === 'list') {
972      const lines = g.items.map((i, k) => `${k + 1}. ${box(i.status)} ${i.stage}: ${i.title}${i.details ? `\n   ${i.details}` : ''}`)
973      const head = `${g.key} · ${g.title} (${g.short}, ${when(g)})\nPlan file: ${g.file ?? '(none)'}\nStages: ${g.stages.join(', ') || 'none'}`
974      return { result: g.items.length ? `${head}\n${lines.join('\n')}` : `${head}\nNo work items yet: break the task down with action "add".` }
975    }
976    if (input.action === 'add') {
977      const add = (input.items ?? []).filter(i => i.title?.trim() && STAGES.includes(i.stage))
978      if (!add.length) return { result: 'Nothing to add: give items as {title, stage, details}.' }
979      const long = add.filter(i => tooLong(i.title))
980      if (long.length)
981        return { result: `Not saved. These titles are sentences, not labels: ${long.map(i => `"${i.title}"`).join(', ')}. Use 2 to 5 words (at most ${ROW_CHARS} characters) and move the rest to details.` }
982      const status: WorkItem['status'] = input.draft === false ? 'todo' : 'draft'
983      const made = add.map(i => ({ id: newId(), title: i.title.trim(), stage: i.stage, status, ...(i.details?.trim() ? { details: i.details.trim() } : {}) }))
984      const msg = await writeEntry($, g.key, x => ({ ...x, items: [...x.items, ...made] }))
985      return { result: `${msg}: ${add.length} item(s) on "${g.title}"${status === 'draft' ? ' as drafts for the person to approve' : ''}.` }
986    }
987    const it = g.items[(input.n ?? 0) - 1]
988    if (!it) return { result: 'Give n, the item number from list (1-based).' }
989    if (input.action === 'edit') {
990      if (tooLong(input.title)) return { result: `Not saved: the title is a sentence. Use 2 to 5 words and put the rest in details.` }
991      if (input.stage && !STAGES.includes(input.stage)) return { result: `Stage is one of ${STAGES.join(', ')}.` }
992      const patch: Partial<WorkItem> = {
993        ...(input.title?.trim() ? { title: input.title.trim() } : {}),
994        ...(input.details !== undefined ? { details: input.details.trim() || undefined } : {}),
995        ...(input.stage ? { stage: input.stage } : {}),
996      }
997      if (!Object.keys(patch).length) return { result: 'Give title, details or stage to change.' }
998      const msg = await writeEntry($, g.key, x => ({ ...x, items: x.items.map(i => (i.id === it.id ? { ...i, ...patch } : i)) }))
999      return { result: `${msg}: ${patch.title ?? it.title}` }
1000    }
1001    if (!input.status) return { result: 'Give status: todo, doing or done.' }
1002    const msg = await writeEntry($, g.key, x => ({ ...x, items: x.items.map(i => (i.id === it.id ? { ...i, status: input.status! } : i)) }))
1003    return { result: `${msg}: ${it.title} → ${input.status}` }
1004  }).catch(() => ({ result: 'Workbench could not read or write the plan files. Try /task refresh.' }))
1005
1006  /* ── band above the prompt: line 1 the task, line 2 the bar ── */
1007
1008  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1009    const snap = await read($, snapAtom)
1010    if (!settings.band || e.props.hasSurvey) return next(e)
1011    if (snap.status !== 'ready' || !snap.cur) {
1012      // No current task here (no plans folder, as at a workspace root): the band only offers the pane while it is
1013      // closed, since it has no chevron to fall back on otherwise.
1014      if ((await $.ui.panes()).some(p => p.id === PANE)) return next(e)
1015      const { Box, Text, Button } = $.ui.resolve(e)
1016      return (
1017        <Box flexDirection="row" alignItems="center" columnGap={1}>
1018          <Text dimColor>Workbench</Text>
1019          <Button key="band-open" plain label="❯" onPress={() => void openPane($)} />
1020        </Box>
1021      )
1022    }
1023    await read($, uiAtom)
1024    const els = $.ui.resolve(e)
1025    const { Box, Text, Button } = els
1026    const cur = snap.cur
1027    const n = byStatus(cur.items)
1028    const bar = barIn(cur)
1029    const now = inHand(cur)
1030    const isUp = (await $.ui.panes()).some(p => p.id === PANE)
1031    const dot = bar.finished ? DONE : n.doing ? DOING : cur.items.length ? ACCENT : MUTED
1032    const chevron = <Button key="band-chev" plain label={isUp ? '❮' : '❯'} onPress={() => void togglePane($)} />
1033
1034    if (e.surface === 'desktop' && 'Svg' in els) {
1035      const { Svg } = els
1036      // About 8 CSS px a column; the rest is the chevron and its gap. A row wider than the slot wraps.
1037      const W = Math.max(180, Math.min(1600, (e.props.bodyColumns || 100) * 8 - 64))
1038      return (
1039        <Box flexDirection="column">
1040          <Box flexDirection="row" alignItems="center" gap={1}>
1041            <Svg key="band-title" width={W} height={20} alt={`${cur.short}: ${cur.title}${now ? `, now ${now.title}` : ''}`} source={bandTitleSvg(W, dot, cur.short, cur.title, now?.title)} />
1042            {chevron}
1043          </Box>
1044          <Svg key="band-bar" width={W} height={20} alt={`${bar.pill}, ${bar.total ? Math.round((bar.done / bar.total) * 100) : 0}% done`} source={bandBarSvg(W, bar)} />
1045        </Box>
1046      )
1047    }
1048
1049    const cols = e.props.bodyColumns ?? e.viewport?.columns ?? 80
1050    const width = Math.max(8, Math.min(48, cols - bar.pill.length - 10))
1051    const filled = bar.total ? Math.round((width * bar.done) / bar.total) : 0
1052    const running = bar.total ? Math.min(width - filled, Math.round((width * bar.doing) / bar.total)) : 0
1053    const pct = `${bar.total ? Math.round((bar.done / bar.total) * 100) : 0}%`
1054    return (
1055      <Box flexDirection="column">
1056        <Box flexDirection="row" columnGap={1} flexWrap="nowrap">
1057          <Text color={dot}>●</Text>
1058          <Text dimColor>{cur.short}</Text>
1059          <Box flexGrow={1} flexShrink={1} minWidth={0}>
1060            <Text bold wrap="truncate-end">
1061              {cur.title}
1062              {now ? <Text dimColor bold={false}>{`  now · ${now.title}`}</Text> : ''}
1063            </Text>
1064          </Box>
1065          {chevron}
1066        </Box>
1067        <Box flexDirection="row" columnGap={1}>
1068          <Text>
1069            <Text color={bar.finished ? DONE : ACCENT}>{'█'.repeat(filled)}</Text>
1070            <Text color={ACCENT} dimColor>{'▓'.repeat(running)}</Text>
1071            <Text dimColor>{'░'.repeat(Math.max(0, width - filled - running))}</Text>
1072          </Text>
1073          <Text color={bar.finished ? DONE : ACCENT} bold>{bar.pill}</Text>
1074          <Text dimColor>{pct}</Text>
1075        </Box>
1076      </Box>
1077    )
1078  })
1079
1080  /* ── side pane: the Workbench ── */
1081
1082  // A prompt starts a turn: Right now shows Claude working until the turn ends.
1083  on('prompt.submit', async ($, e, next) => {
1084    const r = await next(e)
1085    if (settings.openPane && !paneSeen && !paneRetried) {
1086      paneRetried = true
1087      if (!(await $.ui.panes()).some(p => p.id === PANE)) void quiet(openPane($))
1088    }
1089    await quiet(update($, activityAtom, () => ({ busy: true, since: Date.now() })))
1090    return r
1091  }).catch(($, e, next) => next(e))
1092
1093  // What Claude reads and edits, for "Right now" and "Claude touched"; commands and searches for "Right now".
1094  // Every call also runs through In Flight, which settles its permission check and logs edits and errors.
1095  on('tool.call', async ($, e, next) => {
1096    const kind = FILE_TOOLS[e.tool]
1097    const args = e as unknown as { file_path?: unknown; notebook_path?: unknown; command?: unknown; description?: unknown; pattern?: unknown }
1098    const raw = args.file_path ?? args.notebook_path
1099    if (!kind || typeof raw !== 'string') {
1100      const text = (v: unknown) => (typeof v === 'string' ? v.split('\n')[0]!.trim() : '')
1101      const act: Activity =
1102        e.tool === 'Bash' ? { busy: true, kind: 'run', label: text(args.description) || text(args.command) }
1103        : (e.tool as string) === 'Grep' || (e.tool as string) === 'Glob' ? { busy: true, kind: 'search', label: text(args.pattern) } // where the build has them
1104        : { busy: true }
1105      await quiet(update($, activityAtom, a => (act.kind ? { ...act, since: a.since } : { ...a, busy: true })))
1106      return deckToolCall($, e, next)
1107    }
1108    const path = absOf(raw, (await quiet($.session.cwd())) ?? '')
1109    await quiet(update($, activityAtom, a => ({ busy: true, kind, path, since: a.since })))
1110    await quiet(update($, touchedAtom, l => addTouch(l, { path, kind, active: true, at: Date.now() })))
1111    try {
1112      return await deckToolCall($, e, next)
1113    } finally {
1114      await quiet(update($, touchedAtom, l => addTouch(l, { path, kind, active: false, at: Date.now() })))
1115      if (kind === 'edited') {
1116        void quiet(refreshGit($))
1117        const f = await quiet(read($, filesAtom))
1118        if (f?.dirs[parentOf(path)]) void quiet(loadDirs($, [parentOf(path)]))
1119      }
1120    }
1121  }).catch(($, e, next) => next(e)) // never in the way of a tool call
1122
1123  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1124    paneSeen = true
1125    const els = $.ui.resolve(e)
1126    const { Box, Text, Button } = els
1127    const Input = 'Input' in els ? els.Input : undefined
1128    const cols = Math.max(28, e.props?.bodyColumns || 44)
1129    const pal = await paletteNow($)
1130    const snap = await read($, snapAtom)
1131    const ui = await read($, benchAtom)
1132    const files = await read($, filesAtom)
1133    const git = await read($, gitAtom)
1134    const touched = await read($, touchedAtom)
1135    const activity = await read($, activityAtom)
1136    const open = sectionsOf(ui.sections)
1137
1138    // Text in a skin color; with no skin, Claude Code's theme color for the slot (it follows light and dark).
1139    const c = (slot: Slot) => (pal.themed ? { color: pal[slot] } : THEME_KEY[slot] ? { color: THEME_KEY[slot] } : slot === 'muted' ? { dimColor: true } : {})
1140    // Desktop draws Lucide icons, caps labels and pills as SVG; the terminal gets text and glyphs.
1141    const Svg = e.surface === 'desktop' && 'Svg' in els ? els.Svg : undefined
1142    // A drawing's color: the skin's, or with no skin a light and dark pair.
1143    const ink = (slot: Slot): Ink => inkOf(pal, slot)
1144    const mutedInk = ink('muted')
1145    // Room inside `depth` nested cards, in px (about 8 a column; each card takes its border and padding).
1146    const room = (depth: number) => Math.max(140, cols * 8 - 24 - depth * 56)
1147    const capsText = (key: string, text: string, slot: Slot = 'muted', size = 12) => {
1148      if (!Svg) return <Text key={key} bold {...c(slot)}>{text.toUpperCase()}</Text>
1149      const l = caps(text, ink(slot), size)
1150      return <Svg key={key} width={l.w} height={l.h} alt={text} source={l.source} />
1151    }
1152    const label = (key: string, text: string, right?: string) => (
1153      <Box key={key} flexDirection="row" justifyContent="space-between" alignItems="center" marginTop={1} width="100%">
1154        {capsText(key + '-l', text)}
1155        {right ? capsText(key + '-r', right) : null}
1156      </Box>
1157    )
1158    // A tinted card (Current task, Right now) takes the app's message surface, which follows light and dark.
1159    const card = (key: string, kids: unknown[], marginTop = 0, tinted = false) => (
1160      <Box key={key} flexDirection="column" alignItems="stretch" width="100%" marginTop={marginTop} backgroundColor={tinted ? 'userMessageBackground' : undefined} borderStyle="round" borderColor={pal.themed ? pal.muted : undefined} borderDimColor={!pal.themed} paddingX={2} paddingY={1}>
1161        {kids as never}
1162      </Box>
1163    )
1164    const dot = (key: string, slot: Slot) => <Text key={key} {...c(slot)}>●</Text>
1165
1166    /* ── box 1: task management ── */
1167
1168    const ico = (key: string, name: IconName, color: Ink, size = 16) => (Svg ? <Svg key={key} width={size} height={size} alt={name} source={icon(name, color, size)} /> : null)
1169    const divider = (key: string) =>
1170      Svg ? (
1171        <Box key={key} marginY={1} width="100%"><Svg height={9} alt="divider" source={rule(mutedInk)} /></Box>
1172      ) : (
1173        <Text key={key} {...c('muted')} wrap="truncate-end">{'─'.repeat(200)}</Text>
1174      )
1175
1176    const task: unknown[] = []
1177    const cur = snap.cur
1178    if (snap.status === 'idle' || snap.status === 'loading') task.push(<Text key="t-wait" {...c('muted')}>Reading plans…</Text>)
1179    else if (snap.status === 'none') task.push(<Text key="t-none" {...c('muted')}>{'No tasks here yet. /task new <title> starts one.'}</Text>)
1180    else if (snap.status === 'error') task.push(<Text key="t-err" {...c('err')}>{`Plans unavailable: ${snap.message ?? ''}`}</Text>)
1181    else if (!cur) task.push(<Text key="t-free" {...c('muted')}>No open tasks here.</Text>)
1182    else {
1183      const done = cur.items.filter(i => i.status === 'done').length
1184      const doing = cur.items.filter(i => i.status === 'doing')
1185      const total = cur.items.length
1186      const pct = total ? Math.round((done / total) * 100) : 0
1187      // The bar takes the row less its text (about 7 px a character) and a gap.
1188      const tail = `${pct}% · ${total ? `${done} of ${total} done` : 'not broken down'}`
1189      const barW = Math.max(60, room(2) - tail.length * 7 - 12)
1190      const when = cur.start === cur.end ? shortDate(cur.start) : `${shortDate(cur.start)} → ${shortDate(cur.end)}`
1191      // Each stage in its own color, the one the band's bar takes while that stage is current.
1192      const stageTag = (key: string, stage: string) => <Text key={key} color={STAGE_COLOR[stage] ?? MUTED}>{stage}</Text>
1193      const STATUS_ICON = { draft: 'square-dashed', todo: 'square', doing: 'square-dot', done: 'square-check' } as const
1194      const statusInk = (s: WorkItem['status']) => ink(s === 'done' ? 'ok' : s === 'doing' ? 'write' : 'muted')
1195      // The status square: a Lucide icon with a press over it; a glyph on the terminal.
1196      const square = (it: WorkItem) => {
1197        const press = () => setStatus($, cur.key, it.id, nextStatus(it.status))
1198        if (!Svg) return <Button key={'sq-' + it.id} plain label={GLYPH[it.status]} onPress={press} />
1199        return (
1200          <Box key={'sq-' + it.id} width={2} height={1} flexShrink={0} justifyContent="center" alignItems="center">
hooks/draw.ts 117 lines
1/* Desktop drawings. The desktop has no font sizes and wraps sibling elements,
2 * so anything with small type or several parts on one line is one SVG.
3 * Every Svg needs a non-empty alt: the desktop drops one whose alt is empty. */
4
5export const ACCENT = '#8f8cf4'
6export const DONE = '#5fbf8f'
7export const DOING = '#BA7517'
8export const MUTED = '#888780'
9/** Each work item stage's color: the pane's stage tags and the band's bar while that stage is current. */
10export const STAGE_COLOR: Record<string, string> = { spec: '#7F77DD', design: '#D4537E', build: '#378ADD', track: '#1D9E75', test: '#BA7517', ship: '#639922' }
11
12export const FONT = "-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',sans-serif"
13const CSS = `<style>
14.t{fill:#1f1f1f}.m{fill:#8a8a8a}.k{fill:#e4e4e2}.tk{fill:#b4b4b0}.bg{fill:#f0eee6}.k2{fill:#dfdcd2}
15@media (prefers-color-scheme: dark){.t{fill:#ececec}.m{fill:#9a9a9a}.k{fill:#2c2c2c}.tk{fill:#5a5a5a}.bg{fill:#30302e}.k2{fill:#454542}}
16</style>`
17
18const svg = (W: number, H: number, body: string) =>
19  `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">${CSS}${body}</svg>`
20
21export const xml = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] ?? c)
22
23/** Rough advance of system UI text, in em (as savvy-progress measures). */
24const charEm = (ch: string) => (/[\s.,:;'|!il1()[\]]/.test(ch) ? 0.3 : /[A-Z@%mw]/.test(ch) ? 0.72 : 0.56)
25export const textWidth = (s: string, size: number) => [...s].reduce((w, ch) => w + charEm(ch) * size, 0)
26
27export function fitText(s: string, size: number, maxW: number) {
28  if (textWidth(s, size) <= maxW) return s
29  let out = ''
30  for (const ch of s) {
31    if (textWidth(out + ch + '…', size) > maxW) break
32    out += ch
33  }
34  return out.trimEnd() + '…'
35}
36
37/** Deterministic noise so the dither does not shimmer between redraws. */
38const noise = (x: number, y: number) => {
39  const s = Math.sin(x * 12.9898 + y * 78.233) * 43758.5453
40  return s - Math.floor(s)
41}
42
43export type BarIn = { done: number; doing: number; total: number; pill: string; finished: boolean; color?: string }
44
45/** savvy-flow's bar: dithered fill, a faint layer for work in progress, step ticks, a pill at the head. */
46function barG(x: number, y: number, W: number, H: number, b: BarIn, id: string, track = 'k') {
47  const CELL = 3
48  const color = b.finished ? DONE : (b.color ?? ACCENT)
49  const fillW = b.total ? Math.round((W * b.done) / b.total) : 0
50  const runW = b.total ? Math.round((W * Math.min(b.total, b.done + b.doing)) / b.total) : 0
51  const rows = Math.floor(H / CELL)
52  const dots: string[] = []
53  const cols = Math.floor(fillW / CELL)
54  for (let c = 0; c < cols; c++) {
55    const density = 0.35 + 0.6 * Math.pow(c / Math.max(1, cols), 1.2)
56    for (let r = 0; r < rows; r++) if (noise(c, r) < density) dots.push(`<rect x="${c * CELL + 1}" y="${r * CELL + 1}" width="2" height="2"/>`)
57  }
58  const faint: string[] = []
59  for (let c = cols; c < Math.floor(runW / CELL); c++)
60    for (let r = 0; r < rows; r++) if (noise(c + 7, r + 3) < 0.25) faint.push(`<rect x="${c * CELL + 1}" y="${r * CELL + 1}" width="1.7" height="1.7"/>`)
61  const ticks: string[] = []
62  for (let i = 1; i < b.total; i++) {
63    const tx = Math.round((W * i) / b.total)
64    if (tx > fillW + 4) ticks.push(`<rect x="${tx}" y="${H / 2 - 3}" width="1.5" height="6" rx="0.75"/>`)
65  }
66  const pillSize = H >= 16 ? 11 : 9.5
67  const pillW = Math.round(textWidth(b.pill, pillSize) + 16)
68  const pillX = Math.max(0, Math.min(W - pillW, fillW - pillW))
69  return `<defs><clipPath id="${id}"><rect width="${W}" height="${H}" rx="${H / 2}"/></clipPath></defs>
70<g transform="translate(${x},${y})">
71<rect class="${track}" width="${W}" height="${H}" rx="${H / 2}"/>
72<g clip-path="url(#${id})"><g fill="${color}">${dots.join('')}</g><g fill="${color}" opacity="0.45">${faint.join('')}</g><g class="tk">${ticks.join('')}</g></g>
73<rect x="${pillX}" width="${pillW}" height="${H}" rx="${H / 2}" fill="${color}"/>
74<text x="${pillX + pillW / 2}" y="${H / 2 + pillSize * 0.36}" text-anchor="middle" font-family="${FONT}" font-size="${pillSize}" font-weight="600" fill="#ffffff">${xml(b.pill)}</text>
75</g>`
76}
77
78const pct = (b: BarIn) => `${b.total ? Math.round((b.done / b.total) * 100) : 0}%`
79
80/** Band line 2: the bar and the percent, no count. */
81export function bandBarSvg(W: number, b: BarIn) {
82  const H = 20
83  const BAR_H = 16
84  const barW = Math.max(60, W - 44)
85  return svg(
86    W,
87    H,
88    `${barG(0, (H - BAR_H) / 2, barW, BAR_H, b, 'bb')}
89<text class="m" x="${W}" y="${H / 2 + 4.5}" text-anchor="end" font-family="${FONT}" font-size="12.5" font-variant-numeric="tabular-nums">${pct(b)}</text>`,
90  )
91}
92
93/** The pane's bar alone, the band's look; the pane puts its percent and count beside it as text. */
94export function paneBarSvg(W: number, b: BarIn) {
95  const H = 16
96  return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">${CSS}${barG(0, 0, W, H, b, 'pb')}</svg>`
97}
98
99/** Band line 1: status dot, project, task title, the item in hand. */
100export function bandTitleSvg(W: number, dot: string, short: string, title: string, now?: string) {
101  const H = 20
102  const y = H / 2 + 4.5
103  const tx = 16 + textWidth(short, 11.5) + 10
104  const nowLabel = now ? `now · ${now}` : ''
105  const nowMax = now ? Math.min(textWidth(nowLabel, 12), W * 0.38) : 0
106  const t = fitText(title, 13, Math.max(40, W - tx - (now ? nowMax + 18 : 0)))
107  const nx = tx + textWidth(t, 13) + 14
108  return svg(
109    W,
110    H,
111    `<circle cx="5" cy="${H / 2}" r="4" fill="${dot}"/>
112<text class="m" x="16" y="${y - 0.5}" font-family="${FONT}" font-size="11.5" font-weight="500" letter-spacing="0.3">${xml(short)}</text>
113<text class="t" x="${tx}" y="${y}" font-family="${FONT}" font-size="13" font-weight="600">${xml(t)}</text>
114${now ? `<text class="m" x="${nx}" y="${y}" font-family="${FONT}" font-size="12">${xml(fitText(nowLabel, 12, Math.max(30, W - nx)))}</text>` : ''}`,
115  )
116}
117
hooks/logic.ts 66 lines
1import type { DevEntry, WorkItem } from '../types'
2
3export const STAGES = ['spec', 'design', 'build', 'track', 'test', 'ship']
4
5export const counts = (items: WorkItem[]) => {
6  const real = items.filter(i => i.status !== 'draft')
7  return { done: real.filter(i => i.status === 'done').length, total: real.length, drafts: items.length - real.length }
8}
9
10export const nextStatus = (s: WorkItem['status']): WorkItem['status'] =>
11  ({ draft: 'todo', todo: 'doing', doing: 'done', done: 'todo' } as const)[s]
12
13export const newId = () => 'w' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5)
14
15/** Keeps stages in canonical order and adds any the items use. */
16export function withStages(entry: DevEntry, extra: string[] = []): DevEntry {
17  const want = new Set([...entry.stages, ...extra, ...entry.items.map(i => i.stage)])
18  return { ...entry, stages: STAGES.filter(s => want.has(s)) }
19}
20
21/** `/task add build: Create monorepo -- pnpm workspaces` gives stage, title and optional details. */
22export function parseAdd(text: string, fallback: string): { stage: string; title: string; details?: string } {
23  const m = text.match(/^\s*(\w+)\s*:\s*(.+)$/)
24  const st = m?.[1]?.toLowerCase()
25  const isStage = !!(m && st && STAGES.includes(st))
26  const stage = isStage ? st! : fallback
27  const body = (isStage ? m![2] ?? '' : text).trim()
28  const [title = '', ...rest] = body.split(/\s+(?:—|--)\s+/)
29  const details = rest.join(' -- ').trim()
30  return details ? { stage, title: title.trim(), details } : { stage, title: title.trim() }
31}
32
33/** Titles are labels, not sentences: the tool refuses longer ones. */
34export const TITLE_MAX = 40
35
36/** The item the pane details and the band names: the one picked, else in progress, else the next to do. */
37export function activeItem(items: WorkItem[], selected?: string): WorkItem | undefined {
38  return (
39    items.find(i => i.id === selected) ??
40    items.find(i => i.status === 'doing') ??
41    items.find(i => i.status === 'todo') ??
42    items.find(i => i.status === 'draft')
43  )
44}
45
46export const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1).replace(/[\uD800-\uDBFF]$/, '').trimEnd() + '…' : s)
47
48export const byStatus = (items: WorkItem[]) => {
49  const n = { draft: 0, todo: 0, doing: 0, done: 0 }
50  for (const i of items) n[i.status]++
51  return n
52}
53
54export function localDate(d = new Date()) {
55  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
56}
57
58// macOS writes AppleInterfaceStyle = Dark in dark mode and removes the key in light mode.
59// A themed variant keeps its suffix: dark-daltonized becomes light-daltonized.
60export function themeFor(current: unknown, stdout: string): string {
61  const want = stdout.includes('Dark') ? 'dark' : 'light'
62  const variant = typeof current === 'string' ? /^(?:light|dark)(-.+)$/.exec(current)?.[1] : undefined
63
64  return want + (variant ?? '')
65}
66
hooks/plans.ts 202 lines
1import type { DevEntry, Group, Snap, WorkItem } from '../types'
2import { STAGES, withStages } from './logic'
3
4/* Plan files: one markdown file per task, in `plans/` at the project's root (the folder name is a setting).
5 * The file is the only home of a task and its work items: edit it by hand, with /task, or let Claude use the tool. */
6
7export const PLANS_DIR = 'plans'
8
9/** A folder name for `plans_dir`: one plain segment, else the default. */
10export const plansDirName = (v: unknown) => (typeof v === 'string' && /^[\w.-]+$/.test(v.trim()) && !/^\.+$/.test(v.trim()) ? v.trim() : PLANS_DIR)
11
12export type PlanFront = {
13  task: string
14  project: string
15  short: string
16  title: string
17  date: string
18  end: string
19  size?: string
20  /** Parked (on hold) and superseded (replaced by other plans) are kept on disk but not shown. */
21  status: PlanStatus
22}
23export type PlanStatus = 'open' | 'done' | 'parked' | 'superseded'
24const STATUSES: PlanStatus[] = ['open', 'done', 'parked', 'superseded']
25export type Plan = PlanFront & { file: string; items: WorkItem[]; text: string }
26
27const MARK: Record<WorkItem['status'], string> = { todo: ' ', doing: '~', done: 'x', draft: '?' }
28const FROM_MARK: Record<string, WorkItem['status']> = { ' ': 'todo', '~': 'doing', x: 'done', X: 'done', '?': 'draft' }
29const ITEMS_HEAD = '## Work items'
30
31const yamlValue = (v: string) => (/^[\w./-]+$/.test(v) ? v : JSON.stringify(v))
32
33function readFront(text: string): Record<string, string> {
34  const m = text.match(/^---\n([\s\S]*?)\n---\n?/)
35  const out: Record<string, string> = {}
36  if (!m) return out
37  for (const line of m[1]!.split('\n')) {
38    const kv = line.match(/^(\w+):\s*(.*)$/)
39    if (!kv) continue
40    const raw = kv[2]!.trim()
41    try {
42      out[kv[1]!] = raw.startsWith('"') ? (JSON.parse(raw) as string) : raw
43    } catch {
44      out[kv[1]!] = raw
45    }
46  }
47  return out
48}
49
50function writeFront(f: PlanFront) {
51  const keys: (keyof PlanFront)[] = ['task', 'project', 'short', 'title', 'date', 'end', 'size', 'status']
52  return ['---', ...keys.filter(k => f[k] !== undefined && f[k] !== '').map(k => `${k}: ${yamlValue(String(f[k]))}`), '---'].join('\n')
53}
54
55/** The work items under `## Work items`: `- [ ] Title \`stage\`` with indented detail lines. */
56export function parseItems(text: string, key: string): WorkItem[] {
57  const start = text.indexOf(ITEMS_HEAD)
58  if (start < 0) return []
59  const rest = text.slice(start + ITEMS_HEAD.length)
60  const stop = rest.search(/\n## /)
61  const block = stop < 0 ? rest : rest.slice(0, stop)
62  const items: WorkItem[] = []
63  for (const line of block.split('\n')) {
64    const m = line.match(/^\s*[-*] \[( |x|X|~|\?)\]\s+(.+?)\s*$/)
65    if (m) {
66      let title = m[2]!
67      let stage = 'build'
68      const st = title.match(/\s*`(\w+)`\s*$/)
69      if (st && STAGES.includes(st[1]!.toLowerCase())) {
70        stage = st[1]!.toLowerCase()
71        title = title.slice(0, st.index).trim()
72      }
73      items.push({ id: `${key}-${items.length + 1}`, title, stage, status: FROM_MARK[m[1]!] ?? 'todo' })
74      continue
75    }
76    const last = items[items.length - 1]
77    const detail = line.match(/^\s{2,}(\S.*)$/)
78    if (last && detail) last.details = last.details ? `${last.details} ${detail[1]!.trim()}` : detail[1]!.trim()
79  }
80  return items
81}
82
83export function renderItems(items: WorkItem[]) {
84  return items.map(i => `- [${MARK[i.status]}] ${i.title} \`${i.stage}\`${i.details ? `\n  ${i.details}` : ''}`).join('\n')
85}
86
87/** Replaces the work items block, keeping everything else in the file as written. */
88export function setItems(text: string, items: WorkItem[]) {
89  const body = renderItems(items)
90  const start = text.indexOf(ITEMS_HEAD)
91  if (start < 0) return text.replace(/\s*$/, '') + `\n\n${ITEMS_HEAD}\n\n${body}\n`
92  const after = start + ITEMS_HEAD.length
93  const rest = text.slice(after)
94  const stop = rest.search(/\n## /)
95  return text.slice(0, after) + '\n\n' + (body ? body + '\n' : '') + (stop < 0 ? '' : rest.slice(stop))
96}
97
98/** Rewrites the header fields, keeping the body. */
99export function setFront(text: string, f: PlanFront) {
100  const m = text.match(/^---\n[\s\S]*?\n---\n?/)
101  return writeFront(f) + '\n' + (m ? text.slice(m[0].length) : '\n' + text)
102}
103
104export function parsePlan(text: string, file: string): Plan | undefined {
105  const f = readFront(text)
106  if (!f.task || !f.title || !f.date) return undefined
107  return {
108    file,
109    text,
110    task: f.task,
111    project: f.project ?? '',
112    short: f.short ?? f.project ?? '',
113    title: f.title,
114    date: f.date,
115    end: f.end || f.date,
116    size: f.size || undefined,
117    status: STATUSES.includes(f.status as PlanStatus) ? (f.status as PlanStatus) : 'open',
118    items: parseItems(text, f.task),
119  }
120}
121
122/** Lowercase words joined by hyphens, whole words only, up to 40 characters. */
123function slug(s: string) {
124  let out = ''
125  for (const w of s.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)) {
126    if (out && out.length + 1 + w.length > 40) break
127    out = out ? `${out}-${w}` : w.slice(0, 40)
128  }
129  return out
130}
131/** A key for a new task: its title's slug, cut short, made unique among `taken`. */
132export function newTaskKey(title: string, taken: readonly string[]) {
133  const base = slug(title).split('-').slice(0, 4).join('-') || 'task'
134  let key = base
135  for (let n = 2; taken.includes(key); n++) key = `${base}-${n}`
136  return key
137}
138
139export function newPlanText(f: PlanFront, items: WorkItem[], notes?: string) {
140  return [
141    writeFront(f),
142    '',
143    `# ${f.title}`,
144    '',
145    `${ITEMS_HEAD}`,
146    '',
147    ...(items.length ? [renderItems(items)] : []),
148    ...(notes?.trim() ? ['', '## Notes', '', notes.trim()] : []),
149    '',
150  ].join('\n')
151}
152
153/** A plan's work items with the stages they use. */
154export const devEntryOf = (p: Plan): DevEntry => withStages({ stages: [], items: p.items })
155
156/** Every item approved and done: the task counts as finished. */
157export const allDone = (items: WorkItem[]) => items.length > 0 && items.every(i => i.status === 'done')
158
159/** A plan as the band and pane draw a task. */
160export function groupOf(p: Plan): Group & { file: string } {
161  const entry = devEntryOf(p)
162  return {
163    key: p.task,
164    title: p.title,
165    project: p.project,
166    short: p.short,
167    size: p.size,
168    start: p.date,
169    end: p.end,
170    open: p.status === 'open',
171    parts: [],
172    stages: entry.stages,
173    items: p.items,
174    file: p.file,
175  }
176}
177
178/** Current task: the earliest open plan by date; then Up next and recently done. */
179/**
180 * The current task is the open plan picked with `/task switch` (or from Up next), else the earliest
181 * open one by date; Up next is the other open plans in date order. A pick that is done or parked
182 * no longer counts, so the earliest open plan comes back on its own.
183 */
184export function snapshotOfPlans(plans: Plan[], folder: string, picked?: string): Snap {
185  if (!plans.length) return { status: 'none', shorts: [], prev: [], next: [], folder }
186  const byDate = [...plans].sort((a, b) => a.date.localeCompare(b.date) || a.task.localeCompare(b.task))
187  const open = byDate.filter(p => p.status === 'open').map(groupOf)
188  const done = byDate.filter(p => p.status === 'done').sort((a, b) => a.end.localeCompare(b.end)).map(groupOf)
189  const shorts = [...new Set(plans.map(p => p.short).filter(Boolean))]
190  const cur = open.find(g => g.key === picked) ?? open[0]
191  return { status: 'ready', folder, shorts, cur, next: open.filter(g => g !== cur).slice(0, 4), prev: done.slice(-3), isPicked: cur !== open[0] }
192}
193
194/** The open plan `/task switch <arg>` names: its Up next number, its task key, or words of its title. */
195export function findOpen(plans: Plan[], snap: Snap, arg: string): Plan | undefined {
196  const q = arg.trim().toLowerCase()
197  if (!q) return undefined
198  const open = plans.filter(p => p.status === 'open').sort((x, y) => x.date.localeCompare(y.date) || x.task.localeCompare(y.task))
199  if (/^\d+$/.test(q)) return open.find(p => p.task === snap.next[Number(q) - 1]?.key)
200  return open.find(p => p.task.toLowerCase() === q) ?? open.find(p => p.title.toLowerCase().includes(q))
201}
202
hooks/bench.ts 165 lines
1import type { ThemeKey } from 'claude-code'
2
3import type { Entry, Touch } from '../types'
4import type { Ink } from './icons'
5
6/* ── colors from the active /skin ── */
7
8export type Slot = 'read' | 'write' | 'run' | 'search' | 'user' | 'fg' | 'muted' | 'surface' | 'ok' | 'err' | 'warn'
9export type Palette = Record<Slot, string>
10
11// The built-in skins' dark palettes, as the skins mod ships them (hooks/themes).
12const SKINS: Record<string, Palette> = {
13  noir: { read: '#ededed', write: '#ededed', run: '#ededed', search: '#ededed', user: '#f5f5f5', fg: '#ededed', muted: '#8c8c8c', surface: '#151515', ok: '#ededed', err: '#f87171', warn: '#a3a3a3' },
14  'tokyo-night': { read: '#7dcfff', write: '#ff9e64', run: '#e0af68', search: '#bb9af7', user: '#7aa2f7', fg: '#c0caf5', muted: '#737aa2', surface: '#1f2335', ok: '#9ece6a', err: '#f7768e', warn: '#e0af68' },
15  dracula: { read: '#8be9fd', write: '#ffb86c', run: '#f1fa8c', search: '#bd93f9', user: '#bd93f9', fg: '#f8f8f2', muted: '#6272a4', surface: '#2b2d3a', ok: '#50fa7b', err: '#ff5555', warn: '#f1fa8c' },
16  nord: { read: '#8fbcbb', write: '#d08770', run: '#ebcb8b', search: '#b48ead', user: '#88c0d0', fg: '#e5e9f0', muted: '#7b88a1', surface: '#3b4252', ok: '#a3be8c', err: '#bf616a', warn: '#ebcb8b' },
17  gruvbox: { read: '#83a598', write: '#fe8019', run: '#b8bb26', search: '#d3869b', user: '#fabd2f', fg: '#ebdbb2', muted: '#928374', surface: '#32302f', ok: '#b8bb26', err: '#fb4934', warn: '#fe8019' },
18  catppuccin: { read: '#89dceb', write: '#fab387', run: '#f9e2af', search: '#cba6f7', user: '#cba6f7', fg: '#cdd6f4', muted: '#7f849c', surface: '#252536', ok: '#a6e3a1', err: '#f38ba8', warn: '#f9e2af' },
19  mono: { read: '#9e9e9e', write: '#e0e0e0', run: '#bdbdbd', search: '#9e9e9e', user: '#e0e0e0', fg: '#e0e0e0', muted: '#7a7a7a', surface: '#262626', ok: '#e0e0e0', err: '#ffffff', warn: '#bdbdbd' },
20}
21const NOIR_LIGHT: Palette = { read: '#111111', write: '#111111', run: '#111111', search: '#111111', user: '#111111', fg: '#151515', muted: '#6b6b6b', surface: '#ffffff', ok: '#151515', err: '#c42b2b', warn: '#6b6b6b' }
22
23/** No skin on: drawings carry a light and a dark color (`inkOf`), text takes Claude Code's theme colors (`THEME_KEY`). */
24export const PLAIN: Palette & { themed: false } = { read: '', write: '', run: '', search: '', user: '', fg: '', muted: '', surface: '', ok: '', err: '', warn: '', themed: false }
25const PLAIN_DARK: Palette = { read: '#c084fc', write: '#fb923c', run: '#e9c46a', search: '#c084fc', user: '#60a5fa', fg: '#ececec', muted: '#9a9a96', surface: '#1f1f1e', ok: '#4ade80', err: '#f87171', warn: '#e9c46a' }
26const PLAIN_LIGHT: Palette = { read: '#7c3aed', write: '#c2410c', run: '#a16207', search: '#7c3aed', user: '#2563eb', fg: '#1f1f1f', muted: '#6b6b6b', surface: '#ffffff', ok: '#15803d', err: '#b91c1c', warn: '#a16207' }
27
28/** A drawing's color for `slot`: the skin's, or with no skin a light and dark pair. */
29export const inkOf = (pal: Palette & { themed: boolean }, slot: Slot): Ink => (pal.themed ? pal[slot] : { light: PLAIN_LIGHT[slot], dark: PLAIN_DARK[slot] })
30
31/** With no skin, text in these slots takes Claude Code's own theme colors, which follow light and dark. */
32export const THEME_KEY: Partial<Record<Slot, ThemeKey>> = { read: 'suggestion', search: 'suggestion', write: 'claude', run: 'warning', warn: 'warning', ok: 'success', err: 'error', user: 'permission' }
33
34const deepen = (hex: string, amount: number) =>
35  '#' + [1, 3, 5].map(i => Math.round(parseInt(hex.slice(i, i + 2), 16) * (1 - amount)).toString(16).padStart(2, '0')).join('')
36
37/** The skins mod's own light derivation (hooks/light.ts). */
38function toLight(p: Palette): Palette {
39  const d = (h: string) => deepen(h, 0.45)
40  return { read: d(p.read), write: d(p.write), run: d(p.run), search: d(p.search), user: d(p.user), fg: '#1f1f1f', muted: '#6b6b6b', surface: '#ffffff', ok: deepen(p.ok, 0.5), err: deepen(p.err, 0.25), warn: deepen(p.warn, 0.5) }
41}
42
43export type SkinPrefs = { skin?: string } | undefined
44export type SkinCustom = Record<string, { base?: string; palette?: Partial<Record<string, string>> }> | undefined
45
46/** The palette of the skin /skin has on, light or dark; PLAIN when skins is off or absent. */
47export function paletteOf(prefs: SkinPrefs, custom: SkinCustom, isLight: boolean | undefined): Palette & { themed: boolean } {
48  const name = prefs?.skin
49  if (!name || name === 'off') return PLAIN
50  const made = custom?.[name]
51  const baseName = made ? (made.base ?? 'noir') : name
52  const base = SKINS[baseName]
53  if (!base) return PLAIN
54  const dark = { ...base, ...(made?.palette as Partial<Palette> | undefined) }
55  const p = isLight ? (baseName === 'noir' && !made ? NOIR_LIGHT : toLight(dark)) : dark
56  return { ...p, themed: true }
57}
58
59/* ── paths ── */
60
61export const parentOf = (p: string) => (p.lastIndexOf('/') > 0 ? p.slice(0, p.lastIndexOf('/')) : '/')
62export const baseOf = (p: string) => p.slice(p.lastIndexOf('/') + 1)
63export const join = (a: string, b: string) => (a.endsWith('/') ? a + b : `${a}/${b}`)
64export const absOf = (p: string, cwd: string) => (p.startsWith('/') ? p : join(cwd, p.replace(/^\.\//, '')))
65/** `dir` relative to `root`, for "in tests"; the project name at the root itself. */
66export function relDir(path: string, root: string) {
67  const dir = parentOf(path)
68  if (dir === root) return baseOf(root)
69  return dir.startsWith(root + '/') ? dir.slice(root.length + 1) : dir
70}
71/* ── git ── */
72
73/** Absolute paths of changed and untracked files, from `git status --porcelain=v1 -z`. */
74export function parseStatus(out: string, top: string): string[] {
75  const parts = out.split('\0')
76  const dirty: string[] = []
77  for (let i = 0; i < parts.length; i++) {
78    const rec = parts[i]
79    if (!rec || rec.length < 4) continue
80    dirty.push(join(top, rec.slice(3).replace(/\/$/, '')))
81    if (rec[0] === 'R' || rec[0] === 'C') i++ // the old path follows a rename or copy
82  }
83  return dirty
84}
85
86export const isDirty = (path: string, dirty: readonly string[]) => dirty.some(d => d === path || d.startsWith(path + '/'))
87
88/* ── tree ── */
89
90export type Row = { path: string; name: string; depth: number; dir: boolean; size: number; open: boolean }
91
92/** The visible rows: each loaded, expanded folder's entries below it, folders first. */
93export function rowsOf(root: string, dirs: Record<string, Entry[]>, expanded: readonly string[], showHidden: boolean, max = 400): Row[] {
94  const rows: Row[] = []
95  const open = new Set(expanded)
96  const walk = (dir: string, depth: number) => {
97    for (const en of sortEntries(dirs[dir] ?? [], showHidden)) {
98      if (rows.length >= max) return
99      const path = join(dir, en.name)
100      const isOpen = en.dir && open.has(path)
101      rows.push({ path, name: en.name, depth, dir: en.dir, size: en.size, open: isOpen })
102      if (isOpen) walk(path, depth + 1)
103    }
104  }
105  walk(root, 0)
106  return rows
107}
108
109export function sortEntries(list: readonly Entry[], showHidden: boolean): Entry[] {
110  return list
111    .filter(e => e.name !== '.DS_Store' && (showHidden || !e.name.startsWith('.')))
112    .sort((a, b) => (a.dir === b.dir ? a.name.localeCompare(b.name) : a.dir ? -1 : 1))
113}
114
115/** Up to `max` relative paths whose name or path holds every word of `query`. */
116export function search(all: readonly string[], query: string, showHidden: boolean, max = 30): string[] {
117  const words = query.toLowerCase().split(/\s+/).filter(Boolean)
118  if (!words.length) return []
119  const hits: string[] = []
120  for (const p of all) {
121    if (!showHidden && p.split('/').some(s => s.startsWith('.'))) continue
122    const l = p.toLowerCase()
123    if (words.every(w => l.includes(w))) hits.push(p)
124    if (hits.length >= max) break
125  }
126  return hits.sort((a, b) => a.length - b.length)
127}
128
129/** Every folder from `root` down to the one holding `path`, to reveal it. */
130export function foldersTo(path: string, root: string): string[] {
131  const out: string[] = []
132  let d = parentOf(path)
133  while (d.startsWith(root + '/')) {
134    out.unshift(d)
135    d = parentOf(d)
136  }
137  return out
138}
139
140export function humanSize(n: number) {
141  if (n < 1024) return `${n} B`
142  if (n < 1024 * 1024) return `${(n / 1024).toFixed(n < 10240 ? 1 : 0)} KB`
143  return `${(n / 1024 / 1024).toFixed(1)} MB`
144}
145
146/* ── Claude's activity ── */
147
148/** Records a touch: the newest first, one row per file, an edit outranking a read. */
149export function addTouch(list: readonly Touch[], t: Touch, max = 50): Touch[] {
150  const old = list.find(x => x.path === t.path)
151  const kind = old?.kind === 'edited' && t.kind === 'read' && !t.active ? 'edited' : t.kind
152  return [{ ...t, kind }, ...list.filter(x => x.path !== t.path)].slice(0, max)
153}
154
155export const badge = (t: Touch) => (t.active ? (t.kind === 'read' ? 'Reading' : 'Editing') : t.kind === 'read' ? 'Read' : 'Edited')
156
157/** Tools whose target is one file, and whether they write it. */
158export const FILE_TOOLS: Record<string, 'read' | 'edited'> = { Read: 'read', Edit: 'edited', Write: 'edited', MultiEdit: 'edited', NotebookEdit: 'edited' }
159/** "ts" for "a/b.test.ts"; "" for a name with no dot. */
160export const extOf = (p: string) => {
161  const name = baseOf(p)
162  const i = name.lastIndexOf('.')
163  return i > 0 ? name.slice(i + 1) : ''
164}
165
hooks/deck.ts 511 lines
1// In Flight, the Workbench's third card: Flightdeck ported into the pane. Pure data: defaults, reducers and
2// formatting; nothing here touches `$`, so every behaviour is testable directly.
3//
4// Adapted from claude-flightdeck (https://github.com/scasella/claude-flightdeck, hooks/core.ts),
5// MIT License, Copyright (c) 2026 Stephen Casella. Permission is hereby granted, free of charge, to
6// any person obtaining a copy of this software and associated documentation files (the "Software"),
7// to deal in the Software without restriction, including without limitation the rights to use, copy,
8// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
9// persons to whom the Software is furnished to do so, subject to the following conditions: The above
10// copyright notice and this permission notice shall be included in all copies or substantial portions
11// of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
12// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
13// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
14// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
15// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
16import type {
17  DeckAgent,
18  DeckArchitect,
19  DeckBucket,
20  DeckCheck,
21  DeckGate,
22  DeckLogLine,
23  DeckLoop,
24  DeckMain,
25  DeckMoment,
26  DeckReceipt,
27  DeckRoster,
28  DeckSession,
29  DeckSessionStatus,
30  DeckTally,
31  DeckToolNote,
32  DeckTurn,
33  DeckUsage,
34  DeckView,
35} from '../types'
36
37// ---------------------------------------------------------------- defaults
38
39export const DEFAULT_MAIN: DeckMain = { model: '', effort: '', mode: '', steps: 0, isRunning: false }
40export const DEFAULT_USAGE: DeckUsage = {
41  pct: null,
42  tokens: null,
43  window: 0,
44  costUsd: null,
45  limits: [],
46  compactions: 0,
47  lastCompactAt: null,
48}
49export const DEFAULT_ARCHITECT: DeckArchitect = { consults: [], ids: [], seen: [], lastAdvice: '' }
50const ZERO: DeckTally = { rule: 0, ask: 0, cleared: 0, deny: 0 }
51export const DEFAULT_GATE: DeckGate = { recent: [], totals: { file: ZERO, shell: ZERO, other: ZERO } }
52export const DEFAULT_TURN: DeckTurn = { edits: 0, errorStreak: 0, errors: 0, isReviewing: false, startedAt: 0, costAtStart: null }
53export const DEFAULT_VIEW: DeckView = { expanded: null, gateOpen: null }
54export const DEFAULT_ROSTER: DeckRoster = { architectTypes: [] }
55
56const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
57
58/** A stored object merged over its defaults, so a value saved under an older shape still reads. */
59export const normalize = <T extends object>(def: T, stored: unknown): T =>
60  isObject(stored) ? ({ ...def, ...stored } as T) : def
61
62/** A stored list, or empty when what is stored is not a list. */
63export const listOf = <T>(stored: unknown): T[] => (Array.isArray(stored) ? (stored as T[]) : [])
64
65export const normalizeGate = (stored: unknown): DeckGate => {
66  const g = normalize(DEFAULT_GATE, stored)
67  const totals = normalize(DEFAULT_GATE.totals, g.totals)
68  return {
69    recent: listOf<DeckCheck>(g.recent),
70    totals: { file: normalize(ZERO, totals.file), shell: normalize(ZERO, totals.shell), other: normalize(ZERO, totals.other) },
71  }
72}
73
74export const normalizeCard = (stored: unknown): DeckAgent =>
75  normalize<DeckAgent>(
76    {
77      id: '',
78      type: 'agent',
79      model: '',
80      description: '',
81      status: 'running',
82      spawnedAt: 0,
83      endedAt: null,
84      ctx: 0,
85      out: 0,
86      steps: 0,
87      lastStop: null,
88      tools: [],
89      answer: '',
90    },
91    stored,
92  )
93
94export const normalizeLog = (stored: unknown): DeckLogLine[] =>
95  listOf<Record<string, unknown>>(stored).map(l => ({
96    at: typeof l.at === 'number' ? l.at : 0,
97    who: String(l.who ?? ''),
98    text: String(l.text ?? ''),
99    agentId: typeof l.agentId === 'string' ? l.agentId : null,
100    kind: l.kind === 'error' || l.kind === 'consult' || l.kind === 'done' ? l.kind : 'info',
101  }))
102
103// ---------------------------------------------------------------- colors
104
105/** SVG cannot name theme keys: mid-tone colors that read on light and dark backgrounds. */
106export const SVG_COLORS = { running: '#3b82f6', done: '#16a34a', failed: '#dc2626', other: '#8b5cf6', label: '#6b7280' }
107
108// ---------------------------------------------------------------- formatting
109
110/** `claude-opus-5-5` → `Opus 5.5`; anything else is shown as given. */
111/**
112 * A model id as people say it, from any provider's spelling: `claude-opus-5-5[1m]` → `Opus 5.5 1M`,
113 * `us.anthropic.claude-sonnet-4-5-20250929-v1:0` → `Sonnet 4.5`, `claude-3-5-haiku-20241022` →
114 * `Haiku 3.5`. Anything else is shown as given, cut to 22 characters.
115 */
116export const prettyModel = (id: string) => {
117  if (!id) return '-'
118  const cap = (f: string) => f.charAt(0).toUpperCase() + f.slice(1)
119  const big = /\[1m\]|-1m\b/i.test(id) ? ' 1M' : ''
120  const now = /claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(?![\d])/i.exec(id)
121  if (now?.[1] && !/^\d/.test(now[1])) return `${cap(now[1].toLowerCase())} ${now[2]}${now[3] ? `.${now[3]}` : ''}${big}`
122  const old = /claude-(\d+)(?:-(\d))?-([a-z]+)/i.exec(id)
123  if (old?.[3]) return `${cap(old[3].toLowerCase())} ${old[1]}${old[2] ? `.${old[2]}` : ''}${big}`
124  return shorten(id, 22)
125}
126
127export const shorten = (s: string, n: number) => {
128  const one = s.replace(/\s+/g, ' ').trim()
129  return n <= 0 ? '' : one.length > n ? `${one.slice(0, Math.max(0, n - 1)).trimEnd()}…` : one
130}
131
132export const kTokens = (n: number) =>
133  n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n)
134
135export const fmtDuration = (ms: number) => {
136  const s = Math.max(0, Math.round(ms / 1000))
137  if (s < 60) return `${s}s`
138  const m = Math.floor(s / 60)
139  return m < 60 ? `${m}m${String(s % 60).padStart(2, '0')}s` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`
140}
141
142/** A running clock as the live cards draw it: m:ss, or XhYY past an hour. */
143export const fmtTimer = (ms: number) => {
144  const s = Math.max(0, Math.floor(ms / 1000))
145  const m = Math.floor(s / 60)
146  return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
147}
148
149export const fmtClock = (ms: number) => (ms > 0 ? new Date(ms).toTimeString().slice(0, 8) : '--:--:--')
150
151/** `1 error`, `2 errors`. */
152export const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
153
154export const fmtUsd = (n: number) => (n >= 100 ? `$${Math.round(n)}` : `$${n.toFixed(2)}`)
155
156/** A gauge of `width` cells: ▰ filled, ▱ empty. */
157export const gauge = (pct: number, width: number) => {
158  const full = Math.max(0, Math.min(width, Math.round((pct / 100) * width)))
159  return { on: '▰'.repeat(full), off: '▱'.repeat(width - full) }
160}
161
162/** A rate-limit window's short name: `five_hour` → `5h`, `seven_day_opus` → `7d opus`. */
163export const limitLabel = (kind: string) =>
164  kind
165    .replace(/five[_ -]?hours?/i, '5h')
166    .replace(/seven[_ -]?days?/i, '7d')
167    .replace(/[_-]+/g, ' ')
168    .trim()
169
170// ---------------------------------------------------------------- redaction
171
172const SECRETS: [RegExp, string][] = [
173  [/(authorization\s*[:=]\s*)(bearer\s+|basic\s+)?\S+/gi, '$1$2•••'],
174  [/\b(bearer)\s+[A-Za-z0-9._~+/-]{8,}=*/gi, '$1 •••'],
175  [/\b(sk|pk|rk|ghp|gho|ghs|github_pat|xox[abprs])[-_][A-Za-z0-9_-]{8,}/g, '•••'],
176  [/((?:api[_-]?key|access[_-]?token|token|secret|password|passwd|pwd)\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/gi, '$1•••'],
177  [/(--(?:token|password|api-key|secret)[= ])\S+/gi, '$1•••'],
178  [/(\b[A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD)=)\S+/g, '$1•••'],
179  [/(\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:)[^\s@]+@/gi, '$1•••@'],
180]
181
182/** What the gate drill-down may store: credentials masked before anything is written to state. */
183export const redact = (s: string) => SECRETS.reduce((t, [re, to]) => t.replace(re, to), s)
184
185// ---------------------------------------------------------------- tools and gate
186
187const FILE_TOOLS = new Set(['Read', 'Edit', 'Write', 'NotebookEdit', 'Glob', 'Grep'])
188const SHELL_TOOLS = new Set(['Bash', 'PowerShell'])
189export const EDIT_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit'])
190
191export const bucketOf = (tool: string): DeckBucket =>
192  FILE_TOOLS.has(tool) ? 'file' : SHELL_TOOLS.has(tool) ? 'shell' : 'other'
193
194/** One line saying what a call was about: its command, path or pattern; redacted. */
195export const describeInput = (tool: string, input: unknown) => {
196  const i = isObject(input) ? input : {}
197  const path = typeof i.file_path === 'string' ? i.file_path.split(/[\\/]/).slice(-2).join('/') : ''
198  const what =
199    typeof i.command === 'string'
200      ? i.command
201      : path || (typeof i.pattern === 'string' ? i.pattern : typeof i.url === 'string' ? i.url : typeof i.description === 'string' ? i.description : '')
202  return redact(what ? `${tool} → ${what}` : tool)
203}
204
205/** Keeps the last `max` checks, but never drops a pending ask: its settle must still find it. */
206export const trimRecent = (list: DeckCheck[], max: number): DeckCheck[] => {
207  let extra = list.length - max
208  if (extra <= 0) return list
209  const out: DeckCheck[] = []
210  for (const c of list) {
211    if (extra > 0 && c.verdict !== 'ask') {
212      extra -= 1
213      continue
214    }
215    out.push(c)
216  }
217  return out.slice(-max * 2)
218}
219
220export const recordCheck = (g: DeckGate, c: DeckCheck): DeckGate => {
221  const t = g.totals[c.bucket]
222  return {
223    recent: trimRecent([...g.recent, c], 80),
224    totals: { ...g.totals, [c.bucket]: { ...t, [c.verdict]: t[c.verdict] + 1 } },
225  }
226}
227
228/** An `ask` settled by the call that followed it: it ran (cleared) or was refused (deny). */
229export const settleCheck = (g: DeckGate, id: string, didRun: boolean): DeckGate => {
230  const c = g.recent.find(r => r.id === id && r.verdict === 'ask')
231  if (!c) return g
232  const verdict = didRun ? 'cleared' : 'deny'
233  const t = g.totals[c.bucket]
234  return {
235    recent: g.recent.map(r => (r === c ? { ...r, verdict } : r)),
236    totals: { ...g.totals, [c.bucket]: { ...t, ask: Math.max(0, t.ask - 1), [verdict]: t[verdict] + 1 } },
237  }
238}
239
240export const gateSummary = (g: DeckGate) => {
241  const all = (['file', 'shell', 'other'] as const).reduce(
242    (s, k) => ({
243      rule: s.rule + g.totals[k].rule,
244      ask: s.ask + g.totals[k].ask,
245      cleared: s.cleared + g.totals[k].cleared,
246      deny: s.deny + g.totals[k].deny,
247    }),
248    { ...ZERO },
249  )
250  return { ...all, total: all.rule + all.ask + all.cleared + all.deny }
251}
252
253// ---------------------------------------------------------------- turn and architect
254
255/**
256 * The turn after one tool call. Errors count in the main loop only (a subagent's failure is its
257 * own); edits count from every loop, so delegated work still reaches "before done".
258 */
259export const afterCall = (t: DeckTurn, c: { inSubagent: boolean; hasFailed: boolean; isEdit: boolean }): DeckTurn => ({
260  ...t,
261  errorStreak: c.inSubagent ? t.errorStreak : c.hasFailed ? t.errorStreak + 1 : 0,
262  errors: t.errors + (!c.inSubagent && c.hasFailed ? 1 : 0),
263  edits: t.edits + (c.isEdit ? 1 : 0),
264})
265
266/** Which of the architect's three moments a consult falls at: an inference over this turn so far. */
267export const momentOf = (t: Pick<DeckTurn, 'edits' | 'errorStreak'>): DeckMoment =>
268  t.errorStreak >= 2 ? 'error repeats' : t.edits === 0 ? 'before a plan' : 'before done'
269
270export const startConsult = (a: DeckArchitect, c: { id: string; at: number; moment: DeckMoment; via: string }): DeckArchitect =>
271  a.consults.some(x => x.id === c.id) ? a : { ...a, consults: [...a.consults, { ...c, endAt: null }].slice(-40) }
272
273/** Ends the open consult (the latest without an end), or the one named. */
274export const endConsult = (a: DeckArchitect, at: number, advice: string | null, id?: string): DeckArchitect => {
275  const open = [...a.consults].reverse().find(c => c.endAt === null && (id === undefined || c.id === id))
276  return {
277    ...a,
278    consults: a.consults.map(c => (c === open ? { ...c, endAt: at } : c)),
279    lastAdvice: advice ?? a.lastAdvice,
280  }
281}
282
283export const isAdvising = (a: DeckArchitect) => a.consults.some(c => c.endAt === null)
284
285/** A one-row timeline of consults across `width` cells: ◆ a consult, ━ while it ran. */
286export const consultTimeline = (a: DeckArchitect, now: number, width: number) => {
287  if (a.consults.length === 0 || width < 4) return '─'.repeat(Math.max(0, width))
288  const first = a.consults[0]?.at ?? now
289  const span = Math.max(1, now - first)
290  const cells = Array.from({ length: width }, () => '─')
291  for (const c of a.consults) {
292    const from = Math.min(width - 1, Math.floor(((c.at - first) / span) * (width - 1)))
293    const to = Math.min(width - 1, Math.floor((((c.endAt ?? now) - first) / span) * (width - 1)))
294    for (let i = from + 1; i <= to; i += 1) cells[i] = '━'
295    cells[from] = '◆'
296  }
297  return cells.join('')
298}
299
300export const receiptOf = (t: DeckTurn, o: { durationMs: number; agentsSince: number; costNow: number | null; reason: string }): DeckReceipt => ({
301  durationMs: o.durationMs,
302  agents: o.agentsSince,
303  edits: t.edits,
304  errors: t.errors,
305  costDelta: o.costNow !== null && t.costAtStart !== null && o.costNow - t.costAtStart >= 0.005 ? o.costNow - t.costAtStart : null,
306  reason: o.reason,
307})
308
309// ---------------------------------------------------------------- agents and loops
310
311type StepUsage = { input_tokens?: number; cache_read_input_tokens?: number; cache_creation_input_tokens?: number; output_tokens?: number } | null
312
313/** A card after one of its model requests: its context is the latest step's whole input; output adds up. */
314export const applyStep = (c: DeckAgent, s: { model: string; usage: StepUsage; stopReason: string | null }): DeckAgent => {
315  const u = s.usage ?? {}
316  const ctx = (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0)
317  return {
318    ...c,
319    model: c.model || s.model,
320    steps: c.steps + 1,
321    ctx: ctx > 0 ? ctx : c.ctx,
322    out: c.out + (u.output_tokens ?? 0),
323    lastStop: s.stopReason,
324  }
325}
326
327export const noteTool = (c: DeckAgent, n: DeckToolNote): DeckAgent => ({ ...c, tools: [...c.tools, n].slice(-3) })
328
329export const stepLoop = (loops: DeckLoop[], id: string, at: number): DeckLoop[] => {
330  const found = loops.find(l => l.id === id)
331  const next = found
332    ? loops.map(l => (l === found ? { ...l, steps: l.steps + 1, lastAt: at } : l))
333    : [...loops, { id, steps: 1, firstAt: at, lastAt: at, isDone: false }]
334  return next.slice(-60)
335}
336
337export const LOOP_ACTIVE_MS = 15_000
338export const isLoopActive = (l: DeckLoop, now: number) => !l.isDone && now - l.lastAt < LOOP_ACTIVE_MS
339
340/** Swimlane geometry: each agent's bar on one shared axis from the first spawn to now. */
341export const lanes = (cards: DeckAgent[], now: number, width: number) => {
342  const start = Math.min(...cards.map(c => c.spawnedAt).filter(n => n > 0), now)
343  const span = Math.max(1, now - start)
344  return cards.map(c => {
345    const from = Math.floor(((Math.max(c.spawnedAt, start) - start) / span) * width)
346    const to = Math.max(from + 1, Math.ceil((((c.endedAt ?? now) - start) / span) * width))
347    return { id: c.id, before: Math.min(from, width), bar: Math.min(to, width) - Math.min(from, width), after: width - Math.min(to, width) }
348  })
349}
350
351// ---------------------------------------------------------------- text
352
353/** A card's title row: the task in the agent's own words, the type only when there is none. */
354export const cardTitle = (c: DeckAgent) => c.description || c.type
355
356/** A title split over two rows at a word boundary: `first` cells on row one, `rest` on row two. */
357export const titleLines = (title: string, first: number, rest: number): [string, string] => {
358  const t = title.replace(/\s+/g, ' ').trim()
359  if (t.length <= first) return [t, '']
360  const cut = t.lastIndexOf(' ', first)
361  const at = cut > 0 ? cut : first
362  return [t.slice(0, at).trim(), shorten(t.slice(at), rest)]
363}
364
365/**
366 * What a turn's opening text was, for the log: the person's words, or for a turn the engine
367 * opened with a tagged message (a subagent's hand-back, a task notification), that message's kind.
368 */
369export const promptLine = (text: string): { who: string; text: string } => {
370  const tag = /^\s*<([a-z][\w-]*)/i.exec(text)?.[1]
371  if (!tag) return { who: 'you', text: shorten(text, 70) }
372  const from = /\bfrom="([^"]+)"/.exec(text)?.[1]
373  return { who: 'engine', text: shorten(`${tag.replace(/[-_]/g, ' ')}${from ? ` from ${from.slice(0, 8)}` : ''}`, 70) }
374}
375
376/**
377 * A subagent's hand-back message: who sent it and the first line of what it said. The report
378 * follows a framing header in the message; without one, the first line after the opening tag.
379 */
380export const handbackOf = (text: string): { from: string; body: string } | null => {
381  const from = /^\s*<agent-message\s+from="([^"]+)"/.exec(text)?.[1]
382  if (!from) return null
383  const afterHeader = text.split(/The report follows:\s*\n/)[1]
384  const rest = afterHeader ?? text.replace(/^\s*<agent-message[^>]*>/, '')
385  const body =
386    rest
387      .split('\n')
388      .map(l => l.trim())
389      .find(l => l && !l.startsWith('[') && !l.startsWith('<') && !l.startsWith('</')) ?? ''
390  return body ? { from, body } : null
391}
392
393/** The advice line a pane shows for a report: its first real line, markdown markers stripped, cut to 160. */
394export const adviceLine = (report: string) => {
395  const first = report.split('\n').map(l => l.trim()).find(l => l && !l.startsWith('[') && !l.startsWith('<')) ?? ''
396  return shorten(first.replace(/\*\*|__/g, '').replace(/^[#>*\s-]+/, ''), 160)
397}
398
399export const elapsedOf = (c: DeckAgent, now: number) => (c.endedAt ?? now) - c.spawnedAt
400
401// ---------------------------------------------------------------- sessions on this machine
402
403/** The fields read from a `~/.claude/sessions/<pid>.json`, the registry Claude Code keeps of its running sessions. */
404export type SessionFile = {
405  pid: number
406  sessionId: string
407  name: string
408  cwd: string
409  kind: string
410  entrypoint: string
411  status: string
412  waitingFor: string
413  statusUpdatedAt: number
414  isSpare: boolean
415}
416
417/** A session file's fields, or null when the text is not one. */
418export const parseSessionFile = (text: string): SessionFile | null => {
419  let o: unknown
420  try {
421    o = JSON.parse(text)
422  } catch {
423    return null
424  }
425  if (!isObject(o) || typeof o.pid !== 'number') return null
426  const str = (v: unknown) => (typeof v === 'string' ? v : '')
427  return {
428    pid: o.pid,
429    sessionId: str(o.sessionId),
430    name: str(o.name),
431    cwd: str(o.cwd),
432    kind: str(o.kind),
433    entrypoint: str(o.entrypoint),
434    status: str(o.status),
435    waitingFor: str(o.waitingFor),
436    statusUpdatedAt: typeof o.statusUpdatedAt === 'number' ? o.statusUpdatedAt : 0,
437    isSpare: o.spare === true,
438  }
439}
440
441/** The pids `ps -o pid=,comm=` lists that still run Claude Code; a stale file's pid may belong to another program by now. */
442export const alivePids = (ps: string): Set<number> => {
443  const out = new Set<number>()
444  for (const line of ps.split('\n')) {
445    const m = /^\s*(\d+)\s+(.*)$/.exec(line)
446    if (m?.[1] && /claude/i.test(m[2] ?? '')) out.add(Number(m[1]))
447  }
448  return out
449}
450
451const WHERE: Record<string, string> = { 'claude-desktop': 'desktop', 'claude-vscode': 'vscode', cli: 'terminal' }
452const RANK: Record<DeckSessionStatus, number> = { waiting: 0, working: 1, done: 2 }
453
454/**
455 * The sessions to list: running, not a pre-warmed spare or a daemon. busy and shell are working,
456 * waiting (or idle with something to wait for) is waiting, idle is done. Waiting first, then
457 * working, then done; the latest change first within each.
458 */
459export const sessionsOf = (files: SessionFile[], alive: ReadonlySet<number>, selfId: string): DeckSession[] =>
460  files
461    .filter(f => alive.has(f.pid) && !f.isSpare && !f.kind.startsWith('daemon'))
462    .map(f => {
463      const status: DeckSessionStatus =
464        f.status === 'busy' || f.status === 'shell' ? 'working' : f.status === 'waiting' || f.waitingFor ? 'waiting' : 'done'
465      return {
466        pid: f.pid,
467        id: f.sessionId,
468        name: f.name || f.cwd.split('/').filter(Boolean).pop() || `pid ${f.pid}`,
469        cwd: f.cwd,
470        where: f.kind === 'bg' ? 'background' : WHERE[f.entrypoint] ?? (f.entrypoint.replace(/^claude-/, '') || 'terminal'),
471        status,
472        detail: status === 'waiting' ? f.waitingFor || 'needs you' : '',
473        since: f.statusUpdatedAt,
474        isSelf: f.sessionId !== '' && f.sessionId === selfId,
475      }
476    })
477    .sort((a, b) => RANK[a.status] - RANK[b.status] || b.since - a.since)
478
479/** `1 waiting · 2 working · 3 done`, leaving out the zeros; empty with no sessions. */
480export const sessionsLine = (list: DeckSession[]) =>
481  (['waiting', 'working', 'done'] as const)
482    .map(s => [s, list.filter(x => x.status === s).length] as const)
483    .filter(([, n]) => n > 0)
484    .map(([s, n]) => `${n} ${s}`)
485    .join(' · ')
486
487// ---------------------------------------------------------------- the card
488
489/** Everything the card draws, read once per redraw. */
490export type DeckData = {
491  main: DeckMain
492  usage: DeckUsage
493  arch: DeckArchitect
494  gate: DeckGate
495  cards: DeckAgent[]
496  loops: DeckLoop[]
497  log: DeckLogLine[]
498  turn: DeckTurn
499  receipt: DeckReceipt | null
500  view: DeckView
501  sessions: DeckSession[]
502  now: number
503}
504
505/** What a reset writes: agents, checks, consults, log and the turn clear; model, mode, cost, rate limits and compactions stay. */
506export const RESET = {
507  main: (m: unknown): DeckMain => ({ ...DEFAULT_MAIN, model: normalize(DEFAULT_MAIN, m).model, mode: normalize(DEFAULT_MAIN, m).mode }),
508  // The context gauge waits for the next measurement rather than showing the pre-clear fill.
509  usage: (u: unknown): DeckUsage => ({ ...normalize(DEFAULT_USAGE, u), pct: null, tokens: null }),
510}
511
hooks/deck-view.tsx 331 lines
1// The In Flight card's drawing, stacked for the Workbench's one column: main vitals, the
2// sessions on this machine, the architect, the permission gate, the agents list, other loops, the turn receipt and the
3// session log. Pure: register.tsx reads the state and passes the presses back in.
4//
5// Adapted from claude-flightdeck (https://github.com/scasella/claude-flightdeck, hooks/register.tsx),
6// MIT License, Copyright (c) 2026 Stephen Casella. The full notice is at the top of ./deck.ts.
7import type { ThemeKey } from 'claude-code'
8
9import type { DeckAgent, DeckBucket, DeckCheck, DeckLogLine, DeckSession } from '../types'
10import type { Palette, Slot } from './bench'
11import {
12  cardTitle, consultTimeline, fmtDuration, fmtTimer, fmtUsd, gateSummary, gauge, isAdvising, isLoopActive, kTokens,
13  limitLabel, plural, prettyModel, sessionsLine, shorten,
14} from './deck'
15import type { DeckData } from './deck'
16
17/** Agents listed, newest first, before `+n more`. */
18const AGENT_ROWS = 6
19const ARCH_LABEL = 'Architect'
20/** Sessions listed before `+n more`. */
21const SESSION_ROWS = 8
22
23type Role = 'main' | 'agent' | 'gate' | 'cleared' | 'arch' | 'amber' | 'warn' | 'dim' | 'faint' | 'text'
24/** Each role's skin slot, and with no skin the Claude Code theme key the original Flightdeck uses. */
25const ROLE: Record<Role, [Slot, ThemeKey]> = {
26  main: ['write', 'claude'],
27  agent: ['read', 'suggestion'],
28  gate: ['ok', 'success'],
29  cleared: ['user', 'permission'],
30  arch: ['search', 'merged'],
31  amber: ['warn', 'warning'],
32  warn: ['err', 'error'],
33  dim: ['muted', 'inactive'],
34  faint: ['muted', 'subtle'],
35  text: ['fg', 'text'],
36}
37
38/** What the pane lends the card: its elements, width, palette and helpers, so the card looks like the other two. */
39export type DeckKit = {
40  // eslint-disable-next-line @typescript-eslint/no-explicit-any
41  els: any
42  cols: number
43  pal: Palette & { themed: boolean }
44  card: (key: string, kids: unknown[], marginTop?: number, tinted?: boolean) => unknown
45  capsText: (key: string, text: string, slot?: Slot, size?: number) => unknown
46  /** A desktop draws text in a proportional font: a ─ or ■ is wider than a column. */
47  isDesktop: boolean
48  /** The agent whose transcript the person is viewing: the log narrows to it. */
49  viewed: string | null
50  onGate: (b: DeckBucket) => void
51  onExpand: (id: string) => void
52  onReset: () => void
53}
54
55/** The section's title: the main model and whether it works. */
56export function deckTitle(m: DeckData['main']) {
57  return `In Flight · ${m.model ? prettyModel(m.model) : 'main'} ${m.isRunning ? 'working' : 'idle'}`
58}
59
60export function deckKids(d: DeckData, kit: DeckKit): unknown[] {
61  const { els, cols, pal, card, capsText, viewed } = kit
62  const { Box, Text, Button } = els
63  const hasClient = 'Client' in els
64  const { main: m, usage: u, arch: a, gate: g, cards, loops: lp, log: lines, turn: t, receipt: r, view: v, sessions: ss, now } = d
65  const col = (role: Role) => (pal.themed ? pal[ROLE[role][0]] : ROLE[role][1])
66  const slot = (role: Role) => ROLE[role][0]
67  // The text width inside a card inside the section's card: each takes its border and padding.
68  const w = Math.max(20, cols - 13)
69  // Cells for a glyph strip (timeline, permission checks, loops) that must stay on one row: on a desktop
70  // ─ ■ ● draw wider than a column, about 1.6 of them, so a strip w cells long wrapped onto a second row.
71  const strip = kit.isDesktop ? Math.max(8, Math.floor(w * 0.55)) : w
72  const modelName = prettyModel(m.model)
73  const advising = isAdvising(a)
74  const running = cards.filter(c => c.status === 'running')
75  const decider = m.mode === 'auto' ? 'classifier' : 'you'
76  const head = (key: string, left: string, role: Role, right?: unknown) => (
77    <Box key={key} flexDirection="row" justifyContent="space-between" alignItems="center" width="100%">
78      {capsText(key + '-l', left, slot(role))}
79      {right ?? null}
80    </Box>
81  )
82  // A start time of 0 is unknown: no clock rather than decades. The client ticks between redraws.
83  const clock = (key: string, since: number, endAt: number | null, color: string) =>
84    since <= 0 ? <Text key={key} color={color}>-</Text>
85    : hasClient ? <els.Client key={key} module="./elapsed.tsx" props={{ since, now, endAt, color }} />
86    : <Text key={key} color={color}>{fmtTimer((endAt ?? now) - since)}</Text>
87  const out: unknown[] = []
88
89  // ── main: model, effort, context, cost and rate limits
90  const effortN = ({ low: 1, medium: 2, high: 3, xhigh: 4, max: 4 } as Record<string, number>)[m.effort] ?? 0
91  const ctx = u.pct !== null ? gauge(u.pct, Math.min(16, Math.max(6, w - 18))) : null
92  out.push(
93    card('fd-main', [
94      head('fd-main-h', modelName, 'main', <Text key="fd-run" color={m.isRunning ? col('main') : col('dim')}>{m.isRunning ? '● working' : '○ idle'}</Text>),
95      <Text key="fd-effort" wrap="truncate-end">
96        <Text dimColor>effort </Text>
97        <Text color={col('main')}>{'▮'.repeat(effortN) + '▯'.repeat(4 - effortN)} </Text>
98        <Text color={col('main')} bold>{m.effort || '-'}</Text>
99        {m.mode ? <Text dimColor>{`  mode ${m.mode}`}</Text> : null}
100        <Text dimColor>{`  ${m.steps} req`}</Text>
101      </Text>,
102      ctx ? (
103        <Text key="fd-ctx" wrap="truncate-end">
104          <Text dimColor>ctx </Text>
105          <Text color={(u.pct ?? 0) >= 80 ? col('warn') : col('main')}>{ctx.on}</Text>
106          <Text color={col('faint')}>{ctx.off}</Text>
107          <Text bold>{` ${Math.round(u.pct ?? 0)}%`}</Text>
108          {u.tokens !== null ? <Text dimColor>{` ${kTokens(u.tokens)}/${kTokens(u.window)}`}</Text> : null}
109          {u.compactions > 0 ? <Text color={col('amber')}>{`  ⟲${u.compactions}`}</Text> : null}
110        </Text>
111      ) : null,
112      u.costUsd !== null || u.limits.length > 0 ? (
113        <Text key="fd-cost" wrap="truncate-end">
114          {u.costUsd !== null ? <Text color={col('text')}>{fmtUsd(u.costUsd)}</Text> : null}
115          {u.limits.slice(0, 2).map((l, i) => {
116            const lg = gauge(l.pct, 5)
117            return (
118              <Text key={'fd-lim-' + l.kind}>
119                <Text dimColor>{`${u.costUsd !== null || i > 0 ? '  ' : ''}${limitLabel(l.kind)} `}</Text>
120                <Text color={l.pct >= 80 ? col('warn') : col('main')}>{lg.on}</Text>
121                <Text color={col('faint')}>{lg.off}</Text>
122                <Text dimColor>{` ${Math.round(l.pct)}%`}</Text>
123              </Text>
124            )
125          })}
126        </Text>
127      ) : null,
128    ], 1, true),
129  )
130
131  // ── sessions: every Claude Code session on this machine, waiting first, then working, then done
132  if (ss.length > 0) {
133    const look: Record<DeckSession['status'], [string, Role]> = { waiting: ['◆', 'amber'], working: ['●', 'main'], done: ['✓', 'gate'] }
134    const kids: unknown[] = [head('fd-ss-h', 'Sessions', 'dim', <Text key="fd-ss-n" dimColor>{sessionsLine(ss)}</Text>)]
135    for (const x of ss.slice(0, SESSION_ROWS)) {
136      const [glyph, role] = look[x.status]
137      const folder = x.cwd.split('/').filter(Boolean).pop() ?? ''
138      const where = [folder, x.where, x.isSelf ? 'this session' : ''].filter(Boolean).join(' · ')
139      kids.push(
140        <Box key={'fd-ss-' + x.pid} flexDirection="column" marginTop={1} width="100%">
141          <Box flexDirection="row" columnGap={1} width="100%">
142            <Box width={9} flexShrink={0}><Text color={col(role)} bold={x.status !== 'done'}>{`${glyph} ${x.status}`}</Text></Box>
143            <Box flexGrow={1} flexShrink={1} minWidth={0}><Text bold={x.status !== 'done'} wrap="truncate-end">{x.name}</Text></Box>
144            <Box flexShrink={0}>{clock('fd-ssc-' + x.pid, x.since, null, col('dim'))}</Box>
145          </Box>
146          <Box flexDirection="row" columnGap={1} paddingLeft={10} width="100%">
147            {x.detail ? <Box flexShrink={0}><Text color={col('amber')}>{x.detail}</Text></Box> : null}
148            <Box flexGrow={1} flexShrink={1} minWidth={0}><Text dimColor wrap="truncate-end">{where}</Text></Box>
149          </Box>
150        </Box>,
151      )
152    }
153    if (ss.length > SESSION_ROWS) kids.push(<Text key="fd-ss-more" color={col('faint')}>{`+${ss.length - SESSION_ROWS} more`}</Text>)
154    out.push(card('fd-sessions', kids, 1))
155  }
156
157  // ── architect: only once one has been consulted or spawned
158  if (a.consults.length > 0 || a.ids.length > 0) {
159    const last = a.consults[a.consults.length - 1]
160    out.push(
161      card('fd-arch', [
162        head('fd-arch-h', ARCH_LABEL, 'arch', <Text key="fd-arch-n"><Text color={col('arch')}>{advising ? 'advising' : 'on call'}</Text><Text dimColor>{` · ${plural(a.consults.length, 'consult')}`}</Text></Text>),
163        <Text key="fd-arch-tl" color={col('arch')} wrap="truncate-end">{consultTimeline(a, now, strip)}</Text>,
164        <Text key="fd-arch-last" dimColor wrap="truncate-end">
165          {!last ? 'not consulted yet'
166            : advising ? `consulting for ${fmtDuration(now - last.at)}`
167            : `last ${fmtDuration(now - (last.endAt ?? last.at))} ago · took ${fmtDuration((last.endAt ?? now) - last.at)}`}
168        </Text>,
169        <Text key="fd-arch-mo" wrap="truncate-end">
170          {(['before a plan', 'error repeats', 'before done'] as const).map(mo => (
171            <Text key={'fd-mo-' + mo} color={last?.moment === mo ? col('arch') : col('dim')} bold={last?.moment === mo}>{`${last?.moment === mo ? '◆' : '◇'} ${mo}  `}</Text>
172          ))}
173          <Text key="fd-mo-inf" color={col('faint')}>(inferred)</Text>
174        </Text>,
175        a.lastAdvice ? <Text key="fd-arch-adv" color={col('arch')} wrap="truncate-end">{`» ${a.lastAdvice}`}</Text> : null,
176      ], 1),
177    )
178  }
179
180  // ── gate: one cell per permission check, totals, a drill-down per tool family
181  const s = gateSummary(g)
182  if (g.recent.length > 0 || s.total > 0) {
183    const verdictColor = (c: DeckCheck) => (c.verdict === 'rule' ? col('gate') : c.verdict === 'cleared' ? col('cleared') : c.verdict === 'ask' ? col('amber') : col('warn'))
184    const said = (c: DeckCheck) => (c.verdict === 'rule' ? 'allowed' : c.verdict === 'cleared' ? decider : c.verdict === 'ask' ? 'pending' : 'denied')
185    const open = v.gateOpen
186    const kids: unknown[] = [
187      head('fd-gate-h', 'Permissions', 'gate', <Text key="fd-gate-n" dimColor>{plural(s.total, 'check')}</Text>),
188      <Text key="fd-strip" wrap="truncate-end">
189        {g.recent.slice(-strip).map((c, i) => <Text key={'fd-c-' + i} color={verdictColor(c)} dimColor={c.inSubagent}>{c.verdict === 'deny' ? '✗' : '■'}</Text>)}
190      </Text>,
191      <Text key="fd-gate-sum" wrap="truncate-end">
192        <Text color={col('gate')}>■</Text><Text dimColor>{` ${s.rule} allowed  `}</Text>
193        <Text color={col('cleared')}>■</Text><Text dimColor>{` ${s.cleared} ${decider}  `}</Text>
194        {s.ask > 0 ? <Text color={col('amber')}>{`■ ${s.ask} pending  `}</Text> : null}
195        <Text color={s.deny > 0 ? col('warn') : col('dim')}>{`✗ ${s.deny} denied`}</Text>
196      </Text>,
197      <Box key="fd-gate-b" flexDirection="row" columnGap={2} marginTop={1}>
198        {(['file', 'shell', 'other'] as const).map((b: DeckBucket) => {
199          const tl = g.totals[b]
200          const n = tl.rule + tl.ask + tl.cleared + tl.deny
201          return (
202            <Button key={'fd-gb-' + b} plain hotkey={b[0]} label={`${b} ${n}${open === b ? ' ▾' : ''}`} dimColor={n === 0}
203              onPress={() => kit.onGate(b)} />
204          )
205        })}
206      </Box>,
207    ]
208    if (open)
209      for (const [i, c] of g.recent.filter(x => x.bucket === open).slice(-5).entries())
210        kids.push(
211          <Text key={'fd-gd-' + i} wrap="truncate-end">
212            <Text color={verdictColor(c)}>{c.verdict === 'deny' ? '✗ ' : '■ '}</Text>
213            <Text color={col('dim')}>{`${said(c).padEnd(10)} `}</Text>
214            <Text dimColor={c.inSubagent}>{c.detail}</Text>
215          </Text>,
216        )
217    out.push(card('fd-gate', kids, 1))
218  }
219
220  // ── agents: one full-width row each, newest first, like Sessions. The title is Text so it truncates: a desktop
221  // draws a Button natively and wraps its label, so the press sits on the ▸ in front.
222  if (cards.length > 0) {
223    const statusColor = (c: DeckAgent) => (c.status === 'failed' ? col('warn') : c.status === 'done' ? col('gate') : col('agent'))
224    const glyph = (c: DeckAgent) => (c.status === 'running' ? '◐' : c.status === 'done' ? '✓' : c.status === 'failed' ? '✗' : '■')
225    const expand = (id: string) => () => kit.onExpand(id)
226    const rows = cards.slice().reverse()
227    const kids: unknown[] = [head('fd-ag-h', 'Agents', 'agent', <Text key="fd-ag-n" dimColor>{`${running.length} running · ${cards.length} total`}</Text>)]
228    for (const [i, c] of rows.slice(0, AGENT_ROWS).entries()) {
229      const isMax = c.lastStop === 'max_tokens'
230      const sameModel = !c.model || prettyModel(c.model) === modelName
231      const meta = [sameModel ? c.type : `${c.type} · ${prettyModel(c.model)}`, c.steps > 0 ? `${kTokens(c.ctx)} ctx · ${c.steps} st` : 'starting…'].join(' · ')
232      kids.push(
233        <Box key={'fd-ag-' + c.id} flexDirection="column" marginTop={1} width="100%">
234          <Box flexDirection="row" columnGap={1} width="100%">
235            <Box flexShrink={0}>
236              <Button key={'fd-cb-' + c.id} plain hotkey={i < 9 ? String(i + 1) : undefined} label={v.expanded === c.id ? '▾' : '▸'} onPress={expand(c.id)} />
237            </Box>
238            <Box width={9} flexShrink={0}><Text color={isMax ? col('warn') : statusColor(c)} bold={c.status === 'running'} wrap="truncate-end">{`${glyph(c)} ${c.status}`}</Text></Box>
239            <Box flexGrow={1} flexShrink={1} minWidth={0}><Text bold={c.status === 'running'} wrap="truncate-end">{cardTitle(c)}</Text></Box>
240            <Box flexShrink={0}>{clock('fd-cc-' + c.id, c.spawnedAt, c.endedAt, col('dim'))}</Box>
241          </Box>
242          <Box flexDirection="row" columnGap={1} paddingLeft={13} width="100%">
243            {isMax ? <Box flexShrink={0}><Text color={col('warn')}>max_tokens</Text></Box> : null}
244            <Box flexGrow={1} flexShrink={1} minWidth={0}><Text dimColor wrap="truncate-end">{meta}</Text></Box>
245          </Box>
246        </Box>,
247      )
248    }
249    if (rows.length > AGENT_ROWS) kids.push(<Text key="fd-ag-more" color={col('faint')}>{`+${rows.length - AGENT_ROWS} more`}</Text>)
250    const x = cards.find(c => c.id === v.expanded)
251    if (x) {
252      kids.push(
253        <Box key="fd-exp" flexDirection="column" marginTop={1} width="100%" borderStyle="single" borderColor={col('agent')} paddingX={1}>
254          <Text bold wrap="wrap">{x.description || x.type}</Text>
255          <Text dimColor wrap="truncate-end">{`${x.type} · ${prettyModel(x.model)} · ${x.status} · ${plural(x.steps, 'step')}`}</Text>
256          {x.steps > 0 ? <Text dimColor wrap="truncate-end">{`ctx ${kTokens(x.ctx)} · out ${kTokens(x.out)}`}</Text> : null}
257          {x.tools.length === 0 ? <Text color={col('faint')}>no tool calls yet</Text> : null}
258          {x.tools.map((n, i) => <Text key={'fd-et-' + i} color={n.isError ? col('warn') : col('text')} wrap="truncate-end">{`${n.isError ? '✗' : '·'} ${n.text}`}</Text>)}
259          {x.answer ? <Text dimColor wrap="wrap">{`» ${shorten(x.answer, 240)}`}</Text> : null}
260        </Box>,
261      )
262    }
263    kids.push(<Text key="fd-ag-hint" color={col('faint')}>{`press ▸ to expand an agent · 1-${Math.min(9, cards.length)} when the pane has focus`}</Text>)
264    out.push(card('fd-agents', kids, 1))
265  }
266
267  // ── other loops: model loops no card claims (workflow agents, compactions, memory forks)
268  if (lp.length > 0) {
269    const active = lp.filter(l => isLoopActive(l, now)).length
270    out.push(
271      <Box key="fd-loops" flexDirection="row" columnGap={1} marginTop={1} width="100%">
272        <Box flexShrink={0}><Text bold>other loops</Text></Box>
273        <Box flexShrink={0}><Text dimColor>{`${lp.length} seen · ${active} active`}</Text></Box>
274        <Text wrap="truncate-end">
275          {lp.slice(-Math.max(4, strip - 20)).map((l, i) => (
276            <Text key={'fd-lp-' + i} color={isLoopActive(l, now) ? col('agent') : l.isDone ? col('dim') : col('faint')}>{isLoopActive(l, now) ? '●' : l.isDone ? '✓' : '○'}</Text>
277          ))}
278        </Text>
279      </Box>,
280    )
281  }
282
283  // ── receipt: the turn now, or the last one
284  if (m.isRunning || r) {
285    out.push(
286      card('fd-receipt', [
287        m.isRunning ? (
288          <Box key="fd-rc" flexDirection="row" columnGap={1} width="100%">
289            <Box flexShrink={0}><Text color={col('main')}>{`◐ ${modelName.toLowerCase()} · turn`}</Text></Box>
290            <Box flexShrink={0}>{clock('fd-turn', t.startedAt, null, col('main'))}</Box>
291            <Box flexGrow={1} flexShrink={1} minWidth={0}><Text dimColor wrap="truncate-end">{`· ${plural(t.edits, 'edit')} · ${plural(t.errors, 'error')}`}</Text></Box>
292          </Box>
293        ) : r ? (
294          <Text key="fd-rc" wrap="wrap">
295            <Text color={r.reason === 'answer' ? col('gate') : col('warn')}>{r.reason === 'answer' ? '✓ ' : '✗ '}</Text>
296            <Text>{`last turn ${fmtDuration(r.durationMs)} · ${plural(r.agents, 'agent')} · ${plural(r.edits, 'edit')} · ${plural(r.errors, 'error')}`}</Text>
297            {r.costDelta !== null ? <Text color={col('main')}>{` · +${fmtUsd(r.costDelta)}`}</Text> : null}
298          </Text>
299        ) : null,
300        t.isReviewing ? <Text key="fd-rv" color={col('arch')}>architect reviewing before done (inferred)</Text> : null,
301      ], 1),
302    )
303  }
304
305  // ── log: prompts, spawns, completions, consults, edits, errors and denials; one agent's while you view it
306  const shown = (viewed ? lines.filter(l => l.agentId === viewed) : lines).slice(-8)
307  const colorOf = (l: DeckLogLine) =>
308    l.kind === 'error' ? col('warn') : l.kind === 'consult' ? col('arch') : l.who === 'main' ? col('main') : l.who === 'gate' ? col('gate') : l.who === 'you' ? col('text') : col('agent')
309  const hhmm = (ms: number) => (ms > 0 ? new Date(ms).toTimeString().slice(0, 5) : '--:--')
310  out.push(
311    card('fd-log', [
312      head('fd-log-h', 'Session log', 'dim'),
313      ...(shown.length === 0 ? [<Text key="fd-log-none" color={col('faint')}>nothing yet</Text>] : []),
314      ...shown.map((l, i) => (
315        <Box key={'fd-l-' + i} flexDirection="row" columnGap={1} width="100%">
316          <Box width={5} flexShrink={0}><Text color={col('faint')}>{hhmm(l.at)}</Text></Box>
317          <Box width={9} flexShrink={0}><Text color={colorOf(l)} bold wrap="truncate-end">{l.who}</Text></Box>
318          <Box flexGrow={1} flexShrink={1} minWidth={0}><Text color={l.kind === 'error' ? col('warn') : col('text')} wrap="truncate-end">{l.text}</Text></Box>
319        </Box>
320      )),
321    ], 1),
322  )
323
324  out.push(
325    <Box key="fd-reset" flexDirection="row" marginTop={1}>
326      <Button key="fd-reset-b" onPress={() => kit.onReset()}>Reset</Button>
327    </Box>,
328  )
329  return out
330}
331
hooks/icons.ts 172 lines
1// Lucide icons (ISC license, lucide.dev), drawn as small SVGs on the desktop surface.
2
3const PATHS = {
4  eye: '<path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"/><circle cx="12" cy="12" r="3"/>',
5  pencil: '<path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/><path d="m15 5 4 4"/>',
6  coffee: '<path d="M10 2v2"/><path d="M14 2v2"/><path d="M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1"/><path d="M6 2v2"/>',
7  'git-branch': '<line x1="6" x2="6" y1="3" y2="15"/><circle cx="18" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><path d="M18 9a9 9 0 0 1-9 9"/>',
8  folder: '<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/>',
9  'folder-open': '<path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/>',
10  file: '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/>',
11  search: '<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>',
12  'chevron-right': '<path d="m9 18 6-6-6-6"/>',
13  'chevron-down': '<path d="m6 9 6 6 6-6"/>',
14  check: '<path d="M20 6 9 17l-5-5"/>',
15  square: '<rect width="18" height="18" x="3" y="3" rx="2"/>',
16  'square-dot': '<rect width="18" height="18" x="3" y="3" rx="2"/><circle cx="12" cy="12" r="1"/>',
17  'square-check': '<rect width="18" height="18" x="3" y="3" rx="2"/><path d="m9 12 2 2 4-4"/>',
18  'square-dashed': '<path d="M5 3a2 2 0 0 0-2 2"/><path d="M19 3a2 2 0 0 1 2 2"/><path d="M21 19a2 2 0 0 1-2 2"/><path d="M5 21a2 2 0 0 1-2-2"/><path d="M9 3h1"/><path d="M9 21h1"/><path d="M14 3h1"/><path d="M14 21h1"/><path d="M3 9v1"/><path d="M21 9v1"/><path d="M3 14v1"/><path d="M21 14v1"/>',
19  plus: '<path d="M5 12h14"/><path d="M12 5v14"/>',
20  'list-checks': '<path d="m3 17 2 2 4-4"/><path d="m3 7 2 2 4-4"/><path d="M13 6h8"/><path d="M13 12h8"/><path d="M13 18h8"/>',
21  terminal: '<polyline points="4 17 10 11 4 5"/><line x1="12" x2="20" y1="19" y2="19"/>',
22  'loader-circle': '<path d="M21 12a9 9 0 1 1-6.219-8.56"/>',
23  gauge: '<path d="m12 14 4-4"/><path d="M3.34 19a10 10 0 1 1 17.32 0"/>',
24} as const
25
26export type IconName = keyof typeof PATHS
27
28/** A color, or a pair the drawing picks from by light or dark mode. */
29export type Ink = string | { light: string; dark: string }
30
31/** `[style block, value]` for an ink: a pair becomes a CSS variable that follows prefers-color-scheme. */
32const paint = (c: Ink, name = 'ink'): [string, string] =>
33  typeof c === 'string'
34    ? ['', c]
35    : [`<style>svg{--${name}:${c.light}}@media (prefers-color-scheme: dark){svg{--${name}:${c.dark}}}</style>`, `var(--${name})`]
36
37const FONT = 'font-family="-apple-system, BlinkMacSystemFont, system-ui, sans-serif"'
38const esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
39
40/** One Lucide icon, `size` px square, stroked in `color`. */
41export const icon = (name: IconName, color: Ink, size = 16) => {
42  const [css, c] = paint(color)
43  return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" style="stroke:${c}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${css}${PATHS[name]}</svg>`
44}
45
46/** An icon centred on a tinted disc, as the "Right now" card leads with. */
47export const disc = (name: IconName, color: Ink, size = 44) => {
48  const [css, c] = paint(color)
49  const s = Math.round(size * 0.5)
50  const o = (size - s) / 2
51  return (
52    `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">${css}` +
53    `<circle cx="${size / 2}" cy="${size / 2}" r="${size / 2}" style="fill:${c}" fill-opacity="0.18"/>` +
54    `<g transform="translate(${o} ${o}) scale(${s / 24})" fill="none" style="stroke:${c}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${PATHS[name]}</g></svg>`
55  )
56}
57
58/** A rounded label on a tint of its own color: "Reading", "Edited". */
59export const pill = (text: string, color: Ink) => {
60  const [css, c] = paint(color)
61  const w = Math.round(text.length * 7.4 + 22)
62  const h = 22
63  return {
64    w,
65    h,
66    source:
67      `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${css}` +
68      `<rect width="${w}" height="${h}" rx="${h / 2}" style="fill:${c}" fill-opacity="0.18"/>` +
69      `<text x="${w / 2}" y="15" text-anchor="middle" font-size="12" font-weight="600" style="fill:${c}" ${FONT}>${esc(text)}</text></svg>`,
70  }
71}
72
73/** A file-type tag: the extension, short, on a square tint. */
74export const fileTag = (ext: string, color: Ink) => {
75  const [css, c] = paint(color)
76  const label = (ext || '·').slice(0, 4).toUpperCase()
77  const w = Math.max(26, Math.round(label.length * 7 + 12))
78  const h = 20
79  return {
80    w,
81    h,
82    source:
83      `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${css}` +
84      `<rect width="${w}" height="${h}" rx="5" style="fill:${c}" fill-opacity="0.16"/>` +
85      `<text x="${w / 2}" y="14" text-anchor="middle" font-size="10" font-weight="700" style="fill:${c}" ${FONT}>${esc(label)}</text></svg>`,
86  }
87}
88
89/** A hairline: drawn without a width it fills its slot, stretched by preserveAspectRatio. */
90export const rule = (color: Ink) => {
91  const [css, c] = paint(color)
92  return `<svg xmlns="http://www.w3.org/2000/svg" width="2000" height="9" viewBox="0 0 2000 9" preserveAspectRatio="none">${css}<line x1="0" y1="4.5" x2="2000" y2="4.5" style="stroke:${c}" stroke-opacity="0.7" stroke-width="1" vector-effect="non-scaling-stroke"/></svg>`
93}
94
95/** A letter-spaced caps label ("RIGHT NOW", "ALL FILES"), its width from its text. */
96export const caps = (text: string, color: Ink, size = 12) => {
97  const [css, c] = paint(color)
98  const t = text.toUpperCase()
99  const w = Math.ceil(t.length * (size * 0.68 + 1.6)) + 2
100  const h = Math.round(size * 1.5)
101  return {
102    w,
103    h,
104    source:
105      `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${css}` +
106      `<text x="0" y="${Math.round(size * 1.1)}" font-size="${size}" font-weight="700" letter-spacing="1.6" style="fill:${c}" ${FONT}>${esc(t)}</text></svg>`,
107  }
108}
109
110/** A headline in one line, cut with an ellipsis to fit `maxW` px. */
111export const headline = (text: string, color: Ink, maxW: number, size = 17) => {
112  const [css, c] = paint(color)
113  const per = size * 0.56
114  const fit = Math.max(4, Math.floor(maxW / per))
115  const t = text.length > fit ? text.slice(0, fit - 1) + '…' : text
116  const w = Math.min(maxW, Math.ceil(t.length * per) + 4)
117  const h = Math.round(size * 1.45)
118  return {
119    w,
120    h,
121    source:
122      `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${css}` +
123      `<text x="0" y="${Math.round(size * 1.1)}" font-size="${size}" font-weight="700" style="fill:${c}" ${FONT}>${esc(t)}</text></svg>`,
124  }
125}
126
127/** The tree's small filled disclosure triangle. */
128export const triangle = (open: boolean, color: Ink, size = 10) => {
129  const [css, c] = paint(color)
130  return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 10 10">${css}<path d="${open ? 'M1.5 3h7L5 7.5z' : 'M3 1.5v7L7.5 5z'}" style="fill:${c}"/></svg>`
131}
132
133/** A progress bar that fills its slot: `done` of `total`, the doing share lighter. */
134export const progress = (done: number, doing: number, total: number, color: Ink, track: Ink) => {
135  const [cssA, c] = paint(color, 'bar')
136  const [cssB, t] = paint(track, 'track')
137  const W = 1000
138  const a = total ? (W * done) / total : 0
139  const b = total ? (W * doing) / total : 0
140  return (
141    `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="8" viewBox="0 0 ${W} 8" preserveAspectRatio="none">${cssA}${cssB}` +
142    `<rect width="${W}" height="8" style="fill:${t}" fill-opacity="0.22"/>` +
143    `<rect x="${a}" width="${b}" height="8" style="fill:${c}" fill-opacity="0.45"/>` +
144    `<rect width="${a}" height="8" style="fill:${c}"/></svg>`
145  )
146}
147
148/** The top of a hero card: icon disc, caps label, title, a line under it; on its own tinted panel unless `panel` is false.
149 * The disc's left edge sits at x 0, in line with the card's rows below it. */
150export function hero(o: { icon: IconName; accent: Ink; label: string; title: string; sub: string; w: number; panel?: boolean }) {
151  const [css, c] = paint(o.accent, 'acc')
152  const H = 78
153  const x = 58
154  const room = Math.max(60, o.w - x - 14)
155  const cut = (s: string, size: number, bold: boolean) => {
156    const per = size * (bold ? 0.58 : 0.52)
157    const fit = Math.max(4, Math.floor(room / per))
158    return s.length > fit ? s.slice(0, fit - 1) + '…' : s
159  }
160  const label = o.label.toUpperCase()
161  return (
162    `<svg xmlns="http://www.w3.org/2000/svg" width="${o.w}" height="${H}" viewBox="0 0 ${o.w} ${H}">${css}` +
163    `<style>.bg{fill:#f0eee6}.t{fill:#1f1f1f}.m{fill:#5f5f5c}@media (prefers-color-scheme: dark){.bg{fill:#30302e}.t{fill:#ececec}.m{fill:#9a9a96}}</style>` +
164    (o.panel === false ? '' : `<rect class="bg" width="${o.w}" height="${H}" rx="12"/>`) +
165    `<circle cx="22" cy="${H / 2}" r="22" style="fill:${c}" fill-opacity="0.18"/>` +
166    `<g transform="translate(11 ${H / 2 - 11}) scale(${22 / 24})" fill="none" style="stroke:${c}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${PATHS[o.icon]}</g>` +
167    `<text x="${x}" y="24" font-size="11" font-weight="700" letter-spacing="1.6" style="fill:${c}" ${FONT}>${esc(label)}</text>` +
168    `<text class="t" x="${x}" y="47" font-size="17" font-weight="700" ${FONT}>${esc(cut(o.title, 17, true))}</text>` +
169    `<text class="m" x="${x}" y="66" font-size="12.5" ${FONT}>${esc(cut(o.sub, 12.5, false))}</text></svg>`
170  )
171}
172
hooks/shimmer.tsx 36 lines
1// A file name with a band of light sweeping across it: the file Claude is reading or editing right now.
2// It ticks on the surface's frame clock, so the pane need not redraw.
3import type { ClientModule } from 'claude-code'
4
5type Props = { text: string; color: string; shine: string }
6type State = { at: number }
7
8/** Characters lit at once, and the pause after a sweep before the next. */
9const BAND = 3
10const GAP = 6
11
12const Shimmer: ClientModule<Props, State> = (props, surface) => {
13  const { Text } = surface.elements
14  const at = surface.state?.at ?? 0
15  if (surface.state === undefined) {
16    surface.setState({ at: 0 })
17    surface.every(80, () => {
18      const cur = surface.state?.at ?? 0
19      surface.setState({ at: (cur + 1) % (props.text.length + BAND + GAP) })
20    })
21  }
22  const from = Math.max(0, at - BAND)
23  const head = props.text.slice(0, from)
24  const lit = props.text.slice(from, at)
25  const tail = props.text.slice(at)
26  return (
27    <Text bold wrap="truncate-end">
28      <Text color={props.color}>{head}</Text>
29      <Text color={props.shine}>{lit}</Text>
30      <Text color={props.color}>{tail}</Text>
31    </Text>
32  )
33}
34
35export default Shimmer
36
hooks/elapsed.tsx 38 lines
1// A running agent's clock, ticking on the surface's frame clock so the pane need not redraw.
2// `since` and `now` come from the hooks module's $.clock; between redraws it adds its own ticks.
3import type { ClientModule } from 'claude-code'
4
5type Props = { since: number; now: number; endAt: number | null; color: string }
6type Ref = { base: number; ticks: number; lastNow: number; isRunning: boolean }
7type State = { ref: Ref }
8
9const fmt = (ms: number) => {
10  const s = Math.max(0, Math.floor(ms / 1000))
11  const m = Math.floor(s / 60)
12  return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
13}
14
15const Elapsed: ClientModule<Props, State> = (props, surface) => {
16  const { Text } = surface.elements
17  const ref = surface.state?.ref ?? { base: 0, ticks: 0, lastNow: -1, isRunning: true }
18  if (props.now !== ref.lastNow) {
19    // A fresh reading from the hooks module: restart the local count from it.
20    ref.lastNow = props.now
21    ref.base = (props.endAt ?? props.now) - props.since
22    ref.ticks = 0
23  }
24  ref.isRunning = props.endAt === null
25  if (surface.state === undefined) {
26    surface.setState({ ref })
27    surface.every(1000, () => {
28      if (ref.isRunning) {
29        ref.ticks += 1
30        surface.setState({ ref })
31      }
32    })
33  }
34  return <Text color={props.color}>{fmt(ref.base + ref.ticks * 1000)}</Text>
35}
36
37export default Elapsed
38
types/index.d.ts 146 lines
1export type ItemStatus = 'draft' | 'todo' | 'doing' | 'done'
2/** `title` is a short label (a few words); anything longer goes in `details`. */
3export type WorkItem = { id: string; title: string; stage: string; status: ItemStatus; details?: string }
4export type DevEntry = { stages: string[]; items: WorkItem[] }
5export type Part = { id: string; date: string; status: string }
6export type Group = {
7  key: string
8  title: string
9  project: string
10  short: string
11  size?: string
12  start: string
13  end: string
14  open: boolean
15  parts: Part[]
16  stages: string[]
17  items: WorkItem[]
18  /** The plan file this task's work items live in. */
19  file?: string
20}
21export type Snap = {
22  status: 'idle' | 'loading' | 'ready' | 'none' | 'error'
23  message?: string
24  folder?: string
25  shorts: string[]
26  cur?: Group
27  prev: Group[]
28  next: Group[]
29  /** The current task was picked with `/task switch`, not the earliest open plan. */
30  isPicked?: boolean
31  version?: number
32}
33export type PaneUi = { showPrev: boolean; stage?: string; paneOpen?: boolean; selected?: string }
34
35/* The Workbench pane */
36/** One file Claude read or edited this session; `active` while the tool runs. */
37export type Touch = { path: string; kind: 'read' | 'edited'; active: boolean; at: number }
38/** What Claude did last in the turn under way: `busy` from the prompt to the end of the turn; `kind` the last file read or edit, command or search; `since` when the turn began. */
39export type Activity = { busy: boolean; kind?: 'read' | 'edited' | 'run' | 'search'; label?: string; path?: string; since?: number }
40/** One directory entry as the tree shows it. */
41export type Entry = { name: string; dir: boolean; size: number }
42export type Files = {
43  /** The folder the tree shows, absolute. */
44  root: string
45  /** The session's folder, where "Back to project" returns. */
46  project: string
47  expanded: string[]
48  dirs: Record<string, Entry[]>
49  showSizes: boolean
50  showHidden: boolean
51  query: string
52  /** Every file under root, relative, read once a search starts. */
53  all: string[]
54}
55export type Git = { isRepo: boolean; branch: string; top: string; dirty: string[] }
56/** `sections`: which of the pane's three cards are open (kept across sessions in the store). */
57export type WorkbenchUi = { itemsOpen: boolean; adding?: boolean; sections?: { tasks: boolean; files: boolean; deck: boolean } }
58
59/* The Flightdeck card (adapted from claude-flightdeck, MIT, Stephen Casella) */
60export type DeckMoment = 'before a plan' | 'error repeats' | 'before done'
61export type DeckBucket = 'file' | 'shell' | 'other'
62/** rule: settings allowed it. ask: put to the decider, outcome pending. cleared: asked, then ran. deny: refused. */
63export type DeckVerdict = 'rule' | 'ask' | 'cleared' | 'deny'
64export type DeckMain = { model: string; effort: string; mode: string; steps: number; isRunning: boolean }
65export type DeckUsage = {
66  pct: number | null
67  tokens: number | null
68  window: number
69  costUsd: number | null
70  limits: { kind: string; pct: number }[]
71  compactions: number
72  lastCompactAt: number | null
73}
74export type DeckConsult = { id: string; at: number; endAt: number | null; moment: DeckMoment; via: string }
75export type DeckArchitect = { consults: DeckConsult[]; ids: string[]; seen: string[]; lastAdvice: string }
76export type DeckCheck = { id: string; tool: string; bucket: DeckBucket; verdict: DeckVerdict; inSubagent: boolean; detail: string; at: number }
77export type DeckTally = { rule: number; ask: number; cleared: number; deny: number }
78export type DeckGate = { recent: DeckCheck[]; totals: Record<DeckBucket, DeckTally> }
79export type DeckToolNote = { tool: string; text: string; isError: boolean }
80export type DeckAgent = {
81  id: string
82  type: string
83  model: string
84  description: string
85  status: string
86  spawnedAt: number
87  endedAt: number | null
88  /** The agent's context now: input + cache read + cache write of its latest step. */
89  ctx: number
90  /** Output tokens summed over its steps. */
91  out: number
92  steps: number
93  lastStop: string | null
94  tools: DeckToolNote[]
95  answer: string
96}
97/** A model loop whose id matches no card: a workflow agent, a compaction or a memory fork. */
98export type DeckLoop = { id: string; steps: number; firstAt: number; lastAt: number; isDone: boolean }
99export type DeckLogLine = { at: number; who: string; text: string; agentId: string | null; kind: 'info' | 'error' | 'consult' | 'done' }
100export type DeckTurn = { edits: number; errorStreak: number; errors: number; isReviewing: boolean; startedAt: number; costAtStart: number | null }
101export type DeckReceipt = { durationMs: number; agents: number; edits: number; errors: number; costDelta: number | null; reason: string }
102export type DeckView = { expanded: string | null; gateOpen: DeckBucket | null }
103export type DeckRoster = { architectTypes: string[] }
104/** Another Claude Code session on this machine, from its `~/.claude/sessions/<pid>.json`. */
105export type DeckSessionStatus = 'working' | 'waiting' | 'done'
106export type DeckSession = {
107  pid: number
108  id: string
109  name: string
110  cwd: string
111  /** desktop, vscode, terminal, background */
112  where: string
113  status: DeckSessionStatus
114  /** What a waiting session waits for: `input needed`, `dialog open`; empty otherwise. */
115  detail: string
116  /** When the status last changed; 0 unknown. */
117  since: number
118  isSelf: boolean
119}
120
121declare module 'claude-code' {
122  interface PluginState {
123    workbench: {
124      snap: Snap
125      ui: PaneUi
126      files: Files
127      git: Git
128      touched: Touch[]
129      activity: Activity
130      bench: WorkbenchUi
131      deckMain: DeckMain
132      deckUsage: DeckUsage
133      deckArchitect: DeckArchitect
134      deckGate: DeckGate
135      deckAgents: DeckAgent[]
136      deckLoops: DeckLoop[]
137      deckLog: DeckLogLine[]
138      deckTurn: DeckTurn
139      deckReceipt: DeckReceipt | null
140      deckView: DeckView
141      deckRoster: DeckRoster
142      deckSessions: DeckSession[]
143    }
144  }
145}
146