Answers Claude's numbered question rounds one by one in a panel, keeps confirmed answers across restarts, and sends them back as Q1: … lines

Answers Claude's question rounds one question at a time. When Claude ends a turn with numbered questions — the ❓ Q1 - Title: … / ➡️ recommendation format of the grilling skill — a panel opens beside the conversation with a text field for the first open question. Enter saves the answer and moves on; once every question has an answer, a review lets you change any of them or send them all to Claude as Q1: … lines.
| When | What you see |
|---|---|
| Claude's answer ends on a question round | the panel opens on the first open question; 🔥 0/5 in the footer under the prompt counts the answered questions |
| Enter in the field | the answer is saved, the next open question comes up |
| Enter on an empty field | the question's recommendation is taken (Q2: Recommendation accepted) |
a letter alone (b) for a question with (a) … or a) … choices | that choice is saved (Q1: (b) A day off) |
| Edit recommendation | the recommendation's text goes into the field to change before Enter |
| Shift+Tab, then Enter | back to the previous question |
| Skip ▶ | the question stays open and comes back after the others |
| Every question answered | the review: a digit opens that answer again, Enter sends |
| Send… with questions still open | asks first, then sends the open ones as Q4: (unanswered) |
| Discard round | asks first, then closes the round for good; /grill brings it back |
| Esc, or the pane's close mark | the panel closes, the answers stay; /grill reopens it |
The table describes the terminal. The desktop app and VS Code draw the same flow as cards — pictures drawn by the mod, in the light or dark color scheme — with native controls beneath them:
| Where | What you see |
|---|---|
| the header card | Question 2 of 5, the title and one bar segment per question: green answered, amber skipped, the current one pulsing in the accent color; at its right a numbered button per question (✓ once answered), a click jumps there |
| the question card | the question's text with its Markdown (bold, code, lists, quotes, code blocks); choices written as (a) … (b) … or as a), a. list items become lettered tiles, the recommended one framed in the accent color, the one you picked in green |
| the recommendation card | the recommendation, with the choice it names; green once accepted. At its right Accept and Edit |
| where the focus starts | on Accept, so Enter alone takes it; on the field when the question has no recommendation or was answered in text before |
| the answer card | a new field per question; Enter saves. A card beneath it shows what Enter will save, wrapped, as you type; a letter alone (b) saves that choice, and the card names it |
| the bar at the foot | Skip for now, and dimmed Send now… and Discard |
| the review | one card per question with its answer and ✎ Edit, open ones in the warning color; a bar with Send to Claude and Discard round |
The buttons and the field are the app's own controls laid over the cards. In a pane narrower than about 420 pixels they move beneath the cards instead, and the steps do too when a round has too many questions to fit beside the title.
The cards cannot measure their text, so line breaks are estimated a little on the safe side, and a link shows its text without being clickable.
The answers reach Claude as one message of yours. Until you send, nothing you type in the panel reaches Claude.
No setup needed. Works in the terminal, the desktop app and VS Code; the mobile app draws no text field and says so.
The panel reads the format the grilling skill asks for, and tolerates the drift a model falls into: Q2 (updated), a missing ❓, – or : as separators, a question without a recommendation. A bold Q3 in ordinary prose is not a round: one question needs the ❓ or a ➡️ recommendation.
Whenever the grilling skill loads, the mod appends a short paragraph to the prompt the model reads, pinning that format and explaining what Recommendation accepted and (unanswered) mean. The skill's own file is left alone, so updating the skill from upstream loses nothing.
Each answer confirmed with Enter is saved at once in the mod's store under ~/.claude, per project and question round. Starting Claude Code again with --continue or --resume, or /resume in a running session, brings the round back with its answers when the conversation still ends on it. A round you sent or discarded is not offered again; entries untouched for 30 days are dropped at the next start.
/grill); otherwise a toast points to /grill, which opens it at any width. The desktop app always opens it as a side pane.mod-hub loaded, the desktop footer leaves the 🔥 count to its 🧰, whose Grill row shows the answered questions and opens the panel, also while Claude is working.Remove the mod from CLAUDE_CODE_PLUGIN_DIRS. The saved answers live in the mod's store and expire after 30 days.
hooks/register.tsx 851 lines1import { atom, read, update } from 'claude-code'
2import type { ElementTable, EngineInterface, Register, RenderElement, RenderSurface } from 'claude-code'
3
4import type { Draft, Question, Round, StoredRound } from '../types'
5import type { HubCall, HubEntry } from './hub'
6import {
7 FORMAT_CONTRACT,
8 answerCurrent,
9 answerOf,
10 choiceAnswerOf,
11 choiceOf,
12 choicesOf,
13 editAt,
14 footerOf,
15 formatAnswers,
16 goBack,
17 isStoredRound,
18 lastRoundIn,
19 latestRoundIn,
20 newRound,
21 openCount,
22 parseQuestions,
23 prefillRecommendation,
24 previewOf,
25 resume,
26 roundKeyOf,
27 skipCurrent,
28} from './rounds'
29import {
30 barCard,
31 buttonWidthOf,
32 columnsOf,
33 fieldCard,
34 headerCard,
35 noticeCard,
36 previewCard,
37 questionCards,
38 recommendationCards,
39 reviewCard,
40 sendingCard,
41} from './look'
42import type { Card, Segment } from './look'
43import { PAD, ROOMY_WIDTH, cardWidthOf } from './svg'
44
45const PANE = 'grill'
46const TITLE = 'Grill'
47const STORE_PREFIX = 'round:'
48const RETENTION_MS = 30 * 24 * 60 * 60 * 1000
49
50const round = atom({ plugin: 'grill-panel', key: 'round' } as const, null)
51const draft = atom({ plugin: 'grill-panel', key: 'draft' } as const, null)
52const isHubbed = atom({ plugin: 'grill-panel', key: 'isHubbed' } as const, false)
53
54let published: string | null = null
55
56// Without mod-hub the call throws, and the mod keeps its own footer count.
57async function publish($: EngineInterface, entry: HubEntry): Promise<void> {
58 const text = JSON.stringify(entry)
59 if (text === published) {
60 return
61 }
62 let isReached = true
63 try {
64 await ($ as unknown as HubCall).hub.set({ id: 'grill-panel', ...entry })
65 } catch {
66 isReached = false
67 }
68 published = isReached ? text : null
69 if ((await read($, isHubbed)) !== isReached) {
70 await update($, isHubbed, () => isReached)
71 }
72}
73
74async function report($: EngineInterface): Promise<void> {
75 const current = await read($, round)
76 const total = current?.questions.length ?? 0
77 await publish($, {
78 icon: '🔥',
79 title: 'Grill',
80 status: current === null ? 'No open round' : `${total - openCount(current)} of ${total} answered`,
81 attention: current === null ? 'none' : 'info',
82 actions: [{ key: 'open', label: current === null ? 'Latest round' : 'Continue' }],
83 })
84}
85
86type RemoteElements = Pick<ElementTable<'desktop'>, 'Box' | 'Button' | 'Input' | 'Svg' | 'Text'>
87
88async function loadStored($: EngineInterface, key: string): Promise<StoredRound | undefined> {
89 const value = await $.store.get(key)
90
91 return isStoredRound(value) ? value : undefined
92}
93
94async function save($: EngineInterface, value: Round, status: StoredRound['status']): Promise<void> {
95 const stored: StoredRound = { status, answers: value.answers, updatedAt: await $.clock.now() }
96 await $.store.set(value.key, stored)
97}
98
99async function prune($: EngineInterface): Promise<void> {
100 const now = await $.clock.now()
101 const keys = await $.store.keys()
102 for (const key of keys) {
103 if (!key.startsWith(STORE_PREFIX)) {
104 continue
105 }
106 const stored = await loadStored($, key)
107 if (stored === undefined || now - stored.updatedAt > RETENTION_MS) {
108 await $.store.delete(key)
109 }
110 }
111}
112
113// Unasked, a narrow terminal leaves the pane undrawn, and the count in the
114// footer alone does not say how to open it.
115async function openPane($: EngineInterface): Promise<void> {
116 const opened = await $.ui.open({ id: PANE, title: TITLE, focus: true, closeOnEscape: true })
117 if (!opened.isPlaced) {
118 $.ui.toast('Question round ready · /grill opens it', { timeoutMs: 10_000 })
119 }
120}
121
122// Moving the ring is a convenience: where it cannot move (a site without the
123// keys, the test kit, which has no ring) the press that asked still counts.
124async function focus($: EngineInterface, key: string): Promise<void> {
125 await $.ui.focus({ requestId: PANE, key }).catch(() => undefined)
126}
127
128// One field per question: a field kept across questions keeps the text typed
129// into it, since the value it is drawn with stays empty from one to the next.
130function fieldOf(value: Round): string {
131 return `answer-${value.current}`
132}
133
134// Where the desktop's ring starts on a question, so Enter alone takes the
135// recommendation unless an answer was typed before.
136function startOf(value: Round): string {
137 const question = value.questions[value.current]
138 if (value.mode === 'review') {
139 return 'send'
140 }
141 if (question === undefined || value.prefill !== null || value.answers[value.current]?.kind === 'text') {
142 return fieldOf(value)
143 }
144
145 return question.recommendation === null ? fieldOf(value) : 'accept-recommendation'
146}
147
148// The terminal keeps its one field, so the ring stays on it there.
149async function focusStart($: EngineInterface, value: Round | null, surface: RenderSurface): Promise<void> {
150 if (value === null) {
151 return
152 }
153 if (surface === 'terminal') {
154 await focus($, value.mode === 'review' ? 'send' : 'answer')
155 return
156 }
157 await focus($, startOf(value))
158}
159
160// A round already sent or discarded stays closed unless the person asks for it
161// again with /grill (`isRevived`).
162async function begin($: EngineInterface, questions: readonly Question[], isRevived: boolean): Promise<boolean> {
163 const root = await $.session.root()
164 const key = `${STORE_PREFIX}${roundKeyOf(root, questions)}`
165 const current = await read($, round)
166 if (current?.key === key) {
167 return true
168 }
169 const stored = await loadStored($, key)
170 if (stored?.status === 'done' && !isRevived) {
171 return false
172 }
173 const value = newRound(key, questions, stored?.answers ?? [])
174 await update($, round, () => value)
175 await report($)
176 if (stored?.status === 'done') {
177 await save($, value, 'open')
178 }
179
180 return true
181}
182
183async function restore($: EngineInterface): Promise<void> {
184 const current = await read($, round)
185 if (current !== null) {
186 return
187 }
188 const messages = await $.session.messages()
189 const questions = lastRoundIn(messages)
190 if (questions.length > 0 && (await begin($, questions, false))) {
191 await openPane($)
192 }
193}
194
195async function reset($: EngineInterface): Promise<void> {
196 await update($, round, () => null)
197 await report($)
198 await $.ui.close({ id: PANE })
199}
200
201async function openGrill($: EngineInterface): Promise<void> {
202 const current = await read($, round)
203 if (current === null) {
204 const messages = await $.session.messages()
205 const questions = latestRoundIn(messages)
206 if (questions.length === 0) {
207 $.ui.toast('No question round in this conversation.')
208 return
209 }
210 await begin($, questions, true)
211 }
212 await openPane($)
213}
214
215async function finish($: EngineInterface, value: Round): Promise<void> {
216 await save($, value, 'done')
217 await reset($)
218}
219
220async function change($: EngineInterface, apply: (value: Round) => Round): Promise<Round | null> {
221 const value = await update($, round, current => (current === null ? null : apply(current)))
222 if ((await read($, draft)) !== null) {
223 await update($, draft, () => null)
224 }
225 await report($)
226
227 return value
228}
229
230async function submit($: EngineInterface, text: string, surface: RenderSurface): Promise<void> {
231 const before = await read($, round)
232 const question = before?.questions[before.current]
233 if (before?.mode !== 'answer' || question === undefined) {
234 return
235 }
236 if (answerOf(text, question) === null) {
237 $.ui.toast('This question has no recommendation to take; type an answer.')
238 return
239 }
240 const value = await change($, current => answerCurrent(current, text))
241 if (value === null) {
242 return
243 }
244 await save($, value, 'open')
245 await focusStart($, value, surface)
246}
247
248async function skip($: EngineInterface, surface: RenderSurface): Promise<void> {
249 await focusStart($, await change($, skipCurrent), surface)
250}
251
252async function back($: EngineInterface, surface: RenderSurface): Promise<void> {
253 await focusStart($, await change($, goBack), surface)
254}
255
256async function edit($: EngineInterface, index: number, surface: RenderSurface): Promise<void> {
257 await focusStart($, await change($, current => editAt(current, index)), surface)
258}
259
260async function useRecommendation($: EngineInterface, surface: RenderSurface): Promise<void> {
261 const value = await change($, prefillRecommendation)
262 await focusStart($, value, surface)
263}
264
265async function requestSend($: EngineInterface): Promise<void> {
266 const value = await read($, round)
267 if (value === null) {
268 return
269 }
270 if (openCount(value) === 0) {
271 await send($)
272 return
273 }
274 await change($, current => ({ ...current, mode: 'confirm-send', prefill: null }))
275 await focus($, 'confirm-send')
276}
277
278async function send($: EngineInterface): Promise<void> {
279 const value = await read($, round)
280 if (value === null || value.mode === 'sending') {
281 return
282 }
283 await change($, current => ({ ...current, mode: 'sending' }))
284 try {
285 await $.prompt.submit({ text: formatAnswers(value), asUser: true })
286 } catch (error) {
287 await change($, resume)
288 $.ui.toast(`grill-panel could not send the answers; they are kept. ${String(error)}`)
289 return
290 }
291 await finish($, value)
292}
293
294async function requestDiscard($: EngineInterface): Promise<void> {
295 await change($, current => ({ ...current, mode: 'confirm-discard', prefill: null }))
296 await focus($, 'cancel')
297}
298
299async function discard($: EngineInterface): Promise<void> {
300 const value = await read($, round)
301 if (value !== null) {
302 await finish($, value)
303 }
304}
305
306async function cancel($: EngineInterface, surface: RenderSurface): Promise<void> {
307 await focusStart($, await change($, resume), surface)
308}
309
310function markOf(value: Round, index: number): string {
311 if (value.answers[index] !== null) {
312 return '✓'
313 }
314 if (index === value.current && value.mode === 'answer') {
315 return '›'
316 }
317
318 return value.skipped[index] === true ? '↷' : '·'
319}
320
321function headingOf(question: Question): string {
322 return question.title.length > 0 ? `Q${question.number} · ${question.title}` : `Q${question.number}`
323}
324
325// Both discard buttons share the scope; only one of them is ever drawn.
326const DISCARD_HOVER = { scope: 'discard', color: 'error', dimColor: false } as const
327
328function drawStep($: EngineInterface, ui: RemoteElements, value: Round, index: number): RenderElement {
329 const { Button, Text } = ui
330 const number = String(index + 1)
331 const press = (surface: RenderSurface) => edit($, index, surface)
332 if (index === value.current) {
333 return <Button key={`goto-${index}`} variant="primary" label={number} onPress={e => press(e.surface)} />
334 }
335 if (value.answers[index] !== null) {
336 return (
337 <Button key={`goto-${index}`} dimColor onPress={e => press(e.surface)}>
338 <Text color="success">✓</Text>
339 {` ${number}`}
340 </Button>
341 )
342 }
343 if (value.skipped[index] === true) {
344 return (
345 <Button key={`goto-${index}`} dimColor onPress={e => press(e.surface)}>
346 <Text color="warning">↷</Text>
347 {` ${number}`}
348 </Button>
349 )
350 }
351
352 return <Button key={`goto-${index}`} dimColor label={number} onPress={e => press(e.surface)} />
353}
354
355function segmentsOf(value: Round): Segment[] {
356 return value.questions.map((_, index) => {
357 if (index === value.current && value.mode === 'answer') {
358 return 'current'
359 }
360 if (value.answers[index] !== null) {
361 return 'answered'
362 }
363
364 return value.skipped[index] === true ? 'skipped' : 'open'
365 })
366}
367
368function drawCards(ui: RemoteElements, cards: readonly Card[], width: number): RenderElement[] {
369 const { Svg } = ui
370
371 return cards.map(card => <Svg source={card.source} alt={card.alt} width={width} height={card.height} />)
372}
373
374const FIELD_LABEL_WIDTH = 176
375
376// The cards are pictures and take no presses: every control is a native
377// element, laid over the card it belongs to, centered on its height.
378function drawLayered(ui: RemoteElements, key: string, cards: readonly Card[], width: number, overlays: readonly { side: 'left' | 'right'; children: RenderElement[] }[]): RenderElement {
379 const { Box } = ui
380
381 return (
382 <Box key={key} flexDirection="column">
383 {drawCards(ui, cards, width)}
384 {overlays.map(overlay => (
385 <Box position="absolute" top={0} bottom={0} {...(overlay.side === 'right' ? { right: 2 } : { left: 2 })} flexDirection="row" alignItems="center" columnGap={1}>
386 {overlay.children}
387 </Box>
388 ))}
389 </Box>
390 )
391}
392
393function stepLabelOf(value: Round, index: number): string {
394 if (value.answers[index] !== null) {
395 return `✓ ${index + 1}`
396 }
397
398 return value.skipped[index] === true ? `↷ ${index + 1}` : String(index + 1)
399}
400
401function drawHeader(ui: RemoteElements, value: Round, width: number, eyebrow: string, title: string, steps: RenderElement[] | null = null): RenderElement {
402 const total = value.questions.length
403 const counter = `${total - openCount(value)}/${total} answered`
404 if (steps === null) {
405 return drawCards(ui, [headerCard({ width, eyebrow, title, counter, segments: segmentsOf(value) })], width)[0] as RenderElement
406 }
407 const reserve = buttonWidthOf(value.questions.map((_, index) => stepLabelOf(value, index)))
408 const card = headerCard({ width, eyebrow, title, counter, segments: segmentsOf(value), reserve })
409
410 return drawLayered(ui, 'header', [card], width, [{ side: 'right', children: steps }])
411}
412
413function drawRemote($: EngineInterface, ui: RemoteElements, value: Round, typed: Draft | null, width: number): RenderElement {
414 const { Box, Button, Text } = ui
415 const total = value.questions.length
416 const open = openCount(value)
417 const isRoomy = width >= ROOMY_WIDTH
418
419 if (value.mode === 'sending') {
420 return <Box flexDirection="column">{drawCards(ui, [sendingCard(width)], width)}</Box>
421 }
422
423 if (value.mode === 'confirm-send' || value.mode === 'confirm-discard') {
424 const isSend = value.mode === 'confirm-send'
425 const buttons = isSend
426 ? [
427 <Button key="confirm-send" variant="primary" autoFocus label="➤ Send anyway" onPress={() => send($)} />,
428 <Button key="cancel" label="✎ Keep answering" onPress={e => cancel($, e.surface)} />,
429 ]
430 : [
431 <Button key="cancel" variant="primary" autoFocus label="Keep round" onPress={e => cancel($, e.surface)} />,
432 <Button key="confirm-discard" onPress={() => discard($)}>
433 <Text color="error">✕ Discard</Text>
434 </Button>,
435 ]
436 const reserve = isRoomy ? buttonWidthOf(isSend ? ['➤ Send anyway', '✎ Keep answering'] : ['Keep round', '✕ Discard']) : 0
437 const notice = isSend
438 ? noticeCard(width, 'card-warning', 'Send with open questions?', `${open} of ${total} questions are unanswered and go out as "(unanswered)".`, reserve)
439 : noticeCard(width, 'card-error', 'Discard this round?', 'The panel stops offering it; /grill brings it back with its answers.', reserve)
440 if (isRoomy) {
441 return drawLayered(ui, 'notice', notice, width, [{ side: 'right', children: buttons }])
442 }
443
444 return (
445 <Box flexDirection="column" rowGap={1}>
446 {drawCards(ui, notice, width)}
447 <Box flexDirection="row" columnGap={1}>
448 {buttons}
449 </Box>
450 </Box>
451 )
452 }
453
454 if (value.mode === 'review') {
455 return drawRemoteReview($, ui, value, width)
456 }
457
458 return drawRemoteQuestion($, ui, value, typed, width)
459}
460
461// A choice saved earlier comes back as its letter, so Enter keeps it and the
462// preview names it; Enter on an empty field would take the recommendation.
463function fieldValueOf(value: Round, question: Question): string {
464 const answer = value.answers[value.current] ?? null
465 if (value.prefill !== null) {
466 return value.prefill
467 }
468 if (answer?.kind !== 'text') {
469 return ''
470 }
471 const choice = choicesOf(question.body).options.find(i => choiceAnswerOf(i) === answer.text)
472
473 return choice?.letter ?? answer.text
474}
475
476function drawRemoteQuestion($: EngineInterface, ui: RemoteElements, value: Round, typed: Draft | null, width: number): RenderElement {
477 const { Box, Button, Input, Text } = ui
478 const question = value.questions[value.current]
479 if (question === undefined) {
480 return <Text dimColor>No open question round. /grill brings back the latest one.</Text>
481 }
482 const total = value.questions.length
483 const answer = value.answers[value.current] ?? null
484 const hasChoices = choicesOf(question.body).options.length > 0
485 const start = startOf(value)
486 const field = fieldOf(value)
487 const fieldValue = fieldValueOf(value, question)
488 const shown = typed?.field === field ? typed.text : fieldValue
489 const typedChoice = choiceOf(shown, question)
490 // The desktop's field is a single line, so a longer answer scrolls out of
491 // sight; the card beneath it shows the whole of what Enter will save.
492 const preview = shown.trim().length > 0 ? previewCard(width, shown.trim(), typedChoice) : []
493 const isRoomy = width >= ROOMY_WIDTH
494 const steps = value.questions.map((_, index) => drawStep($, ui, value, index))
495 const stepsFit = isRoomy && buttonWidthOf(value.questions.map((_, index) => stepLabelOf(value, index))) <= (width - 2 * PAD) / 2
496 const title = question.title.length > 0 ? question.title : `Question ${question.number}`
497 const isAccepted = answer?.kind === 'recommendation'
498 const recommendationButtons = [
499 <Button
500 key="accept-recommendation"
501 variant="primary"
502 {...(start === 'accept-recommendation' ? { autoFocus: true as const } : {})}
503 label={isAccepted ? '✓ Accepted' : isRoomy ? '✓ Accept' : '✓ Accept recommendation'}
504 onPress={e => submit($, '', e.surface)}
505 />,
506 <Button key="edit-recommendation" label={isRoomy ? '✎ Edit' : '✎ Edit before saving'} onPress={e => useRecommendation($, e.surface)} />,
507 ]
508 const input = (
509 <Input
510 key={field}
511 value={fieldValue}
512 placeholder={hasChoices ? 'A letter, or your own answer' : 'Your answer'}
513 submitLabel="Save"
514 {...(start === field ? { autoFocus: true as const } : {})}
515 onInput={text => {
516 void update($, draft, () => ({ field, text }))
517 }}
518 onSubmit={(text, e) => {
519 void submit($, text, e.surface)
520 }}
521 />
522 )
523 const skipButton = <Button key="skip" dimColor label="↷ Skip for now" onPress={e => skip($, e.surface)} />
524 const endButtons = [
525 <Button key="send" dimColor label="➤ Send now…" onPress={() => requestSend($)} />,
526 <Button key="discard" dimColor hover={DISCARD_HOVER} label="✕ Discard" onPress={() => requestDiscard($)} />,
527 ]
528
529 return (
530 <Box flexDirection="column" rowGap={1}>
531 {stepsFit ? (
532 drawHeader(ui, value, width, `QUESTION ${value.current + 1} OF ${total}`, title, steps)
533 ) : (
534 <Box flexDirection="column" rowGap={1}>
535 {drawHeader(ui, value, width, `QUESTION ${value.current + 1} OF ${total}`, title)}
536 <Box flexDirection="row" columnGap={1} flexWrap="wrap">
537 {steps}
538 </Box>
539 </Box>
540 )}
541 {drawCards(ui, questionCards(width, question, answer), width)}
542 {question.recommendation !== null &&
543 (isRoomy ? (
544 drawLayered(ui, 'recommendation', recommendationCards(width, question.recommendation, isAccepted, buttonWidthOf([isAccepted ? '✓ Accepted' : '✓ Accept', '✎ Edit'])), width, [
545 { side: 'right', children: recommendationButtons },
546 ])
547 ) : (
548 <Box flexDirection="column" rowGap={1}>
549 {drawCards(ui, recommendationCards(width, question.recommendation, isAccepted), width)}
550 <Box flexDirection="row" columnGap={1} flexWrap="wrap">
551 {recommendationButtons}
552 </Box>
553 </Box>
554 ))}
555 {isRoomy ? (
556 <Box key="answer-card" flexDirection="column">
557 {drawCards(ui, [fieldCard(width, 'YOUR ANSWER', hasChoices ? 'A letter or your own words · Enter saves' : 'Enter saves it', FIELD_LABEL_WIDTH)], width)}
558 <Box position="absolute" top={0} bottom={0} left={columnsOf(FIELD_LABEL_WIDTH)} right={2} flexDirection="column" justifyContent="center">
559 {input}
560 </Box>
561 </Box>
562 ) : (
563 <Box flexDirection="column" alignItems="stretch" rowGap={0}>
564 <Text bold dimColor>
565 {hasChoices ? 'YOUR ANSWER · A LETTER OR YOUR OWN WORDS' : 'YOUR ANSWER'}
566 </Text>
567 {input}
568 </Box>
569 )}
570 {drawCards(ui, preview, width)}
571 {isRoomy ? (
572 drawLayered(ui, 'controls', [barCard(width, 'Skip, send or discard the round')], width, [
573 { side: 'left', children: [skipButton] },
574 { side: 'right', children: endButtons },
575 ])
576 ) : (
577 <Box flexDirection="row" justifyContent="space-between" flexWrap="wrap" columnGap={1}>
578 {skipButton}
579 <Box flexDirection="row" columnGap={1}>
580 {endButtons}
581 </Box>
582 </Box>
583 )}
584 </Box>
585 )
586}
587
588function drawRemoteReview($: EngineInterface, ui: RemoteElements, value: Round, width: number): RenderElement {
589 const { Box, Button, Text } = ui
590 const total = value.questions.length
591 const open = openCount(value)
592 const isRoomy = width >= ROOMY_WIDTH
593 const sendButton = <Button key="send" variant="primary" autoFocus label="➤ Send to Claude" onPress={() => requestSend($)} />
594 const discardButton = <Button key="discard" dimColor hover={DISCARD_HOVER} label="✕ Discard round" onPress={() => requestDiscard($)} />
595 const editOf = (index: number, label: string) => <Button key={`edit-${index}`} dimColor label={label} onPress={e => edit($, index, e.surface)} />
596 const header = drawHeader(ui, value, width, 'REVIEW', open === 0 ? 'All questions answered' : `${open} of ${total} unanswered`)
597
598 if (isRoomy) {
599 const reserve = buttonWidthOf(['✎ Edit'])
600
601 return (
602 <Box flexDirection="column" rowGap={1}>
603 {header}
604 {value.questions.map((question, index) =>
605 drawLayered(ui, `review-${index}`, [reviewCard(width, index, question, value.answers[index] ?? null, reserve)], width, [{ side: 'right', children: [editOf(index, '✎ Edit')] }]),
606 )}
607 {drawLayered(ui, 'review-controls', [barCard(width, 'Send the answers or discard the round')], width, [
608 { side: 'left', children: [sendButton] },
609 { side: 'right', children: [discardButton] },
610 ])}
611 </Box>
612 )
613 }
614
615 return (
616 <Box flexDirection="column" rowGap={1}>
617 {header}
618 <Box flexDirection="row" columnGap={1} flexWrap="wrap" alignItems="center">
619 <Text bold dimColor>
620 EDIT
621 </Text>
622 {value.questions.map((_, index) => editOf(index, `✎ ${index + 1}`))}
623 </Box>
624 {drawCards(
625 ui,
626 value.questions.map((question, index) => reviewCard(width, index, question, value.answers[index] ?? null)),
627 width,
628 )}
629 <Box flexDirection="row" justifyContent="space-between" alignItems="center">
630 {sendButton}
631 {discardButton}
632 </Box>
633 </Box>
634 )
635}
636
637export const register: Register = on => {
638 on('session.start', async ($, e, next) => {
639 await $.command.register({
640 name: 'grill',
641 description: 'Open the panel for the open question round, or bring back the latest one',
642 immediate: true,
643 })
644 await prune($)
645 await restore($)
646 await report($)
647
648 return next(e)
649 })
650
651 // An in-process /resume or /clear starts no new session.start; the round on
652 // screen belongs to the conversation that was left.
653 on('classic.SessionStart', async ($, e, next) => {
654 const result = await next(e)
655 if (e.source === 'clear' || e.source === 'resume') {
656 await reset($)
657 }
658 if (e.source === 'resume') {
659 await restore($)
660 }
661
662 return result
663 })
664
665 on('turn.complete', async ($, e, next) => {
666 const result = await next(e)
667 if (e.agentId !== undefined || e.reason !== 'answer') {
668 return result
669 }
670 const questions = parseQuestions(e.answer)
671 if (questions.length > 0 && (await begin($, questions, false))) {
672 await openPane($)
673 }
674
675 return result
676 })
677
678 on('skill.prompt', { skill: 'grilling' }, async ($, e, next) => {
679 const result = await next(e)
680
681 return { text: `${result.text}\n\n${FORMAT_CONTRACT}` }
682 })
683
684 on('command.run', { command: 'grill' }, async $ => {
685 await openGrill($)
686
687 return {}
688 })
689
690 on('ui.press', { plugin: 'mod-hub', element: 'grill-panel:open' }, async ($, e, next) => {
691 await openGrill($)
692
693 return next(e)
694 })
695
696 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
697 const value = await read($, round)
698 if (e.surface === 'mobile') {
699 const { Text } = $.ui.resolve(e)
700
701 return <Text dimColor>This app draws no text field; answer this round in the terminal or the desktop app.</Text>
702 }
703 if (e.surface !== 'terminal') {
704 const remote = $.ui.resolve(e)
705 if (value === null) {
706 return <remote.Text dimColor>No open question round. /grill brings back the latest one.</remote.Text>
707 }
708
709 return drawRemote($, remote, value, await read($, draft), cardWidthOf(e.props.bodyColumns))
710 }
711 const { Box, Button, Input, Markdown, Text } = $.ui.resolve(e)
712 if (value === null) {
713 return <Text dimColor>No open question round. /grill brings back the latest one.</Text>
714 }
715 const total = value.questions.length
716 const open = openCount(value)
717
718 if (value.mode === 'sending') {
719 return <Text dimColor>Sending… Claude gets the answers as soon as it is free.</Text>
720 }
721
722 if (value.mode === 'confirm-send') {
723 return (
724 <Box flexDirection="column">
725 <Text>{`${open} of ${total} questions are unanswered and go out as "(unanswered)".`}</Text>
726 <Box flexDirection="row" columnGap={2} marginTop={1}>
727 <Button key="confirm-send" variant="primary" autoFocus label="Send anyway" onPress={() => send($)} />
728 <Button key="cancel" label="Keep answering" onPress={e => cancel($, e.surface)} />
729 </Box>
730 </Box>
731 )
732 }
733
734 if (value.mode === 'confirm-discard') {
735 return (
736 <Box flexDirection="column">
737 <Text>Discard this round? The panel stops offering it; /grill brings it back with its answers.</Text>
738 <Box flexDirection="row" columnGap={2} marginTop={1}>
739 <Button key="cancel" autoFocus label="Keep round" onPress={e => cancel($, e.surface)} />
740 <Button key="confirm-discard" label="Discard" onPress={() => discard($)} />
741 </Box>
742 </Box>
743 )
744 }
745
746 if (value.mode === 'review') {
747 return (
748 <Box flexDirection="column">
749 <Text bold>{open === 0 ? 'All questions answered' : `${open} of ${total} unanswered`}</Text>
750 {value.questions.map((question, index) => (
751 <Button
752 key={`edit-${index}`}
753 plain
754 {...(index < 9 ? { hotkey: String(index + 1) } : {})}
755 onPress={e => edit($, index, e.surface)}
756 >
757 {`${headingOf(question)}: `}
758 <Text dimColor>{previewOf(value.answers[index] ?? null)}</Text>
759 </Button>
760 ))}
761 <Box flexDirection="row" columnGap={2} marginTop={1}>
762 <Button key="send" variant="primary" autoFocus label="Send to Claude" onPress={() => requestSend($)} />
763 <Button key="discard" dimColor label="Discard round" onPress={() => requestDiscard($)} />
764 </Box>
765 <Text dimColor>A digit edits that answer · Enter sends</Text>
766 </Box>
767 )
768 }
769
770 const question = value.questions[value.current]
771 if (question === undefined) {
772 return <Text dimColor>No open question round. /grill brings back the latest one.</Text>
773 }
774 const answer = value.answers[value.current] ?? null
775 const previous = value.questions[value.current - 1]
776 const placeholder =
777 question.recommendation === null
778 ? 'Your answer'
779 : answer?.kind === 'recommendation'
780 ? 'Enter keeps the recommendation'
781 : 'Your answer · Enter on an empty field takes the recommendation'
782
783 return (
784 <Box flexDirection="column">
785 <Box flexDirection="column" marginBottom={1}>
786 {value.questions.map((item, index) => (
787 <Text bold={index === value.current} dimColor={index !== value.current} wrap="truncate-end">
788 {`${markOf(value, index)} ${headingOf(item)}`}
789 </Text>
790 ))}
791 </Box>
792 <Text bold>{headingOf(question)}</Text>
793 {question.body.length > 0 && <Markdown text={question.body} />}
794 {question.recommendation !== null && <Markdown dimColor text={`➡️ ${question.recommendation}`} />}
795 <Box flexDirection="column" marginTop={1}>
796 {previous !== undefined && (
797 <Button key="back" plain dimColor label={`◀ ${headingOf(previous)}`} onPress={e => back($, e.surface)} />
798 )}
799 <Input
800 key="answer"
801 value={value.prefill ?? (answer?.kind === 'text' ? answer.text : '')}
802 placeholder={placeholder}
803 submitLabel="save"
804 autoFocus
805 onSubmit={(text, e) => {
806 void submit($, text, e.surface)
807 }}
808 />
809 <Box flexDirection="row" columnGap={2} flexWrap="wrap">
810 <Button key="skip" label="Skip ▶" onPress={e => skip($, e.surface)} />
811 {question.recommendation !== null && (
812 <Button key="edit-recommendation" label="Edit recommendation" onPress={e => useRecommendation($, e.surface)} />
813 )}
814 <Button key="send" label="Send…" onPress={() => requestSend($)} />
815 <Button key="discard" dimColor label="Discard round" onPress={() => requestDiscard($)} />
816 </Box>
817 </Box>
818 <Text dimColor>{`${total - open}/${total} answered · Enter saves · Shift+Tab goes back · Esc closes, /grill reopens`}</Text>
819 </Box>
820 )
821 })
822
823 // The terminal draws the mode labels itself, so the label joins them there.
824 // On the desktop, status-band draws the footer from the labels it was handed,
825 // whichever order the mods load in; only a drawn tree survives that.
826 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
827 const current = await read($, round)
828 if (current === null) {
829 return next(e)
830 }
831 const label = footerOf(current)
832 if (e.surface === 'terminal') {
833 return next({ ...e, props: { ...e.props, modes: [...e.props.modes, label] } })
834 }
835 if (await read($, isHubbed)) {
836 return next(e)
837 }
838 const below = await next(e)
839 const { Box, Text } = $.ui.resolve(e)
840 const rest = below.type !== 'engine' ? below : e.props.modes.length === 0 ? null : <Text dimColor>{e.props.modes.join(' & ')}</Text>
841
842 return (
843 <Box flexDirection="row">
844 <Text dimColor>{label}</Text>
845 {rest !== null && <Text dimColor> · </Text>}
846 {rest}
847 </Box>
848 )
849 })
850}
851hooks/hub.ts 12 lines1// mod-hub's contract, restated: listed under dependencies, it would keep this
2// mod from loading where mod-hub is not installed.
3export type HubEntry = {
4 icon: string
5 title: string
6 status: string
7 attention: 'none' | 'info' | 'warning'
8 actions: { key: string; label: string }[]
9}
10
11export type HubCall = { hub: { set: (entry: HubEntry & { id: string }) => Promise<void> } }
12hooks/rounds.ts 376 lines1import type { Answer, Question, Round, StoredRound } from '../types'
2
3// Appended to the grilling skill's prompt rather than written into the skill,
4// whose file is replaced whenever it is updated from upstream.
5export const FORMAT_CONTRACT = `## Answer panel
6
7The grill-panel mod reads each question round from your message, lets the user answer it in a panel, and sends the answers back as \`Q<n>: <answer>\` lines. It only finds questions written exactly like this:
8
9- Every question starts on a line of its own with \`❓ **Q<n>** - **<title>**: <body>\`; no number repeats within one message.
10- The recommendation follows on a line of its own starting with \`➡️\` and ends at the next blank line.
11- Text after the last recommendation, separated by a blank line, belongs to no question.
12
13An answer of \`Recommendation accepted\` means the user took your recommendation as written. \`(unanswered)\` means the user left that question open: ask it again in a later round if it still matters.`
14
15const HEADER = /^\s*(❓\uFE0F?\s*)?(\*\*)?Q(\d{1,3})(?!\d)(.*)$/u
16const RECOMMENDATION = /^\s*➡\uFE0F?\s*/u
17const SEPARATOR = /^\s*(-{3,}|\*{3,}|_{3,})\s*$/
18const FENCE = /^\s*(```|~~~)/
19
20type Draft = {
21 number: number
22 title: string
23 hasMark: boolean
24 body: string[]
25 recommendation: string[] | null
26 isClosed: boolean
27}
28
29export function parseQuestions(text: string): Question[] {
30 const drafts: Draft[] = []
31 let isInFence = false
32 for (const line of text.replace(/\r\n?/g, '\n').split('\n')) {
33 const isCode = isInFence || FENCE.test(line)
34 if (FENCE.test(line)) {
35 isInFence = !isInFence
36 }
37 const header = isCode ? undefined : headerOf(line)
38 if (header !== undefined) {
39 drafts.push(header)
40 continue
41 }
42 const draft = drafts.at(-1)
43 if (draft === undefined || draft.isClosed) {
44 continue
45 }
46 if (draft.recommendation !== null) {
47 if (!isCode && (line.trim().length === 0 || SEPARATOR.test(line))) {
48 draft.isClosed = true
49 } else {
50 draft.recommendation.push(line)
51 }
52 continue
53 }
54 if (!isCode && RECOMMENDATION.test(line)) {
55 draft.recommendation = [line.replace(RECOMMENDATION, '')]
56 continue
57 }
58 if (!isCode && SEPARATOR.test(line)) {
59 draft.isClosed = true
60 continue
61 }
62 draft.body.push(line)
63 }
64 // A bold "**Q3**" alone also turns up in ordinary prose; only the question
65 // mark or a recommendation makes it a round.
66 if (!drafts.some(i => i.hasMark || i.recommendation !== null)) {
67 return []
68 }
69
70 return drafts.map(i => {
71 const recommendation = i.recommendation === null ? '' : i.recommendation.join('\n').trim()
72
73 return {
74 number: i.number,
75 title: i.title,
76 body: i.body.join('\n').trim(),
77 recommendation: recommendation.length === 0 ? null : recommendation,
78 }
79 })
80}
81
82// Accepts "❓ **Q1** - **Title**: body" and the variants a model drifts into:
83// "**Q2 (updated)** - **Title**", "**Q3 – Title**", "❓ Q4 - Title: body".
84function headerOf(line: string): Draft | undefined {
85 const match = HEADER.exec(line)
86 if (match === null) {
87 return undefined
88 }
89 const [, mark, bold, digits = '', rest = ''] = match
90 if (mark === undefined && bold === undefined) {
91 return undefined
92 }
93 let title = ''
94 let remainder = rest
95 if (bold !== undefined) {
96 const end = remainder.indexOf('**')
97 if (end !== -1) {
98 const inner = stripSeparators(remainder.slice(0, end))
99 if (!inner.startsWith('(')) {
100 title = inner
101 }
102 remainder = remainder.slice(end + 2)
103 }
104 }
105 remainder = stripSeparators(remainder)
106 if (remainder.startsWith('**')) {
107 const end = remainder.indexOf('**', 2)
108 if (end !== -1) {
109 title = remainder.slice(2, end)
110 remainder = stripSeparators(remainder.slice(end + 2))
111 }
112 } else if (bold === undefined) {
113 const colon = remainder.indexOf(':')
114 if (colon > 0 && colon <= 80) {
115 title = remainder.slice(0, colon)
116 remainder = remainder.slice(colon + 1).trim()
117 }
118 }
119
120 return {
121 number: Number(digits),
122 title: title.trim().replace(/:$/, '').trim(),
123 hasMark: mark !== undefined,
124 body: remainder.length > 0 ? [remainder] : [],
125 recommendation: null,
126 isClosed: false,
127 }
128}
129
130function stripSeparators(text: string): string {
131 return text.replace(/^[\s:\-–—]+/u, '')
132}
133
134type TranscriptMessage = { role: 'user' | 'assistant'; text: string }
135
136// The round a resumed conversation ends on: only Claude's last words count, so a
137// round the user already answered by hand is not offered again.
138export function lastRoundIn(messages: readonly TranscriptMessage[]): Question[] {
139 for (let index = messages.length - 1; index >= 0; index--) {
140 const message = messages[index]
141 if (message?.role === 'assistant' && message.text.trim().length > 0) {
142 return parseQuestions(message.text)
143 }
144 }
145
146 return []
147}
148
149export function latestRoundIn(messages: readonly TranscriptMessage[]): Question[] {
150 for (let index = messages.length - 1; index >= 0; index--) {
151 const message = messages[index]
152 if (message?.role !== 'assistant') {
153 continue
154 }
155 const questions = parseQuestions(message.text)
156 if (questions.length > 0) {
157 return questions
158 }
159 }
160
161 return []
162}
163
164// The project root is part of the key, so the same wording asked in two
165// projects keeps two sets of answers.
166export function roundKeyOf(root: string, questions: readonly Question[]): string {
167 return hashOf(JSON.stringify([root, questions.map(i => [i.number, i.title, i.body, i.recommendation])]))
168}
169
170// cyrb53: no crypto in the hooks environment, and the key only has to keep
171// rounds apart, not resist anyone.
172export function hashOf(text: string): string {
173 let first = 0xdeadbeef
174 let second = 0x41c6ce57
175 for (let index = 0; index < text.length; index++) {
176 const code = text.charCodeAt(index)
177 first = Math.imul(first ^ code, 2654435761)
178 second = Math.imul(second ^ code, 1597334677)
179 }
180 first = Math.imul(first ^ (first >>> 16), 2246822507) ^ Math.imul(second ^ (second >>> 13), 3266489909)
181 second = Math.imul(second ^ (second >>> 16), 2246822507) ^ Math.imul(first ^ (first >>> 13), 3266489909)
182
183 return (4294967296 * (2097151 & second) + (first >>> 0)).toString(36)
184}
185
186export function newRound(key: string, questions: readonly Question[], answers: readonly (Answer | null)[]): Round {
187 return resume({
188 key,
189 questions: [...questions],
190 answers: questions.map((_, index) => answers[index] ?? null),
191 skipped: questions.map(() => false),
192 current: 0,
193 mode: 'answer',
194 prefill: null,
195 })
196}
197
198// Back to answering where it makes sense: the question in view while it is
199// still open, else the first open one, else the review.
200export function resume(round: Round): Round {
201 const index = round.answers[round.current] === null ? round.current : round.answers.indexOf(null)
202
203 return index === -1 ? toReview(round) : { ...round, current: index, mode: 'answer', prefill: null }
204}
205
206// A lone letter for a question with choices stands for that choice, so Claude
207// reads "(b) A day off" rather than a bare "b".
208export function choiceOf(text: string, question: Question): Choice | undefined {
209 const letter = LETTER_ANSWER.exec(text.trim())?.[1]?.toLowerCase()
210
211 return letter === undefined ? undefined : choicesOf(question.body).options.find(i => i.letter === letter)
212}
213
214export function answerOf(text: string, question: Question): Answer | null {
215 const normalized = text.replace(/\r\n?/g, '\n').trim()
216 const choice = choiceOf(normalized, question)
217 if (choice !== undefined) {
218 return { kind: 'text', text: choiceAnswerOf(choice) }
219 }
220 if (normalized.length > 0) {
221 return { kind: 'text', text: normalized }
222 }
223
224 return question.recommendation === null ? null : { kind: 'recommendation' }
225}
226
227export function answerCurrent(round: Round, text: string): Round {
228 const question = round.questions[round.current]
229 const answer = question === undefined ? null : answerOf(text, question)
230 if (round.mode !== 'answer' || answer === null) {
231 return round
232 }
233
234 return moveOn({
235 ...round,
236 answers: round.answers.map((value, index) => (index === round.current ? answer : value)),
237 skipped: round.skipped.map((value, index) => (index === round.current ? false : value)),
238 })
239}
240
241export function skipCurrent(round: Round): Round {
242 return moveOn({
243 ...round,
244 skipped: round.skipped.map((value, index) => (index === round.current ? round.answers[index] === null : value)),
245 })
246}
247
248export function goBack(round: Round): Round {
249 return round.current === 0 ? round : { ...round, current: round.current - 1, mode: 'answer', prefill: null }
250}
251
252export function editAt(round: Round, index: number): Round {
253 return index < 0 || index >= round.questions.length ? round : { ...round, current: index, mode: 'answer', prefill: null }
254}
255
256export function prefillRecommendation(round: Round): Round {
257 const recommendation = round.questions[round.current]?.recommendation ?? null
258
259 return recommendation === null ? round : { ...round, prefill: recommendation }
260}
261
262// After an answer or a skip the next open question after the current one,
263// wrapping around, so skipped questions come back once the rest are done.
264function moveOn(round: Round): Round {
265 const count = round.questions.length
266 for (let step = 1; step < count; step++) {
267 const index = (round.current + step) % count
268 if (round.answers[index] === null) {
269 return { ...round, current: index, mode: 'answer', prefill: null }
270 }
271 }
272
273 return toReview(round)
274}
275
276function toReview(round: Round): Round {
277 return { ...round, mode: 'review', prefill: null }
278}
279
280export function openCount(round: Round): number {
281 return round.answers.filter(i => i === null).length
282}
283
284export function footerOf(round: Round): string {
285 return `🔥 ${round.questions.length - openCount(round)}/${round.questions.length}`
286}
287
288export function formatAnswers(round: Pick<Round, 'questions' | 'answers'>): string {
289 return round.questions.map((question, index) => `Q${question.number}: ${answerText(round.answers[index] ?? null)}`).join('\n\n')
290}
291
292function answerText(answer: Answer | null): string {
293 if (answer === null) {
294 return '(unanswered)'
295 }
296
297 return answer.kind === 'recommendation' ? 'Recommendation accepted' : answer.text
298}
299
300export function previewOf(answer: Answer | null, length = 60): string {
301 if (answer === null) {
302 return 'unanswered'
303 }
304 if (answer.kind === 'recommendation') {
305 return 'recommendation accepted'
306 }
307 const [first = ''] = answer.text.split('\n')
308 const cut = first.length > length ? `${first.slice(0, length - 1)}…` : first
309
310 return answer.text.includes('\n') && cut === first ? `${cut} …` : cut
311}
312
313export type Choice = { letter: string; text: string }
314
315export type Choices = { lead: string; options: Choice[]; trail: string }
316
317// "(a)" anywhere, or "a)", "a." and "A)" opening a line or a list item, bold or not.
318const CHOICE_MARK = /(^|\s)\(([a-z])\)\s+|(^|\n)([ \t]*(?:[-*•+][ \t]+)?(?:\*\*|__)?)([a-z])[).](?:\*\*|__)?[ \t]+/giu
319const CHOICE_EDGE = /[\s,;\-–—•*]+$/u
320const RECOMMENDED_CHOICE = /^[\s*_]*\(?([a-z])[).](?![a-z])/iu
321const LINE_START = /\n(?=\S)/u
322const LETTER_ANSWER = /^\(?([a-z])\)?\.?$/iu
323
324// Models list the choices inline as "(a) … (b) …" as often as one per line,
325// and as "a) …" list items. Only a run starting at a with the letters in order
326// counts, so a stray "(b)" in the question text is left where it is. The last
327// choice ends with its line (indented lines continue it), so a closing
328// paragraph stays apart.
329export function choicesOf(body: string): Choices {
330 const marks: { start: number; end: number; letter: string }[] = []
331 for (const match of body.matchAll(CHOICE_MARK)) {
332 const [whole, space, inlineLetter, lineStart, prefix = '', lineLetter] = match
333 const letter = (inlineLetter ?? lineLetter ?? '').toLowerCase()
334 const offset = space !== undefined ? space.length : (lineStart ?? '').length + prefix.length
335 if (letter === String.fromCharCode(97 + marks.length)) {
336 marks.push({ start: match.index + offset, end: match.index + whole.length, letter })
337 }
338 }
339 const first = marks[0]
340 const last = marks.at(-1)
341 if (first === undefined || last === undefined || marks.length < 2) {
342 return { lead: body, options: [], trail: '' }
343 }
344 const lineEnd = body.slice(last.end).search(LINE_START)
345 const end = lineEnd === -1 ? body.length : last.end + lineEnd
346
347 return {
348 lead: body.slice(0, first.start).replace(CHOICE_EDGE, ''),
349 options: marks.map((mark, index) => ({
350 letter: mark.letter,
351 text: body
352 .slice(mark.end, marks[index + 1]?.start ?? end)
353 .replace(CHOICE_EDGE, '')
354 .replace(/\s+/gu, ' '),
355 })),
356 trail: body.slice(end).trim(),
357 }
358}
359
360export function recommendedLetterOf(recommendation: string | null): string | null {
361 return recommendation === null ? null : (RECOMMENDED_CHOICE.exec(recommendation)?.[1]?.toLowerCase() ?? null)
362}
363
364export function choiceAnswerOf(choice: Choice): string {
365 return `(${choice.letter}) ${choice.text}`
366}
367
368export function isStoredRound(value: unknown): value is StoredRound {
369 if (typeof value !== 'object' || value === null) {
370 return false
371 }
372 const candidate = value as Partial<StoredRound>
373
374 return (candidate.status === 'open' || candidate.status === 'done') && Array.isArray(candidate.answers) && typeof candidate.updatedAt === 'number'
375}
376hooks/look.ts 147 lines1import type { Answer, Question } from '../types'
2import { choiceAnswerOf, choicesOf, recommendedLetterOf } from './rounds'
3import type { Choice } from './rounds'
4import { LINE, PAD, SIZE, blockSections, cards, escape, eyebrowSection, eyebrowSvg, eyebrowWidth, fitText, frame, parseBlocks, parseInline, plainOf, svgDocument, textSection, textWidth } from './svg'
5import type { Card, Section, Variant } from './svg'
6
7export { barCard, buttonWidthOf, columnsOf, fieldCard, headerCard, noticeCard } from './svg'
8export type { Card, Segment } from './svg'
9
10type ChoiceState = 'plain' | 'recommended' | 'chosen'
11
12function pillSvg(text: string, right: number, y: number, tone: 'pill' | 'pill-success'): { svg: string; width: number } {
13 const width = eyebrowWidth(text) - 1 + 16
14 const label = tone === 'pill' ? 'eyebrow' : 'success'
15
16 return {
17 width,
18 svg: `<rect class="${tone}" x="${(right - width).toFixed(1)}" y="${y}" width="${width.toFixed(1)}" height="20" rx="10"/>${eyebrowSvg(text, right - width / 2, y + 14, label, 'middle')}`,
19 }
20}
21
22function choiceSection(choice: Choice, state: ChoiceState, x: number, width: number): Section {
23 const inset = 12
24 const badge = 26
25 const textX = x + inset + badge + 12
26 const pillText = state === 'recommended' ? 'RECOMMENDED' : state === 'chosen' ? 'YOUR ANSWER' : ''
27 const pillWidth = pillText.length === 0 ? 0 : eyebrowWidth(pillText) + 16 + 10
28 const textWidthMax = x + width - inset - textX
29 const text = textSection(parseInline(choice.text), textX, textWidthMax, { firstWidth: textWidthMax - pillWidth })
30 const height = Math.max(badge, text.height) + 2 * inset
31 const tile = state === 'recommended' ? 'tile-accent' : state === 'chosen' ? 'tile-success' : 'tile'
32 const circle = state === 'recommended' ? 'accent' : state === 'chosen' ? 'success' : 'badge'
33 const glyph = state === 'chosen' ? '✓' : choice.letter.toUpperCase()
34
35 return {
36 height: height + 8,
37 draw: y => {
38 const top = y + 8
39 const centerY = top + inset + badge / 2
40 const pill = pillText.length === 0 ? '' : pillSvg(pillText, x + width - inset, top + inset + 3, state === 'chosen' ? 'pill-success' : 'pill').svg
41 const textTop = top + inset + (text.height <= LINE ? (badge - LINE) / 2 : 0)
42
43 return [
44 `<rect class="${tile}" x="${x + 0.5}" y="${top + 0.5}" width="${width - 1}" height="${height - 1}" rx="11"${state === 'plain' ? '' : ' stroke-width="1.5"'}/>`,
45 `<circle class="${circle}" cx="${x + inset + badge / 2}" cy="${centerY}" r="${badge / 2}"/>`,
46 `<text class="${state === 'plain' ? 'badge-t' : 'on-accent'}" x="${x + inset + badge / 2}" y="${centerY + 4.5}" font-size="13" font-weight="700" text-anchor="middle">${escape(glyph)}</text>`,
47 text.draw(textTop),
48 pill,
49 ].join('')
50 },
51 }
52}
53
54function chosenLetterOf(options: readonly Choice[], answer: Answer | null): string | null {
55 return answer?.kind === 'text' ? (options.find(i => choiceAnswerOf(i) === answer.text)?.letter ?? null) : null
56}
57
58// The question's text with its choices drawn as tiles: the recommended one in
59// the accent color, the one already picked in green.
60export function questionCards(width: number, question: Question, answer: Answer | null): Card[] {
61 const inner = width - 2 * PAD
62 const choices = choicesOf(question.body)
63 const recommended = recommendedLetterOf(question.recommendation)
64 const chosen = chosenLetterOf(choices.options, answer) ?? (answer?.kind === 'recommendation' ? recommended : null)
65 const sections = [
66 ...blockSections(parseBlocks(choices.lead), PAD, inner),
67 ...choices.options.map(choice => choiceSection(choice, choice.letter === chosen ? 'chosen' : choice.letter === recommended && chosen === null ? 'recommended' : 'plain', PAD, inner)),
68 ...blockSections(parseBlocks(choices.trail), PAD, inner).map((section, index) => (index === 0 ? { height: section.height + 12, draw: (y: number) => section.draw(y + 12) } : section)),
69 ]
70 if (sections.length === 0) {
71 return []
72 }
73
74 return cards(width, 'card', sections, plainOf(question.body.replace(/\s+/gu, ' ')))
75}
76
77// `reserve` keeps the text clear of the native buttons laid over the right
78// side, which then also take the place of the accepted mark.
79export function recommendationCards(width: number, recommendation: string, isAccepted: boolean, reserve = 0): Card[] {
80 const letter = recommendedLetterOf(recommendation)
81 const head = letter === null ? '★ RECOMMENDATION' : `★ RECOMMENDATION · CHOICE ${letter.toUpperCase()}`
82 const sections = [
83 reserve > 0 ? eyebrowSection(isAccepted ? `${head} · ✓ ACCEPTED` : head, null, 'success', width) : eyebrowSection(head, isAccepted ? '✓ ACCEPTED' : null, 'success', width),
84 ...blockSections(parseBlocks(recommendation), PAD, width - 2 * PAD - reserve),
85 ]
86
87 return cards(width, isAccepted ? 'card-success' : 'card-accent', sections, `Recommendation: ${plainOf(recommendation.replace(/\s+/gu, ' '))}`, '', reserve > 0 ? 72 : 0)
88}
89
90// What Enter will save, wrapped: the field itself is one line, and a typed
91// letter shows the choice it stands for.
92export function previewCard(width: number, text: string, choice: Choice | undefined): Card[] {
93 const head = eyebrowSection(
94 choice === undefined ? 'YOUR ANSWER' : `SAVES CHOICE ${choice.letter.toUpperCase()}`,
95 choice === undefined ? `${Array.from(text).length} CHARACTERS` : 'ENTER',
96 'muted',
97 width,
98 )
99 const body = textSection(choice === undefined ? [{ text }] : parseInline(choice.text), PAD, width - 2 * PAD)
100
101 return cards(width, 'card', [head, body], choice === undefined ? `Your answer: ${text}` : `Saves choice ${choice.letter}: ${plainOf(choice.text)}`)
102}
103
104export function reviewCard(width: number, index: number, question: Question, answer: Answer | null, reserve = 0): Card {
105 const badge = 26
106 const x = PAD + badge + 12
107 const inner = width - x - PAD - reserve
108 const title = textSection(parseInline(question.title.length > 0 ? question.title : `Question ${question.number}`).map(i => ({ ...i, isBold: true })), x, inner, { maxLines: 2 })
109 const body =
110 answer === null
111 ? textSection([{ text: 'Unanswered · goes out as (unanswered)' }], x, inner, { tone: 'warning' })
112 : answer.kind === 'recommendation'
113 ? textSection([{ text: '★ Recommendation accepted' }], x, inner, { tone: 'accent' })
114 : textSection(parseInline(answer.text.replace(/\n+/gu, ' ')), x, inner, { maxLines: 8 })
115 const detail = answer?.kind === 'recommendation' && question.recommendation !== null ? textSection(parseInline(question.recommendation.replace(/\s+/gu, ' ')), x, inner, { tone: 'muted', maxLines: 3 }) : null
116 const height = Math.max(reserve > 0 ? 64 : 0, PAD + title.height + 4 + body.height + (detail === null ? 0 : detail.height + 2) + PAD)
117 const variant: Variant = answer === null ? 'card-warning' : 'card'
118 const circle = answer === null ? 'skipped' : 'success'
119 const centerY = PAD + badge / 2
120
121 return {
122 height,
123 alt: `${index + 1} · ${plainOf(question.title)}: ${answer === null ? 'unanswered' : answer.kind === 'recommendation' ? 'recommendation accepted' : answer.text}`,
124 source: svgDocument(
125 width,
126 height,
127 [
128 frame(width, height, variant),
129 `<circle class="${circle}" cx="${PAD + badge / 2}" cy="${centerY}" r="${badge / 2}"/>`,
130 `<text class="on-accent" x="${PAD + badge / 2}" y="${centerY + 4.5}" font-size="13" font-weight="700" text-anchor="middle">${answer === null ? index + 1 : '✓'}</text>`,
131 title.draw(PAD + 2),
132 body.draw(PAD + 2 + title.height + 4),
133 detail === null ? '' : detail.draw(PAD + 2 + title.height + 4 + body.height + 2),
134 ].join(''),
135 ),
136 }
137}
138
139export function sendingCard(width: number): Card {
140 const height = 64
141 const dots = [0, 1, 2].map(i => `<circle class="accent dot dot${i + 1}" cx="${PAD + 6 + i * 14}" cy="${height / 2}" r="4"/>`).join('')
142 const label = `<text class="t" x="${PAD + 52}" y="${height / 2 + 5}" font-size="${SIZE}" font-weight="600">Sending</text>`
143 const note = `<text class="muted" x="${PAD + 52 + textWidth('Sending', SIZE, true) + 10}" y="${height / 2 + 5}" font-size="13">${escape(fitText('Claude gets the answers as soon as it is free.', width - PAD * 2 - 62 - textWidth('Sending', SIZE, true), 13))}</text>`
144
145 return { height, alt: 'Sending… Claude gets the answers as soon as it is free.', source: svgDocument(width, height, frame(width, height, 'card-accent') + dots + label + note) }
146}
147hooks/svg.ts 603 lines1// An SVG drawn as an image cannot lay out text: no wrapping, no Markdown, no
2// measuring. This module does that by estimate and stacks the result into
3// cards. Every mod with desktop cards carries the same copy of this file.
4
5export type Run = { text: string; isBold?: boolean; isItalic?: boolean; isCode?: boolean; isLink?: boolean }
6
7export type Block =
8 | { kind: 'paragraph'; runs: Run[] }
9 | { kind: 'heading'; runs: Run[] }
10 | { kind: 'quote'; runs: Run[] }
11 | { kind: 'item'; marker: string; runs: Run[] }
12 | { kind: 'code'; lines: string[] }
13
14export const SANS = '-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif'
15export const MONO = 'ui-monospace,SFMono-Regular,Menlo,monospace'
16
17// Classes rather than colors: drawn as an image the SVG follows the light or
18// dark color scheme by itself, which a color handed in from the hook could not.
19export const STYLE = `<style>
20text{font-family:${SANS};white-space:pre}.mono{font-family:${MONO}}
21.card{fill:#f7f6f3;stroke:#e5e3de}.card-accent{fill:#fbf1ec;stroke:#e7b49c}.card-success{fill:#f1f8f3;stroke:#a9d6b8}
22.card-warning{fill:#fcf6e6;stroke:#e6cf8a}.card-error{fill:#fcefee;stroke:#e8aaa6}
23.tile{fill:#ffffff;stroke:#e5e3de}.tile-accent{fill:#ffffff;stroke:#d97757}.tile-success{fill:#ffffff;stroke:#2e9e5b}
24.t{fill:#1f1e1d}.muted{fill:#77756f}.eyebrow{fill:#c9643f}.code{fill:#a2482a}.link{fill:#c9643f}
25.success{fill:#2e9e5b}.warning{fill:#a87a06}.error{fill:#c0392b}.accent{fill:#d97757}.on-accent{fill:#ffffff}
26.badge{fill:#ecebe7}.badge-t{fill:#4a4844}.codebg{fill:#efede8}.rule{fill:#dad7d0}.pill{fill:#f6e1d7}.pill-success{fill:#dcefe2}
27.open{fill:#e4e2dc}.answered{fill:#2e9e5b}.skipped{fill:#d4a017}.current{fill:#d97757}
28.current,.pulse{animation:pulse 1.8s ease-in-out infinite}@keyframes pulse{50%{opacity:.5}}
29.ripple{transform-box:fill-box;transform-origin:center;animation:ripple 2.4s ease-out infinite}@keyframes ripple{0%{transform:scale(1);opacity:.45}100%{transform:scale(2.8);opacity:0}}
30.spin{transform-box:fill-box;transform-origin:center;animation:spin .9s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}
31.dot{animation:dot 1.2s ease-in-out infinite}.dot2{animation-delay:.2s}.dot3{animation-delay:.4s}@keyframes dot{0%,80%,100%{opacity:.25}40%{opacity:1}}
32@media (prefers-color-scheme: dark){
33.card{fill:#262625;stroke:#363632}.card-accent{fill:#2e2420;stroke:#7a4a36}.card-success{fill:#1f2a23;stroke:#2f5a3d}
34.card-warning{fill:#2c2717;stroke:#6a5a24}.card-error{fill:#2e1f1e;stroke:#6e3430}
35.tile{fill:#1e1e1d;stroke:#3a3a36}.tile-accent{fill:#1e1e1d;stroke:#e08a6a}.tile-success{fill:#1e1e1d;stroke:#3fb36b}
36.t{fill:#ecebe8}.muted{fill:#a5a39d}.eyebrow{fill:#e8916f}.code{fill:#f0a283}.link{fill:#e8916f}
37.success{fill:#4cc27a}.warning{fill:#e2b33c}.error{fill:#e8746a}.accent{fill:#e08a6a}.on-accent{fill:#1f1e1d}
38.badge{fill:#34342f}.badge-t{fill:#d6d4cf}.codebg{fill:#1c1c1b}.rule{fill:#45443f}.pill{fill:#4a3328}.pill-success{fill:#24432f}
39.open{fill:#3a3a37}.answered{fill:#3fb36b}.skipped{fill:#d4a017}.current{fill:#e08a6a}}
40@media (prefers-reduced-motion: reduce){.current,.pulse,.dot,.ripple,.spin{animation:none}}
41</style>`
42
43// Widths are estimated from the font size, on the wide side: a line then ends
44// a little early rather than past the card's edge.
45export function textWidth(text: string, size: number, isBold = false, isMono = false): number {
46 if (isMono) {
47 return Array.from(text).length * size * 0.62
48 }
49 let units = 0
50 for (const char of text) {
51 if (/[\s.,:;'|!ijlI]/u.test(char)) {
52 units += 0.3
53 } else if (/[A-Z@%&MWmw]/u.test(char)) {
54 units += 0.74
55 } else if (/\p{Extended_Pictographic}/u.test(char)) {
56 units += 1.15
57 } else {
58 units += 0.53
59 }
60 }
61
62 return units * size * (isBold ? 1.04 : 1)
63}
64
65function runWidth(run: Run, size: number): number {
66 return textWidth(run.text, size, run.isBold === true, run.isCode === true)
67}
68
69export function fitText(text: string, maxWidth: number, size: number, isBold = false): string {
70 if (textWidth(text, size, isBold) <= maxWidth) {
71 return text
72 }
73 const chars = Array.from(text)
74 while (chars.length > 0 && textWidth(`${chars.join('')}…`, size, isBold) > maxWidth) {
75 chars.pop()
76 }
77
78 return `${chars.join('').trimEnd()}…`
79}
80
81export function escape(text: string): string {
82 return text.replace(/&/gu, '&').replace(/</gu, '<').replace(/>/gu, '>').replace(/"/gu, '"')
83}
84
85const INLINE = /(\*\*[^*]+?\*\*|__[^_]+?__|`[^`]+`|\[[^\]]+\]\([^)\s]+\)|(?<![\w*])\*(?!\s)[^*]+?(?<!\s)\*(?!\w))/gu
86
87export function parseInline(text: string): Run[] {
88 const runs: Run[] = []
89 let last = 0
90 for (const match of text.matchAll(INLINE)) {
91 const [token] = match
92 if (match.index > last) {
93 runs.push({ text: text.slice(last, match.index) })
94 }
95 if (token.startsWith('**') || token.startsWith('__')) {
96 runs.push(...parseInline(token.slice(2, -2)).map(i => ({ ...i, isBold: true })))
97 } else if (token.startsWith('`')) {
98 runs.push({ text: token.slice(1, -1), isCode: true })
99 } else if (token.startsWith('[')) {
100 runs.push({ text: token.slice(1, token.indexOf('](')), isLink: true })
101 } else {
102 runs.push(...parseInline(token.slice(1, -1)).map(i => ({ ...i, isItalic: true })))
103 }
104 last = match.index + token.length
105 }
106 if (last < text.length) {
107 runs.push({ text: text.slice(last) })
108 }
109
110 return runs.filter(i => i.text.length > 0)
111}
112
113export function plainOf(text: string): string {
114 return parseInline(text)
115 .map(i => i.text)
116 .join('')
117}
118
119const ITEM = /^\s*([-*•+]|\d{1,3}[.)])\s+(.*)$/u
120const HEADING = /^\s{0,3}#{1,6}\s+(.*)$/u
121const QUOTE = /^\s*>\s?(.*)$/u
122const FENCE = /^\s*(```|~~~)/u
123
124// Single line breaks join a paragraph, as Markdown reads them; a list item,
125// heading, quote or code fence starts a block of its own.
126export function parseBlocks(markdown: string): Block[] {
127 const blocks: Block[] = []
128 let paragraph: string[] = []
129 let item: { marker: string; text: string[] } | null = null
130 let quote: string[] = []
131 const flush = () => {
132 if (paragraph.length > 0) {
133 blocks.push({ kind: 'paragraph', runs: parseInline(paragraph.join(' ')) })
134 }
135 if (item !== null) {
136 blocks.push({ kind: 'item', marker: item.marker, runs: parseInline(item.text.join(' ')) })
137 }
138 if (quote.length > 0) {
139 blocks.push({ kind: 'quote', runs: parseInline(quote.join(' ')) })
140 }
141 paragraph = []
142 item = null
143 quote = []
144 }
145 const lines = markdown.replace(/\r\n?/gu, '\n').split('\n')
146 for (let index = 0; index < lines.length; index++) {
147 const line = lines[index] ?? ''
148 if (FENCE.test(line)) {
149 flush()
150 const code: string[] = []
151 index += 1
152 while (index < lines.length && !FENCE.test(lines[index] ?? '')) {
153 code.push(lines[index] ?? '')
154 index += 1
155 }
156 blocks.push({ kind: 'code', lines: code })
157 continue
158 }
159 if (line.trim().length === 0) {
160 flush()
161 continue
162 }
163 const heading = HEADING.exec(line)
164 if (heading !== null) {
165 flush()
166 blocks.push({ kind: 'heading', runs: parseInline(heading[1] ?? '') })
167 continue
168 }
169 const listed = ITEM.exec(line)
170 if (listed !== null) {
171 flush()
172 const marker = listed[1] ?? '-'
173 item = { marker: /\d/u.test(marker) ? marker : '•', text: [listed[2] ?? ''] }
174 continue
175 }
176 const quoted = QUOTE.exec(line)
177 if (quoted !== null) {
178 if (quote.length === 0) {
179 flush()
180 }
181 quote.push(quoted[1] ?? '')
182 continue
183 }
184 if (item !== null && /^\s+\S/u.test(line)) {
185 item.text.push(line.trim())
186 continue
187 }
188 if (item !== null || quote.length > 0) {
189 flush()
190 }
191 paragraph.push(line.trim())
192 }
193 flush()
194
195 return blocks
196}
197
198type Word = Run & { hasSpace: boolean }
199
200function wordsOf(runs: readonly Run[]): Word[] {
201 const words: Word[] = []
202 for (const run of runs) {
203 for (const piece of run.text.split(/(\s+)/u)) {
204 if (piece.length === 0) {
205 continue
206 }
207 if (/^\s+$/u.test(piece)) {
208 const previous = words.at(-1)
209 if (previous !== undefined) {
210 previous.hasSpace = true
211 }
212 continue
213 }
214 words.push({ ...run, text: piece, hasSpace: false })
215 }
216 }
217
218 return words
219}
220
221function sameStyle(first: Run, second: Run): boolean {
222 return first.isBold === second.isBold && first.isItalic === second.isItalic && first.isCode === second.isCode && first.isLink === second.isLink
223}
224
225function breakWord(word: Word, maxWidth: number, size: number): Word[] {
226 const pieces: Word[] = []
227 let current = ''
228 for (const char of word.text) {
229 if (current.length > 0 && runWidth({ ...word, text: current + char }, size) > maxWidth) {
230 pieces.push({ ...word, text: current, hasSpace: false })
231 current = ''
232 }
233 current += char
234 }
235 pieces.push({ ...word, text: current })
236
237 return pieces
238}
239
240// Greedy, word by word; a word wider than the line is broken by characters.
241// `firstWidth` keeps the first line clear of a badge drawn at its end.
242export function wrapRuns(runs: readonly Run[], maxWidth: number, size: number, firstWidth = maxWidth): Run[][] {
243 const lines: Word[][] = []
244 let line: Word[] = []
245 let width = 0
246 const space = textWidth(' ', size)
247 const words = wordsOf(runs).flatMap(i => (runWidth(i, size) > maxWidth ? breakWord(i, maxWidth, size) : [i]))
248 for (const word of words) {
249 const previous = line.at(-1)
250 const gap = previous?.hasSpace === true ? space : 0
251 const wordWidth = runWidth(word, size)
252 if (line.length > 0 && width + gap + wordWidth > (lines.length === 0 ? firstWidth : maxWidth)) {
253 lines.push(line)
254 line = []
255 width = 0
256 }
257 width += (line.length > 0 ? gap : 0) + wordWidth
258 line.push(word)
259 }
260 if (line.length > 0) {
261 lines.push(line)
262 }
263
264 // The space after a code span is drawn in the text's font, not the code's
265 // wider one.
266 return lines.map(words => {
267 const merged: Run[] = []
268 const append = (run: Run) => {
269 const previous = merged.at(-1)
270 if (previous !== undefined && sameStyle(previous, run)) {
271 previous.text += run.text
272 } else {
273 merged.push({ ...run })
274 }
275 }
276 words.forEach((word, index) => {
277 const { hasSpace, ...run } = word
278 const hasGap = hasSpace && index < words.length - 1
279 if (run.isCode === true) {
280 append(run)
281 if (hasGap) {
282 append({ text: ' ' })
283 }
284 } else {
285 append({ ...run, text: run.text + (hasGap ? ' ' : '') })
286 }
287 })
288
289 return merged
290 })
291}
292
293// Cuts wrapped lines to `maxLines`, the last one ending in an ellipsis.
294export function clampLines(lines: Run[][], maxLines: number, maxWidth: number, size: number): Run[][] {
295 if (lines.length <= maxLines) {
296 return lines
297 }
298 const kept = lines.slice(0, maxLines)
299 const last = kept[maxLines - 1] ?? []
300 const text = last.map(i => i.text).join('')
301 kept[maxLines - 1] = [{ ...(last[0] ?? { text: '' }), text: fitText(`${text}…`, maxWidth, size, last[0]?.isBold === true) }]
302
303 return kept
304}
305
306export function lineSvg(runs: readonly Run[], x: number, y: number, size: number, tone = 't', weight?: number): string {
307 const spans = runs.map(run => {
308 const classes = run.isCode ? 'code' : run.isLink ? 'link' : tone
309 const attributes = [
310 `class="${classes}"`,
311 run.isBold === true || weight !== undefined ? `font-weight="${run.isBold === true ? 650 : weight}"` : '',
312 run.isItalic === true ? 'font-style="italic"' : '',
313 run.isCode === true ? `font-family="${MONO}" font-size="${(size * 0.92).toFixed(1)}"` : '',
314 run.isLink === true ? 'text-decoration="underline"' : '',
315 ].filter(i => i.length > 0)
316
317 return `<tspan ${attributes.join(' ')}>${escape(run.text)}</tspan>`
318 })
319
320 return `<text x="${x}" y="${y.toFixed(1)}" font-size="${size}">${spans.join('')}</text>`
321}
322
323// A pane reports its width in columns only; about 8 CSS pixels each, as
324// savvy-progress measures it, minus the pane's own inset.
325export function cardWidthOf(columns: number): number {
326 return Math.max(240, Math.min(900, (columns || 40) * 8 - 8))
327}
328
329// The columns a native control laid over a card is pushed in by to clear
330// `pixels` of the card, at the same 8 pixels per column.
331export function columnsOf(pixels: number): number {
332 return Math.ceil(pixels / 8)
333}
334
335// About how wide the desktop draws a row of native buttons with these labels,
336// for text that has to keep clear of buttons laid over a card.
337export function buttonWidthOf(labels: readonly string[]): number {
338 return labels.reduce((sum, label) => sum + textWidth(label, 13) + 30, 0) + Math.max(0, labels.length - 1) * 8
339}
340
341export function svgDocument(width: number, height: number, body: string): string {
342 return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">${STYLE}${body}</svg>`
343}
344
345export type Segment = 'answered' | 'skipped' | 'current' | 'open'
346
347export type Card = { source: string; height: number; alt: string }
348
349export type Variant = 'card' | 'card-accent' | 'card-success' | 'card-warning' | 'card-error'
350
351export type Section = { height: number; draw: (y: number) => string }
352
353export const PAD = 18
354export const SIZE = 14
355export const LINE = 21
356export const EYEBROW = 11
357export const RADIUS = 14
358
359// The engine refuses an Svg taller than 4096 pixels; a longer card is cut
360// between sections into several cards of the same look.
361export const MAX_HEIGHT = 4000
362
363export function baseline(y: number, line: number, lineHeight = LINE): number {
364 return y + line * lineHeight + lineHeight * 0.72
365}
366
367export function frame(width: number, height: number, variant: Variant): string {
368 return `<rect class="${variant}" x="0.5" y="0.5" width="${width - 1}" height="${height - 1}" rx="${RADIUS}"/>`
369}
370
371export function eyebrowSvg(text: string, x: number, y: number, tone = 'eyebrow', anchor = 'start'): string {
372 return `<text class="${tone}" x="${x}" y="${y}" font-size="${EYEBROW}" font-weight="700" letter-spacing="1.1" text-anchor="${anchor}">${escape(text)}</text>`
373}
374
375export function eyebrowWidth(text: string): number {
376 return textWidth(text, EYEBROW, true) + text.length * 1.1
377}
378
379export function textSection(
380 runs: readonly Run[],
381 x: number,
382 maxWidth: number,
383 options: { tone?: string; size?: number; maxLines?: number; weight?: number; firstWidth?: number } = {},
384): Section {
385 const size = options.size ?? SIZE
386 const lineHeight = Math.round(size * 1.5)
387 const wrapped = wrapRuns(runs, maxWidth, size, options.firstWidth)
388 const lines = options.maxLines === undefined ? wrapped : clampLines(wrapped, options.maxLines, maxWidth, size)
389
390 return {
391 height: lines.length * lineHeight,
392 draw: y => lines.map((line, index) => lineSvg(line, x, baseline(y, index, lineHeight), size, options.tone, options.weight)).join(''),
393 }
394}
395
396export function codeSection(lines: readonly string[], x: number, maxWidth: number): Section {
397 const size = 12.5
398 const lineHeight = 18
399 const perLine = Math.max(8, Math.floor((maxWidth - 24) / (size * 0.62)))
400 const rows = lines.flatMap(line => {
401 const chars = Array.from(line)
402 const pieces: string[] = []
403 for (let index = 0; index < Math.max(1, chars.length); index += perLine) {
404 pieces.push(chars.slice(index, index + perLine).join(''))
405 }
406
407 return pieces
408 })
409
410 return {
411 height: rows.length * lineHeight + 20,
412 draw: y =>
413 `<rect class="codebg" x="${x}" y="${y}" width="${maxWidth}" height="${rows.length * lineHeight + 20}" rx="8"/>` +
414 rows.map((row, index) => lineSvg([{ text: row, isCode: true }], x + 12, baseline(y + 10, index, lineHeight), size / 0.92)).join(''),
415 }
416}
417
418export function blockSection(block: Block, x: number, maxWidth: number): Section {
419 switch (block.kind) {
420 case 'code':
421 return codeSection(block.lines, x, maxWidth)
422 case 'heading':
423 return textSection(block.runs, x, maxWidth, { size: SIZE + 1.5, weight: 650 })
424 case 'quote': {
425 const text = textSection(block.runs, x + 14, maxWidth - 14, { tone: 'muted' })
426
427 return { height: text.height, draw: y => `<rect class="rule" x="${x}" y="${y + 2}" width="3" height="${text.height - 4}" rx="1.5"/>${text.draw(y)}` }
428 }
429 case 'item': {
430 const indent = block.marker === '•' ? 16 : textWidth(block.marker, SIZE) + 8
431 const text = textSection(block.runs, x + indent, maxWidth - indent)
432
433 return {
434 height: text.height,
435 draw: y => `<text class="muted" x="${x + (block.marker === '•' ? 3 : 0)}" y="${baseline(y, 0).toFixed(1)}" font-size="${SIZE}">${escape(block.marker)}</text>${text.draw(y)}`,
436 }
437 }
438 default:
439 return textSection(block.runs, x, maxWidth)
440 }
441}
442
443// Paragraphs sit further apart than the items of one list.
444export function blockSections(blocks: readonly Block[], x: number, maxWidth: number): Section[] {
445 return blocks.map((block, index) => {
446 const section = blockSection(block, x, maxWidth)
447 const previous = blocks[index - 1]
448 const spacing = index === 0 ? 0 : previous?.kind === 'item' && block.kind === 'item' ? 4 : 10
449
450 return { height: section.height + spacing, draw: y => section.draw(y + spacing) }
451 })
452}
453
454// Stacks sections inside one frame; past MAX_HEIGHT the rest go on in a next one.
455// `minHeight` keeps a short card tall enough for native controls laid over it.
456export function cards(width: number, variant: Variant, sections: readonly Section[], alt: string, decoration = '', minHeight = 0): Card[] {
457 const result: Card[] = []
458 let pending: Section[] = []
459 let used = 2 * PAD
460 const close = () => {
461 if (pending.length === 0) {
462 return
463 }
464 let y = PAD
465 const body = pending.map(section => {
466 const drawn = section.draw(y)
467 y += section.height
468
469 return drawn
470 })
471 const natural = Math.ceil(y + PAD)
472 const height = result.length === 0 ? Math.max(natural, minHeight) : natural
473 result.push({ height, alt, source: svgDocument(width, height, frame(width, height, variant) + (result.length === 0 ? decoration : '') + body.join('')) })
474 pending = []
475 used = 2 * PAD
476 }
477 for (const section of sections) {
478 if (pending.length > 0 && used + section.height > MAX_HEIGHT) {
479 close()
480 }
481 pending.push(section)
482 used += section.height
483 }
484 close()
485
486 return result
487}
488
489export const GLOW =
490 '<defs><linearGradient id="glow" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#d97757" stop-opacity="0.14"/><stop offset="0.55" stop-color="#d97757" stop-opacity="0"/></linearGradient></defs>'
491
492// The card heading a pane: an eyebrow, a count at the right, a title of up
493// to two lines and, given segments, a bar with one segment per step.
494// `reserve` keeps the title clear of native buttons laid over the right side;
495// a card without a bar is too low for them beside the count at its top right,
496// so the count then goes beneath the title.
497export function headerCard(card: { width: number; eyebrow: string; title: string; counter: string; segments?: readonly Segment[]; reserve?: number }): Card {
498 const { width } = card
499 const segments = card.segments ?? []
500 const inner = width - 2 * PAD
501 const reserve = card.reserve ?? 0
502 const isCountBelow = reserve > 0 && segments.length === 0
503 const counterWidth = isCountBelow ? 0 : textWidth(card.counter, 12)
504 const eyebrow = fitText(card.eyebrow, inner - counterWidth - 16 - (isCountBelow ? reserve : 0), EYEBROW, true)
505 const title = textSection(parseInline(card.title).map(i => ({ ...i, isBold: true })), PAD, inner - reserve, { size: 17, maxLines: 2 })
506 const titleTop = PAD + EYEBROW + 8
507 const countY = titleTop + title.height + 14
508 const barY = titleTop + title.height + 12
509 const height = isCountBelow ? countY + PAD - 2 : segments.length === 0 ? titleTop + title.height + PAD - 4 : barY + 6 + PAD
510 const count = Math.max(1, segments.length)
511 const segmentWidth = (inner - 4 * (count - 1)) / count
512 const bars = segments.map(
513 (segment, index) => `<rect class="${segment}" x="${(PAD + index * (segmentWidth + 4)).toFixed(1)}" y="${barY}" width="${segmentWidth.toFixed(1)}" height="6" rx="3"/>`,
514 )
515 const body = [
516 frame(width, height, 'card'),
517 GLOW,
518 `<rect x="0.5" y="0.5" width="${width - 1}" height="${height - 1}" rx="${RADIUS}" fill="url(#glow)"/>`,
519 eyebrowSvg(eyebrow, PAD, PAD + EYEBROW),
520 isCountBelow
521 ? `<text class="muted" x="${PAD}" y="${countY}" font-size="12.5">${escape(fitText(card.counter, inner - reserve, 12.5))}</text>`
522 : `<text class="muted" x="${width - PAD}" y="${PAD + EYEBROW}" font-size="12" text-anchor="end">${escape(card.counter)}</text>`,
523 title.draw(titleTop),
524 ...bars,
525 ]
526
527 return { height, alt: `${card.eyebrow}: ${plainOf(card.title)}, ${card.counter}`, source: svgDocument(width, height, body.join('')) }
528}
529
530export function noticeCard(width: number, variant: 'card-warning' | 'card-error', title: string, text: string, reserve = 0): Card[] {
531 const inner = width - 2 * PAD - reserve
532 const body = textSection([{ text }], PAD, inner, { tone: 'muted' })
533 const sections = [textSection([{ text: title, isBold: true }], PAD, inner, { size: 15 }), { height: body.height + 6, draw: (y: number) => body.draw(y + 6) }]
534
535 return cards(width, variant, sections, `${title} ${text}`, '', reserve > 0 ? 72 : 0)
536}
537
538const FIELD_HEIGHT = 72
539
540// A card holding a native text field: its label and a hint in a column at the
541// left, the rest left free for the field laid over it. `labelWidth` is that
542// column's width; the field starts past it.
543export function fieldCard(width: number, label: string, hint: string, labelWidth: number): Card {
544 const maxWidth = labelWidth - PAD - 12
545 const hints = wrapRuns([{ text: hint }], maxWidth, 12).slice(0, 2)
546 const top = FIELD_HEIGHT / 2 - (hints.length * 16 + EYEBROW + 6) / 2 + EYEBROW
547 const body = [
548 frame(width, FIELD_HEIGHT, 'card'),
549 eyebrowSvg(fitText(label, maxWidth, EYEBROW, true), PAD, top),
550 ...hints.map((line, index) => lineSvg(line, PAD, top + 18 + index * 16, 12, 'muted')),
551 `<rect class="rule" x="${labelWidth - 6}" y="16" width="1" height="${FIELD_HEIGHT - 32}"/>`,
552 ]
553
554 return { height: FIELD_HEIGHT, alt: `${label}: ${hint}`, source: svgDocument(width, FIELD_HEIGHT, body.join('')) }
555}
556
557// Below this width a card leaves too little room beside native controls, so
558// they go beneath it instead of over it.
559export const ROOMY_WIDTH = 420
560
561// A slim card for a row of native buttons laid over it; given a label, that
562// heads the bar at its left, as a section title with its actions beside it.
563export function barCard(width: number, alt: string, label = '', variant: Variant = 'card', reserve = 0): Card {
564 const height = 56
565 const text = label.length === 0 ? '' : eyebrowSvg(fitText(label, width - 2 * PAD - reserve - 12, EYEBROW, true), PAD, height / 2 + EYEBROW / 2 - 1)
566
567 return { height, alt, source: svgDocument(width, height, frame(width, height, variant) + text) }
568}
569
570// A diff or a list of changes in the code font: added lines green, removed
571// ones red, hunk heads in the accent color. Long lines are cut, not wrapped,
572// so the columns stay aligned.
573export function diffCards(width: number, text: string, alt: string): Card[] {
574 const size = 12
575 const lineHeight = 17
576 const maxWidth = width - 2 * PAD
577 const rows = text.replace(/\s+$/u, '').split('\n')
578 const toneOf = (row: string) =>
579 /^\+(?!\+\+)/u.test(row) ? 'success' : /^-(?!--)/u.test(row) ? 'error' : /^@@/u.test(row) ? 'accent' : /^(diff |index |\+\+\+|---)/u.test(row) ? 'muted' : 't'
580 const sections: Section[] = rows.map(row => ({
581 height: lineHeight,
582 draw: y =>
583 `<text class="${toneOf(row)} mono" x="${PAD}" y="${(y + lineHeight * 0.75).toFixed(1)}" font-size="${size}">${escape(fitMono(row, maxWidth, size))}</text>`,
584 }))
585
586 return cards(width, 'card', sections, alt)
587}
588
589function fitMono(text: string, maxWidth: number, size: number): string {
590 const chars = Array.from(text.replace(/\t/gu, ' '))
591 const fits = Math.floor(maxWidth / (size * 0.62))
592
593 return chars.length <= fits ? chars.join('') : `${chars.slice(0, Math.max(1, fits - 1)).join('')}…`
594}
595
596// An eyebrow line heading a card, with an optional second one at its right.
597export function eyebrowSection(left: string, right: string | null, rightTone: string, width: number): Section {
598 return {
599 height: EYEBROW + 10,
600 draw: y => eyebrowSvg(left, PAD, y + EYEBROW) + (right === null ? '' : eyebrowSvg(right, width - PAD, y + EYEBROW, rightTone, 'end')),
601 }
602}
603types/index.d.ts 42 lines1export type Question = {
2 number: number
3 title: string
4 body: string
5 recommendation: string | null
6}
7
8export type Answer = { kind: 'text'; text: string } | { kind: 'recommendation' }
9
10export type Mode = 'answer' | 'review' | 'confirm-send' | 'confirm-discard' | 'sending'
11
12export type Round = {
13 key: string
14 questions: Question[]
15 answers: (Answer | null)[]
16 skipped: boolean[]
17 current: number
18 mode: Mode
19 prefill: string | null
20}
21
22export type Draft = {
23 field: string
24 text: string
25}
26
27export type StoredRound = {
28 status: 'open' | 'done'
29 answers: (Answer | null)[]
30 updatedAt: number
31}
32
33declare module 'claude-code' {
34 interface PluginState {
35 'grill-panel': {
36 round: Round | null
37 draft: Draft | null
38 isHubbed: boolean
39 }
40 }
41}
42