Collapses long replies to a one-sentence TL;DR: [ more ] expands one, /tldr turns it off.

Long replies collapse to a one-sentence TL;DR.
Collapses long replies — Any reply text over ~100 words is drawn as a one-sentence TL;DR that Sonnet writes from that text alone. [ more ] under it shows the full text, [ less ] collapses it again.
/tldr toggles it — /tldr turns collapsing off or back on, and the choice is kept across sessions. /tldr more and /tldr less expand or collapse the newest reply from the keyboard.
Only the display changes: Claude still writes and reads its full replies.
hooks/register.tsx 236 lines1// tldr as a mod: each long assistant text block is drawn as a one-sentence
2// Sonnet TL;DR with [ more ] to expand it. Only the drawing changes; the stored
3// transcript and the model's context are untouched. /tldr toggles it globally.
4import { atom, read, update, memberOf } from 'claude-code'
5import type { EngineInterface, Register } from 'claude-code'
6import { GUIDELINES, isLong, lineFor, parseArgs, wordCount } from './lib'
7
8const isOn = atom({ plugin: 'tldr', key: 'isOn' } as const, true)
9const line = atom({ plugin: 'tldr', key: 'line' } as const, '')
10const isExpanded = atom({ plugin: 'tldr', key: 'isExpanded' } as const, false)
11const isLearned = atom({ plugin: 'tldr', key: 'isLearned' } as const, false)
12const isTurnRunning = atom({ plugin: 'tldr', key: 'isTurnRunning' } as const, false)
13
14const FAIL = '!fail:'
15const RETRY_MS = 60_000 // a failed summary is tried again on a redraw this long after
16const SEND_AFTER_MS = 250 // past the render that asked: a call sent while its render is in flight is cut when a newer render supersedes it
17const TRIES = 3 // an aborted call is sent again, drawn as summarizing meanwhile, before it shows as failed
18const ABORT_RETRY_MS = 1_000
19const MAX_RUNNING = 3
20const KEEP_PER_SESSION = 200
21const KEEP_SESSIONS = 20
22
23// Module state starts over on every reload; $.state and $.store survive it.
24const started = new Set<string>() // ids queued, in flight or summarized this load
25const order: string[] = [] // long blocks in the order first drawn, for /tldr more|less
26const drawnBefore = new Set<string>() // long blocks first drawn before this load's first turn: left alone
27let hasTurnStarted = false
28const queue: (() => Promise<void>)[] = []
29let running = 0
30let saving: Promise<void> = Promise.resolve()
31
32function pump() {
33 while (running < MAX_RUNNING && queue.length) {
34 const job = queue.shift()!
35 running++
36 job().finally(() => {
37 running--
38 pump()
39 })
40 }
41}
42
43async function save($: EngineInterface, id: string, t: string) {
44 const sid = await $.session.id() // looked up per save: /clear starts a new session
45 const saved = ((await $.store.get('s/' + sid)) ?? {}) as Record<string, string>
46 saved[id] = t
47 const keys = Object.keys(saved)
48 for (const k of keys.slice(0, Math.max(0, keys.length - KEEP_PER_SESSION))) delete saved[k]
49 await $.store.set('s/' + sid, saved)
50 const index = ((await $.store.get('sessions')) ?? []) as string[]
51 if (!index.includes(sid)) {
52 index.push(sid)
53 while (index.length > KEEP_SESSIONS) await $.store.delete('s/' + index.shift())
54 await $.store.set('sessions', index)
55 }
56}
57
58async function summarize($: EngineInterface, id: string, text: string, tries: number) {
59 let t: string
60 try {
61 const r = await $.model.complete({
62 model: 'sonnet',
63 system: GUIDELINES,
64 prompt: '<message>\n' + text + '\n</message>',
65 effort: 'low',
66 timeoutMs: 30000,
67 })
68 if (!r.isAnswered && r.reason === 'aborted' && tries < TRIES) {
69 $.clock.after(ABORT_RETRY_MS, () => enqueue($, id, text, tries + 1))
70 return
71 }
72 t = r.isAnswered ? lineFor(r.text) : FAIL + (r.reason ?? 'no answer')
73 } catch (err) {
74 t = FAIL + 'refused: ' + String(err) // the engine refused to send it (a blocked model, say)
75 }
76 await update($, memberOf(line, { requestId: id }), () => t)
77 await $.ui.log(`tldr ${id}: ${t}`, { to: 'debug' })
78 if (t.startsWith(FAIL)) {
79 $.clock.after(RETRY_MS, () => started.delete(id))
80 return
81 }
82 // Serialized read-modify-writes; a failed save must not stall the ones after it.
83 saving = saving.then(() => save($, id, t)).catch(() => {})
84 await saving
85}
86
87function enqueue($: EngineInterface, id: string, text: string, tries: number) {
88 queue.push(() => summarize($, id, text, tries).catch(() => {}))
89 pump()
90}
91
92/** Summarize a block's visible text, drawn after its turn ended: only then is it whole. */
93function start($: EngineInterface, id: string, text: string) {
94 if (started.has(id)) return
95 started.add(id)
96 // Sent from a timer, once the render that asked has settled: the turn's end redraws the block
97 // several times in a few milliseconds, and a call sent during one is aborted when the next supersedes it.
98 $.clock.after(SEND_AFTER_MS, () => enqueue($, id, text, 1))
99}
100
101async function setOn($: EngineInterface, value: boolean) {
102 await $.store.set('enabled', value)
103 await update($, isOn, () => value)
104}
105
106/** The person has used [ more ], [ less ] or /tldr: the inline hint retires for good. */
107async function learn($: EngineInterface) {
108 if (await read($, isLearned)) return
109 await $.store.set('learned', true)
110 await update($, isLearned, () => true)
111}
112
113async function setExpanded($: EngineInterface, id: string, value: boolean) {
114 await update($, memberOf(isExpanded, { requestId: id }), () => value)
115 await learn($)
116}
117
118export const register: Register = on => {
119 on('session.start', async ($, e, next) => {
120 const enabled = await $.store.get('enabled')
121 await update($, isOn, () => enabled !== false)
122 const learned = (await $.store.get('learned')) === true
123 await update($, isLearned, () => learned)
124 await $.command.register({ name: 'tldr', description: 'Collapse long replies to one sentence: /tldr toggles; on, off, more, less' })
125 const saved = ((await $.store.get('s/' + (await $.session.id()))) ?? {}) as Record<string, string>
126 for (const [id, t] of Object.entries(saved)) await update($, memberOf(line, { requestId: id }), () => t)
127 return next(e)
128 })
129
130 // A block is whole once the turn that wrote it has ended. Surfaces draw a message under ids of
131 // their own (the desktop's is not the stored row's uuid), so the turn's end is the signal, not
132 // the stored row: flipping the atom redraws every pending block that read it, which starts its summary.
133 // Subagents' and teammates' turns (e.agentId set) also raise turn.start and turn.complete; only
134 // the main loop's draw the blocks summarized here.
135 on('turn.start', async ($, e, next) => {
136 if (!e.agentId) {
137 hasTurnStarted = true
138 await update($, isTurnRunning, () => true)
139 }
140 return next(e)
141 })
142
143 on('turn.complete', async ($, e, next) => {
144 if (!e.agentId) await update($, isTurnRunning, () => false)
145 return next(e)
146 })
147
148 on('command.run', { command: 'tldr' }, async ($, e) => {
149 const what = parseArgs(e.args)
150 await learn($)
151 if (what === 'help') return { text: 'Usage: /tldr (toggle), /tldr on, /tldr off, /tldr more, /tldr less' }
152 if (what === 'toggle' || what === 'on' || what === 'off') {
153 const value = what === 'toggle' ? !(await read($, isOn)) : what === 'on'
154 await setOn($, value)
155 return { text: value ? 'tl;dr on: long replies collapse to one sentence; [ more ] expands one.' : 'tl;dr off: replies show in full.' }
156 }
157 if (!(await read($, isOn))) return { text: 'tl;dr is off; /tldr turns it on.' }
158 const wantOpen = what === 'more'
159 for (let i = order.length - 1; i >= 0; i--) {
160 const me = { requestId: order[i]! }
161 const t = await read($, memberOf(line, me))
162 if (!t || t.startsWith(FAIL)) continue // drawn in full anyway
163 if ((await read($, memberOf(isExpanded, me))) !== wantOpen) {
164 await update($, memberOf(isExpanded, me), () => wantOpen)
165 return { text: wantOpen ? 'Expanded the latest collapsed reply.' : 'Collapsed the latest expanded reply.' }
166 }
167 }
168 return { text: wantOpen ? 'No collapsed reply to expand.' : 'No expanded reply to collapse.' }
169 })
170
171 on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
172 const text = e.props.text
173 if (e.props.isSummary || !isLong(text) || !(await read($, isOn))) return next(e)
174 const id = e.requestId
175 if (!order.includes(id)) {
176 order.push(id)
177 if (!hasTurnStarted) drawnBefore.add(id)
178 }
179 const t = await read($, memberOf(line, e))
180 // Only a block still owed a summary reads the turn state, so a turn's start and end redraw those alone.
181 const isOwed = (!t || t.startsWith(FAIL)) && !drawnBefore.has(id)
182 const fin = isOwed && !(await read($, isTurnRunning))
183 if (fin) start($, id, text)
184
185 // No summary and none coming (its turn still running, or drawn before this load's first turn):
186 // the engine's own drawing, untouched.
187 if (!t && !fin) return next(e)
188
189 const { Box, Text, Button } = $.ui.resolve(e)
190 const indent = e.surface === 'terminal' ? 2 : 0 // under the message text, past the bullet
191 if (t.startsWith(FAIL)) {
192 return (
193 <Box flexDirection="column">
194 {await next(e)}
195 <Box paddingLeft={indent}>
196 <Text dimColor>tl;dr unavailable: {t.slice(FAIL.length)}</Text>
197 </Box>
198 </Box>
199 )
200 }
201 if (await read($, memberOf(isExpanded, e))) {
202 return (
203 <Box flexDirection="column">
204 {await next(e)}
205 <Box marginTop={1} paddingLeft={indent}>
206 <Button key="less" label="less" dimColor onPress={() => setExpanded($, id, false)} />
207 </Box>
208 </Box>
209 )
210 }
211 const bullet = e.surface === 'terminal' ? (e.props.isFirstOfReply ? '⏺ ' : ' ') : ''
212 const learned = await read($, isLearned)
213 return (
214 <Box flexDirection="column" marginTop={1}>
215 <Box flexDirection="row">
216 {bullet ? <Text>{bullet}</Text> : null}
217 <Box flexGrow={1} flexShrink={1}>
218 {t ? (
219 <Text>
220 <Text dimColor>tl;dr </Text>
221 {t}
222 </Text>
223 ) : (
224 <Text dimColor italic>summarizing…</Text>
225 )}
226 </Box>
227 </Box>
228 <Box marginTop={1} paddingLeft={indent}>
229 <Button key="more" label={`more · ${wordCount(text)} words`} dimColor onPress={() => setExpanded($, id, true)} />
230 {learned ? null : <Text dimColor> /tldr turns collapsing off</Text>}
231 </Box>
232 </Box>
233 )
234 })
235}
236hooks/lib.ts 35 lines1// Pure helpers, tested with `claude plugin test`.
2
3export const GUIDELINES = `The user's screen will show the message below, an AI assistant's message to them, collapsed to one sentence; the full message stays one click away. Write that sentence in the assistant's voice, to the user: its "I" stays "I", the user is "you".
4
5- One plain sentence, aim for under 30 words, no prefix.
6- Lead with its main point, keeping its hedges and status (proposed vs done, verified vs not).
7- If it puts a question or decision to the user that one sentence can't carry, end by saying what to look at in the full message.
8
9Reply with the sentence only.`
10
11/** Long enough to collapse: over 100 words and more than one non-blank line. */
12export function isLong(text: string): boolean {
13 return wordCount(text) > 100 && text.split('\n').filter(l => l.trim()).length > 1
14}
15
16export function wordCount(text: string): number {
17 return text.split(/\s+/).filter(Boolean).length
18}
19
20/** One line from the model's answer: trimmed, a stray prefix removed, newlines folded. */
21export function lineFor(answer: string): string {
22 return answer
23 .trim()
24 .replace(/^(tl;?dr|summary|one sentence|in one sentence)\s*:\s*/i, '')
25 .replace(/\s*\n+\s*/g, ' ')
26}
27
28/** Parse `/tldr` arguments. */
29export function parseArgs(args: string): 'toggle' | 'on' | 'off' | 'more' | 'less' | 'help' {
30 const a = args.trim().toLowerCase()
31 if (a === '') return 'toggle'
32 if (a === 'on' || a === 'off' || a === 'more' || a === 'less') return a
33 return 'help'
34}
35types/index.d.ts 17 lines1declare module 'claude-code' {
2 interface PluginState {
3 'tldr': {
4 /** Collapsing on (mirrors $.store 'enabled', which persists across sessions). */
5 isOn: boolean
6 /** By message id: the TL;DR, '' while none. */
7 line: StateFamily<string>
8 /** By message id: the person pressed [ more ]. */
9 isExpanded: StateFamily<boolean>
10 /** The person has used [ more ], [ less ] or /tldr (mirrors $.store 'learned'). */
11 isLearned: boolean
12 /** A main-loop turn is running, so a block it draws may still grow. */
13 isTurnRunning: boolean
14 }
15 }
16}
17