A /workers pane of this session's child runs with a live tail, and the session's pinned asks above the prompt with their context on click; a right-click drops…

These skills help one person run product and engineering work through subagents. Workers use separate git worktrees and own each task through checks, review, and push. Repos that use PRs get one small PR per task.
The skills contain no project facts or model choices. Each repo keeps its rules in .agent/orchestrate.md and its agent definitions in the active harness's project files. Claude Code and Codex can read the same repo rules while each uses its own agent file format.
Independent, invoked by the user:
| Skill | Work |
|---|---|
comm | Writing registers and rules for everything an agent writes to a person. |
orchestrate | Why the manager delegates; base, worktree, worker procedure, review, PR, and the final check. |
tech-debt | Weekly debt revisit: gathers friction signals, settles candidates with the user, and cuts tickets. |
intake | Stakeholder interview on the stakeholder's own machine, filed as issues. See intake/INSTALL.md. |
Composed on top of comm and orchestrate:
| Skill | Work |
|---|---|
pm | Settles product choices, updates product docs, creates tickets, and gives ready work to the TL. |
tl | Holds the engineering bar (YAGNI, DRY, performance, OWASP), sends tasks, checks PRs, owns ADRs. |
Loaded by a fresh reviewer that a worker starts, not typed by the user:
| Skill | Work |
|---|---|
review-gate | The reviewer's procedure: scan, review the exact commit, return PASS, BLOCK, or ERROR. |
Clone this repo. Link each skill folder into the skill folder for the harness you use:
~/.claude/skills/~/.codex/skills/A link lets a pull in this repo update the installed skill at once.
Run /orchestrate when a repo has no .agent/orchestrate.md. It reads orchestrate/bootstrap.md, checks what the repo already uses, asks the user for each missing choice, and adds .agent/orchestrate.md plus the project agent files for the chosen harness. templates/orchestrate.md lists every value a repo file states; templates/writing-rules.md seeds the repo's writing overlay. Do not copy model names between runtimes.
Setup happens once. Normal runs read .agent/orchestrate.md from the remote default branch and do not read the setup file or template.
Repo files supply values and exceptions. The shared skills own the worker and review process, so a skill update changes every repo that links these skills.
tools/ contains optional local programs: a PR status poller that turns GitHub into local files, a board snapshot, a per-clone gh identity wrapper, a session boot report, a worktree hook, and Claude Code hooks (watch-guard, asks). Each documents its own setup in tools/README.md or its folder.
plugins/ holds Claude Code plugins. plugins/agent-ui adds /workers, a pane of the session's child runs (GPT, Claude, Claude review panels) with each run's live tail on click, opens itself at start in PM and TL sessions, and pins the session's asks (orchestrate §Pinned asks) above the prompt (an ask whose #N ticket is done is hidden), each expanding to its recorded context on click; a right-click on an ask drops it from the file (under the asks hook's lock), on the surfaces that draw a Client. Above its child runs it draws the session's dispatch chains (orchestrate §Dispatch chains), one line each, #4545 → #4549 → #4552: the newest issue Done on the board ticked green (older Done ones dropped), an issue a running row's label names in the accent colour, each #N linked to its issue with its board title shown on hover. Load it for one session with claude --plugin-dir <clone>/plugins/agent-ui, or for every session by adding that path to CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json. Its paths are userConfig options in /config; each option's description in its plugin.json says what an empty value does. Set childrenDir to the folder of child run out-dirs: empty, the pane lists no child runs from disk and says to set it. The pane lists only runs whose owner-session file holds this session's id, and reads each run's kind from its provider file alone. Review panels come from the clone's git common directory (.review-panel/), the asks, gh-status and board state from state_dir in the main checkout's .agent/local.env (session-bus.md §State directory), and ticket links from the GitHub repository of the session clone's origin remote (no GitHub remote, no link). The avatars draw as terminal pictures, which kitty and Ghostty show. Check it with claude plugin validate, claude plugin test and tsc -p on that folder.
A repo adds its own panels at the top of the pane by listing them in .agent/pane-panels.json at the main checkout's root (no file, no panels): [{ "id": "acme", "title": "Acme", "cmd": ["bun", "scripts/pane/acme.mjs"], "refresh_s": 60 }]. The pane runs cmd as an argv (no shell) in that root, stdin closed, 10 s limit: at most once per refresh_s (default 60, at least 5), collapsed or expanded, so the collapsed summary stays fresh too; never two runs at once. The command prints one JSON object on stdout and exits 0; anything else shows panel error: <first stderr line> and keeps the last good rows. The pane runs the listed commands without asking, with the user's environment: list only commands you trust, as with a repo hook. The output:
{
"summary": "north alpha 78%",
"tab": "north",
"tabs": [{
"id": "north", "label": "north",
"columns": [
{ "key": "name", "label": "cell", "width": 11 },
{ "key": "n", "label": "n", "width": 3, "align": "right" },
{ "key": "pass", "label": "pass", "width": 10, "kind": "bar" }
],
"rows": [{
"id": "alpha", "dim": false,
"cells": { "name": "alpha@med", "n": "9", "pass": { "frac": 0.78, "text": "78%", "tone": "good" } },
"hover": ["alpha@med · north", "pass 7 / fail 2"]
}],
"note": "dim = few runs"
}]
}
summary follows the title while collapsed; tab is the default tab, and the user's pick persists per panel id. Cells are strings, or for a bar column { frac 0..1, text, tone }: a bar the column wide in good, mid, bad or dim over a dark track, its text right-aligned inside it. A dim row draws dimmed; hover (up to 6 lines) is the row's hover card. Only tabs[].id, columns and rows are required; a row is cut to the pane width, never wrapped. Keep cells to narrow single-width text: a wide glyph (CJK, emoji) can wrap a row. A panel draws at most 12 tabs, 12 columns up to 200 wide, and 100 rows; control characters in any text draw as spaces.
Contract v1.2 adds three optional column keys. maxWidth (at least width): after the columns are laid out at their width with one space between, the cells left in the pane width go left to right to columns with a maxWidth, each up to it; width stays the minimum. "keep": "right" keeps an over-long value's right end (cut from the left); the default keeps the left end. {w} in a label becomes the column's laid-out width: { "key": "trend", "label": "{w}d", "width": 7, "maxWidth": 14, "keep": "right" } draws its header as 9d with 2 spare cells, and the header and rows use that one width. A header label longer than the column is cut at its right like any cell.
An optional filters list replaces the tab chips with one chip row per filter; together the picks name the tab, whose id is the picked option ids joined by / in filter order (worker/docs):
"filters": [
{ "id": "role", "options": [{ "id": "worker", "label": "worker" }, { "id": "reviewer", "label": "reviewer" }], "default": "worker" },
{ "id": "class", "options": [{ "id": "all", "label": "all" }, { "id": "docs", "label": "docs" }] }
]
Each filter's pick persists per panel and filter; an unset pick, or one the output no longer offers, falls back to default, else the first option. A combination with no tab draws the columns header and no data. With filters a panel takes at most 3 filters of 12 options and 48 tabs; without them, the tab chips and tab work as above.
hooks/register.tsx 1105 lines1import { atom, read, update } from 'claude-code'
2import type { AgentInfo, EngineInterface, FsEntry, PluginOptions, Register, Timer } from 'claude-code'
3
4import type { OpenAsk, Run } from '../types'
5import { type Avatar, SPRITE_COLS, avatarOf, avatarPicture } from './sprites'
6import {
7 TAIL_LINES,
8 codexTail,
9 elapsed,
10 epochMs,
11 kindOf,
12 labelOf,
13 lines,
14 localEnvValue,
15 chainLinks,
16 prMark,
17 sortPrs,
18 type PrMark,
19 resultJsonMessage,
20 statusOf,
21} from './lib'
22import {
23 PANEL_TIMEOUT_MS,
24 type PanelData,
25 type PanelRow,
26 type PanelSpec,
27 type PanelTab,
28 type Segment,
29 clip,
30 firstLine,
31 fnv1a,
32 headerSegments,
33 parsePanelOutput,
34 parseSpecs,
35 pickOptions,
36 pickTab,
37 placeBeside,
38 rowSegments,
39 TONES,
40} from './panels'
41
42type $ = EngineInterface
43type Root = { dir: string; isPanel: boolean }
44type Tail = { lines: string[]; lastMessage: string }
45type Cached = { key: string; mtimeMs: number; done: boolean; probe: Probe | null }
46type RunDir = { dir: string; mtimeMs: number }
47type Probe = { run: Run; pid: string; hasDone: boolean; exitCode: string }
48type NativeRun = { id: string; label: string; kind: string; status: Run['status'] }
49type Row = {
50 key: string
51 kind: string
52 label: string
53 status: Run['status']
54 avatar: Avatar | null
55 model?: string
56 duration?: string
57 diskRun?: Run
58 agentId?: string
59 parent?: string
60 children: Row[]
61}
62type PrRow = { number: number; title: string; mark: PrMark }
63const MARK_TONES: Record<PrMark, number> = { '✓': TONES.good as number, '⋯': TONES.mid as number, '✗': TONES.bad as number, '⚡': TONES.bad as number }
64type PrFile = { mtimeMs: number; pr: PrRow | null; done: number | null }
65type PrCache = { key: string; files: Map<string, PrFile>; open: Map<number, PrRow>; done: Set<number> }
66
67const REFRESH_MS = 3000
68const RECENT_DONE = 5
69const LIVE_WINDOW_MS = 24 * 3_600_000
70const MAX_ROWS = 30
71const TAIL_BYTES = 262_144
72const ASK_ACCENT = '#CBA6F7'
73
74// Probes keyed by the out-dir's listing (names + newest file mtime): a resume that
75// removes `done`, or a new owner stamp, changes the key and forces a re-probe.
76// A run with `done` is immutable: it is not re-listed while its parent's entry mtime holds.
77const probes = new Map<string, Cached>()
78const shaRuns = new Map<string, { mtimeMs: number; runs: RunDir[] }>()
79let prCache: PrCache = { key: '', files: new Map(), open: new Map(), done: new Set() }
80type Board = { key: string; done: Set<number>; titles: Map<number, string> }
81const NO_BOARD: Board = { key: '', done: new Set(), titles: new Map() }
82let boardCache = NO_BOARD
83
84async function readText($: $, path: string): Promise<string> {
85 return $.fs.read(path).then(
86 text => (typeof text === 'string' ? text.trim() : ''),
87 () => '',
88 )
89}
90
91async function listDir($: $, path: string): Promise<FsEntry[]> {
92 return $.fs.list(path).catch(() => [])
93}
94
95async function tailBytes($: $, path: string, bytes = TAIL_BYTES): Promise<string> {
96 const ran = await $.process.run(['tail', '-c', String(bytes), path]).catch(() => null)
97 return ran?.exitCode === 0 ? ran.stdout : ''
98}
99
100// One answer per session project root, hit or miss: a shell `cd` never moves it, while `/cd`, a
101// host directory change or a worktree move does. The promise is cached, so concurrent callers share one run.
102const byRoot = new Map<string, { root: string; value: Promise<unknown> }>()
103
104async function perRoot<T>($: $, name: string, compute: (root: string) => Promise<T>): Promise<T> {
105 const root = await $.session.root()
106 const hit = byRoot.get(name)
107 if (hit?.root === root) return hit.value as Promise<T>
108 const value = compute(root)
109 byRoot.set(name, { root, value })
110 return value
111}
112
113async function gitCommonDir($: $): Promise<string | null> {
114 return perRoot($, 'git', async root => {
115 const ran = await $.process
116 .run(['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: root })
117 .catch(() => null)
118 return ran?.exitCode === 0 ? ran.stdout.trim() : null
119 })
120}
121
122const childrenDirOf = (options: PluginOptions) => String(options.childrenDir ?? '').replace(/\/+$/, '')
123
124async function resolveRoots($: $, options: PluginOptions): Promise<Root[]> {
125 return perRoot($, 'roots', async () => {
126 const children = childrenDirOf(options)
127 const common = await gitCommonDir($)
128 return [...(children ? [{ dir: children, isPanel: false }] : []), ...(common ? [{ dir: `${common}/.review-panel`, isPanel: true }] : [])]
129 })
130}
131
132const subDirs = (entries: FsEntry[], parent: string): RunDir[] =>
133 entries.filter(entry => entry.kind === 'dir').map(entry => ({ dir: `${parent}/${entry.name}`, mtimeMs: entry.mtimeMs }))
134
135// A sha dir is re-listed only when its own mtime moves (a new panel run dir appears).
136async function runDirs($: $, root: Root): Promise<RunDir[]> {
137 const top = subDirs(await listDir($, root.dir), root.dir)
138 if (!root.isPanel) return top
139 const nested = await Promise.all(
140 top.map(async sha => {
141 let cached = shaRuns.get(sha.dir)
142 if (cached?.mtimeMs !== sha.mtimeMs) {
143 cached = { mtimeMs: sha.mtimeMs, runs: subDirs(await listDir($, sha.dir), sha.dir) }
144 shaRuns.set(sha.dir, cached)
145 }
146 return cached.runs
147 }),
148 )
149 return nested.flat()
150}
151
152async function probe($: $, dir: string, entries: FsEntry[], isPanel: boolean, sid: string): Promise<Probe | null> {
153 const names = new Map(entries.map(entry => [entry.name, entry]))
154 if (!names.has('pid')) return null
155 const field = (name: string) => (names.has(name) ? readText($, `${dir}/${name}`) : Promise.resolve(''))
156 const [owner, pid, provider, model, start, end, exitCode, cwd, agent] = await Promise.all([
157 field('owner-session'),
158 field('pid'),
159 field('provider'),
160 field('model'),
161 field('start-epoch'),
162 field('end-epoch'),
163 field('exit-code'),
164 field('cwd'),
165 field('agent'),
166 ])
167 if (sid === '' || owner !== sid) return null
168 const lastMtime = Math.max(0, ...entries.map(entry => entry.mtimeMs))
169 return {
170 pid,
171 hasDone: names.has('done'),
172 exitCode,
173 run: {
174 dir,
175 kind: kindOf(provider, isPanel),
176 label: labelOf(dir, isPanel),
177 cwd,
178 isReviewer: isPanel || agent === 'reviewer',
179 model: [provider, model].filter(Boolean).join('/'),
180 status: 'running',
181 startedAt: epochMs(start),
182 endedAt: epochMs(end) ?? (lastMtime || null),
183 },
184 }
185}
186
187async function alivePids($: $, pids: string[]): Promise<Set<string>> {
188 const valid = pids.filter(pid => /^\d+$/.test(pid))
189 if (valid.length === 0) return new Set()
190 const ran = await $.process.run(['ps', '-o', 'pid=', '-p', valid.join(',')]).catch(() => null)
191 return new Set((ran?.stdout ?? '').split(/\s+/).filter(Boolean))
192}
193
194async function scanRuns($: $, options: PluginOptions, now: number): Promise<Run[]> {
195 const sid = await $.session.id()
196 const found: Probe[] = []
197 const seen = new Set<string>()
198 for (const root of await resolveRoots($, options)) {
199 for (const { dir, mtimeMs } of await runDirs($, root)) {
200 seen.add(dir)
201 let cached = probes.get(dir)
202 if (!(cached?.done && cached.mtimeMs === mtimeMs)) {
203 const entries = await listDir($, dir)
204 const key = entries
205 .map(entry => entry.name)
206 .sort()
207 .concat(String(Math.max(0, ...entries.map(entry => entry.mtimeMs))))
208 .join('/')
209 if (cached?.key !== key) {
210 const done = entries.some(entry => entry.name === 'done')
211 cached = { key, mtimeMs, done, probe: await probe($, dir, entries, root.isPanel, sid) }
212 } else cached.mtimeMs = mtimeMs
213 probes.set(dir, cached)
214 }
215 if (cached.probe) found.push(cached.probe)
216 }
217 }
218 for (const dir of probes.keys()) if (!seen.has(dir)) probes.delete(dir)
219 // older runs without `done` read as dead: bounds the ps list and ignores reused pids
220 const recent = (one: Probe) => now - (one.run.startedAt ?? 0) <= LIVE_WINDOW_MS
221 const alive = await alivePids($, found.filter(one => !one.hasDone && recent(one)).map(one => one.pid))
222 const running: Run[] = []
223 const done: Run[] = []
224 for (const one of found) {
225 const run = { ...one.run, status: statusOf(one.hasDone, one.exitCode, recent(one) && alive.has(one.pid)) }
226 ;(run.status === 'running' ? running : done).push(run)
227 }
228 const when = (run: Run) => run.endedAt ?? run.startedAt ?? 0
229 done.sort((a, b) => when(b) - when(a))
230 running.sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0))
231 return [...running, ...done]
232}
233
234function runElapsed(run: Run, now: number): string {
235 return run.startedAt === null ? '?' : elapsed(((run.status === 'running' ? now : run.endedAt) ?? now) - run.startedAt)
236}
237
238// GPT runs stream codex events to result.jsonl; Claude runs only stderr.log.
239async function readTail($: $, run: Run): Promise<Tail> {
240 const names = new Set((await listDir($, run.dir)).map(entry => entry.name))
241 const tail = names.has('result.jsonl')
242 ? codexTail(await tailBytes($, `${run.dir}/result.jsonl`))
243 : names.has('stderr.log')
244 ? lines(await tailBytes($, `${run.dir}/stderr.log`)).slice(-TAIL_LINES)
245 : []
246 let lastMessage = ''
247 if (run.status !== 'running') {
248 lastMessage = names.has('last-message')
249 ? await readText($, `${run.dir}/last-message`)
250 : resultJsonMessage(names.has('result.json') ? await readText($, `${run.dir}/result.json`) : '')
251 }
252 return { lines: tail, lastMessage }
253}
254
255async function readNativeTail($: $, agentId: string): Promise<Tail> {
256 const messages = await $.session.messages({ agentId }).catch(() => [])
257 if (!Array.isArray(messages)) return { lines: [], lastMessage: '' }
258 const linesOut = messages.flatMap(message => lines(message.text)).slice(-TAIL_LINES)
259 return { lines: linesOut, lastMessage: '' }
260}
261
262// The gh-status files, re-read only where a file's mtime moved: the open PRs, and the numbers of
263// PRs that are MERGED or CLOSED.
264async function refreshPrCache($: $, dir: string): Promise<PrCache> {
265 const entries = (await listDir($, `${dir}/status`)).filter(entry => entry.kind === 'file' && /^pr-\d+\.json$/.test(entry.name))
266 const key = entries.map(entry => `${entry.name}:${entry.mtimeMs}`).sort().join('|')
267 const cache = prCache
268 if (cache.key !== key) {
269 const current = new Set(entries.map(entry => entry.name))
270 for (const name of cache.files.keys()) if (!current.has(name)) cache.files.delete(name)
271 const changed = entries.filter(entry => cache.files.get(entry.name)?.mtimeMs !== entry.mtimeMs)
272 const parsed = await Promise.all(changed.map(async entry => {
273 const value = jsonObject(await readText($, `${dir}/status/${entry.name}`))
274 const pr = value?.state === 'OPEN' && value.isDraft === false && typeof value.number === 'number'
275 ? { number: value.number, title: typeof value.title === 'string' ? value.title : '', mark: prMark(value.mergeable, value.checks) }
276 : null
277 const done = (value?.state === 'MERGED' || value?.state === 'CLOSED') && typeof value.number === 'number' ? value.number : null
278 return [entry.name, { mtimeMs: entry.mtimeMs, pr, done }] as const
279 }))
280 for (const [name, file] of parsed) cache.files.set(name, file)
281 cache.open = new Map([...cache.files.values()].flatMap(file => file.pr ? [[file.pr.number, file.pr] as const] : []))
282 cache.done = new Set([...cache.files.values()].flatMap(file => file.done === null ? [] : [file.done]))
283 cache.key = key
284 }
285 return cache
286}
287
288async function readReadyPrs($: $): Promise<PrRow[]> {
289 const state = await resolveStateDir($)
290 if (!state) return []
291 const cache = await refreshPrCache($, `${state}/gh-status`)
292 return sortPrs([...cache.open.values()])
293}
294
295// Repo panels: the list re-read when its file changes; each panel's last good output and last
296// error kept per root, id and argv.
297type PanelRun = { data: PanelData | null; error: string | null; startedAt: number | null; running: boolean }
298let panelList = { key: '', specs: [] as PanelSpec[] }
299const panelRuns = new Map<string, PanelRun>()
300const panelKey = (root: string, spec: PanelSpec) => [root, spec.id, ...spec.cmd].join('\0')
301
302// A re-read drops the kept output of every panel the list no longer has, in any root.
303async function readPanelSpecs($: $, root: string): Promise<PanelSpec[]> {
304 const stat = (await listDir($, `${root}/.agent`)).find(entry => entry.name === 'pane-panels.json' && entry.kind === 'file')
305 if (!stat) return []
306 const key = `${root}|${stat.mtimeMs}|${stat.size}`
307 if (panelList.key !== key) {
308 panelList = { key, specs: parseSpecs(await readText($, `${root}/.agent/pane-panels.json`)) }
309 const kept = new Set(panelList.specs.map(spec => panelKey(root, spec)))
310 for (const runKey of panelRuns.keys()) if (!kept.has(runKey)) panelRuns.delete(runKey)
311 }
312 return panelList.specs
313}
314
315const panelRunOf = (root: string, spec: PanelSpec): PanelRun => {
316 const key = panelKey(root, spec)
317 let run = panelRuns.get(key)
318 if (!run) panelRuns.set(key, (run = { data: null, error: null, startedAt: null, running: false }))
319 return run
320}
321
322async function runPanel($: $, root: string, spec: PanelSpec, run: PanelRun, now: number): Promise<void> {
323 run.running = true
324 run.startedAt = now
325 try {
326 const ran = await $.process.run(spec.cmd, { cwd: root, stdin: '', timeoutMs: PANEL_TIMEOUT_MS })
327 const data = ran.exitCode === 0 ? parsePanelOutput(ran.stdout) : null
328 if (data) {
329 run.data = data
330 run.error = null
331 } else run.error = firstLine(ran.stderr) || (ran.exitCode === 0 ? 'stdout is not one panel JSON object' : `exit ${ran.exitCode}`)
332 } catch (error) {
333 run.error = firstLine(error instanceof Error ? error.message : String(error)) || 'did not run'
334 } finally {
335 run.running = false
336 $.ui.invalidate('ui.render')
337 }
338}
339
340// Each panel, collapsed or expanded, runs at most once per refresh, and never twice at once.
341const isDue = (run: PanelRun, spec: PanelSpec, now: number) => !run.running && (run.startedAt === null || now - run.startedAt >= spec.refreshMs)
342
343// The render only schedules: a run it started itself would be cut when its dispatch ends, as
344// every `$` call in flight with a dispatch is ("Work that outlives a dispatch", plugin-authoring
345// reference), so the due panels start on a module timer. The render draws the last data; a
346// run's end draws the pane again. Each render that finds a panel due sets a timer; `isDue` and
347// the `running` flag, set as a run starts, let only the first timer start it.
348function schedulePanels($: $, root: string, specs: PanelSpec[], now: number): void {
349 if (!specs.some(spec => isDue(panelRunOf(root, spec), spec, now))) return
350 $.clock.after(1, () => {
351 for (const spec of specs) {
352 const run = panelRunOf(root, spec)
353 if (isDue(run, spec, now)) void runPanel($, root, spec, run, now)
354 }
355 })
356}
357
358type PanelRowView = { row: PanelRow; key: string; scope: string; segments: Segment[]; card: { top: number; left: number; width: number; lines: string[] } | null }
359// One row of chips: the tabs (`filter` null), or one filter's options.
360type ChipRow = { filter: string | null; chips: { id: string; label: string; selected: boolean }[] }
361type PanelView = {
362 spec: PanelSpec
363 isOpen: boolean
364 summary: string
365 error: string
366 data: PanelData | null
367 tab: PanelTab | null
368 chipRows: ChipRow[]
369 header: Segment[]
370 noData: boolean
371 rows: PanelRowView[]
372}
373const PANEL_INDENT = 2
374
375// The panels as drawn from pane row `top` down, one line each; a row's card goes below it, else
376// above it, never over it.
377function panelViews(
378 root: string,
379 specs: PanelSpec[],
380 open: string[],
381 tabs: Record<string, string>,
382 filterPicks: Record<string, Record<string, string>>,
383 top: number,
384 bodyColumns: number,
385 paneRows: number,
386): PanelView[] {
387 let y = top
388 const width = bodyColumns - PANEL_INDENT
389 return specs.map(spec => {
390 const run = panelRunOf(root, spec)
391 const isOpen = open.includes(spec.id)
392 const data = isOpen ? run.data : null
393 // with filters, their picks name the tab; a combination the output lacks has no rows
394 const filters = data?.filters ?? []
395 const picked = pickOptions(filters, filterPicks[spec.id])
396 const tab = !data ? null : filters.length > 0 ? (data.tabs.find(one => one.id === picked.join('/')) ?? null) : pickTab(data, tabs[spec.id])
397 const noData = !!data && filters.length > 0 && !tab
398 const columnsOf = tab ?? (noData ? (data.tabs[0] ?? null) : null)
399 const chipRows: ChipRow[] = !data
400 ? []
401 : filters.length > 0
402 ? filters.map((filter, k) => ({ filter: filter.id, chips: filter.options.map(option => ({ ...option, selected: option.id === picked[k] })) }))
403 : data.tabs.length > 1
404 ? [{ filter: null, chips: data.tabs.map(one => ({ id: one.id, label: one.label, selected: one.id === tab?.id })) }]
405 : []
406 const header = columnsOf ? headerSegments(columnsOf, width) : []
407 y += 1 + (run.error ? 1 : 0) + chipRows.length + (header.length > 0 ? 1 : 0)
408 const seen = new Set<string>()
409 const rows = (tab?.rows ?? []).map((row, i) => {
410 const key = seen.has(row.id) ? `${row.id}#${i}` : row.id
411 seen.add(key)
412 const at = y++
413 const cardWidth = Math.min(width, Math.max(0, ...row.hover.map(line => line.length)) + 4)
414 const place = placeBeside(at, 1, row.hover.length + 2, paneRows)
415 return {
416 row,
417 key,
418 scope: `panel:${fnv1a(`${spec.id}\0${key}`).toString(36)}`,
419 segments: rowSegments(tab as PanelTab, row, width),
420 card: row.hover.length === 0 ? null : { top: place.x, left: PANEL_INDENT, width: cardWidth, lines: row.hover.map(line => line.slice(0, Math.max(1, cardWidth - 4))) },
421 }
422 })
423 if (noData) y++
424 if (tab?.note) y++
425 const title = `▸ ${spec.title}`
426 return {
427 spec,
428 isOpen,
429 summary: !isOpen && run.data?.summary ? clip([{ text: ` ${run.data.summary}` }], bodyColumns - title.length)[0]?.text ?? '' : '',
430 error: run.error ? clip([{ text: `panel error: ${run.error}` }], width)[0]?.text ?? '' : '',
431 data,
432 tab,
433 chipRows,
434 header,
435 noData,
436 rows,
437 }
438 })
439}
440
441const startOf = (row: Row) => row.diskRun?.startedAt ?? 0
442
443function rowsFor(runs: Run[], agents: AgentInfo[], now: number): Row[] {
444 const disk: Row[] = runs.map(run => ({ key: `disk:${run.dir}`, kind: run.kind, label: run.label, status: run.status, avatar: avatarOf(run.kind), model: run.model, duration: runElapsed(run, now), diskRun: run, children: [] }))
445 const native: Row[] = agents.map(agent => {
446 const run = asNative(agent)
447 const parent = agents.some(other => other.id === agent.parentId) ? `native:${agent.parentId}` : undefined
448 return { key: `native:${run.id}`, kind: run.kind, label: run.label, status: run.status, avatar: 'claude', agentId: run.id, parent, children: [] }
449 })
450 // A disk reviewer joins the newest worker that started before it in the same worktree.
451 const workers = disk.filter(row => row.diskRun && !row.diskRun.isReviewer && row.diskRun.cwd.startsWith('/'))
452 for (const row of disk) {
453 const run = row.diskRun
454 if (!run?.isReviewer || !run.cwd.startsWith('/')) continue
455 row.parent = workers.filter(w => w.diskRun?.cwd === run.cwd && startOf(w) <= (run.startedAt ?? Infinity)).sort((a, b) => startOf(b) - startOf(a))[0]?.key
456 }
457 const all = [...disk, ...native]
458 const byKey = new Map(all.map(row => [row.key, row]))
459 const rootOf = (row: Row) => {
460 let root = row
461 for (let hops = 0; root.parent && hops < 8; hops++) root = byKey.get(root.parent) ?? root
462 return root
463 }
464 const nested = new Set<Row>()
465 for (const row of all) {
466 const root = rootOf(row)
467 if (root !== row) { root.children.push(row); nested.add(row) }
468 }
469 const top = all.filter(row => !nested.has(row))
470 const running = top.filter(row => row.status === 'running')
471 const finishedDisk = top.filter(row => row.diskRun && row.status !== 'running').slice(0, RECENT_DONE)
472 const finishedNative = top.filter(row => !row.diskRun && row.status !== 'running').slice(-RECENT_DONE).reverse()
473 // MAX_ROWS caps the finished rows only: a running row is never dropped
474 const shown = [...running, ...[...finishedDisk, ...finishedNative].slice(0, Math.max(0, MAX_ROWS - running.length))]
475 // a running child whose worker rolled off the list stays visible at the top
476 const orphans = all.filter(row => nested.has(row) && row.status === 'running' && !shown.includes(rootOf(row)))
477 return [...shown, ...orphans]
478}
479
480// The main checkout of the session's clone: its git common dir's parent.
481async function repoRoot($: $): Promise<string | null> {
482 return (await gitCommonDir($))?.replace(/\/\.git$/, '') ?? null
483}
484
485// `state_dir` from the main checkout's `.agent/local.env`; every state path is a fixed name under
486// it. No file or no key: null, and the state-scoped sections draw nothing.
487async function resolveStateDir($: $): Promise<string | null> {
488 return perRoot($, 'state', async () => {
489 const main = await repoRoot($)
490 if (!main) return null
491 return localEnvValue(await readText($, `${main}/.agent/local.env`), 'state_dir', (await $.env.get('HOME')) ?? '')
492 })
493}
494
495// board-snapshot.md's issue rows, cached on its mtime and size: the Done set and each title (a
496// `\|` in a cell is a literal pipe; the Status cell has five cells after it).
497async function readBoard($: $): Promise<Board> {
498 const state = await resolveStateDir($)
499 const stat = state ? (await listDir($, state)).find(entry => entry.name === 'board-snapshot.md' && entry.kind === 'file') : undefined
500 if (!state || !stat) return NO_BOARD
501 const key = `${state}|${stat.mtimeMs}:${stat.size}`
502 if (boardCache.key !== key) {
503 const board: Board = { key, done: new Set(), titles: new Map() }
504 for (const line of (await readText($, `${state}/board-snapshot.md`)).split('\n')) {
505 const row = /^\| #(\d+) \| (.*) \| ([^|]*) \|(?:[^|]*\|){5}$/.exec(line)
506 if (!row) continue
507 board.titles.set(Number(row[1]), (row[2] ?? '').replaceAll('\\|', '|').trim())
508 if (row[3]?.trim() === 'Done') board.done.add(Number(row[1]))
509 }
510 boardCache = board
511 }
512 return boardCache
513}
514
515// Tickets that are done, from local files only: a PR MERGED or CLOSED in the gh-status files, or an
516// issue whose board-snapshot row has Status Done.
517async function readDoneTickets($: $): Promise<Set<number>> {
518 const state = await resolveStateDir($)
519 const [prs, board] = await Promise.all([state ? refreshPrCache($, `${state}/gh-status`) : null, readBoard($)])
520 return new Set([...(prs?.done ?? []), ...board.done])
521}
522
523// `<state>/chains/<session-id>`: one chain a line, issue numbers in dispatch order.
524async function readChains($: $): Promise<number[][]> {
525 const [state, sid] = await Promise.all([resolveStateDir($), $.session.id()])
526 if (!state || !sid) return []
527 return (await readText($, `${state}/chains/${sid}`))
528 .split('\n')
529 .map(line => line.split(/\s+/).flatMap(token => (/^#?\d+$/.test(token) ? [Number(token.replace('#', ''))] : [])))
530 .filter(chain => chain.length > 0)
531}
532
533type Ask = { n: number; text: string }
534
535function jsonObject(text: string): Record<string, unknown> | null {
536 try {
537 const value: unknown = JSON.parse(text)
538 return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null
539 } catch {
540 return null
541 }
542}
543
544function issueNumber(text: string): string | null {
545 return /#(\d+)/.exec(text)?.[1] ?? /\/issues\/(\d+)/.exec(text)?.[1] ?? /\/pull\/(\d+)/.exec(text)?.[1] ?? null
546}
547
548function trailingLink(text: string): string | null {
549 return /https?:\/\/\S+$/.exec(text)?.[0] ?? null
550}
551
552function linkLabel(href: string): string {
553 const issue = issueNumber(href)
554 if (issue) return `#${issue}`
555 try {
556 const url = new URL(href)
557 return url.pathname.split('/').filter(Boolean).at(-1) || url.host
558 } catch {
559 return href
560 }
561}
562
563function labeledLine(line: string): { label: string; value: string } | null {
564 if (/^https?:\/\//i.test(line.trim())) return null
565 const match = /^([\p{L}][\p{L} /_-]*):\s*(.*)$/u.exec(line)
566 return match ? { label: match[1] ?? '', value: match[2] ?? '' } : null
567}
568
569function safeHref(href: string): string | null {
570 if (href.length > 2048 || /[^\x20-\x7E]/.test(href)) return null
571 if (!href.startsWith('https://') && !/^http:\/\/localhost(?::\d+)?(?:\/|$|[?#])/i.test(href)) return null
572 try {
573 const url = new URL(href)
574 return url.href === href && (url.protocol === 'https:' || (url.protocol === 'http:' && url.hostname === 'localhost')) ? href : null
575 } catch {
576 return null
577 }
578}
579
580// `owner/repo` of a GitHub remote URL (https, ssh or scp form), else null.
581function githubSlug(url: string): string | null {
582 const match = /^(?:https:\/\/|ssh:\/\/git@|git@)github\.com[:/]([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/.exec(url.trim())
583 return match?.[1] ?? null
584}
585
586// The session repo's `origin` remote, read from the git config file: null when it names no
587// GitHub repo, and ticket refs stay text.
588async function resolveRepo($: $): Promise<string | null> {
589 return perRoot($, 'repo', async () => {
590 const common = await gitCommonDir($)
591 if (!common) return null
592 let inOrigin = false
593 for (const line of (await readText($, `${common}/config`)).split('\n')) {
594 const section = /^\s*\[(.*)\]\s*$/.exec(line)
595 if (section) inOrigin = section[1] === 'remote "origin"'
596 const url = inOrigin ? /^\s*url\s*=\s*(\S+)/.exec(line)?.[1] : undefined
597 if (url) return githubSlug(url)
598 }
599 return null
600 })
601}
602
603function asNative(agent: AgentInfo): NativeRun {
604 const status = agent.status === 'completed' ? 'done' : agent.status === 'failed' ? 'failed' : agent.status === 'killed' ? 'dead' : 'running'
605 return { id: agent.id, label: agent.description || agent.type, kind: agent.type, status }
606}
607
608// The ask's sentence, minus the linked `#issue` at its very start or end (the link beside it
609// carries the number); a mid-sentence `#issue` and every other `#N` stay.
610function askBody(text: string, issue: string | null, dropUrl: boolean): string {
611 const body = dropUrl ? text.replace(/\s*https?:\/\/\S+$/, '') : text
612 return issue ? body.replace(new RegExp(`^#${issue}(?!\\d)\\s*`), '').replace(new RegExp(`\\s*#${issue}$`), '') : body
613}
614
615function askOptions(detail: string): string[] {
616 const line = detail.split('\n').find(text => /^options?:/i.test(text.trim()))
617 return line ? line.replace(/^options?:/i, '').split(/\s*[|;]\s*/).map(text => text.trim()).filter(Boolean).slice(0, 4) : []
618}
619
620// `n` is the ask's 1-based line number in the file: its detail file is `<n>.md`.
621async function readAsks($: $): Promise<{ asks: Ask[]; detailDir: string }> {
622 const [state, sid] = await Promise.all([resolveStateDir($), $.session.id()])
623 if (!state || !sid) return { asks: [], detailDir: '' }
624 const file = `${state}/asks/${sid}`
625 const all = (await readText($, file))
626 .split('\n')
627 .map((text, i) => ({ n: i + 1, text: text.trim() }))
628 .filter(ask => ask.text !== '')
629 // An ask keyed by a done ticket is hidden at once; the hook deletes it on its next write.
630 const ticketOf = (ask: Ask) => /#(\d+)/.exec(ask.text)?.[1]
631 const done = all.some(ticketOf) ? await readDoneTickets($) : new Set<number>()
632 const asks = all.filter(ask => {
633 const ticket = ticketOf(ask)
634 return ticket === undefined || !done.has(Number(ticket))
635 })
636 return { asks, detailDir: `${file}.d` }
637}
638
639async function toggleAsk($: $, ask: Ask): Promise<void> {
640 await update($, openAsk, was => (isSameAsk(was, ask) ? null : { n: ask.n, text: ask.text }))
641}
642
643// Drops the ask's line and its detail file under the asks hook's own lock (scripts/dismiss-ask.pl),
644// then redraws the band at once rather than on the next tick.
645async function dismissAsk($: $, ask: Ask): Promise<void> {
646 const [state, sid] = await Promise.all([resolveStateDir($), $.session.id()])
647 if (!state || !sid || /[/]|\.\./.test(sid)) return
648 await $.process.run(['perl', `${$.plugin.root}/scripts/dismiss-ask.pl`, `${state}/asks/${sid}`, ask.text]).catch(() => undefined)
649 if (isSameAsk(await read($, openAsk), ask)) await update($, openAsk, () => null)
650 $.ui.invalidate('ui.render')
651}
652
653async function readAskDetail($: $, detailDir: string, n: number): Promise<string> {
654 return readText($, `${detailDir}/${n}.md`)
655}
656
657const PANE = 'workers'
658const expanded = atom({ plugin: 'agent-ui', key: 'expanded' } as const, [] as string[])
659const selectedRun = atom({ plugin: 'agent-ui', key: 'selectedRun' } as const, null)
660const openAsk = atom({ plugin: 'agent-ui', key: 'openAsk' } as const, null)
661const panelsOpen = atom({ plugin: 'agent-ui', key: 'panelsOpen' } as const, [] as string[])
662const panelTabs = atom({ plugin: 'agent-ui', key: 'panelTabs' } as const, {} as Record<string, string>)
663const panelFilters = atom({ plugin: 'agent-ui', key: 'panelFilters' } as const, {} as Record<string, Record<string, string>>)
664
665const FRAME_MS = 250
666const MAX_ANIMATED = 20
667const CHILD_CAP = 8
668
669// Only running rows animate: one timer, one keyed blit per row a frame (no pane redraw).
670// A render lists the rows to animate; the timer cancels itself once the list is empty.
671let frameTimer: Timer | null = null
672let frameTick = 0
673let animating: { key: string; avatar: Avatar }[] = []
674
675function syncFrames($: $): void {
676 if (animating.length === 0) {
677 frameTimer?.cancel()
678 frameTimer = null
679 return
680 }
681 if (frameTimer) return
682 frameTimer = $.clock.every(FRAME_MS, async () => {
683 frameTick++
684 const results = await Promise.all(
685 animating.map(row =>
686 $.ui
687 .blit({ requestId: PANE, key: `avatar:${row.key}`, source: avatarPicture(row.avatar, 'running', frameTick) })
688 .catch(() => ({ deny: 'blit failed' })),
689 ),
690 )
691 // nothing of ours is mounted any more (the pane closed): wait for the next render
692 if (results.every(result => result.deny)) animating = []
693 syncFrames($)
694 })
695}
696
697// A hovered row's background.
698const COLUMN_LIT = '#3a3d50'
699
700// The card draws on its own dark background, so its text colors are fixed, not the theme's.
701const CARD_TEXT = '#e1e1e6'
702const hex = (rgb: number) => `#${rgb.toString(16).padStart(6, '0')}`
703// A hover card, a panel row's or a chain issue's: hidden until its scope is hovered, painted over
704// the pane at its place.
705const CARD = { position: 'absolute', display: 'none', flexDirection: 'column', borderStyle: 'round', backgroundColor: '#2c2e3c', paddingX: 1 } as const
706
707const MARK = { running: '◐', done: '✓', failed: '✗', dead: '†' } as const
708
709const isSameAsk = (open: OpenAsk | null, ask: Ask) => open?.n === ask.n && open.text === ask.text
710
711// boot-report writes the role marker after the session starts, so the pane waits for it a few ticks.
712const MANAGER_ROLE = /^(pm|tl-[a-z0-9-]+)$/
713const ROLE_DIR = '/tmp/cc-session-roles'
714const ROLE_WAIT_TICKS = 60
715let roleTicksLeft = 0
716
717async function openForManager($: $): Promise<void> {
718 if (roleTicksLeft <= 0) return
719 roleTicksLeft--
720 const sid = await $.session.id()
721 if (!sid || /[/]|\.\./.test(sid)) return
722 if (!MANAGER_ROLE.test(await readText($, `${ROLE_DIR}/${sid}`))) return
723 roleTicksLeft = 0
724 await $.ui.open({ id: PANE, title: 'Workers' })
725}
726
727export const register: Register = (on, options) => {
728 on('session.start', async ($, e, next) => {
729 await $.command.register({
730 name: 'workers',
731 description: "Open a pane of this session's child runs; click one for its live tail",
732 })
733 // One tick redraws the pane and the band (each re-reads its files while drawn)
734 // and drops an expanded ask whose line is gone, so a later ask at that line opens closed.
735 roleTicksLeft = e.isInteractive ? ROLE_WAIT_TICKS : 0
736 await openForManager($)
737 $.clock.every(REFRESH_MS, async () => {
738 await openForManager($)
739 $.ui.invalidate('ui.render')
740 const open = await read($, openAsk)
741 if (open === null) return
742 const { asks } = await readAsks($)
743 if (!asks.some(ask => isSameAsk(open, ask))) await update($, openAsk, () => null)
744 })
745
746 return next(e)
747 })
748
749 on('command.run', { command: 'workers' }, async $ => {
750 await $.ui.open({ id: PANE, title: 'Workers' })
751
752 return { text: 'Workers pane opened.' }
753 })
754
755 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
756 const { Box, Text, Button, Markdown, Link } = $.ui.resolve(e)
757 const Image = e.surface === 'terminal' ? $.ui.resolve(e).Image : null
758 const now = await $.clock.now()
759 const [runs, agents] = await Promise.all([scanRuns($, options, now), $.agent.list().catch(() => [])])
760 const rows = rowsFor(runs, agents, now)
761 const prs = await readReadyPrs($)
762 const [chosen, open] = await Promise.all([read($, selectedRun), read($, expanded)])
763 const visible = rows.flatMap(row => [
764 { row, isChild: false },
765 ...(open.includes(row.key) ? row.children.slice(0, CHILD_CAP).map(child => ({ row: child, isChild: true })) : []),
766 ])
767 const shown = rows.flatMap(row => [row, ...row.children]).find(row => row.key === chosen) ?? null
768 animating = Image
769 ? visible.flatMap(({ row }) => (row.status === 'running' && row.avatar ? [{ key: row.key, avatar: row.avatar }] : [])).slice(0, MAX_ANIMATED)
770 : []
771 syncFrames($)
772 const tail = shown ? (shown.diskRun ? await readTail($, shown.diskRun) : await readNativeTail($, shown.agentId ?? '')) : null
773 const repo = await resolveRepo($)
774 const chainFile = await readChains($)
775 const board = chainFile.length > 0 ? await readBoard($) : NO_BOARD
776 // an issue is in progress while a running row's label names its #N
777 const active = new Set(rows.flatMap(row => [row, ...row.children]).flatMap(row => {
778 const n = row.status === 'running' ? issueNumber(row.label) : null
779 return n ? [Number(n)] : []
780 }))
781 const chains = chainFile.map(chain => chainLinks(chain, board.done, active))
782 const root = await repoRoot($)
783 const specs = root ? await readPanelSpecs($, root) : []
784 const [openPanels, tabPicks, filterPicks] = await Promise.all([read($, panelsOpen), read($, panelTabs), read($, panelFilters)])
785 if (root && specs.length > 0) schedulePanels($, root, specs, now)
786 // a card's top counts pane rows: the panels are the first rows of the pane
787 const panels = root ? panelViews(root, specs, openPanels, tabPicks, filterPicks, 0, e.props.bodyColumns, e.props.scroll.offset + e.props.scroll.bodyRows) : []
788 // chain row i sits below the panels (one line each: head, error, chips, columns, rows, no
789 // data, note) and the Needs you list (title, one line per PR, a blank line)
790 const panelLines = panels.reduce(
791 (sum, view) => sum + 1 + (view.error ? 1 : 0) + view.chipRows.length + (view.header.length > 0 ? 1 : 0) + view.rows.length + (view.noData ? 1 : 0) + (view.tab?.note ? 1 : 0),
792 0,
793 )
794 const chainTop = panelLines + (prs.length > 0 ? prs.length + 2 : 0)
795 const paneRows = e.props.scroll.offset + e.props.scroll.bodyRows
796 const segmentTexts = (segments: Segment[], dim: boolean, prefix: string) =>
797 segments.map((segment, k) => (
798 <Text
799 key={`${prefix}-${k}`}
800 color={segment.color === undefined ? undefined : hex(segment.color)}
801 backgroundColor={segment.background === undefined ? undefined : hex(segment.background)}
802 dimColor={dim && segment.background === undefined}
803 >
804 {segment.text}
805 </Text>
806 ))
807
808 return (
809 <Box flexDirection="column">
810 {panels.map(({ spec, isOpen, summary, error, data, tab, chipRows, header, noData, rows: panelRows }) => (
811 <Box key={`panel:${spec.id}`} flexDirection="column">
812 <Box key="panel-head" flexDirection="row">
813 <Button
814 key={`panel-toggle:${spec.id}`}
815 plain
816 label={`${isOpen ? '▾' : '▸'} ${spec.title}`}
817 onPress={() => update($, panelsOpen, ids => (ids.includes(spec.id) ? ids.filter(id => id !== spec.id) : [...ids, spec.id]))}
818 />
819 {summary && <Text dimColor>{summary}</Text>}
820 </Box>
821 {error && (
822 <Box key="panel-error" marginLeft={PANEL_INDENT}>
823 <Text dimColor>{error}</Text>
824 </Box>
825 )}
826 {data && (
827 <Box key="panel-body" flexDirection="column" marginLeft={PANEL_INDENT}>
828 {chipRows.map(({ filter, chips }) => (
829 <Box key={filter === null ? 'panel-tabs' : `panel-filter:${filter}`} flexDirection="row">
830 {chips.map((chip, k) => (
831 <Box key={`panel-chip-box:${chip.id}`} flexDirection="row">
832 {k > 0 && <Text>{' '}</Text>}
833 <Button
834 key={filter === null ? `panel-tab:${spec.id}:${chip.id}` : `panel-filter:${spec.id}:${filter}:${chip.id}`}
835 plain
836 dimColor={!chip.selected}
837 label={chip.label}
838 onPress={() =>
839 filter === null
840 ? update($, panelTabs, picks => ({ ...picks, [spec.id]: chip.id }))
841 : update($, panelFilters, picks => ({ ...picks, [spec.id]: { ...picks[spec.id], [filter]: chip.id } }))
842 }
843 />
844 </Box>
845 ))}
846 </Box>
847 ))}
848 {header.length > 0 && (
849 <Box key="panel-columns" flexDirection="row">
850 {segmentTexts(header, true, 'panel-col')}
851 </Box>
852 )}
853 {noData && (
854 <Box key="panel-no-data">
855 <Text dimColor>no data</Text>
856 </Box>
857 )}
858 {panelRows.map(({ row, key, scope, segments }) => (
859 <Box key={`panel-row:${spec.id}:${key}`} flexDirection="row" hover={{ scope, backgroundColor: COLUMN_LIT }}>
860 {segmentTexts(segments, row.dim, 'panel-cell')}
861 </Box>
862 ))}
863 {tab?.note && <Text dimColor>{clip([{ text: tab.note }], e.props.bodyColumns - PANEL_INDENT)[0]?.text ?? ''}</Text>}
864 </Box>
865 )}
866 </Box>
867 ))}
868 {prs.length > 0 && (
869 <Box key="needs-you" flexDirection="column" marginBottom={1}>
870 <Text bold>Needs you</Text>
871 {prs.map(pr => {
872 const href = repo ? safeHref(`https://github.com/${repo}/pull/${pr.number}`) : null
873 return (
874 <Box key={`pr:${pr.number}`}>
875 <Box key={`pr-mark-${pr.number}`} width={3} flexShrink={0}>
876 <Text color={hex(MARK_TONES[pr.mark])}>{pr.mark}</Text>
877 </Box>
878 <Box key={`pr-num-${pr.number}`} flexShrink={0}>
879 {href ? <Text color={ASK_ACCENT}><Link key={`pr-link-${pr.number}`} href={href} label={`#${pr.number}`} /></Text> : <Text color={ASK_ACCENT}>{`#${pr.number}`}</Text>}
880 </Box>
881 <Text wrap="truncate-end">{` ${pr.title}`}</Text>
882 </Box>
883 )
884 })}
885 </Box>
886 )}
887 {chains.length > 0 && (
888 <Box key="chains" flexDirection="column" marginBottom={1}>
889 {chains.map((chain, i) => (
890 <Box key={`chain:${i}`} flexDirection="row">
891 {chain.map(({ n, mark }, k) => {
892 const href = repo ? safeHref(`https://github.com/${repo}/issues/${n}`) : null
893 return (
894 <Box key={`chain-issue:${i}:${k}`} flexDirection="row" flexShrink={0} hover={{ scope: `chain:${i}:${n}`, backgroundColor: COLUMN_LIT }}>
895 {k > 0 && <Text dimColor>{' → '}</Text>}
896 <Text color={mark === 'merged' ? 'green' : mark === 'active' ? ASK_ACCENT : undefined} dimColor={mark === 'merged'}>
897 {href ? <Link href={href} label={`#${n}`} /> : `#${n}`}
898 {mark === 'merged' ? ' ✓' : ''}
899 </Text>
900 </Box>
901 )
902 })}
903 </Box>
904 ))}
905 </Box>
906 )}
907 <Text bold>Workers</Text>
908 {!childrenDirOf(options) ? (
909 <Box key="no-children-dir">
910 <Text dimColor>set childrenDir in /config</Text>
911 </Box>
912 ) : (
913 rows.length === 0 && <Text dimColor>No child runs for this session.</Text>
914 )}
915 {visible.map(({ row, isChild }) => (
916 <Box key={`row:${row.key}`} flexDirection="row">
917 {isChild && <Text dimColor>{' └ '}</Text>}
918 {Image && row.avatar ? (
919 <Image key={`avatar:${row.key}`} columns={SPRITE_COLS} rows={1} source={avatarPicture(row.avatar, row.status, frameTick)} alt={MARK[row.status]} />
920 ) : (
921 <Box key={`mark:${row.key}`}>
922 <Text dimColor={row.status !== 'running'}>{`${MARK[row.status]} `}</Text>
923 </Box>
924 )}
925 <Text>{' '}</Text>
926 <Button
927 key={row.key}
928 plain
929 dimColor={row.status !== 'running'}
930 label={`${row.kind ? `${row.kind} ` : ''}${row.label}${row.model ? ` ${row.model}` : ''}${row.duration ? ` ${row.duration}` : ''} ${row.status}${row.children.length > 0 ? ` ${open.includes(row.key) ? '▾' : '▸'}${row.children.length}` : ''}`}
931 onPress={async () => {
932 const wasShown = (await read($, selectedRun)) === row.key
933 await update($, selectedRun, () => (wasShown ? null : row.key))
934 if (row.children.length > 0) await update($, expanded, keys => (wasShown ? keys.filter(key => key !== row.key) : [...keys, row.key]))
935 }}
936 />
937 </Box>
938 ))}
939 {shown && tail && (
940 <Box key="tail" flexDirection="column" marginTop={1}>
941 <Text bold>{`${shown.label} (${shown.status})`}</Text>
942 {tail.lines.length === 0 && <Text dimColor>No output yet.</Text>}
943 {tail.lines.map(line => (
944 <Text wrap="truncate-end">{line}</Text>
945 ))}
946 {tail.lastMessage !== '' && (
947 <Box key="last" flexDirection="column" marginTop={1}>
948 <Text bold>last message</Text>
949 <Markdown key="last-message" text={tail.lastMessage} />
950 </Box>
951 )}
952 </Box>
953 )}
954 {panels.flatMap(({ spec, rows: panelRows }) =>
955 panelRows.flatMap(({ key, scope, card }) =>
956 card
957 ? [
958 <Box key={`panel-card:${spec.id}:${key}`} {...CARD} top={card.top} left={card.left} width={card.width} hover={{ display: 'flex', scope }}>
959 {card.lines.map((line, k) => (
960 <Text key={`panel-line-${k}`} color={CARD_TEXT}>{line}</Text>
961 ))}
962 </Box>,
963 ]
964 : [],
965 ),
966 )}
967 {/* a hovered #N reveals a card of its board title, below its chain row or else above it */}
968 {chains.flatMap((chain, i) =>
969 chain.flatMap(({ n, mark }, k) => {
970 const title = board.titles.get(n)
971 if (title === undefined) return []
972 const head = `#${n}${mark === 'merged' ? ' ✓' : ''} · `
973 const width = Math.min(e.props.bodyColumns, head.length + title.length + 4)
974 return [
975 <Box key={`chain-card:${i}:${k}`} {...CARD} top={placeBeside(chainTop + i, 1, 3, paneRows).x} left={0} width={width} hover={{ display: 'flex', scope: `chain:${i}:${n}` }}>
976 <Box key="chain-card-line" flexDirection="row" flexWrap="nowrap">
977 <Text color={mark === 'merged' ? 'green' : mark === 'active' ? ASK_ACCENT : CARD_TEXT}>{head}</Text>
978 <Text color={CARD_TEXT} wrap="truncate-end">{title}</Text>
979 </Box>
980 </Box>,
981 ]
982 }),
983 )}
984 </Box>
985 )
986 })
987
988 // An ask line's Client posts each button press with the ask's text: left toggles its context,
989 // right dismisses it.
990 on('ui.message', async ($, e, next) => {
991 if (e.module !== 'hooks/ask-line.tsx') return next(e)
992 const data = e.data as { button?: unknown; text?: unknown } | null
993 const ask = (await readAsks($)).asks.find(one => one.text === data?.text)
994 if (!ask) return {}
995 if (data?.button === 'left') await toggleAsk($, ask)
996 if (data?.button === 'right') await dismissAsk($, ask)
997 return {}
998 })
999
1000 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1001 if (e.props.hasSurvey) return next(e)
1002 const { asks, detailDir } = await readAsks($)
1003 if (asks.length === 0) return next(e)
1004 const elements = $.ui.resolve(e)
1005 const { Box, Text, Button, Markdown, Link } = elements
1006 // A right-click reaches a plugin only through a Client's pointer listener, where one is drawn.
1007 const Client = 'Client' in elements ? elements.Client : null
1008 const repo = await resolveRepo($)
1009 const open = await read($, openAsk)
1010 const shown = asks.find(ask => isSameAsk(open, ask))
1011 const lineLabel = (ask: Ask, issue: string | null, dropUrl: boolean) => `${ask === shown ? '▾' : '▸'} ${askBody(ask.text, issue, dropUrl)}`
1012 const detail = shown ? await readAskDetail($, detailDir, shown.n) : ''
1013 // Three text lines (options: among them) plus one link: line, whatever the file holds.
1014 const rows = detail.split('\n').map(line => line.trim()).filter(Boolean)
1015 const isLink = (line: string) => /^link:/i.test(line)
1016 const textLines = rows.filter(line => !isLink(line)).slice(0, 3)
1017 const detailLines = [...textLines.filter(line => !/^options?:/i.test(line)), ...rows.filter(isLink).slice(0, 1)]
1018 const askViews = asks.map(ask => {
1019 const issue = issueNumber(ask.text)
1020 const trailing = trailingLink(ask.text)
1021 return {
1022 ask,
1023 issue,
1024 issueHref: issue && repo ? safeHref(`https://github.com/${repo}/issues/${issue}`) : null,
1025 trailing,
1026 trailingHref: trailing ? safeHref(trailing) : null,
1027 askOpts: askOptions(ask === shown ? textLines.join('\n') : ''),
1028 }
1029 })
1030
1031 return (
1032 <Box flexDirection="column">
1033 {askViews.map(({ ask, issue, issueHref, trailing, trailingHref, askOpts }) => {
1034 // The toggle leads every row, ticket or not, so no ask reads as part of the row above.
1035 const urlLink = !issue && trailingHref
1036 return (
1037 <Box key={`ask-row-${ask.n}`} flexDirection="column">
1038 <Box key={`ask-line-${ask.n}`} flexDirection="row">
1039 {Client ? (
1040 <Client key={`ask-client-${ask.n}`} module="./ask-line.tsx" props={{ key: `ask-${ask.n}`, label: lineLabel(ask, issue, !!urlLink), text: ask.text }} />
1041 ) : (
1042 <Button key={`ask-${ask.n}`} plain label={lineLabel(ask, issue, !!urlLink)} onPress={() => toggleAsk($, ask)} />
1043 )}
1044 {issue || urlLink ? <Text>{' '}</Text> : null}
1045 {issue ? issueHref ? <Text color={ASK_ACCENT}><Link href={issueHref} label={`#${issue}`} /></Text> : <Text color={ASK_ACCENT}>{`#${issue}`}</Text> : null}
1046 {urlLink ? <Text color={ASK_ACCENT} underline><Link href={trailingHref} label={linkLabel(trailingHref)} /></Text> : null}
1047 </Box>
1048 {ask === shown &&
1049 (detail ? (
1050 <Box key={`ask-detail-${ask.n}`} flexDirection="column" marginLeft={2}>
1051 <Box key="ask-detail-border" flexDirection="row">
1052 <Text color={ASK_ACCENT}>│</Text>
1053 <Box flexDirection="column" marginLeft={1}>
1054 {detailLines.map((line, i) => {
1055 const labeled = labeledLine(line)
1056 const link = /^link:\s*(?:<([^>]+)>|(\S+))/i.exec(line.trim())
1057 if (link) {
1058 const href = link[1] ?? link[2] ?? ''
1059 const safe = safeHref(href)
1060 if (!safe) return <Text key={`ask-context-${i}`}>{line}</Text>
1061 return (
1062 <Text key={`ask-context-${i}`} color={ASK_ACCENT} underline>
1063 <Link href={safe} label={linkLabel(safe)} />
1064 </Text>
1065 )
1066 }
1067 if (labeled) {
1068 return (
1069 <Box key={`ask-context-${i}`} flexDirection="row">
1070 <Text dimColor bold>{`${labeled.label}: `}</Text>
1071 <Text>{labeled.value}</Text>
1072 </Box>
1073 )
1074 }
1075 return <Text key={`ask-context-${i}`}>{line}</Text>
1076 })}
1077 </Box>
1078 </Box>
1079 {askOpts.length > 0 && (
1080 <Box key="ask-options" flexDirection="row" marginTop={1}>
1081 {askOpts.map((option, i) => (
1082 <Button
1083 key={`ask-option-${ask.n}-${i}`}
1084 plain
1085 label={option}
1086 onPress={() => {
1087 const prefix = issue ? `#${issue}` : trailing ?? ''
1088 return $.prompt.fill({ text: `${prefix} ${option}`.trim(), mode: 'insert' })
1089 }}
1090 />
1091 ))}
1092 </Box>
1093 )}
1094 </Box>
1095 ) : (
1096 <Text dimColor>no context recorded</Text>
1097 ))}
1098 </Box>
1099 )
1100 })}
1101 </Box>
1102 )
1103 })
1104}
1105hooks/sprites.ts 221 lines1import { toBase64 } from './lib'
2
3// Provider avatars: 2 terminal cells wide, one row tall (a square on screen), a square RGBA
4// sprite (its frame's size, 16 or 32 pixels) filling the box. Every frame is encoded once, here.
5export type Avatar = 'claude' | 'gpt'
6export type Status = 'running' | 'done' | 'failed' | 'dead'
7export type Picture = { rgba: string; width: number; height: number }
8type Look = { run: Picture[]; done: Picture; failed: Picture }
9
10export const SPRITE_COLS = 2
11const FAILED = 0xe06c75
12const EYE = 0x1a1a1a
13const COLORS: Record<Avatar, number> = { claude: 0xd97757, gpt: 0xf2f2f2 }
14
15// Sprite frames, square, N rows of N pixels: 'X' the color, 'E' eye, '.' transparent.
16// CADENCE plays them in order.
17const SPRITES: Record<Avatar, string[][]> = {
18 // body, two eyes, arms out; the legs walk
19 claude: [
20 [
21 '................', '................', '...XXXXXXXXXX...', '...XXXXXXXXXX...',
22 '...XXEXXXXEXX...', '...XXEXXXXEXX...', '.XXXXXXXXXXXXXX.', '.XXXXXXXXXXXXXX.',
23 '...XXXXXXXXXX...', '...XXXXXXXXXX...', '...XXXXXXXXXX...', '...XXXXXXXXXX...',
24 '....XX....XX....', '....XX....XX....', '....XX..........', '................',
25 ],
26 [
27 '................', '................', '...XXXXXXXXXX...', '...XXXXXXXXXX...',
28 '...XXEXXXXEXX...', '...XXEXXXXEXX...', '.XXXXXXXXXXXXXX.', '.XXXXXXXXXXXXXX.',
29 '...XXXXXXXXXX...', '...XXXXXXXXXX...', '...XXXXXXXXXX...', '...XXXXXXXXXX...',
30 '....XX....XX....', '....XX....XX....', '..........XX....', '................',
31 ],
32 ],
33 // the six-link knot, spun 15° a frame (it repeats every 60°); generated by
34 // scripts/gpt-knot.ts, rerun it to change the shape
35 gpt: [
36 [
37 '................................',
38 '............XXX.................',
39 '..........XXXXXXX...............',
40 '.........XXXXXXXX...............',
41 '.........XXX...XXX..XXXXXX......',
42 '........XXX....XXX.XXXXXXXX.....',
43 '........XXX....XXX.XXXXXXXXX....',
44 '........XXX....XXX.XX....XXX....',
45 '.....XX..XX..X.XXX.......XXX....',
46 '...XXXXXX...XXXXXX.X.....XXX....',
47 '..XXXXXXXXX.XXXXXXXXXX..XXXX....',
48 '..XXX..XXXXXXX.XXXXXX..XXXX.....',
49 '.XXX.....XXXXXX.XX...XXXXX......',
50 '.XXX......XXXXX.XXXXXXXXX.......',
51 '.XXX....XX..X.X....XXXX..XXXX...',
52 '..XXX...XXX.X.....XXXXX..XXXXX..',
53 '..XXXXX..XXXXX.....X.XXX...XXX..',
54 '...XXXX..XXXX....X.X..XX....XXX.',
55 '.......XXXXXXXXX.XXXXX......XXX.',
56 '......XXXXX...XX.XXXXXX.....XXX.',
57 '.....XXXX..XXXXXX.XXXXXXX..XXX..',
58 '....XXXX..XXXXXXXXXX.XXXXXXXXX..',
59 '....XXX.....X.XXXXXX...XXXXXX...',
60 '....XXX.......XXX.X..XX..XX.....',
61 '....XXX....XX.XXX....XXX........',
62 '....XXXXXXXXX.XXX....XXX........',
63 '.....XXXXXXXX.XXX....XXX........',
64 '......XXXXXX..XXX...XXX.........',
65 '...............XXXXXXXX.........',
66 '...............XXXXXXX..........',
67 '.................XXX............',
68 '................................',
69 ],
70 [
71 '................................',
72 '.............XXXXX..............',
73 '............XXXXXXXX............',
74 '...........XXXXXXXXX............',
75 '...........XXX....XXX...........',
76 '...........XXX....XXX...........',
77 '.....XXXX..XX.....XXX.XXXXX.....',
78 '....XXXXXXX.X.....XXX.XXXXXX....',
79 '...XXXXXXXXX..XX.XXX.XXXXXXXX...',
80 '..XXXX...XXXX.XX.XXX......XXXX..',
81 '..XXX.....XXXXXX.XXX.......XXX..',
82 '..XXX......XXXX..XXXXX.....XXX..',
83 '..XXXX...X..XXXX.XXXXXX...XXX...',
84 '...XXX...XX.X.XX.XX....XXXXXX...',
85 '....XXX..XX.X....X.XXXXXXXXX....',
86 '.........XXXXX....XXXXXXXX......',
87 '......XXXXXXXX....XXXXX.........',
88 '....XXXXXXXXX.X....X.XX..XXX....',
89 '...XXXXXX....XX.XX.X.XX...XXX...',
90 '...XXX...XXXXXX.XXXX..X...XXXX..',
91 '..XXX.....XXXXX..XXXX......XXX..',
92 '..XXX.......XXX.XXXXXX.....XXX..',
93 '..XXXX......XXX.XX.XXXX...XXXX..',
94 '...XXXXXXXX.XXX.XX..XXXXXXXXX...',
95 '....XXXXXX.XXX.....X.XXXXXXX....',
96 '.....XXXXX.XXX.....XX..XXXX.....',
97 '...........XXX....XXX...........',
98 '...........XXX....XXX...........',
99 '............XXXXXXXXX...........',
100 '............XXXXXXXX............',
101 '..............XXXXX.............',
102 '................................',
103 ],
104 [
105 '................................',
106 '.................XXX............',
107 '...............XXXXXXX..........',
108 '..............XXXXXXXXX.........',
109 '......XXXXX...XXX...XXX.........',
110 '.....XXXXXXX..XX.....XXX........',
111 '....XXXXXXXXX.XX.....XXX........',
112 '....XXX...XXXX......XXX.........',
113 '....XXX....XXX..XX..XXX.XXX.....',
114 '....XXX.....XXXXXX.XXX.XXXXXX...',
115 '....XXX...X.XXXXX.XXXX.XXXXXXX..',
116 '....XXXX..XX.XXX..XXX......XXX..',
117 '.....XXX.XXX.XXXXXXXXXX.....XXX.',
118 '..........XX.X.X..XXXXXX....XXX.',
119 '....XXXXXXXXXX...XXX.XX.....XXX.',
120 '..XXXXXXXXXXXX......XXXXXXXXXX..',
121 '..XXXXXXXXXX......XXXXXXXXXXXX..',
122 '.XXX.....XX.XXX...XXXXXXXXXX....',
123 '.XXX....XXXXXX..X.X.XX..........',
124 '.XXX.....XXXXXXXXXX.XXX.XXX.....',
125 '..XXX......XXX..XXX.XX..XXXX....',
126 '..XXXXXXX.XXXX.XXXXX.X...XXX....',
127 '...XXXXXX.XXX.XXXXXX.....XXX....',
128 '.....XXX.XXX..XX..XXX....XXX....',
129 '.........XXX......XXXX...XXX....',
130 '........XXX.....XX.XXXXXXXXX....',
131 '........XXX.....XX..XXXXXXX.....',
132 '.........XXX...XXX...XXXXX......',
133 '.........XXXXXXXXX..............',
134 '..........XXXXXXX...............',
135 '............XXX.................',
136 '................................',
137 ],
138 [
139 '................................',
140 '................................',
141 '.........XXX.......XXXX.........',
142 '........XXXXXX....XXXXXX........',
143 '.......XXXXXXXX..XXXXXXXX.......',
144 '......XXXX..XXX..XXX..XXXX......',
145 '......XXX....XXX.X.....XXX......',
146 '......XXX....XXX.......XXX......',
147 '......XXX....XXX.......XXX......',
148 '......XXX...X.XXXXXX..XXX.......',
149 '........X..XX.XXXXX..XXXX.......',
150 '....XXXX...XX.XXX...XXXX.XXXX...',
151 '..XXXXXXXXXXX.XXXXXXXXX.XXXXXX..',
152 '..XXXXXXXXXXXX.XX..XXX....XXXXX.',
153 '.XXX....XXXXXXX...XXXXXX....XXX.',
154 '.XXX..............XX.XXX....XXX.',
155 '.XXX....XXX.XX..............XXX.',
156 '.XXX....XXXXXX...XXXXXXX....XXX.',
157 '.XXXXX....XXX..XX.XXXXXXXXXXXX..',
158 '..XXXXXX.XXXXXXXXX.XXXXXXXXXXX..',
159 '...XXXX.XXXX...XXX.XX...XXXX....',
160 '.......XXXX..XXXXX.XX..X........',
161 '.......XXX..XXXXXX.X...XXX......',
162 '......XXX.......XXX....XXX......',
163 '......XXX.......XXX....XXX......',
164 '......XXX.....X.XXX....XXX......',
165 '......XXXX..XXX..XXX..XXXX......',
166 '.......XXXXXXXX..XXXXXXXX.......',
167 '........XXXXXX....XXXXXX........',
168 '.........XXXX.......XXX.........',
169 '................................',
170 '................................',
171 ],
172 ],
173}
174const CADENCE: Record<Avatar, number[]> = { claude: [0, 1], gpt: [0, 1, 2, 3] }
175
176function encodeSprite(sprite: string[], color: number): Picture {
177 const size = sprite.length
178 if (size === 0 || sprite.some(row => !new RegExp(`^[XE.]{${size}}$`).test(row))) {
179 throw new Error('agent-ui: a sprite frame must be N rows of N of X, E or .')
180 }
181 const bytes = new Uint8Array(size * size * 4)
182 for (let y = 0; y < size; y++) {
183 for (let x = 0; x < size; x++) {
184 const pixel = sprite[y]?.[x]
185 const rgb = pixel === 'X' ? color : pixel === 'E' ? EYE : null
186 if (rgb !== null) bytes.set([(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255, 255], (y * size + x) * 4)
187 }
188 }
189 return { rgba: toBase64(bytes), width: size, height: size }
190}
191
192function encodePicture(avatar: Avatar, step: number, color: number): Picture {
193 const sprite = SPRITES[avatar][CADENCE[avatar][step] ?? -1]
194 if (!sprite) throw new Error(`agent-ui: ${avatar} has no sprite frame at step ${step}`)
195 return encodeSprite(sprite, color)
196}
197
198export const dim = (rgb: number) => ((((rgb >> 16) & 255) * 0.4) << 16) | ((((rgb >> 8) & 255) * 0.4) << 8) | ((rgb & 255) * 0.4)
199
200// Done and failed show step 0.
201const PICTURES = Object.fromEntries(
202 (Object.keys(SPRITES) as Avatar[]).map(avatar => {
203 const color = COLORS[avatar]
204 return [avatar, {
205 run: CADENCE[avatar].map((_, step) => encodePicture(avatar, step, color)),
206 done: encodePicture(avatar, 0, dim(color)),
207 failed: encodePicture(avatar, 0, FAILED),
208 }]
209 }),
210) as Record<Avatar, Look>
211
212export function avatarPicture(avatar: Avatar, status: Status, tick: number): Picture {
213 const look = PICTURES[avatar]
214 if (status === 'running') return look.run[tick % look.run.length] as Picture
215 return status === 'done' ? look.done : look.failed
216}
217
218export function avatarOf(kind: string): Avatar | null {
219 return kind === 'gpt' ? kind : kind === 'claude' || kind === 'claude-panel' ? 'claude' : null
220}
221hooks/lib.ts 127 lines1import type { RunStatus } from '../types'
2
3export const TAIL_LINES = 40
4
5// Base64 in 8 KiB slices: one spread of a large array overflows the argument limit.
6export function toBase64(bytes: Uint8Array): string {
7 let text = ''
8 for (let i = 0; i < bytes.length; i += 8192) text += String.fromCharCode(...bytes.subarray(i, i + 8192))
9 return btoa(text)
10}
11
12export function baseName(path: string): string {
13 return path.replace(/\/+$/, '').split('/').pop() ?? path
14}
15
16export function parentDir(path: string): string {
17 const trimmed = path.replace(/\/+$/, '')
18 const cut = trimmed.lastIndexOf('/')
19 return cut <= 0 ? '/' : trimmed.slice(0, cut)
20}
21
22// The run's `provider` file: openai and codex are gpt, claude is claude; any other value as written.
23export function kindOf(provider: string, isPanel: boolean): string {
24 if (provider === 'openai' || provider === 'codex') return 'gpt'
25 if (provider === 'claude') return isPanel ? 'claude-panel' : 'claude'
26 return provider
27}
28
29export function labelOf(dir: string, isPanel: boolean): string {
30 if (isPanel) return `rev ${baseName(parentDir(dir)).slice(0, 8)}/${baseName(dir)}`
31 return baseName(dir)
32}
33
34export function statusOf(hasDone: boolean, exitCode: string, isAlive: boolean): RunStatus {
35 if (hasDone) return exitCode === '' || exitCode === '0' ? 'done' : 'failed'
36 return isAlive ? 'running' : 'dead'
37}
38
39export function epochMs(text: string): number | null {
40 const seconds = Number.parseInt(text, 10)
41 return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : null
42}
43
44export function elapsed(ms: number): string {
45 const minutes = Math.max(0, Math.floor(ms / 60_000))
46 if (minutes < 60) return `${minutes}m`
47 const hours = Math.floor(minutes / 60)
48 if (hours < 24) return `${hours}h${String(minutes % 60).padStart(2, '0')}m`
49 return `${Math.floor(hours / 24)}d${String(hours % 24).padStart(2, '0')}h`
50}
51
52export function lines(text: string): string[] {
53 return text.split('\n').filter(line => line.trim() !== '')
54}
55
56function oneLine(text: string, width = 160): string {
57 const flat = text.replace(/\s+/g, ' ').trim()
58 return flat.length > width ? `${flat.slice(0, width - 1)}…` : flat
59}
60
61function parseJson(line: string): Record<string, unknown> | null {
62 try {
63 const value: unknown = JSON.parse(line)
64 return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null
65 } catch {
66 return null
67 }
68}
69
70// codex exec --json events: agent messages, finished commands, errors.
71export function codexTail(jsonl: string): string[] {
72 const out: string[] = []
73 for (const line of jsonl.split('\n')) {
74 const event = parseJson(line)
75 const item = event?.item as Record<string, unknown> | undefined
76 if (event?.type === 'item.completed' && item?.type === 'agent_message') {
77 out.push(...lines(String(item.text ?? '')))
78 } else if (event?.type === 'item.completed' && item?.type === 'command_execution') {
79 const command = String(item.command ?? '').replace(/^\S*bash -lc ['"]?/, '')
80 out.push(`$ ${oneLine(command, 120)} (exit ${String(item.exit_code ?? '?')})`)
81 } else if (event?.type === 'error' || event?.type === 'turn.failed') {
82 out.push(`error: ${oneLine(JSON.stringify(event.error ?? event.message ?? ''))}`)
83 }
84 }
85 return out.slice(-TAIL_LINES)
86}
87
88// claude -p --output-format json writes one object; its `result` is the final message.
89export function resultJsonMessage(text: string): string {
90 const result = parseJson(text)?.result
91 return typeof result === 'string' ? result : ''
92}
93
94// One key of `.agent/local.env`: `key=value` lines (a `#` line never starts with a key), the
95// value everything after the first `=`, a leading `~/` read as $HOME; null when absent or empty.
96export function localEnvValue(text: string, key: string, home: string): string | null {
97 const line = text.split('\n').find(one => one.startsWith(`${key}=`))
98 const value = line?.slice(key.length + 1).trim().replace(/^~(?=\/)/, home).replace(/(.)\/+$/, '$1')
99 return value || null
100}
101
102// A chain from its newest merged issue on: the last merged one before the first open one stays,
103// the merged ones before it go.
104export type ChainLink = { n: number; mark: 'merged' | 'active' | 'next' }
105
106export function chainLinks(chain: number[], merged: Set<number>, active: Set<number>): ChainLink[] {
107 const open = chain.findIndex(n => !merged.has(n))
108 const from = open < 0 ? chain.length - 1 : Math.max(0, open - 1)
109 return chain.slice(from).map(n => ({ n, mark: merged.has(n) ? 'merged' : active.has(n) ? 'active' : 'next' }))
110}
111
112// A PR's mark from its gh-status file: a conflict wins, then red, green, and running for the rest.
113export type PrMark = '⚡' | '✗' | '✓' | '⋯'
114
115export function prMark(mergeable: unknown, checks: unknown): PrMark {
116 if (mergeable === 'CONFLICTING') return '⚡'
117 if (checks === 'FAILURE' || checks === 'ERROR') return '✗'
118 return checks === 'SUCCESS' ? '✓' : '⋯'
119}
120
121const MARK_ORDER: Record<PrMark, number> = { '✓': 0, '⋯': 1, '✗': 2, '⚡': 3 }
122
123// Green first, then running, red, conflict; by PR number within each group.
124export function sortPrs<T extends { number: number; mark: PrMark }>(prs: T[]): T[] {
125 return [...prs].sort((a, b) => MARK_ORDER[a.mark] - MARK_ORDER[b.mark] || a.number - b.number)
126}
127hooks/panels.ts 223 lines1// Repo panels: `.agent/pane-panels.json` lists commands, each prints one JSON object of tabs of
2// rows (README, "Repo panels"). This file parses both and lays a row out as colored segments.
3export type PanelSpec = { id: string; title: string; cmd: string[]; refreshMs: number }
4export type Bar = { frac: number; text: string; tone: string }
5// v1.2: `width` is the minimum; spare pane cells widen a column up to `maxWidth`. `keepRight`
6// cuts an over-long value from the left.
7export type Column = { key: string; label: string; width: number; maxWidth: number; align: 'left' | 'right'; isBar: boolean; keepRight: boolean }
8export type PanelRow = { id: string; dim: boolean; cells: Record<string, string | Bar>; hover: string[] }
9export type PanelTab = { id: string; label: string; columns: Column[]; rows: PanelRow[]; note: string }
10export type FilterOption = { id: string; label: string }
11export type Filter = { id: string; options: FilterOption[]; default: string }
12export type PanelData = { summary: string; tab: string; tabs: PanelTab[]; filters: Filter[] }
13export type Segment = { text: string; color?: number; background?: number }
14
15export const PANEL_TIMEOUT_MS = 10_000
16const REFRESH_DEFAULT_S = 60
17// above the pane's 3 s tick, so a panel never runs on every tick
18const REFRESH_MIN_S = 5
19// what one panel may draw, whatever its command prints
20const HOVER_LINES = 6
21const MAX_WIDTH = 200
22const MAX_COLUMNS = 12
23const MAX_TABS = 12
24// with filters, one tab per option combination
25const MAX_FILTERS = 3
26const MAX_OPTIONS = 12
27const MAX_FILTER_TABS = 48
28const MAX_ROWS = 100
29// one space between columns
30const GAP = 1
31// a bar's unfilled cells, and its text's ink over the fill and over the track
32export const BAR_TRACK = 0x3a3c4e
33export const INK_ON_FILL = 0x1e1f28
34export const INK_ON_TRACK = 0xe1e1e6
35// A bar's fill per tone.
36export const TONES: Record<string, number> = { good: 0x8caa5a, mid: 0xc4c45a, bad: 0xe65a50, dim: 0x787a87 }
37
38// A stable hash of a row's id, for its hover scope.
39export function fnv1a(text: string): number {
40 let hash = 0x811c9dc5
41 for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193)
42 return hash >>> 0
43}
44
45// Where a card goes along one axis of `span` cells, beside the `size` cells it describes at `at`:
46// after them, else before them, never over them; when it fits on neither side whole, on the
47// roomier side, cut to fit.
48export function placeBeside(at: number, size: number, card: number, span: number): { x: number; width: number } {
49 const after = span - (at + size)
50 if (card <= after) return { x: at + size, width: card }
51 if (card <= at) return { x: at - card, width: card }
52 return after >= at ? { x: at + size, width: after } : { x: 0, width: at }
53}
54
55const isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
56// A control character (a newline, an escape sequence's ESC) would break the row or restyle the
57// terminal: each becomes a space.
58export const clean = (text: string): string => text.replace(/[\u0000-\u001f\u007f]/g, ' ')
59const str = (value: unknown, fallback = ''): string => clean(typeof value === 'string' ? value : typeof value === 'number' ? String(value) : fallback)
60
61function parseJson(text: string): unknown {
62 try {
63 return JSON.parse(text)
64 } catch {
65 return undefined
66 }
67}
68
69// Entries without an id or an argv are skipped; a file that is no list lists nothing.
70export function parseSpecs(text: string): PanelSpec[] {
71 const list = parseJson(text)
72 if (!Array.isArray(list)) return []
73 const seen = new Set<string>()
74 return list.flatMap(entry => {
75 if (!isObject(entry) || typeof entry.id !== 'string' || entry.id === '' || seen.has(entry.id)) return []
76 const cmd = entry.cmd
77 if (!Array.isArray(cmd) || cmd.length === 0 || !cmd.every(arg => typeof arg === 'string') || cmd[0] === '') return []
78 seen.add(entry.id)
79 const refresh = typeof entry.refresh_s === 'number' && Number.isFinite(entry.refresh_s) ? entry.refresh_s : REFRESH_DEFAULT_S
80 return [{ id: entry.id, title: str(entry.title, entry.id), cmd: cmd as string[], refreshMs: Math.max(REFRESH_MIN_S, refresh) * 1000 }]
81 })
82}
83
84function parseCell(value: unknown): string | Bar {
85 if (!isObject(value)) return str(value)
86 const frac = typeof value.frac === 'number' && Number.isFinite(value.frac) ? Math.min(1, Math.max(0, value.frac)) : 0
87 return { frac, text: str(value.text), tone: str(value.tone, 'dim') }
88}
89
90// One JSON object with a list of tabs, else null; a tab without an id, columns or rows is dropped.
91// v1.1 filters: chip rows that together pick a tab, its id their picks joined by `/`. A filter
92// without an id or an option, and a filter or option whose id was seen before, is dropped; the
93// caps count what is left.
94function parseFilters(value: unknown): Filter[] {
95 if (!Array.isArray(value)) return []
96 const ids = new Set<string>()
97 const filters = value.flatMap((filter): Filter[] => {
98 if (!isObject(filter) || typeof filter.id !== 'string' || filter.id === '' || ids.has(filter.id) || !Array.isArray(filter.options)) return []
99 const seen = new Set<string>()
100 const options = filter.options.flatMap((option): FilterOption[] => {
101 if (!isObject(option) || typeof option.id !== 'string' || option.id === '' || seen.has(option.id)) return []
102 seen.add(option.id)
103 return [{ id: option.id, label: str(option.label, option.id) }]
104 })
105 if (options.length === 0) return []
106 ids.add(filter.id)
107 return [{ id: filter.id, options: options.slice(0, MAX_OPTIONS), default: typeof filter.default === 'string' ? filter.default : '' }]
108 })
109 return filters.slice(0, MAX_FILTERS)
110}
111
112export function parsePanelOutput(stdout: string): PanelData | null {
113 const value = parseJson(stdout.trim())
114 if (!isObject(value) || !Array.isArray(value.tabs)) return null
115 const filters = parseFilters(value.filters)
116 const tabs = value.tabs.slice(0, filters.length > 0 ? MAX_FILTER_TABS : MAX_TABS).flatMap((tab): PanelTab[] => {
117 if (!isObject(tab) || typeof tab.id !== 'string' || !Array.isArray(tab.columns) || !Array.isArray(tab.rows)) return []
118 const columns = tab.columns.slice(0, MAX_COLUMNS).filter(isObject).map(column => {
119 const width = Math.min(MAX_WIDTH, typeof column.width === 'number' && column.width > 0 ? Math.floor(column.width) : str(column.label, str(column.key)).length)
120 return {
121 key: str(column.key),
122 label: str(column.label, str(column.key)),
123 width,
124 maxWidth: typeof column.maxWidth === 'number' && Number.isFinite(column.maxWidth) ? Math.min(MAX_WIDTH, Math.max(width, Math.floor(column.maxWidth))) : width,
125 align: column.align === 'right' ? ('right' as const) : ('left' as const),
126 isBar: column.kind === 'bar',
127 keepRight: column.keep === 'right',
128 }
129 })
130 const rows = tab.rows.slice(0, MAX_ROWS).filter(isObject).map((row, i) => ({
131 id: str(row.id, String(i)),
132 dim: row.dim === true,
133 cells: Object.fromEntries(Object.entries(isObject(row.cells) ? row.cells : {}).map(([key, cell]) => [key, parseCell(cell)])),
134 hover: (Array.isArray(row.hover) ? row.hover : []).slice(0, HOVER_LINES).map(line => str(line)),
135 }))
136 return [{ id: tab.id, label: str(tab.label, tab.id), columns, rows, note: str(tab.note) }]
137 })
138 return { summary: str(value.summary), tab: str(value.tab), tabs, filters }
139}
140
141// Each filter's option: the user's pick while still offered, else its default, else its first.
142export function pickOptions(filters: Filter[], picks: Record<string, string> | undefined): string[] {
143 const offered = (filter: Filter, id: string | undefined) => filter.options.some(option => option.id === id)
144 return filters.map(filter => {
145 const pick = picks?.[filter.id]
146 return offered(filter, pick) ? (pick as string) : offered(filter, filter.default) ? filter.default : (filter.options[0] as FilterOption).id
147 })
148}
149
150// The user's pick if the output still has it, else the output's default, else the first tab.
151export function pickTab(data: PanelData, chosen: string | undefined): PanelTab | null {
152 return data.tabs.find(tab => tab.id === chosen) ?? data.tabs.find(tab => tab.id === data.tab) ?? data.tabs[0] ?? null
153}
154
155const fit = (text: string, width: number, right: boolean, keepRight = false) => {
156 const kept = keepRight && text.length > width ? text.slice(text.length - width) : text.slice(0, width)
157 return right ? kept.padStart(width) : kept.padEnd(width)
158}
159
160// v1.2: the columns at their minimum widths, one gap apart, leave `width - used` cells; those go
161// left to right to columns with a `maxWidth`, each up to it. Header and rows share the result.
162function layout(columns: Column[], width: number): Column[] {
163 let spare = Math.max(0, width - columns.reduce((sum, column) => sum + column.width, 0) - GAP * Math.max(0, columns.length - 1))
164 return columns.map(column => {
165 const grow = Math.min(spare, column.maxWidth - column.width)
166 spare -= grow
167 return { ...column, width: column.width + grow }
168 })
169}
170
171// A bar the whole cell wide: its first `frac` of the cells on the tone's background, the rest
172// on the track; the text right-aligned over it, one cell clear of the right edge when it fits,
173// each character inked dark over the fill and light over the track. One segment per run of
174// characters alike.
175export function barSegments(bar: Bar, width: number, dim: boolean): Segment[] {
176 // any work done shows: a non-zero fraction fills at least one cell
177 const fill = bar.frac > 0 ? Math.max(1, Math.round(bar.frac * width)) : 0
178 // own keys only: an inherited name ("constructor") is no tone
179 const tone = (!dim && Object.hasOwn(TONES, bar.tone) ? TONES[bar.tone] : TONES.dim) as number
180 const text = bar.text.slice(0, width)
181 const line = (text.length + 2 <= width ? `${text} ` : text).padStart(width)
182 const out: Segment[] = []
183 for (let i = 0; i < width; i++) {
184 const filled = i < fill
185 const last = out.at(-1)
186 if (last && last.background === (filled ? tone : BAR_TRACK)) last.text += line[i]
187 else out.push({ text: line[i] as string, color: filled ? INK_ON_FILL : INK_ON_TRACK, background: filled ? tone : BAR_TRACK })
188 }
189 return out
190}
191
192function cellSegments(column: Column, value: string | Bar | undefined, dim: boolean): Segment[] {
193 if (column.isBar && typeof value === 'object') return barSegments(value, column.width, dim)
194 const text = typeof value === 'object' ? value.text : (value ?? '')
195 return [{ text: fit(text, column.width, column.align === 'right', column.keepRight) }]
196}
197
198// Cut to `width` columns: a row never wraps.
199export function clip(segments: Segment[], width: number): Segment[] {
200 const out: Segment[] = []
201 let left = Math.max(0, width)
202 for (const segment of segments) {
203 if (left === 0) break
204 const text = segment.text.slice(0, left)
205 left -= text.length
206 if (text !== '') out.push({ ...segment, text })
207 }
208 return out
209}
210
211const join = (cells: Segment[][]): Segment[] => cells.flatMap((cell, i) => (i === 0 ? cell : [{ text: ' '.repeat(GAP) }, ...cell]))
212
213export const headerSegments = (tab: PanelTab, width: number): Segment[] =>
214 clip(join(layout(tab.columns, width).map(column => [{ text: fit(column.label.replaceAll('{w}', String(column.width)), column.width, column.align === 'right' && !column.isBar) }])), width)
215
216export const rowSegments = (tab: PanelTab, row: PanelRow, width: number): Segment[] =>
217 clip(join(layout(tab.columns, width).map(column => cellSegments(column, row.cells[column.key], row.dim))), width)
218
219// stderr's first line with text, its control characters spaces
220export function firstLine(text: string): string {
221 return text.split('\n').map(line => clean(line).trim()).find(Boolean) ?? ''
222}
223hooks/ask-line.tsx 23 lines1import type { ClientModule } from 'claude-code'
2
3export type AskLineProps = { key: string; label: string; text: string }
4
5// One ask's toggle line, drawn as Text, never a Button: the terminal's hit test stops at the
6// first pressable (onClick or tabIndex) above the cell and never reaches this Client's pointer
7// listener past it, so a Button here swallowed the right-click. Each button press posts once;
8// the hooks module decides (left toggles the context, right dismisses), naming the ask by its
9// text, so a line that moved since this drew is still the one acted on.
10const AskLine: ClientModule<AskLineProps> = (props, surface) => {
11 const { Box, Text } = surface.elements
12 surface.onPointer(event => {
13 if (event.type === 'down') surface.post({ button: event.button ?? null, text: props.text })
14 })
15 return (
16 <Box key={props.key}>
17 <Text>{props.label}</Text>
18 </Box>
19 )
20}
21
22export default AskLine
23types/index.d.ts 29 lines1export type RunStatus = 'running' | 'done' | 'failed' | 'dead'
2
3export type Run = {
4 dir: string
5 kind: string
6 label: string
7 cwd: string
8 isReviewer: boolean
9 model: string
10 status: RunStatus
11 startedAt: number | null
12 endedAt: number | null
13}
14
15export type OpenAsk = { n: number; text: string }
16
17declare module 'claude-code' {
18 interface PluginState {
19 'agent-ui': {
20 selectedRun: string | null
21 openAsk: OpenAsk | null
22 expanded: string[]
23 panelsOpen: string[]
24 panelTabs: Record<string, string>
25 panelFilters: Record<string, Record<string, string>>
26 }
27 }
28}
29