SLOPSHOPPER

rabe

Watch Claude Code's background work: subagents, Codex jobs, shells, monitors, cron jobs and workflows.

panebandspinnerguardcommandprompt
★ 3v0.10.1MITupdated 2026-10-25lorenzh/rabe
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · rabe
│ ┃ Rabe ✕ › fix the failing auth test and add an audit log call │ ┃ 1: Items 4 2: Cost 3: Effects 4: Timelin │ ┃ ─━━━━━━━━━━───────────────────────────────── ⏺ Read(src/auth.ts) │ ┃ [ s ] [ x: stop ] [ g: stop group ] [ r: rem ⎿ Read 6 lines │ ┃ search: title, kind or command ⏎ filter ⏺ Update(src/auth.ts) │ ┃ ▾ FAILED 1 ⎿ Added 2 lines, removed 1 line │ ┃ ▌✗ Run the test suite · foreground fail ⏺ Bash(bun test) │ ┃ … ⎿ 3 pass, 1 fail │ ┃ ▾ SHELLS 3 ended │ ┃ ✓ Show environment file · foreground do ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ✓ Clean build output and push · foregro… do │ ┃ ✓ Show working tree status · foreground do ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ › /rabe │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Rabe
1: Items 4 2: Cost 3: Effects 4: Timeline ─━━━━━━━━━━───────────────────────────────────────────── [ s ] [ x: stop ] [ g: stop group ] [ r: remove ] [ a: remov search: title, kind or command ⏎ filter ▾ FAILED 1 ▌✗ Run the test suite · foreground failed just now ▾ SHELLS 3 ended ✓ Show environment file · foreground done just now ✓ Clean build output and push · foregro… done just now ✓ Show working tree status · foreground done just now ✗ Run the test suite · foreground · failed tab to select · esc close
README

<img src="docs/assets/banner-light.svg" alt="rabe" width="308" height="84">

rabe

See what Claude Code runs in the background.

Rabe (German for raven) is a Claude Code mod. It shows your subagents, Codex jobs, background shells, monitors, cron jobs and workflows in one place. A short band above the prompt shows what runs now. The /rabe command opens a pane with the full detail.

Rabe in a Claude Code session: the band above the prompt counts one claude and three shells with the session cost; /rabe opens the pane, and the Items tab groups the agent and the shells with the detail of the selected row beside the list, where the agent shows its model and effort (haiku-5-5·medium); the arrow keys move to a shell and its command; the Cost tab shows the estimate in dollars with partial rows for the main session, o groups the rows by model and i by agent; the Effects tab shows the diff of the edited file beside the list; the Timeline tab shows the bars and who started what, and Esc closes the pane

Status: early development. See releases, the changelog, and the documentation index.

What Rabe shows

KindIn the bandIn the pane
Claude subagentsCount (claude)Name when Claude Code provides one, otherwise the task description; model and effort (every change, newest six), tokens, prompt, turns and agent id
WorkflowsCount (workflow)Phases and their agents in start order, with model and effort, tokens and time (the model chip drops on a narrow pane); select an agent to open it
Codex jobs (from the Codex plugin)Count (codex)Model, effort and sandbox, tokens, the prompt, each message and command with its exit code, the thread id (c copies codex resume <thread id>)
Background shellsCount (shell)Bash description and task id, output lines, exit code and port from output or the process tree’s listening sockets on Linux; a foreground command shows as a running shell after 2 s and stays as an ended row (done, failed, or stopped when refused or interrupted) when it returns, also a quick one; the newest 50 ended foreground rows are kept, and they go before other ended items when the list is full. A detached codex exec -o <file> & stays running until its result file appears. A direct codex exec (foreground or background) is listed with the Agents as codex, with its model, effort and sandbox from the command flags. Rabe then finds its Codex session file, by the session id: that a foreground run prints on stderr (leave stderr unredirected) or by its start time, and shows tokens, cost, model and thread like a Codex job; only this run's own turn counts, not a later resume of the thread; when the match is not unique, the thread is already another run's or Codex job's, or the file's model is not the one -m asked for, tokens and cost show n/a. A detached run without -o stays running until its session file records the end
MonitorsCount (monitor)Each line with the time Rabe received it
Cron jobs and /loop wakeupsCount (cron)The next five runs while running; confirmed last fire time, fire count and observed turn end; deleted jobs say deleted
CostSession cost and tokens of the background workCost tab: tokens and an estimate in dollars (≈ $0.16) per worker, workers that look stuck

The band is one line of counts, one chip per kind with failures from the last 10 minutes first (✗ 1 shell failed), then the cost, under an empty row so the status line above does not touch it. Its cost label says session; its token label says bg and includes the cached share when known. It shows the session cost Claude Code reports, or session n/a when that cost is unknown; it does not replace it with a sum of worker estimates or show a top-agent suffix. It shortens readable chip labels only when the full labels and cost do not fit; when needed, it puts the dollar amount first and drops the token part. When Claude Code gives the band only one row, the empty row goes. The names are in the pane. When nothing runs, it draws nothing.

A cron detail can show last fired 10:55 · 3 fires · turn answered. The end word describes a turn Rabe observed, not job success. When Rabe cannot confirm a fire, it shows no fire details. The fire time and count follow the transcript by the end of the fire's turn, when Claude Code has written the fire by then. Wakeups show none.

When the readable form repeats the cron expression, cron detail shows the schedule once. Workflow detail says 1 agent for one child in both the run facts and cost panel.

The pane has four tabs:

  • Items

The Items tab: agents, shells, a monitor and a cron job grouped by kind; the arrow keys move the focus and the detail beside the list follows; Enter opens a workflow with its agents under the phases Draft and Check, then a running agent with its brief and turns, and b goes back

All items grouped by kind, with a search field. Stop group and remove ended act only on rows the search shows. The agent, shell, monitor and cron headers show running and ended counts. The agent header also counts idle teammates and shows counts by kind. Shell rows show the Bash description or command, followed by the task id. Rabe collapses command whitespace for the row. A shell with no lines says No output yet while it runs and No output after it ends. Shells and monitors that an agent started show under the name of that agent. A Codex job shows under the agent that started it, also when it starts while the pane is open. The Codex plugin starts its jobs through a Claude agent that only passes the request on (codex:codex-rescue); that agent has no row of its own, and its tokens and cost count toward the job. Rabe links the two only when the evidence fits one job: the agent's command named the job, or the job started while the command ran and has its prompt or its thread. A link made by the prompt is checked again when the command returns: if it names another job or thread, the link moves to that job, and while two jobs fit, neither is linked. In the job's detail, f opens the agent, with its turns, id and transcript. If the pane is 90 columns or wider, the selected item shows beside the list. Then c (copy), m (message) and d (delete a cron job) act on the selected row from the list, without Enter. Turns with tools and no text show only their tool lines. Cron forecast times use the same duration format as the rest of the pane. The group-stop button shows how many rows g will stop.

Idle teammates show idle in Items, Cost and Timeline. They count as neither running nor ended. The band excludes them from work counts. Cost never flags them stuck. Remove ended keeps them. Plain subagents keep their existing behavior.

You can message or stop an idle teammate. Waking it restores running under the same id. Timeline keeps a continuous lifetime bar through idle gaps. Agents held on work or approval (waiting) still count as running.

  • Cost

The Cost tab: the session cost, the estimated dollars of the Claude agents, the session id, and a token bar with an estimate per agent; c copies the resume command

The session cost as /cost totals it, this session's id (c copies claude --resume <id>), the estimated dollars of the Claude agents and of the Codex jobs when those sources exist, and per agent, Codex job and the main session a bar of tokens and its estimate. Worker names use more of the pane width; in a 26-column pane a name keeps its first 23 characters. The header says "sorted by tokens when opened". Workers keep that order while the pane is open, and new workers follow them. Agents that look slow or stuck show under "Load".

i, o and h group the rows by agent, by model or by harness (Claude Code against Codex); one grouping is active, and the rows keep their order while the pane is open. The main session gets a row marked partial, one per model when grouped by model and one combined row otherwise: it counts only the steps Rabe saw since it loaded, and its dollars are an estimate at the 1-hour cache-write rate (n/a without a price). In a narrow pane a group row puts its numbers on a second line; a long name loses its middle, never (partial). Claude rows add up to the band; Codex is shown on top. A forwarding agent's spend counts once, in its Codex job.

  • Effects

The Effects tab: the files raven.md and notes.md with the agent or main session that wrote them, the main worktree with who worked there, and port 4173 with its ssh -L line, which c copies

Files that agents, Codex jobs and the main session changed, with who changed each and how (edit, write, codex add, deleted), a warning when two of them change the same file, the git worktrees files changed in with their branch and who worked there (the main session included), and open ports with the ssh -L command to reach them. Long file paths use a middle ellipsis and keep both ends. When a file has multiple changes, the label says N changes: write, edit. Files written through shell commands show as via shell when Claude Code reports them in a Bash diff or Rabe confirms them on disk. Script edits need auto mode or the Claude Code setting bashEditDiffEnabled: true in your user settings (project settings do not count). Shared, skipped or unavailable diffs leave only the disk fallback. Relative paths use the main session's current folder or the agent's known cwd. Unknown folders and uncertain directory changes show nothing for relative paths. Without a usable Bash diff, Rabe skips commands inside if or loops and paths with a glob or $var. Script edits without a usable diff stay invisible. Background commands record no edits. Enter or a click on a file opens the agent or Codex job that changed it last, or copies the path of a main-session file. In a Git repository each file shows relative to the worktree that holds it. The selected file's diff shows beside the list at 90 columns or more, with who changed it and when; below that, one summary line (+12 -3 · 2 hunks · edit by <title>). The diff is the latest change Rabe recorded as it happened, cut at 200 lines. A file with no recorded content says diff n/a: content not recorded, a Write too large to diff says diff n/a: file too large, and a delete says deleted.

  • Timeline

The Timeline tab: a bar per shell, monitor, agent, cron job and workflow over the last minutes, who started what, and the previous session with its cost; w widens the window

A bar per item over the last 4 hours, who started what, and a summary of the previous session in this project with its id (c copies claude --resume <id>; a summary saved by Rabe 0.3 or older shows n/a). A short Timeline window shows its start time when no round clock label fits. Cron ticks show scheduled runs, without delays while the session is busy or jitter. Its cost and duration are the whole session's, its tokens only the background items'; each line says which. Items that ended before the window fold into one line (+37 older items, ended before 10:20); a bar that started earlier is cut at the left edge with ◂. w widens the window for the open pane, from 4 hours to 12 hours to the whole session.

Install

Type this at a Claude Code prompt:

/plugin install rabe --marketplace lorenzh/rabe

Then run /reload-plugins or start a new session: a plugin you install does not load in the running session.

Usage

The band shows by itself while background work runs. Type /rabe to open the pane, including while Claude is working. In the terminal the pane docks beside the transcript. Drag its left edge to make it wider.

KeyWhat it does
↑ / ↓Move to the previous / next row; the detail beside the list follows. In a scrolling pane, arrows and view-changing presses take turns while they move focus; a pending stop, delete or message does not block them
EnterOpen the row that has the focus; a click moves the focus onto the clicked row
Click on a rowSelect the row; click it again to open it. A click on the row that has the focus opens it at once
Tab / Shift+TabMove the focus through rows, tabs and buttons
bGo back to the tab and row the detail was opened from (Items without a stored origin)
1 to 4Switch tab and focus its marked row. An empty tab keeps the focus on its label
sFocus search. Enter focuses the first matching row. Esc keeps the pane and the filter open when the query is not empty, but Claude Code then hands the keys to the prompt: press ctrl+x tab to return to the pane
kClear the filter (dim while there is none)
xStop the selected item
gStop the group among rows the search shows (the button shows its count), or the workflow run of the selected run or workflow agent
rRemove the selected row once it is done, failed or stopped
aRemove every done, failed or stopped row the search shows
mSend a message to an agent. Enter sends it and gives the keys back to the pane. If the pane was redrawn as you pressed Enter, the text is still sent once. A toast says Message not sent when the send was refused, or Delivery unknown when it failed after it started; Rabe never retries, and an unknown delivery may already have reached the agent
fOpen the Claude agent that forwarded a Codex job (it has no row of its own); b then goes back to the job's row
cCopy the command, the prompt, the ssh -L line, an agent's id, or the command that resumes a session or a Codex thread. If the clipboard cannot be reached (for example over SSH in a terminal without OSC 52), a message shows the text to select
dDelete a running cron job
wOn the Timeline tab: show more time (4 h, 12 h, the whole session, then 4 h again)
Mouse wheelScroll the pane; on the terminal a long list scrolls under the tabs and buttons, which stay in view. In a short pane only the tabs stay, and the buttons and the search field scroll with the list
EscClose the pane

A deleted cron job shows no next runs, and its delete button stays dim. The previous-session summary counts only cron jobs still running when the session ends. Delete failures show plain text.

After Rabe successfully stops work, stops a group, deletes a cron job or sends a message to an agent, it adds a short note with the item kind and id to the next prompt's private context. Titles, prompts and message text are never included. Notes are capped at 20 and clear after that prompt enters.

The buttons under the tabs show the actions of the current view. Unavailable controls keep their visible labels and stay dim. Their hotkeys do nothing and stay caught while the pane holds the keys outside input fields. Rabe adds no blank buttons for letters a view does not own.

If a list redraw removes a row or search handler during an event, Rabe drops that stale action and keeps the pane's keys.

When all rows fit, fast arrow bursts after a tab switch keep their order and wrap direction. A second tab press keeps arrows received during the first switch. After a refused focus move, later independent arrows go straight to the engine.

A tab key, a fold or a submitted search waits for the new view to draw (usually about 100 to 130 ms, at most about 400 ms), then moves the focus to its row. If you press another key in the pane during that wait, Rabe cancels the move to the row, and your key then works as usual from where the focus is.

Known limit: in a burst such as 2 1 Down Down Down Down with 30 to 50 ms between keys, Claude Code sometimes drops the tab hotkey (1) before it reaches any hook of Rabe, so the pane stays on the Cost tab. A live trace on Claude Code 2.1.296 lost it in 4 of 42 runs (about 1 in 10) on the same machine, and Rabe cannot fix a key it never receives. Keys sent about 100 ms apart or more are not affected in the measurements. See the measurement.

ViewLetters caught outside input fields
Items listx g r a; s k where search is available (k stays caught and dim while there is no filter); beside the detail of the selected row also c and d, and m on surfaces that support input fields, dim when the selected row has no such action
Agent detailb c x; m on surfaces that support input fields
Workflow agent detailb c; g when the parent run is known; no x or m
Workflow detailb g
Shell or monitor detailb x; c when a command is known
Codex detailb x; c when a thread id is known; f when a forwarder is known
Cron job detailb c d
Scheduled wakeup detailb c; no d
Costi agent, o model and h harness grouping; c when the current session id is known
Effectsc on the first port's SSH row while that port exists
Timelinew when timelineHours is greater than zero; c when the previous session id is known

Beside the detail, c copies the selected row's prompt, command, id or resume command, and d deletes the selected cron job while the job is active.

Other letters still reach the prompt because the mod API has no key hook. The letters above also reach the prompt in views without their control. For example, x reaches the prompt on Cost and w does so on Timeline with timelineHours: 0. A focused input field takes every key.

An opened item keeps its recorded turns, steps or output lines in its detail. Use ↑↓, PageUp, PageDown or the wheel to scroll. The scroll hint shows only when the opened detail needs scrolling. Claude Code sets the pane's height. The split preview marks hidden agent text or counts older output lines. Press Enter to open the full detail.

Agent answers keep up to 16,000 characters each. Longer answers end with …. The transcript keeps the original answer. Markdown stays plain text. Wrapped bullet and numbered lists keep their markers beside the start of a long path. Long tool summaries end with …. Answers already shortened by an older version stay shortened.

Shell and monitor commands and cron prompts appear in full in the detail. Text wraps at the detail width. Each CR, LF or CRLF line break shows ↵. Read the full text before pasting it into a shell. Copy does not check commands or prompts. Pasted commands run with your shell's permissions.

Copy replaces terminal control and format characters with ?. Commands and prompts keep tabs and line breaks. Single-line fields refuse CR or LF: ids, paths, ssh -L lines and resume commands. Resume ids and agent ids must match [A-Za-z0-9_][A-Za-z0-9_.-]*. Invalid ids show n/a with no copy button.

A success toast names the copied field and counts its text: Copied command · 3 lines · 412 chars. CRLF counts as one line break. Characters are Unicode code points after the control and format filter. Success toasts contain no copied text.

Other toasts flatten whitespace and replace Unicode control (Cc) and format (Cf) characters with ?. Wide characters, emoji and combining marks stay. Toasts name deleted cron jobs by id. Copy failures show the reason through the same filter. Reasons include no-clipboard and refused. If the filter leaves the copied text unchanged, the failure toast offers the exact text. Cron prompts never appear in toasts.

The search button shows the active query, cut with … when long. The search field keeps the full query at every width. The filter stays visible after Enter and after reopening the pane. To clear it, press k, or submit an empty search. The search label shows ▸ while the field has the focus. A query that matches nothing shows No item matches and keeps the focus in the field. Stop group and remove ended act only on the filtered rows.

With the mouse, click a row once to select it and again to open it. Click a tab to switch to it, a group name to fold the group, a button to press it, or a row on the other tabs to open it. The wheel scrolls the pane. A click on a row moves the focus ring onto it, so the keys and the arrows continue from there. A click on a tab switches to it and puts the focus on the tab's marked row, as the keys 1 to 4 do: Claude Code does not tell Rabe a click from a hotkey, so the focus cannot rest on the tab label after a click. A click does not give the pane the keys: ctrl+x tab does. The mouse works only in Claude Code's fullscreen layout: type /tui fullscreen to turn it on. Without it, use the keys.

On the list, the stop keys x and g and the remove key r work only after you move onto a row yourself, with an arrow, Tab or a click. Until then, and after the view or the selected row changes without you, they are dim, so a key press never stops something you did not pick. If they stay dim after a click, the pane does not have the keys yet: press ctrl+x tab, then move onto the row with Tab or an arrow.

/rabe asks for the keyboard as soon as the command clears the prompt. Arrows also follow rapid view changes when every row fits.

While the pane is open, rows and buttons keep their places, so Enter acts on what you see under the focus. An item that starts after you open the pane goes into the group of its kind, after the rows already there; on the Effects tab, a new file or port goes into its section the same way. When it comes above the focused row, Rabe moves the focus back onto that row; until then, Enter on a row does nothing. A row that is gone leaves the Items list and the Effects tab at once, and the same rule applies: when the focused row moves up, Enter on a row does nothing until Rabe moves the focus back; when the focused row itself is gone, Enter on a row does nothing until you move the focus. Buttons and tabs never move. In an open item and on the Cost and Timeline tabs, a row that is gone stays as a dim gone slot until you change the view or close the pane. Type /rabe again to sort the lists.

Removed rows stay off the Items list and the band's counts for the rest of the session. They still show in a workflow's agent rows, phases and tokens, in the Cost rows and totals, on the Timeline and on the Effects tab, so no view loses work that ran. Running items are never removed; an item that runs again shows again. Ended items stay hidden even when a poll finds them again. A removed row leaves the list at once, with no gone slot; when it was the selected row, the selection moves to the next row (the previous one at the end of the list) and the keys go dim until you move onto a row again. Each tab keeps its own selected row: a visit to Cost, Effects or Timeline leaves the Items selection as it was, and a reopened pane puts the focus on the selected row of the tab you left.

Ended items keep their stop buttons in place. These buttons stay dim. Pressing them does nothing.

Commands:

  • /rabe: open the pane. On any attached surface (terminal, desktop app, VS Code panel, mobile; the last two are [not measured]) it opens the pane and adds no text. Where nothing can draw it (a plain claude -p run or an SDK session, or a host that cannot place the pane), it answers with text instead: the running, idle and ended counts and one count per kind, never a title or prompt.
  • /rabe-stop codex:<job id>: cancel a running Codex job. Use the job id shown in Rabe, not the thread id. Empty arguments or arguments without codex: show usage. To stop other items, use x in the pane.
  • /rabe-diag: (also in non-interactive sessions) show what each source read in its la
Source 51 files
hooks/register.tsx 180 lines
1import type { EngineInterface, Register } from 'claude-code'
2import type { RabeDiag } from '../types'
3import { diag } from './diag'
4import { collect, delayOf, mergeDiag, nextStep, type Pollers } from './loop'
5import type { RabeItem } from './model'
6import { type Change, commit, prune } from './registry'
7import { sources } from './sources'
8import { band } from './ui/band'
9import { builtin } from './ui/builtin'
10import { pane } from './ui/pane'
11import { hoursOf } from './ui/views/timeline'
12
13export const register: Register = (on, options) => {
14  const file = String(options.pricesFile ?? '')
15  const pollers: Pollers = []
16  let cancel = () => {}
17  let generation = 0
18  on('session.start', { cwd: /^/ }, async ($, e, next) => {
19    cancel()
20    const session = ++generation
21    pollers.length = 0
22    const started = await next(e)
23    let running = true
24    let due = 0
25    let idle = 0
26    const timer = $.clock.every(1000, () => {
27      if (running || session !== generation) return
28      running = true
29      void (async () => {
30        try {
31          const now = await $.clock.now()
32          const { value: items = [], version } = await $.state.get({ plugin: 'rabe', key: 'items' })
33          const step = nextStep(
34            now,
35            due,
36            items.some(item => item.status === 'running'),
37          )
38          if (step === 'skip') return
39          if (step === 'redraw') {
40            $.ui.invalidate('ui.render')
41            return
42          }
43          const collected = await collect([...pollers], items, now, false, () => $.clock.now())
44          if (session !== generation) return
45          await saveDiag($, collected.stats)
46          const changed = await write($, collected.change, {
47            version,
48            before: items,
49            items: collected.items,
50          })
51          const { value: current = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
52          const active = current.some(item => item.status === 'running')
53          const pace = delayOf(idle, active, changed)
54          idle = pace.idle
55          due = now + pace.delay
56          if (active || changed) $.ui.invalidate('ui.render')
57        } catch {
58          try {
59            due = (await $.clock.now()) + 2000
60          } catch {}
61        } finally {
62          running = false
63        }
64      })()
65    })
66    cancel = () => timer.cancel()
67    try {
68      const now = await $.clock.now()
69      const { value: items = [], version } = await $.state.get({ plugin: 'rabe', key: 'items' })
70      const collected = await collect([...pollers], items, now, true, () => $.clock.now())
71      if (session === generation) await saveDiag($, collected.stats)
72      if (session === generation)
73        await write($, collected.change, { version, before: items, items: collected.items })
74    } catch {
75    } finally {
76      running = false
77    }
78    due = (await $.clock.now()) + 2000
79    return started
80  })
81  sources(on, file, pollers)
82  band(on)
83  pane(on, hoursOf(options.timelineHours))
84  diag(on, options)
85  if (options.hideBuiltinTasks !== false) builtin(on)
86}
87
88// Writes the polls' records only when one changed. A version conflict retries
89// a few times; a refusal or an error leaves the records as they are, and the
90// items are written anyway.
91async function saveDiag(
92  $: Pick<EngineInterface, 'state'>,
93  stats: Record<string, RabeDiag>,
94): Promise<void> {
95  try {
96    for (let attempt = 0; attempt < 3; attempt++) {
97      const { value = {}, version } = await $.state.get({ plugin: 'rabe', key: 'diag' })
98      const next = mergeDiag(value, stats)
99      if (next === value) return
100      const { isSet } = await $.state.set({ plugin: 'rabe', key: 'diag' }, next, {
101        ifVersion: version,
102      })
103      if (isSet) return
104    }
105  } catch {}
106}
107
108async function write(
109  $: Pick<EngineInterface, 'state'>,
110  change: Change,
111  snapshot: { version: number; before: RabeItem[]; items: RabeItem[] },
112): Promise<boolean> {
113  for (;;) {
114    const { value, version } = await $.state.get({ plugin: 'rabe', key: 'items' })
115    const next =
116      version === snapshot.version
117        ? commit(snapshot.before, () => snapshot.items)
118        : commit(value, change)
119    if (next === undefined) {
120      await dropOrphans($)
121      return false
122    }
123    const { isSet } = await $.state.set({ plugin: 'rabe', key: 'items' }, next.items, {
124      ifVersion: version,
125    })
126    if (isSet) {
127      await forget($, next.dropped)
128      await dropOrphans($)
129      return true
130    }
131  }
132}
133
134// An item staged and capped out inside one poll is in neither list, so no
135// `dropped` id names it: the poll's commit also drops the diffs whose editor
136// the final list lacks, also when the replay changed nothing. `main` has no item.
137async function dropOrphans($: Pick<EngineInterface, 'state'>): Promise<void> {
138  for (;;) {
139    const { value = {}, version } = await $.state.get({ plugin: 'rabe', key: 'diffs' })
140    const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
141    const next = prune(
142      value,
143      Object.keys(value).filter(id => id !== 'main'),
144      items,
145    )
146    if (next === value) return
147    const diffs = await $.state.set({ plugin: 'rabe', key: 'diffs' }, next, { ifVersion: version })
148    if (diffs.isSet) return
149  }
150}
151
152// Drops the lines and turns of the items a write dropped.
153async function forget($: Pick<EngineInterface, 'state'>, dropped: string[]): Promise<void> {
154  if (dropped.length === 0) return
155  for (;;) {
156    const { value = {}, version } = await $.state.get({ plugin: 'rabe', key: 'lines' })
157    const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
158    const next = prune(value, dropped, items)
159    if (next === value) break
160    const lines = await $.state.set({ plugin: 'rabe', key: 'lines' }, next, { ifVersion: version })
161    if (lines.isSet) break
162  }
163  for (;;) {
164    const { value = {}, version } = await $.state.get({ plugin: 'rabe', key: 'turns' })
165    const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
166    const next = prune(value, dropped, items)
167    if (next === value) break
168    const turns = await $.state.set({ plugin: 'rabe', key: 'turns' }, next, { ifVersion: version })
169    if (turns.isSet) break
170  }
171  for (;;) {
172    const { value = {}, version } = await $.state.get({ plugin: 'rabe', key: 'diffs' })
173    const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
174    const next = prune(value, dropped, items)
175    if (next === value) return
176    const diffs = await $.state.set({ plugin: 'rabe', key: 'diffs' }, next, { ifVersion: version })
177    if (diffs.isSet) return
178  }
179}
180
hooks/diag.ts 112 lines
1import type { EngineInterface, On } from 'claude-code'
2
3import type { RabeDiag } from '../types'
4import { shorten } from './loop'
5import { KINDS, type RabeItem } from './model'
6import { isRecord } from './reading'
7
8export type DiagFacts = {
9  rabe: string
10  claude: string
11  options: Record<string, unknown>
12  diag: Record<string, RabeDiag>
13  items: RabeItem[]
14}
15
16const POLLED = ['agents', 'codex', 'shells', 'ports', 'monitors', 'worktrees']
17
18// The report `/rabe-diag` prints. It has counts, sizes, versions and option
19// values only: fixed words, numbers and versions.
20export function diagText(facts: DiagFacts): string {
21  const options = [
22    `pricesFile: ${facts.options.pricesFile ? 'set' : 'not set'}`,
23    `hideBuiltinTasks: ${typeof facts.options.hideBuiltinTasks === 'boolean' ? facts.options.hideBuiltinTasks : 'n/a'}`,
24    `timelineHours: ${typeof facts.options.timelineHours === 'number' && Number.isFinite(facts.options.timelineHours) ? facts.options.timelineHours : 'n/a'}`,
25  ]
26  const counts = new Map<string, number>()
27  for (const item of Array.isArray(facts.items) ? facts.items : []) {
28    if (
29      !item ||
30      !(KINDS as readonly string[]).includes(item.kind) ||
31      !['running', 'idle', 'done', 'failed', 'stopped'].includes(item.status)
32    )
33      continue
34    const key = `${item.kind} ${item.status}`
35    counts.set(key, (counts.get(key) ?? 0) + 1)
36  }
37  const polls = POLLED.map(name => {
38    const d = isRecord(facts.diag) ? facts.diag[name] : undefined
39    if (!isRecord(d))
40      return `- ${name}: no poll recorded (not due, inactive session, or hook unavailable)`
41
42    return (
43      `- ${name}: ${count(d.ms)} ms, ${count(d.files)} files, ${count(d.chars)} chars, ${count(d.bytes)} bytes, ${count(d.skipped)} skipped, ${count(d.errors)} errors` +
44      (d.lastError ? `, last error: ${shorten(d.lastError)}` : '')
45    )
46  })
47
48  return [
49    `Rabe ${versionOf(facts.rabe)}, Claude Code ${versionOf(facts.claude)}`,
50    `Options: ${options.join(', ') || 'none'}`,
51    `Items: ${[...counts].map(([key, n]) => `${key} ${n}`).join(', ') || 'none'}`,
52    'Last poll per source:',
53    ...polls,
54    '- crons, workflows: event sources, no polls',
55  ].join('\n')
56}
57
58function count(value: unknown): number {
59  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0
60}
61
62function versionOf(value: unknown): string {
63  return typeof value === 'string' && /^\d+\.\d+\.\d+$/.test(value) ? value : 'n/a'
64}
65
66async function report($: EngineInterface, options: Record<string, unknown>) {
67  const read = async () => {
68    try {
69      const text = String(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`))
70      return String(JSON.parse(text).version ?? 'n/a')
71    } catch {
72      return 'n/a'
73    }
74  }
75  const { value: diag = {} } = await $.state.get({ plugin: 'rabe', key: 'diag' })
76  const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
77  const claude = await $.session
78    .version()
79    .then(v => v.version)
80    .catch(() => 'n/a')
81
82  return diagText({ rabe: await read(), claude, options, diag, items })
83}
84
85// `/rabe-diag`: why Rabe shows n/a or misses something, safe to paste in a report.
86export function diag(on: On, all: Record<string, unknown>): void {
87  const options = Object.fromEntries(
88    ['hideBuiltinTasks', 'pricesFile', 'timelineHours'].map(key => [key, all[key]]),
89  )
90  on('session.start', { isInteractive: [true, false] }, async ($, e, next) => {
91    const started = await next(e)
92    await $.command
93      .register({
94        name: 'rabe-diag',
95        description: 'Show what each Rabe source read last, without private data',
96        immediate: true,
97      })
98      .catch(() => undefined)
99
100    return started
101  })
102  on('command.run', { command: 'rabe-diag' }, async $ => ({
103    text: await report($, options).catch(() => 'diagnostics unavailable'),
104  }))
105  on('command.run', { command: 'rabe:report-bug' }, async ($, e, next) => {
106    const result = await next(e)
107    const text = await report($, options).catch(() => 'diagnostics unavailable')
108
109    return { ...result, context: [...(result.context ?? []), `Rabe diagnostics:\n${text}`] }
110  })
111}
112
hooks/loop.ts 166 lines
1import type { RabeDiag } from '../types'
2import type { RabeItem } from './model'
3import { byteLength } from './reading'
4import { type Change, capEnded } from './registry'
5
6// Read results and unchanged files in one poll; lastError is a fixed category.
7export type Probe = {
8  files: number
9  chars: number
10  bytes: number
11  skipped: number
12  errors: number
13  lastError?: string
14}
15
16export type Poller = {
17  // `name` keys the poll's record in `rabe.diag`; a poll without one keeps none.
18  name?: string
19  run: (items: RabeItem[]) => Promise<Change | undefined>
20  every?: number
21  initial?: boolean
22  due?: number
23}
24export type Pollers = Poller[]
25
26export function delayOf(idle: number, isRunning: boolean, isChanged: boolean) {
27  const quiet = isRunning || isChanged ? 0 : idle + 1
28  return { idle: quiet, delay: quiet < 5 ? 2000 : 10000 }
29}
30
31export function nextStep(now: number, due: number, isRunning: boolean) {
32  if (now >= due || (isRunning && due - now > 2000)) return 'poll'
33  return isRunning ? 'redraw' : 'skip'
34}
35
36export function pollDue(
37  poll: Pick<Poller, 'every' | 'due' | 'initial'>,
38  now: number,
39  initial = false,
40) {
41  return (!initial || poll.initial !== false) && now >= (poll.due ?? 0)
42}
43
44// Classify failures without retaining any message text or file names.
45export function shorten(error: unknown): string {
46  const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined
47  const text = error instanceof Error ? error.message : typeof error === 'string' ? error : ''
48  const known = typeof code === 'string' ? code : text
49  if (/\bENOENT\b|no such file|^not found$/i.test(known)) return 'not found'
50  if (/\bEACCES\b|\bEPERM\b|permission denied/i.test(known)) return 'permission denied'
51  if (/\bETIMEDOUT\b|timed? ?out|timeout/i.test(known)) return 'timeout'
52  if (/\bEFBIG\b|too large|exceeds 4 MiB/i.test(known)) return 'too large'
53  const exit = /(?:exit(?:ed)? (?:with )?(?:code )?)(\d+)\b/i.exec(known)
54  if (exit) return `exit code ${Number(exit[1])}`
55  if (error instanceof SyntaxError || /^parse error$/i.test(known)) return 'parse error'
56  if (/refused|denied by policy|^denied$/i.test(known)) return 'refused'
57  return 'other'
58}
59
60function fail(probe: Probe, error: unknown): void {
61  probe.errors++
62  probe.lastError = shorten(error)
63}
64
65// The poll in flight: polls run one after another, so a source that reads a
66// file or runs a process reports it here without a probe argument. An event
67// hook that reads while a poll runs counts into that poll.
68let current: Probe | undefined
69
70// Counts a read result; returns it.
71export function tally<T>(text: T): T {
72  if (current) {
73    current.files++
74    current.chars += typeof text === 'string' ? text.length : 0
75    current.bytes += typeof text === 'string' ? byteLength(text) : 0
76  }
77
78  return text
79}
80
81// Counts a file whose content read was skipped because it is unchanged.
82export function skipped(): void {
83  if (current) current.skipped++
84}
85
86// Counts a failure; returns `fallback`, so `.catch(fault)` and `.catch(e => fault(e, ''))` stand
87// where a read's `.catch(() => undefined)` stood.
88export function fault<F = undefined>(error: unknown, fallback?: F): F {
89  if (current) fail(current, error)
90
91  return fallback as F
92}
93
94const ROUND = 100
95
96// The diag record after a pass: `ms` is rounded and `at` ignored when deciding
97// whether anything changed, so a steady source causes no write.
98export function mergeDiag(
99  held: Record<string, RabeDiag>,
100  stats: Record<string, RabeDiag>,
101): Record<string, RabeDiag> {
102  let next = held
103  for (const [name, stat] of Object.entries(stats)) {
104    const ms = Math.round(stat.ms / ROUND) * ROUND
105    const old = held[name]
106    const same =
107      old &&
108      old.ms === ms &&
109      old.files === stat.files &&
110      old.chars === stat.chars &&
111      old.bytes === stat.bytes &&
112      old.skipped === stat.skipped &&
113      old.errors === stat.errors &&
114      old.lastError === stat.lastError
115    if (!same) next = { ...next, [name]: { ...stat, ms } }
116  }
117
118  return next
119}
120
121export async function collect(
122  pollers: Pollers,
123  items: RabeItem[],
124  now: number,
125  initial = false,
126  tick: () => Promise<number> = async () => now,
127): Promise<{ change: Change; items: RabeItem[]; stats: Record<string, RabeDiag> }> {
128  const changes: Change[] = []
129  const stats: Record<string, RabeDiag> = {}
130  for (const poll of pollers) {
131    if (!pollDue(poll, now, initial)) continue
132    const probe: Probe = { files: 0, chars: 0, bytes: 0, skipped: 0, errors: 0 }
133    const started = await tick().catch(() => now)
134    current = probe
135    try {
136      const change = await poll.run(items)
137      if (change) {
138        changes.push(change)
139        items = capEnded(change(items))
140      }
141    } catch (error) {
142      fail(probe, error)
143    }
144    current = undefined
145    if (poll.name) {
146      const ended = await tick().catch(() => started)
147      stats[poll.name] = {
148        at: now,
149        ms: Math.max(0, ended - started),
150        files: probe.files,
151        chars: probe.chars,
152        bytes: probe.bytes,
153        skipped: probe.skipped,
154        errors: probe.errors,
155        ...(probe.lastError && { lastError: probe.lastError }),
156      }
157    }
158    poll.due = now + (poll.every ?? 0)
159  }
160  return {
161    change: held => changes.reduce((list, change) => capEnded(change(list)), held),
162    items,
163    stats,
164  }
165}
166
hooks/model.ts 109 lines
1import type { RabeItem, RabeItemDetails, RabeItemKind, RabeItemOf, RabeItemStatus } from '../types'
2
3export type {
4  RabeItem,
5  RabeItemDetails,
6  RabeItemKind,
7  RabeItemOf,
8  RabeItemStatus,
9  RabeTokens,
10  RabeToolUse,
11  RabeTurn,
12} from '../types'
13
14export type NewItem = { [K in RabeItemKind]: Omit<RabeItemOf<K>, 'seenAt'> }[RabeItemKind]
15
16export type ItemPatch = Partial<
17  Pick<RabeItem, 'title' | 'status' | 'startedAt' | 'endedAt' | 'parentId' | 'tokens' | 'costUsd'>
18> & { detail?: Partial<RabeItemDetails[RabeItemKind]> }
19
20export type EndStatus = Exclude<RabeItemStatus, 'running' | 'idle'>
21
22// Every kind, in the band order; diagnostics use it to check membership only.
23export const KINDS = ['agent', 'codex', 'workflow', 'shell', 'monitor', 'cron'] as const
24
25// The lookups by id and by parent that views and sources ask per item. One
26// pass per list, cached on the array (lists are never changed in place), so a
27// lookup is O(1) and a draw stays linear in the item count. The first item of
28// an id wins, as `find` did.
29type Index = { byId: Map<string, RabeItem>; firstCodexOf: Map<string, RabeItem> }
30const indexes = new WeakMap<readonly RabeItem[], Index>()
31
32function indexOf(items: readonly RabeItem[]): Index {
33  let index = indexes.get(items)
34  if (!index) {
35    index = { byId: new Map(), firstCodexOf: new Map() }
36    for (const item of items) {
37      if (!index.byId.has(item.id)) index.byId.set(item.id, item)
38      if (
39        item.kind === 'codex' &&
40        item.parentId !== undefined &&
41        !index.firstCodexOf.has(item.parentId)
42      )
43        index.firstCodexOf.set(item.parentId, item)
44    }
45    indexes.set(items, index)
46  }
47
48  return index
49}
50
51// The first item with `id`.
52export const itemById = (items: readonly RabeItem[], id: string) => indexOf(items).byId.get(id)
53
54// The first Codex job whose parent is `id`.
55export const firstCodexOf = (items: readonly RabeItem[], id: string) =>
56  indexOf(items).firstCodexOf.get(id)
57
58// The item that started `item`, if it is in the list.
59export function parentOf(item: Pick<RabeItem, 'parentId'>, items: readonly RabeItem[]) {
60  return item.parentId === undefined ? undefined : itemById(items, item.parentId)
61}
62
63// The workflow run that started `item`, if it is in the list.
64export function runOf(item: Pick<RabeItem, 'parentId'>, items: readonly RabeItem[]) {
65  const parent = parentOf(item, items)
66
67  return parent?.kind === 'workflow' ? parent : undefined
68}
69
70export function isEnded(item: Pick<RabeItem, 'status'>): boolean {
71  return item.status !== 'running' && item.status !== 'idle'
72}
73
74// Cuts text to `max` characters, the last one an ellipsis.
75export function clip(text: string, max: number): string {
76  return text.length > max ? `${text.slice(0, max - 1)}…` : text
77}
78
79export function itemId(kind: RabeItemKind, nativeId: string): string {
80  return `${kind}:${nativeId}`
81}
82
83export function mergeItem(item: RabeItem, patch: ItemPatch): RabeItem {
84  return {
85    ...item,
86    ...patch,
87    seenAt: item.seenAt,
88    detail: { ...item.detail, ...patch.detail },
89  } as RabeItem
90}
91
92// A Windows path: a drive (`C:\`, `c:/`) or UNC (`\\host\share`, `//host/share`).
93const isWindows = (path: string) => /^[A-Za-z]:[\\/]/.test(path) || /^[\\/]{2}[^\\/]/.test(path)
94
95export const isAbsolute = (path: string) => path.startsWith('/') || isWindows(path)
96
97// What two paths are compared by: a Windows path with `/` and in lower case,
98// since Windows ignores case; a POSIX path as it is.
99export const pathKey = (path: string) =>
100  isWindows(path) ? path.replace(/\\/g, '/').toLowerCase() : path
101
102// Whether `path` is `root` or inside it.
103export function isInside(path: string, root: string): boolean {
104  const at = pathKey(path)
105  const base = pathKey(root).replace(/\/+$/, '')
106
107  return at === base || at.startsWith(`${base}/`)
108}
109
hooks/registry.ts 127 lines
1import {
2  type EndStatus,
3  type ItemPatch,
4  isEnded,
5  mergeItem,
6  type NewItem,
7  type RabeItem,
8} from './model'
9
10export const MAX_ENDED = 200
11// Ended foreground Bash rows (`shell:fg-…`) kept; they go before any other ended item.
12export const MAX_FOREGROUND = 50
13
14export type Change = (items: RabeItem[]) => RabeItem[]
15
16function sortKeys(_key: string, value: unknown): unknown {
17  if (!value || typeof value !== 'object' || Array.isArray(value)) return value
18
19  return Object.fromEntries(Object.entries(value).toSorted(([a], [b]) => (a < b ? -1 : 1)))
20}
21
22function replace(items: RabeItem[], index: number, next: RabeItem): RabeItem[] {
23  if (JSON.stringify(items[index], sortKeys) === JSON.stringify(next, sortKeys)) return items
24
25  return items.with(index, next)
26}
27
28export function addItem(items: RabeItem[], item: NewItem, now: number): RabeItem[] {
29  const index = items.findIndex(one => one.id === item.id)
30  if (index === -1) return [...items, { ...item, seenAt: now } as RabeItem]
31
32  return replace(items, index, mergeItem(items[index] as RabeItem, item))
33}
34
35export function updateItem(items: RabeItem[], id: string, patch: ItemPatch): RabeItem[] {
36  const index = items.findIndex(one => one.id === id)
37  if (index === -1) return items
38
39  return replace(items, index, mergeItem(items[index] as RabeItem, patch))
40}
41
42export function endItem(items: RabeItem[], id: string, status: EndStatus, now: number): RabeItem[] {
43  const item = items.find(one => one.id === id)
44  if (!item || isEnded(item)) return items
45
46  return updateItem(items, id, { status, endedAt: now })
47}
48
49// A direct Codex run counts like a Codex job, not as a foreground shell.
50const isForeground = (item: RabeItem) =>
51  item.id.startsWith('shell:fg-') && !(item.kind === 'shell' && item.detail.codex)
52const byEnd = (a: RabeItem, b: RabeItem) => (a.endedAt ?? a.seenAt) - (b.endedAt ?? b.seenAt)
53
54// Ended foreground rows go first, the oldest first, and never more than
55// MAX_FOREGROUND stay. Of two other items that ended at once, the one Rabe saw
56// later goes first.
57export function capEnded(items: RabeItem[], max = MAX_ENDED): RabeItem[] {
58  const ended = items.filter(isEnded)
59  const foreground = ended.filter(isForeground)
60  const count = Math.max(ended.length - max, foreground.length - MAX_FOREGROUND)
61  if (count <= 0) return items
62  const order = [
63    ...foreground.toSorted(byEnd),
64    ...ended
65      .filter(item => !isForeground(item))
66      .toReversed()
67      .toSorted(byEnd),
68  ]
69  const dropped = new Set(order.slice(0, count))
70
71  return items.filter(item => !dropped.has(item))
72}
73
74// The end time of an ended item Rabe did not watch end: the oldest end held,
75// so it never pushes out one Rabe watched. `undefined` once ended items other
76// than foreground rows fill the cap, since the cap would drop it.
77export function pastEnd(items: RabeItem[], now: number, max = MAX_ENDED): number | undefined {
78  const ended = items.filter(isEnded)
79  if (ended.filter(item => !isForeground(item)).length >= max) return undefined
80
81  return Math.min(now, ...ended.map(item => item.endedAt ?? item.seenAt))
82}
83
84// The capped list and the ids the write drops (also one it added), or
85// `undefined` when the capped list is the held one.
86export function commit(
87  held: RabeItem[] | undefined,
88  change: Change,
89): { items: RabeItem[]; dropped: string[] } | undefined {
90  const items = held ?? []
91  const changed = change(items)
92  const next = capEnded(changed)
93  if (next.length === items.length && next.every((item, i) => item === items[i])) return undefined
94  const kept = new Set(next.map(item => item.id))
95  const dropped = new Set([...items, ...changed].map(item => item.id).filter(id => !kept.has(id)))
96
97  return { items: next, dropped: [...dropped] }
98}
99
100// `record` without the entries of `dropped` ids that are not back in `items`;
101// the same record when none goes.
102export function prune<T>(
103  record: Record<string, T>,
104  dropped: string[],
105  items: RabeItem[],
106): Record<string, T> {
107  const gone = dropped.filter(id => id in record && !items.some(item => item.id === id))
108  if (gone.length === 0) return record
109
110  return Object.fromEntries(Object.entries(record).filter(([id]) => !gone.includes(id)))
111}
112
113// A poll stages changes; event hooks still write immediately.
114export type Poll = { items: RabeItem[]; changes: Change[] }
115
116export function stage(poll: Poll, change: Change): void {
117  poll.changes.push(change)
118  poll.items = capEnded(change(poll.items))
119}
120
121export function changeOf(poll: Poll, start: RabeItem[]): Change {
122  return items =>
123    items === start
124      ? poll.items
125      : poll.changes.reduce((list, change) => capEnded(change(list)), items)
126}
127
hooks/sources/index.ts 22 lines
1import type { On } from 'claude-code'
2
3import type { Pollers } from '../loop'
4import { agents } from './agents'
5import { codex } from './codex'
6import { crons } from './crons'
7import { monitors } from './monitors'
8import { shells } from './shells'
9import { workflows } from './workflows'
10import { worktrees } from './worktrees'
11
12// `file`: the user's price table (option `pricesFile`), '' for none.
13export function sources(on: On, file: string, pollers: Pollers): void {
14  agents(on, file, pollers)
15  workflows(on)
16  codex(on, file, pollers)
17  shells(on, pollers)
18  monitors(on, pollers)
19  worktrees(on, pollers)
20  crons(on)
21}
22
hooks/ui/band.tsx 32 lines
1import type { On } from 'claude-code'
2
3import { render } from './render'
4import { bounded, NO_SELECTION } from './view'
5import { bandView } from './views/band'
6
7export function band(on: On): void {
8  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
9    if (e.props.hasSurvey) return next(e)
10    const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
11    const { value: removed = [] } = await $.state.get({ plugin: 'rabe', key: 'removed' })
12    if (!items.some(item => item.status === 'running')) return next(e)
13    const usage = await $.session.usage().catch(() => undefined)
14    const model = {
15      items,
16      removed,
17      turns: {},
18      lines: {},
19      now: await $.clock.now(),
20      usd: usage?.cost?.usd,
21    }
22    const size = bounded({
23      columns: e.props.bodyColumns,
24      rows: e.props.maxRows,
25      surface: e.surface,
26      hasInput: false,
27    })
28
29    return render($.ui.resolve(e), e.surface, bandView(model, size, NO_SELECTION), () => {}, 'band')
30  })
31}
32
hooks/ui/builtin.tsx 57 lines
1import type { On } from 'claude-code'
2
3const TASK =
4  /^\d+ (background |dynamic )?(shell|monitor|agent|subagent|workflow|task|teammate|MCP task|cloud session)s?$/
5
6// Removes the part of Claude Code's prompt hint that counts background work
7// ("2 shells, 1 monitor") and its "↓ to manage"; keeps every other part.
8export function stripTasks(hint: string): string {
9  return hint
10    .split(' · ')
11    .filter(part => part !== '↓ to manage' && !part.split(', ').every(one => TASK.test(one)))
12    .join(' · ')
13}
14
15// The engine's duration format on the turn line: 5s, 1m 4s, 1h 2m 5s.
16export function turnDuration(ms: number): string {
17  const s = Math.floor(ms / 1000)
18  const h = Math.floor(s / 3600)
19  const m = Math.floor(s / 60) % 60
20  if (h > 0) return `${h}h ${m}m ${s % 60}s`
21
22  return m > 0 ? `${m}m ${s % 60}s` : `${s}s`
23}
24
25// Hides Claude Code's own count of background work, since the band shows it.
26export function builtin(on: On): void {
27  on('ui.render', { component: 'PromptHint' }, async (_$, e, next) => {
28    const hint = stripTasks(e.props.hint)
29
30    return hint === e.props.hint ? next(e) : next({ ...e, props: { ...e.props, hint } })
31  })
32
33  // The line's "N shells, M monitors still running" part is not a prop, so the
34  // hook draws the line itself, only while Rabe knows of a running shell or
35  // monitor and no running agent or workflow (then the engine waits for those
36  // and draws no such part). That line leaves out "done 1:16": no prop has it.
37  on('ui.render', { component: 'TurnDuration' }, async ($, e, next) => {
38    const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
39    const running = items.filter(item => item.status === 'running')
40    const isWaiting = running.some(item => item.kind === 'agent' || item.kind === 'workflow')
41    const hasTasks = running.some(item => item.kind === 'shell' || item.kind === 'monitor')
42    if (isWaiting || !hasTasks) return next(e)
43    const { Box, Text } = $.ui.resolve(e)
44
45    return (
46      <Box flexDirection="row" marginTop={1} width="100%">
47        <Box minWidth={2}>
48          <Text dimColor>✻</Text>
49        </Box>
50        <Text dimColor>
51          {e.props.word} for {turnDuration(e.props.durationMs)}
52        </Text>
53      </Box>
54    )
55  })
56}
57
hooks/ui/pane.tsx 988 lines
1import type { EngineInterface, Next, On, RenderSurface, UiFocusInput } from 'claude-code'
2
3import type { RabePrevious } from '../../types'
4import { isEnded, type RabeItem } from '../model'
5import { orderIds } from './groups'
6import {
7  deferredFocus,
8  heldOf,
9  IDLE,
10  type InteractionEvent,
11  interact,
12  isHeldBack,
13  movedFocus,
14  REGAIN_MS,
15  type Shift,
16  scopeOf,
17} from './interaction'
18import { KIND_LABEL, kept, matches, orderOf, previousOf, rowOf } from './lists'
19import { asPrevious, clipText, itemsText, nameOf, toastText } from './pane-data'
20import { follow, geometry, MIN_ROWS, measure, NO_PIN, type Pin } from './pin'
21import { type At, hold, render } from './render'
22import { inTurn, reserve, screens, sequence, slots } from './sequence'
23import {
24  type Action,
25  bounded,
26  holdsClose,
27  isWorkflowAgent,
28  landing,
29  landingOf,
30  landOn,
31  layout,
32  type Model,
33  messageLanding,
34  rowKeys,
35  type Selection,
36  stepRow,
37  taskIdOf,
38  waitsForView,
39} from './view'
40import { listOrder, queryOf, selectedItem } from './views/items'
41import { isLiveRow, paneView, seatsRows, selectsOnPress, TABS } from './views/pane'
42import { widen, windowOf } from './views/timeline'
43
44const PANE = 'rabe'
45const MAX_ACTIONS = 20
46// The engine's answer to an event whose drawing a redraw released.
47const RELEASED = 'no handler is held under handle'
48
49// The option `timelineHours`, set by `pane(on, hours)`: the Timeline's window
50// when the pane opens.
51let baseHours = 4
52
53// The list under the pinned header (see `geometry`): where it stands, and
54// whether the last drawing clipped it, so a scroll moves it, not the engine.
55let pinned: Pin = NO_PIN
56let isPinned = false
57
58// Whether this open has put the focus back on the person's row.
59let isRestored = false
60
61// Reasons come from files and tools.
62function toast($: EngineInterface, text: string): void {
63  $.ui.toast(toastText(text))
64}
65
66// Esc may have closed the pane before the delayed focus call.
67async function refocus($: EngineInterface, tries = 0): Promise<void> {
68  let shown = (await $.ui.panes()).find(one => one.id === PANE)
69  if (shown && !shown.isFocused) {
70    await $.ui.open({ id: PANE, title: 'Rabe', focus: true, closeOnEscape: true })
71    shown = (await $.ui.panes()).find(one => one.id === PANE)
72  }
73  feed($, { type: 'refocused', isOpen: !!shown, isFocused: !!shown?.isFocused })
74  // The reopened pane puts the focus on the tab's selected row (#188), once.
75  // Only a pane that holds the keys can take it; a timer's call runs none of
76  // Rabe's focus hooks, so a landing is the call's answer, not `landedOn`.
77  if (shown?.isFocused && !isRestored) isRestored = await restore($).catch(() => false)
78  // A refused landing (a move abandoned) tries again, as the keys do; a retry
79  // also goes on while the pane lost the keys, since `opening` no longer asks.
80  if (shown && (shown.isFocused || tries > 0) && !isRestored && tries < 40) {
81    $.clock.after(50, () => void refocus($, tries + 1).catch(() => undefined))
82  }
83}
84
85async function restore($: EngineInterface): Promise<boolean> {
86  const { value: tab = 'items' } = await $.state.get({ plugin: 'rabe', key: 'tab' })
87  const action: Action = { type: 'tab', tab }
88  const { model, selection } = await look($, true)
89  const drawn = paneView(
90    model,
91    { columns: 80, rows: 24, surface: 'terminal', hasInput: true },
92    selection,
93  )
94  return landOn(
95    landing(action, selection.open, drawn),
96    () => undefined,
97    async key => {
98      const result = await $.ui.focus({ requestId: PANE, key }).catch(() => ({ deny: 'threw' }))
99      const isMoved = !('deny' in result && result.deny)
100      if (isMoved) feed($, { type: 'restored', key })
101      return isMoved
102    },
103  )
104}
105
106async function previous($: EngineInterface): Promise<RabePrevious | undefined> {
107  const key = `previous:${await $.session.cwd()}`
108  const stored = await $.store.get(key)
109  const summary = asPrevious(stored)
110  if (summary && stored && typeof stored === 'object' && 'failed' in stored) {
111    await $.store.set(key, summary)
112  }
113
114  return summary
115}
116
117// Keeps this session's summary for the next one in this project; a session
118// with no background work leaves the last summary in place.
119async function remember($: EngineInterface, sessionId?: string): Promise<void> {
120  const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
121  if (items.length === 0) {
122    await previous($)
123    return
124  }
125  const usage = await $.session.usage()
126  const summary = previousOf(
127    items,
128    await $.clock.now(),
129    { startedAt: usage.startedAt, usd: usage.cost?.usd },
130    sessionId,
131  )
132  await $.store.set(`previous:${await $.session.cwd()}`, summary)
133}
134
135async function stop($: EngineInterface, ids: string[]): Promise<void> {
136  const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
137  const targets = items.filter(item => ids.includes(item.id))
138  const one = targets.length === 1 ? targets[0] : undefined
139  if (one) toast($, `Stopping ${KIND_LABEL[one.kind]} ${nameOf(one)}…`)
140  let stopped = 0
141  const stoppedItems: RabeItem[] = []
142  let ended = 0
143  let refused: string | undefined
144  for (const item of targets) {
145    if (item.kind === 'codex' && item.status === 'running') {
146      const { text = 'n/a' } = await $.command
147        .run({ command: 'rabe-stop', args: item.id })
148        .catch((error: unknown) => ({ text: `Stop refused: ${String(error)}` }))
149      if (text.startsWith('Stopped')) {
150        stopped += 1
151        stoppedItems.push(item)
152      } else {
153        const { value: current = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
154        const job = current.find(one => one.id === item.id)
155        refused =
156          (job?.kind === 'codex' && job.detail.stopError) || text.replace(/^Stop refused: /, '')
157      }
158      continue
159    }
160    const task = taskIdOf(item)
161    if (isEnded(item) || !task) {
162      ended += 1
163      continue
164    }
165    try {
166      const result = await $.tool.call({ tool: 'TaskStop', task_id: task })
167      if (result.deny) refused = result.deny
168      else if (result.isError) refused = result.text ?? 'n/a'
169      else {
170        stopped += 1
171        stoppedItems.push(item)
172      }
173    } catch (error) {
174      refused = error instanceof Error ? error.message : String(error)
175    }
176  }
177  for (const item of stoppedItems) {
178    await queueAction($, `Rabe: user stopped ${item.kind} ${item.id}`)
179  }
180  if (one && refused) toast($, `Stop refused: ${refused}`)
181  else if (one)
182    toast(
183      $,
184      ended
185        ? `${KIND_LABEL[one.kind]} ${nameOf(one)} had already finished`
186        : `Stopped ${KIND_LABEL[one.kind]} ${nameOf(one)}`,
187    )
188  else {
189    const done = ended ? `; ${ended} had already finished` : ''
190    const no = refused ? `; refused: ${refused}` : ''
191    toast($, `Stopped ${stopped} of ${targets.length}${done}${no}`)
192  }
193}
194
195async function queueAction($: EngineInterface, note: string): Promise<void> {
196  for (;;) {
197    const { value = [], version } = await $.state.get({ plugin: 'rabe', key: 'actions' })
198    const { isSet } = await $.state.set(
199      { plugin: 'rabe', key: 'actions' },
200      [...value, note].slice(-MAX_ACTIONS),
201      { ifVersion: version },
202    )
203    if (isSet) return
204  }
205}
206
207async function clearActions($: EngineInterface, delivered: string[]): Promise<void> {
208  for (;;) {
209    const { value = [], version } = await $.state.get({ plugin: 'rabe', key: 'actions' })
210    if (!delivered.every((note, index) => value[index] === note)) return
211    const { isSet } = await $.state.set(
212      { plugin: 'rabe', key: 'actions' },
213      value.slice(delivered.length),
214      { ifVersion: version },
215    )
216    if (isSet) return
217  }
218}
219
220// A reload drops the hold too, so interaction starts disarmed.
221let interaction = IDLE
222
223function feed($: EngineInterface, event: InteractionEvent) {
224  const was = interaction.arming
225  const result = interact(interaction, event)
226  interaction = result.state
227  for (const effect of result.effects) {
228    if (effect.type === 'refocus')
229      $.clock.after(effect.after, () => void refocus($).catch(() => undefined))
230    else if (effect.type === 'regain')
231      $.clock.after(REGAIN_MS, () => void regain($, effect.want).catch(() => undefined))
232    else $.ui.invalidate('ui.render')
233  }
234  const now = interaction.arming
235  if (now.isArmed !== was.isArmed || now.isListArmed !== was.isListArmed) {
236    $.ui.invalidate('ui.render')
237  }
238  return result
239}
240
241async function focusOn($: EngineInterface, key: string): Promise<boolean> {
242  feed($, { type: 'focus-start', key })
243  const result = await $.ui.focus({ requestId: PANE, key }).catch(() => ({ deny: 'threw' }))
244  const isMoved = !('deny' in result && result.deny) && interaction.landedOn === key
245  feed($, { type: 'landed', isMoved })
246  return isMoved
247}
248
249// A dropped `m` press must not leave the ring away from the field: the typed
250// letters would reach the main prompt. Land the ring, or say that it did not land.
251async function missedMessage($: EngineInterface, element: string): Promise<void> {
252  try {
253    const id = element.slice('message-agent:'.length)
254    const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
255    const item = items.find(one => one.id === id)
256    if (item?.kind === 'agent' && !isEnded(item) && !isWorkflowAgent(item)) {
257      if (!(await focusOn($, `message:${id}`))) toast($, 'Message field not focused')
258    } else {
259      toast($, 'Message not sent')
260    }
261  } catch {}
262}
263
264async function regain($: EngineInterface, want: Shift): Promise<void> {
265  if (interaction.shift !== want) return
266  const result = await $.ui
267    .focus({ requestId: PANE, key: want.key })
268    .catch(() => ({ deny: 'threw' }))
269  feed($, { type: 'regained', want, isMoved: !('deny' in result && result.deny) })
270}
271
272// The landings waiting for a drawing of their new view (`screens`). The next
273// press, Input event, arrow or person's focus move, and a close, end them.
274const screen = screens()
275
276async function onScreen($: EngineInterface, surface: RenderSurface): Promise<boolean> {
277  const ready = screen.ask(surface, (ms, signal) => $.clock.sleep(ms, { signal }))
278  $.ui.invalidate('ui.render')
279  return ready
280}
281
282// A new view starts its hold anew, but the ring keeps its index, where the new
283// view may draw a stop; so the pane disarms and the ring moves (`landing`).
284async function land(
285  $: EngineInterface,
286  keys: string[],
287  action?: Action,
288  surface?: RenderSurface,
289): Promise<void> {
290  await landOn(
291    keys,
292    () => interaction.ringOn,
293    key => focusOn($, key),
294    action && surface && waitsForView(action) ? () => onScreen($, surface) : undefined,
295  )
296}
297
298async function landView($: EngineInterface, action: Action, surface: RenderSurface): Promise<void> {
299  const { model, selection } = await look($, true)
300  const drawn = paneView(model, { columns: 80, rows: 24, surface, hasInput: true }, selection)
301  return land($, landing(action, selection.open, drawn), action, surface)
302}
303
304// The ring follows a click (#186). A move that the engine refuses leaves the
305// ring where it was; the focus hook then clears the arming (`landed: false`),
306// so `x` stays inert until the person moves the ring.
307async function ringOnto($: EngineInterface, key: string): Promise<void> {
308  await $.ui.focus({ requestId: PANE, key }).catch(() => undefined)
309}
310
311// A press on a live row of the Items list away from the ring selects it: only
312// a pointer presses a row away from the ring, so the press is the person's
313// choice of that row and the ring follows it (#186). The ring's row and the
314// selected row open.
315async function choose($: EngineInterface, id: string): Promise<boolean> {
316  const { model, selection } = await look($, true)
317  if (!selectsOnPress(model, selection, id, interaction.ringOn)) return false
318  await $.state.set({ plugin: 'rabe', key: 'selected' }, id)
319  feed($, { type: 'press' })
320  await ringOnto($, `row:${id}`)
321
322  return true
323}
324
325// The selected row of a tab. The Items tab keeps `selected`; every other tab
326// keeps its own pick in `picked`, so a visit never moves the Items selection
327// (#188). Absent state is no pick: the view falls back to its first row.
328async function pickedOn($: EngineInterface, tab: string): Promise<string> {
329  if (tab === 'items') {
330    const { value = '' } = await $.state.get({ plugin: 'rabe', key: 'selected' })
331    return value
332  }
333  const { value = {} } = await $.state.get({ plugin: 'rabe', key: 'picked' })
334  return value[tab] ?? ''
335}
336
337async function pick($: EngineInterface, tab: string, id: string): Promise<void> {
338  if (tab === 'items') {
339    await $.state.set({ plugin: 'rabe', key: 'selected' }, id)
340    return
341  }
342  const { value = {} } = await $.state.get({ plugin: 'rabe', key: 'picked' })
343  await $.state.set({ plugin: 'rabe', key: 'picked' }, { ...value, [tab]: id })
344}
345
346// Hides ended items for the session: they stay in `rabe.items`, which polls
347// fill again, and only the Items list leaves them out (`kept`). An id stays even when
348// the cap drops its item, which a poll may find again.
349async function remove($: EngineInterface, action: Action & { type: 'remove' | 'clear' }) {
350  const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
351  const { value: query = '' } = await $.state.get({ plugin: 'rabe', key: 'query' })
352  // The list as drawn before the removal: the selection moves to a neighbour.
353  const seen = await look($, true)
354  const order =
355    seen.selection.tab === 'items' && seen.selection.open === ''
356      ? listOrder(seen.model, seen.selection).map(item => item.id)
357      : []
358  const was = selectedItem(listOrder(seen.model, seen.selection), seen.selection)?.id
359  let gone: RabeItem[] = []
360  for (;;) {
361    const { value: removed = [], version } = await $.state.get({ plugin: 'rabe', key: 'removed' })
362    gone = kept(items, removed).filter(
363      item =>
364        isEnded(item) &&
365        (action.type === 'remove' ? action.ids.includes(item.id) : matches(item, query)),
366    )
367    if (gone.length === 0) return
368    const next = [...removed, ...gone.map(item => item.id)]
369    const { isSet } = await $.state.set({ plugin: 'rabe', key: 'removed' }, next, {
370      ifVersion: version,
371    })
372    if (isSet) break
373  }
374  const at = was ? order.indexOf(was) : -1
375  if (at >= 0 && gone.some(item => item.id === was)) {
376    const left = (id: string) => !gone.some(item => item.id === id)
377    const near = order.slice(at + 1).find(left) ?? order.slice(0, at).reverse().find(left)
378    if (near) {
379      await $.state.set({ plugin: 'rabe', key: 'selected' }, near)
380      feed($, { type: 'landed', isMoved: false })
381    }
382  }
383  const [one] = gone
384  toast(
385    $,
386    gone.length === 1 && one
387      ? `Removed ${KIND_LABEL[one.kind]} ${nameOf(one)}`
388      : `Removed ${gone.length} ended items`,
389  )
390}
391
392async function act(
393  $: EngineInterface,
394  action: Action,
395  surface: RenderSurface,
396  pressed?: string,
397): Promise<void> {
398  if (action.type === 'open' && (await choose($, action.id))) return
399  const { value: open = '' } = await $.state.get({ plugin: 'rabe', key: 'open' })
400  const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
401  // The origin belongs to the open detail: once that item left the list, the
402  // pane shows the Items list, and no detail is open to go back from.
403  const isOpen = open !== '' && items.some(item => item.id === open)
404  const { value: stored } = await $.state.get({ plugin: 'rabe', key: 'openFrom' })
405  const origin = isOpen ? stored : null
406  const [safe] = landing(action, '', undefined, origin?.tab)
407  if (action.type !== 'message' && safe) {
408    feed($, { type: 'reset' })
409    await focusOn($, safe)
410  }
411  switch (action.type) {
412    case 'tab':
413      await $.state.set({ plugin: 'rabe', key: 'tab' }, action.tab)
414      return landView($, action, surface)
415    case 'fold': {
416      const { value: folded = [] } = await $.state.get({ plugin: 'rabe', key: 'folded' })
417      const next = folded.includes(action.group)
418        ? folded.filter(group => group !== action.group)
419        : [...folded, action.group]
420      await $.state.set({ plugin: 'rabe', key: 'folded' }, next)
421      return land($, landing(action, ''), action, surface)
422    }
423    case 'open': {
424      // Back selects the item that was open: the focus may have moved onto a
425      // row inside its detail (a workflow's agents). A folded forwarder has no
426      // row, so back selects its job.
427      const was = rowOf(open, items)
428      if (action.id) {
429        // One level: a detail opened from a list replaces the origin; one
430        // opened inside a detail (on the Items tab) keeps it, so back leaves
431        // both at once.
432        const { value: tab = 'items' } = await $.state.get({ plugin: 'rabe', key: 'tab' })
433        const inside = tab === 'items' && isOpen
434        if (!origin || !inside) {
435          // Without a stored origin inside a detail, the open item is the row.
436          // An Effects row is a file: the pressed key, not the item's id, is the row.
437          const id = inside
438            ? was || action.id
439            : tab === 'effects' && pressed?.startsWith('row:')
440              ? pressed.slice(4)
441              : action.id
442          await $.state.set({ plugin: 'rabe', key: 'openFrom' }, { tab, id })
443        }
444        await $.state.set({ plugin: 'rabe', key: 'selected' }, action.id)
445        await $.state.set({ plugin: 'rabe', key: 'tab' }, 'items')
446      } else {
447        const tab = origin?.tab ?? 'items'
448        if (was) await $.state.set({ plugin: 'rabe', key: 'selected' }, was)
449        // The row the detail was opened from: its own pick, or for Items the
450        // selection (a workflow's run, not the agent that was open).
451        if (origin) await pick($, tab, origin.id)
452        await $.state.set({ plugin: 'rabe', key: 'tab' }, tab)
453        await $.state.set({ plugin: 'rabe', key: 'openFrom' }, null)
454      }
455      await $.state.set({ plugin: 'rabe', key: 'open' }, action.id)
456      return land($, landing(action, origin?.id ?? was, undefined, origin?.tab))
457    }
458    case 'query':
459      await $.state.set({ plugin: 'rabe', key: 'query' }, action.text)
460      return action.isSubmit ? landView($, action, surface) : land($, landing(action, ''))
461    case 'window': {
462      const now = await $.clock.now()
463      const { value = windowOf(baseHours, now) } = await $.state.get({
464        plugin: 'rabe',
465        key: 'window',
466      })
467      await $.state.set({ plugin: 'rabe', key: 'window' }, widen(value, now))
468      return land($, landing(action, ''))
469    }
470    case 'group':
471      await $.state.set({ plugin: 'rabe', key: 'grouping' }, action.by)
472      return land($, landing(action, ''))
473    case 'focus':
474      await focusOn($, action.key)
475      return
476    case 'stop':
477      await stop($, action.ids)
478      return
479    case 'remove':
480    case 'clear':
481      await remove($, action)
482      return
483    case 'delete': {
484      const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
485      const item = items.find(one => one.id === action.id)
486      if (
487        item?.kind !== 'cron' ||
488        item.status !== 'running' ||
489        item.detail.scheduledFor !== undefined
490      )
491        return
492      const result = await $.tool.call({ tool: 'CronDelete', id: item.detail.jobId })
493      const reason = result.deny ?? (result.isError ? (result.text ?? 'n/a') : undefined)
494      toast(
495        $,
496        reason
497          ? `Delete refused: ${reason.replace(/<\/?tool_use_error>/g, '').trim()}`
498          : `Deleted cron ${nameOf(item)}`,
499      )
500      if (!reason) await queueAction($, `Rabe: user deleted cron ${item.id}`)
501      return
502    }
503    case 'copy': {
504      if (action.what !== 'command' && action.what !== 'prompt' && /[\r\n]/.test(action.text)) {
505        toast($, `Copy refused: ${action.what} contains a line break.`)
506        return
507      }
508      // Over SSH the clipboard needs the terminal's OSC 52.
509      const text = clipText(action.text)
510      const result = await $.ui
511        .copy({ text, surface })
512        .catch((error: unknown) => ({ isCopied: false as const, reason: String(error) }))
513      const preview = toastText(text)
514      // only text the filters left alone is offered for selection
515      const selectable = action.what !== 'prompt' && preview === action.text
516      const lines = text.split(/\r\n|\r|\n/).length
517      const chars = [...text].length
518      const copied = `Copied ${action.what} · ${lines} ${lines === 1 ? 'line' : 'lines'} · ${chars} ${chars === 1 ? 'char' : 'chars'}`
519      toast(
520        $,
521        result.isCopied
522          ? copied
523          : `Copy failed: ${result.reason}.${selectable ? ` Select it: ${text}` : ''}`,
524      )
525      return
526    }
527    case 'none':
528      return
529    case 'message': {
530      const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
531      const item = items.find(one => one.id === action.id)
532      if (!action.text.trim()) return
533      if (item?.kind !== 'agent' || isEnded(item) || isWorkflowAgent(item)) {
534        toast($, 'Message not sent')
535        return
536      }
537      // Never resend: the send may have reached the agent.
538      const sent = await $.session
539        .send({ to: { agentId: item.detail.agentId }, text: action.text })
540        .catch(() => undefined)
541      if (!sent) {
542        toast($, 'Delivery unknown')
543        return
544      }
545      toast($, sent.isDelivered ? `Message sent to claude ${nameOf(item)}` : 'Message not sent')
546      if (sent.isDelivered) await queueAction($, `Rabe: user sent a message to agent ${item.id}`)
547      return sequence(async () => {
548        const { selection } = await look($, true)
549        const target = messageLanding(action, selection, interaction.ringOn)
550        if (target) await land($, target)
551      })
552    }
553  }
554}
555
556// What the pane draws from: the sources' values and the person's place.
557async function look(
558  $: EngineInterface,
559  isFocused: boolean,
560): Promise<{ model: Model; selection: Selection }> {
561  const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
562  const { value: removed = [] } = await $.state.get({ plugin: 'rabe', key: 'removed' })
563  const { value: turns = {} } = await $.state.get({ plugin: 'rabe', key: 'turns' })
564  const { value: lines = {} } = await $.state.get({ plugin: 'rabe', key: 'lines' })
565  const { value: edits = [] } = await $.state.get({ plugin: 'rabe', key: 'edits' })
566  const { value: diffs = {} } = await $.state.get({ plugin: 'rabe', key: 'diffs' })
567  const { value: tab = 'items' } = await $.state.get({ plugin: 'rabe', key: 'tab' })
568  const { value: query = '' } = await $.state.get({ plugin: 'rabe', key: 'query' })
569  const { value: folded = [] } = await $.state.get({ plugin: 'rabe', key: 'folded' })
570  const selected = await pickedOn($, tab)
571  const { value: open = '' } = await $.state.get({ plugin: 'rabe', key: 'open' })
572  const { value: order } = await $.state.get({ plugin: 'rabe', key: 'order' })
573  const { value: worktrees } = await $.state.get({ plugin: 'rabe', key: 'worktrees' })
574  const { value: window } = await $.state.get({ plugin: 'rabe', key: 'window' })
575  const { value: grouping } = await $.state.get({ plugin: 'rabe', key: 'grouping' })
576  const { value: mainUsage } = await $.state.get({ plugin: 'rabe', key: 'mainUsage' })
577  const now = await $.clock.now()
578  const usage = await $.session.usage().catch(() => undefined)
579  const model = {
580    items,
581    removed,
582    turns,
583    lines,
584    now,
585    usd: usage?.cost?.usd,
586    previous: await previous($).catch(() => undefined),
587    edits,
588    diffs,
589    cwd: await $.session.cwd().catch(() => undefined),
590    sessionId: await $.session.id().catch(() => undefined),
591    ...(worktrees && { worktrees }),
592    ...(mainUsage && { mainUsage }),
593  }
594
595  const selection = {
596    tab,
597    query,
598    folded,
599    selected,
600    open,
601    isFocused,
602    isArmed: interaction.arming.isArmed,
603    isListArmed: interaction.arming.isListArmed,
604    isOnSearch: interaction.ringOn === 'search',
605    window: window ?? windowOf(baseHours, now),
606    ...(grouping && { grouping }),
607    ...(order && { order }),
608  }
609
610  return { model, selection }
611}
612
613// The presses and Input events under way, per surface and element (`slots`
614// in `sequence.ts`). Each event's hook adds its own slot before `next(e)`, and
615// the closure beneath, which the engine runs inside that `next(e)`, fills the
616// oldest empty slot of its element. Input events of one element run one at a
617// time (`inTurn`), so an Input event's slot is the only one of its element and
618// its closure's action is its own, whatever text a hook beneath hands the
619// closure.
620// ponytail: two presses of one Button in flight at once may swap their
621// actions; both are that Button's, and each runs exactly once.
622type Press = { action: Action; surface: RenderSurface; element: string }
623type Slot = { press?: Press }
624const table = slots<Press>()
625
626// The submit as the link that refused it received it: what the hooks beneath
627// made of Rabe's event (a redaction, a trim). Undefined when the trace does
628// not show a submit of this field.
629function refusedText(trace: readonly { received: unknown }[], element: string): string | undefined {
630  const last = trace.at(-1)?.received as { element?: unknown; kind?: unknown; value?: unknown }
631  return last?.element === element && last.kind === 'submit' && typeof last.value === 'string'
632    ? last.value
633    : undefined
634}
635
636// A submitted message whose drawing a redraw released before its closure ran:
637// send the text the hooks beneath passed on (`refusedText`) if the field is
638// still drawn, else say it was not sent.
639async function lostMessage(
640  $: EngineInterface,
641  e: { element: string; surface: RenderSurface },
642  text: string | undefined,
643  mine: Slot,
644): Promise<void> {
645  const id = e.element.slice('message:'.length)
646  const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
647  const item = items.find(one => one.id === id)
648  if (text !== undefined && !text.trim()) return
649  if (text === undefined || item?.kind !== 'agent' || isEnded(item) || isWorkflowAgent(item)) {
650    toast($, 'Message not sent')
651    return
652  }
653  mine.press = { action: { type: 'message', id, text }, surface: e.surface, element: e.element }
654}
655
656const slotOf = (at: At) => `${at.surface} ${at.element}`
657
658function leave(action: Action, at: At): void {
659  table.leave(slotOf(at), { action, surface: at.surface, element: at.element })
660}
661
662// Runs a press or an Input event beneath the hook, then carries out the action
663// its closure left in this event's own slot with the hook's `$`.
664async function carry<R>($: EngineInterface, at: At, run: (mine: Slot) => Promise<R>): Promise<R> {
665  let mine: Slot = {}
666  screen.release()
667  const focusTurn = reserve()
668  feed($, { type: 'press-start' })
669  let result: R
670  try {
671    result = await table.enter(slotOf(at), one => {
672      mine = one
673      return run(one)
674    })
675  } catch (error) {
676    await focusTurn(async () => undefined)
677    feed($, { type: 'press-end' })
678    throw error
679  }
680  try {
681    const press = mine.press
682    if (press && !isHeldBack(interaction, at)) {
683      const action = press.action
684      if (
685        action.type === 'focus' ||
686        (action.type !== 'message' && landing(action, '').length > 0)
687      ) {
688        await focusTurn(() => act($, action, press.surface, press.element))
689      } else {
690        await focusTurn(async () => undefined)
691        await act($, action, press.surface, press.element)
692      }
693    } else {
694      await focusTurn(async () => undefined)
695    }
696
697    return result
698  } finally {
699    feed($, { type: 'press-end' })
700  }
701}
702
703// An arrow key in a pane taller than its body scrolls it a row; Rabe moves
704// the focus to the next or previous row instead, and the pane follows the
705// focus. Past either end the scroll goes on, to show what is above or below.
706async function arrow($: EngineInterface, by: number, bodyRows: number): Promise<number | false> {
707  const { model, selection } = await look($, true)
708  const size = { columns: 80, rows: bodyRows, surface: 'terminal', hasInput: true } as const
709  const drawn = layout(paneView(model, size, selection))
710  const keys = rowKeys(
711    hold(drawn, heldOf(interaction, 'terminal', selection), seatsRows(selection)).list,
712  )
713  const key = stepRow(keys, selection.selected, by)
714  if (!key) return false
715  const from = keys.indexOf(`row:${selection.selected}`)
716  const to = keys.indexOf(key)
717  const moved = from < 0 ? to + 1 : to - from
718  feed($, { type: 'step', key })
719  await focusOn($, key)
720
721  return by - moved
722}
723
724async function focused($: EngineInterface, e: UiFocusInput, next: Next<'ui.focus'>) {
725  const { value: tab = 'items' } = await $.state.get({ plugin: 'rabe', key: 'tab' })
726  const before = await pickedOn($, tab)
727  const asked = e.element?.startsWith('row:') ? e.element.slice(4) : before
728  if (asked !== before) await pick($, tab, asked)
729  const result = await next(e)
730  const landing = landingOf(next.trace, 'deny' in result && !!result.deny)
731  const landed = landing?.element
732  const selected = landed?.startsWith('row:') ? landed.slice(4) : before
733  if (selected !== asked) await pick($, tab, selected)
734  if (landing && !landed) feed($, { type: 'unfocused' })
735  if (!landing) feed($, { type: 'landed', isMoved: false })
736  else if (landed) {
737    const { model, selection } = await look($, true)
738    feed($, {
739      type: 'focus',
740      byPerson: e.origin.kind === 'person',
741      key: landed,
742      requested: e.element,
743      isLiveRow: isLiveRow(model, selection, landed),
744      selected: selection.selected,
745    })
746    // A control or Input inside the clipped list is scrolled into view.
747    if (isPinned && !landed.startsWith('row:')) $.ui.invalidate('ui.render')
748  }
749
750  return result
751}
752
753export function pane(on: On, hours = baseHours): void {
754  baseHours = hours
755  on('session.start', async ($, e, next) => {
756    await $.command.register({
757      name: 'rabe',
758      description:
759        'Show background work: agents, Codex jobs, shells, monitors, cron jobs and workflows',
760      immediate: true,
761    })
762
763    return next(e)
764  })
765
766  // Each open sorts the lists once; then they hold their order (see `stable`).
767  on('command.run', { command: 'rabe' }, async $ => {
768    let items: RabeItem[] = []
769    // A rejected state or ui call must not escape the hook; the text answers.
770    try {
771      items = (await $.state.get({ plugin: 'rabe', key: 'items' })).value ?? []
772      const surfaces = await $.session.surfaces().catch(() => [])
773      // An empty list means nothing draws (a plain -p run), so text is the answer.
774      // Checked first: `$.ui.open` reports isPlaced true there although nothing draws.
775      if (surfaces.length === 0) return { text: itemsText(items) }
776      const { value: edits = [] } = await $.state.get({ plugin: 'rabe', key: 'edits' })
777      const { value: mainUsage } = await $.state.get({ plugin: 'rabe', key: 'mainUsage' })
778      await $.state.set(
779        { plugin: 'rabe', key: 'order' },
780        {
781          ...orderOf(items, edits, mainUsage),
782          'cost:model': orderIds('model', items, mainUsage),
783          'cost:harness': orderIds('harness', items, mainUsage),
784        },
785      )
786      await $.state.set({ plugin: 'rabe', key: 'window' }, windowOf(baseHours, await $.clock.now()))
787      isRestored = false
788      pinned = NO_PIN
789      const opened = await $.ui.open({ id: PANE, title: 'Rabe', closeOnEscape: true })
790      // Unplaced: the host cannot draw the pane (it waits undrawn). Close it, and
791      // never feed `opened` (that schedules the refocus), so the text is the answer.
792      if (!opened.isPlaced) {
793        // A refused or intercepted close leaves the pane pending: it stays the
794        // only answer. A resolved close counts only when the pane is gone.
795        const closed = await $.ui
796          .close({ id: PANE })
797          .then(async () => !(await $.ui.panes()).some(one => one.id === PANE))
798          .catch(() => false)
799        return closed ? { text: itemsText(items) } : {}
800      }
801      feed($, { type: 'opened' })
802
803      // The pane is the answer; text would also reach the transcript.
804      return {}
805    } catch {
806      return { text: itemsText(items) }
807    }
808  })
809
810  // A close the host carries out clears every hold; a canceled one keeps it.
811  // Esc in a filled search field is refused, so the pane and the filter stay
812  // (#187). The engine has released the keyboard before this hook runs, so the
813  // ring cannot be landed anywhere: the keys go to the prompt until the person
814  // presses `ctrl+x tab`. The ring state is dropped with the keyboard.
815  on('ui.close', { id: PANE, origin: { kind: 'person' } }, async ($, e, next) => {
816    const { value: query = '' } = await $.state.get({ plugin: 'rabe', key: 'query' })
817    if (!holdsClose(interaction.ringOn, query)) return next(e)
818    feed($, { type: 'unfocused' })
819    return { value: undefined }
820  }).catch((_$, e, next) => next(e))
821
822  on('ui.close', { id: PANE }, async ($, e, next) => {
823    const result = await next(e)
824    if (!(await $.ui.panes()).some(one => one.id === PANE)) {
825      screen.release()
826      feed($, { type: 'closed' })
827      isPinned = false
828      await $.state.set({ plugin: 'rabe', key: 'openFrom' }, null)
829    }
830    return result
831  }).catch((_$, e, next) => next(e))
832
833  on('session.end', { reason: /^/ }, async ($, e, next) => {
834    await remember($, e.resume?.id ?? e.sessionId)
835
836    return next(e)
837  }).catch((_$, e, next) => next(e))
838
839  on('prompt.submit', { origin: { kind: /^/ } }, async ($, e, next) => {
840    const { value: actions = [] } = await $.state.get({ plugin: 'rabe', key: 'actions' })
841    if (actions.length === 0) return next(e)
842    const result = await next({ ...e, context: [...(e.context ?? []), ...actions] })
843    if (!result.drop) await clearActions($, actions)
844    return result
845  }).catch((_$, e, next) => next(e))
846
847  on('ui.focus', { requestId: PANE, origin: { kind: 'plugin' } }, ($, e, next) =>
848    focused($, e, next),
849  ).catch((_$, e, next) => next(e))
850
851  // A fresh plugin move must reach a different hook than this active person hook.
852  on('ui.focus', { requestId: PANE, origin: { kind: 'person' } }, ($, e, next) => {
853    screen.release()
854    const keys =
855      interaction.holds[interaction.surface ?? 'terminal']?.keys.map(one => one.key) ?? []
856    const move = deferredFocus(interaction, keys, e.element)
857    if (move) {
858      feed($, { type: 'focus-queued', key: e.element, move })
859      return sequence(async () => {
860        const current =
861          interaction.holds[interaction.surface ?? 'terminal']?.keys.map(one => one.key) ?? []
862        const key = movedFocus(interaction, current, move)
863        if (!key) return focused($, e, next)
864        feed($, { type: 'step', key })
865        return (await focusOn($, key)) ? {} : { deny: 'Rabe focus move refused' }
866      })
867    }
868    return interaction.ringOn && e.element !== interaction.ringOn
869      ? sequence(() => focused($, e, next))
870      : focused($, e, next)
871  }).catch((_$, e, next) => next(e))
872
873  // Rabe's own `$.ui.focus` from a Button's or Input's closure reaches no
874  // hook of Rabe's, so its landings would never count; calls from these do.
875  on('ui.press', { requestId: PANE }, ($, e, next) =>
876    carry($, e, async () => {
877      const tab = TABS.find(one => e.element === `tab-${one.tab}`)
878      if (!tab) return next(e)
879      leave({ type: 'tab', tab: tab.tab }, e)
880      return { element: e.element }
881    }),
882  ).catch(async ($, e, next) => {
883    if (!(next.called && next.error.message?.includes(RELEASED))) return next(e)
884    if (e.element.startsWith('message-agent:')) await missedMessage($, e.element)
885    return { element: e.element }
886  })
887  // A redraw between a key and its closure releases the field's handler. The
888  // event carries the field's whole text, so the search filter still follows
889  // the field (#180) and a submitted message is still sent once (#218). Any
890  // other Input's event is dropped. Events of one field run one at a time.
891  on('ui.input', { requestId: PANE }, ($, e, next) =>
892    inTurn(slotOf(e), () =>
893      carry($, e, mine =>
894        next(e).catch(async (error: Error) => {
895          if (!error?.message?.includes(RELEASED)) throw error
896          if (e.element === 'search') {
897            leave(queryOf(e.value, e.kind), e)
898            return { element: e.element, value: e.value }
899          }
900          if (!(e.element.startsWith('message:') && e.kind === 'submit')) throw error
901          // A filled slot: the closure ran and `carry` sends its action.
902          if (!mine.press) await lostMessage($, e, refusedText(next.trace, e.element), mine)
903          return { element: e.element, value: e.value }
904        }),
905      ),
906    ),
907  ).catch((_$, e, next) =>
908    next.called && next.error.message?.includes(RELEASED)
909      ? { element: e.element, value: e.value }
910      : next(e),
911  )
912
913  on('ui.scroll', { requestId: PANE }, async ($, e, next) => {
914    // The pane fits its body: the list scrolls under the header, by our own offset.
915    if (isPinned && e.contentRows <= e.bodyRows) {
916      if (e.by !== 0) {
917        pinned = { ...pinned, top: Math.max(0, pinned.top + e.by) }
918        $.ui.invalidate('ui.render')
919      }
920      return {}
921    }
922    if (e.pointer || e.by === 0 || Math.abs(e.by) >= e.bodyRows) return next(e)
923    screen.release()
924    const remaining = await sequence(() => arrow($, e.by, e.bodyRows)).catch(() => false)
925    if (remaining === 0) return {}
926    if (typeof remaining === 'number')
927      return next(
928        e.offset > 0 && e.offset < e.contentRows - e.bodyRows
929          ? { ...e, offset: e.offset - e.by + remaining }
930          : e,
931      )
932
933    return next(e)
934  })
935
936  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
937    const ask = screen.asked()
938    const ui = $.ui.resolve(e)
939    const { model, selection: seen } = await look($, e.props.isFocused)
940    const size = bounded({
941      columns: e.props.bodyColumns,
942      rows: e.props.scroll?.bodyRows || 24,
943      surface: e.surface,
944      hasInput: 'Input' in ui,
945      ...(e.props.scroll && {
946        window: { top: e.props.scroll.offset, rows: e.props.scroll.bodyRows },
947      }),
948    })
949
950    // On the terminal a body taller than its room scrolls under the header.
951    // The scroll is measured on the held pieces the pane draws: a dry run of
952    // the drawing finds them for the scroll the view gets.
953    let fresh = e.surface === 'terminal' && e.props.scroll ? geometry(model, size, seen) : undefined
954    const drawing = (rows: number): InteractionEvent => ({
955      type: 'render',
956      model,
957      size: fresh ? { ...size, window: { top: fresh.above + pinned.top, rows } } : size,
958      selection: seen,
959      placement: e.props.placement,
960    })
961    let rows = fresh?.rows ?? 0
962    if (fresh) {
963      const dry = interact(interaction, drawing(rows)).list ?? []
964      const geo = measure(dry, fresh.head, size, seen.selected, interaction.ringOn, fresh.isTight)
965      // Held pieces (gone slots, a message field) can take rows the fresh view
966      // does not count: under the minimum the engine's scroll takes over.
967      if (geo.rows < MIN_ROWS) fresh = undefined
968      else {
969        pinned = follow(pinned, geo, scopeOf(seen), geo.key)
970        rows = geo.rows
971      }
972    }
973    isPinned = !!fresh
974
975    const { list = [] } = feed($, drawing(rows))
976    screen.drew(e.surface, ask)
977    if (!fresh) return render(ui, e.surface, list, leave)
978    const geo = measure(list, fresh.head, size, seen.selected, interaction.ringOn, fresh.isTight)
979    pinned = { ...pinned, top: Math.min(pinned.top, Math.max(0, geo.total - geo.rows)) }
980
981    return render(ui, e.surface, list, leave, 'cells', {
982      split: geo.split,
983      rows: geo.rows,
984      top: pinned.top,
985    })
986  })
987}
988
hooks/ui/views/timeline.ts 318 lines
1import type { RabeWindow } from '../../../types'
2import { isEnded, type RabeItem } from '../../model'
3import { nextRun } from '../../schedule'
4import { fit } from '../cells/grid'
5import { C, CHIP, type Style, tone } from '../cells/palette'
6import { clockTime, day, duration, idOrNa, tokens, usd, validId } from '../format'
7import {
8  bar,
9  byStart,
10  forwarderOf,
11  glyph,
12  KIND_LABEL,
13  kindOf,
14  nameSpans,
15  shown,
16  stable,
17  tree,
18} from '../lists'
19import type { Drawn, Line, Model, View, ViewButton } from '../view'
20import { resumeButton } from './detail'
21import { beside, fitLine, focusOn, text } from './lines'
22
23const dim = { fg: C.dim }
24const BOX = 40
25const SIDE_COLUMNS = 90
26
27const LEGEND: [string, Style][] = [
28  ['shell', CHIP.shell],
29  ['claude', CHIP.agent],
30  ['codex', CHIP.codex],
31  ['monitor', CHIP.monitor],
32  ['scheduled run', CHIP.cron],
33  ['done', CHIP.done],
34  ['failed', CHIP.failed],
35]
36
37const COUNTS: [RabeItem['kind'], string, string][] = [
38  ['agent', 'agent', 'agents'],
39  ['codex', 'codex', 'codex'],
40  ['workflow', 'workflow', 'workflows'],
41  ['shell', 'shell', 'shells'],
42  ['monitor', 'monitor', 'monitors'],
43]
44
45function color(item: RabeItem): number {
46  if (item.status === 'failed') return C.red
47  if (item.status === 'done') return C.green
48  if (item.status === 'stopped' || item.status === 'idle') return C.dim
49
50  return CHIP[item.kind].fg
51}
52
53// One cell per slice of the window: a bar over the run, or for a cron job a
54// tick at each scheduled run since Rabe saw it (jitter not counted).
55// What began before the window starts with `◂` at the left edge.
56function track(item: RabeItem, start: number, now: number, width: number): string {
57  const out = cells(item, start, now, width)
58
59  return (item.startedAt ?? item.seenAt) < start ? `◂${out.slice(1)}` : out
60}
61
62function cells(item: RabeItem, start: number, now: number, width: number): string {
63  if (item.kind !== 'cron') {
64    return bar(item.startedAt ?? item.seenAt, item.endedAt ?? now, start, now, width)
65  }
66  const cells = Array<string>(width).fill(' ')
67  const schedule = item.detail.schedule
68  const span = Math.max(1, now - start)
69  const end = Math.min(now, item.endedAt ?? now)
70  let at = schedule ? nextRun(schedule, Math.max(start, item.startedAt ?? item.seenAt)) : undefined
71  for (let n = 0; at !== undefined && at <= end && n < width; n++) {
72    cells[Math.min(width - 1, Math.floor(((at - start) / span) * width))] = '█'
73    at = nextRun(schedule as string, at)
74  }
75
76  return cells.join('')
77}
78
79function treeLines(items: RabeItem[]): Line[] {
80  return [
81    {
82      spans: [
83        ['WHO STARTED WHAT?', { fg: C.bright }],
84        ['  agents and their children', dim],
85      ],
86    },
87    { spans: [['main session']] },
88    ...tree(items).map(
89      (line): Line => ({
90        spans: [
91          [line.prefix, dim],
92          [`${glyph(line.item)} `, { fg: tone(line.item) }],
93          [line.item.title],
94          [line.item.kind === 'agent' ? '' : ` (${KIND_LABEL[kindOf(line.item)]})`, dim],
95        ],
96      }),
97    ),
98  ]
99}
100
101function previousLines(model: Model, width: number): Line[] {
102  const prev = model.previous
103  const head: Line = { spans: [[' PREVIOUS SESSION', { fg: C.bright }]] }
104  if (!prev) {
105    return [
106      head,
107      ...text('No earlier session with background work in this project.', width, dim, ' '),
108    ]
109  }
110  const counts = COUNTS.flatMap(([kind, one, many]) => {
111    const n = prev.counts[kind] ?? 0
112    return n ? [`${n} ${n === 1 ? one : many}`] : []
113  })
114  const crons = prev.counts.cron ?? 0
115  const took = prev.startedAt === undefined ? '' : ` · ${duration(prev.endedAt - prev.startedAt)}`
116  const failed = prev.failedIds
117    .slice(0, 2)
118    .map((id): Line => ({ spans: [[' ✗ failed', { fg: C.red }], [` ${id}`]] }))
119  const more = prev.failedIds.length - failed.length
120
121  const out: Line[] = [
122    head,
123    { spans: [[` this project · ended ${day(prev.endedAt, model.now)}`, dim]] },
124    { spans: [[' ✓', { fg: C.green }], [` ${counts.join(' · ') || 'no items'}`]] },
125    {
126      spans: [
127        [' session ', dim],
128        [prev.usd === undefined ? 'cost n/a' : `≈ ${usd(prev.usd)}`, { fg: C.bright }],
129        [took, dim],
130      ],
131    },
132    { spans: [[` background ${tokens(prev.tokens)} tok`, dim]] },
133    ...failed,
134    ...(more ? [{ spans: [[` +${more} more failed`, dim]] } as Line] : []),
135    ...(crons
136      ? [
137          {
138            spans: [
139              [' ⟳', { fg: C.purple }],
140              [` ${crons} cron job${crons === 1 ? '' : 's'} ended with the session`, dim],
141            ],
142          } as Line,
143        ]
144      : []),
145    { spans: [[` id ${idOrNa(prev.sessionId)}`, dim]] },
146  ]
147
148  return out.map(line => ({ ...line, bg: C.raised }))
149}
150
151const MIN = 60_000
152const STEPS = [1, 2, 5, 10, 15, 30, 60, 120, 180, 360, 720, 1440].map(one => one * MIN)
153
154// The time axis: round clock times, at most four, spaced for the window, then
155// `now`. A label that would repeat the one before it, run into it or into
156// `now` is left out.
157function axis(start: number, span: number, labelWidth: number, columns: number): string {
158  const barWidth = columns - labelWidth
159  const cells = Array<string>(columns).fill(' ')
160  const put = (x: number, value: string) => {
161    ;[...value].forEach((ch, i) => {
162      if (x + i >= 0 && x + i < columns) cells[x + i] = ch
163    })
164  }
165  const step = STEPS.find(one => span / one <= 4) ?? (STEPS.at(-1) as number)
166  // Round in local time: the zone's offset from UTC at the start.
167  const offset = new Date(start).getTimezoneOffset() * MIN
168  let last = ''
169  let end = labelWidth
170  for (let at = Math.ceil((start - offset) / step) * step + offset; at < start + span; at += step) {
171    const label = clockTime(at).slice(0, 5)
172    const x = labelWidth + Math.round((barWidth * (at - start)) / span) - 2
173    if (label === last || x < end || x + label.length > columns - 4) continue
174    put(x, label)
175    last = label
176    end = x + label.length + 1
177  }
178  if (!last && labelWidth + 5 <= columns - 4) put(labelWidth, clockTime(start).slice(0, 5))
179  put(columns - 3, 'now')
180
181  return cells.join('')
182}
183
184const HOUR = 3_600_000
185const DEFAULT_HOURS = 4
186const WIDE_HOURS = 12
187
188// The option `timelineHours`: hours, 0 for no limit; anything else the default.
189export function hoursOf(value: unknown): number {
190  const hours = typeof value === 'string' && value.trim() ? Number(value) : value
191  return typeof hours === 'number' && Number.isFinite(hours) && hours >= 0 ? hours : DEFAULT_HOURS
192}
193
194// The window `/rabe` opens with: the last `base` hours, or the whole session.
195export const windowOf = (base: number, now: number): RabeWindow => ({
196  base,
197  hours: base,
198  since: base > 0 ? now - base * HOUR : 0,
199})
200
201const steps = (base: number) => [base, ...(base < WIDE_HOURS ? [WIDE_HOURS] : []), 0]
202
203const next = (w: RabeWindow) => {
204  const list = steps(w.base)
205  return list[(list.indexOf(w.hours) + 1) % list.length] ?? 0
206}
207
208// The next window `w` steps to: base hours, 12 hours, the whole session, then
209// base again. A wider one never starts later than the one before.
210export function widen(w: RabeWindow, now: number): RabeWindow {
211  const hours = next(w)
212  if (hours === 0) return { ...w, hours, since: 0 }
213  const since = now - hours * HOUR
214
215  return { ...w, hours, since: w.hours === 0 || hours < w.hours ? since : Math.min(w.since, since) }
216}
217
218const spanText = (ms: number) => (ms < 2 * HOUR ? `${Math.round(ms / 60_000)} min` : duration(ms))
219
220// The Timeline tab: a bar per item over the window with a legend and a time
221// axis, then the tree of who started what beside (or above) the previous
222// session in this project. The rows keep the order the pane opened with.
223// Items that ended before the window (`sel.window`) fold into one line of
224// plain text, so the rows' focus order stays; `w` widens the window.
225export const timelineView: View = (model, size, sel): Drawn => {
226  const since = sel.window?.since ?? 0
227  const all = stable(shown(model.items), sel.order?.timeline, byStart)
228  const list = all.filter(item => !isEnded(item) || (item.endedAt ?? since) >= since)
229  const folded = all.length - list.length
230  const selected = list.find(item => item.id === sel.selected) ?? list[0]
231  const start = Math.max(
232    since,
233    Math.min(model.now - 60_000, ...list.map(item => item.startedAt ?? item.seenAt)),
234  )
235  const span = model.now - start
236  const labelWidth = Math.min(24, Math.floor(size.columns / 3))
237  const barWidth = size.columns - labelWidth
238  const isSide = size.columns >= SIDE_COLUMNS
239  const bars: Line[] = list.length
240    ? list.map(item => {
241        const name = fit(
242          (item.status === 'idle' ? 'idle ' : '') +
243            nameSpans(item)
244              .map(([one]) => one)
245              .join(''),
246          labelWidth - 2,
247        ).trimEnd()
248        return {
249          spans: [
250            [item === selected ? '▌' : ' ', { fg: C.orange }],
251            {
252              key: `row:${item.id}`,
253              label: name,
254              action: { type: 'open', id: item.id },
255              ...(item !== selected && { dim: true }),
256            },
257            [' '.repeat(labelWidth - 2 - [...name].length + 1)],
258            [track(item, start, model.now, barWidth), { fg: color(item) }],
259          ],
260          ...(item === selected && { bg: C.selected }),
261        }
262      })
263    : folded
264      ? []
265      : [{ spans: [[' Nothing ran yet.', dim]] }]
266  const fold: Line[] = folded
267    ? [
268        {
269          spans: [
270            [
271              ` +${folded} older item${folded === 1 ? '' : 's'}, ended before ${day(since, model.now).replace(/^today /, '')}`,
272              dim,
273            ],
274          ],
275        },
276      ]
277    : []
278  // a forwarder has no row, but stays in the tree above its job
279  const inList = new Set(list)
280  const forwarders = new Set(list.map(one => forwarderOf(one, model.items)))
281  const who = treeLines(model.items.filter(item => inList.has(item) || forwarders.has(item)))
282  const prev = previousLines(model, isSide ? BOX : size.columns)
283  const below = isSide
284    ? beside(who, size.columns - BOX - 2, [['  ']], prev, BOX)
285    : [...who, { spans: [] }, ...prev].map(line => fitLine(line, size.columns))
286  const lines: Line[] = [
287    {
288      spans: [
289        ['WHEN DID THINGS RUN?', { fg: C.bright }],
290        [`  this session, last ${spanText(span)}`, dim],
291      ],
292    },
293    { spans: LEGEND.flatMap(([label, chip]) => [[` ${label} `, chip], [' ']]) },
294    { spans: [] },
295    { spans: [[axis(start, span, labelWidth, size.columns), dim]] },
296    ...fold,
297    ...focusOn(bars, selected?.id ?? ''),
298    { spans: [] },
299  ]
300  const w = sel.window
301  const buttons: ViewButton[] =
302    w && w.base > 0
303      ? [
304          {
305            key: 'window',
306            label: `w: show ${next(w) ? `${next(w)} h` : 'all'}`,
307            hotkey: 'w',
308            action: { type: 'window' },
309          },
310        ]
311      : []
312
313  const id = model.previous?.sessionId
314  if (validId(id)) buttons.push(resumeButton(`claude --resume ${id}`, id))
315
316  return { nodes: [...lines.map(line => fitLine(line, size.columns)), ...below], buttons }
317}
318
hooks/reading.ts 227 lines
1import type { RabeFileCursor, RabeLines } from '../types'
2import { appendLines, MAX_LINES } from './tasks'
3
4export type FileStamp = { size: number; mtimeMs: number; identity?: string }
5
6export function isRecord(value: unknown): value is Record<string, unknown> {
7  return value !== null && typeof value === 'object' && !Array.isArray(value)
8}
9
10export type Rec = Record<string, unknown>
11
12// The record itself, or an empty one for anything else.
13export function rec(value: unknown): Rec {
14  return isRecord(value) ? value : {}
15}
16
17export function list(value: unknown): unknown[] {
18  return Array.isArray(value) ? value : []
19}
20
21export function str(value: unknown): string | undefined {
22  return typeof value === 'string' && value !== '' ? value : undefined
23}
24
25export function num(value: unknown): number | undefined {
26  return typeof value === 'number' ? value : undefined
27}
28
29// One JSON object; arrays, scalars and bad text give undefined.
30export function parseJson(text: string): Rec | undefined {
31  try {
32    const value = JSON.parse(text)
33    return isRecord(value) ? value : undefined
34  } catch {
35    return undefined
36  }
37}
38
39// The JSON objects of a JSONL text; blank and bad lines are skipped.
40export function jsonRecords(text: string): Rec[] {
41  return text.split('\n').flatMap(line => {
42    const one = parseJson(line)
43    return one ? [one] : []
44  })
45}
46
47export function restored<T>(value: Record<string, T> | undefined): Record<string, T> {
48  return isRecord(value) ? value : {}
49}
50
51export function cursorOf(value: unknown): RabeFileCursor | undefined {
52  if (!isRecord(value)) return
53  if (
54    !['size', 'mtimeMs', 'offset'].every(
55      key => typeof value[key] === 'number' && Number.isFinite(value[key]) && value[key] >= 0,
56    ) ||
57    !Number.isSafeInteger(value.size) ||
58    !Number.isSafeInteger(value.offset) ||
59    typeof value.partial !== 'boolean' ||
60    (value.identity !== undefined && typeof value.identity !== 'string') ||
61    (value.isDiscarding !== undefined && typeof value.isDiscarding !== 'boolean')
62  )
63    return
64  return value as RabeFileCursor
65}
66
67export function linesOf(value: unknown): RabeLines | undefined {
68  if (
69    !isRecord(value) ||
70    typeof value.seen !== 'number' ||
71    !Number.isFinite(value.seen) ||
72    value.seen < 0 ||
73    !Array.isArray(value.lines) ||
74    !value.lines.every(
75      line =>
76        isRecord(line) &&
77        typeof line.text === 'string' &&
78        typeof line.at === 'number' &&
79        Number.isFinite(line.at),
80    ) ||
81    (value.cursor !== undefined && !cursorOf(value.cursor)) ||
82    (value.ended !== undefined && !['done', 'failed', 'stopped'].includes(String(value.ended))) ||
83    ['exitCode', 'port'].some(
84      key =>
85        value[key] !== undefined &&
86        (typeof value[key] !== 'number' || !Number.isFinite(value[key])),
87    )
88  )
89    return
90  return value as RabeLines
91}
92
93export function inodeOf(stdout: string): string | undefined {
94  return /^\s*(\d+)/.exec(stdout)?.[1]
95}
96
97export function unchanged(stat: FileStamp, held?: Pick<FileStamp, 'size' | 'mtimeMs'>): boolean {
98  return held !== undefined && stat.size === held.size && stat.mtimeMs === held.mtimeMs
99}
100
101export function readPlan(stat: FileStamp, held: RabeFileCursor | undefined, max: number) {
102  const offset = fileOffset(stat, held)
103  if (offset === undefined) return
104  return { offset, reset: fileReset(stat, held), whole: offset === 0 && stat.size <= max }
105}
106
107export function outputUpdate(
108  held: RabeLines | undefined,
109  lines: string[],
110  now: number,
111  reset: boolean,
112  partial: boolean,
113  ended: boolean,
114  cursor?: RabeFileCursor,
115  result: Pick<RabeLines, 'ended' | 'exitCode' | 'port'> = {},
116  whole = false,
117): RabeLines | undefined {
118  const output = whole
119    ? { ...(appendLines(held, lines, now) ?? held ?? { seen: 0, lines: [] }), cursor }
120    : cursor
121      ? { ...outputLines(held, lines, now, reset, partial, ended), cursor }
122      : (appendLines(held, lines, now) ?? held ?? { seen: 0, lines: [] })
123  const { ended: status, exitCode, port } = result
124  const before = reset ? undefined : held
125  const next = {
126    ...output,
127    ...(status || before?.ended ? { ended: status ?? before?.ended } : {}),
128    ...(exitCode !== undefined || before?.exitCode !== undefined
129      ? { exitCode: exitCode ?? before?.exitCode }
130      : {}),
131    ...(port || before?.port ? { port: port ?? before?.port } : {}),
132  }
133  return JSON.stringify(next) === JSON.stringify(held) ? undefined : next
134}
135
136export function fileOffset(stat: FileStamp, held?: RabeFileCursor): number | undefined {
137  if (fileReset(stat, held)) return 0
138  if (!held) return 0
139  if (held.offset < held.size && !held.partial) return held.offset
140  if (stat.size === held.size && stat.mtimeMs === held.mtimeMs) return undefined
141  return held.offset
142}
143
144export function fileReset(stat: FileStamp, held?: RabeFileCursor): boolean {
145  return (
146    !held ||
147    stat.size < Math.max(held.size, held.offset) ||
148    stat.identity !== held.identity ||
149    (stat.size === held.size && stat.mtimeMs !== held.mtimeMs)
150  )
151}
152
153export function byteLength(text: string): number {
154  let bytes = 0
155  for (const char of text) {
156    const code = char.codePointAt(0) ?? 0
157    bytes += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4
158  }
159  return bytes
160}
161
162export function readChunk(text: string, truncated: boolean, json: boolean, discarding = false) {
163  const start = discarding ? text.indexOf('\n') + 1 : 0
164  const endLine = text.lastIndexOf('\n') + 1
165  if ((discarding && start === 0) || (truncated && endLine === 0)) {
166    return { text: '', bytes: byteLength(text), partial: false, isDiscarding: true }
167  }
168  let end = endLine
169  if (json && !truncated) {
170    try {
171      JSON.parse(text.slice(end))
172      end = text.length
173    } catch {}
174  }
175  return {
176    text: json || truncated ? text.slice(start, end) : text.slice(start),
177    bytes: byteLength(text.slice(0, end)),
178    partial: !truncated && end < text.length,
179  }
180}
181
182// The cursor after one read: the file stamp, the byte offset past the chunk
183// and whether the chunk was partial or skipped.
184export function nextCursor(
185  stamp: FileStamp,
186  offset: number,
187  chunk: { bytes: number; partial: boolean; isDiscarding?: boolean },
188) {
189  return {
190    ...stamp,
191    offset: offset + chunk.bytes,
192    partial: chunk.partial,
193    isDiscarding: chunk.isDiscarding,
194  }
195}
196
197// True when `stat` is the regular file `name` directly inside `root`, after
198// symlinks resolve: the one check that keeps a link from leaving a task folder.
199export function isOwnFile(
200  root: { realPath?: string },
201  stat: { realPath?: string; kind?: string },
202  name: string,
203): boolean {
204  return !!root.realPath && stat.realPath === `${root.realPath}/${name}` && stat.kind === 'file'
205}
206
207export function outputLines(
208  held: RabeLines | undefined,
209  lines: string[],
210  now: number,
211  reset: boolean,
212  partial: boolean,
213  ended = false,
214): RabeLines {
215  const before = reset ? undefined : held
216  const last = partial ? before?.lines.at(-1) : undefined
217  const kept = last ? (before?.lines.slice(0, -1) ?? []) : (before?.lines ?? [])
218  const fresh = lines.map((text, n) => ({ at: n === 0 && last ? last.at : now, text }))
219  const combined = [...kept, ...fresh]
220  const separator = ended && combined.at(-1)?.text === ''
221  if (separator) combined.pop()
222  return {
223    seen: (before?.seen ?? 0) - (last ? 1 : 0) + lines.length - (separator ? 1 : 0),
224    lines: combined.slice(-MAX_LINES),
225  }
226}
227
hooks/sources/agents.ts 598 lines
1import type {
2  EngineInterface,
3  On,
4  ToolResultOf,
5  TurnCompleteReason,
6  TurnStepResult,
7  TurnUsage,
8} from 'claude-code'
9
10import type { RabeDiff, RabeEdit, RabeModelPair } from '../../types'
11import { fromHunks, fromToolResult, keep } from '../diffs'
12import { companionCall } from '../forwarders'
13import { fault, type Pollers, skipped, tally } from '../loop'
14import { addMain } from '../main-usage'
15import { clip, type EndStatus, isAbsolute, isEnded, itemId, type RabeItem, runOf } from '../model'
16import { claudeUsd, type Prices, parsePrices, withOverride } from '../prices'
17import { isRecord, restored, unchanged } from '../reading'
18import {
19  addItem,
20  type Change,
21  changeOf,
22  commit,
23  endItem,
24  type Poll,
25  pastEnd,
26  prune,
27  stage,
28  updateItem,
29} from '../registry'
30import { changed, type Seen, shellWrites } from '../writes'
31
32import {
33  addTurn,
34  agentTranscript,
35  answered,
36  asAgent,
37  called,
38  changedFile,
39  edited,
40  LISTED,
41  listed,
42  MAX_EDITS,
43  metaPatch,
44  metaPath,
45  pairOf,
46  ranBash,
47  stepped,
48  type Turns,
49  toolSummary,
50  workflowTranscript,
51} from './agent-items'
52
53export { addTurn, agentTranscript, metaPatch, metaPath, toolSummary } from './agent-items'
54
55const MAX_ANSWER = 16000
56const MAX_CHECKS = 20
57const LOOK_MS = 1000
58const MAX_PROMPT = 600
59
60const ENDED: Record<TurnCompleteReason, EndStatus> = {
61  answer: 'done',
62  aborted: 'stopped',
63  refusal: 'failed',
64  error: 'failed',
65}
66
67async function write($: Pick<EngineInterface, 'state'>, change: Change): Promise<void> {
68  for (;;) {
69    const { value, version } = await $.state.get({ plugin: 'rabe', key: 'items' })
70    const next = commit(value, change)
71    if (next === undefined) return
72    const { isSet } = await $.state.set({ plugin: 'rabe', key: 'items' }, next.items, {
73      ifVersion: version,
74    })
75    if (isSet) return forget($, next.dropped)
76  }
77}
78
79// Drops the lines and turns of the items a write dropped.
80async function forget($: Pick<EngineInterface, 'state'>, dropped: string[]): Promise<void> {
81  if (dropped.length === 0) return
82  for (;;) {
83    const { value = {}, version } = await $.state.get({ plugin: 'rabe', key: 'lines' })
84    const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
85    const next = prune(value, dropped, items)
86    if (next === value) break
87    const lines = await $.state.set({ plugin: 'rabe', key: 'lines' }, next, { ifVersion: version })
88    if (lines.isSet) break
89  }
90  for (;;) {
91    const { value = {}, version } = await $.state.get({ plugin: 'rabe', key: 'turns' })
92    const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
93    const next = prune(value, dropped, items)
94    if (next === value) break
95    const turns = await $.state.set({ plugin: 'rabe', key: 'turns' }, next, { ifVersion: version })
96    if (turns.isSet) break
97  }
98  for (;;) {
99    const { value = {}, version } = await $.state.get({ plugin: 'rabe', key: 'diffs' })
100    const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
101    const next = prune(value, dropped, items)
102    if (next === value) return
103    const diffs = await $.state.set({ plugin: 'rabe', key: 'diffs' }, next, { ifVersion: version })
104    if (diffs.isSet) return
105  }
106}
107
108async function writeTurns(
109  $: Pick<EngineInterface, 'state'>,
110  change: (turns: Turns) => Turns,
111): Promise<void> {
112  for (;;) {
113    const { value = {}, version } = await $.state.get({ plugin: 'rabe', key: 'turns' })
114    const { isSet } = await $.state.set({ plugin: 'rabe', key: 'turns' }, change(value), {
115      ifVersion: version,
116    })
117    if (isSet) return
118  }
119}
120
121// The main session's changes go to `rabe.edits`, an agent's to its item.
122async function record(
123  $: EngineInterface,
124  agentId: string | undefined,
125  changes: RabeEdit[],
126): Promise<void> {
127  if (changes.length === 0) return
128  if (agentId) {
129    const id = itemId('agent', agentId)
130    return write($, items => edited(items, id, changes))
131  }
132  for (;;) {
133    const { value = [], version } = await $.state.get({ plugin: 'rabe', key: 'edits' })
134    const next = [...value, ...changes].slice(-MAX_EDITS)
135    const { isSet } = await $.state.set({ plugin: 'rabe', key: 'edits' }, next, {
136      ifVersion: version,
137    })
138    if (isSet) return
139  }
140}
141
142// The diffs of recorded operations, kept by editor: the agent's item id, or
143// `main`. Content is held in session state only, never read from files.
144async function recordDiffs(
145  $: EngineInterface,
146  agentId: string | undefined,
147  diffs: RabeDiff[],
148): Promise<void> {
149  if (diffs.length === 0) return
150  const editor = agentId ? itemId('agent', agentId) : 'main'
151  for (;;) {
152    // A late result of an evicted agent leaves no diff behind.
153    if (agentId) {
154      const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
155      if (!items.some(one => one.id === editor)) return
156    }
157    const { value = {}, version } = await $.state.get({ plugin: 'rabe', key: 'diffs' })
158    const next = keep(value, editor, diffs)
159    if (next === value) return
160    const { isSet } = await $.state.set({ plugin: 'rabe', key: 'diffs' }, next, {
161      ifVersion: version,
162    })
163    // An eviction may have finished its cleanup after the check above: drop what this write left.
164    if (isSet) return agentId ? forget($, [editor]) : undefined
165  }
166}
167
168type Listings = Map<string, Promise<Set<string> | undefined>>
169
170// A path whose stat failed is missing only when its folder lists without it,
171// or that folder is missing itself; error text is never read.
172function hasName(names: Set<string>, name: string): boolean {
173  if (names.has(name)) return true
174  const fold = (one: string) => one.normalize('NFC').toLowerCase()
175  const wanted = fold(name)
176  for (const one of names) if (fold(one) === wanted) return true
177
178  return false
179}
180
181async function isMissing($: EngineInterface, path: string, lists: Listings): Promise<boolean> {
182  const cut = path.lastIndexOf('/')
183  if (cut < 0 || path === '/') return false
184  const folder = path.slice(0, cut) || '/'
185  let names = lists.get(folder)
186  if (!names) {
187    names = $.fs.list(folder).then(
188      entries => new Set(entries.map(entry => entry.name)),
189      () => undefined,
190    )
191    lists.set(folder, names)
192  }
193  const listed = await names
194  // A name the folder lists in another case or Unicode form may be this file (macOS, Windows).
195  if (listed) return !hasName(listed, path.slice(cut + 1))
196
197  return folder !== '/' && isMissing($, folder, lists)
198}
199
200// What is on disk at each path, or undefined when the looks outlast LOOK_MS.
201async function look($: EngineInterface, paths: string[]): Promise<Seen[] | undefined> {
202  const stop = new AbortController()
203  const late = $.clock.sleep(LOOK_MS, { signal: stop.signal }).then(
204    () => undefined,
205    () => undefined,
206  )
207  const lists: Listings = new Map()
208  const seen = Promise.all(
209    paths.map(path =>
210      $.fs.stat(path).then(
211        (stat): Seen => stat,
212        async (): Promise<Seen> => ((await isMissing($, path, lists)) ? 'none' : undefined),
213      ),
214    ),
215  )
216  try {
217    return await Promise.race([seen, late])
218  } finally {
219    stop.abort()
220  }
221}
222
223type Looked = { paths: string[]; seen: Seen[] }
224
225async function beforeBash(
226  $: EngineInterface,
227  command: string,
228  agentId: string | undefined,
229): Promise<Looked | undefined> {
230  const home = await $.env.get('HOME')
231  let candidates = shellWrites(command, undefined, home)
232  if (candidates.some(one => !one.path.startsWith('/'))) {
233    let cwd: string | undefined
234    if (agentId) {
235      const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
236      cwd = asAgent(items, itemId('agent', agentId))?.detail.cwd
237    } else {
238      cwd = await $.session.cwd().catch(() => undefined)
239    }
240    candidates = shellWrites(command, cwd, home)
241  }
242  const paths = candidates.map(one => one.path).filter(path => path.startsWith('/'))
243  if (paths.length === 0 || paths.length > MAX_CHECKS) return undefined
244  const seen = await look($, paths)
245
246  return seen && { paths, seen }
247}
248
249async function afterBash(
250  $: EngineInterface,
251  agentId: string | undefined,
252  before: Looked | undefined,
253  result: unknown,
254) {
255  const after = before && (await look($, before.paths).catch(() => undefined))
256  const at = await $.clock.now()
257  const changes =
258    before && after
259      ? before.paths.flatMap((path, n): RabeEdit[] => {
260          const change = changed(before.seen[n], after[n])
261          if (!change) return []
262          return [{ path, at, via: 'shell', ...(change === 'delete' && { change }) }]
263        })
264      : []
265  const diff = (result as { bashEditDiff?: ToolResultOf<'Bash'>['bashEditDiff'] })?.bashEditDiff
266  if (
267    diff &&
268    !diff.shared &&
269    !diff.skipped &&
270    !diff.unavailable &&
271    Array.isArray(diff.changedFiles)
272  ) {
273    const paths = new Set(changes.map(one => one.path))
274    for (const path of diff.changedFiles) {
275      if (typeof path !== 'string' || !isAbsolute(path) || paths.has(path)) continue
276      const deleted =
277        Array.isArray(diff.files) &&
278        diff.files.some(file => file?.filePath === path && file?.deleted === true)
279      changes.push({ path, at, via: 'shell', ...(deleted && { change: 'delete' }) })
280      paths.add(path)
281    }
282  }
283  await record($, agentId, changes)
284  const hunks = new Map(
285    (diff && !diff.shared && !diff.skipped && !diff.unavailable && Array.isArray(diff.files)
286      ? diff.files
287      : []
288    ).map(file => [file?.filePath, file]),
289  )
290  const diffs = changes.flatMap(change => {
291    const file = hunks.get(change.path)
292    if (!file || file.deleted) return []
293    return [fromHunks(change.path, at, file.hunks)].filter(one => one !== undefined)
294  })
295  await recordDiffs($, agentId, diffs)
296}
297
298function cachedMeta(
299  items: RabeItem[],
300  id: string,
301  data: Record<string, unknown>,
302  before?: Record<string, unknown>,
303): RabeItem[] {
304  const item = asAgent(items, id)
305  if (!item) return items
306  const detail: Record<string, unknown> = item.detail
307  const patch = Object.fromEntries(
308    Object.entries(data).filter(([key]) =>
309      before
310        ? JSON.stringify(detail[key]) === JSON.stringify(before[key])
311        : detail[key] === undefined,
312    ),
313  )
314  return updateItem(items, id, { detail: patch })
315}
316
317async function readMeta(
318  $: EngineInterface,
319  id: string,
320  items: RabeItem[],
321): Promise<Change | undefined> {
322  const item = asAgent(items, id)
323  const path = item && metaPath(item, items)
324  if (!path) return
325  const stat = await $.fs.stat(path).catch(fault)
326  if (stat?.kind !== 'file') return
327  const { value: saved, version } = await $.state.get({ plugin: 'rabe', key: 'agentFiles' })
328  const value = restored(saved)
329  const held = value[id]
330  if (
331    held?.path === path &&
332    isRecord(held.data) &&
333    (held.before === undefined || isRecord(held.before)) &&
334    unchanged(stat, held)
335  ) {
336    skipped()
337    return list => cachedMeta(list, id, held.data, held.before)
338  }
339  const text = await $.fs.read(path).then(tally, fault)
340  const patch = typeof text === 'string' ? metaPatch(text) : undefined
341  if (!patch) return
342  const detail: Record<string, unknown> = item.detail
343  const before = Object.fromEntries(
344    Object.keys(patch)
345      .filter(key => detail[key] !== undefined)
346      .map(key => [key, detail[key]]),
347  )
348  await $.state.set(
349    { plugin: 'rabe', key: 'agentFiles' },
350    {
351      ...value,
352      [id]: { path, size: stat.size, mtimeMs: stat.mtimeMs, data: patch, before },
353    },
354    { ifVersion: version },
355  )
356  return list => cachedMeta(list, id, patch, before)
357}
358
359async function cleanFiles($: EngineInterface, items: RabeItem[]): Promise<void> {
360  const { value: saved, version } = await $.state.get({ plugin: 'rabe', key: 'agentFiles' })
361  const value = restored(saved)
362  const { value: current = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
363  const next = prune(value, Object.keys(value), [...items, ...current])
364  if (next !== value)
365    await $.state.set({ plugin: 'rabe', key: 'agentFiles' }, next, { ifVersion: version })
366}
367
368async function pollAgents($: EngineInterface, items: RabeItem[]): Promise<Change> {
369  const poll: Poll = { items, changes: [] }
370  const agents = await $.agent.list().catch(() => [])
371  const now = await $.clock.now()
372  stage(poll, items => {
373    const end = pastEnd(items, now)
374
375    return agents.reduce((list, info) => listed(list, info, now, end), items)
376  })
377  const { value: cached } = await $.state.get({ plugin: 'rabe', key: 'agentFiles' })
378  const metadata = restored(cached)
379  for (const item of poll.items) {
380    if (item.kind !== 'agent') continue
381    const workflow = runOf(item, poll.items)
382    if (
383      item.status === 'running' ||
384      (item.status === 'idle' && item.detail.isTeammate) ||
385      (workflow?.detail.phases?.length && item.detail.workflowPhase === undefined)
386    ) {
387      const change = await readMeta($, item.id, poll.items)
388      if (change) stage(poll, change)
389    } else {
390      const held = metadata[item.id]
391      if (isRecord(held?.data) && (held.before === undefined || isRecord(held.before)))
392        stage(poll, list => cachedMeta(list, item.id, held.data, held.before))
393    }
394  }
395  await cleanFiles($, poll.items)
396  return changeOf(poll, items)
397}
398
399// The built-in table, or with the user's file (`pricesFile`) its rows first. A
400// file that is set but cannot be read gives no prices: costs show n/a.
401async function prices($: EngineInterface, file: string): Promise<Prices> {
402  const read = (path: string) => $.fs.read(path).then(text => parsePrices(String(tally(text))))
403  const built = await read(`${$.plugin.root}/data/prices.csv`).catch(e => fault(e, []))
404  if (!file) return built
405  const home = file.startsWith('~/') && (await $.env.get('HOME').catch(() => undefined))
406  const own = await read(home ? `${home}${file.slice(1)}` : file).catch(fault)
407
408  return own ? withOverride(built, own) : []
409}
410
411async function recordStep(
412  $: EngineInterface,
413  agentId: string,
414  result: TurnStepResult,
415  file: string,
416  pair?: RabeModelPair,
417) {
418  const id = itemId('agent', agentId)
419  const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
420  if (!asAgent(items, id)) return
421  const now = await $.clock.now()
422  const tools = result.toolUses.map(use => ({ name: use.name, summary: toolSummary(use.input) }))
423  const usage = result.usage
424  const usd = usage ? claudeUsd(await prices($, file), usage, usage.model) : undefined
425  await write($, list => stepped(list, id, result, tools, now, usd, pair))
426  if (!result.answer && tools.length === 0) return
427  await writeTurns($, turns => {
428    const index = (turns[id]?.at(-1)?.index ?? 0) + 1
429    const turn = { index, at: now, text: clip(result.answer, MAX_ANSWER), tools }
430
431    return addTurn(turns, id, turn)
432  })
433}
434
435// A step of the main session (no agent), by model. Cache writes of the main
436// loop live 1 hour, so they bill at that rate; the sum starts when Rabe loads.
437async function recordMain($: EngineInterface, usage: TurnUsage, file: string) {
438  const usd = claudeUsd(await prices($, file), usage, usage.model, '1h')
439  const { value = {} } = await $.state.get({ plugin: 'rabe', key: 'mainUsage' })
440  await $.state.set({ plugin: 'rabe', key: 'mainUsage' }, addMain(value, usage, usd))
441}
442
443export function agents(on: On, file: string, pollers: Pollers): void {
444  on('session.start', { cwd: /^/ }, async ($, e, next) => {
445    pollers.push({ name: 'agents', run: items => pollAgents($, items), every: 3000 })
446    return next(e)
447  })
448
449  on('agent.spawn', { subagentType: /^/ }, async ($, e, next) => {
450    const result = await next(e)
451    const agentId = result.agentId
452    if (!agentId) return result
453    const now = await $.clock.now()
454    const runId = e.workflow?.runId
455    const parent = e.parentAgentId ? itemId('agent', e.parentAgentId) : undefined
456    const id = itemId('agent', agentId)
457    const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
458    const transcriptPath = runId
459      ? workflowTranscript(asAgent(items, id)?.detail.transcriptPath, agentId, runId)
460      : undefined
461    await write($, items =>
462      addItem(
463        items,
464        {
465          id: itemId('agent', agentId),
466          kind: 'agent',
467          title: e.description || e.subagentType,
468          status: 'running',
469          startedAt: now,
470          parentId: runId ? itemId('workflow', runId) : parent,
471          detail: {
472            agentId,
473            ...((e.isTeammate || result.teammateId) && { isTeammate: true }),
474            ...(transcriptPath && { transcriptPath }),
475            type: e.subagentType,
476            model: result.model,
477            description: e.description,
478            prompt: clip(e.prompt, MAX_PROMPT),
479            workflowIndex: e.workflow?.agentIndex,
480          },
481        },
482        now,
483      ),
484    )
485
486    return result
487  }).catch((_$, e, next) => next(e))
488
489  on('classic.SubagentStart', { agent_id: /^/ }, async ($, e, next) => {
490    const transcriptPath = agentTranscript(e.transcript_path, e.agent_id)
491    const detail = {
492      agentId: e.agent_id,
493      ...(transcriptPath && { transcriptPath }),
494      ...(e.cwd && { cwd: e.cwd }),
495    }
496    const id = itemId('agent', e.agent_id)
497    const now = await $.clock.now()
498    await write($, items =>
499      items.some(item => item.id === id)
500        ? updateItem(items, id, { detail })
501        : addItem(
502            items,
503            { id, kind: 'agent', title: e.agent_type, status: 'running', startedAt: now, detail },
504            now,
505          ),
506    )
507
508    return next(e)
509  }).catch((_$, e, next) => next(e))
510
511  on('turn.step', { agentId: /^/ }, async function* ($, e, next) {
512    const result = yield* next(e)
513    if (e.agentId)
514      await recordStep($, e.agentId, result, file, pairOf(result.usage?.model, e.effort))
515
516    return result
517  })
518
519  // `{ agentId: /^/ }` does not match a step without the field, so the main
520  // loop's steps come through `model`, which every step has.
521  on('turn.step', { model: /^/ }, async function* ($, e, next) {
522    const result = yield* next(e)
523    if (!e.agentId && result.usage) await recordMain($, result.usage, file)
524
525    return result
526  })
527
528  on('tool.call', { tool: ['Edit', 'Write'] }, async ($, e, next) => {
529    const answer = await next(e)
530    try {
531      const path = (e.tool === 'Edit' || e.tool === 'Write') && changedFile(answer, e.file_path)
532      if (path) {
533        const via = e.tool === 'Edit' ? 'edit' : 'write'
534        const at = await $.clock.now()
535        await record($, e.agentId, [{ path, at, via }])
536        const diff = fromToolResult(path, at, answer.result)
537        if (diff) await recordDiffs($, e.agentId, [diff])
538      }
539    } catch {}
540
541    return answer
542  })
543
544  // Host diffs name script edits; disk checks confirm command-line candidates.
545  // A call of the Codex companion is kept on its agent, so the Codex source can
546  // link the job it starts (see forwarders.ts).
547  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
548    const before =
549      e.tool === 'Bash'
550        ? await beforeBash($, e.command, e.agentId).catch(() => undefined)
551        : undefined
552    const call = e.tool === 'Bash' && e.agentId ? companionCall(e.command) : undefined
553    const id = itemId('agent', e.agentId ?? '')
554    const at = call && (await $.clock.now().catch(() => undefined))
555    if (call && at !== undefined) {
556      await write($, items => called(items, id, at, call)).catch(() => undefined)
557    }
558    const answer = await next(e)
559    try {
560      if (at !== undefined) {
561        const patch = answered(answer, await $.clock.now())
562        await write($, items => called(items, id, at, patch))
563      }
564    } catch {}
565    try {
566      if (ranBash(answer)) await afterBash($, e.agentId, before, answer.result)
567    } catch {}
568
569    return answer
570  })
571
572  on('turn.complete', { agentId: /^/ }, async ($, e, next) => {
573    const result = await next(e)
574    const agentId = e.agentId
575    if (!agentId) return result
576    const now = await $.clock.now()
577    const id = itemId('agent', agentId)
578    const info = (await $.agent.list().catch(() => [])).find(one => one.id === agentId)
579    await write($, items => {
580      const teammate = asAgent(items, id)?.detail.isTeammate || info?.teammateId
581      const status = info && LISTED[info.status]
582      if (teammate && (!status || !isEnded({ status }))) {
583        return updateItem(items, id, {
584          status: 'idle',
585          endedAt: undefined,
586          detail: { isTeammate: true },
587        })
588      }
589      return endItem(items, id, teammate && status ? (status as EndStatus) : ENDED[e.reason], now)
590    })
591    const { value: items = [] } = await $.state.get({ plugin: 'rabe', key: 'items' })
592    const change = await readMeta($, itemId('agent', agentId), items)
593    if (change) await write($, change)
594
595    return result
596  })
597}
598