SLOPSHOPPER

cactus pane

A live cactus inbox pane for the session's project, answerable in place

paneguardcommandtoastpromptprocess
★ 10v0.3.0MITupdated 2026-10-24eighteyes/cactus/mods/cactus-pane
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cactus-pane
│ ┃ cactus ✕ › fix the failing auth test and add an audit log call │ ┃ ⠁⠁ ⢀ ⠂ │ ┃ ⡈ ⠠⠈ ⏺ Read(src/auth.ts) │ ┃ ⢰⣹⣻⡆ ⠔ ⠠ ⢀ ⢀ ⠄ ⢀ ⢀ ⎿ Read 6 lines │ ┃ ⠁⣞⡟⡆ ⠂ ⏺ Update(src/auth.ts) │ ┃ ⠐⠠ ⢸⣸⣺⡇⢰⣻⣷ ⠠ ⢄⠠⡀⠂ ⠂ ⢀ ⠈ ⎿ Added 2 lines, removed 1 line │ ┃ ⡀⠄⡌⢀⣀⢀ ⣟⡗⡇ ⠂ ⏺ Bash(bun test) │ ┃ ⠈⢀⠄⠄⣘⡮⡋⡆⢸⣸⣺⡇⢸⣺⣾ ⠣⠂ ⠁⠠ ⠄⠁⢀ ⠠⡠ ⠠⠁⠆⠁⠠⠈ ⎿ 3 pass, 1 fail │ ┃ ⡠⠠⠑⢀⣟⡗⡇⠢⣟⡗⡇⠅⡈⠈ ⡀ │ ┃ ⠄⢀⠠⠘⡠⡧⡊⡇⢸⣸⣺⣷⣾⣺⣾ ⣤ ⢂⢓⠃⠤⣁⠘⢃⢀⠁⣀⣀⣄⣀⡀⠨⠈⣀ ⠗⣔⢆⠄ ⠠ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ⣟⡗⡇⠐⣟⡗⡇⠇⣠⡤⡀⡠ │ ┃ ⡔⠡⠋⡠⣣⡧⡊⡷⢺⣸⣺⡏⠉⠉⠉⢁⡓⠬⢣⠂⡠⢩⠁ ✻ Worked for 42s · done 4:20 PM │ ┃ ⡡⣴⣿⣿⣿⣿⣿⣿⣷⡄⠆⠋⠄⣥⠰⣩⡅⢈⠴⣟⡗⡇⢄⣟⡗⡇⢆⣟⡗⡇⠣⢅ │ ┃ ⢅⢃⣹⣮⣭⠉⠉⠉⢹⣸⣺⡇⣢⠪⡬⣨⢼⢦⡀⢧⡐⠚⣝⣟⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣥⣜⢿⣵⢢⣇⠊⣤⡦⣟ › /cactus-pane │ ┃ ⡗⡇⠲⣟⡗⡇⠜⣟⡗⡇⠐⢑ │ ┃ ⠑⢕⢕⢕⢕⢕⢕⢕⢸⣸⣺⡇⠋⠉⠏⠉⡉⠉⠉⠉⠍⠉⠋⠛⠍⠉⠫⠹⢭⠭⡭⣍⠉⢏⠉⢉⠙⠉⠉⠉⠝⠟⢉⣟ │ ┃ ⡗⡇⢕⣟⡗⡇⢕⣟⡗⡇⢕⢕ │ ┃ ⠑⢕⢕⢕⢕⢕⢸⣸⣺⡇⠠ ⠂ ⠄⠅⠠⡐ ⠈⠠⠤⠡⠄ ⠂⠁⠘ ⠂⠐⠙ ⡀ │ ┃ ⣟⡗⡇⢕⣟⡗⡇⢕⣟⡗⡇⢕⢕ │ ┃ │ ┃ Cactus inbox empty. │ ┃ Decisions incoming... │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · cactus
⠁⠁ ⢀ ⠂ ⡈ ⠠⠈ ⢰⣹⣻⡆ ⠔ ⠠ ⢀ ⢀ ⠄ ⢀ ⢀ ⠁⣞⡟⡆ ⠂ ⠐⠠ ⢸⣸⣺⡇⢰⣻⣷ ⠠ ⢄⠠⡀⠂ ⠂ ⢀ ⠈ ⡀⠄⡌⢀⣀⢀ ⣟⡗⡇ ⠂ ⠈⢀⠄⠄⣘⡮⡋⡆⢸⣸⣺⡇⢸⣺⣾ ⠣⠂ ⠁⠠ ⠄⠁⢀ ⠠⡠ ⠠⠁⠆⠁⠠⠈ ⡠⠠⠑⢀⣟⡗⡇⠢⣟⡗⡇⠅⡈⠈ ⡀ ⠄⢀⠠⠘⡠⡧⡊⡇⢸⣸⣺⣷⣾⣺⣾ ⣤ ⢂⢓⠃⠤⣁⠘⢃⢀⠁⣀⣀⣄⣀⡀⠨⠈⣀ ⠗⣔⢆⠄ ⠠ ⣟⡗⡇⠐⣟⡗⡇⠇⣠⡤⡀⡠ ⡔⠡⠋⡠⣣⡧⡊⡷⢺⣸⣺⡏⠉⠉⠉⢁⡓⠬⢣⠂⡠⢩⠁ ⡡⣴⣿⣿⣿⣿⣿⣿⣷⡄⠆⠋⠄⣥⠰⣩⡅⢈⠴⣟⡗⡇⢄⣟⡗⡇⢆⣟⡗⡇⠣⢅ ⢅⢃⣹⣮⣭⠉⠉⠉⢹⣸⣺⡇⣢⠪⡬⣨⢼⢦⡀⢧⡐⠚⣝⣟⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣥⣜⢿⣵⢢⣇⠊⣤⡦⣟⡗⡇⠲⣟⡗⡇⠜⣟⡗⡇⠐⢑ ⠑⢕⢕⢕⢕⢕⢕⢕⢸⣸⣺⡇⠋⠉⠏⠉⡉⠉⠉⠉⠍⠉⠋⠛⠍⠉⠫⠹⢭⠭⡭⣍⠉⢏⠉⢉⠙⠉⠉⠉⠝⠟⢉⣟⡗⡇⢕⣟⡗⡇⢕⣟⡗⡇⢕⢕ ⠑⢕⢕⢕⢕⢕⢸⣸⣺⡇⠠ ⠂ ⠄⠅⠠⡐ ⠈⠠⠤⠡⠄ ⠂⠁⠘ ⠂⠐⠙ ⡀ ⣟⡗⡇⢕⣟⡗⡇⢕⣟⡗⡇⢕⢕ Cactus inbox empty. Decisions incoming...
README

cactus pane

A live cactus inbox inside Claude Code. Your agent's questions show up as a pane; answer them in place.

Needs

  • The cactus CLI: uv tool install git+https://github.com/eighteyes/cactus
  • Claude Code with mods (function hooks) support

Use

  • Opens at session start (turn off in settings). /cactus-pane opens it again.
  • A rail of open rows, a card for the focused one. A digit answers, i types (enter in the text line sends it), g sends a multi pick. Enter on a question only opens it; it never answers, so a stray enter cannot send a recommendation.
  • When one of the session's rows moves, the pane waits the cooldown (15s by default), then starts a turn carrying the answer in full and clears the row. u inside the cooldown takes the answer back and nothing is sent; n sends it now. cactus answer KEY --now skips the cooldown for that answer. The agent posts cactus ask --no-wait and keeps working.
  • When one of the session's rows sits untouched a day (cactus's stale mark), the pane starts one turn asking the agent to reassert it with a bare cactus edit or clear it.
  • Esc in the text line puts you back on the question, not in Claude's prompt. Esc on a question leaves the pane.
  • h opens settings: autoshow at session start, wake cooldown (0/5/15/30/60s, or idle: sends once the pane has sat 15s untouched and the agent's turn has ended). Kept across sessions.

What it runs and sends

Everything stays on your machine. The pane talks to nothing over the network.

Programs it runs (process.run), each with a fixed program name:

  • cactus: the local CLI, in the session's project directory (session.cwd). feed --json --here every few seconds to draw the pane; answer, undo, elaborate, clear, get, plan, review when you press a key. exec runs the command a run or review row carries, only when you press r on that row.
  • git diff HEAD -- FILE and head -n 40 FILE: the o preview of a file attached to a row.
  • open FILE: the f key, opens an attached file in your default app (macOS).

Prompts it submits (prompt.submit): when one of this session's own rows is answered, it submits one prompt to this session holding each moved row's key, its question's first line and your answer, so the agent can act on it. Nothing else goes in.

Hooks that change what passes through:

  • tool.call on Bash: adds --no-wait to a cactus ask --no-wait or cactus run --no-wait command the agent writes, so the agent never blocks waiting for you; the pane wakes it instead. No other command is touched.
  • prompt.compose: adds one section to the system prompt describing the cactus workflow in mod mode.
  • command.run / command.register: the /cactus-pane command that reopens the pane.

License

MIT

Source 2 files
hooks/register.tsx 1441 lines
1// cactus-pane: a live cactus inbox pane for the session's project.
2// - polls `cactus feed --json --here` and keeps the open/live/elaborate rows; each poll first stats the cactus db and
3//   its -wal, and spawns cactus only when they changed, 60s have passed, or it is the first poll
4// - draws a one-line rail per row and a TUI-style card for the selected one
5// - the card's buttons carry the TUI's row keys (1-9, y/n, s, i, c, x, d, e, b, r, m)
6// - acts through the `cactus` CLI, so cli.py stays the only validator
7// - /cactus-pane opens the pane focused; it also opens unasked at session start
8// - wakes this session when its own rows move, after a cooldown an undo cancels (n skips it), and turns its cactus waits off
9// - wakes the session once when one of its rows goes stale: reassert (bare edit) or clear
10// - h opens settings: autoshow at session start, wake cooldown (or idle: you quiet, agent's turn over); kept in $.store
11// - Esc out of a text line takes the keys back onto the row header; Esc on a header leaves
12
13import { atom, read, update } from 'claude-code'
14import type { EngineInterface, Register } from 'claude-code'
15
16import type { Answer, PaneSettings, Row } from '../types'
17
18const PANE = 'cactus-pane'
19const POLL_MS = 5000
20// A poll spawns cactus at least this often even when the db is unchanged: rows go stale by wall clock.
21const REFRESH_MS = 60_000
22const PREVIEW_LINES = 40
23const HISTORY = 3
24// Headers drawn at once, centred on the selection, so its card stays in view.
25const LIST_WINDOW = 7
26const rows = atom({ plugin: 'cactus-pane', key: 'rows' } as const, [])
27const picks = atom({ plugin: 'cactus-pane', key: 'picks' } as const, {})
28const error = atom({ plugin: 'cactus-pane', key: 'error' } as const, null)
29const selected = atom({ plugin: 'cactus-pane', key: 'selected' } as const, null)
30const previews = atom({ plugin: 'cactus-pane', key: 'previews' } as const, {})
31const undo = atom({ plugin: 'cactus-pane', key: 'undo' } as const, [])
32const modes = atom({ plugin: 'cactus-pane', key: 'modes' } as const, {})
33const flips = atom({ plugin: 'cactus-pane', key: 'flips' } as const, {})
34const drafts = atom({ plugin: 'cactus-pane', key: 'drafts' } as const, {})
35const settings = atom({ plugin: 'cactus-pane', key: 'settings' } as const, { autoshow: true, cooldown: 15 })
36const settingsOpen = atom({ plugin: 'cactus-pane', key: 'settingsOpen' } as const, false)
37// Wakes waiting out the cooldown: row key -> seconds left at the last poll.
38const held = atom({ plugin: 'cactus-pane', key: 'held' } as const, {})
39const SETTINGS_KEY = 'h'
40const SEND_KEY = 'n'
41const COOLDOWNS: PaneSettings['cooldown'][] = [0, 5, 15, 30, 60, 'idle']
42// Under 'idle', how long the pane must sit untouched before a held wake goes.
43const IDLE_QUIET_MS = 15_000
44const UNDO_DEPTH = 20
45const RUN_TIMEOUT_MS = 600_000
46
47const ACT_COLOUR: Record<string, string> = {
48  ask: 'cyan',
49  steer: 'blue',
50  run: 'red',
51  review: 'magenta',
52  plan: 'green',
53  data: 'yellow',
54  notify: 'gray',
55}
56const CONFIDENCE: Record<string, string> = { low: '○', med: '◐', high: '●' }
57const PERSISTENT = new Set(['review', 'plan', 'data'])
58const QUIET = new Set(['open', 'live'])
59
60// The feed's change token; '' forces the next poll to rewrite the rows.
61let lastCursor = ''
62
63function firstLine(s: string | null | undefined): string {
64  return (s ?? '').split('\n')[0] ?? ''
65}
66
67// Rows arrive hard-wrapped for an 80-column terminal; the pane is narrower,
68// so soft breaks are joined and the pane wraps to its own width. A blank
69// line, a list or tradeoff marker, an indent, or a line after a colon keeps
70// its break.
71const KEEP_BREAK = /^(\s|[-+*•>]\s|\d+[.)]\s|→)/
72
73function reflow(s: string | null | undefined): string {
74  const out: string[] = []
75  for (const line of (s ?? '').split('\n')) {
76    const prev = out[out.length - 1]
77    const joins =
78      prev !== undefined && prev.trim() !== '' && line.trim() !== '' &&
79      !KEEP_BREAK.test(line) && !prev.trimEnd().endsWith(':')
80    if (joins) out[out.length - 1] = `${prev.trimEnd()} ${line.trim()}`
81    else out.push(line)
82  }
83  return out.join('\n').replace(/\n{3,}/g, '\n\n').trim()
84}
85
86function verdict(a: Answer): string {
87  if (a.skipped) return 'skipped'
88  const label = a.selected.join(', ')
89  if (label !== '' && a.text) return `${label} — ${a.text}`
90  return label || a.text || ''
91}
92
93// mtime+size of the cactus db and its -wal (a missing file reads 0:0), or null when the stat itself fails.
94async function dbSignature($: EngineInterface): Promise<string | null> {
95  try {
96    const db =
97      (await $.env.get('CACTUS_DB')) || `${(await $.env.get('HOME')) ?? ''}/.local/share/cactus/cactus.db`
98    const one = (path: string) =>
99      $.fs.stat(path).then(
100        st => `${st.mtimeMs}:${st.size}`,
101        (err: { code?: string }) => {
102          if (err?.code === 'ENOENT') return '0:0'
103          throw err
104        },
105      )
106    return `${await one(db)}|${await one(`${db}-wal`)}`
107  } catch {
108    return null
109  }
110}
111
112// What the last successful spawn saw: the db signature and when.
113let lastSig: string | null = null
114let lastSpawnAt = 0
115
116// The pane's title carries the open-question count: `cactus (3)`.
117function paneTitle(list: readonly Row[]): string {
118  const n = list.filter(r => r.status === 'open').length
119  return n > 0 ? `cactus (${n})` : 'cactus'
120}
121
122// Retitles the pane only while it is open: an open id retitles, a closed one
123// would open unasked.
124async function retitle($: EngineInterface, list: readonly Row[]): Promise<void> {
125  if (!(await $.ui.panes()).some(p => p.id === PANE)) return
126  await $.ui.open({ id: PANE, title: paneTitle(list) })
127}
128
129// Runs in the session root, not the shell cwd: a `cd` into a subdirectory of a
130// non-git project would scope `--here` to that subdirectory and empty the pane.
131async function poll($: EngineInterface): Promise<void> {
132  await refresh($)
133  await flush($).catch(() => undefined)
134}
135
136async function refresh($: EngineInterface): Promise<void> {
137  const sig = await dbSignature($)
138  if (sig !== null && sig === lastSig && Date.now() - lastSpawnAt < REFRESH_MS) return
139  const ran = await $.process.run(['cactus', 'feed', '--json', '--here'], {
140    cwd: await $.session.root(),
141  })
142  if (ran.exitCode === 0 || ran.exitCode === 3) {
143    lastSig = sig
144    lastSpawnAt = Date.now()
145  }
146  if (ran.exitCode === 3) {
147    if (lastCursor !== 'empty') {
148      lastCursor = 'empty'
149      await update($, rows, () => [])
150      await update($, error, () => null)
151      await retitle($, []).catch(() => undefined)
152      await wake($, []).catch(() => undefined)
153    }
154    return
155  }
156  if (ran.exitCode !== 0) {
157    await update($, error, () => firstLine(ran.stderr) || `feed exit ${ran.exitCode}`)
158    return
159  }
160  const doc = JSON.parse(ran.stdout) as { cursor: unknown; questions: Row[] }
161  // Staleness moves with the clock, not the cursor: checked on every feed.
162  await nudgeStale($, doc.questions).catch(() => undefined)
163  const cursor = JSON.stringify(doc.cursor)
164  if (cursor === lastCursor) return
165  lastCursor = cursor
166  await update($, rows, () => doc.questions)
167  await update($, error, () => null)
168  await retitle($, doc.questions).catch(() => undefined)
169  await wake($, doc.questions).catch(() => undefined)
170}
171
172// A row's state as the wake reads it; `sig` also tells a re-answer apart.
173type Seen = { status: string; n: number; sig: string; now: boolean }
174
175function seen(r: Row): Seen {
176  const last = r.answers[r.answers.length - 1]
177  return {
178    status: r.status,
179    n: r.answers.length,
180    sig: `${r.status}:${r.answers.length}:${last?.created_at ?? ''}`,
181    now: last?.now === true,
182  }
183}
184
185// This session's own rows as last seen: key -> status and verdict count.
186// Null until the first poll seeds it, so rows already settled never wake.
187let watched: { sid: string; rows: Map<string, Seen> } | null = null
188
189// Moves waiting out the cooldown: key -> the state before the move, the state
190// now, and when the wake is due. Back at `before` (an undo) drops it; any other
191// change restarts the clock.
192const pending = new Map<string, { before: Seen; sig: string; due: number }>()
193let cooldownMs = 15_000
194// 'idle': a wake waits for you to go quiet in the pane and the agent's own turn to end.
195let idleMode = false
196let agentBusy = false
197
198function applyCooldown(s: PaneSettings): void {
199  idleMode = s.cooldown === 'idle'
200  cooldownMs = s.cooldown === 'idle' ? IDLE_QUIET_MS : s.cooldown * 1000
201}
202
203// Under 'idle', any touch in the pane pushes every held wake back to a fresh quiet spell.
204async function quiet($: EngineInterface): Promise<void> {
205  if (!idleMode || pending.size === 0) return
206  const at = await $.clock.now()
207  for (const [key, p] of pending) pending.set(key, { ...p, due: at + cooldownMs })
208  $.clock.after(cooldownMs, () => poll($))
209}
210
211// What a wake says about one row, and what is left for the agent to do. A
212// proper answer arrives whole and is cleared here, so it needs no get/clear.
213type Moved = { row: Row; text: string; clears: boolean; heard: boolean }
214
215function describe(row: Row): Moved {
216  const last = row.answers[row.answers.length - 1]
217  const asked = `${row.key} ${firstLine(row.text)}`
218  if (row.status === 'cleared' && row.closed_by_pass === true && last !== undefined) {
219    return { row, text: `${asked}\n  verdict: ${verdict(last)}\n  (the pass closed it)`, clears: false, heard: false }
220  }
221  if (row.status === 'cleared') {
222    return { row, text: `${asked}\n  declined: the human cleared it`, clears: false, heard: false }
223  }
224  if (row.status === 'elaborate') {
225    const hint = row.elaborate ?? 'no hint: rewrite plainly, add numbers and costs'
226    return {
227      row,
228      text: `${asked}\n  sent back for a rewrite: ${hint}\n  rewrite it with \`cactus edit ${row.key}\``,
229      clears: false,
230      heard: false,
231    }
232  }
233  if (last === undefined) return { row, text: `${asked}\n  ${row.status}`, clears: false, heard: false }
234  const ran = row.result ? `\n  ran: exit ${String(row.result.exit)}${row.result.log ? `, log ${row.result.log}` : ''}` : ''
235  if (PERSISTENT.has(row.act)) {
236    return {
237      row,
238      text: `${asked}\n  verdict: ${verdict(last)}${ran}\n  respond with \`cactus ${row.act === 'plan' ? 'plan' : row.act === 'review' ? 'review' : 'edit'} ${row.key}\` once acted on`,
239      clears: false,
240      heard: true,
241    }
242  }
243  if (last.skipped) {
244    return { row, text: `${asked}\n  skipped: act on your stated default\n  (cleared)`, clears: true, heard: false }
245  }
246  return { row, text: `${asked}\n  answer: ${verdict(last)}${ran}\n  (cleared)`, clears: true, heard: false }
247}
248
249// The client end of delivery: when one of this session's rows moves, hold it
250// for the cooldown, then start a turn (queued behind a running one). A prompt
251// the mod submits replaces the backgrounded wait while the mod is loaded.
252async function wake($: EngineInterface, list: Row[]): Promise<void> {
253  const sid = await $.session.id()
254  const now = new Map(list.filter(r => r.agent === sid).map(r => [r.key, seen(r)]))
255  if (watched === null || watched.sid !== sid) {
256    watched = { sid, rows: now }
257    pending.clear()
258    return
259  }
260  const at = await $.clock.now()
261  for (const key of new Set([...watched.rows.keys(), ...pending.keys()])) {
262    const after = now.get(key)
263    const sig = after?.sig ?? 'gone'
264    const p = pending.get(key)
265    if (p !== undefined) {
266      if (after !== undefined && after.status === p.before.status && after.n === p.before.n) pending.delete(key)
267      else if (sig !== p.sig) {
268        pending.set(key, { ...p, sig, due: at + cooldownMs })
269        $.clock.after(cooldownMs, () => poll($))
270      }
271      continue
272    }
273    const before = watched.rows.get(key)
274    if (before === undefined) continue
275    // A move back to open/live with no new verdict is this agent's own edit
276    // answering an elaborate request: never wake on it (q334's echo rule).
277    if (after === undefined || after.n > before.n || (after.status !== before.status && !QUIET.has(after.status))) {
278      // An answer made with --now has no undo to wait out: due at once.
279      if (await answeredNow($, key, after, before)) {
280        pending.set(key, { before, sig, due: at })
281        continue
282      }
283      pending.set(key, { before, sig, due: at + cooldownMs })
284      if (cooldownMs > 0) $.clock.after(cooldownMs, () => poll($))
285      await quiet($)
286    }
287  }
288  watched = { sid, rows: now }
289  await flush($)
290}
291
292// Whether this move is a new answer made with --now. A one-shot row leaves the
293// feed once answered, so its answer is read with `get`; a persistent row is
294// still in the feed and carries it.
295async function answeredNow($: EngineInterface, key: string, after: Seen | undefined, before: Seen): Promise<boolean> {
296  if (after !== undefined) return after.n > before.n && after.now
297  try {
298    const got = await $.process.run(['cactus', 'get', key, '--json'], { cwd: await $.session.root() })
299    const parsed: unknown = got.exitCode === 0 ? JSON.parse(got.stdout) : null
300    const row = Array.isArray(parsed) ? (parsed[0] as Row | undefined) : undefined
301    return row?.status === 'answered' && row.answers.length > before.n && row.answers[row.answers.length - 1]?.now === true
302  } catch {
303    return false
304  }
305}
306
307// Skips the cooldown: every held move is due now.
308async function sendNow($: EngineInterface): Promise<void> {
309  const at = await $.clock.now()
310  for (const [key, p] of pending) pending.set(key, { ...p, due: at })
311  await flush($, true)
312}
313
314// This session's own stale rows already nudged. Seeded on first sight, so the
315// rows the session-start hook listed are not repeated; a reassert (a bare edit)
316// or an answer restarts the clock, the row leaves stale, and leaves this set.
317let nudged: { sid: string; keys: Set<string> } | null = null
318
319// Wakes the session when one of its rows goes stale: reassert it or clear it.
320async function nudgeStale($: EngineInterface, list: Row[]): Promise<void> {
321  const sid = await $.session.id()
322  const stale = list.filter(r => r.agent === sid && r.stale === true)
323  const keys = new Set(stale.map(r => r.key))
324  if (nudged === null || nudged.sid !== sid) {
325    nudged = { sid, keys }
326    return
327  }
328  for (const key of nudged.keys) if (!keys.has(key)) nudged.keys.delete(key)
329  const fresh = stale.filter(r => !nudged?.keys.has(r.key))
330  if (fresh.length === 0) return
331  for (const r of fresh) nudged.keys.add(r.key)
332  const lines = fresh.map(r => `${r.key} ${firstLine(r.text)}\n  stale: untouched ${idleLabel(r.idle_hours ?? 0)}`)
333  // Off the clock, not inline: a poll from /cactus-pane runs inside a command
334  // hook, where a submit is refused and the nudge would be lost.
335  $.clock.after(0, () => void submitNudge($, sid, lines).catch(() => undefined))
336}
337
338async function submitNudge($: EngineInterface, sid: string, lines: string[]): Promise<void> {
339  await $.prompt.submit({
340    text: [
341      ...lines,
342      '',
343      `Still needed and unanswered: reassert with a bare \`cactus edit KEY --agent ${sid}\` (restarts the clock).`,
344      `Dead: \`cactus clear KEY --agent ${sid}\`.`,
345    ].join('\n'),
346    asUser: true,
347  })
348}
349
350// Sends every held move whose cooldown ran out, and shows the rest counting down.
351// Under 'idle' a due wake also waits out the agent's turn (-1 in `held`); send-now forces it.
352async function flush($: EngineInterface, force = false): Promise<void> {
353  const at = await $.clock.now()
354  const blocked = idleMode && agentBusy && !force
355  const due = blocked ? [] : [...pending].filter(([, p]) => p.due <= at).map(([key]) => key)
356  for (const key of due) pending.delete(key)
357  await update($, held, () =>
358    Object.fromEntries(
359      [...pending].map(([key, p]) => [key, p.due <= at ? -1 : Math.ceil((p.due - at) / 1000)]),
360    ),
361  )
362  if (due.length === 0) return
363  const sid = await $.session.id()
364  const list = await read($, rows)
365  const moved: Row[] = []
366  const gone: string[] = []
367  for (const key of due) {
368    const row = list.find(r => r.key === key)
369    if (row === undefined) gone.push(key)
370    else moved.push(row)
371  }
372  if (gone.length > 0) {
373    const got = await $.process.run(['cactus', 'get', ...gone, '--json'], {
374      cwd: await $.session.root(),
375    })
376    const parsed: unknown = got.exitCode === 0 ? JSON.parse(got.stdout) : null
377    if (Array.isArray(parsed)) {
378      // A row this agent cleared itself is not the human declining it.
379      for (const row of parsed as Row[]) {
380        if (row.status === 'cleared' && selfCleared.delete(row.key)) continue
381        moved.push(row)
382      }
383    }
384  }
385  if (moved.length === 0) return
386  const told = moved.map(describe)
387  const cwd = await $.session.root()
388  const clears = told.filter(t => t.clears).map(t => t.row.key)
389  if (clears.length > 0) await $.process.run(['cactus', 'clear', ...clears, '--agent', sid], { cwd })
390  // A read under the owner's --agent is what tells the human the verdict was
391  // heard; the wake carries it, so the mod reads it on the agent's behalf.
392  const heard = told.filter(t => t.heard).map(t => t.row.key)
393  if (heard.length > 0) await $.process.run(['cactus', 'get', ...heard, '--agent', sid, '--json'], { cwd })
394  // Bare, as the person's own words: no plugin frame, no header, just the rows.
395  await $.prompt.submit({ text: told.map(t => t.text).join('\n\n'), asUser: true })
396}
397
398// The cactus workflow in mod mode, injected into the system prompt for as long
399// as the mod is loaded; unloading it restores the session-start hook's waits.
400function guide(sid: string): string {
401  return [
402    '# cactus (mod mode)',
403    'cactus-pane is loaded: this session runs cactus in mod mode. It overrides the',
404    "session-start hook's wait instructions for as long as the mod is loaded.",
405    '',
406    `Identity: pass \`--agent ${sid}\` on every ask, edit, plan, review and clear.`,
407    '',
408    '1 ask    post every decision the human makes with `cactus ask`, not chat or',
409    '         AskUserQuestion: one -c per direction, --recommend LABEL --confidence L',
410    '         when you have a pick, -f for every file it is about.',
411    '2 post   post with --no-wait (the mod adds it when missing) and keep working.',
412    '         Never background-wait: no `cactus get --wait`, no waiting ask.',
413    '3 wake   the mod starts a turn, worded as the human, listing each row that moved',
414    '         is answered, gets a verdict, is sent back for a rewrite, or is cleared.',
415    '4 act    the wake carries each answer in full. An answered or skipped row is',
416    '         already cleared: act on the answer, or on your stated default.',
417    `         An elaborate row: rewrite it with \`cactus edit KEY --agent ${sid}\`.`,
418    '         A review/plan verdict (already marked heard): act, then respond with',
419    '         `cactus plan|review|edit`. `cactus get` only for more detail.',
420    '5 clear  the rows the mod did not clear (steer, notify, review, plan, data),',
421    '         by key, once acted on.',
422    '',
423    'The Stop hook stays quiet while you have an open row; end a turn with one open.',
424  ].join('\n')
425}
426
427// Blocking `cactus ask`/`cactus run` gain --no-wait: the mod is the wait.
428// Keys the agent clears through Bash, so their clear never reads as a decline.
429const selfCleared = new Set<string>()
430
431function noteClears(command: string): void {
432  for (const m of command.matchAll(/\bcactus\s+clear\b([^\n;&|]*)/g)) {
433    for (const word of (m[1] ?? '').split(/\s+/)) {
434      if (/^([\w.-]+:)?q\d+$/.test(word)) selfCleared.add(word.replace(/^.*:/, ''))
435    }
436  }
437}
438
439function noWait(command: string): string {
440  return command.replace(/\bcactus\s+(ask|run)\b(?![^\n;&|]*--no-wait)/g, 'cactus $1 --no-wait')
441}
442
443async function cactus(
444  $: EngineInterface,
445  key: string,
446  args: string[],
447  timeoutMs?: number,
448): Promise<string | null> {
449  const ran = await $.process.run(['cactus', ...args], {
450    cwd: await $.session.root(),
451    ...(timeoutMs === undefined ? {} : { timeoutMs }),
452  })
453  if (ran.exitCode !== 0) {
454    $.ui.toast(`cactus ${key}: ${firstLine(ran.stderr) || `exit ${ran.exitCode}`}`)
455    return null
456  }
457  await update($, picks, all => {
458    const { [key]: _gone, ...rest } = all
459    return rest
460  })
461  const before = (await read($, rows)).map(r => r.key)
462  lastCursor = ''
463  await poll($)
464  await refocus($, key, before)
465  return ran.stdout
466}
467
468// A row that left the inbox takes the focus ring with it, and a pane with no
469// ring hears no arrows. Land it on the header of the row now in that place.
470async function refocus($: EngineInterface, key: string, before: string[]): Promise<void> {
471  const now = (await read($, rows)).map(r => r.key)
472  if (now.includes(key)) return
473  const at = before.indexOf(key)
474  const after = before.slice(at + 1).find(k => now.includes(k))
475  const prior = before.slice(0, Math.max(0, at)).reverse().find(k => now.includes(k))
476  const target = after ?? prior
477  if (target === undefined) return
478  await select($, target)
479  await $.ui.focus({ requestId: PANE, key: `${target}:sel` }).catch(() => undefined)
480  await pinTop($, target)
481}
482
483// An answer or verdict the pane recorded goes on the undo stack: `u` pops it.
484async function answerRow($: EngineInterface, key: string, args: string[]): Promise<void> {
485  const row = (await read($, rows)).find(r => r.key === key)
486  if ((await cactus($, key, ['answer', key, ...args])) !== null) {
487    await update($, undo, stack => [...stack.filter(k => k !== key), key].slice(-UNDO_DEPTH))
488    // A review or plan stays open after a verdict; move on to the next
489    // question so the one just sent does not sit under the reader.
490    if (row !== undefined && PERSISTENT.has(row.act)) await advancePast($, key)
491  }
492}
493
494// Select the question after `key`, wrapping to the top; a no-op when `key` is
495// not the selected one any more or is the only question left.
496async function advancePast($: EngineInterface, key: string): Promise<void> {
497  const list = await read($, rows)
498  // Nothing stored yet means the first question is the open one.
499  if (((await read($, selected)) ?? list[0]?.key) !== key || list.length < 2) return
500  const at = list.findIndex(r => r.key === key)
501  const to = list[(at + 1) % list.length]
502  if (to === undefined || to.key === key) return
503  await select($, to.key)
504  await $.ui.focus({ requestId: PANE, key: `${to.key}:sel` }).catch(() => undefined)
505  await pinTop($, to.key)
506}
507
508async function undoLast($: EngineInterface): Promise<void> {
509  const stack = await read($, undo)
510  const key = stack[stack.length - 1]
511  if (key === undefined) return
512  await update($, undo, s => s.slice(0, -1))
513  if ((await cactus($, key, ['undo', key])) !== null) {
514    $.ui.toast(`cactus ${key}: answer withdrawn`)
515    await select($, key)
516  }
517}
518
519async function loadSettings($: EngineInterface): Promise<PaneSettings> {
520  const raw = (await $.store.get('settings').catch(() => undefined)) as Partial<PaneSettings> | undefined
521  const s: PaneSettings = {
522    autoshow: typeof raw?.autoshow === 'boolean' ? raw.autoshow : true,
523    cooldown: raw?.cooldown === 'idle' || (typeof raw?.cooldown === 'number' && raw.cooldown >= 0) ? raw.cooldown : 15,
524  }
525  applyCooldown(s)
526  await update($, settings, () => s)
527  return s
528}
529
530async function changeSettings($: EngineInterface, fn: (s: PaneSettings) => PaneSettings): Promise<void> {
531  const s = fn(await read($, settings))
532  applyCooldown(s)
533  await update($, settings, () => s)
534  await $.store.set('settings', s)
535}
536
537// The TUI's `R`: run the row's command; on a run row that is the approval.
538async function runRow($: EngineInterface, key: string, isRunAct: boolean): Promise<void> {
539  $.ui.toast(`cactus ${key}: running`)
540  const out = await cactus($, key, ['exec', key], RUN_TIMEOUT_MS)
541  if (out === null) return
542  if (isRunAct) {
543    await update($, undo, stack => [...stack.filter(k => k !== key), key].slice(-UNDO_DEPTH))
544  }
545  $.ui.toast(`cactus ${key}: ran — ${firstLine(out.trim().split('\n').slice(-1)[0])}`)
546}
547
548// The flip is the pane's alone: `cactus answer -s a -s b` already records
549// several picks on a choice row, so the row itself never changes.
550async function setFlip($: EngineInterface, key: string, flipOn: boolean): Promise<void> {
551  await update($, flips, all => {
552    const { [key]: _gone, ...rest } = all
553    return flipOn ? { ...rest, [key]: true as const } : rest
554  })
555  await update($, picks, all => {
556    const { [key]: _gone, ...rest } = all
557    return rest
558  })
559}
560
561async function setDraft($: EngineInterface, key: string, text: string): Promise<void> {
562  await update($, drafts, all => {
563    const { [key]: _gone, ...rest } = all
564    return text === '' ? rest : { ...rest, [key]: text }
565  })
566}
567
568// One input line; enter sends. Multi-line is hidden until asked for: a line
569// ending in `\` is kept (without the `\`) and shown above the input, and the
570// next plain enter sends every kept line plus that one.
571async function submitLine($: EngineInterface, key: string, line: string): Promise<void> {
572  const draft = (await read($, drafts))[key] ?? ''
573  if (line.endsWith('\\')) {
574    const kept = line.slice(0, -1)
575    await setDraft($, key, draft === '' ? kept : `${draft}\n${kept}`)
576    return
577  }
578  const full = draft === '' ? line : line === '' ? draft : `${draft}\n${line}`
579  if (await submitText($, key, full)) await setDraft($, key, '')
580}
581
582// Enter on the open question never answers on its own: an enter meant to open
583// the next question sent its recommendation (q622). It sends only a note you
584// typed and kept as a draft (with any ticks on a multi row); otherwise a digit
585// answers, `g` sends a multi pick, and the text line sends on its own enter.
586async function enterOnOpen($: EngineInterface, row: Row): Promise<void> {
587  const draft = (await read($, drafts))[row.key] ?? ''
588  if (draft !== '') {
589    if (await submitText($, row.key, draft)) await setDraft($, row.key, '')
590    return
591  }
592  if (row.choices.length === 0 && row.act !== 'run') {
593    await focusInput($, row.key)
594    return
595  }
596  $.ui.toast(`cactus ${row.key}: enter does not answer; press a digit or type a note${row.kind === 'multi' ? ', then g to send' : ''}`)
597}
598
599// The send path behind the input line.
600async function submitText($: EngineInterface, key: string, value: string): Promise<boolean> {
601  const row = (await read($, rows)).find(r => r.key === key)
602  if (row === undefined) return false
603  const typed = value.trim() === '' ? [] : [value]
604  if ((await read($, modes))[key] === 'elaborate') {
605    await setMode($, key, null)
606    await cactus($, key, ['elaborate', key, ...typed])
607    return true
608  }
609  const isMulti = row.kind === 'multi' || (await read($, flips))[key] === true
610  const mine = (await read($, picks))[key] ?? (isMulti ? (row.recommend ?? []) : [])
611  const sel = isMulti ? mine.flatMap(l => ['-s', l]) : []
612  if (sel.length === 0 && typed.length === 0) {
613    $.ui.toast(`cactus ${key}: nothing picked or typed`)
614    return false
615  }
616  await answerRow($, key, [...sel, ...typed])
617  return true
618}
619
620async function setMode($: EngineInterface, key: string, mode: 'elaborate' | null): Promise<void> {
621  await update($, modes, all => {
622    const { [key]: _gone, ...rest } = all
623    return mode === null ? rest : { ...rest, [key]: mode }
624  })
625}
626
627async function toggle(
628  $: EngineInterface,
629  key: string,
630  label: string,
631  start: readonly string[],
632): Promise<void> {
633  await update($, picks, all => {
634    const mine = all[key] ?? [...start]
635    return {
636      ...all,
637      [key]: mine.includes(label) ? mine.filter(l => l !== label) : [...mine, label],
638    }
639  })
640}
641
642async function select($: EngineInterface, key: string): Promise<void> {
643  if ((await read($, selected)) !== key) await update($, selected, () => key)
644}
645
646// Keep the open question's header in view.
647// The empty inbox: a braille sunset drawn at the pane's width. Sky dots
648// thicken toward the horizon around a half-set sun; an armed saguaro stands on
649// the left and a stand of single stalks on the right. Every cactus is lit on
650// the side facing the sun and shadowed on the other (solid outline, solid rib,
651// sparse shadow column), and casts a long ground shadow away from it.
652const ART_ROWS = 9
653const ART_MIN_COLUMNS = 20
654const GROVE_STALKS = 3
655// Dot row each stalk's top reaches: tall, middle, short (the sky is 28 dots).
656const GROVE_TOPS = [5, 12, 19]
657const HORIZON = 28
658const SKY_COLOURS = ['#4b2a6b', '#6e2f6e', '#9a3468', '#c4405e', '#e05a4f', '#f07f45', '#f9a640']
659const SUN_COLOUR = '#ffd166'
660const CACTUS_LIT = '#3f9a5c'
661const CACTUS_SHADE = '#24603a'
662const GROUND_COLOUR = '#8a5a3c'
663const SHADOW_COLOUR = '#4a2c2a'
664const BRAILLE_BITS: [number, number, number][] = [
665  [0, 0, 0x01], [0, 1, 0x02], [0, 2, 0x04], [1, 0, 0x08],
666  [1, 1, 0x10], [1, 2, 0x20], [0, 3, 0x40], [1, 3, 0x80],
667]
668const STIPPLE: Record<number, number[]> = { 1: [0], 2: [0, 2], 3: [0, 1, 2], 4: [0, 1, 2, 3] }
669
670// A cactus part: dot rectangles [x0, x1, y0, y1] inclusive, how many of every
671// 4 rows each interior column draws (absent: all 4), and its base span on the
672// ground, which casts the shadow.
673type Part = { rects: [number, number, number, number][]; cols: Record<number, number>; base: [number, number] }
674// Stipple phase counts from each part's left edge, so every stalk shades alike.
675
676// Fixed hash in [0, 1): the same art at the same width, every draw.
677function noise(x: number, y: number): number {
678  let mix = (Math.imul(x, 374761393) + Math.imul(y, 668265263)) >>> 0
679  mix = Math.imul(mix ^ (mix >>> 13), 1274126177) >>> 0
680  return ((mix ^ (mix >>> 16)) >>> 0) / 2 ** 32
681}
682
683// The armed saguaro on the left, lit from the right (the sun is east of it).
684function saguaro(): Part[] {
685  const base: [number, number] = [17, 22]
686  return [
687    { rects: [[17, 22, 5, 99], [18, 21, 4, 4]], cols: { 18: 1, 19: 4, 20: 2, 21: 4 }, base },
688    { rects: [[10, 14, 13, 23], [11, 13, 12, 12]], cols: { 11: 1, 12: 2, 13: 1 }, base },
689    { rects: [[10, 17, 21, 24]], cols: { 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1 }, base },
690    { rects: [[25, 29, 9, 19], [26, 28, 8, 8]], cols: { 26: 2, 27: 4, 28: 3 }, base },
691    { rects: [[22, 29, 17, 20]], cols: { 23: 3, 24: 3, 25: 3, 26: 3, 27: 4, 28: 3 }, base },
692  ]
693}
694
695// Three single stalks bunched on the right, past the sun: each lit on
696// the side facing it (west), shadowed on the east, heights from the hash.
697// Tallest first, so a shorter stalk in front keeps its own outline.
698function grove(dotWidth: number, sunX: number): Part[] {
699  const out: Part[] = []
700  // Even columns only: every stalk then splits into braille cells the same way.
701  // Laid right to left from the pane's edge; a stalk too close to the sun is
702  // dropped, so a narrow pane gets fewer.
703  let x = (dotWidth - 9) & ~1
704  // Three clearly different heights (tall, middle, short), dealt in an order
705  // the width picks, so the stand never reads as one height.
706  const turn = Math.floor(noise(dotWidth, 3) * GROVE_TOPS.length)
707  for (let i = 0; i < GROVE_STALKS && x >= sunX + 12; i++) {
708    const top = GROVE_TOPS[(i + turn) % GROVE_TOPS.length] ?? 12
709    const lit = x + 2 < sunX
710    const cols = lit ? { [x + 1]: 1, [x + 2]: 4, [x + 3]: 3 } : { [x + 1]: 3, [x + 2]: 4, [x + 3]: 1 }
711    out.push({ rects: [[x, x + 4, top, 99], [x + 1, x + 3, top - 1, top - 1]], cols, base: [x, x + 4] })
712    x -= 6 + 2 * Math.floor(noise(x, 7) * 2)
713  }
714  return out.sort((p, q) => (q.rects[0]?.[2] ?? 0) - (p.rects[0]?.[2] ?? 0))
715}
716
717function sunsetArt(columns: number): [string, string | undefined][][] {
718  const dotWidth = columns * 2
719  const dotHeight = ART_ROWS * 4
720  const sunX = Math.round(dotWidth * 0.52)
721  const sunR = 10
722  const parts = [...saguaro(), ...grove(dotWidth, sunX)]
723  const partAt = (x: number, y: number) =>
724    y < dotHeight ? parts.find(p => p.rects.some(([x0, x1, y0, y1]) => x >= x0 && x <= x1 && y >= y0 && y <= y1)) : undefined
725  const sides: [number, number][] = [[1, 0], [-1, 0], [0, 1], [0, -1]]
726  const cactusDot = (x: number, y: number): boolean | undefined => {
727    const p = partAt(x, y)
728    if (p === undefined) return undefined
729    // An edge against open sky or another cactus: stalks in a stand stay apart.
730    if (sides.some(([dx, dy]) => y + dy < dotHeight && partAt(x + dx, y + dy) !== p && !sameCactus(p, partAt(x + dx, y + dy)))) return true
731    return (STIPPLE[p.cols[x] ?? 4] ?? []).includes((y + x - p.base[0]) % 4)
732  }
733  // The saguaro's parts are one plant: no outline between trunk and arm.
734  const plant = new Set(parts.slice(0, 5))
735  const sameCactus = (p: Part, q: Part | undefined) => q !== undefined && plant.has(p) && plant.has(q)
736  // Long evening shadows on the ground, cast away from the sun, thinning out.
737  const shadow = (x: number, y: number) =>
738    y >= HORIZON && parts.some(({ base: [x0, x1] }) => {
739      const away = x0 > sunX ? x - x1 : x0 - x
740      const reach = 18 - (y - HORIZON)
741      return away > 0 && away <= reach
742    })
743  const sun = (x: number, y: number) => y < HORIZON && (x - sunX) ** 2 + (y - HORIZON) ** 2 <= sunR * sunR
744  const sky = (x: number, y: number) => {
745    const t = y / HORIZON
746    const glow = Math.max(0, 1 - Math.hypot(x - sunX, (y - HORIZON) * 1.8) / 22)
747    return noise(x, y) < Math.min(0.9, 0.02 + 0.6 * t ** 2.4 + 0.35 * glow)
748  }
749  const ground = (x: number, y: number) => {
750    const t = (y - HORIZON) / (dotHeight - HORIZON)
751    const reflect = Math.abs(x - sunX) < 8 - 2 * (y - HORIZON) && y % 2 === 0
752    return reflect || y === HORIZON || noise(x + 91, y) < 0.18 - 0.12 * t
753  }
754  const lines: [string, string | undefined][][] = []
755  for (let cy = 0; cy < ART_ROWS; cy++) {
756    const line: [string, string | undefined][] = []
757    for (let cx = 0; cx < columns; cx++) {
758      let cactusBits = 0, inCactus = false, sunBits = 0, skyBits = 0, groundBits = 0, shadeBits = 0
759      for (const [dx, dy, bit] of BRAILLE_BITS) {
760        const x = cx * 2 + dx, y = cy * 4 + dy
761        const c = cactusDot(x, y)
762        if (c !== undefined) {
763          inCactus = true
764          if (c) cactusBits |= bit
765        } else if (sun(x, y)) sunBits |= bit
766        else if (y < HORIZON && sky(x, y)) skyBits |= bit
767        else if (y >= HORIZON && shadow(x, y)) {
768          if ((x + y) % 2 === 0) shadeBits |= bit
769        } else if (y >= HORIZON && ground(x, y)) groundBits |= bit
770      }
771      let cell: [string, string | undefined] = [' ', undefined]
772      if (inCactus) {
773        const lit = cactusBits.toString(2).split('1').length - 1 >= 5
774        cell = [String.fromCharCode(0x2800 | cactusBits), lit ? CACTUS_LIT : CACTUS_SHADE]
775      } else if (sunBits) cell = [String.fromCharCode(0x2800 | sunBits), SUN_COLOUR]
776      else if (skyBits) cell = [String.fromCharCode(0x2800 | skyBits), SKY_COLOURS[Math.min(SKY_COLOURS.length - 1, cy)]]
777      else if (shadeBits) cell = [String.fromCharCode(0x2800 | shadeBits), SHADOW_COLOUR]
778      else if (groundBits) {
779        const nearSun = Math.abs(cx * 2 - sunX) < 8
780        cell = [String.fromCharCode(0x2800 | groundBits), nearSun ? SUN_COLOUR : GROUND_COLOUR]
781      }
782      const last = line[line.length - 1]
783      if (last !== undefined && last[1] === cell[1]) last[0] += cell[0]
784      else line.push([cell[0], cell[1]])
785    }
786    const tail = line[line.length - 1]
787    if (tail !== undefined && tail[1] === undefined) tail[0] = tail[0].trimEnd()
788    lines.push(line.filter(([text]) => text !== ''))
789  }
790  return lines
791}
792
793// One drawing per width: the art only changes when the pane is resized.
794const artCache = new Map<number, [string, string | undefined][][]>()
795function sunsetAt(columns: number): [string, string | undefined][][] {
796  const hit = artCache.get(columns)
797  if (hit !== undefined) return hit
798  const art = sunsetArt(columns)
799  artCache.set(columns, art)
800  return art
801}
802
803// cactus's own idle label: whole days from 48h up, else whole hours.
804function idleLabel(hours: number): string {
805  const whole = Math.floor(hours)
806  return whole >= 48 ? `${Math.floor(whole / 24)}d` : `${whole}h`
807}
808
809async function pinTop($: EngineInterface, key: string): Promise<void> {
810  await $.ui.scroll({ to: { key: `${key}:sel` }, block: 'nearest' }).catch(() => undefined)
811}
812
813// The TUI's j/k: move the selection one row and bring its card into view.
814async function step($: EngineInterface, by: number): Promise<void> {
815  const list = await read($, rows)
816  if (list.length === 0) return
817  const current = await read($, selected)
818  const at = Math.max(0, list.findIndex(r => r.key === current))
819  const to = list[Math.min(list.length - 1, Math.max(0, at + Math.sign(by)))]
820  if (to === undefined) return
821  await select($, to.key)
822  await $.ui.focus({ requestId: PANE, key: `${to.key}:sel` }).catch(() => undefined)
823  await pinTop($, to.key)
824}
825
826// Diff against HEAD when the file changed, else its head: the TUI's `o`.
827async function togglePreview($: EngineInterface, path: string): Promise<void> {
828  const shown = await read($, previews)
829  if (path in shown) {
830    await update($, previews, all => {
831      const { [path]: _gone, ...rest } = all
832      return rest
833    })
834    return
835  }
836  const dir = path.slice(0, path.lastIndexOf('/')) || '/'
837  const diff = await $.process.run(['git', '-C', dir, 'diff', 'HEAD', '--', path], {
838    timeoutMs: 2000,
839  }).catch(() => null)
840  const body =
841    diff !== null && diff.exitCode === 0 && diff.stdout.trim() !== ''
842      ? diff.stdout
843      : (await $.process.run(['head', '-n', String(PREVIEW_LINES), path])).stdout
844  const text = body.split('\n').slice(0, PREVIEW_LINES).join('\n')
845  await update($, previews, all => ({ ...all, [path]: text }))
846}
847
848export const register: Register = on => {
849  on('session.start', async ($, e, next) => {
850    await $.command.register({
851      name: 'cactus-pane',
852      description: "Show this project's cactus inbox in a pane",
853    })
854    const saved = await loadSettings($)
855    $.clock.every(POLL_MS, () => poll($))
856    // While a wake is held, poll each second: the countdown ticks and an undo
857    // from another surface is seen before the wake goes.
858    $.clock.every(1000, () => (pending.size > 0 ? poll($) : undefined))
859    if (e.isInteractive && saved.autoshow) await $.ui.open({ id: PANE, title: 'cactus' })
860    void poll($)
861
862    return next(e)
863  })
864
865  on('command.run', { command: 'cactus-pane' }, async $ => {
866    lastCursor = ''
867    await poll($)
868    await $.ui.open({ id: PANE, title: paneTitle(await read($, rows)), focus: true })
869    const first = (await read($, selected)) ?? (await read($, rows))[0]?.key
870    if (first !== undefined) await pinTop($, first)
871
872    return { text: 'cactus pane opened.' }
873  })
874
875  on('prompt.compose', async ($, e, next) => {
876    const composed = await next(e)
877    const text = guide(await $.session.id())
878    return {
879      ...composed,
880      sections: [...composed.sections, { id: 'cactus-pane:guide', text, scope: 'session' }],
881    }
882  })
883
884  on('tool.call', { tool: 'Bash' }, ($, e, next) => {
885    noteClears(e.command)
886    return next({ ...e, command: noWait(e.command) })
887  })
888
889  // Walking the ring onto any of a row's elements selects that row.
890  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
891    const els = $.ui.resolve(e)
892    const { Box, Text, Button } = els
893    // The pane's inner width, redrawn on resize; the sunset is drawn to fit it.
894    const width = Math.min(200, e.props.bodyColumns)
895    const Input = 'Input' in els ? els.Input : undefined
896    const list = await read($, rows)
897    const picked = await read($, picks)
898    const failed = await read($, error)
899    const shown = await read($, previews)
900    const wanted = await read($, selected)
901    const stack = await read($, undo)
902    const modeOf = await read($, modes)
903    const flipped = await read($, flips)
904    const drafted = await read($, drafts)
905    const prefs = await read($, settings)
906    const holding = await read($, held)
907    const current = list.find(r => r.key === wanted) ?? list[0]
908    if (!e.props.isFocused && ring?.endsWith(':text')) void reclaim($, ring).catch(() => undefined)
909
910    if (await read($, settingsOpen)) {
911      const next = COOLDOWNS[(COOLDOWNS.indexOf(prefs.cooldown) + 1) % COOLDOWNS.length] ?? 0
912      const said = (c: PaneSettings['cooldown']) => (c === 'idle' ? `idle (${IDLE_QUIET_MS / 1000}s quiet, agent free)` : `${c}s`)
913      return (
914        <Box flexDirection="column">
915          <Text bold>cactus pane settings</Text>
916          <Button
917            key="set:autoshow"
918            label={`autoshow at session start: ${prefs.autoshow ? 'on' : 'off'}`}
919            hotkey="1"
920            plain
921            onPress={() => void changeSettings($, s => ({ ...s, autoshow: !s.autoshow }))}
922          />
923          <Button
924            key="set:cooldown"
925            label={`wake cooldown: ${said(prefs.cooldown)} (next ${said(next)})`}
926            hotkey="2"
927            plain
928            onPress={() => void changeSettings($, s => ({ ...s, cooldown: next }))}
929          />
930          <Text dimColor>An answer waits the cooldown before it reaches the agent; u inside it takes it back.</Text>
931          <Button key="set:close" label="back" hotkey={SETTINGS_KEY} plain onPress={() => void update($, settingsOpen, () => false)} />
932        </Box>
933      )
934    }
935
936    const card = (row: Row) => {
937      // m turns a single-choice row into pick-several for this one answer.
938      const canFlip = row.kind === 'choice' && row.act !== 'data' && row.act !== 'run' && row.choices.length > 1
939      const isFlipped = canFlip && flipped[row.key] === true
940      const isMulti = row.kind === 'multi' || isFlipped
941      const isConfirm = row.kind === 'confirm'
942      const isData = row.act === 'data'
943      const isPlan = row.act === 'plan'
944      const isRunAct = row.act === 'run'
945      const isElaborate = row.status === 'elaborate'
946      const isHinting = modeOf[row.key] === 'elaborate'
947      const canRun = isRunAct || Boolean(row.review?.run_cmd)
948      const hasInput =
949        Input !== undefined && (row.allow_free || isMulti || PERSISTENT.has(row.act) || isHinting) && !isData
950      const rec = row.recommend ?? []
951      // A multi row starts with its recommended set ticked, as the TUI does.
952      const mine = picked[row.key] ?? (isMulti ? rec : [])
953      const inputLabel = isHinting ? 'hint' : isMulti ? 'note' : PERSISTENT.has(row.act) ? 'verdict' : 'answer'
954      const owner = row.agent ? ['--agent', row.agent] : []
955      const pick = (label: string, surface: typeof e.surface) => {
956        if (isData) {
957          const body = row.choices.find(c => c.label === label)?.description ?? ''
958          void $.ui.copy({ text: body, surface })
959          void answerRow($, row.key, ['-s', label])
960        } else if (isMulti) {
961          // The ring stays on the header, where enter sends.
962          void toggle($, row.key, label, rec).then(() =>
963            $.ui.focus({ requestId: PANE, key: `${row.key}:sel` }).catch(() => undefined),
964          )
965        } else if (isRunAct && label === 'approve') {
966          void runRow($, row.key, true)
967        } else {
968          void answerRow($, row.key, ['-s', label])
969        }
970      }
971      const choiceKey = (i: number) => (isConfirm && i < 2 ? (i === 0 ? 'y' : 'n') : String(i + 1))
972
973      // The keys the hidden Buttons below carry, named once in the card.
974      const legend = [
975        hasInput ? 'i type' : null,
976        row.act === 'notify' ? 'd dismiss' : 's skip',
977        canRun ? 'r run' : null,
978        isElaborate ? 'u withdraw' : `e ${isHinting ? 'cancel' : 'elaborate'} · b break up`,
979        row.act === 'review' || isPlan ? 'x close' : 'c clear',
980        canFlip ? `m ${isFlipped ? 'single' : 'multiple'}` : null,
981        isMulti ? `g send ${mine.length}` : null,
982        row.files.length > 0 ? 'f view · o preview' : null,
983        stack.length > 0 && !isElaborate ? 'u undo' : null,
984        list.length > 1 ? 'j/k move' : null,
985      ]
986        .filter(Boolean)
987        .join(' · ')
988      const body = (
989        <Box key={`${row.key}:card`} flexDirection="column" borderStyle="round" paddingX={1}>
990          <Text bold wrap="wrap">{reflow(row.text)}</Text>
991          <Text dimColor>
992            {[
993              row.thread ? `thread ${row.thread}` : null,
994              row.agent ? `agent ${row.agent.slice(0, 8)}` : null,
995              row.blocked ? 'blocking' : null,
996              row.status === 'open' ? null : row.status,
997              row.files.length > 0 ? `${row.files.length} file(s)` : null,
998            ]
999              .filter(Boolean)
1000              .join(' · ')}
1001          </Text>
1002          {row.context && (
1003            <Box marginTop={1} flexDirection="column">
1004              {reflow(row.context).split('\n\n').map((para, j) => (
1005                <Box key={String(j)} marginTop={j === 0 ? 0 : 1}>
1006                  <Text dimColor wrap="wrap">{para}</Text>
1007                </Box>
1008              ))}
1009            </Box>
1010          )}
1011          {isElaborate && (
1012            <Text color="yellow">
1013              waiting on a rewrite{row.elaborate ? `: ${firstLine(row.elaborate)}` : ''}
1014            </Text>
1015          )}
1016
1017          {row.choices.length > 0 && (
1018            <Box flexDirection="column" marginTop={1}>
1019              {row.choices.map((c, i) => {
1020                const lines = (isData ? c.description ?? '' : reflow(c.description)).split('\n')
1021                const isPicked = mine.includes(c.label)
1022                return (
1023                  <Box key={`${row.key}:c${i}`} flexDirection="column">
1024                    <Box flexDirection="row" columnGap={2}>
1025                      <Text bold={isPicked}>
1026                        <Text color="cyan">{choiceKey(i)}:</Text> {isPicked ? '✓ ' : ''}
1027                        {c.label}
1028                      </Text>
1029                      {rec.includes(c.label) && <Text color="yellow">recommended</Text>}
1030                      {row.chosen === c.label && <Text color="blue">chosen</Text>}
1031                      {!isData && lines[0] && <Text dimColor wrap="wrap">{lines[0]}</Text>}
1032                    </Box>
1033                    {isData && <Text dimColor>   {firstLine(c.description)}</Text>}
1034                    {!isData &&
1035                      lines.slice(1).map((l, j) =>
1036                        l.startsWith('+ ') ? (
1037                          <Text key={String(j)} color="green" wrap="wrap">   ✓ {l.slice(2)}</Text>
1038                        ) : l.startsWith('- ') ? (
1039                          <Text key={String(j)} color="red" wrap="wrap">   ✗ {l.slice(2)}</Text>
1040                        ) : (
1041                          <Text key={String(j)} dimColor wrap="wrap">   {l}</Text>
1042                        ),
1043                      )}
1044                  </Box>
1045                )
1046              })}
1047            </Box>
1048          )}
1049
1050          {rec.length > 0 && (
1051            <Text color="yellow">
1052              recommend {rec.join(', ')} {CONFIDENCE[row.confidence ?? ''] ?? ''} {row.confidence ?? ''}
1053              {row.recommend_why ? ` — ${row.recommend_why}` : ''}
1054            </Text>
1055          )}
1056
1057          {isPlan && row.steps.length > 0 && (
1058            <Box flexDirection="column" marginTop={1}>
1059              {row.steps.map(s => (
1060                <Text key={`step${s.n}`}>
1061                  <Text color="cyan">{s.n <= 9 ? `${s.n}:` : '  '}</Text> [{s.done ? 'x' : ' '}] {s.text}
1062                </Text>
1063              ))}
1064            </Box>
1065          )}
1066
1067          {row.review && (
1068            <Box flexDirection="column" marginTop={1}>
1069              {row.review.look_at && <Text>look at  <Text dimColor>{row.review.look_at}</Text></Text>}
1070              {row.review.run_cmd && <Text>run      <Text color="cyan">{row.review.run_cmd}</Text></Text>}
1071              {row.review.pass_when && <Text>pass     <Text color="green">{row.review.pass_when}</Text></Text>}
1072              {row.review.fail_when && <Text>fail     <Text color="red">{row.review.fail_when}</Text></Text>}
1073              {row.review.then_do && <Text>then     <Text dimColor>{row.review.then_do}</Text></Text>}
1074            </Box>
1075          )}
1076
1077          {row.result && (
1078            <Box flexDirection="column" marginTop={1}>
1079              <Text color={row.result.exit === 0 ? 'green' : 'red'}>exit {String(row.result.exit)}</Text>
1080              {row.result.tail.slice(-8).map((l, j) => (
1081                <Text key={String(j)} dimColor>{l}</Text>
1082              ))}
1083            </Box>
1084          )}
1085
1086          {row.files.length > 0 && (
1087            <Box flexDirection="column" marginTop={1}>
1088              {row.files.map((f, j) => (
1089                <Box key={`${row.key}:f${j}`} flexDirection="column">
1090                  <Box flexDirection="row" columnGap={2}>
1091                    <Text dimColor>{j === 0 ? 'f/o ' : '    '}{f}</Text>
1092                  </Box>
1093                  {f in shown && <Text dimColor>{shown[f]}</Text>}
1094                </Box>
1095              ))}
1096            </Box>
1097          )}
1098
1099          {row.answers.length > 0 && (
1100            <Box flexDirection="column" marginTop={1}>
1101              {row.answers.slice(-HISTORY).map((a, j) => (
1102                <Text key={String(j)} dimColor>→ {verdict(a)}</Text>
1103              ))}
1104            </Box>
1105          )}
1106
1107          <Box marginTop={1}>
1108            <Text dimColor wrap="wrap">{legend}</Text>
1109          </Box>
1110        </Box>
1111      )
1112      const input = hasInput ? (
1113        <Box key={`${row.key}:input`} flexDirection="column" marginTop={1}>
1114          {(drafted[row.key] ?? '') !== '' && (
1115            <Box key={`${row.key}:draft`}>
1116              <Text wrap="wrap" dimColor>{drafted[row.key]}</Text>
1117            </Box>
1118          )}
1119          {Input !== undefined && (
1120            <Input
1121              key={`${row.key}:text`}
1122              label={inputLabel}
1123              placeholder="i to type · enter sends · end a line with \ for another line"
1124              submitLabel="send"
1125              onSubmit={(value: string) => void submitLine($, row.key, value)}
1126            />
1127          )}
1128        </Box>
1129      ) : null
1130      // Probe (q555): every key Button sits in a display:none Box, so nothing
1131      // draws, and the question is whether its hotkey still presses it.
1132      const controls = (
1133        <Box key={`${row.key}:controls`} display="none" flexDirection="column">
1134          {row.choices.length > 0 && (
1135            <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
1136              {row.choices.slice(0, 9).map((c, i) => (
1137                <Button
1138                  key={`${row.key}:${c.label}`}
1139                  label={c.label.length > 14 ? `${c.label.slice(0, 13)}…` : c.label}
1140                  hotkey={choiceKey(i)}
1141                  plain
1142                  onPress={press => pick(c.label, press.surface)}
1143                />
1144              ))}
1145            </Box>
1146          )}
1147          {isPlan && row.steps.length > 0 && (
1148            <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
1149              {row.steps.filter(s => s.n <= 9).map(s => (
1150                <Button
1151                  key={`${row.key}:step${s.n}`}
1152                  label={s.done ? 'undo step' : 'step'}
1153                  hotkey={String(s.n)}
1154                  plain
1155                  onPress={() =>
1156                    void cactus($, row.key, ['plan', row.key, s.done ? '--undone' : '--done', String(s.n)])
1157                  }
1158                />
1159              ))}
1160            </Box>
1161          )}
1162          <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
1163            {hasInput && (
1164              <Button
1165                key={`${row.key}:type`}
1166                label="type"
1167                hotkey="i"
1168                plain
1169                onPress={() =>
1170                  void focusInput($, row.key)
1171                }
1172              />
1173            )}
1174            {row.act === 'notify' ? (
1175              <Button
1176                key={`${row.key}:dismiss`}
1177                label="dismiss"
1178                hotkey="d"
1179                plain
1180                onPress={() => void answerRow($, row.key, ['--dismiss'])}
1181              />
1182            ) : (
1183              <Button
1184                key={`${row.key}:skip`}
1185                label="skip"
1186                hotkey="s"
1187                plain
1188                onPress={() => void answerRow($, row.key, ['--skip'])}
1189              />
1190            )}
1191            {canRun && (
1192              <Button
1193                key={`${row.key}:run`}
1194                label="run"
1195                hotkey="r"
1196                plain
1197                onPress={() => void runRow($, row.key, isRunAct)}
1198              />
1199            )}
1200            {isElaborate ? (
types/index.d.ts 79 lines
1export type Choice = { label: string; description: string | null }
2
3export type Answer = {
4  selected: string[]
5  text: string | null
6  skipped: boolean
7  created_at: string
8  // Answered with --now: wake at once, no cooldown. Absent unless set.
9  now?: boolean
10}
11
12export type Step = { idx: number; n: number; text: string; done: boolean }
13
14export type Review = {
15  look_at: string | null
16  run_cmd: string | null
17  pass_when: string | null
18  fail_when: string | null
19  then_do: string | null
20}
21
22export type RunResult = { exit: number | null; tail: string[]; log: string | null }
23
24export type Row = {
25  key: string
26  text: string
27  act: string
28  kind: string
29  agent: string | null
30  thread: string | null
31  word: string | null
32  status: string
33  blocked: boolean
34  context: string | null
35  choices: Choice[]
36  allow_free: boolean
37  recommend: string[] | null
38  confidence: string | null
39  recommend_why: string | null
40  chosen: string | null
41  files: string[]
42  steps: Step[]
43  review: Review | null
44  result: RunResult | null
45  answers: Answer[]
46  elaborate: string | null
47  // Untouched past CACTUS_STALE_HOURS (cactus stale rows); absent on older cactus.
48  stale?: boolean
49  idle_hours?: number
50  // A review a pass closed (q601): cleared by the verdict, not by a decline.
51  closed_by_pass?: boolean
52  // A review/plan waiting on the agent after the human's verdict (q660); the feed sorts it last.
53  parked?: boolean
54}
55
56// Kept in $.store across sessions. cooldown: seconds a wake waits so undo can cancel it,
57// or 'idle': until the pane sits quiet and the agent's turn has ended.
58export type PaneSettings = { autoshow: boolean; cooldown: number | 'idle' }
59
60declare module 'claude-code' {
61  interface PluginState {
62    'cactus-pane': {
63      rows: Row[]
64      picks: Record<string, string[]>
65      error: string | null
66      selected: string | null
67      previews: Record<string, string>
68      undo: string[]
69      modes: Record<string, 'elaborate'>
70      flips: Record<string, true>
71      drafts: Record<string, string>
72      settings: PaneSettings
73      settingsOpen: boolean
74      // Seconds left per held wake; -1 once due but waiting out the agent's turn.
75      held: Record<string, number>
76    }
77  }
78}
79