SLOPSHOPPER

conversation-toolbar

A toolbar above the prompt: open or move the conversation to one of the 100 most recent folders, browse for a folder, subagent status dots, waiting clocks with…

bandguardcommandtoastpromptprocess
v0.14.3MITupdated 2026-10-17liyuanhe211/Claude_Desktop_Toolbar
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · conversation-toolbar
› fix the failing auth test and add an audit log call ╭────────────────────────────────────────────╮ │ conversation-toolbar │ ● conversation-toolbar: The usage endpoint answered 0 │ Copied transcript path: │ ● conversation-toolbar: Reading the Monitors from the │ /Users/dev\.claude\projects\-work-app\preview-session.jsonl │ ⏺ 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 › /copy-transcript-path ⎿ conversation-toolbar: Copied transcript path: /Users/dev\.claude\projects\-work-app\preview-session.jsonl ● conversation-toolbar: The usage endpoint answered 0 app ▾ [ Copied ✓ ] Model ? · ctx 97k/200k · 5h 31% · 1w ? Details ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
app ▾ [ Copied ✓ ] Model ? · ctx 97k/200k · 5h 31% · 1w ? Details
README

Conversation Toolbar

A Claude Code plugin (a hooks-module mod) that draws one row above the prompt, in the Claude desktop app's Code tab and in the terminal: a recent-folder list, status dots for the conversation's subagents, a button that copies the transcript path, and live usage widgets for the context window and the plan's rate limits.

The toolbar above the prompt: a Monitor's clock counting down, subagents finishing, the context growing, a ring's tooltip, the pinned details, Copy Transcript Path answering Copied, and the folder list

Features

ControlWhat it does
Folder listShows the current folder by its name alone (my-project; "No folder" in a scratch workspace) and lists the most recently used folders: the 64 newest of the 100 the plugin remembers, because Claude Code refuses a Select with more options. Picking one starts the conversation there before the first prompt, or moves the session there afterwards. A name too long for the row keeps its end behind an ellipsis.
Browse… (last entry of the folder list)Opens the Windows folder picker at the most recently used folder rather than the user profile. The picked folder is used and recorded the same way.
Subagent dotsOne dot per subagent of this conversation, oldest left, shown once the first one starts. Running dots pulse in orange, one after another; finished ones are green, failed ones red, stopped ones a grey ring (also a subagent that ended without a known result). A subagent that waits is a slowly pulsing orange ring, a teammate between turns a still one. Hover for a summary and one line per subagent, newest first: state, type, task, and for an ended one its duration. The newest 12 show, +n counting the older ones; the history keeps 50. The ↗ button right of the dots opens the desktop app's Background tasks pane, which lists the subagents with their tasks; in the terminal it only shows a toast. The pane also counts shell commands as tasks, so its count is higher than the number of dots.
Monitor clocksOne orange clock per Monitor still watching, left of the subagent dots, blinking at half the rate of a running dot, with the time left before the Monitor expires on its right: whole minutes rounded up (12m), seconds in the last minute (45s), ∞ for a Monitor without a deadline. A conversation that ended its turn with a Monitor still watching looks idle in the desktop sidebar; the clock shows that it is still waiting. Hover for one line per Monitor with its time left. The newest 6 show.
Program buttonsButtons that other programs on the machine ask for, right of the subagent dots, shown only while the program wants them. A long-running script, for example, can show Exporting report ... with the dots cycling, and a press asks it to stop. See Buttons for other programs.
Copy Transcript PathCopies the path of this conversation's transcript (.jsonl) to the clipboard; the button reads Copied ✓ for 2 s. Also available as /copy-transcript-path.
Usage widgets (right end)Left to right: a ring for the model's weekly quota (for example Fable), the token count, a context bar full at 500k tokens, a ring for the 5-hour limit and a ring for the weekly limit. Each ring shows its whole percentage inside.

Usage widgets

  • Colors follow the Codex usage widget: quotas green below 70 %, yellow to 85 %, red above; the context bar blue below 300k tokens, yellow to 400k, red above. A grey track shows only under 25 % used, and a missing reading shows ?, never 0.
  • Refresh: the context every 5 seconds; the plan windows every minute and after each turn, from one cached reading shared by all sessions.
  • Hover a ring or the bar for its figures in one sentence: 5 h limit: 12% (Reset in 3 h 30 min. Runs out in 1 h 5 min.)
  • Press the token count to pin a monospaced block with every figure, aligned:
  Context  : 350k / 1M
  5 h limit: 91% (Reset in 4 h 10 min. Runs out in       5 min.)
  7 d limit: 76% (Reset in 5 d 14 h.   Runs out in 10 h 45 min.)
  Fable    : 88% (Reset in 5 d 14 h.   Runs out in  4 h 39 min.)

"Runs out in" projects the average rate since the window began. A window that lasts until its reset at that rate says Lasts past reset., a full one Ran out..

  • In the terminal the widgets are one text line with a Details button.

Choosing a folder for a new conversation

The desktop app draws the row only after a session exists, so a new conversation that has not received any input shows no toolbar. Send /folder <name or path> as the first message: this creates the session without a model turn and opens the recent folder whose name matches (exact name, then a name starting with the argument, then a name containing it, then a path containing it) or the given absolute path. /folder alone just creates the session so the toolbar appears.

Moving uses the desktop app's own change_directory tool, so the app asks to approve the folder unless permissions are bypassed. The desktop app applies a move only at a turn you drive: during a running turn it waits for that turn to end; in an idle conversation it waits for your next message (a turn the toolbar itself submits does not count, so the toolbar does not try). Until then the list keeps the current folder, and a grey note beside it names the target, → Python_Lib Moving after your next message..., with its dots cycling. The note clears once the session is there. If the move is refused while a turn is running, the toolbar adds a note asking Claude to move the working directory once the turn is complete.

Buttons for other programs

A program shows a button by writing <id>.json into %TEMP%\claude_desktop_toolbar\buttons (the id is letters, digits, _, - and .), and removes it by deleting the file. The toolbar reads the folder every half second.

{
  "label": "Exporting report",
  "animation": "dots",
  "pressed_label": "Cancelling export",
  "session_id": "<the conversation's session id>",
  "expires_at_ms": 1792184415315
}
  • label is required. Rewrite the file to change it; write a temporary file and rename it so the toolbar never reads half a file.
  • animation: "dots" cycles ..., ., .. after the label; leave it out for a still label.
  • session_id limits the button to one conversation; leave it out to show it in every conversation.
  • expires_at_ms hides a button the program never removed; without it, the button hides 10 minutes after the file's last write.
  • A press writes <id>.pressed beside the file. The program watches for it, does what the press means, and deletes both files. Until then the button shows pressed_label.
  • At most four buttons show, the newest files first.

Requirements

  • Windows. The folder picker is a PowerShell script, and the folder handling expects Windows paths.
  • Claude Code 2.1.275 or later, which loads hooks-module plugins and installs them from a marketplace in one step. The Claude desktop app's Code tab runs a bundled Claude Code and draws the toolbar too.

Install

This repository is a one-plugin marketplace. In a terminal Claude Code session, type:

/plugin install conversation-toolbar --marketplace liyuanhe211/Claude_Desktop_Toolbar

Answer y to add the marketplace, then pick the user scope with Enter. The plugin is active in that session at once and in every session started afterwards, including the desktop app's Code tab.

From a shell:

claude plugin install conversation-toolbar --marketplace liyuanhe211/Claude_Desktop_Toolbar

In the desktop app, where the prompt does not accept /plugin: click + next to the prompt box, then Plugins, Add marketplace with liyuanhe211/Claude_Desktop_Toolbar, then Add plugin.

To update later, run claude plugin marketplace update and then claude plugin update conversation-toolbar, or use the same Plugins menu.

To run a local copy instead, name its folder in CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json (paths separated by ; on Windows), or start Claude Code with --plugin-dir <folder>.

What the plugin runs, reads, writes and sends

Everything below happens on your machine, except the one network request named under Network.

Programs it starts (Windows PowerShell, powershell.exe, and nothing else):

  • Browse… runs the plugin's own script scripts/Pick_Folder.ps1 (powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -STA -File <plugin>\scripts\Pick_Folder.ps1 -Title … [-InitialFolder <folder>]) to show the Windows folder picker. The script only shows the dialog and prints the folder you picked.
  • Copy Transcript Path first asks Claude Code to copy the path. Only where the surface cannot (the desktop app may refuse), it runs powershell -NoProfile -NonInteractive -Command "[Console]::InputEncoding = [System.Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())" with the path on standard input, which puts the path on the Windows clipboard.

Tools it calls itself (only on your click, both tools of the Claude desktop app):

  • ccd_directory › change_directory, when you pick a folder in the list, to open or move the conversation there. The desktop app asks you to approve the folder unless permissions are bypassed.
  • ccd_view › show_pane with { pane: "tasks" }, when you press ↗, to open the Background tasks pane.

Network: one request, GET https://api.anthropic.com/api/oauth/usage, the endpoint Claude Code's /usage reads, with the session's own authorization handled by the engine (the plugin never sees the token). It runs about once a minute and after a turn, and only reads the plan's usage figures. Nothing from the conversation, your files or your folders is sent anywhere.

What it reads:

  • The desktop app's session records under %APPDATA%\Claude\claude-code-sessions, once, for their folder paths only, to fill the folder list the first time.
  • The folder names of ~/.claude/projects, to find this conversation's transcript path.
  • This conversation's transcript (.jsonl), once per load, to find the Monitors still waiting; it stays on your machine.
  • The button folder %TEMP%\claude_desktop_toolbar\buttons, every half second, for buttons other programs ask for.
  • The session's own figures (context, rate limits, model, subagent list) through Claude Code.

What it writes:

  • It keeps its own store and session state under the Claude Code configuration directory, including recent folders, the cached usage reading, and records of the dots and clocks. All sessions on the machine share the store. Each session's starting folder, any folder picked here, and any folder a session moves to is added to the front of the list. Scratch workspaces, session worktrees, and temporary folders are never recorded.
  • A <id>.pressed file in %TEMP%\claude_desktop_toolbar\buttons when you press a program's button, holding the time and the session id. Only the program that asked for the button reads it; it is not a build, start-up, settings or instruction file.
  • When a move to another folder is refused during a turn, one user message in the conversation: "After this conversation turn is complete, move the working directory to <folder>."

Hooks: session.start registers /copy-transcript-path and /folder and starts the timers; agent.spawn, turn.start, turn.complete and session.measure update the dots, the folder list and the usage; tool.call on Monitor and TaskStop and prompt.submit with task notifications start and end the Monitor clocks. Every hook passes the event on unchanged: the plugin does not alter prompts, tool calls, their results or the system prompt.

Layout

  • .claude-plugin/plugin.json: the manifest (conversation-toolbar)
  • .claude-plugin/marketplace.json: makes this repository a one-plugin marketplace
  • hooks/register.tsx: the hooks: session start, turn boundaries, the slash commands, and the row above the prompt
  • hooks/folder_list.ts: path handling and the recent-folder list, with no engine calls
  • hooks/subagent_dots.ts: the subagent records and their dots, with no engine calls
  • hooks/usage_wheels.ts: the usage figures, their text and the SVG rings and bar, with no engine calls
  • hooks/external_buttons.ts: the ExternalButton class for buttons other programs ask for, with no engine calls
  • scripts/Pick_Folder.ps1: the folder picker Browse runs
  • types/index.d.ts: the $.state contract
  • tests/: claude plugin test suites

Development

From the repository folder:

claude plugin validate .
claude plugin test .

The engine writes its type declarations into .claude-plugin/types/ when it loads the plugin; after that, tsc -p . type-checks it.

License

MIT

Source 7 files
hooks/register.tsx 1308 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, McpToolResult, Register } from 'claude-code'
3
4import type {
5  CopyFeedback,
6  ExternalButtonRecord,
7  ExternalButtonState,
8  MonitorRecord,
9  RecentFolderList,
10  SubagentRecord,
11  UsageSnapshot,
12  UsageWindow,
13} from '../types'
14import {
15  findFolder,
16  folderIdentity,
17  folderOptionLabel,
18  isAbsoluteFolder,
19  isFolderInside,
20  isPickableFolder,
21  joinWindowsPath,
22  mergeFolderLists,
23  normalizeFolder,
24  placeFolderFirst,
25  projectDirectoryName,
26  rankSessionFolders,
27  readFolderList,
28  readSessionRecordFolder,
29  type SessionRecordFolder,
30} from './folder_list'
31import {
32  BAR_HEIGHT_PX,
33  BAR_WIDTH_PX,
34  RING_SIZE_PX,
35  contextBarSvg,
36  detailBlockSize,
37  detailBlockSvg,
38  mergeWindows,
39  parseUsageEndpoint,
40  quotaRingSvg,
41  usageText,
42  usageWidgets,
43} from './usage_wheels'
44import {
45  DOTS_HEIGHT_PX,
46  mergeListedAgents,
47  recordSpawn,
48  recordTurnEnd,
49  subagentDotsSvg,
50  subagentDotsWidth,
51  subagentLines,
52  subagentSummary,
53  subagentText,
54} from './subagent_dots'
55import {
56  activeMonitors,
57  applyEndings,
58  expireMonitors,
59  isCountingSeconds,
60  mergeMonitorRecords,
61  monitorClocksSvg,
62  monitorClocksWidth,
63  monitorLines,
64  monitorSummary,
65  monitorText,
66  parseNotificationEndings,
67  parseTranscriptMonitors,
68  readMonitorStart,
69  recordMonitorEnd,
70  recordMonitorStart,
71} from './monitor_clock'
72import {
73  BUTTON_FILE_SUFFIX,
74  BUTTON_FOLDER_NAME,
75  BUTTON_SUBFOLDER_NAME,
76  EXTERNAL_BUTTON_POLL_MS,
77  ExternalButton,
78  PRESS_FILE_SUFFIX,
79  buttonRecords,
80  isAnimating,
81  pressNote,
82  type ButtonFile,
83} from './external_buttons'
84
85type CopySurface = Parameters<EngineInterface['ui']['copy']>[0]['surface']
86
87const STORE_KEY_RECENT_FOLDERS = 'recentFolders'
88const STORE_KEY_IS_SEEDED = 'isSeededFromDesktopSessions'
89const STORE_KEY_USAGE_ENDPOINT = 'usageEndpoint'
90// The plan usage endpoint the engine's /usage reads (five_hour, seven_day and
91// the model-scoped weekly windows in limits[]); the bearer header is the engine's.
92const USAGE_ENDPOINT_INTERVAL_MS = 60_000
93const SESSION_USAGE_INTERVAL_MS = 5_000
94// The value in the folder list that opens the folder picker.
95const BROWSE_OPTION = '<browse for a folder>'
96// The engine refuses a Select with more than 64 options (and with it the whole
97// band), so the list draws at most that many; the store still keeps 100.
98const SELECT_OPTION_LIMIT = 64
99// Newest records first; enough to cover months of sessions without reading
100// every record the desktop app has ever kept.
101const SESSION_RECORD_READ_LIMIT = 1500
102const FOLDER_PICKER_TIMEOUT_MS = 10 * 60 * 1000
103const NO_FOLDER_CHOSEN = '<no folder chosen>'
104// Columns the folder labels may take: what the band leaves beside the Browse
105// and Copy buttons, kept between a readable minimum and a tidy maximum.
106const COLUMNS_BESIDE_FOLDER_LABEL = 40
107const MINIMUM_FOLDER_LABEL_WIDTH = 24
108const MAXIMUM_FOLDER_LABEL_WIDTH = 72
109
110const recentFoldersState = { plugin: 'conversation-toolbar', key: 'recentFolders' } as const
111const usageAtom = atom({ plugin: 'conversation-toolbar', key: 'usage' } as const, null as UsageSnapshot | null)
112// Whether the usage detail row stays open (toggled by the token-count button).
113const usageDetailsPinnedAtom = atom({ plugin: 'conversation-toolbar', key: 'usageDetailsPinned' } as const, false)
114// The folder a move is waiting to reach, and the dots of its note.
115const pendingMoveAtom = atom({ plugin: 'conversation-toolbar', key: 'pendingMove' } as const, null as string | null)
116const movingDotsAtom = atom({ plugin: 'conversation-toolbar', key: 'movingDots' } as const, 1)
117const MOVING_DOTS_MAXIMUM = 6
118const MOVING_DOTS_INTERVAL_MS = 400
119// This session's subagents for the dots, refreshed from `$.agent.list()`.
120const subagentsAtom = atom({ plugin: 'conversation-toolbar', key: 'subagents' } as const, [] as SubagentRecord[])
121const SUBAGENT_LIST_INTERVAL_MS = 2_000
122// The desktop app's session view server and its pane tool.
123const TASKS_PANE_SERVER = 'ccd_view'
124const TASKS_PANE_TOOL = 'show_pane'
125// The button beside the dots that opens the pane: an arrow out to the pane
126// (a math-axis glyph, so it sits on the dots' centre line; the trigram ☰ sat above it).
127const OPEN_TASKS_GLYPH = '↗'
128// Lines the dots' tooltip lists below the summary, newest first.
129const SUBAGENT_TOOLTIP_LINE_LIMIT = 15
130// The main conversation's Monitors for the waiting clocks.
131const monitorsAtom = atom({ plugin: 'conversation-toolbar', key: 'monitors' } as const, [] as MonitorRecord[])
132// How often the clocks' tooltip (waited, stops in) is redrawn while one waits.
133// A waiting clock's countdown in minutes redraws this often; in its last
134// minute, every poll.
135const MONITOR_COUNTDOWN_REFRESH_MS = 10_000
136// The Copy Transcript Path button says how the copy went for this long.
137const copyFeedbackAtom = atom({ plugin: 'conversation-toolbar', key: 'copyFeedback' } as const, null as CopyFeedback | null)
138const COPY_FEEDBACK_DURATION_MS = 2_000
139const COPY_BUTTON_LABELS: Record<CopyFeedback | 'idle', string> = {
140  idle: 'Copy Transcript Path',
141  copied: 'Copied ✓',
142  failed: 'Copy failed',
143}
144
145// Buttons other programs ask for through the button folder, and the frame
146// their dots draw.
147const NO_EXTERNAL_BUTTONS: ExternalButtonState = { buttons: [], frame: 0 }
148const externalButtonsAtom = atom({ plugin: 'conversation-toolbar', key: 'externalButtons' } as const, NO_EXTERNAL_BUTTONS)
149
150type MoveOutcome = { isMoved: true } | { isMoved: false; reason: string; isDeclined: boolean }
151
152function describeError(error: unknown): string {
153  return error instanceof Error ? error.message : String(error)
154}
155
156function moveAfterTurnMessage(folder: string): string {
157  return `After this conversation turn is complete, move the working directory to ${folder}.`
158}
159async function resolveConfigDirectory($: EngineInterface): Promise<string> {
160  const configured = await $.env.get('CLAUDE_CONFIG_DIR')
161  if (configured) {
162    return configured
163  }
164  const userProfile = await $.env.get('USERPROFILE')
165  const home = userProfile ?? (await $.env.get('HOME')) ?? ''
166
167  return joinWindowsPath(home, '.claude')
168}
169
170async function resolveTranscriptPath($: EngineInterface): Promise<string> {
171  const sessionId = await $.session.id()
172  const projectsDirectory = joinWindowsPath(await resolveConfigDirectory($), 'projects')
173  const fileName = `${sessionId}.jsonl`
174
175  const expected = joinWindowsPath(
176    projectsDirectory,
177    projectDirectoryName(await $.session.cwd()),
178    fileName,
179  )
180  if (await $.fs.exists(expected)) {
181    return expected
182  }
183
184  // The working directory may have changed since the session started; search
185  // every project folder for this session's transcript.
186  const entries = await $.fs.list(projectsDirectory).catch(() => [])
187  for (const entry of entries) {
188    if (entry.kind !== 'dir') {
189      continue
190    }
191    const candidate = joinWindowsPath(projectsDirectory, entry.name, fileName)
192    if (await $.fs.exists(candidate)) {
193      return candidate
194    }
195  }
196
197  return expected
198}
199
200async function copyToClipboard(
201  $: EngineInterface,
202  text: string,
203  surface?: CopySurface,
204): Promise<boolean> {
205  const copied = await $.ui.copy({ text, surface }).catch(() => ({ isCopied: false }))
206  if (copied.isCopied) {
207    return true
208  }
209
210  // A remote surface such as the desktop app may not take the copy; fall back
211  // to the Windows clipboard directly.
212  const script =
213    '[Console]::InputEncoding = [System.Text.Encoding]::UTF8; ' +
214    'Set-Clipboard -Value ([Console]::In.ReadToEnd())'
215  const result = await $.process
216    .run(['powershell', '-NoProfile', '-NonInteractive', '-Command', script], {
217      stdin: text,
218      timeoutMs: 15000,
219    })
220    .catch(() => undefined)
221
222  return result?.exitCode === 0
223}
224
225// Module variables start over on a hot reload; a feedback left showing then
226// clears at the next press.
227let copyFeedbackTimer: ReturnType<EngineInterface['clock']['after']> | null = null
228
229// The button itself says how the copy went, so a press always shows something
230// where the user is looking; the toast carries the path.
231async function showCopyFeedback($: EngineInterface, feedback: CopyFeedback): Promise<void> {
232  copyFeedbackTimer?.cancel()
233  await update($, copyFeedbackAtom, () => feedback)
234  copyFeedbackTimer = $.clock.after(COPY_FEEDBACK_DURATION_MS, () => {
235    copyFeedbackTimer = null
236    void update($, copyFeedbackAtom, () => null)
237  })
238}
239
240async function copyTranscriptPath($: EngineInterface, surface?: CopySurface): Promise<string> {
241  const path = await resolveTranscriptPath($)
242  const isCopied = await copyToClipboard($, path, surface)
243  const message = isCopied
244    ? `Copied transcript path: ${path}`
245    : `Could not copy; the transcript path is ${path}`
246  await showCopyFeedback($, isCopied ? 'copied' : 'failed').catch(() => undefined)
247  $.ui.toast(message)
248
249  return message
250}
251
252async function resolveAppDataDirectory($: EngineInterface): Promise<string | undefined> {
253  return (await $.env.get('APPDATA')) || undefined
254}
255
256async function resolveScratchRoot($: EngineInterface): Promise<string | undefined> {
257  const appData = await resolveAppDataDirectory($)
258
259  return appData === undefined ? undefined : joinWindowsPath(appData, 'Claude', 'scratch-workspaces')
260}
261
262async function resolveTemporaryRoots($: EngineInterface): Promise<string[]> {
263  // $.env.get takes a literal name, so the module's variables can be listed.
264  const values = [
265    await $.env.get('TEMP').catch(() => undefined),
266    await $.env.get('TMP').catch(() => undefined),
267    await $.env.get('CLAUDE_CODE_TMPDIR').catch(() => undefined),
268  ]
269
270  return values.filter((value): value is string => typeof value === 'string' && value !== '')
271}
272
273// What a person can pick: the stored list less scratch, worktree and temporary
274// folders (older versions recorded some of those).
275async function pickableFolderFilter($: EngineInterface): Promise<(folder: string) => boolean> {
276  const scratchRoot = await resolveScratchRoot($)
277  const temporaryRoots = await resolveTemporaryRoots($)
278
279  return folder => isPickableFolder(folder, scratchRoot, temporaryRoots)
280}
281
282async function readStoredFolders($: EngineInterface): Promise<RecentFolderList> {
283  const isPickable = await pickableFolderFilter($)
284
285  return readFolderList(await $.store.get(STORE_KEY_RECENT_FOLDERS)).filter(isPickable)
286}
287
288// Other sessions write the same store, so every change starts from what it
289// holds now rather than from this session's copy.
290async function saveRecentFolders(
291  $: EngineInterface,
292  change: (stored: RecentFolderList) => RecentFolderList,
293): Promise<void> {
294  const folders = change(await readStoredFolders($))
295  await $.store.set(STORE_KEY_RECENT_FOLDERS, folders)
296  await $.state.set(recentFoldersState, folders)
297}
298
299async function recordFolder($: EngineInterface, folder: string): Promise<void> {
300  if (!(await pickableFolderFilter($))(folder)) {
301    return
302  }
303  await saveRecentFolders($, stored => placeFolderFirst(stored, folder))
304}
305
306type SessionRecordFile = { path: string; mtimeMs: number }
307
308// <APPDATA>\Claude\claude-code-sessions\<account>\<organization>\local_<id>.json
309async function listSessionRecordFiles(
310  $: EngineInterface,
311  sessionsRoot: string,
312): Promise<SessionRecordFile[]> {
313  const files: SessionRecordFile[] = []
314  for (const account of await $.fs.list(sessionsRoot).catch(() => [])) {
315    if (account.kind !== 'dir') {
316      continue
317    }
318    const accountPath = joinWindowsPath(sessionsRoot, account.name)
319    for (const organization of await $.fs.list(accountPath).catch(() => [])) {
320      if (organization.kind !== 'dir') {
321        continue
322      }
323      const organizationPath = joinWindowsPath(accountPath, organization.name)
324      for (const entry of await $.fs.list(organizationPath).catch(() => [])) {
325        if (entry.kind === 'file' && /^local_.+\.json$/.test(entry.name)) {
326          files.push({ path: joinWindowsPath(organizationPath, entry.name), mtimeMs: entry.mtimeMs })
327        }
328      }
329    }
330  }
331
332  return files
333}
334
335// The first time the toolbar loads, the folders of the desktop app's own
336// session records fill the list behind the ones already recorded.
337async function seedFromDesktopSessions($: EngineInterface): Promise<void> {
338  if ((await $.store.get(STORE_KEY_IS_SEEDED)) === true) {
339    return
340  }
341  const appData = await resolveAppDataDirectory($)
342  if (appData === undefined) {
343    return
344  }
345  const sessionsRoot = joinWindowsPath(appData, 'Claude', 'claude-code-sessions')
346  const files = (await listSessionRecordFiles($, sessionsRoot))
347    .sort((first, second) => second.mtimeMs - first.mtimeMs)
348    .slice(0, SESSION_RECORD_READ_LIMIT)
349  const records: SessionRecordFolder[] = []
350  for (const file of files) {
351    const text = await $.fs.read(file.path).catch(() => undefined)
352    const record = typeof text === 'string' ? readSessionRecordFolder(text, file.mtimeMs) : null
353    if (record !== null) {
354      records.push(record)
355    }
356  }
357  const seeded = rankSessionFolders(records).filter(await pickableFolderFilter($))
358  await saveRecentFolders($, stored => mergeFolderLists(stored, seeded))
359  await $.store.set(STORE_KEY_IS_SEEDED, true)
360}
361
362function describeToolResult(result: McpToolResult): string {
363  return result.content
364    .map(block => (typeof block.text === 'string' ? block.text : ''))
365    .join(' ')
366    .trim()
367}
368
369// The desktop app's own tool: it asks the person to approve the folder (unless
370// permissions are bypassed) and moves the session when the current turn ends.
371async function moveSession($: EngineInterface, folder: string): Promise<MoveOutcome> {
372  try {
373    const result = await $.mcp.call('ccd_directory', 'change_directory', { path: folder })
374    if (!result.isError) {
375      return { isMoved: true }
376    }
377    const reason = describeToolResult(result) || 'the desktop app refused the move'
378
379    return { isMoved: false, reason, isDeclined: /declin|denied|reject|cancel/i.test(reason) }
380  } catch (error) {
381    return { isMoved: false, reason: describeError(error), isDeclined: false }
382  }
383}
384
385async function hasConversationStarted($: EngineInterface, isWorking: boolean): Promise<boolean> {
386  return isWorking || (await $.session.turns()) > 0
387}
388
389// Module variables start over on a hot reload; session.start restarts the
390// dots of a move still pending.
391let movingDotsTimer: ReturnType<EngineInterface['clock']['every']> | null = null
392
393function startMovingDots($: EngineInterface): void {
394  if (movingDotsTimer === null) {
395    movingDotsTimer = $.clock.every(MOVING_DOTS_INTERVAL_MS, () =>
396      void update($, movingDotsAtom, dots => ((dots ?? 1) % MOVING_DOTS_MAXIMUM) + 1),
397    )
398  }
399}
400
401function stopMovingDots(): void {
402  movingDotsTimer?.cancel()
403  movingDotsTimer = null
404}
405
406// The desktop app moves the session when a turn ends, not at once: the toolbar
407// shows the target beside the folder list until the session is there.
408async function markPendingMove($: EngineInterface, target: string): Promise<void> {
409  const root = normalizeFolder(await $.session.root().catch(() => ''))
410  if (folderIdentity(root) === folderIdentity(target)) {
411    await update($, pendingMoveAtom, () => null)
412    stopMovingDots()
413    return
414  }
415  await update($, pendingMoveAtom, () => target)
416  startMovingDots($)
417}
418
419// Clears the pending move once the session has reached it.
420async function settlePendingMove($: EngineInterface): Promise<void> {
421  const pending = await read($, pendingMoveAtom)
422  if (pending === null) {
423    stopMovingDots()
424    return
425  }
426  const root = normalizeFolder(await $.session.root())
427  if (folderIdentity(root) === folderIdentity(pending)) {
428    await update($, pendingMoveAtom, () => null)
429    stopMovingDots()
430  } else {
431    startMovingDots($)
432  }
433}
434
435function whenMoveApplies(isWorking: boolean): string {
436  return isWorking ? 'when this turn ends' : 'after your next message'
437}
438
439// What happened, for a command's output; `isShownInToolbar` when the toolbar
440// already shows it (the folder list or the pending-move note), so no toast.
441type FolderOpening = { message: string; isShownInToolbar: boolean }
442
443async function openFolder($: EngineInterface, folder: string, isWorking: boolean): Promise<FolderOpening> {
444  const target = normalizeFolder(folder)
445  await recordFolder($, target).catch(() => undefined)
446  const hasStarted = await hasConversationStarted($, isWorking)
447  const outcome = await moveSession($, target)
448  if (outcome.isMoved) {
449    await markPendingMove($, target).catch(() => undefined)
450    // A turn a plugin submits does not make the desktop app apply the move;
451    // only a message the person sends does.
452    const message = hasStarted
453      ? `This conversation moves to ${target} ${whenMoveApplies(isWorking)}`
454      : `This conversation starts in ${target}`
455    return { message, isShownInToolbar: true }
456  }
457  if (outcome.isDeclined) {
458    return { message: `The move to ${target} was declined`, isShownInToolbar: false }
459  }
460  if (!hasStarted) {
461    return { message: `Could not open ${target}: ${outcome.reason}`, isShownInToolbar: false }
462  }
463
464  // A running conversation may refuse the move; leave the model a note to
465  // make it once this turn is done.
466  const appended = await $.session
467    .append({
468      message: { type: 'user', content: [{ type: 'text', text: moveAfterTurnMessage(target) }] },
469    })
470    .catch((error: unknown) => ({ deny: describeError(error) }))
471  if ('deny' in appended) {
472    return { message: `Could not move to ${target}: ${outcome.reason}`, isShownInToolbar: false }
473  }
474  await markPendingMove($, target).catch(() => undefined)
475
476  return {
477    message: `Could not move now (${outcome.reason}); Claude will move to ${target} after this turn`,
478    isShownInToolbar: true,
479  }
480}
481
482// Toasts only what the toolbar does not show: a failed or declined move.
483async function openFolderWithToast($: EngineInterface, folder: string, isWorking: boolean): Promise<void> {
484  const opening = await openFolder($, folder, isWorking)
485  if (!opening.isShownInToolbar) {
486    $.ui.toast(opening.message)
487  }
488}
489
490// `/folder <name or path>`: the toolbar is drawn only once a session exists,
491// so a new conversation can pick its folder with this as its first message.
492async function runFolderCommand($: EngineInterface, query: string): Promise<string> {
493  const wanted = query.trim().replace(/^"(.*)"$/, '$1')
494  if (wanted === '') {
495    return 'Pick a folder in the toolbar above the prompt, or name one: /folder <name or path>'
496  }
497  const folder = isAbsoluteFolder(wanted) ? wanted : findFolder(await readStoredFolders($), wanted)
498  if (folder === undefined) {
499    return `No recent folder matches "${wanted}"`
500  }
501  if (!(await $.fs.exists(folder).catch(() => false))) {
502    return `${folder} does not exist`
503  }
504
505  return (await openFolder($, folder, false)).message
506}
507
508async function pickFolder($: EngineInterface, initialFolder: string | undefined): Promise<string | null> {
509  const script = joinWindowsPath($.plugin.root, 'scripts', 'Pick_Folder.ps1')
510  const argv = [
511    'powershell',
512    '-NoProfile',
513    '-NonInteractive',
514    '-ExecutionPolicy',
515    'Bypass',
516    '-STA',
517    '-File',
518    script,
519    '-Title',
520    'Choose a folder for this conversation',
521  ]
522  if (initialFolder !== undefined) {
523    argv.push('-InitialFolder', initialFolder)
524  }
525  const result = await $.process.run(argv, { timeoutMs: FOLDER_PICKER_TIMEOUT_MS })
526  if (result.exitCode !== 0) {
527    throw new Error(result.stderr.trim() || `the folder picker exited with code ${result.exitCode}`)
528  }
529  const folder = result.stdout.trim()
530
531  return folder === '' ? null : folder
532}
533
534async function browseAndOpen($: EngineInterface, isWorking: boolean): Promise<void> {
535  try {
536    const lastUsedFolder = (await readStoredFolders($))[0]
537    const folder = await pickFolder($, lastUsedFolder)
538    if (folder !== null) {
539      await openFolderWithToast($, folder, isWorking)
540    }
541  } catch (error) {
542    $.ui.toast(`Could not show the folder picker: ${describeError(error)}`)
543  }
544}
545
546// Module variables start over on a hot reload; this one only saves a redundant
547// store write.
548let lastRecordedFolder = ''
549
550async function recordCurrentFolder($: EngineInterface): Promise<void> {
551  const root = normalizeFolder(await $.session.root())
552  if (folderIdentity(root) === lastRecordedFolder) {
553    return
554  }
555  lastRecordedFolder = folderIdentity(root)
556  await recordFolder($, root)
557}
558
559function usageSnapshot(usage: {
560  context: { tokens?: number; window: number; percent?: number }
561  rateLimits: readonly { kind: string; percentUsed: number; resetsAt?: string }[]
562}): UsageSnapshot {
563  return {
564    context: { tokens: usage.context.tokens, window: usage.context.window, percent: usage.context.percent },
565    rateLimits: usage.rateLimits.map(window => ({ kind: window.kind, percentUsed: window.percentUsed, resetsAt: window.resetsAt })),
566  }
567}
568
569type UsageEndpointCache = { fetchedAtMs: number; windows: UsageWindow[] }
570
571function readUsageEndpointCache(value: unknown): UsageEndpointCache | null {
572  if (typeof value !== 'object' || value === null) {
573    return null
574  }
575  const cache = value as { fetchedAtMs?: unknown; windows?: unknown }
576  if (typeof cache.fetchedAtMs !== 'number' || !Array.isArray(cache.windows) || cache.fetchedAtMs < processStartedAtMs) {
577    return null
578  }
579  const windows = cache.windows.filter(
580    (window): window is UsageWindow =>
581      typeof window === 'object' && window !== null && typeof window.kind === 'string' && typeof window.percentUsed === 'number',
582  )
583
584  return { fetchedAtMs: cache.fetchedAtMs, windows }
585}
586
587// Module variables start over on a hot reload, as the timers do.
588// The shared cache does not say whose account it read, and switching accounts
589// starts the sessions over, so an answer from before this process may be
590// another account's: it is neither shown nor taken as fresh.
591const processStartedAtMs = Date.now()
592let latestSessionUsage: UsageSnapshot | null = null
593let usageEndpointRequest: Promise<void> | null = null
594// The session's window readings come from response headers, so they are fresh
595// only during a turn and as it ends; 0 before any turn of this process.
596let isTurnRunning = false
597let lastTurnCompletedAtMs = 0
598
599function sessionWindowsReadAtMs(): number {
600  return isTurnRunning ? Date.now() : lastTurnCompletedAtMs
601}
602
603// The plan's usage windows, the Fable weekly quota among them, from the same
604// endpoint the engine's /usage reads. Every session shares one cached answer,
605// so the endpoint is asked at most once a minute however many sessions run.
606async function refreshUsageEndpoint($: EngineInterface, maximumAgeMs: number): Promise<void> {
607  const cached = readUsageEndpointCache(await $.store.get(STORE_KEY_USAGE_ENDPOINT))
608  if (cached !== null && Date.now() - cached.fetchedAtMs < maximumAgeMs) {
609    return
610  }
611  if (usageEndpointRequest !== null) {
612    return usageEndpointRequest
613  }
614  usageEndpointRequest = (async () => {
615    try {
616      const authorization = await $.session.authorize()
617      if (authorization === null) {
618        return
619      }
620      // The endpoint Claude Code's /usage reads, with the session's own authorization.
621      const response = await $.http.fetch('https://api.anthropic.com/api/oauth/usage', {
622        auth: authorization.handle,
623        headers: { 'Content-Type': 'application/json', 'anthropic-beta': 'oauth-2025-04-20' },
624      })
625      if (!response.ok) {
626        $.ui.log(`The usage endpoint answered ${response.status}`, { to: 'debug' })
627        return
628      }
629      const windows = parseUsageEndpoint(JSON.parse(response.text))
630      await $.store.set(STORE_KEY_USAGE_ENDPOINT, { fetchedAtMs: Date.now(), windows })
631    } catch (error: unknown) {
632      $.ui.log(`Reading the usage endpoint failed: ${describeError(error)}`, { to: 'debug' })
633    } finally {
634      usageEndpointRequest = null
635    }
636  })()
637
638  return usageEndpointRequest
639}
640
641// The snapshot the widgets draw: the session's context, and the header and
642// endpoint windows, the fresher first. Not written to state from a render.
643async function composeUsage($: EngineInterface): Promise<UsageSnapshot | null> {
644  if (latestSessionUsage === null) {
645    latestSessionUsage = usageSnapshot(await $.session.usage())
646  }
647  const cached = readUsageEndpointCache(await $.store.get(STORE_KEY_USAGE_ENDPOINT))
648
649  return {
650    context: latestSessionUsage.context,
651    rateLimits: mergeWindows(latestSessionUsage.rateLimits, cached?.windows ?? [], sessionWindowsReadAtMs(), cached?.fetchedAtMs ?? 0),
652  }
653}
654
655// Writes the snapshot only when a figure changed, so a quiet session does not redraw.
656async function publishUsage($: EngineInterface): Promise<void> {
657  try {
658    const snapshot = await composeUsage($)
659    const current = await read($, usageAtom)
660    if (JSON.stringify(current) !== JSON.stringify(snapshot)) {
661      await update($, usageAtom, () => snapshot)
662    }
663  } catch (error: unknown) {
664    $.ui.log(`Updating the usage widgets failed: ${describeError(error)}`, { to: 'debug' })
665  }
666}
667
668async function refreshSessionUsage($: EngineInterface): Promise<void> {
669  try {
670    latestSessionUsage = usageSnapshot(await $.session.usage())
671  } catch (error: unknown) {
672    $.ui.log(`Reading the session usage failed: ${describeError(error)}`, { to: 'debug' })
673    return
674  }
675  await publishUsage($)
676}
677
678// Takes the engine's agent list into the dots' records, writing only when a
679// state changed so a quiet session does not redraw.
680async function refreshSubagents($: EngineInterface): Promise<void> {
681  try {
682    const listed = await $.agent.list()
683    const nowMs = Date.now()
684    const current = (await read($, subagentsAtom)) ?? []
685    if (JSON.stringify(mergeListedAgents(current, listed, nowMs)) !== JSON.stringify(current)) {
686      await writeSubagents($, records => mergeListedAgents(records, listed, nowMs))
687    }
688  } catch (error: unknown) {
689    $.ui.log(`Reading the subagent list failed: ${describeError(error)}`, { to: 'debug' })
690  }
691}
692
693// Writes the dots' records and asks for a redraw: the desktop app does not
694// redraw the band on the state change alone, so a dot would wait for the
695// next unrelated redraw (a usage figure, a turn boundary).
696async function writeSubagents(
697  $: EngineInterface,
698  change: (records: SubagentRecord[]) => SubagentRecord[],
699): Promise<void> {
700  await update($, subagentsAtom, records => change(records ?? []))
701  $.ui.invalidate('ui.render')
702}
703
704// Module variables start over on a hot reload, which does not run
705// session.start again; every turn boundary makes sure the list is polled.
706let subagentListTimer: ReturnType<EngineInterface['clock']['every']> | null = null
707
708function ensureSubagentPolling($: EngineInterface): void {
709  if (subagentListTimer === null) {
710    subagentListTimer = $.clock.every(SUBAGENT_LIST_INTERVAL_MS, () => {
711      void refreshSubagents($)
712      void checkMonitorDeadlines($)
713    })
714    void refreshSubagents($)
715  }
716  ensureMonitorBackfill($)
717}
718
719// Writes the clocks' records and asks for a redraw, as writeSubagents does.
720async function writeMonitors(
721  $: EngineInterface,
722  change: (records: MonitorRecord[]) => MonitorRecord[],
723): Promise<void> {
724  await update($, monitorsAtom, records => change(records ?? []))
725  $.ui.invalidate('ui.render')
726}
727
728// Module variables start over on a hot reload, and a Monitor started before
729// this module loaded raised no tool.call here: once per load, the transcript
730// gives the Monitors back.
731let monitorBackfill: Promise<void> | null = null
732
733function ensureMonitorBackfill($: EngineInterface): void {
734  if (monitorBackfill !== null) {
735    return
736  }
737  monitorBackfill = (async () => {
738    try {
739      const transcript = await $.fs.read(await resolveTranscriptPath($))
740      const nowMs = Date.now()
741      const parsed = expireMonitors(parseTranscriptMonitors(typeof transcript === 'string' ? transcript : '', nowMs), nowMs)
742      const current = (await read($, monitorsAtom)) ?? []
743      const merged = mergeMonitorRecords(current, parsed)
744      if (JSON.stringify(merged) !== JSON.stringify(current)) {
745        await writeMonitors($, () => merged)
746      }
747    } catch (error: unknown) {
748      $.ui.log(`Reading the Monitors from the transcript failed: ${describeError(error)}`, { to: 'debug' })
749    }
750  })()
751}
752
753let lastMonitorRedrawMs = 0
754
755// Ends the clocks past their deadline, and redraws a waiting clock now and
756// then so its countdown and tooltip move on.
757async function checkMonitorDeadlines($: EngineInterface): Promise<void> {
758  try {
759    const nowMs = Date.now()
760    const current = (await read($, monitorsAtom)) ?? []
761    const expired = expireMonitors(current, nowMs)
762    if (JSON.stringify(expired) !== JSON.stringify(current)) {
763      lastMonitorRedrawMs = nowMs
764      await writeMonitors($, records => expireMonitors(records, nowMs))
765    } else if (
766      activeMonitors(current).length > 0 &&
767      (isCountingSeconds(activeMonitors(current), nowMs) || nowMs - lastMonitorRedrawMs >= MONITOR_COUNTDOWN_REFRESH_MS)
768    ) {
769      lastMonitorRedrawMs = nowMs
770      $.ui.invalidate('ui.render')
771    }
772  } catch (error: unknown) {
773    $.ui.log(`Checking the Monitor deadlines failed: ${describeError(error)}`, { to: 'debug' })
774  }
775}
776
777function monitorTooltip(active: readonly MonitorRecord[], nowMs: number): string {
778  return [monitorSummary(active), ...monitorLines(active, nowMs)].join('\n')
779}
780
781async function resolveButtonFolder($: EngineInterface): Promise<string | undefined> {
782  const temporary = (await $.env.get('TEMP').catch(() => undefined)) || (await $.env.get('TMP').catch(() => undefined))
783
784  return temporary ? joinWindowsPath(temporary, BUTTON_FOLDER_NAME, BUTTON_SUBFOLDER_NAME) : undefined
785}
786
787// Module variables start over on a hot reload; every turn boundary and draw
788// makes sure the button folder is polled.
789let externalButtonTimer: ReturnType<EngineInterface['clock']['every']> | null = null
790let isReadingExternalButtons = false
791
792function ensureExternalButtonPolling($: EngineInterface): void {
793  if (externalButtonTimer === null) {
794    externalButtonTimer = $.clock.every(EXTERNAL_BUTTON_POLL_MS, () => void refreshExternalButtons($))
795    void refreshExternalButtons($)
796  }
797}
798
799// Reads the button folder (only the files there, usually none) and writes the
800// buttons when they changed, or every poll while one animates: each poll moves
801// the dots one frame on, so a late timer never skips a frame.
802async function refreshExternalButtons($: EngineInterface): Promise<void> {
803  if (isReadingExternalButtons) {
804    return
805  }
806  isReadingExternalButtons = true
807  try {
808    const folder = await resolveButtonFolder($)
809    const entries = folder === undefined ? [] : await $.fs.list(folder).catch(() => [])
810    const pressFileNames = new Set(
811      entries.filter(entry => entry.kind === 'file' && entry.name.endsWith(PRESS_FILE_SUFFIX)).map(entry => entry.name),
812    )
813    const files: ButtonFile[] = []
814    for (const entry of entries) {
815      if (folder === undefined || entry.kind !== 'file' || !entry.name.endsWith(BUTTON_FILE_SUFFIX)) {
816        continue
817      }
818      // The program may delete the file between the list and the read.
819      const text = await $.fs.read(joinWindowsPath(folder, entry.name)).catch(() => undefined)
820      if (typeof text === 'string') {
821        files.push({ name: entry.name, mtimeMs: entry.mtimeMs, text })
822      }
823    }
824    const records = files.length === 0 ? [] : buttonRecords(files, pressFileNames, await $.session.id(), Date.now())
825    const current = (await read($, externalButtonsAtom)) ?? NO_EXTERNAL_BUTTONS
826    const isUnchanged = JSON.stringify(current.buttons) === JSON.stringify(records)
827    if (isUnchanged && !isAnimating(records)) {
828      return
829    }
830    // Buttons that just appeared start at the first frame (three dots).
831    const frame = current.buttons.length === 0 || !isAnimating(records) ? 0 : current.frame + 1
832    await update($, externalButtonsAtom, () => ({ buttons: records, frame }))
833    $.ui.invalidate('ui.render')
834  } catch (error: unknown) {
835    $.ui.log(`Reading the toolbar button folder failed: ${describeError(error)}`, { to: 'debug' })
836  } finally {
837    isReadingExternalButtons = false
838  }
839}
840
841// A press writes the button's press file for its program, and the button
842// shows its pressed label until the program removes it.
843async function pressExternalButton($: EngineInterface, record: ExternalButtonRecord): Promise<void> {
844  if (record.isPressed) {
845    return
846  }
847  const folder = await resolveButtonFolder($)
848  if (folder === undefined) {
849    $.ui.toast(`Could not press ${record.label}: TEMP is not set`)
850    return
851  }
852  try {
853    const button = ExternalButton.fromRecord(record)
854    await $.fs.write(joinWindowsPath(folder, button.pressFileName), pressNote(await $.session.id(), Date.now()))
855    await update($, externalButtonsAtom, state => {
856      const current = state ?? NO_EXTERNAL_BUTTONS
857      return {
858        ...current,
859        buttons: current.buttons.map(shown => (shown.id === record.id ? { ...shown, isPressed: true } : shown)),
860      }
861    })
862    $.ui.invalidate('ui.render')
863  } catch (error: unknown) {
864    $.ui.toast(`Could not press ${record.label}: ${describeError(error)}`)
865  }
866}
867
868// The desktop app's own pane of background tasks, opened through the app's
869// session MCP server; a surface without it (the terminal) gets a toast.
870async function openBackgroundTasksPane($: EngineInterface): Promise<void> {
871  try {
872    const result = await $.mcp.call(TASKS_PANE_SERVER, TASKS_PANE_TOOL, { pane: 'tasks' })
873    if (result.isError) {
874      const text = result.content.find(block => block.type === 'text')?.text ?? 'the app refused'
875      $.ui.toast(`Could not open the background tasks pane: ${text}`)
876    }
877  } catch (error: unknown) {
878    $.ui.toast(`Could not open the background tasks pane: ${describeError(error)}`)
879  }
880}
881
882function subagentTooltip(records: readonly SubagentRecord[]): string {
883  const lines = subagentLines(records)
884  const shown = lines.slice(0, SUBAGENT_TOOLTIP_LINE_LIMIT)
885  const more = lines.length > shown.length ? [`… ${lines.length - shown.length} more`] : []
886  return [subagentSummary(records), ...shown, ...more].join('\n')
887}
888
889// The usage widgets, left to right: the model's weekly ring (Fable), the
890// context bar and its token count (a button that pins the detail row open),
891// the 5-hour ring and the weekly ring, each ring drawn alike. Hovering a
892// widget shows its SVG title as a tooltip; an Svg takes no press, so the count
893// is the click target. The terminal gets one dim line and the detail row on demand.
894function usageElements(
895  $: EngineInterface,
896  e: Parameters<Parameters<EngineInterface['ui']['resolve']>[0] extends infer Argument ? (argument: Argument) => void : never>[0],
897  widgets: ReturnType<typeof usageWidgets>,
898  isPinned: boolean,
899) {
900  const togglePin = () => void update($, usageDetailsPinnedAtom, value => !value)
901  if (e.surface === 'terminal') {
902    const { Box, Button, Text } = $.ui.resolve(e)
903
904    return {
905      row: (
906        <Box key="usage-widgets" flexDirection="row" columnGap={1}>
907          <Text dimColor>{usageText(widgets)}</Text>
908          <Button key="usage-details" label={isPinned ? 'Hide' : 'Details'} plain dimColor onPress={togglePin} />
909        </Box>
910      ),
911      details: isPinned ? (
912        <Box key="usage-detail-row" flexDirection="column">
913          {widgets.details.map(line => (
914            <Text dimColor>{line}</Text>
915          ))}
916        </Box>
917      ) : null,
918    }
919  }
920  const { Box, Button, Svg } = $.ui.resolve(e)
921  // Tooltips take the single-spaced sentences; only the pinned block is aligned.
922  const { fiveHour: fiveHourLine, weekly: weeklyLine, model: modelLine, context: contextLine } = widgets.tooltips
923  const detailSize = detailBlockSize(widgets.details)
924
925  return {
926    row: (
927      <Box key="usage-widgets" flexDirection="row" columnGap={1} alignItems="center">
928        <Box key="model-weekly-ring">
929          <Svg
930            source={quotaRingSvg(widgets.modelWeekly.window?.percentUsed ?? null, modelLine)}
931            alt={modelLine}
932            width={RING_SIZE_PX}
933            height={RING_SIZE_PX}
934            isInteractive
935          />
936        </Box>
937        <Button key="usage-details" label={widgets.context.label} plain dimColor={!isPinned} onPress={togglePin} />
938        <Box key="context-bar">
939          <Svg
940            source={contextBarSvg(widgets.context.percentOfScale, widgets.context.color, contextLine)}
941            alt={contextLine}
942            width={BAR_WIDTH_PX}
943            height={BAR_HEIGHT_PX}
944            isInteractive
945          />
946        </Box>
947        <Box key="five-hour-ring">
948          <Svg
949            source={quotaRingSvg(widgets.fiveHour?.percentUsed ?? null, fiveHourLine)}
950            alt={fiveHourLine}
951            width={RING_SIZE_PX}
952            height={RING_SIZE_PX}
953            isInteractive
954          />
955        </Box>
956        <Box key="seven-day-ring">
957          <Svg
958            source={quotaRingSvg(widgets.weekly?.percentUsed ?? null, weeklyLine)}
959            alt={weeklyLine}
960            width={RING_SIZE_PX}
961            height={RING_SIZE_PX}
962            isInteractive
963          />
964        </Box>
965      </Box>
966    ),
967    // Drawn only while pinned: the desktop app does not hide a Box drawn
968    // display "none", so a hover reveal would show the row all the time.
969    // The block is Consolas text in an SVG, right-aligned under the widgets.
970    details: isPinned ? (
971      <Box key="usage-detail-row" flexDirection="row" justifyContent="flex-end">
972        <Svg source={detailBlockSvg(widgets.details)} alt={widgets.details.join('; ')} width={detailSize.width} height={detailSize.height} />
973      </Box>
974    ) : null,
975  }
976}
977
978export const register: Register = on => {
979  on('session.start', async ($, e, next) => {
980    await $.command.register({
981      name: 'copy-transcript-path',
982      description: 'Copy the path of this conversation transcript (.jsonl)',
983    })
984    await $.command.register({
985      name: 'folder',
986      description: 'Open or move this conversation to a recent folder (matched by name) or a path',
987      argumentHint: '<name or path>',
988    })
989    await $.state.set(recentFoldersState, await readStoredFolders($))
990    lastRecordedFolder = folderIdentity(e.cwd)
991    await recordFolder($, e.cwd).catch(() => undefined)
992    void seedFromDesktopSessions($).catch((error: unknown) =>
993      $.ui.log(`Reading the desktop session records failed: ${describeError(error)}`, { to: 'debug' }),
994    )
995    // Live usage: the session's own figures (a free local read) every few
996    // seconds, so the context bar follows each response within a turn; the
997    // plan windows from the shared endpoint cache once a minute.
998    void refreshUsageEndpoint($, USAGE_ENDPOINT_INTERVAL_MS - 5_000).then(() => refreshSessionUsage($))
999    // A move still pending from before a reload gets its dots back; the same
1000    // cheap check every few seconds clears the note once the session is there.
1001    void settlePendingMove($).catch(() => undefined)
1002    $.clock.every(SESSION_USAGE_INTERVAL_MS, () => {
1003      void refreshSessionUsage($)
1004      void settlePendingMove($).catch(() => undefined)
1005    })
1006    $.clock.every(USAGE_ENDPOINT_INTERVAL_MS, () =>
1007      void refreshUsageEndpoint($, USAGE_ENDPOINT_INTERVAL_MS - 5_000).then(() => publishUsage($)),
1008    )
1009    // The subagent dots follow the engine's agent list (a local read).
1010    ensureSubagentPolling($)
1011    ensureExternalButtonPolling($)
1012
1013    return next(e)
1014  })
1015
1016  // A started subagent gets its dot at once, before the next list read.
1017  on('agent.spawn', async ($, e, next) => {
1018    ensureSubagentPolling($)
1019    const result = await next(e)
1020    const agentId = result.agentId
1021    if (agentId !== undefined) {
1022      const agent = { id: agentId, description: e.description, type: e.subagentType }
1023      await writeSubagents($, records => recordSpawn(records, agent, Date.now())).catch(() => undefined)
1024    }
1025
1026    return result
1027  })
1028
1029  // A Monitor of the main conversation gets its waiting clock once the tool
1030  // answers with its task id.
1031  on('tool.call', { tool: 'Monitor' }, async ($, e, next) => {
1032    ensureSubagentPolling($)
1033    const ran = await next(e)
1034    if (e.agentId === undefined && ran.deny === undefined && ran.isError !== true) {
1035      const monitor = readMonitorStart(ran.result, e.description, Date.now())
1036      if (monitor !== null) {
1037        await writeMonitors($, records => recordMonitorStart(records, monitor)).catch(() => undefined)
1038      }
1039    }
1040
1041    return ran
1042  })
1043
1044  on('tool.call', { tool: 'TaskStop' }, async ($, e, next) => {
1045    const ran = await next(e)
1046    const taskId = e.task_id ?? e.shell_id
1047    if (e.agentId === undefined && taskId !== undefined && ran.deny === undefined && ran.isError !== true) {
1048      await writeMonitors($, records => recordMonitorEnd(records, taskId, 'stopped', Date.now())).catch(() => undefined)
1049    }
1050
1051    return ran
1052  })
1053
1054  // A Monitor's last notification carries a status (completed, failed,
1055  // killed...); its event notifications carry none.
1056  on('prompt.submit', async ($, e, next) => {
1057    if (e.origin.kind === 'task-notification') {
1058      const endings = parseNotificationEndings(e.text)
1059      if (endings.length > 0) {
1060        await writeMonitors($, records => applyEndings(records, endings, Date.now())).catch(() => undefined)
1061      }
1062    }
1063
1064    return next(e)
1065  })
1066
1067  // A session moved by the desktop app, the model or this toolbar records its
1068  // new folder at the next turn boundary.
1069  on('turn.start', async ($, e, next) => {
1070    isTurnRunning = true
1071    ensureSubagentPolling($)
1072    ensureExternalButtonPolling($)
1073    await recordCurrentFolder($).catch(() => undefined)
1074    await settlePendingMove($).catch(() => undefined)
1075
1076    return next(e)
1077  })
1078
1079  on('turn.complete', async ($, e, next) => {
1080    // A subagent's run ends in a turn.complete of its own: its dot takes the
1081    // outcome; the main loop's turn state is untouched.
1082    const agentId = e.agentId
1083    if (agentId !== undefined) {
1084      const result = await next(e)
1085      await writeSubagents($, records => recordTurnEnd(records, agentId, e.reason, Date.now())).catch(() => undefined)
1086
1087      return result
1088    }
1089    isTurnRunning = false
1090    lastTurnCompletedAtMs = Date.now()
1091    const result = await next(e)
1092    await recordCurrentFolder($).catch(() => undefined)
1093    await settlePendingMove($).catch(() => undefined)
1094    // A turn spends quota: ask the endpoint again unless another session just did.
1095    void refreshUsageEndpoint($, 15_000).then(() => refreshSessionUsage($))
1096
1097    return result
1098  })
1099
1100  // The engine measures the context fill and the rate-limit windows after each
1101  // turn and whenever a plan window moves a point; a moved window also asks
1102  // the endpoint again so the Fable ring follows.
1103  on('session.measure', async ($, e, next) => {
1104    latestSessionUsage = usageSnapshot({ context: e.context, rateLimits: e.rateLimits })
1105    await publishUsage($)
1106    if (e.changed.includes('rateLimits')) {
1107      void refreshUsageEndpoint($, 15_000).then(() => publishUsage($))
1108    }
1109
1110    return next(e)
1111  })
1112
1113  on('command.run', { command: 'copy-transcript-path' }, async $ => {
1114    return { text: await copyTranscriptPath($) }
1115  })
1116
1117  on('command.run', { command: 'folder' }, async ($, e) => {
1118    return { text: await runFolderCommand($, e.args) }
1119  })
1120
1121  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1122    if (e.props.hasSurvey || e.props.view.agentId !== undefined) {
1123      return next(e)
1124    }
1125
1126    const elements = $.ui.resolve(e)
1127    const { Box, Button, Text } = elements
1128    const copyFeedback = (await read($, copyFeedbackAtom)) ?? 'idle'
1129    const copyButton = (
1130      <Button
1131        key="copy-transcript-path"
1132        label={COPY_BUTTON_LABELS[copyFeedback]}
1133        variant="secondary"
1134        onPress={press => void copyTranscriptPath($, press.surface)}
1135      />
1136    )
1137    // The usage widgets at the right end. Before the first publication the
1138    // figures are composed here (a render reads state, it never writes it).
1139    const usage = (await read($, usageAtom)) ?? (await composeUsage($).catch(() => null))
1140    const modelId = await $.session.model().catch(() => '')
1141    const usageParts = usageElements($, e, usageWidgets(usage, Date.now(), modelId), await read($, usageDetailsPinnedAtom))
1142    // One dot per subagent of this session, drawn once there is one; hovering
1143    // lists them. The terminal shows the counts as text.
1144    const subagents = (await read($, subagentsAtom)) ?? []
1145    // A clock per Monitor still watching, left of the dots. A hot reload at an
1146    // idle moment raises no turn: the first draw starts the poll and the
1147    // transcript read (their writes come after this draw).
1148    ensureSubagentPolling($)
1149    ensureExternalButtonPolling($)
1150    const monitors = activeMonitors((await read($, monitorsAtom)) ?? [])
1151    // Buttons other programs asked for, after the dots; a press writes the
1152    // button's press file for its program.
1153    const externalButtons = (await read($, externalButtonsAtom)) ?? NO_EXTERNAL_BUTTONS
1154    const externalButtonRow =
1155      externalButtons.buttons.length > 0 ? (
1156        <Box key="external-buttons" flexDirection="row" columnGap={1}>
1157          {externalButtons.buttons.map(record => (
1158            <Button
1159              key={`external-button-${record.id}`}
1160              label={ExternalButton.fromRecord(record).text(externalButtons.frame, record.isPressed)}
1161              variant="secondary"
1162              dimColor={record.isPressed}
1163              onPress={() => void pressExternalButton($, record)}
1164            />
1165          ))}
1166        </Box>
1167      ) : null
1168    let subagentIndicator = null
1169    if (subagents.length > 0 || monitors.length > 0) {
1170      // An Svg takes no press and a Button holds no Svg, so a one-glyph plain
1171      // button beside the dots opens the desktop app's background tasks pane.
1172      const openTasks = (
1173        <Button
1174          key="open-background-tasks"
1175          label={OPEN_TASKS_GLYPH}
1176          plain
1177          dimColor
1178          onPress={() => void openBackgroundTasksPane($)}
1179        />
1180      )
1181      const nowMs = Date.now()
1182      if (e.surface !== 'terminal' && 'Svg' in elements) {
1183        const { Svg } = elements
1184        subagentIndicator = (
1185          <Box key="subagent-dots" flexDirection="row" alignItems="center">
1186            {monitors.length > 0 ? (
1187              <Box key="monitor-clocks">
1188                <Svg
1189                  source={monitorClocksSvg(monitors, monitorTooltip(monitors, nowMs), nowMs)}
1190                  alt={monitorSummary(monitors)}
1191                  width={monitorClocksWidth(monitors, nowMs)}
1192                  height={DOTS_HEIGHT_PX}
1193                  isInteractive
1194                />
1195              </Box>
1196            ) : null}
1197            {subagents.length > 0 ? (
1198              <Box key="subagent-dot-row">
1199                <Svg
1200                  source={subagentDotsSvg(subagents, subagentTooltip(subagents))}
hooks/folder_list.ts 281 lines
1export const RECENT_FOLDER_LIMIT = 100
2
3export function joinWindowsPath(...parts: string[]): string {
4  return parts.map(part => part.replace(/[\\/]+$/, '')).join('\\')
5}
6
7// Claude Code names each project folder after the working directory with every
8// character outside [A-Za-z0-9] replaced by '-'.
9export function projectDirectoryName(workingDirectory: string): string {
10  return workingDirectory.replace(/[^a-zA-Z0-9]/g, '-')
11}
12
13const ELLIPSIS = '\u2026'
14// East Asian wide characters take two columns.
15const WIDE_CHARACTER =
16  /[\u1100-\u115F\u2E80-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6]/
17
18function isWindowsPath(folder: string): boolean {
19  return /^[A-Za-z]:[\\/]/.test(folder) || /^[\\/]{2}[^\\/]/.test(folder)
20}
21
22export function isAbsoluteFolder(folder: string): boolean {
23  return isWindowsPath(folder) || folder.startsWith('/')
24}
25
26export function displayWidth(text: string): number {
27  let width = 0
28  for (const character of text) {
29    width += WIDE_CHARACTER.test(character) ? 2 : 1
30  }
31
32  return width
33}
34
35// Keeps the end of the text behind an ellipsis.
36function keepEndWithinWidth(text: string, maxWidth: number): string {
37  if (displayWidth(text) <= maxWidth) {
38    return text
39  }
40  const characters = [...text]
41  let kept = ''
42  let width = displayWidth(ELLIPSIS)
43  for (let index = characters.length - 1; index >= 0; index -= 1) {
44    const character = characters[index] ?? ''
45    const characterWidth = displayWidth(character)
46    if (width + characterWidth > maxWidth) {
47      break
48    }
49    kept = character + kept
50    width += characterWidth
51  }
52
53  return ELLIPSIS + kept
54}
55
56// Shortens a path to the width by dropping its middle folders: the drive (or
57// share) and as many trailing folders as fit stay, `E:\…\Projects\Chemistry`.
58export function compressPath(path: string, maxWidth: number): string {
59  if (displayWidth(path) <= maxWidth) {
60    return path
61  }
62  const separator = path.includes('\\') ? '\\' : '/'
63  const segments = path.split(separator)
64  const headCount = path.startsWith(separator + separator) ? 4 : 1
65  const head = segments.slice(0, headCount).join(separator)
66  const rest = segments.slice(headCount).filter(segment => segment !== '')
67  let tail = ''
68  for (let index = rest.length - 1; index >= 0; index -= 1) {
69    const candidateTail = tail === '' ? (rest[index] ?? '') : `${rest[index] ?? ''}${separator}${tail}`
70    if (displayWidth(`${head}${separator}${ELLIPSIS}${separator}${candidateTail}`) > maxWidth) {
71      break
72    }
73    tail = candidateTail
74  }
75  if (tail !== '') {
76    return `${head}${separator}${ELLIPSIS}${separator}${tail}`
77  }
78
79  return keepEndWithinWidth(path, maxWidth)
80}
81
82// Windows paths are written with backslashes, an upper-case drive letter and
83// no trailing separator (a drive root keeps its own).
84export function normalizeFolder(folder: string): string {
85  const trimmed = folder.trim()
86  if (!isWindowsPath(trimmed)) {
87    return trimmed.length > 1 ? trimmed.replace(/\/+$/, '') : trimmed
88  }
89  const backslashed = trimmed
90    .replace(/\//g, '\\')
91    .replace(/^([a-z]):/, (_match, drive: string) => `${drive.toUpperCase()}:`)
92
93  return /^[A-Z]:\\$/.test(backslashed) ? backslashed : backslashed.replace(/\\+$/, '')
94}
95
96// Two spellings of one Windows folder differ only in case.
97export function folderIdentity(folder: string): string {
98  const normalized = normalizeFolder(folder)
99
100  return isWindowsPath(normalized) ? normalized.toLowerCase() : normalized
101}
102
103export function folderName(folder: string): string {
104  const normalized = normalizeFolder(folder)
105  const parts = normalized.split(/[\\/]/).filter(part => part !== '')
106
107  return parts.at(-1) ?? normalized
108}
109
110// The folder holding this one; empty for a drive or file-system root.
111export function folderParent(folder: string): string {
112  const normalized = normalizeFolder(folder)
113  const separatorIndex = Math.max(normalized.lastIndexOf('\\'), normalized.lastIndexOf('/'))
114  if (separatorIndex < 0 || separatorIndex === normalized.length - 1) {
115    return ''
116  }
117  const parent = normalized.slice(0, separatorIndex)
118  if (parent === '') {
119    return '/'
120  }
121
122  return /^[A-Za-z]:$/.test(parent) ? `${parent}\\` : parent
123}
124
125// The folder's own name alone, `Python_Lib`; a name past the width keeps its
126// end behind an ellipsis. The full path stays in the option's value.
127export function folderOptionLabel(folder: string, maxWidth: number): string {
128  return keepEndWithinWidth(folderName(folder), maxWidth)
129}
130
131// The recent folder a typed name means: the same name, then a name starting
132// with it, then a name containing it, then a path containing it.
133export function findFolder(folders: readonly string[], query: string): string | undefined {
134  const wanted = query.trim().toLowerCase()
135  if (wanted === '') {
136    return undefined
137  }
138  const named = (matches: (name: string) => boolean) =>
139    folders.find(folder => matches(folderName(folder).toLowerCase()))
140
141  return (
142    named(name => name === wanted) ??
143    named(name => name.startsWith(wanted)) ??
144    named(name => name.includes(wanted)) ??
145    folders.find(folder => folder.toLowerCase().includes(wanted))
146  )
147}
148
149export function mergeFolderLists(
150  first: readonly string[],
151  second: readonly string[],
152  limit = RECENT_FOLDER_LIMIT,
153): string[] {
154  const seen = new Set<string>()
155  const merged: string[] = []
156  for (const folder of [...first, ...second]) {
157    if (folder.trim() === '') {
158      continue
159    }
160    const normalized = normalizeFolder(folder)
161    const identity = folderIdentity(normalized)
162    if (seen.has(identity)) {
163      continue
164    }
165    seen.add(identity)
166    merged.push(normalized)
167    if (merged.length >= limit) {
168      break
169    }
170  }
171
172  return merged
173}
174
175export function placeFolderFirst(
176  folders: readonly string[],
177  folder: string,
178  limit = RECENT_FOLDER_LIMIT,
179): string[] {
180  return mergeFolderLists([folder], folders, limit)
181}
182
183export function isFolderInside(folder: string, parent: string): boolean {
184  const child = folderIdentity(folder)
185  const root = folderIdentity(parent)
186  const prefix = /[\\/]$/.test(root) ? root : `${root}\\`
187
188  return child === root || child.startsWith(prefix)
189}
190
191// Temporary folders: Python's tempfile names (tmpk3j_x9ab), anything under a
192// Temp folder or the session temp folder, and scratch folders named _Claude_tmp.
193const TEMPORARY_FOLDER_PATTERNS = [
194  /[\\/]tmp[a-z0-9_]{5,}([\\/]|$)/i,
195  /[\\/]AppData[\\/]Local[\\/]Temp([\\/]|$)/i,
196  /[\\/]_Claude_Desktop_Temp([\\/]|$)/i,
197  /[\\/]_Claude_tmp([\\/]|$)/i,
198]
199
200// Scratch workspaces ("No folder" sessions), session worktrees and temporary
201// folders are not folders a person picks. `temporaryRoots` are the TEMP, TMP
202// and CLAUDE_CODE_TMPDIR folders of this machine.
203export function isPickableFolder(folder: string, scratchRoot: string | undefined, temporaryRoots: readonly string[] = []): boolean {
204  if (folder.trim() === '') {
205    return false
206  }
207  if (scratchRoot !== undefined && isFolderInside(folder, scratchRoot)) {
208    return false
209  }
210  if (temporaryRoots.some(root => root.trim() !== '' && isFolderInside(folder, root))) {
211    return false
212  }
213  if (TEMPORARY_FOLDER_PATTERNS.some(pattern => pattern.test(folder))) {
214    return false
215  }
216
217  return !/[\\/]\.claude[\\/]worktrees([\\/]|$)/i.test(folder)
218}
219
220// The store holds JSON written by any version of this plugin; keep what is a path.
221export function readFolderList(value: unknown): string[] {
222  if (!Array.isArray(value)) {
223    return []
224  }
225
226  return mergeFolderLists(
227    value.filter((item): item is string => typeof item === 'string'),
228    [],
229  )
230}
231
232export type SessionRecordFolder = { folder: string; lastActivityAt: number }
233
234// One record the desktop app keeps per local session, as JSON text.
235export function readSessionRecordFolder(
236  text: string,
237  fallbackTime: number,
238): SessionRecordFolder | null {
239  let record: unknown
240  try {
241    record = JSON.parse(text)
242  } catch {
243    return null
244  }
245  if (typeof record !== 'object' || record === null) {
246    return null
247  }
248  const fields = record as Record<string, unknown>
249  if (fields.isScratchWorkspace === true) {
250    return null
251  }
252  const folder = [fields.originCwd, fields.cwd].find(
253    (value): value is string => typeof value === 'string' && value.trim() !== '',
254  )
255  if (folder === undefined) {
256    return null
257  }
258  const lastActivityAt =
259    [fields.lastActivityAt, fields.createdAt].find(
260      (value): value is number => typeof value === 'number',
261    ) ?? fallbackTime
262
263  return { folder, lastActivityAt }
264}
265
266// Each folder once, ordered by the newest session that used it.
267export function rankSessionFolders(records: readonly SessionRecordFolder[]): string[] {
268  const newest = new Map<string, SessionRecordFolder>()
269  for (const record of records) {
270    const identity = folderIdentity(record.folder)
271    const known = newest.get(identity)
272    if (known === undefined || record.lastActivityAt > known.lastActivityAt) {
273      newest.set(identity, record)
274    }
275  }
276
277  return [...newest.values()]
278    .sort((first, second) => second.lastActivityAt - first.lastActivityAt)
279    .map(record => normalizeFolder(record.folder))
280}
281
hooks/usage_wheels.ts 487 lines
1// Pure helpers for the usage widgets at the right end of the toolbar, left to
2// right: the model's weekly ring (Fable), the token count and the context bar,
3// then the 5-hour ring and the weekly ring, every ring the same: the Codex
4// outer arc with the whole percentage inside. Drawing rules and colors are
5// copied from the author's Codex usage widget (its rings.mjs and Widget.cs).
6// No engine calls here.
7
8import type { UsageSnapshot, UsageWindow } from '../types'
9
10export type UsageWidgets = {
11  // The weekly window scoped to one model (Fable), as the usage endpoint lists it.
12  modelWeekly: { window: UsageWindow | undefined; name: string }
13  // `label` is the count alone ("110k"), `figure` the count over the window ("110k / 1M").
14  context: { tokens: number | null; percentOfScale: number | null; color: string; label: string; figure: string }
15  fiveHour: UsageWindow | undefined
16  weekly: UsageWindow | undefined
17  // The detail block's lines, every column padded for Consolas:
18  // "Context  : 350k / 1M",
19  // "5 h limit: 91% (Reset in 4 h 10 min. Runs out in       5 min.)",
20  // "7 d limit: 76% (Reset in 5 d 14 h.   Runs out in 10 h 45 min.)", "Fable    : ...".
21  lines: { context: string; fiveHour: string; weekly: string; model: string }
22  // The same figures with single spaces, for the tooltips:
23  // "5 h limit: 91% (Reset in 4 h 2 min. Runs out in 25 min.)", "Context: 350k / 1M".
24  tooltips: { context: string; fiveHour: string; weekly: string; model: string }
25  // The detail block, in that order, then any other model's weekly window.
26  details: string[]
27}
28
29export const RING_SIZE_PX = 24
30export const BAR_WIDTH_PX = 48
31export const BAR_HEIGHT_PX = 24
32// The context bar is full at 500k tokens, whatever the model's own window.
33export const CONTEXT_BAR_SCALE_TOKENS = 500_000
34// A model-scoped weekly window, as the usage endpoint's limits[] lists it.
35export const MODEL_WEEKLY_KIND_PREFIX = 'model_weekly:'
36
37// The Codex usage widget's palette and thresholds.
38export const CODEX_COLORS = { blue: '#4797ed', green: '#5abd7b', yellow: '#eeb347', red: '#ef6666' } as const
39const UNKNOWN_COLOR = '#9ca3af'
40// Below this share the unused part shows a grey track, as the Codex widget does.
41const LOW_USAGE_VISIBILITY_PERCENT = 25
42const TRACK_COLOR = 'rgba(128,128,128,0.38)'
43
44// rings.mjs contextColor, for a window of 280k tokens or more.
45export function contextColor(tokens: number | null): string {
46  if (tokens === null) {
47    return UNKNOWN_COLOR
48  }
49  return tokens > 400_000 ? CODEX_COLORS.red : tokens >= 300_000 ? CODEX_COLORS.yellow : CODEX_COLORS.blue
50}
51
52// rings.mjs quotaColor.
53export function quotaColor(percent: number | null): string {
54  if (percent === null) {
55    return UNKNOWN_COLOR
56  }
57  return percent > 85 ? CODEX_COLORS.red : percent >= 70 ? CODEX_COLORS.yellow : CODEX_COLORS.green
58}
59
60// Whole percent, rounded down as the Codex widget shows it (99.9 → 99).
61export function wholePercent(percent: number | null): string {
62  return percent === null ? '?' : `${Math.max(0, Math.floor(percent))}%`
63}
64
65export function formatTokens(tokens: number): string {
66  if (tokens >= 1_000_000) {
67    return `${(tokens / 1_000_000).toFixed(tokens % 1_000_000 === 0 ? 0 : 1)}M`
68  }
69  if (tokens >= 1_000) {
70    return `${Math.round(tokens / 1_000)}k`
71  }
72  return String(tokens)
73}
74
75const MINUTE_MS = 60_000
76const HOUR_MS = 60 * MINUTE_MS
77const DAY_MS = 24 * HOUR_MS
78
79const DURATION_UNITS = ['d', 'h', 'min'] as const
80type DurationUnit = (typeof DURATION_UNITS)[number]
81type DurationPart = { unit: DurationUnit; value: number }
82
83// The two largest units of a span of time: days and hours, hours and minutes,
84// or minutes alone.
85export function durationParts(durationMs: number): DurationPart[] {
86  const minutes = Math.max(0, Math.ceil(durationMs / MINUTE_MS))
87  const days = Math.floor(minutes / 1_440)
88  const hours = Math.floor((minutes % 1_440) / 60)
89  const rest = minutes % 60
90  if (days > 0) {
91    return [{ unit: 'd', value: days }, { unit: 'h', value: hours }]
92  }
93  if (hours > 0) {
94    return [{ unit: 'h', value: hours }, { unit: 'min', value: rest }]
95  }
96  return [{ unit: 'min', value: rest }]
97}
98
99// "5 d 3 h", "3 h 30 min", "35 min", single spaces.
100export function formatDuration(durationMs: number): string {
101  return durationParts(durationMs)
102    .map(part => `${part.value} ${part.unit}`)
103    .join(' ')
104}
105
106// Spans left-aligned in a monospaced column, number by number in reading order:
107// each first number padded to the widest first number, each second to the
108// widest second, so "5 d  3 h" stands under "3 h 30 min" and "5 d 14 h" under
109// "4 h 10 min". Units may differ from row to row. Null stays null.
110export function alignDurationsByPosition(durations: readonly (number | null)[]): (string | null)[] {
111  const partLists = durations.map(duration => (duration === null ? null : durationParts(duration)))
112  const widthAt = (position: number) =>
113    Math.max(0, ...partLists.map(parts => (parts?.[position] === undefined ? 0 : String(parts[position].value).length)))
114  const widths = [widthAt(0), widthAt(1)]
115  return partLists.map(parts =>
116    parts === null
117      ? null
118      : parts.map((part, position) => `${String(part.value).padStart(widths[position] ?? 0, ' ')} ${part.unit}`).join(' '),
119  )
120}
121
122// Spans meant to stand one under another in a monospaced column. Every unit
123// the column uses gets a slot as wide as its widest number, so "h" stands under
124// "h" and "min" under "min"; a span without that unit leaves the slot blank:
125// "      5 min", "10 h 45 min", " 4 h 39 min". Null stays null.
126export function alignDurations(durations: readonly (number | null)[]): (string | null)[] {
127  const partLists = durations.map(duration => (duration === null ? null : durationParts(duration)))
128  const widths = new Map<DurationUnit, number>()
129  partLists.flatMap(parts => parts ?? []).forEach(part => {
130    widths.set(part.unit, Math.max(widths.get(part.unit) ?? 0, String(part.value).length))
131  })
132  const slots = DURATION_UNITS.filter(unit => widths.has(unit))
133  return partLists.map(parts => {
134    if (parts === null) {
135      return null
136    }
137    return slots
138      .map(unit => {
139        const width = widths.get(unit) ?? 0
140        const part = parts.find(candidate => candidate.unit === unit)
141        return part === undefined ? ' '.repeat(width + 1 + unit.length) : `${String(part.value).padStart(width, ' ')} ${unit}`
142      })
143      .join(' ')
144      .trimEnd()
145  })
146}
147
148// Time left until the window resets, in milliseconds; null when unknown or past.
149export function resetsInMs(resetsAt: string | undefined, nowMs: number): number | null {
150  if (!resetsAt) {
151    return null
152  }
153  const remaining = Date.parse(resetsAt) - nowMs
154  return Number.isFinite(remaining) && remaining > 0 ? remaining : null
155}
156
157// How long each kind of window runs from one reset to the next.
158export function windowLengthMs(kind: string): number {
159  return kind === 'five_hour' ? 5 * HOUR_MS : 7 * DAY_MS
160}
161
162export type RunOut = { state: 'ranOut' } | { state: 'pastReset' } | { state: 'in'; durationMs: number }
163
164// When the window runs out at the average rate since it began: the percentage
165// used so far over the time elapsed in the window. Null without a reset time.
166export function projectRunOut(window: UsageWindow, nowMs: number): RunOut | null {
167  const remaining = resetsInMs(window.resetsAt, nowMs)
168  if (remaining === null) {
169    return null
170  }
171  if (window.percentUsed >= 100) {
172    return { state: 'ranOut' }
173  }
174  const elapsed = windowLengthMs(window.kind) - remaining
175  if (window.percentUsed <= 0 || elapsed <= 0) {
176    return { state: 'pastReset' }
177  }
178  const untilFull = ((100 - window.percentUsed) * elapsed) / window.percentUsed
179  return untilFull >= remaining ? { state: 'pastReset' } : { state: 'in', durationMs: untilFull }
180}
181
182// `duration` is the run-out span already written, plain or aligned.
183function runOutText(runOut: RunOut, duration: string): string {
184  if (runOut.state === 'ranOut') {
185    return 'Ran out.'
186  }
187  if (runOut.state === 'pastReset') {
188    return 'Lasts past reset.'
189  }
190  return `Runs out in ${duration}.`
191}
192
193// The model's context window, "1M"; "?" without a reading.
194function formatWindow(window: number | undefined): string {
195  return window !== undefined && Number.isFinite(window) && window > 0 ? formatTokens(window) : '?'
196}
197
198// Every label padded to this width, so the colons line up in a monospaced block.
199const DETAIL_LABEL_WIDTH = 9
200
201function detailLabel(label: string): string {
202  return label.padEnd(DETAIL_LABEL_WIDTH, ' ')
203}
204
205// The model-scoped weekly window to show: the one for the session's model family
206// when listed, else the first one listed (the Fable quota on this account).
207export function pickModelWeeklyWindow(windows: readonly UsageWindow[], modelId = ''): UsageWindow | undefined {
208  const scoped = windows.filter(window => window.kind.startsWith(MODEL_WEEKLY_KIND_PREFIX))
209  const family = modelId.toLowerCase()
210  return scoped.find(window => family.includes(window.kind.slice(MODEL_WEEKLY_KIND_PREFIX.length).toLowerCase())) ?? scoped[0]
211}
212
213// One window's figures before they are written out.
214type WindowFigures = { label: string; percent: string; resetMs: number | null; runOut: RunOut | null }
215
216function windowFigures(label: string, window: UsageWindow | undefined, nowMs: number): WindowFigures {
217  if (window === undefined) {
218    return { label, percent: '?', resetMs: null, runOut: null }
219  }
220  return {
221    label,
222    percent: wholePercent(window.percentUsed),
223    resetMs: resetsInMs(window.resetsAt, nowMs),
224    runOut: projectRunOut(window, nowMs),
225  }
226}
227
228function runOutMs(runOut: RunOut | null): number | null {
229  return runOut?.state === 'in' ? runOut.durationMs : null
230}
231
232// "5 h limit: 12% (Reset in 3 h 30 min. Runs out in 2 h 10 min.)", single spaces, for a tooltip.
233function plainWindowLine(figures: WindowFigures): string {
234  const reset = figures.resetMs === null ? null : `Reset in ${formatDuration(figures.resetMs)}.`
235  const runOut = figures.runOut === null ? null : runOutText(figures.runOut, formatDuration(runOutMs(figures.runOut) ?? 0))
236  const tail = [reset, runOut].filter((piece): piece is string => piece !== null).join(' ')
237  return `${figures.label}: ${figures.percent}${tail ? ` (${tail})` : ''}`
238}
239
240// The window lines of the detail block for Consolas: the percentages
241// right-aligned, the reset spans left-aligned number by number, "Runs out in"
242// starting in one column and the run-out spans aligned unit by unit.
243function alignedWindowLines(rows: readonly WindowFigures[]): string[] {
244  const resets = alignDurationsByPosition(rows.map(row => row.resetMs)).map(span => (span === null ? null : `Reset in ${span}.`))
245  const runOutSpans = alignDurations(rows.map(row => runOutMs(row.runOut)))
246  const runOuts = rows.map((row, index) => (row.runOut === null ? null : runOutText(row.runOut, runOutSpans[index] ?? '')))
247  const percentWidth = Math.max(0, ...rows.map(row => row.percent.length))
248  const resetWidth = Math.max(0, ...resets.map(reset => reset?.length ?? 0))
249  return rows.map((row, index) => {
250    const head = `${detailLabel(row.label)}: ${row.percent.padStart(percentWidth, ' ')}`
251    const reset = resets[index]
252    const runOut = runOuts[index]
253    if (reset === null || runOut === null) {
254      return reset === null ? head : `${head} (${reset})`
255    }
256    return `${head} (${reset.padEnd(resetWidth, ' ')} ${runOut})`
257  })
258}
259
260export function usageWidgets(usage: UsageSnapshot | null, nowMs: number, modelId = ''): UsageWidgets {
261  const context = usage?.context
262  const tokens = context?.tokens ?? null
263  const percentOfScale = tokens === null ? null : (tokens / CONTEXT_BAR_SCALE_TOKENS) * 100
264  const windows = usage?.rateLimits ?? []
265  const modelWeekly = pickModelWeeklyWindow(windows, modelId)
266  const name = modelWeekly === undefined ? 'Model' : modelWeekly.kind.slice(MODEL_WEEKLY_KIND_PREFIX.length)
267  const fiveHour = windows.find(window => window.kind === 'five_hour')
268  const weekly = windows.find(window => window.kind === 'seven_day')
269  const otherModels = windows.filter(window => window.kind.startsWith(MODEL_WEEKLY_KIND_PREFIX) && window !== modelWeekly)
270
271  const contextLabel = tokens === null ? '?' : formatTokens(tokens)
272  // "110k / 1M": the count over the model's own context window.
273  const contextFigure = `${contextLabel} / ${formatWindow(context?.window)}`
274  // The windows in detail-block order: 5-hour, weekly, this model's, then other models'.
275  const shown: [string, UsageWindow | undefined][] = [
276    ['5 h limit', fiveHour],
277    ['7 d limit', weekly],
278    [name, modelWeekly],
279    ...otherModels.map((window): [string, UsageWindow] => [window.kind.slice(MODEL_WEEKLY_KIND_PREFIX.length), window]),
280  ]
281  const alignedLines = alignedWindowLines(shown.map(([label, window]) => windowFigures(label, window, nowMs)))
282  const plainLine = (label: string, window: UsageWindow | undefined) => plainWindowLine(windowFigures(label, window, nowMs))
283  const lines = {
284    context: `${detailLabel('Context')}: ${contextFigure}`,
285    fiveHour: alignedLines[0],
286    weekly: alignedLines[1],
287    model: alignedLines[2],
288  }
289
290  return {
291    modelWeekly: { window: modelWeekly, name },
292    context: { tokens, percentOfScale, color: contextColor(tokens), label: contextLabel, figure: contextFigure },
293    fiveHour,
294    weekly,
295    lines,
296    tooltips: {
297      context: `Context: ${contextFigure}`,
298      fiveHour: plainLine('5 h limit', fiveHour),
299      weekly: plainLine('7 d limit', weekly),
300      model: plainLine(name, modelWeekly),
301    },
302    details: [lines.context, ...alignedLines],
303  }
304}
305
306function escapeXml(text: string): string {
307  return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
308}
309
310function round(value: number): string {
311  return String(Math.round(value * 1000) / 1000)
312}
313
314function fractionOf(percent: number | null): number {
315  return percent === null ? 0 : Math.min(100, Math.max(0, percent)) / 100
316}
317
318function svgOpen(width: number, height: number, viewWidth: number, viewHeight: number, title: string): string {
319  return (
320    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${viewWidth} ${viewHeight}" role="img">` +
321    `<title>${escapeXml(title)}</title>`
322  )
323}
324
325// Widget.cs outer ring, in a 32-unit box: radius 11, width 2, round caps,
326// clockwise from the top; a grey track while under 25 % used.
327function outerArc(percent: number | null, color: string): string {
328  const fraction = fractionOf(percent)
329  const track =
330    percent !== null && percent < LOW_USAGE_VISIBILITY_PERCENT
331      ? `<circle cx="16" cy="16" r="11" fill="none" stroke="${TRACK_COLOR}" stroke-width="2"/>`
332      : ''
333  if (fraction >= 1) {
334    return track + `<circle cx="16" cy="16" r="11" fill="none" stroke="${color}" stroke-width="2"/>`
335  }
336  if (fraction <= 0) {
337    return track
338  }
339  const angle = fraction * 2 * Math.PI
340  const endX = 16 + 11 * Math.sin(angle)
341  const endY = 16 - 11 * Math.cos(angle)
342  return (
343    track +
344    `<path d="M 16 5 A 11 11 0 ${fraction > 0.5 ? 1 : 0} 1 ${round(endX)} ${round(endY)}"` +
345    ` fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round"/>`
346  )
347}
348
349// Digits stand about 0.7 em tall on the baseline, so a baseline this far below
350// the centre centres them; dominant-baseline="central" centres the font's whole
351// ascent-to-descent box instead, which sits the digits low in Segoe UI.
352const DIGIT_HALF_HEIGHT_EM = 0.35
353
354// A quota ring (the Fable, 5-hour and weekly windows alike): the Codex outer
355// ring with the whole percentage inside.
356export function quotaRingSvg(percent: number | null, title: string, sizePx = RING_SIZE_PX): string {
357  const color = quotaColor(percent)
358  const text = percent === null ? '?' : String(Math.max(0, Math.floor(percent)))
359  const fontSize = text.length > 2 ? 10 : 12
360  return (
361    svgOpen(sizePx, sizePx, 32, 32, title) +
362    outerArc(percent, color) +
363    `<text x="16" y="${round(16 + DIGIT_HALF_HEIGHT_EM * fontSize)}" text-anchor="middle" font-family="system-ui, sans-serif"` +
364    ` font-size="${fontSize}" font-weight="600" fill="${color}">${text}</text>` +
365    '</svg>'
366  )
367}
368
369// A horizontal bar, full at CONTEXT_BAR_SCALE_TOKENS, in the context color.
370export function contextBarSvg(percentOfScale: number | null, color: string, title: string): string {
371  const width = BAR_WIDTH_PX
372  const height = BAR_HEIGHT_PX
373  const barHeight = 6
374  const top = (height - barHeight) / 2
375  const fraction = fractionOf(percentOfScale)
376  return (
377    svgOpen(width, height, width, height, title) +
378    `<rect x="0" y="${top}" width="${width}" height="${barHeight}" rx="3" fill="${TRACK_COLOR}"/>` +
379    (fraction > 0 ? `<rect x="0" y="${top}" width="${round(width * fraction)}" height="${barHeight}" rx="3" fill="${color}"/>` : '') +
380    '</svg>'
381  )
382}
383
384function percentField(value: unknown): number | undefined {
385  return typeof value === 'number' && Number.isFinite(value) ? value : undefined
386}
387
388function resetField(value: unknown): string | undefined {
389  if (typeof value === 'string' && value !== '') {
390    return value
391  }
392  return typeof value === 'number' && Number.isFinite(value) ? new Date(value * 1000).toISOString() : undefined
393}
394
395// The windows in an answer of GET https://api.anthropic.com/api/oauth/usage:
396// five_hour and seven_day ({ utilization: percent, resets_at }), and each
397// limits[] entry of kind weekly_scoped with scope.model.display_name (the Fable
398// quota) as `model_weekly:<display name>` ({ percent, resets_at }).
399export function parseUsageEndpoint(body: unknown): UsageWindow[] {
400  if (typeof body !== 'object' || body === null) {
401    return []
402  }
403  const record = body as Record<string, unknown>
404  const windows: UsageWindow[] = []
405  for (const kind of ['five_hour', 'seven_day']) {
406    const entry = record[kind]
407    if (typeof entry === 'object' && entry !== null) {
408      const percent = percentField((entry as Record<string, unknown>).utilization)
409      if (percent !== undefined) {
410        windows.push({ kind, percentUsed: percent, resetsAt: resetField((entry as Record<string, unknown>).resets_at) })
411      }
412    }
413  }
414  const limits = Array.isArray(record.limits) ? record.limits : []
415  for (const limit of limits) {
416    if (typeof limit !== 'object' || limit === null) {
417      continue
418    }
419    const entry = limit as Record<string, unknown>
420    const scope = entry.scope as { model?: { display_name?: unknown } } | null | undefined
421    const name = scope?.model?.display_name
422    const percent = percentField(entry.percent)
423    if (entry.kind === 'weekly_scoped' && typeof name === 'string' && name !== '' && percent !== undefined) {
424      windows.push({ kind: `${MODEL_WEEKLY_KIND_PREFIX}${name}`, percentUsed: percent, resetsAt: resetField(entry.resets_at) })
425    }
426  }
427  return windows
428}
429
430// Where both name the same window the fresher reading wins: the engine's own
431// (response headers) only while its responses are newer than the endpoint's
432// answer, since an idle or finished session keeps its last turn's figures for
433// good. The other source adds the windows the first lacks.
434export function mergeWindows(
435  fromSession: readonly UsageWindow[],
436  fromEndpoint: readonly UsageWindow[],
437  sessionReadAtMs: number,
438  endpointFetchedAtMs: number,
439): UsageWindow[] {
440  const [first, second] = endpointFetchedAtMs > sessionReadAtMs ? [fromEndpoint, fromSession] : [fromSession, fromEndpoint]
441  const kinds = new Set(first.map(window => window.kind))
442  return [...first, ...second.filter(window => !kinds.has(window.kind))]
443}
444
445const DETAIL_FONT_SIZE_PX = 12
446const DETAIL_LINE_HEIGHT_PX = 16
447// Consolas advances 0.55 em per character.
448const DETAIL_CHARACTER_WIDTH_PX = DETAIL_FONT_SIZE_PX * 0.55
449const DETAIL_TEXT_COLOR = '#8a8a8a'
450
451export function detailBlockSize(lines: readonly string[]): { width: number; height: number } {
452  const longest = lines.reduce((maximum, line) => Math.max(maximum, line.length), 0)
453  return {
454    width: Math.ceil(longest * DETAIL_CHARACTER_WIDTH_PX) + 4,
455    height: lines.length * DETAIL_LINE_HEIGHT_PX + 4,
456  }
457}
458
459// The detail block in Consolas: one line per figure, spaces kept so the
460// colons line up (Text takes no font, so the block is drawn as SVG text).
461export function detailBlockSvg(lines: readonly string[]): string {
462  const { width, height } = detailBlockSize(lines)
463  const rows = lines
464    .map(
465      (line, index) =>
466        `<text x="2" y="${2 + index * DETAIL_LINE_HEIGHT_PX + DETAIL_LINE_HEIGHT_PX / 2}" dominant-baseline="central" xml:space="preserve">${escapeXml(line)}</text>`,
467    )
468    .join('')
469  return (
470    svgOpen(width, height, width, height, lines.join('\n')) +
471    `<g font-family="Consolas, 'Cascadia Mono', monospace" font-size="${DETAIL_FONT_SIZE_PX}" fill="${DETAIL_TEXT_COLOR}" style="white-space:pre">` +
472    rows +
473    '</g></svg>'
474  )
475}
476
477// What a surface without Svg (the terminal) shows instead.
478export function usageText(widgets: UsageWidgets): string {
479  const percentOf = (window: UsageWindow | undefined) => wholePercent(window?.percentUsed ?? null)
480  return [
481    `${widgets.modelWeekly.name} ${percentOf(widgets.modelWeekly.window)}`,
482    `ctx ${widgets.context.figure.replace(' / ', '/')}`,
483    `5h ${percentOf(widgets.fiveHour)}`,
484    `1w ${percentOf(widgets.weekly)}`,
485  ].join(' · ')
486}
487
hooks/subagent_dots.ts 247 lines
1import type { SubagentRecord, SubagentState } from '../types'
2
3// The subagent dots: one dot per subagent of the session, in launch order.
4// Running dots pulse (SMIL, drawn by an interactive Svg); ended ones stand
5// still in their outcome's color. No engine calls here.
6
7// The engine's AgentStatus, spelled out so this module needs no engine types.
8export type ListedAgentStatus = 'pending' | 'running' | 'waiting' | 'idle' | 'completed' | 'failed' | 'killed'
9export type ListedAgent = { id: string; description: string; type: string; status: ListedAgentStatus }
10export type TurnEndReason = 'answer' | 'aborted' | 'refusal' | 'error'
11
12export const SUBAGENT_HISTORY_LIMIT = 50
13export const SUBAGENT_DOT_LIMIT = 12
14export const DOTS_HEIGHT_PX = 24
15const DOT_RADIUS = 4
16const DOT_PITCH = 12
17const OVERFLOW_TEXT_WIDTH = 22
18
19export const SUBAGENT_COLORS = {
20  running: '#d97757',
21  completed: '#5abd7b',
22  failed: '#ef6666',
23  stopped: '#9ca3af',
24} as const
25
26const STATE_LABELS: Record<SubagentState, string> = {
27  running: 'Running',
28  waiting: 'Waiting',
29  idle: 'Idle',
30  completed: 'Completed',
31  failed: 'Failed',
32  stopped: 'Stopped',
33}
34
35export function isActiveState(state: SubagentState): boolean {
36  return state === 'running' || state === 'waiting' || state === 'idle'
37}
38
39export function stateOfStatus(status: ListedAgentStatus): SubagentState {
40  switch (status) {
41    case 'pending':
42    case 'running':
43      return 'running'
44    case 'waiting':
45      return 'waiting'
46    case 'idle':
47      return 'idle'
48    case 'completed':
49      return 'completed'
50    case 'failed':
51      return 'failed'
52    case 'killed':
53      return 'stopped'
54  }
55}
56
57export function stateOfTurnEnd(reason: TurnEndReason): SubagentState {
58  if (reason === 'answer') {
59    return 'completed'
60  }
61  return reason === 'aborted' ? 'stopped' : 'failed'
62}
63
64function withState(record: SubagentRecord, state: SubagentState, nowMs: number): SubagentRecord {
65  if (record.state === state) {
66    return record
67  }
68  return { ...record, state, endedAtMs: isActiveState(state) ? undefined : (record.endedAtMs ?? nowMs) }
69}
70
71function keepNewest(records: SubagentRecord[]): SubagentRecord[] {
72  return records.length > SUBAGENT_HISTORY_LIMIT ? records.slice(records.length - SUBAGENT_HISTORY_LIMIT) : records
73}
74
75// A subagent the Agent tool just started, before the engine lists it.
76export function recordSpawn(
77  records: readonly SubagentRecord[],
78  agent: { id: string; description: string; type: string },
79  nowMs: number,
80): SubagentRecord[] {
81  if (records.some(record => record.id === agent.id)) {
82    return [...records]
83  }
84  return keepNewest([
85    ...records,
86    { id: agent.id, description: agent.description, type: agent.type, state: 'running', startedAtMs: nowMs, hasBeenListed: false },
87  ])
88}
89
90// A subagent's run ended (its turn.complete); a later listing may resume it.
91export function recordTurnEnd(
92  records: readonly SubagentRecord[],
93  id: string,
94  reason: TurnEndReason,
95  nowMs: number,
96): SubagentRecord[] {
97  return records.map(record => (record.id === id ? withState(record, stateOfTurnEnd(reason), nowMs) : record))
98}
99
100// The engine's list wins for every agent it lists. It drops an agent's task a
101// while after the agent ends, so one missing from the list keeps its last
102// state; an active one that was listed before and is gone ended unseen, and
103// is shown as stopped.
104export function mergeListedAgents(
105  records: readonly SubagentRecord[],
106  listed: readonly ListedAgent[],
107  nowMs: number,
108): SubagentRecord[] {
109  const listedById = new Map(listed.map(agent => [agent.id, agent]))
110  const merged = records.map(record => {
111    const agent = listedById.get(record.id)
112    if (agent === undefined) {
113      return record.hasBeenListed && isActiveState(record.state) ? withState(record, 'stopped', nowMs) : record
114    }
115    const updated = withState(record, stateOfStatus(agent.status), nowMs)
116    return updated.hasBeenListed ? updated : { ...updated, hasBeenListed: true }
117  })
118  const known = new Set(records.map(record => record.id))
119  for (const agent of listed) {
120    if (!known.has(agent.id)) {
121      const state = stateOfStatus(agent.status)
122      merged.push({
123        id: agent.id,
124        description: agent.description,
125        type: agent.type,
126        state,
127        startedAtMs: nowMs,
128        endedAtMs: isActiveState(state) ? undefined : nowMs,
129        hasBeenListed: true,
130      })
131    }
132  }
133  return keepNewest(merged)
134}
135
136export function countStates(records: readonly SubagentRecord[]): Record<SubagentState, number> {
137  const counts: Record<SubagentState, number> = { running: 0, waiting: 0, idle: 0, completed: 0, failed: 0, stopped: 0 }
138  for (const record of records) {
139    counts[record.state] += 1
140  }
141  return counts
142}
143
144// "Subagents: 2 running, 3 completed, 1 failed", the states in a fixed order.
145export function subagentSummary(records: readonly SubagentRecord[]): string {
146  const counts = countStates(records)
147  const parts = (Object.keys(STATE_LABELS) as SubagentState[])
148    .filter(state => counts[state] > 0)
149    .map(state => `${counts[state]} ${STATE_LABELS[state].toLowerCase()}`)
150  return `Subagents: ${parts.join(', ')}`
151}
152
153export function formatElapsed(durationMs: number): string {
154  const seconds = Math.max(0, Math.round(durationMs / 1000))
155  if (seconds < 60) {
156    return `${seconds} s`
157  }
158  const minutes = Math.floor(seconds / 60)
159  if (minutes < 60) {
160    return `${minutes} min ${seconds % 60} s`
161  }
162  return `${Math.floor(minutes / 60)} h ${minutes % 60} min`
163}
164
165// One line per subagent, newest first: "Running  Explore: Find the config",
166// an ended one with its run time, "Completed  Explore: Find the config (2 min 5 s)".
167// No running clock: the desktop app reloads the frame of an Svg whose source
168// changed, and every band redraw would make the dots flash.
169export function subagentLines(records: readonly SubagentRecord[]): string[] {
170  return [...records].reverse().map(record => {
171    const line = `${STATE_LABELS[record.state]}  ${record.type}: ${record.description}`
172    return record.endedAtMs === undefined ? line : `${line} (${formatElapsed(record.endedAtMs - record.startedAtMs)})`
173  })
174}
175
176export function escapeXml(text: string): string {
177  return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
178}
179
180export function subagentDotsWidth(records: readonly SubagentRecord[]): number {
181  const shown = Math.min(records.length, SUBAGENT_DOT_LIMIT)
182  return (records.length > SUBAGENT_DOT_LIMIT ? OVERFLOW_TEXT_WIDTH : 0) + shown * DOT_PITCH
183}
184
185// Running dots breathe one after another; waiting and idle ones are hollow,
186// a waiting one breathing slowly; ended ones are still.
187function dotMarkup(record: SubagentRecord, centerX: number, index: number): string {
188  const centerY = DOTS_HEIGHT_PX / 2
189  const delay = `${(index * 0.15).toFixed(2)}s`
190  switch (record.state) {
191    case 'running':
192      return (
193        `<circle cx="${centerX}" cy="${centerY}" r="${DOT_RADIUS}" fill="${SUBAGENT_COLORS.running}">` +
194        `<animate attributeName="r" values="${DOT_RADIUS};${DOT_RADIUS * 0.6};${DOT_RADIUS}" dur="1.2s" begin="${delay}" repeatCount="indefinite"/>` +
195        `<animate attributeName="opacity" values="1;0.3;1" dur="1.2s" begin="${delay}" repeatCount="indefinite"/>` +
196        '</circle>'
197      )
198    case 'waiting':
199      return (
200        `<circle cx="${centerX}" cy="${centerY}" r="${DOT_RADIUS - 0.6}" fill="none" stroke="${SUBAGENT_COLORS.running}" stroke-width="1.2">` +
201        `<animate attributeName="opacity" values="1;0.35;1" dur="2.4s" begin="${delay}" repeatCount="indefinite"/>` +
202        '</circle>'
203      )
204    case 'idle':
205      return `<circle cx="${centerX}" cy="${centerY}" r="${DOT_RADIUS - 0.6}" fill="none" stroke="${SUBAGENT_COLORS.running}" stroke-width="1.2"/>`
206    case 'stopped':
207      return `<circle cx="${centerX}" cy="${centerY}" r="${DOT_RADIUS - 0.6}" fill="none" stroke="${SUBAGENT_COLORS.stopped}" stroke-width="1.2"/>`
208    case 'completed':
209    case 'failed':
210      return `<circle cx="${centerX}" cy="${centerY}" r="${DOT_RADIUS}" fill="${SUBAGENT_COLORS[record.state]}"/>`
211  }
212}
213
214// The newest SUBAGENT_DOT_LIMIT dots, oldest left; "+n" before them counts
215// the older ones not drawn. The title is the hover tooltip.
216export function subagentDotsSvg(records: readonly SubagentRecord[], title: string): string {
217  const width = subagentDotsWidth(records)
218  const hidden = Math.max(0, records.length - SUBAGENT_DOT_LIMIT)
219  const shown = records.slice(hidden)
220  const offset = hidden > 0 ? OVERFLOW_TEXT_WIDTH : 0
221  const overflow =
222    hidden > 0
223      ? `<text x="${OVERFLOW_TEXT_WIDTH - 3}" y="${DOTS_HEIGHT_PX / 2 + 4}" text-anchor="end" font-family="system-ui, sans-serif"` +
224        ` font-size="11" fill="${SUBAGENT_COLORS.stopped}">+${hidden}</text>`
225      : ''
226  return (
227    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${DOTS_HEIGHT_PX}" viewBox="0 0 ${width} ${DOTS_HEIGHT_PX}" role="img">` +
228    `<title>${escapeXml(title)}</title>` +
229    overflow +
230    shown.map((record, index) => dotMarkup(record, offset + index * DOT_PITCH + DOT_PITCH / 2, index)).join('') +
231    '</svg>'
232  )
233}
234
235// What a surface without Svg (the terminal) shows instead: "Agents 2 running · 3 done · 1 failed".
236export function subagentText(records: readonly SubagentRecord[]): string {
237  const counts = countStates(records)
238  const active = counts.running + counts.waiting + counts.idle
239  const parts = [
240    active > 0 ? `${active} running` : '',
241    counts.completed > 0 ? `${counts.completed} done` : '',
242    counts.failed > 0 ? `${counts.failed} failed` : '',
243    counts.stopped > 0 ? `${counts.stopped} stopped` : '',
244  ].filter(part => part !== '')
245  return `Agents ${parts.join(' · ')}`
246}
247
hooks/monitor_clock.ts 320 lines
1import type { MonitorRecord } from '../types'
2import { DOTS_HEIGHT_PX, SUBAGENT_COLORS, escapeXml } from './subagent_dots'
3
4// The waiting clocks: one clock per Monitor of the main conversation that is
5// still watching, so a conversation idle on a Monitor does not look finished.
6// A clock blinks at 1/2 of a running subagent dot's rate and shows the time
7// left before its Monitor expires. No engine calls here.
8
9export const MONITOR_HISTORY_LIMIT = 20
10export const MONITOR_CLOCK_LIMIT = 6
11// The Monitor's own expiry notification arrives at its deadline; past this
12// grace the clock stops even if the notification was missed.
13export const MONITOR_DEADLINE_GRACE_MS = 60_000
14const CLOCK_RADIUS = 6.2
15const CLOCK_SIZE = 18
16const COUNTDOWN_FONT_PX = 11
17// Roughly one digit's advance at COUNTDOWN_FONT_PX, and the gap after a countdown.
18const COUNTDOWN_CHARACTER_WIDTH = 6.6
19const COUNTDOWN_GAP = 6
20// The running subagent dot pulses over 1.2 s; the clock at 1/2 of that rate.
21const CLOCK_PERIOD_S = 2.4
22// Below this the countdown counts seconds and needs a redraw every poll.
23export const COUNTDOWN_SECONDS_BELOW_MS = 60_000
24
25export type MonitorEnding = { id: string; status: string }
26
27export function isActiveMonitor(record: MonitorRecord): boolean {
28  return record.endedAtMs === undefined
29}
30
31export function activeMonitors(records: readonly MonitorRecord[]): MonitorRecord[] {
32  return records.filter(isActiveMonitor)
33}
34
35function keepNewest(records: MonitorRecord[]): MonitorRecord[] {
36  return records.length > MONITOR_HISTORY_LIMIT ? records.slice(records.length - MONITOR_HISTORY_LIMIT) : records
37}
38
39// What the Monitor tool answered: `{ taskId, timeoutMs, persistent }`.
40export function readMonitorStart(
41  result: unknown,
42  description: string,
43  nowMs: number,
44): MonitorRecord | null {
45  if (typeof result !== 'object' || result === null) {
46    return null
47  }
48  const output = result as { taskId?: unknown; timeoutMs?: unknown; persistent?: unknown }
49  if (typeof output.taskId !== 'string' || output.taskId === '') {
50    return null
51  }
52  const isPersistent = output.persistent === true || output.timeoutMs === 0
53  const timeoutMs = typeof output.timeoutMs === 'number' ? output.timeoutMs : undefined
54  return {
55    id: output.taskId,
56    description,
57    startedAtMs: nowMs,
58    deadlineMs: isPersistent || timeoutMs === undefined ? undefined : nowMs + timeoutMs,
59  }
60}
61
62export function recordMonitorStart(records: readonly MonitorRecord[], monitor: MonitorRecord): MonitorRecord[] {
63  return keepNewest([...records.filter(record => record.id !== monitor.id), monitor])
64}
65
66export function recordMonitorEnd(
67  records: readonly MonitorRecord[],
68  id: string,
69  outcome: string,
70  nowMs: number,
71): MonitorRecord[] {
72  return records.map(record =>
73    record.id === id && isActiveMonitor(record) ? { ...record, endedAtMs: nowMs, outcome } : record,
74  )
75}
76
77// The ending notifications in a task-notification text: a block that carries
78// a `<status>`; a Monitor's event blocks carry none.
79export function parseNotificationEndings(text: string): MonitorEnding[] {
80  if (!text.includes('<task-notification>')) {
81    return []
82  }
83  const endings: MonitorEnding[] = []
84  for (const block of text.split('<task-notification>').slice(1)) {
85    const id = /<task-id>([^<]+)<\/task-id>/.exec(block)?.[1]?.trim()
86    const status = /<status>([^<]+)<\/status>/.exec(block)?.[1]?.trim()
87    if (id !== undefined && status !== undefined && id !== '' && status !== '') {
88      endings.push({ id, status })
89    }
90  }
91  return endings
92}
93
94export function applyEndings(
95  records: readonly MonitorRecord[],
96  endings: readonly MonitorEnding[],
97  nowMs: number,
98): MonitorRecord[] {
99  return endings.reduce<MonitorRecord[]>((current, ending) => recordMonitorEnd(current, ending.id, ending.status, nowMs), [
100    ...records,
101  ])
102}
103
104// Ends the clocks past their deadline and its grace: the expiry notification
105// was missed, or a restart of the engine killed the Monitor without one.
106export function expireMonitors(records: readonly MonitorRecord[], nowMs: number): MonitorRecord[] {
107  return records.map(record => {
108    if (!isActiveMonitor(record)) {
109      return record
110    }
111    if (record.deadlineMs !== undefined && nowMs > record.deadlineMs + MONITOR_DEADLINE_GRACE_MS) {
112      return { ...record, endedAtMs: record.deadlineMs, outcome: 'expired' }
113    }
114    return record
115  })
116}
117
118type TranscriptBlock = { type?: unknown; id?: unknown; name?: unknown; input?: unknown; tool_use_id?: unknown; text?: unknown }
119type TranscriptLine = {
120  type?: unknown
121  timestamp?: unknown
122  message?: { content?: unknown }
123  toolUseResult?: unknown
124  // A queue-operation line's queued text.
125  content?: unknown
126  // A queued_command attachment's prompt.
127  attachment?: { prompt?: unknown }
128}
129
130function lineBlocks(line: TranscriptLine): TranscriptBlock[] {
131  const content = line.message?.content
132  if (typeof content === 'string') {
133    return [{ type: 'text', text: content }]
134  }
135  return Array.isArray(content) ? content.filter((block): block is TranscriptBlock => typeof block === 'object' && block !== null) : []
136}
137
138function lineTimeMs(line: TranscriptLine, fallbackMs: number): number {
139  const parsed = typeof line.timestamp === 'string' ? Date.parse(line.timestamp) : Number.NaN
140  return Number.isFinite(parsed) ? parsed : fallbackMs
141}
142
143// The Monitors of a transcript (.jsonl): each Monitor call with its result's
144// task id, ended by a notification with a status or by a TaskStop. Only the
145// lines that can matter are parsed, so a long transcript stays cheap.
146export function parseTranscriptMonitors(transcript: string, nowMs: number): MonitorRecord[] {
147  const descriptions = new Map<string, string>()
148  let records: MonitorRecord[] = []
149  for (const raw of transcript.split('\n')) {
150    const isMonitorCall = raw.includes('"name":"Monitor"')
151    const isStartResult = raw.includes('"toolUseResult"') && raw.includes('"taskId"')
152    const isTaskStop = raw.includes('"name":"TaskStop"')
153    const isNotification = raw.includes('<task-notification>')
154    if (!isMonitorCall && !isStartResult && !isTaskStop && !isNotification) {
155      continue
156    }
157    let line: TranscriptLine
158    try {
159      line = JSON.parse(raw) as TranscriptLine
160    } catch {
161      continue
162    }
163    const atMs = lineTimeMs(line, nowMs)
164    const blocks = lineBlocks(line)
165    if (line.type === 'assistant') {
166      for (const block of blocks) {
167        if (block.type !== 'tool_use' || typeof block.id !== 'string') {
168          continue
169        }
170        const input = (typeof block.input === 'object' && block.input !== null ? block.input : {}) as {
171          description?: unknown
172          task_id?: unknown
173          shell_id?: unknown
174        }
175        if (block.name === 'Monitor') {
176          descriptions.set(block.id, typeof input.description === 'string' ? input.description : 'Monitor')
177        } else if (block.name === 'TaskStop') {
178          const taskId = typeof input.task_id === 'string' ? input.task_id : input.shell_id
179          if (typeof taskId === 'string') {
180            records = recordMonitorEnd(records, taskId, 'stopped', atMs)
181          }
182        }
183      }
184      continue
185    }
186    // A notification is stored as it is queued (queue-operation), as a
187    // queued_command attachment, or as a user message when it is dequeued.
188    if (line.type === 'queue-operation') {
189      if (typeof line.content === 'string') {
190        records = applyEndings(records, parseNotificationEndings(line.content), atMs)
191      }
192      continue
193    }
194    if (typeof line.attachment?.prompt === 'string') {
195      records = applyEndings(records, parseNotificationEndings(line.attachment.prompt), atMs)
196      continue
197    }
198    if (line.type !== 'user') {
199      continue
200    }
201    const toolResult = blocks.find(block => block.type === 'tool_result')
202    if (toolResult !== undefined) {
203      const description = typeof toolResult.tool_use_id === 'string' ? descriptions.get(toolResult.tool_use_id) : undefined
204      const started = description === undefined ? null : readMonitorStart(line.toolUseResult, description, atMs)
205      if (started !== null) {
206        records = recordMonitorStart(records, started)
207      }
208      continue
209    }
210    // A notification the session received; quoted ones inside tool results
211    // were skipped above.
212    const text = blocks.map(block => (typeof block.text === 'string' ? block.text : '')).join('\n')
213    records = applyEndings(records, parseNotificationEndings(text), atMs)
214  }
215  return records
216}
217
218// Adds the transcript's Monitors to the recorded ones; an ending either side
219// knows wins.
220export function mergeMonitorRecords(current: readonly MonitorRecord[], parsed: readonly MonitorRecord[]): MonitorRecord[] {
221  const byId = new Map(current.map(record => [record.id, record]))
222  for (const record of parsed) {
223    const known = byId.get(record.id)
224    if (known === undefined || (isActiveMonitor(known) && !isActiveMonitor(record))) {
225      byId.set(record.id, known === undefined ? record : { ...known, endedAtMs: record.endedAtMs, outcome: record.outcome })
226    }
227  }
228  return keepNewest([...byId.values()].sort((first, second) => first.startedAtMs - second.startedAtMs))
229}
230
231export function monitorSummary(active: readonly MonitorRecord[]): string {
232  return `Waiting on ${active.length} monitor${active.length === 1 ? '' : 's'}`
233}
234
235// One line per waiting Monitor, newest first: "Monitor: round-29 harvest (stops in 27m)".
236// The time left is the clock's own countdown, so the tooltip changes only when
237// the countdown does: the desktop app reloads the frame of an Svg whose source
238// changed, and every band redraw would make the clocks flash.
239export function monitorLines(active: readonly MonitorRecord[], nowMs: number): string[] {
240  return [...active].reverse().map(record => {
241    const remaining = record.deadlineMs === undefined ? 'no deadline' : `stops in ${monitorCountdown(record, nowMs)}`
242    return `Monitor: ${record.description} (${remaining})`
243  })
244}
245
246function shownClocks(active: readonly MonitorRecord[]): readonly MonitorRecord[] {
247  return active.slice(Math.max(0, active.length - MONITOR_CLOCK_LIMIT))
248}
249
250// The time left before a Monitor expires: "12m" (whole minutes, rounded up),
251// "45s" in its last minute, "∞" without a deadline.
252export function monitorCountdown(record: MonitorRecord, nowMs: number): string {
253  if (record.deadlineMs === undefined) {
254    return '∞'
255  }
256  const remainingMs = Math.max(0, record.deadlineMs - nowMs)
257  if (remainingMs < COUNTDOWN_SECONDS_BELOW_MS) {
258    return `${Math.ceil(remainingMs / 1000)}s`
259  }
260  return `${Math.ceil(remainingMs / 60_000)}m`
261}
262
263// Whether a shown countdown counts seconds, so the clocks redraw every poll.
264export function isCountingSeconds(active: readonly MonitorRecord[], nowMs: number): boolean {
265  return shownClocks(active).some(
266    record => record.deadlineMs !== undefined && record.deadlineMs - nowMs < COUNTDOWN_SECONDS_BELOW_MS,
267  )
268}
269
270function countdownWidth(countdown: string): number {
271  return Math.ceil(countdown.length * COUNTDOWN_CHARACTER_WIDTH) + COUNTDOWN_GAP
272}
273
274export function monitorClocksWidth(active: readonly MonitorRecord[], nowMs: number): number {
275  return shownClocks(active).reduce((width, record) => width + CLOCK_SIZE + countdownWidth(monitorCountdown(record, nowMs)), 0)
276}
277
278function countdownMarkup(left: number, countdown: string): string {
279  return (
280    `<text x="${left}" y="${DOTS_HEIGHT_PX / 2}" dominant-baseline="central" font-size="${COUNTDOWN_FONT_PX}" ` +
281    `font-family="system-ui, sans-serif" fill="${SUBAGENT_COLORS.running}">${escapeXml(countdown)}</text>`
282  )
283}
284
285function clockMarkup(centerX: number): string {
286  const centerY = DOTS_HEIGHT_PX / 2
287  const color = SUBAGENT_COLORS.running
288  return (
289    `<g fill="none" stroke="${color}" stroke-width="1.4" stroke-linecap="round">` +
290    `<circle cx="${centerX}" cy="${centerY}" r="${CLOCK_RADIUS}"/>` +
291    `<path d="M${centerX} ${centerY - 3.6}V${centerY}L${centerX + 2.6} ${centerY + 1.6}"/>` +
292    `<animate attributeName="opacity" values="1;0.3;1" dur="${CLOCK_PERIOD_S}s" repeatCount="indefinite"/>` +
293    '</g>'
294  )
295}
296
297// The newest MONITOR_CLOCK_LIMIT clocks, oldest left, each followed by its
298// countdown. The title is the hover tooltip.
299export function monitorClocksSvg(active: readonly MonitorRecord[], title: string, nowMs: number): string {
300  const width = monitorClocksWidth(active, nowMs)
301  let left = 0
302  const parts: string[] = []
303  for (const record of shownClocks(active)) {
304    const countdown = monitorCountdown(record, nowMs)
305    parts.push(clockMarkup(left + CLOCK_SIZE / 2), countdownMarkup(left + CLOCK_SIZE, countdown))
306    left += CLOCK_SIZE + countdownWidth(countdown)
307  }
308  return (
309    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${DOTS_HEIGHT_PX}" viewBox="0 0 ${width} ${DOTS_HEIGHT_PX}" role="img">` +
310    `<title>${escapeXml(title)}</title>` +
311    parts.join('') +
312    '</svg>'
313  )
314}
315
316// What a surface without Svg (the terminal) shows instead: "Monitors 1 waiting".
317export function monitorText(active: readonly MonitorRecord[]): string {
318  return `Monitors ${active.length} waiting`
319}
320
hooks/external_buttons.ts 144 lines
1// Buttons other programs ask the toolbar to show, with no engine calls.
2//
3// A program shows a button by writing `<id>.json` into the button folder,
4// `%TEMP%\claude_desktop_toolbar\buttons`, and removes it by deleting the file.
5// A press writes `<id>.pressed` beside it; the program watches for that file,
6// does what the press means, and deletes both files. The file holds:
7//
8//   label          the button text (required)
9//   animation      "dots": three dots cycle after the label; absent or "none": still
10//   pressed_label  the text once pressed, until the program removes the button
11//   session_id     the conversation it belongs to; absent or empty: every one
12//   expires_at_ms  when to stop showing it if the program never removes it
13//
14// The program may rewrite the file at any time to change the label.
15
16import type { ExternalButtonAnimation, ExternalButtonRecord } from '../types'
17
18export const BUTTON_FOLDER_NAME = 'claude_desktop_toolbar'
19export const BUTTON_SUBFOLDER_NAME = 'buttons'
20export const BUTTON_FILE_SUFFIX = '.json'
21export const PRESS_FILE_SUFFIX = '.pressed'
22export const EXTERNAL_BUTTON_POLL_MS = 500
23// A file without its own expiry stops showing this long after its last write,
24// so a program killed before it could delete the file leaves no button behind.
25export const DEFAULT_BUTTON_LIFETIME_MS = 10 * 60 * 1000
26// At most this many buttons draw; the newest files win.
27export const EXTERNAL_BUTTON_LIMIT = 4
28export const DOT_FRAME_COUNT = 3
29const LABEL_LIMIT = 80
30const NO_BREAK_SPACE = ' '
31
32export type ButtonFile = { name: string; mtimeMs: number; text: string }
33
34// One requested button: parsed from its file, and drawn from the record the
35// toolbar keeps in state.
36export class ExternalButton {
37  constructor(
38    readonly id: string,
39    readonly label: string,
40    readonly animation: ExternalButtonAnimation,
41    readonly pressedLabel: string,
42    readonly sessionId: string,
43    readonly expiresAtMs: number,
44    readonly writtenAtMs: number,
45  ) {
46    this.pressFileName = `${id}${PRESS_FILE_SUFFIX}`
47  }
48
49  readonly pressFileName: string
50
51  // The button a file asks for, or null for a file that is not one.
52  static parse(file: ButtonFile): ExternalButton | null {
53    if (!file.name.endsWith(BUTTON_FILE_SUFFIX)) {
54      return null
55    }
56    const id = file.name.slice(0, -BUTTON_FILE_SUFFIX.length)
57    if (!/^[A-Za-z0-9_.-]+$/.test(id)) {
58      return null
59    }
60    let value: unknown
61    try {
62      value = JSON.parse(file.text)
63    } catch {
64      return null
65    }
66    if (typeof value !== 'object' || value === null) {
67      return null
68    }
69    const fields = value as Record<string, unknown>
70    const label = cleanLabel(fields.label)
71    if (label === '') {
72      return null
73    }
74    const animation: ExternalButtonAnimation = fields.animation === 'dots' ? 'dots' : 'none'
75    const pressedLabel = cleanLabel(fields.pressed_label)
76    const sessionId = typeof fields.session_id === 'string' ? fields.session_id : ''
77    const expiresAtMs =
78      typeof fields.expires_at_ms === 'number' && Number.isFinite(fields.expires_at_ms)
79        ? fields.expires_at_ms
80        : file.mtimeMs + DEFAULT_BUTTON_LIFETIME_MS
81
82    return new ExternalButton(id, label, animation, pressedLabel === '' ? label : pressedLabel, sessionId, expiresAtMs, file.mtimeMs)
83  }
84
85  static fromRecord(record: ExternalButtonRecord): ExternalButton {
86    return new ExternalButton(record.id, record.label, record.animation, record.pressedLabel, '', Infinity, 0)
87  }
88
89  isShownIn(sessionId: string, nowMs: number): boolean {
90    return (this.sessionId === '' || this.sessionId === sessionId) && nowMs <= this.expiresAtMs
91  }
92
93  // The text drawn now. Dots run `...`, `.`, `..` and are padded with no-break
94  // spaces so the row beside the button does not shift.
95  text(frame: number, isPressed: boolean): string {
96    const base = isPressed ? this.pressedLabel : this.label
97    if (this.animation !== 'dots') {
98      return base
99    }
100    const dotCount = ((frame + DOT_FRAME_COUNT - 1) % DOT_FRAME_COUNT) + 1
101
102    return `${base} ${'.'.repeat(dotCount).padEnd(DOT_FRAME_COUNT, NO_BREAK_SPACE)}`
103  }
104
105  toRecord(isPressed: boolean): ExternalButtonRecord {
106    return { id: this.id, label: this.label, animation: this.animation, pressedLabel: this.pressedLabel, isPressed }
107  }
108}
109
110function cleanLabel(value: unknown): string {
111  if (typeof value !== 'string') {
112    return ''
113  }
114  const flat = value.replace(/\s+/g, ' ').trim()
115
116  return flat.length > LABEL_LIMIT ? `${flat.slice(0, LABEL_LIMIT - 1)}…` : flat
117}
118
119// The records the toolbar draws from the files found: this session's live
120// buttons, newest first, each pressed once its press file is there.
121export function buttonRecords(
122  files: readonly ButtonFile[],
123  pressFileNames: ReadonlySet<string>,
124  sessionId: string,
125  nowMs: number,
126): ExternalButtonRecord[] {
127  return files
128    .map(file => ExternalButton.parse(file))
129    .filter((button): button is ExternalButton => button !== null && button.isShownIn(sessionId, nowMs))
130    .sort((first, second) => second.writtenAtMs - first.writtenAtMs || first.id.localeCompare(second.id))
131    .slice(0, EXTERNAL_BUTTON_LIMIT)
132    .map(button => button.toRecord(pressFileNames.has(button.pressFileName)))
133}
134
135// Whether any button animates, so the frame has to move on.
136export function isAnimating(records: readonly ExternalButtonRecord[]): boolean {
137  return records.some(record => record.animation === 'dots')
138}
139
140// The note a press writes, for the program's own log.
141export function pressNote(sessionId: string, nowMs: number): string {
142  return JSON.stringify({ pressed_at_ms: nowMs, session_id: sessionId })
143}
144
types/index.d.ts 84 lines
1// Most recently used first, at most 100 absolute paths.
2export type RecentFolderList = string[]
3
4// One rate-limit window as `$.session.usage()` reports it (five_hour, seven_day, seven_day_<tier>...).
5export type UsageWindow = { kind: string; percentUsed: number; resetsAt?: string }
6
7// The figures the usage widgets draw, taken from `$.session.usage()` / `session.measure`.
8export type UsageSnapshot = {
9  context: { tokens?: number; window: number; percent?: number }
10  rateLimits: UsageWindow[]
11}
12
13// A subagent as the dots draw it: running, waiting (held) or idle (a teammate
14// between turns) while active; completed, failed or stopped once ended.
15export type SubagentState = 'running' | 'waiting' | 'idle' | 'completed' | 'failed' | 'stopped'
16
17export type SubagentRecord = {
18  id: string
19  description: string
20  type: string
21  state: SubagentState
22  startedAtMs: number
23  endedAtMs?: number
24  // Whether `$.agent.list()` has listed it; one listed and then gone ended unseen.
25  hasBeenListed: boolean
26}
27
28// A Monitor the main conversation started: active until its end notification,
29// a TaskStop, or its deadline (absent for a persistent one) passes.
30export type MonitorRecord = {
31  id: string
32  description: string
33  startedAtMs: number
34  deadlineMs?: number
35  endedAtMs?: number
36  // How it ended: the notification's status (completed, failed, killed...),
37  // `stopped` for a TaskStop, `expired` past its deadline.
38  outcome?: string
39}
40
41// The outcome of the last Copy Transcript Path press, shown on the button.
42export type CopyFeedback = 'copied' | 'failed'
43
44// How a button another program asked for moves: `dots` cycles three dots after its label.
45export type ExternalButtonAnimation = 'dots' | 'none'
46
47// A button another program asked for through the button folder.
48export type ExternalButtonRecord = {
49  id: string
50  label: string
51  animation: ExternalButtonAnimation
52  pressedLabel: string
53  // Pressed and waiting for the program to remove it.
54  isPressed: boolean
55}
56
57// The buttons drawn now, newest first, and the animation frame they draw.
58export type ExternalButtonState = { buttons: ExternalButtonRecord[]; frame: number }
59
60declare module 'claude-code' {
61  interface PluginState {
62    'conversation-toolbar': {
63      recentFolders: RecentFolderList
64      usage: UsageSnapshot | null
65      usageDetailsPinned: boolean
66      // The folder a move was asked for that the session has not reached yet
67      // (the desktop app moves it when a turn ends); null when none is pending.
68      pendingMove: string | null
69      // How many dots the pending-move note draws now, 1 to 6, cycling.
70      movingDots: number
71      // This session's subagents in launch order, at most 50, kept after the
72      // engine drops them from `$.agent.list()`.
73      subagents: SubagentRecord[]
74      // This session's Monitors, at most 20, the newest last.
75      monitors: MonitorRecord[]
76      // What the Copy Transcript Path button says for a moment after a press;
77      // null shows its own label.
78      copyFeedback: CopyFeedback | null
79      // Buttons other programs ask for, with their frame.
80      externalButtons: ExternalButtonState
81    }
82  }
83}
84