Terminal UI for planning, running and understanding complex agent workflows inside Claude Code.


A terminal UI for planning, running and understanding complex agent workflows inside Claude Code.
Don't hope that Claude one-shots your multi-step logic from a loosely worded description.
Try design → review → run instead.
/plugin install workflow-conductor --marketplace bruw/workflow-conductor
/conductor
# make sure you're in a large terminal window
Conductor has Claude draw a visual plan that thinks through the workflow step by step. You can read it in ten seconds and check the logic before Claude writes the script.
A plan costs about as much as Plan mode, and it can save a lot of tokens compared with a workflow done badly.
Type /conductor review this PR thoroughly. Claude drafts this and puts it on the board:
╭───────────────────────────────────────────────────────────────────── n6 ─╮
│ START │
│ Review the current diff along several dimensions and keep only findings… │
╰──────────────────────────────────────────────────────────────────────────╯
↓ [+]
╭───────────────────────────────────────────────────────────────────── n1 ─╮
│ AGENT scout / scout diff low │
│ Cheap and mechanical. Its list of dimensions is the work-list for the p… │
╰──────────────────────────────────────────────────────────────────────────╯
↓ [+]
┌╴ PIPELINE / review · once per: ×4 dimensions ╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴ n2 ╴┐
╎ ╭───────────────────────────────────────────────────────────────── n3 ─╮ ╎
╎ │ AGENT / review │ ╎
╎ │ One reviewer per dimension. │ ╎
╎ ╰──────────────────────────────────────────────────────────────────────╯ ╎
╎ ↓ [+] ╎
╎ ╭───────────────────────────────────────────────────────────────── n4 ─╮ ╎
╎ │ AGENT verify / verify findings │ ╎
╎ │ 3 votes: each skeptic tries to refute a finding and defaults to ref… │ ╎
╎ ╰──────────────────────────────────────────────────────────────────────╯ ╎
└╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴ [+] ╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴┘
all ⇓ [+]
╭───────────────────────────────────────────────────────────────────── n5 ─╮
│ AGENT merge │
│ Runs once over all surviving findings: merge duplicates, order by sever… │
╰──────────────────────────────────────────────────────────────────────────╯
Edit it directly in the UI, or ask Claude to edit it for you.
Then press r to script and run. Claude asks only about what is unresolved, states the plan with its worst-case cost, writes a real Workflow script from the project, and runs it. The board becomes the run:
╭───────────────────────────────────────────────────────────────────── n1 ─╮
│ AGENT scout / scout diff low │
│ Cheap and mechanical. Its list of dimensions is the work-list for the p… │
╰─ ✗ 3/4 done · 1 failed · 20.4k ──────────────────────────────────────────╯
↓
┌╴ PIPELINE / review · once per: ×4 dimensions ╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴ n2 ╴┐
╎ ╭───────────────────────────────────────────────────────────────── n3 ─╮ ╎
╎ │ AGENT / review │ ╎
╎ │ One reviewer per dimension. │ ╎
╎ ╰─ ✓ 4/4 done · 30.6k ─────────────────────────────────────────────────╯ ╎
╎ ↓ ╎
╎ ╭───────────────────────────────────────────────────────────────── n4 ─╮ ╎
╎ │ AGENT verify / verify findings │ ╎
╎ │ 3 votes: each skeptic tries to refute a finding and defaults to ref… │ ╎
╎ ╰─ ✓ 4/4 done · 40.8k ─────────────────────────────────────────────────╯ ╎
└╴ ✓ 8/8 done · 71.4k ╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴┘
all ⇓
╭───────────────────────────────────────────────────────────────────── n5 ─╮
│ AGENT merge │
│ Runs once over all surviving findings: merge duplicates, order by sever… │
╰─ · not run ──────────────────────────────────────────────────────────────╯
Workflow script estimates, in tokens.
| Flow | Design | Hand-off (r) |
|---|---|---|
Draw it yourself, press r | ~0k: the board makes no Claude calls | ~10–20k, what Claude spends writing any Workflow script, but from a full spec |
/conductor <description…>, press r | ~5–15k for the draft, like Plan mode | ~10–20k |
Draft, q for a review, fix, press r | ~10–25k, like Plan mode plus a round of refinement | ~10–20k |
There are eight blocks:
agent, code, subworkflowpipeline, parallel, loop, branchstartEach block comes in several kinds. A kind is a common pattern that prefills the block's logic field:
| Block | Kinds |
|---|---|
| agent | task · scout · check · verify · judge · critic · merge · classify |
| loop | custom · count · pass · dry · converged · target · budget |
| parallel | arms · each · sweep · attempts |
| branch | if-else · guard · route |
Four templates to start from (Review, Research, Migrate, Judge panel), or a blank board.
Conductor supports full mouse and keyboard navigation.
/conductor | the board: the live run, else the last project, else the start screen |
/conductor <description…> | Claude drafts a new project from your words |
/conductor min · max | fold the designer away, bring it back |
| Key | Does |
|---|---|
w a s d | move the selection; with Shift, move the block |
Enter | edit the block's fields |
n x t | add a block, delete it, change its type or kind |
1 2 | step the model, the effort |
o b | open a container as the view, back up a level |
u y | undo, redo: fifty steps a project |
r | implement and run |
q | ask Claude to review the design |
p | projects and templates |
f | write the board over a project file that is no longer valid |
? | every other key, and the mouse |
It's MIT-licensed, so feel free to change it to fit your needs.
claude --plugin-dir /path/to/conductor
In the desktop app, where no flag can be given, the env of your user settings takes it:
{ "env": { "CLAUDE_CODE_PLUGIN_DIRS": "/path/to/conductor" } }
bun install, then bun run check: the plugin validation, tsc and the tests.bun scripts/render-graph.ts --list names what it can draw, and draws it with no session.scripts/dev-session.sh starts Claude Code with the mod in tmux; scripts/send.sh sends it keys, scripts/capture.sh prints the screen and the debug lines.src/ is pure logic; hooks/ is what Claude Code loads.Conductor makes no network requests and reads no settings or credentials.
| Area | What Conductor does | What it never does |
|---|---|---|
| Files | Writes only under the session's root: .claude/workflow-conductor/<name>.json, and, when you answer Save to repo after a project's run, a copy of the script that run ran to .claude/workflows/<name>.js, which the Workflow tool runs by name; <name> is always kebab-case. On a hand-off Claude passes the Workflow script inline; the Workflow tool keeps its own copy in the session folder, and Conductor remembers that path for the next hand-off. | Write any other file another tool runs, settings, CLAUDE.md, build or start-up files. Delete or rename a file: to remove or rename a project, remove or rename its files. |
| Programs | Nothing. | Run any program. |
| Prompts | Submits a prompt to your own session in two cases. r: Implement and run the "<name>" workflow project (Conductor hands it off: call mcp__workflow-conductor__before_workflow first). /conductor <description>: Draft a workflow project: <description>, your own words. q and the draft key only put a sentence in the prompt box for you to send. | Put file content or conversation text in a prompt it submits: only the project name, or your own words. Read the prompt box beyond whether it is empty. |
| Tools | Stands in for two tools, both its own, on every call: its tool.call hook returns the result, and no other tool runs in their place. It is the only way a mod serves a tool it adds. mcp__workflow-conductor__before_workflow (hooks/offer.tsx): Claude calls it before writing or running a Workflow script; Conductor asks you whether to design the workflow on the board first and answers with your choice; subagents and -p runs get the standard answer without a question. mcp__workflow-conductor__project (hooks/project.tsx): Claude calls it to read and edit a project (read, apply, write, attach); the project's goal, blocks and file paths reach Claude this way and in notes on the prompts you send while the board is open. | Answer another tool's call in that tool's place. |
| Claude's tools | Refreshes the board after a project file is written and tracks a started run. Refuses a write or edit of a project file while that project is running. Asks once whether to draw a Workflow run no project claims: a yes, or what you type instead, is added to the tool's result as a note to Claude. | Change Claude's own Write, Edit and Workflow calls otherwise. |
| Hooks | /conductor (command.run, on that command name alone): opens the board or the run view, folds or expands the designer, or starts a draft, the same whoever runs the command, you or other code. Subagent starts, model requests and turn ends (agent.spawn, turn.step, turn.complete): reads a workflow agent's id and label, a subagent's token usage and how its turn ended, to draw the run, and passes each on unchanged; the end of Claude's own turn after a run finished is when the save question is asked. The prompt box (prompt.edit): while the board is taking the keyboard back, one letter typed into the empty box goes to the board as a key instead. Prompts you send (prompt.submit): reads each for the hand-off sentence, and adds a note of board changes Claude has not seen as context. Run ends (tool.call on TaskStop, the task-notification row's UserMessage render): reads which run was stopped or ended. session.compact and session.end (on clear or resume): reset what Claude was told. | Hook any other command. Read a prompt, instruction or tool description in the run hooks. |
hooks/register.tsx 17 lines1import type { Register } from 'claude-code'
2
3import { createTracker } from '../src/run/tracker'
4
5import { registerProject } from './project'
6import { registerOffer } from './offer'
7import { registerRun } from './run'
8
9// Composes only: run hooks live in run.tsx, project hooks in project.tsx, the question before a workflow in offer.tsx.
10// They share the one tracker, so a handoff can tell it which project the next run is.
11export const register: Register = on => {
12 const tracker = createTracker()
13 registerRun(on, tracker)
14 registerProject(on, tracker)
15 registerOffer(on, tracker)
16}
17src/run/tracker.ts 501 lines1import { endText, statusText } from '../ui/rail'
2
3import { emptyRunState } from './events'
4import type { RunEvent, RunState } from './events'
5import { journalPhases, journalResults } from './journal'
6import { reduce, remap } from './reducer'
7import type { Mapping } from './reducer'
8import { replayDue } from './replay'
9
10// Decides when things happen for a live run: which agents count, when the state is written, the journal read, the run ended.
11// Reaches everything outside through a TrackerHost, so it runs under a fake host in tests.
12
13export const TICK_MS = 96
14/** The engine sends no notice of a stop from the workflow view; a skipped agent is aborted too, but its run spawns on at once. */
15export const STOPPED_MS = 8000
16/** A handoff waits this long for a run under another name than its project's; a prompt from the person starts the wait again. */
17export const HANDOFF_MS = 180_000
18/** A slow replay spreads its events over this long. */
19export const REPLAY_MS = 10_000
20/** An agent neither heard from (a spawn, a usage count) nor ended for this long is held failed, so its run can end. */
21const STALE_MS = 30 * 60_000
22
23// In ticks. A full state write may go out every tick (~10/s); the rest are slower.
24const USAGE_EVERY = 5
25const JOURNAL_EVERY = 5
26const PANE_EVERY = 10
27/** Journal reads an agent may miss before its phase is given up on. */
28const JOURNAL_TRIES = 8
29const STALE_TICKS = Math.ceil(STALE_MS / TICK_MS)
30
31export type Timer = { cancel: () => void }
32
33export type TrackerHost = {
34 write: (state: RunState) => unknown
35 /** Stores the tick clock (ms), which the pane's spinner follows. */
36 frame: (now: number) => unknown
37 readText: (path: string) => Promise<string>
38 every: (ms: number, fn: () => void) => Timer
39 after: (ms: number, fn: () => void) => Timer
40 paneShown: () => Promise<boolean>
41 status: (text: string | undefined) => unknown
42 toast: (text: string) => unknown
43 /** Null: the run was not started from a project. */
44 project?: (name: string | null) => unknown
45 /** A real run (not a replay) ended; `project` is the one it was tracked as. */
46 ended?: (end: RunEnded) => unknown
47}
48
49/** A project's claim on a run: handed off, the next run to start is its run; adopted, the run already tracked is. */
50export type Handoff = { name: string; nodeIds: readonly string[]; titles?: Readonly<Record<string, string>>; match?: Readonly<Record<string, readonly string[]>> }
51
52type Claim = Mapping & { name: string; titles?: Readonly<Record<string, string>> }
53
54const claimOf = (from: Handoff): Claim => ({ name: from.name, ids: new Set(from.nodeIds), titles: from.titles, match: from.match })
55
56/** `project`: the saved project the run's workflow is named as; the run is that project's, handed off or not. */
57export type RunStarted = { runId: string; name?: string; transcriptDir?: string; taskId?: string; project?: Handoff }
58export type AgentSpawned = { runId: string; agentId: string; label: string; index?: number }
59export type AgentEnded = { ok: boolean; aborted?: boolean; durationMs?: number }
60
61export type Tracker = ReturnType<typeof createTracker>
62
63const hasRunning = (state: RunState): boolean => Object.values(state.agents).some(agent => agent.status === 'running')
64
65export type Ending = 'done' | 'failed' | 'stopped'
66
67export type RunEnded = { runId: string; ending: Ending; project?: string }
68
69/** The words a task notification ends with: `completed`, `failed`, `killed`, or another its producer wrote. */
70const endingOf = (status: string): Ending => (status === 'completed' ? 'done' : status === 'killed' ? 'stopped' : 'failed')
71
72export function createTracker() {
73 let host: TrackerHost | undefined
74 let state = emptyRunState()
75 /** 0 clean, 1 token counts only, 2 anything else. */
76 let dirty: 0 | 1 | 2 = 0
77 let ticker: Timer | undefined
78 let stopWait: Timer | undefined
79 let replaying: Timer | undefined
80 let ticks = 0
81 let lastRead = -JOURNAL_EVERY
82 let reading = false
83 let shown = false
84 let lastStatus: string | undefined
85 /** The handoff waiting for its run, and the one the tracked run came from. */
86 let pending: Claim | undefined
87 let active: Claim | undefined
88 let expiry: Timer | undefined
89 /** The project whose handoff is being worked on: from the handoff until the person's next prompt after its claim is spent. A run of it meanwhile (the first, a retry) comes out of the handoff. */
90 let handed: string | undefined
91 let replayed = false
92 /** Agents ended since the last spawn, and whether every one of them was aborted. */
93 let ends = 0
94 let abortedOnly = true
95
96 /** Agents of the tracked run still running, with their latest request's token count: its context, which the built-in workflow row shows. */
97 const latest = new Map<string, number>()
98 /** Agents waiting for a phase, with the journal reads that missed them. */
99 const noPhase = new Map<string, number>()
100 /** The tick each agent was last heard from: its spawn, or a usage count. */
101 const heard = new Map<string, number>()
102 /** Runs a newer one replaced: their late agents are not this run's. */
103 const superseded = new Set<string>()
104
105 // A host call must never break tracking: its failure is the host's to report.
106 const call = (fn: (host: TrackerHost) => unknown): void => {
107 if (!host) return
108 try {
109 Promise.resolve(fn(host)).catch(() => {})
110 } catch {
111 // ignored
112 }
113 }
114
115 const isDirty = (): boolean => dirty !== 0
116
117 const syncStatus = (): void => {
118 const want = state.status === 'running' && !shown ? statusText(state, active?.titles) : undefined
119 if (want === lastStatus) return
120 lastStatus = want
121 call(h => h.status(want))
122 }
123
124 const flush = (): void => {
125 dirty = 0
126 const snapshot = state
127 call(h => h.write(snapshot))
128 syncStatus()
129 }
130
131 const pollPane = (): void => {
132 if (!host) return
133 host.paneShown().then(
134 isShown => {
135 if (isShown === shown) return
136 shown = isShown
137 syncStatus()
138 },
139 () => {},
140 )
141 }
142
143 const cancelStopWait = (): void => {
144 stopWait?.cancel()
145 stopWait = undefined
146 }
147
148 const looksStopped = (): boolean => ends > 0 && abortedOnly && !hasRunning(state)
149
150 const armStopWait = (): void => {
151 if (!host || stopWait) return
152 stopWait = host.after(STOPPED_MS, () => {
153 stopWait = undefined
154 if (state.status === 'running' && looksStopped()) conclude('stopped')
155 })
156 }
157
158 /** Ends the run as the engine says it ended. Agents still open (an end missed, as across a reload) take their journal result, else fail. */
159 function conclude(ending: Ending, durationMs?: number): void {
160 const runId = state.runId
161 if (runId === undefined) return
162 cancelStopWait()
163
164 const close = (results: Map<string, boolean>): void => {
165 if (state.runId !== runId) return
166 const open = Object.values(state.agents).filter(agent => agent.status === 'running')
167 for (const agent of open) latest.delete(agent.agentId)
168 noPhase.clear()
169 apply([
170 ...open.map((agent): RunEvent => ({ kind: 'agent-end', agentId: agent.agentId, ok: results.get(agent.agentId) ?? false })),
171 { kind: 'run-end', runId, ok: ending === 'done', stopped: ending === 'stopped', durationMs },
172 ])
173 }
174
175 const dir = state.transcriptDir
176 if (!host || dir === undefined || !hasRunning(state)) {
177 close(new Map())
178
179 return
180 }
181 host.readText(`${dir}/journal.jsonl`).then(
182 text => close(journalResults(text)),
183 () => close(new Map()),
184 )
185 }
186
187 const readJournal = (): void => {
188 lastRead = ticks
189 const runId = state.runId
190 const dir = state.transcriptDir
191 if (!host || reading) return
192
193 const settle = (phases: Map<string, string | null>): void => {
194 reading = false
195 if (state.runId !== runId) return
196
197 const events: RunEvent[] = []
198 for (const [agentId, misses] of [...noPhase]) {
199 const phase = phases.get(agentId)
200 const agent = state.agents[agentId]
201 if (phase === undefined && agent && misses + 1 < JOURNAL_TRIES) {
202 noPhase.set(agentId, misses + 1)
203 continue
204 }
205 noPhase.delete(agentId)
206 if (agent && typeof phase === 'string') {
207 events.push({ kind: 'agent-start', runId: runId ?? '', agentId, label: agent.label, phase })
208 }
209 }
210 apply(events)
211 }
212
213 if (dir === undefined) {
214 settle(new Map())
215
216 return
217 }
218 reading = true
219 host.readText(`${dir}/journal.jsonl`).then(
220 text => settle(journalPhases(text)),
221 () => settle(new Map()),
222 )
223 }
224
225 const stopTicker = (): void => {
226 ticker?.cancel()
227 ticker = undefined
228 }
229
230 /** An agent not heard from for STALE_MS is held failed: its end was missed, or never comes. */
231 const closeStale = (): void => {
232 const stale = Object.values(state.agents).filter(agent => agent.status === 'running' && ticks - (heard.get(agent.agentId) ?? 0) >= STALE_TICKS)
233 if (stale.length === 0) return
234 ends += stale.length
235 abortedOnly = false
236 for (const agent of stale) latest.delete(agent.agentId)
237 apply(stale.map(agent => ({ kind: 'agent-end', agentId: agent.agentId, ok: false })))
238 }
239
240 const tick = (): void => {
241 ticks++
242 if (ticks % PANE_EVERY === 0) {
243 pollPane()
244 closeStale()
245 }
246 const running = hasRunning(state)
247
248 let wrote = false
249 if (dirty === 2 || (dirty === 1 && ticks % USAGE_EVERY === 0)) {
250 flush()
251 wrote = true
252 }
253 if (noPhase.size > 0 && ticks - lastRead >= JOURNAL_EVERY) readJournal()
254 // One write a tick at most: the spinner holds its frame on a tick that wrote the state.
255 if (running && shown && !wrote) call(h => h.frame(ticks * TICK_MS))
256 if (!running && dirty === 0 && noPhase.size === 0 && !reading) stopTicker()
257 }
258
259 const startTicker = (): void => {
260 if (!host || ticker) return
261 pollPane()
262 ticker = host.every(TICK_MS, tick)
263 }
264
265 const finish = (): void => {
266 cancelStopWait()
267 flush()
268 const text = endText(state)
269 call(h => h.toast(text))
270 report()
271 }
272
273 const report = (): void => {
274 const { runId, status } = state
275 const project = active?.name
276 if (!replayed && runId !== undefined && status !== 'idle' && status !== 'running') call(h => h.ended?.({ runId, ending: status, project }))
277 }
278
279 function apply(events: readonly RunEvent[]): void {
280 const before = state
281 let wasRunning = state.status === 'running'
282 const wasStopped = state.status === 'stopped'
283 for (const event of events) {
284 const next = reduce(state, event, active)
285 if (next === state) continue
286 state = next
287 wasRunning ||= state.status === 'running'
288 if (event.kind === 'agent-start' || event.kind === 'agent-usage') heard.set(event.agentId, ticks)
289 if (event.kind !== 'agent-usage') dirty = 2
290 else if (dirty === 0) dirty = 1
291 }
292 if (state === before) return
293
294 if (state.status === 'running') {
295 if (looksStopped()) armStopWait()
296 else cancelStopWait()
297 }
298 if (wasRunning && state.status !== 'running') finish()
299 // A run held stopped that a later notice ends otherwise: told once more, without a second toast, so a run that ended done is asked about.
300 else if (wasStopped && state.status !== 'stopped' && state.status !== 'running') report()
301 else startTicker()
302 }
303
304 const dropPending = (): void => {
305 expiry?.cancel()
306 expiry = undefined
307 pending = undefined
308 }
309
310 const armExpiry = (): void => {
311 expiry?.cancel()
312 expiry = host?.after(HANDOFF_MS, dropPending)
313 }
314
315 /** Forgets the run held so far so that `runId` starts clean. `own` is the saved project the run is named as. */
316 const begin = (runId: string, own?: Handoff): void => {
317 replaying?.cancel()
318 replaying = undefined
319 cancelStopWait()
320 replayed = false
321 ends = 0
322 abortedOnly = true
323 latest.clear()
324 noPhase.clear()
325 heard.clear()
326 if (own !== undefined) {
327 // Named as a saved project: that project's run, whatever waits. A handoff of another project goes on waiting for its own.
328 active = claimOf(own)
329 if (pending?.name === own.name) dropPending()
330 call(h => h.project?.(own.name))
331 } else if (pending !== undefined || state.runId !== runId) {
332 // Another run, or the one a handoff waited for: it belongs to that project, or to none.
333 active = pending
334 dropPending()
335 // Said for every run, the same project's next one too: the host's copy is the session's and starts over on a /clear, this one does not.
336 const name = active?.name ?? null
337 call(h => h.project?.(name))
338 }
339 if (state.runId !== undefined && state.runId !== runId) superseded.add(state.runId)
340 superseded.delete(runId)
341 }
342
343 /** The run tracked now is `claim`'s project's: every agent seen so far is placed again by it. */
344 const take = (claim: Handoff): void => {
345 const before = active
346 active = claimOf(claim)
347 if (pending?.name === claim.name) dropPending()
348 if (active.name !== before?.name) call(h => h.project?.(claim.name))
349 state = remap(state, active)
350 flush()
351 }
352
353 /** Whether a real run holds the tracker: one running now, or the one a handoff waits for. A replay would take its place. */
354 const busy = (): boolean => pending !== undefined || (state.status === 'running' && !replayed)
355
356 return {
357 /** The state as of every event so far (the stored copy may lag by a tick). */
358 state: (): RunState => state,
359
360 /** `stored` is the state a previous load of the module left: its run is picked up, with `claim` as its project (node ids are not stored). */
361 attach(next: TrackerHost, stored?: RunState, claim?: Handoff): void {
362 host = next
363 if (stored && state.status === 'idle' && Object.keys(state.agents).length === 0) {
364 state = stored
365 if (claim && state.status !== 'idle') active = claimOf(claim)
366 for (const agent of Object.values(state.agents)) {
367 if (agent.status !== 'running') continue
368 latest.set(agent.agentId, agent.tokens)
369 heard.set(agent.agentId, ticks)
370 }
371 }
372 if (state.status === 'running') startTicker()
373 },
374
375 /** The first run to start within HANDOFF_MS is the project's; then the claim drops, so a later unrelated run is not taken. */
376 handoff(next: Handoff): void {
377 dropPending()
378 pending = claimOf(next)
379 handed = next.name
380 armExpiry()
381 },
382
383 /**
384 * While a handoff waits, a prompt is the person answering Claude about the project: the wait starts again.
385 * With none waiting the handoff's work is over: a later run of the project is one asked for anew.
386 */
387 prompted(): void {
388 if (pending === undefined) handed = undefined
389 else armExpiry()
390 },
391
392 /** Returns the labels of the agents no block claims, one per agent; null with no run to give the project to. */
393 adopt(claim: Handoff): string[] | null {
394 if (state.status === 'idle') return null
395 take(claim)
396 return state.unmapped.map(id => state.agents[id]?.label ?? '')
397 },
398
399 /** A project is handed off and its run has not started: Claude is writing the script for it. */
400 awaitsRun: (): boolean => pending !== undefined,
401
402 busy,
403
404 project: (): string | undefined => active?.name,
405
406 /** Whether the tracked run comes out of a handoff of its project (the run it waited for, or a retry of it), not only out of its name. */
407 handedOff: (): boolean => active !== undefined && active.name === handed,
408
409 /** Whether the run held is a replay, not one the engine ran. */
410 replayed: (): boolean => replayed,
411
412 paneOpened(): void {
413 shown = true
414 syncStatus()
415 },
416
417 runStarted(run: RunStarted): void {
418 const isNew = state.runId !== run.runId || state.status !== 'running'
419 if (isNew) begin(run.runId, run.project)
420 apply([{ kind: 'run-start', runId: run.runId, name: run.name, transcriptDir: run.transcriptDir || undefined, taskId: run.taskId || undefined }])
421 // Its agents were seen before the run was announced, so it began with no name: they are placed again by its project.
422 if (!isNew && run.project !== undefined && active?.name !== run.project.name) take(run.project)
423 },
424
425 agentSpawned(agent: AgentSpawned): void {
426 if (superseded.has(agent.runId)) return
427 if (state.runId !== agent.runId) {
428 begin(agent.runId)
429 apply([{ kind: 'run-start', runId: agent.runId }])
430 }
431 cancelStopWait()
432 ends = 0
433 abortedOnly = true
434 latest.set(agent.agentId, 0)
435 noPhase.set(agent.agentId, 0)
436 apply([{ kind: 'agent-start', runId: agent.runId, agentId: agent.agentId, label: agent.label, index: agent.index }])
437 if (ticks - lastRead >= JOURNAL_EVERY) readJournal()
438 },
439
440 /** `tokens`: one request's four usage counts. Each request re-reads the whole prompt, so a sum would count it once per request. */
441 agentUsage(agentId: string, tokens: number): void {
442 if (!latest.has(agentId) || !Number.isFinite(tokens) || tokens <= 0) return
443 latest.set(agentId, tokens)
444 apply([{ kind: 'agent-usage', agentId, tokens }])
445 },
446
447 agentEnded(agentId: string, end: AgentEnded): void {
448 const tokens = latest.get(agentId)
449 if (tokens === undefined) return
450 latest.delete(agentId)
451 ends++
452 abortedOnly &&= end.aborted === true
453 apply([{ kind: 'agent-end', agentId, ok: end.ok, durationMs: end.durationMs, tokens }])
454 },
455
456 /** Raised again on every drawing of the notice, so only the first counts; a run held stopped takes a later one's status. */
457 taskEnded(taskId: string, status: string, durationMs?: number): void {
458 if (state.taskId === undefined || state.taskId !== taskId) return
459 const ending = endingOf(status)
460 if (state.status === ending || (state.status !== 'running' && state.status !== 'stopped')) return
461 conclude(ending, durationMs)
462 },
463
464 /** Refused (false) while `busy`: the real run's agents would be dropped as a superseded run's. */
465 replay(events: readonly RunEvent[], mode: 'fast' | 'slow', own?: Handoff): boolean {
466 if (busy()) return false
467 const first = events.find(event => event.kind === 'run-start')
468 begin(first?.kind === 'run-start' ? first.runId : '', own)
469 replayed = true
470 state = emptyRunState()
471 dirty = 2
472
473 if (mode === 'fast' || !host) {
474 apply(events)
475 if (isDirty()) flush()
476
477 return true
478 }
479
480 const steps = Math.ceil(REPLAY_MS / TICK_MS)
481 let step = 0
482 let applied = 0
483 const timer = host.every(TICK_MS, () => {
484 step++
485 const due = replayDue(events.length, step, steps)
486 const slice = events.slice(applied, due)
487 applied = due
488 if (step >= steps) {
489 timer.cancel()
490 if (replaying === timer) replaying = undefined
491 }
492 apply(slice)
493 })
494 replaying = timer
495 startTicker()
496
497 return true
498 },
499 }
500}
501hooks/project.tsx 2870 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On, RenderChildren } from 'claude-code'
3
4import { FLASH_CLEAR_MS, TOOL_FULL_NAME, TOOL_NAME, TOOL_SCHEMA, TOOL_TITLE, applyOps, attachNote, callLine, changeWords, changedNote, clearFlash, projectOfPath, diffProjects, draftBrief, editReport, knownAfterEdit, readReport, replaceProject, resultLine, showEdit, staleNote, toolDescription, unplacedNote } from '../src/project/chat'
5import { UNDO_HINT, remember, travel } from '../src/project/history'
6import type { History } from '../src/project/history'
7import { lint, preflightLine, problemFields } from '../src/project/lints'
8import * as partial29 from '../fixtures/partial-29'
9import * as review41 from '../fixtures/review-41'
10import { LAST_SCRIPTS_STORE, handoffPrompt, handoffTarget, noteScript, reviewPrompt } from '../src/project/handoff'
11import { replayEvents } from '../src/run/replay'
12import type { ReplayFixture } from '../src/run/replay'
13import { emptyProject, findNode, flatten, goalOf, isBlank, isProjectName, kindsOf, parseProject, sameProject, serializeProject, typeName } from '../src/project/model'
14import type { Project, ProjectNode, NodeType } from '../src/project/model'
15import { nextIdNumber, quickKnob } from '../src/project/ops'
16import type { NodePatch } from '../src/project/ops'
17import {
18 AGENT_ROWS_MAX,
19 DEFAULT_PROJECT_NAME,
20 DRAFT_LOCK_NOTICE,
21 DRAFT_WAIT_NOTE,
22 PROJECT_DIR,
23 PROJECT_PANE_ID,
24 PROJECT_PANE_TITLE,
25 HANDED_NOTICE,
26 HELP_PAGES,
27 KEYS_CUE,
28 LOCK_NOTICE,
29 REVEAL_STEPS,
30 SCRATCH_PREFIX,
31 FIELD_KNOBS,
32 addHeading,
33 agentsOf,
34 applyMessage,
35 applyOp,
36 bareTarget,
37 firstBlocks,
38 isProjectEntry,
39 blocksWord,
40 carryUi,
41 projectFile,
42 projectName,
43 detailWidth,
44 dockColumns,
45 elapsedOf,
46 fitHelp,
47 freeName,
48 graphProps,
49 handoffOf,
50 helpColumn,
51 helpPage,
52 initialTimes,
53 initialUi,
54 isDefaultName,
55 isSaved,
56 listWindow,
57 movePick,
58 moveStartMark,
59 nothingToRestore,
60 noticeInforms,
61 openProject,
62 openRetype,
63 overlaysProject,
64 patchNode,
65 pickBlock,
66 pickerMatches,
67 previewProps,
68 restoreProject,
69 runOverlay,
70 runSummary,
71 savedEntry,
72 startProject,
73 startEntries,
74 filterText,
75 fitsFull,
76 typePicker,
77 viewRootOf,
78 withoutKeys,
79} from '../src/project/session'
80import type { ProjectUi, GraphBox, PickRow, RunContext, SavedProject, Step, TextKnob } from '../src/project/session'
81import { FIELD_LABEL, PALETTE_GROUPS, TEACH, fieldWord, groupOf, hasLogic, hasName, knobsOf, pickName, placeholderOf, teachOf, useWhen } from '../src/project/teach'
82import type { BlockRef } from '../src/project/teach'
83import { TEMPLATES } from '../src/project/templates'
84import { emptyRunState } from '../src/run/events'
85import type { RunState } from '../src/run/events'
86import { replayProjectEvents } from '../src/run/replay'
87import type { Tracker } from '../src/run/tracker'
88import { NOT_SET, UNMAPPED_ID, canOpen } from '../src/ui/graph-layout'
89import { parseGraphMessage } from '../src/ui/graph-model'
90import { EXPAND_W, EXPAND_WORD, WHY_TEXT, currentStep, initialShell, planStrip, stripItems, whyCompact, wouldDock } from '../src/ui/compact'
91import type { CompactWhy, Minimized, StripPart, StripTone } from '../src/ui/compact'
92import { ENTER, FOCUS_HINT, KEY_OPS, MINIMIZE_KEYS, PASTE_NOTICE, burstKeys, legendItems, legendRows, unboundNotice, LEGEND_GAP } from '../src/ui/keys'
93import type { KeyOp, LegendAction, LegendItem } from '../src/ui/keys'
94import { FAILED, fmtCount } from '../src/ui/rail'
95import { BEAT_MS, SCENE_COLUMNS, SCENE_ROWS, SOLO_ROWS, SPLASH_MS, splashScene, waitScene } from '../src/ui/persona'
96import type { PersonaSpan } from '../src/ui/persona'
97import { MARK_ROWS, MARK_W, markFrame, markPalette } from '../src/ui/mark'
98import { cellWidth, clip, cutCells, firstLines, oneLine, padCells, sanitize, wrapText } from '../src/ui/text'
99import { ACCENT, FADED, GLYPH, PANE_ID, PANE_TITLE, RULE, TEXT } from '../src/ui/theme'
100import { wordmark } from '../src/ui/wordmark'
101
102import { offerDrafted, offerHanded, offerPrompted, offerRan, setOfferBoard, takeOffered } from './offer'
103
104// The designer: owns the Project and what is chosen on it, applies ops, saves the file and draws the screen.
105// Keys are typed into the key catcher, an Input that is not drawn; the graph (./canvas.tsx) is a Client that posts here.
106
107const COMMAND = 'conductor'
108const CANVAS_ELEMENT = 'canvas'
109const SPLASH_ELEMENT = 'splash'
110const SPLASH_NOTE = 'designed for full screen'
111const NAME_FIELD = 'project-name'
112const LOGIC_FIELD = 'project-logic'
113/** Drawn under a new `n` (`project-add:<n>`) to empty it of the keys it took. */
114const PICKER_ELEMENT = 'project-add'
115const TYPE_ELEMENT = 'project-type'
116const REST_PREFIX = 'project-rest:'
117const START_PREFIX = 'start:'
118const DRAFT_LABEL = '[Draft using claude]'
119const NAME_BUTTON = 'projects-button'
120const ACTION_BUTTON_PREFIX = 'act:'
121const MINIMIZE_BUTTON = 'project-minimize'
122const ARROWS_CHOOSE = 'the arrows choose a row'
123/** Saved projects the start screen lists at once where it is short of rows. */
124const SAVED_ROWS = 8
125const SAVED_MAX = 60
126const KNOB_PREFIX = 'project-knob:'
127/** The engine keeps what was typed in an Input under its address, so a field's address names its block. */
128const fieldKey = (base: string, id: string): string => `${base}@${id}#${editGen}`
129const baseOf = (element: string): string => element.split('@')[0] ?? element
130/** Counts the times the fields closed: fields opened again have new addresses and show the block as it is. */
131let editGen = 0
132let fieldsDrawn = false
133const isField = (element: string | undefined): boolean => {
134 const base = baseOf(element ?? '')
135 return base === NAME_FIELD || base === LOGIC_FIELD || base.startsWith(KNOB_PREFIX)
136}
137const draftFieldWord = (base: string): string => fieldWord(base === NAME_FIELD ? 'name' : base === LOGIC_FIELD ? 'logic' : base.slice(KNOB_PREFIX.length))
138const firstField = (node: { type: ProjectNode['type'] }): string => (hasName(node) ? NAME_FIELD : `${KNOB_PREFIX}goal`)
139/**
140 * Where the ring rests while no field is open: an Input (a Button's hotkey cannot see Shift), first among the stops, since the engine keeps the ring by its place.
141 * Not drawn (`display: none`). Emptied by drawing it under a new key, once the typing has paused: a key typed in the frame it is drawn anew is dropped.
142 */
143const CATCH_ELEMENT = 'keys'
144/** This load, in the catcher's key: a module loaded again counts from 0, and the engine would bring back an old key's text. */
145const LOAD = Date.now().toString(36)
146let catchGen = 0
147const catcherKey = (): string => `${CATCH_ELEMENT}:${LOAD}.${catchGen}`
148const isCatcher = (element: string | undefined): boolean => (element ?? '').startsWith(`${CATCH_ELEMENT}:`)
149/** '' where the last drawing drew none. */
150let drawnCatcher = ''
151let pickGen = 0
152const pickerKey = (): string => `${PICKER_ELEMENT}:${LOAD}.${pickGen}`
153const isPickerField = (element: string | undefined): boolean => (element ?? '').startsWith(`${PICKER_ELEMENT}:`)
154const restBase = (element: string | undefined): string | null => (element !== undefined && element.startsWith(REST_PREFIX) ? baseOf(element.slice(REST_PREFIX.length)) : null)
155/** The door: an Input right after the catcher while a block's fields are shown. Down or Tab from the catcher lands on it, which opens the fields; a step back onto it returns to the graph. */
156const DOOR_ELEMENT = 'door'
157let doorGen = 0
158const doorKey = (): string => `${DOOR_ELEMENT}:${LOAD}.${doorGen}`
159const isDoor = (element: string | undefined): boolean => (element ?? '').startsWith(`${DOOR_ELEMENT}:`)
160const isDetailStop = (element: string | undefined): boolean => element !== undefined && (isField(element) || isPickerField(element) || restBase(element) !== null)
161/** How long after the command's answer the handoff prompt is submitted. */
162export const SUBMIT_DELAY_MS = 64
163/** How many times the ring is sent to an element before the field is given up. */
164const LAND_TRIES = 5
165/** A redraw's worth of wait before the ring moves to an element just drawn. */
166export const FOCUS_DELAY_MS = 48
167export const BOX_POLL_MS = 600
168/** The mark's two rows. */
169const HEAD_ROWS = 2
170const EDIT_HINT = 'click a field of the block, or press the Down arrow to reach the name'
171const MAIN_LEAST_ROWS = 5
172/** The detail pane's last rows name its keys: one row where the pane is short. */
173const HINT_ROWS = 2
174const ACTION_GAP = 4
175/** Cells of rule kept at each side of what is said over the footer. */
176const SAID_RULE_W = 3
177/** Rows asked for when the pane sits inline above the prompt. */
178export const PANE_ROWS = 28
179/** A command's `e.presentation.columns` is the only place a hook is told the terminal's width: undefined until one has run. */
180let terminalColumns: number | undefined
181/** The person's theme setting, for the mark's raw colours; read again once it is this old. */
182const THEME_MS = 5000
183let themeRead: { at: number; theme: string | undefined } = { at: -THEME_MS, theme: undefined }
184let splashing = false
185/** The splash stays on its last beat this long before the designer is drawn. */
186const SPLASH_REST_MS = 150
187/** Without `focus` the pane is shown and the person goes on typing in the prompt (an edit from chat). */
188export const paneArgs = (focus: boolean): { id: string; title: string; rows: number; columns?: number; focus?: true } => {
189 const columns = dockColumns(terminalColumns)
190
191 return { id: PROJECT_PANE_ID, title: PROJECT_PANE_TITLE, rows: PANE_ROWS, ...(columns === undefined ? {} : { columns }), ...(focus ? { focus: true as const } : {}) }
192}
193const runNotice = (line: string, isFilled: boolean): string => `run: ${isFilled ? 'the request is in the prompt · Enter sends it' : `type in the prompt: ${line.trim()}`}`
194const askNotice = (line: string, isFilled: boolean): string => (isFilled ? 'ask: the question is in the prompt · change it as you like, then Enter' : `ask: type in the prompt: ${line.trim()}`)
195const draftLine = (): string => `/${COMMAND} `
196const draftNotice = (line: string, isFilled: boolean): string => (isFilled ? 'draft: say in the prompt what the workflow should do, then Enter' : `draft: type in the prompt: ${line.trim()} <what you want>`)
197/** A run, ask or draft notice waits on the prompt box, as does a refusal worded as one. */
198const isRequestNotice = (notice: string | null): boolean => notice !== null && /^(run|ask|draft): /.test(notice)
199
200/** Undo and redo, per project. Module variables, not state: fifty projects are too much to store, and a drawing may read them. */
201const histories: Record<string, History> = {}
202/** Changes per project in this load, and the count Claude last saw: they differ when the board changed by hand since. */
203const revisions: Record<string, number> = {}
204const seenByClaude: Record<string, number> = {}
205/** The project as Claude last saw it whole; none where it never read it, or the conversation was compacted or cleared. */
206const seenProjects: Record<string, Project> = {}
207const sawProject = (name: string, project: Project): void => {
208 seenByClaude[name] = revisions[name] ?? 0
209 seenProjects[name] = project
210}
211const forgetSeenProjects = (): void => {
212 for (const name of Object.keys(seenProjects)) delete seenProjects[name]
213}
214/** The model is told a project is stale once per change, not with every prompt. */
215const warnedAt: Record<string, number> = {}
216const forgetConversation = (): void => {
217 forgetSeenProjects()
218 for (const book of [seenByClaude, warnedAt]) for (const name of Object.keys(book)) delete book[name]
219}
220const record = (name: string, before: Project | null, what: string | undefined): void => {
221 revisions[name] = (revisions[name] ?? 0) + 1
222 if (before) histories[name] = remember(histories[name], before, what ?? 'an edit')
223}
224/** Ids are never reused: the counter never goes back. */
225const timeTravel = (project: Project | null, ui: ProjectUi, way: 'undo' | 'redo', context: RunContext): Step => {
226 if (!project || ui.status !== 'ready') return { project, ui, changed: false }
227 if (context.locked || ui.handed) return applyOp(project, ui, way, context)
228 const moved = travel(histories[ui.name], project, way)
229 if (!moved) return { project, ui: nothingToRestore(ui, way), changed: false }
230 histories[ui.name] = moved.history
231 revisions[ui.name] = (revisions[ui.name] ?? 0) + 1
232 const target: Project = { ...moved.entry.project, name: project.name, nextId: Math.max(nextIdNumber(moved.entry.project), nextIdNumber(project)) }
233 return restoreProject(project, ui, target, way, moved.entry.what, context)
234}
235const keyStep = (project: Project | null, ui: ProjectUi, op: KeyOp, context: RunContext): Step =>
236 op === 'undo' || op === 'redo' ? timeTravel(project, ui, op, context) : applyOp(project, ui, op, context)
237/** Typed and not saved yet. Not state: a keystroke must not redraw the pane. `flushDrafts` saves it on every way out of a field. */
238type Drafts = { name: string; id: string | null; values: Record<string, string> }
239const noDrafts = (): Drafts => ({ name: '', id: null, values: {} })
240let drafts: Drafts = noDrafts()
241const hasDrafts = (): boolean => drafts.id !== null && Object.keys(drafts.values).length > 0
242const fieldPatch = (node: { name: string }, base: string, value: string): NodePatch =>
243 base === NAME_FIELD ? { name: value.trim() || node.name } : base === LOGIC_FIELD ? { logic: value.trim() } : ({ knobs: { [base.slice(KNOB_PREFIX.length)]: value.trim() } } as NodePatch)
244let paneShape = ''
245/** When the focus stops change under a ring at rest, the ring is put back on the catcher. */
246let ringStops = ''
247/** Undefined when unknown. A field typed in while the ring is known to be elsewhere got it by its place among the stops: what is typed there is not its text. */
248let ringOn: string | undefined
249/** The element the ring is moving to ('' with none): what is typed there meanwhile is its text. */
250let ringTo = ''
251/**
252 * A field's drawn `value`, the letters that came by the catcher or the door (`head`) and those typed at its end (`tail`). An Input keeps its text while
253 * `value` holds; a changed `value` replaces the text but not the cursor, and a letter typed in the frame of a new address is dropped: so a field keeps the text it opened with until the typing pauses.
254 */
255let pins: Record<string, { value: string; head: string; tail: string }> = {}
256const pinned = (element: string, value: string): string => (pins[element] ??= { value, head: '', tail: '' }).value
257/** `loose` when the letters kept beside the field cannot be placed: the field is then drawn anew at once. */
258const fieldText = (element: string, typed: string): { text: string; loose: boolean } => {
259 const pin = pins[element]
260 if (!pin) return { text: typed, loose: false }
261 if (typed.startsWith(pin.value)) {
262 pin.tail = typed.slice(pin.value.length)
263
264 return { text: `${pin.value}${pin.head}${pin.tail}`, loose: false }
265 }
266 if (pin.head === '') return { text: typed, loose: false }
267 // A cut at its end is made at the end of the whole; anything else keeps the letters after it.
268 const whole = `${pin.value}${pin.head}`
269 return { text: pin.value.startsWith(typed) ? whole.slice(0, Math.max(0, whole.length - (pin.value.length - typed.length))) : `${typed}${pin.head}`, loose: true }
270}
271/** New addresses for the open fields: the ring, kept by its place, stays on the same field. */
272const redrawFields = (): void => {
273 editGen++
274 for (const pin of Object.values(pins)) pin.head = ''
275 const swap = (key: string): string => key.replace(/#\d+$/, `#${editGen}`)
276 if (ringOn !== undefined && isField(ringOn)) ringOn = swap(ringOn)
277 if (isField(ringTo)) ringTo = swap(ringTo)
278}
279/** Counts every key typed in the pane, for what waits for the typing to pause. */
280let typingSeq = 0
281const TIDY_MS = 600
282/** The catcher is emptied once it holds more keys than this. */
283const CATCH_FULL = 40
284let doored = { element: '', taken: 0 }
285/** For the start screen's preview: null for a file that is no project. */
286const previews: Record<string, Project | null> = {}
287let savedPast = 0
288/** The project the list of projects was opened from: one no file holds yet comes back from here. */
289let behind: { project: Project; ui: ProjectUi } | null = null
290/** `sent` is the text Enter was last pressed on, until the next key: Enter empties the catcher, so what it holds next is counted from the start. */
291let caught: { element: string; taken: number; sent: string | null } = { element: '', taken: 0, sent: null }
292/** The same for the add list's filter: how many of its characters were keys, not text. */
293let picked = { element: '', taken: 0 }
294/** What is typed in the filter once the list has closed is for whatever opened next. */
295let pickedField = { element: '', value: '', taken: 0 }
296/** What is typed in a field after Enter, before the ring has left, is keys. */
297let savedField = { element: '', value: '', taken: 0 }
298/** Where the characters not yet taken start: after the text Enter sent, where the field still holds it (Enter empties some fields). */
299const afterEnter = (sent: { value: string; taken: number }, value: string): number => (value.startsWith(sent.value) ? sent.value.length : 0) + sent.taken
300/** The keys walk the layout the Client made for the same room. */
301let graphBox: GraphBox | undefined
302/** Where the graph stands in the pane's body, in cells, for the wheel; null while none is drawn. */
303let graphArea: { top: number; left: number; columns: number; rows: number } | null = null
304/** Summed over this load: the Client moves its pan by what was added since it last drew. */
305let wheelRows = 0
306/** The keys typed, applied one at a time in the order they came. */
307let keyChain: Promise<void> = Promise.resolve()
308let flushAsked = false
309let boxWatched = false
310let runTracker: Tracker | undefined
311let draftTicker: { cancel: () => void } | null = null
312
313// Both hooks modules declare these (an atom must be spelled in the file that reads it): run.tsx writes them through the tracker.
314const runAtom = atom({ plugin: 'workflow-conductor', key: 'run' } as const, emptyRunState())
315const clockAtom = atom({ plugin: 'workflow-conductor', key: 'runClock' } as const, 0)
316/** Null for a run that no handoff started. */
317const runProjectAtom = atom({ plugin: 'workflow-conductor', key: 'runProject' } as const, null)
318const projectAtom = atom({ plugin: 'workflow-conductor', key: 'project' } as const, null)
319const uiAtom = atom({ plugin: 'workflow-conductor', key: 'projectUi' } as const, initialUi())
320const splashedAtom = atom({ plugin: 'workflow-conductor', key: 'splashed' } as const, false)
321const draftBeatAtom = atom({ plugin: 'workflow-conductor', key: 'draftBeat' } as const, 0)
322/** Grows by one on each key that moves the selection: the mark steps on at once. */
323const nudgeAtom = atom({ plugin: 'workflow-conductor', key: 'markNudge' } as const, 0)
324const timesAtom = atom({ plugin: 'workflow-conductor', key: 'runTimes' } as const, initialTimes())
325const shellAtom = atom({ plugin: 'workflow-conductor', key: 'shell' } as const, initialShell())
326const runScriptAtom = atom({ plugin: 'workflow-conductor', key: 'runScript' } as const, null)
327
328class StaleFile extends Error {
329 constructor(
330 readonly name: string,
331 readonly text: string,
332 ) {
333 super(`project ${name} was changed in another session`)
334 }
335}
336
337/** The file holds no valid project: a save does not write over it unless the person says so (`f`). */
338class InvalidFile extends Error {
339 constructor(readonly name: string) {
340 super(`${name}.json is not a valid project`)
341 }
342}
343
344/** Projects whose last save met an invalid file: the board holds the edits, unsaved, until a save gets through. */
345const heldOver = new Set<string>()
346const invalidNotice = (name: string): string => `not saved: ${name}.json is not a valid project now · the board keeps your edit · [f] Write over it`
347
348/** What this session last read from or wrote to each project's file. Another session sharing the root may save over it. */
349const onDisk: Record<string, Project> = {}
350/** The revision at which each project last changed in another session, so Claude is not told the user did it. */
351const elsewhereAt: Record<string, number> = {}
352const changedElsewhere = (name: string): void => {
353 revisions[name] = (revisions[name] ?? 0) + 1
354 elsewhereAt[name] = revisions[name]
355}
356/** A file taken onto the board or for Claude. */
357const loadedDisk = (name: string, project: Project): void => {
358 const known = onDisk[name]
359 if (known !== undefined && !sameProject(known, project)) changedElsewhere(name)
360 onDisk[name] = project
361 heldOver.delete(name)
362}
363
364// Spelled whole, not built by `projectFile`, so that a reader of the call sees where every save lands.
365// `board` stands in for `onDisk` where a reload with changed source lost it; null for a project not saved yet.
366const saveProject = async ($: EngineInterface, name: string, project: Project, board: Project | null, overwrite = false): Promise<void> => {
367 // The name is spelled into the path: anything but kebab-case could reach outside the projects' directory.
368 if (!isProjectName(name)) throw new Error(`not a project name: ${name}`)
369 const root = await $.session.root()
370 const path = `${root.replace(/\/+$/, '')}/.claude/workflow-conductor/${name}.json`
371 // Read and write are two calls, so a save landing between them is still lost: the engine has no write-if-unchanged.
372 const text = (await $.fs.exists(path)) ? await $.fs.read(path) : undefined
373 if (text !== undefined) {
374 const known = onDisk[name] ?? board
375 const now = parseProject(text)
376 if (!now.ok) {
377 if (!overwrite) {
378 heldOver.add(name)
379 throw new InvalidFile(name)
380 }
381 } else if (known === null || !sameProject(now.project, known)) throw new StaleFile(name, text)
382 }
383 await $.fs.write(path, serializeProject(project))
384 onDisk[name] = project
385 heldOver.delete(name)
386}
387
388type Shown = Pick<Step, 'project' | 'ui'>
389
390type Refused = { project: Project; what: string }
391
392/**
393 * The board takes what another session saved in place of the edit that met it. One undo brings back the board with
394 * `refused`, the edit, made on it, and saves that over the other session's; the next undo goes to before the edit.
395 */
396const takeSaved = (stale: StaleFile, board: Project | null, refused: Refused | null, held: ProjectUi): Shown => {
397 changedElsewhere(stale.name)
398 const opened = openProject(stale.name, stale.text, held)
399 // A StaleFile is thrown only over a file that parses.
400 if (opened.project === null) return { project: board, ui: { ...held, notice: invalidNotice(stale.name) } }
401 if (board) {
402 const history = refused ? remember(histories[stale.name], board, refused.what) : histories[stale.name]
403 histories[stale.name] = remember(history, refused?.project ?? board, 'the file changed in another session')
404 }
405 onDisk[stale.name] = opened.project
406 const back = board ? ' · [u] Back to yours' : ''
407
408 return { project: opened.project, ui: { ...opened.ui, notice: `not saved: ${stale.name} was changed in another session, the board shows it now${back}` } }
409}
410
411const showSaved = async ($: EngineInterface, stale: StaleFile, board: Project | null, refused: Refused | null, held: ProjectUi): Promise<string | null> => {
412 const shown = takeSaved(stale, board, refused, held)
413 await update($, projectAtom, () => shown.project)
414 await update($, uiAtom, () => shown.ui)
415
416 return shown.ui.notice
417}
418
419const reason = (error: unknown): string => cutCells(sanitize(error instanceof Error ? error.message : String(error)), 160)
420
421/** Both atoms are set before `adopt`: the tracker's write reads the run's project and the board. Returns the labels no block took; null with no run. */
422const showRunOn = async ($: EngineInterface, tracker: Tracker, name: string, project: Project): Promise<string[] | null> => {
423 await update($, uiAtom, held => ({ ...held, follow: true, runCleared: false }))
424 await update($, runProjectAtom, () => name)
425
426 return tracker.adopt(handoffOf(name, project))
427}
428
429/** Null when no saved project has the workflow's name. The caller tells the tracker next: its write reads what is set here. */
430const projectOfRun = async ($: EngineInterface, workflow: string | undefined): Promise<{ name: string; project: Project } | null> => {
431 if (workflow === undefined) return null
432 const name = projectName(workflow)
433 if (name === null) return null
434 const path = projectFile(await $.session.root(), name)
435 if (!isSaved(name) || !(await $.fs.exists(path).catch(() => false))) return null
436 await flushDrafts($)
437 const shown = await read($, uiAtom)
438 let project = shown.name === name && shown.status === 'ready' ? await read($, projectAtom) : null
439 if (project === null) {
440 const opened = openProject(name, await $.fs.read(path).catch(() => ''), shown)
441 if (opened.project === null) return null
442 project = opened.project
443 loadedDisk(name, project)
444 await update($, projectAtom, () => opened.project)
445 await update($, uiAtom, () => opened.ui)
446 }
447 await update($, uiAtom, held => ({ ...held, follow: true, runCleared: false }))
448 await update($, runProjectAtom, () => name)
449
450 return { name, project }
451}
452
453/** `$` does not cross files (`claude plugin validate` refuses a `$` passed to an imported function), so the session's start hook gives run.tsx these. */
454export type RunBoard = { projectOfRun: (workflow: string | undefined) => Promise<{ name: string; project: Project } | null> }
455let runBoard: RunBoard | undefined
456export const runBoardOf = (): RunBoard | undefined => runBoard
457
458const lockedNow = async ($: EngineInterface): Promise<boolean> => {
459 const run = await read($, runAtom)
460 const ui = await read($, uiAtom)
461 return ui.drafting === 'show' || (run.status === 'running' && overlaysProject(run, await read($, runProjectAtom), ui))
462}
463
464let flushing: Promise<string | null> = Promise.resolve(null)
465/** Kept for a moment: a drawing may have asked for the save just before the action that would have. */
466let justSaid: string | null = null
467const SAID_MS = 400
468/** Saves what was typed and not sent with Enter, as one edit, before anything else acts on the project. One at a time, in the order asked. */
469// `keep`: a field that met another session's save is kept, with its text, to be sent again onto that save.
470const flushDrafts = ($: EngineInterface, keep = false): Promise<string | null> => {
471 const run = flushing.then(async (): Promise<string | null> => {
472 if (!hasDrafts()) return null
473 const pending = drafts
474 drafts = noDrafts()
475 const ui = await read($, uiAtom)
476 let project: Project | null = await read($, projectAtom)
477 // The project typed for is not the one shown, or a run locks it: nothing can be saved, and it is said.
478 const lost = `unsaved text in ${Object.keys(pending.values).map(draftFieldWord).join(', ')} discarded`
479 if (!project || ui.status !== 'ready' || ui.name !== pending.name) {
480 $.ui.toast(`conductor: ${lost} (project ${pending.name} is no longer on the board)`)
481
482 return null
483 }
484 if (await lockedNow($)) {
485 await update($, uiAtom, held => ({ ...held, notice: `${lost} · ${held.drafting === 'show' ? DRAFT_LOCK_NOTICE : LOCK_NOTICE}` }))
486
487 return null
488 }
489 const before = project
490 const said: string[] = []
491 let titled = false
492 let label: string | undefined
493 const node = pending.id === null ? undefined : findNode(project, pending.id)
494 if (node) {
495 let patch: NodePatch = {}
496 for (const [base, text] of Object.entries(pending.values)) {
497 const part = fieldPatch(node, base, text)
498 patch = { ...patch, ...part, ...(patch.knobs || part.knobs ? { knobs: { ...patch.knobs, ...part.knobs } } : {}) }
499 }
500 const step = patchNode(project, ui, node.id, patch)
501 if (step.changed && step.project) {
502 label = step.what
503 project = step.project
504 said.push(step.what ?? `${node.id} changed`)
505 titled = patch.name !== undefined
506 }
507 }
508 if (said.length === 0) return null
509 let notice = `${said.join('; ')} · ${UNDO_HINT}`
510 let stale: StaleFile | null = null
511 try {
512 if (isSaved(ui.name)) await saveProject($, ui.name, project, before)
513 } catch (error) {
514 if (error instanceof StaleFile) stale = error
515 else notice = error instanceof InvalidFile ? invalidNotice(ui.name) : `not saved: ${reason(error)}`
516 }
517 if (stale !== null) {
518 notice = (await showSaved($, stale, before, { project, what: label ?? 'an edit' }, ui)) ?? notice
519 const theirs = await read($, projectAtom)
520 if (keep && pending.id !== null && theirs !== null && findNode(theirs, pending.id)) {
521 drafts = pending
522 notice = `not saved: ${ui.name} was changed in another session, the board shows it now · Enter: your text onto it`
523 await update($, uiAtom, held => ({ ...held, notice, editing: true, selectedId: pending.id }))
524 }
525 } else {
526 record(ui.name, before, label)
527 const saved = project
528 await update($, projectAtom, () => saved)
529 await update($, uiAtom, held => ({ ...held, notice, runCleared: true, unsaved: false, freshId: titled ? null : held.freshId }))
530 }
531 justSaid = notice
532 $.clock.after(SAID_MS, () => {
533 if (justSaid === notice) justSaid = null
534 })
535
536 return notice
537 })
538 flushing = run.catch(() => null)
539
540 return run
541}
542/** An action that left nothing said keeps what the flush said. */
543const keepSaid = async ($: EngineInterface, flushed: string | null): Promise<void> => {
544 const said = flushed ?? justSaid
545 justSaid = null
546 if (said !== null) await update($, uiAtom, held => (held.notice === null ? { ...held, notice: said } : held))
547}
548
549/** The catcher is the first stop, so the ring is there by its place but for the ways out of the detail pane. */
550const settleRing = ($: EngineInterface, tries = 1): void => {
551 $.clock.after(FOCUS_DELAY_MS, () => {
552 void (async (): Promise<void> => {
553 const ui = await read($, uiAtom)
554 if ((ui.status !== 'ready' && ui.status !== 'pick' && ui.status !== 'error') || ui.editing) return
555 const key = ui.status === 'ready' && ui.picker !== null && !(await lockedNow($)) ? pickerKey() : drawnCatcher
556 const moved = await $.ui.focus({ requestId: PROJECT_PANE_ID, key }).catch(() => ({ deny: 'no' }))
557 if (moved.deny === undefined) ringOn = key
558 else if (tries > 0) settleRing($, tries - 1)
559 })()
560 })
561}
562
563/** The ring goes to the catcher before the fields close: kept by its place, it must not be left on what takes their place. */
564const home = async ($: EngineInterface): Promise<void> => {
565 const key = drawnCatcher
566 ringTo = ''
567 const moved = await $.ui.focus({ requestId: PROJECT_PANE_ID, key }).catch(() => ({ deny: 'no' }))
568 if (moved.deny === undefined) ringOn = key
569 // Not drawn at this moment (the add list stands in its place): once it is.
570 else settleRing($)
571 await update($, uiAtom, held => (held.editing || held.freshId !== null ? { ...held, editing: false, freshId: null } : held))
572 $.ui.invalidate('ui.render')
573}
574
575/** What to land on: its key is made anew on each try, as letters typed meanwhile draw it under another. */
576type Spot = { base: string; id: string } | 'picker'
577const spotKey = (spot: Spot): string => (spot === 'picker' ? pickerKey() : fieldKey(spot.base, spot.id))
578
579/** Where the element cannot be reached at all the field is given up and `fallback` is said. */
580const landOn = async ($: EngineInterface, spot: Spot, fallback: string, tries = LAND_TRIES, last = ''): Promise<void> => {
581 const key = spotKey(spot)
582 // Said before the move is asked: a letter that reaches the element before the answer does is its text.
583 ringTo = key
584 const moved = await $.ui.focus({ requestId: PROJECT_PANE_ID, key }).catch((error: unknown) => ({ deny: reason(error) }))
585 if (moved.deny === undefined && key === spotKey(spot)) {
586 ringOn = key
587 if (ringTo === key) ringTo = ''
588 $.ui.invalidate('ui.render')
589
590 return
591 }
592 // Refused: not drawn yet, or drawn anew under another address meanwhile (letters typed on the way do that): that one counts from the start.
593 const left = key === last ? tries - 1 : LAND_TRIES
594 if (left > 0) {
595 $.clock.after(left > LAND_TRIES - 2 ? FOCUS_DELAY_MS : FOCUS_DELAY_MS * 2, () => void landOn($, spot, fallback, left, key))
596
597 return
598 }
599 if (ringTo === key) ringTo = ''
600 await update($, uiAtom, held => ({ ...held, editing: false, freshId: null, notice: fallback }))
601}
602
603/** What `e` does, for the ways that are not a key: the Down arrow from the catcher, a click on a field at rest. */
604const openFields = async ($: EngineInterface, base?: string): Promise<void> => {
605 const ui = await read($, uiAtom)
606 const project = await read($, projectAtom)
607 const node = project === null || ui.selectedId === null ? undefined : findNode(project, ui.selectedId)
608 if (ui.status !== 'ready' || !node || ui.handed || (await lockedNow($))) return
609 if (!ui.editing || ui.help > 0 || ui.picker !== null) await update($, uiAtom, held => ({ ...held, editing: true, help: 0, picker: null, detailHidden: false, confirmId: null }))
610 void landOn($, { base: base ?? firstField(node), id: node.id }, `edit: ${EDIT_HINT}`)
611}
612
613/** After a click on the graph, until the ring is on the catcher: the engine gives a letter typed on a Button to the prompt box, and the keyboard with it (`prompt.edit` makes it a key). */
614let landing = false
615/** `landing` is given up after this long, whatever became of the ring. */
616const LANDING_MS = 400
617/** Nothing tells a hook when the graph loses the keyboard a click gave it, so the pane takes the keys back at once; refused (the prompt box holds text), no key is answered (`handed`). */
618const retake = async ($: EngineInterface, picks: boolean): Promise<void> => {
619 landing = true
620 $.clock.after(LANDING_MS, () => {
621 landing = false
622 })
623 await $.ui.open(paneArgs(true)).catch(() => undefined)
624 // Asked before the fields close, or the ring would rest on what takes a field's place; a move refused while the pane's take lands is asked again below.
625 const early = picks || drawnCatcher === '' ? { deny: 'no' } : await $.ui.focus({ requestId: PROJECT_PANE_ID, key: drawnCatcher }).catch((error: unknown) => ({ deny: reason(error) }))
626 if (early.deny === undefined) ringOn = drawnCatcher
627 await update($, uiAtom, held => (held.editing || held.freshId !== null ? { ...held, editing: false, freshId: null } : held))
628 // Moving the ring is how the pane learns whether it holds the keyboard (`$.ui.panes()` asked right after the open still says no). One more try: the pane may not be drawn yet.
629 const land = async (tries: number): Promise<void> => {
630 const key = picks ? pickerKey() : drawnCatcher
631 const moved = await $.ui.focus({ requestId: PROJECT_PANE_ID, key }).catch((error: unknown) => ({ deny: reason(error) }))
632 const holds = moved.deny === undefined
633 if (!holds && tries > 0) {
634 $.clock.after(FOCUS_DELAY_MS * 2, () => void land(tries - 1))
635
636 return
637 }
638 landing = false
639 if (holds) ringOn = key
640 const now = await read($, uiAtom)
641 if (holds === now.handed) await update($, uiAtom, held => ({ ...held, handed: !holds, notice: !holds ? HANDED_NOTICE : held.notice === HANDED_NOTICE ? null : held.notice }))
642 else $.ui.invalidate('ui.render')
643 }
644 // The filter exists once the list is drawn: the ring moves there a frame later.
645 if (picks) $.clock.after(FOCUS_DELAY_MS, () => void land(1))
646 else await land(1)
647}
648
649/** Tidies the Inputs once no key has been typed for TIDY_MS: a letter typed in the frame an Input is drawn anew would be dropped. */
650const tidySoon = ($: EngineInterface): void => {
651 const mine = ++typingSeq
652 $.clock.after(TIDY_MS, () => {
653 if (mine !== typingSeq) return
654 let tidied = false
655 if (caught.taken > CATCH_FULL && caught.element === drawnCatcher) {
656 catchGen++
657 tidied = true
658 }
659 if (doored.taken > 0) {
660 doorGen++
661 doored = { element: '', taken: 0 }
662 tidied = true
663 }
664 // Drawn anew, a field keeps the cursor of the one before it, short of the end by the letters added. The ring is
665 // stepped off it and on again: landing puts the cursor at the end.
666 const at = ringOn
667 const again = (spot: Spot): void => {
668 const off = $.ui.focus({ requestId: PROJECT_PANE_ID, key: drawnCatcher })
669 void off.then(() => landOn($, spot, `edit: ${EDIT_HINT}`)).catch(() => undefined)
670 }
671 if (Object.entries(pins).some(([element, pin]) => pin.head !== '' && isField(element))) {
672 redrawFields()
673 tidied = true
674 const [base = '', id = ''] = (at ?? '').replace(/#\d+$/, '').split('@')
675 if (at !== undefined && isField(at)) again({ base, id })
676 }
677 if (tidied) $.ui.invalidate('ui.render')
678 })
679}
680const runContext = async ($: EngineInterface): Promise<RunContext> => {
681 const now = await read($, runAtom)
682 const ui = await read($, uiAtom)
683 const held = overlaysProject(now, await read($, runProjectAtom), ui)
684 // A draft being laid out locks the project as a run does.
685 const laying = ui.drafting === 'show'
686
687 return { ...(held ? { run: now, locked: now.status === 'running' || laying } : laying ? { locked: true } : {}), ...(laying ? { drafting: true } : {}), ...(graphBox ? { graph: graphBox } : {}) }
688}
689
690/** `kept` is the project's undo history from before the step. */
691const store = async ($: EngineInterface, step: Step, before: Project | null, kept: History | undefined): Promise<Shown> => {
692 if (!step.changed || !step.project) return step
693 const name = step.ui.name
694 const board = before?.name === name ? before : null
695 let notice: string | undefined
696 try {
697 if (isSaved(name)) await saveProject($, name, step.project, board)
698 } catch (error) {
699 if (error instanceof InvalidFile) notice = invalidNotice(name)
700 else if (!(error instanceof StaleFile)) notice = `not saved: ${reason(error)}`
701 else {
702 // An undo or redo has moved the history already, for a step that is not taken; it is not offered again.
703 const travelled = board !== null && histories[name] !== kept
704 if (travelled) {
705 if (kept === undefined) delete histories[name]
706 else histories[name] = kept
707 }
708 const refused = !travelled && step.what !== undefined ? { project: step.project, what: step.what } : null
709 return takeSaved(error, board, refused, step.ui)
710 }
711 }
712 if (step.what !== undefined) record(step.ui.name, before, step.what)
713
714 return { project: step.project, ui: notice === undefined ? step.ui : { ...step.ui, notice } }
715}
716
717const beat = ($: EngineInterface): void => {
718 void update($, nudgeAtom, nudge => nudge + 1)
719}
720
721const themeOf = async ($: EngineInterface): Promise<string | undefined> => {
722 const now = Date.now()
723 if (now - themeRead.at < THEME_MS) return themeRead.theme
724 const row = (await $.config.list().catch(() => [])).find(one => one.key === 'theme')
725 themeRead = { at: now, theme: typeof row?.value === 'string' ? row.value : undefined }
726
727 return themeRead.theme
728}
729
730/** Started by the drawing that shows the splash; a reload in the middle of it starts it again. */
731const startSplash = ($: EngineInterface): void => {
732 if (splashing) return
733 splashing = true
734 $.clock.after(SPLASH_MS + SPLASH_REST_MS, () => {
735 // Given back: a /clear starts the session's state over (the splash is unseen again) while this module lives on.
736 splashing = false
737 void update($, splashedAtom, () => true).then(() => settleRing($))
738 })
739}
740
741const commit = async ($: EngineInterface, make: (project: Project | null, held: ProjectUi, context: RunContext) => Step): Promise<Step> => {
742 const before = await read($, projectAtom)
743 const held = await read($, uiAtom)
744 const kept = histories[held.name]
745 const step = make(before, held, await runContext($))
746 const shown = await store($, step, before, kept)
747 if (shown.project !== before) await update($, projectAtom, () => shown.project)
748 if (shown.ui !== held) await update($, uiAtom, () => shown.ui)
749
750 return { ...step, ...shown }
751}
752
753/** Polls the prompt box while a request waits in it or the keys are off (`handed`): once it is empty the line goes and the keys are keys again. */
754const watchBox = ($: EngineInterface): void => {
755 if (boxWatched) return
756 boxWatched = true
757 const look = (): void => {
758 $.clock.after(BOX_POLL_MS, () => {
759 void (async (): Promise<void> => {
760 const ui = await read($, uiAtom)
761 const waits = ui.handed || isRequestNotice(ui.notice)
762 const box = waits ? await $.prompt.read().catch(() => ({ text: '', cursor: 0 })) : null
763 if (box !== null && box.text.trim() !== '') return look()
764 boxWatched = false
765 if (waits) await update($, uiAtom, held => ({ ...held, handed: false, notice: (isRequestNotice(held.notice) || held.notice === HANDED_NOTICE) ? null : held.notice }))
766 })()
767 })
768 }
769 look()
770}
771
772const MINIMIZE_WORDS: readonly string[] = ['min', 'minimize']
773const EXPAND_WORDS: readonly string[] = ['max', 'expand']
774/** A Button's hotkey has no case, so `M` presses it too. */
775const EXPAND_ELEMENT = 'conductor-expand'
776const EXPAND_HOTKEY = 'm'
777/** The strip's cells below which the band drops its focus hint. */
778const BAND_HINT_MIN = 48
779const STRIP_TONES: Record<StripTone, string> = { text: TEXT, faded: FADED, claude: 'claude', success: 'success', error: 'error' }
780/** The run's project as read from its file, for a band whose board has another one open; its file is locked while the run is on. */
781let stripProject: { name: string; runId: string | undefined; project: Project | null } | null = null
782/** The terminal's size at which the band last opened the pane by itself: not tried again until the size changes. */
783let autoTried = ''
784
785/** Until the pane is gone its drawings ask for no other minimize, and do not take the pane back. */
786let minimizing = false
787/** The pane is given this long to be drawn with the room it has before a pane short of room is minimized. */
788const MINIMIZE_DELAY_MS = 32
789/** Opened by the person from the band: short of room it stays and says why, since a dock can be widened only while it is on screen. */
790let heldOpen = false
791
792/** The band shows a run's progress, so the person minimizes only while one is on, or while a replay's is on the board. */
793const MINIMIZE_IDLE = 'minimize: the designer minimizes while a workflow runs or replays'
794const minimizes = (run: RunState, over: boolean): boolean => run.status === 'running' || (over && runTracker?.replayed() === true)
795const canMinimize = async ($: EngineInterface): Promise<boolean> => {
796 const run = await read($, runAtom)
797 return minimizes(run, overlaysProject(run, await read($, runProjectAtom), await read($, uiAtom)))
798}
799
800/** From a clock callback: a drawing asks for it too, and a drawing closes nothing. */
801const minimize = ($: EngineInterface, by: Exclude<Minimized, 'no'>, why: CompactWhy | null = null): void => {
802 if (minimizing) return
803 minimizing = true
804 heldOpen = false
805 $.clock.after(by === 'auto' ? MINIMIZE_DELAY_MS : 0, () => {
806 void (async (): Promise<void> => {
807 await flushDrafts($)
808 await update($, uiAtom, held => (held.editing || held.picker !== null || held.help > 0 ? { ...held, editing: false, freshId: null, picker: null, help: 0 } : held))
809 await update($, shellAtom, () => ({ minimized: by, why }))
810 await $.ui.close({ id: PROJECT_PANE_ID }).catch(() => undefined)
811 })()
812 .catch(() => undefined)
813 .then(() => {
814 minimizing = false
815 $.ui.invalidate('ui.render')
816 })
817 })
818}
819
820/** `asked` opens the pane with the keyboard (a key or a click), else without (the terminal was widened); a pane still short of room minimizes itself anew. */
821const expand = async ($: EngineInterface, asked: boolean, columns?: number): Promise<void> => {
822 terminalColumns = columns ?? terminalColumns
823 heldOpen = asked
824 const opened = await $.ui.open(paneArgs(asked)).catch(() => undefined)
825 if (opened?.isPlaced === false) return
826 // A press in the band holds the keyboard: the pane is shown without it and takes the keys once drawn, as after a click on the graph.
827 if (asked) $.clock.after(FOCUS_DELAY_MS * 2, () => void retake($, false).catch(() => undefined))
828}
829
830const stripProjectOf = async ($: EngineInterface, name: string, runId: string | undefined): Promise<Project | null> => {
831 if (stripProject?.name === name && stripProject.runId === runId) return stripProject.project
832 const parsed = isSaved(name) ? parseProject(await $.fs.read(projectFile(await $.session.root(), name)).catch(() => '')) : null
833 stripProject = { name, runId, project: parsed?.ok === true ? parsed.project : null }
834 return stripProject.project
835}
836
837/** A pane opened with nobody asking, in a terminal too narrow for it to be placed: the designer is in the band instead. */
838const bandIfWaiting = async ($: EngineInterface, opened: { isPlaced: boolean } | undefined): Promise<void> => {
839 if (opened?.isPlaced === false) await update($, shellAtom, held => (held.minimized === 'no' ? { minimized: 'auto' as const, why: 'narrow' as const } : held))
840}
841
842const say = async ($: EngineInterface, notice: string): Promise<void> => {
843 await update($, uiAtom, held => ({ ...held, notice }))
844}
845
846/** The hand-off is left with the offer tool, which the sentence tells Claude to call first. False where there is nothing to hand off. */
847const handOff = async ($: EngineInterface, name: string): Promise<boolean> => {
848 const shown = await read($, uiAtom)
849 const path = projectFile(await $.session.root(), name)
850 // A template nobody edited yet is on the board only: handing it off is what saves it.
851 const onBoard = shown.name === name && shown.status === 'ready' ? await read($, projectAtom) : null
852 if (onBoard !== null && !(await $.fs.exists(path).catch(() => true))) await saveProject($, name, onBoard, null).catch(() => undefined)
853 if (!(await $.fs.exists(path).catch(() => false))) return false
854 if (onBoard !== null && shown.unsaved) await update($, uiAtom, held => ({ ...held, unsaved: false }))
855 const parsed = parseProject(await $.fs.read(path).catch(() => ''))
856 if (!parsed.ok || isBlank(parsed.project)) return false
857 runTracker?.handoff(handoffOf(name, parsed.project))
858 offerHanded(name)
859 await update($, uiAtom, held => ({ ...held, follow: true, runCleared: false, notice: held.notice?.startsWith('run: ') ? null : held.notice }))
860
861 return true
862}
863
864/** No call hands the keyboard from a pane to the prompt, so the pane is closed and shown again without it; where the keys stayed, none is acted on until the person takes them (`handed`). */
865const request = async ($: EngineInterface, kind: 'run' | 'ask' | 'draft'): Promise<void> => {
866 const ui = await read($, uiAtom)
867 const now = await read($, projectAtom)
868 if (kind === 'run' && !isSaved(ui.name)) return say($, 'run: a replay is not a saved project, there is nothing to hand off')
869 if (kind === 'run' && (now === null || isBlank(now))) return say($, 'run: the project is empty, add a block first')
870 const line = kind === 'run' ? handoffPrompt(ui.name) : kind === 'ask' ? reviewPrompt(ui.name) : draftLine()
871 const fill = async (): Promise<boolean> => {
872 const filled = await $.prompt.fill({ text: line }).catch(() => ({ isFilled: false }))
873 await say($, kind === 'run' ? runNotice(line, filled.isFilled) : kind === 'ask' ? askNotice(line, filled.isFilled) : draftNotice(line, filled.isFilled))
874 if (filled.isFilled) watchBox($)
875
876 return filled.isFilled
877 }
878 if (kind === 'run') {
879 // The mod's own prompt does not come by its `prompt.submit` hook: the hand-off is made here.
880 if (!(await handOff($, ui.name))) return say($, `run: ${ui.name} could not be handed off`)
881 const problems = now === null ? null : preflightLine(now)
882 if (now !== null) $.ui.toast(`conductor: ${ui.name} handed to Claude${problems === null ? '' : ` · ${problems}`}`)
883 // From a clock callback, never from inside the chain of keys, which it would hold for the turn.
884 // Refused (the prompt box holds text): the request is left there for the person to send.
885 $.clock.after(SUBMIT_DELAY_MS, () => {
886 const submitted = $.prompt.submit({ text: line, asUser: true })
887 void submitted.then(entered => (entered.drop === undefined ? undefined : fill())).catch(() => fill())
888 })
889 await $.ui.close({ id: PROJECT_PANE_ID }).catch(() => undefined)
890 await $.ui.open(paneArgs(false)).catch(() => undefined)
891
892 return
893 }
894 if (!(await fill())) return
895 await $.ui.close({ id: PROJECT_PANE_ID }).catch(() => undefined)
896 await $.ui.open(paneArgs(false)).catch(() => undefined)
897 // The ring can be moved only in a site that holds the keyboard: if it still can, the keys did not go.
898 $.clock.after(FOCUS_DELAY_MS * 2, () => {
899 const focused = $.ui.focus({ requestId: PROJECT_PANE_ID, key: drawnCatcher })
900 void focused
901 .catch(() => ({ deny: 'no' }))
902 .then(moved => (moved.deny === undefined ? update($, uiAtom, held => ({ ...held, handed: true, notice: HANDED_NOTICE })) : undefined))
903 .then(() => watchBox($))
904 })
905}
906
907const stopDraftTicker = (): void => {
908 draftTicker?.cancel()
909 draftTicker = null
910}
911
912const draftBeat = async ($: EngineInterface): Promise<void> => {
913 const ui = await read($, uiAtom)
914 if ((ui.drafting ?? null) === null) return stopDraftTicker()
915 await update($, draftBeatAtom, beats => beats + 1)
916 const project = await read($, projectAtom)
917 const shownSoFar = ui.reveal ?? null
918 if (ui.drafting !== 'show' || shownSoFar === null || project === null) return
919 const rows = flatten(project)
920 const upTo = shownSoFar + Math.max(1, Math.ceil(rows.length / REVEAL_STEPS))
921 const fresh = rows.slice(shownSoFar, upTo).map(row => row.node.id)
922 const done = upTo >= rows.length
923 let seq = 0
924 await update($, uiAtom, held => {
925 if (held.drafting !== 'show' || held.reveal !== shownSoFar) return held
926 seq = (held.flash?.seq ?? 0) + 1
927 return { ...held, reveal: done ? null : upTo, selectedId: done ? (project.nodes[0]?.id ?? null) : (fresh.at(-1) ?? held.selectedId), flash: { ids: fresh, seq } }
928 })
929 if (done && seq > 0) {
930 $.clock.after(FLASH_CLEAR_MS, () => {
931 void update($, uiAtom, held => clearFlash(held, seq))
932 })
933 }
934}
935
936const startDraftTicker = ($: EngineInterface): void => {
937 if (draftTicker !== null) return
938 draftTicker = $.clock.every(BEAT_MS, () => {
939 void draftBeat($).catch(() => undefined)
940 })
941}
942
943/** The keyboard stays in the prompt, where Claude's questions are answered. */
944const beginDraft = async ($: EngineInterface): Promise<void> => {
945 await flushDrafts($)
946 await update($, draftBeatAtom, () => 0)
947 await update($, uiAtom, held => ({ ...held, drafting: 'wait' as const, reveal: null, editing: false, freshId: null, picker: null, confirmId: null, handed: false, notice: null }))
948 await $.ui.open(paneArgs(false)).catch(() => undefined)
949 startDraftTicker($)
950}
951
952/** With `keys` a landed project's board takes the keyboard, where nothing is being typed in the prompt. */
953const endDraft = async ($: EngineInterface, keys: boolean): Promise<void> => {
954 const ui = await read($, uiAtom)
955 if ((ui.drafting ?? null) === null) return
956 stopDraftTicker()
957 const landed = ui.drafting === 'show'
958 await update($, uiAtom, held => ({ ...held, drafting: null, reveal: null, flash: held.flash ? { ids: [], seq: held.flash.seq } : null }))
959 $.ui.invalidate('ui.render')
960 if (!landed || !keys) return
961 const box = await $.prompt.read().catch(() => ({ text: '?', cursor: 0 }))
962 if (box.text.trim() !== '') return
963 await $.ui.open(paneArgs(true)).catch(() => undefined)
964 settleRing($)
965}
966
967/** The ring is claimed for the catcher first: a letter typed on Enter's heels is then no text of the field. */
968const saveField = async ($: EngineInterface, id: string, base: string, value: string): Promise<void> => {
969 ringOn = drawnCatcher
970 savedField = { element: fieldKey(base, id), value, taken: 0 }
971 const ui = await read($, uiAtom)
972 const mine = drafts.id === id && drafts.name === ui.name
973 drafts = { name: ui.name, id, values: { ...(mine ? drafts.values : {}), [base]: value } }
974 await home($)
975 await flushDrafts($, true)
976 if (drafts.id === id && drafts.name === ui.name) await landOn($, { base, id }, (await read($, uiAtom)).notice ?? '')
977}
978
979const pick = async ($: EngineInterface, choice: Partial<PickRow>): Promise<void> => {
980 await flushDrafts($)
981 const step = await commit($, (before, held, context) => pickBlock(before, held, choice, context))
982 // A block opened on its kinds: the filter is drawn anew, empty, for the kinds' list.
983 if (step.ui.picker?.block !== undefined && step.ui.picker.query === '') pickGen++
984 const fresh = step.changed && step.ui.editing ? step.ui.freshId : null
985 if (fresh !== null) void landOn($, { base: NAME_FIELD, id: fresh }, `edit: ${EDIT_HINT}`)
986 else if (!step.ui.picker) await home($)
987}
988
989const startFrom = async ($: EngineInterface, templateId: string): Promise<void> => {
990 const held = await read($, uiAtom)
991 const root = await $.session.root()
992 // The name was chosen when the list opened: a project saved under it since (a rename) is never written over.
993 const taken = isSaved(held.name) && (await $.fs.exists(projectFile(root, held.name)).catch(() => false))
994 const step = startProject(taken ? { ...held, name: freeName(await savedNames($, root)) } : held, templateId)
995 if (!step.project) return
996 // Not written yet: the first edit (or handing it off) saves it. A project looked at and left leaves no file.
997 delete histories[step.ui.name]
998 await update($, projectAtom, () => step.project)
999 await update($, uiAtom, () => ({ ...step.ui, help: 0, notice: isDefaultName(step.ui.name) ? `named ${step.ui.name} for now · once it is saved, p lists it and e renames it there` : null }))
1000 settleRing($)
1001}
1002
1003const savedNames = async ($: EngineInterface, root: string): Promise<string[]> => {
1004 const entries = await $.fs.list(`${root.replace(/\/+$/, '')}/${PROJECT_DIR}`).catch(() => [])
1005
1006 return entries
1007 .filter(entry => entry.kind === 'file' && entry.name.endsWith('.json'))
1008 .map(entry => entry.name.slice(0, -'.json'.length))
1009 .filter(isSaved)
1010 .sort()
1011}
1012
1013const readSaved = async ($: EngineInterface, root: string): Promise<SavedProject[]> => {
1014 const dir = `${root.replace(/\/+$/, '')}/${PROJECT_DIR}`
1015 const names = await savedNames($, root)
1016 savedPast = Math.max(0, names.length - SAVED_MAX)
1017 const saved: SavedProject[] = []
1018 for (const one of names.slice(0, SAVED_MAX)) {
1019 const text = await $.fs.read(`${dir}/${one}.json`).catch(() => '')
1020 const parsed = parseProject(text)
1021 previews[one] = parsed.ok ? parsed.project : null
1022 saved.push(savedEntry(one, parsed))
1023 }
1024
1025 return saved
1026}
1027
1028const openProjectList = async ($: EngineInterface): Promise<void> => {
1029 await flushDrafts($)
1030 const held = await read($, uiAtom)
1031 if (held.status !== 'ready' && held.status !== 'error') return
1032 const project = await read($, projectAtom)
1033 const root = await $.session.root()
1034 const saved = await readSaved($, root)
1035 behind = project !== null && held.status === 'ready' ? { project, ui: { ...held, editing: false, freshId: null, picker: null, confirmId: null, help: 0, notice: null } } : null
1036 // A template picked there starts a new project, under a name no saved one has.
1037 const started = openProject(freeName(await savedNames($, root)), undefined, held)
1038 await update($, projectAtom, () => null)
1039 await update($, uiAtom, () => ({ ...started.ui, saved, startMark: Math.max(0, saved.findIndex(one => one.name === held.name)), back: held.name }))
1040 settleRing($)
1041}
1042
1043const closeProjectList = async ($: EngineInterface): Promise<void> => {
1044 const held = await read($, uiAtom)
1045 const name = held.back ?? null
1046 if (held.status !== 'pick' || name === null) return
1047 const kept = behind !== null && behind.ui.name === name ? behind : null
1048 const text = isSaved(name) ? await $.fs.read(projectFile(await $.session.root(), name)).catch(() => undefined) : undefined
1049 const step = typeof text === 'string' ? openProject(name, text, held) : null
1050 behind = null
1051 if (step !== null && step.project !== null) {
1052 const project = step.project
1053 loadedDisk(name, project)
1054 const viewRootId = kept !== null && kept.ui.viewRootId !== null && findNode(project, kept.ui.viewRootId) ? kept.ui.viewRootId : null
1055 await update($, projectAtom, () => project)
1056 await update($, uiAtom, () => ({ ...step.ui, viewRootId, carousels: kept?.ui.carousels ?? {}, runCleared: kept?.ui.runCleared ?? false, follow: kept?.ui.follow ?? true }))
1057 } else if (step !== null) {
1058 // Its file is no project: said as it is when opened by name.
1059 await update($, projectAtom, () => null)
1060 await update($, uiAtom, () => step.ui)
1061 } else if (kept !== null) {
1062 await update($, projectAtom, () => kept.project)
1063 await update($, uiAtom, ui => ({ ...kept.ui, detailHidden: ui.detailHidden === true, picks: ui.picks ?? {} }))
1064 } else {
1065 await update($, uiAtom, ui => ({ ...ui, back: null, notice: `${name} is gone: it could not be read` }))
1066
1067 return
1068 }
1069 settleRing($)
1070}
1071
1072const openSaved = async ($: EngineInterface, name: string): Promise<void> => {
1073 const held = await read($, uiAtom)
1074 const text = await $.fs.read(projectFile(await $.session.root(), name)).catch(() => undefined)
1075 const step = openProject(name, typeof text === 'string' ? text : undefined, held)
1076 if (step.ui.status === 'pick') {
1077 await update($, uiAtom, ui => ({ ...ui, notice: `${name} is gone: it could not be read` }))
1078
1079 return
1080 }
1081 if (step.project !== null) loadedDisk(name, step.project)
1082 await update($, projectAtom, () => step.project)
1083 await update($, uiAtom, () => step.ui)
1084 settleRing($)
1085}
1086
1087const FIXTURES: Record<string, ReplayFixture> = { 'review-41': review41, 'partial-29': partial29 }
1088
1089/** A replay would take the place of a real run, whose agents would then be counted nowhere. Null when one may start. */
1090const replayRefusal = (): string | null => {
1091 if (runTracker === undefined || !runTracker.busy()) return null
1092
1093 return runTracker.awaitsRun() ? 'a project handed to Claude waits for its run: a replay can start once that run ends' : 'a workflow is running: a replay can start once the run ends'
1094}
1095
1096/** The project is named `replay-<template>` and lives in the session only: no file is written, and none is listed. */
1097const replayOver = async ($: EngineInterface, templateId: string): Promise<void> => {
1098 const template = TEMPLATES.find(one => one.id === templateId)
1099 if (!template || runTracker === undefined) return
1100 const refusal = replayRefusal()
1101 if (refusal !== null) return say($, refusal)
1102 const name = `${SCRATCH_PREFIX}${template.id}`
1103 const made: Project = { ...template.make(), name }
1104 // Another project under the same name: what could be undone in the one before is not its history.
1105 delete histories[name]
1106 behind = null
1107 await update($, projectAtom, () => made)
1108 await update($, uiAtom, held => ({ ...carryUi(held, initialUi()), name, status: 'ready' as const, selectedId: made.nodes[0]?.id ?? null, notice: 'replaying a made-up run: token counts are made up, nothing is saved' }))
1109 settleRing($)
1110 // A replay reuses its run id: the clock of the one before must not time this one.
1111 await update($, timesAtom, () => initialTimes())
1112 if (runTracker.replay(replayProjectEvents(made, name), 'fast', handoffOf(name, made))) return
1113 // A run began while the board was put up: the tracker kept it.
1114 const late = replayRefusal()
1115 if (late !== null) await say($, late)
1116}
1117
1118const replayRecording = async ($: EngineInterface, id: string): Promise<void> => {
1119 const fixture = FIXTURES[id]
1120 if (!fixture || runTracker === undefined) return
1121 const refusal = replayRefusal()
1122 if (refusal !== null) return say($, refusal)
1123 runTracker.replay(replayEvents(id, fixture), 'fast')
1124 const opened = await $.ui.open({ id: PANE_ID, title: PANE_TITLE }).catch(() => undefined)
1125 if (opened?.isPlaced) runTracker.paneOpened()
1126 await say($, `replaying ${id} in the run view: token counts are made up`)
1127}
1128
1129const openEntry = async ($: EngineInterface, at?: number): Promise<void> => {
1130 const ui = await read($, uiAtom)
1131 if (ui.status !== 'pick') return
1132 const entry = startEntries(ui.saved ?? [])[at ?? ui.startMark ?? 0]
1133 if (!entry) return
1134 if (entry.kind === 'replay') return replayOver($, entry.id)
1135 if (entry.kind === 'recording') return replayRecording($, entry.id)
1136 const back = ui.back ?? null
1137 if (entry.kind === 'saved' && entry.id === back) return closeProjectList($)
1138 // A project started from a template and never edited has no file: left for another, nothing of it is kept.
1139 const dropped = back !== null && behind !== null && behind.ui.name === back && behind.ui.unsaved ? back : null
1140 if (entry.kind === 'saved') await openSaved($, entry.id)
1141 else await startFrom($, entry.id)
1142 const now = await read($, uiAtom)
1143 if (now.status !== 'ready') return
1144 behind = null
1145 if (dropped !== null && now.notice === null) await say($, `${dropped} was not saved: nothing of it was kept`)
1146}
1147
1148const startKey = async ($: EngineInterface, key: string): Promise<boolean> => {
1149 const ui = await read($, uiAtom)
1150 if (key === ENTER) {
1151 await openEntry($)
1152
1153 return false
1154 }
1155 const op = KEY_OPS[key]
1156 if (op === 'minimize') {
1157 if (!(await canMinimize($))) {
1158 await say($, MINIMIZE_IDLE)
1159
1160 return true
1161 }
1162 minimize($, 'person')
1163
1164 return false
1165 }
1166 const helping = (ui.help ?? 0) > 0
1167 if (op === 'up' || op === 'down') beat($)
1168 if (op === 'up' || op === 'down') await update($, uiAtom, held => ({ ...moveStartMark(held, op === 'up' ? -1 : 1), help: 0 }))
1169 else if (op === 'help') await update($, uiAtom, held => ({ ...held, notice: null, help: ((held.help ?? 0) % HELP_PAGES) + 1 }))
1170 else if (op === 'remove' && helping) await update($, uiAtom, held => ({ ...held, help: 0 }))
1171 else if ((op === 'projects' || op === 'back') && (ui.back ?? null) !== null) {
1172 await closeProjectList($)
1173
1174 return false
1175 } else await say($, unboundNotice(key))
1176
1177 return true
1178}
1179
1180/** Resolves to false when the keys typed with it are not to be applied (the keyboard went to the prompt, nothing is on the board). */
1181/** `f`: the board is written over a file that holds no valid project, once the person asks. */
1182const overwriteFile = async ($: EngineInterface, name: string): Promise<void> => {
1183 const project = await read($, projectAtom)
1184 if (!heldOver.has(name) || project === null) return say($, `f: ${name} is saved, there is nothing to write over`)
1185 try {
1186 await saveProject($, name, project, project, true)
1187 } catch (error) {
1188 // Made valid since: by another session, so the board takes it as any save does.
1189 if (error instanceof StaleFile) return void (await showSaved($, error, project, null, await read($, uiAtom)))
1190 return say($, `not saved: ${reason(error)}`)
1191 }
1192 await update($, uiAtom, held => ({ ...held, unsaved: false, runCleared: true }))
1193 await say($, `wrote the board over ${name}.json`)
1194}
1195
1196const runKey = async ($: EngineInterface, key: string): Promise<boolean> => {
1197 const ui = await read($, uiAtom)
1198 const project = await read($, projectAtom)
1199 if (ui.drafting === 'wait') return false
1200 if (ui.status === 'pick') return startKey($, key)hooks/offer.tsx 159 lines1import type { EngineInterface, On } from 'claude-code'
2
3import { offerBrief } from '../src/project/chat'
4import { LAST_SCRIPTS_STORE, buildHandoff, lastScripts, newestScript, savedWorkflowFile } from '../src/project/handoff'
5import type { HandoffScript, LastRun, ScriptFile } from '../src/project/handoff'
6import { isBlank, parseProject } from '../src/project/model'
7import {
8 DISMISSED_RESULT,
9 OFFER_HEADER,
10 OFFER_OPTIONS,
11 OFFER_QUESTION,
12 OFFER_TOOL_DESCRIPTION,
13 OFFER_TOOL_FULL_NAME,
14 OFFER_TOOL_NAME,
15 handedResult,
16 offerChoice,
17 standardResult,
18 typedResult,
19 waitingResult,
20} from '../src/project/offer'
21import { projectFile } from '../src/project/session'
22import type { Tracker } from '../src/run/tracker'
23
24/** Per project, its last run in this session, whose script is the one remembered: a resume works only in the session that ran it. */
25const lastRuns: Record<string, LastRun> = {}
26
27export const offerRan = (name: string, run: LastRun): void => {
28 lastRuns[name] = run
29}
30
31const fileOf = async ($: EngineInterface, path: string | undefined): Promise<ScriptFile | null> => {
32 if (path === undefined) return null
33 const stat = await $.fs.stat(path).catch(() => undefined)
34
35 return stat?.kind === 'file' ? { path, mtimeMs: stat.mtimeMs } : null
36}
37
38/** The last run's script in the session folder, or the copy saved in the repository: the newer, as the session's is cleared after a while. */
39const scriptOf = async ($: EngineInterface, name: string): Promise<HandoffScript> => {
40 const last = lastScripts(await $.store.get(LAST_SCRIPTS_STORE).catch(() => undefined))[name]
41 const path = newestScript(await fileOf($, last), await fileOf($, savedWorkflowFile(await $.session.root(), name)))
42 // The run is named only with the script it ran: the saved copy may be another.
43 if (path === null) return { path: null }
44
45 return path === last ? { path, run: lastRuns[name] } : { path }
46}
47
48/** "Conductor" was answered and the draft it asks Claude for has not landed yet. A module variable: it lasts a turn. */
49let offered = false
50
51/** Whether the project being written is the one the person just asked for in the question; asking spends it. */
52export const takeOffered = (): boolean => {
53 const was = offered
54 offered = false
55
56 return was
57}
58
59/** While it waits the question is not asked again: Claude would draft a second project, or a script the board knows nothing of. */
60let waiting: string | null = null
61/** The tool already answered in this turn that a project waits: a second call is for another workflow, and asks. */
62let answered = false
63
64/** `$` does not cross files, so project.tsx's session.start hook gives this file its board, as it gives run.tsx its `RunBoard`. */
65export type OfferBoard = { drafting: () => Promise<void> }
66let offerBoard: OfferBoard | undefined
67export const setOfferBoard = (board: OfferBoard): void => {
68 offerBoard = board
69}
70
71export const offerDrafted = (name: string): void => {
72 waiting = name
73}
74
75/** The project handed off on the board (`r`) whose hand-off Claude has not been given yet: the tool's next answer is it. */
76let handing: string | null = null
77
78export const offerHanded = (name: string): void => {
79 handing = name
80 if (waiting === name) waiting = null
81}
82
83/** Handed off or run: project `name` waits for no approval. */
84export const offerSettled = (name: string): void => {
85 if (waiting === name) waiting = null
86}
87
88/** A prompt was sent: a "Conductor" answer whose draft never came is over with its turn, and so is what the tool said in it. */
89export const offerPrompted = (): void => {
90 offered = false
91 answered = false
92 handing = null
93}
94
95export const registerOffer = (on: On, tracker: Tracker): void => {
96 // Not deferred: Claude calls a tool before a workflow only when its description is in front of it.
97 // The matcher is always true: run.tsx holds the unmatched session.start, project.tsx the one on `cwd`.
98 on('session.start', { isInteractive: [true, false] }, async ($, e, next) => {
99 await $.tool.register({ name: OFFER_TOOL_NAME, description: OFFER_TOOL_DESCRIPTION, isDeferred: false })
100
101 return next(e)
102 })
103 // A cleared or resumed conversation is another session: no run of it can be resumed from there.
104 on('session.end', { reason: ['clear', 'resume'] }, async (_$, e, next) => {
105 for (const name of Object.keys(lastRuns)) delete lastRuns[name]
106
107 return next(e)
108 })
109
110 // Claude always gets a result to act on, never a throw and never a deny: it does not take instructions from a refusal.
111 on('tool.call', { tool: OFFER_TOOL_FULL_NAME }, async ($, e) => {
112 // A workflow's own agents, and any subagent: the person is asked by the conversation, once.
113 if (e.agentId !== undefined) return { result: standardResult('subagent') }
114 // The project the person just handed off on the board: its hand-off, once.
115 if (handing !== null) {
116 const name = handing
117 handing = null
118 const root = await $.session.root()
119 const path = projectFile(root, name)
120 const parsed = parseProject(await $.fs.read(path).catch(() => ''))
121 if (parsed.ok && !isBlank(parsed.project)) {
122 return { result: handedResult(buildHandoff({ ...parsed.project, name }, path, await scriptOf($, name)).context.join('\n')) }
123 }
124 }
125 // The script being written is the project the person approved on the board: that was their answer.
126 if (tracker.awaitsRun()) return { result: standardResult('handoff') }
127 // A `-p` run draws nowhere: nobody reads a question, and nobody would review a project.
128 const surfaces = await $.session.surfaces().catch(() => undefined)
129 if (surfaces !== undefined && surfaces.length === 0) return { result: standardResult('headless') }
130 // The project drafted after the last "Conductor" answer still waits for the person: said once a turn, with what an
131 // approval given in chat is carried out by. Gone, emptied or said already: the question is asked as for any workflow.
132 if (waiting !== null && !answered) {
133 const root = await $.session.root()
134 const path = projectFile(root, waiting)
135 const parsed = parseProject(await $.fs.read(path).catch(() => ''))
136 if (parsed.ok && !isBlank(parsed.project)) {
137 answered = true
138 return { result: waitingResult(waiting, buildHandoff({ ...parsed.project, name: waiting }, path, await scriptOf($, waiting)).context.join('\n')) }
139 }
140 }
141 waiting = null
142
143 let answer: string
144 try {
145 answer = await $.ui.ask(OFFER_QUESTION, { options: OFFER_OPTIONS, header: OFFER_HEADER })
146 } catch {
147 return { result: DISMISSED_RESULT }
148 }
149 const picked = offerChoice(answer)
150 if (picked === null) return { result: answer.trim() === '' ? DISMISSED_RESULT : typedResult(answer) }
151 if (picked === 'standard') return { result: standardResult('chosen') }
152 offered = true
153 // project.tsx shows the splash until the project lands.
154 await offerBoard?.drafting().catch(() => undefined)
155
156 return { result: offerBrief() }
157 })
158}
159hooks/run.tsx 335 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On } from 'claude-code'
3
4import { visualizeBrief } from '../src/project/chat'
5import { LAST_SCRIPTS_STORE, lastScripts, noteScript, saveAsk, savedWorkflowFile } from '../src/project/handoff'
6import { parseProject } from '../src/project/model'
7import {
8 SAVE_HEADER,
9 SAVE_OPTIONS,
10 VISUALIZE_HEADER,
11 VISUALIZE_OPTIONS,
12 VISUALIZE_QUESTION,
13 reusedToast,
14 saveChoice,
15 saveFailedToast,
16 saveQuestion,
17 savedToast,
18 visualizeChoice,
19 visualizeTyped,
20} from '../src/project/offer'
21import { PROJECT_PANE_ID, bareTarget, projectFile, projectName, endRun, followRun, handoffOf, initialTimes, initialUi, isSaved, stampTimes } from '../src/project/session'
22import { emptyRunState } from '../src/run/events'
23import type { RunState } from '../src/run/events'
24import { usageTotal } from '../src/run/journal'
25import type { Handoff, RunEnded, Tracker } from '../src/run/tracker'
26import { buildRunRows, togglePhase } from '../src/ui/rail'
27import type { Part, Row } from '../src/ui/rail'
28import { initialShell } from '../src/ui/compact'
29import { FADED, GLYPH, PANE_ID, PANE_TITLE, TEXT } from '../src/ui/theme'
30
31import { paneArgs, runBoardOf } from './project'
32import { offerRan, offerSettled } from './offer'
33
34const PLACEHOLDER = 'no workflow running yet'
35const MAX_WIDTH = 96
36const MAX_ROWS = 400
37// Both hooks modules declare the run's atoms (an atom must be spelled in the file that reads it):
38// run.tsx writes them through the tracker, project.tsx reads them.
39const runAtom = atom({ plugin: 'workflow-conductor', key: 'run' } as const, emptyRunState())
40const clockAtom = atom({ plugin: 'workflow-conductor', key: 'runClock' } as const, 0)
41/** The project the tracked run belongs to (handed off, or named as it); null for any other run. */
42const runProjectAtom = atom({ plugin: 'workflow-conductor', key: 'runProject' } as const, null)
43const uiAtom = atom({ plugin: 'workflow-conductor', key: 'runUi' } as const, { expanded: [], collapsed: [] })
44/** When the run began and ended: stamped as its state is written. */
45const timesAtom = atom({ plugin: 'workflow-conductor', key: 'runTimes' } as const, initialTimes())
46/** The tracked run's script file, and the project drawn of that run after it started (project.tsx `attach` sets it). */
47const runScriptAtom = atom({ plugin: 'workflow-conductor', key: 'runScript' } as const, null)
48// The designer's state (project.tsx owns it): read and written here only so the selection can follow the run.
49const projectAtom = atom({ plugin: 'workflow-conductor', key: 'project' } as const, null)
50const projectUiAtom = atom({ plugin: 'workflow-conductor', key: 'projectUi' } as const, initialUi())
51/** Where the designer is (project.tsx owns it): written here only so a run whose pane could not open is shown in the band. */
52const shellAtom = atom({ plugin: 'workflow-conductor', key: 'shell' } as const, initialShell())
53
54// The reducer leaves optional fields present but undefined; the stored copy is plain data.
55const plain = (state: RunState): RunState => JSON.parse(JSON.stringify(state)) as RunState
56
57const text = (value: unknown): string | undefined => (typeof value === 'string' && value.length > 0 ? value : undefined)
58
59/** Runs the main conversation started: a subagent's run is not the person's to be asked about. */
60const ownRuns = new Set<string>()
61/** A run that ended, held until the main loop's turn ends, so the question does not cut into Claude's reply to the notice. */
62let saveDue: RunEnded | undefined
63
64const textOf = ($: EngineInterface, path: string): Promise<string | null> =>
65 $.fs.read(path).then(
66 body => (typeof body === 'string' ? body : null),
67 () => null,
68 )
69
70/** Asks whether a project's run's script goes into the repository; on yes the mod copies it itself, so no tool of Claude's writes there. Never throws. */
71const offerSave = async ($: EngineInterface, end: RunEnded): Promise<void> => {
72 const name = end.project
73 const ran = await read($, runScriptAtom)
74 if (name === undefined || ran === null || ran.runId !== end.runId) return
75 const root = await $.session.root()
76 const file = savedWorkflowFile(root, name)
77 const surfaces = await $.session.surfaces().catch(() => undefined)
78 const answerable = ownRuns.has(end.runId) && (surfaces === undefined || surfaces.length > 0)
79 const script = await textOf($, ran.path)
80 const ask = saveAsk({ ending: end.ending, project: name, script, copy: await textOf($, file), answerable })
81 if (ask === null || script === null) return
82 let said: string
83 try {
84 said = await $.ui.ask(saveQuestion(name, ask === 'update'), { options: SAVE_OPTIONS, header: SAVE_HEADER })
85 } catch {
86 return
87 }
88 if (saveChoice(said) !== 'save') return
89 try {
90 await $.fs.write(file, script)
91 $.ui.toast(savedToast(name, file.startsWith(`${root}/`) ? file.slice(root.length + 1) : file))
92 } catch (error) {
93 $.ui.toast(saveFailedToast(error instanceof Error ? error.message : String(error)))
94 }
95}
96
97export const registerRun = (on: On, tracker: Tracker): void => {
98 on('session.start', async ($, e, next) => {
99 await $.command.register({
100 name: 'conductor',
101 description: 'Workflow designer and run view: no argument opens the board (a run in progress, the project last opened, or the start screen to pick one); with a description, Claude drafts a new project for it; min and max move the designer between its pane and the band above the prompt',
102 argumentHint: '[what the workflow should do | min | max]',
103 })
104
105 // A run a previous load of the module was following: its project's node ids are not stored, so the project file is read again.
106 const stored = await read($, runAtom)
107 const attached = stored.status === 'idle' ? null : await read($, runProjectAtom)
108 let claim: Handoff | undefined
109 if (attached !== null) {
110 const body = await $.fs.read(projectFile(await $.session.root(), attached)).catch(() => '')
111 const parsed = parseProject(typeof body === 'string' ? body : '')
112 if (parsed.ok) claim = handoffOf(attached, parsed.project)
113 }
114
115 // The tracker's only way out: every `$` call it causes is spelled here. Its timers
116 // outlive this hook, as a `$.clock` callback does.
117 tracker.attach(
118 {
119 write: async state => {
120 await update($, runAtom, () => plain(state))
121 const now = await $.clock.now()
122 const times = await read($, timesAtom)
123 if (stampTimes(times, state, now) !== times) await update($, timesAtom, held => stampTimes(held, state, now))
124 // The designer's selection follows the block that is running, until the person moves it.
125 const name = await read($, runProjectAtom)
126 if (name === null || state.status === 'idle') return
127 const project = await read($, projectAtom)
128 const shown = await read($, projectUiAtom)
129 // Over: the selection goes to the first block with a failure, once.
130 const settle = state.status === 'running' ? followRun : endRun
131 if (settle(shown, project, state, name) !== shown) await update($, projectUiAtom, held => settle(held, project, state, name))
132 },
133 frame: async tick => {
134 await update($, clockAtom, () => tick)
135 // The elapsed time in the designer's header: stamped here, about once a second, so no drawing reads a clock.
136 const now = await $.clock.now()
137 const times = await read($, timesAtom)
138 if (stampTimes(times, tracker.state(), now) !== times) await update($, timesAtom, held => stampTimes(held, tracker.state(), now))
139 },
140 readText: async path => {
141 const body = await $.fs.read(path)
142
143 return typeof body === 'string' ? body : ''
144 },
145 every: (ms, fn) => $.clock.every(ms, fn),
146 after: (ms, fn) => $.clock.after(ms, fn),
147 // Either pane shows the run (the run view, or the designer with the run laid over it), and so does the band above the prompt while the designer is minimized.
148 paneShown: async () => (await read($, shellAtom)).minimized !== 'no' || (await $.ui.panes()).some(pane => (pane.id === PANE_ID || pane.id === PROJECT_PANE_ID) && pane.isShown && pane.isPlaced),
149 project: name => update($, runProjectAtom, () => name),
150 ended: end => {
151 saveDue = end
152 },
153 status: line => $.ui.status(line),
154 toast: line => $.ui.toast(line),
155 },
156 stored,
157 claim,
158 )
159
160 return next(e)
161 })
162
163 on('command.run', { command: 'conductor' }, async ($, e, next) => {
164 // With words it is a draft, and project.tsx's, whichever of the hooks the engine asks first.
165 if (e.args.trim() !== '') return next(e)
166 // A run that came from a project is shown on that project, and with no run there is nothing to show here: both are project.tsx's.
167 if (bareTarget((await read($, runAtom)).status, await read($, runProjectAtom), await read($, projectUiAtom)).view === 'project') return next(e)
168 const opened = await $.ui.open({ id: PANE_ID, title: PANE_TITLE })
169 if (opened.isPlaced) tracker.paneOpened()
170
171 return { text: 'Conductor pane opened.' }
172 })
173
174 // A run named as a saved project is that project's, handed off or not; one a handoff waited for is that project's under any name.
175 // A run no project claimed is asked about, the turn held meanwhile. Whatever follows the start, the tool's result goes back: never a throw.
176 on('tool.call', { tool: 'Workflow' }, async ($, e, next) => {
177 const answer = await next(e)
178 const result = (answer as { result?: unknown }).result
179 if (result === null || typeof result !== 'object') return answer
180 const { runId, taskId, workflowName, transcriptDir, scriptPath } = result as Record<string, unknown>
181 const id = text(runId)
182 if (id === undefined) return answer
183 const workflow = text(workflowName)
184 if (e.agentId === undefined) ownRuns.add(id)
185 // The board is on the run's project before the tracker places an agent on it. Never a throw: a run is tracked all the same.
186 const board = runBoardOf()
187 const own = (await board?.projectOfRun(workflow).catch(() => null)) ?? null
188 tracker.runStarted({ runId: id, name: workflow, transcriptDir: text(transcriptDir), taskId: text(taskId), project: own === null ? undefined : handoffOf(own.name, own.project) })
189
190 try {
191 // The script is the file the result names, in every form of the call. A run started again keeps its drawing.
192 const script = text(scriptPath)
193 await update($, runScriptAtom, held => (script === undefined ? null : { runId: id, path: script, drawn: held !== null && held.runId === id ? held.drawn : null }))
194 const claimed = tracker.project()
195 if (claimed !== undefined) {
196 offerSettled(claimed)
197 // Out of a handoff the script is the project's as of now, for the next handoff to start from.
198 if (script !== undefined && isSaved(claimed)) {
199 const stored = await $.store.get(LAST_SCRIPTS_STORE).catch(() => undefined)
200 const kept = lastScripts(stored)[claimed]
201 const replace = tracker.handedOff() || (kept !== undefined && !(await $.fs.exists(kept).catch(() => true)))
202 const noted = noteScript(stored, claimed, script, replace)
203 if (noted[claimed] === script) offerRan(claimed, { runId: id, transcriptDir: text(transcriptDir) })
204 await $.store.set(LAST_SCRIPTS_STORE, noted).catch(() => undefined)
205 }
206 // Where nobody handed the project off, a toast says where the run went.
207 if (own !== null) {
208 const pane = await $.ui.open(paneArgs(false)).catch(() => undefined)
209 // Not placed (nobody asked, a narrow terminal): the run is shown in the band above the prompt.
210 if (pane?.isPlaced === false) await update($, shellAtom, held => (held.minimized === 'no' ? { minimized: 'auto' as const, why: 'narrow' as const } : held))
211 if (!tracker.handedOff()) $.ui.toast(reusedToast(own.name, pane?.isPlaced !== false))
212 }
213
214 return answer
215 }
216 // A subagent's workflow is not the person's to be asked about; nor is one where nobody reads a question.
217 if (e.agentId !== undefined || answer.deny !== undefined || answer.isError === true) return answer
218 const surfaces = await $.session.surfaces().catch(() => undefined)
219 if (surfaces !== undefined && surfaces.length === 0) return answer
220 // With no script file there is nothing to draw a project of.
221 if (script === undefined) return answer
222 let said: string
223 try {
224 said = await $.ui.ask(VISUALIZE_QUESTION, { options: VISUALIZE_OPTIONS, header: VISUALIZE_HEADER })
225 } catch {
226 return answer
227 }
228 const choice = visualizeChoice(said)
229 if (choice === null) return said.trim() === '' ? answer : { ...answer, context: [...(answer.context ?? []), visualizeTyped(said)] }
230
231 return choice === 'skip' ? answer : { ...answer, context: [...(answer.context ?? []), visualizeBrief(script, workflow === undefined ? undefined : (projectName(workflow) ?? undefined))] }
232 } catch {
233 return answer
234 }
235 })
236
237 // Only a workflow's agents carry `e.workflow`; the id is on what `next` resolves to.
238 on('agent.spawn', async (_$, e, next) => {
239 const answer = await next(e)
240 const agentId = e.workflow ? text((answer as { agentId?: unknown }).agentId) : undefined
241 if (e.workflow && agentId !== undefined) {
242 tracker.agentSpawned({ runId: e.workflow.runId, agentId, label: e.description, index: e.workflow.agentIndex })
243 }
244
245 return answer
246 })
247
248 // Runs on every loop: each chunk goes through untouched, the last one is read.
249 on('turn.step', async function* (_$, e, next) {
250 for await (const chunk of next(e)) {
251 if (chunk.kind === 'stop' && e.agentId !== undefined) tracker.agentUsage(e.agentId, usageTotal(chunk.usage))
252 yield chunk
253 }
254 })
255
256 on('turn.complete', async ($, e, next) => {
257 // The main loop's turn after a run's end: the question, from a timer so the turn's end is not held while it is up.
258 if (e.agentId === undefined && saveDue !== undefined) {
259 const end = saveDue
260 saveDue = undefined
261 $.clock.after(0, () => void offerSave($, end))
262 }
263 if (e.agentId !== undefined) {
264 tracker.agentEnded(e.agentId, {
265 ok: !e.isAborted && e.reason !== 'error' && e.reason !== 'refusal',
266 aborted: e.isAborted,
267 durationMs: e.durationMs,
268 })
269 }
270
271 return next(e)
272 })
273
274 // A stopped run gets no notice; Claude's stop of its task is the one sign of it there is, besides its agents' aborted ends.
275 on('tool.call', { tool: 'TaskStop' }, async (_$, e, next) => {
276 const answer = await next(e)
277 const stopped = text((answer as { result?: { task_id?: unknown } }).result?.task_id)
278 if (stopped !== undefined && answer.deny === undefined && answer.isError !== true) tracker.taskEnded(stopped, 'killed')
279
280 return answer
281 })
282
283 // The run's end: the engine's notice of its task, as the transcript draws it, passed on untouched and drawn again on every redraw.
284 // Told from a timer: no state is written while a render hook draws.
285 on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
286 const task = e.props.task
287 if (e.props.origin.kind === 'task-notification' && task?.id !== undefined && task.status !== undefined) {
288 const { id, status, durationMs } = task
289 $.clock.after(0, () => tracker.taskEnded(id, status, durationMs))
290 }
291
292 return next(e)
293 })
294
295 on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e) => {
296 const { Box, Text, Button } = $.ui.resolve(e)
297 const state = await read($, runAtom)
298 const ui = await read($, uiAtom)
299 const now = await read($, clockAtom)
300 const rows = buildRunRows(state, {
301 expanded: new Set(ui.expanded),
302 collapsed: new Set(ui.collapsed),
303 now,
304 width: Math.min(MAX_WIDTH, e.props.bodyColumns),
305 })
306
307 const span = (part: Part) => (
308 <Text color={part.color ?? TEXT} bold={part.bold}>
309 {part.text}
310 </Text>
311 )
312 const draw = (row: Row) => {
313 const phase = row.phase
314 if (row.kind !== 'phase' || phase === undefined) return <Text wrap="truncate-end">{row.parts.map(span)}</Text>
315 const isOpen = row.open === true
316
317 // Keyed by the phase, not its text: the counts in the label change, the address must not.
318 return (
319 <Button key={row.key} plain onPress={() => update($, uiAtom, held => togglePhase(held, phase, isOpen))}>
320 {row.parts.map(span)}
321 </Button>
322 )
323 }
324
325 return (
326 <Box flexDirection="column">
327 <Text bold color={TEXT}>{`${GLYPH.diamond} ${PANE_TITLE}`}</Text>
328 {rows.length === 0 && <Text color={FADED}>{`${GLYPH.railEnd} ${PLACEHOLDER}`}</Text>}
329 {rows.slice(0, MAX_ROWS).map(draw)}
330 {rows.length > MAX_ROWS && <Text color={FADED}>{`… ${rows.length - MAX_ROWS} more rows`}</Text>}
331 </Box>
332 )
333 })
334}
335src/ui/rail.ts 325 lines1import type { AgentRun, RunState } from '../run/events'
2
3import { cellWidth, clip, oneLine } from './text'
4import { FADED, GLYPH, RULE, STATUS_COLOR } from './theme'
5
6// The run pane as plain rows: no `$`, no elements. hooks/run.tsx maps rows to elements.
7
8export type ColorKey = 'text' | 'claude' | 'success' | 'error' | 'subtle' | 'inactive'
9
10export type Part = { text: string; color?: ColorKey; bold?: boolean }
11
12export type RowKind = 'header' | 'phase' | 'agent' | 'footer'
13
14export type Counts = { total: number; running: number; done: number; failed: number }
15
16export type Row = {
17 kind: RowKind
18 /** Stable address: `header`, `phase:<title>`, `agent:<id>`, `footer`. */
19 key: string
20 glyph: string
21 /** Color of the glyph, which is the row's state. */
22 color: ColorKey
23 /** The whole line left to right, glyph included, padded to the width. */
24 parts: Part[]
25 text: string
26 /** Phase title: on a phase row its own, on an agent row its group's. */
27 phase?: string
28 /** Phase rows: whether its agents follow. */
29 open?: boolean
30 counts?: Counts
31 tokens?: string
32 bar?: string
33}
34
35export type RailUi = {
36 expanded: ReadonlySet<string>
37 /** Phases the person closed; wins over the automatic expansion on failure. */
38 collapsed?: ReadonlySet<string>
39 /** Milliseconds on the run's tick clock; picks the spinner frame. */
40 now?: number
41 /** Cells across; rows are padded so the right-hand columns line up. */
42 width?: number
43}
44
45export type RailUiState = { expanded: string[]; collapsed: string[] }
46
47export const NO_PHASE = '(no phase)'
48export const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] as const
49export const SPIN_MS = 96
50export const FAILED = '✗'
51const DEFAULT_WIDTH = 60
52const BAR_WIDTH = 8
53
54const MIN_WIDTH = 36
55const EIGHTHS = ['▏', '▎', '▍', '▌', '▋', '▊', '▉'] as const
56const COUNT_COLUMN = 8
57const TOKEN_COLUMN = 8
58
59/** `842`, `18.2k`, `120k`, `1.2M`. */
60export function fmtCount(tokens: number): string {
61 if (typeof tokens !== 'number' || !Number.isFinite(tokens) || tokens <= 0) return '0'
62 const n = Math.round(tokens)
63 if (n < 1000) return String(n)
64 if (n < 99_950) return `${(n / 1000).toFixed(1)}k`
65 if (n < 999_500) return `${Math.round(n / 1000)}k`
66
67 return `${(n / 1_000_000).toFixed(1)}M`
68}
69
70/** `850ms`, `1.1s`, `42s`, `3m05s`, `1h02m`. */
71export function fmtDuration(ms: number): string {
72 if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) return ''
73 if (ms < 1000) return `${Math.round(ms)}ms`
74 if (ms < 9950) return `${(ms / 1000).toFixed(1)}s`
75
76 const seconds = Math.round(ms / 1000)
77 if (seconds < 60) return `${seconds}s`
78
79 const minutes = Math.floor(seconds / 60)
80 if (minutes < 60) return `${minutes}m${String(seconds % 60).padStart(2, '0')}s`
81
82 return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, '0')}m`
83}
84
85export function bar(done: number, total: number, width: number = BAR_WIDTH): string {
86 const cells = Math.max(0, Math.floor(width))
87 const ratio = total > 0 ? Math.min(1, Math.max(0, done / total)) : 0
88 const eighths = Math.round(ratio * cells * 8)
89 const full = Math.floor(eighths / 8)
90 const rest = eighths % 8
91
92 return ('█'.repeat(full) + (rest > 0 ? EIGHTHS[rest - 1] : '')).padEnd(cells, ' ')
93}
94
95export function spinnerFrame(now: number = 0): string {
96 const frame = Math.floor(Math.max(0, now) / SPIN_MS) % SPINNER.length
97
98 return SPINNER[frame] ?? SPINNER[0]
99}
100
101/** Left parts, a gap, right parts: `width` cells in all, the left side clipped to fit. */
102function line(left: Part[], right: Part[], width: number): Part[] {
103 const rightCells = right.reduce((sum, part) => sum + cellWidth(part.text), 0)
104 let room = Math.max(0, width - rightCells - (rightCells > 0 ? 1 : 0))
105 const fitted: Part[] = []
106
107 for (const part of left) {
108 const text = clip(part.text, room)
109 if (text.length > 0) fitted.push({ ...part, text })
110 room -= cellWidth(text)
111 }
112
113 const used = fitted.reduce((sum, part) => sum + cellWidth(part.text), 0)
114 const gap = Math.max(0, width - used - rightCells)
115
116 return [...fitted, ...(gap > 0 && rightCells > 0 ? [{ text: ' '.repeat(gap) }] : []), ...right]
117}
118
119function countOf(agents: readonly AgentRun[]): Counts & { tokens: number } {
120 const sum = { total: 0, running: 0, done: 0, failed: 0, tokens: 0 }
121 for (const agent of agents) {
122 sum.total++
123 sum[agent.status]++
124 sum.tokens += agent.tokens
125 }
126
127 return sum
128}
129
130function stateColor(counts: Counts): ColorKey {
131 if (counts.running > 0) return 'claude'
132 if (counts.failed > 0) return 'error'
133
134 return counts.total > 0 ? 'success' : 'inactive'
135}
136
137function tally(counts: Counts & { tokens: number }): Part[] {
138 const settled = `${counts.done + counts.failed}/${counts.total}`
139 const failed = counts.failed > 0 ? `${counts.failed}${FAILED} ` : ''
140 const pad = ' '.repeat(Math.max(1, COUNT_COLUMN - cellWidth(settled) - cellWidth(failed)))
141
142 return [
143 { text: pad },
144 ...(failed ? [{ text: failed, color: 'error' as const }] : []),
145 { text: settled },
146 { text: fmtCount(counts.tokens).padStart(TOKEN_COLUMN, ' '), color: FADED },
147 ]
148}
149
150const row = (fields: Omit<Row, 'text'>): Row => ({ ...fields, text: fields.parts.map(part => part.text).join('') })
151
152/** Agents grouped by phase in first-seen order; agents without one come last. */
153function groupByPhase(state: RunState): { phase: string; agents: AgentRun[] }[] {
154 const groups = new Map<string, AgentRun[]>()
155 const loose: AgentRun[] = []
156
157 for (const agent of Object.values(state.agents)) {
158 if (agent.phase === undefined || agent.phase === '') {
159 loose.push(agent)
160 continue
161 }
162 const group = groups.get(agent.phase)
163 if (group) group.push(agent)
164 else groups.set(agent.phase, [agent])
165 }
166
167 const ordered = [...groups].map(([phase, agents]) => ({ phase, agents }))
168 if (loose.length > 0) ordered.push({ phase: NO_PHASE, agents: loose })
169
170 return ordered
171}
172
173export function buildRunRows(state: RunState, ui: RailUi): Row[] {
174 const agents = Object.values(state.agents)
175 if (state.status === 'idle' && agents.length === 0) return []
176
177 const width = Math.max(MIN_WIDTH, Math.floor(ui.width ?? DEFAULT_WIDTH))
178 const spin = spinnerFrame(ui.now)
179 const all = countOf(agents)
180 const statusColor: ColorKey = STATUS_COLOR[state.status]
181 const rows: Row[] = []
182 // A run's name, a phase's title and an agent's label are not this mod's words: each is shown cleaned, on one line.
183 const name = oneLine(state.name ?? state.runId ?? '') || 'workflow'
184
185 rows.push(
186 row({
187 kind: 'header',
188 key: 'header',
189 glyph: GLYPH.dot,
190 color: statusColor,
191 parts: line(
192 [
193 { text: `${GLYPH.dot} `, color: statusColor },
194 { text: 'wf: ', color: FADED },
195 { text: name, bold: true },
196 ],
197 [{ text: state.status, color: statusColor }, ...tally(all)],
198 width,
199 ),
200 counts: { total: all.total, running: all.running, done: all.done, failed: all.failed },
201 tokens: fmtCount(all.tokens),
202 }),
203 )
204
205 for (const { phase, agents: members } of groupByPhase(state)) {
206 const counts = countOf(members)
207 const color = stateColor(counts)
208 const open = ui.collapsed?.has(phase) ? false : ui.expanded.has(phase) || counts.failed > 0
209 const glyph = counts.running > 0 ? spin : GLYPH.diamond
210 const progress = bar(counts.done + counts.failed, counts.total)
211
212 rows.push(
213 row({
214 kind: 'phase',
215 key: `phase:${phase}`,
216 glyph,
217 color,
218 phase,
219 open,
220 parts: line(
221 [
222 { text: `${glyph} `, color },
223 { text: oneLine(phase), color: phase === NO_PHASE ? FADED : undefined },
224 { text: ` ×${counts.total}`, color: FADED },
225 ],
226 [{ text: `▕${progress}▏`, color: counts.running > 0 ? 'claude' : RULE }, ...tally(counts)],
227 width,
228 ),
229 counts: { total: counts.total, running: counts.running, done: counts.done, failed: counts.failed },
230 tokens: fmtCount(counts.tokens),
231 bar: progress,
232 }),
233 )
234
235 if (!open) continue
236
237 members.forEach((agent, at) => {
238 const agentColor: ColorKey = STATUS_COLOR[agent.status]
239 const agentGlyph = agent.status === 'running' ? spin : agent.status === 'failed' ? FAILED : GLYPH.done
240 const branch = at === members.length - 1 ? GLYPH.railEnd : GLYPH.railBranch
241 const took = agent.durationMs === undefined ? '' : fmtDuration(agent.durationMs)
242 const tokens = agent.tokens > 0 ? fmtCount(agent.tokens) : ''
243
244 rows.push(
245 row({
246 kind: 'agent',
247 key: `agent:${agent.agentId}`,
248 glyph: agentGlyph,
249 color: agentColor,
250 phase,
251 parts: line(
252 [
253 { text: `${GLYPH.rail} ${branch} `, color: RULE },
254 { text: `${agentGlyph} `, color: agentColor },
255 { text: oneLine(agent.label) || oneLine(agent.agentId) },
256 ],
257 [
258 { text: took, color: FADED },
259 { text: tokens.padStart(TOKEN_COLUMN, ' '), color: FADED },
260 ],
261 width,
262 ),
263 tokens,
264 }),
265 )
266 })
267 }
268
269 const summary = [
270 all.running > 0 ? `${all.running} running` : '',
271 `${all.done} done`,
272 all.failed > 0 ? `${all.failed} failed` : '',
273 ].filter(Boolean)
274
275 rows.push(
276 row({
277 kind: 'footer',
278 key: 'footer',
279 glyph: GLYPH.railEnd,
280 color: FADED,
281 parts: line([{ text: `${GLYPH.railEnd}─ `, color: RULE }, { text: summary.join(' · '), color: FADED }], [], width),
282 counts: { total: all.total, running: all.running, done: all.done, failed: all.failed },
283 tokens: fmtCount(all.tokens),
284 }),
285 )
286
287 return rows
288}
289
290export function currentPhase(state: RunState): string | undefined {
291 const groups = groupByPhase(state)
292 const busy = groups.filter(group => group.agents.some(agent => agent.status === 'running'))
293
294 return (busy.at(-1) ?? groups.at(-1))?.phase
295}
296
297/** Status line while the pane is closed: `wf 7/12 ▸ verify`. With `titles` (a project's block titles by id, in project order) it names the last block running: `wf 3/4 ▸ n3 review`. */
298export function statusText(state: RunState, titles?: Readonly<Record<string, string>>): string {
299 const all = countOf(Object.values(state.agents))
300 const head = `wf ${all.done + all.failed}/${all.total}`
301 if (titles !== undefined) {
302 const busy = Object.keys(titles).filter(id => (state.byNode[id]?.running ?? 0) > 0).at(-1)
303 return busy === undefined ? head : `${head} ▸ ${busy} ${oneLine(titles[busy] ?? '')}`.trimEnd()
304 }
305 const phase = currentPhase(state)
306
307 return `${head}${phase === undefined || phase === NO_PHASE ? '' : ` ▸ ${oneLine(phase)}`}`
308}
309
310/** The one toast at run end. */
311export function endText(state: RunState): string {
312 const all = countOf(Object.values(state.agents))
313 const failed = all.failed > 0 ? ` · ${all.failed} failed` : ''
314
315 return `wf ${oneLine(state.name ?? state.runId ?? '') || 'workflow'} ${state.status}: ${all.done}/${all.total} agents${failed} · ${fmtCount(all.tokens)} tokens`
316}
317
318/** `open` is what the person sees now; the phase goes to its opposite. */
319export function togglePhase(ui: RailUiState, phase: string, open: boolean): RailUiState {
320 const expanded = (ui.expanded ?? []).filter(one => one !== phase)
321 const collapsed = (ui.collapsed ?? []).filter(one => one !== phase)
322
323 return open ? { expanded, collapsed: [...collapsed, phase] } : { expanded: [...expanded, phase], collapsed }
324}
325src/run/events.ts 51 lines1export type RunEvent =
2 | { kind: 'run-start'; runId: string; name?: string; transcriptDir?: string; taskId?: string; at?: number }
3 | { kind: 'agent-start'; runId: string; agentId: string; label: string; phase?: string; index?: number; at?: number }
4 | { kind: 'agent-usage'; agentId: string; tokens: number }
5 | { kind: 'agent-end'; agentId: string; ok: boolean; durationMs?: number; tokens?: number }
6 | { kind: 'run-end'; runId: string; ok: boolean; stopped?: boolean; durationMs?: number }
7
8export type RunStatus = 'idle' | 'running' | 'done' | 'failed' | 'stopped'
9
10export type AgentStatus = 'running' | 'done' | 'failed'
11
12export type AgentRun = {
13 agentId: string
14 label: string
15 nodeId?: string
16 phase?: string
17 status: AgentStatus
18 tokens: number
19 durationMs?: number
20}
21
22export type NodeRun = { total: number; running: number; done: number; failed: number; tokens: number }
23
24export type RunState = {
25 runId?: string
26 name?: string
27 /** Kept in the state so that a load of the module midway through a run still reads its phases. */
28 transcriptDir?: string
29 /** The background task the engine runs it as: its end notice names it. Kept for the same reason. */
30 taskId?: string
31 status: RunStatus
32 /** How long the engine says the run took; set at its end. */
33 durationMs?: number
34 /** By agentId. */
35 agents: Record<string, AgentRun>
36 /** By project node id. */
37 byNode: Record<string, NodeRun>
38 /** By phase title, for a run with no project. */
39 byPhase: Record<string, NodeRun>
40 /** AgentIds whose label carries no known node id. */
41 unmapped: string[]
42}
43
44export function emptyNodeRun(): NodeRun {
45 return { total: 0, running: 0, done: 0, failed: 0, tokens: 0 }
46}
47
48export function emptyRunState(): RunState {
49 return { status: 'idle', agents: {}, byNode: {}, byPhase: {}, unmapped: [] }
50}
51src/run/journal.ts 113 lines1import type { RunEvent } from './events'
2
3export type AgentMeta = { description?: string; workflowPhase?: string }
4
5export type JournalOptions = {
6 /** The journal carries no run id of its own. */
7 runId?: string
8}
9
10function parseLine(line: string): Record<string, unknown> | undefined {
11 if (!line.trim()) return undefined
12 try {
13 const value: unknown = JSON.parse(line)
14 return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined
15 } catch {
16 return undefined
17 }
18}
19
20function text(value: unknown): string | undefined {
21 return typeof value === 'string' && value.length > 0 ? value : undefined
22}
23
24/** `metas` (by agentId, from `agent-<id>.meta.json`) gives the label or phase a `started` line lacks. */
25export function journalToEvents(journalText: string, metas: Record<string, AgentMeta> = {}, options: JournalOptions = {}): RunEvent[] {
26 const runId = options.runId ?? ''
27 const events: RunEvent[] = []
28 let index = 0
29
30 if (typeof journalText !== 'string') return events
31
32 for (const line of journalText.split('\n')) {
33 const entry = parseLine(line)
34 if (!entry) continue
35
36 if (entry.type === 'launched') {
37 events.push({ kind: 'run-start', runId })
38 continue
39 }
40
41 const agentId = text(entry.agentId)
42 if (agentId === undefined) continue
43
44 if (entry.type === 'started') {
45 const meta = metas?.[agentId]
46 const start: RunEvent = {
47 kind: 'agent-start',
48 runId,
49 agentId,
50 label: text(entry.label) ?? text(meta?.description) ?? '',
51 index: index++,
52 }
53 const phase = text(entry.phase) ?? text(meta?.workflowPhase)
54 if (phase !== undefined) start.phase = phase
55 events.push(start)
56 } else if (entry.type === 'result') {
57 events.push({ kind: 'agent-end', agentId, ok: entry.result !== null && entry.result !== undefined })
58 }
59 }
60
61 return events
62}
63
64/** Null: the `started` line names no phase. Absent: the agent is not journalled yet. */
65export function journalPhases(journalText: string): Map<string, string | null> {
66 const phases = new Map<string, string | null>()
67 if (typeof journalText !== 'string') return phases
68
69 for (const line of journalText.split('\n')) {
70 // Read with every burst of spawns, so a line without the word (a result, with all it carries) is not parsed.
71 if (!line.includes('"started"')) continue
72 const entry = parseLine(line)
73 if (entry?.type !== 'started') continue
74
75 const agentId = text(entry.agentId)
76 if (agentId !== undefined) phases.set(agentId, text(entry.phase) ?? null)
77 }
78
79 return phases
80}
81
82/** By agentId, whether the agent's `result` line holds a value: the engine writes one per agent that completed, null where it gave nothing back. */
83export function journalResults(journalText: string): Map<string, boolean> {
84 const results = new Map<string, boolean>()
85 if (typeof journalText !== 'string') return results
86
87 for (const line of journalText.split('\n')) {
88 if (!line.includes('"result"')) continue
89 const entry = parseLine(line)
90 if (entry?.type !== 'result') continue
91
92 const agentId = text(entry.agentId)
93 if (agentId !== undefined) results.set(agentId, entry.result !== null && entry.result !== undefined)
94 }
95
96 return results
97}
98
99function count(value: unknown): number {
100 return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0
101}
102
103/** The usage counts that make up the token figure shown: prompt tokens mostly arrive as cache writes and reads. */
104const USAGE_KEYS = ['input_tokens', 'output_tokens', 'cache_creation_input_tokens', 'cache_read_input_tokens'] as const
105
106/** One request's figure: all four usage counts, as the built-in workflow row counts an agent's latest request. */
107export function usageTotal(usage: unknown): number {
108 if (usage === null || typeof usage !== 'object') return 0
109 const counts = usage as Record<string, unknown>
110
111 return USAGE_KEYS.reduce((sum, key) => sum + count(counts[key]), 0)
112}
113src/run/reducer.ts 174 lines1import { emptyNodeRun, emptyRunState } from './events'
2import type { AgentRun, NodeRun, RunEvent, RunState } from './events'
3
4const NODE_ID = /^(n\d+)\b/
5
6export function parseNodeId(label: string): string | undefined {
7 if (typeof label !== 'string') return undefined
8 return NODE_ID.exec(label)?.[1]
9}
10
11/** `match` holds a block's agent labels and phase titles from the script, in project order; one ending in `*` is a prefix. */
12export type Mapping = { ids: ReadonlySet<string>; match?: Readonly<Record<string, readonly string[]>> }
13
14/** An exact string wins over any prefix, then the longest prefix, then the first block in project order. */
15function matchNode(text: string, match: Mapping['match']): string | undefined {
16 let found: string | undefined
17 let length = -1
18 for (const [id, patterns] of Object.entries(match ?? {})) {
19 for (const pattern of patterns) {
20 if (pattern === text) return id
21 if (pattern.endsWith('*') && pattern.length - 1 > length && text.startsWith(pattern.slice(0, -1))) {
22 found = id
23 length = pattern.length - 1
24 }
25 }
26 }
27 return found
28}
29
30/** The id the label opens with (with a project, only one it has), else a match on the label, else on the phase title. */
31function nodeOf(label: string, phase: string | undefined, mapping?: Mapping): string | undefined {
32 const parsed = parseNodeId(label)
33 if (parsed !== undefined && (!mapping || mapping.ids.has(parsed))) return parsed
34 if (!mapping?.match) return undefined
35 return (label === '' ? undefined : matchNode(label, mapping.match)) ?? (phase === undefined || phase === '' ? undefined : matchNode(phase, mapping.match))
36}
37
38type Buckets = Record<string, NodeRun>
39
40function patchBucket(buckets: Buckets, key: string | undefined, patch: (one: NodeRun) => NodeRun): Buckets {
41 if (key === undefined) return buckets
42 return { ...buckets, [key]: patch(buckets[key] ?? emptyNodeRun()) }
43}
44
45function patchAgentBuckets(state: RunState, agent: AgentRun, patch: (one: NodeRun) => NodeRun): Pick<RunState, 'byNode' | 'byPhase'> {
46 return {
47 byNode: patchBucket(state.byNode, agent.nodeId, patch),
48 byPhase: patchBucket(state.byPhase, agent.phase, patch),
49 }
50}
51
52function usageCount(value: unknown): number | undefined {
53 return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined
54}
55
56/** Returns the same state when the event changes nothing; the input is never mutated. */
57export function reduce(state: RunState, event: RunEvent, mapping?: Mapping): RunState {
58 switch (event.kind) {
59 case 'run-start': {
60 // A repeated start for the run already in progress must not drop its agents.
61 const dir = event.transcriptDir === undefined ? {} : { transcriptDir: event.transcriptDir }
62 const task = event.taskId === undefined ? {} : { taskId: event.taskId }
63 if (state.status === 'running' && state.runId === event.runId) {
64 const same = (event.name === undefined || event.name === state.name) && (event.transcriptDir === undefined || event.transcriptDir === state.transcriptDir) && (event.taskId === undefined || event.taskId === state.taskId)
65 return same ? state : { ...state, ...(event.name === undefined ? {} : { name: event.name }), ...dir, ...task }
66 }
67 return { ...emptyRunState(), runId: event.runId, name: event.name, ...dir, ...task, status: 'running' }
68 }
69
70 case 'agent-start': {
71 if (typeof event.agentId !== 'string') return state
72
73 const known = state.agents[event.agentId]
74 if (known) {
75 // A start seen again never counts twice, but it may carry the phase the first lacked.
76 const phase = typeof event.phase === 'string' && event.phase.length > 0 ? event.phase : undefined
77 if (known.phase !== undefined || phase === undefined) return state
78
79 // An agent no label placed may be placed by its phase title.
80 const nodeId = known.nodeId ?? nodeOf(known.label, phase, mapping)
81 const counted = (one: NodeRun): NodeRun => ({ ...one, total: one.total + 1, [known.status]: one[known.status] + 1, tokens: one.tokens + known.tokens })
82
83 return {
84 ...state,
85 agents: { ...state.agents, [known.agentId]: { ...known, nodeId, phase } },
86 byNode: nodeId === known.nodeId ? state.byNode : patchBucket(state.byNode, nodeId, counted),
87 byPhase: patchBucket(state.byPhase, phase, counted),
88 unmapped: nodeId === known.nodeId ? state.unmapped : state.unmapped.filter(id => id !== known.agentId),
89 }
90 }
91
92 const label = typeof event.label === 'string' ? event.label : ''
93 const nodeId = nodeOf(label, event.phase, mapping)
94 const agent: AgentRun = { agentId: event.agentId, label, nodeId, phase: event.phase, status: 'running', tokens: 0 }
95 // A spawn for a run held stopped (no notice says so, the stop is inferred) reopens it.
96 const sameRun = state.runId === undefined || state.runId === event.runId
97
98 return {
99 ...state,
100 // Agents can be seen before the run itself is announced.
101 runId: state.runId ?? event.runId,
102 status: state.status === 'idle' || sameRun ? 'running' : state.status,
103 agents: { ...state.agents, [agent.agentId]: agent },
104 ...patchAgentBuckets(state, agent, one => ({ ...one, total: one.total + 1, running: one.running + 1 })),
105 unmapped: nodeId === undefined ? [...state.unmapped, agent.agentId] : state.unmapped,
106 }
107 }
108
109 case 'agent-usage': {
110 const agent = state.agents[event.agentId]
111 const tokens = usageCount(event.tokens)
112 if (!agent || tokens === undefined || tokens === agent.tokens) return state
113
114 const delta = tokens - agent.tokens
115 return {
116 ...state,
117 agents: { ...state.agents, [agent.agentId]: { ...agent, tokens } },
118 ...patchAgentBuckets(state, agent, one => ({ ...one, tokens: one.tokens + delta })),
119 }
120 }
121
122 case 'agent-end': {
123 const agent = state.agents[event.agentId]
124 if (!agent || agent.status !== 'running') return state
125
126 const status = event.ok ? 'done' : 'failed'
127 const tokens = usageCount(event.tokens) ?? agent.tokens
128 const delta = tokens - agent.tokens
129 const ended: AgentRun = { ...agent, status, tokens }
130 if (typeof event.durationMs === 'number') ended.durationMs = event.durationMs
131
132 return {
133 ...state,
134 agents: { ...state.agents, [agent.agentId]: ended },
135 ...patchAgentBuckets(state, agent, one => ({
136 ...one,
137 running: one.running - 1,
138 [status]: one[status] + 1,
139 tokens: one.tokens + delta,
140 })),
141 }
142 }
143
144 case 'run-end': {
145 if (state.runId !== undefined && event.runId !== state.runId) return state
146 const status = event.stopped === true ? 'stopped' : event.ok ? 'done' : 'failed'
147 const durationMs = typeof event.durationMs === 'number' && Number.isFinite(event.durationMs) && event.durationMs >= 0 ? event.durationMs : state.durationMs
148 if (status === state.status && durationMs === state.durationMs) return state
149 return { ...state, status, ...(durationMs === undefined ? {} : { durationMs }) }
150 }
151
152 default:
153 return state
154 }
155}
156
157/** Places every agent again under `mapping`, for a project given to a run after it started; the phases stay. */
158export function remap(state: RunState, mapping?: Mapping): RunState {
159 const agents: RunState['agents'] = {}
160 let byNode: Buckets = {}
161 const unmapped: string[] = []
162 for (const agent of Object.values(state.agents)) {
163 const nodeId = nodeOf(agent.label, agent.phase, mapping)
164 agents[agent.agentId] = { ...agent, nodeId }
165 byNode = patchBucket(byNode, nodeId, one => ({ ...one, total: one.total + 1, [agent.status]: one[agent.status] + 1, tokens: one.tokens + agent.tokens }))
166 if (nodeId === undefined) unmapped.push(agent.agentId)
167 }
168 return { ...state, agents, byNode, unmapped }
169}
170
171export function reduceAll(events: readonly RunEvent[], mapping?: Mapping, from: RunState = emptyRunState()): RunState {
172 return events.reduce((state, event) => reduce(state, event, mapping), from)
173}
174src/run/replay.ts 95 lines1import { flatten, idNumber } from '../project/model'
2import type { Project } from '../project/model'
3
4import type { RunEvent } from './events'
5import { journalToEvents } from './journal'
6import type { AgentMeta } from './journal'
7
8// Dev aid: turns a recorded journal into a whole run's events, so the pane can be driven without a real workflow.
9
10export type ReplayFixture = { journal: string; metas: Record<string, AgentMeta> }
11
12/** A journal records no token counts, so a replay makes one up per agent, stable across runs. */
13export function replayUsage(agentId: string): number {
14 let hash = 0
15 for (const char of agentId) hash = (hash * 31 + (char.codePointAt(0) ?? 0)) % 9973
16
17 return 1200 + hash
18}
19
20/** A recording that stops with agents open is an interrupted run: those agents end failed, and so does the run. */
21export function replayEvents(name: string, fixture: ReplayFixture): RunEvent[] {
22 const runId = `replay:${name}`
23 const events: RunEvent[] = [{ kind: 'run-start', runId, name }]
24 const open = new Set<string>()
25
26 for (const event of journalToEvents(fixture.journal, fixture.metas, { runId })) {
27 if (event.kind === 'run-start') continue
28 if (event.kind === 'agent-start') open.add(event.agentId)
29 if (event.kind === 'agent-end') {
30 open.delete(event.agentId)
31 events.push({ ...event, tokens: replayUsage(event.agentId) })
32 continue
33 }
34 events.push(event)
35 }
36
37 for (const agentId of open) events.push({ kind: 'agent-end', agentId, ok: false })
38 events.push({ kind: 'run-end', runId, ok: open.size === 0 })
39
40 return events
41}
42
43export function replayDue(total: number, step: number, steps: number): number {
44 if (steps <= 0 || step >= steps) return total
45
46 return Math.min(total, Math.max(0, Math.ceil((total * step) / steps)))
47}
48
49/** Labels of the agents a project replay adds that no node of the project claims. */
50export const REPLAY_STRAYS = ['fix lint', 'stray check'] as const
51
52function replayAgents(id: string): number {
53 return 2 + (idNumber(id) % 3)
54}
55
56/** Labels are `<nodeId>: <title> <k>`, as a handed-off script writes them; one agent fails and two carry labels no node claims. */
57export function replayProjectEvents(project: Project, name: string = project.name): RunEvent[] {
58 const runId = `replay:project:${name}`
59 const events: RunEvent[] = [{ kind: 'run-start', runId, name }]
60 const rows = flatten(project)
61 const leaves = rows.filter(row => (row.node.children?.length ?? 0) === 0 && row.node.type !== 'code' && row.node.type !== 'start')
62 const phaseOf = new Map<string, string>()
63 let phase = ''
64 for (const row of rows) {
65 if (row.depth === 0) phase = `${row.node.id} ${row.node.name}`
66 phaseOf.set(row.node.id, phase)
67 }
68 const strayId = `n${rows.reduce((max, row) => Math.max(max, idNumber(row.node.id)), 0) + 90}`
69 const strays = [REPLAY_STRAYS[0], `${strayId}: ${REPLAY_STRAYS[1]}`]
70 const failing = leaves[Math.min(1, leaves.length - 1)]?.node.id
71
72 const run = (agentId: string, label: string, phase: string | undefined, ok: boolean): RunEvent[][] => {
73 const tokens = replayUsage(agentId)
74
75 return [
76 [{ kind: 'agent-start', runId, agentId, label, phase }],
77 [{ kind: 'agent-usage', agentId, tokens: Math.round(tokens / 2) }],
78 [{ kind: 'agent-end', agentId, ok, tokens, durationMs: 1000 + (tokens % 4000) }],
79 ]
80 }
81
82 for (const [at, { node }] of leaves.entries()) {
83 const count = replayAgents(node.id)
84 const agents = Array.from({ length: count }, (_, k) => run(`replay-${node.id}-${k + 1}`, `${node.id}: ${node.name} ${k + 1}`, phaseOf.get(node.id), !(node.id === failing && k === 1)))
85 const stray = at === 0 ? strays[0] : at === leaves.length - 1 ? strays[1] : undefined
86 if (stray !== undefined) agents.push(run(`replay-stray-${at === 0 ? 1 : 2}`, stray, undefined, true))
87 // Starts together, then usage, then ends: a node's agents overlap as a fan-out does.
88 for (const stage of [0, 1, 2]) for (const agent of agents) events.push(...(agent[stage] ?? []))
89 }
90 if (leaves.length === 1) events.push(...run('replay-stray-2', strays[1] ?? '', undefined, true).flat())
91 events.push({ kind: 'run-end', runId, ok: true })
92
93 return events
94}
95src/project/chat.ts 682 lines1// The project as Claude edits it from chat: the tool's description and schema, generated from the teaching content
2// and the model; the edits; the tool's answers. Every edit goes through ops.ts and is checked by parseProject.
3
4import { OUTLINE_MAX, outline } from './handoff'
5import { OFFER_TOOL_FULL_NAME } from './offer'
6import { lint } from './lints'
7import { CONTAINER_TYPES, KINDS, NODE_TYPES, startOf, typeName, canHoldChildren, findNode, flatten, isRecord, kindsOf, parseProject, readType, serializeProject } from './model'
8import type { Project, ProjectNode, Kind, Row } from './model'
9import { addNode, moveNode, nextIdNumber, removeNode, retypeNode, updateNode } from './ops'
10import type { NodePatch, Place } from './ops'
11import { FLASH_MS } from '../ui/graph-model'
12import { clip, oneLine } from '../ui/text'
13import { UNDO_HINT } from './history'
14import { PROJECT_DIR, carryUi, initialUi } from './session'
15import type { ProjectUi } from './session'
16import { KIND_TEACH, KNOB_HELP, TEACH, defaultName, fillOf, logicOf } from './teach'
17
18export const TOOL_NAME = 'project'
19export const TOOL_FULL_NAME = 'mcp__workflow-conductor__project'
20export const TOOL_TITLE = 'Conductor'
21const PROJECT_DIR_HINT = `${PROJECT_DIR}/<name>.json`
22
23const ACTIONS = ['read', 'apply', 'write', 'attach'] as const
24const OP_KINDS = ['add', 'update', 'move', 'remove'] as const
25
26const KNOB_NAMES = Object.keys(KNOB_HELP)
27
28function typeLines(): string[] {
29 return NODE_TYPES.map(type => `- ${type}${canHoldChildren(type) ? ' (container)' : ''}: ${TEACH[type].hint}. Use when ${TEACH[type].when}.`)
30}
31
32/** All but the plain kind, which a block does not name. */
33function namedKinds(type: keyof typeof KINDS): readonly Kind[] {
34 return kindsOf(type).slice(1)
35}
36
37function kindNames(): string {
38 return (Object.keys(KINDS) as (keyof typeof KINDS)[]).map(type => `${type}: ${namedKinds(type).join(', ')}`).join('. ')
39}
40
41function kindLine(): string {
42 return (Object.keys(KINDS) as (keyof typeof KINDS)[]).map(type => `${type}: ${namedKinds(type).map(kind => `${kind} = ${KIND_TEACH[kind].hint}`).join('; ')}`).join('. ')
43}
44
45function knobLine(): string {
46 return Object.entries(KNOB_HELP)
47 .map(([key, help]) => `${key} (${help})`)
48 .join('; ')
49}
50
51/** The tool is deferred: only its name is in every turn, and the model reads this once it loads the tool. */
52export function toolDescription(): string {
53 return [
54 `Reads and edits the user's Conductor workflow project: the board of blocks they see, saved at ${PROJECT_DIR_HINT}. Use it whenever the user asks to draft, add, change, move or remove workflow blocks or steps ("add a verify after n3", "this block"); do not edit that file by hand. A project is a spec the user reviews, not a script: never run it from here.`,
55 'Actions: read = the project JSON, the block selected on the board ("this block") and the lints. Read before you describe, review or edit a project, unless a Conductor note with the prompt has told you what changed: the user changes the board by hand between your turns, so what you read or wrote earlier may be gone (every answer names the revision it shows). apply = `ops` in order, all or nothing. write = replace the whole tree with `nodes` (drafting, large restructures). attach = a write, with `match`, of a project OF the workflow run tracked now: the run shows on it. An edit shows on the board at once and returns the lints: fix them or tell the user.',
56 "Block: { id, type, kind?, name, logic?, knobs?, match?, children? }. Ids (n1, n2…) are assigned for you and never change. name is a short label; logic is free text saying what the block should do. Order is execution order. Only containers hold children. Blocks directly inside a branch are its arms (one runs, picked by its `condition`), and directly inside a parallel they run side by side: to run two blocks one after the other there, put both in a pipeline. Every project starts with its start block: it is not added, moved or removed, and it alone has the knobs `goal` (the goal of the whole workflow, in a sentence: set it when drafting, keep it true) and `args` (the workflow's input, or unset for none). Update it by id; in a write, put it first, or leave it out to keep it as it is.",
57 'Types:',
58 ...typeLines(),
59 `Kinds: \`kind\` names the pattern a block is used for (each explained on \`kind\` in the schema); leave it out for the plain block. ${kindNames()}.`,
60 // A description is cut at 4096 characters, and the types take them: what belongs to one field (what each knob and kind means, how a write keeps ids) is said on that field in the schema.
61 `Knobs, all optional, explained on \`knobs\` in the schema: ${KNOB_NAMES.join(', ')}.`,
62 ].join('\n')
63}
64
65const BLOCK_FIELDS = {
66 type: { enum: [...NODE_TYPES] },
67 kind: { type: 'string', description: `Optional: the pattern, by type. ${kindLine()}. A new block of a kind gets the knobs its pattern needs where you set none. In an update, "" makes the block plain again.` },
68 name: { type: 'string' },
69 logic: { type: 'string' },
70 knobs: { type: 'object', description: `All optional: ${knobLine()}. The board and the lints say a key in words: oncePer is "once per", stopCondition "stop condition". In an update, "" clears a knob.` },
71 match: { type: 'array', items: { type: 'string' }, description: "Only on a project of a script that exists: the script's agent labels or phase titles this block stands for, each exact, or a prefix when it ends in *. In an update, [] clears it." },
72 children: { type: 'array', items: { type: 'object' }, description: 'Blocks inside a container, same shape.' },
73}
74
75export const TOOL_SCHEMA: Record<string, unknown> = {
76 type: 'object',
77 required: ['action'],
78 properties: {
79 action: { enum: [...ACTIONS] },
80 name: { type: 'string', description: 'Project name. Default: the one open on the board (attach: name it).' },
81 ops: {
82 type: 'array',
83 description:
84 'apply. add: a new block (type, kind?, name, logic?, knobs?, children?) placed by `after` or `before` (a sibling id) or `parent` (a container id: appended); none of them = end of the top level. update: `id` plus the fields to change (type and kind too). move: `id` plus after | before | parent. remove: `id`, with everything it holds.',
85 items: {
86 type: 'object',
87 required: ['op'],
88 properties: { op: { enum: [...OP_KINDS] }, id: { type: 'string' }, after: { type: 'string' }, before: { type: 'string' }, parent: { type: 'string' }, ...BLOCK_FIELDS },
89 },
90 },
91 nodes: {
92 type: 'array',
93 description: 'write/attach. The whole tree, top level first: keep the id of every block that stays, leave id off new ones.',
94 // The knobs are explained once, on the ops.
95 items: { type: 'object', required: ['type', 'name'], properties: { id: { type: 'string', description: 'Only for a block that already exists.' }, ...BLOCK_FIELDS, kind: { type: 'string', description: 'The same kinds as in `ops`.' }, knobs: { type: 'object', description: 'The same knobs as in `ops`.' }, match: { type: 'array', items: { type: 'string' }, description: 'As in `ops`.' } } },
96 },
97 },
98}
99
100const DRAFT_RULES = [
101 'The project is a spec the user reviews on the board. Do not write a workflow script and do not run anything.',
102 'Pick the structure the task needs and no more: a few blocks with clear logic beat many. Give a block its kind where one fits, and use knobs where they say something (oncePer, stopCondition, output).',
103]
104
105const DRAFT_AFTER = 'Afterwards stop: the user takes it from there. Say in two or three lines what the blocks do, name any lint you chose to leave, and tell the user to review and edit the project on the board and to approve it there with r (Implement and Run).'
106
107/** For `/conductor <description>`. It names the tool in full: the tool is deferred, and the name is what Claude loads it by. */
108export function draftBrief(description: string): string[] {
109 return [
110 [
111 `Conductor draft: the user wants a new workflow project for: ${description}`,
112 '',
113 'Where what they want is too unclear to pick a structure for, ask them first, briefly, and wait for the answer. Otherwise do not ask.',
114 `Make it with the ${TOOL_FULL_NAME} tool (it is deferred: load it by that name): one call with action "write", a short kebab-case name of your choosing that no project has, and the nodes, the start block first with the goal in a sentence in its \`goal\` knob. It is always a new project, unless the user's own words name an existing one to change.`,
115 ...DRAFT_RULES,
116 DRAFT_AFTER,
117 ].join('\n'),
118 ]
119}
120
121export function offerBrief(): string {
122 return [
123 `The user chose Conductor: they want this workflow as a project on the Conductor board, to review and edit before anything is written or run.`,
124 '',
125 `Make it with the ${TOOL_FULL_NAME} tool (it is deferred: load it by that name): one call with action "write", a short kebab-case name of your choosing and the nodes, the start block first with the goal of the workflow in its \`goal\` knob.`,
126 ...DRAFT_RULES,
127 DRAFT_AFTER,
128 `If they then tell you in chat to run it, call ${OFFER_TOOL_FULL_NAME} again before anything else: its answer says how this project is run.`,
129 ].join('\n')
130}
131
132/** Added to the Workflow tool's result. Under `name` the next run of the same script finds the project, and is shown on it with no question. */
133export function visualizeBrief(scriptPath: string, name: string | undefined): string {
134 return [
135 `Conductor: the user chose to see this workflow run as a project on the Conductor board. The run goes on meanwhile: do not change, re-run or stop the script.`,
136 '',
137 `Draw the project OF the script that is running with the ${TOOL_FULL_NAME} tool (it is deferred: load it by that name): one call with action "attach", ${name === undefined ? 'a short kebab-case name' : `name "${name}" (the workflow's own name as a project's: the next run of this script is then shown on this project without a question)`} and the nodes, the start block first with the workflow's goal in its \`goal\` knob.`,
138 "- The nodes mirror the script's real structure: its pipelines, parallels, loops, branches and agents, no more. A phase is no block: its blocks stand at the top level in its place.",
139 '- `match` ties the run to the blocks. It goes on the INNERMOST block an agent belongs to, and a label on one block only (never also on the container around it): the exact `label` of each agent() the block stands for, or the fixed start of the label and a * ("review *") where the script builds it at runtime.',
140 "- Where the script groups its agents by `phase`, the first top-level block of each phase gets that phase's exact title in `match`.",
141 `The script, if you do not hold its text: ${scriptPath}`,
142 'The answer lists the agent labels no block took: fix `match` and call attach again under the same name. Afterwards tell the user in one or two lines what the board shows.',
143 ].join('\n')
144}
145
146/** A label two blocks both list in `match`: the first in project order takes its agents, and the other shows none. */
147function sharedMatch(project: Project): string[] {
148 const first = new Map<string, string>()
149 const notes: string[] = []
150 for (const { node } of flatten(project)) {
151 for (const one of node.match ?? []) {
152 const held = first.get(one)
153 if (held === undefined) first.set(one, node.id)
154 else if (held !== node.id) notes.push(`Note: ${JSON.stringify(one)} is in the \`match\` of ${held} and ${node.id}: ${held} comes first and takes those agents. Keep it on the innermost block only.`)
155 }
156 }
157 return notes
158}
159
160/** The agents of the run no block took, each label once. Later phases may still place some. */
161export function attachNote(project: Project, unplaced: readonly string[]): string {
162 const labels = [...new Set(unplaced)]
163 const placed =
164 labels.length === 0
165 ? 'The run is shown on it: every agent so far is on a block.'
166 : `The run is shown on it. Agent labels not placed yet (an agent whose phase has not been read yet may still land): ${labels.map(label => JSON.stringify(label)).join(', ')}. For any that no \`match\` covers, fix \`match\` and call attach again.`
167 return [placed, ...sharedMatch(project)].join('\n')
168}
169
170/** Added to an edit's answer when the board could not be put on screen (an open nobody typed waits under 144 columns). */
171export function unplacedNote(name: string): string {
172 return `The board is not on screen (the terminal is too narrow for it to open by itself; the band above the prompt names the project): tell the user that /conductor opens it (project ${name}).`
173}
174
175// Edits
176
177/** `notes` are things the edit did that the caller may not have meant, said in the answer. */
178export type Change = { added: string[]; changed: string[]; removed: string[]; notes?: string[] }
179
180export type Edit = ({ ok: true; project: Project } & Change) | { ok: false; error: string }
181
182const TYPES_HINT = `types: ${NODE_TYPES.join(', ')}`
183const CONTAINERS_HINT = `containers: ${CONTAINER_TYPES.join(', ')}`
184const KNOBS_HINT = `knobs: ${KNOB_NAMES.join(', ')}`
185
186// A refusal Claude can act on: the reason, plus the list it should have picked from.
187function explain(error: string): string {
188 if (error.includes('unknown type')) return `${error}; ${TYPES_HINT}`
189 if (error.includes('cannot hold children')) return `${error}; ${CONTAINERS_HINT}`
190 if (error.includes('unknown knob')) return `${error}; ${KNOBS_HINT}`
191 return error
192}
193
194function knobsError(raw: unknown, where: string): string | undefined {
195 if (raw === undefined || raw === null) return undefined
196 if (!isRecord(raw)) return `${where}: knobs must be an object`
197 const stray = Object.keys(raw).find(key => !KNOB_NAMES.includes(key))
198 return stray === undefined ? undefined : `${where}: unknown knob ${stray}`
199}
200
201function signature(project: Project): Map<string, string> {
202 const out = new Map<string, string>()
203 for (const row of flatten(project)) {
204 const { id, type, kind, name, logic, knobs, match } = row.node
205 out.set(id, JSON.stringify([row.parentId ?? null, type, kind ?? '', name, logic ?? '', Object.entries(knobs ?? {}).sort(([a], [b]) => a.localeCompare(b)), match ?? []]))
206 }
207 return out
208}
209
210/** Order among siblings is not compared. */
211export function diffProjects(before: Project | null, after: Project): Change {
212 const old = before ? signature(before) : new Map<string, string>()
213 const now = signature(after)
214 const change: Change = { added: [], changed: [], removed: [] }
215 for (const [id, mark] of now) {
216 if (!old.has(id)) change.added.push(id)
217 else if (old.get(id) !== mark) change.changed.push(id)
218 }
219 for (const id of old.keys()) if (!now.has(id)) change.removed.push(id)
220 return change
221}
222
223/** A `condition` on a block that is no arm of a branch picks nothing. */
224function strayConditions(project: Project, ids: readonly string[]): string[] {
225 return flatten(project)
226 .filter(row => ids.includes(row.node.id) && (row.node.knobs?.condition ?? '').trim() !== '' && (row.parentId === undefined ? undefined : findNode(project, row.parentId)?.type) !== 'branch')
227 .map(row => `${row.node.id} has a \`condition\` but does not stand directly in a branch, so nothing reads it: move the block into the branch as an arm, or clear the knob (condition: "").`)
228}
229
230// The last gate: whatever was assembled is read back by the model's own parser.
231function checked(before: Project, candidate: Project, touched: Iterable<string> = [], notes: string[] = []): Edit {
232 const parsed = parseProject(serializeProject(candidate))
233 if (!parsed.ok) return { ok: false, error: explain(parsed.error) }
234 const change = diffProjects(before, parsed.project)
235 for (const id of touched) {
236 if (!change.added.includes(id) && !change.changed.includes(id) && findNode(parsed.project, id)) change.changed.push(id)
237 }
238 const said = [...notes, ...strayConditions(parsed.project, [...change.added, ...change.changed])]
239 return { ok: true, project: parsed.project, ...change, ...(said.length > 0 ? { notes: said } : {}) }
240}
241
242/** An `add` beside a sibling in a branch or a parallel makes another arm, not a step after it. Null elsewhere. */
243function armNote(project: Project, id: string, beside: string): string | null {
244 const row = flatten(project).find(one => one.node.id === id)
245 const parent = row?.parentId === undefined ? undefined : findNode(project, row.parentId)
246 if (!parent) return null
247 if (parent.type === 'branch') return `${id} was added as a new arm of branch ${parent.id} (a branch runs one of its arms; every arm but the last needs a \`condition\`), not as a step after ${beside}. To run it after ${beside} in the same arm, wrap the two in a pipeline: add a pipeline in ${parent.id}, then move ${beside} and ${id} into it.`
248 if (parent.type === 'parallel') return `${id} was added beside ${beside} in ${parent.type} ${parent.id}: the two run at the same time, not one after the other. To run it after ${beside}, wrap the two in a pipeline inside ${parent.id}.`
249 return null
250}
251
252/** A tree written in another order: `diffProjects` does not compare order. */
253function reordered(before: Project, after: Project): string[] {
254 const order = (project: Project): Map<string, string[]> => {
255 const out = new Map<string, string[]>()
256 for (const row of flatten(project)) out.set(row.parentId ?? '', [...(out.get(row.parentId ?? '') ?? []), row.node.id])
257 return out
258 }
259 const old = order(before)
260 const moved: string[] = []
261 for (const [parent, ids] of order(after)) {
262 const was = (old.get(parent) ?? []).filter(id => ids.includes(id))
263 ids.filter(id => was.includes(id)).forEach((id, index) => {
264 if (was[index] !== id) moved.push(id)
265 })
266 }
267 return moved
268}
269
270/** A block whose id is in the project as it stood keeps it; every other gets a fresh id, whatever it came with, so ids never collide. */
271export function replaceProject(before: Project, rawNodes: unknown): Edit {
272 if (!Array.isArray(rawNodes)) return { ok: false, error: 'write needs `nodes`: the array of top-level blocks' }
273 const known = new Set(flatten(before).map(row => row.node.id))
274 const startId = startOf(before)?.id
275 const kept = new Set<string>()
276 let next = nextIdNumber(before)
277 let problem: string | undefined
278
279 const build = (raw: unknown, where: string): Record<string, unknown> => {
280 if (!isRecord(raw)) {
281 problem ??= `${where} must be an object`
282 return {}
283 }
284 let id: string
285 let stays = false
286 if (typeof raw.id === 'string' && known.has(raw.id)) {
287 if (kept.has(raw.id)) problem ??= `duplicate id ${raw.id}: a block that stays appears once; leave id off new blocks`
288 kept.add(raw.id)
289 id = raw.id
290 stays = true
291 } else if (raw.type === 'start' && startId !== undefined && !kept.has(startId)) {
292 // The start block is never new: one sent without its id is still the one there.
293 kept.add(startId)
294 id = startId
295 } else id = `n${next++}`
296 const read = readType(raw.type, raw.kind)
297 if ('error' in read) problem ??= `${id}: ${read.error}`
298 const block = 'error' in read ? undefined : read
299 problem ??= knobsError(raw.knobs, id)
300 const node: Record<string, unknown> = { id, type: block?.type ?? raw.type, name: typeof raw.name === 'string' && raw.name.trim() !== '' ? raw.name : block ? defaultName(block) : '' }
301 if (block?.kind !== undefined) node.kind = block.kind
302 // A new block of a kind gets what the kind fills in, under the logic and the knobs it came with; a block that stays is taken as written.
303 const filled = stays || !block ? undefined : logicOf(block)
304 if (typeof raw.logic === 'string' && raw.logic.trim() !== '') node.logic = raw.logic
305 else if (raw.logic !== undefined && raw.logic !== null && typeof raw.logic !== 'string') problem ??= `${id}: logic must be a string`
306 else if (filled !== undefined) node.logic = filled
307 const given = isRecord(raw.knobs) ? Object.fromEntries(Object.entries(raw.knobs).filter(([, value]) => value !== '' && value !== null)) : {}
308 const knobs = stays || !block ? given : { ...fillOf(block), ...given }
309 if (isRecord(raw.knobs) || Object.keys(knobs).length > 0) node.knobs = knobs
310 // Read back by parseProject below, which refuses a list that is not one of strings.
311 if (raw.match !== undefined && raw.match !== null) node.match = raw.match
312 const children = raw.children
313 if (children !== undefined && children !== null && !Array.isArray(children)) problem ??= `${id}: children must be an array`
314 const list = Array.isArray(children) ? children : []
315 if (list.length > 0 || (block !== undefined && canHoldChildren(block.type))) node.children = list.map((child, index) => build(child, `${id}.children[${index}]`))
316 return node
317 }
318
319 const nodes = rawNodes.map((raw, index) => build(raw, `nodes[${index}]`))
320 if (problem !== undefined) return { ok: false, error: explain(problem) }
321 // A tree written without the start block keeps the one the project has, as it is.
322 const start = startOf(before)
323 if (start && !nodes.some(node => node.type === 'start')) nodes.unshift({ ...start })
324 const candidate = { version: 1, name: before.name, nextId: next, nodes } as unknown as Project
325 // Not serializeProject: it would trust shapes that have not been checked yet.
326 const parsed = parseProject(JSON.stringify(candidate))
327 if (!parsed.ok) return { ok: false, error: explain(parsed.error) }
328 return checked(before, parsed.project, reordered(before, parsed.project))
329}
330
331function placeOf(project: Project, op: Record<string, unknown>): Place | string {
332 // A null is a place not said, as one left out is.
333 const beside = op.after ?? op.before
334 if (beside !== undefined && beside !== null) {
335 if (typeof beside !== 'string') return 'after/before must be a block id'
336 const row = flatten(project).find(one => one.node.id === beside)
337 if (!row) return `no block ${beside}`
338 const index = op.after !== undefined && op.after !== null ? row.index + 1 : row.index
339 return row.parentId === undefined ? { index } : { parentId: row.parentId, index }
340 }
341 if (op.parent !== undefined && op.parent !== null) {
342 if (typeof op.parent !== 'string') return 'parent must be a block id'
343 const parent = findNode(project, op.parent)
344 if (!parent) return `no block ${op.parent}`
345 return { parentId: parent.id, index: parent.children?.length ?? 0 }
346 }
347 return { index: project.nodes.length }
348}
349
350function patchOf(raw: Record<string, unknown>): NodePatch {
351 const patch: Record<string, unknown> = {}
352 if (raw.name !== undefined && raw.name !== null) patch.name = raw.name
353 if (raw.logic !== undefined && raw.logic !== null) patch.logic = raw.logic
354 if (raw.knobs !== undefined && raw.knobs !== null) patch.knobs = raw.knobs
355 if (raw.match !== undefined && raw.match !== null) patch.match = raw.match
356 return patch as NodePatch
357}
358
359type Grown = { project: Project; ids: string[] } | { error: string }
360
361function grow(project: Project, raw: unknown, at: Place): Grown {
362 if (!isRecord(raw)) return { error: 'a block must be an object' }
363 const block = readType(raw.type, raw.kind)
364 if ('error' in block) return { error: block.error }
365 // The blocks a kind starts with are left out: an edit from chat brings its own.
366 const added = addNode(project, { ...block, name: typeof raw.name === 'string' && raw.name.trim() !== '' ? raw.name : undefined, bare: true }, at)
367 if (added.error || added.id === undefined) return { error: added.error ?? 'could not add' }
368 const id = added.id
369 const knobs = knobsError(raw.knobs, id)
370 if (knobs) return { error: knobs }
371 const patched = updateNode(added.project, id, patchOf({ logic: raw.logic, knobs: raw.knobs, match: raw.match }))
372 if (patched.error) return { error: `${id}: ${patched.error}` }
373 let current = patched.project
374 const ids = [id]
375 const children = raw.children
376 if (children !== undefined && children !== null && !Array.isArray(children)) return { error: `${id}: children must be an array` }
377 for (const [index, child] of (Array.isArray(children) ? children : []).entries()) {
378 const inner = grow(current, child, { parentId: id, index })
379 if ('error' in inner) return inner
380 current = inner.project
381 ids.push(...inner.ids)
382 }
383 return { project: current, ids }
384}
385
386/** One refused op refuses them all. */
387export function applyOps(before: Project, ops: unknown): Edit {
388 if (!Array.isArray(ops)) return { ok: false, error: 'apply needs `ops`: an array of { op: add | update | move | remove, … }' }
389 let project: Project = before
390 const touched: string[] = []
391 const notes: string[] = []
392
393 for (const [index, op] of ops.entries()) {
394 const kind = isRecord(op) ? op.op : undefined
395 const refuse = (error: string): Edit => ({ ok: false, error: `ops[${index}]${typeof kind === 'string' ? ` (${kind})` : ''}: ${explain(error)}. Nothing was changed.` })
396 if (!isRecord(op)) return refuse('an op must be an object')
397 if (kind === 'add') {
398 const at = placeOf(project, op)
399 if (typeof at === 'string') return refuse(at)
400 const grown = grow(project, op, at)
401 if ('error' in grown) return refuse(grown.error)
402 project = grown.project
403 const beside = op.after ?? op.before
404 const note = typeof beside === 'string' && grown.ids[0] !== undefined ? armNote(project, grown.ids[0], beside) : null
405 if (note !== null) notes.push(note)
406 continue
407 }
408 const id = op.id
409 if (kind !== 'update' && kind !== 'move' && kind !== 'remove') return refuse(`op must be one of ${OP_KINDS.join(', ')}`)
410 if (typeof id !== 'string') return refuse('needs the `id` of a block')
411 if (!findNode(project, id)) return refuse(`no block ${id}`)
412 if (kind === 'remove') {
413 const removed = removeNode(project, id)
414 if (removed.error) return refuse(removed.error)
415 project = removed.project
416 continue
417 }
418 if (kind === 'move') {
419 // The place is read with the block lifted out, as moveNode counts it.
420 if ((op.after ?? op.before ?? op.parent ?? null) === null) return refuse('needs after, before or parent')
421 const at = placeOf(removeNode(project, id).project, op)
422 if (typeof at === 'string') return refuse(at.startsWith('no block') ? `${at} outside ${id}` : at)
423 const moved = moveNode(project, id, at)
424 if (moved.error) return refuse(moved.error)
425 project = moved.project
426 touched.push(id)
427 continue
428 }
429 if (op.type !== undefined || op.kind !== undefined) {
430 const now = findNode(project, id)
431 const asked = readType(op.type ?? now?.type, op.kind)
432 if ('error' in asked) return refuse(asked.error)
433 // A type said again with no kind leaves the kind the block has; `kind: ""` makes it plain.
434 const kept = op.kind === undefined && asked.kind === undefined && asked.type === now?.type ? now.kind : asked.kind
435 const retyped = retypeNode(project, id, asked.type, kept)
436 if (retyped.error) return refuse(retyped.error)
437 project = retyped.project
438 }
439 const knobs = knobsError(op.knobs, id)
440 if (knobs) return refuse(knobs)
441 const updated = updateNode(project, id, patchOf(op))
442 if (updated.error) return refuse(updated.error)
443 project = updated.project
444 }
445 return checked(before, project, touched, notes)
446}
447
448// What the tool answers with
449
450// The reports' fixed words, read back by `resultLine`.
451const NO_LINTS = 'Lints: none.'
452const LINTS_HEAD = 'Lints (advisory: fix them, or tell the user why they stand):'
453const READ_HEAD = 'as it is on the board now'
454const SAVED_HEAD = 'saved and shown on the board: '
455const NO_CHANGE = 'nothing differs from before'
456
457function lintLines(project: Project): string[] {
458 const lints = lint(project)
459 if (lints.length === 0) return [NO_LINTS]
460 return [LINTS_HEAD, ...lints.map(one => `- ${one.nodeId} [${one.rule}]: ${one.message}`)]
461}
462
463/** `revision` counts every change to the project this session, by hand or from chat: an answer that names an older one is stale. */
464export type ReadState = { open: boolean; selectedId: string | null; locked: boolean; revision?: number }
465
466function revisionWords(revision: number | undefined): string {
467 return revision === undefined ? '' : ` Revision ${revision}: the user edits the board by hand, so in a later turn read again before relying on this, unless a Conductor note with that prompt says what changed.`
468}
469
470export function readReport(project: Project, state: ReadState): string {
471 const selected = state.selectedId === null ? undefined : findNode(project, state.selectedId)
472 const where = state.open ? `open on the board; selected block ("this block"): ${selected ? `${selected.id} (${typeName(selected)} "${selected.name}")` : 'none'}` : 'not open on the board'
473 return [
474 `Project "${project.name}" ${READ_HEAD} (${where})${state.locked ? '. A run of it is in progress: editing is locked until it ends' : ''}.${revisionWords(state.revision)}`,
475 serializeProject(project).trimEnd(),
476 ...lintLines(project),
477 ].join('\n')
478}
479
480export function editReport(project: Project, change: Change, revision?: number): string {
481 const parts = [
482 change.added.length > 0 ? `added ${change.added.join(', ')}` : '',
483 change.changed.length > 0 ? `changed ${change.changed.join(', ')}` : '',
484 change.removed.length > 0 ? `removed ${change.removed.join(', ')}` : '',
485 ].filter(Boolean)
486 return [
487 `Project "${project.name}" ${SAVED_HEAD}${parts.length > 0 ? parts.join('; ') : NO_CHANGE}.${revisionWords(revision)}`,
488 ...(change.notes ?? []).map(note => `Note: ${note}`),
489 'Now:',
490 ...outline(project),
491 ...lintLines(project),
492 ].join('\n')
493}
494
495/** False where the stored project holds a text Claude neither sent nor saw (`seen`), such as what a kind fills in: Claude must read again. */
496export function knownAfterEdit(stored: Project, seen: Project | undefined, input: unknown): boolean {
497 const rows = flatten(stored)
498 if (rows.length > OUTLINE_MAX) return false
499 const sent = new Set<string>()
500 const collect = (value: unknown): void => {
501 if (typeof value === 'string') sent.add(value)
502 else if (Array.isArray(value)) value.forEach(collect)
503 else if (isRecord(value)) Object.values(value).forEach(collect)
504 }
505 collect(input)
506 const texts = (node: ProjectNode | undefined): string[] => (node ? [`logic=${node.logic ?? ''}`, ...Object.entries(node.knobs ?? {}).map(([key, value]) => `${key}=${String(value)}`), ...(node.match ?? []).map(one => `match=${one}`)] : [])
507 const before = new Map((seen ? flatten(seen) : []).map(row => [row.node.id, new Set(texts(row.node))]))
508 const known = (id: string, text: string): boolean => text === 'logic=' || sent.has(text.slice(text.indexOf('=') + 1)) || before.get(id)?.has(text) === true
509 return rows.every(({ node }) => texts(node).every(text => known(node.id, text)))
510}
511
512export function projectOfPath(root: string, cwd: string, path: string): string | null {
513 if (path === '') return null
514 const absolute = path.startsWith('/') ? path : `${cwd.replace(/\/+$/, '')}/${path}`
515 const parts: string[] = []
516 for (const part of absolute.split('/')) {
517 if (part === '' || part === '.') continue
518 if (part === '..') parts.pop()
519 else parts.push(part)
520 }
521 const prefix = `${root.replace(/\/+$/, '')}/${PROJECT_DIR}/`
522 const clean = `/${parts.join('/')}`
523 if (!clean.startsWith(prefix)) return null
524 const file = clean.slice(prefix.length)
525 return /^[a-z0-9-]+\.json$/.test(file) ? file.slice(0, -'.json'.length) : null
526}
527
528/** For the message row and the undo history: `added n12; changed n3, n4`. */
529export function changeWords(change: Change): string {
530 const list = (ids: string[]): string => (ids.length > 4 ? `${ids.slice(0, 4).join(', ')} and ${ids.length - 4} more` : ids.join(', '))
531 return [change.added.length > 0 ? `added ${list(change.added)}` : '', change.changed.length > 0 ? `changed ${list(change.changed)}` : '', change.removed.length > 0 ? `removed ${list(change.removed)}` : ''].filter(Boolean).join('; ')
532}
533
534// The transcript draws these lines in place of the call's input and its report; Claude reads both whole.
535
536const LINE_MAX = 120
537
538function countBlocks(nodes: unknown): number {
539 return Array.isArray(nodes) ? nodes.reduce((sum: number, node: unknown) => sum + (isRecord(node) ? 1 + countBlocks(node.children) : 0), 0) : 0
540}
541
542const counted = (n: number, word: string): string => `${n} ${word}${n === 1 ? '' : 's'}`
543
544/** The call's row: `apply prep-revamp: 3 ops`. */
545export function callLine(input: unknown): string {
546 const call = isRecord(input) ? input : {}
547 const action = typeof call.action === 'string' && call.action !== '' ? oneLine(call.action) : 'call'
548 const name = typeof call.name === 'string' && call.name.trim() !== '' ? ` ${oneLine(call.name)}` : ''
549 const size = action === 'apply' && Array.isArray(call.ops) ? `: ${counted(call.ops.length, 'op')}` : (action === 'write' || action === 'attach') && Array.isArray(call.nodes) ? `: ${counted(countBlocks(call.nodes), 'block')}` : ''
550 return clip(`${action}${name}${size}`, LINE_MAX)
551}
552
553/** The result's row: the change and the problems the report names, or a refusal's reason. A text no report wrote gives its first line. */
554export function resultLine(text: string, isError: boolean): string {
555 const lines = text.replace(/<\/?tool_use_error>/g, '').trim().split('\n')
556 const head = lines[0] ?? ''
557 if (isError) return clip(oneLine(head.replace(/^Error: /, '').replace(/\s*Nothing was changed\..*$/, '')) || oneLine(head), LINE_MAX)
558 const at = lines.indexOf(LINTS_HEAD)
559 let problems = 0
560 if (at >= 0) while (lines[at + 1 + problems]?.startsWith('- ')) problems++
561 const lints = at >= 0 ? counted(problems, 'problem') : lines.includes(NO_LINTS) ? 'no problems' : ''
562 let words = ''
563 const saved = head.indexOf(SAVED_HEAD)
564 if (saved >= 0) {
565 const said = head.slice(saved + SAVED_HEAD.length).split('.')[0] ?? ''
566 const change: Change = { added: [], changed: [], removed: [] }
567 for (const part of said.split('; ')) {
568 const space = part.indexOf(' ')
569 const verb = part.slice(0, space)
570 if (verb === 'added' || verb === 'changed' || verb === 'removed') change[verb].push(...part.slice(space + 1).split(', '))
571 }
572 words = changeWords(change) || 'saved, nothing changed'
573 } else if (head.includes(READ_HEAD)) {
574 const end = lints === '' ? lines.length : lines.indexOf(at >= 0 ? LINTS_HEAD : NO_LINTS)
575 const parsed = parseProject(lines.slice(1, end).join('\n'))
576 words = parsed.ok ? counted(flatten(parsed.project).length, 'block') : 'read'
577 } else return clip(oneLine(head), LINE_MAX)
578 return clip([words, lints].filter(Boolean).join(' · '), LINE_MAX)
579}
580
581/** Sent, unseen, with a prompt when the board changed by hand and the change itself cannot be said (`changedNote`). */
582/** `elsewhere`: the change came from another session saving the file, not from the user's hand on this board. */
583function changedLine(name: string, elsewhere: boolean): string {
584 return elsewhere ? `the "${name}" workflow project was changed in another session` : `the user changed the "${name}" workflow project on the board by hand`
585}
586
587export function staleNote(name: string, revision: number, elsewhere = false): string {
588 return `Conductor: ${changedLine(name, elsewhere)} since you last read or edited it (it is now revision ${revision}). This note cannot say what changed, so what you know of it is out of date: call ${TOOL_FULL_NAME} with action "read" before you describe, review or edit it.`
589}
590
591function blockOf(node: ProjectNode, deep: boolean): Record<string, unknown> {
592 const { id, type, kind, name, logic, knobs, match, children } = node
593 const own = { id, type, kind, name, logic, knobs: knobs && Object.keys(knobs).length > 0 ? knobs : undefined, match }
594 return deep && children ? { ...own, children: children.map(child => blockOf(child, true)) } : own
595}
596
597const TOP = ''
598
599function childIds(rows: readonly Row[]): Map<string, string[]> {
600 const out = new Map<string, string[]>()
601 for (const row of rows) out.set(row.parentId ?? TOP, [...(out.get(row.parentId ?? TOP) ?? []), row.node.id])
602 return out
603}
604
605const whereWords = (parentId: string): string => (parentId === TOP ? 'at the top level' : `inside ${parentId}`)
606
607/** Everything that differs between the project as Claude last saw it and the board, so that the one and the lines give the other exactly. */
608function boardChanges(seen: Project, now: Project): string[] {
609 const old = new Map(flatten(seen).map(row => [row.node.id, row]))
610 const rows = flatten(now)
611 const kids = childIds(rows)
612 // A block is placed by the one before it: with the blocks that stayed keeping their order, that says the whole order.
613 const place = (row: Row): string => `${whereWords(row.parentId ?? TOP)}, ${row.index === 0 ? 'first' : `after ${kids.get(row.parentId ?? TOP)?.[row.index - 1]}`}`
614 const added: string[] = []
615 const changed: string[] = []
616 const moved: string[] = []
617 // A new block is said whole, so nothing it holds is said again.
618 const within = new Set<string>()
619 for (const row of rows) {
620 const { id } = row.node
621 const was = old.get(id)
622 if (row.parentId !== undefined && within.has(row.parentId)) within.add(id)
623 else if (!was) {
624 within.add(id)
625 added.push(`- ${place(row)}: ${JSON.stringify(blockOf(row.node, true))}`)
626 } else {
627 if (JSON.stringify(blockOf(was.node, false)) !== JSON.stringify(blockOf(row.node, false))) changed.push(`- ${JSON.stringify(blockOf(row.node, false))}`)
628 if (was.parentId !== row.parentId) moved.push(`- ${id}: ${place(row)}`)
629 }
630 }
631 // Blocks that stayed in their container but not in their order: the container's whole order is said.
632 const before = childIds([...old.values()])
633 const order: string[] = []
634 for (const [parentId, ids] of kids) {
635 if (within.has(parentId)) continue
636 const stayed = ids.filter(id => (old.get(id)?.parentId ?? TOP) === parentId && old.has(id))
637 const asWas = (before.get(parentId) ?? []).filter(id => stayed.includes(id))
638 if (stayed.join() !== asWas.join()) order.push(`Order ${whereWords(parentId)} now: ${ids.join(', ')}.`)
639 }
640 const removed = [...old.keys()].filter(id => !findNode(now, id))
641 return [
642 ...(added.length > 0 ? ['Added, each whole (a block you knew that is written inside one now stands there):', ...added] : []),
643 ...(changed.length > 0 ? ['Changed, each as it is now (what it holds is as before, but for what these lines say):', ...changed] : []),
644 ...(moved.length > 0 ? ['Moved, each with everything it holds:', ...moved] : []),
645 ...order,
646 ...(removed.length > 0 ? [`Removed: ${removed.join(', ')}.`] : []),
647 ]
648}
649
650/** In place of `staleNote` when the project as Claude last saw it is at hand. Null when saying the change takes more than the project does: a read is cheaper. */
651export function changedNote(name: string, revision: number, seen: Project, now: Project, selectedId: string | null, elsewhere = false): string | null {
652 const lines = boardChanges(seen, now)
653 if (lines.join('\n').length > serializeProject(now).length) return null
654 const selected = selectedId === null ? undefined : findNode(now, selectedId)
655 return [
656 `Conductor: ${changedLine(name, elsewhere)} since you last read or edited it (it is now revision ${revision}). ${lines.length > 0 ? 'What follows is everything that changed' : 'Nothing in it differs from what you last saw'}: with it you know the board as it is, so this is the note that stands in for a read: none is needed. An edit with ${TOOL_FULL_NAME} from here is accepted.`,
657 ...lines,
658 `Selected block ("this block"): ${selected ? `${selected.id} (${typeName(selected)} "${selected.name}")` : 'none'}.`,
659 ].join('\n')
660}
661
662/** When the hooks module takes the mark's ids back: once the graph has shown it. */
663export const FLASH_CLEAR_MS = FLASH_MS + 400
664
665/** The selection goes to the first new block so the graph scrolls to it. `seq` only ever grows, so the graph can tell one edit from the next. */
666export function showEdit(ui: ProjectUi, name: string, project: Project, change: Change): ProjectUi {
667 const same = ui.name === name && ui.status === 'ready'
668 // A draft being laid out stays so under a later edit of Claude's turn (a lint fixed): the turn's end is what ends it.
669 // An edit never lands under the results of a run that is over: they are put away.
670 const base: ProjectUi = same ? { ...ui, picker: null, confirmId: null, editing: false, freshId: null, drafting: ui.drafting === 'show' ? 'show' : null, notice: null, runCleared: true, unsaved: false } : { ...carryUi(ui, initialUi()), name, status: 'ready' }
671 const still = same && ui.selectedId !== null && findNode(project, ui.selectedId) ? ui.selectedId : null
672 const selectedId = change.added[0] ?? still ?? change.changed[0] ?? project.nodes[0]?.id ?? null
673 // An edit from chat is undone like any other.
674 const said = changeWords(change)
675 return { ...base, selectedId, notice: said !== '' ? `Claude ${said} · ${UNDO_HINT}` : base.notice, flash: { ids: [...change.added, ...change.changed], seq: (ui.flash?.seq ?? 0) + 1 } }
676}
677
678/** The mark is spent: the ids go, the count stays. */
679export function clearFlash(ui: ProjectUi, seq: number): ProjectUi {
680 return ui.flash && ui.flash.seq === seq && ui.flash.ids.length > 0 ? { ...ui, flash: { ids: [], seq } } : ui
681}
682src/project/history.ts 32 lines1// Undo and redo: the projects each change left behind, newest last, with what the change was in words.
2// One history per project, held for the session by the hooks module.
3
4import type { Project } from './model'
5
6/** A project as it stood, and the change that led away from it (`deleted n7 "verify"`). */
7export type HistoryEntry = { project: Project; what: string }
8
9export type History = { undo: HistoryEntry[]; redo: HistoryEntry[] }
10
11const HISTORY_MAX = 50
12
13/** What every message announcing a change ends with. */
14export const UNDO_HINT = '[u] Undo'
15export const REDO_HINT = '[y] Redo'
16
17export function remember(history: History | undefined, before: Project, what: string): History {
18 const undo = [...(history?.undo ?? []), { project: before, what }]
19 return { undo: undo.slice(Math.max(0, undo.length - HISTORY_MAX)), redo: [] }
20}
21
22export function travel(history: History | undefined, current: Project, way: 'undo' | 'redo'): { history: History; entry: HistoryEntry } | null {
23 const from = way === 'undo' ? (history?.undo ?? []) : (history?.redo ?? [])
24 const entry = from.at(-1)
25 if (!history || !entry) return null
26 const left = from.slice(0, -1)
27 const kept: HistoryEntry = { project: current, what: entry.what }
28 return way === 'undo'
29 ? { history: { undo: left, redo: [...history.redo, kept].slice(-HISTORY_MAX) }, entry }
30 : { history: { undo: [...history.undo, kept].slice(-HISTORY_MAX), redo: left }, entry }
31}
32