Select text in the fullscreen transcript and attach it, with an optional comment, to your next prompt

Codex's "Add to chat", for Claude Code. In the fullscreen terminal, select any text in the transcript (a line of Claude's reply, one of your own earlier prompts, a tool's output), add an optional comment, and it goes with your next prompt as a numbered annotation. Claude answers each one and cites it as ①②… in its reply.
CLAUDE_CODE_NO_FLICKER=1, or set it under env in your settings. Outside fullscreen the terminal owns the mouse selection and no mod can read it.At the prompt of a Claude Code terminal session:
/plugin install add-to-chat --marketplace FunJim/claude-code-add-to-chat
[ ✚ Add to chat ]; click it, or run /add-to-chat.📎 N annotations ↗, and Claude's reply marks the sentences that answer each annotation.What the mod reads and sends: only the text you select and the comments you type, added to your own next prompt. It makes no network requests. For your latest 200 prompts sent with annotations, it keeps what you typed and those annotations in the plugin's local store, so a resumed session still shows them.
Full documentation, the Annotation Template and the limitations: <https://github.com/FunJim/claude-code-add-to-chat>
MIT licensed.
hooks/register.tsx 571 lines1// The engine glue: every call on `$` lives here (the engine follows `$`
2// only within this file); the decisions are the pure modules beside it.
3import { atom, read, update } from 'claude-code'
4import type { EngineInterface, Register, SessionMessage, UiPane } from 'claude-code'
5
6import type { Annotation, AnnotationSource, Candidate, Original, PaneMode, SelectionNote } from '../types'
7import { added, cleared, drafted, flushed, recalledBack, removed, saved, shown, withoutRecalled } from './annotations'
8import type { Pending, Recalled } from './annotations'
9import { NO_REPLIES, bound, checked, drawn, ended, promptSent, settled, toCheck } from './answering'
10import type { Replies } from './answering'
11import { promptsIn, replyCountsOf, sameRecord, sentInBox, sentPrompts } from './history'
12import { ALREADY_ADDED, NEEDS_FULLSCREEN, NOT_DRAWN, PANE_TITLE, SEND_PLACEHOLDER, addedToast } from './labels'
13import { PANE_COLUMNS, PANE_ID, commentKey, ownWords, paneView } from './pane'
14import { promptHint } from './prompt-hint'
15import { promptRow } from './prompt-row'
16import { promptRowView, replyText } from './rows'
17import { SYSTEM_ROWS, TOOL_ROWS, isSelectionOf, judge, noteOf, rowSource, selectionKey } from './selection'
18import type { Surroundings, Verdict } from './selection'
19import { forgotten, keysToLoad, loaded, originalOf, promptHash, remembered, stored, withReplies } from './originals'
20import type { Originals, StoreWrite } from './originals'
21import { annotated } from './send'
22
23const pending = atom({ plugin: 'add-to-chat', key: 'pending' } as const, [])
24const candidate = atom({ plugin: 'add-to-chat', key: 'candidate' } as const, null)
25const handled = atom({ plugin: 'add-to-chat', key: 'handled' } as const, null)
26const selectionNote = atom({ plugin: 'add-to-chat', key: 'selectionNote' } as const, null)
27const isPaneOpen = atom({ plugin: 'add-to-chat', key: 'isPaneOpen' } as const, false)
28const isPaneDrawn = atom({ plugin: 'add-to-chat', key: 'isPaneDrawn' } as const, false)
29const paneTab = atom({ plugin: 'add-to-chat', key: 'paneTab' } as const, 1)
30const commentDrafts = atom({ plugin: 'add-to-chat', key: 'commentDrafts' } as const, {})
31const commentSaves = atom({ plugin: 'add-to-chat', key: 'commentSaves' } as const, 0)
32const isDraftEmpty = atom({ plugin: 'add-to-chat', key: 'isDraftEmpty' } as const, true)
33const recalled = atom({ plugin: 'add-to-chat', key: 'recalled' } as const, null)
34const originals = atom({ plugin: 'add-to-chat', key: 'originals' } as const, {})
35const sessionPrompts = atom({ plugin: 'add-to-chat', key: 'sessionPrompts' } as const, [])
36const replyCounts = atom({ plugin: 'add-to-chat', key: 'replyCounts' } as const, {})
37const paneMode = atom({ plugin: 'add-to-chat', key: 'paneMode' } as const, { kind: 'pending' } as PaneMode)
38
39const POLL_MS = 250
40/** How long after the prompt box empties a submit has surely read what is pending. */
41const CLEAR_GRACE_MS = 1_000
42
43/**
44 * Each transcript row's Source, by requestId.
45 * Render hooks fill it and may not write state; it is a cache, not drawing
46 * state: after a reload every row in view draws again and refills it, and a
47 * selection in a row out of view carries no requestId anyway.
48 */
49const roles = new Map<string, AnnotationSource>()
50
51function rememberRole(requestId: string | undefined, component: string, props: unknown) {
52 if (requestId !== undefined && requestId !== 'placeholder') roles.set(requestId, rowSource(component, props))
53}
54
55/**
56 * Each rewritten prompt row's requestId, by `hashText` of its text: where
57 * the pane's history jumps to. Filled as rows draw, like `roles`; a prompt
58 * not drawn since the load has none, and the pane offers no jump.
59 */
60const promptRows = new Map<string, string>()
61
62/**
63 * The reply rows drawn since the load and the prompt they may answer (see
64 * answering.ts). Render hooks note rows here and may not write state; the
65 * poll checks them once the turn has ended and keeps them with the prompt.
66 */
67let replies: Replies = NO_REPLIES
68
69/**
70 * Once the turn has ended, checks the rows noted since against the
71 * transcript and keeps those that answer the prompt with its Original.
72 */
73async function keepReplies($: EngineInterface) {
74 const check = toCheck(replies)
75 if (check === undefined) return
76 replies = check.replies
77 const messages = await $.session.messages()
78 const transcript = Array.isArray(messages) ? messages : []
79 // Against the value now: rows noted while the transcript was read count.
80 const done = checked(replies, check.hash, transcript)
81 replies = done.replies
82 if (done.fresh.length > 0) await editOriginals($, now => withReplies(now, check.hash, done.fresh))
83 await refreshSession($, false, transcript)
84}
85
86async function surroundings($: EngineInterface): Promise<Surroundings> {
87 const [prompt, list, key, mode, map, inSession] = await Promise.all([
88 $.prompt.read(),
89 read($, pending),
90 read($, handled),
91 read($, paneMode),
92 read($, originals),
93 read($, sessionPrompts),
94 ])
95 return { draft: prompt.text, pending: list, handled: key, paneWords: ownWords({ mode, pending: list, sent: sentPrompts(map, inSession) }) }
96}
97
98/** What the poll last wrote, so it writes state only on a change. */
99type PollWatch = { isDraftEmpty?: boolean; isPaneOpen?: boolean; isPaneDrawn?: boolean; sessionId?: string; note?: string }
100
101function offerKey(offer: Candidate | null): string | null {
102 return offer === null ? null : selectionKey(offer)
103}
104
105/** One tick of the selection poll: what the pane offers, the draft's state, whether the pane is open. */
106async function poll($: EngineInterface, watch: PollWatch) {
107 // The offer before what decides it (see markHandled).
108 const offered = await read($, candidate)
109 const [selection, around, panes, sessionId] = await Promise.all([$.ui.selection(), surroundings($), $.ui.panes(), $.session.id()])
110
111 // /branch, /resume and /clear go on under another session id, with
112 // $.state cleared and no session.start: the originals come back from the
113 // store, and the history follows the new transcript.
114 if (watch.sessionId !== undefined && watch.sessionId !== sessionId) {
115 replies = settled(replies)
116 await refreshSession($, true)
117 }
118 watch.sessionId = sessionId
119 await keepReplies($)
120
121 const isEmpty = around.draft.trim() === ''
122 if (watch.isDraftEmpty !== isEmpty) {
123 watch.isDraftEmpty = isEmpty
124 await update($, isDraftEmpty, () => isEmpty)
125 }
126 const isOpen = panes.some(p => p.id === PANE_ID)
127 if (watch.isPaneOpen !== isOpen) {
128 watch.isPaneOpen = isOpen
129 await update($, isPaneOpen, () => isOpen)
130 }
131 const isDrawn = isPanePlaced(panes)
132 if (watch.isPaneDrawn !== isDrawn) {
133 watch.isPaneDrawn = isDrawn
134 await update($, isPaneDrawn, () => isDrawn)
135 }
136
137 // `handled` holds only while the engine still reports that selection.
138 // Once it reports none or another (a new drag, a command run, the turn's
139 // end), the same text selected again is a new selection. Cleared only if
140 // unchanged since read: a dismissal landing meanwhile stays.
141 let decide = around
142 const was = around.handled
143 if (was !== null && (selection === undefined || selectionKey(selection) !== was)) {
144 await update($, handled, now => (now === was ? null : now))
145 decide = { ...around, handled: null }
146 }
147
148 // The pane previews the Excerpt as it will be kept, marks and 📎 gone;
149 // or says why it offers nothing.
150 const verdict = judge(selection, decide)
151 const offer = 'key' in verdict ? verdict.excerpt : null
152 if (offerKey(offer) !== offerKey(offered)) await update($, candidate, () => offer)
153 const note = noteOf(verdict)
154 const noteKey = JSON.stringify(note)
155 if (watch.note !== noteKey) {
156 watch.note = noteKey
157 await update($, selectionNote, () => note)
158 }
159}
160
161/** Done with a selection: it is not offered again until another is made. */
162async function markHandled($: EngineInterface, key: string | undefined) {
163 // `handled` before the offer goes: a poll that reads the offer gone then
164 // reads the selection handled, and does not offer it again.
165 if (key !== undefined) await update($, handled, () => key)
166 await update($, candidate, () => null)
167}
168
169/**
170 * Adds the selection as an Annotation, if it can be. `isAsked` (from
171 * /add-to-chat) adds a selection last added or dismissed too: the command
172 * is the person asking for it; one pending is still not added twice.
173 */
174async function addSelection($: EngineInterface, isAsked = false): Promise<{ annotation: Annotation } | Exclude<Verdict, { key: string }>> {
175 const around = await surroundings($)
176 const verdict = judge(await $.ui.selection(), isAsked ? { ...around, handled: null } : around)
177 if (!('key' in verdict)) return verdict
178
179 const { excerpt } = verdict
180 const source = (excerpt.requestId !== undefined && roles.get(excerpt.requestId)) || 'transcript'
181 const { now } = await editPending($, p => added(p, excerpt, source))
182 const annotation = now.list.at(-1)!
183 // The new tab shows, whatever the pane was showing.
184 await Promise.all([markHandled($, verdict.key), update($, paneMode, () => ({ kind: 'pending' }) as const)])
185 return { annotation }
186}
187
188/**
189 * The offer's ✕: not this time. The engine still reports the selection,
190 * so it is marked handled, or the next poll would offer it again; selected
191 * again, it is offered (see the poll).
192 */
193async function dismissOffer($: EngineInterface) {
194 const selection = await $.ui.selection()
195 await markHandled($, selection === undefined ? undefined : selectionKey(selection))
196}
197
198/** Whether the pane is drawn now: open, and placed by the surface. */
199function isPanePlaced(panes: readonly UiPane[]): boolean {
200 return panes.some(p => p.id === PANE_ID && p.isPlaced)
201}
202
203async function removeAnnotation($: EngineInterface, index: number) {
204 const [{ was }, selection, key] = await Promise.all([editPending($, p => removed(p, index)), $.ui.selection(), read($, handled)])
205 const gone = was.list.find(a => a.index === index)
206 // The selection it came from, still reported, can be added again: offered
207 // once more, as the engine reports it until another is made.
208 if (gone !== undefined && key !== null && selection !== undefined && selectionKey(selection) === key && isSelectionOf(selection, gone)) {
209 await update($, handled, now => (now === key ? null : now))
210 }
211}
212
213/**
214 * Edits what is pending (see annotations.ts), writing only the atoms that
215 * changed: every transcript row reads `pending`, so a write of it, even of
216 * the same list, may redraw them all.
217 */
218async function editPending($: EngineInterface, edit: (p: Pending) => Pending): Promise<{ was: Pending; now: Pending }> {
219 const [list, drafts, tab, back] = await Promise.all([read($, pending), read($, commentDrafts), read($, paneTab), read($, recalled)])
220 const was: Pending = { list, drafts, tab, recalled: back }
221 const now = edit(was)
222 await Promise.all([
223 now.list !== was.list && update($, pending, () => now.list),
224 now.drafts !== was.drafts && update($, commentDrafts, () => now.drafts),
225 now.tab !== was.tab && update($, paneTab, () => now.tab),
226 now.recalled !== was.recalled && update($, recalled, () => now.recalled),
227 ])
228 return { was, now }
229}
230
231async function clearPending($: EngineInterface) {
232 await editPending($, cleared)
233}
234
235/** Keeps what the Comment fields hold as their Comments, saved with Enter or not (see `flushed`). */
236async function keepDrafts($: EngineInterface) {
237 await editPending($, flushed)
238}
239
240/** A Comment saved with Enter: kept, and its field drawn anew holding it, the keyboard still in it. */
241async function saveComment($: EngineInterface, index: number, value: string) {
242 await editPending($, p => saved(p, index, value))
243 const saves = await update($, commentSaves, n => n + 1)
244 await $.ui.focus({ requestId: PANE_ID, key: commentKey(index, saves) }).catch(() => undefined)
245}
246
247/**
248 * The prompt box changed by no edit (`by`: a rewind is `engine`, a step
249 * through the prompt history `history`).
250 *
251 * Annotations that came back with a prompt are that prompt's: they are
252 * pending while the box shows it. So a rewind or a step through the
253 * history first takes out those the last prompt brought back (a clear
254 * does too, a moment later: see the prompt.change hook). Then, a sent
255 * prompt with Annotations back in the box gets what was typed in its
256 * place, and its Annotations are pending again, to be edited and sent
257 * anew. From the history only a prompt of this conversation brings its
258 * Annotations back: another's point at rows this transcript does not hold.
259 */
260async function boxChanged($: EngineInterface, text: string, by: string) {
261 const isHistory = by === 'history'
262 if (isHistory || by === 'engine') await dropRecalled($)
263 const [map, inSession] = await Promise.all([read($, originals), read($, sessionPrompts)])
264 const sent = sentInBox(text, map, inSession)
265 if (sent === undefined) return
266 if (!isHistory || sent.isHere) {
267 const { was, now } = await editPending($, p => recalledBack(p, sent.original.annotations))
268 if (now.list.length > was.list.length) await update($, paneMode, () => ({ kind: 'pending' }) as const)
269 }
270 if (text !== sent.original.text) await $.prompt.fill({ text: sent.original.text, mode: 'replace' })
271}
272
273/**
274 * Takes out of pending the Annotations the last prompt put back in the box
275 * brought with it; with `only`, only if they are still those.
276 */
277async function dropRecalled($: EngineInterface, only?: Recalled) {
278 await editPending($, p => withoutRecalled(p, only))
279}
280
281/** Opens the pane at the person's asking: placed at any width. */
282async function openPane($: EngineInterface) {
283 const opened = await $.ui.open({ id: PANE_ID, title: PANE_TITLE, columns: PANE_COLUMNS })
284 await Promise.all([update($, isPaneOpen, () => true), update($, isPaneDrawn, () => opened.isPlaced)])
285}
286
287/** Closes the pane at the person's asking, from the count under the prompt. */
288async function hidePane($: EngineInterface) {
289 await Promise.all([update($, isPaneOpen, () => false), update($, isPaneDrawn, () => false)])
290 await $.ui.close({ id: PANE_ID })
291}
292
293/**
294 * Reads which sent prompts are in this conversation's transcript (or in
295 * `transcript`, when the caller has just read it), for the pane's history;
296 * with `reload`, takes the originals from the store first.
297 */
298async function refreshSession($: EngineInterface, reload: boolean, transcript?: readonly SessionMessage[]) {
299 const [messages, stored] = await Promise.all([transcript ?? $.session.messages(), reload ? loadOriginals($) : undefined])
300 const map = stored !== undefined ? await update($, originals, now => ({ ...now, ...stored })) : await read($, originals)
301 const hashes = Array.isArray(messages) ? promptsIn(messages, map) : []
302 const counts = replyCountsOf(map, hashes)
303 // Written only on a change: reply rows read replyCounts, and a write, even
304 // of the same value, may redraw them all.
305 const [shown, bounds] = await Promise.all([read($, sessionPrompts), read($, replyCounts)])
306 if (shown.length !== hashes.length || shown.some((h, i) => h !== hashes[i])) await update($, sessionPrompts, () => hashes)
307 if (!sameRecord(bounds, counts)) await update($, replyCounts, () => counts)
308}
309
310/**
311 * Every Original in the store: 0.4.0's one map and the records of their own
312 * keys, with their replies. Writes nothing, so it cannot drop what another
313 * session writes meanwhile.
314 */
315async function loadOriginals($: EngineInterface): Promise<Originals> {
316 const keys = await $.store.keys()
317 const wanted = keysToLoad(keys)
318 const values = await Promise.all(wanted.map(k => $.store.get(k)))
319 return loaded(Object.fromEntries(wanted.map((k, i) => [k, values[i]])), keys)
320}
321
322/** Edits the Originals (see originals.ts): state, then the store's writes, in their order. */
323async function editOriginals($: EngineInterface, edit: (map: Originals) => { originals: Originals; writes: StoreWrite[] }) {
324 let writes: StoreWrite[] = []
325 await update($, originals, now => {
326 const edited = edit(now)
327 writes = edited.writes
328 return edited.originals
329 })
330 for (const w of writes) await ('set' in w ? $.store.set(w.set, w.value) : $.store.delete(w.delete))
331}
332
333/** Shows a sent prompt's Annotations in the pane, from its row's 📎. */
334async function showSentPrompt($: EngineInterface, hash: string, requestId: string | undefined) {
335 await Promise.all([openPane($), keepDrafts($)])
336 await update($, paneMode, () => ({ kind: 'sent', hash, tab: 1, ...(requestId === undefined ? {} : { requestId }) }) as const)
337}
338
339/** Scrolls the transcript to the sent prompt the pane shows. */
340async function jumpToSent($: EngineInterface) {
341 const mode = await read($, paneMode)
342 if (mode.kind !== 'sent') return
343 const requestId = mode.requestId ?? promptRows.get(mode.hash)
344 const moved =
345 requestId === undefined ? { deny: 'not drawn' } : await $.ui.scroll({ to: { requestId }, block: 'center' }).catch((err: unknown) => ({ deny: String(err) }))
346 if ('deny' in moved) $.ui.toast(NOT_DRAWN)
347}
348
349export const register: Register = on => {
350 on('session.start', async ($, e, next) => {
351 await $.command.register({
352 name: 'add-to-chat',
353 description: 'Add the text selected in the transcript to your next prompt',
354 })
355 await refreshSession($, true)
356 // A reload keeps state but not the pane's drawing: clearing the offer
357 // makes the first poll write it again, so the new code draws it.
358 await update($, candidate, () => null)
359 // A reload drops the previous load's timers and fires session.start
360 // again, so this is the only interval running.
361 // Empty, so its first tick sets the status line too.
362 const watch: PollWatch = {}
363 $.clock.every(POLL_MS, () => poll($, watch))
364 return next(e)
365 })
366
367 // /clear ends the session without a new session.start: the rows the
368 // pending Annotations point at are gone.
369 on('session.end', async ($, e, next) => {
370 if (e.reason === 'clear') {
371 await clearPending($)
372 await update($, candidate, () => null)
373 }
374 return next(e)
375 })
376
377 // Opens the pane (again), and adds the selection if there is one to add.
378 on('command.run', { command: 'add-to-chat' }, async ($, e) => {
379 if (!e.presentation.isFullscreen) {
380 $.ui.toast(NEEDS_FULLSCREEN)
381 return {}
382 }
383 await openPane($)
384 const added = await addSelection($, true)
385 if ('annotation' in added) $.ui.toast(addedToast(added.annotation.index))
386 else if (added.reason === 'pending') $.ui.toast(ALREADY_ADDED)
387 return {}
388 })
389
390 on('prompt.submit', async ($, e, next) => {
391 if (e.origin.kind !== 'composer') return next(e)
392 const { list } = (await editPending($, flushed)).now
393 if (list.length === 0) {
394 replies = settled(replies)
395 return next(e)
396 }
397 const sent = annotated(e.text, list)
398 const hash = promptHash(sent.text)
399 // In state before the engine has it: its row draws the rewritten text
400 // soon after. In the store only once sent.
401 let was: Original | undefined
402 await update($, originals, now => {
403 was = now[hash]
404 return remembered(now, hash, sent.original)
405 })
406 const entered = await next({ ...e, text: sent.text })
407 if ('drop' in entered) {
408 await update($, originals, now => forgotten(now, hash, was))
409 } else {
410 const keys = await $.store.keys()
411 await editOriginals($, now => stored(now, hash, keys))
412 await clearPending($)
413 replies = promptSent(replies, hash, sent.original.count)
414 await update($, sessionPrompts, now => (now.includes(hash) ? now : [...now, hash]))
415 }
416 return entered
417 }).catch(($, e, next) => next(e))
418
419 // A long reply's row can stay as it was drawn mid-stream, before its
420 // Citations were complete; drawing the rows again once the turn ends
421 // shows them.
422 on('turn.complete', async ($, e, next) => {
423 const done = await next(e)
424 $.ui.invalidate('ui.render')
425 // The main loop's turn ends (a subagent's carries its agentId): the
426 // replies noted for it are checked and kept, and the poll keeps doing so
427 // for rows drawn after.
428 if (e.agentId === undefined && replies.answering !== null) {
429 replies = ended(replies)
430 await keepReplies($)
431 } else {
432 await refreshSession($, false)
433 }
434 return done
435 })
436
437 on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
438 rememberRole(e.requestId, e.component, e.props)
439 replies = drawn(replies, e.requestId, e.props.text)
440 // Only a row with a directive reads the counts (not the originals,
441 // written at every start): every reply redrawing, or drawing slower,
442 // just after a launch moves the transcript under a drag about to start.
443 const hasDirective = e.props.text.includes(':annotation{')
444 const [list, counts] = await Promise.all([read($, pending), hasDirective ? read($, replyCounts) : {}])
445 const id = e.requestId
446 const text = replyText(e.props.text, id, list, bound(replies, id, counts))
447 return text === e.props.text ? next(e) : next({ ...e, props: { ...e.props, text } })
448 })
449
450 on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
451 rememberRole(e.requestId, e.component, e.props)
452 if (e.props.origin.kind !== 'composer') return next(e)
453 const [list, map] = await Promise.all([read($, pending), read($, originals)])
454 const view = promptRowView({ text: e.props.text, requestId: e.requestId, isExpanded: e.props.isExpanded, surface: e.surface }, originalOf(map, e.props.text), list)
455 if (view.kind === 'text') return view.text === e.props.text ? next(e) : next({ ...e, props: { ...e.props, text: view.text } })
456 // In the terminal Claude Code draws the prompt as typed, and the mod its
457 // 📎 row beneath: a button to the pane, and a card on hover.
458 if (e.requestId !== undefined) promptRows.set(view.hash, e.requestId)
459 const engine = await next({ ...e, props: { ...e.props, text: view.text } })
460 return promptRow(
461 $.ui.resolve(e),
462 engine,
463 { hash: view.hash, count: view.count, annotations: view.annotations, columns: e.viewport?.columns ?? 80 },
464 () => showSentPrompt($, view.hash, e.requestId),
465 )
466 })
467
468 // The rows nothing here draws on are seen only for their Source.
469 on('ui.render', { component: [...TOOL_ROWS, ...SYSTEM_ROWS] }, async ($, e, next) => {
470 rememberRole(e.requestId, e.component, e.props)
471 return next(e)
472 })
473
474 // The person closing the pane (its ✕, ctrl+x x); it opens again only
475 // asked (/add-to-chat, the count under the prompt, a sent prompt's 📎 row).
476 on('ui.close', { id: PANE_ID }, async ($, e, next) => {
477 await update($, isPaneOpen, () => false)
478 await update($, isPaneDrawn, () => false)
479 return next(e)
480 })
481
482 // The line under the prompt: the offer for the selection while the pane
483 // is closed (its first row has it while it is drawn), and the count of
484 // Annotations pending, a click showing the pane or hiding it.
485 on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
486 const engine = await next(e)
487 const [list, offer, isDrawn] = await Promise.all([read($, pending), read($, candidate), read($, isPaneDrawn)])
488 if (list.length === 0 && offer === null) return engine
489 return promptHint(
490 $.ui.resolve(e),
491 engine,
492 { count: list.length, isPaneDrawn: isDrawn, offer: offer === null ? null : offer.text, columns: e.viewport?.columns ?? 80 },
493 { toggle: () => (isDrawn ? hidePane($) : openPane($)), add: () => void addSelection($), dismiss: () => void dismissOffer($) },
494 )
495 })
496
497 // A rewind or a step through the prompt history (no edit, and not this
498 // plugin's own fill): see boxChanged.
499 on('prompt.change', async ($, e, next) => {
500 const changed = await next(e)
501 if (e.origin.kind === 'clear') {
502 // An emptied box shows the prompt no more: what came back with it
503 // goes. But a submit empties the box too, before its prompt.submit
504 // has read pending: so a moment later, and only if they are still
505 // pending as that prompt's (a submit has taken them, and forgotten).
506 const last = await read($, recalled)
507 if (last !== null) $.clock.after(CLEAR_GRACE_MS, () => void dropRecalled($, last))
508 } else if (e.origin.kind !== 'plugin') {
509 await boxChanged($, e.text, e.origin.kind)
510 }
511 return changed
512 })
513
514 on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e, next) => {
515 // Mobile has no text field to edit a Comment in.
516 if (e.surface === 'mobile') return next(e)
517 const [offer, note, list, tab, saves, isEmpty, mode, map, inSession] = await Promise.all([
518 read($, candidate),
519 read($, selectionNote),
520 read($, pending),
521 read($, paneTab),
522 read($, commentSaves),
523 read($, isDraftEmpty),
524 read($, paneMode),
525 read($, originals),
526 read($, sessionPrompts),
527 ])
528 const canJump = mode.kind === 'sent' && (mode.requestId ?? promptRows.get(mode.hash)) !== undefined
529 return paneView(
530 $.ui.resolve(e),
531 {
532 offer,
533 note,
534 pending: list,
535 tab,
536 commentSaves: saves,
537 isDraftEmpty: isEmpty,
538 isFullscreen: e.viewport?.isFullscreen === true,
539 columns: e.props.bodyColumns,
540 mode,
541 sent: sentPrompts(map, inSession),
542 canJump,
543 },
544 {
545 add: async () => {
546 const added = await addSelection($)
547 // A click leaves the keyboard with the prompt, so this only
548 // moves the ring when the pane was focused.
549 if ('annotation' in added) {
550 await $.ui.focus({ requestId: PANE_ID, key: commentKey(added.annotation.index, await read($, commentSaves)) }).catch(() => undefined)
551 }
552 },
553 dismiss: () => dismissOffer($),
554 show: index => editPending($, p => shown(p, index)),
555 remove: index => removeAnnotation($, index),
556 draft: (index, value) => update($, commentDrafts, now => drafted(now, index, value)),
557 comment: (index, value) => saveComment($, index, value),
558 send: () => $.prompt.fill({ text: SEND_PLACEHOLDER }),
559 openHistory: async () => {
560 await Promise.all([refreshSession($, false), keepDrafts($)])
561 await update($, paneMode, () => ({ kind: 'history' }) as const)
562 },
563 openSent: hash => update($, paneMode, () => ({ kind: 'sent', hash, tab: 1 }) as const),
564 showSent: index => update($, paneMode, now => (now.kind === 'sent' ? { ...now, tab: index } : now)),
565 back: () => update($, paneMode, now => (now.kind === 'sent' ? { kind: 'history' } : { kind: 'pending' }) as PaneMode),
566 jump: () => jumpToSent($),
567 },
568 )
569 })
570}
571hooks/annotations.ts 118 lines1// The pending Annotations: the list, what their Comment fields hold, the tab
2// the pane shows and which of them a recall brought back, edited together,
3// so a renumbering never leaves a Comment field's text or the tab behind.
4import type { Annotation, AnnotationSource } from '../types'
5import type { Selection } from './selection'
6
7/** What a recall brought back to pending, by Excerpt and row: the next prompt put in the box takes them out. */
8export type Recalled = { annotations: Pick<Annotation, 'text' | 'requestId'>[] }
9
10/**
11 * Everything pending, as one value. A function here returns the same value
12 * (and the same parts) for what it leaves unchanged, so its caller can write
13 * only what changed: every transcript row reads `list`, no drawing reads
14 * `drafts`.
15 */
16export type Pending = {
17 list: Annotation[]
18 /** What a Comment field holds, by its Annotation's index, typed since the last save. */
19 drafts: Record<string, string>
20 /** The index of the Annotation whose tab the pane shows. */
21 tab: number
22 recalled: Recalled | null
23}
24
25/** Whether two are the same Excerpt from the same row: one is never pending twice. */
26export function isSameExcerpt(a: Pick<Annotation, 'text' | 'requestId'>, b: Pick<Annotation, 'text' | 'requestId'>): boolean {
27 return a.text === b.text && a.requestId === b.requestId
28}
29
30/**
31 * The Comment fields' text kept as their Comments: a field is left (a tab
32 * shown, added or closed, the history opened, a recall's Annotations taken
33 * out) or the prompt goes. Every edit that renumbers or moves the tab does
34 * this first, so a field's text never outlives the index it was typed at.
35 */
36export function flushed(p: Pending): Pending {
37 const entries = Object.entries(p.drafts)
38 if (entries.length === 0) return p
39 return { ...p, list: entries.reduce((now, [index, value]) => withComment(now, Number(index), value), p.list), drafts: {} }
40}
41
42/** One more, from `excerpt`, its tab shown. */
43export function added(p: Pending, excerpt: Selection, source: AnnotationSource): Pending {
44 const now = flushed(p)
45 const index = now.list.length + 1
46 return { ...now, list: [...now.list, { index, text: excerpt.text, source, requestId: excerpt.requestId }], tab: index }
47}
48
49/** Annotation `index` taken out, the rest renumbered from 1. */
50export function removed(p: Pending, index: number): Pending {
51 return kept(flushed(p), a => a.index !== index)
52}
53
54/** Annotation `index`'s tab shown. */
55export function shown(p: Pending, index: number): Pending {
56 const now = flushed(p)
57 return now.tab === index ? now : { ...now, tab: index }
58}
59
60/** What Annotation `index`'s Comment field holds now, unsaved: the drafts with it. */
61export function drafted(drafts: Readonly<Record<string, string>>, index: number, value: string): Record<string, string> {
62 return { ...drafts, [index]: value }
63}
64
65/** A Comment saved with Enter: kept, its field's draft gone. */
66export function saved(p: Pending, index: number, value: string): Pending {
67 const drafts = Object.fromEntries(Object.entries(p.drafts).filter(([at]) => Number(at) !== index))
68 return { ...p, list: withComment(p.list, index, value), drafts }
69}
70
71/** Nothing pending: the prompt went, or /clear. The tab stays, to be clamped. */
72export function cleared(p: Pending): Pending {
73 return { ...p, list: [], drafts: {}, recalled: null }
74}
75
76/**
77 * A sent prompt's Annotations back, after those pending, numbered on; one
78 * already pending is not added twice. The first of those added shows, and
79 * they are the recall's.
80 */
81export function recalledBack(p: Pending, sent: readonly Annotation[]): Pending {
82 const back = sent.filter(a => !p.list.some(b => isSameExcerpt(a, b)))
83 if (back.length === 0) return p
84 const now = flushed(p)
85 const list = [...now.list, ...back.map((a, i) => ({ ...a, index: now.list.length + i + 1 }))]
86 return { ...now, list, tab: now.list.length + 1, recalled: { annotations: back.map(a => ({ text: a.text, requestId: a.requestId })) } }
87}
88
89/**
90 * The Annotations the last recall brought back taken out, the rest
91 * renumbered; with `only`, only if the recall is still that one.
92 */
93export function withoutRecalled(p: Pending, only?: Recalled): Pending {
94 const last = p.recalled
95 if (last === null || (only !== undefined && JSON.stringify(last) !== JSON.stringify(only))) return p
96 return { ...kept(flushed(p), a => !last.annotations.some(t => isSameExcerpt(a, t))), recalled: null }
97}
98
99/**
100 * Those that `keep` keeps, renumbered from 1; the tab on the Annotation it
101 * showed, or where that one stood, the one that took its place.
102 */
103function kept(p: Pending, keep: (a: Annotation) => boolean): Pending {
104 const list = p.list.filter(keep)
105 if (list.length === p.list.length) return p
106 const before = list.filter(a => a.index < p.tab).length
107 return { ...p, list: list.map((a, i) => ({ ...a, index: i + 1 })), tab: before + 1 }
108}
109
110function withComment(list: readonly Annotation[], index: number, value: string): Annotation[] {
111 const comment = value.trim()
112 return list.map(a => (a.index === index ? { ...a, comment: comment === '' ? undefined : comment } : a))
113}
114
115export function marksFor(list: readonly Annotation[], requestId: string | undefined): Annotation[] {
116 return list.filter(a => a.requestId !== undefined && a.requestId === requestId)
117}
118hooks/answering.ts 129 lines1// Which sent prompt a reply answers, and so how far its Citations may go:
2// the reply rows first drawn after a prompt sent with Annotations, noted
3// as they draw, and checked against the transcript once the turn has ended.
4// A value with pure transitions; register.tsx holds the one current value,
5// since render hooks note rows and may not write state.
6import { promptHash } from './originals'
7import { oneLine } from './text'
8
9/** A reply row noted during a turn: its requestId, and its text as it drew. */
10export type NotedReply = { id: string; text: string }
11
12/**
13 * The last prompt sent with Annotations, and the reply rows first drawn
14 * since: the rows noted with their latest text, and which of them the
15 * transcript showed to answer it (`kept`) or not (`rejected`). It stays
16 * open past the turn's end, since a short reply can first draw after
17 * `turn.complete`, until the next typed prompt or another session. Once the
18 * turn has ended, noted rows are checked while any changed (`isDirty`).
19 */
20export type Answering = {
21 hash: string
22 count: number
23 noted: NotedReply[]
24 kept: string[]
25 rejected: string[]
26 hasEnded: boolean
27 isDirty: boolean
28}
29
30export type Replies = {
31 /** Reply rows (requestIds) drawn since the load: a row new to it during a turn is that turn's. */
32 drawn: ReadonlySet<string>
33 answering: Answering | null
34}
35
36export const NO_REPLIES: Replies = { drawn: new Set(), answering: null }
37
38/** A prompt sent with Annotations (`hash`, `count` of them): the rows drawn from now on are noted for it. */
39export function promptSent(r: Replies, hash: string, count: number): Replies {
40 return { ...r, answering: { hash, count, noted: [], kept: [], rejected: [], hasEnded: false, isDirty: false } }
41}
42
43/** A prompt typed without Annotations, or another session: no row is noted any more. */
44export function settled(r: Replies): Replies {
45 return r.answering === null ? r : { ...r, answering: null }
46}
47
48/** A reply row drawn: noted if new since the load, or its text kept up to date if noted. The same value if nothing changed. */
49export function drawn(r: Replies, id: string | undefined, text: string): Replies {
50 if (id === undefined || id === 'placeholder') return r
51 const a = r.answering
52 const noted = a?.noted.find(n => n.id === id)
53 if (a !== null && noted !== undefined) {
54 if (noted.text === text) return r
55 return { ...r, answering: { ...a, noted: a.noted.map(n => (n.id === id ? { id, text } : n)), isDirty: true } }
56 }
57 if (r.drawn.has(id)) return r
58 const seen = new Set(r.drawn).add(id)
59 return { drawn: seen, answering: a === null ? null : { ...a, noted: [...a.noted, { id, text }], isDirty: true } }
60}
61
62/**
63 * The Citations a reply row may draw: to the count of the prompt it is
64 * known to answer (`counts`); else, noted since the last prompt and not let
65 * go by the check, to that prompt's. An older reply first drawn since
66 * (scrolled to) is known to answer its own prompt, if it answered one sent
67 * with Annotations.
68 */
69export function bound(r: Replies, id: string | undefined, counts: Readonly<Record<string, number>>): number | undefined {
70 if (id === undefined) return undefined
71 const known = counts[id]
72 if (known !== undefined) return known
73 const a = r.answering
74 return a !== null && !a.rejected.includes(id) && a.noted.some(n => n.id === id) ? a.count : undefined
75}
76
77/** The main loop's turn ended: the noted rows are to be checked, now and whenever more are noted. */
78export function ended(r: Replies): Replies {
79 return r.answering === null ? r : { ...r, answering: { ...r.answering, hasEnded: true, isDirty: true } }
80}
81
82/**
83 * Whether the noted rows are to be checked: the value with the check
84 * begun, and the prompt to check them for; undefined if not.
85 */
86export function toCheck(r: Replies): { replies: Replies; hash: string } | undefined {
87 const a = r.answering
88 if (a === null || !a.hasEnded || !a.isDirty) return undefined
89 return { replies: { ...r, answering: { ...a, isDirty: false } }, hash: a.hash }
90}
91
92/**
93 * The check against the transcript: the rows that answer the prompt kept,
94 * the others let go; `fresh`, those kept by no check before, to keep with
95 * its Original. Rows noted while the transcript was read are checked too;
96 * a prompt sent meanwhile is left as it is.
97 */
98export function checked(r: Replies, hash: string, messages: readonly { role: string; text: string }[]): { replies: Replies; fresh: string[] } {
99 const a = r.answering
100 if (a === null || a.hash !== hash) return { replies: r, fresh: [] }
101 const kept = turnReplies(messages, hash, a.noted)
102 const fresh = kept.filter(id => !a.kept.includes(id))
103 const rejected = a.noted.map(n => n.id).filter(id => !kept.includes(id))
104 return { replies: { ...r, answering: { ...a, kept, rejected } }, fresh }
105}
106
107
108/**
109 * The noted rows that are the turn's own replies: those whose text is in an
110 * assistant message after the prompt (`hash`) in the transcript, before the
111 * next prompt. An older
112 * reply first drawn during the turn (scrolled to) is not. Without the
113 * prompt in the transcript, every noted row is kept.
114 */
115export function turnReplies(messages: readonly { role: string; text: string }[], hash: string, noted: readonly NotedReply[]): string[] {
116 const at = messages.findLastIndex(m => m.role === 'user' && promptHash(m.text) === hash)
117 if (at === -1) return noted.map(r => r.id)
118 // Up to the next prompt (a user message with text; tool results have none).
119 const next = messages.findIndex((m, i) => i > at && m.role === 'user' && m.text !== '')
120 const said = oneLine(
121 messages
122 .slice(at + 1, next === -1 ? undefined : next)
123 .filter(m => m.role === 'assistant')
124 .map(m => m.text)
125 .join('\n'),
126 )
127 return noted.filter(r => said.includes(oneLine(r.text))).map(r => r.id)
128}
129hooks/history.ts 71 lines1// Sent prompts in this conversation: which are in its transcript and which
2// one the prompt box holds. How their Originals are kept is originals.ts;
3// which one a reply answers, answering.ts.
4import type { Annotation, Original } from '../types'
5import { hasAnnotations, promptHash } from './originals'
6import type { Annotated } from './originals'
7
8/**
9 * The rewritten prompts in a transcript (its user messages, as
10 * `$.session.messages()` gives them), by the hash `originals` is keyed by,
11 * oldest first; each once.
12 */
13export function promptsIn(messages: readonly { role: string; text: string }[], originals: Record<string, Original>): string[] {
14 const hashes = messages.filter(m => m.role === 'user').map(m => promptHash(m.text))
15 return [...new Set(hashes.filter(h => originals[h] !== undefined))]
16}
17
18/** A sent prompt the pane's history lists. */
19export type SentPrompt = { hash: string; text: string; annotations: Annotation[] }
20
21/** The prompts of this conversation whose Annotations are known, newest first. */
22export function sentPrompts(originals: Record<string, Original>, inSession: readonly string[]): SentPrompt[] {
23 return inSession
24 .flatMap(hash => {
25 const o = originals[hash]
26 return hasAnnotations(o) ? [{ hash, text: o.text, annotations: o.annotations }] : []
27 })
28 .reverse()
29}
30
31/** A sent prompt with Annotations that a text in the prompt box is. */
32export type InBox = {
33 hash: string
34 original: Annotated
35 /** Whether it was sent in this conversation (`inSession`). */
36 isHere: boolean
37}
38
39/**
40 * The sent prompt with Annotations that `text` is: its rewritten text, as a
41 * rewind or the prompt history first gives it back, or what was typed for
42 * one of this conversation's, as the history gives it back once the mod
43 * filled that in. The newest of several.
44 */
45export function sentInBox(text: string, originals: Record<string, Original>, inSession: readonly string[]): InBox | undefined {
46 const withAnnotations = (hash: string): InBox | undefined => {
47 const o = originals[hash]
48 return hasAnnotations(o) ? { hash, original: o, isHere: inSession.includes(hash) } : undefined
49 }
50 const rewritten = withAnnotations(promptHash(text))
51 if (rewritten !== undefined) return rewritten
52 const typed = [...inSession].reverse().find(hash => originals[hash]?.text === text)
53 return typed === undefined ? undefined : withAnnotations(typed)
54}
55
56/** Each reply row known to answer a prompt in `inSession` → that prompt's Annotation count. */
57export function replyCountsOf(originals: Record<string, Original>, inSession: readonly string[]): Record<string, number> {
58 const counts: Record<string, number> = {}
59 for (const hash of inSession) {
60 const o = originals[hash]
61 for (const id of o?.replies ?? []) counts[id] = o!.count
62 }
63 return counts
64}
65
66/** Whether two records hold the same keys and values. */
67export function sameRecord(a: Record<string, number>, b: Record<string, number>): boolean {
68 const keys = Object.keys(a)
69 return keys.length === Object.keys(b).length && keys.every(k => a[k] === b[k])
70}
71hooks/labels.ts 125 lines1// What the mod draws in its own words and numbers, shared by the pane, the
2// rows, the toasts and the selection filter (which must know the pane's
3// words to tell them from transcript text). A leaf module: the end-to-end
4// harness imports it too.
5import type { Annotation, AnnotationSource } from '../types'
6
7/** ①–⑳, ㉑–㉟, ㊱–㊿; past fifty, the number in parentheses. */
8export function circled(n: number): string {
9 if (n >= 1 && n <= 20) return String.fromCodePoint(0x2460 + n - 1)
10 if (n >= 21 && n <= 35) return String.fromCodePoint(0x3251 + n - 21)
11 if (n >= 36 && n <= 50) return String.fromCodePoint(0x32b1 + n - 36)
12 return `(${n})`
13}
14
15const SUPERSCRIPT = '⁰¹²³⁴⁵⁶⁷⁸⁹'
16
17/** `⁽ⁿ⁾`, the mark drawn after an Excerpt in its row. */
18export function superscript(n: number): string {
19 return `⁽${[...String(n)].map(d => SUPERSCRIPT[Number(d)]).join('')}⁾`
20}
21
22export const SOURCE_LABEL: Record<AnnotationSource, string> = { assistant: 'Claude', user: 'You', tool: 'Tool', system: 'System', transcript: 'Transcript' }
23
24/** Where each Source's Excerpt was selected, as the pane says it. */
25export const SOURCE_HINT: Record<AnnotationSource, string> = {
26 assistant: "from Claude's reply",
27 user: 'from your prompt',
28 tool: "from a tool's row",
29 system: "from Claude Code's own row",
30 transcript: 'from the transcript',
31}
32
33/** The pane's title, and its tab when other panes are open beside it. */
34export const PANE_TITLE = 'Add to chat'
35export const ADD_LABEL = '✚ Add to chat'
36/** What the pane's first row says while nothing is selected. */
37export const IDLE_HINT = 'Select text in the transcript to add it.'
38export const NEEDS_FULLSCREEN_HINT = 'Selections show here in fullscreen (CLAUDE_CODE_NO_FLICKER=1).'
39/** The first row's word for a selection already pending, after its preview. */
40export function addedNote(index: number): string {
41 return `added as ${circled(index)}`
42}
43
44export const PANE_EMPTY = 'Nothing added yet.'
45export const COMMENT_LABEL = 'Comment'
46export const COMMENT_PLACEHOLDER = 'Add an optional comment…'
47/** The Comment field's submit label; the engine draws it as `⏎ save`. */
48export const SAVE_LABEL = 'save'
49export const CLOSE_TAB = '✕'
50export const SEND_BUTTON = 'Send'
51/** Beside `[ Send ]`, while the prompt box is empty. */
52export const SEND_HINT = 'now, or type a prompt and press ↵'
53export const SENT_HINT = 'They go with your next prompt ↵'
54/** What `[ Send ]` puts in an empty prompt box. */
55export const SEND_PLACEHOLDER = '(see annotations)'
56
57/** The pane's way to the sent prompts' Annotations, and back. */
58export function historyLabel(count: number): string {
59 return `History (${count})`
60}
61export const BACK_LABEL = '← back'
62/** The way into the history, as its row draws it. */
63export function historyRowLabel(count: number): string {
64 return `${historyLabel(count)} ›`
65}
66export const HISTORY_TITLE = 'Sent with annotations'
67export const HISTORY_EMPTY = 'No prompt sent with annotations yet.'
68export const SENT_TITLE = 'You sent'
69export const NO_COMMENT = 'No comment'
70export const JUMP_LABEL = 'jump to prompt'
71/** The sent view's way to the prompt's row, as it draws it. */
72export const JUMP_ROW_LABEL = `↑ ${JUMP_LABEL}`
73export const NOT_DRAWN = 'That prompt is not drawn yet: scroll to it once, then jump'
74
75export const ALREADY_ADDED = 'That selection is already added'
76export const NEEDS_FULLSCREEN = 'add-to-chat needs fullscreen mode (CLAUDE_CODE_NO_FLICKER=1) to read the selection'
77
78export function addedToast(index: number): string {
79 return `Added ${circled(index)}: a Comment can go with it in the pane`
80}
81
82/** `📎 N annotations`: a rewritten prompt row's second line, and the status line. */
83export function clipLine(count: number): string {
84 return `📎 ${count} annotation${count === 1 ? '' : 's'}`
85}
86
87/** The button under a rewritten prompt row that opens its Annotations in the pane. */
88export function clipButtonLabel(count: number): string {
89 return `${clipLine(count)} ↗`
90}
91
92/** The count under the prompt, a toggle: it shows the pane, or hides the pane drawn. */
93export function hintLabel(count: number, isPaneDrawn: boolean): string {
94 return `${clipLine(count)} · ${isPaneDrawn ? 'hide' : 'show'} pane`
95}
96
97/** Whether a line is a `📎 N annotations` line (or its button), or any head of one. */
98export function isClipLineHead(line: string): boolean {
99 const head = line.trim().replace(/\s*↗$/u, '')
100 const count = /^📎 (\d+)/u.exec(head)?.[1]
101 return head === '📎' || (count !== undefined && clipLine(Number(count)).startsWith(head))
102}
103
104/** The highest tab number a digit key shows. */
105export const MAX_TAB_HOTKEY = 9
106
107/**
108 * One Annotation's tab label in the pane: its Source. The terminal draws a
109 * hotkey's digit before it (`1: Claude`); past nine the label carries the
110 * number itself.
111 */
112export function tabLabel(a: Annotation): string {
113 return a.index <= MAX_TAB_HOTKEY ? SOURCE_LABEL[a.source] : `${a.index}: ${SOURCE_LABEL[a.source]}`
114}
115
116/** A tab as the terminal draws it, hotkey digit included: `1: Claude`. */
117export function drawnTab(a: Annotation): string {
118 return a.index <= MAX_TAB_HOTKEY ? `${a.index}: ${tabLabel(a)}` : tabLabel(a)
119}
120
121/** The open tab's first line: the number its marks carry in the transcript, and where it was selected. */
122export function sourceLine(a: Annotation): string {
123 return `${circled(a.index)} ${SOURCE_HINT[a.source]}`
124}
125hooks/pane.tsx 372 lines1// The add-to-chat pane: everything the mod shows. Its first row offers the
2// selection (or says how to make one); below it, one of three views:
3// - pending: one tab per pending Annotation, the open tab showing where its
4// Excerpt came from, the whole Excerpt in a frame, and its Comment, which
5// can be edited there; closing a tab removes its Annotation;
6// - history: the prompts sent with Annotations, newest first;
7// - sent: one of them, its Annotations in tabs, read-only.
8// A view: it draws from the values and calls back the actions register.tsx
9// hands it.
10//
11// The first row is always there and always one row high: an offer that
12// added a row would move what is under a mouse still dragging. Rows below it
13// change on clicks only.
14import type { BoxProps, ButtonProps, ElementConstructor, InputProps, RenderElement, TextProps } from 'claude-code'
15
16import type { Annotation, Candidate, PaneMode, SelectionNote } from '../types'
17import type { SentPrompt } from './history'
18import {
19 ADD_LABEL,
20 BACK_LABEL,
21 CLOSE_TAB,
22 COMMENT_LABEL,
23 COMMENT_PLACEHOLDER,
24 HISTORY_EMPTY,
25 HISTORY_TITLE,
26 IDLE_HINT,
27 JUMP_ROW_LABEL,
28 MAX_TAB_HOTKEY,
29 NEEDS_FULLSCREEN_HINT,
30 NO_COMMENT,
31 PANE_EMPTY,
32 SAVE_LABEL,
33 SEND_BUTTON,
34 SEND_HINT,
35 SENT_HINT,
36 SENT_TITLE,
37 SOURCE_HINT,
38 addedNote,
39 circled,
40 clipLine,
41 historyRowLabel,
42 drawnTab,
43 sourceLine,
44 tabLabel,
45} from './labels'
46import { preview, width } from './text'
47
48/** The pane's id: what opens, closes and draws it. */
49export const PANE_ID = 'add-to-chat'
50
51/** The cells across to ask for when the pane docks beside the transcript. */
52export const PANE_COLUMNS = 56
53
54/** The elements the pane draws with, from `$.ui.resolve(e)`. */
55export type PaneElements = {
56 Box: ElementConstructor<BoxProps>
57 Button: ElementConstructor<ButtonProps>
58 Input: ElementConstructor<InputProps>
59 Text: ElementConstructor<TextProps>
60}
61
62export type PaneValues = {
63 offer: Candidate | null
64 /** The selection reported, not offered as its Excerpt is pending: the row says as which. */
65 note: SelectionNote | null
66 pending: readonly Annotation[]
67 /** The index of the Annotation whose tab is open. */
68 tab: number
69 /** Comments saved with Enter so far: the field's key (`commentKey`). */
70 commentSaves: number
71 isDraftEmpty: boolean
72 /** The fullscreen terminal, the only place a selection reads. */
73 isFullscreen: boolean
74 /** The cells across the pane's body (`bodyColumns`). */
75 columns: number
76 mode: PaneMode
77 /** The prompts sent with Annotations, newest first. */
78 sent: readonly SentPrompt[]
79 /** Whether the sent prompt shown has a row to jump to. */
80 canJump: boolean
81}
82
83export type PaneActions = {
84 add: () => unknown
85 /** The offer's ✕: not this time. */
86 dismiss: () => unknown
87 show: (index: number) => unknown
88 remove: (index: number) => unknown
89 /** The Comment field's text, at each edit. */
90 draft: (index: number, value: string) => unknown
91 /** The Comment field's text, at Enter. */
92 comment: (index: number, value: string) => unknown
93 send: () => unknown
94 openHistory: () => unknown
95 openSent: (hash: string) => unknown
96 showSent: (index: number) => unknown
97 back: () => unknown
98 jump: () => unknown
99}
100
101/**
102 * The key of Annotation `index`'s Comment field after `saves` saves. The
103 * terminal empties a field on Enter and keeps its text by key, filling it
104 * again only with another value: a new key after each save draws the field
105 * anew, holding the Comment.
106 */
107export function commentKey(index: number, saves: number): string {
108 return `comment-${index}-${saves}`
109}
110
111/** The tab open for `count` Annotations: `tab`, kept within them. */
112export function shownTab(tab: number, count: number): number {
113 return Math.min(Math.max(1, tab), count)
114}
115
116/** The sent prompt the mode shows, if it is one the history knows. */
117export function shownSent(mode: PaneMode, sent: readonly SentPrompt[]): SentPrompt | undefined {
118 return mode.kind === 'sent' ? sent.find(p => p.hash === mode.hash) : undefined
119}
120
121/**
122 * Every line of words the pane can draw in this state, but the offer: a
123 * selection that matches the offer's preview is the offer's own, of the
124 * transcript. The view draws these words and the selection rule ignores
125 * them, from this one list: adding words to `paneView` means adding them
126 * here, where they sit beside it. (The pending view's words count whatever
127 * the mode: the pane switches modes in a click, and they are its own.)
128 */
129export function ownWords(v: PaneWords): string[] {
130 const pending = [
131 ADD_LABEL,
132 IDLE_HINT,
133 NEEDS_FULLSCREEN_HINT,
134 PANE_EMPTY,
135 `${COMMENT_LABEL}: ${COMMENT_PLACEHOLDER} ⏎ ${SAVE_LABEL}`,
136 `[ ${SEND_BUTTON} ] ${SEND_HINT}`,
137 SENT_HINT,
138 historyRowLabel(v.sent.length),
139 ...v.pending.map(a => `${drawnTab(a)} ${CLOSE_TAB}`),
140 ...v.pending.map(a => addedNote(a.index)),
141 ...v.pending.map(sourceLine),
142 ...v.pending.map(a => a.text),
143 ...v.pending.flatMap(a => (a.comment === undefined ? [] : [`${COMMENT_LABEL}: ${a.comment}`])),
144 ]
145 const beside = [BACK_LABEL, HISTORY_TITLE, HISTORY_EMPTY, SENT_TITLE, NO_COMMENT, JUMP_ROW_LABEL]
146 if (v.mode.kind === 'history') return [...pending, ...beside, ...v.sent.flatMap(p => [p.text, clipLine(p.annotations.length)])]
147 const shown = shownSent(v.mode, v.sent)
148 if (shown === undefined) return [...pending, ...beside]
149 return [
150 ...pending,
151 ...beside,
152 shown.text,
153 ...shown.annotations.flatMap(a => [tabLabel(a), `${circled(a.index)} ${SOURCE_HINT[a.source]}`, a.text, ...(a.comment === undefined ? [] : [`${COMMENT_LABEL}: ${a.comment}`])]),
154 ]
155}
156
157/** What the pane is showing, for its own words (see `ownWords`). */
158export type PaneWords = { mode: PaneMode; pending: readonly Annotation[]; sent: readonly SentPrompt[] }
159
160/**
161 * A row of tabs, one per Annotation: its label, which shows it, and (when
162 * `remove` is given) a ✕, which closes it and so removes its Annotation. The
163 * first nine answer to their digit, which the terminal draws before the
164 * label. The open tab is drawn bold and underlined in the accent color, the
165 * others dim.
166 */
167function tabRow(el: PaneElements, list: readonly Annotation[], open: number, prefix: string, show: (index: number) => unknown, remove?: (index: number) => unknown) {
168 const { Box, Button, Text } = el
169 const tabs = list.map(a => {
170 const press = {
171 key: `${prefix}show-${a.index}`,
172 plain: true,
173 ...(a.index <= MAX_TAB_HOTKEY ? { hotkey: String(a.index) } : {}),
174 onPress: () => show(a.index),
175 } as const
176 return (
177 <Box key={`${prefix}tab-${a.index}`} gap={1}>
178 {a.index === open ? (
179 <Button {...press}>
180 <Text color="claude" bold underline>
181 {tabLabel(a)}
182 </Text>
183 </Button>
184 ) : (
185 <Button {...press} dimColor label={tabLabel(a)} />
186 )}
187 {remove === undefined ? null : (
188 <Button key={`close-${a.index}`} plain onPress={() => remove(a.index)}>
189 <Text dimColor>{CLOSE_TAB}</Text>
190 </Button>
191 )}
192 </Box>
193 )
194 })
195 return (
196 <Box flexWrap="wrap" columnGap={3}>
197 {tabs}
198 </Box>
199 )
200}
201
202/** Where an Annotation's Excerpt came from, and the Excerpt in a frame. */
203function excerptBlock(el: PaneElements, a: Annotation) {
204 const { Box, Text } = el
205 return [
206 <Text key="source">
207 <Text color="claude" bold>
208 {circled(a.index)}
209 </Text>
210 <Text dimColor> {SOURCE_HINT[a.source]}</Text>
211 </Text>,
212 <Box key="excerpt" borderStyle="round" borderDimColor paddingX={1}>
213 <Text wrap="wrap">{a.text}</Text>
214 </Box>,
215 ]
216}
217
218export function paneView(el: PaneElements, v: PaneValues, act: PaneActions): RenderElement {
219 const { Box, Button, Input, Text } = el
220 const rule = (key: string) => (
221 <Text key={key} dimColor>
222 {'─'.repeat(Math.max(1, v.columns))}
223 </Text>
224 )
225
226 // The offer, cut to one row: the button, the preview, and the ✕ that
227 // dismisses it. With none, that the selection is added (as which), or
228 // the hint.
229 const room = v.columns - (width(ADD_LABEL) + 4) - width(CLOSE_TAB) - 4
230 const noteWords = v.note === null ? '' : addedNote(v.note.index)
231 const offer =
232 v.offer !== null ? (
233 <Box key="offer" gap={1}>
234 <Button key="add" variant="primary" label={ADD_LABEL} onPress={act.add} />
235 <Text italic wrap="truncate">
236 “{preview(v.offer.text, room)}”
237 </Text>
238 <Button key="dismiss" plain onPress={act.dismiss}>
239 <Text dimColor>{CLOSE_TAB}</Text>
240 </Button>
241 </Box>
242 ) : v.note !== null ? (
243 <Text key="offer" dimColor wrap="truncate">
244 “{preview(v.note.text, Math.max(8, v.columns - width(noteWords) - 4))}” {noteWords}
245 </Text>
246 ) : (
247 <Text key="offer" dimColor wrap="truncate">
248 {v.isFullscreen ? IDLE_HINT : NEEDS_FULLSCREEN_HINT}
249 </Text>
250 )
251
252 const header = (title: string) => (
253 <Box key="header" gap={2}>
254 <Button key="back" plain label={BACK_LABEL} onPress={act.back} />
255 <Text bold wrap="truncate">
256 {title}
257 </Text>
258 </Box>
259 )
260
261 if (v.mode.kind === 'history') {
262 // One row per prompt, its first nine answering to their digit.
263 const room = v.columns - 3 - width(clipLine(99)) - 2
264 return (
265 <Box flexDirection="column">
266 {offer}
267 {rule('rule')}
268 {header(HISTORY_TITLE)}
269 <Text> </Text>
270 {v.sent.length === 0 ? (
271 <Text dimColor>{HISTORY_EMPTY}</Text>
272 ) : (
273 v.sent.map((p, i) => (
274 <Button
275 key={`sent-${p.hash}`}
276 plain
277 {...(i < MAX_TAB_HOTKEY ? { hotkey: String(i + 1) } : {})}
278 onPress={() => act.openSent(p.hash)}
279 >
280 {preview(p.text, room)} <Text dimColor>{clipLine(p.annotations.length)}</Text>
281 </Button>
282 ))
283 )}
284 </Box>
285 ) as RenderElement
286 }
287
288 if (v.mode.kind === 'sent') {
289 const shown = shownSent(v.mode, v.sent)
290 if (shown === undefined) {
291 return (
292 <Box flexDirection="column">
293 {offer}
294 {rule('rule')}
295 {header(HISTORY_TITLE)}
296 <Text dimColor>{HISTORY_EMPTY}</Text>
297 </Box>
298 ) as RenderElement
299 }
300 const open = shown.annotations[shownTab(v.mode.tab, shown.annotations.length) - 1]!
301 return (
302 <Box flexDirection="column">
303 {offer}
304 {rule('rule')}
305 {header(`${SENT_TITLE} “${preview(shown.text, Math.max(8, v.columns - width(BACK_LABEL) - width(SENT_TITLE) - 6))}”`)}
306 <Text> </Text>
307 {tabRow(el, shown.annotations, open.index, 'sent-', act.showSent)}
308 <Text> </Text>
309 {excerptBlock(el, open)}
310 {open.comment === undefined ? (
311 <Text dimColor>{NO_COMMENT}</Text>
312 ) : (
313 <Text wrap="wrap">
314 <Text dimColor>{COMMENT_LABEL}: </Text>
315 {open.comment}
316 </Text>
317 )}
318 {rule('rule-foot')}
319 {v.canJump ? <Button key="jump" plain label={JUMP_ROW_LABEL} onPress={act.jump} /> : null}
320 </Box>
321 ) as RenderElement
322 }
323
324 // The way into the history, under the pending view, once there is one.
325 const historyRow =
326 v.sent.length === 0 ? null : <Button key="history" plain dimColor label={historyRowLabel(v.sent.length)} onPress={act.openHistory} />
327
328 if (v.pending.length === 0) {
329 return (
330 <Box flexDirection="column">
331 {offer}
332 {rule('rule')}
333 <Text dimColor>{PANE_EMPTY}</Text>
334 {historyRow === null ? null : <Text> </Text>}
335 {historyRow}
336 </Box>
337 ) as RenderElement
338 }
339
340 const open = v.pending[shownTab(v.tab, v.pending.length) - 1]!
341 return (
342 <Box flexDirection="column">
343 {offer}
344 {rule('rule')}
345 {tabRow(el, v.pending, open.index, '', act.show, act.remove)}
346 <Text> </Text>
347 {excerptBlock(el, open)}
348 <Input
349 key={commentKey(open.index, v.commentSaves)}
350 label={COMMENT_LABEL}
351 placeholder={COMMENT_PLACEHOLDER}
352 value={open.comment ?? ''}
353 submitLabel={SAVE_LABEL}
354 onInput={value => act.draft(open.index, value)}
355 onSubmit={value => act.comment(open.index, value)}
356 />
357 {rule('rule-foot')}
358 {v.isDraftEmpty ? (
359 <Box key="footer" gap={1}>
360 <Button key="send" variant="primary" label={SEND_BUTTON} onPress={act.send} />
361 <Text dimColor>{SEND_HINT}</Text>
362 </Box>
363 ) : (
364 <Text key="footer" dimColor>
365 {SENT_HINT}
366 </Text>
367 )}
368 {historyRow}
369 </Box>
370 ) as RenderElement
371}
372hooks/prompt-hint.tsx 65 lines1// The line under the prompt: Claude Code's own hint as it draws it, and under
2// it, while the pane is closed, the offer for the selection (✚ Add to chat,
3// its preview, a ✕ that dismisses it), and while Annotations are pending
4// `📎 N annotations · show pane`, a toggle of the pane (`· hide pane` while
5// it is drawn). A view: register.tsx hands it the engine's drawing (`next(e)`).
6import type { BoxProps, ButtonProps, ElementConstructor, RenderElement, TextProps } from 'claude-code'
7
8import { ADD_LABEL, CLOSE_TAB, hintLabel } from './labels'
9import { preview, width } from './text'
10
11export type PromptHintElements = {
12 Box: ElementConstructor<BoxProps>
13 Button: ElementConstructor<ButtonProps>
14 Text: ElementConstructor<TextProps>
15}
16
17export type PromptHintValues = {
18 count: number
19 isPaneDrawn: boolean
20 /** The offer's Excerpt, while there is one (shown only while the pane is not drawn). */
21 offer: string | null
22 /** The cells across the line. */
23 columns: number
24}
25
26/** The line's offer row: the same offer the pane's first row carries (its button, preview and ✕), one row high. */
27function offerRow(el: PromptHintElements, offer: string, columns: number, add: () => unknown, dismiss: () => unknown) {
28 const { Box, Button, Text } = el
29 const room = Math.max(8, columns - width(ADD_LABEL) - width(CLOSE_TAB) - 8)
30 return (
31 <Box key="hint-offer-row" gap={1} paddingLeft={2}>
32 <Button key="hint-add" variant="primary" label={ADD_LABEL} onPress={add} />
33 <Text italic wrap="truncate">
34 “{preview(offer, room)}”
35 </Text>
36 <Button key="hint-dismiss" plain onPress={dismiss}>
37 <Text dimColor>{CLOSE_TAB}</Text>
38 </Button>
39 </Box>
40 )
41}
42
43export function promptHint(
44 el: PromptHintElements,
45 engine: RenderElement,
46 v: PromptHintValues,
47 act: { toggle: () => unknown; add: () => unknown; dismiss: () => unknown },
48): RenderElement {
49 const { Box, Button } = el
50 const offer = v.offer === null || v.isPaneDrawn ? null : offerRow(el, v.offer, v.columns, act.add, act.dismiss)
51 const clip =
52 v.count === 0 ? null : (
53 <Box key="hint-clip-row" paddingLeft={2}>
54 <Button key="hint-clip" plain dimColor label={hintLabel(v.count, v.isPaneDrawn)} onPress={act.toggle} />
55 </Box>
56 )
57 return (
58 <Box flexDirection="column">
59 {engine}
60 {offer}
61 {clip}
62 </Box>
63 ) as RenderElement
64}
65hooks/prompt-row.tsx 85 lines1// A rewritten prompt row in the terminal: Claude Code's own drawing of the
2// prompt as typed, and under it a row of the mod's: `📎 N annotations ↗`,
3// which opens them in the pane, and a card listing them that shows while
4// the pointer is over that row. A view: register.tsx hands it the engine's
5// drawing (`next(e)`), so the row keeps Claude Code's look and theme.
6import type { BoxProps, ButtonProps, ElementConstructor, RenderElement, TextProps } from 'claude-code'
7
8import type { Annotation } from '../types'
9import { SOURCE_LABEL, circled, clipButtonLabel } from './labels'
10import { preview } from './text'
11
12/** The most Annotations the card lists; the rest it counts. */
13export const CARD_MAX = 6
14
15/**
16 * The card's background: opaque, or the rows beneath show through its blank
17 * cells. The theme's prompt-row background, which Claude Code draws a sent
18 * prompt on.
19 */
20export const CARD_BACKGROUND = 'userMessageBackground'
21
22export type PromptRowElements = {
23 Box: ElementConstructor<BoxProps>
24 Button: ElementConstructor<ButtonProps>
25 Text: ElementConstructor<TextProps>
26}
27
28export type PromptRowValues = {
29 /** `hashText` of the rewritten prompt: the row's keys. */
30 hash: string
31 count: number
32 /** Its Annotations: the card lists them. */
33 annotations: readonly Annotation[]
34 /** The cells across the terminal. */
35 columns: number
36}
37
38/** The card's rows: one per Annotation listed, and one counting the rest. */
39export function cardRows(count: number): number {
40 return Math.min(count, CARD_MAX) + (count > CARD_MAX ? 1 : 0)
41}
42
43export function promptRow(el: PromptRowElements, engine: RenderElement, v: PromptRowValues, open: () => unknown): RenderElement {
44 const { Box, Button, Text } = el
45 const listed = v.annotations.slice(0, CARD_MAX)
46 const room = Math.max(16, Math.min(64, v.columns - 24))
47 // Above the button, over the prompt and the rows before it: a card below
48 // would be painted over by the rows drawn after this one.
49 const card =
50 listed.length === 0 ? null : (
51 <Box
52 position="absolute"
53 top={-(cardRows(v.annotations.length) + 2)}
54 left={0}
55 display="none"
56 hover={{ display: 'flex' }}
57 flexDirection="column"
58 borderStyle="round"
59 borderDimColor
60 paddingX={1}
61 backgroundColor={CARD_BACKGROUND}
62 >
63 {listed.map(a => (
64 <Text key={`card-${a.index}`} wrap="truncate">
65 <Text color="claude" bold>
66 {circled(a.index)}
67 </Text>{' '}
68 <Text dimColor>{SOURCE_LABEL[a.source]}</Text> “{preview(a.text, room)}”
69 {a.comment === undefined ? null : <Text dimColor> — {preview(a.comment, Math.max(8, Math.floor(room / 2)))}</Text>}
70 </Text>
71 ))}
72 {v.annotations.length > CARD_MAX ? <Text dimColor>{`+${v.annotations.length - CARD_MAX} more`}</Text> : null}
73 </Box>
74 )
75 return (
76 <Box flexDirection="column">
77 {engine}
78 <Box key={`clip-row-${v.hash}`} paddingLeft={2}>
79 <Button key={`clip-${v.hash}`} plain dimColor label={clipButtonLabel(v.count)} onPress={open} />
80 {card}
81 </Box>
82 </Box>
83 ) as RenderElement
84}
85hooks/rows.ts 37 lines1// What a transcript row draws: Citations and marks in replies, and how a
2// rewritten prompt's row is drawn: its text, or the mod's 📎 row.
3import type { Annotation, Original } from '../types'
4import { marksFor } from './annotations'
5import { drawCitations, drawMarks } from './excerpt'
6import { clipLine } from './labels'
7import { hasAnnotations } from './originals'
8
9/** A reply row's text: its Citations (to `count`, the prompt it answers was sent with, when known) and marks. */
10export function replyText(text: string, requestId: string | undefined, pending: readonly Annotation[], count?: number): string {
11 return drawMarks(drawCitations(text, count), marksFor(pending, requestId), 'assistant')
12}
13
14/** A sent prompt's row, decided: the text it draws, or (in the terminal, an Original with its Annotations kept) that text wrapped with the mod's 📎 row beneath. */
15export type PromptRowView =
16 | { kind: 'text'; text: string }
17 | { kind: 'wrapped'; text: string; hash: string; count: number; annotations: readonly Annotation[] }
18
19/**
20 * How a sent prompt's row draws. As text: no Original for it (ctrl+o
21 * expanded reads the prompt as the model read it), kept without its
22 * Annotations (a `📎` line, but no button: sent before 0.3.0), or another
23 * surface (the terminal is the only one with the 📎 row). Else wrapped:
24 * the Original as typed, the row of the mod's beside it.
25 */
26export function promptRowView(
27 row: { text: string; requestId: string | undefined; isExpanded: boolean; surface: string },
28 found: { hash: string; original: Original } | undefined,
29 pending: readonly Annotation[],
30): PromptRowView {
31 const original = row.isExpanded ? undefined : found?.original
32 if (original === undefined) return { kind: 'text', text: drawMarks(row.text, marksFor(pending, row.requestId), 'user') }
33 const drawn = drawMarks(original.text, marksFor(pending, row.requestId), 'user')
34 if (!hasAnnotations(original) || row.surface !== 'terminal') return { kind: 'text', text: `${drawn}\n${clipLine(original.count)}` }
35 return { kind: 'wrapped', text: drawn, hash: found!.hash, count: original.count, annotations: original.annotations }
36}
37hooks/selection.ts 116 lines1// Deciding what a mouse selection is: an Excerpt worth offering, the pane's
2// or the draft's own words, or one already handled. Pure: register.tsx reads
3// the selection and the state and acts on the answer.
4import type { Annotation, AnnotationSource, Candidate, SelectionNote } from '../types'
5import { isSameExcerpt } from './annotations'
6import { stripMarks } from './excerpt'
7import { isClipLineHead } from './labels'
8import { oneLine } from './text'
9
10/** What `$.ui.selection()` gives; a Candidate is one kept to offer. */
11export type Selection = Candidate
12
13/** Rows the person types into the session from: a terminal, Remote Control, the SDK. */
14const USER_ORIGINS = ['composer', 'bridge', 'sdk']
15
16/** The components a Source is known for, beside the reply and prompt rows. */
17export const TOOL_ROWS = ['ToolUse', 'ToolResult', 'ToolGroup', 'ToolProgress', 'AskUserQuestion'] as const
18export const SYSTEM_ROWS = ['TurnDuration', 'CommandOutput', 'InfoNotice'] as const
19
20/**
21 * The Source of a selection in a row drawn as `component`: a prompt row is
22 * the person's only when they typed it; one a notification, a schedule or
23 * another session sent is Claude Code's own.
24 */
25export function rowSource(component: string, props: unknown): AnnotationSource {
26 if (component === 'AssistantMessage') return 'assistant'
27 if (component === 'UserMessage') {
28 const kind = (props as { origin?: { kind?: string } }).origin?.kind ?? ''
29 return USER_ORIGINS.includes(kind) ? 'user' : 'system'
30 }
31 if ((TOOL_ROWS as readonly string[]).includes(component)) return 'tool'
32 if ((SYSTEM_ROWS as readonly string[]).includes(component)) return 'system'
33 return 'transcript'
34}
35
36export function selectionKey(s: Selection): string {
37 return `${s.requestId ?? ''}\u0000${s.text}`
38}
39
40/**
41 * The Excerpt a selection holds: its text with marks and `📎` lines (this
42 * mod's own, any head of one) gone; null when nothing is left. Plain JSON,
43 * fit for state: no `requestId` key when it lies in no row.
44 */
45export function excerptOf(s: Selection | undefined): Selection | null {
46 if (s === undefined) return null
47 const text = stripMarks(s.text)
48 .split('\n')
49 .filter(line => !isClipLineHead(line))
50 .join('\n')
51 .trim()
52 if (text === '') return null
53 return s.requestId === undefined ? { text } : { text, requestId: s.requestId }
54}
55
56const flatten = oneLine
57
58/** What the pane and the prompt box hold while a selection is judged. */
59export type Surroundings = {
60 draft: string
61 pending: readonly Annotation[]
62 /** `selectionKey` of the selection last added or dismissed. */
63 handled: string | null
64 /** Every word the pane draws, beyond the offer's preview: a selection of them is the pane's own. */
65 paneWords: readonly string[]
66}
67
68/**
69 * Whether a selection with no row lies in the prompt box or in the pane
70 * rather than in the transcript: its text is the draft's or the pane's own.
71 */
72function isOutsideTranscript(excerpt: Selection, around: Surroundings): boolean {
73 if (excerpt.requestId !== undefined) return false
74 // A selection across the Excerpt's frame in the pane picks up its border.
75 const text = flatten(excerpt.text.replace(/[│╭╮╰╯─]/g, ' '))
76 return flatten(around.draft).includes(text) || around.paneWords.some(line => flatten(line).includes(text))
77}
78
79/** Whether `selection` is where Annotation `a` was added from: its Excerpt, in its row. */
80export function isSelectionOf(selection: Selection | undefined, a: { text: string; requestId?: string }): boolean {
81 const excerpt = excerptOf(selection)
82 return excerpt !== null && isSameExcerpt(excerpt, a)
83}
84
85/**
86 * An Excerpt to offer, with the key that marks its selection handled; or
87 * why not: `nothing` to offer, `pending` as Annotation `index`, or
88 * `handled` (just added, or its offer dismissed).
89 */
90export type Verdict =
91 | { excerpt: Selection; key: string }
92 | { reason: 'nothing' }
93 | { reason: 'pending'; text: string; index: number }
94 | { reason: 'handled' }
95
96/**
97 * What to do with a selection: offer (and add) its Excerpt, or not —
98 * `nothing` when it holds none or lies outside the transcript, `pending`
99 * when its Excerpt is (same Excerpt, same row), `handled` when it was last
100 * added or its offer dismissed.
101 */
102export function judge(selection: Selection | undefined, around: Surroundings): Verdict {
103 const excerpt = excerptOf(selection)
104 if (selection === undefined || excerpt === null || isOutsideTranscript(excerpt, around)) return { reason: 'nothing' }
105 const added = around.pending.find(a => isSameExcerpt(a, excerpt))
106 if (added !== undefined) return { reason: 'pending', text: excerpt.text, index: added.index }
107 const key = selectionKey(selection)
108 if (key === around.handled) return { reason: 'handled' }
109 return { excerpt, key }
110}
111
112/** What the pane's first row says of a selection it does not offer: that it is added, as which; nothing else. */
113export function noteOf(verdict: Verdict): SelectionNote | null {
114 return 'reason' in verdict && verdict.reason === 'pending' ? { text: verdict.text, index: verdict.index } : null
115}
116hooks/originals.ts 147 lines1// The Originals: what was typed for each prompt sent with Annotations, by the
2// hash of its rewritten text, in state and mirrored in `$.store` (ADR 0004).
3// Every rule of how they are kept lives here: the key formats, the newest
4// 200, the order of the writes, 0.4.0's map read and never written. What
5// touches the store comes back as writes, for register.tsx to make in order.
6import type { Annotation, Original } from '../types'
7import { hashText } from './hash'
8
9const KEY_PREFIX = 'original:'
10const REPLY_PREFIX = 'reply:'
11/** The one map of Originals 0.4.0 and earlier kept: read, never written. */
12const LEGACY_KEY = 'originals'
13export const MAX_ORIGINALS = 200
14
15export type Originals = Record<string, Original>
16
17/** One write to the store; a list of them is made in its order. */
18export type StoreWrite = { set: string; value: unknown } | { delete: string }
19
20/** An Original known to hold its Annotations (one sent from 0.3.0 on, with some). */
21export type Annotated = Original & { annotations: Annotation[] }
22
23/** The key a rewritten prompt's Original is kept under: its text as the row and the transcript give it, byte for byte. */
24export function promptHash(rewritten: string): string {
25 return hashText(rewritten)
26}
27
28/** The Original kept for a row's or a message's text, and its hash. */
29export function originalOf(map: Originals, rewritten: string): { hash: string; original: Original } | undefined {
30 const hash = promptHash(rewritten)
31 const original = map[hash]
32 return original === undefined ? undefined : { hash, original }
33}
34
35/** Whether an Original holds Annotations to show again. */
36export function hasAnnotations(o: Original | undefined): o is Annotated {
37 return o?.annotations !== undefined && o.annotations.length > 0
38}
39
40/**
41 * A prompt about to be sent, in state: the row draws from it as soon as the
42 * engine draws the rewritten text. Sent again, it keeps the replies kept
43 * with it, as the store does.
44 */
45export function remembered(map: Originals, hash: string, original: Original): Originals {
46 const replies = map[hash]?.replies
47 return { ...map, [hash]: replies === undefined ? original : { ...original, replies } }
48}
49
50/** A prompt that was not sent after all (another plugin dropped it): its entry as it was before. */
51export function forgotten(map: Originals, hash: string, was: Original | undefined): Originals {
52 if (was !== undefined) return { ...map, [hash]: was }
53 const { [hash]: _, ...rest } = map
54 return rest
55}
56
57/**
58 * A sent prompt, in the store: its record deleted first and set, so the
59 * store's insertion order counts it as the newest; then, past the newest
60 * 200 records, the oldest with their replies' keys. `keys` are the store's
61 * keys before these writes. State lets go of the same prompts, and of no
62 * other: one only 0.4.0's map holds stays.
63 */
64export function stored(map: Originals, hash: string, keys: readonly string[]): { originals: Originals; writes: StoreWrite[] } {
65 const key = originalKey(hash)
66 const { replies: _, ...record } = map[hash]!
67 const after = [...keys.filter(k => k !== key), key]
68 const records = after.filter(k => hashOfKey(k) !== undefined)
69 const old = new Set(records.slice(0, Math.max(0, records.length - MAX_ORIGINALS)).map(k => hashOfKey(k)!))
70 const gone = after.filter(k => old.has(hashOfKey(k) ?? replyOfKey(k)?.hash ?? ''))
71 const originals = old.size === 0 ? map : Object.fromEntries(Object.entries(map).filter(([h]) => !old.has(h)))
72 return { originals, writes: [{ delete: key }, { set: key, value: record }, ...gone.map(k => ({ delete: k }))] }
73}
74
75/**
76 * Reply rows (requestIds) kept with a sent prompt: in state, and in the
77 * store under a key each, set and never read back to be set again, so two
78 * sessions keeping replies to the same prompt keep both.
79 */
80export function withReplies(map: Originals, hash: string, ids: readonly string[]): { originals: Originals; writes: StoreWrite[] } {
81 const o = map[hash]
82 const originals = o === undefined || ids.length === 0 ? map : { ...map, [hash]: { ...o, replies: [...new Set([...(o.replies ?? []), ...ids])] } }
83 return { originals, writes: ids.map(id => ({ set: replyKey(hash, id), value: true })) }
84}
85
86/** The store keys a load reads the values of: 0.4.0's map and every record. */
87export function keysToLoad(keys: readonly string[]): string[] {
88 return [LEGACY_KEY, ...keys.filter(k => hashOfKey(k) !== undefined)]
89}
90
91/**
92 * The Originals the store holds, from the values of `keysToLoad` and all its
93 * keys: those of 0.4.0's map, each under the record of its own key where
94 * there is one, the replies of all three (that map, a record of 0.4.1, the
95 * reply keys) together. Reads only, so it cannot drop what another session
96 * writes meanwhile.
97 */
98export function loaded(values: Readonly<Record<string, unknown>>, keys: readonly string[]): Originals {
99 const map: Originals = {}
100 const legacy = values[LEGACY_KEY]
101 if (typeof legacy === 'object' && legacy !== null) {
102 for (const [hash, o] of Object.entries(legacy)) if (isOriginal(o)) map[hash] = o
103 }
104 for (const key of keys) {
105 const hash = hashOfKey(key)
106 const o = hash === undefined ? undefined : values[key]
107 if (hash === undefined || !isOriginal(o)) continue
108 const older = map[hash]?.replies ?? []
109 map[hash] = older.length > 0 ? addReplies(o, older) : o
110 }
111 for (const key of keys) {
112 const r = replyOfKey(key)
113 if (r !== undefined && map[r.hash] !== undefined) map[r.hash] = addReplies(map[r.hash]!, [r.id])
114 }
115 return map
116}
117
118/** The store key of one sent prompt's Original. */
119export function originalKey(hash: string): string {
120 return `${KEY_PREFIX}${hash}`
121}
122
123/** The store key of one reply kept with a sent prompt. (A hash holds no colon.) */
124export function replyKey(hash: string, id: string): string {
125 return `${REPLY_PREFIX}${hash}:${id}`
126}
127
128function hashOfKey(key: string): string | undefined {
129 return key.startsWith(KEY_PREFIX) ? key.slice(KEY_PREFIX.length) : undefined
130}
131
132function replyOfKey(key: string): { hash: string; id: string } | undefined {
133 if (!key.startsWith(REPLY_PREFIX)) return undefined
134 const rest = key.slice(REPLY_PREFIX.length)
135 const at = rest.indexOf(':')
136 return at <= 0 ? undefined : { hash: rest.slice(0, at), id: rest.slice(at + 1) }
137}
138
139function isOriginal(value: unknown): value is Original {
140 const o = value as Partial<Original> | null
141 return typeof o === 'object' && o !== null && typeof o.text === 'string' && typeof o.count === 'number'
142}
143
144function addReplies(original: Original, more: readonly string[]): Original {
145 return { ...original, replies: [...new Set([...(original.replies ?? []), ...more])] }
146}
147hooks/send.ts 15 lines1// What the person's prompt carries once the Annotations go with it.
2import type { Annotation, Original } from '../types'
3import { renderTemplate } from './template'
4
5export type Annotated = {
6 text: string
7 /** What the prompt's row draws instead: the text as typed. */
8 original: Original
9}
10
11/** The prompt rewritten by the Annotation Template, and what was typed. */
12export function annotated(text: string, list: readonly Annotation[]): Annotated {
13 return { text: renderTemplate(text, list), original: { text, count: list.length, annotations: [...list] } }
14}
15