SLOPSHOPPER

multitask

Multitasking: the main session becomes the talking mind and hands all work to background thoughts it watches and steers

panebandrowsguardcommandtoast
★ 1v0.5.0no licenseupdated 2026-10-15othrayte/claude-multitask/multitask
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · multitask
│ ┃ Thoughts ✕ › fix the failing auth test and add an audit log call │ ┃ Multitask mode · No thoughts yet. │ ┃ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /multitask │ ⎿ multitask: Multitask is on in this chat, in Multitask mode: this │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Thoughts
Multitask mode · No thoughts yet.
README

claude-multitask

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.

Demo: replies sorted into colour-coded threads, the thread view filtered to one thread, a background task running as a dot while the chat carries on, and an emoji reaction

Why

  • Talk while it works. With multitask you talk to one voice, and its thoughts (background agents) do the work. The voice is always free to talk.
  • No waiting, nothing held back. Ask something new, add a detail or change your mind whenever it occurs to you. The voice passes it to the right piece of work.
  • Questions come straight away. Your message isn't queued behind work in progress, so clarifying questions come at once and the right work starts sooner.
  • Topics stay apart. With thread-chat, a # heading puts a message in its topic's thread: colour-coded, readable on its own and easy to find later.
  • Emoji reactions. With react, the agent can acknowledge a message with an emoji reaction instead of a reply.

Examples: docs/why.md.

Install

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.

Use

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:

  • Alone, the command asks whether the mod is on in this chat, with its current value marked. Dismissing the question changes nothing.
  • 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.
  • In the command menu, each command's line shows how it is set, here and in new chats.

Multitask

  • Multitask is off in a new chat, unless you change the default (below). /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.
  • While it is on, the chat is in one of two modes. It starts in 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.
  • While it is off, Multitask shows nothing above the prompt and closes its Thoughts pane, and the chat stays in Focus. Thoughts it started run on unseen. Turning it off in Multitask mode switches to Focus.
  • /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.
  • Left of the mode control, the 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.
  • The 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

  • Threads are off in a new chat. /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.
  • While threads are off, thread-chat shows nothing: no picker or buttons above the prompt, no thread tags, no thread view. Your threads are kept for when /threads on turns them on again.
  • A # 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.
  • To put a message in a thread, hover it for + 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.
  • The thread picker above the prompt, a dropdown named for the picked thread and tinted in its colour, picks the thread messages without a heading go to, or No thread. A heading still wins, and moves the picker to its thread.
  • A message is sent with its thread's exact # 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).
  • Archived threads leave the pickers but keep their messages; /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.
  • Thread summaries: when you write in a thread after a long gap (75k tokens of other conversation by default), or after the chat was compacted, the agent gets a short summary of the thread with your message. A small model (Haiku) writes the summaries ahead, in the background, whenever threads are on. The agent can also read a thread's summary and latest messages itself, with its 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.
  • The 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.

Reactions

  • Reactions are on in a new chat. /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.
  • While they are on, a reply of a single emoji shows as a reaction on your message, not as a reply. With thread-chat, reactions show in its thread view too.
  • On the desktop the reaction sits on your message's bottom-right corner.
Source 9 files
hooks/register.tsx 1763 lines
1import { atom, read, update } from 'claude-code'
2import type {
3  AgentStatus,
4  EngineInterface,
5  Register,
6  RenderElement,
7  SessionSendAddress,
8  SessionSendResult,
9  Timer,
10  TurnCompleteReason,
11} from 'claude-code'
12
13import type { KeptThoughts, Thought, ThoughtStatus, Update } from '../types'
14import type { HookStream, TurnStepChunk, TurnStepResult } from 'claude-code'
15import {
16  NO_RESPONSE,
17  QUIET,
18  RELAY_NOTES,
19  THOUGHT,
20  VOICE,
21  VOICE_OFF,
22  VOICE_REMINDER,
23  WAKE,
24  describeThoughts,
25  formatNews,
26  formatUpdates,
27  fromPerson,
28  heardOf,
29  isQuiet,
30  isRelayText,
31  isWakeText,
32  marksOf,
33  newsOf,
34  oneLine,
35  pendingNote,
36  relayNames,
37} from './prompts'
38import { TELL_FIELD, drawThoughts } from './pane'
39import { BLINK_MS, FADE_MS, drawThoughtsButton } from './band'
40import { argumentHint, askAmong, descriptionOf, runSwitch, statusOf as switchStatus, usageOf, wordsOf } from './command'
41import type { Names, Session, State } from './command'
42import { watchSwitch } from './ui-switch'
43import { welcome } from './welcome'
44
45const isOn = atom({ plugin: 'multitask', key: 'isOn' } as const, false)
46const choice = atom({ plugin: 'multitask', key: 'choice' } as const, null)
47const isEnabledByDefault = atom({ plugin: 'multitask', key: 'isEnabledByDefault' } as const, false)
48const thoughts = atom({ plugin: 'multitask', key: 'thoughts' } as const, [])
49const inbox = atom({ plugin: 'multitask', key: 'inbox' } as const, [])
50const isMainBusy = atom({ plugin: 'multitask', key: 'isMainBusy' } as const, false)
51const toldVoice = atom({ plugin: 'multitask', key: 'toldVoice' } as const, false)
52const expanded = atom({ plugin: 'multitask', key: 'expanded' } as const, [])
53const openReports = atom({ plugin: 'multitask', key: 'openReports' } as const, [])
54const heard = atom({ plugin: 'multitask', key: 'heard' } as const, {})
55const paneTick = atom({ plugin: 'multitask', key: 'paneTick' } as const, 0)
56const bandTick = atom({ plugin: 'multitask', key: 'bandTick' } as const, 0)
57const tellingTo = atom({ plugin: 'multitask', key: 'tellingTo' } as const, '')
58const colorTurn = atom({ plugin: 'multitask', key: 'colorTurn' } as const, 0)
59const showsAllEnded = atom({ plugin: 'multitask', key: 'showsAllEnded' } as const, false)
60
61const PANE = 'multitask-thoughts'
62// Multitask's mode control in the band, drawn while the mod is on in the chat; it shows the
63// mode the chat is in, Multitask or Focus (Multitask mode off). In the terminal it is a
64// button: a press, or its hotkey while the band has the keyboard and thread-chat's picker
65// does not, switches to the other mode. ctrl+x tab lands on that picker when there are
66// threads; Tab moves along the band. Elsewhere it is a dropdown: picking the other mode
67// switches to it.
68const MODE_CONTROL = 'multitask'
69const MODE_HOTKEY = 'm'
70// The keys of the hit areas over the parts of the desktop's `thoughts` button: this, then the part.
71const THOUGHTS_HIT = 'thoughts-hit:'
72const MULTITASK_MODE = 'multitask'
73const FOCUS_MODE = 'focus'
74const AGENT = 'multitask:thought'
75const TOOL = {
76  think: 'mcp__multitask__think',
77  tell: 'mcp__multitask__tell',
78  unqueue: 'mcp__multitask__unqueue',
79  stop: 'mcp__multitask__stop',
80  thoughts: 'mcp__multitask__thoughts',
81} as const
82const OWN_TOOLS: ReadonlySet<string> = new Set(Object.values(TOOL))
83
84// The ways a person's own prompt arrives: typed in the terminal, the desktop
85// app (an SDK host) or Remote Control.
86const PERSON = new Set(['composer', 'sdk', 'bridge'])
87
88// How hard a model request may be asked to think, from least to most.
89const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const
90
91// What the voice may still call itself while multitasking is on.
92const VOICE_TOOLS = /^(mcp__multitask__|mcp__thread-chat__)|^(AskUserQuestion|ToolSearch)$/
93
94// The colours thoughts are drawn in: the first ones, the clearest, taken in turn; the rest
95// only while every one of those is held (see freeColor).
96const FIRST_COLORS = ['#4fa3e0', '#d9636a', '#58b36b', '#c98a2e']
97const PALETTE = [...FIRST_COLORS, '#9b6fd6', '#2fb3a6', '#d66bb0', '#8a9a3a']
98
99// Updates arriving close together reach the voice as one message.
100const FLUSH_MS = 2000
101// How long an interrupted thought gets to end its turn before the message goes anyway.
102const INTERRUPT_GRACE_MS = 4000
103// How often, and how many times, a hand-over looks for the engine to have ended a thought's run.
104const SETTLE_POLL_MS = 250
105const SETTLE_POLLS = 20
106// How long after a thought's turn ended its run may still count as running, ending, before
107// what waits for it goes anyway.
108const SETTLE_MS = SETTLE_POLL_MS * SETTLE_POLLS
109// When the voice is woken to hand a thought what waits for it, should no hook of this
110// mod's have handed it over since it fell due: after each of these waits, then no more.
111const DUE_WAKES_MS = [3000, 15000, 60000]
112// How many of a thought's progress notes are kept, and how long each may be.
113const NOTES_KEPT = 5
114const NOTE_MAX = 500
115// How long the engine's notice that a thought's turn ended waits, at most, for that end
116// to be settled.
117const NOTICE_WAIT_MS = 1000
118// How long after a change to the thoughts they are kept in the store, changes meanwhile
119// going with it. A progress note alone keeps nothing: it goes with the next change, or as
120// the session ends.
121const KEEP_MS = 2000
122// What of a session's thoughts the store keeps: those running, and of the rest the most
123// recently ended, to this many in all and this many characters of JSON; each one's task and
124// report cut to this length.
125const THOUGHTS_KEPT = 200
126const THOUGHTS_KEPT_CHARS = 256 * 1024
127const TEXT_KEPT = 4000
128// Of the sessions whose thoughts the store keeps, those kept last, to this many and this
129// many characters of JSON in all; the rest are dropped as a session starts. The store
130// holds 4 MiB at most, the switches of every session included.
131const SESSIONS_KEPT = 20
132const SESSIONS_KEPT_CHARS = 2 * 1024 * 1024
133// What marks the engine's own hand-back of an agent's final report to the session that
134// started it ("Another Claude session sent a message: ... [Subagent hand-back] ...").
135const HANDBACK = '[Subagent hand-back]'
136
137const OFF = {
138  deny: 'Multitask mode is off. The user switches to it with the mode control above the prompt or /multitask mode, or, where Multitask is off in the chat, turns it on with /multitask.',
139}
140const NOT_VOICE = { deny: 'Only the voice starts, steers or lists thoughts; this call came from another agent.' }
141
142let flushTimer: Timer | undefined
143// What keeps the thoughts in the store KEEP_MS after a change, while one is pending.
144let keepTimer: Timer | undefined
145// What draws the Thoughts pane's ages afresh, AGE_TICK_MS after it was last drawn.
146let ageTick: Timer | undefined
147const AGE_TICK_MS = 60_000
148// What draws the band afresh when its dots next change (band.tsx), and when each running
149// thought's turn was last seen to end or it was stopped, by thought id, for its dot to
150// fade out by: kept here, as `settling` is, and set before the change it goes with.
151let bandTimer: Timer | undefined
152const endings = new Map<string, number>()
153// When each running thought's dot last began to blink, by thought id: kept here, so a row
154// that starts no blink writes nothing to state and draws nothing afresh.
155const blinks = new Map<string, number>()
156// The settling of each thought's latest turn end, by thought id, with its name, which the
157// engine's notice or hand-back of that end waits for. Kept here, not in state: what one
158// dispatch reads of state stands still while it runs, so a wait for it would never see it.
159const settling = new Map<string, { name: string; done: Promise<void> }>()
160// Of the messages due to each thought, by thought id, kept here for the same reason: the
161// hand-overs in flight, when each thought's fell due, the refusal the voice was last told
162// of, and the timer that wakes the voice to hand them over.
163const handingOver = new Set<string>()
164const dueAt = new Map<string, number>()
165const toldRefusal = new Map<string, string>()
166const dueWakes = new Map<string, Timer>()
167
168// Whether an engine's notice or hand-back is about this thought: the notice names its
169// agent id, the hand-back its sender (by id or, once named, by name).
170const isAbout = (text: string, id: string, name: string) => text.includes(id) || text.includes(`from="${name}"`)
171
172// How tell delivers a message, given as `how` (or `mode`).
173const TELL_HOWS = ['post', 'queue', 'interrupt']
174
175const TOOL_SPECS = [
176  {
177    name: 'think',
178    description:
179      'Start a thought: a background agent that does the work on one task while you keep talking with the user. Give it a self-contained brief; it cannot see this conversation.',
180    inputSchema: {
181      type: 'object',
182      properties: {
183        name: {
184          type: 'string',
185          description:
186            'A short kebab-case name for the thought, 1-3 words, by its task (fix-login-expiry); one already taken gets -2, -3',
187        },
188        task: { type: 'string', description: 'The full, self-contained brief' },
189      },
190      required: ['name', 'task'],
191    },
192  },
193  {
194    name: 'tell',
195    description:
196      'Give the thought `name` the text `message`, delivered as `how`. post (default): it reads it at its next step. queue: held until it finishes its current turn (can be unqueued until then). interrupt: cut what it is doing and hand it this now.',
197    inputSchema: {
198      type: 'object',
199      properties: {
200        name: { type: 'string', description: 'The thought\'s name' },
201        message: { type: 'string' },
202        how: { type: 'string', enum: TELL_HOWS, description: 'post, queue or interrupt; default post' },
203      },
204      required: ['name', 'message'],
205    },
206  },
207  {
208    name: 'unqueue',
209    description: 'Withdraw messages queued for a thought before it reads them.',
210    inputSchema: {
211      type: 'object',
212      properties: {
213        name: { type: 'string', description: 'The thought\'s name' },
214        index: { type: 'integer', description: '1-based position in its queue; leave out to withdraw all' },
215      },
216      required: ['name'],
217    },
218  },
219  {
220    name: 'stop',
221    description: 'Stop a thought for good.',
222    inputSchema: {
223      type: 'object',
224      properties: { name: { type: 'string', description: 'The thought\'s name' } },
225      required: ['name'],
226    },
227  },
228  {
229    name: 'thoughts',
230    description:
231      'Every thought\'s status, queue, latest progress notes and last report; with a thought\'s name, its recent transcript instead.',
232    inputSchema: { type: 'object', properties: { name: { type: 'string', description: 'The thought\'s name' } } },
233  },
234]
235
236function str(e: unknown, key: string): string {
237  const value = (e as Record<string, unknown>)[key]
238  return typeof value === 'string' ? value.trim() : ''
239}
240
241// The thought a call names: every tool takes its name as `name`, as think gives it; an
242// earlier spelling, `thought`, still works.
243function refOf(e: unknown): string {
244  return str(e, 'name') || str(e, 'thought')
245}
246
247function findThought(list: Thought[], ref: string): Thought | undefined {
248  const wanted = ref.toLowerCase()
249  return list.find(t => t.id === ref) ?? list.find(t => t.name.toLowerCase() === wanted)
250}
251
252function unknownThought(list: Thought[], ref: string) {
253  const names = list.map(t => t.name).join(', ') || 'none'
254  if (ref === '') return { deny: `Give the thought's name as \`name\`. Thoughts: ${names}.` }
255  return { deny: `No thought called "${ref}". Thoughts: ${names}.` }
256}
257
258// What tell answers: what became of the message, or, as an error, why it did not arrive.
259type TellAnswer = { result: string } | { deny: string }
260
261function notDelivered(t: Thought, reason: string): TellAnswer {
262  return { deny: `${t.name} did not get the message: ${reason}` }
263}
264
265// A thought's name: up to three words of the text in lower-case kebab-case, of plain
266// letters and digits alone, as an agent's name is spelled; "" when it has none.
267function slug(text: string): string {
268  const words = text
269    .normalize('NFKD')
270    .replace(/[̀-ͯ]/g, '')
271    .toLowerCase()
272    .split(/[^a-z0-9]+/)
273    .filter(word => word !== '')
274    .slice(0, 3)
275  return words.join('-').slice(0, 40).replace(/-+$/, '')
276}
277
278function uniqueName(list: Thought[], name: string): string {
279  const taken = new Set(list.map(t => t.name))
280  let candidate = name
281  for (let n = 2; taken.has(candidate); n++) candidate = `${name}-${n}`
282  return candidate
283}
284
285// The colour a thought takes as it starts, or resumes when its own is taken, and where the
286// turn through the first colours stands after it. The first colours go in turn from `turn`,
287// past any another running thought holds, and the turn moves on past the one taken, so
288// thoughts started one after another go through them all; with every first colour held,
289// the first of the rest no running thought holds, the turn left as it is; with every one
290// held, the one fewest hold. An ended thought holds none, so a new one may take its colour.
291function freeColor(list: readonly Thought[], turn: number, except?: string): { color: string; turn: number } {
292  const held = list.filter(t => t.status === 'running' && t.id !== except).map(t => t.color)
293  const next = [...FIRST_COLORS.slice(turn), ...FIRST_COLORS.slice(0, turn)].find(color => !held.includes(color))
294  if (next !== undefined) return { color: next, turn: (FIRST_COLORS.indexOf(next) + 1) % FIRST_COLORS.length }
295  const holders = (color: string) => held.filter(one => one === color).length
296  return { color: PALETTE.reduce((best, color) => (holders(color) < holders(best) ? color : best)), turn }
297}
298
299// Picks a colour for a thought in `list` through freeColor, moving the turn on.
300type PickColor = (list: readonly Thought[], except?: string) => string
301
302// A thought set running in `list`: one running already is left as it is, so its rows keep
303// their colour while it runs; one resuming keeps its colour unless a running thought now
304// holds it, then takes a free one.
305function asRunning(list: readonly Thought[], t: Thought, pick: PickColor): Thought {
306  if (t.status === 'running') return t
307  const isTaken = list.some(one => one.id !== t.id && one.status === 'running' && one.color === t.color)
308  return { ...t, status: 'running', color: isTaken ? pick(list, t.id) : t.color }
309}
310
311function statusOf(status: AgentStatus): ThoughtStatus {
312  if (status === 'failed') return 'failed'
313  if (status === 'killed') return 'stopped'
314  if (status === 'completed' || status === 'idle') return 'idle'
315  return 'running'
316}
317
318function textOf(content: readonly { type: string; [field: string]: unknown }[]): string {
319  return content
320    .filter(block => block.type === 'text' && typeof block.text === 'string')
321    .map(block => block.text as string)
322    .join('\n')
323    .trim()
324}
325
326// The time now, for the Thoughts pane's ages; none where the clock cannot be read, which
327// leaves them out and fails nothing else.
328async function timeNow($: EngineInterface): Promise<number | undefined> {
329  try {
330    return await $.clock.now()
331  } catch {
332    return undefined
333  }
334}
335
336// Updates the thoughts through `fn`, which picks any colour it needs with `pick`. Where the
337// turn through the first colours then stands is kept in state, so a reload carries it on.
338async function updateThoughts($: EngineInterface, fn: (list: readonly Thought[], pick: PickColor) => Thought[]) {
339  const start = await read($, colorTurn)
340  let turn = start
341  await update($, thoughts, list => {
342    // Run again from the start should the write miss.
343    turn = start
344    return fn(list, (all, except) => {
345      const picked = freeColor(all, turn, except)
346      turn = picked.turn
347      return picked.color
348    })
349  })
350  if (turn !== start) await update($, colorTurn, () => turn)
351  scheduleKeep($)
352}
353
354async function patchThought($: EngineInterface, id: string, fn: (t: Thought) => Thought) {
355  await update($, thoughts, list => list.map(t => (t.id === id ? fn(t) : t)))
356  scheduleKeep($)
357}
358
359// Patches a thought as patchThought does, for a change that may pick it a colour.
360async function patchPicking($: EngineInterface, id: string, fn: (t: Thought, list: readonly Thought[], pick: PickColor) => Thought) {
361  await updateThoughts($, (list, pick) => list.map(t => (t.id === id ? fn(t, list, pick) : t)))
362}
363
364// Opens a thought in the Thoughts pane to show everything, or closes it: a finished
365// thought's one line becomes its whole card, a running card shows its whole task.
366async function toggleExpanded($: EngineInterface, id: string) {
367  await update($, expanded, ids => (ids.includes(id) ? ids.filter(one => one !== id) : [...ids, id]))
368}
369
370// Opens a thought's last report in the Thoughts pane to read whole, or folds it to its first line.
371async function toggleReport($: EngineInterface, id: string) {
372  await update($, openReports, ids => (ids.includes(id) ? ids.filter(one => one !== id) : [...ids, id]))
373}
374
375// Opens the field in a thought's card in the Thoughts pane to tell it something, or closes it.
376async function toggleTell($: EngineInterface, id: string) {
377  await update($, tellingTo, was => (was === id ? '' : id))
378}
379
380// Multitask is on in a chat as the person last chose there with /multitask, else as the
381// default (`/multitask default`), off until they choose. Off, the mod leaves the chat be:
382// nothing of it shown, not above the prompt nor in a pane, Focus mode, no tool of the
383// voice's offered; a thought it started runs on unseen, the voice hearing of it as news
384// once the mod is on again. On, the chat is in Multitask mode (isOn),
385// where it is the voice, or in Focus, as off but with the band's mode control; that control
386// or `/multitask mode` switches between them. Turned on with /multitask, or on by default in
387// a new chat, it starts in Multitask mode; an open chat the default turns on stays in
388// Focus. Multitask mode is only for a chat the mod is on in: off, it is left (settleMode).
389async function isEnabled($: EngineInterface): Promise<boolean> {
390  return (await read($, choice)) ?? (await read($, isEnabledByDefault))
391}
392
393// Leaves Multitask mode where the mod is off in the chat: a default gone off, or state a
394// reload of this code kept from before.
395async function settleMode($: EngineInterface) {
396  if ((await read($, isOn)) && !(await isEnabled($))) await setMode($, false)
397}
398
399// The voice's tools are the model's from Multitask mode first coming on: a session that
400// never switches to it has no tool of this mod's. Registered again, each is replaced.
401async function offerVoiceTools($: EngineInterface) {
402  for (const spec of TOOL_SPECS) {
403    try {
404      await $.tool.register(spec)
405    } catch {
406      // the switch stands; the next time it comes on tries again
407    }
408  }
409}
410
411// Switches Multitask mode on, or off to Focus, and keeps the switch; the mode the chat is
412// in already leaves it be.
413async function setMode($: EngineInterface, now: boolean) {
414  if (now === (await read($, isOn))) return
415  await update($, isOn, () => now)
416  redescribe($)
417  if (now) {
418    await offerVoiceTools($)
419    // What fell due for a thought while off goes to it now that it can be resumed again.
420    for (const t of await read($, thoughts)) if (isDue(t)) scheduleDueWake($, t.id, 0)
421  }
422  await keepSwitch($)
423}
424
425// `/multitask on|off`: turns the mod on in this chat, in Multitask mode, or off, leaving
426// Multitask mode; the chat's own choice from then on, whatever the default. On already,
427// it stays in the mode it is in. What to say.
428async function setEnabled($: EngineInterface, now: boolean): Promise<string> {
429  const wasEnabled = await isEnabled($)
430  await update($, choice, () => now)
431  if (!now || !wasEnabled) await setMode($, now)
432  await keepSwitch($)
433  if (wasEnabled !== now) redescribe($)
434  await closeIfOff($)
435  return now ? ON_TEXT : OFF_TEXT
436}
437
438// Off in the chat, the mod shows nothing: its Thoughts pane closes (a hook's refusal
439// leaves it open).
440async function closeIfOff($: EngineInterface) {
441  if (!(await isEnabled($))) await $.ui.close({ id: PANE }).catch(() => undefined)
442}
443
444// Switches to the mode picked with the band's mode control; the mode the chat is in already
445// (a stale control), anything else, or a pick while the mod is off, leaves it be.
446async function pickMode($: EngineInterface, value: string) {
447  const wantsOn = value === MULTITASK_MODE ? true : value === FOCUS_MODE ? false : undefined
448  if (wantsOn !== undefined && (await isEnabled($))) await setMode($, wantsOn)
449}
450
451// `/multitask mode [multitask|focus]`: switches between Multitask and Focus, as the band's
452// mode control does (the mobile app draws none); alone, it asks which. Says which the chat is
453// now in; already in it, or not answered, changes nothing. Off, it says how to turn it on.
454async function runMode($: EngineInterface, words: readonly string[]): Promise<string> {
455  const [, picked, ...rest] = words
456  const wanted = picked === MULTITASK_MODE ? true : picked === FOCUS_MODE ? false : undefined
457  if (rest.length > 0 || (picked !== undefined && wanted === undefined)) return usageOf(NAMES)
458  if (!(await isEnabled($))) return `${OFF_TEXT} It comes on in Multitask mode; \`/multitask mode\` then switches to Focus.`
459  const isMultitask = await read($, isOn)
460  let now = wanted
461  if (now === undefined) {
462    const session = sessionOf($)
463    if (!(await session.canAsk())) return switchStatus(NAMES, await stateOf($))
464    const answer = await askAmong(session.ask, 'Which mode for this chat?', 'Mode', ['Multitask', 'Focus'], isMultitask ? 0 : 1)
465    if (answer === undefined) return `No change. ${switchStatus(NAMES, await stateOf($))}`
466    now = answer === 0
467  }
468  if (now === isMultitask) return `This chat is already in ${now ? 'Multitask' : 'Focus'} mode.`
469  await setMode($, now)
470  return now ? MULTITASK_TEXT : FOCUS_TEXT
471}
472
473// What /multitask says.
474const ON_TEXT =
475  'Multitask is on in this chat, in Multitask mode: this chat is now the voice and hands all work to thoughts. Switch to Focus above the prompt, or use `/multitask mode`, to work with the agent as usual.'
476const OFF_TEXT = 'Multitask is off in this chat; `/multitask on` turns it on.'
477const MULTITASK_TEXT = 'Multitask mode: this chat is now the voice and hands all work to thoughts.'
478const FOCUS_TEXT = 'Focus mode: this chat does its work itself again.'
479
480// Whether the mod is on in new chats, and in those never switched with /multitask: the
481// person's choice for every chat, kept under its own key; off until they choose.
482const DEFAULT_KEY = 'isEnabledByDefault'
483
484async function takeUpDefault($: EngineInterface) {
485  const chosen = await $.store.get(DEFAULT_KEY).catch(() => undefined)
486  if (typeof chosen === 'boolean') await update($, isEnabledByDefault, () => chosen)
487}
488
489// `/multitask default on|off`: sets the default, which this chat follows too unless the
490// person switched it with /multitask: turned on so, it stays in Focus, and turned off, it
491// leaves Multitask mode. Says what the default now is.
492async function setDefault($: EngineInterface, now: boolean): Promise<string> {
493  await update($, isEnabledByDefault, () => now)
494  await $.store.set(DEFAULT_KEY, now).catch(() => undefined)
495  await settleMode($)
496  await closeIfOff($)
497  redescribe($)
498  const word = now ? 'on' : 'off'
499  const said = `Multitask is now ${word} by default, in new chats and in chats where you have not used \`/multitask\`.`
500  const chosen = await read($, choice)
501  if (chosen === null || chosen === now) return said
502  return `${said} This chat keeps it ${chosen ? 'on' : 'off'}; \`/multitask ${chosen ? 'off' : 'on'}\` turns it ${chosen ? 'off' : 'on'} here.`
503}
504
505// `/multitask` and its arguments, as every mod's switch takes them (command.ts), and
506// `mode` beside them.
507const NAMES: Names = { command: 'multitask', noun: 'Multitask', be: 'is', extraUsage: 'mode [multitask|focus]' }
508
509async function stateOf($: EngineInterface): Promise<State> {
510  return {
511    isOnHere: await isEnabled($),
512    choiceHere: await read($, choice),
513    isOnByDefault: await read($, isEnabledByDefault),
514    detail: (await read($, isOn)) ? 'Multitask mode' : 'Focus mode',
515  }
516}
517
518function sessionOf($: EngineInterface): Session {
519  return {
520    state: () => stateOf($),
521    canAsk: async () => (await $.session.surfaces().catch(() => [])).length > 0,
522    ask: (question, options) => $.ui.ask(question, options),
523    setHere: now => setEnabled($, now),
524    setDefault: now => setDefault($, now),
525  }
526}
527
528// Has the menu ask for /multitask's line again, as what it says has changed.
529function redescribe($: EngineInterface) {
530  try {
531    $.ui.invalidate('command.describe')
532  } catch {
533    // the menu keeps the line it had
534  }
535}
536
537// Where a session's switch is kept between runs of the app: whether it is in Multitask
538// mode, the person's choice of the mod there (null: never switched, so it follows the
539// default), when it was kept, and, once it has been in Multitask mode or chosen, the marks
540// of its newest messages.
541const switchKey = (sessionId: string) => `session:${sessionId}`
542type KeptSwitch = { isOn: boolean; choice: boolean | null; at: number; marks: string[] }
543const MARKS_KEPT = 200
544
545// Keeps the switch for the session's next run. A session never switched nor in Multitask
546// mode keeps no marks: one rewound or forked from it follows the default as it would
547// anyway. Best effort: a store or transcript that cannot be read or written keeps what it
548// kept.
549async function keepSwitch($: EngineInterface) {
550  try {
551    const key = switchKey(await $.session.id())
552    const was = (await $.store.get(key)) as Partial<KeptSwitch> | undefined
553    const now = await read($, isOn)
554    const chosen = await read($, choice)
555    const isMarked = now || chosen !== null || (was?.marks?.length ?? 0) > 0
556    const marks = isMarked ? marksOf(await $.session.messages()).slice(-MARKS_KEPT) : []
557    await $.store.set(key, { isOn: now, choice: chosen, at: await $.clock.now(), marks } satisfies KeptSwitch)
558  } catch {
559    // kept as it was
560  }
561}
562
563// The session whose kept switch and thoughts a session takes up: its own, once it has kept
564// its switch; for one rewound or forked, which starts under a new id with copies of the
565// messages it kept, the session it came from: the kept one that knows the most of its
566// messages, else, of those near that, the one kept last (the one it was just in). None
567// when no session is known.
568async function keptSession($: EngineInterface): Promise<string | undefined> {
569  const own = await $.session.id()
570  if ((await $.store.get(switchKey(own))) !== undefined) return own
571  const mine = new Set(marksOf(await $.session.messages()))
572  if (mine.size === 0) return undefined
573  const scored: { id: string; at: number; score: number }[] = []
574  for (const key of await $.store.keys()) {
575    if (!key.startsWith('session:')) continue
576    const kept = ((await $.store.get(key)) ?? {}) as Partial<KeptSwitch>
577    const score = new Set((kept.marks ?? []).filter(mark => mine.has(mark))).size
578    if (score > 0) scored.push({ id: key.slice('session:'.length), at: kept.at ?? 0, score })
579  }
580  const best = Math.max(0, ...scored.map(s => s.score))
581  if (best < 3) return undefined
582  return scored.filter(s => s.score * 2 > best).sort((a, b) => b.at - a.at)[0]?.id
583}
584
585// The switch the session `from` kept: the person's choice of the mod there, and whether it
586// was in Multitask mode, which a chat they turned it off in is not. One kept before
587// choices were (Multitask mode was then the only switch) chose only if it was in it.
588async function keptSwitch($: EngineInterface, from: string): Promise<{ isOn: boolean; choice: boolean | null }> {
589  const kept = ((await $.store.get(switchKey(from))) ?? {}) as Partial<KeptSwitch>
590  const chosen = kept.choice === true || kept.choice === false || kept.choice === null ? kept.choice : kept.isOn === true ? true : null
591  return { isOn: kept.isOn === true && chosen !== false, choice: chosen }
592}
593
594// Where a session's thoughts are kept between runs of the app (KeptThoughts).
595const thoughtsKey = (sessionId: string) => `thoughts:${sessionId}`
596
597// The thoughts as the store keeps them: each one's task and report cut to TEXT_KEPT, and,
598// past THOUGHTS_KEPT of them or THOUGHTS_KEPT_CHARS of JSON, those that ended longest ago
599// dropped; running ones are never dropped.
600function keptList(list: readonly Thought[]): Thought[] {
601  const all = list.map((t, i) => {
602    const kept = { ...t, task: t.task.slice(0, TEXT_KEPT), lastText: t.lastText.slice(0, TEXT_KEPT) }
603    return { t: kept, i, chars: JSON.stringify(kept).length + 1 }
604  })
605  let count = all.length
606  let chars = all.reduce((n, one) => n + one.chars, 0)
607  const oldestFirst = all
608    .filter(one => one.t.status !== 'running')
609    .sort((a, b) => (a.t.endedAt ?? 0) - (b.t.endedAt ?? 0) || a.i - b.i)
610  const dropped = new Set<number>()
611  for (const one of oldestFirst) {
612    if (count <= THOUGHTS_KEPT && chars <= THOUGHTS_KEPT_CHARS) break
613    dropped.add(one.i)
614    count--
615    chars -= one.chars
616  }
617  return all.filter(one => !dropped.has(one.i)).map(one => one.t)
618}
619
620// Keeps the thoughts in the store under the session's id (or `sessionId`), for its next
621// run. A session with none keeps nothing. Best effort: a store that cannot be written
622// (it holds 4 MiB at most) keeps what it kept.
623async function keepThoughts($: EngineInterface, sessionId?: string) {
624  keepTimer?.cancel()
625  keepTimer = undefined
626  try {
627    const list = await read($, thoughts)
628    if (list.length === 0) return
629    const kept: KeptThoughts = { at: (await timeNow($)) ?? 0, thoughts: keptList(list) }
630    await $.store.set(thoughtsKey(sessionId ?? (await $.session.id())), kept)
631  } catch {
632    // kept as it was
633  }
634}
635
636// Keeps the thoughts KEEP_MS from now, unless that is pending already: changes in a burst,
637// or one after another without pause, are kept together, at most each KEEP_MS.
638function scheduleKeep($: EngineInterface) {
639  if (keepTimer !== undefined) return
640  keepTimer = $.clock.after(KEEP_MS, () => {
641    keepTimer = undefined
642    void keepThoughts($)
643  })
644}
645
646// Takes up the thoughts the session `from` kept, unless the session has thoughts already
647// (this code was reloaded, which state outlives). A thought that was running when they were
648// kept is running still only if its agent is; else its turn ended with the run that held it,
649// and what waited for that end falls due, as when a turn ends (settleThought), though the
650// voice is not told it ended. The voice has heard of each as it is taken up, so what is new
651// from the thoughts tells it only what changes after.
652async function takeUpThoughts($: EngineInterface, from: string) {
653  if ((await read($, thoughts)).length > 0) return
654  const kept = (await $.store.get(thoughtsKey(from))) as Partial<KeptThoughts> | undefined
655  const list = Array.isArray(kept?.thoughts) ? kept.thoughts : []
656  if (list.length === 0) return
657  const agents = await $.agent.list()
658  const endedAt = kept?.at ?? (await timeNow($))
659  const taken = list.map((t): Thought => {
660    if (t.status !== 'running') return t
661    const status = statusOf(agents.find(a => a.id === t.id)?.status ?? 'completed')
662    if (status === 'running') return t
663    const queued = status === 'stopped' ? [] : withInterruption(t)
664    return { ...t, status, turnId: null, queued, interruptWith: null, isHandOverDue: queued.length > 0, endedAt }
665  })
666  await update($, thoughts, now => (now.length > 0 ? now : taken))
667  await update($, heard, was => ({ ...Object.fromEntries(taken.map(t => [t.id, heardOf(t)])), ...was }))
668  if (await read($, isOn)) for (const t of taken) if (isDue(t)) scheduleDueWake($, t.id, 0)
669  // Under this session's id too, for its next run, should it have come from another.
670  if (from !== (await $.session.id())) await keepThoughts($)
671}
672
673// Drops from the store the thoughts of sessions kept longest ago, past SESSIONS_KEPT of
674// them or SESSIONS_KEPT_CHARS of JSON, this session's own aside. Best effort.
675async function dropOldThoughts($: EngineInterface) {
676  try {
677    const own = thoughtsKey(await $.session.id())
678    const others: { key: string; at: number; chars: number }[] = []
679    for (const key of await $.store.keys()) {
680      if (!key.startsWith('thoughts:') || key === own) continue
681      const kept = await $.store.get(key)
682      const at = (kept as Partial<KeptThoughts> | undefined)?.at
683      others.push({ key, at: typeof at === 'number' ? at : 0, chars: JSON.stringify(kept ?? null).length })
684    }
685    others.sort((a, b) => b.at - a.at)
686    let chars = 0
687    for (const [i, one] of others.entries()) {
688      chars += one.chars
689      if (i >= SESSIONS_KEPT || chars > SESSIONS_KEPT_CHARS) await $.store.delete(one.key)
690    }
691  } catch {
692    // left as they were
693  }
694}
695
696function scheduleFlush($: EngineInterface) {
697  flushTimer?.cancel()
698  flushTimer = $.clock.after(FLUSH_MS, () => void flushInbox($))
699}
700
701// Hands what the thoughts said to the voice, once it is idle: as a row the person never
702// sees, then the wake-up that draws as nothing; failing that, as one plugin message.
703async function flushInbox($: EngineInterface) {
704  if (!(await read($, isOn)) || (await read($, isMainBusy))) return
705  const text = await takeRelay($)
706  if (text === undefined) return
707  if (await appendHidden($, text)) void $.prompt.submit({ text: WAKE, asUser: true })
708  else void $.prompt.submit({ text })
709}
710
711// Puts text in the conversation as a user row the person does not see; whether it went in.
712async function appendHidden($: EngineInterface, text: string): Promise<boolean> {
713  try {
714    const appended = await $.session.append({ message: { type: 'user', content: [{ type: 'text', text }] } })
715    return appended.deny === undefined
716  } catch {
717    return false
718  }
719}
720
721async function relay($: EngineInterface, fn: (list: Update[]) => Update[]) {
722  if (!(await read($, isOn))) return
723  await update($, inbox, fn)
724  scheduleFlush($)
725}
726
727// What a thought writes as it works is a progress note: kept to follow it by, and
728// relayed to the voice while RELAY_NOTES is on. Its tool calls never are. Whether it was
729// one.
730async function noteThoughtSaid($: EngineInterface, id: string, text: string): Promise<boolean> {
731  const t = (await read($, thoughts)).find(one => one.id === id)
732  // The turn's report, should its row land after the turn ended, has been relayed already.
733  if (t === undefined || text === '' || text === t.lastText) return false
734  const now = await timeNow($)
735  // Not through patchThought: a note alone is not kept in the store straight away (KEEP_MS).
736  await update($, thoughts, list =>
737    list.map(one =>
738      one.id !== id
739        ? one
740        : { ...one, notes: [...(one.notes ?? []), text.slice(0, NOTE_MAX)].slice(-NOTES_KEPT), notedSinceReport: true, notedAt: now },
741    ),
742  )
743  if (RELAY_NOTES) await relay($, list => [...list, { thought: t.name, text }])
744  return true
745}
746
747// Any other new row in a running thought's conversation (a tool call or its result, a
748// message to it) blinks its dot in the band, unless a blink began under BLINK_MS ago: only
749// a blink's start draws the band afresh, so a busy thought redraws it once a BLINK_MS at most.
750async function blinkThought($: EngineInterface, id: string) {
751  const now = await timeNow($)
752  const last = blinks.get(id)
753  if (now === undefined || (last !== undefined && now - last < BLINK_MS)) return
754  if ((await read($, thoughts)).find(one => one.id === id)?.status !== 'running') return
755  for (const [one, at] of blinks) if (now - at >= BLINK_MS) blinks.delete(one)
756  blinks.set(id, now)
757  await update($, bandTick, n => n + 1)
758}
759
760// The end of a thought's turn reaches the voice once, as a done line. Its report replaces
761// the notes still waiting that it repeats; if it went out already as the latest note,
762// the line is a bare "done". With notes not relayed, nothing went out before it.
763async function relayDone($: EngineInterface, t: Thought, report: string, isFailed: boolean, pending: number) {
764  const notes = t.notes ?? []
765  const wasSent = RELAY_NOTES && report !== '' && notes.at(-1) === report.slice(0, NOTE_MAX)
766  await relay($, list => {
767    const kept = [...list]
768    let isWaiting = false
769    for (let i = kept.length - 1; i >= 0; i--) {
770      const u = kept[i] as Update
771      if (u.thought !== t.name) continue
772      if (u.isDone === true || u.isFromPerson === true || !report.includes(u.text)) break
773      kept.splice(i, 1)
774      isWaiting = true
775    }
776    const said = isWaiting || !wasSent ? report : ''
777    const text = isFailed ? [said, '(ended on an error)'].filter(part => part !== '').join(' ') : said
778    return [...kept, { thought: t.name, text, isDone: true, ...(pending > 0 && { pending }) }]
779  })
780}
781
782// Sends a thought a message: to its agent's id, failing that to its name. The answer says
783// whether it got there and why not; a thought that has it runs again, one that has not
784// keeps the status it had.
785async function deliver($: EngineInterface, t: Thought, text: string): Promise<SessionSendResult> {
786  let was: ThoughtStatus = t.status
787  let wasColor = t.color
788  await patchPicking($, t.id, (one, list, pick) => {
789    was = one.status
790    wasColor = one.color
791    return asRunning(list, one, pick)
792  })
793  const send = async (to: SessionSendAddress): Promise<SessionSendResult> => {
794    try {
795      return await $.session.send({ to, text })
796    } catch (error) {
797      return { isDelivered: false, reason: error instanceof Error ? error.message : String(error) }
798    }
799  }
800  const byId = await send({ agentId: t.id })
801  const sent = byId.isDelivered || !(await send(t.name)).isDelivered ? byId : { isDelivered: true as const }
802  // Not delivered, it goes back to its colour; the turn through the first colours stays
803  // moved on, which does no harm, as a pick passes over the colours held.
804  if (!sent.isDelivered) {
805    await patchThought($, t.id, one => (one.status === 'running' ? { ...one, status: was, color: wasColor } : one))
806  }
807  return sent
808}
809
810// Posts a thought a message, as tell's post does: one running reads it at its next step;
811// one whose turn has ended gets it once its run has ended (it may still be winding down),
812// after the messages still pending for it, and resumes. What the send answered, and how
813// many pending messages went before it.
814async function post(
815  $: EngineInterface,
816  t: Thought,
817  text: string,
818  isRunning: boolean,
819): Promise<{ sent: SessionSendResult; pending: number }> {
820  if (!isRunning) await runEnded($, t.id)
821  const pending = !isRunning && isDue(t) ? t.queued.length : 0
822  const sent = (pending > 0 ? await handOver($, t.id, text) : undefined) ?? (await deliver($, t, text))
823  return { sent, pending }
824}
825
826// The person's own message to a thought, typed in its card in the Thoughts pane: posted as
827// tell posts the voice's, then put before the voice with the thoughts' next updates, so it
828// knows what the thought was asked. Sent from the pane's ui.input hook (below), as auto
829// mode allows only a send made from an event the engine raised to this mod (handOverDue).
830// A message that did not arrive is told in a toast, the field left open.
831async function tellFromPane($: EngineInterface, id: string, text: string) {
832  const message = text.trim()
833  const t = (await read($, thoughts)).find(one => one.id === id)
834  if (message === '' || t === undefined || t.status === 'stopped') return
835  if (!(await read($, isOn))) {
836    $.ui.toast('Switch to Multitask mode to tell a thought something.')
837    return
838  }
839  const { sent } = await post($, t, fromPerson(message), t.status === 'running')
840  if (!sent.isDelivered) {
841    $.ui.toast(`${t.name} did not get your message: ${sent.reason}`)
842    return
843  }
844  await update($, tellingTo, was => (was === id ? '' : was))
845  await update($, inbox, list => [...list, { thought: t.name, text: message, isFromPerson: true }])
846}
847
848// Queues a message for the end of a thought's turn, if it has a turn running that will
849// end: its place in the queue, or 0 when it has none and nothing would hand it over.
850async function queueFor($: EngineInterface, id: string, text: string): Promise<number> {
851  let at = 0
852  await patchThought($, id, one => {
853    if (one.status !== 'running') return one
854    at = one.queued.length + 1
855    return { ...one, queued: [...one.queued, text] }
856  })
857  return at
858}
859
860// The engine's status of a thought's agent once its run no longer counts as running, or
861// after SETTLE_POLLS looks. A message sent while a finished run is still winding down
862// waits for a tool round that never comes, until something else wakes the session; sent
863// once the run has ended, it resumes the thought straight away.
864async function runEnded($: EngineInterface, id: string): Promise<AgentStatus | undefined> {
865  for (let look = 1; ; look++) {
866    const status = (await $.agent.list()).find(a => a.id === id)?.status
867    if (status !== 'running' || look >= SETTLE_POLLS) return status
868    await new Promise<void>(resolve => $.clock.after(SETTLE_POLL_MS, resolve))
869  }
870}
871
872// Whether a thought has messages due: its queue no longer waits for a turn to end.
873function isDue(t: Thought): boolean {
874  return t.isHandOverDue === true && t.queued.length > 0 && t.status !== 'stopped'
875}
876
877// What a thought is handed for an interruption that waited for its turn to be cut.
878const interruption = (text: string) => `Interruption from the voice: ${text}`
879
880// Its queue, after the interruption waiting for its turn to be cut, if any.
881function withInterruption(t: Thought): string[] {
882  return t.interruptWith === null ? t.queued : [interruption(t.interruptWith), ...t.queued]
883}
884
885// What waits for a thought fell due (isHandOverDue set with it): the next hook of this
886// mod's the engine raises hands it over (handOverDue), and should none have by then, the
887// voice is woken, for its turn to.
888async function fellDue($: EngineInterface, id: string) {
889  dueAt.set(id, await $.clock.now())
890  scheduleDueWake($, id, 0)
891}
892
893// Forgets a thought's due messages: handed over, withdrawn, or the thought stopped.
894function forgetDue(id: string) {
895  dueWakes.get(id)?.cancel()
896  dueWakes.delete(id)
897  dueAt.delete(id)
898  toldRefusal.delete(id)
899}
900
901function scheduleDueWake($: EngineInterface, id: string, step: number) {
902  dueWakes.get(id)?.cancel()
903  dueWakes.delete(id)
904  const ms = DUE_WAKES_MS[step]
905  if (ms !== undefined) dueWakes.set(id, $.clock.after(ms, () => void wakeForDue($, id, step)))
906}
907
908// Messages are still due to a thought, which no hook of this mod's has handed over since
909// they fell due: the voice is told they are still pending, which wakes it, and its turn
910// hands them over. A note already waiting for the voice about the thought wakes it as well.
911async function wakeForDue($: EngineInterface, id: string, step: number) {
912  dueWakes.delete(id)
913  const t = (await read($, thoughts)).find(one => one.id === id)
914  const isInFlight = handingOver.has(id)
915  if (t === undefined || (!isInFlight && !isDue(t))) return
916  scheduleDueWake($, id, step + 1)
917  if (isInFlight) return
918  const note: Update = { thought: t.name, text: `(${pendingNote(t.queued.length)})`, isPending: true }
919  await relay($, list => (list.some(u => u.thought === t.name) ? list : [...list, note]))
920}
921
922// Hands each thought whose turn has ended the messages due to it. Called only from hooks
923// of this mod's that the engine raises (the voice's turns, the engine's notice that a
924// thought finished, tell), as only there does the engine run this mod's allowance of its
925// own SendMessage (tool.check, below). A $ call made after the hook that made it has
926// returned, or from a timer, runs beneath this mod's own frame, where the engine leaves out
927// every hook of this mod, the allowance too: auto mode then refuses the send.
928async function handOverDue($: EngineInterface) {
929  if (!(await read($, isOn))) return
930  const due = (await read($, thoughts)).filter(t => isDue(t) && !handingOver.has(t.id))
931  if (due.length === 0) return
932  const agents = await $.agent.list()
933  const now = await $.clock.now()
934  for (const t of due) {
935    // Still ending the run its turn ended, a message would wait unread (runEnded): it goes
936    // at the next chance. One running a new turn reads it at its next step.
937    const run = agents.find(a => a.id === t.id)?.status
938    const isEnding = run === 'running' && t.turnId === null && now - (dueAt.get(t.id) ?? 0) < SETTLE_MS
939    if (!isEnding) await handOver($, t.id)
940  }
941}
942
943// Hands a thought the messages due to it, and `also` after them (tell's message to an idle
944// one), from a hook of this mod's the engine raised (handOverDue says why). Delivered, they
945// are off its queue and the voice's relay says so; refused, they stay at its front, due
946// still, and the voice is told why, once a reason. Undefined when there was nothing to send.
947async function handOver($: EngineInterface, id: string, also?: string): Promise<SessionSendResult | undefined> {
948  const isFree = !handingOver.has(id)
949  let waited: string[] = []
950  if (isFree) {
951    handingOver.add(id)
952    await patchThought($, id, one => {
953      if (!isDue(one)) return one
954      waited = one.queued
955      return { ...one, queued: [] }
956    })
957  }
958  try {
959    const t = (await read($, thoughts)).find(one => one.id === id)
960    const parts = also === undefined ? waited : [...waited, also]
961    if (t === undefined || parts.length === 0) return undefined
962    const sent = await deliver($, t, parts.join('\n\n'))
963    if (waited.length === 0) return sent
964    if (sent.isDelivered) {
965      await patchThought($, id, one => ({ ...one, isHandOverDue: false }))
966      forgetDue(id)
967      // The voice's relay, if it has not gone out yet, says they reached it.
968      await update($, inbox, list =>
969        list
970          .filter(u => u.thought !== t.name || u.isPending !== true)
971          .map(u => (u.thought === t.name && u.isDone === true && (u.pending ?? 0) > 0 ? { ...u, isHandedOver: true } : u)),
972      )
973      return sent
974    }
975    await patchThought($, id, one =>
976      one.status === 'stopped' ? one : { ...one, queued: [...waited, ...one.queued], isHandOverDue: true },
977    )
978    if (toldRefusal.get(id) !== sent.reason) {
979      toldRefusal.set(id, sent.reason)
980      const text = `(${pendingNote(waited.length)}. The last try failed: ${sent.reason})`
981      await relay($, list => [...list, { thought: t.name, text, isPending: true }])
982    }
983    return sent
984  } finally {
985    if (isFree) handingOver.delete(id)
986  }
987}
988
989// A running thought's turn ended, or it was stopped, at `now`: its dot in the band fades
990// out from then. Ends from FADE_MS ago or more are forgotten.
991function noteEnding(id: string, now: number | undefined) {
992  if (now === undefined) return
993  for (const [one, at] of endings) if (now - at >= FADE_MS) endings.delete(one)
994  endings.set(id, now)
995}
996
997async function stopThought($: EngineInterface, id: string) {
998  const now = await timeNow($)
999  if ((await read($, thoughts)).find(t => t.id === id)?.status === 'running') noteEnding(id, now)
1000  await patchThought($, id, t => ({ ...t, status: 'stopped', queued: [], interruptWith: null, isHandOverDue: false, endedAt: now }))
1001  forgetDue(id)
1002  try {
1003    await $.tool.call({ tool: 'TaskStop', task_id: id })
1004  } catch {
1005    // it had already ended
1006  }
1007}
1008
1009async function unqueue($: EngineInterface, id: string, index: number | undefined) {
1010  let isEmpty = false
1011  await patchThought($, id, t => {
1012    const queued = index === undefined ? [] : t.queued.filter((_, i) => i !== index)
1013    isEmpty = queued.length === 0
1014    return { ...t, queued, isHandOverDue: !isEmpty && t.isHandOverDue === true }
1015  })
1016  if (isEmpty) forgetDue(id)
1017}
1018
1019// Cuts a thought's running turn so the message goes in at once: the cut turn's end (or
1020// the grace timer) makes it due, and it goes at the next chance. With no turn the engine
1021// will cut, the message waits in its queue for the run's end, or goes now when the run has
1022// ended. The thought is never stopped: a stopped agent takes no more messages. Answers as
1023// tell does.
1024async function interrupt($: EngineInterface, t: Thought, text: string): Promise<TellAnswer> {
1025  let pending = text
1026  if (t.turnId !== null) {
1027    await patchThought($, t.id, one => ({
1028      ...one,
1029      interruptWith: one.interruptWith === null ? text : `${one.interruptWith}\n\n${text}`,
1030    }))
1031    try {
1032      await $.turn.abort({ turnId: t.turnId })
1033      // Normally its turn.complete makes the message due; this covers a turn that never reports.
1034      $.clock.after(INTERRUPT_GRACE_MS, () => void interruptionFallsDue($, t.id))
1035      return { result: `Interrupting ${t.name}; it gets the message as soon as its current turn is cut.` }
1036    } catch {
1037      // That turn had ended. Unless its end made the message due, it goes another way.
1038      let taken = null as string | null
1039      await patchThought($, t.id, one => {
1040        taken = one.interruptWith
1041        return { ...one, interruptWith: null }
1042      })
1043      if (taken === null) {
1044        // Due now, it goes from here, this being the voice's own call.
1045        await runEnded($, t.id)
1046        const sent = await handOver($, t.id)
1047        if (sent === undefined || sent.isDelivered) return { result: `${t.name}'s turn had just ended; it has the message now.` }
1048        return { result: `${t.name}'s turn had just ended; the message is pending and goes to it at the next chance (${sent.reason}).` }
1049      }
1050      pending = taken
1051    }
1052  }
1053  if ((await $.agent.list()).find(a => a.id === t.id)?.status === 'running') {
1054    const at = await queueFor($, t.id, pending)
1055    if (at > 0) return { result: `Could not cut ${t.name}'s turn; the message is queued as #${at}, for when that turn ends.` }
1056  }
1057  await runEnded($, t.id)
1058  const sent = await deliver($, t, pending)
1059  if (!sent.isDelivered) return notDelivered(t, sent.reason)
1060  return { result: `${t.name} had no turn running; it has the message now and resumes.` }
1061}
1062
1063// Makes the interruption still waiting, if any, due, before the thought's queue: the grace
1064// timer's, for a cut turn that never reports. Whichever comes second, the cut turn's end
1065// or the grace timer, finds none and leaves the thought be.
1066async function interruptionFallsDue($: EngineInterface, id: string) {
1067  let isMoved = false
1068  await patchThought($, id, t => {
1069    if (t.interruptWith === null || t.status === 'stopped') return t
1070    isMoved = true
1071    return { ...t, queued: withInterruption(t), interruptWith: null, isHandOverDue: true }
1072  })
1073  if (isMoved) await fellDue($, id)
1074}
1075
1076// The notes a turn's report leaves: its own text arrived as notes too, last.
1077function notesBefore(notes: string[], report: string): string[] {
1078  const kept = [...notes]
1079  while (kept.length > 0 && report.includes(kept.at(-1) as string)) kept.pop()
1080  return kept
1081}
1082
1083// A thought's turn ended: it goes idle (or failed), and what waited for that end, an
1084// interruption and its queue, falls due; the voice is told, with the text it ended on as
1085// its report (a result, question or problem) and how many messages are still pending.
1086// Nothing is handed over here: this runs on after the engine's hook has returned (see
1087// handOverDue), and the run that turn ended may not have ended yet.
1088async function settleThought($: EngineInterface, id: string, reason: TurnCompleteReason, answer: string) {
1089  const t = (await read($, thoughts)).find(one => one.id === id)
1090  if (t === undefined || t.status === 'stopped') return
1091  // A turn that was cut ended on whatever it was doing, not on a report; it was cut by
1092  // the voice's interruption or a stop, so the voice is not told it ended.
1093  const isCut = reason === 'aborted'
1094  const report = isCut ? '' : answer.trim()
1095  if (report !== '') {
1096    await patchThought($, id, one => ({
1097      ...one,
1098      lastText: report,
1099      notes: notesBefore(one.notes ?? [], report),
1100      notedSinceReport: false,
1101    }))
1102  }
1103  // What waits for it is read as it stands now, in the same step that settles it, not as
1104  // it stood when the turn ended: the voice may have queued or interrupted since.
1105  const isFailed = reason === 'error' || reason === 'refusal'
1106  const status: ThoughtStatus = isFailed ? 'failed' : 'idle'
1107  let pending = 0
1108  const now = await timeNow($)
1109  // A cut turn's thought goes on with the message it was cut for: its dot does not fade.
1110  if (!isCut && t.status === 'running') noteEnding(id, now)
1111  await patchThought($, id, one => {
1112    if (one.status === 'stopped') return one
1113    const queued = withInterruption(one)
1114    pending = queued.length
1115    return { ...one, status, turnId: null, queued, interruptWith: null, isHandOverDue: pending > 0, endedAt: now }
1116  })
1117  if (!isCut) await relayDone($, t, report, isFailed, pending)
1118  if (pending > 0) await fellDue($, id)
1119}
1120
1121// What the voice is told beside the person's message: its whole part once Multitask
1122// comes on (and again after a compaction), a reminder while it stays on, and once
1123// that it has gone off.
1124async function voiceNote($: EngineInterface): Promise<string | undefined> {
1125  const now = await read($, isOn)
1126  const told = await read($, toldVoice)
1127  if (now !== told) await update($, toldVoice, () => now)
1128  if (now) return told ? VOICE_REMINDER : VOICE
1129  return told ? VOICE_OFF : undefined
1130}
1131
1132// What is new from the thoughts the voice has not heard of, but those a relay names (it
1133// tells of them itself); none when nothing is. Once told, the voice has heard of them all.
1134async function takeNews($: EngineInterface, relayed: ReadonlySet<string> = new Set()): Promise<string | undefined> {
1135  const list = await read($, thoughts)
1136  const was = await read($, heard)
1137  const lines = list.filter(t => !relayed.has(t.name)).flatMap(t => newsOf(t, was[t.id]))
1138  await update($, heard, () => Object.fromEntries(list.map(t => [t.id, heardOf(t)])))
1139  return lines.length === 0 ? undefined : formatNews(lines)
1140}
1141
1142// The updates waiting for the voice, taken, as one relay with what is new from the other
1143// thoughts after them; none when no update waits.
1144async function takeRelay($: EngineInterface): Promise<string | undefined> {
1145  let taken: Update[] = []
1146  await update($, inbox, list => {
1147    taken = list
1148    return []
1149  })
1150  if (taken.length === 0) return undefined
1151  const news = await takeNews($, new Set(taken.map(u => u.thought)))
1152  return news === undefined ? formatUpdates(taken) : `${formatUpdates(taken)}\n\n${news}`
1153}
1154
1155// Waits, a short while at most, for the turn end an engine's notice tells of to be
1156// settled (its update waiting for the voice), when the notice names a thought whose turn
1157// ended. The notice can come while the settling still runs.
1158async function settledFor($: EngineInterface, notice: string) {
1159  const found = [...settling].find(([id, s]) => isAbout(notice, id, s.name))
1160  if (found === undefined) return
1161  await Promise.race([found[1].done, $.clock.sleep(NOTICE_WAIT_MS)])
1162  settling.delete(found[0])
1163}
1164
1165// The voice's reply as it streams, its text held back while it could still be QUIET: then
1166// passed on as it came or, being QUIET, as NO_RESPONSE, which the desktop draws as
1167// nothing. A reply that calls a tool, or thinks after its text, is passed on as it came.
1168async function* unquiet(
1169  stream: HookStream<TurnStepChunk, TurnStepResult>,
1170): AsyncGenerator<TurnStepChunk, TurnStepResult> {
1171  // Every piece since the reply's text began, in order (null once passed on), and that text.
1172  let held: TurnStepChunk[] | null = []
1173  let text = ''
1174  let isRewritten = false
1175  for await (const chunk of stream) {
1176    if (held === null || (held.length === 0 && chunk.kind !== 'text')) {
1177      yield chunk
1178      continue
1179    }
1180    if (chunk.kind === 'stop') {
1181      isRewritten = text.trim() === QUIET
1182      yield* isRewritten ? quieted(held) : held
1183      held = null
1184      yield chunk
1185      continue
1186    }
1187    held.push(chunk)
1188    if (chunk.kind === 'engine') continue
1189    if (chunk.kind === 'text') {
1190      text += chunk.text
1191      if (QUIET.startsWith(text.trim())) continue
1192    }
1193    yield* held
1194    held = null
1195  }
1196  if (held !== null) {
1197    isRewritten = text.trim() === QUIET
1198    yield* isRewritten ? quieted(held) : held
1199  }
1200  const result = await stream.result
hooks/prompts.ts 192 lines
1import type { Heard, Thought, Update } from '../types'
2
3// What the voice replies when it has nothing to say.
4export const QUIET = '(quiet)'
5
6// What a quiet reply goes on as, and is kept as: a reply the desktop draws as nothing.
7export const NO_RESPONSE = 'No response requested.'
8
9export const isQuiet = (text: string) => text.trim() === QUIET || text.trim() === NO_RESPONSE
10
11// How every relay of the thoughts' updates to the voice begins, on a line of its own.
12export const RELAY_HEAD = 'Thought updates:'
13
14// How the note of what is new from the thoughts begins, beside the person's messages and
15// after a relay's updates.
16export const NEWS_HEAD = "What's new from your thoughts:"
17
18// The prompt that wakes the voice to read the updates just handed to it as a hidden row.
19// It is shaped as a local command's output (a /model echo), which Claude Code does not
20// replay to the desktop and the desktop draws as nothing; it is submitted as the person's
21// own words, so it is read bare. The voice's brief says what it is.
22export const WAKE =
23  '<local-command-stdout>Set model to unchanged (multitask wake-up: read the thought updates just above)</local-command-stdout>'
24
25export const isWakeText = (text: string) => text.includes('(multitask wake-up: read the thought updates just above)')
26
27// TEMPORARY: whether a thought's mid-turn progress notes are relayed to the voice. Off
28// for now: each relay adds transcript rows, which leave gaps in the desktop chat, until
29// a hidden delivery route is found. Notes are still kept (Thoughts pane, thoughts tool),
30// and the end of each turn is still relayed. Set true to switch back; the prompts follow.
31export const RELAY_NOTES: boolean = false
32
33export const VOICE = `# Multitasking mind
34
35Multitasking is on. You are the voice of a multitasking mind: you talk with the user, and your thoughts (background agents you start and steer) do all of the actual thinking and work. You do none of it yourself: reading, searching, running and editing are refused to you.
36
37Your tools:
38- think: start a thought on a task. Name each thought briefly by its task, in a few words of kebab-case (fix-login-expiry); you address it by that name.
39- tell: give a thought a message. Its parameters are \`name\` (the thought's name), \`message\` (the text) and \`how\`: post (the default; it reads it at its next step), queue (it reads it once it finishes its current turn; you can still unqueue it) or interrupt (cut what it is doing and give it this now).
40- unqueue: withdraw messages you queued for a thought.
41- stop: end a thought.
42- thoughts: every thought's status, queue, latest progress notes and last report, or one thought's recent transcript.
43
44Updates from your thoughts reach you as rows the user never sees (failing that, as messages from the multitask plugin). When they arrive while you are idle, a wake-up follows them: a line "Set model to unchanged (multitask wake-up: read the thought updates just above)". It is not from the user and changes no model; it only means read the updates just above it. Neither updates nor wake-ups need a reply. Each update starts "${RELAY_HEAD}", then one line per update: ${RELAY_NOTES ? '"name: text" is a progress note or report, ' : ''}"name (done): text" the text a turn ended with, "name: done" a turn that ended with nothing more, "name (from the user): text" a message the user sent that thought themselves from the Thoughts pane, which it acts on as it would on yours, "name: (...)" messages of yours still pending for it, which reach it at the next chance and you hear back after (with why the last try failed, if one did)${RELAY_NOTES ? '' : ' (for now their progress notes are not sent to you; they are shown in the Thoughts pane)'}; your default reply is ${QUIET}. For each, choose:
45- Say nothing. Reply with exactly ${QUIET} and nothing else; the user never sees it. This is the default.
46- Steer: post, queue or interrupt a thought, unqueue what is no longer wanted, stop a thought, or start another.
47- Speak to the user, only when something deserves their attention: a result they asked for, a decision only they can make, a problem. Use your own words, briefly.
48
49When a thought's turn ends, its update may come in place of the engine's own notice that the thought finished. After the updates, and beside the user's messages and the engine's notices, there may be a short note starting "${NEWS_HEAD}": the thoughts that finished, failed or were stopped since you were last told, and the latest progress notes of those still running. It needs no reply either, and an update may repeat what it said. Your history keeps each ${QUIET} reply as "${NO_RESPONSE}"; both mean you said nothing.
50
51Never restate or summarise an update just because it arrived, and never narrate what the thoughts are doing unless the user asks. When the user asks for something, start or steer thoughts and keep track of what they asked for until the thoughts have delivered it.
52
53Thoughts work in the user's own checkout; the only way to set one apart is to ask in its brief. Before starting a thought that will edit files, check what the running thoughts are changing (thoughts), and give each editing thought its own files or have its brief ask for a git worktree on a branch of its own. A worktree is worth it when edits could collide with another thought's, or with files the user or live tooling (a dev server, a watcher, anything that reloads on save) reads while the work runs, or for long or risky changes across many files. Leave it out for reading and research, small edits to files nothing else touches, and work the user must see live. In auto mode the files of a plugin loaded live in this session can't be edited in place, so a thought changing them needs a git worktree and a merge back.
54
55When two tasks need the same files, queue the second on the thought doing the first, or wait for it, or split the work by file. A thought in a worktree hands back a branch: tell the user, and have a thought merge it into their checkout only when they ask. Once a thought's branch is merged, have its worktree and branch removed; raise unmerged ones with the user rather than leaving them behind.
56
57To the user you are one mind. Your thoughts are your own thinking, not workers you manage in front of them, so never speak of thoughts as items or workers ("I've started a thought to dig into this", "the thought will report back"). Speak naturally, as a person does about their own work: "I'm looking into which rows we can hide", "I'll let you know what I find". When you start or steer thoughts for a request, keep your message very brief, often a few words; if an acknowledgement adds nothing, reply exactly ${QUIET}.`
58
59// Beside each of the person's messages while Multitask stays on, once the voice has its part.
60export const VOICE_REMINDER = `Multitask is on: you are the voice. Hand work to thoughts (think, tell) and do none yourself. To the user, speak as one mind about your own work ("I'm looking into it"), never of thoughts as workers; keep acknowledgements to a few words, or reply ${QUIET} when nothing needs saying.`
61
62// Beside the person's next message once Multitask is turned off.
63export const VOICE_OFF = `Multitask is now off: you are no longer the voice. Work directly with your own tools again. Thoughts you started may still be running; their updates no longer reach you, only the engine's own notice when one finishes.`
64
65export const THOUGHT =`You are one thought in a multitasking mind. Several thoughts run at once; one voice talks with the user and steers you. You do the actual thinking and work for your task: read, search, run, edit, test, whatever it needs.
66
67Before each meaningful step, write a one-line progress note in plain words, such as "Checking how the engine stamps plugin prompts". ${RELAY_NOTES ? 'Your notes reach the voice as brief updates so it can follow your work; your tool calls do not.' : 'For now your notes are shown in the Thoughts pane, and the voice sees only your latest ones, now and then; your tool calls are not shown there.'} No pleasantries, and no note for every small tool call.
68
69You share the user's checkout with them and other thoughts: keep to the files your task needs. If your brief asks for a worktree, or you will edit files something reads live (a dev server, a watcher, anything that reloads on save), work in a git worktree instead.
70
71Make it with git worktree add on a new branch, in a folder outside the project so its watchers and builds leave it alone; not with EnterWorktree, which would move the whole session. Use absolute paths into it, as your shell's directory resets between calls. A new worktree lacks ignored files (installed packages, generated files): set up or copy in what your build and tests need. Finish by committing on the branch and reporting the branch and folder; leave the worktree for whoever merges it. Never merge into the user's checkout or commit to their main branch unless asked.
72
73The text you end your turn with reaches the voice as your report. So when you finish, end your turn with a short, plain report the voice can act on: what you found or changed, where, and anything still open. If you need an answer, or a problem blocks you, do not bury it in a note: end your turn with the question or the problem, plainly, and wait.
74
75Messages from the voice, or now and then from the user directly, may arrive while you work. They steer you: take them into account straight away, and if one changes your task, follow it.`
76
77// A text on one line.
78const flat = (text: string) => text.replace(/\s+/g, ' ').trim()
79
80// The person's own message to a thought, sent from the Thoughts pane, as the thought reads it.
81export const fromPerson = (text: string) => `The user, from the Thoughts pane: ${text}`
82
83// A text on one line, cut to at most `max` characters.
84export function oneLine(text: string, max: number): string {
85  const line = flat(text)
86  return line.length > max ? `${line.slice(0, max - 1)}…` : line
87}
88
89// What a relay says of messages of the voice's still pending for a thought: they will
90// reach it, and the voice hears from it after.
91export function pendingNote(count: number): string {
92  const what = count === 1 ? '1 message' : `${count} messages`
93  return `${what} still pending; ${count === 1 ? 'it' : 'they'} will be handed over and you'll hear back`
94}
95
96// What a relay says once the messages that waited for a thought's turn to end reached it.
97function handedOverNote(count: number): string {
98  return `it has your ${count === 1 ? 'queued message' : `${count} queued messages`} now; you'll hear back`
99}
100
101// One line an update: "name: text" a note (or a report already sent as one),
102// "name (done): text" the text a turn ended with, "name: done" a turn ended bare; a
103// turn's end then says what became of the messages that waited for it. "name (from the
104// user): text" is the person's own message to the thought, from the Thoughts pane.
105export function formatUpdates(updates: Update[]): string {
106  const lines = updates.map(u => {
107    if (u.isFromPerson === true) return `${u.thought} (from the user): ${flat(u.text)}`
108    if (u.isDone !== true) return `${u.thought}: ${flat(u.text)}`
109    const pending = u.pending ?? 0
110    const queue = pending === 0 ? '' : ` — ${u.isHandedOver === true ? handedOverNote(pending) : pendingNote(pending)}`
111    return u.text === '' ? `${u.thought}: done${queue}` : `${u.thought} (done): ${flat(u.text)}${queue}`
112  })
113  return `${RELAY_HEAD}\n${lines.join('\n')}`
114}
115
116// How many of a running thought's notes a what's-new note carries, at most, and how long each.
117const NEWS_NOTES = 2
118const NEWS_MAX = 160
119
120// One line a thought whose turn ended, failed or was stopped, with its report's start.
121export function newsLine(t: Thought): string {
122  const report = t.lastText === '' ? '' : `: ${oneLine(t.lastText, NEWS_MAX)}`
123  if (t.status === 'stopped') return `${t.name} was stopped`
124  if (t.status === 'failed') return `${t.name} ended on an error${report}`
125  return `${t.name} finished${report}`
126}
127
128// What the voice has not heard of a thought, one line each: that it finished, failed or
129// was stopped; while it runs, the latest notes it wrote since the voice last heard of it.
130export function newsOf(t: Thought, heard: Heard | undefined): string[] {
131  if (t.status === 'running') {
132    const notes = t.notes ?? []
133    const since = heard === undefined ? 0 : notes.lastIndexOf(heard.note) + 1
134    return notes.slice(since).slice(-NEWS_NOTES).map(n => `${t.name}: ${oneLine(n, NEWS_MAX)}`)
135  }
136  if (heard?.status === t.status && heard.report === t.lastText) return []
137  return [newsLine(t)]
138}
139
140// What the voice has heard of a thought once it is told of it as it is now.
141export const heardOf = (t: Thought): Heard => ({ status: t.status, report: t.lastText, note: t.notes?.at(-1) ?? '' })
142
143export const formatNews = (lines: string[]) => `${NEWS_HEAD}\n${lines.join('\n')}`
144
145// A relay row as a surface holds it: bare, or still in the engine's frame for a
146// plugin's prompt ("The multitask plugin sent a message:"), as the desktop shows it.
147// The header ends its line, so a person's own words starting the same way stay theirs.
148const RELAY_ROW = new RegExp(
149  `^\\s*(?:The multitask plugin sent a message[^:\\n]*:\\s*)?${RELAY_HEAD.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[ \\t]*\\r?\\n`,
150)
151
152export const isRelayText = (text: string) => RELAY_ROW.test(text)
153
154// The thoughts a relay's update lines name, each once, in order.
155export function relayNames(text: string): string[] {
156  const at = text.search(RELAY_ROW)
157  if (at < 0) return []
158  const names = new Set<string>()
159  for (const line of text.slice(text.indexOf(RELAY_HEAD, at) + RELAY_HEAD.length).trimStart().split(/\r?\n/)) {
160    const name = /^([^\s:]+)(?: \((?:done|from the user)\))?: /.exec(line)?.[1]
161    if (name === undefined) break
162    names.add(name)
163  }
164  return [...names]
165}
166
167export function describeThoughts(thoughts: Thought[]): string {
168  if (thoughts.length === 0) return 'No thoughts yet.'
169  return thoughts
170    .map(t => {
171      const queue = t.queued.length === 0 ? '' : `\n  queued: ${t.queued.map((q, i) => `${i + 1}. ${q}`).join(' | ')}`
172      const notes = (t.notes ?? []).slice(-3).map(n => `\n  · ${oneLine(n, 160)}`).join('')
173      const last = t.lastText === '' ? '' : `\n  report: ${t.lastText.slice(0, 300)}`
174      return `- ${t.name} [${t.status}]: ${t.task.slice(0, 200)}${queue}${notes}${last}`
175    })
176    .join('\n')
177}
178
179// Each message's start with its spacing dropped, hashed: how a session rewound or forked
180// from another, which starts under a new id with copies of the messages it kept, is
181// matched to it. A start too short to tell sessions apart ("ok", "(quiet)") is left out.
182export function marksOf(messages: readonly { text: string }[]): string[] {
183  return messages
184    .map(m => m.text.replace(/\s+/g, '').slice(0, 80))
185    .filter(start => start.length >= 12)
186    .map(start => {
187      let hash = 0x811c9dc5
188      for (let i = 0; i < start.length; i++) hash = Math.imul(hash ^ start.charCodeAt(i), 0x01000193)
189      return (hash >>> 0).toString(16).padStart(8, '0')
190    })
191}
192
hooks/pane.tsx 422 lines
1import type { Color, ElementTable, RenderElement, RenderSurface } from 'claude-code'
2
3import type { Thought, ThoughtStatus } from '../types'
4import { oneLine } from './prompts'
5
6// The Thoughts pane: running thoughts first, each a card in its colour's border; the
7// rest one line each, the one most recently ended first, until opened, the
8// ENDED_SHOWN most recently ended alone until `N more` shows them all. A card sets
9// each kind of line apart by a label at its left: the task, the progress notes (the
10// latest at full strength with its age, in the warning colour once the thought has
11// been quiet a while), the report, and the messages queued for its turn's end. A card's
12// `tell` opens a field at its foot to send the thought a message of the person's own.
13//
14// It is drawn as the thread view is (thread-chat's pane.tsx): plain functions here,
15// every hook and every call on `$` in register.tsx, which hands them what they draw
16// with. A plugin hooks an event once without a matcher, and the engine follows `$`
17// only into functions of the file that uses it.
18
19const GLYPH: Record<ThoughtStatus, string> = { running: '◐', idle: '●', stopped: '×', failed: '!' }
20
21// What each status reads as: a turn that ended is done, though a message resumes it.
22const STATUS_WORD: Record<ThoughtStatus, string> = { running: 'running', idle: 'done', stopped: 'stopped', failed: 'failed' }
23
24// The order thoughts are listed in: running ones, then those that failed, then done,
25// then stopped.
26const RANK: Record<ThoughtStatus, number> = { running: 0, failed: 1, idle: 2, stopped: 3 }
27
28// How long a running thought may go without a note, or since its turn started, before
29// its age is drawn in the warning colour.
30export const QUIET_MS = 5 * 60_000
31
32// How many thoughts that are not running the pane lists, the most recently ended, until
33// `N more` shows them all.
34export const ENDED_SHOWN = 16
35
36// Notes a card shows, at most: folded, and opened.
37const NOTES_FOLDED = 3
38const NOTES_OPENED = 5
39
40// The most of a report drawn when opened: what one Markdown element takes.
41const REPORT_MAX = 10_000
42
43// Cells the labels at a card's left take, the gap after them included.
44const LABEL_COLUMNS = 7
45
46// How a thought's colour is drawn: as it is, or dim (see drawThoughts).
47type Tint = { color: Color; dimColor?: true }
48
49// The key of a card's field to tell its thought something: this, then the thought's id.
50export const TELL_FIELD = 'tell-field:'
51
52// A card's padding inside its border, as the thread view pads a reply's thread part: on
53// the desktop on every side (a bordered Box there is padded 8px above and below unless
54// told otherwise); on the terminal, where a row is a whole line, at the sides alone.
55const DESKTOP_CARD_PADDING = { padding: 1 } as const
56const CARD_PADDING = { paddingX: 1 } as const
57
58// A span of time, short: under a minute, minutes, hours and minutes, or days.
59export function spanOf(ms: number): string {
60  const minutes = Math.floor(Math.max(0, ms) / 60_000)
61  if (minutes < 1) return '<1m'
62  if (minutes < 60) return `${minutes}m`
63  const hours = Math.floor(minutes / 60)
64  if (hours < 10) return minutes % 60 === 0 ? `${hours}h` : `${hours}h ${minutes % 60}m`
65  if (hours < 48) return `${hours}h`
66  return `${Math.floor(hours / 24)}d`
67}
68
69// How long ago a time was, as the pane says it.
70export const agoOf = (ms: number) => (ms < 60_000 ? 'just now' : `${spanOf(ms)} ago`)
71
72// A task's first line, which a running card shows until it is opened.
73export function firstLine(task: string): string {
74  return task.trimStart().split('\n')[0]?.trimEnd() ?? ''
75}
76
77// The thoughts in the order the pane lists them: running ones as they were started,
78// the rest the one most recently ended first.
79export function orderOf(list: readonly Thought[]): Thought[] {
80  return list
81    .map((t, i) => ({ t, i }))
82    .sort((a, b) => {
83      const rank = RANK[a.t.status] - RANK[b.t.status]
84      if (rank !== 0) return rank
85      if (a.t.status === 'running') return a.i - b.i
86      return (b.t.endedAt ?? 0) - (a.t.endedAt ?? 0) || b.i - a.i
87    })
88    .map(({ t }) => t)
89}
90
91// The thoughts not running beyond the ENDED_SHOWN most recently ended, by id, but those
92// opened: what the pane lists only once `N more` is pressed.
93export function endedBeyond(list: readonly Thought[], opened: readonly string[]): Set<string> {
94  const ended = list
95    .map((t, i) => ({ t, i }))
96    .filter(({ t }) => t.status !== 'running')
97    .sort((a, b) => (b.t.endedAt ?? 0) - (a.t.endedAt ?? 0) || b.i - a.i)
98  return new Set(ended.slice(ENDED_SHOWN).map(({ t }) => t.id).filter(id => !opened.includes(id)))
99}
100
101// Whether a thought's report is shown: once it has one and has stopped working, and
102// unless it wrote notes since (an old report would read as the result of new work).
103export const showsReport = (t: Thought) => t.lastText !== '' && t.status !== 'running' && t.notedSinceReport !== true
104
105// How long a running thought has gone without a note, or since its turn started if
106// that came later; none where neither time is known.
107export function quietFor(t: Thought, now: number | undefined): number | undefined {
108  const times = [t.notedAt, t.startedAt].filter((at): at is number => at !== undefined)
109  return times.length === 0 || now === undefined ? undefined : now - Math.max(...times)
110}
111
112// How long ago `at` was, as agoOf says it; none where either time is not known.
113const agoSince = (at: number | undefined, now: number | undefined) =>
114  at === undefined || now === undefined ? undefined : agoOf(now - at)
115
116// What the pane is drawn with, as register.tsx reads it while drawing: the surface and
117// its elements, the time (none where it cannot be read: no ages are drawn), the pane's
118// width, which thoughts and reports are opened, and what each control does.
119export type ThoughtsDrawing = {
120  surface: RenderSurface
121  ui: ElementTable
122  now: number | undefined
123  // whether the mod is on in the chat, and whether it is in Multitask mode (not Focus)
124  isEnabled: boolean
125  isOn: boolean
126  bodyColumns: number
127  opened: readonly string[]
128  shownReports: readonly string[]
129  toggleExpanded: (id: string) => void
130  toggleReport: (id: string) => void
131  stop: (id: string) => void
132  unqueue: (id: string, index: number) => void
133  // the thought whose card has its field open ('' none), what opens or closes it, and
134  // what Enter there sends, should the pane's ui.input hook not take it first
135  tellingTo: string
136  toggleTell: (id: string) => void
137  tell: (id: string, text: string) => void
138  // whether every thought not running is listed (`N more` pressed), and what toggles it
139  showsAllEnded: boolean
140  toggleShowsAllEnded: () => void
141}
142
143// The field a card's thought is told something in, where the surface draws one (the
144// mobile app draws none yet, though its table may hand one over) in Multitask mode: in
145// Focus, a thought whose turn ended cannot be resumed.
146function tellFieldOf(draw: ThoughtsDrawing) {
147  if (!draw.isOn || draw.surface === 'mobile' || !('Input' in draw.ui)) return undefined
148  return draw.ui.Input
149}
150
151// The pane's body: a line of how many thoughts there are, by status, then each one, and,
152// with more ended than ENDED_SHOWN, `N more` (or `less`) at the end.
153export function drawThoughts(draw: ThoughtsDrawing, list: readonly Thought[]): RenderElement {
154  const { Box, Text, Button } = draw.ui
155  const counts = (['running', 'failed', 'idle', 'stopped'] as const)
156    .map(status => ({ status, count: list.filter(t => t.status === status).length }))
157    .filter(c => c.count > 0)
158    .map(c => `${c.count} ${STATUS_WORD[c.status]}`)
159  const summary = list.length === 0 ? 'No thoughts yet.' : counts.join(' · ')
160  // Only running thoughts hold their colours: one that ended keeps its own, dimmed while a
161  // running thought has taken it, so the two are not mistaken for each other.
162  const held = new Set(list.filter(t => t.status === 'running').map(t => t.color))
163  const tintOf = (t: Thought): Tint => ({ color: t.color, ...(t.status !== 'running' && held.has(t.color) && { dimColor: true }) })
164  const beyond = endedBeyond(list, draw.opened)
165  const shown = draw.showsAllEnded ? orderOf(list) : orderOf(list).filter(t => !beyond.has(t.id))
166  return (
167    <Box flexDirection="column">
168      <Box marginBottom={1}>
169        <Text dimColor>
170          {!draw.isEnabled ? 'Multitask is off' : draw.isOn ? 'Multitask mode' : 'Focus mode'} · {summary}
171        </Text>
172      </Box>
173      {shown.map(t =>
174        t.status !== 'running' && !draw.opened.includes(t.id) ? drawLine(draw, t, tintOf(t)) : drawCard(draw, t, tintOf(t)),
175      )}
176      {beyond.size > 0 && (
177        <Box key="ended-more" flexDirection="row">
178          <Button
179            key="more-ended"
180            plain
181            dimColor
182            label={draw.showsAllEnded ? 'less' : `${beyond.size} more`}
183            onPress={() => draw.toggleShowsAllEnded()}
184          />
185        </Box>
186      )}
187    </Box>
188  )
189}
190
191// What a thought's status says, in its colour, with how long it has been so: running
192// for how long its turn has run, else how long ago it ended.
193function drawStatus(draw: ThoughtsDrawing, t: Thought): RenderElement {
194  const { Text } = draw.ui
195  const at = t.status === 'running' ? t.startedAt : t.endedAt
196  const { now } = draw
197  const age = at === undefined || now === undefined ? '' : t.status === 'running' ? ` for ${spanOf(now - at)}` : ` ${agoOf(now - at)}`
198  const look: { color?: Color; dimColor?: boolean } =
199    t.status === 'running' ? { color: t.color } : t.status === 'failed' ? { color: 'error' } : { dimColor: true }
200  return (
201    <Text {...look} wrap="truncate-end">
202      {STATUS_WORD[t.status]}
203      {age}
204    </Text>
205  )
206}
207
208// A thought that is not running, folded to one line: its name, status, its report's
209// first line, and stop.
210function drawLine(draw: ThoughtsDrawing, t: Thought, tint: Tint): RenderElement {
211  const { Box, Text, Button } = draw.ui
212  return (
213    <Box key={`line:${t.id}`} flexDirection="row" columnGap={1} alignItems="center">
214      <Box flexShrink={0}>
215        <Text {...tint}>{GLYPH[t.status]}</Text>
216      </Box>
217      <Box flexShrink={0}>
218        <Button key={`expand:${t.id}`} plain label={t.name} hover={tint} onPress={() => draw.toggleExpanded(t.id)} />
219      </Box>
220      <Box flexShrink={0}>{drawStatus(draw, t)}</Box>
221      <Box flexGrow={1} flexShrink={1} minWidth={0}>
222        {showsReport(t) && (
223          <Text dimColor wrap="truncate-end">
224            {oneLine(t.lastText, 200)}
225          </Text>
226        )}
227      </Box>
228      {t.status !== 'stopped' && (
229        <Box flexShrink={0}>
230          <Button key={`stop:${t.id}`} plain dimColor hover={tint} label="stop" onPress={() => draw.stop(t.id)} />
231        </Box>
232      )}
233    </Box>
234  )
235}
236
237// One kind of a card's lines under its label: the label on the first line alone, dim
238// or in `tint`, the lines beside it, `gap` rows below what is above.
239function drawSection(draw: ThoughtsDrawing, label: string, lines: RenderElement[], gap: number, tint?: Tint): RenderElement {
240  const { Box, Text } = draw.ui
241  return (
242    <Box flexDirection="row" marginTop={gap}>
243      <Box width={LABEL_COLUMNS} flexShrink={0}>
244        <Text {...(tint ?? { dimColor: true })}>{label}</Text>
245      </Box>
246      <Box flexDirection="column" flexGrow={1} flexShrink={1} minWidth={0}>
247        {lines}
248      </Box>
249    </Box>
250  )
251}
252
253// A thought's card: its name, status and controls; then its task, its notes, its
254// report and its queue, each kind under its label.
255function drawCard(draw: ThoughtsDrawing, t: Thought, tint: Tint): RenderElement {
256  const { Box, Text, Button, Markdown } = draw.ui
257  const Input = t.status === 'stopped' ? undefined : tellFieldOf(draw)
258  const isTelling = Input !== undefined && draw.tellingTo === t.id
259  const isPage = draw.surface !== 'terminal'
260  // half a line between kinds on a page; none on the terminal, where the labels part them
261  const gap = isPage ? 1 : 0
262  const isOpened = draw.opened.includes(t.id)
263  const isRunning = t.status === 'running'
264  // Cells a card's task line has: the pane's body less the card's border and padding and the labels.
265  const taskColumns = draw.bodyColumns - 4 - LABEL_COLUMNS
266  const task = firstLine(t.task)
267  const hasMore = isRunning && (t.task.trim() !== task || task.length > taskColumns)
268  const control = { plain: true, dimColor: true, hover: tint } as const
269
270  const notes = (t.notes ?? []).slice(isOpened ? -NOTES_OPENED : -NOTES_FOLDED)
271  const quiet = isRunning ? quietFor(t, draw.now) : undefined
272  const isQuiet = quiet !== undefined && quiet >= QUIET_MS
273  const noteAge = agoSince(t.notedAt, draw.now)
274  const noteLines = notes.map((note, i) => {
275    const isLatest = i === notes.length - 1
276    const text = isOpened ? note : oneLine(note, 200)
277    const wrap = isOpened ? 'wrap' : 'truncate-end'
278    if (!isLatest) {
279      return (
280        <Text dimColor wrap={wrap}>
281          {text}
282        </Text>
283      )
284    }
285    return (
286      <Box flexDirection="row" columnGap={2}>
287        <Box flexGrow={1} flexShrink={1} minWidth={0}>
288          <Text wrap={wrap}>{text}</Text>
289        </Box>
290        {noteAge !== undefined && (
291          <Box flexShrink={0}>
292            <Text {...(isQuiet ? { color: 'warning' } : { dimColor: true })}>{noteAge}</Text>
293          </Box>
294        )}
295      </Box>
296    )
297  })
298  // A running thought with no notes yet says how long it has been at it.
299  const started = agoSince(t.startedAt, draw.now)
300  if (noteLines.length === 0 && isRunning && started !== undefined) {
301    noteLines.push(
302      <Text {...(isQuiet ? { color: 'warning' } : { dimColor: true })} wrap="truncate-end">
303        none yet, started {started}
304      </Text>,
305    )
306  }
307
308  const isReportShown = draw.shownReports.includes(t.id)
309  const report = showsReport(t) && (
310    <Box key={`reportbox:${t.id}`} flexDirection="column">
311      {isReportShown && <Markdown text={t.lastText.length > REPORT_MAX ? `${t.lastText.slice(0, REPORT_MAX - 1)}…` : t.lastText} />}
312      <Box flexDirection="row" columnGap={1}>
313        {!isReportShown && (
314          <Box flexGrow={1} flexShrink={1} minWidth={0}>
315            <Text wrap="truncate-end">{oneLine(t.lastText, 200)}</Text>
316          </Box>
317        )}
318        {/* Lit in the thought's colour with the pointer anywhere on the report; the line gives way, not it. */}
319        <Box flexShrink={0}>
320          <Button
321            key={`report:${t.id}`}
322            plain
323            dimColor
324            hover={tint}
325            label={isReportShown ? 'less' : 'more'}
326            onPress={() => draw.toggleReport(t.id)}
327          />
328        </Box>
329      </Box>
330    </Box>
331  )
332
333  const queued = t.queued.map((q, i) => (
334    <Box flexDirection="row" columnGap={1}>
335      <Box flexShrink={0}>
336        <Text dimColor>{i + 1}.</Text>
337      </Box>
338      <Box flexGrow={1} flexShrink={1} minWidth={0}>
339        <Text wrap={isOpened ? 'wrap' : 'truncate-end'}>{isOpened ? q : oneLine(q, 200)}</Text>
340      </Box>
341      <Box flexShrink={0}>
342        <Button key={`unqueue:${t.id}:${i}`} {...control} label="unqueue" onPress={() => draw.unqueue(t.id, i)} />
343      </Box>
344    </Box>
345  ))
346
347  return (
348    <Box
349      key={`card:${t.id}`}
350      flexDirection="column"
351      borderStyle="round"
352      borderColor={tint.color}
353      {...(tint.dimColor && { borderDimColor: true })}
354      {...(draw.surface === 'desktop' ? DESKTOP_CARD_PADDING : CARD_PADDING)}
355      marginBottom={1}
356    >
357      <Box flexDirection="row" columnGap={1} alignItems="center">
358        <Box flexShrink={0}>
359          <Text {...tint} bold>
360            {GLYPH[t.status]}
361          </Text>
362        </Box>
363        <Box flexShrink={0}>
364          <Button key={`expand:${t.id}`} plain label={t.name} hover={tint} onPress={() => draw.toggleExpanded(t.id)} />
365        </Box>
366        <Box flexGrow={1} flexShrink={1} minWidth={0}>
367          {drawStatus(draw, t)}
368        </Box>
369        {hasMore && (
370          <Box flexShrink={0}>
371            <Button key={`more:${t.id}`} {...control} label={isOpened ? 'less' : 'more'} onPress={() => draw.toggleExpanded(t.id)} />
372          </Box>
373        )}
374        {!isRunning && (
375          <Box flexShrink={0}>
376            <Button key={`collapse:${t.id}`} {...control} label="hide" onPress={() => draw.toggleExpanded(t.id)} />
377          </Box>
378        )}
379        {Input !== undefined && (
380          <Box flexShrink={0}>
381            <Button key={`tell:${t.id}`} {...control} label={isTelling ? 'cancel' : 'tell'} onPress={() => draw.toggleTell(t.id)} />
382          </Box>
383        )}
384        {t.status !== 'stopped' && (
385          <Box flexShrink={0}>
386            <Button key={`stop:${t.id}`} {...control} label="stop" onPress={() => draw.stop(t.id)} />
387          </Box>
388        )}
389      </Box>
390      {drawSection(
391        draw,
392        'task',
393        [
394          <Text dimColor italic wrap={isOpened ? 'wrap' : 'truncate-end'}>
395            {isOpened ? t.task.trim() : task}
396          </Text>,
397        ],
398        gap,
399      )}
400      {noteLines.length > 0 && drawSection(draw, 'notes', noteLines, gap)}
401      {report !== false && drawSection(draw, 'report', [report], gap, tint)}
402      {queued.length > 0 && drawSection(draw, 'queued', queued, gap)}
403      {isTelling &&
404        drawSection(
405          draw,
406          'tell',
407          [
408            <Input
409              key={`${TELL_FIELD}${t.id}`}
410              placeholder={`a message for ${t.name}`}
411              submitLabel="send"
412              autoFocus
413              onSubmit={(value: string) => draw.tell(t.id, value)}
414            />,
415          ],
416          gap,
417          tint,
418        )}
419    </Box>
420  )
421}
422
hooks/band.tsx 320 lines
1import type { ElementTable, RenderElement, RenderSurface } from 'claude-code'
2
3import type { Thought } from '../types'
4import { agoOf } from './pane'
5import { oneLine } from './prompts'
6
7// The band's `thoughts` button, left of Multitask's mode control, which opens the Thoughts
8// pane, with the thoughts' dots after its word: one for each running thought, in its
9// colour, in the order they started, DOTS_SHOWN at most and `+N` for the rest. A dot
10// blinks white as its thought works, at each new row in its conversation (BLINK_MS apart
11// at least: register.tsx starts a blink, none while one runs), and swells a little and
12// back as it writes a progress note. As a turn ends, the dot flashes and gives way to a
13// check (a cross for one that failed; a stopped one only fades), which fades out of the
14// button. Hovered on the desktop, a dot's card says the thought's name, its latest note
15// and how long ago that came.
16//
17// The desktop draws a dot as a small SVG, which it shows as an image: its SMIL animation
18// runs there, with no redraw. The desktop builds the band afresh at each redraw, which
19// would start an animation over, so one is drawn with how far it has got (a negative
20// `begin`): a redraw carries it on, and once it is over the dot is drawn still. A blink
21// and a note's swell are two animations of the one disc, each carried on alone. A Button
22// holds only text, so there the button is a Box drawn as the dropdown is, each of its
23// parts under a hit area that opens the pane (drawField). Every other surface draws a
24// Button, a dot in it a glyph: white a moment for a blink, inverted for a note; a check
25// or cross as a turn ends.
26//
27// As pane.tsx: plain functions here, every hook and call on `$` in register.tsx.
28
29// The most dots the band shows; the rest are counted as `+N`.
30export const DOTS_SHOWN = 8
31// How long a dot's swell at a note takes; its blink, which is also the least time from one
32// blink's start to the next; the white of a blink in a glyph; and its end.
33export const PULSE_MS = 1000
34export const BLINK_MS = 1000
35const FLICKER_MS = 400
36export const FADE_MS = 1500
37// How long a blink takes to reach white, the rest of it back to the thought's colour.
38const BLINK_PEAK_MS = 250
39// How often the ages in the dots' cards are drawn afresh while they stand.
40export const CARD_AGE_MS = 60_000
41
42// The key of a dot's Box on the desktop: this, then the thought's id. A glyph has none: a
43// Button keeps no key on the text in it.
44export const DOT = 'dot:'
45
46// The side of a dot's picture, in CSS pixels: its disc 8 across, the rest room to swell
47// and flash in, so neither moves the band.
48const DOT_PX = 14
49const WHITE = '#ffffff'
50// The disc's radius, its stroke drawing it half a pixel wider; at a note's height, 1.3
51// times as wide.
52const R = 3.5
53const R_SWELL = 4.7
54
55// What a dot shows: a running thought, or the end of its turn.
56type DotKind = 'running' | 'done' | 'failed' | 'stopped'
57// `since`: when its latest note came (running) or its turn ended; `blinkAt`: when its
58// latest blink began (running).
59type Dot = { t: Thought; kind: DotKind; since: number | undefined; blinkAt?: number | undefined }
60
61// The glyph for each where a dot is no picture, the pane's for a failed or stopped thought.
62const GLYPH: Record<DotKind, string> = { running: '●', done: '✓', failed: '!', stopped: '×' }
63const WORD: Record<DotKind, string> = { running: 'running', done: 'done', failed: 'failed', stopped: 'stopped' }
64
65// What the dots are drawn with, as register.tsx reads it while drawing the band: the
66// surface and its elements, the time (none where it cannot be read: nothing animates or
67// fades, and the cards have no ages), when each thought's turn was last seen to end in
68// this run, by id (a thought taken up from the store has none, so does not fade), and when
69// each running thought's latest blink began, by id.
70export type DotsDrawing = {
71  surface: RenderSurface
72  ui: ElementTable
73  now: number | undefined
74  endings: ReadonlyMap<string, number>
75  blinks: ReadonlyMap<string, number>
76}
77
78// The thoughts with a dot, in the order they started: those running, and those whose
79// turn ended under FADE_MS ago.
80export function dotsOf(list: readonly Thought[], draw: Pick<DotsDrawing, 'now' | 'endings' | 'blinks'>): Dot[] {
81  const { now, endings, blinks } = draw
82  return list.flatMap((t): Dot[] => {
83    if (t.status === 'running') return [{ t, kind: 'running', since: t.notedAt, blinkAt: blinks.get(t.id) }]
84    const at = endings.get(t.id)
85    if (at === undefined || now === undefined || now - at >= FADE_MS) return []
86    return [{ t, kind: t.status === 'idle' ? 'done' : t.status, since: at }]
87  })
88}
89
90// How far an animation that began `at` and takes `ms` has got, in ms, while it runs;
91// undefined when it does not.
92function runningFor(at: number | undefined, ms: number, now: number | undefined): number | undefined {
93  if (at === undefined || now === undefined) return undefined
94  const gone = now - at
95  return gone >= 0 && gone < ms ? gone : undefined
96}
97
98// What of a dot runs now, each as how far it has got: a running thought's swell at a
99// note and blink (its white on the terminal, which lasts `blinkMs`), or the end of a turn.
100function runsOf(d: Dot, now: number | undefined, blinkMs = BLINK_MS) {
101  if (d.kind !== 'running') return { end: runningFor(d.since, FADE_MS, now) }
102  return { swell: runningFor(d.since, PULSE_MS, now), blink: runningFor(d.blinkAt, blinkMs, now) }
103}
104
105// How long until the band must be drawn again for its dots: an end to fade out of the
106// button, a swell or blink in a glyph to end, the cards' ages; undefined when nothing
107// waits. A swell or blink in a picture ends of itself; only a picture has a card.
108function redrawIn(dots: readonly Dot[], draw: ButtonDrawing): number | undefined {
109  const { now } = draw
110  if (now === undefined || dots.length === 0) return undefined
111  const waits = dots.flatMap(d => {
112    const { end, swell, blink } = runsOf(d, now, FLICKER_MS)
113    if (end !== undefined) return [FADE_MS - end]
114    if (isPicture(draw)) return []
115    return [swell === undefined ? [] : [PULSE_MS - swell], blink === undefined ? [] : [FLICKER_MS - blink]].flat()
116  })
117  if (isPicture(draw)) waits.push(CARD_AGE_MS)
118  return waits.length === 0 ? undefined : Math.max(1, Math.min(...waits))
119}
120
121// A colour as it may go into a picture's markup: a thought's is one of the palette's; any
122// other is drawn grey.
123const markupColor = (color: string) => (/^#[0-9a-fA-F]{3,8}$/.test(color) ? color : '#888888')
124
125// One SMIL animation of `attribute` over the whole of a swell, blink or end (`ms`),
126// through `steps` of [ms from its start, value], `begin` ms from when the picture was
127// drawn (negative: under way already), held at its end. Each spans the whole, never
128// ending before the picture is drawn: one that had ended by then would not be held, as
129// the desktop's engine counts only an animation that ends after its picture began.
130function animate(attribute: string, ms: number, begin: number, steps: [number, string][], more = ''): string {
131  const values = steps.map(([, value]) => value).join(';')
132  const keyTimes = steps.map(([at]) => Math.round((at / ms) * 1000) / 1000).join(';')
133  return `<animate attributeName="${attribute}" values="${values}" keyTimes="${keyTimes}" dur="${ms}ms" begin="${begin}ms" fill="freeze"${more}/>`
134}
135
136// Easing for an animation of two steps: there and back.
137const EASE = ' calcMode="spline" keySplines="0.42 0 0.58 1;0.42 0 0.58 1"'
138const EASE_BLINK = ' calcMode="spline" keySplines="0.25 0.1 0.25 1;0.42 0 0.58 1"'
139
140const disc = (color: string, inner = '') =>
141  `<circle cx="7" cy="7" r="${R}" fill="${color}" stroke="${color}" stroke-width="1">${inner}</circle>`
142
143// A stroke of a turn's end (a check or cross): drawn in from its start after the flash,
144// then faded out by the end's close.
145const stroke = (color: string, path: string, length: number, begin: number) =>
146  `<path d="${path}" fill="none" stroke="${color}" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" ` +
147  `stroke-dasharray="${length}" stroke-dashoffset="${length}">` +
148  animate('stroke-dashoffset', FADE_MS, begin, [[0, `${length}`], [300, `${length}`], [650, '0'], [FADE_MS, '0']]) +
149  animate('opacity', FADE_MS, begin, [[0, '1'], [FADE_MS - 500, '1'], [FADE_MS, '0']]) +
150  '</path>'
151
152// A dot's picture: still, swelling, blinking, or its end, as far as each has got. Each
153// animation's start is marked in it, so two blinks are two pictures, never one the
154// desktop held.
155export function pictureOf(d: Dot, now: number | undefined): string {
156  const color = markupColor(d.t.color)
157  const { end, swell, blink } = runsOf(d, now)
158  const marks = [swell !== undefined && `note ${d.since}`, blink !== undefined && `blink ${d.blinkAt}`, end !== undefined && `end ${d.since}`]
159  const mark = marks.filter(Boolean).join(', ')
160  const svg = (body: string) =>
161    `<svg xmlns="http://www.w3.org/2000/svg" width="${DOT_PX}" height="${DOT_PX}" viewBox="0 0 14 14">` +
162    `${mark === '' ? '' : `<!--${mark}-->`}${body}</svg>`
163  if (d.kind === 'running') {
164    const swelling = swell === undefined ? '' : animate('r', PULSE_MS, -swell, [[0, `${R}`], [PULSE_MS / 2, `${R_SWELL}`], [PULSE_MS, `${R}`]], EASE)
165    const blinking =
166      blink === undefined ? '' : animate('fill', BLINK_MS, -blink, [[0, color], [BLINK_PEAK_MS, WHITE], [BLINK_MS, color]], EASE_BLINK)
167    return svg(disc(color, swelling + blinking))
168  }
169  if (end === undefined) return svg('')
170  const begin = -end
171  const ending = (attribute: string, steps: [number, string][]) => animate(attribute, FADE_MS, begin, steps)
172  if (d.kind === 'stopped') return svg(disc(color, ending('r', [[0, `${R}`], [FADE_MS, '2']]) + ending('opacity', [[0, '1'], [FADE_MS, '0']])))
173  // A flash: white, wider, gone; then the check or cross.
174  const flash = disc(
175    color,
176    ending('fill', [[0, color], [150, WHITE], [FADE_MS, WHITE]]) +
177      ending('r', [[0, `${R}`], [400, '6'], [FADE_MS, '6']]) +
178      ending('stroke-width', [[0, '1'], [400, '0'], [FADE_MS, '0']]) +
179      ending('opacity', [[0, '1'], [100, '1'], [400, '0'], [FADE_MS, '0']]),
180  )
181  const check = d.kind === 'done' ? stroke(color, 'M4 7.3 6.2 9.5 10.2 4.8', 10, begin) : stroke(color, 'M4.5 4.5 9.5 9.5M9.5 4.5 4.5 9.5', 8, begin)
182  return svg(flash + check)
183}
184
185// A dot's card, shown while it is hovered: the thought's name; its latest note and how
186// long ago that came, or, as its turn ends, its report and how it ended.
187function drawCard(draw: DotsDrawing, d: Dot): RenderElement {
188  const { Box, Text } = draw.ui
189  const { t } = d
190  const { now } = draw
191  const note = t.notes?.at(-1)
192  const isRunning = d.kind === 'running'
193  const said = isRunning ? note : t.lastText || note
194  const ago = (at: number | undefined) => (at === undefined || now === undefined ? undefined : agoOf(now - at))
195  const started = ago(t.startedAt)
196  const age = !isRunning ? WORD[d.kind] : note !== undefined ? ago(t.notedAt) : started === undefined ? undefined : `started ${started}`
197  return (
198    <Box position="absolute" display="none" hover={{ display: 'flex' }} flexDirection="column">
199      <Text color={t.color} bold>
200        {t.name}
201      </Text>
202      {said !== undefined && said !== '' ? <Text>{oneLine(said, 300)}</Text> : <Text dimColor>No notes yet</Text>}
203      {age !== undefined && <Text dimColor>{age}</Text>}
204    </Box>
205  )
206}
207
208// What the `thoughts` button is drawn with besides the dots': what opens the Thoughts
209// pane, and on the desktop the hit area (a Client, which register.tsx makes) for each of
210// its parts, by name.
211export type ButtonDrawing = DotsDrawing & {
212  open: () => void
213  hitOf?: (part: string) => RenderElement
214}
215
216// The key of the `thoughts` button.
217export const THOUGHTS_BUTTON = 'open-thoughts'
218const WORD_SHOWN = 'thoughts'
219
220// The fill of the desktop's Select field, white at 5% over the band (no theme colour
221// names it), and its 6px either side of its text from its outer edge, in the band's ch:
222// as thread-chat draws its menu beside its thread picker. The room between the button's
223// word and its first dot, and before its `+N`. The clear 3px right of a dot's disc in its
224// picture, in the band's ch, which a last dot's padding leaves out.
225const FIELD_FILL = 'rgba(255,255,255,0.05)'
226const FIELD_PADDING = 0.7
227const WORD_GAP = 0.5
228const MORE_GAP = 0.3
229const DOT_ROOM = 0.4
230
231// Whether the dots are pictures, in a button drawn of a Box: on the desktop, the one
232// surface with both pictures and hit areas.
233const isPicture = (draw: ButtonDrawing) => draw.hitOf !== undefined && 'Svg' in draw.ui
234
235// A dot on any surface but the desktop: a glyph.
236function drawGlyph(draw: DotsDrawing, d: Dot): RenderElement {
237  const { Text } = draw.ui
238  const { swell, blink } = runsOf(d, draw.now, FLICKER_MS)
239  const isSwell = swell !== undefined
240  return (
241    <Text color={blink !== undefined && !isSwell ? WHITE : d.t.color} {...(isSwell && { inverse: true })}>
242      {GLYPH[d.kind]}
243    </Text>
244  )
245}
246
247// The button on the desktop: a Box drawn as the dropdown beside it is (its fill and its
248// ring, stronger under the pointer, one line high), holding its word, its dots and its
249// `+N`, each in a Box of its own under a hit area that fills it, the padding inside them,
250// so a click anywhere in the ring opens the pane. Its own side padding is set to none, as
251// the desktop gives a bordered Box 12px either side unless told otherwise. A dot's Box
252// holds its picture, its card and its hit area: the pointer on the hit area is on the
253// dot, so the card shows.
254function drawField(draw: ButtonDrawing, shown: readonly Dot[], more: number): RenderElement {
255  const { ui, hitOf } = draw
256  if (!('Svg' in ui) || hitOf === undefined) return <ui.Box />
257  const { Box, Text, Svg } = ui
258  const hit = (part: string) => (
259    <Box position="absolute" top={0} left={0} width="100%" height="100%">
260      {hitOf(part)}
261    </Box>
262  )
263  const lastDot = more > 0 ? -1 : shown.length - 1
264  return (
265    <Box
266      key={THOUGHTS_BUTTON}
267      flexDirection="row"
268      alignItems="center"
269      flexShrink={0}
270      height={1}
271      paddingY={0}
272      paddingLeft={0}
273      paddingRight={0}
274      borderStyle="single"
275      backgroundColor={FIELD_FILL}
276      hover={{ borderColor: 'promptBorder' }}
277    >
278      <Box flexShrink={0} paddingLeft={FIELD_PADDING} paddingRight={shown.length === 0 ? FIELD_PADDING : WORD_GAP}>
279        <Text>{WORD_SHOWN}</Text>
280        {hit('word')}
281      </Box>
282      {shown.map((d, i) => (
283        <Box key={`${DOT}${d.t.id}`} flexShrink={0} {...(i === lastDot && { paddingRight: FIELD_PADDING - DOT_ROOM })}>
284          <Svg source={pictureOf(d, draw.now)} alt={`${d.t.name}: ${WORD[d.kind]}`} width={DOT_PX} height={DOT_PX} />
285          {drawCard(draw, d)}
286          {hit(`dot:${d.t.id}`)}
287        </Box>
288      ))}
289      {more > 0 && (
290        <Box flexShrink={0} paddingLeft={MORE_GAP} paddingRight={FIELD_PADDING}>
291          <Text dimColor>{`+${more}`}</Text>
292          {hit('more')}
293        </Box>
294      )}
295    </Box>
296  )
297}
298
299// The `thoughts` button, which opens the Thoughts pane: its word, then a dot for each
300// thought with one (none: the word alone), and how long until it must be drawn again.
301export function drawThoughtsButton(draw: ButtonDrawing, list: readonly Thought[]): { button: RenderElement; redrawIn?: number } {
302  const all = dotsOf(list, draw)
303  const shown = all.slice(0, DOTS_SHOWN)
304  const more = all.length - shown.length
305  const wait = redrawIn(shown, draw)
306  const timing = wait === undefined ? {} : { redrawIn: wait }
307  if (isPicture(draw)) return { button: drawField(draw, shown, more), ...timing }
308  const { Button, Text } = draw.ui
309  const dots: (string | RenderElement)[] = shown.length === 0 ? [] : [' ', ...shown.map(d => drawGlyph(draw, d))]
310  const rest = more > 0 ? [<Text dimColor>{` +${more}`}</Text>] : []
311  return {
312    button: (
313      <Button key={THOUGHTS_BUTTON} label={WORD_SHOWN} onPress={draw.open}>
314        {[WORD_SHOWN, ...dots, ...rest]}
315      </Button>
316    ),
317    ...timing,
318  }
319}
320
hooks/command.ts 171 lines
1import 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}
171
hooks/ui-switch.ts 112 lines
1import 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}
112
hooks/welcome.tsx 205 lines
1import 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: 'multitask', 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}
205
hooks/press.tsx 32 lines
1import type { ClientModule, JsonValue } from 'claude-code'
2
3type State = { isHeld: boolean }
4
5// An invisible hit area laid over a part of the desktop's `thoughts` button (its word, a
6// dot, its `+N`): a click, Enter or Space posts `{ press: true }` to the hooks module,
7// which opens the Thoughts pane. One per part, inside the part's own Box, so the pointer
8// over a dot is still over that dot, for its card.
9const Press: ClientModule<JsonValue, State> = (props, surface) => {
10  const { Text } = surface.elements
11  const press = () => surface.post({ press: true })
12
13  // A click presses once, whether the surface reports its down, its up or both.
14  surface.onPointer(e => {
15    if (e.button !== undefined && e.button !== 'left') return
16    if (e.type === 'down') {
17      surface.setState({ isHeld: true })
18      press()
19    } else if (e.type === 'up') {
20      if (surface.state?.isHeld === true) surface.setState({ isHeld: false })
21      else press()
22    }
23  })
24  surface.onKey(e => {
25    if (e.key === 'return' || e.key === ' ') press()
26  })
27
28  return <Text>{' '.repeat(Math.max(1, surface.columns))}</Text>
29}
30
31export default Press
32
types/index.d.ts 101 lines
1export type ThoughtStatus = 'running' | 'idle' | 'stopped' | 'failed'
2
3export type Thought = {
4  // the subagent's id, as $.agent.spawn answered it
5  id: string
6  name: string
7  task: string
8  color: string
9  status: ThoughtStatus
10  // messages the voice queued for when the thought finishes its current turn
11  queued: string[]
12  // the text of its latest finished turn: its report, question or problem
13  lastText: string
14  // its latest progress notes, oldest first, kept for following its work (each is relayed too)
15  notes: string[]
16  // whether it wrote a note after its latest report, which the Thoughts pane then no longer shows
17  notedSinceReport?: boolean
18  // the turn it is running now, from its latest model request
19  turnId: string | null
20  // a message to hand over once the interrupted turn has ended
21  interruptWith: string | null
22  // whether its queue waits no longer for a turn to end: the turn it waited for ended, and
23  // it goes to the thought at the next chance
24  isHandOverDue?: boolean
25  // when it was started, or its latest turn began; when it wrote its latest note; when its
26  // latest turn ended or it was stopped (ms, by $.clock). Absent for a thought kept before
27  // they were noted.
28  startedAt?: number
29  notedAt?: number
30  endedAt?: number
31}
32
33// What a thought said, waiting to reach the voice: a progress note, or the end of a
34// turn (isDone), with the text it ended on or none. A turn's end tells how many of the
35// voice's messages waited for it (pending), and whether they have reached the thought
36// since; a note about such messages still pending is isPending, dropped once they reach it.
37// isFromPerson: not the thought's but the person's own message to it, from the Thoughts pane.
38export type Update = {
39  thought: string
40  text: string
41  isDone?: boolean
42  pending?: number
43  isHandedOver?: boolean
44  isPending?: boolean
45  isFromPerson?: boolean
46}
47
48// A session's thoughts as kept in the store between runs of the app: when they were kept,
49// and the list, its oldest ended thoughts dropped past a bound.
50export type KeptThoughts = { at: number; thoughts: Thought[] }
51
52// What the voice was last told of a thought, by a relay or a what's-new note: its status,
53// its report and its latest progress note as they were then
54export type Heard = { status: ThoughtStatus; report: string; note: string }
55
56declare module 'claude-code' {
57  interface PluginState {
58    multitask: {
59      // whether the chat is in Multitask mode (the voice), not Focus; only while the mod is on
60      isOn: boolean
61      // whether the person turned the mod on in this chat with /multitask; null: never, so
62      // it is on as the default says
63      choice: boolean | null
64      // whether the mod is on in new chats, and in those never switched with /multitask
65      isEnabledByDefault: boolean
66      thoughts: Thought[]
67      inbox: Update[]
68      isMainBusy: boolean
69      // what the voice was last told of each thought, by thought id
70      heard: Record<string, Heard>
71      // whether the voice was last told, beside the person's message, that Multitask is on;
72      // false again after a compaction while on, so its whole part is told again
73      toldVoice: boolean
74      // thoughts the person opened in the Thoughts pane to show everything: a finished one's
75      // whole card instead of one line, a running one's whole task instead of its first line
76      expanded: string[]
77      // thoughts whose last report the person opened in the Thoughts pane to read whole,
78      // instead of its first line; a thought leaves it when it starts new work
79      openReports: string[]
80      // counts the minutes the Thoughts pane has stood open, so its ages are drawn afresh
81      paneTick: number
82      // counts the band's own redraws: a dot starting to blink, a thought's dot fading out as
83      // its turn ends, a blink or note on the terminal ending, the ages in the dots' hover
84      // cards each minute
85      bandTick: number
86      // the thought whose card in the Thoughts pane has its field open to tell it something; '' none
87      tellingTo: string
88      // whether the Thoughts pane lists every thought that is not running, not only the
89      // most recently ended (the person pressed `N more`)
90      showsAllEnded: boolean
91      // where the turn through the palette's first colours stands: the index of the next a
92      // thought takes, unless a running thought holds it
93      colorTurn: number
94      // the mods the welcome line above the prompt was last dismissed with, as this mod's
95      // store kept them (hooks/welcome.tsx); written as the session starts, so the other
96      // mods know this one is installed
97      welcome: { seen: string[] }
98    }
99  }
100}
101