Claude Code mods: draws mermaid diagrams in replies as Unicode text, jumps between prompts, and copies a reply's markdown

Claude Code mods from SimpleClaude. A mod is a plugin that changes Claude Code's own interface; see the mods documentation.
sc-mods does three things:
◀ and ▶ buttons in the band above the prompt, which scroll the conversation to your previous or next prompt.⧉ copy button under Claude's replies, which copies the reply's markdown.When a reply contains a closed mermaid code block, the mod runs merman on the diagram and shows the drawing in place of the source. Nothing else in the reply changes, and the conversation the model sees still holds the mermaid source.
Before:
flowchart LR Plan --> Build --> Review --> Ship
After:
┌──────┐ ┌───────┐ ┌────────┐ ┌──────┐
│ │ │ │ │ │ │ │
│ Plan ├──►│ Build ├──►│ Review ├──►│ Ship │
│ │ │ │ │ │ │ │
└──────┘ └───────┘ └────────┘ └──────┘
A mermaid code block is one whose fence is three or more backticks or tildes and whose language, the first word after the fence, is mermaid in any case. It closes on the same fence character repeated at least as many times. A block indented inside a list item or a > blockquote is drawn there, with the drawing kept inside the item or quote. A mermaid block inside another code block, such as a ``markdown example, or inside an HTML comment, is left as it is.
The drawing has to fit the terminal's width. For a flowchart that is too wide, the mod tries a compact layout, then wraps long node labels, then turns a left-to-right chart top-to-bottom. A sequence diagram gets a second, automatic layout. If no layout fits, or merman cannot read the diagram, the source stays as it was.
The band above the prompt shows two buttons, ◀ and ▶, with a dim count between them: [ ◀ ] 2/5 [ ▶ ] while the arrows are on the second of five prompts. Click a button to scroll the conversation so your previous or next prompt sits at the bottom of the view, just above the prompt box, with Claude's reply to it out of view below. The first few prompts cannot reach the bottom, so the view stops at the start of the conversation. On the newest prompt, ▶ scrolls to the end of the conversation. The hotkeys 1 and 2 press the buttons while the band holds the keyboard: press ctrl+x then tab to move the keyboard to the band, or click in it; Esc returns it to the prompt box.
The arrows count every prompt you send while the mod runs. When the mod loads into a conversation that already has prompts (claude --resume, claude --continue, a plugin reload), it counts that conversation's prompts from its last compaction on. The arrows step from the prompt they last jumped to; each new prompt you send puts them back on the newest. Scrolling the conversation yourself does not move them. A toast says so when there is no earlier prompt, or no later one in a conversation the mod loaded into that has not stored a row since, and gives Claude Code's reason when it does not scroll.
Jumping needs fullscreen mode, where Claude Code draws the conversation itself. The classic layout leaves the conversation to the terminal's scrollback and refuses the scroll.
A dim ⧉ copy button sits under each block of Claude's reply text. Click it to put that block's markdown on the clipboard, as Claude wrote it: a mermaid diagram is copied as its source, not as the drawing. A toast says how many characters were copied, or why nothing was. A reply split by tool calls has a button under each block of text.
The button takes a mouse click only. The conversation's rows can't take keyboard focus, so no key presses it.
claude plugin install sc-mods --marketplace kylesnowschwartz/SimpleClaude
The plugin holds no merman binary. The first time a diagram needs drawing, bin/merman-cli downloads the merman release archive for your machine from merman's GitHub releases, checks it against the sha256 pinned in bin/merman.pin, and keeps the binary and merman's licenses in ${XDG_CACHE_HOME:-~/.cache}/sc-mods/merman-<version>/. Later sessions run the cached binary, so the network is needed once per merman version. A plugin update that pins a new version downloads it and removes the old one from the cache.
merman-cli runs on macOS and on Linux with glibc, on arm64 and x86_64. The download needs curl and shasum or sha256sum, and on Linux also xz.
A mod runs with your permissions. It runs inside Claude Code and can start programs as you. This one starts merman-cli to draw diagrams, and find and grep to read the session's own transcript file (<session id>.jsonl under ~/.claude/projects/, or $CLAUDE_CONFIG_DIR/projects/). Its only network call and its only file writes are the merman download above. The copy button writes to the clipboard through Claude Code, the way /copy does. Read hooks/register.ts and bin/merman-cli before you install it.
| Setting | What it does |
|---|---|
MERMAN_PATH | Absolute path to a merman-cli to run instead of the downloaded one. With it set, nothing is downloaded. Set it at install with --config MERMAN_PATH=/path/to/merman-cli, or later with /plugin configure. |
If merman-cli cannot run, every diagram stays as source and Claude Code shows one notice with the reason, such as a failed download or a missing curl.
Load the plugin from the checkout, either for one session:
claude --plugin-dir plugins/sc-mods
or as an installed plugin that reads straight from your checkout:
claude plugin marketplace add /path/to/SimpleClaude
claude plugin install sc-mods@simpleclaude
Then edit the files and run /reload-plugins.
Check and test the mod:
just test-mods
These tests stand in for merman-cli, so they need no binary. just test includes the launcher's tests, which download from local archives rather than the network. To draw a flowchart, a sequence diagram and an invalid diagram with the real merman-cli, install bun, then run:
just test-mods-real
It downloads merman-cli into the cache if it is not there, and stops with the launcher's reason if merman-cli cannot run on your machine.
just check-merman reports whether a newer merman release is out. To move to it:
just update-merman <version> writes the version and the published checksum of each platform's archive to bin/merman.pin.just test-mods and just test-mods-real.claude --plugin-dir plugins/sc-mods.just bump and just release.claude --resume, claude --continue, a plugin reload), it runs find and grep once over the session's transcript file to learn them, on load or at the first press. Without those commands on the PATH, those prompts are not counted. Prompts from before the conversation's last compaction are not counted: Claude Code draws a resumed conversation from that point, so there is nothing to scroll to./clear or /resume.MERMAN_PATH points at a merman-cli.hooks/register.ts 149 lines1import type { EngineInterface, Register } from 'claude-code'
2import { findMermaidFences, replaceFences, type FenceReplacement, type MermaidFence } from './fences'
3import { drawDiagram, type Runner } from './merman'
4import { registerPromptJump } from './prompt-jump'
5import { registerReplyCopy } from './reply-copy'
6
7// The reply's indent plus a margin column on each side.
8const GUTTER = 4
9const WIDTH_WITHOUT_VIEWPORT = 100
10const RUN_TIMEOUT_MS = 5000
11// The first check of a merman version downloads it, and a new binary's first
12// launch can wait on the OS scanning it.
13const CHECK_TIMEOUT_MS = 15000
14const NOTICE_TIMEOUT_MS = 15000
15
16// How Claude Code words a $.process.run rejection for a command that
17// outlived its timeoutMs; any other rejection is a failure to run.
18const TIMED_OUT = /still running after/
19
20// Enough for every diagram of a long session, each at a few widths.
21const MAX_DRAWINGS = 200
22
23/**
24 * Each diagram's drawing, finished or under way, keyed by width and source;
25 * undefined keeps the source. A draw that rejects is removed so a later
26 * render tries it again. Past MAX_DRAWINGS the least recently used goes.
27 */
28const drawings = new Map<string, Promise<string | undefined>>()
29
30/** Whether merman-cli runs; `timed-out` is not an answer and is asked again. */
31type MermanCheck = 'runnable' | 'missing' | 'timed-out'
32
33let mermanCheck: Promise<MermanCheck> | undefined
34
35const textBlock = (drawing: string) => '```text\n' + drawing + '\n```'
36
37/** The notice for a merman-cli that cannot run; `reason` is its last stderr line, if any. */
38function missingMermanNotice(reason: string | undefined): string {
39 const because = reason ? ` (${reason})` : ''
40 return (
41 `sc-mods: merman-cli could not run${because}, so mermaid diagrams stay as source. ` +
42 'To fix it, restart Claude Code once the cause is fixed, or set MERMAN_PATH to a merman-cli.'
43 )
44}
45
46const lastLine = (text: string) => text.trim().split('\n').pop() || undefined
47
48async function checkMerman($: EngineInterface, bin: string): Promise<MermanCheck> {
49 let reason: string | undefined
50 try {
51 const { exitCode, stderr } = await $.process.run([bin, '--version'], { timeoutMs: CHECK_TIMEOUT_MS })
52 if (exitCode === 0) return 'runnable'
53 reason = lastLine(stderr)
54 } catch (error) {
55 if (error instanceof Error && TIMED_OUT.test(error.message)) return 'timed-out'
56 }
57 $.ui.toast(missingMermanNotice(reason), { timeoutMs: NOTICE_TIMEOUT_MS })
58 return 'missing'
59}
60
61/** A cached drawing, moved to the newest end so it is the last to go. */
62function recall(key: string): Promise<string | undefined> | undefined {
63 const drawing = drawings.get(key)
64 if (drawing === undefined) return undefined
65
66 drawings.delete(key)
67 drawings.set(key, drawing)
68 return drawing
69}
70
71function remember(key: string, drawing: Promise<string | undefined>) {
72 drawings.set(key, drawing)
73 if (drawings.size <= MAX_DRAWINGS) return
74
75 // A Map iterates in insertion order, so its first key is the least recently used.
76 const [leastRecentKey] = drawings.keys()
77 if (leastRecentKey !== undefined) drawings.delete(leastRecentKey)
78}
79
80function startDrawing(run: Runner, source: string, width: number, key: string): Promise<string | undefined> {
81 const attempt = drawDiagram(run, source, width)
82 attempt.catch(() => {
83 if (drawings.get(key) === attempt) drawings.delete(key)
84 })
85 remember(key, attempt)
86 return attempt
87}
88
89function drawingFor(run: Runner, source: string, width: number): Promise<string | undefined> {
90 const key = `${width}\0${source}`
91 const drawing = recall(key) ?? startDrawing(run, source, width, key)
92 return drawing.catch(() => undefined)
93}
94
95type DrawConditions = { run: Runner; replyColumns: number }
96
97// A list or quote prefix is ASCII, one cell a character.
98const widthFor = (fence: MermaidFence, replyColumns: number) => replyColumns - fence.linePrefix.length
99
100/**
101 * A text block of the fence's drawing. Undefined keeps the source: the
102 * fence has not closed, or merman refused it.
103 */
104async function replacementText(fence: MermaidFence, { run, replyColumns }: DrawConditions): Promise<string | undefined> {
105 if (!fence.isClosed) return undefined
106
107 const drawing = await drawingFor(run, fence.source, widthFor(fence, replyColumns))
108 return drawing === undefined ? undefined : textBlock(drawing)
109}
110
111type PossibleReplacement = { fence: MermaidFence; text: string | undefined }
112
113const replacesSource = (candidate: PossibleReplacement): candidate is FenceReplacement => candidate.text !== undefined
114
115async function replacementsFor(fences: MermaidFence[], conditions: DrawConditions): Promise<FenceReplacement[]> {
116 const candidates = await Promise.all(
117 fences.map(async fence => ({ fence, text: await replacementText(fence, conditions) })),
118 )
119 return candidates.filter(replacesSource)
120}
121
122export const register: Register = (on, options) => {
123 // Registered first so it sits outermost: it copies the reply's text as
124 // Claude wrote it and puts its button under the diagrams drawn beneath it.
125 registerReplyCopy(on)
126 registerPromptJump(on)
127
128 const configuredPath = typeof options.MERMAN_PATH === 'string' ? options.MERMAN_PATH.trim() : ''
129
130 on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
131 const fences = findMermaidFences(e.props.text)
132 if (fences.length === 0) return next(e)
133
134 const bin = configuredPath || `${$.plugin.root}/bin/merman-cli`
135 const pendingCheck = (mermanCheck ??= checkMerman($, bin))
136 const check = await pendingCheck
137 if (check === 'timed-out' && mermanCheck === pendingCheck) mermanCheck = undefined
138 if (check !== 'runnable') return next(e)
139
140 const replyColumns = e.viewport ? e.viewport.columns - GUTTER : WIDTH_WITHOUT_VIEWPORT
141 const run: Runner = (args, stdin) => $.process.run([bin, ...args], { stdin, timeoutMs: RUN_TIMEOUT_MS })
142 const replacements = await replacementsFor(fences, { run, replyColumns })
143 if (replacements.length === 0) return next(e)
144
145 const text = replaceFences(e.props.text, replacements)
146 return next({ ...e, props: { ...e.props, text } })
147 })
148}
149hooks/fences.ts 252 lines1/**
2 * A mermaid code block in a reply. A block inside a list item or a
3 * blockquote carries that container's prefix on each of its lines.
4 */
5export type MermaidFence = {
6 /** Where the block starts and ends in the reply, its fence lines included. */
7 start: number
8 end: number
9 /** The diagram: the lines between the fence lines, without their prefix. */
10 source: string
11 /** False while the closing fence has not arrived. */
12 isClosed: boolean
13 /** What the opening line holds before its fence: indentation, `>` and list markers. */
14 openingPrefix: string
15 /** What each later line of the block starts with. */
16 linePrefix: string
17}
18
19/** One block's new text, put in place of the block's lines. */
20export type FenceReplacement = { fence: MermaidFence; text: string }
21
22/** `isLast` marks the reply's final line, which can be cut off mid-line. */
23type Line = { text: string; start: number; end: number; isLast: boolean }
24
25type FenceRun = { char: string; length: number; info: string }
26
27/** A code block whose closing fence has not been read yet. */
28type OpenFence = FenceRun & {
29 isMermaid: boolean
30 start: number
31 end: number
32 openingPrefix: string
33 linePrefix: string
34 bodyLines: string[]
35}
36
37const FENCE_CHARS = ['`', '~']
38const MIN_FENCE_LENGTH = 3
39const DIAGRAM_LANGUAGE = 'mermaid'
40const COMMENT_OPEN = '<!--'
41const COMMENT_CLOSE = '-->'
42const QUOTE_MARKER = '>'
43
44// The pieces a container prefix is made of, read left to right.
45const INDENT = /^ +/
46const QUOTE = /^> ?/
47const LIST_MARKER = /^(?:[-*+]|\d{1,9}[.)]) /
48const PREFIX_PIECES = [INDENT, QUOTE, LIST_MARKER]
49const LIST_MARKER_ANYWHERE = /[-*+]|\d{1,9}[.)]/g
50
51function splitLines(text: string): Line[] {
52 const lines: Line[] = []
53 let start = 0
54 const lineTexts = text.split('\n')
55 for (const [index, lineText] of lineTexts.entries()) {
56 lines.push({ text: lineText, start, end: start + lineText.length, isLast: index === lineTexts.length - 1 })
57 start += lineText.length + 1
58 }
59 return lines
60}
61
62/** The indentation, quote marker or list marker that `text` starts with. */
63function nextPrefixPiece(text: string): string | undefined {
64 for (const pattern of PREFIX_PIECES) {
65 const match = pattern.exec(text)
66 if (match !== null) return match[0]
67 }
68 return undefined
69}
70
71/** Splits a line into its container prefix and what follows it. */
72function readPrefix(line: string): { prefix: string; rest: string } {
73 let rest = line
74 let piece = nextPrefixPiece(rest)
75 while (piece !== undefined) {
76 rest = rest.slice(piece.length)
77 piece = nextPrefixPiece(rest)
78 }
79 return { prefix: line.slice(0, line.length - rest.length), rest }
80}
81
82/** The prefix a block's later lines carry: list markers become spaces, quote markers stay. */
83function continuationOf(openingPrefix: string): string {
84 return openingPrefix.replace(LIST_MARKER_ANYWHERE, marker => ' '.repeat(marker.length))
85}
86
87/**
88 * The line without the block's prefix. Undefined when a quote marker is
89 * missing, as that ends the blockquote and the block inside it. Markdown
90 * lets a later line drop indentation, so missing spaces are allowed.
91 */
92function stripLinePrefix(line: string, linePrefix: string): string | undefined {
93 let at = 0
94 for (const expected of linePrefix) {
95 if (line[at] === expected) {
96 at += 1
97 } else if (expected === QUOTE_MARKER) {
98 return undefined
99 }
100 }
101 return line.slice(at)
102}
103
104function readFenceRun(text: string): FenceRun | undefined {
105 const char = text[0] ?? ''
106 if (!FENCE_CHARS.includes(char)) return undefined
107
108 let length = 0
109 while (text[length] === char) length += 1
110 if (length < MIN_FENCE_LENGTH) return undefined
111
112 return { char, length, info: text.slice(length).trim() }
113}
114
115/** A backtick fence's info string cannot hold a backtick: that line is inline code. */
116function readOpeningFence(text: string): FenceRun | undefined {
117 const run = readFenceRun(text)
118 if (run === undefined) return undefined
119 if (run.char === '`' && run.info.includes('`')) return undefined
120 return run
121}
122
123function closesFence(text: string, open: OpenFence): boolean {
124 const run = readFenceRun(text.trimStart())
125 if (run === undefined) return false
126 return run.char === open.char && run.length >= open.length && run.info === ''
127}
128
129/** Markdown names a code block's language by the first word of its info string. */
130function namesMermaid(info: string): boolean {
131 const language = info.split(/\s+/)[0] ?? ''
132 return language.toLowerCase() === DIAGRAM_LANGUAGE
133}
134
135/**
136 * Reads a reply line by line, tracking every code block, so a mermaid fence
137 * quoted inside another code block, as in a markdown example, is not taken
138 * for a diagram. HTML comments are skipped the same way.
139 */
140class FenceScanner {
141 private readonly fences: MermaidFence[] = []
142 private open: OpenFence | undefined
143 private isInComment = false
144
145 scan(text: string): MermaidFence[] {
146 for (const line of splitLines(text)) this.read(line)
147 if (this.open !== undefined) this.finish(this.open, false)
148 return this.fences
149 }
150
151 private read(line: Line): void {
152 if (this.open !== undefined) {
153 this.readInsideFence(this.open, line)
154 } else if (this.isInComment) {
155 this.readInsideComment(line)
156 } else {
157 this.readOutside(line)
158 }
159 }
160
161 private readInsideFence(open: OpenFence, line: Line): void {
162 const body = stripLinePrefix(line.text, open.linePrefix)
163 if (body === undefined) {
164 this.readPastQuote(open, line)
165 return
166 }
167
168 open.end = line.end
169 if (closesFence(body, open)) {
170 this.finish(open, true)
171 return
172 }
173 open.bodyLines.push(body)
174 }
175
176 /** A line without the block's quote marker ends the quote, and the block inside it. */
177 private readPastQuote(open: OpenFence, line: Line): void {
178 // A reply can end part way into a line, so a blank last line does not
179 // show that the blockquote has ended.
180 if (line.isLast && line.text.trim() === '') return
181
182 this.finish(open, true)
183 this.read(line)
184 }
185
186 private readInsideComment(line: Line): void {
187 if (line.text.includes(COMMENT_CLOSE)) this.isInComment = false
188 }
189
190 private readOutside(line: Line): void {
191 const { prefix, rest } = readPrefix(line.text)
192 if (rest.startsWith(COMMENT_OPEN)) {
193 this.isInComment = !rest.includes(COMMENT_CLOSE, COMMENT_OPEN.length)
194 return
195 }
196
197 const run = readOpeningFence(rest)
198 if (run === undefined) return
199 this.open = {
200 ...run,
201 isMermaid: namesMermaid(run.info),
202 start: line.start,
203 end: line.end,
204 openingPrefix: prefix,
205 linePrefix: continuationOf(prefix),
206 bodyLines: [],
207 }
208 }
209
210 private finish(open: OpenFence, isClosed: boolean): void {
211 this.open = undefined
212 if (!open.isMermaid) return
213
214 this.fences.push({
215 start: open.start,
216 end: open.end,
217 source: open.bodyLines.join('\n'),
218 isClosed,
219 openingPrefix: open.openingPrefix,
220 linePrefix: open.linePrefix,
221 })
222 }
223}
224
225/**
226 * Every mermaid code block in a reply, in order, including one whose closing
227 * fence has not arrived. The fence is three or more backticks or tildes, and
228 * a block closes on the same character repeated at least as many times.
229 */
230export function findMermaidFences(text: string): MermaidFence[] {
231 return new FenceScanner().scan(text)
232}
233
234/** Puts a block's prefix back on each line of its replacement, so it stays inside its list item or blockquote. */
235function withPrefix(fence: MermaidFence, text: string): string {
236 return text
237 .split('\n')
238 .map((line, index) => (index === 0 ? fence.openingPrefix : fence.linePrefix) + line)
239 .join('\n')
240}
241
242/** The reply with each replaced block's lines swapped for its new text. */
243export function replaceFences(text: string, replacements: readonly FenceReplacement[]): string {
244 let rewritten = ''
245 let copiedUpTo = 0
246 for (const { fence, text: replacement } of replacements) {
247 rewritten += text.slice(copiedUpTo, fence.start) + withPrefix(fence, replacement)
248 copiedUpTo = fence.end
249 }
250 return rewritten + text.slice(copiedUpTo)
251}
252hooks/merman.ts 79 lines1export type RunResult = { exitCode: number; stdout: string; stderr: string }
2
3/** Runs merman-cli with these arguments and the diagram source on stdin. */
4export type Runner = (args: string[], stdin: string) => Promise<RunResult>
5
6const RENDER = ['render', '-q', '-f', 'unicode', '--ascii-trim-trailing-spaces']
7const COMPACT = ['--ascii-layout-profile', 'compact']
8const AUTO = ['--ascii-layout-profile', 'auto']
9const MIRROR_ACTORS = ['--sequence-mirror-actors']
10const OVERFLOW = /exceeds requested width/
11// Anchored at the start of a diagram's body, where its keyword line stands.
12const HORIZONTAL_HEADER = /^([ \t]*(?:flowchart|graph)\s+)(LR|RL)\b/
13// What mermaid allows before the keyword line: one `---` frontmatter block,
14// then blank lines, `%%` comment lines and `%%{...}%%` directives.
15const PREAMBLE = /^(?:\s*---[ \t]*\n[\s\S]*?\n[ \t]*---[ \t]*(?:\n|$))?(?:[ \t]*(?:%%\{[\s\S]*?\}%%[ \t]*|%%.*)?(?:\n|$))*/
16
17type Attempt = { source: string; flags: string[] }
18
19/** Splits a diagram into what precedes its keyword line and the rest. */
20function splitPreamble(source: string): { preamble: string; body: string } {
21 const preamble = PREAMBLE.exec(source)?.[0] ?? ''
22 return { preamble, body: source.slice(preamble.length) }
23}
24
25const diagramType = (source: string) => splitPreamble(source).body.trimStart().split(/\s/)[0] ?? ''
26
27/** The same diagram drawn top to bottom, when its header is LR or RL. */
28function verticalVariant(source: string): string | undefined {
29 const { preamble, body } = splitPreamble(source)
30 return HORIZONTAL_HEADER.test(body) ? preamble + body.replace(HORIZONTAL_HEADER, '$1TD') : undefined
31}
32
33const wrapLabels = (columns: number) => [...COMPACT, '--ascii-flowchart-node-label-wrap-width', String(columns)]
34
35function flowchartAttempts(source: string): Attempt[] {
36 // The auto profile draws the canonical layout and switches to compact only
37 // when canonical is too wide, because compact merges the borders of
38 // side-by-side subgraphs. The label-wrap steps run only once a diagram is
39 // already too wide, so they stay compact.
40 const layouts = [AUTO, wrapLabels(12), wrapLabels(6)]
41 const vertical = verticalVariant(source)
42 const sources = vertical === undefined ? [source] : [source, vertical]
43 return sources.flatMap(s => layouts.map(flags => ({ source: s, flags })))
44}
45
46/** The layouts to try for one diagram, in the order tried. */
47function attemptsFor(source: string): Attempt[] {
48 switch (diagramType(source)) {
49 case 'flowchart':
50 case 'graph':
51 return flowchartAttempts(source)
52 case 'sequenceDiagram':
53 return [
54 { source, flags: MIRROR_ACTORS },
55 { source, flags: [...MIRROR_ACTORS, '--ascii-layout-profile', 'auto'] },
56 ]
57 default:
58 // merman rejects the compact and auto layout profiles for state diagrams.
59 return [{ source, flags: [] }]
60 }
61}
62
63const trimEnd = (text: string) => text.replace(/[ \t]+$/gm, '').replace(/\n+$/, '')
64
65/**
66 * Draws one mermaid diagram as Unicode text no wider than `width` columns,
67 * trying each layout in turn until one fits. Undefined when none fits or
68 * merman refuses the source.
69 */
70export async function drawDiagram(run: Runner, source: string, width: number): Promise<string | undefined> {
71 const bound = ['--ascii-max-width', String(width), '--ascii-overflow', 'error', '-o', '-', '-']
72 for (const { source: attemptSource, flags } of attemptsFor(source)) {
73 const result = await run([...RENDER, ...flags, ...bound], attemptSource)
74 if (result.exitCode === 0) return trimEnd(result.stdout)
75 if (!OVERFLOW.test(result.stderr)) return undefined
76 }
77 return undefined
78}
79hooks/prompt-jump.tsx 333 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On, ProcessRunResult, SessionAppendDoor, SessionAppendInput } from 'claude-code'
3
4/** A step through the person's prompts: back to the previous one, or on to the next. */
5export type Step = -1 | 1
6
7/**
8 * The person's prompts the conversation keeps, by their stored row ids, in
9 * the order sent: those its transcript file held when the plugin loaded,
10 * then those stored since. `at` is the index of the prompt the arrows last
11 * jumped to, or undefined while they rest on the newest prompt, where every
12 * new prompt puts them. `storedRead` is the read of the transcript file,
13 * under way or done; undefined until it starts, and again when it found no
14 * file or a file behind the conversation, so the next need tries again.
15 * `endRow` is the id of the row the conversation stored last, where its end
16 * is drawn; undefined until it stores one while the plugin runs.
17 */
18export type PromptTrail = { prompts: string[]; at: number | undefined; storedRead: Promise<void> | undefined; endRow: string | undefined }
19
20export const newTrail = (): PromptTrail => ({ prompts: [], at: undefined, storedRead: undefined, endRow: undefined })
21
22/** Whether the person sent it: typed at the terminal, or through Remote Control. */
23export const isPersonsPrompt = (origin: { kind: string }) => origin.kind === 'composer' || origin.kind === 'bridge'
24
25/**
26 * The id of the person's prompt a `session.append` stores in the main
27 * conversation; undefined for any other row. A prompt sent while a turn
28 * runs its tools is delivered into that turn as a `queued_command` row, and
29 * drawn as a prompt all the same.
30 */
31export function promptIdOf(e: SessionAppendInput): string | undefined {
32 const isTyped = e.door === 'prompt' || (e.door === 'delivery' && e.message.name === 'queued_command')
33 const isPrompt = e.agentId === undefined && isTyped && isPersonsPrompt(e.origin) && e.message.isMeta !== true
34 return isPrompt ? e.uuid : undefined
35}
36
37/** The index of the prompt the arrows are on: the one last jumped to, else the newest. */
38const indexOn = ({ prompts, at }: PromptTrail) => at ?? prompts.length - 1
39
40/** The index of the prompt a step from the one the arrows are on lands on, or undefined past either end. */
41export function jumpTarget(trail: PromptTrail, step: Step): number | undefined {
42 const target = indexOn(trail) + step
43 return target >= 0 && target < trail.prompts.length ? target : undefined
44}
45
46/** `7/8` while the arrows are on the seventh of eight prompts; empty with none known. */
47export const positionText = (trail: PromptTrail): string => (trail.prompts.length === 0 ? '' : `${indexOn(trail) + 1}/${trail.prompts.length}`)
48
49/** Adds a prompt the conversation stored; the arrows rest on it. */
50export function notePrompt(trail: PromptTrail, id: string) {
51 if (trail.prompts.includes(id)) return
52 trail.prompts.push(id)
53 trail.at = undefined
54}
55
56/**
57 * Puts the prompts the transcript file held before the first prompt already
58 * known, each once: all of them while none is known, those up to the first
59 * known where the file holds it, and none where it does not (a prompt from
60 * before the file's last compaction, or one the file has not stored yet).
61 * The arrows keep the prompt they are on.
62 */
63export function noteStored(trail: PromptTrail, ids: readonly string[]) {
64 const [first] = trail.prompts
65 const olderCount = first === undefined ? ids.length : ids.indexOf(first)
66 if (olderCount <= 0) return
67
68 const older = ids.slice(0, olderCount)
69 const held = new Set(older)
70 trail.prompts = [...older, ...trail.prompts.filter(id => !held.has(id))]
71 if (trail.at !== undefined) trail.at += older.length
72}
73
74/** Forgets the conversation that ended: `/clear` and `/resume` go on in this process with other prompts. */
75function startOver(trail: PromptTrail) {
76 Object.assign(trail, newTrail())
77}
78
79// --- The prompts a transcript file holds --------------------------------
80
81/**
82 * The fields of a transcript line that tell a prompt the person typed: its
83 * row type and id, who wrote it, whether the person sees it as typed or a
84 * subagent keeps it, and a compaction's boundary. Inside a JSON string every
85 * quote is escaped, so these match the line's own fields and never text the
86 * row quotes.
87 */
88const ROW_FIELDS = '"type":"user"|"type":"attachment"|"type":"queued_command"|"origin":\\{"kind":"human"|"isMeta":true|"isSidechain":true|"subtype":"compact_boundary"|"uuid":"[^"]+"'
89
90const UUID_FIELD = /^"uuid":"([^"]+)"$/
91
92/** The command that prints ROW_FIELDS of each line of a transcript file, as `grep -n -o` does: `<line>:<field>`. */
93export const transcriptFieldsCommand = (path: string) => ['grep', '-a', '-n', '-o', '-E', ROW_FIELDS, path]
94
95/** Each line's fields, in file order. */
96function linesOf(grepOutput: string): string[][] {
97 const lines: Array<{ line: string; fields: string[] }> = []
98 for (const printed of grepOutput.split('\n')) {
99 const colon = printed.indexOf(':')
100 if (colon < 0) continue
101
102 const [line, field] = [printed.slice(0, colon), printed.slice(colon + 1)]
103 const current = lines.at(-1)
104 if (current?.line === line) current.fields.push(field)
105 else lines.push({ line, fields: [field] })
106 }
107 return lines.map(({ fields }) => fields)
108}
109
110// A prompt typed at rest is a user row; one delivered into a running turn is a queued_command attachment row.
111const isTypedRow = (fields: readonly string[]) =>
112 fields.includes('"type":"user"') || (fields.includes('"type":"attachment"') && fields.includes('"type":"queued_command"'))
113
114const isPersonsRow = (fields: readonly string[]) =>
115 isTypedRow(fields) && fields.includes('"origin":{"kind":"human"') && !fields.includes('"isMeta":true') && !fields.includes('"isSidechain":true')
116
117/**
118 * The ids of the person's prompts since the last compaction, in order, from
119 * `grep -n -o` of ROW_FIELDS over a transcript file. Claude Code draws a
120 * resumed conversation from its last compaction's boundary, so the prompts
121 * before it have no row to scroll to.
122 */
123export function storedPromptIds(grepOutput: string): string[] {
124 let ids: string[] = []
125 for (const fields of linesOf(grepOutput)) {
126 if (fields.includes('"subtype":"compact_boundary"')) {
127 ids = []
128 continue
129 }
130 const id = fields.map(field => UUID_FIELD.exec(field)?.[1]).find(found => found !== undefined)
131 if (id !== undefined && isPersonsRow(fields)) ids.push(id)
132 }
133 return ids
134}
135
136// grep's exit status when it read the file and matched nothing.
137const NO_MATCH = 1
138
139/** Whether the file read holds the row anywhere, before its last compaction included. */
140export const readHoldsRow = (grepOutput: string, id: string) => grepOutput.includes(`"uuid":"${id}"`)
141
142/** The prompt ids `transcriptFieldsCommand` found, from what it printed and how it exited. */
143export function promptIdsOfRead({ exitCode, stdout, stderr, isStdoutTruncated }: ProcessRunResult): string[] {
144 // A cut output loses the newest rows, the ones a jump reaches.
145 if (isStdoutTruncated) throw new Error('grep output truncated')
146 if (exitCode === 0) return storedPromptIds(stdout)
147 if (exitCode === NO_MATCH) return []
148 throw new Error(stderr.trim() || `grep exited ${exitCode}`)
149}
150
151/**
152 * The command that prints the path of the session's transcript file:
153 * `<id>.jsonl` in one of the config folder's project folders. It is searched
154 * for rather than built, since a project folder's name is Claude Code's own
155 * encoding of the project's path.
156 */
157export const findTranscriptCommand = (configDir: string, sessionId: string) => [
158 'find',
159 `${configDir}/projects`,
160 '-maxdepth',
161 '2',
162 '-name',
163 `${sessionId}.jsonl`,
164 '-print',
165 '-quit',
166]
167
168const TRANSCRIPT_FIND_TIMEOUT_MS = 5000
169const TRANSCRIPT_READ_TIMEOUT_MS = 10000
170
171async function configDir($: EngineInterface): Promise<string | undefined> {
172 const configured = await $.env.get('CLAUDE_CONFIG_DIR')
173 if (configured !== undefined) return configured
174
175 const home = await $.env.get('HOME')
176 return home === undefined ? undefined : `${home}/.claude`
177}
178
179async function findTranscript($: EngineInterface): Promise<string | undefined> {
180 const dir = await configDir($)
181 if (dir === undefined) return undefined
182
183 const found = await $.process.run(findTranscriptCommand(dir, await $.session.id()), { timeoutMs: TRANSCRIPT_FIND_TIMEOUT_MS })
184 return found.stdout.trim() || undefined
185}
186
187/**
188 * Reads the transcript file once for the prompts the conversation stored
189 * before the plugin saw them: those of a session resumed or continued, or
190 * one the plugin loaded into. A session's file is written with its first
191 * row, so a read that finds none leaves the next need to read again.
192 */
193function readStored($: EngineInterface, trail: PromptTrail): Promise<void> {
194 if (trail.storedRead !== undefined) return trail.storedRead
195
196 const pending = (async () => {
197 try {
198 const path = await findTranscript($)
199 if (path === undefined) {
200 if (trail.storedRead === pending) trail.storedRead = undefined
201 return
202 }
203 const read = await $.process.run(transcriptFieldsCommand(path), { timeoutMs: TRANSCRIPT_READ_TIMEOUT_MS })
204 if (trail.storedRead !== pending) return
205 noteStored(trail, promptIdsOfRead(read))
206 // A file that holds none of the prompts known lags the conversation: the next need reads it again.
207 const [first] = trail.prompts
208 if (first !== undefined && !readHoldsRow(read.stdout, first)) trail.storedRead = undefined
209 await publishPosition($, trail)
210 } catch (error) {
211 // The prompts stored before the plugin loaded go uncounted.
212 $.ui.log(`sc-mods: could not read the transcript: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })
213 }
214 })()
215 trail.storedRead = pending
216 return pending
217}
218
219// --- The band -----------------------------------------------------------
220
221/**
222 * The doors whose rows reach this plugin where managed settings are present.
223 * Rows through the other doors (attachment, hook-context, compaction,
224 * tool-message, note) do not.
225 */
226const REACHABLE_DOORS: SessionAppendDoor[] = ['prompt', 'delivery', 'response', 'tool-result', 'command', 'notice', 'queue']
227
228/**
229 * The count the band shows. A jump does not change the band's props, so the
230 * band reads the count from state, and a write draws the band again without
231 * drawing the transcript's rows.
232 */
233const PROMPT_POSITION = atom({ plugin: 'sc-mods', key: 'promptPosition' } as const, '')
234
235const publishPosition = ($: EngineInterface, trail: PromptTrail) => update($, PROMPT_POSITION, () => positionText(trail))
236
237async function jump($: EngineInterface, trail: PromptTrail, step: Step) {
238 await readStored($, trail)
239 const target = jumpTarget(trail, step)
240 if (target === undefined) {
241 if (step === 1 && trail.endRow !== undefined) {
242 const refusal = await scrollRefusal($, trail.endRow)
243 if (refusal !== undefined) $.ui.toast(`Can't scroll to the end: ${refusal}`)
244 return
245 }
246 $.ui.toast(step === -1 ? 'No earlier prompt' : 'No later prompt')
247 return
248 }
249
250 // The arrows move on past a prompt the transcript cannot reach (one a rewind took away), so the next press goes beyond it.
251 const refusal = await scrollRefusal($, trail.prompts[target] as string)
252 if (refusal !== undefined) $.ui.toast(`Can't jump to that prompt: ${refusal}`)
253 trail.at = target
254 await publishPosition($, trail)
255}
256
257/**
258 * Why the transcript did not move to the row, or undefined once it did. The
259 * row lands at the window's bottom, just above the prompt box, with the rows
260 * after it out of view. Claude Code scrolls to a row its transcript has
261 * drawn; the window stays where it is when the row cannot reach the bottom
262 * (a prompt near the start), and that answers as moved.
263 */
264async function scrollRefusal($: EngineInterface, requestId: string): Promise<string | undefined> {
265 try {
266 return (await $.ui.scroll({ to: { requestId }, block: 'end' })).deny
267 } catch (error) {
268 // Where no surface scrolls the transcript, the call rejects instead of denying.
269 return error instanceof Error ? error.message : String(error)
270 }
271}
272
273/**
274 * The band's ◀ and ▶ buttons, which scroll the transcript so the previous or
275 * next of the person's prompts sits at the bottom of the view, with the
276 * arrows' place among them between; on the newest prompt, ▶ scrolls to the
277 * end of the conversation. Hotkeys 1 and 2 press them while the band holds
278 * the keyboard.
279 *
280 * The prompts counted are those the transcript file holds since its last
281 * compaction, read when the plugin loads or at the first press, and those
282 * stored since. The arrows step from the prompt last jumped to, so a press
283 * moves them on even where the window could not move; the person's own
284 * scrolling does not move them.
285 */
286export function registerPromptJump(on: On) {
287 const trail = newTrail()
288
289 on('session.start', async ($, e, next) => {
290 const started = await next(e)
291 void readStored($, trail)
292 return started
293 })
294
295 on('session.end', ($, e, next) => {
296 if (e.reason === 'clear' || e.reason === 'resume') {
297 startOver(trail)
298 void publishPosition($, trail)
299 }
300 return next(e)
301 })
302
303 on('session.append', { door: REACHABLE_DOORS }, ($, e, next) => {
304 if (e.agentId === undefined) trail.endRow = e.uuid
305 const id = promptIdOf(e)
306 if (id !== undefined) {
307 notePrompt(trail, id)
308 void publishPosition($, trail)
309 }
310 return next(e)
311 })
312
313 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
314 // The prompts it knows are the main conversation's, not an agent's.
315 if (e.props.hasSurvey || e.props.view.agentId !== undefined) return next(e)
316
317 const position = await read($, PROMPT_POSITION)
318 // The band is shared: what the plugins beneath draw stays, above the arrows.
319 const beneath = await next(e)
320 const { Box, Button, Text } = $.ui.resolve(e)
321 return (
322 <Box flexDirection="column">
323 {beneath}
324 <Box flexDirection="row" columnGap={1}>
325 <Button key="prompt-jump:previous" hotkey="1" label="◀" onPress={() => jump($, trail, -1)} />
326 {position === '' ? null : <Text dimColor>{position}</Text>}
327 <Button key="prompt-jump:next" hotkey="2" label="▶" onPress={() => jump($, trail, 1)} />
328 </Box>
329 </Box>
330 )
331 })
332}
333hooks/reply-copy.tsx 38 lines1import type { EngineInterface, On, RenderSurface } from 'claude-code'
2
3async function copyReply($: EngineInterface, markdown: string, surface: RenderSurface) {
4 const result = await $.ui.copy({ text: markdown, surface })
5 // A string's length counts UTF-16 units, two for most emoji; its iterator yields code points, one each.
6 $.ui.toast(result.isCopied ? `Copied ${[...markdown].length} characters` : `Copy failed: ${result.reason}`)
7}
8
9/**
10 * A dim `⧉ copy` button under each block of Claude's reply text, which puts
11 * that block's markdown on the clipboard.
12 *
13 * Register it before any hook that rewrites the reply's text: a plugin's
14 * hooks nest in the order registered, so this one reads the text as Claude
15 * wrote it and wraps what the later hooks drew.
16 */
17export function registerReplyCopy(on: On) {
18 on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
19 // A summary stands for text the model wrote; it is not that text.
20 if (e.props.isSummary) return next(e)
21
22 const markdown = e.props.text
23 const drawn = await next(e)
24 const { Box, Button } = $.ui.resolve(e)
25 return (
26 <Box flexDirection="column">
27 {drawn}
28 <Button
29 key={`reply-copy:${e.requestId}`}
30 dimColor
31 label="⧉ copy"
32 onPress={press => copyReply($, markdown, press.surface)}
33 />
34 </Box>
35 )
36 })
37}
38types/index.d.ts 9 lines1/** The view's place among the prompts, as the band shows it: `2/5`, or '' with none known. */
2export type PromptPosition = string
3
4declare module 'claude-code' {
5 interface PluginState {
6 'sc-mods': { promptPosition: PromptPosition }
7 }
8}
9