SLOPSHOPPER

drawer

A ```dot or ```svg fence in a reply is drawn in place, as the reply streams. Graphviz and resvg compiled in; nothing else running.

rowsprocess
★ 2v0.9.0MITupdated 2026-10-18Sureffi/drawer
A shopper browsing a rack in a slop shop
README

drawer

check

Claude draws. Ask anything with a shape in it and the picture is in the reply, where the words are, while it's still typing. How your services hang together, the fork in a decision, a screen before it's built: a grid with the cursor on a row, the same grid in three tints, and you say which. No tab, no file, no browser. It's in the terminal, in the conversation, and it scrolls past like any other line.

Under it: Claude writes Graphviz or SVG, drawer renders it in place. One binary, kitty or ghostty, two lines to install.

The model drawing while it thinks:

a live session

A screen mocked up in the reply:

a screen mocked up in the reply

install

/plugin marketplace add Sureffi/cyberware.sh /plugin install drawer@cyberware

Then ask for a graph. Nothing else is installed: graphviz, resvg and the type are in the binary.

drawer is for kitty and ghostty; in other terminals a picture is empty boxes.

Pictures take Claude Code's theme; DRAWER_THEME names a theme file.

developing

git clone https://github.com/sureffi/drawer && cd drawer scripts/check.sh claude --plugin-dir /path/to/drawer

license

MIT; NOTICE names what the binary embeds and its licences.

Source 1 files
hooks/render.tsx 794 lines
1// render.tsx — the hooks module: a ```dot or ```svg fence
2// drawn on every screen Claude Code draws a reply on, and a list drawn with rails — a dim
3// vertical at each level's marker column, so a wrapped item's lines say
4// which marker they hang from.
5//
6// The MessageDisplay hook is asked about the live turn of the main thread
7// and nothing else. A fork's view, a subagent's, a transcript replayed by
8// --resume and a background job reattached are drawn from the transcript,
9// and no display hook is asked about them — measured on 2.1.283, each of
10// them showed the fence as source. ui.render is asked about every
11// assistant text block on every one of those screens.
12//
13// On the main thread the display hook draws the live turn as it streams,
14// a fence at its close (drawer's hookForm). ui.render is not asked about a
15// message while it streams, only once it is complete and again at each
16// width (measured 2026-10-18, CC 2.1.302), and the text it is handed then
17// is the display hook's drawing, not the fence. Outside tmux this module
18// keeps the turn's text off the stream (turn.step) and draws each of the
19// hook's blocks again from its fence's source, at every width (restore);
20// behind tmux, or with no source kept, the hook's drawing stands. In a
21// background job forced to draw Images the display hook draws nothing and
22// hands every delta on as it arrived, and this hook draws the fences it
23// finds. Either way one of the two draws a fence and the other passes it.
24//
25// A block with a graph in it is cut at its fences. The prose between them
26// is Claude Code's own drawing (next, with the text cut to that stretch);
27// each fence is what `drawer -element` makes of it: an Image wherever
28// Claude Code draws one; Text rows of box drawing where it draws none —
29// behind tmux, screen or mosh, and in a background job no Image reaches
30// (drawer's elementForm); and Text rows of a notice over the source where
31// the picture fails. Anything that fails here leaves the block to Claude
32// Code as it arrived.
33//
34// Function hooks are early access. A build that does not load hooks
35// modules runs the command hooks in hooks.json alone, and there they are
36// the whole plugin.
37
38import type { Elements, EngineInterface, Register, RenderChildren } from 'claude-code'
39
40// The fence rules are internal/fence's, for a block that has arrived
41// whole: a run of three or more backticks or tildes at the start of a
42// line, closed by a run of the same character at least as long with
43// nothing else on the line. A fence labelled dot or graphviz is a graph's;
44// an unlabelled one is when its first line opens a graph; one labelled
45// svg is an SVG picture; any other is somebody else's, and a ```dot
46// quoted inside it is text.
47//
48// They are Go's character for character. A space is unicode.IsSpace's,
49// which strings.TrimSpace and strings.Fields cut at, and not JavaScript's
50// \s or trim(): U+0085 is one, U+FEFF is not. RE2's . is anything but a
51// newline, and its \s and \b are ASCII; its (?i) folds by Unicode's simple
52// folding, so ſ is an s, which /iu does too, in a class as well: the word
53// boundary after graph is read apart, without the flag. strings.ToLower
54// makes İ an i.
55const space = '\\t\\n\\v\\f\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000'
56const edgeSpace = new RegExp(`^[${space}]+|[${space}]+$`, 'g')
57const spaces = new RegExp(`[${space}]+`)
58const fenceRe = /^([ \t]*)(`{3,}|~{3,})([^\n]*)$/
59const graphKeyword = /^[\t\n\f\r ]*(strict[\t\n\f\r ]+)?(di)?graph/iu
60const graphRest = /^(?![0-9A-Za-z_])[^{]*\{/
61
62const trimSpace = (s: string) => s.replace(edgeSpace, '')
63
64// graphStart is a DOT graph's first line: the keyword, a name if any, and
65// the brace.
66function graphStart(line: string) {
67  const m = graphKeyword.exec(line)
68  return m !== null && graphRest.test(line.slice(m[0].length))
69}
70
71type Opener = { indent: string; run: string; info: string }
72
73function openerOf(line: string): Opener | null {
74  const m = fenceRe.exec(line.replace(/[ \t\r]+$/, ''))
75  if (!m) return null
76  const [, indent = '', run = '', rest = ''] = m
77  if (run[0] === '`' && rest.includes('`')) return null
78  const info = (trimSpace(rest).split(spaces)[0] ?? '').replace(/İ/g, 'i').toLowerCase()
79  return { indent, run, info }
80}
81
82function closes(f: Opener, line: string) {
83  const t = trimSpace(line)
84  return t.length >= f.run.length && [...t].every((c) => c === f.run[0])
85}
86
87// columnsOf is an indent's width as the display hook measures it,
88// grid.Cells: a space is a column and a tab is none.
89function columnsOf(indent: string) {
90  return [...indent].filter((c) => c === ' ').length
91}
92
93// A stretch of a block: prose, or a picture's fence with its source cut
94// out and the language it is in (drawer's Opener.Tag).
95type Tag = 'dot' | 'svg'
96type Part = { raw: string; src?: string; tag?: Tag; indent?: number; closed?: boolean; list?: string[] }
97
98function tagOf(info: string): Tag {
99  return info === 'svg' ? 'svg' : 'dot'
100}
101
102// split cuts a block into stretches of prose and graphs, by line. Every
103// stretch keeps its lines exactly as they arrived, so a graph that will
104// not draw goes back into the prose around it byte for byte.
105function split(text: string): Part[] {
106  const lines = text.split('\n')
107  const parts: Part[] = []
108  let prose = 0
109  for (let i = 0; i < lines.length; ) {
110    const f = openerOf(lines[i] ?? '')
111    if (!f) {
112      i++
113      continue
114    }
115    let j = i + 1
116    while (j < lines.length && !closes(f, lines[j] ?? '')) j++
117    const closed = j < lines.length
118    const body = lines
119      .slice(i + 1, j)
120      .map((l) => (l.startsWith(f.indent) ? l.slice(f.indent.length) : l))
121      .join('\n')
122    const first = body.split('\n').find((l) => trimSpace(l) !== '') ?? ''
123    const ours =
124      f.info === 'dot' || f.info === 'graphviz' || f.info === 'svg' || (f.info === '' && graphStart(trimSpace(first)))
125    const end = closed ? j + 1 : lines.length
126    if (ours) {
127      if (i > prose) parts.push({ raw: lines.slice(prose, i).join('\n') })
128      parts.push({ raw: lines.slice(i, end).join('\n'), src: body, tag: tagOf(f.info), indent: columnsOf(f.indent), closed })
129      prose = end
130    }
131    i = end
132  }
133  if (prose < lines.length) parts.push({ raw: lines.slice(prose).join('\n') })
134  return parts
135}
136
137// A span is a run of one style in a row of glyphs. The first three are
138// the wall's; bold, italic, strikethrough and a link's address are the
139// list door's, read out of an item's inline markdown.
140type Span = { t: string; c?: string; d?: boolean; b?: boolean; i?: boolean; s?: boolean; href?: string }
141
142// Drawing is what `drawer element` answers for one fence: a picture, rows
143// of text (a row with none is blank) — box drawing, or a notice that says
144// why there is no picture, over the source — or none, the fence left as it
145// arrived. failed is a run that answered nothing, which is asked again.
146// viewers is an answer picked for whoever watches a background job now
147// (drawer's elementForm), which is asked again once it is viewersMs old.
148type Drawing = (
149  | { kind: 'image'; png: string; columns: number; rows: number; alt?: string; notice?: boolean }
150  | { kind: 'text'; lines: (Span[] | null)[]; notice?: boolean }
151  | { kind: 'none'; failed?: boolean; notice?: undefined }
152) & { viewers?: boolean }
153
154// The drawings this module has asked for, newest last: a block is drawn
155// again on every scroll that moves it past an edge of the screen, and on
156// every width, and the answer does not change between them — but in a
157// background job forced to draw Images, where it is an Image for the
158// windows it reaches and box drawing while one watches from behind tmux,
159// screen or mosh, and the windows come and go for as long as this worker
160// runs. That answer is kept viewersMs, one burst of renders, so a render
161// after a window came or went asks for that window. A window attaching is
162// not one: measured 2026-10-08, Claude Code 2.1.293, a fresh `claude
163// attach` 67 s after the reply asked this module nothing and was sent the
164// Image drawn before. The theme is in the key, because a picture is
165// painted in it, and so is the indent, because the drawing is as wide as
166// the screen less it, and so is the tag, because the same text is another
167// picture in another language.
168const drawn = new Map<string, { p: Promise<Drawing>; until: number }>()
169const drawnMost = 48
170const viewersMs = 1000
171
172function drawOnce($: EngineInterface, src: string, cols: number, indent: number, theme: string, door: 'element' | 'list' = 'element', tag: Tag = 'dot') {
173  const key = `${door}\u0000${tag}\u0000${theme}\u0000${cols}\u0000${indent}\u0000${src}`
174  const had = drawn.get(key)
175  if (had && Date.now() < had.until) {
176    drawn.delete(key)
177    drawn.set(key, had)
178    return had.p
179  }
180  const entry = { p: drawElement($, src, cols, indent, door, tag), until: Infinity }
181  entry.p = entry.p.then((el) => {
182    if (el.kind === 'none' && el.failed && drawn.get(key) === entry) drawn.delete(key)
183    if (el.viewers) entry.until = Date.now() + viewersMs
184    return el
185  })
186  drawn.delete(key)
187  drawn.set(key, entry)
188  const oldest = drawn.keys().next().value
189  if (drawn.size > drawnMost && oldest !== undefined) drawn.delete(oldest)
190  return entry.p
191}
192
193// drawElement runs the binary on one fence. A run that fails is failed,
194// and asked again on the next render: the wrapper exits non-zero where it
195// finds no binary, which the next session start puts in place. A run past
196// runMs is killed by the engine, which rejects with "still running after";
197// that is a layout too slow to wait for, and it is a none for the session.
198// A fence that is not a graph's names its language last; a graph's names
199// none, which the wrapper reads as dot.
200const runMs = 15000
201
202async function drawElement($: EngineInterface, src: string, cols: number, indent: number, door: 'element' | 'list' = 'element', tag: Tag = 'dot'): Promise<Drawing> {
203  const argv = [`${$.plugin.root}/scripts/drawer`, door, String(cols), String(indent)]
204  if (door === 'element' && tag !== 'dot') argv.push(tag)
205  try {
206    const { exitCode, stdout } = await $.process.run(argv, { stdin: src, timeoutMs: runMs })
207    if (exitCode !== 0) return { kind: 'none', failed: true }
208    return JSON.parse(stdout) as Drawing
209  } catch (err) {
210    const said = typeof err === 'object' && err !== null && 'message' in err ? String(err.message) : String(err)
211    return /still running after/.test(said) ? { kind: 'none' } : { kind: 'none', failed: true }
212  }
213}
214
215// ---- lists ----
216//
217// A list in the prose is drawn with rails: a hairline at each level's
218// marker column, so a wrapped item's lines say which marker they hang
219// from. The rows come from the binary's -list door — wrapped and styled
220// by the same hand that draws the rail, so the rail stands on every row
221// by construction — and a span carrying a link's address is drawn as a
222// Link, clickable where the terminal clicks. A picture inside an item
223// breaks its rail for its own rows and the rail resumes under it.
224//
225// A hairline needs the row count, and the row count belongs to whoever
226// wraps: the engine validates element props against an allowlist
227// (measured on 2.1.295) with none of the per-side borders its own quote
228// rail is drawn with, nothing else a plugin draws stretches to a height
229// it does not know, and Claude Code wraps after this hook has answered.
230// So the door wraps. Where there is no door — an older binary, or none —
231// the level falls back to the one stretch the engine does give a plugin:
232// a width-1 Box behind the engine's own Markdown, its background the
233// theme's user-message background (railsBlock).
234//
235// The cut is by line and fence-aware both ways: a fence inside an item
236// stays inside its item, and a marker inside any fence is code.
237
238const markerRe = /^( *)(?:[-*+]|\d{1,9}[.)])( |$)/
239const anyMarker = new RegExp(markerRe.source, 'm')
240
241// markerIndentOf is the marker's column where a line opens a list item,
242// and null where it does not.
243function markerIndentOf(line: string): number | null {
244  const m = markerRe.exec(line)
245  return m ? (m[1] ?? '').length : null
246}
247
248function leadingSpaces(line: string): number {
249  let n = 0
250  while (line[n] === ' ') n++
251  return n
252}
253
254// A piece of a prose stretch: prose, or a list block kept as its lines.
255type Piece = { prose: string } | { list: string[] }
256
257// cutLists cuts one prose stretch at its lists. A block opens at a marker
258// and holds further markers, continuation lines indented two or more,
259// fences indented into an item, and blank lines a later list line
260// reclaims. Anything else ends it. A fence at the margin is prose with
261// whatever markers it quotes.
262function cutLists(text: string): Piece[] {
263  const lines = text.split('\n')
264  const pieces: Piece[] = []
265  let plain = 0
266  const fenceEnd = (from: number): number => {
267    const f = openerOf(lines[from] ?? '')
268    if (!f) return from + 1
269    let k = from + 1
270    while (k < lines.length && !closes(f, lines[k] ?? '')) k++
271    return k < lines.length ? k + 1 : lines.length
272  }
273  for (let i = 0; i < lines.length; ) {
274    if (openerOf(lines[i] ?? '')) {
275      i = fenceEnd(i)
276      continue
277    }
278    if (markerIndentOf(lines[i] ?? '') === null) {
279      i++
280      continue
281    }
282    let end = i + 1
283    for (let j = i + 1; j < lines.length; ) {
284      const l = lines[j] ?? ''
285      if (openerOf(l) && leadingSpaces(l) >= 2) {
286        j = end = fenceEnd(j)
287        continue
288      }
289      if (trimSpace(l) === '') {
290        j++
291        continue
292      }
293      if (markerIndentOf(l) === null && leadingSpaces(l) < 2) break
294      end = ++j
295    }
296    if (i > plain) pieces.push({ prose: lines.slice(plain, i).join('\n') })
297    pieces.push({ list: lines.slice(i, end) })
298    plain = i = end
299  }
300  if (plain < lines.length) pieces.push({ prose: lines.slice(plain).join('\n') })
301  return pieces
302}
303
304// The rail's paint is the binary's answer (`drawer rail`): the theme's
305// user-message background as Claude Code resolves it, a custom theme's
306// overrides included — the module sees only the theme's name in the
307// settings, the binary reads the theme files themselves. Asked once per
308// theme name and kept; an edited custom theme is read again next session,
309// as a picture's colours are. A binary without the door, or none, falls
310// to the stock table in railHex.
311// A run that died — a signal or no binary, both exit 1 — or was abandoned
312// past runMs answers the stock table for this render only, and the next
313// render asks again.
314const railAsked = new Map<string, Promise<string>>()
315
316function railOnce($: EngineInterface, theme: string) {
317  let p = railAsked.get(theme)
318  if (p === undefined) {
319    const asked: Promise<string> = (async () => {
320      try {
321        const { exitCode, stdout } = await $.process.run([`${$.plugin.root}/scripts/drawer`, 'rail'], { timeoutMs: runMs })
322        const hex = stdout.trim()
323        if (exitCode === 0 && /^#[0-9a-fA-F]{6}$/.test(hex)) return hex
324        if (exitCode === 1 && railAsked.get(theme) === asked) railAsked.delete(theme)
325      } catch {
326        if (railAsked.get(theme) === asked) railAsked.delete(theme)
327      }
328      return railHex(theme)
329    })()
330    p = asked
331    railAsked.set(theme, p)
332  }
333  return p
334}
335
336// railHex is the stock table, for a binary without the -rail door or none
337// in place: internal/theme's user-message backgrounds by stock name. A
338// theme it cannot place is dark, as the binary reads it.
339function railHex(theme: string): string {
340  if (!theme.startsWith('light')) return '#373737'
341  return theme.includes('daltonized') ? '#dcdcdc' : '#f0f0f0'
342}
343
344// listText draws the list door's rows: every span in its own style, a
345// span with an address as a Link around its text.
346function listText(ui: Elements['terminal'], el: Extract<Drawing, { kind: 'text' }>, top: number) {
347  const { Box, Text, Link } = ui
348  return (
349    <Box flexDirection="column" marginTop={top}>
350      {el.lines.map((line) => (
351        <Text wrap="truncate-end">
352          {!line || line.length === 0
353            ? ' '
354            : line.map((s) => {
355                const style: { color?: string; dimColor?: boolean; bold?: boolean; italic?: boolean; strikethrough?: boolean } = {}
356                if (s.c) style.color = s.c
357                if (s.d) style.dimColor = true
358                if (s.b) style.bold = true
359                if (s.i) style.italic = true
360                if (s.s) style.strikethrough = true
361                const run = <Text {...style}>{s.t}</Text>
362                return s.href === undefined ? run : <Link href={s.href}>{run}</Link>
363              })}
364        </Text>
365      ))}
366    </Box>
367  )
368}
369
370// railsBlock draws one level the fallback way: its items as Markdown
371// runs, each deeper level as a block of its own between them, all beside
372// this level's stripe.
373function railsBlock(ui: Elements['terminal'], lines: string[], top: number, hex: string): RenderChildren {
374  const { Box, Markdown } = ui
375  let base = 0
376  for (const l of lines) {
377    const mi = markerIndentOf(l)
378    if (mi !== null) {
379      base = mi
380      break
381    }
382  }
383  const deep = base + 2
384  const kids: RenderChildren[] = []
385  let run: string[] = []
386  const flush = () => {
387    while (run.length > 0 && trimSpace(run[0] ?? '') === '') run.shift()
388    while (run.length > 0 && trimSpace(run[run.length - 1] ?? '') === '') run.pop()
389    if (run.length > 0) kids.push(<Markdown text={run.join('\n')} />)
390    run = []
391  }
392  const dedent = (l: string) => (leadingSpaces(l) >= base ? l.slice(base) : l.slice(leadingSpaces(l)))
393  for (let i = 0; i < lines.length; ) {
394    const l = lines[i] ?? ''
395    const f = openerOf(l)
396    if (f) {
397      run.push(dedent(l))
398      let k = i + 1
399      while (k < lines.length && !closes(f, lines[k] ?? '')) run.push(dedent(lines[k] ?? '')), k++
400      if (k < lines.length) run.push(dedent(lines[k] ?? '')), k++
401      i = k
402      continue
403    }
404    const mi = markerIndentOf(l)
405    if (mi !== null && mi >= deep) {
406      let j = i + 1
407      while (j < lines.length) {
408        const n = lines[j] ?? ''
409        if (openerOf(n) && leadingSpaces(n) >= deep) {
410          const k = (() => {
411            const g = openerOf(n)
412            let x = j + 1
413            while (g && x < lines.length && !closes(g, lines[x] ?? '')) x++
414            return x < lines.length ? x + 1 : lines.length
415          })()
416          j = k
417          continue
418        }
419        if (trimSpace(n) === '') {
420          j++
421          continue
422        }
423        const ni = markerIndentOf(n)
424        if (ni !== null ? ni < deep : leadingSpaces(n) < deep) break
425        j++
426      }
427      flush()
428      kids.push(railsBlock(ui, lines.slice(i, j), 0, hex))
429      i = j
430      continue
431    }
432    run.push(dedent(l))
433    i++
434  }
435  flush()
436  return (
437    <Box flexDirection="row" marginTop={top}>
438      <Box width={1} backgroundColor={hex} />
439      <Box flexDirection="column" flexGrow={1} paddingLeft={1}>
440        {kids}
441      </Box>
442    </Box>
443  )
444}
445
446// cutListsSafe is cutLists held: a stretch the cutter chokes on is prose,
447// and the reply still draws.
448function cutListsSafe(text: string): Piece[] {
449  try {
450    return cutLists(text)
451  } catch {
452    return [{ prose: text }]
453  }
454}
455
456// The bullet that opens a reply is Claude Code's, drawn with the first
457// stretch of prose. A reply that opens with a graph has no prose there to
458// carry it, and gets Claude Code's glyph from here: ⏺ on macOS, ● elsewhere.
459let bullet: string | undefined
460
461async function bulletOf($: EngineInterface) {
462  if (bullet === undefined) {
463    try {
464      bullet = (await $.process.run(['uname', '-s'])).stdout.trim() === 'Darwin' ? '⏺' : '●'
465    } catch {
466      bullet = '●'
467    }
468  }
469  return bullet
470}
471
472// picture is one drawing, standing where the display hook's would: at the
473// text's own column, in the fence's indent, a row clear of the prose above.
474function picture(ui: Elements['terminal'], el: Exclude<Drawing, { kind: 'none' }>, indent: number, top: number) {
475  const { Box, Text, Image } = ui
476  const pad = { paddingLeft: indent, marginTop: top }
477  if (el.kind === 'image') {
478    return (
479      <Box {...pad}>
480        <Image source={{ png: el.png }} columns={el.columns} rows={el.rows} alt={el.alt ?? ''} />
481      </Box>
482    )
483  }
484  return (
485    <Box flexDirection="column" {...pad}>
486      {el.lines.map((line) => (
487        <Text wrap="truncate-end">
488          {!line || line.length === 0
489            ? ' '
490            : line.map((s) => {
491                const style: { color?: string; dimColor?: boolean } = {}
492                if (s.c) style.color = s.c
493                if (s.d) style.dimColor = true
494                return <Text {...style}>{s.t}</Text>
495              })}
496        </Text>
497      ))}
498    </Box>
499  )
500}
501
502// live is the main thread outside tmux: there the display hook's picture
503// of the live turn is drawn again here, from the source kept off the
504// stream, at every width. Behind tmux the hook's picture goes down the
505// tmux wire and this module's would be box drawing, so the hook's stands;
506// in a background job the turn is the module's own or the hook's as
507// hookForm says. Read once off claude's environment.
508let live: boolean | undefined
509
510async function liveOf($: EngineInterface) {
511  if (live === undefined) {
512    try {
513      live = (await $.env.get('CLAUDE_CODE_SESSION_KIND')) !== 'bg' && !(await $.env.get('TMUX'))
514    } catch {
515      live = false
516    }
517  }
518  return live
519}
520
521// ---- the stream ----
522//
523// The text of the main loop's turns as the model streamed it, by turn, and
524// in a turn by step and content block, the newest turns kept. A turn.step
525// chunk is read and passed on as it came: what leaves the hook is what is
526// shown and recorded, so nothing here rewrites it.
527const kept = new Map<string, Map<string, string>>()
528const keptMost = 4
529
530function keepText(turnId: string, step: number, block: number, text: string): string {
531  let turn = kept.get(turnId)
532  if (turn === undefined) {
533    turn = new Map()
534    kept.set(turnId, turn)
535    const oldest = kept.keys().next().value
536    if (kept.size > keptMost && oldest !== undefined) kept.delete(oldest)
537  }
538  const key = `${step}\u0000${block}`
539  const whole = (turn.get(key) ?? '') + text
540  turn.set(key, whole)
541  return whole
542}
543
544// ends trims the blank lines at either end of a block, which are Claude
545// Code's to trim.
546const ends = (t: string) => t.replace(/^(?:[ \t]*\n)+/, '').replace(/(?:\n[ \t]*)+$/, '')
547
548// The picture of a fence is drawn as soon as the stream closes the fence,
549// and a list's rows as soon as the list ends, at the columns the last
550// render reported, so the render that comes once the message is complete
551// finds them drawn (drawOnce) and does not wait on the binary. warmed is
552// the drawings each kept block has asked for.
553let lastColumns = 0
554const warmed = new Map<string, Set<string>>()
555
556async function warm($: EngineInterface, key: string, text: string, done: boolean) {
557  if (lastColumns <= 0) return
558  const asks: { src: string; indent: number; door: 'element' | 'list'; tag?: Tag }[] = []
559  const parts = split(ends(text))
560  parts.forEach((p, i) => {
561    if (p.src !== undefined) {
562      if (p.closed) asks.push({ src: p.src, indent: p.indent ?? 0, door: 'element', tag: p.tag })
563      return
564    }
565    const pieces = cutListsSafe(p.raw)
566    pieces.forEach((piece, k) => {
567      const last = i === parts.length - 1 && k === pieces.length - 1
568      if ('list' in piece && (done || !last)) asks.push({ src: piece.list.join('\n'), indent: 0, door: 'list' })
569    })
570  })
571  let had = warmed.get(key)
572  if (had === undefined) {
573    had = new Set()
574    warmed.set(key, had)
575    if (warmed.size > drawnMost) warmed.delete(warmed.keys().next().value ?? key)
576  }
577  const cols = lastColumns
578  const fresh = asks.filter((a) => !had.has(`${a.door}\u0000${cols}\u0000${a.src}`))
579  if (fresh.length === 0) return
580  for (const a of fresh) had.add(`${a.door}\u0000${cols}\u0000${a.src}`)
581  const theme = String((await $.settings.read()).theme ?? '')
582  for (const a of fresh) void drawOnce($, a.src, cols, a.indent, theme, a.door, a.tag)
583}
584
585// restore cuts a block the display hook drew back into the stretches split
586// would have cut from its source: the prose as shown, each of the hook's
587// drawn blocks a part carrying its fence's source, kept from the stream,
588// with the drawing as its raw, so a picture that does not draw here leaves
589// the hook's standing. It answers the parts of the newest kept block the
590// shown text is the drawing of, and null where none is.
591function restore(shown: string): Part[] | null {
592  if (!shown.includes('```text')) return null
593  for (const turn of [...kept.values()].reverse()) {
594    for (const source of [...turn.values()].reverse()) {
595      const parts = drawingOf(source, shown)
596      if (parts !== null) return parts
597    }
598  }
599  return null
600}
601
602// drawingOf matches the shown text to a source block, line by line: every
603// stretch of prose as it streamed; every fence of a picture's either as it
604// streamed, the hook having left it, or as one ```text block in its place,
605// the hook's drawing (drawer's fenced, indented as the fence was); and
606// every list either as it streamed or as one ```text block at the margin,
607// the hook's rows (drawer's liststream.go), cut as cutLists cuts it. The
608// shown text may stop short of the source, its last line partway or a
609// list's block not yet closed, as the display hook's text stands before
610// its last delta; a fence the reply never closed may leave lines after the
611// drawing, given back as prose.
612function drawingOf(source: string, shown: string): Part[] | null {
613  const theirs = split(ends(source))
614  const lines = ends(shown).split('\n')
615  const parts: Part[] = []
616  let r = 0
617  let drew = false
618  // block is the last line of the hook's ```text block at r, standing in
619  // that many columns, or -1 where none stands there.
620  const block = (indent: number) => {
621    const f = openerOf(lines[r] ?? '')
622    if (f === null || f.info !== 'text' || columnsOf(f.indent) !== indent) return -1
623    let j = r + 1
624    while (j < lines.length && !closes(f, lines[j] ?? '')) j++
625    return Math.min(j, lines.length - 1)
626  }
627  // asShown takes a stretch's lines as they stand at r: whole, or cut short
628  // where the shown text ends; null where it differs.
629  const asShown = (raw: string[]): { raw: string; whole: boolean } | null => {
630    const n = Math.min(raw.length, lines.length - r)
631    for (let i = 0; i < n; i++) {
632      const want = (raw[i] ?? '').trimEnd()
633      const got = (lines[r + i] ?? '').trimEnd()
634      if (got !== want && !(r + i === lines.length - 1 && want.startsWith(got))) return null
635    }
636    const whole = n === raw.length && (lines[r + n - 1] ?? '').trimEnd() === (raw[n - 1] ?? '').trimEnd()
637    const got = { raw: lines.slice(r, r + n).join('\n'), whole }
638    r += n
639    return got
640  }
641  for (const p of theirs) {
642    if (r === lines.length) break
643    if (p.src !== undefined) {
644      const j = block(p.indent ?? 0)
645      if (j >= 0) {
646        parts.push({ raw: lines.slice(r, j + 1).join('\n'), src: p.src, tag: p.tag, indent: p.indent, closed: true })
647        r = j + 1
648        drew = true
649        continue
650      }
651      const got = asShown(p.raw.split('\n'))
652      if (got === null) return null
653      parts.push(got.whole ? { ...p, raw: got.raw } : { raw: got.raw })
654      continue
655    }
656    for (const piece of cutListsSafe(p.raw)) {
657      if (r === lines.length) break
658      if ('list' in piece) {
659        const j = block(0)
660        if (j >= 0) {
661          parts.push({ raw: lines.slice(r, j + 1).join('\n'), list: piece.list })
662          r = j + 1
663          drew = true
664          continue
665        }
666      }
667      const got = asShown('list' in piece ? piece.list : piece.prose.split('\n'))
668      if (got === null) return null
669      parts.push({ raw: got.raw })
670    }
671  }
672  if (r < lines.length) {
673    const last = theirs[theirs.length - 1]
674    const rest = lines.slice(r)
675    if (!(last?.src !== undefined && last.closed === false) && rest.some((l) => l.trim() !== '')) return null
676    parts.push({ raw: rest.join('\n') })
677  }
678  return drew ? parts : null
679}
680
681export const register: Register = (on) => {
682  on('turn.step', async function* ($, e, next) {
683    const keep = e.agentId === undefined && (await liveOf($))
684    const beneath = next(e)
685    for await (const c of beneath) {
686      if (keep && c.kind === 'text') {
687        try {
688          const whole = keepText(e.turnId, e.index, c.index, c.text)
689          if (/[`~\n]/.test(c.text)) warm($, `${e.turnId}\u0000${e.index}\u0000${c.index}`, whole, false).catch(() => {})
690        } catch {
691          // a turn not kept is a turn the hook's drawing stands for
692        }
693      }
694      yield c
695    }
696    if (keep) {
697      for (const [k, whole] of kept.get(e.turnId) ?? []) {
698        if (k.startsWith(`${e.index}\u0000`)) warm($, `${e.turnId}\u0000${k}`, whole, true).catch(() => {})
699      }
700    }
701    return await beneath.result
702  })
703
704  on('ui.render', { component: 'UserMessage' }, async (_, e, next) => {
705    if (e.surface === 'terminal' && e.viewport) lastColumns = e.viewport.columns
706    return next(e)
707  })
708
709  on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
710    if (e.surface !== 'terminal') return next(e)
711    if (e.viewport) lastColumns = e.viewport.columns
712    const text = e.props.text
713    if (!text.includes('```') && !text.includes('~~~') && !anyMarker.test(text)) return next(e)
714    const parts = ((await liveOf($)) && restore(text)) || split(text)
715
716    const cols = e.viewport?.columns ?? 0
717    const theme = String((await $.settings.read()).theme ?? '')
718    const els = await Promise.all(
719      parts.map((p) => (p.src === undefined ? null : drawOnce($, p.src, cols, p.indent ?? 0, theme, 'element', p.tag))),
720    )
721
722    // A graph that will not draw is prose again, and so is a notice on a
723    // fence the reply never closed: that is a reply cut off, not a graph
724    // somebody got wrong.
725    const blocks: ({ prose: string; el?: undefined } | { el: Exclude<Drawing, { kind: 'none' }>; indent: number })[] = []
726    let prose: string[] = []
727    parts.forEach((p, i) => {
728      if (p.list !== undefined) {
729        prose.push(p.list.join('\n'))
730        return
731      }
732      const el = els[i]
733      if (!el || el.kind === 'none' || (el.notice && !p.closed)) {
734        prose.push(p.raw)
735        return
736      }
737      blocks.push({ prose: prose.join('\n') })
738      blocks.push({ el, indent: p.indent ?? 0 })
739      prose = []
740    })
741    blocks.push({ prose: prose.join('\n') })
742    const cuts = blocks.map((b) => (b.el ? null : cutListsSafe(b.prose)))
743    const anyList = cuts.some((c) => c !== null && c.some((p) => 'list' in p))
744    if (!blocks.some((b) => b.el) && !anyList) return next(e)
745
746    const ui = $.ui.resolve(e)
747    const { Box, Text } = ui
748    const body: RenderChildren[] = []
749    let first = e.props.isFirstOfReply
750    let opened = false // a bullet is on screen, so what follows stands in its column
751    for (let bi = 0; bi < blocks.length; bi++) {
752      const b = blocks[bi]
753      if (b === undefined) continue
754      if (b.el) {
755        body.push(picture(ui, b.el, b.indent, body.length === 0 ? 0 : 1))
756        continue
757      }
758      for (const p of cuts[bi] ?? []) {
759        if ('list' in p) {
760          const top = body.length === 0 ? 0 : 1
761          const el = await drawOnce($, p.list.join('\n'), cols, 0, theme, 'list')
762          if (el.kind === 'text') body.push(listText(ui, el, top))
763          else body.push(railsBlock(ui, p.list, top, await railOnce($, theme)))
764          continue
765        }
766        const stretch = p.prose.replace(/^(?:[ \t]*\n)+/, '').replace(/(?:\n[ \t]*)+$/, '')
767        if (stretch.trim() === '') continue
768        body.push(await next({ ...e, props: { ...e.props, text: stretch, isFirstOfReply: first && body.length === 0 } }))
769        if (first && body.length === 1) opened = true
770      }
771    }
772
773    if (!first) return <Box flexDirection="column">{body}</Box>
774    if (opened) {
775      return (
776        <Box flexDirection="column">
777          {body[0]}
778          <Box flexDirection="column" paddingLeft={2}>
779            {body.slice(1)}
780          </Box>
781        </Box>
782      )
783    }
784    return (
785      <Box flexDirection="row" alignItems="flex-start" marginTop={1}>
786        <Box minWidth={2}>
787          <Text color="text">{await bulletOf($)}</Text>
788        </Box>
789        <Box flexDirection="column">{body}</Box>
790      </Box>
791    )
792  })
793}
794