SLOPSHOPPER

plan-progress

Live plan progress bars above the Claude Code prompt: stages, steps, a pixel fill and soft sounds for decision, error and done

panebandguardcommandprompttool
v0.5.69MITupdated 2026-10-150x5421/plan-progress/plugins/plan-progress
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · plan-progress
│ ┃ 進度條樣式 ✕ › fix the failing auth test and add an audit log call │ ┃ 進度條 提示音 [ 儲存 │ ┃ ⏺ Read(src/auth.ts) │ ┃ [ 顯示 ] [ 隱藏 ] [ 開 ] [ 關 ] ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ 其他 session ⏺ Bash(bun test) │ ┃ ⎿ Denied by plan-progress: plan-progress: several changes a │ ┃ [ 開 ] [ 關 ] │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ Subagent 顯示 ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ [ 展開 ] [ 摘要 ] [ 隱藏 ] › /progress │ ┃ ⎿ plan-progress: Progress bars hidden. No plan yet. /progress-demo │ ┃ │ ┃ 顏色 │ ┃ │ ┃ [ 跟樣式預設 ] [ 陶土橘 ] [ 藍 ] [ 紫 ] [ 青 │ ┃ │ ┃ │ ┃ 進度條樣式 │ ┃ │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ 分段 segments [ ✓ 使用中 ] │ │ ┃ ╰──────────────────────────────────────────╯ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · 進度條樣式
進度條 提示音 [ 儲存並關閉 ] [ 顯示 ] [ 隱藏 ] [ 開 ] [ 關 ] 其他 session [ 開 ] [ 關 ] Subagent 顯示 [ 展開 ] [ 摘要 ] [ 隱藏 ] 顏色 [ 跟樣式預設 ] [ 陶土橘 ] [ 藍 ] [ 紫 ] [ 青 ] [ 桃紅 ] [ 墨 進度條樣式 ╭──────────────────────────────────────────────────────────╮ │ 分段 segments [ ✓ 使用中 ] │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ 細線 hairline [ 使用 ] │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ 串珠 beads [ 使用 ] │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ 刻度字 ledger [ 使用 ] │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ 路線圖 transit [ 使用 ] │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ 點陣 grid [ 使用 ] │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ 原版 original [ 使用 ] │ ╰──────────────────────────────────────────────────────────╯
README

plan-progress(多樣式版)

在 Claude Code 輸入框上方顯示即時進度條:Claude 接到多步驟任務時,會把工作拆成幾個階段和步驟,邊做邊更新,你看得到它走到哪。

這個版本是 zycck/claude-mods 裡 plan-progress 外掛的 fork(衍生版本),在原作上加了可切換的外觀(6 種新樣式加原版,共 7 種)和一個樣式面板。

原作者

Kirill Serditov(@zycck),以 MIT 授權發布。

本專案從原作 commit ea2c96b 複製而來。以下功能都是原作者做的,本版本沿用:

  • 進度條的運作機制:Claude 建立一次完整計畫,之後只送很短的更新(例如「下一步」)
  • 寫進系統提示的使用規則,以及「連續動手幾次還沒建進度條就提醒」的檢查
  • Subagent(子代理)狀態條:每個子代理正在做什麼、跑多久、是否在等你核准
  • 需要你決定、出錯、完成時的提示音
  • 底部的 Progress 按鈕,以及 /progress、/progress-demo、/progress-sounds、/progress-clear 指令
  • 原版的像素顆粒進度條畫法(本版本保留為 original 樣式)

這個版本改了什麼

由 @0x5421 修改。

類別內容
新增 6 種樣式分段 segments、細線 hairline、串珠 beads、刻度字 ledger、路線圖 transit、點陣 grid,畫法在 hooks/styles.ts
樣式面板點進度條區右上角的齒輪 ⚙(或輸入 /progress-style)打開,7 種樣式各有即時預覽,點「使用」立刻切換
齒輪在進度條區右上角原版底部的 Progress 按鈕拿掉,改成一個 ⚙,放在輸入框上方進度條那塊灰底區的右上角,自成一欄、不多佔一行(新版桌面 app 會把外掛放在底部的東西另排一行,所以不放底部);沒有進度條時看不到它,用 /progress-style 打開面板;顯示/隱藏進度條在面板最上面切換
隱藏會一直記住原版隱藏後,有新進度條或開新 session 就會自動跳回顯示。現在隱藏後一直保持隱藏,直到你按「顯示」或用 /progress-demo
顏色⚙ 面板的「顏色」可以替所有樣式換「跑著」的顏色:陶土橘、藍、紫、青、桃紅、墨黑,或「跟樣式預設」。完成的綠、等你決定的黃、出錯的紅固定不變。細線和刻度字平常黑白,只有線頭和游標格跟著換色
提示音開關面板裡可以開關提示音,預設開;關掉後 /progress-sounds 試聽仍會響
Subagent 顯示面板最上面切換「展開/摘要/隱藏」:每個 subagent 一條、合成一行只顯示各狀態數量、或完全不顯示
完成音等回覆寫完才響原版 Claude 一把最後一步標完成就變 Done、響完成音,那時回覆還沒寫。現在進度條先停在最後一步,等這一輪回覆整則寫完才變 Done、響一次完成音;subagent 全部跑完的完成音也一樣等到回覆寫完
其他 session 的進度條桌面版每個 session 會把自己的狀態和進度條寫進 ~/.claude/plan-progress/sessions/。其他還在跑、跑完或在等你決定的 session,會在你的進度條下方各顯示一條(它最新的那條進度條,用你選的樣式畫),最多 5 條,名稱用 app 左側清單上的 session 標題(讀不到時才用「專案名 · 進度條標題」);這時你目前這個 session 自己的進度條會用圓角框框起來,跟其他 session 的分開,框的上緣線上寫著這個 session 在左側清單上的名稱(就是其他 session 看到的那個名字),不多佔一行;點左邊的標題就切換過去。跑完或等你決定的 session,只要你點進去看過(從進度條標題、左側清單或通知都算),或你正看著它跑完,所有 session 都會拿掉它那一條;按 ✕ 也一樣,會先變淡再消失。它開始下一輪後會再出現。還在跑的 session 一律顯示,沒有 ✕;它還沒有進度條時,那一列畫一條來回流動的短條(顏色跟著你選的樣式),旁邊寫它正在做什麼(例如「執行指令 · Bash」「改檔案 · Edit」,剛開始還沒用工具時寫「處理中」),右邊顯示這一輪已經跑了多久。⚙ 面板的「其他 session」可以開關,預設開
自動收掉完成的進度條原版完成的進度條會一直留著(最多 3 條)。現在你送出下一則訊息時,或你從別處點進這個 session 時(左側清單、通知、其他 session 的進度條標題),完成的那幾條會漸淡後消失,進行中的不受影響;你停在畫面上看著它跑完時會先留著
跳著做也算對Claude 有時先跳過某一步、晚點再回頭做。進度條的文字和步數跟著「正在做的那一步」,步數是「做完幾步/總共幾步」;被跳過、之後要補的步驟用主色虛線框標出來,跟還沒輪到的步驟分開
右邊欄統一細線右邊顯示已經跑了多久(完成後改成步數),其他樣式一律顯示「第幾步/總步數」,例如 3/7
記住選擇選好的樣式、subagent 顯示方式、進度條顯示/隱藏、提示音開關都會存起來,下次開 session 沿用
切換指令/progress-style 打開面板並列出樣式;/progress-style <名稱> 直接切換;/progress-style next 換下一個
深淺色新樣式的顏色跟著深淺色主題切換
規則調整階段名一律用英文,任務標題和步驟仍用使用者的語言
修正原版 subagent 條在淺色主題下文字幾乎看不見
修正每一列左邊的狀態圖示(● ? ! ✓)畫在同一個寬度的位置,後面的標題起點對齊;每一列的標題起點和進度條左邊緣都對齊:右邊的百分比或時間放進同寬的欄位,所有標題都用同一種無邊框按鈕;標題最多佔整列 40%,再長才截斷
修正判斷「Claude 在問你問題」時也認得中文全形問號「?」,不會再把中文提問的回覆擋回去
測試tests/panel.test.ts:畫出 ⚙ 按鈕、樣式面板和 7 種樣式的進度條,以及分段與點陣兩種樣式各種狀態的畫法,並按按鈕確認會切換

樣式一覽

名稱說明
segments(預設)一個階段一格,現在這一段最顯眼、做完的變淡;目前階段是一整段漸層,正在做的那一步慢慢呼吸;等你決定或出錯時只有出問題那一步亮黃或亮紅;放不下名字的階段縮成細條,陶土橘
hairline2px 細線+會呼吸的線頭,平常黑白,右邊顯示經過時間(完成後改成步數)
beads一步一顆珠子,同階段用線串起來,藍色
ledger等寬字+小方格,正在做的那格慢慢呼吸,只有要注意時才有顏色
transit像捷運路線圖,站名在下方,現在位置是一個會呼吸的圓圈,紫色,比其他樣式高一點;放不下的站名不顯示,不會截成「Res…」
grid一步一個小方格,兩格一欄,階段之間空一格,步驟多也排得下,青色
original原作者的像素顆粒進度條

安裝

在 Claude Code 外的終端機執行:

claude plugin marketplace add 0x5421/plan-progress
claude plugin install plan-progress@fork-zycck-mods

已經下載到本機的話,第一行改成 claude plugin marketplace add /path/to/plan-progress。

開一個新的 session 就會載入。

改完之後更新

先把 plugins/plan-progress/.claude-plugin/plugin.json 的 version 加一,再執行:

claude plugin update plan-progress@fork-zycck-mods

版本號沒變的話,更新指令會說已經是最新版而不更新。

使用

  • 想換外觀:點進度條區右上角的齒輪 ⚙,或輸入 /progress-style,在面板裡點「使用」
  • 想看示範:/progress-demo
  • 隱藏/顯示進度條:在 ⚙ 面板最上面點「顯示」或「隱藏」,或輸入 /progress
  • 開關提示音:在 ⚙ 面板的「提示音」點「開」或「關」
  • 清掉所有進度條:/progress-clear

進度條在桌面版 app 顯示圖形;在終端機只顯示文字進度條,樣式切換不影響終端機。

測試

claude plugin test plugins/plan-progress

授權

MIT。原作版權屬於 Kirill Serditov,見 LICENSE;依 MIT 授權,轉發或修改時必須保留這份版權聲明與授權文字。本版本的修改同樣以 MIT 授權提供。

Source 3 files
hooks/register.tsx 1773 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AgentRun, OtherSession, OthersView, Plan, PlanStage, PlanState, PlanStep, StepStatus } from '../types'
5import { ACCENT_IDS, ACCENT_INFO, DEFAULT_STYLE, STYLE_IDS, STYLE_INFO, STYLES, accentGlyph, isAccentId, isStyleId, setAccent } from './styles'
6import type { StyleId } from './styles'
7
8const TOOL = 'mcp__plan-progress__plan_progress'
9const plans = atom({ plugin: 'plan-progress', key: 'plans' } as const, [])
10const MAX_BARS = 3
11// a space as wide as a digit, so '  0%' and '100%' take the same room
12const FIGURE_SPACE = String.fromCharCode(0x2007)
13// whether the bars show; kept in $.store too, so hidden stays hidden across sessions and new bars
14// until the person shows them again
15const isOpen = atom({ plugin: 'plan-progress', key: 'isOpen' } as const, true)
16const SHOWN_STORE_KEY = 'isOpen'
17const setShown = async ($: EngineInterface, shown: boolean) => {
18  await update($, isOpen, () => shown)
19  await $.store.set(SHOWN_STORE_KEY, shown)
20}
21// whether the decision, error and done sounds play; kept in $.store the same way
22const soundsOn = atom({ plugin: 'plan-progress', key: 'sounds' } as const, true)
23const SOUNDS_STORE_KEY = 'sounds'
24const setSounds = async ($: EngineInterface, isOn: boolean) => {
25  await update($, soundsOn, () => isOn)
26  await $.store.set(SOUNDS_STORE_KEY, isOn)
27}
28const tick = atom({ plugin: 'plan-progress', key: 'tick' } as const, 0)
29// the chosen look; kept in $.store too so a new session starts with it
30const barStyle = atom({ plugin: 'plan-progress', key: 'style' } as const, DEFAULT_STYLE as string)
31const STYLE_STORE_KEY = 'style'
32const styleOf = async ($: EngineInterface): Promise<StyleId> => {
33  const v = await read($, barStyle)
34  return isStyleId(v) ? v : DEFAULT_STYLE
35}
36const setStyle = async ($: EngineInterface, id: StyleId) => {
37  await update($, barStyle, () => id)
38  await $.store.set(STYLE_STORE_KEY, id)
39}
40// whether the band shows one row instead of all of them; kept in $.store too, so a new session starts folded
41const isCollapsed = atom({ plugin: 'plan-progress', key: 'collapsed' } as const, false)
42const COLLAPSED_STORE_KEY = 'collapsed'
43const setCollapsed = async ($: EngineInterface, collapsed: boolean) => {
44  await update($, isCollapsed, () => collapsed)
45  await $.store.set(COLLAPSED_STORE_KEY, collapsed)
46}
47// the fold button: ⌃ folds the band to nothing but ⌄ and the number of rows hidden, which opens it again. On the desktop ⌃ sits
48// at the middle of the band's top edge, one row up out of the tree; a terminal has no room above, so there it takes a
49// column left of the gear
50const FOLD_CELLS = 5
51const FOLD_UP = '⌃'
52const FOLD_DOWN = '⌄'
53// the pane that lists every style with a live preview; opened from the ⚙ beside the Progress button
54const STYLE_PANE = 'plan-progress-styles'
55const STYLE_PANE_TITLE = '進度條樣式'
56
57// what the footer's gear does: it opens the style pane, where the bars are also shown or hidden
58async function openStyles($: EngineInterface) {
59  return $.ui.open({ id: STYLE_PANE, title: STYLE_PANE_TITLE })
60}
61// the gear that opens the pane; U+FE0E asks for the plain text glyph, not the colour emoji
62const SETTINGS_GLYPH = '⚙︎'
63// the column the gear takes at the band's right, in cells
64const GEAR_CELLS = 3
65
66// how subagent strips show under a bar: one strip each, one summary line, or none
67const AGENT_VIEWS = ['expanded', 'summary', 'hidden'] as const
68type AgentView = (typeof AGENT_VIEWS)[number]
69const AGENT_VIEW_LABEL: Record<AgentView, string> = { expanded: '展開', summary: '摘要', hidden: '隱藏' }
70const isAgentView = (v: unknown): v is AgentView => typeof v === 'string' && (AGENT_VIEWS as readonly string[]).includes(v)
71const agentView = atom({ plugin: 'plan-progress', key: 'agentView' } as const, 'expanded' as string)
72const AGENT_VIEW_STORE_KEY = 'agentView'
73const agentViewOf = async ($: EngineInterface): Promise<AgentView> => {
74  const v = await read($, agentView)
75  return isAgentView(v) ? v : 'expanded'
76}
77const setAgentView = async ($: EngineInterface, v: AgentView) => {
78  await update($, agentView, () => v)
79  await $.store.set(AGENT_VIEW_STORE_KEY, v)
80}
81// the colour the bars run in, one of ACCENT_IDS, or '' for each style's own; the drawing module holds it too
82const accentChoice = atom({ plugin: 'plan-progress', key: 'accent' } as const, '' as string)
83const ACCENT_STORE_KEY = 'accent'
84const setAccentChoice = async ($: EngineInterface, v: string) => {
85  setAccent(v)
86  await update($, accentChoice, () => v)
87  await $.store.set(ACCENT_STORE_KEY, v)
88}
89const STRIP_H = 18
90const STRIP_GAP = 3
91const MAX_STRIPS = 4 // past this, the finished ones fold into one "+N more" strip
92const FOLD_MS = 5000 // finished strips stay this long, failed ones stay until the bar closes
93
94const STATE_COLOR: Record<PlanState, string> = { running: '#8B7CF6', needs_input: '#E09A1E', error: '#E5484D', done: '#30A46C' }
95const STATE_GLYPH: Record<PlanState, string> = { running: '●', needs_input: '?', error: '!', done: '✓' }
96const STATUSES: StepStatus[] = ['pending', 'active', 'done', 'error', 'skipped']
97const TRACK_H = 22
98const NARROW = 360
99
100const RULES = `# Progress bars
101Tasks needing more than ~3 edits or commands get a bar via ${TOOL}: create it once with the full breakdown (2-7 stages with short steps, or kind "todo" for one flat list; titles of at most 4 words; the bar title and step titles in the user's language, stage names always in English), then update it with short calls only: {id, next:true} when the active step is finished, or {id, done:[...], active:"..."}, {id, failed:"...", note}. Send state "needs_input" with a note before asking the user to decide. Never describe the bars to the user.`
102
103type Raw = Record<string, unknown>
104const str = (v: unknown, max = 120) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, max) : '')
105// a message as a person reads it: the app wraps pasted text and slash commands in tags (<pasted_content id="…">,
106// <command-name>/handoff</command-name>), which made a session's row read "<pasted_content id="5589"> 0x…".
107// Pasted text becomes (貼上的內容), a command its name, and any other tag goes
108const readable = (v: unknown, max = 60) => {
109  if (typeof v !== 'string') return ''
110  const t = v
111    .replace(/<pasted_content\b[^>]*>[\s\S]*?(<\/pasted_content>|$)/g, ' (貼上的內容) ')
112    .replace(/<command-name>\s*([^<]*?)\s*<\/command-name>/g, ' $1 ')
113    .replace(/<command-(message|args)>[\s\S]*?(<\/command-\1>|$)/g, ' ')
114    .replace(/<\/?[a-zA-Z][\w-]*(\s[^<>]*)?>?/g, ' ')
115  return str(t, max)
116}
117const status = (v: unknown): StepStatus => (STATUSES.includes(v as StepStatus) ? (v as StepStatus) : 'pending')
118const list = (v: unknown): Raw[] => (Array.isArray(v) ? v.filter(x => x && typeof x === 'object') : []) as Raw[]
119const isFinished = (s: StepStatus) => s === 'done' || s === 'skipped'
120
121const same = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase()
122
123// short updates: {next:true}, {done:[titles]}, {active:title}, {failed:title} against the stored plan
124function applyOps(stages: PlanStage[], input: Raw): PlanStage[] {
125  const next = stages.map(s => ({ ...s, steps: s.steps.map(st => ({ ...st })) }))
126  const steps = next.flatMap(s => s.steps)
127  const find = (title: string) => steps.find(st => same(st.title, title))
128  if (input.next === true) {
129    const at = steps.findIndex(st => st.status === 'active') >= 0 ? steps.findIndex(st => st.status === 'active') : steps.findIndex(st => !isFinished(st.status))
130    const cur = steps[at]
131    if (cur) cur.status = 'done'
132    const following = steps.slice(at + 1).find(st => st.status === 'pending')
133    if (following) following.status = 'active'
134  }
135  for (const t of Array.isArray(input.done) ? input.done : []) {
136    const st = typeof t === 'string' ? find(t) : undefined
137    if (st) st.status = 'done'
138  }
139  const active = typeof input.active === 'string' ? find(input.active) : undefined
140  if (active) {
141    const at = steps.indexOf(active)
142    steps.forEach((st, i) => {
143      if (st.status === 'active' && i !== at) st.status = i < at ? 'done' : 'pending'
144    })
145    active.status = 'active'
146  }
147  const failed = typeof input.failed === 'string' ? find(input.failed) : undefined
148  if (failed) failed.status = 'error'
149
150  return next
151}
152
153function normalize(input: Raw, prev: Plan | null, now: number, id: string): Plan {
154  const isPartial = list(input.stages).length === 0 && prev !== null
155  const stages: PlanStage[] = isPartial ? applyOps(prev.stages, input) : list(input.stages)
156    .map(s => ({
157      name: str(s.name, 80) || 'Stage',
158      steps: list(s.steps).map(st => ({
159        title: str(st.title) || 'Step',
160        status: status(st.status),
161        substeps: list(st.substeps).map(sub => ({ title: str(sub.title) || '…', status: status(sub.status) })),
162      })),
163    }))
164    .filter(s => s.steps.length > 0) as PlanStage[]
165  const title = str(input.title, 80) || prev?.title || 'Plan'
166  const steps = stages.flatMap(s => s.steps)
167  const isAllDone = steps.length > 0 && steps.every(s => isFinished(s.status))
168  const asked = input.state as PlanState
169  const failedNow = typeof input.failed === 'string'
170  const state: PlanState = ['running', 'needs_input', 'error', 'done'].includes(asked) ? asked : isAllDone ? 'done' : failedNow ? 'error' : 'running'
171
172  return {
173    id,
174    title,
175    kind: input.kind === 'todo' || (isPartial && prev?.kind === 'todo') ? 'todo' : 'plan',
176    stages,
177    state,
178    note: str(input.note, 160) || null,
179    startedAt: prev && prev.title === title ? prev.startedAt : now,
180  }
181}
182
183const clean = (s: string) =>
184  s
185    .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
186    .replace(/[*_`]/g, '')
187    .replace(/^\s*(\d+[.)]|[-*+]|\[[ xX]\])\s+/, '')
188    .replace(/^(\d+[.)]|\[[ xX]\])\s+/, '')
189    .trim()
190
191function parsePlan(markdown: string, now: number): Plan | null {
192  let title = ''
193  const headed: PlanStage[] = []
194  const items: { depth: number; text: string }[] = []
195  for (const line of markdown.split(/\r?\n/)) {
196    const h = line.match(/^(#{1,4})\s+(.*)$/)
197    if (h) {
198      const text = clean(h[2] ?? '')
199      if (h[1] === '#' && !title) title = text
200      else headed.push({ name: text, steps: [] })
201      continue
202    }
203    const li = line.match(/^(\s*)(\d+[.)]|[-*+])\s+(.*)$/)
204    if (!li) continue
205    const depth = Math.floor((li[1] ?? '').replace(/\t/g, '  ').length / 2)
206    const text = clean(li[3] ?? '').slice(0, 120)
207    if (!text) continue
208    items.push({ depth, text })
209    const stage = headed[headed.length - 1]
210    if (!stage) continue
211    const step = stage.steps[stage.steps.length - 1]
212    if (depth === 0 || !step) stage.steps.push({ title: text, status: 'pending', substeps: [] })
213    else step.substeps.push({ title: text, status: 'pending' })
214  }
215  let stages = headed.filter(s => s.steps.length > 0)
216  if (stages.length === 0) {
217    if (items.some(i => i.depth > 0)) {
218      for (const item of items) {
219        const stage = stages[stages.length - 1]
220        if (item.depth === 0 || !stage) stages.push({ name: item.text, steps: [] })
221        else stage.steps.push({ title: item.text, status: 'pending', substeps: [] })
222      }
223      stages = stages.map(s => (s.steps.length ? s : { ...s, steps: [{ title: s.name, status: 'pending', substeps: [] }] }))
224    } else if (items.length > 0) {
225      stages = [{ name: 'Tasks', steps: items.map(i => ({ title: i.text, status: 'pending' as StepStatus, substeps: [] })) }]
226    }
227  }
228  if (stages.length === 0) return null
229  const first = stages[0]?.steps[0]
230  if (first) first.status = 'active'
231
232  return { id: 'plan', title: title || 'Plan', kind: stages.length === 1 ? 'todo' : 'plan', stages, state: 'running', note: null, startedAt: now }
233}
234
235function st(title: string, s: StepStatus): PlanStep {
236  return { title, status: s, substeps: [] }
237}
238
239const DEMO = (now: number): Plan => ({
240  id: 'demo',
241  title: 'Orders module',
242  kind: 'plan',
243  state: 'running',
244  note: null,
245  startedAt: now - 260_000,
246  stages: [
247    { name: 'Analysis', steps: [st('Read modules', 'done'), st('Find dependencies', 'done'), st('List changes', 'done')] },
248    { name: 'DB migration', steps: [st('Table schema', 'done'), st('Create migration', 'done'), st('Move data', 'active'), st('Indexes', 'pending')] },
249    { name: 'API', steps: [st('Endpoints', 'pending'), st('Validation', 'pending'), st('Access rules', 'pending')] },
250    { name: 'Interface', steps: [st('List page', 'pending'), st('Order card', 'pending'), st('Filters', 'pending'), st('Empty states', 'pending')] },
251    { name: 'Verify', steps: [st('Tests', 'pending'), st('Build', 'pending')] },
252  ],
253})
254
255// ---------- drawing ----------
256
257// the current step is the one marked active (or failed), since Claude may leave a step for later; pos counts the
258// finished steps, at is the current step's place (the same rule as where() in styles.ts)
259type Where = { pos: number; at: number; total: number; stage: number; step: number; stageSize: number }
260
261function where(p: Plan): Where {
262  const steps = p.stages.flatMap((s, i) => s.steps.map((step, j) => ({ i, j, step })))
263  const live = steps.findIndex(x => x.step.status === 'active' || x.step.status === 'error')
264  const first = steps.findIndex(x => !isFinished(x.step.status))
265  const isDone = p.state === 'done' || first < 0
266  const at = isDone ? steps.length : live >= 0 ? live : first
267  const pos = isDone ? steps.length : steps.filter(x => isFinished(x.step.status)).length
268  const cur = steps[Math.min(at, steps.length - 1)]
269  const stage = cur?.i ?? 0
270
271  return { pos, at, total: steps.length, stage, step: at >= steps.length ? (p.stages[stage]?.steps.length ?? 0) : (cur?.j ?? 0) + 1, stageSize: p.stages[stage]?.steps.length ?? 0 }
272}
273
274const hex = (h: string) => [1, 3, 5].map(i => parseInt(h.slice(i, i + 2), 16))
275const mix = (a: number[], b: number[], m: number) => a.map((v, i) => Math.round(v + ((b[i] ?? 0) - v) * m))
276const rgb = (c: number[]) => `rgb(${c.join(',')})`
277const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] ?? c)
278const hash = (a: number, b: number, k: number) => {
279  const x = Math.sin(a * 127.1 + b * 311.7 + k * 74.7) * 43758.5453
280  return x - Math.floor(x)
281}
282const textWidth = (s: string, px = 6.7) => [...s].reduce((w, ch) => w + (/[ -鿿]/.test(ch) ? 12 : /[ilI.,:;'|!]/.test(ch) ? 3.4 : /[mwMWШЩЖМ]/.test(ch) ? 9.5 : px), 0)
283
284const ICON_PATH: Partial<Record<PlanState, string>> = {
285  needs_input: 'M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3M12 17h.01',
286  error: 'M18 6 6 18M6 6l12 12',
287  done: 'M20 6 9 17l-5-5',
288}
289
290// last drawn head position per plan, so a redraw glides from where the bar was
291const lastHead = new Map<string, number>()
292
293function trackSvg(p: Plan, W: number): string {
294  const H = TRACK_H
295  const w = where(p)
296  const done = p.state === 'done'
297  // the fill is exactly the finished share: a fresh plan starts empty
298  const frac = done ? 1 : Math.min(1, w.pos / Math.max(1, w.total))
299  const fx = frac * W
300  const key = p.id
301  const from = lastHead.get(key) ?? fx
302  lastHead.set(key, fx)
303
304  const acc = hex(STATE_COLOR[p.state])
305  const light = mix(acc, [255, 255, 255], 0.32)
306  const grey = [132, 130, 138]
307  const ease = 'calcMode="spline" keyTimes="0;1" keySplines=".2 .8 .2 1"'
308  const glide = Math.abs(from - fx) > 0.5
309
310  const bounds: number[] = []
311  let acc2 = 0
312  p.stages.forEach((s, i) => {
313    acc2 += s.steps.length
314    if (i < p.stages.length - 1) bounds.push((acc2 / w.total) * W)
315  })
316
317  // pixels: 3px grid, 7 rows, denser and closer to the state colour towards the head
318  const buckets = [0, 1, 2, 3, 4].map(b => {
319    const m = b / 4
320    const dense = done ? 0.8 : 0.22 + 0.78 * Math.pow(m, 1.5)
321    return { color: rgb(done ? light : mix(grey, light, m)), opacity: (0.35 + 0.65 * dense).toFixed(2) }
322  })
323  let px = ''
324  for (let col = 0; col * 3 < fx; col++) {
325    const x = col * 3
326    const u = Math.min(1, (x + 1.5) / fx)
327    const dense = done ? 0.8 : 0.22 + 0.78 * Math.pow(u, 1.5)
328    const bucket = done ? 4 : Math.min(4, Math.floor(Math.min(1, Math.pow(u, 0.9) * 1.1) * 4.99))
329    for (let r = 0; r < 7; r++) {
330      if (hash(col, r, 1) > dense + 0.1) continue
331      px += `<rect x="${x}" y="${1 + r * 3}" class="b${bucket} t${Math.floor(hash(col, r, 2) * 4)}"/>`
332    }
333  }
334
335  let marks = ''
336  let k = 0
337  p.stages.forEach((s, i) => {
338    s.steps.forEach((_, j) => {
339      if (k > 0) {
340        const x = (k / w.total) * W
341        const isStage = j === 0
342        // stage boundaries are full-height lines, steps are short ticks; bright once passed
343        const passed = x < fx - 1
344        const h = isStage ? H : 8
345        const fill = passed ? rgb(mix(light, [255, 255, 255], 0.45)) : '#8A8984'
346        const opacity = passed ? (isStage ? 0.95 : 0.6) : isStage ? 0.7 : 0.45
347        marks += `<rect x="${(x - (isStage ? 1 : 0.75)).toFixed(1)}" y="${(H - h) / 2}" width="${isStage ? 2 : 1.5}" height="${h}" rx=".75" fill="${fill}" opacity="${opacity}"/>`
348      }
349      k++
350    })
351    void i
352  })
353
354  // knob: a pill with stage and count, or a round dot with the stage number when narrow
355  const isNarrow = W < NARROW
356  const color = STATE_COLOR[p.state]
357  const icon = ICON_PATH[p.state]
358  const single = p.stages.length === 1
359  const number = single ? Math.min(w.total, w.at + 1) : w.stage + 1
360  let knob = ''
361  let kw = H
362  if (isNarrow) {
363    const label = done ? '' : String(number)
364    knob = `<circle cx="0" cy="${H / 2}" r="${H / 2}" fill="${color}"/>${
365      done ? `<path d="${ICON_PATH.done}" transform="translate(-6 5) scale(.5)" fill="none" stroke="#fff" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>` : `<text x="0" y="${H / 2 + 4.2}" text-anchor="middle" class="kt">${label}</text>`
366    }`
367  } else {
368    const name = done ? 'Done' : single ? (p.stages[0]?.name ?? 'Tasks') : (p.stages[w.stage]?.name ?? '')
369    const agents = p.agents ?? []
370    const base = p.id === AGENTS ? `${w.pos}/${w.total}` : done ? `${w.total}/${w.total}` : single ? `${number}/${w.total}` : `${w.step}/${w.stageSize}`
371    const agentCount = agents.length > 0 && p.id !== AGENTS ? ` · ${agents.filter(a => a.state === 'done').length}/${agents.length} agents` : ''
372    const count = base + agentCount
373    const iconW = icon ? 16 : 0
374    const countW = textWidth(count, 6.5)
375    const maxW = Math.max(80, W * 0.55)
376    let shown = name
377    while (shown.length > 3 && 20 + iconW + textWidth(shown) + 6 + countW > maxW) shown = shown.slice(0, -1)
378    if (shown !== name) shown = shown.trimEnd() + '…'
379    kw = Math.round(20 + iconW + textWidth(shown) + 6 + countW)
380    const left = -kw / 2 + 10
381    knob = `<rect x="${-kw / 2}" y="0" width="${kw}" height="${H}" rx="${H / 2}" fill="${color}"/>`
382    if (icon) knob += `<path d="${icon}" transform="translate(${left} 5) scale(.5)" fill="none" stroke="#fff" stroke-width="3.6" stroke-linecap="round" stroke-linejoin="round"/>`
383    knob += `<text x="${left + iconW}" y="${H / 2 + 4.2}" class="kt">${esc(shown)}<tspan class="kc" dx="6">${count}</tspan></text>`
384  }
385  const clampX = (x: number) => Math.max(kw / 2, Math.min(W - kw / 2, x))
386  const kx = clampX(fx)
387  const kFrom = clampX(from)
388
389  const style = `<style>
390.b0{fill:${buckets[0]?.color};fill-opacity:${buckets[0]?.opacity}}.b1{fill:${buckets[1]?.color};fill-opacity:${buckets[1]?.opacity}}
391.b2{fill:${buckets[2]?.color};fill-opacity:${buckets[2]?.opacity}}.b3{fill:${buckets[3]?.color};fill-opacity:${buckets[3]?.opacity}}
392.b4{fill:${buckets[4]?.color};fill-opacity:${buckets[4]?.opacity}}
393rect[class]{width:2px;height:2px}
394.t0,.t1,.t2,.t3{animation:tw ${done ? 3.2 : 2.2}s ease-in-out infinite}
395.t1{animation-duration:${done ? 3.8 : 2.8}s;animation-delay:-.7s}.t2{animation-duration:${done ? 4.4 : 1.9}s;animation-delay:-1.3s}.t3{animation-duration:${done ? 3.5 : 3.3}s;animation-delay:-.4s}
396@keyframes tw{0%,100%{opacity:1}50%{opacity:${done ? 0.8 : 0.45}}}
397.kt{font:500 12px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:#fff}
398.kc{font-weight:400;fill-opacity:.75}
399@media (prefers-reduced-motion:reduce){.t0,.t1,.t2,.t3{animation:none}}
400</style>`
401  const glideFill = glide ? `<animate attributeName="width" from="${from.toFixed(1)}" to="${fx.toFixed(1)}" dur=".45s" ${ease} fill="freeze"/>` : ''
402  const glideKnob = glide ? `<animateTransform attributeName="transform" type="translate" from="${kFrom.toFixed(1)} 0" to="${kx.toFixed(1)} 0" dur=".45s" ${ease} fill="freeze"/>` : ''
403
404  return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">${style}
405<defs><clipPath id="pill"><rect width="${W}" height="${H}" rx="${H / 2}"/></clipPath><clipPath id="fill"><rect width="${fx.toFixed(1)}" height="${H}">${glideFill}</rect></clipPath>
406<linearGradient id="base" x1="0" x2="${fx.toFixed(1)}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${rgb(acc)}" stop-opacity="${done ? 0.3 : 0.05}"/><stop offset="1" stop-color="${rgb(acc)}" stop-opacity=".33"/></linearGradient></defs>
407<g clip-path="url(#pill)"><rect width="${W}" height="${H}" fill="#808080" fill-opacity=".16"/>
408<g clip-path="url(#fill)"><rect width="${fx.toFixed(1)}" height="${H}" fill="url(#base)"/>${px}</g>${marks}</g>
409<g transform="translate(${kx.toFixed(1)} 0)">${glideKnob}${knob}</g></svg>`
410}
411
412const AGENT_COLOR: Record<AgentRun['state'], string> = {
413  running: STATE_COLOR.running,
414  waiting: STATE_COLOR.needs_input,
415  done: STATE_COLOR.done,
416  error: STATE_COLOR.error,
417}
418
419const elapsed = (ms: number) => {
420  const sec = Math.max(0, Math.round(ms / 1000))
421  return sec < 60 ? `${sec}s` : `${Math.floor(sec / 60)}m ${sec % 60}s`
422}
423
424// which strips show: all of a small batch; in a big one the unfinished first, the rest folded into one line
425function visibleAgents(p: Plan, now: number): { shown: AgentRun[]; hidden: AgentRun[] } | null {
426  const list = p.agents ?? []
427  if (list.length === 0) return null
428  const hasError = list.some(a => a.state === 'error')
429  if (p.agentsDoneAt && now - p.agentsDoneAt > FOLD_MS && !hasError) return null
430  if (list.length <= MAX_STRIPS) return { shown: list, hidden: [] }
431  const keep = new Set(list.filter(a => a.state !== 'done').slice(0, MAX_STRIPS - 1).map(a => a.id))
432  for (const a of [...list].reverse()) {
433    if (keep.size >= MAX_STRIPS - 1) break
434    keep.add(a.id)
435  }
436  return { shown: list.filter(a => keep.has(a.id)), hidden: list.filter(a => !keep.has(a.id)) }
437}
438
439// the person's choice applied to the strips: summary folds them into one made-up run that every style draws as a strip
440function applyAgentView(v: { shown: AgentRun[]; hidden: AgentRun[] } | null, view: AgentView): { shown: AgentRun[]; hidden: AgentRun[] } | null {
441  if (!v || view === 'expanded') return v
442  if (view === 'hidden') return null
443  const all = [...v.shown, ...v.hidden]
444  const count = (s: AgentRun['state']) => all.filter(a => a.state === s).length
445  const tool = (
446    [
447      ['running', 'running'],
448      ['waiting', 'waiting'],
449      ['done', 'done'],
450      ['error', 'failed'],
451    ] as const
452  )
453    .map(([s, label]) => (count(s) ? `${count(s)} ${label}` : ''))
454    .filter(Boolean)
455    .join(' · ')
456  const state: AgentRun['state'] = count('waiting') ? 'waiting' : count('running') ? 'running' : count('error') ? 'error' : 'done'
457  const ends = all.map(a => a.endedAt)
458  const endedAt = ends.every((t): t is number => t !== null) ? Math.max(...ends) : null
459  const startedAt = Math.min(...all.map(a => a.startedAt))
460  return { shown: [{ id: 'agents-summary', title: plural(all.length, 'subagent'), state, tool, startedAt, endedAt, depth: 0 }], hidden: [] }
461}
462
463// what each strip showed last time it was drawn, so a change morphs from the old status instead of jumping
464const lastStrip = new Map<string, { tool: string; color: string }>()
465const MORPH = '.2s'
466
467const stripsHeight = (n: number) => n * STRIP_H + (n - 1) * STRIP_GAP
468
469// one tinted strip per agent: state colour, name, what it does now and for how long; not a progress bar
470function stripsSvg(v: { shown: AgentRun[]; hidden: AgentRun[] }, W: number, now: number): string {
471  const isNarrow = W < NARROW
472  const rows: string[] = []
473  v.shown.forEach((a, i) => {
474    const c = AGENT_COLOR[a.state]
475    const y = i * (STRIP_H + STRIP_GAP)
476    const indent = a.depth > 0 ? 12 : 0
477    let px = ''
478    if (a.state === 'running') {
479      for (let col = 0; col * 3 < W; col++) {
480        for (let r = 0; r < 4; r++) {
481          if (hash(col + i * 41, r, 5) > 0.2) continue
482          px += `<rect x="${col * 3}" y="${y + 3 + r * 3.6}" class="t${Math.floor(hash(col, r, 6) * 4)}" fill="${c}" fill-opacity=".32"/>`
483        }
484      }
485    }
486    const nameRoom = isNarrow ? W - 30 - indent : W * 0.5
487    let name = (a.depth > 0 ? '↳ ' : '') + a.title
488    while (name.length > 4 && textWidth(name, 6.2) > nameRoom) name = name.slice(0, -1)
489    if (name !== (a.depth > 0 ? '↳ ' : '') + a.title) name = name.trimEnd() + '…'
490    const nameX = 19 + indent
491    const toolX = nameX + textWidth(name, 6.2) + 8
492    const time = elapsed((a.endedAt ?? now) - a.startedAt)
493    // a status change: the old word blurs out while the new one blurs in, and the tint flows to the new colour
494    const was = lastStrip.get(a.id)
495    lastStrip.set(a.id, { tool: a.tool, color: c })
496    const isToolChanged = was !== undefined && was.tool !== a.tool
497    const flow = (attr: string) => (was && was.color !== c ? `<animate attributeName="${attr}" from="${was.color}" to="${c}" dur="${MORPH}" fill="freeze"/>` : '')
498    const tool = isNarrow
499      ? ''
500      : (isToolChanged ? `<text x="${toolX}" y="${y + 12.5}" class="sn mo" style="fill:${was.color}">${esc(was.tool)}</text>` : '') +
501        `<text x="${toolX}" y="${y + 12.5}" class="sn${isToolChanged ? ' mi' : ''}" style="fill:${c}">${esc(a.tool)}</text>` +
502        `<text x="${W - 9}" y="${y + 12.5}" text-anchor="end" class="sn st">${time}</text>`
503    rows.push(
504      `<rect x="0" y="${y}" width="${W}" height="${STRIP_H}" rx="${STRIP_H / 2}" fill="${c}" fill-opacity=".15">${flow('fill')}</rect>${px}` +
505        `<circle cx="${10 + indent}" cy="${y + STRIP_H / 2}" r="3" fill="${c}"${a.state === 'running' ? ' class="sd"' : ''}>${flow('fill')}</circle>` +
506        `<text x="${nameX}" y="${y + 12.5}" class="sn">${esc(name)}</text>` +
507        tool,
508    )
509  })
510  if (v.hidden.length > 0) {
511    const y = v.shown.length * (STRIP_H + STRIP_GAP)
512    const doneCount = v.hidden.filter(a => a.state === 'done').length
513    rows.push(
514      `<rect x="0" y="${y}" width="${W}" height="${STRIP_H}" rx="${STRIP_H / 2}" fill="#808080" fill-opacity=".14"/>` +
515        `<text x="10" y="${y + 12.5}" class="sn st">+${plural(v.hidden.length, 'more agent')} · ${doneCount} done</text>`,
516    )
517  }
518  return `<style>.sn{font:400 11.5px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:#1F1E1C}.st{fill-opacity:.65}
519@media (prefers-color-scheme:dark){.sn{fill:#F0EEFC}}
520.sd{animation:sp 1.1s ease-in-out infinite}@keyframes sp{50%{opacity:.3}}
521.mi{animation:mi ${MORPH} ease-out both}@keyframes mi{from{opacity:0;filter:blur(3px)}}
522.mo{animation:mo ${MORPH} ease-in both}@keyframes mo{to{opacity:0;filter:blur(3px)}}
523@media (prefers-reduced-motion:reduce){.sd,.mi,.mo{animation:none}.mo{opacity:0}}</style>${rows.join('')}`
524}
525
526function plural(n: number, word: string) {
527  return `${n} ${word}${n === 1 ? '' : 's'}`
528}
529
530// the state glyph left of a title, drawn in a box of one width with its mark at the middle: as letters, ● ? ! ✓
531// are each a different width, so the titles after them did not start at one place
532const GLYPH_W = 12
533// what a glyph says to a reader that cannot see it; a desktop draws no Svg whose alt is empty (0.5.41-0.5.49 drew the
534// glyphs and the colour dots with none, and they did not show)
535const GLYPH_WORD: Record<string, string> = { '●': '進行中', '?': '等你決定', '!': '出錯', '✓': '完成' }
536const GLYPH_H = 16
537function glyphSvg(char: string, color: string, isDim = false) {
538  const c = GLYPH_W / 2
539  const mark =
540    char === '●'
541      ? `<circle cx="${c}" cy="${GLYPH_H / 2}" r="4.5" fill="${color}"/>`
542      : char === '✓'
543        ? `<path d="M${c - 4} ${GLYPH_H / 2}l2.8 2.9 5.2-5.6" fill="none" stroke="${color}" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>`
544        : `<text x="${c}" y="${GLYPH_H / 2 + 4.5}" text-anchor="middle" style="font:700 13px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,sans-serif" fill="${color}">${esc(char)}</text>`
545  return `<svg xmlns="http://www.w3.org/2000/svg" width="${GLYPH_W}" height="${GLYPH_H}" viewBox="0 0 ${GLYPH_W} ${GLYPH_H}"${isDim ? ' opacity=".45"' : ''}>${mark}</svg>`
546}
547
548// another session's state in words, for a row with no bar: left-aligned in the bar's own width, in the bars' note type (12 px, regular, muted)
549const statusSvg = (word: string, W: number) =>
550  `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${TRACK_H}" viewBox="0 0 ${W} ${TRACK_H}"><style>.w{font:400 12px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:#73726C}@media (prefers-color-scheme:dark){.w{fill:#A3A19A}}</style><text x="0" y="${TRACK_H / 2 + 4.5}" class="w">${esc(word)}</text></svg>`
551
552// what another session's main loop is doing, from the tool it runs now; an MCP tool goes by its server's name
553function toolLabel(tool?: string) {
554  if (!tool) return '處理中'
555  const mcp = /^mcp__(.+?)__/.exec(tool)
556  if (mcp) return `外部工具 · ${mcp[1]}`
557  const word: Record<string, string> = {
558    Bash: '執行指令', PowerShell: '執行指令', Read: '讀檔案', Edit: '改檔案', Write: '改檔案', MultiEdit: '改檔案', NotebookEdit: '改檔案',
559    Grep: '找檔案', Glob: '找檔案', Agent: '派 subagent', Task: '派 subagent', WebFetch: '查網路', WebSearch: '查網路', Skill: '用技能',
560  }
561  return word[tool] ? `${word[tool]} · ${tool}` : tool
562}
563
564// a session that runs with no bar: a short track with a segment sweeping across it in the style's running colour, then what
565// it does now, about where the other bars' notes start;
566// the source stays the same while the label does, so a redraw does not restart the sweep
567function runningSvg(label: string, W: number, color: string) {
568  const trackW = Math.round(Math.min(110, W * 0.4))
569  const seg = Math.round(trackW * 0.3)
570  const y = TRACK_H / 2 - 2
571  return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${TRACK_H}" viewBox="0 0 ${W} ${TRACK_H}"><style>.t{fill:#E2E0DA}.w{font:400 12px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:#73726C}.sweep{animation:sw 1.4s ease-in-out infinite}@keyframes sw{from{transform:translateX(-${seg}px)}to{transform:translateX(${trackW}px)}}@media (prefers-color-scheme:dark){.t{fill:#3A3A38}.w{fill:#A3A19A}}@media (prefers-reduced-motion:reduce){.sweep{animation:none;transform:translateX(${Math.round((trackW - seg) / 2)}px)}}</style><clipPath id="c"><rect y="${y}" width="${trackW}" height="4" rx="2"/></clipPath><rect class="t" y="${y}" width="${trackW}" height="4" rx="2"/><g clip-path="url(#c)"><rect class="sweep" y="${y}" width="${seg}" height="4" rx="2" fill="${color}"/></g><text x="${trackW + 12}" y="${TRACK_H / 2 + 4.5}" class="w">${esc(label)}</text></svg>`
572}
573
574// a drawing placed in a fixed-height slot (centred or at the top), so previews of different heights take the same room
575function inSlot(drawn: { svg: string; height: number }, W: number, slotH: number, align: 'center' | 'top'): { svg: string; height: number } {
576  const dy = align === 'center' ? Math.max(0, (slotH - drawn.height) / 2) : 0
577  return {
578    svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${slotH}" viewBox="0 0 ${W} ${slotH}"><g transform="translate(0 ${dy})">${drawn.svg}</g></svg>`,
579    height: slotH,
580  }
581}
582
583// one bar with its strips in the chosen style; the bar above the prompt and the pane's previews both draw through here
584function drawBar(style: StyleId, p: Plan, W: number, now: number, v: { shown: AgentRun[]; hidden: AgentRun[] } | null): { svg: string; height: number } {
585  if (style !== 'original') return STYLES[style].draw(p, W, now, v)
586  if (!v) return { svg: trackSvg(p, W), height: TRACK_H }
587  const stripsH = 5 + stripsHeight(v.shown.length + (v.hidden.length > 0 ? 1 : 0))
588  return {
589    svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${TRACK_H + stripsH}">${trackSvg(p, W)}<g transform="translate(0 ${TRACK_H + 5})">${stripsSvg(v, W, now)}</g></svg>`,
590    height: TRACK_H + stripsH,
591  }
592}
593
594// ---------- engine glue ----------
595
596// a sound the mod raises on its own: silent while the person has turned sounds off
597function play($: EngineInterface, name: 'decision' | 'error' | 'done') {
598  void read($, soundsOn).then(isOn => (isOn ? playNow($, name) : undefined))
599}
600// the engine's player first (afplay on macOS); PowerShell where it cannot play
601function playNow($: EngineInterface, name: 'decision' | 'error' | 'done') {
602  const file = `${$.plugin.root}/sounds/${name}.wav`.replace(/\//g, '\\')
603  void $.audio.play({ asset: `sounds/${name}.wav` }).catch(() =>
604    $.process
605      .run(['powershell', '-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', `(New-Object Media.SoundPlayer '${file}').PlaySync()`], { timeoutMs: 5000 })
606      .catch(() => undefined),
607  )
608}
609
610// the agents bar is the mod's own; the model never owes it an update
611const AGENTS = 'agents:auto' // slug() never yields ':', so no model id can take it
612const isOpenPlan = (p: Plan) => p.id !== AGENTS && p.state === 'running' && !p.isFinishing && !p.stages.flatMap(s => s.steps).every(s => isFinished(s.status))
613
614const slug = (s: string) =>
615  s
616    .toLowerCase()
617    .replace(/[^\p{L}\p{N}]+/gu, '-')
618    .replace(/^-|-$/g, '')
619    .slice(0, 40) || 'plan'
620
621// adds or replaces one bar by id; keeps at most MAX_BARS, dropping finished ones first
622// computed inside update() from the latest list, so concurrent writers (parallel agents) do not drop each other
623function placeBar(list: readonly Plan[], next: Plan): Plan[] {
624  const prev = list.find(p => p.id === next.id)
625  // an update keeps its row; a new bar goes to the bottom
626  const rest = prev ? list.map(p => (p.id === next.id ? next : p)) : [...list, next]
627  while (rest.length > MAX_BARS) {
628    const doneAt = rest.findIndex(p => p.state === 'done')
629    rest.splice(doneAt >= 0 ? doneAt : 0, 1)
630  }
631  return rest
632}
633
634// a main-loop turn is running: a done reached inside it sounds once the turn ends, after the reply is written
635let isMainTurn = false
636let owesDone = false
637
638function chime($: EngineInterface, prev: PlanState | undefined, next: PlanState) {
639  if (next === prev) return
640  if (next === 'needs_input') play($, 'decision')
641  if (next === 'error') play($, 'error')
642  if (next === 'done') {
643    if (isMainTurn) owesDone = true
644    else play($, 'done')
645  }
646}
647
648async function putPlan($: EngineInterface, next: Plan) {
649  let prev: Plan | undefined
650  await update($, plans, list => {
651    prev = list.find(p => p.id === next.id)
652    return placeBar(list, next)
653  })
654  chime($, prev?.state, next.state)
655}
656
657// ---------- agents: drawn from engine events alone, no model calls ----------
658// each subagent lives on a bar as one state strip: the open task bar it was started under,
659// the bar of its parent agent, or the mod's own "Agents" bar when no task is open.
660// Module maps: a reload forgets running agents, whose strips then stay until the bar is closed.
661const agentHome = new Map<string, string>() // agentId -> bar id
662const toolUses = new Map<string, string>() // tool_use_id -> agentId, to find who waits on a permission
663const waiting = new Set<string>()
664let foldUntil = 0 // keep ticking until finished strips have folded
665
666// the mod's own bar mirrors its agents as steps, finished first, so percent and count read done/total
667function syncAuto(p: Plan, now: number): Plan {
668  const agents = p.agents ?? []
669  const isOver = agents.length > 0 && agents.every(a => a.state === 'done' || a.state === 'error')
670  const agentsDoneAt = isOver ? (p.agentsDoneAt ?? now) : null
671  if (p.id !== AGENTS) return { ...p, agentsDoneAt }
672  const rank = (a: AgentRun) => (a.state === 'done' ? 0 : a.state === 'error' ? 1 : 2)
673  const steps: PlanStep[] = [...agents]
674    .sort((a, b) => rank(a) - rank(b))
675    .map(a => ({ title: a.title, status: a.state === 'done' ? 'done' : a.state === 'error' ? 'error' : 'active', substeps: [] }))
676  const state: PlanState = isOver
677    ? agents.some(a => a.state === 'error') ? 'error' : 'done'
678    : agents.some(a => a.state === 'waiting') ? 'needs_input' : 'running'
679  return { ...p, agentsDoneAt, stages: [{ name: 'Agents', steps }], state }
680}
681
682function addRun(p: Plan, run: AgentRun, parentId: string | undefined, now: number): Plan {
683  // a batch that has finished makes room for the next one
684  const list = p.agentsDoneAt ? [] : [...(p.agents ?? [])]
685  let at = list.length
686  const parentAt = parentId ? list.findIndex(a => a.id === parentId) : -1
687  if (parentAt >= 0) {
688    at = parentAt + 1
689    while (at < list.length && (list[at]?.depth ?? 0) > 0) at++
690  }
691  list.splice(at, 0, run)
692  return syncAuto({ ...p, agents: list, agentsDoneAt: null }, now)
693}
694
695// changes one agent's strip inside the latest list; sounds follow the bar's state
696async function editAgent($: EngineInterface, agentId: string, change: (a: AgentRun) => AgentRun) {
697  const home = agentHome.get(agentId)
698  if (!home) return
699  const now = await $.clock.now()
700  let before: PlanState | undefined
701  let after: PlanState | undefined
702  let isFolding = false
703  await update($, plans, list =>
704    list.map(p => {
705      if (p.id !== home || !p.agents?.some(a => a.id === agentId)) return p
706      before = p.state
707      const next = syncAuto({ ...p, agents: p.agents.map(a => (a.id === agentId ? change(a) : a)) }, now)
708      after = next.state
709      isFolding = !p.agentsDoneAt && next.agentsDoneAt !== null
710      return next
711    }),
712  )
713  if (isFolding) foldUntil = now + FOLD_MS + 1500
714  if (before !== undefined && after !== undefined) chime($, before, after)
715}
716
717async function dropPlan($: EngineInterface, id: string) {
718  lastHead.delete(id)
719  for (const p of await read($, plans)) if (p.id === id) for (const a of p.agents ?? []) lastStrip.delete(a.id)
720  await update($, plans, list => list.filter(p => p.id !== id))
721}
722
723// finished bars stay until the person sends their next message (they have seen the result by then):
724// they fade out for LEAVE_MS, then leave the list
725const LEAVE_MS = 400
726async function fadeOutDone($: EngineInterface) {
727  const now = await $.clock.now()
728  let isLeaving = false
729  await update($, plans, list =>
730    list.map(p => {
731      if (p.state !== 'done' || p.leavingAt) return p
732      isLeaving = true
733      return { ...p, leavingAt: now }
734    }),
735  )
736  if (isLeaving) $.clock.after(LEAVE_MS, () => dropLeft($))
737}
738async function dropLeft($: EngineInterface) {
739  const now = await $.clock.now()
740  for (const p of await read($, plans)) {
741    if (!p.leavingAt || now - p.leavingAt < LEAVE_MS) continue
742    lastHead.delete(p.id)
743    for (const a of p.agents ?? []) lastStrip.delete(a.id)
744  }
745  await update($, plans, list => list.filter(p => !p.leavingAt || now - p.leavingAt < LEAVE_MS))
746}
747// a leaving bar's drawing fades to nothing; its title and count dim, since Text has no opacity
748const fadeOut = (svg: string, W: number, H: number) =>
749  `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}"><style>@keyframes pp-leave{to{opacity:0}}.pp-leave{animation:pp-leave ${LEAVE_MS}ms ease-out forwards}</style><g class="pp-leave">${svg}</g></svg>`
750
751// ---------- other sessions: each desktop session writes its status to a shared folder, every session reads the others ----------
752type SessionStatus = 'working' | 'done' | 'needs_input' | 'idle' | 'ended'
753type SessionFile = { v: 1; hostId: string; cwd: string; label: string; title?: string; tool?: string; state: SessionStatus; since: number; updatedAt: number; bars?: unknown[] }
754const others = atom({ plugin: 'plan-progress', key: 'others' } as const, { rows: [] } as OthersView)
755const crossOn = atom({ plugin: 'plan-progress', key: 'crossSessions' } as const, true)
756const CROSS_STORE_KEY = 'crossSessions'
757const setCross = async ($: EngineInterface, isOn: boolean) => {
758  await update($, crossOn, () => isOn)
759  await $.store.set(CROSS_STORE_KEY, isOn)
760}
761// the desktop's own session id; the link is built from it, never read from a file, since `open` acts on whatever it is given
762const HOST_ID = /^local_[0-9a-f-]{36}$/
763const linkOf = (hostId: string) => `claude://claude.ai/epitaxy/${hostId}`
764// a session in a worktree (<project>/.claude/worktrees/<random name>) is named by its project, not the random folder
765const projectOf = (cwd: string) => (cwd.includes('/.claude/worktrees/') ? cwd.split('/.claude/worktrees/')[0] : cwd).split('/').pop() ?? ''
766const SEEN = 'seen.json'
767const HEARTBEAT_MS = 30_000 // a working session rewrites its file this often
768const WORKING_FRESH_MS = 90_000 // a working file older than this belongs to a session that is gone
769const KEEP_MS = 24 * 3600_000 // a finished session older than this no longer shows
770const MAX_OTHERS = 5
771// every row's ✕ sits in a cell this wide, so a row without one keeps its bar in line
772const CLOSE_CELLS = 3
773// this session's own bars sit in a rounded frame when other sessions show under them: the frame's border and padding
774// take about FRAME_PX across, and the rows under it are inset by FRAME_INSET cells so both groups line up
775// (a terminal draws the border as a whole cell, so there the rows under it move in one cell more)
776const FRAME_PX = 24
777const FRAME_INSET = 1
778// the space between the frame and the other sessions under it on the desktop, in px (a row's gap was too much)
779const FRAME_GAP_PX = 2
780// the space between rows on the desktop, in px: a row's gap (about 10 px) spread them out; no gap and this instead
781const ROW_GAP_PX = 5
782// the name on the frame's top line: its background is the desktop's grey band (measured in the light theme; the dark one
783// is a guess), so the line does not show through the letters. The desktop places a Box one row up (top: -1) about
784// FRAME_ROW_PX above the line (measured on a screenshot), so the drawing is two rows tall and the name sits at its middle
785const FRAME_ROW_PX = 20
786const FRAME_NAME_H = 2 * FRAME_ROW_PX
787// the name starts where the rows' titles start, past the glyph's column: the titles start about this far right of where
788// the name's drawing is placed (one cell in), measured on a screenshot; the line shows left of the name, its background
789// only hides the line behind the letters
790const FRAME_NAME_X = 27
791function frameNameSvg(text: string) {
792  // 10 px letters, smaller than the rows' titles; textWidth measures 12 px ones
793  // a font with wider CJK letters than the estimate cut the name's end (seen in the promo's renderer), so leave room
794  const textW = Math.round(((textWidth(text, 7.5) * 10) / 12) * 1.15)
795  const width = FRAME_NAME_X + textW + 10
796  // the line is hidden by a halo of the band's grey round the letters (a stroke painted under them), so the gap
797  // fits the name as drawn on both sides; a background sized from the estimate left a wider gap on the right (0.5.62)
798  const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${FRAME_NAME_H}" viewBox="0 0 ${width} ${FRAME_NAME_H}"><style>.w{font:500 10px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:#73726C;stroke:#F0F0F0;stroke-width:12px;stroke-linejoin:round;paint-order:stroke}@media (prefers-color-scheme:dark){.w{fill:#A3A19A;stroke:#2B2B29}}</style><text x="${FRAME_NAME_X}" y="${FRAME_ROW_PX + 3.5}" class="w">${esc(text)}</text></svg>`
799  return { text, svg, width }
800}
801// the band's grey, painted as the fold button's own background so the frame's line has a gap there; the button is
802// its content, drawn over it (a drawing of the grey placed beside the button hid it, 0.5.59-0.5.60). A Box takes one
803// raw colour, so the theme setting picks it: the desktop's light grey, measured, and its dark one, a guess
804const BAND_GREY = { light: '#F0F0F0', dark: '#2B2B29' }
805// read from the theme setting when the session starts
806let isDarkTheme = false
807const POLL_EVERY = 2 // seconds between reads of the shared folder
808let sessionsDir: string | null = null
809// the app's own record of each desktop session, which holds the title its sessions list shows
810let appSessionsDir: string | null = null
811let appRecord: string | null = null
812let appTitle = ''
813const TITLE_EVERY = 60 // seconds between rereads of the title, which the app may set after the first turn
814let mine: { hostId: string; cwd: string; state: SessionStatus; since: number; lastPrompt: string; tool: string } | null = null
815let lastBeat = 0
816let lastBars = ''
817let lastTool = ''
818// the desktop (or a phone) attaches to a session while it shows it and detaches when the person leaves it
819const viewers = new Set<string>()
820const isWaitingOnPerson = (s: SessionStatus) => s === 'done' || s === 'needs_input'
821let lastOthers = ''
822let pollCount = 0
823
824// writes this session's status; a new state restarts `since`, so a second finish shows again after the first was seen
825async function publish($: EngineInterface, state?: SessionStatus) {
826  if (!mine || !sessionsDir) return
827  const now = await $.clock.now()
828  if (state) {
829    mine.state = state
830    mine.since = now
831  }
832  lastBeat = now
833  const list = await read($, plans)
834  const bar = [...list].reverse().find(p => p.id !== AGENTS)
835  const bars = barsOf(list)
836  lastBars = JSON.stringify(bars)
837  lastTool = mine.tool
838  const file: SessionFile = { v: 1, hostId: mine.hostId, cwd: mine.cwd, label: bar?.title || mine.lastPrompt, title: appTitle, tool: mine.tool, state: mine.state, since: mine.since, updatedAt: now, bars }
839  await $.fs.write(`${sessionsDir}/${mine.hostId}.json`, JSON.stringify(file)).catch(() => undefined)
840  // the person is looking at this session as it finishes: the other sessions need not show it
841  if (state && isWaitingOnPerson(state) && viewers.size > 0) await writeSeen($, mine.hostId, mine.since)
842}
843
844// reads this session's title from the app's record of it (claude-code-sessions/<account>/<org>/<id>.json), the name
845// its sessions list shows. That file is the app's own, not an interface: when it is missing or changes shape, the
846// title stays empty and the other sessions fall back to the bar's title or the person's last message
847async function refreshTitle($: EngineInterface): Promise<boolean> {
848  if (!mine || !appSessionsDir) return false
849  if (!appRecord) {
850    for (const a of await $.fs.list(appSessionsDir).catch(() => [])) {
851      if (a.kind !== 'dir') continue
852      for (const b of await $.fs.list(`${appSessionsDir}/${a.name}`).catch(() => [])) {
853        const path = `${appSessionsDir}/${a.name}/${b.name}/${mine.hostId}.json`
854        if (b.kind === 'dir' && (await $.fs.exists(path).catch(() => false))) appRecord = path
855      }
856    }
857    if (!appRecord) return false
858  }
859  let title = ''
860  try {
861    const record = JSON.parse((await $.fs.read(appRecord)) as string)
862    title = typeof record?.title === 'string' ? str(record.title, 60) : ''
863  } catch {
864    appRecord = null
865  }
866  if (title === appTitle) return false
867  appTitle = title
868  return true
869}
870
871// the bars the other sessions draw: shape and state only, no subagent strips, none that is leaving
872const barsOf = (list: readonly Plan[]) =>
873  list.filter(p => !p.leavingAt).map(p => ({ id: p.id, title: p.title, kind: p.kind, stages: p.stages, state: p.state, note: p.note, startedAt: p.startedAt }))
874
875// a bar read from another session's file, rebuilt through the same checks a model's call goes through
876function awayBar(raw: unknown, hostId: string, now: number): Plan | undefined {
877  if (!raw || typeof raw !== 'object') return undefined
878  const r = raw as Raw
879  const p = normalize(r, null, now, `away:${hostId}`)
880  if (p.stages.length === 0) return undefined
881  return { ...p, startedAt: typeof r.startedAt === 'number' && Number.isFinite(r.startedAt) ? r.startedAt : now }
882}
883
884async function readSeen($: EngineInterface): Promise<Record<string, number>> {
885  if (!sessionsDir) return {}
886  try {
887    const v = JSON.parse((await $.fs.read(`${sessionsDir}/${SEEN}`)) as string)
888    return v && typeof v === 'object' ? v : {}
889  } catch {
890    return {}
891  }
892}
893
894async function pollOthers($: EngineInterface) {
895  if (!sessionsDir) return
896  const now = await $.clock.now()
897  const entries = await $.fs.list(sessionsDir).catch(() => [])
898  const seen = await readSeen($)
899  const rows: OtherSession[] = []
900  for (const entry of entries) {
901    if (entry.kind !== 'file' || !entry.name.endsWith('.json') || entry.name === SEEN || now - entry.mtimeMs > KEEP_MS) continue
902    let f: SessionFile
903    try {
904      f = JSON.parse((await $.fs.read(`${sessionsDir}/${entry.name}`)) as string)
905    } catch {
906      continue
907    }
908    if (f?.v !== 1 || !HOST_ID.test(f.hostId) || f.hostId === mine?.hostId) continue
909    const isShown =
910      f.state === 'working' ? now - f.updatedAt < WORKING_FRESH_MS : (f.state === 'done' || f.state === 'needs_input') && now - f.since < KEEP_MS
911    // a finish that was seen (opened, switched to, or ✕) hides until the session changes state again;
912    // a running session always shows
913    if (!isShown || (f.state !== 'working' && f.since <= (seen[f.hostId] ?? 0))) continue
914    const bars = (Array.isArray(f.bars) ? f.bars : [])
915      .map(raw => ({ isAgents: (raw as Raw | null)?.id === AGENTS, p: awayBar(raw, f.hostId, now) }))
916      .filter((b): b is { isAgents: boolean; p: Plan } => b.p !== undefined)
917    // its newest task bar, or its subagents' bar when it has no task bar
918    const bar = ([...bars].reverse().find(b => !b.isAgents) ?? bars[bars.length - 1])?.p
919    rows.push({
920      hostId: f.hostId,
921      folder: str(projectOf(String(f.cwd)), 40),
922      ...(typeof f.title === 'string' && f.title ? { title: str(f.title, 60) } : {}),
923      label: readable(f.label, 60),
924      state: f.state as OtherSession['state'],
925      since: f.since,
926      ...(typeof f.tool === 'string' && f.tool ? { tool: str(f.tool, 60) } : {}),
927      ...(bar ? { bar } : {}),
928      ...(leavingAway.has(f.hostId) ? { isLeaving: true } : {}),
929    })
930  }
931  // waiting on the person first, then finished, then running; the newest first within each
932  const rank = { needs_input: 0, done: 1, working: 2 } as const
933  rows.sort((a, b) => rank[a.state] - rank[b.state] || b.since - a.since)
934  const view = { rows }
935  const key = JSON.stringify(view)
936  if (key === lastOthers) return
937  lastOthers = key
938  await update($, others, () => view)
939}
940
941// the person has seen this finish: every session stops showing it until that session finishes again
942// writes that a session's finish (the state that began at `since`) has been seen, for every session to read
943async function writeSeen($: EngineInterface, hostId: string, since: number) {
944  if (!sessionsDir) return
945  const now = await $.clock.now()
946  const seen = await readSeen($)
947  seen[hostId] = since
948  for (const [id, at] of Object.entries(seen)) if (now - at > KEEP_MS) delete seen[id]
949  await $.fs.write(`${sessionsDir}/${SEEN}`, JSON.stringify(seen)).catch(() => undefined)
950}
951
952async function markSeen($: EngineInterface, row: OtherSession) {
953  await writeSeen($, row.hostId, row.since)
954  lastOthers = ''
955  await update($, others, v => ({ ...v, rows: v.rows.filter(r => r.hostId !== row.hostId) }))
956}
957
958// ✕: the row dims for LEAVE_MS, then leaves; the seen mark is written once it has gone, so a read in between keeps it dimmed
959const leavingAway = new Set<string>()
960async function dismissAway($: EngineInterface, row: OtherSession) {
961  if (leavingAway.has(row.hostId)) return
962  leavingAway.add(row.hostId)
963  await update($, others, v => ({ ...v, rows: v.rows.map(r => (r.hostId === row.hostId ? { ...r, isLeaving: true } : r)) }))
964  $.clock.after(LEAVE_MS, async () => {
965    await markSeen($, row)
966    leavingAway.delete(row.hostId)
967  })
968}
969
970async function switchTo($: EngineInterface, row: OtherSession) {
971  if (!HOST_ID.test(row.hostId)) return
972  await markSeen($, row)
973  await $.process.run(['open', linkOf(row.hostId)], { timeoutMs: 5000 }).catch(() => undefined)
974}
975
976const STEP_SCHEMA = {
977  type: 'object',
978  required: ['title', 'status'],
979  properties: {
980    title: { type: 'string' },
981    status: { enum: STATUSES },
982    substeps: {
983      type: 'array',
984      items: { type: 'object', required: ['title', 'status'], properties: { title: { type: 'string' }, status: { enum: STATUSES } } },
985    },
986  },
987}
988
989// only calls that change something count as work for the enforcement below; reading and searching are free
990const WORK_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Bash', 'PowerShell'])
991const WORK_BEFORE_PLAN = 3 // the 4th changing call without a plan is refused once
992const CALLS_BEFORE_NUDGE = 6 // working calls without a plan update before a reminder
993
994
995export const register: Register = on => {
996  // per-turn bookkeeping; module variables are fine here, a reload just starts a fresh count
997  let workCalls = 0
998  let sinceUpdate = 0
999  let isPlanTouched = false
1000  let hasRefused = false
1001  let isWaitingOnBackground = false
1002
1003  on('turn.start', async ($, e, next) => {
1004    workCalls = 0
1005    sinceUpdate = 0
1006    isPlanTouched = false
1007    hasRefused = false
1008    isWaitingOnBackground = false
1009    isMainTurn = true
1010    owesDone = false
1011    await refreshTitle($)
1012    await publish($, 'working')
1013
1014    return next(e)
1015  })
1016
1017  // the rule lives in the cached system prompt; a message only carries one short line when bars are open,
1018  // and the person answering clears any "needs input" without a model call
1019  on('prompt.submit', async ($, e, next) => {
1020    // the person's own message, typed here or sent from their phone, retires the finished bars;
1021    // a prompt with no origin is the person's own too
1022    const origin = e.origin as { kind: string; asUser?: boolean } | undefined
1023    if (!origin || origin.kind === 'composer' || origin.kind === 'bridge' || (origin.kind === 'plugin' && origin.asUser === true)) {
1024      await fadeOutDone($)
1025      // the name other sessions show when this one has no bar: the person's own words, never a turn the system opened
1026      if (mine) mine.lastPrompt = readable(e.text, 30)
1027    }
1028    if (origin?.kind !== 'composer') return next(e)
1029    const list = await read($, plans)
1030    if (list.some(p => p.state === 'needs_input')) {
1031      await update($, plans, all => all.map(p => (p.state === 'needs_input' ? { ...p, state: 'running' as const, note: null } : p)))
1032    }
1033    const open = list.filter(p => p.state !== 'done' && p.id !== AGENTS)
1034    if (open.length === 0) return next(e)
1035    const line = `plan-progress open bars: ${open
1036      .map(p => {
1037        const w = where(p)
1038        return `${p.id} (${p.stages[w.stage]?.name ?? ''} ${w.step}/${w.stageSize})`
1039      })
1040      .join(', ')}`
1041
1042    return next({ ...e, context: [...(e.context ?? []), line] })
1043  })
1044
1045  // watches the main loop's changing calls: refuses once when multi-step work starts without a bar,
1046  // and reminds to update the bar when it goes stale mid-turn
1047  on('tool.call', async ($, e, next) => {
1048    // a subagent's call only names its current tool on its strip; no gate, no reminders
1049    if (e.agentId) {
1050      const agentId = e.agentId
1051      if (!agentHome.has(agentId)) return next(e)
1052      await editAgent($, agentId, a => ({ ...a, state: 'running', tool: e.tool }))
1053      if (e.tool_use_id) toolUses.set(e.tool_use_id, agentId)
1054      const ran = await next(e)
1055      if (e.tool_use_id) toolUses.delete(e.tool_use_id)
1056      if (waiting.delete(agentId)) await editAgent($, agentId, a => (a.state === 'waiting' ? { ...a, state: 'running' } : a))
1057      return ran
1058    }
1059    // the tool the main loop runs now, which other sessions show beside a session that has no bar
1060    if (mine && e.tool !== TOOL) mine.tool = e.tool
1061    if (!WORK_TOOLS.has(e.tool)) return next(e)
1062    isWaitingOnBackground = (e as unknown as Raw).run_in_background === true
1063    const hasLivePlan = isPlanTouched || (await read($, plans)).some(isOpenPlan)
1064    if (!hasLivePlan && !hasRefused && workCalls >= WORK_BEFORE_PLAN) {
1065      hasRefused = true
1066
1067      return { deny: `plan-progress: several changes ahead. Create a bar with ${TOOL} first, then retry.` }
1068    }
1069    const ran = await next(e)
1070    // a shell call that only read (ls, git status, grep) is not work
1071    if (ran.deny !== undefined || ran.isReadOnly) return ran
1072    workCalls += 1
1073    sinceUpdate += 1
1074    if (hasLivePlan && sinceUpdate >= CALLS_BEFORE_NUDGE) {
1075      sinceUpdate = 0
1076
1077      return { ...ran, context: [...(ran.context ?? []), `plan-progress: bar is stale, send {id, next:true} or {id, done, active}.`] }
1078    }
1079
1080    return ran
1081  })
1082
1083  // an open bar at the end of a turn: a question to the user marks it waiting on its own;
1084  // only a turn that did work and left the bar unexplained is sent back once
1085  on('classic.Stop', async ($, e, next) => {
1086    const result = await next(e)
1087    if (e.stop_hook_active || result.block || isWaitingOnBackground || (e.background_tasks?.length ?? 0) > 0) return result
1088    const open = (await read($, plans)).filter(isOpenPlan)
1089    if (open.length === 0) return result
1090    const asks = /[??]\s*$/.test(e.last_assistant_message ?? '')
1091    if (asks) {
1092      const last = open[open.length - 1]
1093      if (last) await putPlan($, { ...last, state: 'needs_input' })
1094
1095      return result
1096    }
1097    if (workCalls === 0 && !isPlanTouched) return result
1098
1099    return {
1100      ...result,
1101      block: `plan-progress: ${open.map(p => p.id).join(', ')} still open. Update each with ${TOOL}: {id, next:true}, or state "done", "needs_input" or "error" with a note.`,
1102    }
1103  })
1104
1105  on('session.start', async ($, e, next) => {
1106    await $.tool.register({
1107      name: 'plan_progress',
1108      description: 'Live progress bar above the prompt, one per id. Create with title + stages; update with short ops (next, done, active, failed) or state.',
1109      inputSchema: {
1110        type: 'object',
1111        required: ['id'],
1112        properties: {
1113          id: { type: 'string', description: 'Bar id; reuse it for updates' },
1114          title: { type: 'string' },
1115          kind: { enum: ['plan', 'todo'] },
1116          stages: {
1117            type: 'array',
1118            description: 'Full breakdown, only when creating or restructuring',
1119            items: { type: 'object', required: ['name', 'steps'], properties: { name: { type: 'string' }, steps: { type: 'array', items: STEP_SCHEMA } } },
1120          },
1121          next: { type: 'boolean', description: 'Active step finished, start the next one' },
1122          done: { type: 'array', items: { type: 'string' }, description: 'Step titles now finished' },
1123          active: { type: 'string', description: 'Step title now in progress' },
1124          failed: { type: 'string', description: 'Step title that failed' },
1125          state: { enum: ['running', 'needs_input', 'error', 'done'] },
1126          note: { type: 'string', description: 'One line for needs_input or error' },
1127        },
1128      },
1129    })
1130    const saved = await $.store.get(STYLE_STORE_KEY)
1131    if (isStyleId(saved)) await update($, barStyle, () => saved)
1132    const savedView = await $.store.get(AGENT_VIEW_STORE_KEY)
1133    if (isAgentView(savedView)) await update($, agentView, () => savedView)
1134    const savedAccent = await $.store.get(ACCENT_STORE_KEY)
1135    if (isAccentId(savedAccent)) {
1136      setAccent(savedAccent)
1137      await update($, accentChoice, () => savedAccent)
1138    }
1139    const savedShown = await $.store.get(SHOWN_STORE_KEY)
1140    if (typeof savedShown === 'boolean') await update($, isOpen, () => savedShown)
1141    const savedSounds = await $.store.get(SOUNDS_STORE_KEY)
1142    if (typeof savedSounds === 'boolean') await update($, soundsOn, () => savedSounds)
1143    isDarkTheme = String((await $.config.list()).find(row => row.key === 'theme')?.value ?? '').includes('dark')
1144    const savedCollapsed = await $.store.get(COLLAPSED_STORE_KEY)
1145    if (typeof savedCollapsed === 'boolean') await update($, isCollapsed, () => savedCollapsed)
1146    const savedCross = await $.store.get(CROSS_STORE_KEY)
1147    if (typeof savedCross === 'boolean') await update($, crossOn, () => savedCross)
1148    // a desktop session names itself in its environment; a terminal session has no id to switch to and only reads
1149    const home = await $.env.get('HOME')
1150    const hostId = await $.env.get('CLAUDE_CODE_HOST_SESSION_ID')
1151    if (home) sessionsDir = `${home}/.claude/plan-progress/sessions`
1152    if (home) appSessionsDir = `${home}/Library/Application Support/Claude/claude-code-sessions`
1153    if (hostId && HOST_ID.test(hostId)) mine = { hostId, cwd: await $.session.cwd(), state: 'idle', since: await $.clock.now(), lastPrompt: '', tool: '' }
1154    await refreshTitle($)
1155    $.clock.every(1000, async () => {
1156      // a bar that moved reaches the other sessions within a second; a working session also beats every 30 s
1157      const isBarMoved = mine !== null && (JSON.stringify(barsOf(await read($, plans))) !== lastBars || mine.tool !== lastTool)
1158      if (isBarMoved || (mine?.state === 'working' && (await $.clock.now()) - lastBeat >= HEARTBEAT_MS)) await publish($)
1159      pollCount += 1
1160      if (pollCount % POLL_EVERY === 0 && (await read($, crossOn))) await pollOthers($)
1161      if (pollCount % TITLE_EVERY === 0 && (await refreshTitle($))) await publish($)
1162      // the hairline style shows elapsed time, so it redraws every second while a bar runs
1163      const isTiming = (await styleOf($)) === 'hairline' && (await read($, plans)).some(p => p.state !== 'done')
1164      const isAwayTiming = (await read($, crossOn)) && (await read($, others)).rows.some(r => r.state === 'working' && !r.bar)
1165      if (isTiming || isAwayTiming || agentHome.size > 0 || (await $.clock.now()) < foldUntil) await update($, tick, n => n + 1)
1166    })
1167    await $.command.register({ name: 'progress', description: 'Show or hide the progress bars' })
1168    await $.command.register({ name: 'progress-style', description: 'Switch the progress bar style (no argument lists them, "next" cycles)' })
1169    await $.command.register({ name: 'progress-demo', description: 'Show a sample plan in the progress bars' })
1170    await $.command.register({ name: 'progress-sounds', description: 'Play the decision, error and done sounds' })
1171    await $.command.register({ name: 'progress-clear', description: 'Remove all progress bars' })
1172
1173    return next(e)
1174  })
1175
1176  on('prompt.compose', async ($, e, next) => {
1177    const result = await next(e)
1178
1179    return { sections: [...result.sections, { id: 'plan-progress:rules', text: RULES, scope: 'session' as const }] }
1180  })
1181
1182  on('tool.call', { tool: TOOL }, async ($, e) => {
1183    const raw = e as unknown as Raw
1184    const now = await $.clock.now()
1185    const list = await read($, plans)
1186    const id = slug(str(raw.id, 60) || str(raw.title, 80))
1187    const next = normalize(raw, list.find(p => p.id === id) ?? null, now, id)
1188    if (next.stages.length === 0) return { deny: `plan_progress: no bar "${id}" yet; create it with title and stages.` }
1189    isPlanTouched = true
1190    sinceUpdate = 0
1191    // finished mid-turn: the bar holds at its last step until the turn ends, so done comes after the reply
1192    const prevState = list.find(p => p.id === id)?.state
1193    const isHeld = isMainTurn && next.state === 'done' && prevState !== 'done'
1194    await putPlan($, isHeld ? { ...next, state: 'running', isFinishing: true } : next)
1195    const w = where(next)
1196
1197    const active = next.stages.flatMap(st => st.steps).find(st => st.status === 'active')
1198
1199    return { result: `${id}: ${Math.min(w.pos, w.total)}/${w.total}, ${next.state}${active ? `, active "${active.title}"` : ''}` }
1200  })
hooks/styles.ts 595 lines
1import type { AgentRun, Plan, PlanState, StepStatus } from '../types'
2
3// the bar styles a person can switch between with /progress-style; 'original' is the author's pixel bar in register.tsx
4export const STYLE_IDS = ['segments', 'hairline', 'beads', 'ledger', 'transit', 'grid', 'original'] as const
5export type StyleId = (typeof STYLE_IDS)[number]
6export const DEFAULT_STYLE: StyleId = 'segments'
7export const STYLE_INFO: Record<StyleId, string> = {
8  segments: '分段:一個階段一格,現在這段最顯眼、做完的變淡(陶土橘)',
9  hairline: '細線:2px 細線+會呼吸的線頭,平常黑白,右邊顯示經過時間',
10  beads: '串珠:一步一顆珠子,同階段用線串起來(藍)',
11  ledger: '刻度字:等寬字+小方格,正在做的那格慢慢呼吸,只有要注意時才有顏色',
12  transit: '路線圖:像捷運圖,站名在下方,比其他版本高一點(紫)',
13  grid: '點陣:一步一個小方格,階段之間空一格,步驟多也排得下(青)',
14  original: '原版:作者的像素顆粒進度條',
15}
16export const isStyleId = (v: unknown): v is StyleId => typeof v === 'string' && (STYLE_IDS as readonly string[]).includes(v)
17
18export type Visible = { shown: AgentRun[]; hidden: AgentRun[] }
19export type Drawn = { svg: string; height: number }
20export type Glyph = { char: string; color: string } | null
21export type BarStyle = {
22  glyph: (p: Plan) => Glyph
23  right: (p: Plan, now: number) => string
24  draw: (p: Plan, W: number, now: number, agents: Visible | null) => Drawn
25}
26
27// colours live in CSS variables so one drawing follows the app's light or dark scheme
28const PALETTE = `<style>svg{--ink:#1F1E1C;--muted:#73726C;--track:rgba(31,30,28,.08);--faint:rgba(31,30,28,.24);--panel:#F0EEE6;--on:#FFFBF7;--amber:#B26F12;--red:#C93C3C;--green:#2E8655;--clay:#C6613F;--blue:#3D6FD6;--violet:#6B5BD2;--clayS:#A9502F;--greenS:#256F46;--teal:#0E8A8F}
29@media (prefers-color-scheme:dark){svg{--ink:#F2F0EA;--muted:#A3A19A;--track:rgba(242,240,234,.10);--faint:rgba(242,240,234,.30);--panel:#2A2927;--on:#1F1E1C;--amber:#E2A64B;--red:#F07272;--green:#5FC58D;--clay:#E08A6A;--blue:#86A8F2;--violet:#A99CF6;--clayS:#E08A6A;--greenS:#5FC58D;--teal:#4FC3C7}}</style>`
30// the colour a person picks in the pane for "running", in place of the style's own; done, waiting and failed keep
31// green, amber and red. light/dark are the drawing's colour in each scheme, deep the light one behind white letters
32// (5:1 or better), glyph the dot left of the title, one hex for both schemes
33export const ACCENT_IDS = ['clay', 'blue', 'violet', 'teal', 'pink', 'ink'] as const
34export type AccentId = (typeof ACCENT_IDS)[number]
35export const ACCENT_INFO: Record<AccentId, { name: string; light: string; dark: string; deep: string; glyph: string }> = {
36  clay: { name: '陶土橘', light: '#C6613F', dark: '#E08A6A', deep: '#A9502F', glyph: '#D97757' },
37  blue: { name: '藍', light: '#3D6FD6', dark: '#86A8F2', deep: '#2F5BB8', glyph: '#5B85E8' },
38  violet: { name: '紫', light: '#6B5BD2', dark: '#A99CF6', deep: '#5A4AC0', glyph: '#8B7CF6' },
39  teal: { name: '青', light: '#0E8A8F', dark: '#4FC3C7', deep: '#0B7378', glyph: '#14A3A8' },
40  pink: { name: '桃紅', light: '#B83A78', dark: '#E48AB8', deep: '#9E2F66', glyph: '#D0548F' },
41  ink: { name: '墨黑', light: '#1F1E1C', dark: '#F2F0EA', deep: '#1F1E1C', glyph: '#8A8984' },
42}
43export const isAccentId = (v: unknown): v is AccentId => typeof v === 'string' && (ACCENT_IDS as readonly string[]).includes(v)
44// set by the plugin from the saved choice before it draws; null keeps every style's own colour
45let accent: AccentId | null = null
46export const setAccent = (v: unknown) => {
47  accent = isAccentId(v) ? v : null
48}
49// the chosen glyph colour, for a row the plugin colours itself
50export const accentGlyph = () => (accent ? ACCENT_INFO[accent].glyph : null)
51// every style names its colour through these variables, so one override recolours them all; hairline and ledger,
52// black and white by design, take it through --acc on their moving point only
53const accentStyle = () => {
54  if (!accent) return ''
55  const a = ACCENT_INFO[accent]
56  const vars = (c: string, deep: string) => `--clay:${c};--blue:${c};--violet:${c};--teal:${c};--clayS:${deep};--acc:${c}`
57  return `<style>svg{${vars(a.light, a.deep)}}@media (prefers-color-scheme:dark){svg{${vars(a.dark, a.dark)}}}</style>`
58}
59
60// the glyph left of the title is a Text colour, one hex for both schemes
61const GLYPH_COLOR = { clay: '#D97757', blue: '#5B85E8', violet: '#8B7CF6', teal: '#14A3A8', needs_input: '#E09A1E', error: '#E5484D', done: '#30A46C' }
62const SANS = "'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif"
63const MONO = "ui-monospace,'SF Mono',Menlo,monospace"
64
65const svg = (W: number, H: number, body: string) => `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">${PALETTE}${accentStyle()}${body}</svg>`
66const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] ?? c)
67const fin = (s: StepStatus) => s === 'done' || s === 'skipped'
68const n1 = (v: number) => v.toFixed(1)
69const fill = (c: string, op?: number) => `style="fill:${c}${op === undefined ? '' : `;fill-opacity:${op}`}"`
70const ring = (c: string, w: number, bg = 'var(--panel)') => `style="fill:${bg};stroke:${c};stroke-width:${w}"`
71// the outline of a step left behind (see leftBehind): dashed, in the style's running colour
72const dashed = (c: string, w = 1.5) => `style="fill:var(--panel);stroke:${c};stroke-width:${w};stroke-dasharray:2.2 1.8"`
73
74// an estimate of drawn text width; the module has no canvas to measure with
75function textWidth(s: string, px: number, mono = false): number {
76  return [...s].reduce((w, ch) => {
77    if (/[ -鿿＀-￯]/.test(ch)) return w + px
78    if (mono) return w + px * 0.6
79    if (/[ilI.,:;'|!]/.test(ch)) return w + px * 0.3
80    if (/[mwMW]/.test(ch)) return w + px * 0.82
81    if (/[A-Z]/.test(ch)) return w + px * 0.66
82    return w + px * 0.55
83  }, 0)
84}
85function fit(s: string, px: number, max: number, mono = false): string {
86  if (textWidth(s, px, mono) <= max) return s
87  let t = s
88  while (t.length > 1 && textWidth(t + '…', px, mono) > max) t = t.slice(0, -1)
89  return t.length > 1 ? t + '…' : ''
90}
91
92// where a plan stands. Claude may work out of order: it can leave a step and come back to it later, so the
93// current step is the one marked active (or failed), not the first unfinished one; pos counts the finished steps
94// and at is the current step's place among all steps
95type Where = { pos: number; at: number; total: number; stage: number; step: number; stageSize: number; title: string }
96function where(p: Plan): Where {
97  const steps = p.stages.flatMap((s, i) => s.steps.map((step, j) => ({ i, j, step })))
98  const live = steps.findIndex(x => x.step.status === 'active' || x.step.status === 'error')
99  const first = steps.findIndex(x => !fin(x.step.status))
100  const isDone = p.state === 'done' || first < 0
101  const at = isDone ? steps.length : live >= 0 ? live : first
102  const pos = isDone ? steps.length : steps.filter(x => fin(x.step.status)).length
103  const cur = steps[Math.min(at, steps.length - 1)]
104  const stage = cur?.i ?? 0
105  const stageSize = p.stages[stage]?.steps.length ?? 0
106  return { pos, at, total: steps.length, stage, step: at >= steps.length ? stageSize : (cur?.j ?? 0) + 1, stageSize, title: cur?.step.title ?? '' }
107}
108// a step left behind: not finished, and before the current one. Every style draws it with a dashed outline in the
109// running colour, so it reads apart from the steps still ahead (solid, faint)
110function leftBehind(p: Plan): (i: number, j: number) => boolean {
111  const w = where(p)
112  const flat = p.stages.flatMap((s, i) => s.steps.map((step, j) => ({ i, j, step })))
113  const keys = new Set(flat.filter((x, k) => k < w.at && !fin(x.step.status) && x.step.status !== 'error').map(x => `${x.i}:${x.j}`))
114  return (i, j) => keys.has(`${i}:${j}`)
115}
116const stateVar = (state: PlanState, accent: string) =>
117  state === 'running' ? accent : state === 'needs_input' ? 'var(--amber)' : state === 'error' ? 'var(--red)' : 'var(--green)'
118const glyphFor = (p: Plan, own: string): Glyph => ({
119  char: p.state === 'needs_input' ? '?' : p.state === 'error' ? '!' : p.state === 'done' ? '✓' : '●',
120  color: p.state === 'running' ? (accentGlyph() ?? own) : GLYPH_COLOR[p.state],
121})
122const stepCount = (p: Plan) => {
123  const w = where(p)
124  return `${Math.min(w.pos, w.total)}/${w.total}`
125}
126const elapsed = (ms: number) => {
127  const sec = Math.max(0, Math.round(ms / 1000))
128  return sec < 60 ? `${sec}s` : `${Math.floor(sec / 60)}m ${sec % 60}s`
129}
130
131// ---------- agent strips, shared by the new styles ----------
132
133type StripLook = { accent: string; bg: boolean; mono?: boolean; tint?: number }
134function strips(v: Visible, W: number, now: number, o: StripLook): { body: string; height: number } {
135  const RH = o.bg ? 18 : 16
136  const GAP = o.bg ? 3 : 2
137  const px = o.mono ? 10.5 : 11.5
138  const family = o.mono ? MONO : SANS
139  const colour = (a: AgentRun) => (a.state === 'running' ? o.accent : a.state === 'waiting' ? 'var(--amber)' : a.state === 'done' ? 'var(--green)' : 'var(--red)')
140  const rows: string[] = []
141  v.shown.forEach((a, i) => {
142    const y = i * (RH + GAP)
143    const cy = y + RH / 2
144    const c = colour(a)
145    const indent = a.depth > 0 ? 12 : 0
146    let row = o.bg ? `<rect x="0" y="${y}" width="${W}" height="${RH}" rx="${RH / 2}" ${fill(c, o.tint ?? 0.12)}/>` : ''
147    const dx = (o.bg ? 10 : 4) + indent
148    row += `<circle cx="${dx}" cy="${cy}" r="3" ${fill(c)}>${a.state === 'running' ? '<animate attributeName="opacity" values="1;.35;1" dur="1.4s" repeatCount="indefinite"/>' : ''}</circle>`
149    const name = fit((a.depth > 0 ? '↳ ' : '') + a.title, px, W * 0.45, o.mono)
150    const nx = dx + 9
151    row += `<text x="${nx}" y="${cy + 4}" font-family="${family}" font-size="${px}" ${fill('var(--ink)')}>${esc(name)}</text>`
152    if (W > 300) row += `<text x="${n1(nx + textWidth(name, px, o.mono) + 8)}" y="${cy + 4}" font-family="${family}" font-size="${px}" ${fill(c)}>${esc(a.tool)}</text>`
153    row += `<text x="${W - (o.bg ? 9 : 2)}" y="${cy + 4}" text-anchor="end" font-family="${SANS}" font-size="11" ${fill('var(--muted)')}>${elapsed((a.endedAt ?? now) - a.startedAt)}</text>`
154    rows.push(row)
155  })
156  if (v.hidden.length > 0) {
157    const y = v.shown.length * (RH + GAP)
158    const done = v.hidden.filter(a => a.state === 'done').length
159    rows.push(
160      (o.bg ? `<rect x="0" y="${y}" width="${W}" height="${RH}" rx="${RH / 2}" ${fill('var(--faint)', 0.35)}/>` : '') +
161        `<text x="${o.bg ? 10 : 4}" y="${y + RH / 2 + 4}" font-family="${family}" font-size="${px}" ${fill('var(--muted)')}>+${v.hidden.length} more · ${done} done</text>`,
162    )
163  }
164  const count = rows.length
165  return { body: rows.join(''), height: count ? count * (RH + GAP) - GAP : 0 }
166}
167
168function withStrips(body: string, trackH: number, W: number, now: number, v: Visible | null, o: StripLook): Drawn {
169  if (!v) return { svg: svg(W, trackH, body), height: trackH }
170  const s = strips(v, W, now, o)
171  const off = trackH + 6
172  return { svg: svg(W, off + s.height, `${body}<g transform="translate(0 ${off})">${s.body}</g>`), height: off + s.height }
173}
174
175// ---------- segments: one cell per stage, every stage name visible ----------
176// the current stage is the loudest cell; finished ones fade to a tint. When the plan waits on the person or fails,
177// only the step at fault takes the amber or red, so it stands out from the clay. A stage too narrow for its name
178// shrinks to a thin bar, and the count lives only right of the bar
179
180const segments: BarStyle = {
181  glyph: p => glyphFor(p, GLYPH_COLOR.clay),
182  right: stepCount,
183  draw(p, W, now, agents) {
184    const H = 22
185    const gap = 2
186    const px = 11.5
187    const n = Math.max(1, p.stages.length)
188    const allDone = p.state === 'done'
189    const w = where(p)
190    const cs = allDone ? -1 : w.stage
191    const avail = W - gap * (n - 1)
192    // each stage's width follows its step count; the current one is widened to fit its name when it can be
193    const steps = p.stages.map(s => Math.max(1, s.steps.length))
194    const sum = steps.reduce((a, b) => a + b, 0)
195    let widths = steps.map(k => (avail * k) / sum)
196    const curName = p.stages[cs]?.name ?? ''
197    const curMin = textWidth(curName, px) + 18
198    if (cs >= 0 && (widths[cs] ?? 0) < curMin && avail - curMin > (n - 1) * 8) {
199      const rest = sum - (steps[cs] ?? 0)
200      widths = steps.map((k, i) => (i === cs ? curMin : ((avail - curMin) * k) / Math.max(1, rest)))
201    }
202    // the solid fills behind white letters are a shade deeper in the light scheme, so the letters stay readable
203    const solid = allDone ? 'var(--greenS)' : 'var(--clayS)'
204    const fault = p.state === 'needs_input' ? 'var(--amber)' : p.state === 'error' ? 'var(--red)' : null
205    let x = 0
206    let defs = ''
207    let out = ''
208    const isBehind = leftBehind(p)
209    // a step left behind: a dashed outline inside its cell, in the running colour
210    const behindBox = (bx: number, by: number, bw: number, bh: number) =>
211      `<rect x="${n1(bx + 1.5)}" y="${n1(by + 1.5)}" width="${n1(Math.max(0, bw - 3))}" height="${n1(Math.max(0, bh - 3))}" rx="${bh > 10 ? 4 : 2}" style="fill:none;stroke:var(--clayS);stroke-width:1.3;stroke-dasharray:3 2.5"/>`
212    p.stages.forEach((s, i) => {
213      const sw = widths[i] ?? 0
214      const k = Math.max(1, s.steps.length)
215      const stepW = sw / k
216      const doneN = s.steps.filter(t => fin(t.status)).length
217      const isCur = i === cs
218      const isDone = allDone || (!isCur && doneN === s.steps.length && s.steps.length > 0)
219      let label = fit(s.name, px, sw - 16)
220      // a stage with no room for its name is a thin bar, not an empty cell
221      const isThin = !isCur && !allDone && (label === '' || label.length < Math.min(3, s.name.length))
222      if (isThin) label = ''
223      const y = isThin ? 8 : 0
224      const h = isThin ? 6 : H
225      let g = `<rect x="${n1(x)}" y="${y}" width="${n1(sw)}" height="${h}" ${fill('var(--track)')}/>`
226      let labelFill: string | null = null
227      if (allDone) {
228        g += `<rect x="${n1(x)}" y="0" width="${n1(sw)}" height="${H}" ${fill(solid)}/>`
229      } else if (isDone) {
230        g += `<rect x="${n1(x)}" y="${y}" width="${n1(sw)}" height="${h}" ${fill(fault ? 'var(--ink)' : 'var(--clayS)', fault ? 0.12 : 0.26)}/>`
231      } else if (!isCur && s.steps.some((_, j) => isBehind(i, j))) {
232        // a stage the work moved past with steps still open: its finished steps tinted, the open ones outlined
233        s.steps.forEach((t, j) => {
234          if (fin(t.status)) g += `<rect x="${n1(x + stepW * j)}" y="${y}" width="${n1(stepW)}" height="${h}" ${fill(fault ? 'var(--ink)' : 'var(--clayS)', fault ? 0.12 : 0.26)}/>`
235          else if (isBehind(i, j)) g += behindBox(x + stepW * j, y, stepW, h)
236        })
237      } else if (isCur) {
238        // one fill over the whole stage: solid over its finished steps, fading through the active one to a tint, so
239        // there is no hard edge where the finished part stops. The middle of the fade breathes, slowly, eased
240        // the step being worked on: the active (or failed) one, which may come after a step left behind
241        const live = s.steps.findIndex(t => t.status === 'active' || t.status === 'error')
242        const curIdx = Math.max(0, live >= 0 ? live : s.steps.findIndex(t => !fin(t.status)))
243        const at = (v: number) => n1(Math.min(100, Math.max(0, ((v - x) / Math.max(1, sw)) * 100)))
244        const d = x + stepW * curIdx
245        const m = d + stepW * 0.5
246        const e2 = d + stepW
247        const [head, headOp] = fault ? ['var(--ink)', 0.22] : ['var(--clayS)', 1]
248        const tone = fault ?? 'var(--clayS)'
249        const [lo, hi] = fault ? [0.25, 0.6] : [0.35, 0.7]
250        const breathe = `<animate attributeName="stop-opacity" values="${hi};${lo};${hi}" keyTimes="0;.5;1" calcMode="spline" keySplines=".45 0 .55 1;.45 0 .55 1" dur="2.4s" repeatCount="indefinite"/>`
251        const stop = (v: number, c: string, op: number, alive = false) => `<stop offset="${at(v)}%" style="stop-color:${c}" stop-opacity="${op}">${alive ? breathe : ''}</stop>`
252        // the finished steps before the current one are solid; one left behind is clear, with a hard edge, and gets
253        // its dashed outline below. Nothing before the current step: no head, the fade starts at the left edge
254        let headStops = ''
255        for (let j = 0; j < curIdx; j++) {
256          const op = isBehind(i, j) ? 0 : headOp
257          headStops += stop(x + stepW * j, head, op) + stop(x + stepW * (j + 1), head, op)
258        }
259        // running: the solid part fades out through the active step. Waiting or failed: the active step is one soft
260        // band of amber or red between the grey finished part and the tint
261        const bodyStops = fault
262          ? stop(d + stepW * 0.3, tone, hi, true) + stop(e2 - stepW * 0.2, tone, hi, true) + stop(Math.min(x + sw, e2 + stepW * 0.3), tone, 0.14)
263          : stop(curIdx > 0 ? m : x, tone, hi, true) + stop(e2, tone, 0.14)
264        defs += `<linearGradient id="g${i}" gradientUnits="userSpaceOnUse" x1="${n1(x)}" x2="${n1(x + sw)}" y1="0" y2="0">${headStops}${bodyStops}${stop(x + sw, tone, 0.14)}</linearGradient>`
265        g += `<rect x="${n1(x)}" y="0" width="${n1(sw)}" height="${H}" fill="url(#g${i})"/>`
266        for (let j = 0; j < curIdx; j++) if (isBehind(i, j)) g += behindBox(x + stepW * j, 0, stepW, H)
267        // the name is light over the solid steps and ink over a step left behind (hard edges, like the fill), and
268        // turns back to ink through the fade of the active step
269        if (!fault && curIdx > 0) {
270          let ts = ''
271          for (let j = 0; j < curIdx; j++) {
272            const c = isBehind(i, j) ? 'var(--ink)' : 'var(--on)'
273            ts += `<stop offset="${at(x + stepW * j)}%" style="stop-color:${c}"/><stop offset="${at(x + stepW * (j + 1))}%" style="stop-color:${c}"/>`
274          }
275          const last = isBehind(i, curIdx - 1) ? 'var(--ink)' : 'var(--on)'
276          ts += `<stop offset="${at(d)}%" style="stop-color:${last}"/><stop offset="${at(m)}%" style="stop-color:var(--ink)"/>`
277          defs += `<linearGradient id="t${i}" gradientUnits="userSpaceOnUse" x1="${n1(x)}" x2="${n1(x + sw)}" y1="0" y2="0">${ts}</linearGradient>`
278          labelFill = `fill="url(#t${i})"`
279        }
280      }
281      if (label) g += `<text x="${n1(x + 8)}" y="15" font-family="${SANS}" font-size="${px}" font-weight="${isCur ? 600 : 500}" ${labelFill ?? fill(allDone ? 'var(--on)' : isCur ? 'var(--ink)' : 'var(--muted)')}>${esc(label)}</text>`
282      out += g
283      x += sw + gap
284    })
285    // one rounded outline for the whole bar, so the cells read as one bar, not a row of buttons
286    defs += `<clipPath id="bar"><rect x="0" y="0" width="${n1(Math.max(0, x - gap))}" height="${H}" rx="6"/></clipPath>`
287    return withStrips(`<defs>${defs}</defs><g clip-path="url(#bar)">${out}</g>`, H, W, now, agents, { accent: 'var(--clay)', bg: true })
288  },
289}
290
291// ---------- hairline: a 2px line with a breathing head, ink until something needs attention ----------
292
293const hairline: BarStyle = {
294  glyph: () => null,
295  // how long it has run; once done, the step count (the bar already says Done)
296  right: (p, now) => (p.state === 'done' ? stepCount(p) : elapsed(now - p.startedAt)),
297  draw(p, W, now, agents) {
298    const H = 22
299    const w = where(p)
300    const done = p.state === 'done'
301    const c = done ? 'var(--green)' : p.state === 'running' ? 'var(--acc, var(--ink))' : stateVar(p.state, 'var(--ink)')
302    const sName = done ? 'Done' : (p.stages[w.stage]?.name ?? '')
303    const stepT = done ? '' : (p.state !== 'running' && p.note) || w.title
304    const nW = textWidth(sName, 12) * 1.05
305    const sT = fit(stepT, 12, Math.max(0, W * 0.42 - nW - 8))
306    const labelW = nW + (sT ? 6 + textWidth(`· ${sT}`, 12) : 0)
307    let out = `<text x="0" y="15" font-family="${SANS}" font-size="12"><tspan font-weight="500" ${fill(done ? 'var(--green)' : 'var(--ink)')}>${esc(sName)}</tspan>${sT ? `<tspan dx="6" ${fill(p.state === 'running' ? 'var(--muted)' : c)}>· ${esc(sT)}</tspan>` : ''}</text>`
308    const L = labelW + 16
309    const R = W - 8
310    const X = (k: number) => L + (k / Math.max(1, w.total)) * (R - L)
311    // the head sits at the current step; the line is ink over each run of finished steps and dashed over a step left
312    // behind, so a skipped stretch shows as a gap still to fill
313    const fx = X(done ? w.total : w.at)
314    const isBehind = leftBehind(p)
315    let k = 0
316    p.stages.forEach((s, si) => {
317      const a = X(k) + (k ? 2 : 0)
318      const end = k + s.steps.length
319      const b = X(end) - (end < w.total ? 2 : 0)
320      out += `<rect x="${n1(a)}" y="10" width="${n1(Math.max(0, b - a))}" height="2" rx="1" ${fill('var(--faint)', 0.55)}/>`
321      let run = -1
322      for (let j = 0; j <= s.steps.length; j++) {
323        const isFin = j < s.steps.length && (done || fin(s.steps[j]?.status ?? 'pending'))
324        if (isFin && run < 0) run = j
325        if (!isFin && run >= 0) {
326          const x1 = Math.max(a, X(k + run))
327          const x2 = Math.min(b, X(k + j))
328          out += `<rect x="${n1(x1)}" y="10" width="${n1(Math.max(0, x2 - x1))}" height="2" rx="1" ${fill(done ? 'var(--green)' : 'var(--ink)', done ? 1 : 0.85)}/>`
329          run = -1
330        }
331      }
332      s.steps.forEach((_, j) => {
333        if (isBehind(si, j)) out += `<line x1="${n1(Math.max(a, X(k + j)) + 1.5)}" x2="${n1(Math.min(b, X(k + j + 1)) - 1.5)}" y1="11" y2="11" style="stroke:var(--acc, var(--ink));stroke-width:2;stroke-dasharray:2.5 2"/>`
334      })
335      k = end
336    })
337    if (done) {
338      out += `<circle cx="${n1(R)}" cy="11" r="6" ${fill('var(--green)')}/><path d="M${n1(R - 2.6)} 11.2l1.8 1.8 3.4-3.6" style="fill:none;stroke:var(--on);stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round"/>`
339    } else if (p.state === 'needs_input') {
340      out += `<circle cx="${n1(fx)}" cy="11" r="5" ${ring(c, 2)}><animate attributeName="stroke-opacity" values="1;.35;1" dur="1.8s" repeatCount="indefinite"/></circle>`
341    } else {
342      if (p.state === 'running') out += `<circle cx="${n1(fx)}" cy="11" r="4" ${fill(c, 0.3)}><animate attributeName="r" values="4;10" dur="1.8s" repeatCount="indefinite" calcMode="spline" keyTimes="0;1" keySplines=".2 .8 .3 1"/><animate attributeName="fill-opacity" values=".3;0" dur="1.8s" repeatCount="indefinite"/></circle>`
343      out += `<circle cx="${n1(fx)}" cy="11" r="${p.state === 'error' ? 5 : 4}" ${fill(c)}/>`
344      if (p.state === 'error') out += `<path d="M${n1(fx - 2)} 9l4 4M${n1(fx + 2)} 9l-4 4" style="stroke:var(--on);stroke-width:1.4;stroke-linecap:round"/>`
345    }
346    return withStrips(out, H, W, now, agents, { accent: 'var(--ink)', bg: false })
347  },
348}
349
350// ---------- beads: one bead per step, a stage's beads strung together ----------
351
352const beads: BarStyle = {
353  glyph: p => glyphFor(p, GLYPH_COLOR.blue),
354  right: stepCount,
355  draw(p, W, now, agents) {
356    const H = 22
357    const cy = 11
358    const w = where(p)
359    const done = p.state === 'done'
360    const acc = done ? 'var(--green)' : 'var(--blue)'
361    // narrow bars pull the beads of a stage together first; the gap between stages keeps at least 12, so the
362    // stages stay apart, and the beads shrink with their spacing
363    let sp = 15
364    let sg = 14
365    const need = () => p.stages.reduce((a, s) => a + (s.steps.length - 1) * sp + 10, 0) + (p.stages.length - 1) * sg
366    while (need() > W * 0.55 && sp > 8) {
367      sp -= 1
368      sg = Math.max(12, sg - 0.4)
369    }
370    const k = Math.max(0.7, Math.min(1, sp / 12))
371    let x = 6
372    let out = ''
373    const isBehind = leftBehind(p)
374    let si = -1
375    for (const s of p.stages) {
376      si += 1
377      const xs = s.steps.map((_, j) => x + j * sp)
378      for (let j = 1; j < xs.length; j++) {
379        const on = fin(s.steps[j]?.status ?? 'pending')
380        out += `<rect x="${n1(xs[j - 1] ?? 0)}" y="${cy - 0.75}" width="${n1(sp)}" height="1.5" ${fill(on ? acc : 'var(--faint)', on ? 0.9 : 0.6)}/>`
381      }
382      s.steps.forEach((st, j) => {
383        const bx = n1(xs[j] ?? 0)
384        if (fin(st.status)) out += `<circle cx="${bx}" cy="${cy}" r="${n1(4.5 * k)}" ${fill(acc)}/>`
385        else if (st.status === 'error') out += `<circle cx="${bx}" cy="${cy}" r="5.5" ${fill('var(--red)')}/><path d="M${n1(Number(bx) - 2)} ${cy - 2}l4 4M${n1(Number(bx) + 2)} ${cy - 2}l-4 4" style="stroke:var(--on);stroke-width:1.4;stroke-linecap:round"/>`
386        else if (st.status === 'active') {
387          const c = p.state === 'needs_input' ? 'var(--amber)' : acc
388          out += `<circle cx="${bx}" cy="${cy}" r="5.5" ${ring(c, 1.8)}/><circle cx="${bx}" cy="${cy}" r="2.4" ${fill(c)}><animate attributeName="r" values="2;3.2;2" dur="${p.state === 'needs_input' ? 1.8 : 1.2}s" repeatCount="indefinite"/></circle>`
389        } else if (isBehind(si, j)) out += `<circle cx="${bx}" cy="${cy}" r="${n1(3.8 * k)}" ${dashed(acc)}/>`
390        else out += `<circle cx="${bx}" cy="${cy}" r="${n1(3.6 * k)}" ${ring('var(--faint)', 1.5)}/>`
391      })
392      x = (xs[xs.length - 1] ?? x) + 10 + sg - 4
393    }
394    const lx = x + 4
395    const sName = done ? 'Done' : (p.stages[w.stage]?.name ?? '')
396    const stepT = done ? '' : (p.state !== 'running' && p.note) || w.title
397    const room = W - lx
398    const nW = textWidth(sName, 12) * 1.05
399    const sT = fit(stepT, 12, room - nW - 22)
400    if (room > nW) out += `<text x="${n1(lx)}" y="15" font-family="${SANS}" font-size="12"><tspan font-weight="500" ${fill(done ? 'var(--green)' : 'var(--ink)')}>${esc(sName)}</tspan>${sT ? `<tspan dx="6" ${fill('var(--muted)')}>· ${esc(sT)}</tspan>` : ''}</text>`
401    return withStrips(out, H, W, now, agents, { accent: 'var(--blue)', bg: false })
402  },
403}
404
405// ---------- ledger: mono stage names and a row of cells, the active cell blinks like a cursor ----------
406
407const ledger: BarStyle = {
408  glyph: () => null,
409  right: stepCount,
410  draw(p, W, now, agents) {
411    const H = 22
412    const done = p.state === 'done'
413    const w = where(p)
414    const cw = 6
415    const cg = 3
416    const lg = 7
417    const sgap = 14
418    const px = 10.5
419    const cellsW = (n: number) => n * (cw + cg) - cg
420    const nameOf = (name: string, mode: 'full' | 'short') => (mode === 'short' ? name.slice(0, 3) : name).toUpperCase()
421    const width = (mode: 'full' | 'short' | 'none') =>
422      p.stages.reduce((a, s) => a + (mode === 'none' ? 0 : textWidth(nameOf(s.name, mode), px, true) * 1.04 + lg) + cellsW(s.steps.length), 0) + (p.stages.length - 1) * sgap
423    const mode = width('full') <= W * 0.78 ? 'full' : width('short') <= W * 0.9 ? 'short' : 'none'
424    let x = 0
425    let out = ''
426    const isBehind = leftBehind(p)
427    p.stages.forEach((s, i) => {
428      const isCur = !done && i === w.stage
429      const allDone = s.steps.every(t => fin(t.status))
430      // too narrow for every name: the current stage still shows its short one
431      if (mode !== 'none' || isCur) {
432        const name = nameOf(s.name, mode === 'none' ? 'short' : mode)
433        out += `<text x="${n1(x)}" y="15" font-family="${MONO}" font-size="${px}" font-weight="${isCur ? 700 : 500}" letter-spacing=".04em" ${fill(isCur ? 'var(--ink)' : 'var(--muted)', isCur || allDone ? 1 : 0.7)}>${esc(name)}</text>`
434        x += textWidth(name, px, true) * 1.04 + lg
435      }
436      s.steps.forEach((st, j) => {
437        if (done) out += `<rect x="${n1(x)}" y="5" width="${cw}" height="12" rx="1.5" ${fill('var(--green)')}/>`
438        else if (fin(st.status)) out += `<rect x="${n1(x)}" y="5" width="${cw}" height="12" rx="1.5" ${fill('var(--ink)', 0.72)}/>`
439        else if (st.status === 'error') out += `<rect x="${n1(x)}" y="5" width="${cw}" height="12" rx="1.5" ${fill('var(--red)')}/>`
440        else if (st.status === 'active') {
441          const c = p.state === 'needs_input' ? 'var(--amber)' : 'var(--acc, var(--ink))'
442          out += `<rect x="${n1(x)}" y="5" width="${cw}" height="12" rx="1.5" ${fill(c)}><animate attributeName="opacity" values="1;.3;1" keyTimes="0;.5;1" calcMode="spline" keySplines=".45 0 .55 1;.45 0 .55 1" dur="1.8s" repeatCount="indefinite"/></rect>`
443        } else if (isBehind(i, j)) out += `<rect x="${n1(x + 0.6)}" y="5.6" width="${cw - 1.2}" height="10.8" rx="1.2" ${dashed('var(--acc, var(--ink))', 1.2)}/>`
444        else out += `<rect x="${n1(x + 0.6)}" y="5.6" width="${cw - 1.2}" height="10.8" rx="1.2" style="fill:none;stroke:var(--faint);stroke-width:1.2"/>`
445        x += cw + cg
446      })
447      x += sgap - cg
448    })
449    const label = done ? 'Done' : (p.state !== 'running' && p.note) || w.title
450    const lc = done ? 'var(--green)' : p.state === 'running' ? 'var(--muted)' : stateVar(p.state, 'var(--ink)')
451    const t = fit(label, 12, W - x - 4)
452    if (t) out += `<text x="${n1(x)}" y="15" font-family="${SANS}" font-size="12" ${fill(lc)}>${esc(t)}</text>`
453    return withStrips(out, H, W, now, agents, { accent: 'var(--ink)', bg: false, mono: true })
454  },
455}
456
457// ---------- transit: stages as stretches of a line, names below, a train moving along ----------
458
459const transit: BarStyle = {
460  glyph: p => glyphFor(p, GLYPH_COLOR.violet),
461  right: stepCount,
462  draw(p, W, now, agents) {
463    const H = 36
464    const cy = 10
465    const pad = 7
466    const w = where(p)
467    const done = p.state === 'done'
468    const c = done ? 'var(--green)' : stateVar(p.state, 'var(--violet)')
469    const lineC = done ? 'var(--green)' : 'var(--violet)'
470    const L = pad
471    const R = W - pad
472    const X = (k: number) => L + (k / Math.max(1, w.total)) * (R - L)
473    // where the train is: the current step, which may lie past a step left behind
474    const pos = done ? w.total : w.at
475    const isBehind = leftBehind(p)
476    const flat = p.stages.flatMap((s, i) => s.steps.map((st, j) => ({ i, j, st })))
477    let out = `<rect x="${L}" y="${cy - 1.5}" width="${n1(R - L)}" height="3" rx="1.5" ${fill('var(--faint)', 0.5)}/>`
478    // the line is coloured over each run of finished steps, dashed over a step left behind
479    let run = -1
480    for (let k = 0; k <= flat.length; k++) {
481      const isFin = k < flat.length && (done || fin(flat[k]?.st.status ?? 'pending'))
482      if (isFin && run < 0) run = k
483      if (!isFin && run >= 0) {
484        out += `<rect x="${n1(X(run))}" y="${cy - 1.5}" width="${n1(X(k) - X(run))}" height="3" rx="1.5" ${fill(lineC)}/>`
485        run = -1
486      }
487    }
488    flat.forEach((x, k) => {
489      if (isBehind(x.i, x.j)) out += `<line x1="${n1(X(k) + 2)}" x2="${n1(X(k + 1) - 2)}" y1="${cy}" y2="${cy}" style="stroke:${lineC};stroke-width:3;stroke-dasharray:3 2.5"/>`
490    })
491    const bounds = [0]
492    for (const s of p.stages) bounds.push((bounds[bounds.length - 1] ?? 0) + s.steps.length)
493    for (let k = 1; k < w.total; k++) if (!bounds.includes(k)) out += `<circle cx="${n1(X(k))}" cy="${cy}" r="1.4" ${fill(k <= pos ? 'var(--panel)' : 'var(--faint)')}/>`
494    bounds.forEach((k, i) => {
495      const passed = k <= pos
496      const last = i === bounds.length - 1
497      // a passed station is a filled dot; one still ahead is smaller and faint, so the way ahead stays quiet
498      out += passed
499        ? `<circle cx="${n1(X(k))}" cy="${cy}" r="${last ? 5.5 : 4.5}" style="fill:${lineC};stroke:var(--panel);stroke-width:2"/>`
500        : `<circle cx="${n1(X(k))}" cy="${cy}" r="${last ? 4 : 3.4}" style="fill:var(--panel);stroke:var(--faint);stroke-width:1.4"/>`
501      if (last && done) out += `<path d="M${n1(X(k) - 2.4)} ${cy + 0.2}l1.6 1.6 3.2-3.4" style="fill:none;stroke:var(--on);stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round"/>`
502    })
503    if (!done) {
504      const tx = X(pos + 0.5)
505      // where the train is: a ring with a breathing centre, like the beads' active step; amber with ? or red with ×
506      // when it waits or fails
507      if (p.state === 'running') {
508        out += `<circle cx="${n1(tx)}" cy="${cy}" r="6" ${fill(c, 0.22)}><animate attributeName="r" values="6;11" dur="2.4s" repeatCount="indefinite" calcMode="spline" keyTimes="0;1" keySplines=".2 .8 .3 1"/><animate attributeName="fill-opacity" values=".22;0" dur="2.4s" repeatCount="indefinite"/></circle>`
509        out += `<circle cx="${n1(tx)}" cy="${cy}" r="6" ${ring(c, 2)}/><circle cx="${n1(tx)}" cy="${cy}" r="2.6" ${fill(c)}><animate attributeName="r" values="2.2;3.2;2.2" keyTimes="0;.5;1" calcMode="spline" keySplines=".45 0 .55 1;.45 0 .55 1" dur="2.4s" repeatCount="indefinite"/></circle>`
510      } else {
511        out += `<circle cx="${n1(tx)}" cy="${cy}" r="6.5" style="fill:${c};stroke:var(--panel);stroke-width:2"/>`
512        if (p.state === 'needs_input') out += `<text x="${n1(tx)}" y="${cy + 3.4}" text-anchor="middle" font-family="${SANS}" font-size="9.5" font-weight="700" ${fill('var(--on)')}>?</text>`
513        else out += `<path d="M${n1(tx - 2)} ${cy - 2}l4 4M${n1(tx + 2)} ${cy - 2}l-4 4" style="stroke:var(--on);stroke-width:1.4;stroke-linecap:round"/>`
514      }
515    }
516    // station names under their stretch, without the count (it is right of the bar). The current one always shows,
517    // kept inside the bar; another shows only whole and clear of it, never cut to "Res…"
518    const px = 10.5
519    const mid = (i: number) => (X(bounds[i] ?? 0) + X(bounds[i + 1] ?? 0)) / 2
520    const cur = done ? -1 : w.stage
521    const curName = cur >= 0 ? (p.stages[cur]?.name ?? '') : ''
522    const curW = textWidth(curName, px)
523    const curX = cur >= 0 ? Math.min(R - curW / 2, Math.max(L + curW / 2, mid(cur))) : 0
524    p.stages.forEach((s, i) => {
525      const a = X(bounds[i] ?? 0)
526      const b = X(bounds[i + 1] ?? 0)
527      const isCur = i === cur
528      const passed = (bounds[i + 1] ?? 0) <= pos
529      const tw = textWidth(s.name, px)
530      const x = isCur ? curX : mid(i)
531      const isClear = isCur || (tw <= b - a - 6 && (cur < 0 || x + tw / 2 + 8 < curX - curW / 2 || x - tw / 2 - 8 > curX + curW / 2))
532      if (isClear) out += `<text x="${n1(x)}" y="${cy + 21}" text-anchor="middle" font-family="${SANS}" font-size="${px}" font-weight="${isCur ? 600 : 500}" ${fill(isCur ? 'var(--ink)' : 'var(--muted)', isCur || passed ? 1 : 0.7)}>${esc(s.name)}</text>`
533    })
534    return withStrips(out, H, W, now, agents, { accent: 'var(--violet)', bg: true, tint: 0.1 })
535  },
536}
537
538// ---------- grid: one small square per step, two to a column, a stage's squares set apart ----------
539
540const grid: BarStyle = {
541  glyph: p => glyphFor(p, GLYPH_COLOR.teal),
542  right: stepCount,
543  draw(p, W, now, agents) {
544    const H = 22
545    const w = where(p)
546    const done = p.state === 'done'
547    const acc = done ? 'var(--green)' : 'var(--teal)'
548    // squares shrink when a long plan would take more than half the bar
549    let cell = 7
550    let cg = 2
551    let sgap = 7
552    const cols = (k: number) => Math.ceil(Math.max(1, k) / 2)
553    const need = () => p.stages.reduce((a, s) => a + cols(s.steps.length) * (cell + cg) - cg, 0) + (p.stages.length - 1) * sgap
554    while (need() > W * 0.5 && cell > 4) {
555      cell -= 1
556      cg = Math.max(1, cg - 0.5)
557      sgap = Math.max(4, sgap - 1)
558    }
559    const top = (H - (cell * 2 + cg)) / 2
560    let x = 0
561    let out = ''
562    const isBehind = leftBehind(p)
563    let si = -1
564    for (const s of p.stages) {
565      si += 1
566      s.steps.forEach((st, j) => {
567        const cx = n1(x + Math.floor(j / 2) * (cell + cg))
568        // a column holding one square, the last of an odd stage, puts it at the middle
569        const isAlone = j % 2 === 0 && j === s.steps.length - 1
570        const cy = n1(isAlone ? (H - cell) / 2 : top + (j % 2) * (cell + cg))
571        const box = `x="${cx}" y="${cy}" width="${cell}" height="${cell}" rx="${cell > 5 ? 1.5 : 1}"`
572        if (st.status === 'done') out += `<rect ${box} ${fill(acc)}/>`
573        else if (st.status === 'skipped') out += `<rect ${box} ${fill(acc, 0.4)}/>`
574        else if (st.status === 'error') out += `<rect ${box} ${fill('var(--red)')}/>`
575        else if (st.status === 'active') {
576          const c = p.state === 'needs_input' ? 'var(--amber)' : acc
577          out += `<rect ${box} ${fill(c)}><animate attributeName="fill-opacity" values="1;.3;1" dur="${p.state === 'needs_input' ? 1.8 : 1.2}s" repeatCount="indefinite"/></rect>`
578        } else
579          out += `<rect x="${n1(Number(cx) + 0.5)}" y="${n1(Number(cy) + 0.5)}" width="${cell - 1}" height="${cell - 1}" rx="${cell > 5 ? 1.2 : 0.8}" ${isBehind(si, j) ? dashed(acc, 1.2) : 'style="fill:none;stroke:var(--faint);stroke-width:1"'}/>`
580      })
581      x += cols(s.steps.length) * (cell + cg) - cg + sgap
582    }
583    const lx = x - sgap + 12
584    const sName = done ? 'Done' : (p.stages[w.stage]?.name ?? '')
585    const stepT = done ? '' : (p.state !== 'running' && p.note) || w.title
586    const room = W - lx
587    const nW = textWidth(sName, 12) * 1.05
588    const sT = fit(stepT, 12, room - nW - 22)
589    if (room > nW) out += `<text x="${n1(lx)}" y="15" font-family="${SANS}" font-size="12"><tspan font-weight="500" ${fill(done ? 'var(--green)' : 'var(--ink)')}>${esc(sName)}</tspan>${sT ? `<tspan dx="6" ${fill('var(--muted)')}>· ${esc(sT)}</tspan>` : ''}</text>`
590    return withStrips(out, H, W, now, agents, { accent: 'var(--teal)', bg: false })
591  },
592}
593
594export const STYLES: Record<Exclude<StyleId, 'original'>, BarStyle> = { segments, hairline, beads, ledger, transit, grid }
595
types/index.d.ts 65 lines
1export type StepStatus = 'pending' | 'active' | 'done' | 'error' | 'skipped'
2export type PlanSubstep = { title: string; status: StepStatus }
3export type PlanStep = { title: string; status: StepStatus; substeps: PlanSubstep[] }
4export type PlanStage = { name: string; steps: PlanStep[] }
5export type PlanState = 'running' | 'needs_input' | 'error' | 'done'
6// one subagent shown as a state strip under a bar; depth 1 sits under its parent agent
7export type AgentRun = {
8  id: string
9  title: string
10  state: 'running' | 'waiting' | 'done' | 'error'
11  tool: string
12  startedAt: number
13  endedAt: number | null
14  depth: number
15}
16export type Plan = {
17  id: string
18  title: string
19  kind: 'plan' | 'todo'
20  stages: PlanStage[]
21  state: PlanState
22  note: string | null
23  startedAt: number
24  agents?: AgentRun[]
25  // when the current batch of agents all finished; their strips fold a few seconds later
26  agentsDoneAt?: number | null
27  // set when the person's next message retires a finished bar; it fades out, then leaves the list
28  leavingAt?: number | null
29  // the model finished it mid-turn; it turns done, with its sound, once the main turn ends
30  isFinishing?: boolean
31}
32
33// another desktop session, as this session reads it from the shared folder: what it does now and its newest bar
34// isLeaving: the person pressed ✕; the row dims for a moment, then leaves
35// title: the name the app's sessions list shows for it, when that session could read it
36// tool: the tool its main loop runs now, while it works
37export type OtherSession = { hostId: string; folder: string; label: string; title?: string; tool?: string; state: 'working' | 'done' | 'needs_input'; since: number; bar?: Plan; isLeaving?: boolean }
38export type OthersView = { rows: OtherSession[] }
39
40declare module 'claude-code' {
41  interface PluginState {
42    'plan-progress': {
43      plans: Plan[]
44      // whether the bars show; also in $.store, so it holds across sessions
45      isOpen: boolean
46      // whether the decision, error and done sounds play; also in $.store
47      sounds: boolean
48      // bumped every second while agents run, so elapsed times and folding redraw
49      tick: number
50      // the bar style chosen with /progress-style, one of STYLE_IDS in hooks/styles.ts
51      style: string
52      // how subagent strips show: 'expanded', 'summary' or 'hidden'
53      agentView: string
54      // the other sessions that run, finished or wait on the person, each with its newest bar
55      others: OthersView
56      // whether those other sessions show above the prompt; also in $.store
57      crossSessions: boolean
58      // the running colour picked in the pane, one of ACCENT_IDS in hooks/styles.ts, or '' for each style's own; also in $.store
59      accent: string
60      // whether the band is folded to one row; also in $.store
61      collapsed: boolean
62    }
63  }
64}
65