SLOPSHOPPER

session-pulse

Every open Claude Code session on one live board: a progress bar per session, a rough time left, click a row to switch to that session, x to hide it (/pulse)

panebandguardcommandprocesstimer
v0.1.8MITupdated 2026-10-26meatball-cat/my-mods/session-pulse
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-pulse
│ ┃ Sessions ✕ › fix the failing auth test and add an audit log call │ ┃ 1 session · 1 finished │ ┃ Band: full Alerts: on ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ Finished ⏺ Update(src/auth.ts) │ ┃ ✓ go-preview-session ━━━━━━━━━━ 100% just no ⎿ Added 2 lines, removed 1 line │ ┃ Finished just now · took 42s · app · Termin… ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ Click a title to switch · × hides · /pulse … │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /pulse │ │ ✓ go-preview-session ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% just now done × [ pane ] ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
✓ go-preview-session ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% just now done × [ pane ] ⟨Claude Code's own drawing⟩
Pane · Sessions
1 session · 1 finished Band: full Alerts: on Finished ✓ go-preview-session ━━━━━━━━━━ 100% just now done × Finished just now · took 42s · app · Terminal Click a title to switch · × hides · /pulse help
README

Session Pulse

Every open Claude Code session on one live board, above the prompt:

● Edit the opening animation   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  72%  ~30m      ×
✓ Fix the login bug            ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100%  3m ago    ×
● Write the newsletter         ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  45%  ~12m      ×
● Review the payments PR       ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  60%  needs you ×
  • A row per live session: working, waiting on you, or finished within the last hour. The bar warms from orange to yellow-green as it fills, green with a check when done, blue when the session needs you (a permission or a question), grey when interrupted, red on an error.
  • A rough time left at the end of each row (~30m, <1m).
  • Click a row to switch to that session. A desktop session opens in the Claude app (claude://code/continue?session=local_…). A terminal session can't be focused from here, so its cd … && claude --resume … command is copied.
  • × hides a row until that session starts its next turn.
  • Alerts: a toast when another session finishes or needs you.
  • /pulse opens the whole board in a pane: idle, hidden and silent sessions too, each with what it is doing (Editing register.tsx, plan 3/5, running 4m).

Commands

CommandDoes
/pulseOpen or close the board pane
/pulse compact · full · offOne summary line, a row per session, or no band
/pulse alerts on · offToasts when another session finishes or needs you
/pulse showBring hidden rows back
/pulse name <title>Rename this session on the board (no title: back to automatic)
/pulse demo · demo offFive made-up sessions for three minutes, to see every state

If another plugin owns /pulse, the command is /session-pulse.

How the percent is worked out

  • With a plan (TodoWrite, the Task tools, savvy-progress, or a goal-meter goal): finished tasks out of the plan, with the task in progress creeping forward at the pace the earlier tasks took. Time left is that pace times the work left.
  • Without a plan: how long turns usually take, learned from this session's last turns and every session's median (90 s before anything is learned). At the usual length the bar shows two thirds; it slows as a turn runs long and only reaches 100% when the turn ends. Time spent waiting on you doesn't count.

It's an estimate, marked with ~. It never moves backwards during a turn.

Where it keeps things

  • ~/.claude/mods-data/session-pulse/s-<session>.json: each session's heartbeat (state, title, timing, plan), rewritten at least every 15 s. A session silent for 75 s shows as not responding; files older than 12 h are removed.
  • ~/.claude/mods-data/session-pulse/hide-<session>.json: rows you hid.
  • The plugin's store: settings and recent turn lengths.
  • Titles come from the desktop app's own session title when there is one, else the first prompt.
  • While Recording Mode is on (~/.claude/mods-data/recording.json), rows show as Session 1, Session 2 with no activity or folder.

No network calls, no model requests, nothing added to Claude's prompt.

Source 3 files
hooks/register.tsx 1480 lines
1// Session Pulse: every open Claude Code session on one live board.
2// - Each session writes a heartbeat, ~/.claude/mods-data/session-pulse/s-<id>.json:
3//   its state (working, waiting on you, done, stopped, error, idle), when its turn
4//   started, how long that turn should take, its task plan when it keeps one
5//   (TodoWrite, the Task tools, savvy-progress, goal-meter) and what it is doing.
6// - The band above the prompt draws a row per live session: a colored dot, the
7//   title, a bar, the percent and a rough time left. Click a row to switch to that
8//   session (the desktop app opens it; for a terminal session its resume command
9//   is copied). x hides a row until that session starts its next turn.
10// - /pulse opens the whole board in a pane: idle, hidden and silent sessions too,
11//   with what each one is doing. /pulse compact|full|off, /pulse alerts on|off,
12//   /pulse show (bring hidden rows back), /pulse name <title>.
13// - The percent comes from the plan when there is one, else from how long turns
14//   usually take, learned per session and across sessions. The bar warms from
15//   orange to yellow-green as it fills; blue means the session needs you.
16// - It sends no model requests and adds nothing to Claude's prompt.
17
18import { atom, read, update } from 'claude-code'
19import type { CommandRunResult, Elements, EngineInterface, Register, RenderElement, RenderSurface, ToolCallResult } from 'claude-code'
20
21import type { Beat, Plan, Prefs, PulseState, Row } from '../types'
22import {
23  COLOR,
24  DEFAULT_TURN_MS,
25  asDigitFont,
26  HOST_ID,
27  HOUR,
28  MIN,
29  SEC,
30  SVG_HEIGHT,
31  activityOf,
32  askNeed,
33  agoText,
34  asBeat,
35  barCells,
36  barSvg,
37  basename,
38  cells,
39  clamp,
40  clip,
41  colorOf,
42  demoTiming,
43  durText,
44  estimate,
45  etaText,
46  expectedMs,
47  fit,
48  goalPlan,
49  iconOf,
50  permissionNeed,
51  savvyPlan,
52  tasksPlan,
53  titleFromPrompt,
54  todosPlan,
55  withChange,
56  workingColor,
57} from './estimate'
58import type { DigitFont, TaskEntry } from './estimate'
59
60const rowsAtom = atom({ plugin: 'session-pulse', key: 'rows' } as const, [])
61const nowAtom = atom({ plugin: 'session-pulse', key: 'now' } as const, 0)
62const prefsAtom = atom({ plugin: 'session-pulse', key: 'prefs' } as const, { mode: 'full', alerts: true })
63const maskedAtom = atom({ plugin: 'session-pulse', key: 'isMasked' } as const, false)
64
65const PANE = 'session-pulse'
66const DATA = '/.claude/mods-data/session-pulse'
67const DESKTOP_SESSIONS = '/Library/Application Support/Claude/claude-code-sessions'
68const SAVVY_PROGRESS = 'mcp__savvy-progress__progress'
69const SAVVY_STEP = 'mcp__savvy-progress__step'
70const GOAL_TOOL = 'mcp__goal-meter__tasks'
71const BEAT_MS = 15 * SEC // a live session rewrites its file at least this often
72const STALE_MS = 75 * SEC // a file older than this belongs to a session that stopped answering
73const FORGET_MS = 12 * HOUR // files older than this are removed
74const RECENT_MS = 60 * MIN // a finished session stays on the band this long
75const MISSED_TURN_GRACE_MS = 15 * SEC // the band may draw before the engine marks a new turn running
76const HEARD_TURN_GRACE_MS = 3 * MIN // a turn this module heard start must look idle this long before it is settled
77const BAND_ROWS = 6
78// The status dot's column: a row's title and its detail line both start after it.
79const ICON_CELLS = 2
80const BEAT_FILE = /^s-([A-Za-z0-9-]{8,64})\.json$/
81const HIDE_FILE = /^hide-([A-Za-z0-9-]{8,64})\.json$/
82
83type Kit = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'>
84type SvgElement = Elements['desktop']['Svg']
85type Item = { row: Row; label: string }
86type View = { pct: number; pctText: string; color: string; tail: string; tailColor: string; tailHex: string; isLive: boolean; state: string; stateColor: string }
87type CachedFile = { mtimeMs: number; beat: Beat | null; hiddenAt: number }
88
89// This session
90let home = ''
91let dir = ''
92let hostId = ''
93let me: Beat | null = null
94let isTracked = false
95let isTicking = false
96let isBusy = false
97let isDirty = false
98let lastWrite = 0
99let titleFrom: 'name' | 'desktop' | 'prompt' | 'folder' = 'folder'
100let desktopRecord = ''
101let myTurns: number[] = []
102let pace: number[] = []
103let waitKind: '' | 'ask' | 'permission' = ''
104// The turn this module itself heard start (a reload loses it), when the engine's
105// band first said no turn was running, and whether a row was settled by that.
106let heardStartAt = 0
107let notWorkingSince = 0
108let isSettledEarly = false
109let commandName = 'pulse'
110const tasks = new Map<string, TaskEntry>()
111// The app's own digit outlines (scripts/digits-from-app-font.py), when extracted.
112let digitFont: DigitFont | null = null
113
114// What this session sees of the others
115const files = new Map<string, CachedFile>()
116const hidden = new Map<string, number>()
117const lastState = new Map<string, PulseState>()
118const highest = new Map<string, number>()
119// What each drawing site last showed per session, so the next drawing animates
120// from there: the bar grows, the changed digits roll.
121const lastShown = new Map<string, { pct: number; pctText: string }>()
122let hasScanned = false
123let ticks = 0
124let lastPrune = 0
125
126// /pulse demo: made-up sessions for a few minutes, never written to disk
127const DEMO_PREFIX = 'demo0000-'
128let demo: Beat[] = []
129let demoUntil = 0
130const demoHidden = new Set<string>()
131const isDemo = (id: string): boolean => id.startsWith(DEMO_PREFIX)
132
133const beatPath = (id: string): string => `${dir}/s-${id}.json`
134const hidePath = (id: string): string => `${dir}/hide-${id}.json`
135
136function freshBeat(id: string, surface: string, cwd: string, at: number): Beat {
137  return {
138    v: 1,
139    id,
140    hostId,
141    surface,
142    title: '',
143    project: basename(cwd),
144    cwd,
145    state: 'idle',
146    bornAt: at,
147    startedAt: 0,
148    endedAt: 0,
149    waitMs: 0,
150    waitingSince: 0,
151    tools: 0,
152    activity: '',
153    plan: null,
154    planAt: 0,
155    expectMs: DEFAULT_TURN_MS,
156    turns: 0,
157    lastMs: 0,
158    stopPct: 0,
159    agents: 0,
160    updatedAt: at,
161  }
162}
163
164function demoBeats(at: number): Beat[] {
165  const make = (i: number, title: string, project: string, over: Partial<Beat>): Beat => ({
166    ...freshBeat(`${DEMO_PREFIX}0000-0000-0000-00000000000${i}`, 'desktop', `/demo/${project}`, at - (10 - i) * MIN),
167    hostId: '',
168    title,
169    turns: 1,
170    ...over,
171  })
172  const working = (pct: number, etaMinutes: number, activity: string): Partial<Beat> => {
173    const timing = demoTiming(pct, etaMinutes * MIN)
174    return { state: 'working', startedAt: at - timing.workedMs, expectMs: timing.expectMs, activity }
175  }
176  return [
177    make(1, 'Edit the opening animation', 'promo-video', working(72, 30, 'Rendering frames')),
178    make(2, 'Fix the login bug', 'webapp', { state: 'done', startedAt: at - 9 * MIN, endedAt: at - 3 * MIN, lastMs: 6 * MIN, turns: 3 }),
179    make(3, 'Write the newsletter', 'newsletter', working(45, 12, 'Editing issue-42.md')),
180    make(4, 'Organize research notes', 'research', working(88, 5, 'Reading sources.md')),
181    make(5, 'Review the payments PR', 'payments', { state: 'waiting', startedAt: at - 4 * MIN, waitingSince: at - MIN, expectMs: 6 * MIN, activity: 'Waiting for your permission', need: 'allow bash', turns: 2 }),
182  ]
183}
184
185async function loadDigitFont($: EngineInterface): Promise<DigitFont | null> {
186  try {
187    const path = `${dir}/digits.json`
188    if (!(await $.fs.exists(path))) return null
189    return asDigitFont(JSON.parse(await $.fs.read(path)))
190  } catch {
191    return null
192  }
193}
194
195async function saveDemo($: EngineInterface, startedAt: number): Promise<void> {
196  try {
197    await $.store.set('demo', startedAt)
198  } catch {
199    // the demo ends with this load
200  }
201}
202
203// A demo started before a hot reload carries on where it was.
204async function restoreDemo($: EngineInterface, at: number): Promise<void> {
205  try {
206    const startedAt = await $.store.get('demo')
207    if (typeof startedAt === 'number' && startedAt > 0 && at < startedAt + 3 * MIN) {
208      demo = demoBeats(startedAt)
209      demoUntil = startedAt + 3 * MIN
210    }
211  } catch {
212    // no demo to restore
213  }
214}
215
216function beatOf(row: Row): Beat {
217  const { isSelf, isHidden, isStale, ...beat } = row
218  return beat
219}
220
221const isHiddenBeat = (b: Beat, hiddenAt: number): boolean => hiddenAt > 0 && b.startedAt <= hiddenAt
222
223const byBirth = (a: Row, b: Row): number => a.bornAt - b.bornAt || (a.id < b.id ? -1 : 1)
224
225function selfRow(): Row | null {
226  return me === null ? null : { ...me, isSelf: true, isHidden: isHiddenBeat(me, hidden.get(me.id) ?? 0), isStale: false }
227}
228
229function labelOf(row: Row, index: number, isMasked: boolean): string {
230  if (isMasked) return `session ${index + 1}`
231  // The session's name exactly as Claude Code shows it.
232  if (row.title) return row.title
233  return row.project ? `untitled · ${row.project}` : 'untitled session'
234}
235
236function isOnBand(r: Row, at: number): boolean {
237  if (r.isHidden || r.isStale || r.ended === true || r.state === 'idle') return false
238  if (r.state === 'done' || r.state === 'stopped' || r.state === 'error') return at - r.endedAt < RECENT_MS
239  return true
240}
241
242const isLiveState = (s: PulseState): boolean => s === 'working' || s === 'waiting'
243
244// ---------------------------------------------------------------------------
245// This session's own heartbeat
246
247async function startTracking($: EngineInterface, cwd: string, surface: string): Promise<void> {
248  if (isTracked || !dir) return
249  isTracked = true
250  const at = await $.clock.now()
251  const id = await $.session.id()
252  // A hot reload keeps $.state, so the row drawn before it carries on as it was.
253  const kept = (await read($, rowsAtom)).find(r => r.isSelf && r.id === id)
254  if (kept !== undefined) {
255    me = beatOf(kept)
256  } else {
257    // A resumed session: keep its title, count and age; its last turn is over.
258    const saved = await readBeat($, beatPath(id))
259    me = freshBeat(id, surface, cwd, at)
260    if (saved !== null && saved.ended !== true) {
261      me = { ...me, title: saved.title, turns: saved.turns, lastMs: saved.lastMs, bornAt: saved.bornAt || at, endedAt: saved.endedAt, state: saved.turns > 0 ? 'done' : 'idle' }
262    }
263  }
264  me = { ...me, hostId, surface: surface || me.surface, cwd, project: basename(cwd) }
265  if (me.title) titleFrom = 'prompt'
266  if (me.lastMs > 0) myTurns = [me.lastMs]
267  pace = await loadPace($)
268  digitFont = await loadDigitFont($)
269  await restoreDemo($, at)
270  await refreshTitle($)
271  await writeSelf($)
272  await scan($, at)
273  startTicking($)
274}
275
276function startTicking($: EngineInterface): void {
277  if (isTicking) return
278  isTicking = true
279  $.clock.every(SEC, () => {
280    void tick($)
281  })
282}
283
284async function tick($: EngineInterface): Promise<void> {
285  if (me === null || isBusy) return
286  isBusy = true
287  try {
288    ticks += 1
289    const at = await $.clock.now()
290    if (ticks % 5 === 0 || me.ended === true) await followClear($)
291    if (isDirty || at - lastWrite >= BEAT_MS) await writeSelf($)
292    if (ticks % 2 === 0) await scan($, at)
293    if (ticks % 10 === 1) await readSettings($)
294    // A rename in the app shows within seconds.
295    if (ticks % 5 === 0 && titleFrom !== 'prompt') await refreshTitle($)
296    else if (ticks % 120 === 0) await refreshTitle($)
297    const list = await read($, rowsAtom)
298    const isLive = list.some(r => isLiveState(r.state) && !r.isStale)
299    if (isLive || ticks % 30 === 0) await update($, nowAtom, () => at)
300  } catch {
301    // the next tick tries again
302  } finally {
303    isBusy = false
304  }
305}
306
307async function writeSelf($: EngineInterface): Promise<void> {
308  if (me === null || !dir) return
309  const at = await $.clock.now()
310  me.updatedAt = at
311  lastWrite = at
312  isDirty = false
313  try {
314    await $.fs.write(beatPath(me.id), JSON.stringify(me))
315  } catch {
316    // this session still shows itself
317  }
318  const self = selfRow()
319  if (self !== null) await update($, rowsAtom, list => [...list.filter(r => !r.isSelf), self].sort(byBirth))
320}
321
322async function writeEnded($: EngineInterface, beat: Beat): Promise<void> {
323  try {
324    await $.fs.write(beatPath(beat.id), JSON.stringify({ ...beat, ended: true, updatedAt: await $.clock.now() }))
325  } catch {
326    // its file goes stale and drops off the board
327  }
328}
329
330async function readBeat($: EngineInterface, path: string): Promise<Beat | null> {
331  try {
332    if (!(await $.fs.exists(path))) return null
333    return asBeat(JSON.parse(await $.fs.read(path)))
334  } catch {
335    return null
336  }
337}
338
339// /clear gives the session a new id: the old row ends and a fresh one starts.
340async function followClear($: EngineInterface): Promise<void> {
341  if (me === null) return
342  const id = await $.session.id()
343  if (id === me.id) return
344  await writeEnded($, me)
345  const at = await $.clock.now()
346  const keepTitle = titleFrom === 'desktop' || titleFrom === 'name' ? me.title : ''
347  me = { ...freshBeat(id, me.surface, me.cwd, at), title: keepTitle }
348  if (!keepTitle) titleFrom = 'folder'
349  tasks.clear()
350  myTurns = []
351  waitKind = ''
352  await refreshTitle($)
353  await writeSelf($)
354}
355
356// The desktop app's own title for this session (what its sidebar shows), else
357// the first prompt; the folder name until there is one.
358async function refreshTitle($: EngineInterface): Promise<void> {
359  if (me === null || titleFrom === 'name') return
360  if (hostId) {
361    if (!desktopRecord) desktopRecord = await findDesktopRecord($)
362    if (desktopRecord) {
363      try {
364        const raw = JSON.parse(await $.fs.read(desktopRecord)) as { title?: unknown }
365        const title = typeof raw.title === 'string' ? raw.title.replace(/\s+/g, ' ').trim() : ''
366        if (title) {
367          if (title !== me.title) {
368            me.title = title
369            isDirty = true
370          }
371          titleFrom = 'desktop'
372          return
373        }
374      } catch {
375        desktopRecord = ''
376      }
377    }
378  }
379  if (me.title) return
380  try {
381    const messages = await $.session.messages()
382    if (!Array.isArray(messages)) return
383    for (const m of messages) {
384      const title = m.role === 'user' ? titleFromPrompt(m.text) : ''
385      if (title) {
386        me.title = title
387        titleFrom = 'prompt'
388        isDirty = true
389        return
390      }
391    }
392  } catch {
393    // the folder name stands in
394  }
395}
396
397async function findDesktopRecord($: EngineInterface): Promise<string> {
398  const base = home + DESKTOP_SESSIONS
399  try {
400    if (!(await $.fs.exists(base))) return ''
401    for (const account of await $.fs.list(base)) {
402      if (account.kind !== 'dir') continue
403      for (const org of await $.fs.list(`${base}/${account.name}`)) {
404        if (org.kind !== 'dir') continue
405        const path = `${base}/${account.name}/${org.name}/${hostId}.json`
406        if (await $.fs.exists(path)) return path
407      }
408    }
409  } catch {
410    // no desktop record: the prompt names the session
411  }
412  return ''
413}
414
415async function loadPace($: EngineInterface): Promise<number[]> {
416  try {
417    const value = await $.store.get('pace')
418    return Array.isArray(value) ? value.filter((n): n is number => typeof n === 'number' && n > 0).slice(-60) : []
419  } catch {
420    return []
421  }
422}
423
424async function recordPace($: EngineInterface, ms: number): Promise<void> {
425  pace = [...(await loadPace($)), Math.round(ms)].slice(-60)
426  try {
427    await $.store.set('pace', pace)
428  } catch {
429    // learned again from the next turns
430  }
431}
432
433// Settings live in the store, so a change in one session reaches the others,
434// and the recording flag Recording Mode keeps masks titles while it is on.
435async function readSettings($: EngineInterface): Promise<void> {
436  try {
437    const saved = (await $.store.get('prefs')) as Partial<Prefs> | undefined
438    const prefs: Prefs = {
439      mode: saved?.mode === 'compact' || saved?.mode === 'off' ? saved.mode : 'full',
440      alerts: saved?.alerts !== false,
441    }
442    const current = await read($, prefsAtom)
443    if (current.mode !== prefs.mode || current.alerts !== prefs.alerts) await update($, prefsAtom, () => prefs)
444  } catch {
445    // defaults stand
446  }
447  let isRecording = false
448  try {
449    const path = `${home}/.claude/mods-data/recording.json`
450    if (await $.fs.exists(path)) isRecording = (JSON.parse(await $.fs.read(path)) as { on?: unknown }).on === true
451  } catch {
452    isRecording = false
453  }
454  if (isRecording !== (await read($, maskedAtom))) await update($, maskedAtom, () => isRecording)
455}
456
457async function savePrefs($: EngineInterface, change: (p: Prefs) => Prefs): Promise<Prefs> {
458  const prefs = await update($, prefsAtom, change)
459  try {
460    await $.store.set('prefs', prefs)
461  } catch {
462    // this session keeps it until it ends
463  }
464  return prefs
465}
466
467// ---------------------------------------------------------------------------
468// The turn: started, its tool calls, waits on the person, its end
469
470function setPlan(counts: { done: number; active: number; total: number } | null, source: string, at: number, activity: string): void {
471  if (me === null) return
472  const prev = me.plan
473  const plan = counts === null ? null : withChange(prev, counts, source, at)
474  // A new list, or one that started over, restarts the plan's clock.
475  if (plan !== null && (prev === null || prev.source !== source || plan.done < prev.done)) me.planAt = at
476  if (plan === null) me.planAt = 0
477  me.plan = plan
478  if (activity) me.activity = clip(activity, 60)
479  isDirty = true
480}
481
482async function readGoal($: EngineInterface): Promise<void> {
483  if (me === null) return
484  try {
485    const path = `${home}/.claude/mods-data/goal-meter/${me.id}.json`
486    if (!(await $.fs.exists(path))) return
487    const counts = goalPlan(JSON.parse(await $.fs.read(path)))
488    if (counts !== null) setPlan(counts, 'goal', await $.clock.now(), '')
489  } catch {
490    // Goal Meter's own band still shows it
491  }
492}
493
494async function startTurn($: EngineInterface, text: string): Promise<void> {
495  if (me === null) return
496  await followClear($)
497  const at = await $.clock.now()
498  const plan: Plan | null = me.plan !== null && me.plan.done < me.plan.total ? me.plan : null
499  if (plan === null) tasks.clear()
500  me = {
501    ...me,
502    state: 'working',
503    startedAt: at,
504    endedAt: 0,
505    waitMs: 0,
506    waitingSince: 0,
507    tools: 0,
508    activity: 'Thinking',
509    need: '',
510    plan,
511    planAt: plan === null ? 0 : me.planAt,
512    expectMs: expectedMs(pace, myTurns),
513    stopPct: 0,
514    agents: 0,
515  }
516  waitKind = ''
517  heardStartAt = at
518  notWorkingSince = 0
519  isSettledEarly = false
520  if (titleFrom === 'folder') {
521    const title = titleFromPrompt(text)
522    if (title) {
523      me.title = title
524      titleFrom = 'prompt'
525    }
526  }
527  await readGoal($)
528  await writeSelf($)
529}
530
531async function beginWait($: EngineInterface, kind: 'ask' | 'permission', need: string): Promise<void> {
532  if (me === null || me.state !== 'working') return
533  me.state = 'waiting'
534  me.waitingSince = await $.clock.now()
535  me.need = need
536  if (kind === 'permission') me.activity = 'Waiting for your permission'
537  waitKind = kind
538  await writeSelf($)
539}
540
541async function endWait($: EngineInterface): Promise<void> {
542  waitKind = ''
543  if (me === null || me.state !== 'waiting') return
544  const at = await $.clock.now()
545  me.waitMs += Math.max(0, at - me.waitingSince)
546  me.waitingSince = 0
547  me.state = 'working'
548  me.need = ''
549  await writeSelf($)
550}
551
552// A row settled while its turn was still running (the engine's band said idle
553// during a long wait) is live again the moment the turn shows activity.
554function reviveSettled(): void {
555  if (me === null || !isSettledEarly || me.state !== 'done') return
556  isSettledEarly = false
557  notWorkingSince = 0
558  me = { ...me, state: 'working', endedAt: 0, turns: Math.max(0, me.turns - 1), stopPct: 0 }
559}
560
561async function noteCall($: EngineInterface, tool: string, input: Record<string, unknown>, isMain: boolean, isAsk: boolean): Promise<void> {
562  reviveSettled()
563  notWorkingSince = 0
564  if (me === null || !isLiveState(me.state)) return
565  // A tool runs once its permission was given.
566  if (waitKind === 'permission') await endWait($)
567  const at = await $.clock.now()
568  me.tools += 1
569  if (isMain) {
570    const activity = activityOf(tool, input)
571    if (activity) me.activity = activity
572  }
573  if (tool === 'TodoWrite') {
574    const found = todosPlan(input.todos)
575    setPlan(found === null ? null : found.counts, 'todos', at, found === null ? '' : found.activity)
576  } else if (tool === 'TaskUpdate') {
577    const id = String(input.taskId ?? '')
578    const prev = tasks.get(id)
579    if (id) {
580      tasks.set(id, {
581        status: typeof input.status === 'string' ? input.status : (prev?.status ?? 'pending'),
582        label: typeof input.activeForm === 'string' ? input.activeForm : (prev?.label ?? ''),
583      })
584      const found = tasksPlan(tasks)
585      setPlan(found === null ? null : found.counts, 'tasks', at, found === null ? '' : found.activity)
586    }
587  } else if (tool === SAVVY_PROGRESS || tool === SAVVY_STEP) {
588    setPlan(savvyPlan(input, me.plan), 'savvy', at, typeof input.note === 'string' ? input.note : '')
589  }
590  isDirty = true
591  if (isAsk) await beginWait($, 'ask', askNeed(tool, input))
592}
593
594function taskIdOf(ran: ToolCallResult): string {
595  const result = ran.result as { task?: { id?: unknown }; taskId?: unknown; id?: unknown } | undefined
596  const direct = result?.task?.id ?? result?.taskId ?? result?.id
597  if (typeof direct === 'string' || typeof direct === 'number') return String(direct)
598  const text = (ran as { text?: unknown }).text
599  const found = /#?(\d+)/.exec(typeof text === 'string' ? text : '')
600  return found?.[1] ?? ''
601}
602
603async function afterCall($: EngineInterface, tool: string, input: Record<string, unknown>, ran: ToolCallResult, isAsk: boolean): Promise<void> {
604  if (me === null) return
605  if (isAsk || waitKind === 'permission') await endWait($)
606  if (tool === 'TaskCreate' && ran.deny === undefined) {
607    const id = taskIdOf(ran)
608    if (id) {
609      tasks.set(id, { status: 'pending', label: String(input.activeForm ?? input.subject ?? '') })
610      const found = tasksPlan(tasks)
611      setPlan(found === null ? null : found.counts, 'tasks', await $.clock.now(), '')
612    }
613  }
614  if (tool === GOAL_TOOL) await readGoal($)
615}
616
617async function finishTurn($: EngineInterface, reason: string, durationMs: number): Promise<void> {
618  reviveSettled()
619  if (me === null || me.startedAt === 0 || !isLiveState(me.state)) return
620  const at = await $.clock.now()
621  if (me.waitingSince) {
622    me.waitMs += Math.max(0, at - me.waitingSince)
623    me.waitingSince = 0
624  }
625  const pct = estimate(me, at).pct
626  const took = durationMs > 0 ? durationMs : at - me.startedAt
627  const state: PulseState = reason === 'answer' ? 'done' : reason === 'aborted' ? 'stopped' : 'error'
628  me = { ...me, state, endedAt: at, turns: me.turns + 1, lastMs: took, stopPct: pct, activity: '', need: '' }
629  waitKind = ''
630  if (state === 'done') {
631    const worked = Math.max(SEC, took - me.waitMs)
632    myTurns = [...myTurns, worked].slice(-10)
633    if (worked > 3 * SEC) await recordPace($, worked)
634  }
635  try {
636    const running = (await $.agent.list()).filter(a => a.status === 'running').length
637    me.agents = running
638    if (running > 0) me.activity = `${running} background agent${running === 1 ? '' : 's'} still running`
639  } catch {
640    me.agents = 0
641  }
642  await writeSelf($)
643  if (titleFrom !== 'desktop' || me.turns <= 3) await refreshTitle($)
644}
645
646// A turn whose end this module never heard (a reload or an unload between its
647// start and its end) would stay "working" for good. The engine's own band says
648// whether a turn runs: past a short grace, a live row with no turn running is
649// over. Its length is unknown, so it teaches the pace nothing.
650async function settleMissedTurn($: EngineInterface, isWorking: boolean): Promise<void> {
651  if (isWorking) notWorkingSince = 0
652  if (isWorking || me === null || me.startedAt === 0 || !isLiveState(me.state)) return
653  const at = await $.clock.now()
654  if (at - me.startedAt < MISSED_TURN_GRACE_MS) return
655  // A turn this module saw start is still running while it waits on a long tool,
656  // a workflow or background agents, whatever the engine's band says: settle it
657  // only after a long quiet spell with nothing running.
658  const isHeard = me.startedAt === heardStartAt
659  if (isHeard) {
660    if (notWorkingSince === 0) notWorkingSince = at
661    if (at - notWorkingSince < HEARD_TURN_GRACE_MS) return
662    try {
663      if ((await $.agent.list()).some(a => a.status === 'running')) return
664    } catch {
665      // no agent list: go by the quiet spell alone
666    }
667  }
668  isSettledEarly = isHeard
669  me = { ...me, state: 'done', endedAt: at, turns: me.turns + 1, stopPct: 100, waitingSince: 0, activity: '', need: '' }
670  waitKind = ''
671  await writeSelf($)
672}
673
674// ---------------------------------------------------------------------------
675// Everyone else: read their heartbeats, notice who finished or needs you
676
677async function scan($: EngineInterface, at: number): Promise<void> {
678  if (me === null || !dir) return
679  let entries: readonly { name: string; kind: string; mtimeMs: number }[] = []
680  try {
681    entries = await $.fs.list(dir)
682  } catch {
683    entries = []
684  }
685  const beats: Beat[] = []
686  const old: string[] = []
687  const seen = new Set<string>()
688  hidden.clear()
689  for (const entry of entries) {
690    if (entry.kind !== 'file') continue
691    const beatName = BEAT_FILE.exec(entry.name)
692    const hideName = beatName === null ? HIDE_FILE.exec(entry.name) : null
693    if (beatName === null && hideName === null) continue
694    seen.add(entry.name)
695    const path = `${dir}/${entry.name}`
696    let cached = files.get(entry.name)
697    if (cached === undefined || cached.mtimeMs !== entry.mtimeMs) {
698      cached = { mtimeMs: entry.mtimeMs, beat: null, hiddenAt: 0 }
699      try {
700        const raw: unknown = JSON.parse(await $.fs.read(path))
701        if (beatName !== null) cached.beat = asBeat(raw)
702        else cached.hiddenAt = typeof (raw as { at?: unknown })?.at === 'number' ? (raw as { at: number }).at : 0
703      } catch {
704        cached.mtimeMs = -1 // caught mid-write: read it again next time
705      }
706      files.set(entry.name, cached)
707    }
708    if (hideName !== null) {
709      if (cached.hiddenAt > 0) hidden.set(hideName[1] ?? '', cached.hiddenAt)
710      else if (cached.mtimeMs > 0 && at - cached.mtimeMs > FORGET_MS) old.push(path)
711      continue
712    }
713    const beat = cached.beat
714    if (beat === null || beat.id === me.id) continue
715    if (beat.ended === true || at - beat.updatedAt > FORGET_MS) {
716      old.push(path)
717      continue
718    }
719    beats.push(beat)
720  }
721  for (const name of [...files.keys()]) if (!seen.has(name)) files.delete(name)
722  if (at < demoUntil) beats.push(...demo.map(b => ({ ...b, updatedAt: at })))
723  else demo = []
724
725  const others: Row[] = beats.map(b => ({
726    ...b,
727    isSelf: false,
728    isHidden: isDemo(b.id) ? demoHidden.has(b.id) : isHiddenBeat(b, hidden.get(b.id) ?? 0),
729    isStale: at - b.updatedAt > STALE_MS,
730  }))
731  const self = selfRow()
732  const next = (self === null ? others : [...others, self]).sort(byBirth)
733  await alert($, next)
734  const before = await read($, rowsAtom)
735  if (JSON.stringify(before) !== JSON.stringify(next)) await update($, rowsAtom, () => next)
736  if (old.length > 0 && at - lastPrune > 10 * MIN) {
737    lastPrune = at
738    await prune($, old)
739  }
740}
741
742async function prune($: EngineInterface, paths: readonly string[]): Promise<void> {
743  const safe = paths.filter(p => p.startsWith(`${dir}/`) && /\/(s|hide)-[A-Za-z0-9-]{8,64}\.json$/.test(p))
744  if (safe.length === 0) return
745  try {
746    await $.process.run(['rm', '-f', '--', ...safe], { timeoutMs: 5000 })
747  } catch {
748    // they stay off the board either way
749  }
750}
751
752async function alert($: EngineInterface, list: readonly Row[]): Promise<void> {
753  const prefs = await read($, prefsAtom)
754  const isMasked = await read($, maskedAtom)
755  list.forEach((r, i) => {
756    const before = lastState.get(r.id)
757    lastState.set(r.id, r.state)
758    if (!hasScanned || !prefs.alerts || r.isSelf || r.isHidden || r.isStale || before === undefined || before === r.state) return
759    const name = clip(labelOf(r, i, isMasked), 48)
760    if (r.state === 'done' && isLiveState(before)) $.ui.toast(`✓ ${name} finished · took ${durText(r.lastMs)}`)
761    else if (r.state === 'waiting') $.ui.toast(`● ${name} needs you`)
762    else if (r.state === 'error') $.ui.toast(`✗ ${name} stopped on an error`)
763  })
764  hasScanned = true
765}
766
767// ---------------------------------------------------------------------------
768// Acting on a row: switch to it, hide it
769
770const shellQuote = (s: string): string => `'${s.replace(/'/g, `'\\''`)}'`
771
772async function switchTo($: EngineInterface, row: Row, surface: RenderSurface): Promise<void> {
773  if (row.isSelf) {
774    $.ui.toast('This is the session you are in.')
775    return
776  }
777  if (isDemo(row.id)) {
778    $.ui.toast(`Demo row: a real "${clip(row.title, 40)}" session would open here.`)
779    return
780  }
781  if (HOST_ID.test(row.hostId)) {
782    const url = `claude://code/continue?session=${row.hostId}`
783    for (const argv of [['open', url], ['xdg-open', url]]) {
784      try {
785        const ran = await $.process.run(argv, { timeoutMs: 8000 })
786        if (ran.exitCode === 0) return
787      } catch {
788        // try the next opener
789      }
790    }
791    $.ui.toast('Could not open that session in the desktop app.')
792    return
793  }
794  const resume = `cd ${shellQuote(row.cwd)} && claude --resume ${row.id}`
795  let isCopied = false
796  try {
797    isCopied = (await $.ui.copy({ text: resume, surface })).isCopied
798  } catch {
799    isCopied = false
800  }
801  $.ui.toast(isCopied ? 'That session runs in a terminal. Its resume command is on the clipboard.' : `That session runs in a terminal: ${resume}`, { timeoutMs: 8000 })
802}
803
804async function hideRow($: EngineInterface, row: Row): Promise<void> {
805  if (isDemo(row.id)) {
806    demoHidden.add(row.id)
807    await update($, rowsAtom, list => list.map(r => (r.id === row.id ? { ...r, isHidden: true } : r)))
808    return
809  }
810  if (!dir) return
811  const at = await $.clock.now()
812  try {
813    await $.fs.write(hidePath(row.id), JSON.stringify({ at }))
814  } catch {
815    // hidden in this session only
816  }
817  hidden.set(row.id, at)
818  await update($, rowsAtom, list => list.map(r => (r.id === row.id ? { ...r, isHidden: true } : r)))
819}
820
821async function unhideAll($: EngineInterface): Promise<number> {
822  const ids = [...hidden.keys()]
823  for (const id of ids) {
824    try {
825      await $.fs.write(hidePath(id), JSON.stringify({ at: 0 }))
826    } catch {
827      // stays hidden until its next turn
828    }
829  }
830  const count = ids.length + demoHidden.size
831  hidden.clear()
832  demoHidden.clear()
833  await update($, rowsAtom, list => list.map(r => ({ ...r, isHidden: false })))
834  return count
835}
836
837async function openPane($: EngineInterface): Promise<void> {
838  // Docked beside the transcript where the surface docks panes (the right side).
839  await $.ui.open({ id: PANE, title: 'Sessions', focus: true, closeOnEscape: true, columns: 72 })
840}
841
842async function togglePane($: EngineInterface): Promise<boolean> {
843  const isOpen = (await $.ui.panes()).some(p => p.id === PANE)
844  if (isOpen) {
845    await $.ui.close({ id: PANE })
846    return false
847  }
848  await openPane($)
849  return true
850}
851
852// ---------------------------------------------------------------------------
853// Drawing
854
855// A dark tint of a state color, for the terminal's one-row chip behind its word.
856function chipTint(hex: string): string {
857  const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex)
858  if (m === null) return '#2a2a2a'
859  const mix = (h: string | undefined): string => Math.round(0x22 + (parseInt(h ?? '0', 16) - 0x22) * 0.18).toString(16).padStart(2, '0')
860  return `#${mix(m[1])}${mix(m[2])}${mix(m[3])}`
861}
862
863function viewOf(r: Row, at: number): View {
864  const est = estimate(r, at)
865  let pct = est.pct
866  if (isLiveState(r.state)) {
867    // Never step backwards while one turn runs (a plan appearing can lower the estimate).
868    const key = `${r.id}:${r.startedAt}`
869    pct = Math.max(pct, highest.get(key) ?? 0)
870    if (highest.size > 300) highest.clear()
871    highest.set(key, pct)
872  }
873  const color = colorOf(r.state, pct)
874  const pctText = r.state === 'idle' ? '' : `${Math.round(pct)}%`
875  const base = { pct, pctText, color, isLive: r.state === 'working', tailHex: '' }
876  // The time column says when (time left, or how long ago); the state column
877  // after it says what it is, or, while the session waits on you, what to do.
878  const time = (tail: string) => ({ tail, tailColor: 'subtle' })
879  const state = (word: string, c = 'subtle') => ({ state: word, stateColor: c })
880  switch (r.state) {
881    case 'working':
882      return { ...base, ...time(etaText(est.etaMs)), ...state('working', color) }
883    case 'waiting':
884      return { ...base, ...time(`${durText(Math.max(0, at - (r.waitingSince || at)))} waiting`), ...state(r.need || 'needs you', COLOR.waiting) }
885    case 'done':
886      return { ...base, ...time(agoText(at - r.endedAt)), ...state('done', COLOR.done) }
887    case 'stopped':
888      return { ...base, ...time(agoText(at - r.endedAt)), ...state('interrupted', COLOR.stopped) }
889    case 'error':
890      return { ...base, ...time(agoText(at - r.endedAt)), ...state('error', COLOR.error) }
891    default:
892      return { ...base, ...time(''), ...state(r.isStale ? 'offline' : 'idle', COLOR.idle) }
893  }
894}
895
896function termRow($: EngineInterface, ui: Kit, item: Item, at: number, cols: number, hotkey: string, need: Need): RenderElement {
897  const { Box, Text, Button } = ui
898  const r = item.row
899  const view = viewOf(r, at)
900  // The title column fits the longest title shown; the bar gives up room first
901  // (down to 10 cells) and a title is cut only past half the row.
902  // The alert column fits the longest shown whole, on one line.
903  // Besides those four columns the row holds the dot, the percent, the × and
904  // the seven gaps between its eight pieces.
905  const room = cols - (ICON_CELLS - 1) - 4 - 1 - 7
906  let tailW = clamp(need.tail, 6, 16)
907  let stateW = clamp(need.state, 4, 32)
908  // In a narrow row the bar shrinks to 3 cells, then the state and the time
909  // are cut, before the row would wrap: a title keeps at least 10 cells.
910  let short = 13 - (room - tailW - stateW)
911  if (short > 0) {
912    const cut = Math.min(short, stateW - 4)
913    stateW -= cut
914    short -= cut
915  }
916  if (short > 0) tailW -= Math.min(short, tailW - 4)
917  const free = room - tailW - stateW
918  const titleW = clamp(need.title, Math.min(10, Math.max(6, free - 3)), Math.max(10, Math.min(Math.floor(cols * 0.5), free - 10)))
919  const barW = clamp(free - titleW, 3, 32)
920  const { fill, rest } = barCells(view.pct, barW)
921  const name = fit(r.isSelf ? `${item.label} (here)` : item.label, titleW)
922  const keys = hotkey ? { hotkey } : {}
923  return (
924    <Box key={`row-${r.id}`} flexDirection="row" width="100%" gap={1}>
925      <Box width={ICON_CELLS - 1} flexShrink={0}>
926        <Text color={view.color}>{iconOf(r.state)}</Text>
927      </Box>
928      <Button key={`go-${r.id}`} plain {...keys} onPress={press => void switchTo($, r, press.surface)}>
929        <Text bold={r.isSelf}>{name}</Text>
930      </Button>
931      <Box flexDirection="row">
932        <Text color={view.color}>{fill}</Text>
933        <Text color="subtle">{rest}</Text>
934      </Box>
935      <Text bold>{view.pctText.padStart(4)}</Text>
936      <Text color={view.tailColor}>{fit(view.tail, tailW)}</Text>
937      {r.state === 'waiting' ? <Text color={COLOR.waiting}>{fit(view.state, stateW)}</Text> : <Text dimColor>{fit(view.state, stateW)}</Text>}
938      <Box flexGrow={1} />
939      <Button key={`x-${r.id}`} label="×" plain dimColor onPress={() => void hideRow($, r)} />
940    </Box>
941  )
942}
943
944function svgRow($: EngineInterface, ui: Kit, Svg: SvgElement, item: Item, at: number, cols: number, hotkey: string, site: string, need: Need): RenderElement {
945  const { Box, Text, Button } = ui
946  const r = item.row
947  const view = viewOf(r, at)
948  // The row is laid out in the band's columns (about 8 CSS px each; the app's
949  // text runs about 0.85 of a column per character), so it never runs past the
950  // band's right edge. The title and time-left columns fit the longest of each
951  // shown; the buttons take their own width; the bar gets the rest, down to 10
952  // columns, and a title is cut only past half the row.
953  const span = clamp(cols, 40, 220)
954  const PCT = 4
955  // The alert column gets room to spare (0.95 of a column a character, plus
956  // two), so a "needs you" phrase always fits whole on one line.
957  // Time, then state (or what to do), each as wide as its longest shown, whole on one line.
958  const TIME = Math.max(4, Math.ceil(need.tail * 0.95) + 1)
959  // The state column, its longest word whole on one line.
960  const PANE = Math.max(4, Math.ceil(need.state * 0.95) + 1)
961  const TAIL = TIME
962  const BUTTONS = 6 // ↗ and ×: their labels plus the buttons' padding
963  const GAPS = 7
964  const FIXED = PCT + TAIL + PANE + BUTTONS + GAPS + 2
965  // The pane has no band to share: a title may take up to two thirds of its row.
966  const share = site.endsWith(':pane') ? 0.65 : 0.5
967  const maxTitle = Math.max(10, Math.min(Math.floor(span * share), span - FIXED - 10))
968  const titleCells = clamp(Math.ceil(need.title * 0.9) + 3, 10, maxTitle)
969  const titleChars = Math.floor((titleCells - 3) / 0.9)
970  const barCells = Math.max(8, span - titleCells - FIXED)
971  // The bar and, at its right end, the rolling percent in the app's own glyphs.
972  const width = (barCells + 1 + PCT) * 8
973  const keys = hotkey ? { hotkey } : {}
974  const name = item.label
975  const shownKey = `${site}:${r.id}`
976  const before = lastShown.get(shownKey)
977  if (lastShown.size > 300) lastShown.clear()
978  lastShown.set(shownKey, { pct: view.pct, pctText: view.pctText })
979  const source = barSvg({
980    pct: view.pct,
981    color: view.color,
982    width,
983    pctText: view.pctText,
984    prevPct: before?.pct,
985    prevPctText: before !== undefined && before.pctText !== view.pctText ? before.pctText : '',
986    tail: '',
987    tailColor: '',
988    isLive: view.isLive,
989    font: digitFont,
990    pctW: PCT * 8,
991  })
992  return (
993    <Box key={`row-${r.id}`} flexDirection="row" alignItems="center" width="100%" gap={1}>
994      {/* The dot and the title are one plain line of text, drawn as the
995          status line above draws "● cache warm", so both line up with it
996          exactly (a button's own padding would push the title right). The ↗
997          before the × switches to the session. No wrap prop (the desktop draws
998          a wrapped text larger): the title is cut instead. */}
999      <Box width={titleCells} flexShrink={0} flexDirection="row" alignItems="center">
1000        <Text>
1001          <Text color={view.color}>{iconOf(r.state)}</Text>
1002          <Text dimColor>{` ${cells(name) <= titleChars ? name : clip(name, Math.max(8, titleChars))}`}</Text>
1003        </Text>
1004      </Box>
1005      {/* The bar starts right after the title column, so it always sits
1006          between the title and its percent; spare room goes before the ×. */}
1007      <Svg source={source} alt={`${name}: ${[view.pctText, view.tail].filter(Boolean).join(', ')}`} width={width} height={SVG_HEIGHT} />
1008      {/* Time, then state (or what to do while it waits on you), each column
1009          as wide as its longest shown, so the × buttons line up row to row. */}
1010      <Box width={TAIL} flexShrink={0}>
1011        <Text color={view.tailColor}>{view.tail}</Text>
1012      </Box>
1013      {/* The state in dim text; what to do, while it waits on you, in blue. */}
1014      <Box width={PANE} flexShrink={0}>
1015        {r.state === 'waiting' ? <Text color={COLOR.waiting}>{view.state}</Text> : <Text dimColor>{view.state}</Text>}
1016      </Box>
1017      <Box flexGrow={1} />
1018      <Button key={`go-${r.id}`} label="↗" plain dimColor {...keys} onPress={press => void switchTo($, r, press.surface)} />
1019      <Button key={`x-${r.id}`} label="×" plain dimColor onPress={() => void hideRow($, r)} />
1020    </Box>
1021  )
1022}
1023
1024// The terminal draws text bars; the desktop and the other remote surfaces an
1025// SVG bar. The surface decides, not the table: the terminal's carries an Svg too.
1026function rowOf($: EngineInterface, ui: ReturnType<EngineInterface['ui']['resolve']>, surface: RenderSurface, item: Item, at: number, cols: number, hotkey: string, site: string, need: Need): RenderElement {
1027  return surface !== 'terminal' && 'Svg' in ui ? svgRow($, ui, ui.Svg, item, at, cols, hotkey, `${surface}:${site}`, need) : termRow($, ui, item, at, cols, hotkey, need)
1028}
1029
1030// The cells the longest shown title, time and state need, so every row's
1031// columns are as wide as their widest entry and nothing is cut while the row has room.
1032type Need = { title: number; tail: number; state: number }
1033
1034function columnNeeds(items: readonly Item[], surface: RenderSurface, at: number): Need {
1035  return items.reduce(
1036    (a, x) => ({
1037      title: Math.max(a.title, cells(surface === 'terminal' && x.row.isSelf ? `${x.label} (here)` : x.label)),
1038      tail: Math.max(a.tail, cells(viewOf(x.row, at).tail)),
1039      state: Math.max(a.state, cells(viewOf(x.row, at).state)),
1040    }),
1041    { title: 0, tail: 0, state: 0 },
1042  )
1043}
1044
1045// "+3 more sessions · /pulse", or just "+3 more" where the band is too narrow
1046// for it beside the pane button.
1047function moreText(more: number, cols: number): string {
1048  const full = `+${more} more session${more === 1 ? '' : 's'} · /${commandName || 'pulse'}`
1049  return full.length + 12 <= cols ? full : `+${more} more`
1050}
1051
1052function compactBand($: EngineInterface, ui: Kit, surface: RenderSurface, items: readonly Item[], at: number): RenderElement {
1053  const { Box, Text, Button } = ui
1054  const views = items.map(x => ({ row: x.row, view: viewOf(x.row, at), est: estimate(x.row, at) }))
1055  const working = views.filter(v => v.row.state === 'working')
1056  const waiting = views.filter(v => v.row.state === 'waiting')
1057  const finished = views.filter(v => v.row.state === 'done')
1058  const failed = views.filter(v => v.row.state === 'error' || v.row.state === 'stopped')
1059  const parts: RenderElement[] = []
1060  if (working.length > 0) {
1061    const avg = working.reduce((a, v) => a + v.view.pct, 0) / working.length
1062    const soonest = Math.min(...working.map(v => v.est.etaMs ?? Infinity))
1063    const next = Number.isFinite(soonest) ? ` · next ${etaText(soonest)}` : ''
1064    parts.push(<Text color={workingColor(avg)}>{`● ${working.length} working${next}`}</Text>)
1065  }
1066  if (waiting.length > 0) parts.push(<Text color={COLOR.waiting}>{`● ${waiting.length} need${waiting.length === 1 ? 's' : ''} you`}</Text>)
1067  if (finished.length > 0) parts.push(<Text color={COLOR.done}>{`✓ ${finished.length} done`}</Text>)
1068  if (failed.length > 0) parts.push(<Text color={COLOR.stopped}>{`■ ${failed.length} stopped`}</Text>)
1069  const children: (RenderElement | string)[] = []
1070  parts.forEach((p, i) => {
1071    if (i > 0) children.push('   ')
1072    children.push(p)
1073  })
1074  // A desktop button insets its label and drops the colors, so off the
1075  // terminal the line is plain text that starts where the band's other text does.
1076  if (surface !== 'terminal') {
1077    return (
1078      <Box flexDirection="row" width="100%">
1079        {children}
1080      </Box>
1081    )
1082  }
1083  return (
1084    <Box flexDirection="row" width="100%">
1085      <Button key="pulse-open" plain onPress={() => void openPane($)}>
1086        {children}
1087      </Button>
1088    </Box>
1089  )
1090}
1091
1092function stateWord(r: Row): string {
1093  switch (r.state) {
1094    case 'working':
1095      return 'Working'
1096    case 'waiting':
1097      return 'Needs you'
1098    case 'done':
1099      return 'Done'
1100    case 'stopped':
1101      return 'Interrupted'
1102    case 'error':
1103      return 'Stopped on an error'
1104    default:
1105      return 'Idle'
1106  }
1107}
1108
1109// The second line of a pane row: what the session is doing or how its last
1110// turn went, then the plan, the folder and where it runs.
1111function detailOf(r: Row, at: number, isMasked: boolean): string {
1112  const since = (t: number): string => durText(Math.max(0, at - t))
1113  const activity = !isMasked && r.activity ? r.activity : ''
1114  let lead: string
1115  if (r.isStale) lead = `No heartbeat for ${since(r.updatedAt)}, probably closed`
1116  else if (r.state === 'working') lead = `${activity || 'Working'} · ${since(r.startedAt)} so far${r.plan === null ? ' · time left estimated from past turns' : ''}`
1117  else if (r.state === 'waiting') lead = `Needs you: ${r.need || (activity ? activity.replace(/^Waiting for /, '') : 'your answer')} · waiting ${since(r.waitingSince || r.startedAt)}`
1118  else if (r.state === 'done') lead = `Finished ${agoText(at - r.endedAt)} · took ${durText(r.lastMs)}`
1119  else if (r.state === 'stopped') lead = `Interrupted ${agoText(at - r.endedAt)}`
1120  else if (r.state === 'error') lead = `Stopped on an error ${agoText(at - r.endedAt)}`
1121  else lead = r.turns > 0 ? `Idle since ${agoText(at - r.endedAt)}` : 'Open, no prompt yet'
1122  const parts = [lead]
1123  if (r.plan !== null) {
1124    parts.push(r.plan.source === 'goal' ? `goal ${Math.round((100 * r.plan.done) / r.plan.total)}% done` : `${r.plan.done} of ${r.plan.total} tasks done`)
1125  }
1126  if (r.agents > 0 && !isLiveState(r.state)) parts.push(`${r.agents} background agent${r.agents === 1 ? '' : 's'} running`)
1127  if (!isMasked && r.project) parts.push(r.project)
1128  parts.push(r.hostId ? 'Desktop app' : 'Terminal')
1129  return parts.join(' · ')
1130}
1131
1132function boardText(list: readonly Row[], at: number, isMasked: boolean): string {
1133  const live = list.filter(r => r.ended !== true)
1134  if (live.length === 0) return 'No sessions on the board.'
1135  return live
1136    .map((r, i) => {
1137      const view = viewOf(r, at)
1138      return `${iconOf(r.state)} ${labelOf(r, i, isMasked)}${r.isSelf ? ' (here)' : ''}  ${view.pctText} ${view.tail}`.trimEnd()
1139    })
1140    .join('\n')
1141}
1142
1143const HELP = [
1144  '/pulse: open or close the session board.',
1145  '/pulse compact | full | off: one summary line, a row per session, or no band.',
1146  '/pulse alerts on | off: a toast when another session finishes or needs you.',
1147  '/pulse show: bring hidden rows back.',
1148  '/pulse name <title>: rename this session on the board.',
1149  '/pulse demo [off]: five made-up sessions for three minutes, to see every state.',
1150].join('\n')
1151
1152async function runCommand($: EngineInterface, args: string): Promise<CommandRunResult> {
1153  const [verb = '', ...rest] = args.trim().split(/\s+/).filter(Boolean)
1154  const word = verb.toLowerCase()
1155  if (word === '') {
1156    if ((await $.session.surfaces()).length === 0) {
1157      return { text: boardText(await read($, rowsAtom), await $.clock.now(), await read($, maskedAtom)) }
1158    }
1159    const isOpen = await togglePane($)
1160    return isOpen ? {} : { text: 'Session board closed.' }
1161  }
1162  if (word === 'full' || word === 'compact' || word === 'off') {
1163    const mode: Prefs['mode'] = word
1164    await savePrefs($, p => ({ ...p, mode }))
1165    return { text: mode === 'off' ? 'Session band off. /pulse still opens the board.' : `Session band: ${mode}.` }
1166  }
1167  if (word === 'alerts') {
1168    const value = (rest[0] ?? '').toLowerCase()
1169    const isOn = value === 'on' ? true : value === 'off' ? false : !(await read($, prefsAtom)).alerts
1170    await savePrefs($, p => ({ ...p, alerts: isOn }))
1171    return { text: `Session alerts ${isOn ? 'on' : 'off'}.` }
1172  }
1173  if (word === 'show') {
1174    const count = await unhideAll($)
1175    return { text: count === 0 ? 'No hidden sessions.' : `Showing ${count} hidden session${count === 1 ? '' : 's'} again.` }
1176  }
1177  if (word === 'demo') {
1178    const at = await $.clock.now()
1179    demoHidden.clear()
1180    if ((rest[0] ?? '').toLowerCase() === 'off') {
1181      demo = []
1182      demoUntil = 0
1183      await saveDemo($, 0)
1184      await scan($, at)
1185      return { text: 'Demo rows removed.' }
1186    }
1187    demo = demoBeats(at)
1188    demoUntil = at + 3 * MIN
1189    await saveDemo($, at)
1190    await scan($, at)
1191    return { text: 'Five demo sessions for three minutes (/pulse demo off ends it). Clicks and × work on them; nothing is written.' }
1192  }
1193  if (word === 'name') {
1194    const title = clip(rest.join(' ').trim(), 80)
1195    if (me === null) return { text: 'This session is not on the board.' }
1196    if (!title) {
1197      titleFrom = 'folder'
1198      me.title = ''
1199      await refreshTitle($)
1200    } else {
hooks/estimate.ts 664 lines
1// Session Pulse's math and text: how far along a session is, how long it has
2// left, and how a row reads. Pure functions with no mods API calls, so the
3// tests drive them directly.
4
5import type { Beat, Plan, PulseState } from '../types'
6
7export const SEC = 1000
8export const MIN = 60 * SEC
9export const HOUR = 60 * MIN
10
11/** A turn's length before anything has been learned. */
12export const DEFAULT_TURN_MS = 90 * SEC
13const MIN_EXPECT = 15 * SEC
14const MAX_EXPECT = 2 * HOUR
15
16export const STATES: readonly PulseState[] = ['working', 'waiting', 'done', 'stopped', 'error', 'idle']
17
18export const clamp = (n: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, n))
19
20const finite = (n: unknown, fallback = 0): number => (typeof n === 'number' && Number.isFinite(n) ? n : fallback)
21
22export function median(list: readonly number[]): number {
23  const s = list.filter(n => Number.isFinite(n) && n > 0).sort((a, b) => a - b)
24  if (s.length === 0) return 0
25  const m = Math.floor(s.length / 2)
26  const mid = s[m] ?? 0
27  return s.length % 2 ? mid : ((s[m - 1] ?? mid) + mid) / 2
28}
29
30// ---------------------------------------------------------------------------
31// Progress and time left
32
33/**
34 * How long the next turn should take: this session's last five turns
35 * (geometric mean), pulled toward every session's median, harder the fewer
36 * turns this one has had.
37 */
38export function expectedMs(all: readonly number[], mine: readonly number[]): number {
39  const global = median(all) || DEFAULT_TURN_MS
40  const recent = mine.filter(n => Number.isFinite(n) && n > 0).slice(-5)
41  if (recent.length === 0) return clamp(global, MIN_EXPECT, MAX_EXPECT)
42  const own = Math.exp(recent.reduce((a, d) => a + Math.log(Math.max(d, SEC)), 0) / recent.length)
43  const w = recent.length / (recent.length + 2)
44  return Math.round(clamp(Math.exp(w * Math.log(own) + (1 - w) * Math.log(global)), MIN_EXPECT, MAX_EXPECT))
45}
46
47/** Time the turn has spent working; waits on the person don't count. */
48export function workedMs(b: Beat, now: number): number {
49  const waiting = b.waitingSince ? Math.max(0, now - b.waitingSince) : 0
50  return Math.max(0, now - b.startedAt - b.waitMs - waiting)
51}
52
53export type Estimate = {
54  /** 0 to 100; 100 only once the turn is done. */
55  pct: number
56  /** Rough time left, or null when nothing is running. */
57  etaMs: number | null
58  basis: 'plan' | 'pace' | 'final'
59}
60
61export function estimate(b: Beat, now: number): Estimate {
62  if (b.state === 'done') return { pct: 100, etaMs: null, basis: 'final' }
63  if (b.state === 'idle') return { pct: 0, etaMs: null, basis: 'final' }
64  if (b.state === 'stopped' || b.state === 'error') {
65    return { pct: clamp(Math.round(b.stopPct), 0, 99), etaMs: null, basis: 'final' }
66  }
67  const expect = Math.max(b.expectMs || DEFAULT_TURN_MS, MIN_EXPECT)
68  if (b.plan !== null && b.plan.total >= 2) return planEstimate(b.plan, b, now, expect)
69
70  // No plan: a curve over the expected length. At the expected length the bar
71  // shows two thirds; it slows as the turn runs long and stays under 100
72  // until the turn ends.
73  const worked = workedMs(b, now)
74  const pct = 95 * (1 - Math.exp((-1.2 * worked) / expect))
75  // A turn past its expected length is likely a long one: what is left grows with it.
76  const etaMs = Math.max(expect - worked, 0.5 * worked, 5 * SEC)
77  return { pct: clamp(pct, 1, 95), etaMs, basis: 'pace' }
78}
79
80function planEstimate(plan: Plan, b: Beat, now: number, expect: number): Estimate {
81  const total = plan.total
82  const done = clamp(plan.done, 0, total)
83  const since = b.planAt || b.startedAt
84  // The pace per task so far; before the first task is done, the expected turn
85  // split across the plan.
86  const spent = Math.max(0, plan.changedAt - since)
87  const per = done >= 1 && spent > 0 ? Math.max(spent / done, 5 * SEC) : Math.max(expect / total, 20 * SEC)
88  // A task in progress creeps toward done as its expected time passes.
89  const active = clamp(plan.active, 0, total - done)
90  const creep = Math.min(0.9, 1 - Math.exp(-Math.max(0, now - plan.changedAt) / per))
91  const units = done + active * creep
92  const pct = clamp((100 * units) / total, 1, 99)
93  return { pct, etaMs: Math.max(per * Math.max(total - units, 0.1), 5 * SEC), basis: 'plan' }
94}
95
96/**
97 * The expected length and time worked that put a plan-less turn at `pct` with
98 * about `etaMs` left: the pace curve run backwards, for `/pulse demo`.
99 */
100export function demoTiming(pct: number, etaMs: number): { expectMs: number; workedMs: number } {
101  const x = -Math.log(1 - clamp(pct, 1, 94) / 95) / 1.2
102  // Up to two thirds of the expected length what is left is the rest of it;
103  // past that, half the time worked.
104  const expectMs = x <= 2 / 3 ? etaMs / (1 - x) : etaMs / (0.5 * x)
105  return { expectMs: Math.round(expectMs), workedMs: Math.round(x * expectMs) }
106}
107
108// ---------------------------------------------------------------------------
109// Plans
110
111type PlanCounts = { done: number; active: number; total: number }
112
113/** A plan with `changedAt` kept when the counts did not move. */
114export function withChange(prev: Plan | null, next: PlanCounts, source: string, now: number): Plan | null {
115  if (next.total < 1) return null
116  const isSame = prev !== null && prev.done === next.done && prev.active === next.active && prev.total === next.total
117  return { ...next, source, changedAt: isSame ? prev.changedAt : now }
118}
119
120/** TodoWrite's list: its counts and the item in progress. */
121export function todosPlan(todos: unknown): { counts: PlanCounts; activity: string } | null {
122  if (!Array.isArray(todos) || todos.length === 0) return null
123  let done = 0
124  let active = 0
125  let activity = ''
126  for (const t of todos) {
127    const item = (t ?? {}) as { status?: unknown; activeForm?: unknown; content?: unknown }
128    if (item.status === 'completed') done += 1
129    if (item.status === 'in_progress') {
130      active += 1
131      if (!activity) activity = clip(oneLine(str(item.activeForm) || str(item.content)), 60)
132    }
133  }
134  return { counts: { done, active, total: todos.length }, activity }
135}
136
137export type TaskEntry = { status: string; label: string }
138
139/** The Task tools' list (TaskCreate, TaskUpdate), kept by the session as it sees the calls. */
140export function tasksPlan(tasks: ReadonlyMap<string, TaskEntry>): { counts: PlanCounts; activity: string } | null {
141  const live = [...tasks.values()].filter(t => t.status !== 'deleted')
142  if (live.length === 0) return null
143  const active = live.filter(t => t.status === 'in_progress')
144  return {
145    counts: { done: live.filter(t => t.status === 'completed').length, active: active.length, total: live.length },
146    activity: active[0]?.label ?? '',
147  }
148}
149
150type GoalTask = { status?: unknown; size?: unknown; replaced?: unknown }
151const SIZE: Record<string, number> = { S: 1, M: 2, L: 3 }
152
153/** Goal Meter's plan file for this session, weighted by task size as Goal Meter weighs it. */
154export function goalPlan(raw: unknown): PlanCounts | null {
155  const g = (raw ?? {}) as { status?: unknown; tasks?: unknown }
156  if (g.status !== 'running' || !Array.isArray(g.tasks)) return null
157  const live = (g.tasks as GoalTask[]).filter(t => t && !t.replaced && t.status !== 'dropped')
158  if (live.length === 0) return null
159  const w = (t: GoalTask): number => SIZE[String(t.size ?? 'M').toUpperCase()] ?? 2
160  return {
161    done: live.filter(t => t.status === 'done').reduce((a, t) => a + w(t), 0),
162    active: live.filter(t => t.status === 'active').reduce((a, t) => a + w(t), 0),
163    total: live.reduce((a, t) => a + w(t), 0),
164  }
165}
166
167/** savvy-progress's `progress` and `step` calls. */
168export function savvyPlan(input: Record<string, unknown>, prev: Plan | null): PlanCounts | null {
169  const total = Math.round(finite(input.total, prev?.total ?? 0))
170  if (total < 1) return null
171  if (input.finished === true) return { done: total, active: 0, total }
172  const done = clamp(Math.round(finite(input.done, prev?.done ?? 0)), 0, total)
173  return { done, active: done < total ? 1 : 0, total }
174}
175
176// ---------------------------------------------------------------------------
177// What a session is doing, from its tool calls
178
179const str = (v: unknown): string => (typeof v === 'string' ? v : '')
180const oneLine = (s: string): string => s.replace(/\s+/g, ' ').trim()
181
182export function clip(s: string, max: number): string {
183  const chars = [...s]
184  return chars.length > max ? chars.slice(0, Math.max(1, max - 1)).join('') + '…' : s
185}
186
187export function basename(path: string): string {
188  return path.split(/[\\/]/).filter(Boolean).pop() ?? path
189}
190
191export function activityOf(tool: string, input: Record<string, unknown>): string {
192  switch (tool) {
193    case 'Edit':
194    case 'MultiEdit':
195    case 'Write':
196      return `Editing ${basename(str(input.file_path))}`
197    case 'NotebookEdit':
198      return `Editing ${basename(str(input.notebook_path))}`
199    case 'Read':
200      return `Reading ${basename(str(input.file_path))}`
201    case 'Bash': {
202      const what = oneLine(str(input.description))
203      if (what) return clip(what, 60)
204      const head = oneLine(str(input.command)).split(' ').slice(0, 3).join(' ')
205      return clip(`Running ${head}`, 60)
206    }
207    case 'Grep':
208    case 'Glob':
209    case 'ToolSearch':
210      return 'Searching'
211    case 'WebFetch':
212    case 'WebSearch':
213      return 'Researching the web'
214    case 'Agent':
215    case 'Task': {
216      const what = oneLine(str(input.description))
217      return what ? clip(`Delegating: ${what}`, 60) : 'Running a subagent'
218    }
219    case 'AskUserQuestion':
220      return 'Waiting for your answer'
221    case 'ExitPlanMode':
222      return 'Waiting for plan approval'
223    case 'Skill':
224      return str(input.skill) ? clip(`Using skill ${str(input.skill)}`, 60) : 'Using a skill'
225    case 'TodoWrite':
226    case 'TaskCreate':
227    case 'TaskUpdate':
228    case 'TaskGet':
229    case 'TaskList':
230      return ''
231  }
232  if (tool.startsWith('mcp__')) {
233    const name = tool.split('__').slice(2).join('__') || tool.slice(5)
234    return clip(`Using ${name.replace(/_/g, ' ')}`, 60)
235  }
236  return clip(`Using ${tool}`, 60)
237}
238
239/**
240 * What a waiting session needs from you, in two or three words: the tool it
241 * asks to run, the question it asks, the plan it wants approved.
242 */
243export function permissionNeed(tool: string): string {
244  const name: Record<string, string> = {
245    Bash: 'bash',
246    Edit: 'edit',
247    MultiEdit: 'edit',
248    Write: 'write',
249    NotebookEdit: 'notebook edit',
250    WebFetch: 'web fetch',
251    WebSearch: 'web search',
252    Read: 'read',
253    Agent: 'subagent',
254    Task: 'subagent',
255  }
256  if (name[tool] !== undefined) return `allow ${name[tool]}`
257  if (tool.startsWith('mcp__')) return clip(`allow ${(tool.split('__').slice(2).join(' ') || tool.slice(5)).replace(/_/g, ' ')}`, 30)
258  return tool ? clip(`allow ${tool.toLowerCase()}`, 30) : 'allow tool'
259}
260
261export function askNeed(tool: string, input: Record<string, unknown>): string {
262  if (tool === 'ExitPlanMode') return 'approve plan'
263  const first = Array.isArray(input.questions) ? (input.questions[0] as { header?: unknown } | undefined) : undefined
264  const header = typeof first?.header === 'string' ? oneLine(first.header) : ''
265  return header ? clip(`pick ${header.toLowerCase()}`, 30) : 'answer question'
266}
267
268/** A board title from a prompt: its first line, one space between words. */
269export function titleFromPrompt(text: string): string {
270  const line = text.split(/\r?\n/).map(l => l.trim()).find(Boolean) ?? ''
271  if (line.startsWith('<')) return ''
272  return clip(oneLine(line), 80)
273}
274
275// ---------------------------------------------------------------------------
276// Reading another session's heartbeat safely
277
278const ID = /^[A-Za-z0-9-]{8,64}$/
279export const HOST_ID = /^local_[A-Za-z0-9-]{1,64}$/
280
281/** A heartbeat read from disk, checked field by field; null when it is not one. */
282export function asBeat(raw: unknown): Beat | null {
283  if (raw === null || typeof raw !== 'object') return null
284  const r = raw as Record<string, unknown>
285  if (r.v !== 1 || typeof r.id !== 'string' || !ID.test(r.id)) return null
286  const state = STATES.includes(r.state as PulseState) ? (r.state as PulseState) : 'idle'
287  const p = r.plan as Record<string, unknown> | null | undefined
288  const plan: Plan | null =
289    p && typeof p === 'object' && finite(p.total) >= 1
290      ? {
291          done: Math.max(0, finite(p.done)),
292          active: Math.max(0, finite(p.active)),
293          total: finite(p.total),
294          source: clip(str(p.source), 20),
295          changedAt: finite(p.changedAt),
296        }
297      : null
298  return {
299    v: 1,
300    id: r.id,
301    hostId: HOST_ID.test(str(r.hostId)) ? str(r.hostId) : '',
302    surface: clip(str(r.surface), 16),
303    title: clip(oneLine(str(r.title)), 120),
304    project: clip(str(r.project), 80),
305    cwd: str(r.cwd).slice(0, 1024),
306    state,
307    bornAt: finite(r.bornAt),
308    startedAt: finite(r.startedAt),
309    endedAt: finite(r.endedAt),
310    waitMs: Math.max(0, finite(r.waitMs)),
311    waitingSince: Math.max(0, finite(r.waitingSince)),
312    tools: Math.max(0, finite(r.tools)),
313    activity: clip(oneLine(str(r.activity)), 80),
314    plan,
315    planAt: finite(r.planAt),
316    expectMs: finite(r.expectMs, DEFAULT_TURN_MS),
317    turns: Math.max(0, finite(r.turns)),
318    lastMs: Math.max(0, finite(r.lastMs)),
319    stopPct: clamp(finite(r.stopPct), 0, 100),
320    agents: Math.max(0, finite(r.agents)),
321    need: clip(oneLine(str(r.need)), 32),
322    ended: r.ended === true,
323    updatedAt: finite(r.updatedAt),
324  }
325}
326
327// ---------------------------------------------------------------------------
328// Text and color
329
330export function durText(ms: number): string {
331  // 59.6 s rounds to a minute, not to "60s".
332  if (ms < MIN - SEC / 2) return `${Math.max(1, Math.round(ms / SEC))}s`
333  const m = Math.round(ms / MIN)
334  if (m < 60) return `${m}m`
335  const h = Math.floor(m / 60)
336  const rest = m % 60
337  return rest ? `${h}h ${rest}m` : `${h}h`
338}
339
340/** The time-left label, `~30m` as the board shows it. */
341export function etaText(ms: number | null): string {
342  if (ms === null || !Number.isFinite(ms)) return ''
343  if (ms < MIN) return '<1m'
344  return `~${durText(ms)}`
345}
346
347export function agoText(ms: number): string {
348  return ms < MIN ? 'just now' : `${durText(ms)} ago`
349}
350
351// Muted throughout: no state color is far from grey, so the band reads calm.
352export const COLOR = {
353  done: '#4f9a72',
354  waiting: '#6f9fd6',
355  error: '#cf6a62',
356  stopped: '#8e8e8e',
357  idle: '#767676',
358  track: '#3a3a3a',
359} as const
360
361function hex(n: number): string {
362  return Math.round(clamp(n, 0, 1) * 255)
363    .toString(16)
364    .padStart(2, '0')
365}
366
367export function hsl(h: number, s: number, l: number): string {
368  const k = (n: number): number => (n + h / 30) % 12
369  const a = s * Math.min(l, 1 - l)
370  const f = (n: number): number => l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1))
371  return `#${hex(f(0))}${hex(f(8))}${hex(f(4))}`
372}
373
374/** Orange at the start, warming to yellow-green as the bar fills. */
375/**
376 * Light to deep as the bar fills: a pale straw yellow at the start, a soft
377 * lime midway, a deep sage near the end, and the done green past it. Hue,
378 * saturation and lightness move together, saturation kept low throughout.
379 */
380export function workingColor(pct: number): string {
381  const t = clamp(pct, 0, 99) / 99
382  return hsl(52 + t * 88, 0.58 - t * 0.2, 0.76 - t * 0.3)
383}
384
385export function colorOf(state: PulseState, pct: number): string {
386  switch (state) {
387    case 'working':
388      return workingColor(pct)
389    case 'waiting':
390      return COLOR.waiting
391    case 'done':
392      return COLOR.done
393    case 'error':
394      return COLOR.error
395    case 'stopped':
396      return COLOR.stopped
397    default:
398      return COLOR.idle
399  }
400}
401
402export function iconOf(state: PulseState): string {
403  switch (state) {
404    case 'done':
405      return '✓'
406    case 'error':
407      return '✗'
408    case 'stopped':
409      return '■'
410    case 'idle':
411      return '○'
412    default:
413      return '●'
414  }
415}
416
417/** Cells a code point takes on a terminal: CJK and emoji take two. */
418export function charCells(cp: number): number {
419  if (cp < 32 || (cp >= 0x7f && cp < 0xa0)) return 0
420  if ((cp >= 0x300 && cp <= 0x36f) || cp === 0x200d || (cp >= 0xfe00 && cp <= 0xfe0f)) return 0
421  const isWide =
422    (cp >= 0x1100 && cp <= 0x115f) ||
423    (cp >= 0x2e80 && cp <= 0x303e) ||
424    (cp >= 0x3041 && cp <= 0x33ff) ||
425    (cp >= 0x3400 && cp <= 0x4dbf) ||
426    (cp >= 0x4e00 && cp <= 0x9fff) ||
427    (cp >= 0xa000 && cp <= 0xa4cf) ||
428    (cp >= 0xac00 && cp <= 0xd7a3) ||
429    (cp >= 0xf900 && cp <= 0xfaff) ||
430    (cp >= 0xfe30 && cp <= 0xfe4f) ||
431    (cp >= 0xff00 && cp <= 0xff60) ||
432    (cp >= 0xffe0 && cp <= 0xffe6) ||
433    (cp >= 0x1f300 && cp <= 0x1f64f) ||
434    (cp >= 0x1f900 && cp <= 0x1f9ff) ||
435    (cp >= 0x20000 && cp <= 0x3fffd)
436  return isWide ? 2 : 1
437}
438
439export function cells(s: string): number {
440  let n = 0
441  for (const ch of s) n += charCells(ch.codePointAt(0) ?? 0)
442  return n
443}
444
445/** Cut to `width` cells with an ellipsis, then pad with spaces to exactly `width`. */
446export function fit(s: string, width: number): string {
447  if (width <= 0) return ''
448  if (cells(s) <= width) return s + ' '.repeat(width - cells(s))
449  let out = ''
450  let used = 0
451  for (const ch of s) {
452    const w = charCells(ch.codePointAt(0) ?? 0)
453    if (used + w > width - 1) break
454    out += ch
455    used += w
456  }
457  return out + '…' + ' '.repeat(Math.max(0, width - used - 1))
458}
459
460/** A terminal bar: the filled part and the track, `width` cells in all. */
461export function barCells(pct: number, width: number): { fill: string; rest: string } {
462  const raw = Math.round((clamp(pct, 0, 100) / 100) * width)
463  const n = pct > 0 ? clamp(raw, 1, width) : 0
464  return { fill: '━'.repeat(n), rest: '━'.repeat(Math.max(0, width - n)) }
465}
466
467const FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Inter, Roboto, sans-serif"
468
469const xml = (s: string): string =>
470  s.replace(/[<>&'"]/g, c => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', "'": '&apos;', '"': '&quot;' })[c] ?? c)
471
472export const SVG_HEIGHT = 22
473
474// Rolling numbers: each changed digit is a strip of 0-9 behind a window that
475// rolls from the old digit to the new one, odometer style; digits that kept
476// their value stand still. SMIL, so it plays inside the SVG image.
477//
478// With the app's own glyphs (DigitFont, extracted from the Claude app's UI
479// font by scripts/digits-from-app-font.py) the digits are drawn as outlines at
480// the app's text size, so they match the band's text exactly; without them,
481// as text in the system font.
482
483export type DigitFont = {
484  unitsPerEm: number
485  capHeight: number
486  glyphs: Record<string, { advance: number; path: string }>
487}
488
489/** The extracted glyph file, checked; null when it is not one. */
490export function asDigitFont(raw: unknown): DigitFont | null {
491  const f = raw as { unitsPerEm?: unknown; capHeight?: unknown; glyphs?: Record<string, { advance?: unknown; path?: unknown }> } | null
492  if (f === null || typeof f !== 'object' || typeof f.unitsPerEm !== 'number' || typeof f.capHeight !== 'number' || f.glyphs === undefined) return null
493  const glyphs: DigitFont['glyphs'] = {}
494  const isGlyph = (g: { advance?: unknown; path?: unknown } | undefined): g is { advance: number; path: string } =>
495    g !== undefined && typeof g.advance === 'number' && typeof g.path === 'string' && /^[MLHVQCZz0-9 .,-]*$/.test(g.path)
496  // The digits and % are required; letters (for the state chips) are taken when present.
497  for (const ch of '0123456789%') {
498    const g = f.glyphs[ch]
499    if (!isGlyph(g)) return null
500    glyphs[ch] = { advance: g.advance, path: g.path }
501  }
502  for (const [ch, g] of Object.entries(f.glyphs)) {
503    if ([...ch].length === 1 && glyphs[ch] === undefined && isGlyph(g)) glyphs[ch] = { advance: g.advance, path: g.path }
504  }
505  return { unitsPerEm: f.unitsPerEm, capHeight: f.capHeight, glyphs }
506}
507
508/**
509 * A state chip styled as the app's hotkey keycap (the handoff button's H): a
510 * rounded rectangle a shade off the background with a thin border, no color,
511 * sized to the word
512 * and to the row (18px tall in a 22px row); grey as the band's dim text, in
513 * either theme. Drawn in the app's own glyphs when every letter is there, else
514 * in the system font. (`color` is kept for a coloured variant; unused.)
515 */
516export function chipSvg(word: string, color: string, font: DigitFont | null): { source: string; width: number; height: number } {
517  const H = 18
518  const PAD = 7
519  const size = 12
520  void color
521  const hasGlyphs = font !== null && [...word].every(ch => ch === ' ' || font.glyphs[ch] !== undefined)
522  let inner: string
523  let textW: number
524  if (hasGlyphs && font !== null) {
525    const k = size / font.unitsPerEm
526    const baseline = H / 2 + (font.capHeight * k) / 2
527    let x = PAD
528    const uses: string[] = []
529    for (const ch of word) {
530      const g = font.glyphs[ch]
531      if (g !== undefined && g.path) uses.push(`<path d="${g.path}" transform="translate(${x.toFixed(2)} ${baseline.toFixed(2)}) scale(${k} ${-k})"/>`)
532      x += (g?.advance ?? font.unitsPerEm * 0.3) * k
533    }
534    textW = x - PAD
535    inner = `<g class="c">${uses.join('')}</g>`
536  } else {
537    textW = cells(word) * size * 0.56
538    inner = `<text class="c" x="${PAD}" y="${H / 2 + 4}" font-family="${FONT}" font-size="${size}">${xml(word)}</text>`
539  }
540  const W = Math.ceil(textW + PAD * 2)
541  const source = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">
542<style>.c{fill:#7f7d78}.b{stroke:#d3d1cc;fill:#f3f2ef}
543@media (prefers-color-scheme: dark){.c{fill:#9a9893}.b{stroke:#4a4a48;fill:#272727}}</style>
544<rect class="b" x="0.5" y="0.5" width="${W - 1}" height="${H - 1}" rx="4"/>
545${inner}
546</svg>`
547  return { source, width: W, height: H }
548}
549
550/** The app's text size in the band, measured against its own font. */
551export const APP_TEXT_PX = 13
552const DIGIT_W = 8
553const ROW_H = 18
554const ROLL = 'dur="0.6s" fill="freeze" calcMode="spline" keyTimes="0;1" keySplines="0.2 0.8 0.2 1"'
555
556export function rollingNumber(text: string, prev: string, right: number, H: number, font: DigitFont | null = null): string {
557  const m = /^(\d+)(.*)$/.exec(text)
558  if (font !== null && m !== null && [...text].every(ch => font.glyphs[ch] !== undefined)) return rollingGlyphs(text, prev, right, H, font)
559  const baseline = H / 2 + 5
560  const plain = (x: number, ch: string, anchor = 'middle'): string =>
561    `<text class="t" x="${x}" y="${baseline}" text-anchor="${anchor}" font-family="${FONT}" font-size="13">${xml(ch)}</text>`
562  if (m === null) return text ? plain(right, text, 'end') : ''
563  const digits = m[1] ?? ''
564  const suffix = m[2] ?? ''
565  const suffixW = suffix ? 10 : 0
566  const was = (/^(\d+)/.exec(prev)?.[1] ?? '').padStart(digits.length, ' ').slice(-digits.length)
567  const x0 = right - suffixW - digits.length * DIGIT_W
568  const top = H / 2 - ROW_H / 2
569  const parts: string[] = [`<defs><clipPath id="win"><rect x="${x0 - 1}" y="${top}" width="${digits.length * DIGIT_W + 2}" height="${ROW_H}"/></clipPath></defs>`]
570  const rolls: string[] = []
571  ;[...digits].forEach((ch, i) => {
572    const cx = x0 + i * DIGIT_W + DIGIT_W / 2
573    const from = was[i] ?? ' '
574    if (prev === '' || from === ch) {
575      parts.push(plain(cx, ch))
576      return
577    }
578    const strip = Array.from({ length: 10 }, (_, d) =>
579      `<text class="t" x="${cx}" y="${baseline + d * ROW_H}" text-anchor="middle" font-family="${FONT}" font-size="13">${d}</text>`).join('')
580    const start = from === ' ' ? ROW_H : -Number(from) * ROW_H
581    const end = -Number(ch) * ROW_H
582    rolls.push(`<g transform="translate(0 ${end})"><animateTransform attributeName="transform" type="translate" from="0 ${start}" to="0 ${end}" ${ROLL}/>${strip}</g>`)
583  })
584  if (rolls.length) parts.push(`<g clip-path="url(#win)">${rolls.join('')}</g>`)
585  if (suffix) parts.push(plain(right, suffix, 'end'))
586  return parts.join('')
587}
588
589// The same roll with the app's glyph outlines: each glyph defined once, used
590// by reference, scaled to the app's text size and centred on the bar's line.
591function rollingGlyphs(text: string, prev: string, right: number, H: number, font: DigitFont): string {
592  const k = APP_TEXT_PX / font.unitsPerEm
593  const baseline = H / 2 + (font.capHeight * k) / 2
594  const advance = (ch: string): number => (font.glyphs[ch]?.advance ?? 0) * k
595  const m = /^(\d+)(.*)$/.exec(text)
596  const digits = m?.[1] ?? ''
597  const suffix = m?.[2] ?? ''
598  const was = (/^(\d+)/.exec(prev)?.[1] ?? '').padStart(digits.length, ' ').slice(-digits.length)
599  const isRolling = prev !== '' && [...digits].some((ch, i) => (was[i] ?? ' ') !== ch)
600  const used = new Set(isRolling ? '0123456789' + suffix : text)
601  const defs = [...used].map(ch => `<path id="g${ch === '%' ? 'p' : ch}" d="${font.glyphs[ch]?.path ?? ''}"/>`).join('')
602  const use = (ch: string, x: number, y: number): string =>
603    `<use href="#g${ch === '%' ? 'p' : ch}" transform="translate(${x.toFixed(2)} ${y.toFixed(2)}) scale(${k} ${-k})"/>`
604  const total = [...text].reduce((a, ch) => a + advance(ch), 0)
605  let x = right - total
606  const top = H / 2 - ROW_H / 2
607  const parts: string[] = []
608  const rolls: string[] = []
609  for (const [i, ch] of [...digits].entries()) {
610    const w = advance(ch)
611    const from = was[i] ?? ' '
612    if (prev === '' || from === ch) {
613      parts.push(use(ch, x, baseline))
614    } else {
615      // A strip of 0-9 down the slot, each glyph centred in it.
616      const strip = Array.from({ length: 10 }, (_, d) => use(String(d), x + (w - advance(String(d))) / 2, baseline + d * ROW_H)).join('')
617      const start = from === ' ' ? ROW_H : -Number(from) * ROW_H
618      const end = -Number(ch) * ROW_H
619      rolls.push(`<g transform="translate(0 ${end})"><animateTransform attributeName="transform" type="translate" from="0 ${start}" to="0 ${end}" ${ROLL}/>${strip}</g>`)
620    }
621    x += w
622  }
623  for (const ch of suffix) {
624    parts.push(use(ch, x, baseline))
625    x += advance(ch)
626  }
627  const clip = rolls.length ? `<clipPath id="win"><rect x="${right - total - 1}" y="${top}" width="${total + 2}" height="${ROW_H}"/></clipPath>` : ''
628  return `<defs>${defs}${clip}</defs><g class="d">${parts.join('')}${rolls.length ? `<g clip-path="url(#win)">${rolls.join('')}</g>` : ''}</g>`
629}
630
631/**
632 * A desktop bar: a rounded track, the fill, the percent and the time left dim,
633 * as the board's mock-up draws them. Light and dark theme alike. Given what
634 * the last drawing showed (`prevPct`, `prevPctText`), the fill grows from its
635 * old length and the changed digits roll to their new values.
636 */
637export function barSvg(o: { pct: number; color: string; width: number; pctText: string; prevPct?: number; prevPctText?: string; tail: string; tailColor: string; isLive: boolean; isBarOnly?: boolean; font?: DigitFont | null; pctW?: number }): string {
638  const W = Math.max(120, Math.round(o.width))
639  const H = SVG_HEIGHT
640  // Bar only: the percent and time left are drawn as text beside the picture.
641  // No tail given: the time left is drawn as text beside the picture.
642  const tailW = o.isBarOnly === true || o.tail === '' ? 0 : 64
643  const pctW = o.isBarOnly === true ? 0 : (o.pctW ?? 48)
644  const barW = o.isBarOnly === true ? W : Math.max(40, W - tailW - pctW - (tailW === 0 ? 8 : 12))
645  const barH = 8
646  const y = (H - barH) / 2
647  const widthOf = (pct: number): number => (pct > 0 ? Math.max(barH, Math.round((barW * clamp(pct, 0, 100)) / 100)) : 0)
648  const fillW = widthOf(o.pct)
649  const fromW = o.prevPct === undefined ? fillW : widthOf(o.prevPct)
650  const grow = fromW !== fillW ? `<animate attributeName="width" from="${fromW}" to="${fillW}" ${ROLL}/>` : ''
651  // An inline style, since the theme class would win over a fill attribute.
652  const tailStyle = /^#[0-9a-f]{6}$/i.test(o.tailColor) ? ` style="fill:${o.tailColor}"` : ' class="m"'
653  return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">
654<style>.k{fill:#e2e2df}.t{fill:#1f1f1f}.m{fill:#8a8a86}.d{fill:#7f7d78}
655@media (prefers-color-scheme: dark){.k{fill:#3a3a3a}.t{fill:#f4f4f2}.m{fill:#8f8f8b}.d{fill:#898782}}
656.p{animation:pl 1.8s ease-in-out infinite}@keyframes pl{50%{opacity:.6}}
657@media (prefers-reduced-motion: reduce){.p{animation:none}}</style>
658<rect class="k" x="0" y="${y}" width="${barW}" height="${barH}" rx="${barH / 2}"/>
659${fillW ? `<rect${o.isLive ? ' class="p"' : ''} x="0" y="${y}" width="${fillW}" height="${barH}" rx="${barH / 2}" fill="${o.color}">${grow}</rect>` : ''}
660${o.isBarOnly === true ? '' : rollingNumber(o.pctText, o.prevPctText ?? '', barW + 8 + pctW, H, o.font ?? null)}
661${o.isBarOnly === true ? '' : `<text${tailStyle} x="${W}" y="${H / 2 + 5}" text-anchor="end" font-family="${FONT}" font-size="13" font-variant-numeric="tabular-nums">${xml(o.tail)}</text>`}
662</svg>`
663}
664
types/index.d.ts 83 lines
1// Session Pulse's state contract: what each session publishes about itself
2// (a Beat), what the board draws (a Row), and the person's display settings.
3
4/** Where a session stands. `stopped` is an interrupted turn. */
5export type PulseState = 'working' | 'waiting' | 'done' | 'stopped' | 'error' | 'idle'
6
7/** A task plan the session is following, from TodoWrite, the Task tools or another mod. */
8export type Plan = {
9  done: number
10  active: number
11  total: number
12  source: string
13  /** When `done` or `active` last changed. */
14  changedAt: number
15}
16
17/** One session's heartbeat, written to its own file under mods-data. */
18export type Beat = {
19  v: 1
20  /** The Claude Code session id (the transcript's name). */
21  id: string
22  /** The desktop app's `local_…` id, or '' outside the desktop app. */
23  hostId: string
24  surface: string
25  title: string
26  /** The working directory's last folder name. */
27  project: string
28  cwd: string
29  state: PulseState
30  /** When the board first saw the session: rows keep this order, so they never jump under the pointer. */
31  bornAt: number
32  /** When the current (or last) turn started. */
33  startedAt: number
34  /** When the last turn ended; 0 while working. */
35  endedAt: number
36  /** Time spent waiting on the person during this turn. */
37  waitMs: number
38  /** When the current wait began; 0 when not waiting. */
39  waitingSince: number
40  tools: number
41  activity: string
42  plan: Plan | null
43  /** When the current plan first appeared. */
44  planAt: number
45  /** How long this turn was expected to take when it started. */
46  expectMs: number
47  turns: number
48  lastMs: number
49  /** The bar's position when an interrupted or failed turn stopped. */
50  stopPct: number
51  /** Subagents still running after the turn ended. */
52  agents: number
53  /** What the session needs from you while waiting, in a few words ("allow bash"); '' otherwise. */
54  need?: string
55  ended?: boolean
56  updatedAt: number
57}
58
59/** A board row: a beat plus how this viewer sees it. */
60export type Row = Beat & {
61  isSelf: boolean
62  isHidden: boolean
63  isStale: boolean
64}
65
66export type Prefs = {
67  /** `full`: a row per session; `compact`: one summary line; `off`: no band. */
68  mode: 'full' | 'compact' | 'off'
69  /** Toast when another session finishes or needs you. */
70  alerts: boolean
71}
72
73declare module 'claude-code' {
74  interface PluginState {
75    'session-pulse': {
76      rows: Row[]
77      now: number
78      prefs: Prefs
79      isMasked: boolean
80    }
81  }
82}
83