Emoji reactions: the agent can acknowledge a message with one emoji, shown as a reaction on it instead of a reply

Talk to Claude while it works, keep every topic in its own thread, and get a quick emoji when a reply would be overkill. Three Claude Code mods: multitask, thread-chat and react.

# heading puts a message in its topic's thread: colour-coded, readable on its own and easy to find later.Examples: docs/why.md.
Requires Claude Code 2.1.290 or later. Made for the Code tab in the Claude desktop app.
claude plugin marketplace add othrayte/claude-multitask
claude plugin install multitask@claude-multitask
claude plugin install thread-chat@claude-multitask
claude plugin install react@claude-multitask
Install any or all of them. Once installed, a line above the prompt names each new mod's command, until you dismiss it. Getting started: a quick start for each mod, in docs/getting-started.md.
In the band above the prompt, Multitask, while it is on, has a mode control (a button in the terminal, a dropdown in the desktop app and VS Code), and thread-chat, while threads are on, a thread picker followed by +, which starts a thread, and ☰, which opens the thread view. The mobile app shows only the thread picker: use the commands there. React has no control in the band: /react is its switch.
In the terminal, ctrl+x tab moves from the prompt to the band, onto the thread picker when there are threads. Tab moves along the band. From any band button, m presses Multitask's mode button, as does Enter on that button. Esc goes back to the prompt.
The three commands, /multitask, /threads and /react, work alike:
on or off (or enable, disable) sets this chat, toggle switches it, and status says how it is set, here and in new chats.default asks whether it is on in new chats (the default); default on or default off sets it./multitask on turns it on in that chat, and /multitask off turns it off. The choice is per chat, and kept when the chat is restarted.Multitask mode, where the chat becomes the voice and hands all work to thoughts. In Focus you work with the agent as usual. Multitask's mode control shows the mode. In the terminal it is a button: press it, or m (keys above), to switch to the other mode. In the desktop app and VS Code it is a dropdown: pick the other mode to switch. /multitask mode asks which mode, and /multitask mode multitask or /multitask mode focus switches to it: the way to switch in the mobile app, which has no mode control./multitask default on or off sets whether Multitask is on by default: in new chats, and in chats where you have not used /multitask. A chat's own /multitask choice wins over the default. A new chat it is on in starts in Multitask mode; a chat already open that it turns on starts in Focus. The default applies to every chat and is kept across restarts.thoughts button holds a dot in its colour for each running thought, which blinks as the thought works, swells a little at each of its notes, and fades out as it ends, as a check, or a cross if it failed. In the desktop app, hover a dot for the thought's name, latest note and its age./thoughts, or a click anywhere on the thoughts button (a dot included), opens the Thoughts pane: what each thought is doing and how long since its last note, its report, tell to send it a message yourself, and stop. It lists the 16 most recently ended thoughts (N more shows the rest). The thoughts are per chat, and kept when the chat is restarted.voiceEffort setting (Voice effort, in /config) sets how hard the voice thinks: low (default), medium, high, or session to match the session. Thoughts keep the session's setting./threads on turns them on in that chat, and /threads off turns them off. The choice is per chat, and kept when the chat is restarted./threads default on or off sets whether threads are on by default: in new chats, and in chats where you have not turned them on or off. A chat's own choice wins over the default. The default applies to every chat and is kept across restarts./threads on turns them on again.# name heading in a message starts a thread, or replies to it if it exists. Close or abbreviated names find the existing thread. The agent replies under the same headings.#+name starts a new thread even when an existing one is close.+ thread (desktop app); to move it to another, press ▾ beside its thread tag. Press ᯤ, at the other end of the tag's line, to open the thread view on that thread alone.No thread. A heading still wins, and moves the picker to its thread.# name heading on a line of its own, however its heading was typed, and also when the picker or a reply to a part of a thread chose the thread.+, after the thread picker, starts a thread by name and picks it./threads manage shows your threads in the chat, each with buttons to merge, archive or delete it (click them; done closes the list)./threads manage brings them back, as does a heading naming one. Deleting a thread takes its tag off its messages./threads filter on filters the chat, which is off at first, so the chat shows every message. On, with a thread picked, the chat shows only that thread's messages, and those since your last message that are in no thread. /threads filter off turns it off; /threads filter alone asks. It is per chat, and kept when the chat is restarted./thread-view, or ☰ above the prompt, opens the thread view: a pane with a switch for each thread below its newest message. With none on it shows every message; with some on, only those threads' messages, and those since your last message that are in no thread, as the chat's filter does. The thread picker above the prompt and the chat's filter do not change it./merge-threads <thread> into <thread> also merges two threads./threads agent on lets the agent start threads itself, and /threads agent off stops it; /threads agent alone asks. It is off at first, per chat, and kept when the chat is restarted.read_thread tool./threads summaries on shows a one-line summary of the picked thread above the prompt (of the latest thread, with none picked), and /threads summaries off hides it; /threads summaries alone asks. It is off at first, per chat, and kept when the chat is restarted. In the desktop app, hover a thread's switch in the thread view for its one-line summary./threads status lists these settings, agent, filter and summaries, after whether threads are on. They work while threads are on.catchUpAfter setting (Catch up after, in /config) sets that gap in tokens, 75000 by default; summaryModel sets the model that writes the summaries, claude-haiku-5-5 by default./react off turns them off in that chat, and /react on back on. The choice is per chat, and kept when the chat is restarted./react default on or off sets whether reactions are on by default: in new chats, and in chats where you have not used /react. A chat's own /react choice wins over the default. The default applies to every chat and is kept across restarts.hooks/register.tsx 470 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, HookStream, Register, RenderElement, TurnStepChunk, TurnStepResult } from 'claude-code'
3
4import type { Reaction } from '../types'
5import {
6 BRIEF,
7 NO_RESPONSE,
8 OFF_NOTE,
9 couldBeEmoji,
10 isOneEmoji,
11 joinReactions,
12 markOf,
13 marksOf,
14 reactionFor,
15 reactionsHeld,
16 withReaction,
17} from './reactions'
18import { argumentHint, descriptionOf, runSwitch } from './command'
19import type { Names, Session, State } from './command'
20import { watchSwitch } from './ui-switch'
21import { welcome } from './welcome'
22
23const isOn = atom({ plugin: 'react', key: 'isOn' } as const, false)
24const choice = atom({ plugin: 'react', key: 'choice' } as const, null)
25const isOnByDefault = atom({ plugin: 'react', key: 'isOnByDefault' } as const, true)
26const isBriefed = atom({ plugin: 'react', key: 'isBriefed' } as const, false)
27const reactions = atom({ plugin: 'react', key: 'reactions' } as const, [])
28const answering = atom({ plugin: 'react', key: 'answering' } as const, null)
29
30// The ways a person's own prompt arrives: typed in the terminal, the desktop
31// app (an SDK host) or Remote Control.
32const PERSON = new Set(['composer', 'sdk', 'bridge'])
33
34type Block = { type: string; [field: string]: unknown }
35
36function textsOf(content: readonly Block[]): string[] {
37 return content.flatMap(block => (block.type === 'text' && typeof block.text === 'string' ? [block.text] : []))
38}
39
40// Reactions are on in a session as the person last chose there with /react, else as
41// the default (`/react default`), on until they choose. Off, the mod leaves the session
42// be: nothing beside the person's messages, replies go on as they come, and messages
43// and replies are the engine's drawing alone.
44async function setHere($: EngineInterface, now: boolean): Promise<string> {
45 const was = await read($, isOn)
46 await update($, isOn, () => now)
47 await update($, choice, () => now)
48 await keep($)
49 if (was !== now) redescribe($)
50 return now
51 ? 'Reactions are on in this chat: the agent may acknowledge a message with an emoji reaction on it instead of a reply.'
52 : 'Reactions are off in this chat.'
53}
54
55// Sets the switch to the session's own choice, else the default.
56async function settle($: EngineInterface) {
57 const chosen = await read($, choice)
58 const now = chosen ?? (await read($, isOnByDefault))
59 if ((await read($, isOn)) === now) return
60 await update($, isOn, () => now)
61 redescribe($)
62}
63
64// Whether reactions are on in new sessions, and in those never switched with /react:
65// the person's choice for every session, kept under its own key; on until they choose.
66const DEFAULT_KEY = 'isOnByDefault'
67
68async function takeUpDefault($: EngineInterface) {
69 const chosen = await $.store.get(DEFAULT_KEY).catch(() => undefined)
70 if (typeof chosen === 'boolean') await update($, isOnByDefault, () => chosen)
71}
72
73// `/react default on|off`: sets the default, which this session follows too unless the
74// person switched it with /react; says what the default now is.
75async function setDefault($: EngineInterface, now: boolean): Promise<string> {
76 await update($, isOnByDefault, () => now)
77 await $.store.set(DEFAULT_KEY, now).catch(() => undefined)
78 await settle($)
79 await keep($)
80 redescribe($)
81 const word = now ? 'on' : 'off'
82 const said = `Reactions are now ${word} by default, in new chats and in chats where you have not used \`/react\`.`
83 const chosen = await read($, choice)
84 if (chosen === null || chosen === now) return said
85 return `${said} This chat keeps them ${chosen ? 'on' : 'off'}; \`/react ${chosen ? 'off' : 'on'}\` turns them ${chosen ? 'off' : 'on'} here.`
86}
87
88// `/react` and its arguments, as every mod's switch takes them (command.ts).
89const NAMES: Names = { command: 'react', noun: 'Reactions', be: 'are' }
90
91async function stateOf($: EngineInterface): Promise<State> {
92 return { isOnHere: await read($, isOn), choiceHere: await read($, choice), isOnByDefault: await read($, isOnByDefault), detail: '' }
93}
94
95function sessionOf($: EngineInterface): Session {
96 return {
97 state: () => stateOf($),
98 canAsk: async () => (await $.session.surfaces().catch(() => [])).length > 0,
99 ask: (question, options) => $.ui.ask(question, options),
100 setHere: now => setHere($, now),
101 setDefault: now => setDefault($, now),
102 }
103}
104
105// Has the menu ask for /react's line again, as what it says has changed.
106function redescribe($: EngineInterface) {
107 try {
108 $.ui.invalidate('command.describe')
109 } catch {
110 // the menu keeps the line it had
111 }
112}
113
114// Where a session's switch and reactions are kept between runs of the app: whether it
115// is on, the person's own choice there (null: never switched, so it follows the
116// default), when it was kept, whether the model was told, its reactions, and, once it
117// has been on, the marks of its newest messages.
118const recordKey = (sessionId: string) => `session:${sessionId}`
119type Kept = { isOn: boolean; choice: boolean | null; at: number; isBriefed: boolean; reactions: Reaction[]; marks: string[] }
120
121// The person's choice a session kept. One kept before choices were (off was then the
122// default) chose only if it was on.
123const choiceOf = (record: Partial<Kept>): boolean | null =>
124 record.choice !== undefined ? record.choice : record.isOn === true ? true : null
125
126const MARKS_KEPT = 200
127
128// Keeps the switch and reactions for the session's next run. A session never on keeps
129// no marks: one rewound or forked from it starts off as it would anyway. Best effort: a
130// store or transcript that cannot be read or written keeps what it kept.
131async function keep($: EngineInterface) {
132 try {
133 const key = recordKey(await $.session.id())
134 const was = (await $.store.get(key)) as Partial<Kept> | undefined
135 const now = await read($, isOn)
136 const isMarked = now || (was?.marks?.length ?? 0) > 0
137 const marks = isMarked ? marksOf(await $.session.messages()).slice(-MARKS_KEPT) : []
138 await $.store.set(key, {
139 isOn: now,
140 choice: await read($, choice),
141 at: await $.clock.now(),
142 isBriefed: await read($, isBriefed),
143 reactions: await read($, reactions),
144 marks,
145 } satisfies Kept)
146 } catch {
147 // kept as it was
148 }
149}
150
151// What a session kept, and whether it is its own: for one rewound or forked, which starts
152// under a new id with copies of the messages it kept, that of the session it came from:
153// the kept one that knows the most of its messages, else, of those near that, the one
154// kept last (the one it was just in). None when no session is known.
155async function kept($: EngineInterface): Promise<{ record: Partial<Kept>; isOwn: boolean } | undefined> {
156 const own = (await $.store.get(recordKey(await $.session.id()))) as Partial<Kept> | undefined
157 if (own !== undefined) return { record: own, isOwn: true }
158 const mine = new Set(marksOf(await $.session.messages()))
159 if (mine.size === 0) return undefined
160 const scored: { record: Partial<Kept>; score: number }[] = []
161 for (const key of await $.store.keys()) {
162 if (!key.startsWith('session:')) continue
163 const record = ((await $.store.get(key)) ?? {}) as Partial<Kept>
164 const score = new Set((record.marks ?? []).filter(mark => mine.has(mark))).size
165 if (score > 0) scored.push({ record, score })
166 }
167 const best = Math.max(0, ...scored.map(s => s.score))
168 if (best < 3) return undefined
169 const near = scored.filter(s => s.score * 2 > best).sort((a, b) => (b.record.at ?? 0) - (a.record.at ?? 0))
170 return near[0] === undefined ? undefined : { record: near[0].record, isOwn: false }
171}
172
173// Takes up what the session, or the one it came from, kept: the person's choice (one
174// already made, by a reload, stays), the reactions on messages it still holds, and, its
175// own, whether the model was told.
176async function takeUp($: EngineInterface) {
177 const found = await kept($).catch(() => undefined)
178 if (found === undefined) return
179 const { record, isOwn } = found
180 const chosen = choiceOf(record)
181 if (chosen !== null) await update($, choice, was => was ?? chosen)
182 const theirs = record.reactions ?? []
183 const held = isOwn ? theirs : reactionsHeld(theirs, await $.session.messages().catch(() => []))
184 if (held.length > 0) await update($, reactions, mine => joinReactions(held, mine))
185 if (isOwn && record.isBriefed === true) await update($, isBriefed, () => true)
186}
187
188// What the model is told beside the person's message: how reactions work once they come
189// on (and again after a compaction), and once that they have gone off.
190async function noteFor($: EngineInterface): Promise<string | undefined> {
191 const now = await read($, isOn)
192 if (now === (await read($, isBriefed))) return undefined
193 await update($, isBriefed, () => now)
194 await keep($)
195 return now ? BRIEF : OFF_NOTE
196}
197
198// Puts `emoji` on the person's message the turn answers; whether there was one.
199async function react($: EngineInterface, emoji: string): Promise<boolean> {
200 const to = await read($, answering)
201 if (to === null) return false
202 await update($, reactions, list => withReaction(list, { id: to.id, mark: to.mark, emoji }))
203 return true
204}
205
206// The main conversation's reply as it streams, its text held back while it could still
207// be one emoji: then passed on as it came or, being one emoji on a person's message, as
208// NO_RESPONSE, which the desktop draws as nothing, the emoji put on the message. A reply
209// that calls a tool, or thinks after its text, is passed on as it came.
210async function* reacting(
211 $: EngineInterface,
212 stream: HookStream<TurnStepChunk, TurnStepResult>,
213): AsyncGenerator<TurnStepChunk, TurnStepResult> {
214 // Every piece since the reply's text began, in order (null once passed on), and that text.
215 let held: TurnStepChunk[] | null = []
216 let text = ''
217 let isReaction = false
218 const settle = async () => isOneEmoji(text) && (await react($, text.trim()))
219 for await (const chunk of stream) {
220 if (held === null || (held.length === 0 && chunk.kind !== 'text')) {
221 yield chunk
222 continue
223 }
224 if (chunk.kind === 'stop') {
225 isReaction = await settle()
226 yield* isReaction ? asNoResponse(held) : held
227 held = null
228 yield chunk
229 continue
230 }
231 held.push(chunk)
232 if (chunk.kind === 'engine') continue
233 if (chunk.kind === 'text') {
234 text += chunk.text
235 if (couldBeEmoji(text)) continue
236 }
237 yield* held
238 held = null
239 }
240 if (held !== null) {
241 isReaction = await settle()
242 yield* isReaction ? asNoResponse(held) : held
243 }
244 const result = await stream.result
245 return isReaction ? { ...result, answer: NO_RESPONSE } : result
246}
247
248// The pieces of a reply with its text as NO_RESPONSE, in the first piece of text.
249function asNoResponse(held: TurnStepChunk[]): TurnStepChunk[] {
250 const first = held.findIndex(chunk => chunk.kind === 'text')
251 return held.flatMap((chunk, i): TurnStepChunk[] => {
252 if (chunk.kind !== 'text') return [chunk]
253 return i === first ? [{ ...chunk, text: NO_RESPONSE }] : []
254 })
255}
256
257// A stored reply's blocks with its text as NO_RESPONSE, in its first text block.
258function asNoResponseContent(content: readonly Block[]): Block[] {
259 const first = content.findIndex(block => block.type === 'text')
260 return content.flatMap((block, i) => (block.type !== 'text' ? [block] : i === first ? [{ type: 'text', text: NO_RESPONSE }] : []))
261}
262
263// Props that give a Box something to show, or room, though it holds nothing.
264const SHAPED = /^(border|padding|margin|height|minHeight|width|minWidth|background)/
265
266// A drawing that shows nothing, as a plugin beneath draws a row it hides: none, a Box
267// drawn "none" that no hover reveals, or a Box or Text of only such with no shape of
268// its own. Anything else, the engine's own drawing among it, shows something.
269function isBlank(node: unknown): boolean {
270 if (node === null || node === undefined || node === false || node === '') return true
271 if (typeof node !== 'object') return false
272 const el = node as { type?: unknown; props?: Record<string, unknown>; hover?: Record<string, unknown>; children?: unknown[] }
273 if (el.type === 'Box' && el.props?.display === 'none') return el.hover?.display === undefined
274 if (el.type !== 'Box' && el.type !== 'Text') return false
275 if (Object.keys(el.props ?? {}).some(prop => SHAPED.test(prop))) return false
276 return (el.children ?? []).every(isBlank)
277}
278
279const BADGE_HEIGHT = 20
280const BADGE_WIDTH = 30
281
282// The SVG of a reaction: the emoji in a small faint pill, as thread-chat draws its
283// filter pills, light or dark with the app. A solid one (`isSolid`) first paints the
284// pill, its outline included, in the desktop's transcript colour, so what it floats over
285// (the bubble's corner) does not show through and it looks as it does on the bare page.
286// The desktop draws an Svg as an image, so it takes no colour from the page around it.
287function badgePicture(emoji: string, isSolid = false): string {
288 const escaped = emoji.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
289 const h = BADGE_HEIGHT
290 const w = BADGE_WIDTH
291 return [
292 `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">`,
293 '<style>.bg{fill:#ffffff14;stroke:#ffffff38}.base{fill:#151515}',
294 '@media (prefers-color-scheme: light){.bg{fill:#0000000a;stroke:#00000038}.base{fill:#fcfcfb}}</style>',
295 isSolid ? `<rect class="base" x="0.25" y="0.25" width="${w - 0.5}" height="${h - 0.5}" rx="${(h - 0.5) / 2}"/>` : '',
296 `<rect class="bg" x="0.75" y="0.75" width="${w - 1.5}" height="${h - 1.5}" rx="${(h - 1.5) / 2}"/>`,
297 `<text x="${w / 2}" y="${h / 2}" text-anchor="middle" dominant-baseline="central" font-size="12"`,
298 ` font-family="Segoe UI Emoji, Apple Color Emoji, Noto Color Emoji, sans-serif">${escaped}</text>`,
299 '</svg>',
300 ].join('')
301}
302
303// How far up from the bottom of the message's row the desktop's reaction floats, in
304// lines: the row ends with the room the desktop keeps under the bubble for the message's
305// time and copy buttons (shown on hover), so one line up sits on the bubble's corner.
306const RISE = 1
307
308// How far in from the right edge of the message's row the desktop's reaction floats, in
309// columns: off the bubble's right edge, so the pill sits on its corner, not flush with it.
310const INSET = 1
311
312// A message with its reaction. On the desktop, a small solid pill floating over the
313// message's row near its right edge, on the bubble's bottom-right corner: the desktop
314// draws the bubble and the time and copy buttons under it as one piece, so a pill drawn
315// after it in the flow would sit below those buttons, away from the bubble. It floats
316// beside the message, never round it: the engine refuses a drawing that puts position
317// or size on a box holding its message. On the terminal, the emoji in
318// faint brackets on the line under the message. Elsewhere, a pill on the line above the
319// bubble, at the edge the person's messages keep to. Never beside the bubble in the flow:
320// the desktop sizes its bubble to a share of the row it is drawn in, and a row shared
321// with the badge shrinks to the message, so the bubble would narrow and its words wrap.
322function withBadge(
323 $: EngineInterface,
324 e: Parameters<EngineInterface['ui']['resolve']>[0],
325 message: RenderElement,
326 emoji: string,
327): RenderElement {
328 if (e.surface === 'desktop') {
329 const { Box, Svg } = $.ui.resolve(e)
330 return (
331 <Box flexDirection="column">
332 {message}
333 <Box position="absolute" right={INSET} bottom={RISE}>
334 <Svg source={badgePicture(emoji, true)} alt={`Reaction: ${emoji}`} width={BADGE_WIDTH} height={BADGE_HEIGHT} />
335 </Box>
336 </Box>
337 )
338 }
339 if (e.surface === 'terminal') {
340 const { Box, Text } = $.ui.resolve(e)
341 return (
342 <Box flexDirection="column">
343 {message}
344 <Box flexDirection="row" marginLeft={2}>
345 <Text dimColor>(</Text>
346 <Text>{emoji}</Text>
347 <Text dimColor>)</Text>
348 </Box>
349 </Box>
350 )
351 }
352 const { Box, Svg } = $.ui.resolve(e)
353 const isOnRight = e.surface === 'mobile'
354 return (
355 <Box flexDirection="column">
356 <Box flexDirection="row" justifyContent={isOnRight ? 'flex-end' : 'flex-start'}>
357 <Svg source={badgePicture(emoji)} alt={`Reaction: ${emoji}`} width={BADGE_WIDTH} height={BADGE_HEIGHT} />
358 </Box>
359 {message}
360 </Box>
361 )
362}
363
364export const register: Register = on => {
365 watchSwitch(on)
366 welcome(on)
367 on('session.start', async ($, e, next) => {
368 await $.command.register({
369 name: 'react',
370 description: 'Turn emoji reactions on or off in this chat, or by default in new chats',
371 argumentHint: argumentHint(NAMES),
372 })
373 // A restarted or resumed session takes up the choice and reactions it kept; a
374 // rewound or forked one, those of the session it came from. Never switched, it
375 // follows the default.
376 await takeUpDefault($)
377 await takeUp($)
378 await settle($)
379 await keep($)
380 redescribe($)
381 return next(e)
382 })
383
384 // `/react` asks whether reactions are on in this chat, `/react default` whether in new
385 // chats; its arguments set either, or say how they are (command.ts).
386 on('command.run', { command: 'react' }, async ($, e) => ({ text: await runSwitch(sessionOf($), NAMES, e.args) }))
387
388 // The menu's line for /react says whether reactions are on here and in new chats.
389 on('command.describe', { command: 'react' }, async ($, e, next) => next({ ...e, description: descriptionOf(NAMES, await stateOf($)) }))
390
391 // Beside the person's message the model is told when reactions came on or went off:
392 // that is the one way it is told. A system prompt section would not follow the switch,
393 // as the engine sends the prompt it recorded at the first request until a compaction.
394 on('prompt.submit', async ($, e, next) => {
395 if (!PERSON.has(e.origin.kind)) return next(e)
396 const note = await noteFor($)
397 // While on, the marks a session rewound or forked from this one is known by are kept fresh.
398 if (note === undefined && (await read($, isOn))) await keep($)
399 return note === undefined ? next(e) : next({ ...e, context: [...(e.context ?? []), note] })
400 })
401
402 // A compaction may summarise how reactions work away: while they are on, the model is
403 // told again beside the person's next message. (Gone off, it is still told so.)
404 on('session.compact', async ($, e, next) => {
405 const result = await next(e)
406 const isCompacted = e.agentId === undefined && e.trigger !== 'precompute' && result.skip === undefined
407 if (isCompacted && (await read($, isOn)) && (await read($, isBriefed))) {
408 await update($, isBriefed, () => false)
409 await keep($)
410 }
411 return result
412 })
413
414 // The person's message a turn answers is noted as it is stored: one sent to a running
415 // turn too. A turn started by anything else (a notification, a command, a plugin's
416 // prompt) answers none of theirs. While on, a reply of one emoji that reached here as
417 // it came is stored as NO_RESPONSE all the same, and put on the message.
418 on('session.append', async ($, e, next) => {
419 if (e.agentId !== undefined) return next(e)
420 const isTurnStart = e.door === 'prompt' || e.door === 'delivery' || e.door === 'command'
421 if (e.message.type === 'user' && isTurnStart) {
422 if (PERSON.has(e.origin.kind) && e.door !== 'command') {
423 await update($, answering, () => ({ id: e.uuid, mark: markOf(textsOf(e.message.content)[0] ?? '') }))
424 } else if (e.door !== 'delivery') {
425 await update($, answering, () => null)
426 }
427 }
428 if (e.door !== 'response' || e.message.type !== 'assistant' || !(await read($, isOn))) return next(e)
429 const isText = e.message.content.every(block => block.type === 'text' || block.type === 'thinking' || block.type === 'redacted_thinking')
430 const text = textsOf(e.message.content).join('')
431 if (!isText || !isOneEmoji(text) || !(await react($, text.trim()))) return next(e)
432 return next({ ...e, message: { ...e.message, content: asNoResponseContent(e.message.content) } })
433 })
434
435 // While on, the main conversation's reply of one emoji goes on as NO_RESPONSE, the
436 // emoji put on the person's message it answers.
437 on('turn.step', async function* ($, e, next) {
438 if (e.agentId !== undefined || !(await read($, isOn))) return yield* next(e)
439 return yield* reacting($, next(e))
440 })
441
442 // The reactions are kept for the session's next run as each turn ends.
443 on('turn.complete', async ($, e, next) => {
444 const result = await next(e)
445 if (e.agentId === undefined && (await read($, isOn))) await keep($)
446 return result
447 })
448
449 // A reply that became a reaction draws as nothing, on every surface. Off, a reply is
450 // the engine's drawing alone.
451 on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
452 if (e.props.text.trim() !== NO_RESPONSE || !(await read($, isOn))) return next(e)
453 const { Box } = $.ui.resolve(e)
454 return <Box display="none" />
455 })
456
457 // A message with a reaction is the engine's drawing (or another mod's), the reaction on
458 // it (on the desktop, its bubble's bottom-right corner; under it on the terminal). A row
459 // drawn as nothing stays nothing.
460 on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
461 if (!(await read($, isOn))) return next(e)
462 const isPerson = PERSON.has(e.props.origin.kind)
463 const reaction = reactionFor(await read($, reactions), e.requestId, isPerson ? e.props.text : undefined)
464 if (reaction === undefined) return next(e)
465 const message = await next(e)
466 if (isBlank(message)) return message
467 return withBadge($, e, message, reaction.emoji)
468 })
469}
470hooks/reactions.ts 100 lines1import type { Reaction } from '../types'
2
3// What a reply that became a reaction goes on as, and is kept as: a reply the desktop
4// draws as nothing, which the model reads as having said nothing.
5export const NO_RESPONSE = 'No response requested.'
6
7// What the model is told beside the person's message once reactions come on (and again
8// after a compaction), and once after they go off.
9export const BRIEF = `# Emoji reactions
10When your whole reply would only acknowledge the user's message (such as "on it", "done", "got it" or "thanks"), you may reply with exactly one emoji and nothing else, for example 👍, ✅ or 🙏. It is shown as a reaction on the user's message instead of as a reply, and your history keeps that reply as "${NO_RESPONSE}". Any other reply, more than one emoji included, is shown as a normal reply. This holds for the rest of the conversation, until a note says the user turned reactions off.`
11
12export const OFF_NOTE =
13 'The user turned emoji reactions off. Acknowledge in words again: a reply of one emoji is now shown as a normal reply.'
14
15// One emoji: a flag, a keycap, or a pictograph with its presentation and skin tone
16// marks, joined to others by zero-width joiners, and a subdivision flag's tags.
17const PICTOGRAPH = '\\p{Extended_Pictographic}\\uFE0F?\\p{Emoji_Modifier}?'
18const ONE_EMOJI = new RegExp(
19 `^(?:\\p{Regional_Indicator}{2}|[#*0-9]\\uFE0F?\\u20E3|${PICTOGRAPH}(?:\\u200D${PICTOGRAPH})*[\\u{E0020}-\\u{E007F}]*)$`,
20 'u',
21)
22// What an emoji is made of, a lone surrogate included: a reply streamed so far that
23// holds nothing else may still turn out to be one.
24const EMOJI_PARTS =
25 /^[\p{Extended_Pictographic}\p{Emoji_Modifier}\p{Regional_Indicator}️⃣\u{E0020}-\u{E007F}#*0-9\uD800-\uDFFF]*$/u
26// The longest emoji held for, in UTF-16 units: a family or a subdivision flag is
27// under 20.
28const EMOJI_MAX = 32
29
30// Whether a reply's whole text is one emoji, spacing round it aside.
31export const isOneEmoji = (text: string) => ONE_EMOJI.test(text.trim())
32
33// Whether a reply streamed so far could still be one emoji once it has all come.
34export function couldBeEmoji(text: string): boolean {
35 const t = text.trim()
36 return t.length <= EMOJI_MAX && EMOJI_PARTS.test(t)
37}
38
39// A text's start with its spacing dropped: the same however the text's blocks were
40// joined, and with notes for the model after it.
41export const markOf = (text: string) => text.replace(/\s+/g, '').slice(0, 80)
42
43// A mark this short ("ok", "thanks") is said too often to know a message by.
44const MIN_MARK = 12
45
46// A row's id as the screen may know it: blocks of one stored row drawn apart take ids
47// that keep the row's first 24 characters.
48const stemOf = (id: string) => id.slice(0, 24)
49
50function newest(list: readonly Reaction[], is: (r: Reaction) => boolean): Reaction | undefined {
51 for (let i = list.length - 1; i >= 0; i--) {
52 const r = list[i] as Reaction
53 if (is(r)) return r
54 }
55 return undefined
56}
57
58// The reaction drawn on a message: the one kept for its row id; failing that, for a
59// person's message (`text` given), the newest kept for a message that starts the same,
60// where that start is long enough to tell messages apart.
61export function reactionFor(list: readonly Reaction[], id: string, text?: string): Reaction | undefined {
62 const byId = newest(list, r => r.id === id) ?? (id.length >= 24 ? newest(list, r => stemOf(r.id) === stemOf(id)) : undefined)
63 if (byId !== undefined || text === undefined) return byId
64 const mark = markOf(text)
65 return mark.length < MIN_MARK ? undefined : newest(list, r => r.mark === mark)
66}
67
68// How many reactions a session keeps: the newest.
69const REACTIONS_KEPT = 500
70
71// The reactions once `reaction` is on its message, in place of one it had.
72export function withReaction(list: readonly Reaction[], reaction: Reaction): Reaction[] {
73 return [...list.filter(r => r.id !== reaction.id), reaction].slice(-REACTIONS_KEPT)
74}
75
76// The reactions of both lists, `newer` winning for a message both have.
77export function joinReactions(older: readonly Reaction[], newer: readonly Reaction[]): Reaction[] {
78 return newer.reduce((all, r) => withReaction(all, r), [...older])
79}
80
81// The reactions on messages a conversation still holds: those of a session rewound or
82// forked from another, which may have left some of its messages behind.
83export function reactionsHeld(list: readonly Reaction[], messages: readonly { role: string; text: string }[]): Reaction[] {
84 const marks = messages.filter(m => m.role === 'user').map(m => markOf(m.text))
85 return list.filter(r => r.mark !== '' && marks.some(mark => mark.startsWith(r.mark)))
86}
87
88// Hashes of the starts of a conversation's messages, long enough to tell it apart:
89// what a session rewound or forked from this one is known by.
90export function marksOf(messages: readonly { text: string }[]): string[] {
91 return messages
92 .map(m => markOf(m.text))
93 .filter(start => start.length >= MIN_MARK)
94 .map(start => {
95 let hash = 0x811c9dc5
96 for (let i = 0; i < start.length; i++) hash = Math.imul(hash ^ start.charCodeAt(i), 0x01000193)
97 return (hash >>> 0).toString(16).padStart(8, '0')
98 })
99}
100hooks/command.ts 171 lines1import type { AskOptions } from 'claude-code'
2
3// This file is the same in thread-chat, multitask and react: keep the copies identical.
4//
5// Each mod's slash command (/threads, /multitask, /react) switches it on or off in the
6// chat, and by default in new chats, with the same arguments:
7//
8// (none) asks whether it is on in this chat, in the engine's question dialog
9// on | enable on in this chat, as the person's choice there
10// off | disable off in this chat, as the person's choice there
11// toggle the other way in this chat
12// status says how it is, here and in new chats
13// default asks whether new chats start with it on
14// default on | enable on in new chats, and in chats never switched
15// default off | disable off in new chats, and in chats never switched
16//
17// Setting the chat to what it is already still makes it the person's choice there, so a
18// default set later leaves the chat be, and says it was so; setting the default to what it
19// is already changes nothing and says so. Anything else changes nothing and says how to use
20// it. Where no one can be asked (a `-p` run draws nowhere), the command says how it is
21// instead. Its line in the command menu says how it is too.
22//
23// The engine lets `$` reach only functions declared in the file that uses it, so this file
24// never touches the session: each mod's command hook hands it what it needs (Session).
25
26// One mod's switch, by name.
27export type Names = {
28 // the command's name, without its slash
29 command: string
30 // what it switches, as a sentence starts with it (`Threads`), and the verb that follows
31 noun: string
32 be: 'is' | 'are'
33 // the arguments the mod takes beside these, for the usage line (`mode [multitask|focus]`)
34 extraUsage?: string
35}
36
37// How the switch is.
38export type State = {
39 // whether it is on in this chat
40 isOnHere: boolean
41 // the person's own choice in this chat; null where the chat follows the default
42 choiceHere: boolean | null
43 // whether it is on in new chats
44 isOnByDefault: boolean
45 // what more there is to say of the chat while it is on (multitask's mode), or ''
46 detail: string
47}
48
49// The session, as a mod's command hook hands it over.
50export type Session = {
51 // how the switch is now
52 state: () => Promise<State>
53 // whether anyone can be asked: a session that draws nowhere (a `-p` run) has no one
54 canAsk: () => Promise<boolean>
55 // `$.ui.ask`: the label picked, or typed text; rejects when dismissed
56 ask: (question: string, options: AskOptions) => Promise<string>
57 // turns it on or off in this chat as the person's choice; what to say. Called with what
58 // the chat is already, it records the choice and changes nothing else.
59 setHere: (isOn: boolean) => Promise<string>
60 // turns it on or off by default; what to say
61 setDefault: (isOn: boolean) => Promise<string>
62}
63
64const ON = new Set(['on', 'enable'])
65const OFF = new Set(['off', 'disable'])
66
67// On or off, as a word of the person's means it; undefined for any other word.
68export const valueOf = (word: string): boolean | undefined =>
69 ON.has(word.toLowerCase()) ? true : OFF.has(word.toLowerCase()) ? false : undefined
70
71const onOff = (isOn: boolean) => (isOn ? 'on' : 'off')
72
73// The command's arguments, as the menu draws them dim after its name.
74export const argumentHint = (names: Names) =>
75 `[on|off|toggle|status|${names.extraUsage === undefined ? '' : `${names.extraUsage.split(' ')[0]}|`}default [on|off]]`
76
77// What the command says to an argument it does not take.
78export const usageOf = (names: Names) =>
79 `Usage: \`/${names.command} [on|off|toggle|status|${names.extraUsage === undefined ? '' : `${names.extraUsage}|`}default [on|off]]\`; with no argument it asks.`
80
81// The person's words after the command, lower case.
82export const wordsOf = (args: string) => args.trim().toLowerCase().split(/\s+/).filter(word => word !== '')
83
84const detailOf = (state: State) => (state.isOnHere && state.detail !== '' ? `, ${state.detail}` : '')
85
86// How it is, here and in new chats: `Threads: on in this chat (your choice) · off in new chats`.
87export function statusOf(names: Names, state: State): string {
88 const why = state.choiceHere === null ? 'following the default' : 'your choice'
89 return `${names.noun}: ${onOff(state.isOnHere)} in this chat (${why})${detailOf(state)} · ${onOff(state.isOnByDefault)} in new chats`
90}
91
92// The command's line in the menu: `Threads: on here · off in new chats`.
93export const descriptionOf = (names: Names, state: State) =>
94 `${names.noun}: ${onOff(state.isOnHere)} here${detailOf(state)} · ${onOff(state.isOnByDefault)} in new chats`
95
96// Asks `question` with `labels`, the one at `current` marked as the current one; the
97// index of the label picked, or of the one a typed answer names; undefined when the
98// dialog was dismissed or the answer names none.
99export async function askAmong(
100 ask: Session['ask'],
101 question: string,
102 header: string,
103 labels: readonly string[],
104 current: number,
105): Promise<number | undefined> {
106 const shown = labels.map((label, i) => (i === current ? `${label} (current)` : label))
107 try {
108 const answer = await ask(question, { options: shown, header })
109 const picked = shown.indexOf(answer)
110 if (picked >= 0) return picked
111 const typed = labels.findIndex(label => label.toLowerCase() === answer.trim().toLowerCase())
112 return typed >= 0 ? typed : undefined
113 } catch {
114 return undefined
115 }
116}
117
118// Asks on or off; true or false, or undefined when dismissed or answered otherwise.
119async function askOnOff(session: Session, question: string, header: string, isOn: boolean): Promise<boolean | undefined> {
120 const picked = await askAmong(session.ask, question, header, ['On', 'Off'], isOn ? 0 : 1)
121 return picked === undefined ? undefined : picked === 0
122}
123
124// Makes `isOn`, which the chat is already, the person's choice there, as `on` or `off`
125// does; says it was so, and, where the chat followed the default, that it now keeps it.
126async function keepHere(session: Session, names: Names, state: State, isOn: boolean): Promise<string> {
127 await session.setHere(isOn)
128 const already = `${names.noun} ${names.be} already ${onOff(isOn)}`
129 if (state.choiceHere === isOn) return `${already} in this chat.`
130 return `${already}; this chat now keeps ${names.be === 'are' ? 'them' : 'it'} ${onOff(isOn)}.`
131}
132
133// Asks whether it is on in this chat (the bare command) or, with `isDefault`, in new chats
134// (`/<command> default`), and changes it as answered. A dismissed question changes nothing
135// and says how it is; so does an answer of the default it is already. An answer of what
136// the chat is already makes it the person's choice there.
137async function askOne(session: Session, names: Names, isDefault: boolean): Promise<string> {
138 if (!(await session.canAsk())) return statusOf(names, await session.state())
139 const before = await session.state()
140 const isOn = isDefault
141 ? await askOnOff(session, `${names.noun} in new chats?`, 'New chats', before.isOnByDefault)
142 : await askOnOff(session, `${names.noun} in this chat?`, 'This chat', before.isOnHere)
143 const now = await session.state()
144 if (isOn === undefined || (isDefault && isOn === now.isOnByDefault)) return `No change. ${statusOf(names, now)}`
145 if (isDefault) return session.setDefault(isOn)
146 return isOn === now.isOnHere ? keepHere(session, names, now, isOn) : session.setHere(isOn)
147}
148
149// Runs the command with the person's arguments (any the mod takes beside these handled
150// before); what it says.
151export async function runSwitch(session: Session, names: Names, args: string): Promise<string> {
152 const words = wordsOf(args)
153 const [first = '', second = ''] = words
154 if (words.length === 0) return askOne(session, names, false)
155 const state = await session.state()
156 if (words.length === 1) {
157 const value = valueOf(first)
158 if (value === state.isOnHere) return keepHere(session, names, state, value)
159 if (value !== undefined) return session.setHere(value)
160 if (first === 'toggle') return session.setHere(!state.isOnHere)
161 if (first === 'status') return statusOf(names, state)
162 if (first === 'default') return askOne(session, names, true)
163 }
164 if (words.length === 2 && first === 'default') {
165 const value = valueOf(second)
166 if (value === state.isOnByDefault) return `${names.noun} ${names.be} already ${onOff(value)} by default in new chats.`
167 if (value !== undefined) return session.setDefault(value)
168 }
169 return usageOf(names)
170}
171hooks/ui-switch.ts 112 lines1import type { EngineInterface, On } from 'claude-code'
2
3// This file is the same in thread-chat, multitask and react: keep the copies identical.
4//
5// Claude Code draws a mod's controls in an app (the desktop's, a phone's) only while its
6// hooks-modules switch reads on. The switch is a rollout flag each Claude Code process
7// saves, as it starts, to one cache in the global config that every version shares. An
8// older version that is served it off (such as one bundled in another app) saves it off,
9// and a running session then refuses each request to draw a mod's controls, though the
10// mods' hooks go on running; a newer version starting saves it on again. A session run
11// with DISABLE_GROWTHBOOK set reads the flag's default instead, on since 2.1.289.
12//
13// So beside the person's message, while the saved switch reads off and the session
14// draws in an app, the model is told what happened and what to do, once until the
15// switch reads on again; a toast says so too. Whichever mod's hook runs first tells;
16// the others find its note in the message's context and stay quiet.
17
18const FLAG = 'tengu_plugin_hooks_modules'
19
20// What every copy's note holds, so the others know it is told.
21export const SWITCH_MARK = 'hooks-modules switch'
22
23export const SWITCH_NOTE =
24 `The mods' controls are off in the app: an older Claude Code version on this computer (such as one bundled in another app) reset the shared ${SWITCH_MARK}, so Claude Code has stopped drawing the controls of the thread-chat, multitask and react mods (the band above the prompt, reactions); the mods still work underneath. ` +
25 'Tell the user this once, plainly, with what to do: open a new session in the Code tab, which turns the switch back on. ' +
26 'For a lasting fix, run the older Claude Code with DISABLE_GROWTHBOOK=1 set, or upgrade it to 2.1.289 or later.'
27
28export const SWITCH_TOAST = `The mods' controls are off: an older Claude Code version reset the ${SWITCH_MARK}. Open a new session in the Code tab to turn it back on.`
29
30const TOAST_MS = 20_000
31
32// A read over this rejects; such a config is left unread.
33const READ_LIMIT = 4 * 1024 * 1024
34
35// The ways a person's own prompt arrives: typed in the terminal, the desktop app (an SDK
36// host) or Remote Control.
37const PERSON = /^(composer|sdk|bridge)$/
38
39type Watch = {
40 // the global config's path; null where there is no home folder
41 path?: string | null
42 // the global config as last read: its file's size and time, and whether it held the
43 // switch saved off
44 saved?: { mtimeMs: number; size: number; isOff: boolean }
45 // whether the session reads the flag's default (on) whatever is saved
46 isDefaultOn?: boolean
47 // whether the person was told since the switch last read on
48 isTold: boolean
49}
50
51// Where the engine keeps the global config: in CLAUDE_CONFIG_DIR, else the home folder.
52async function configPath($: EngineInterface, watch: Watch): Promise<string | null> {
53 if (watch.path !== undefined) return watch.path
54 const dir = (await $.env.get('CLAUDE_CONFIG_DIR')) || (await $.env.get('USERPROFILE')) || (await $.env.get('HOME'))
55 watch.path = dir ? `${dir.replace(/[\\/]+$/, '')}/.claude.json` : null
56 return watch.path
57}
58
59// Whether the saved switch reads off; undefined when the config cannot be read. Read
60// again only once the file changed.
61async function isSavedOff($: EngineInterface, watch: Watch): Promise<boolean | undefined> {
62 const file = await configPath($, watch)
63 if (file === null) return undefined
64 const stat = await $.fs.stat(file).catch(() => undefined)
65 if (stat === undefined || stat.size > READ_LIMIT) return undefined
66 if (watch.saved?.mtimeMs === stat.mtimeMs && watch.saved.size === stat.size) return watch.saved.isOff
67 const text = await $.fs.read(file).catch(() => undefined)
68 if (typeof text !== 'string') return undefined
69 let config: { cachedGrowthBookFeatures?: Record<string, unknown> } | null
70 try {
71 config = JSON.parse(text)
72 } catch {
73 return undefined
74 }
75 const isOff = config?.cachedGrowthBookFeatures?.[FLAG] === false
76 watch.saved = { mtimeMs: stat.mtimeMs, size: stat.size, isOff }
77 return isOff
78}
79
80// The note to put beside the person's message, when they are to be told.
81async function switchNote($: EngineInterface, watch: Watch, context: readonly string[], kind: string): Promise<string | undefined> {
82 if (watch.isDefaultOn === undefined) {
83 const value = (await $.env.get('DISABLE_GROWTHBOOK'))?.trim() ?? ''
84 watch.isDefaultOn = !/^(|0|false|no|off)$/i.test(value)
85 }
86 if (watch.isDefaultOn) return undefined
87 const isOff = await isSavedOff($, watch)
88 if (isOff === undefined) return undefined
89 if (!isOff) {
90 watch.isTold = false
91 return undefined
92 }
93 if (context.some(note => note.includes(SWITCH_MARK))) watch.isTold = true
94 if (watch.isTold) return undefined
95 // The terminal draws the controls itself: only an app's are refused.
96 const isInApp = kind !== 'composer' || (await $.session.surfaces()).some(surface => surface !== 'terminal')
97 if (!isInApp) return undefined
98 watch.isTold = true
99 $.ui.toast(SWITCH_TOAST, { timeoutMs: TOAST_MS })
100 return SWITCH_NOTE
101}
102
103// Tells the model and the person, beside the person's message, when Claude Code stopped
104// drawing the mods' controls.
105export function watchSwitch(on: On) {
106 const watch: Watch = { isTold: false }
107 on('prompt.submit', { origin: { kind: PERSON } }, async ($, e, next) => {
108 const note = await switchNote($, watch, e.context ?? [], e.origin.kind).catch(() => undefined)
109 return note === undefined ? next(e) : next({ ...e, context: [...(e.context ?? []), note] })
110 })
111}
112hooks/welcome.tsx 205 lines1import type { ElementTable, On, RenderElement } from 'claude-code'
2
3// This file is the same in thread-chat, multitask and react but for OWN, the mod's own
4// value: keep the copies otherwise identical.
5//
6// The welcome line, in the band above the prompt: the command of each of the mods newly
7// installed, the ones not installed with what each is for, a link to the getting-started
8// page and a Dismiss button. Dismissed, it stays away until another of the mods is
9// installed. It shows whether the mods are on or off: it says how to turn them on. The
10// engine raises the band on the terminal and the desktop only, and never in a `-p` run.
11//
12// One line for every mod installed: each runs this, and only the one whose hook stands
13// outermost in the band's chain draws it, so it sits above all the mods draw there. Each
14// mod knows which of the others are installed by their `welcome` values, which each writes
15// as the session starts, and whether it stands outermost by what ran beneath its hook: the
16// outermost finds every other installed mod there.
17//
18// The press on Dismiss passes every mod's hook, whichever drew it, and each installed mod
19// keeps in its own store (shared by every session) the mods installed then, with those
20// any of them kept before. The line shows while an installed mod is in none of the
21// installed mods' records: a mod installed later, its store empty, still finds in the
22// others' that they were seen, and a dismissal holds whichever mods stay installed.
23
24// The one line that differs between the copies: this mod's own value. The engine refuses
25// a module that names another plugin's value in a write, though the write never runs.
26const OWN = { plugin: 'react', key: 'welcome' } as const
27
28const THREAD_CHAT = { plugin: 'thread-chat', key: 'welcome' } as const
29const MULTITASK = { plugin: 'multitask', key: 'welcome' } as const
30const REACT = { plugin: 'react', key: 'welcome' } as const
31
32type Mod = 'thread-chat' | 'multitask' | 'react'
33const MODS: readonly Mod[] = ['thread-chat', 'multitask', 'react']
34
35// What each installed mod published: the mods its store says were seen.
36type Seen = Partial<Record<Mod, string[]>>
37
38// What the line says: the mods newly installed, and those to try.
39type Plan = { fresh: Mod[]; missing: Mod[] }
40
41// The mods installed when the person last dismissed the line, kept in this mod's store.
42const KEPT = 'welcome'
43
44export const DISMISS = 'claude-multitask-welcome-dismiss'
45export const DOCS = 'https://github.com/othrayte/claude-multitask/blob/main/docs/getting-started.md'
46
47// Every directory: the session.start matcher that lets every session through. A mod
48// registers an event once without a matcher, and its own hook is that one.
49const ANY = /^/
50
51const ABOUT: Record<Mod, { command: string; what: string; why: string; whyShort: string }> = {
52 'thread-chat': { command: '/threads', what: 'topic threads', why: 'keep each topic in its own thread', whyShort: 'topic threads' },
53 multitask: { command: '/multitask', what: 'multitasking', why: 'talk to Claude while it works', whyShort: 'talk while it works' },
54 react: { command: '/react', what: 'emoji reactions', why: "emoji reactions instead of 'done' replies", whyShort: 'emoji reactions' },
55}
56
57// The cells the first line gives the link and the button: `Docs [ Dismiss ]` and the gap.
58const CONTROLS_WIDTH = 19
59
60const isMod = (name: string): name is Mod => (MODS as readonly string[]).includes(name)
61const namesOf = (value: unknown): string[] => (Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : [])
62const join = (parts: readonly string[]) => (parts.length <= 1 ? parts.join('') : `${parts.slice(0, -1).join(', ')} and ${parts.at(-1)}`)
63
64// The values the three mods published, in MODS order; one never written is undefined.
65function seenOf(values: readonly ({ seen: string[] } | undefined)[]): Seen {
66 const seen: Seen = {}
67 MODS.forEach((mod, i) => {
68 const value = values[i]
69 if (value !== undefined) seen[mod] = namesOf(value.seen)
70 })
71 return seen
72}
73
74const installedOf = (seen: Seen) => MODS.filter(mod => seen[mod] !== undefined)
75
76// Dismissed: the mods installed now, with those any installed mod kept.
77function dismissed(seen: Seen): string[] {
78 const installed = installedOf(seen)
79 const names = new Set([...installed.flatMap(mod => seen[mod] ?? []), ...installed])
80 return MODS.filter(mod => names.has(mod))
81}
82
83// What the line says, when `me` draws it: none while another installed mod stands outside
84// it in the chain (not among the plugins `beneath` it), or while every installed mod was
85// seen.
86function planFor(seen: Seen, me: string, beneath: ReadonlySet<string>): Plan | undefined {
87 const installed = installedOf(seen)
88 if (!isMod(me) || !installed.includes(me)) return undefined
89 if (installed.some(mod => mod !== me && !beneath.has(mod))) return undefined
90 const known = new Set(installed.flatMap(mod => seen[mod] ?? []))
91 const fresh = installed.filter(mod => !known.has(mod))
92 if (fresh.length === 0) return undefined
93 return { fresh, missing: MODS.filter(mod => !installed.includes(mod) && !known.has(mod)) }
94}
95
96// The longest of the texts that fits in `room` cells; the last when none does.
97const fit = (texts: readonly string[], room: number | undefined) =>
98 texts.find(text => room === undefined || text.length <= room) ?? texts.at(-1) ?? ''
99
100// The commands of the mods newly installed.
101function freshLine(fresh: readonly Mod[], room: number | undefined): string {
102 const lead = fresh.length === 1 ? 'New mod' : 'New mods'
103 return fit(
104 [
105 `${lead}: ${join(fresh.map(mod => `${ABOUT[mod].command} for ${ABOUT[mod].what}`))}.`,
106 `${lead}: ${join(fresh.map(mod => ABOUT[mod].command))}.`,
107 ],
108 room,
109 )
110}
111
112// The mods not installed, each with what it is for, shorter where the long text doesn't fit.
113function missingLine(missing: readonly Mod[], room: number | undefined): string {
114 const long = join(missing.map(mod => `${mod} (${ABOUT[mod].why})`))
115 const short = join(missing.map(mod => `${mod} (${ABOUT[mod].whyShort})`))
116 return fit([`Also try ${long}.`, `Also try ${short}.`], room)
117}
118
119// Props that give a Box something to show, or room, though it holds nothing.
120const SHAPED = /^(border|padding|margin|height|minHeight|width|minWidth|background)/
121
122// A drawing that shows nothing: the engine's own (the band holds nothing of its own but
123// a survey), none, a Box drawn "none", or a Box or Text of only such with no shape.
124function isBlank(node: unknown): boolean {
125 if (node === null || node === undefined || node === false || node === '') return true
126 if (typeof node !== 'object') return false
127 const el = node as { type?: unknown; props?: Record<string, unknown>; hover?: Record<string, unknown>; children?: unknown[] }
128 if (el.type === 'engine') return true
129 if (el.type === 'Box' && el.props?.display === 'none') return el.hover?.display === undefined
130 if (el.type !== 'Box' && el.type !== 'Text') return false
131 if (Object.keys(el.props ?? {}).some(prop => SHAPED.test(prop))) return false
132 return (el.children ?? []).every(isBlank)
133}
134
135// The line: the new mods' commands, the link and the button; under it, the mods to try.
136// `width` is the band's, in cells, when the surface measured it.
137function drawWelcome(ui: ElementTable, width: number | undefined, plan: Plan): RenderElement {
138 const { Box, Text, Button, Link } = ui
139 return (
140 <Box flexDirection="column" minWidth={0}>
141 <Box flexDirection="row" columnGap={2}>
142 <Box flexGrow={1} flexShrink={1} minWidth={0}>
143 <Text>{freshLine(plan.fresh, width === undefined ? undefined : width - CONTROLS_WIDTH)}</Text>
144 </Box>
145 <Box flexDirection="row" columnGap={2} flexShrink={0}>
146 <Link href={DOCS} label="Docs" />
147 {/* Every mod's `ui.press` hook keeps the dismissal: the press needs nothing more. */}
148 <Button key={DISMISS} label="Dismiss" onPress={() => {}} />
149 </Box>
150 </Box>
151 {plan.missing.length > 0 && <Text dimColor>{missingLine(plan.missing, width)}</Text>}
152 </Box>
153 )
154}
155
156export function welcome(on: On) {
157 // As the session starts, each mod publishes what its store kept, which also says it is
158 // installed.
159 on('session.start', { cwd: ANY }, async ($, e, next) => {
160 const result = await next(e)
161 try {
162 await $.state.set(OWN, { seen: namesOf(await $.store.get(KEPT)) })
163 } catch {
164 // unpublished: the line counts this mod as not installed
165 }
166 return result
167 })
168
169 // A press on Dismiss, whichever of the mods drew it: this mod keeps and publishes the
170 // mods installed now, with those any of them kept.
171 on('ui.press', { element: DISMISS }, async ($, e, next) => {
172 const result = await next(e)
173 if (!isMod(e.plugin)) return result
174 try {
175 const values = [(await $.state.get(THREAD_CHAT)).value, (await $.state.get(MULTITASK)).value, (await $.state.get(REACT)).value]
176 const seen = dismissed(seenOf(values))
177 await $.store.set(KEPT, seen)
178 await $.state.set(OWN, { seen })
179 } catch {
180 // kept as it was
181 }
182 return result
183 })
184
185 // The band: the line above what the rest draw there, a gap between them when they draw
186 // anything. A survey holds the band alone: the matcher leaves it be, and is the mod's
187 // own band hook's with that added, as a mod registers one matcher once.
188 on('ui.render', { component: 'AbovePrompt', props: { hasSurvey: false } }, async ($, e, next) => {
189 const below = await next(e)
190 const values = [(await $.state.get(THREAD_CHAT)).value, (await $.state.get(MULTITASK)).value, (await $.state.get(REACT)).value]
191 const plan = planFor(seenOf(values), $.plugin.name, new Set(next.trace.map(link => link.plugin)))
192 if (plan === undefined) return below
193 const ui = $.ui.resolve(e)
194 const line = drawWelcome(ui, e.props.bodyColumns > 0 ? e.props.bodyColumns : undefined, plan)
195 if (isBlank(below)) return line
196 const { Box } = ui
197 return (
198 <Box flexDirection="column" rowGap={1} minWidth={0}>
199 {line}
200 {below}
201 </Box>
202 )
203 })
204}
205types/index.d.ts 44 lines1// An emoji the agent answered a person's message with, shown on that message: the
2// message by its stored row id and the start of its text as typed.
3export type Reaction = {
4 id: string
5 // the text's start, whitespace dropped: how the message is known where the screen
6 // draws it under another id
7 mark: string
8 emoji: string
9}
10
11// The person's message the main conversation's current turn answers.
12export type Answering = { id: string; mark: string }
13
14// thread-chat's thread view reads `isOn` and `reactions` to draw the reactions on the
15// person's messages as the chat does (its types/react.d.ts): keep their keys and shape,
16// or change both mods together.
17declare module 'claude-code' {
18 interface PluginState {
19 react: {
20 // whether reactions are on in the session: as the person last chose there with
21 // /react, else as the default; off, the mod leaves the session be
22 isOn: boolean
23 // the person's own choice in the session with /react, kept over the default; null
24 // until they make one
25 choice: boolean | null
26 // whether reactions are on in a session with no choice of its own, as the person
27 // last set with /react default (kept for every session); on until they set it
28 isOnByDefault: boolean
29 // whether the model was last told, beside the person's message, that reactions
30 // are on; false again after a compaction while on, so it is told again
31 isBriefed: boolean
32 // the reactions so far, oldest first, one per message
33 reactions: Reaction[]
34 // the person's message the turn running now answers; null when the turn came
35 // from anything else (a notification, a plugin's prompt)
36 answering: Answering | null
37 // the mods the welcome line above the prompt was last dismissed with, as this mod's
38 // store kept them (hooks/welcome.tsx); written as the session starts, so the other
39 // mods know this one is installed
40 welcome: { seen: string[] }
41 }
42 }
43}
44