SLOPSHOPPER

roer-ui

Roer's Generative UI in a Claude Code pane: /roer <what to show>

paneguardcommandtoasttoolprocess
★ 33v0.1.0Apache-2.0updated 2026-10-26JetBrains/roer/claude-plugin/roer-ui
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · roer-ui
│ ┃ Roer ✕ › fix the failing auth test and add an audit log call │ ┃ Nothing to show yet. Try /roer a form to │ ┃ file a bug ⏺ 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 │ │ › /roer │ ⎿ roer-ui: Roer pane opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Roer
Nothing to show yet. Try /roer a form to file a bug
README

roer-ui (spike)

Roer's Generative UI drawn in a Claude Code pane, beside the transcript, with no Roer app or tmux involved: /roer <what to show> opens the pane and asks Claude to draw it through this mod's own show tool, which takes the same A2UI v1.0 messages as Roer's show_ui. Presses come back to Claude as a prompt starting [roer-ui], with the action message and, under sendDataModel, the data model.

It is a Claude Code function hooks plugin: early access, off unless CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1, and the API may change between releases.

CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude --plugin-dir claude-plugin/roer-ui
# then: /roer a form to file a bug

Draws the whole of roer:catalog/1, as Roer's panel does, with what a terminal cannot do drawn another way:

  • Image, Video and AudioPlayer are named and linked rather than shown or played.
  • Icon's svgPath draws as a mark; a named icon draws as its name.
  • Modal opens beneath its trigger, in a frame, rather than over the pane.
  • DiffView draws each file's diff with its notes under it, unified only.
  • Mermaid shows the diagram's source, not the diagram, with its open threads under it, and takes no comments.
  • An obscured TextField never shows its value, only its length. The field itself cannot mask what is being typed.
  • A long TextField is one line.
  • A Chart is text: a bar per row and series, a stack per row, or a sparkline per series, in the panel's series colours, with no hover readout or table view. Its numbers are written beside the bars instead.
  • A Table's columns share the pane's width: the widest is cut first.

Beyond A2UI v1.0, and not in Roer's panel yet, the pane can work without a turn of Claude's, which is where the waiting was (hooks/local.ts):

  • A loadData message fills a data-model path from a command's output (argv, no shell) or a file, so Claude names where a diff or a list comes from instead of writing it out.
  • createSurface { hidden: true } keeps a surface without drawing it.
  • A Button's action.local opens another surface in place of its own and fills loads, off the pressed item, in the pane itself. An event beside it still reaches Claude.

Commands, and files (read as cat), run under the person's permissions, as Claude's own Bash calls do: what their rules and mode allow runs at once, what needs asking opens the permission dialog when the call lands or the button is pressed, and what they deny is refused. So a button may merge a PR, and the pane marks it "(asks first)" when it will ask, or "(not allowed)". An allowed command runs directly rather than as a Bash tool call; PreToolUse hooks see only the ones that ask. Either way its output comes whole: what the Bash tool keeps in a file for being too long for Claude is read from there.

A DiffView draws each file under a header that opens and closes it, and colours the code by the file's path. The engine refuses a drawing of more than 100000 characters of text, so the diffs on screen share about 60000: files are open while they fit, one the person opens takes the room first, and one that does not fit says so. A file longer than one Code takes (10000 characters) is drawn in pieces, cut between hunks.

The pane keeps its own state, as Roer's panel does: the tab showing, what is expanded or open, a picker's filter, and a work item's ticks and answers.

CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude plugin validate claude-plugin/roer-ui
CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude plugin test claude-plugin/roer-ui

For tsc -p claude-plugin/roer-ui, write the API's declarations first with /plugin-types claude-plugin/roer-ui/.claude/types in a session that has the flag set.

Source 6 files
hooks/register.tsx 1382 lines
1// roer-ui: Roer's Generative UI drawn in a Claude Code pane instead of Roer's
2// side panel. `/roer <what to show>` opens the pane and asks the model to
3// draw it; the model draws through this mod's own `show` tool, which takes
4// the same A2UI v1.0 messages as Roer's `show_ui`, so nothing here needs Roer
5// running. A press in the pane comes back to the model as a prompt.
6//
7// It draws the whole of `roer:catalog/1`, each component the way a terminal
8// can; a component the catalog does not have draws as a dim placeholder.
9
10import { atom, read, update } from 'claude-code'
11import type { Register, RenderChildren } from 'claude-code'
12import type { RoerUiComponent, RoerUiSurface } from '../types'
13import { EMPTY, apply, binding, children, contextOf, own, resolve, setAt, text } from './a2ui'
14import {
15  SOURCE_NAMES,
16  progressValue,
17  readChanges,
18  readComments,
19  readDecisions,
20  readDiagramThreads,
21  readFindings,
22  readNotes,
23  readRequirements,
24  readSources,
25  shownValue,
26  statusTone,
27} from './workItem'
28import type { Comment, Decision, Finding, FindingState, Note, Requirement, SourceRef, Tone } from './workItem'
29import { bashRan, fetchLoad, opened, readLoadData, readLocal, shellCommand } from './local'
30import { toNumber } from './functions'
31import type { Load, LocalAction, RunIo } from './local'
32
33const PANE = 'roer-ui'
34const TOOL = 'mcp__roer-ui__show'
35const GUIDE_TOOL = 'mcp__roer-ui__guide'
36const surfaces = atom({ plugin: 'roer-ui', key: 'surfaces' } as const, EMPTY)
37
38const CATALOG = `Components (flat list, each { id, component, ...props }; one must have id "root"). Any component takes
39weight (flex-grow inside a Row/Column).
40Layout:
41- Column / Row { children, justify?, align? } and List { children, direction? }: children is an array of ids, or a
42  template { componentId, path } repeating one component per item of a data-model list. Inside it, a path without a
43  leading / is the item's own ({ "path": "title" }); one with it, /title, reads the surface's root. { "call": "@index",
44  args?: { offset } } is the item's position
45- Grid { children, columns?, minItemWidth? } wraps; Card { child }; Divider { axis? }; Tabs { tabs: [{ title, child }] };
46  Modal { trigger, content }; Expandable { title, child, defaultExpanded? }; Arrow { direction?, label? }
47Display:
48- Text { text, variant?: "caption" | "body" }; Icon { name }; Image { url, description? }; Video { url };
49  AudioPlayer { url, description? } (media is linked, not played)
50Input:
51- Button { child (usually a Text id), action: { event: { name, context?, userMessage? } }, variant?: "primary" | "borderless" }
52- TextField { label, value?, placeholder?, variant?: "shortText" | "number" | "obscured" }, CheckBox { label, value },
53  ChoicePicker { label?, options: [{ label, value }], value: [selected values], variant?: "mutuallyExclusive" |
54  "multipleSelection", displayStyle?: "checkbox" | "chips", filterable? },
55  Slider { max, value, min?, steps?, label? }, DateTimeInput { value, enableDate?, enableTime?, min?, max?, label? }
56Roer's own:
57- Table { columns: [{ key, title, align?: "start" | "end", width?, mono? }], rows, toneKey?, emptyText?, source? }: rows
58  of records, each cell the row's field key; with toneKey a row whose field reads as failed or blocked is coloured
59- Chart { rows, x, series: [{ key, title? }], variant?: "bar" | "stackedBar" | "line", orientation?, title?, source?, emptyText? }:
60  numbers from rows on one axis, at most 8 series; x is the row field naming each point. A non-number is a gap
61- Badge { text, tone?: "neutral" | "accent" | "success" | "warning" | "danger" }; EmptyState { text, detail?,
62  variant?: "empty" | "loading" | "error", footer? }
63- StatTile { label, value, trend?: { delta, direction: "up" | "down" | "flat" }, icon?, source? }
64- StatusCard { title, subtitle?, meta?, icon?, status?, progress? (0-100), url?, footer? }
65- WorkItem { title, source?, key?, status?, url?, assignee?, labels?, meta?, footer? }; with variant: "detail" also goal,
66  requirements [{ id, text, met }], decisions [{ id, question, options: [{ label, value }], answer? }],
67  findings [{ id, severity: info|warn|error, text, at?: { changeId, path, line }, state? }], sources [{ kind, label, url?,
68  path? }], comments [{ id, author, text, at? }], changes [{ id, title, patch }]. The person's ticks, answers and settled
69  findings arrive as toggleRequirement / answerDecision / settleFinding events with the item's key as workItem.
70- Requirements / Findings / Decisions / Sources / Comments { items }: one of those sections on its own
71- DiffView { diff (a whole git diff), title?, emptyText?, notes?: [{ path, line?, text }] }
72Any string/number/boolean prop may instead be { "path": "/json/pointer" } into the surface's dataModel; bind an
73input's value that way and the person's edits write back to the data model. Or a { "call": name, "args": {...} }
74computed from it in the pane: add, subtract, multiply, divide, min, max, round, gt, lt, eq, and, or, not, if, isSet,
75isNumber, length, formatNumber, formatString ("\${/path}", "\${argName}"), pluralize; bad input gives nothing, never
76NaN. Every component takes visible: drawn only while it is true.`
77
78// The engine caps a tool's description at 4096 characters, so the catalog
79// and the pane-side rules are the guide tool's answer, read before drawing.
80const DESCRIPTION = `Show or update a UI in the Roer pane of this Claude Code session. Call ${GUIDE_TOOL} first, once
81per session: it answers the component catalog and how the pane fetches data and handles presses itself.
82\`messages\` is a list of A2UI v1.0 messages, each { "version": "v1.0", <one body> }: createSurface { surfaceId,
83components, dataModel?, sendDataModel?, hidden? }, updateComponents { surfaceId, components }, updateDataModel
84{ surfaceId, path?, value }, deleteSurface { surfaceId }, loadData { surfaceId, path, run | file, as? }.
85Usually one createSurface with everything inline, then updates to the same surfaceId.
86When the person presses a Button, its event arrives as a prompt starting "[roer-ui]" with the action as JSON
87(and the data model when sendDataModel is true).`
88
89const GUIDE = `${CATALOG}
90
91Each press that reaches you, and every value you write out, costs the person a wait. Have the pane fetch what it
92can, and handle presses that need no judgement of yours itself:
93- { "version": "v1.0", "loadData": { surfaceId, path, run: [argv] | file, as?: "text" | "json" } } fills path with
94  a command's standard output (argv, no shell, the session's working directory) or a file's text, parsed when as is
95  "json". It lands after the messages before it; a command that fails refuses the whole call. For example
96  run ["gh", "pr", "list", "--json", "number,title"], as "json", for a list's rows; ["gh", "pr", "diff", "36"] for a
97  DiffView's diff.
98- createSurface { ..., hidden: true } keeps a surface without drawing it, until a press opens it.
99- Button action { local: { open?: surfaceId, load?: [{ path, run | file | value, as?, surfaceId? }] }, event? }:
100  pressed, the pane itself draws the surface open names in place of the button's, and fills each load (into open's
101  surface unless it names one, else the button's). run's arguments, file and value may be { "path" } off the pressed
102  item, relative as in a template: ["gh", "pr", "diff", { "path": "number" }]. Nothing reaches you unless event is
103  there too. Use it for navigation (a hidden detail surface, a back button opening the list again), drill-downs, and
104  load or refresh buttons; keep event for what needs you.
105- Commands in loadData and action.local run as your own Bash calls do, under the person's permissions: what their
106  rules and mode allow runs at once, what needs asking opens the permission dialog when the call lands or the button
107  is pressed, and what they deny is refused. So a button may merge a PR or re-run a check; the pane marks one that
108  will ask. Write a command's own words out; only ids, numbers and paths may come off the data model, never text you
109  did not choose (a PR's body, a page, a file's contents). The pane refuses a bound command, and a bound argument that
110  is anything else or starts with -.
111- When a press does reach you, send only what changed (updateDataModel, updateComponents), not a new createSurface.`
112
113export const register: Register = on => {
114  on('session.start', async ($, e, next) => {
115    await $.command.register({
116      name: 'roer',
117      description: "Show Roer's Generative UI in a pane",
118      argumentHint: '<what to show>',
119    })
120    await $.tool.register({
121      name: 'show',
122      description: DESCRIPTION,
123      inputSchema: {
124        type: 'object',
125        properties: { messages: { type: 'array', items: { type: 'object' }, minItems: 1 } },
126        required: ['messages'],
127      },
128    })
129    await $.tool.register({
130      name: 'guide',
131      description: `The component catalog and pane-side rules for ${TOOL}. Read it before drawing.`,
132    })
133    return next(e)
134  })
135
136  on('command.run', { command: 'roer' }, async ($, e) => {
137    await $.ui.open({ id: PANE, title: 'Roer', focus: true })
138    const ask = e.args.trim()
139    if (ask === '') return { text: 'Roer pane opened.' }
140    // Not from here: a submit waits on the turn this hook is holding.
141    const text = `${ask}\n\n(Draw this in the Roer pane with the ${TOOL} tool, after reading ${GUIDE_TOOL} if you have not.)`
142    $.clock.after(0, () => void $.prompt.submit({ text }))
143    return { text: 'Roer pane opened; asking Claude to draw it.' }
144  })
145
146  on('tool.call', { tool: TOOL }, async ($, e) => {
147    const wire = (e as unknown as { messages?: unknown }).messages
148    if (!Array.isArray(wire) || wire.length === 0) return { deny: '`messages` needs at least one message' }
149    // A loadData stands for the updateDataModel its output becomes. Tried
150    // with a stand-in first, so a malformed call runs no command.
151    const loads = wire.map(readLoadData)
152    const bad = loads.findIndex(load => typeof load === 'string')
153    if (bad >= 0) return { deny: `Nothing was shown: message ${bad + 1}: ${loads[bad] as string}` }
154    const asUpdate = (load: Load, value: unknown) => ({ version: 'v1.0', updateDataModel: { surfaceId: load.surfaceId, path: load.path, value } })
155    const standIns = wire.map((message, n) => {
156      const load = loads[n] as Load | undefined
157      return load === undefined ? message : asUpdate(load, '')
158    })
159    let tried: typeof EMPTY | string = await read($, surfaces)
160    for (const [n, message] of standIns.entries()) {
161      tried = apply(tried, message)
162      if (typeof tried === 'string') return { deny: `Nothing was shown: message ${n + 1}: ${tried}` }
163    }
164    // The model's own call: its loads are asked about as its Bash calls are.
165    const io: RunIo = {
166      check: command => $.tool.check({ tool: 'Bash', input: { command } }),
167      run: argv => $.process.run(argv, { timeoutMs: 60_000 }),
168      bash: async command => {
169        return bashRan(await $.tool.call({ tool: 'Bash', command, description: 'Load data for the Roer pane' }))
170      },
171      read: path => $.fs.read(path),
172    }
173    const fetched = await Promise.all(
174      loads.map(load => (load === undefined || typeof load === 'string' ? undefined : fetchLoad(load, io))),
175    )
176    const failed = fetched.findIndex(got => typeof got === 'string')
177    if (failed >= 0) return { deny: `Nothing was shown: message ${failed + 1}: ${fetched[failed] as string}` }
178    const messages = wire.map((message, n) => {
179      const load = loads[n] as Load | undefined
180      const got = fetched[n] as { value: unknown } | undefined
181      return load === undefined || got === undefined ? message : asUpdate(load, got.value)
182    })
183    let problem: string | undefined
184    await update($, surfaces, before => {
185      let after = before
186      for (const [n, message] of messages.entries()) {
187        const next = apply(after, message)
188        if (typeof next === 'string') {
189          problem = `message ${n + 1}: ${next}`
190          return before
191        }
192        after = next
193      }
194      problem = undefined
195      return after
196    })
197    if (problem !== undefined) return { deny: `Nothing was shown: ${problem}` }
198    const opened = await $.ui.open({ id: PANE, title: 'Roer' })
199    const where = opened.isPlaced ? 'the Roer pane' : `the Roer pane, which is waiting to be placed (${opened.reason})`
200    return { result: `Sent ${messages.length} message(s) to ${where}.` }
201  })
202
203  on('tool.call', { tool: GUIDE_TOOL }, async () => ({ result: GUIDE }))
204
205  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
206    const el = $.ui.resolve(e)
207    const { Box, Text, Button, Link, Code } = el
208    // The mobile app draws no fields yet, whatever its table holds.
209    const Input = e.surface !== 'mobile' && 'Input' in el ? el.Input : undefined
210    const Select = e.surface !== 'mobile' && 'Select' in el ? el.Select : undefined
211    const { order, bySurface } = await read($, surfaces)
212    if (order.length === 0) {
213      return (
214        <Box>
215          <Text dimColor>Nothing to show yet. Try /roer a form to file a bug</Text>
216        </Box>
217      )
218    }
219    const columns = Math.max(10, (e.props as { bodyColumns?: number }).bodyColumns ?? 60)
220    /** A Chart in text: a bar per row and series, a stack per row, or a
221     * sparkline per series, with a legend from two series as in the panel. */
222    const chart = (c: RoerUiComponent, value: (v: unknown) => unknown, str: (prop: string) => string, room: number): RenderChildren => {
223      const rows = records(value(c.rows))
224      const x = typeof c.x === 'string' ? c.x : ''
225      const series = (Array.isArray(c.series) ? c.series : []).filter(isColumn).slice(0, 8)
226      const name = (s: TableColumnWire) => {
227        const t = value(s.title)
228        return typeof t === 'string' && t !== '' ? t : s.key
229      }
230      const values = rows.map(row => series.map(s => toNumber(row[s.key])))
231      const title = str('title')
232      const source = str('source')
233      const head = title !== '' && <Text bold>{title}</Text>
234      const foot = source !== '' && <Text dimColor>{source}</Text>
235      if (rows.length === 0 || series.length === 0 || values.every(vs => vs.every(v => v === undefined))) {
236        return (
237          <Box flexDirection="column">
238            {head}
239            <Text dimColor>{c.emptyText === undefined ? 'Nothing to chart.' : str('emptyText')}</Text>
240            {foot}
241          </Box>
242        )
243      }
244      const legend = series.length > 1 && (
245        <Text>
246          {series.map((s, j) => <Text color={SERIES[j]}>{`■ ${name(s)}  `}</Text>)}
247        </Text>
248      )
249      const labels = rows.map(row => cell(row[x]))
250      const labelWidth = Math.min(16, Math.max(...labels.map(l => l.length)))
251      const variant = c.variant === 'line' || c.variant === 'stackedBar' ? c.variant : 'bar'
252
253      if (variant === 'line') {
254        const flat = values.flat().filter((v): v is number => v !== undefined)
255        const lo = Math.min(...flat)
256        const hi = Math.max(...flat)
257        return (
258          <Box flexDirection="column">
259            {head}
260            {series.map((s, j) => {
261              const ys = values.map(vs => vs[j])
262              const spark = ys
263                .map(v => (v === undefined ? ' ' : SPARKS[hi === lo ? 3 : Math.round(((v - lo) / (hi - lo)) * 7)]))
264                .join('')
265              const last = [...ys].reverse().find(v => v !== undefined)
266              return (
267                <Text>
268                  <Text color={SERIES[j]}>{spark}</Text>
269                  {` ${last === undefined ? '' : valueFormat.format(last)} ${series.length > 1 ? name(s) : ''}`}
270                </Text>
271              )
272            })}
273            <Text dimColor>{`${labels[0] ?? ''} … ${labels[labels.length - 1] ?? ''}`}</Text>
274            {foot}
275          </Box>
276        )
277      }
278
279      const stacked = variant === 'stackedBar'
280      const totals = values.map(vs => vs.reduce<number>((sum, v) => sum + Math.max(0, v ?? 0), 0))
281      const top = Math.max(1e-9, stacked ? Math.max(...totals) : Math.max(0, ...values.flat().map(v => v ?? 0)))
282      const width = Math.max(10, Math.min(50, room - labelWidth - 12))
283      const cells = (v: number) => Math.round((Math.max(0, v) / top) * width)
284      return (
285        <Box flexDirection="column">
286          {head}
287          {rows.map((_, i) => {
288            const label = fit(labels[i] ?? '', labelWidth, false)
289            const vs = values[i] ?? []
290            if (stacked) {
291              return (
292                <Text>
293                  {`${label} `}
294                  {vs.map((v, j) => <Text color={SERIES[j]}>{'█'.repeat(cells(v ?? 0))}</Text>)}
295                  {` ${valueFormat.format(totals[i] ?? 0)}`}
296                </Text>
297              )
298            }
299            return (
300              <Box flexDirection="column">
301                {vs.map((v, j) => (
302                  <Text>
303                    {`${j === 0 ? label : ' '.repeat(labelWidth)} `}
304                    <Text color={SERIES[j]}>{v === undefined ? '' : '█'.repeat(cells(v)) || '▏'}</Text>
305                    {` ${v === undefined ? '–' : valueFormat.format(v)}`}
306                  </Text>
307                ))}
308              </Box>
309            )
310          })}
311          {legend}
312          {foot}
313        </Box>
314      )
315    }
316    // The permission decision for each command a drawn button would run.
317    // A drawing names the ones it did not know; they are asked, then drawn
318    // again.
319    const verdicts = new Map<string, 'allow' | 'ask' | 'deny'>()
320    const unchecked = new Set<string>()
321
322    // Closures rather than helpers: the engine wants `$` spelled at each call
323    // site, never handed to a function of the module's own.
324    const change = (surfaceId: string, edit: (surface: RoerUiSurface) => RoerUiSurface) =>
325      update($, surfaces, all => {
326        const surface = own(all.bySurface, surfaceId)
327        if (surface === undefined) return all
328        return { ...all, bySurface: { ...all.bySurface, [surfaceId]: edit(surface) } }
329      })
330    const writeModel = (surfaceId: string, pointer: string | undefined, value: unknown) =>
331      pointer === undefined
332        ? undefined
333        : change(surfaceId, surface => ({ ...surface, dataModel: setAt(surface.dataModel, pointer, value) }))
334    // The pane's own state, never the data model's: nothing the agent sent
335    // says which tab is showing, and a press must not report it.
336    const setView = (surfaceId: string, at: string, value: unknown) =>
337      change(surfaceId, surface => ({ ...surface, view: { ...surface.view, [at]: value } }))
338
339    // Something the person did, handed to the model as v1.0's
340    // renderer-to-agent `action` message, the way Roer's panel reports it,
341    // but as a prompt.
342    const send = async (
343      surfaceId: string,
344      sourceComponentId: string,
345      name: string,
346      context: Record<string, unknown>,
347      said: string,
348      userMessage?: string,
349    ) => {
350      // Read afresh: the drawing's copy predates whatever was typed since.
351      const surface = own((await read($, surfaces)).bySurface, surfaceId)
352      if (surface === undefined) return
353      const message = {
354        version: 'v1.0',
355        action: {
356          name,
357          surfaceId,
358          sourceComponentId,
359          timestamp: new Date().toISOString(),
360          context,
361          ...(userMessage ? { userMessage } : {}),
362        },
363      }
364      const lines = [`[roer-ui] ${userMessage || said}`, JSON.stringify(message)]
365      if (surface.sendDataModel) lines.push(`dataModel: ${JSON.stringify(surface.dataModel)}`)
366      await $.prompt.submit({ text: lines.join('\n') })
367    }
368
369    // What a press does in the pane itself: open a surface in place of the
370    // pressed one at once, then fill each load. Each surface being filled
371    // says so while it is; a later press on it wins over this one.
372    const runLocal = async (from: string, local: LocalAction, label: string) => {
373      const token = `${Date.now()}.${Math.random()}`
374      const fetching = local.loads.filter(load => !('value' in load))
375      const filling = [...new Set(fetching.map(load => load.surfaceId))]
376      const into = (all: typeof EMPTY, load: Load, value: unknown) => {
377        const surface = own(all.bySurface, load.surfaceId)
378        if (surface === undefined) return all
379        return { ...all, bySurface: { ...all.bySurface, [load.surfaceId]: { ...surface, dataModel: setAt(surface.dataModel, load.path, value) } } }
380      }
381      const marked = (all: typeof EMPTY, surfaceId: string, loading: unknown) => {
382        const surface = own(all.bySurface, surfaceId)
383        if (surface === undefined) return all
384        return { ...all, bySurface: { ...all.bySurface, [surfaceId]: { ...surface, view: { ...surface.view, loading } } } }
385      }
386      await update($, surfaces, all => {
387        let next = local.open === undefined ? all : opened(all, from, local.open)
388        for (const load of local.loads) {
389          // What is being fetched is cleared, never shown under the wrong title.
390          next = into(next, load, 'value' in load ? load.value : null)
391        }
392        for (const surfaceId of filling) next = marked(next, surfaceId, { token })
393        return next
394      })
395      if (fetching.length === 0) return
396      // The person's press is theirs to vouch for, not the command: the
397      // dialog, or the auto-mode classifier, weighs one against the other.
398      const io: RunIo = {
399        check: command => $.tool.check({ tool: 'Bash', input: { command } }),
400        run: argv => $.process.run(argv, { timeoutMs: 60_000 }),
401        bash: async command => {
402          return bashRan(
403            await $.tool.call({
404              tool: 'Bash',
405              command,
406              description: `"${label}" in the Roer pane`,
407              consent: `The user pressed "${label}" in the Roer pane.`,
408            }),
409          )
410        },
411        read: path => $.fs.read(path),
412      }
413      const got = await Promise.all(fetching.map(load => fetchLoad(load, io)))
414      await update($, surfaces, all => {
415        let next = all
416        const mine = (surfaceId: string) => {
417          const loading = own(own(next.bySurface, surfaceId)?.view ?? {}, 'loading') as { token?: string } | undefined
418          return loading?.token === token
419        }
420        const current = filling.filter(mine)
421        for (const [n, load] of fetching.entries()) {
422          const one = got[n]
423          if (current.includes(load.surfaceId) && typeof one === 'object') next = into(next, load, one.value)
424        }
425        for (const surfaceId of current) {
426          const problems = fetching.flatMap((load, n) => (load.surfaceId === surfaceId && typeof got[n] === 'string' ? [got[n] as string] : []))
427          next = marked(next, surfaceId, problems.length > 0 ? { failed: problems.join('; ') } : undefined)
428        }
429        return next
430      })
431    }
432
433    const press = async (surfaceId: string, c: RoerUiComponent, label: string, scope: string) => {
434      const event = (c.action as { event?: { name?: unknown; context?: unknown; userMessage?: unknown } } | undefined)?.event
435      const hasEvent = event !== undefined && typeof event.name === 'string'
436      const surface = own((await read($, surfaces)).bySurface, surfaceId)
437      if (surface === undefined) return
438      const model = surface.dataModel
439      const local = readLocal(c.action, model, scope, surfaceId)
440      if (typeof local === 'string') {
441        $.ui.toast(`roer-ui: "${label}": ${local}`)
442        return
443      }
444      if (local === undefined && !hasEvent) {
445        $.ui.toast(`roer-ui: "${label}" has no event to send`)
446        return
447      }
448      if (local !== undefined) await runLocal(surfaceId, local, label)
449      if (!hasEvent) return
450      const said = `The person pressed "${label}" in the ${surfaceId} UI.`
451      await send(surfaceId, c.id, event.name as string, contextOf(event.context, model, scope), said, text(event.userMessage, model, scope))
452    }
453
454    // `ancestors` are the components on the way down to this one. The graph
455    // is the model's, so it can loop back on itself; a loop draws as a
456    // placeholder the moment it closes, as in Roer's GenerativeSurface. A
457    // depth limit alone would first draw exponentially many nodes.
458    const draw = (surfaceId: string, surface: RoerUiSurface, id: string, scope: string, ancestors: ReadonlySet<string>): RenderChildren => {
459      if (ancestors.has(id)) return <Text dimColor>{`(cycle at ${id})`}</Text>
460      const c = own(surface.components, id)
461      if (c === undefined) return <Text dimColor>{`(missing ${id})`}</Text>
462      const model = surface.dataModel
463      // Roer's `visible`: drawn only while it resolves to true.
464      if (c.visible !== undefined && resolve(c.visible, model, scope) !== true) return null
465      const key = `${surfaceId}.${id}${scope}`
466      const at = `${id}${scope}`
467      const view = (name: string) => own(surface.view ?? {}, `${name}:${at}`)
468      const below = new Set(ancestors).add(id)
469      // A child with a `weight` grows inside its Row or Column, as flex-grow
470      // does in Roer's panel.
471      const weighed = (child: string, node: RenderChildren) => {
472        const weight = own(surface.components, child)?.weight
473        return typeof weight === 'number' ? <Box flexGrow={weight} flexDirection="column">{node}</Box> : node
474      }
475      const kids = (list: unknown) =>
476        children(list, model, scope).map(([child, childScope]) => weighed(child, draw(surfaceId, surface, child, childScope, below)))
477      const one = (child: unknown) => (typeof child === 'string' ? draw(surfaceId, surface, child, scope, below) : null)
478      const value = (v: unknown) => resolve(v, model, scope)
479      const str = (prop: string) => text(c[prop], model, scope)
480      const write = (pointer: string | undefined, next: unknown) => writeModel(surfaceId, pointer, next)
481      const link = (url: string, label: string) =>
482        url.startsWith('https://') ? <Link href={url} label={label} /> : <Text>{label}</Text>
483
484      switch (c.component) {
485        case 'Column':
486          return (
487            <Box flexDirection="column" justifyContent={justify(c.justify)} alignItems={align(c.align)}>
488              {kids(c.children)}
489            </Box>
490          )
491        case 'Row':
492          return (
493            <Box flexDirection="row" gap={1} justifyContent={justify(c.justify)} alignItems={align(c.align)}>
494              {kids(c.children)}
495            </Box>
496          )
497        case 'List': {
498          const isRow = c.direction === 'horizontal'
499          return (
500            <Box flexDirection={isRow ? 'row' : 'column'} gap={isRow ? 1 : 0} alignItems={align(c.align)}>
501              {kids(c.children)}
502            </Box>
503          )
504        }
505        case 'Grid': {
506          // The one layout that wraps. `columns` wins over `minItemWidth`, as
507          // in Roer's panel; a pixel width becomes cells at 8 pixels each.
508          const count = typeof c.columns === 'number' && c.columns >= 1 ? Math.floor(c.columns) : undefined
509          const minWidth = typeof c.minItemWidth === 'number' ? Math.max(8, Math.ceil(c.minItemWidth / 8)) : 24
510          return (
511            <Box flexDirection="row" flexWrap="wrap" rowGap={1}>
512              {kids(c.children).map(node => (
513                <Box
514                  flexDirection="column"
515                  paddingRight={1}
516                  width={count === undefined ? undefined : `${Math.floor(100 / count)}%`}
517                  minWidth={count === undefined ? minWidth : undefined}
518                >
519                  {node}
520                </Box>
521              ))}
522            </Box>
523          )
524        }
525        case 'Card':
526          return (
527            <Box borderStyle="round" borderDimColor flexDirection="column" paddingX={1}>
528              {one(c.child)}
529            </Box>
530          )
531        case 'Tabs': {
532          // A row of buttons, one per tab, and only the chosen tab's child.
533          const tabs = Array.isArray(c.tabs) ? (c.tabs as { title?: unknown; child?: unknown }[]) : []
534          if (tabs.length === 0) return null
535          const chosen = view('tab')
536          const shown = Math.min(Math.max(0, typeof chosen === 'number' ? chosen : 0), tabs.length - 1)
537          return (
538            <Box flexDirection="column" gap={1}>
539              <Box flexDirection="row" gap={2}>
540                {tabs.map((tab, n) => {
541                  const title = text(tab.title, model, scope) || `Tab ${n + 1}`
542                  return (
543                    <Button
544                      key={`${key}.tab${n}`}
545                      plain
546                      label={n === shown ? `[${title}]` : title}
547                      dimColor={n === shown ? undefined : true}
548                      onPress={() => void setView(surfaceId, `tab:${at}`, n)}
549                    />
550                  )
551                })}
552              </Box>
553              {one(tabs[shown]?.child)}
554            </Box>
555          )
556        }
557        case 'Modal': {
558          // No layer to float it on: the trigger, a button that opens and
559          // closes it, and the content in a frame beneath while open.
560          const open = view('open') === true
561          return (
562            <Box flexDirection="column">
563              <Box flexDirection="row" gap={1}>
564                {one(c.trigger)}
565                <Button key={`${key}.open`} plain dimColor label={open ? '▾ close' : '▸ open'} onPress={() => void setView(surfaceId, `open:${at}`, !open)} />
566              </Box>
567              {open && (
568                <Box borderStyle="double" flexDirection="column" paddingX={1}>
569                  {one(c.content)}
570                </Box>
571              )}
572            </Box>
573          )
574        }
575        case 'Expandable': {
576          const set = view('expanded')
577          const open = typeof set === 'boolean' ? set : c.defaultExpanded === true
578          return (
579            <Box flexDirection="column">
580              <Button key={`${key}.toggle`} plain label={`${open ? '▾' : '▸'} ${str('title')}`} onPress={() => void setView(surfaceId, `expanded:${at}`, !open)} />
581              {open && (
582                <Box flexDirection="column" paddingLeft={2}>
583                  {one(c.child)}
584                </Box>
585              )}
586            </Box>
587          )
588        }
589        case 'Divider':
590          return c.axis === 'vertical' ? (
591            <Text dimColor>│</Text>
592          ) : (
593            <Text dimColor wrap="truncate-end">{'─'.repeat(columns)}</Text>
594          )
595        case 'Arrow': {
596          const label = str('label')
597          if (c.direction === 'vertical') {
598            return (
599              <Box flexDirection="column" alignItems="center">
600                <Text dimColor>│</Text>
601                {label !== '' && <Text dimColor>{label}</Text>}
602                <Text dimColor>▼</Text>
603              </Box>
604            )
605          }
606          return <Text dimColor>{label === '' ? '──▶' : `── ${label} ──▶`}</Text>
607        }
608        case 'Text':
609          return <Text dimColor={c.variant === 'caption'}>{str('text')}</Text>
610        case 'Icon':
611          return <Text>{iconText(c.name, model, scope)}</Text>
612        case 'Image': {
613          // A terminal cannot fetch and draw a picture from a link: the pane
614          // names it and links to it.
615          const description = str('description')
616          return link(str('url'), `[image${description ? `: ${description}` : ''}]`)
617        }
618        case 'Video':
619          return link(str('url'), '▶ video')
620        case 'AudioPlayer': {
621          const description = str('description')
622          return link(str('url'), `♪ ${description || 'audio'}`)
623        }
624        case 'Button': {
625          const label = (typeof c.child === 'string' ? labelOf(own(surface.components, c.child), model, scope) : '') || id
626          // What the person's permissions say of the commands a press would
627          // run: marked when one would ask, or would be refused.
628          const local = readLocal(c.action, model, scope, surfaceId)
629          const commands = typeof local === 'object' ? local.loads.flatMap(load => ('run' in load ? [shellCommand(load.run)] : [])) : []
630          const decisions = commands.map(command => {
631            const decided = verdicts.get(command)
632            if (decided === undefined) unchecked.add(command)
633            return decided
634          })
635          const mark = decisions.includes('deny') ? ' (not allowed)' : decisions.includes('ask') ? ' (asks first)' : ''
636          return (
637            <Button
638              key={key}
639              label={`${label}${mark}`}
640              variant={c.variant === 'primary' ? 'primary' : undefined}
641              dimColor={c.variant === 'borderless' || decisions.includes('deny') ? true : undefined}
642              onPress={() => void press(surfaceId, c, label, scope)}
643            />
644          )
645        }
646        case 'TextField': {
647          const pointer = binding(c.value, scope)
648          const shown = str('value')
649          // No masked field in a terminal: an obscured one never shows its
650          // value, only how long it is.
651          const obscured = c.variant === 'obscured'
652          const asTyped = (typed: string) =>
653            c.variant === 'number' && typed.trim() !== '' && Number.isFinite(Number(typed)) ? Number(typed) : typed
654          if (Input === undefined) return <Text>{`${str('label')}: ${obscured ? '•'.repeat(shown.length) : shown}`}</Text>
655          return (
656            <Input
657              key={key}
658              label={`${str('label')} `}
659              placeholder={obscured ? '•'.repeat(shown.length) || undefined : str('placeholder') || undefined}
660              value={obscured ? undefined : shown}
661              onInput={typed => write(pointer, asTyped(typed))}
662              onSubmit={typed => write(pointer, asTyped(typed))}
663            />
664          )
665        }
666        case 'CheckBox': {
667          const isOn = value(c.value) === true
668          return (
669            <Button
670              key={key}
671              plain
672              label={`${isOn ? '[x]' : '[ ]'} ${str('label')}`}
673              onPress={() => write(binding(c.value, scope), !isOn)}
674            />
675          )
676        }
677        case 'ChoicePicker': {
678          const options = (Array.isArray(c.options) ? c.options : []) as { label?: unknown; value?: unknown }[]
679          const picked = value(c.value)
680          const chosen = Array.isArray(picked) ? picked.map(String) : []
681          const pointer = binding(c.value, scope)
682          const multiple = c.variant === 'multipleSelection'
683          const filter = c.filterable === true ? String(view('filter') ?? '') : ''
684          const shown = options.filter(option => text(option.label, model, scope).toLowerCase().includes(filter.toLowerCase()))
685          // As in Roer's panel: a single choice pressed again is cleared.
686          const toggle = (v: string) =>
687            write(pointer, multiple ? (chosen.includes(v) ? chosen.filter(x => x !== v) : [...chosen, v]) : chosen.includes(v) ? [] : [v])
688          const filterBox =
689            c.filterable === true && Input !== undefined ? (
690              <Input key={`${key}.filter`} label="Filter " value={filter} onInput={typed => void setView(surfaceId, `filter:${at}`, typed)} onSubmit={typed => void setView(surfaceId, `filter:${at}`, typed)} />
691            ) : null
692          if (!multiple && c.displayStyle !== 'chips' && c.filterable !== true && Select !== undefined) {
693            return (
694              <Select
695                key={key}
696                label={c.label === undefined ? undefined : `${str('label')} `}
697                options={options.map(option => ({ value: String(option.value), label: text(option.label, model, scope) }))}
698                value={chosen[0]}
699                onSelect={picked => write(pointer, [picked])}
700              />
701            )
702          }
703          const mark = (isOn: boolean) => (multiple ? (isOn ? '[x]' : '[ ]') : isOn ? '(•)' : '( )')
704          const buttons = shown.map(option => {
705            const v = String(option.value)
706            const isOn = chosen.includes(v)
707            const label = text(option.label, model, scope)
708            return (
709              <Button
710                key={`${key}.${v}`}
711                plain
712                label={c.displayStyle === 'chips' ? (isOn ? `[${label}]` : ` ${label} `) : `${mark(isOn)} ${label}`}
713                dimColor={c.displayStyle === 'chips' && !isOn ? true : undefined}
714                onPress={() => toggle(v)}
715              />
716            )
717          })
718          return (
719            <Box flexDirection="column">
720              {c.label !== undefined && <Text>{str('label')}</Text>}
721              {filterBox}
722              {c.displayStyle === 'chips' ? <Box flexDirection="row" flexWrap="wrap" columnGap={1}>{buttons}</Box> : buttons}
723            </Box>
724          )
725        }
726        case 'Slider': {
727          const min = typeof c.min === 'number' ? c.min : 0
728          const max = typeof c.max === 'number' && c.max > min ? c.max : min + 100
729          const raw = Number(value(c.value) ?? min)
730          const current = Number.isFinite(raw) ? Math.min(max, Math.max(min, raw)) : min
731          const step = typeof c.steps === 'number' && c.steps > 0 ? (max - min) / c.steps : (max - min) / 10
732          const pointer = binding(c.value, scope)
733          const to = (next: number) => write(pointer, Number(Math.min(max, Math.max(min, next)).toFixed(6)))
734          const width = 20
735          const filled = Math.round(((current - min) / (max - min)) * width)
736          return (
737            <Box flexDirection="row" gap={1}>
738              {c.label !== undefined && <Text>{str('label')}</Text>}
739              <Button key={`${key}.less`} plain label="◀" onPress={() => to(current - step)} />
740              <Text>{`${'━'.repeat(filled)}${'─'.repeat(width - filled)}`}</Text>
741              <Button key={`${key}.more`} plain label="▶" onPress={() => to(current + step)} />
742              <Text key={`${key}.value`}>{String(current)}</Text>
743            </Box>
744          )
745        }
746        case 'DateTimeInput': {
747          // Both flags default to off in v1.0; with neither set, offer both,
748          // as Roer's panel does. Typed as text, in the format the value keeps.
749          const date = c.enableDate === true
750          const time = c.enableTime === true
751          const format = date && !time ? 'YYYY-MM-DD' : time && !date ? 'HH:MM' : 'YYYY-MM-DDTHH:MM'
752          const pointer = binding(c.value, scope)
753          const range = [str('min'), str('max')].some(Boolean) ? ` (${str('min') || '…'} to ${str('max') || '…'})` : ''
754          if (Input === undefined) return <Text>{`${str('label')}: ${str('value') || format}`}</Text>
755          return (
756            <Input
757              key={key}
758              label={`${str('label') || 'When'}${range} `}
759              placeholder={format}
760              value={str('value')}
761              onInput={typed => write(pointer, typed)}
762              onSubmit={typed => write(pointer, typed)}
763            />
764          )
765        }
766        case 'DiffView': {
767          const patch = str('diff')
768          const title = str('title')
769          return (
770            <Box flexDirection="column">
771              {title !== '' && <Text bold>{title}</Text>}
772              {patch.trim() === ''
773                ? <Text dimColor>{c.emptyText === undefined ? 'No changes.' : str('emptyText')}</Text>
774                : diffWithNotes(surfaceId, at, patch, readNotes(value(c.notes)))}
775            </Box>
776          )
777        }
778        case 'Mermaid': {
779          // A terminal cannot lay a graph out: the pane shows the source,
780          // which is what the diagram is anyway, and the open threads under it.
781          const source = str('source')
782          const title = str('title')
783          const open = readDiagramThreads(value(c.notes)).filter(t => t.state === 'open')
784          return (
785            <Box flexDirection="column">
786              {title !== '' && <Text bold>{title}</Text>}
787              {source.trim() === ''
788                ? <Text dimColor>No diagram.</Text>
789                : <Code source={source.slice(0, CODE_LIMIT)} />}
790              {open.map(t => (
791                <Box flexDirection="column">
792                  <Text>{`💬 ${t.node} · ${t.author || 'Agent'}: ${t.text}`}</Text>
793                  {t.replies.map(reply => <Text dimColor>{`   ${reply.author}: ${reply.text}`}</Text>)}
794                </Box>
795              ))}
796            </Box>
797          )
798        }
799        case 'Badge': {
800          const tone = str('tone')
801          const color = BADGE_COLORS[tone as keyof typeof BADGE_COLORS]
802          return <Text color={color} dimColor={color === undefined ? true : undefined}>{`[${str('text')}]`}</Text>
803        }
804        case 'EmptyState': {
805          const variant = c.variant === 'loading' || c.variant === 'error' ? c.variant : 'empty'
806          const detail = str('detail')
807          return (
808            <Box flexDirection="column">
809              {variant === 'error'
810                ? <Text color="red">{`✗ ${str('text')}`}</Text>
811                : <Text dimColor>{`${variant === 'loading' ? '… ' : ''}${str('text')}`}</Text>}
812              {detail !== '' && <Text dimColor>{detail}</Text>}
813              {one(c.footer)}
814            </Box>
815          )
816        }
817        case 'Table': {
818          const rows = records(value(c.rows))
819          const cols = (Array.isArray(c.columns) ? c.columns : []).filter(isColumn)
820          const title = (col: TableColumnWire) => text(col.title, model, scope)
821          const widths = tableWidths(cols.map(col => [title(col), ...rows.map(row => cell(row[col.key]))]), cols, columns)
822          const line = (cells: string[]) =>
823            cells.map((v, i) => fit(v, widths[i] ?? 0, cols[i]?.align === 'end')).join(' ')
824          const toneKey = typeof c.toneKey === 'string' ? c.toneKey : undefined
825          const source = str('source')
826          return (
827            <Box flexDirection="column">
828              <Text dimColor>{line(cols.map(title))}</Text>
829              {rows.length === 0
830                ? <Text dimColor>{c.emptyText === undefined ? 'Nothing to show.' : str('emptyText')}</Text>
831                : rows.map(row => (
832                    <Text color={toneKey === undefined ? undefined : toneColor(statusTone(cell(row[toneKey])))}>
833                      {line(cols.map(col => cell(row[col.key])))}
834                    </Text>
835                  ))}
836              {source !== '' && <Text dimColor>{source}</Text>}
837            </Box>
838          )
839        }
840        case 'Chart':
841          return chart(c, value, str, columns)
842        case 'StatTile': {
843          const trend = typeof c.trend === 'object' && c.trend !== null ? (c.trend as { delta?: unknown; direction?: unknown }) : undefined
844          const up = trend?.direction === 'up'
845          const down = trend?.direction === 'down'
846          return (
847            <Box borderStyle="round" borderDimColor flexDirection="row" gap={1} paddingX={1}>
848              {c.icon !== undefined && <Text>{iconText(c.icon, model, scope)}</Text>}
849              <Box flexDirection="column" flexGrow={1}>
850                <Text bold>{str('value')}</Text>
851                <Text dimColor>{str('label')}</Text>
852                {str('source') !== '' && <Text dimColor>{str('source')}</Text>}
853              </Box>
854              {trend && (
855                <Text color={up ? 'green' : down ? 'red' : undefined} dimColor={!up && !down ? true : undefined}>
856                  {`${up ? '▲' : down ? '▼' : '•'} ${text(trend.delta, model, scope)}`}
857                </Text>
858              )}
859            </Box>
860          )
861        }
862        case 'StatusCard': {
863          const status = str('status')
864          const progress = c.progress === undefined ? undefined : progressValue(value(c.progress))
865          return (
866            <Box borderStyle="round" borderDimColor flexDirection="column" paddingX={1}>
867              <Box flexDirection="row" gap={1}>
868                {c.icon !== undefined && <Text>{iconText(c.icon, model, scope)}</Text>}
869                <Box flexGrow={1}>{link(str('url'), str('title'))}</Box>
870                {status !== '' && <Text color={toneColor(statusTone(status))}>{status}</Text>}
871              </Box>
872              {c.subtitle !== undefined && <Text dimColor>{str('subtitle')}</Text>}
873              {progress !== undefined && <Text key={`${key}.progress`}>{bar(progress)}</Text>}
874              {c.meta !== undefined && <Text dimColor>{str('meta')}</Text>}
875              {one(c.footer)}
876            </Box>
877          )
878        }
879        case 'WorkItem': {
880          const status = str('status')
881          const source = str('source')
882          const itemKey = str('key')
883          const assignee = str('assignee')
884          const labels = value(c.labels)
885          const tags = Array.isArray(labels) ? labels.map(String) : []
886          const origin = [SOURCE_NAMES[source.toLowerCase()] ?? source, itemKey].filter(Boolean).join(' ')
887          return (
888            <Box borderStyle="round" borderDimColor flexDirection="column" paddingX={1}>
889              <Box flexDirection="row" gap={1}>
890                {origin !== '' && <Text dimColor>{origin}</Text>}
891                <Box flexGrow={1}>{link(str('url'), str('title'))}</Box>
892                {status !== '' && <Text color={toneColor(statusTone(status))}>{status}</Text>}
893              </Box>
894              {(assignee !== '' || tags.length > 0) && (
895                <Box flexDirection="row" gap={1} flexWrap="wrap">
896                  {assignee !== '' && <Text>{`@${assignee}`}</Text>}
897                  {tags.map(tag => <Text dimColor>{`[${tag}]`}</Text>)}
898                </Box>
899              )}
900              {c.meta !== undefined && <Text dimColor>{str('meta')}</Text>}
901              {one(c.footer)}
902              {c.variant === 'detail' && detail(surfaceId, surface, c, scope, itemKey)}
903            </Box>
904          )
905        }
906        case 'Requirements':
907          return requirements(surfaceId, surface, c, scope, readRequirements(value(c.items)), undefined)
908        case 'Findings':
909          return findings(surfaceId, surface, c, scope, readFindings(value(c.items)), undefined)
910        case 'Decisions':
911          return decisions(surfaceId, surface, c, scope, readDecisions(value(c.items)), undefined)
912        case 'Sources':
913          return section('Sources', undefined, sources(readSources(value(c.items))))
914        case 'Comments':
915          return section('Comments', undefined, comments(readComments(value(c.items))))
916        default:
917          return <Text dimColor>{`[${c.component}: not in roer:catalog/1]`}</Text>
918      }
919    }
920
921    // A work item opened up, in the order Roer's panel draws it: its goal,
922    // what needs the person, the requirements, where it came from, the
923    // discussion, and what changed.
924    const detail = (surfaceId: string, surface: RoerUiSurface, c: RoerUiComponent, scope: string, itemKey: string) => {
925      const value = (v: unknown) => resolve(v, surface.dataModel, scope)
926      const goal = text(c.goal, surface.dataModel, scope)
927      // The agent's lists, and what is shown: the person's values over them.
928      // A second change compares against the agent's, never the first change.
929      const rawFound = readFindings(value(c.findings))
930      const rawAsked = readDecisions(value(c.decisions))
931      const found = localized(surface, c, scope, 'state', rawFound)
932      const asked = localized(surface, c, scope, 'answer', rawAsked)
933      const reqs = readRequirements(value(c.requirements))
934      const srcs = readSources(value(c.sources))
935      const talk = readComments(value(c.comments))
936      const changes = readChanges(value(c.changes))
937      const waiting = asked.filter(d => d.answer === undefined).length + found.filter(f => f.state === 'open').length
938      return (
939        <Box flexDirection="column" gap={1} marginTop={1}>
940          {goal !== '' && <Text>{goal}</Text>}
941          {asked.length + found.length > 0 &&
942            section('Needs you', waiting > 0 ? String(waiting) : 'nothing open', [
943              decisionRows(surfaceId, c, scope, asked, itemKey, rawAsked),
944              findingRows(surfaceId, c, scope, found, itemKey, rawFound),
945            ])}
946          {reqs.length > 0 && requirements(surfaceId, surface, c, scope, reqs, itemKey)}
947          {srcs.length > 0 && section('Sources', undefined, sources(srcs))}
948          {talk.length > 0 && section('Comments', undefined, comments(talk))}
949          {changes.length > 0 &&
950            section(
951              'Changes',
952              undefined,
953              changes.map(one => {
954                const at = `change:${c.id}${scope}:${one.id}`
955                const set = own(surface.view ?? {}, at)
956                const open = typeof set === 'boolean' ? set : changes.length === 1
957                // An open finding about a line of this change is drawn there too.
958                const notes = [
959                  ...(one.notes ?? []),
960                  ...found
961                    .filter(f => f.state === 'open' && f.at?.changeId === one.id)
962                    .map(f => ({ path: f.at!.path, line: f.at!.line, text: `${f.severity}: ${f.text}` })),
963                ]
964                return (
965                  <Box flexDirection="column">
966                    <Button key={`${surfaceId}.${c.id}${scope}.change.${one.id}`} plain label={`${open ? '▾' : '▸'} ${one.title}`} onPress={() => void setView(surfaceId, at, !open)} />
967                    {open && <Box paddingLeft={2} flexDirection="column">{diffWithNotes(surfaceId, at, one.patch, notes)}</Box>}
968                  </Box>
969                )
970              }),
971            )}
972        </Box>
973      )
974    }
975
976    // The person's own values over the agent's, as long as the agent's value
977    // is still the one they replaced. See `shownValue`.
978    const localized = <T extends { id: string }, K extends keyof T>(surface: RoerUiSurface, c: RoerUiComponent, scope: string, field: K, items: T[]): T[] =>
979      items.map(item => ({ ...item, [field]: shownValue(own(surface.view ?? {}, `local:${c.id}${scope}:${String(field)}:${item.id}`), item[field]) }))
980    const answer = (surfaceId: string, c: RoerUiComponent, scope: string, field: string, id: string, base: unknown, next: unknown) =>
981      setView(surfaceId, `local:${c.id}${scope}:${field}:${id}`, { base: base ?? null, value: next })
982    // As a button's event would: the item's key rides along as `workItem`
983    // when the section is part of one.
984    const report = (surfaceId: string, c: RoerUiComponent, name: string, context: Record<string, unknown>, itemKey: string | undefined) =>
985      send(surfaceId, c.id, name, itemKey === undefined ? context : { workItem: itemKey, ...context }, `The person did ${name} in the ${surfaceId} UI.`)
986
987    const section = (title: string, aside: string | undefined, body: RenderChildren) => (
988      <Box flexDirection="column">
989        <Text bold>{aside === undefined ? title : `${title} · ${aside}`}</Text>
990        {body}
991      </Box>
992    )
993
994    const requirements = (surfaceId: string, surface: RoerUiSurface, c: RoerUiComponent, scope: string, raw: Requirement[], itemKey: string | undefined) => {
995      const items = localized(surface, c, scope, 'met', raw)
996      const met = items.filter(r => r.met).length
997      return section(
998        'Requirements',
999        `${met} of ${items.length}`,
1000        items.map((r, n) => (
1001          <Button
1002            key={`${surfaceId}.${c.id}${scope}.req.${r.id}`}
1003            plain
1004            label={`${r.met ? '[x]' : '[ ]'} ${r.text}`}
1005            dimColor={r.met ? true : undefined}
1006            onPress={() => {
1007              void answer(surfaceId, c, scope, 'met', r.id, raw[n]?.met, !r.met)
1008              void report(surfaceId, c, 'toggleRequirement', { id: r.id, met: !r.met }, itemKey)
1009            }}
1010          />
1011        )),
1012      )
1013    }
1014
1015    const findings = (surfaceId: string, surface: RoerUiSurface, c: RoerUiComponent, scope: string, raw: Finding[], itemKey: string | undefined) =>
1016      section('Findings', undefined, findingRows(surfaceId, c, scope, localized(surface, c, scope, 'state', raw), itemKey, raw))
1017
1018    // Open ones first: they are what the section is for.
1019    const findingRows = (surfaceId: string, c: RoerUiComponent, scope: string, items: Finding[], itemKey: string | undefined, raw: Finding[]) => {
1020      const sorted = [...items.filter(f => f.state === 'open'), ...items.filter(f => f.state !== 'open')]
1021      const base = (id: string) => raw.find(f => f.id === id)?.state
1022      const settle = (f: Finding, state: FindingState) => {
1023        void answer(surfaceId, c, scope, 'state', f.id, base(f.id) ?? f.state, state)
1024        void report(surfaceId, c, 'settleFinding', { id: f.id, state }, itemKey)
1025      }
1026      return sorted.map(f => {
1027        const keyOf = `${surfaceId}.${c.id}${scope}.finding.${f.id}`
1028        return (
1029          <Box flexDirection="column">
1030            <Box flexDirection="row" gap={1}>
1031              <Text color={f.severity === 'error' ? 'red' : f.severity === 'warn' ? 'yellow' : 'cyan'} dimColor={f.state === 'open' ? undefined : true}>
1032                {f.severity}
1033              </Text>
1034              <Text dimColor={f.state === 'open' ? undefined : true}>{f.text}</Text>
1035              {f.at && <Text dimColor>{`${f.at.path}:${f.at.line}`}</Text>}
1036            </Box>
1037            <Box flexDirection="row" gap={2} paddingLeft={2}>
1038              {f.state === 'open' ? (
1039                [
1040                  <Button key={`${keyOf}.resolve`} plain label="Resolve" onPress={() => settle(f, 'resolved')} />,
1041                  <Button key={`${keyOf}.dismiss`} plain dimColor label="Dismiss" onPress={() => settle(f, 'dismissed')} />,
1042                ]
1043              ) : (
1044                [<Text dimColor>{f.state}</Text>, <Button key={`${keyOf}.reopen`} plain dimColor label="Reopen" onPress={() => settle(f, 'open')} />]
1045              )}
1046            </Box>
1047          </Box>
1048        )
1049      })
1050    }
1051
1052    const decisions = (surfaceId: string, surface: RoerUiSurface, c: RoerUiComponent, scope: string, raw: Decision[], itemKey: string | undefined) =>
1053      section('Decisions', undefined, decisionRows(surfaceId, c, scope, localized(surface, c, scope, 'answer', raw), itemKey, raw))
1054
1055    // An option pressed is the answer, as is anything written under Other.
1056    // An answered one shows what it was, with Change to answer again.
1057    const decisionRows = (surfaceId: string, c: RoerUiComponent, scope: string, items: Decision[], itemKey: string | undefined, raw: Decision[]) =>
1058      items.map(d => {
1059        const keyOf = `${surfaceId}.${c.id}${scope}.decision.${d.id}`
1060        const editing = own(own(bySurface, surfaceId)?.view ?? {}, `editing:${c.id}${scope}:${d.id}`) === true
1061        const base = raw.find(x => x.id === d.id)?.answer
1062        const decide = (value: string) => {
1063          if (value.trim() === '') return
1064          void answer(surfaceId, c, scope, 'answer', d.id, base, value.trim())
1065          void setView(surfaceId, `editing:${c.id}${scope}:${d.id}`, false)
1066          void report(surfaceId, c, 'answerDecision', { id: d.id, answer: value.trim() }, itemKey)
1067        }
1068        if (d.answer !== undefined && d.answer !== null && !editing) {
1069          const label = d.options.find(o => o.value === d.answer)?.label ?? d.answer
1070          return (
1071            <Box flexDirection="column">
1072              <Text>{d.question}</Text>
1073              <Box flexDirection="row" gap={2} paddingLeft={2}>
1074                <Text dimColor>{`Answered: ${label}`}</Text>
1075                <Button key={`${keyOf}.change`} plain dimColor label="Change" onPress={() => void setView(surfaceId, `editing:${c.id}${scope}:${d.id}`, true)} />
1076              </Box>
1077            </Box>
1078          )
1079        }
1080        return (
1081          <Box flexDirection="column">
1082            <Text>{d.question}</Text>
1083            <Box flexDirection="column" paddingLeft={2}>
1084              {d.options.map(o => (
1085                <Button key={`${keyOf}.${o.value}`} plain label={`${d.answer === o.value ? '(•)' : '( )'} ${o.label}`} onPress={() => decide(o.value)} />
1086              ))}
1087              {Input !== undefined && <Input key={`${keyOf}.other`} label="Other " placeholder="your own answer" onSubmit={typed => decide(typed)} />}
1088            </Box>
1089          </Box>
1090        )
1091      })
1092
1093    const sources = (items: SourceRef[]) =>
1094      items.map(s => {
1095        // A path is the project's, with no file viewer here to open it in:
1096        // it is named. Only https leaves for the browser.
1097        const label = `${s.kind}  ${s.label}`
1098        return s.url?.startsWith('https://') ? (
1099          <Link href={s.url} label={label} />
1100        ) : (
1101          <Text>{s.path ? `${label}  ${s.path}` : label}</Text>
1102        )
1103      })
1104
1105    const comments = (items: Comment[]) =>
1106      items.map(one => (
1107        <Box flexDirection="column">
1108          <Box flexDirection="row" gap={1}>
1109            <Text bold>{one.author}</Text>
1110            {one.at !== undefined && <Text dimColor>{one.at}</Text>}
1111          </Box>
1112          <Text>{one.text}</Text>
1113        </Box>
1114      ))
1115
1116    // The engine refuses a drawing of more than 100000 characters of text,
1117    // so the diffs on screen share a budget under that, leaving the rest
1118    // room. Each drawing starts it over.
1119    let diffRoom = DIFF_BUDGET
1120
1121    // A whole `git diff`, one file at a time under a header that opens and
1122    // closes it, each file's notes under it: by line where they name one,
1123    // first where they do not. The files the person opened take the budget
1124    // first, then the rest are open while they fit; an open one that does
1125    // not fit says so.
1126    const diffWithNotes = (surfaceId: string, at: string, patch: string, notes: Note[]) => {
1127      const files = splitPatch(patch).map(file => {
1128        const where = `file:${at}:${file.path}`
1129        const set = own(own(bySurface, surfaceId)?.view ?? {}, where)
1130        return { ...file, where, set: typeof set === 'boolean' ? set : undefined, drawn: false }
1131      })
1132      for (const asked of [true, undefined])
1133        for (const file of files)
1134          if (file.set === asked && file.text.length <= diffRoom) {
1135            file.drawn = true
1136            diffRoom -= file.text.length
1137          }
1138      return files.map(file => {
1139        const mine = notes.filter(note => note.path === file.path)
1140        const where = file.where
1141        const open = file.set ?? file.drawn
1142        const fits = file.drawn
1143        const { added, removed } = counts(file.text)
1144        return (
1145          <Box flexDirection="column">
1146            <Button key={`${surfaceId}.${at}.file.${file.path}`} plain label={`${open ? '▾' : '▸'} ${file.path}  +${added} −${removed}`} onPress={() => void setView(surfaceId, where, !open)} />
1147            {open &&
1148              (fits ? (
1149                diffPieces(file.text).map(text => <Code source={text} format="diff" path={file.path} />)
1150              ) : (
1151                <Text dimColor>{'  Too long to draw with the other open files: close one to see this one.'}</Text>
1152              ))}
1153            {mine
1154              .sort((a, b) => (a.line ?? 0) - (b.line ?? 0))
1155              .map(note => (
1156                <Text color="yellow">{`  ${note.line === undefined ? file.path : `${file.path}:${note.line}${note.side === 'old' ? ' (old)' : ''}`}  ${note.text}`}</Text>
1157              ))}
1158          </Box>
1159        )
1160      })
1161    }
1162
1163    const drawing = () => {
1164      diffRoom = DIFF_BUDGET
1165      return (
1166      <Box flexDirection="column" gap={1}>
1167        {order.flatMap(surfaceId => {
1168          const surface = own(bySurface, surfaceId) as RoerUiSurface
1169          if (surface.hidden === true) return []
1170          const loading = own(surface.view ?? {}, 'loading') as { token?: string; failed?: string } | undefined
1171          return [
1172            <Box flexDirection="column">
1173              {loading?.token !== undefined && <Text key={`${surfaceId}.loading`} dimColor>Loading…</Text>}
1174              {loading?.failed !== undefined && <Text key={`${surfaceId}.failed`} color="red">{loading.failed}</Text>}
1175              {draw(surfaceId, surface, 'root', '', new Set())}
1176            </Box>,
1177          ]
1178        })}
1179      </Box>
1180      )
1181    }
1182    const first = drawing()
1183    if (unchecked.size === 0) return first
1184    const asked = await Promise.all([...unchecked].map(command => $.tool.check({ tool: 'Bash', input: { command } })))
1185    for (const [n, command] of [...unchecked].entries()) verdicts.set(command, asked[n]?.decision ?? 'ask')
1186    return drawing()
1187  })
1188}
1189
1190function justify(value: unknown) {
1191  switch (value) {
1192    case 'center':
1193      return 'center'
1194    case 'end':
1195      return 'flex-end'
1196    case 'spaceBetween':
1197      return 'space-between'
1198    case 'spaceAround':
1199      return 'space-around'
1200    case 'spaceEvenly':
hooks/a2ui.ts 216 lines
1// The A2UI v1.0 reducer and data binding, cut down from Roer's own
2// (src/generative-ui/apply.ts, evaluate.ts) to what the pane draws. Pure:
3// every function takes the surfaces and gives back new ones.
4
5import type { RoerUiComponent, RoerUiSurface, RoerUiSurfaces } from '../types'
6import { callFunction } from './functions'
7
8export const EMPTY: RoerUiSurfaces = { order: [], bySurface: {} }
9
10type Message = Record<string, unknown>
11
12const isRecord = (v: unknown): v is Record<string, unknown> =>
13  typeof v === 'object' && v !== null && !Array.isArray(v)
14
15const KINDS = ['createSurface', 'updateComponents', 'updateDataModel', 'deleteSurface']
16
17/** Applies one message, or says why it was refused. The checks are
18 * isA2uiMessage's (src/generative-ui/schema.ts): a malformed message is
19 * refused whole, never shown in part. */
20export function apply(surfaces: RoerUiSurfaces, message: unknown): RoerUiSurfaces | string {
21  if (!isRecord(message)) return 'a message is not an object'
22  if (message.version !== 'v1.0') return `version is ${JSON.stringify(message.version)}, not "v1.0"`
23  const kinds = Object.keys(message).filter(key => key !== 'version')
24  if (kinds.length !== 1) return `a message carries exactly one of ${KINDS.join(', ')}, not ${kinds.length}`
25  const kind = kinds[0] as string
26  const body = (message as Message)[kind]
27  if (!KINDS.includes(kind)) return `the message has none of ${KINDS.join(', ')} (it has ${kind})`
28  if (!isRecord(body)) return `${kind} is not an object`
29  const { surfaceId } = body
30  if (typeof surfaceId !== 'string' || surfaceId === '') return `${kind} needs a surfaceId`
31
32  if (kind === 'createSurface') {
33    const { components, dataModel, sendDataModel, hidden } = body
34    if (components !== undefined && !isComponentList(components)) return badComponents(kind)
35    if (dataModel !== undefined && !isRecord(dataModel)) return 'createSurface.dataModel is not an object'
36    const surface: RoerUiSurface = {
37      components: indexed(components ?? []),
38      dataModel: dataModel ?? {},
39      sendDataModel: sendDataModel === true,
40      // Roer-only (see local.ts): kept, not drawn, until a press opens it.
41      ...(hidden === true ? { hidden: true } : {}),
42    }
43    return {
44      order: [...surfaces.order.filter(id => id !== surfaceId), surfaceId],
45      bySurface: { ...surfaces.bySurface, [surfaceId]: surface },
46    }
47  }
48  if (kind === 'deleteSurface') {
49    const { [surfaceId]: _gone, ...bySurface } = surfaces.bySurface
50    return { order: surfaces.order.filter(id => id !== surfaceId), bySurface }
51  }
52
53  const surface = own(surfaces.bySurface, surfaceId)
54  if (!surface) return `${kind} names no surface on screen (${surfaceId})`
55  if (kind === 'updateComponents') {
56    if (!isComponentList(body.components)) return badComponents(kind)
57    return put(surfaces, surfaceId, {
58      ...surface,
59      components: { ...surface.components, ...indexed(body.components) },
60    })
61  }
62  // updateDataModel. `value` is required even when it is null, the deletion
63  // sentinel: a message without one is malformed, not a delete.
64  if (!('value' in body)) return 'updateDataModel needs a value (null deletes)'
65  const { path, value } = body
66  if (path !== undefined && typeof path !== 'string') return 'updateDataModel.path is not a string'
67  return put(surfaces, surfaceId, { ...surface, dataModel: setAt(surface.dataModel, path ?? '', value) })
68}
69
70const badComponents = (kind: string) => `${kind}.components is not a list of { id, component } entries`
71
72function isComponentList(list: unknown): list is RoerUiComponent[] {
73  return (
74    Array.isArray(list) &&
75    list.every(one => isRecord(one) && typeof one.id === 'string' && typeof one.component === 'string')
76  )
77}
78
79function put(surfaces: RoerUiSurfaces, id: string, surface: RoerUiSurface): RoerUiSurfaces {
80  return { ...surfaces, bySurface: { ...surfaces.bySurface, [id]: surface } }
81}
82
83/** Components by id. From entries, so every wire id is data: assigning
84 * `out['__proto__']` would set the index's prototype instead of an entry. */
85const indexed = (list: RoerUiComponent[]): Record<string, RoerUiComponent> =>
86  Object.fromEntries(list.map(one => [one.id, one]))
87
88/** `record[key]` when it is the record's own, never something inherited: a
89 * wire id like `__proto__` or `toString` names nothing unless it was sent. */
90export const own = <T>(record: Record<string, T>, key: string): T | undefined =>
91  Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined
92
93/** A pointer made absolute: relative ones (no leading `/`) hang off `scope`,
94 * the current template item. */
95export function absolute(scope: string, path: string): string {
96  if (path.startsWith('/')) return path
97  return path === '' ? scope : `${scope}/${path}`
98}
99
100/** Keys that would reach an object's prototype rather than its own data. */
101const FORBIDDEN = new Set(['__proto__', 'constructor', 'prototype'])
102
103/** A pointer's unescaped segments. The leading `/` is optional: a relative
104 * pointer (`title`) names the same member as `/title`. */
105const tokens = (pointer: string): string[] =>
106  pointer === ''
107    ? []
108    : (pointer.startsWith('/') ? pointer.slice(1) : pointer).split('/').map(t => t.replace(/~1/g, '/').replace(/~0/g, '~'))
109
110export function getAt(model: unknown, pointer: string): unknown {
111  let at = model
112  for (const token of tokens(pointer)) {
113    if (FORBIDDEN.has(token) || typeof at !== 'object' || at === null) return undefined
114    if (!Object.prototype.hasOwnProperty.call(at, token)) return undefined
115    at = (at as Record<string, unknown>)[token]
116  }
117  return at
118}
119
120/** Writes `value` at `pointer`, copying on the way down; `null` (or
121 * `undefined`) deletes, as updateDataModel defines it. As writePointer in
122 * src/generative-ui/schema.ts. */
123export function setAt(model: Record<string, unknown>, pointer: string, value: unknown): Record<string, unknown> {
124  const path = tokens(pointer)
125  if (path.length === 0) return isRecord(value) ? value : {}
126  if (path.some(token => FORBIDDEN.has(token))) return model
127  return writeAt(model, path, value) as Record<string, unknown>
128}
129
130function writeAt(at: unknown, [head, ...rest]: string[], value: unknown): unknown {
131  const token = head as string
132  const remove = value === null || value === undefined
133  if (Array.isArray(at)) {
134    const index = token === '-' ? at.length : Number(token)
135    if (!Number.isInteger(index) || index < 0) return at
136    // Deleting through a parent that isn't there leaves the model alone.
137    if (rest.length > 0 && remove && index >= at.length) return at
138    const copy = [...at]
139    if (rest.length > 0) copy[index] = writeAt(copy[index], rest, value)
140    else if (remove) copy.splice(index, 1)
141    else copy[index] = value
142    return copy
143  }
144  const base = isRecord(at) ? at : {}
145  if (rest.length > 0) {
146    if (remove && !Object.prototype.hasOwnProperty.call(base, token)) return at
147    return { ...base, [token]: writeAt(base[token], rest, value) }
148  }
149  if (remove) {
150    const { [token]: _gone, ...kept } = base
151    return kept
152  }
153  return { ...base, [token]: value }
154}
155
156/** A dynamic value: a literal, `{ path }` read from the data model, or a
157 * `{ call }`, as in Roer's evaluate.ts. `@index` is the template item's
158 * 0-based position, plus `args.offset`, and nothing outside a template; any
159 * other call is one of the catalog's functions (functions.ts, Roer's own
160 * copy), and a name it does not have resolves to nothing. */
161export function resolve(value: unknown, model: unknown, scope: string): unknown {
162  if (isRecord(value) && typeof value.path === 'string') return getAt(model, absolute(scope, value.path))
163  if (isRecord(value) && typeof value.call === 'string') {
164    if (value.call !== '@index') {
165      return callFunction(value.call, value.args, {
166        value: arg => resolve(arg, model, scope),
167        read: pointer => getAt(model, absolute(scope, pointer)),
168      })
169    }
170    const index = indexIn(scope)
171    if (index === undefined) return undefined
172    const args = isRecord(value.args) ? value.args : {}
173    const offset = Number(resolve(args.offset, model, scope) ?? 0)
174    return index + (Number.isFinite(offset) ? offset : 0)
175  }
176  return value
177}
178
179/** The position of the template item `scope` points at: its last segment,
180 * when that is an array index. */
181function indexIn(scope: string): number | undefined {
182  const last = scope.slice(scope.lastIndexOf('/') + 1)
183  return scope !== '' && /^\d+$/.test(last) ? Number(last) : undefined
184}
185
186/** An action's context with each value resolved. From entries, as Roer's
187 * panel builds it: assigning a `__proto__` key would set the object's
188 * prototype and drop that value from the action. */
189export const contextOf = (context: unknown, model: unknown, scope: string): Record<string, unknown> =>
190  isRecord(context)
191    ? Object.fromEntries(Object.entries(context).map(([name, value]) => [name, resolve(value, model, scope)]))
192    : {}
193
194export const text = (value: unknown, model: unknown, scope: string): string => {
195  const v = resolve(value, model, scope)
196  return v === undefined || v === null ? '' : typeof v === 'string' ? v : JSON.stringify(v)
197}
198
199/** The bound pointer behind an input's value, when it is bound. */
200export function binding(value: unknown, scope: string): string | undefined {
201  return isRecord(value) && typeof value.path === 'string' ? absolute(scope, value.path) : undefined
202}
203
204/** A ChildList as (component id, scope) pairs: fixed ids share the scope,
205 * a template repeats one component over each item of a bound list. */
206export function children(list: unknown, model: unknown, scope: string): [string, string][] {
207  if (Array.isArray(list)) return list.filter((id): id is string => typeof id === 'string').map(id => [id, scope])
208  if (isRecord(list) && typeof list.componentId === 'string' && typeof list.path === 'string') {
209    const at = absolute(scope, list.path)
210    const items = getAt(model, at)
211    const keys = Array.isArray(items) ? items.map((_, i) => String(i)) : isRecord(items) ? Object.keys(items) : []
212    return keys.map(key => [list.componentId as string, `${at}/${key}`])
213  }
214  return []
215}
216
hooks/workItem.ts 178 lines
1// What a work item's detail view is made of, and how each piece is read off
2// the wire: Roer's own readers (src/generative-ui/workItem.ts), and the
3// status and progress rules its cards use (GenerativeSurface.tsx). Every
4// reader keeps what is shaped right and drops the rest, one element at a
5// time: a typo in one finding costs that finding, not the whole view.
6
7export type Requirement = { id: string; text: string; met: boolean }
8export type SourceRef = { kind: 'ticket' | 'slack' | 'doc' | 'file'; label: string; url?: string; path?: string }
9export type Note = { path: string; text: string; line?: number; side?: 'old' }
10export type ChangeRef = { id: string; title: string; patch: string; notes?: Note[] }
11export type FindingState = 'open' | 'resolved' | 'dismissed'
12export type Finding = {
13  id: string
14  severity: 'info' | 'warn' | 'error'
15  text: string
16  at?: { changeId: string; path: string; line: number; side?: 'old' }
17  state: FindingState
18}
19export type DiagramThread = { id: string; node: string; author: string; text: string; replies: { author: string; text: string }[]; state: 'open' | 'resolved' }
20export type Comment = { id: string; author: string; text: string; at?: string }
21export type Decision = { id: string; question: string; options: { label: string; value: string }[]; answer?: string }
22
23type Wire = Record<string, unknown>
24
25const isWire = (v: unknown): v is Wire => typeof v === 'object' && v !== null && !Array.isArray(v)
26const str = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined)
27const each = <T>(v: unknown, read: (w: Wire) => T | undefined): T[] =>
28  Array.isArray(v) ? v.flatMap(w => (isWire(w) ? (read(w) ?? []) : [])) : []
29
30export const readRequirements = (v: unknown): Requirement[] =>
31  each(v, w => {
32    const id = str(w.id)
33    const text = str(w.text)
34    return id && text ? { id, text, met: w.met === true } : undefined
35  })
36
37const SOURCE_KINDS = ['ticket', 'slack', 'doc', 'file'] as const
38
39export const readSources = (v: unknown): SourceRef[] =>
40  each(v, w => {
41    const label = str(w.label)
42    if (!label) return undefined
43    const kind = SOURCE_KINDS.find(k => k === w.kind) ?? (str(w.path) ? 'file' : 'doc')
44    const url = str(w.url)
45    const path = str(w.path)
46    return { kind, label, ...(url ? { url } : {}), ...(path ? { path } : {}) }
47  })
48
49export const readComments = (v: unknown): Comment[] =>
50  each(v, w => {
51    const id = str(w.id)
52    const author = str(w.author)
53    const text = str(w.text)
54    if (!id || !author || !text) return undefined
55    const at = str(w.at)
56    return { id, author, text, ...(at ? { at } : {}) }
57  })
58
59export const readDiagramThreads = (v: unknown): DiagramThread[] =>
60  each(v, w => {
61    const id = str(w.id)
62    const node = str(w.node)
63    const text = str(w.text)
64    if (!id || !node || !text) return undefined
65    const replies = each(w.replies, r => {
66      const author = str(r.author)
67      const said = str(r.text)
68      return author !== undefined && said !== undefined ? { author, text: said } : undefined
69    })
70    return { id, node, author: str(w.author) ?? '', text, replies, state: w.state === 'resolved' ? 'resolved' : 'open' }
71  })
72
73export const readNotes = (v: unknown): Note[] =>
74  each(v, w => {
75    const path = str(w.path)
76    const text = str(w.text)
77    if (!path || !text) return undefined
78    return {
79      path,
80      text,
81      ...(typeof w.line === 'number' ? { line: w.line } : {}),
82      ...(w.side === 'old' ? { side: 'old' as const } : {}),
83    }
84  })
85
86export const readChanges = (v: unknown): ChangeRef[] =>
87  each(v, w => {
88    const id = str(w.id)
89    const patch = str(w.patch)
90    if (!id || patch === undefined) return undefined
91    const notes = readNotes(w.notes)
92    return { id, title: str(w.title) ?? id, patch, ...(notes.length > 0 ? { notes } : {}) }
93  })
94
95const SEVERITIES = ['info', 'warn', 'error'] as const
96const FINDING_STATES = ['open', 'resolved', 'dismissed'] as const
97
98export const readFindings = (v: unknown): Finding[] =>
99  each(v, w => {
100    const id = str(w.id)
101    const text = str(w.text)
102    if (!id || !text) return undefined
103    const at = isWire(w.at) ? w.at : undefined
104    const changeId = str(at?.changeId)
105    const path = str(at?.path)
106    const line = at?.line
107    return {
108      id,
109      text,
110      severity: SEVERITIES.find(s => s === w.severity) ?? 'info',
111      state: FINDING_STATES.find(s => s === w.state) ?? 'open',
112      ...(changeId && path && typeof line === 'number'
113        ? { at: { changeId, path, line, ...(at?.side === 'old' ? { side: 'old' as const } : {}) } }
114        : {}),
115    }
116  })
117
118export const readDecisions = (v: unknown): Decision[] =>
119  each(v, w => {
120    const id = str(w.id)
121    const question = str(w.question)
122    if (!id || !question) return undefined
123    const options = each(w.options, o => {
124      const value = str(o.value)
125      return value === undefined ? undefined : { value, label: str(o.label) ?? value }
126    })
127    const answer = str(w.answer)
128    return { id, question, options, ...(answer ? { answer } : {}) }
129  })
130
131/** How each tracker is named on an item; anything else is shown as sent. */
132export const SOURCE_NAMES: Record<string, string> = {
133  github: 'GitHub',
134  youtrack: 'YouTrack',
135  notion: 'Notion',
136  jira: 'Jira',
137  personal: 'Personal',
138}
139
140export type Tone = 'done' | 'doing' | 'blocked' | 'failed' | 'todo'
141
142/** A status, by what it means for the work rather than what a tracker calls
143 * it: every tracker spells "finished" its own way. */
144export function statusTone(status: string): Tone {
145  const s = status.toLowerCase().replace(/[\s_-]+/g, ' ').trim()
146  if (
147    ['done', 'closed', 'fixed', 'resolved', 'completed', 'merged', 'verified', 'success', 'succeeded', 'passed', 'deployed'].includes(s)
148  )
149    return 'done'
150  if (['doing', 'in progress', 'in review', 'active', 'started', 'review', 'working', 'running'].includes(s)) return 'doing'
151  if (['blocked', 'on hold', 'waiting'].includes(s)) return 'blocked'
152  if (['failed', 'failure', 'error', 'errored', 'broken'].includes(s)) return 'failed'
153  return 'todo'
154}
155
156/** Only a number or a numeric string counts as progress; anything else,
157 * `false`, `null` and `" "` included, draws no bar at all. */
158export function progressValue(raw: unknown): number | undefined {
159  const n = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : NaN
160  return Number.isFinite(n) ? Math.min(100, Math.max(0, n)) : undefined
161}
162
163/** A value the person set in the pane, shown only while the agent's value is
164 * still the one it replaced: the agent resending the old item does not undo
165 * the person's click, and the agent sending anything else wins. As
166 * `useLocal` in Roer's WorkItemDetail. */
167export type Local = { base: unknown; value: unknown }
168
169export function shownValue<T>(local: unknown, current: T): T {
170  if (typeof local !== 'object' || local === null || !('value' in local)) return current
171  const { base, value } = local as Local
172  return same(base, current) ? (value as T) : current
173}
174
175/** Plugin state keeps no `undefined`, so a missing value is stored as `null`
176 * and the two compare equal. */
177const same = (a: unknown, b: unknown) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null)
178
hooks/local.ts 215 lines
1// What the pane does on its own, with no turn of the model's: Roer-only
2// additions to A2UI v1.0, none of them in Roer's panel yet.
3//
4// - A `loadData` message fills a data-model path from a command's output or
5//   a file, so the model names where data comes from instead of writing it.
6// - A Button's `action.local` loads data and opens another surface when it is
7//   pressed; `action.event`, beside it or not, still reaches the model.
8// - A surface created with `hidden: true` is kept but not drawn until a
9//   press opens it.
10//
11// Every command runs as the model's own Bash calls do, under the person's
12// permissions: what their rules and mode allow runs at once, what needs asking
13// opens the permission dialog, what they deny is refused (`runPermitted`).
14//
15// Pure but for `runPermitted` and `fetchLoad`, which reach the host through
16// closures register.tsx makes over `$`.
17
18import type { RoerUiSurfaces } from '../types'
19import { absolute, own, resolve } from './a2ui'
20
21/** Where a load's value comes from: a command's standard output (argv; a
22 * file is `cat` of it, so the same permissions decide), or, in a press, a
23 * value off the pressed item. */
24export type LoadSource = { run: string[] } | { value: unknown }
25
26export type Load = LoadSource & { surfaceId: string; path: string; as: 'text' | 'json' }
27
28export type LocalAction = { loads: Load[]; open?: string }
29
30const isRecord = (v: unknown): v is Record<string, unknown> =>
31  typeof v === 'object' && v !== null && !Array.isArray(v)
32
33/** Why a wire value did not resolve to what a load needs: what it came to,
34 * and for a binding, the pointer it read. Inside a template a pointer with
35 * a leading `/` reads the surface's root, not the item: said when that is
36 * the likely slip. */
37function unlike(wire: unknown, got: unknown, scope: string, wanted: string): string {
38  const came = got === undefined ? 'nothing' : got === null ? 'null' : Array.isArray(got) ? 'a list' : `a ${typeof got}`
39  const path = isRecord(wire) && typeof wire.path === 'string' ? wire.path : undefined
40  if (path === undefined) return `is ${came}, not ${wanted}`
41  const slip = scope !== '' && path.startsWith('/') ? `; inside a template, "${path.slice(1)}" is the item's own` : ''
42  return `{ "path": ${JSON.stringify(path)} } found ${came} at ${absolute(scope, path)}, not ${wanted}${slip}`
43}
44
45/** An id, a number or a path, as a bound argument must be: nothing a shell
46 * or a command would read as more, and no leading `-` to be an option. */
47const isToken = (v: unknown): boolean =>
48  (typeof v === 'number' && Number.isFinite(v)) || (typeof v === 'string' && /^[\w@%+=:,./~#-]+$/.test(v) && !v.startsWith('-'))
49
50/** A load off the wire, each dynamic value resolved against `model` at
51 * `scope`, or why it is malformed. `surfaceId` is the load's own, else
52 * `fallback`. `value` is offered only where `allowValue` (a press: in a
53 * message, updateDataModel says it). */
54export function readLoad(
55  wire: unknown,
56  model: unknown,
57  scope: string,
58  fallback: string | undefined,
59  allowValue: boolean,
60): Load | string {
61  if (!isRecord(wire)) return 'a load is not an object'
62  const surfaceId = wire.surfaceId === undefined ? fallback : wire.surfaceId
63  if (typeof surfaceId !== 'string' || surfaceId === '') return 'a load needs a surfaceId'
64  if (typeof wire.path !== 'string') return 'a load needs a path'
65  const as = wire.as ?? 'text'
66  if (as !== 'text' && as !== 'json') return `a load's as is ${JSON.stringify(as)}, not "text" or "json"`
67  const sources = ['run', 'file', ...(allowValue ? ['value'] : [])].filter(key => key in wire)
68  if (sources.length !== 1) return `a load carries exactly one of ${allowValue ? 'run, file, value' : 'run, file'}`
69  const base = { surfaceId, path: wire.path, as } as const
70  if ('run' in wire) {
71    if (!Array.isArray(wire.run) || wire.run.length === 0) return 'a load\'s run is not a non-empty argv list'
72    if (typeof wire.run[0] !== 'string') return 'a load\'s command is written out, never bound to the data model'
73    const argv = wire.run.map(arg => resolve(arg, model, scope))
74    // A number off the data model (a PR's number) is an argument as well.
75    const bad = argv.findIndex(arg => typeof arg !== 'string' && typeof arg !== 'number')
76    if (bad >= 0) return `argument ${bad + 1} of a load's run ${unlike(wire.run[bad], argv[bad], scope, 'a string or a number')}`
77    // What comes off the data model may have come from anywhere (a PR's
78    // body, a page), so it may be an id, a number or a path, never an option
79    // or text: a model's `['sh', '-c', { path: '/body' }]` runs nothing.
80    const loose = wire.run.findIndex((arg, n) => typeof arg !== 'string' && !isToken(argv[n]))
81    if (loose >= 0) return `argument ${loose + 1} of a load's run is bound to ${JSON.stringify(String(argv[loose]).slice(0, 40))}, not an id, a number or a path`
82    const run = argv.map(String)
83    if (run[0] === '') return 'a load\'s run names no command'
84    return { ...base, run }
85  }
86  if ('file' in wire) {
87    const file = resolve(wire.file, model, scope)
88    if (typeof file !== 'string' || file === '') return `a load's file ${unlike(wire.file, file, scope, 'a path')}`
89    return { ...base, run: ['cat', '--', file] }
90  }
91  return { ...base, value: resolve(wire.value, model, scope) }
92}
93
94/** A Button's `action.local`, resolved as `readLoad` does, or undefined when
95 * the action has none. A load names the surface it opens unless it says
96 * otherwise, else the button's own. */
97export function readLocal(action: unknown, model: unknown, scope: string, from: string): LocalAction | string | undefined {
98  if (!isRecord(action) || action.local === undefined) return undefined
99  const local = action.local
100  if (!isRecord(local)) return 'action.local is not an object'
101  const open = local.open
102  if (open !== undefined && (typeof open !== 'string' || open === '')) return 'action.local.open is not a surfaceId'
103  const wires = local.load ?? []
104  if (!Array.isArray(wires)) return 'action.local.load is not a list'
105  const loads: Load[] = []
106  for (const wire of wires) {
107    const load = readLoad(wire, model, scope, open ?? from, true)
108    if (typeof load === 'string') return load
109    loads.push(load)
110  }
111  return { loads, ...(open === undefined ? {} : { open }) }
112}
113
114/** A command's or a file's text as the load asked for it, or why it could
115 * not be read that way. */
116export function parsed(load: Load, text: string): { value: unknown } | string {
117  if (load.as === 'text') return { value: text }
118  try {
119    return { value: JSON.parse(text) }
120  } catch {
121    return `${describe(load)} did not print JSON`
122  }
123}
124
125/** A load, as a person reading an error would name it. */
126export const describe = (load: Load): string => ('run' in load ? `\`${shellCommand(load.run)}\`` : load.path)
127
128/** At most `limit` characters of a command's complaint, on one line. */
129export const brief = (text: string, limit = 300): string => {
130  const line = text.trim().replace(/\s+/g, ' ')
131  return line.length > limit ? `${line.slice(0, limit)}…` : line
132}
133
134/** The surfaces with `to` drawn in place of `from`, the surface pressed:
135 * `from` is kept, hidden, to be opened again. Nothing changes when `to`
136 * names no surface. */
137export function opened(surfaces: RoerUiSurfaces, from: string, to: string): RoerUiSurfaces {
138  const target = own(surfaces.bySurface, to)
139  if (target === undefined) return surfaces
140  const source = own(surfaces.bySurface, from)
141  const bySurface = { ...surfaces.bySurface, [to]: { ...target, hidden: false } }
142  if (source !== undefined && from !== to) bySurface[from] = { ...source, hidden: true }
143  return { ...surfaces, bySurface }
144}
145
146/** A `loadData` message read as a load, or why it is malformed; undefined
147 * for any other message. */
148export function readLoadData(message: unknown): Load | string | undefined {
149  if (!isRecord(message) || !('loadData' in message)) return undefined
150  if (message.version !== 'v1.0') return `version is ${JSON.stringify(message.version)}, not "v1.0"`
151  if (Object.keys(message).length !== 2) return 'a loadData message carries nothing else'
152  return readLoad(message.loadData, {}, '', undefined, false)
153}
154
155/** `argv` as one shell command line that runs exactly it: what the
156 * permission rules read (they are written over Bash command lines) and what
157 * the dialog shows. */
158export const shellCommand = (argv: string[]): string =>
159  argv.map(arg => (/^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`)).join(' ')
160
161type Ran = { exitCode: number; stdout: string; stderr: string }
162
163/** How a command reaches the host, as closures over the hook's `$` (the
164 * engine wants `$` spelled where it is called). */
165export type RunIo = {
166  /** The session's permission decision for a Bash command line. */
167  check: (command: string) => Promise<{ decision: 'allow' | 'ask' | 'deny'; reason?: string }>
168  /** Runs argv at once, whole output. */
169  run: (argv: string[]) => Promise<Ran>
170  /** Runs a command line as a Bash tool call: the permission dialog, hooks
171   * and classifier on the way. */
172  bash: (command: string) => Promise<BashRan>
173  /** A file's whole text: where the Bash tool kept output too long to hand back. */
174  read: (path: string) => Promise<string>
175}
176
177/** What a Bash tool call answered, as `runPermitted` reads it. */
178export type BashRan = { deny?: string; isError?: boolean; stdout?: unknown; persisted?: unknown; text?: string }
179
180/** A Bash tool call's answer, from `$.tool.call`'s result. */
181export const bashRan = (ran: { deny?: string; isError?: boolean; result?: unknown; text?: string }): BashRan => {
182  const result = ran.result as { stdout?: unknown; persistedOutputPath?: unknown } | undefined
183  return { deny: ran.deny, isError: ran.isError, stdout: result?.stdout, persisted: result?.persistedOutputPath, text: ran.text }
184}
185
186/** Runs argv as the person's permissions say. An allowed command runs
187 * directly, so its output comes whole (a Bash tool's is cut for the model);
188 * one that needs asking goes through the Bash tool, whose dialog asks; a
189 * denied one throws. */
190export async function runPermitted(argv: string[], io: RunIo): Promise<Ran> {
191  const command = shellCommand(argv)
192  const { decision, reason } = await io.check(command)
193  if (decision === 'deny') throw new Error(`denied by your permissions${reason ? ` (${reason})` : ''}`)
194  if (decision === 'allow') return io.run(argv)
195  const ran = await io.bash(command)
196  if (ran.deny !== undefined) throw new Error(`not run: ${ran.deny}`)
197  if (ran.isError) return { exitCode: 1, stdout: '', stderr: ran.text ?? '' }
198  // Output too long for the model is kept whole in a file, and `stdout` is
199  // only its start: a diff's first hunks, half a JSON list.
200  if (typeof ran.persisted === 'string' && ran.persisted !== '') return { exitCode: 0, stdout: await io.read(ran.persisted), stderr: '' }
201  return { exitCode: 0, stdout: typeof ran.stdout === 'string' ? ran.stdout : (ran.text ?? ''), stderr: '' }
202}
203
204/** A load's value, or why it could not be had. Never throws. */
205export async function fetchLoad(load: Load, io: RunIo): Promise<{ value: unknown } | string> {
206  if ('value' in load) return { value: load.value }
207  try {
208    const ran = await runPermitted(load.run, io)
209    if (ran.exitCode !== 0) return `${describe(load)} exited ${ran.exitCode}: ${brief(ran.stderr || ran.stdout)}`
210    return parsed(load, ran.stdout)
211  } catch (err) {
212    return `${describe(load)}: ${brief(err instanceof Error ? err.message : String(err))}`
213  }
214}
215
hooks/functions.ts 174 lines
1/**
2 * The functions of `roer:catalog/1`: a closed, pure set a `{ call }` can
3 * name, so a surface can count, compare, compute and word things from its
4 * own data model without a turn of the agent's. A slider bound to `/tip`
5 * and a `Text` that divides by it is a working calculator.
6 *
7 * There is no expression language and no way to reach outside the data
8 * model: a function the catalog does not know resolves to nothing, and so
9 * does a sum over something that is not a number, a division by zero, or a
10 * result that is not finite. Nothing here ever shows NaN or Infinity; a
11 * surface asks `isSet` and says what is missing instead.
12 *
13 * This file is shared, byte for byte, with the roer-ui Claude Code plugin
14 * (claude-plugin/roer-ui/hooks/functions.ts), which ships on its own; keep it
15 * free of imports. functions.test.ts checks that the two copies agree.
16 */
17
18/** How a function reads what it was given: `value` resolves one of its
19 * Dynamic args, `read` a JSON Pointer from the data model (absolute, or
20 * relative to the current template item). */
21export interface FunctionScope {
22  value(arg: unknown): unknown;
23  read(pointer: string): unknown;
24}
25
26type Args = Record<string, unknown>;
27type CatalogFunction = (args: Args, scope: FunctionScope) => unknown;
28
29/** A number, or undefined for anything that only looks like one: blank
30 * text, booleans, `null`, NaN and the infinities. */
31export function toNumber(value: unknown): number | undefined {
32  if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
33  if (typeof value !== "string" || value.trim() === "") return undefined;
34  const parsed = Number(value);
35  return Number.isFinite(parsed) ? parsed : undefined;
36}
37
38const finite = (n: number): number | undefined => (Number.isFinite(n) ? n : undefined);
39
40/** Each of `values`, resolved, as a number; undefined if any one is not. */
41function numbers(args: Args, scope: FunctionScope): number[] | undefined {
42  const list = args.values;
43  if (!Array.isArray(list) || list.length === 0) return undefined;
44  const out: number[] = [];
45  for (const item of list) {
46    const n = toNumber(scope.value(item));
47    if (n === undefined) return undefined;
48    out.push(n);
49  }
50  return out;
51}
52
53/** `a` and `b`, resolved, as numbers; undefined unless both are. */
54function pair(args: Args, scope: FunctionScope): [number, number] | undefined {
55  const a = toNumber(scope.value(args.a));
56  const b = toNumber(scope.value(args.b));
57  return a === undefined || b === undefined ? undefined : [a, b];
58}
59
60const isScalar = (v: unknown) => typeof v === "string" || typeof v === "number" || typeof v === "boolean";
61
62const shown = (v: unknown): string =>
63  v === undefined || v === null ? "" : typeof v === "object" ? JSON.stringify(v) : String(v);
64
65/** How many decimals a format asks for: a whole number from 0 to 20. */
66function decimals(arg: unknown): number | undefined {
67  const n = toNumber(arg);
68  return n === undefined ? undefined : Math.min(20, Math.max(0, Math.round(n)));
69}
70
71const FUNCTIONS: Record<string, CatalogFunction> = {
72  /** `value` with each `${…}` filled in: `${/path}` or `${path}` from the
73   * data model, `${name}` from the call's own arg of that name. */
74  formatString: (args, scope) => {
75    const template = scope.value(args.value);
76    if (typeof template !== "string") return undefined;
77    return template.replace(/\$\{([^}]*)\}/g, (_, ref: string) => {
78      const name = ref.trim();
79      if (name !== "value" && Object.prototype.hasOwnProperty.call(args, name)) return shown(scope.value(args[name]));
80      return shown(scope.read(name));
81    });
82  },
83  pluralize: (args, scope) => {
84    const count = toNumber(scope.value(args.count));
85    if (count === undefined) return undefined;
86    const zero = args.zero === undefined ? undefined : scope.value(args.zero);
87    const word = count === 0 && zero !== undefined ? zero : count === 1 ? scope.value(args.one) : scope.value(args.other);
88    return typeof word === "string" ? word : undefined;
89  },
90  and: (args, scope) => Array.isArray(args.values) && args.values.every((v) => scope.value(v) === true),
91  or: (args, scope) => Array.isArray(args.values) && args.values.some((v) => scope.value(v) === true),
92  not: (args, scope) => scope.value(args.value) !== true,
93  if: (args, scope) => (scope.value(args.condition) === true ? scope.value(args.then) : scope.value(args.else)),
94  eq: (args, scope) => {
95    const a = scope.value(args.a);
96    const b = scope.value(args.b);
97    return isScalar(a) && isScalar(b) && a === b;
98  },
99  gt: (args, scope) => {
100    const p = pair(args, scope);
101    return p === undefined ? undefined : p[0] > p[1];
102  },
103  lt: (args, scope) => {
104    const p = pair(args, scope);
105    return p === undefined ? undefined : p[0] < p[1];
106  },
107  length: (args, scope) => {
108    const v = scope.value(args.value);
109    return typeof v === "string" || Array.isArray(v) ? v.length : undefined;
110  },
111  isSet: (args, scope) => {
112    const v = scope.value(args.value);
113    return v !== undefined && v !== null && v !== "";
114  },
115  isNumber: (args, scope) => toNumber(scope.value(args.value)) !== undefined,
116  add: (args, scope) => {
117    const ns = numbers(args, scope);
118    return ns === undefined ? undefined : finite(ns.reduce((sum, n) => sum + n, 0));
119  },
120  multiply: (args, scope) => {
121    const ns = numbers(args, scope);
122    return ns === undefined ? undefined : finite(ns.reduce((product, n) => product * n, 1));
123  },
124  subtract: (args, scope) => {
125    const p = pair(args, scope);
126    return p === undefined ? undefined : finite(p[0] - p[1]);
127  },
128  divide: (args, scope) => {
129    const p = pair(args, scope);
130    return p === undefined || p[1] === 0 ? undefined : finite(p[0] / p[1]);
131  },
132  min: (args, scope) => {
133    const ns = numbers(args, scope);
134    return ns === undefined ? undefined : Math.min(...ns);
135  },
136  max: (args, scope) => {
137    const ns = numbers(args, scope);
138    return ns === undefined ? undefined : Math.max(...ns);
139  },
140  round: (args, scope) => {
141    const n = toNumber(scope.value(args.value));
142    if (n === undefined) return undefined;
143    const places = args.decimals === undefined ? 0 : decimals(scope.value(args.decimals));
144    if (places === undefined) return undefined;
145    const factor = 10 ** places;
146    return finite(Math.round(n * factor) / factor);
147  },
148  /** In the reader's own locale: grouping on unless `grouping` is false,
149   * exactly `decimals` places when given, up to 3 otherwise. */
150  formatNumber: (args, scope) => {
151    const n = toNumber(scope.value(args.value));
152    if (n === undefined) return undefined;
153    const places = args.decimals === undefined ? undefined : decimals(scope.value(args.decimals));
154    if (args.decimals !== undefined && places === undefined) return undefined;
155    return new Intl.NumberFormat(undefined, {
156      useGrouping: scope.value(args.grouping) !== false,
157      ...(places === undefined ? {} : { minimumFractionDigits: places, maximumFractionDigits: places }),
158    }).format(n);
159  },
160};
161
162/** The names a `{ call }` can use, `@index` aside: it needs the template
163 * item, so each renderer resolves it itself. */
164export const FUNCTION_NAMES: readonly string[] = Object.keys(FUNCTIONS);
165
166/** The value of `{ call: name, args }`, or undefined for a function the
167 * catalog does not have. */
168export function callFunction(name: string, args: unknown, scope: FunctionScope): unknown {
169  if (!Object.prototype.hasOwnProperty.call(FUNCTIONS, name)) return undefined;
170  const fn = FUNCTIONS[name];
171  const given = typeof args === "object" && args !== null && !Array.isArray(args) ? (args as Args) : {};
172  return fn === undefined ? undefined : fn(given, scope);
173}
174
types/index.d.ts 24 lines
1// The A2UI v1.0 surfaces this mod keeps, as the model sent them through its
2// `show` tool: flat, id-referenced components and one data model each, the
3// same shape Roer's own panel holds (src/generative-ui/schema.ts).
4export type RoerUiComponent = { id: string; component: string; [prop: string]: unknown }
5export type RoerUiSurface = {
6  components: Record<string, RoerUiComponent>
7  dataModel: Record<string, unknown>
8  sendDataModel: boolean
9  /** Kept but not drawn, until a press's `action.local.open` names it. */
10  hidden?: boolean
11  /** The pane's own state, by what it is about: which tab a Tabs shows,
12   * which Expandable and Modal are open, a picker's filter, the person's
13   * answers in a work item. Nothing the agent sent says any of it, so it is
14   * never written to the data model, and a new createSurface starts over. */
15  view?: Record<string, unknown>
16}
17export type RoerUiSurfaces = { order: string[]; bySurface: Record<string, RoerUiSurface> }
18
19declare module 'claude-code' {
20  interface PluginState {
21    'roer-ui': { surfaces: RoerUiSurfaces }
22  }
23}
24