Sessions pane: every open session with a status light, step progress and time, plus 5-hour and weekly usage

A Claude Code mod that adds a Sessions pane: one place to see what every open session is doing, how far along it is, which ones are waiting for you, and how much of your 5-hour and weekly usage is left.
- (for example Admin site and Admin site-login) are grouped under one header.-purpose suffix. Sessions started by the desktop app's project system get - and the first 2 characters of their folder name appended, so you can tell which project they belong to. Sessions you renamed yourself are left alone.| Light | Meaning |
|---|---|
| Blue dot | Working (including background work that is still running) |
| Orange dot | Finished, and you have not looked at it yet |
| Hollow dot | You have seen it |
| Red dot | There is a problem you need to handle |
| Red triangle | A severe problem; the work may have stopped |
%APPDATA%\Claude\claude-code-sessions\;claude:// link through rundll32.exe). git clone https://github.com/KeaneCloud/session-dashboard.git
CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json (separate several mods with ;): {
"env": {
"CLAUDE_CODE_PLUGIN_DIRS": "C:\\path\\to\\session-dashboard"
}
}
To try it once in a terminal instead:
claude --plugin-dir /path/to/session-dashboard
The pane opens automatically with each session. If you close it, press ☰ Sessions above the prompt to open it again.
The pane is in English by default. For Traditional Chinese, set an environment variable in ~/.claude/settings.json:
{
"env": {
"SESSION_DASHBOARD_LANG": "zh-TW"
}
}
All strings live in hooks/i18n.js; to add a language, add a block there with the same keys.
The mod registers a tool, mcp__session-dashboard__progress. When Claude calls it, the step timeline appears in the pane. To make that a habit, add something like this to your ~/.claude/CLAUDE.md:
- **Sessions pane**: when the `mcp__session-dashboard__progress` tool is available (use ToolSearch
if it is not loaded), call it when a task starts, when a step finishes, when you are blocked and
waiting for me, and when the task is done. Pass the full step list every time, at most 5 steps,
a few words per step. status: done / running / warn (a problem I need to handle) / bad (a severe
problem) / todo. Pass an empty list when the task is over.
When Claude has not called the tool, the pane falls back to the checkboxes in checklist.md (or TASKS.md) in the working folder, but only once that session has written to the file itself. A checklist left there by another session is ignored:
- [x] A finished step
- [ ] A step still to do
- [ ] A blocked step BLOCKED: what you need from the user
- [ ] A broken step CRITICAL: what went wrong
Two features call a small model (Haiku), each for a few tokens:
To turn auto-naming off, set AUTO_RENAME to false at the top of hooks/register.js.
Tunable values are constants at the top of hooks/register.js and hooks/lib.js. Restart the app after changing them.
| Constant | Default | Meaning |
|---|---|---|
AUTO_OPEN | true | Open the pane when a session starts |
AUTO_RENAME | true | Name sessions automatically |
RENAME_AFTER_TURNS | 2 | Turn after which a session is named |
TITLE_MAX | 6 | Longest session name, in words (plus up to SUFFIX_MAX for a -purpose suffix) |
TASK_LABEL_MAX | 12 | Longest task summary, in words |
TIME_REDRAW_MS | 60 s | How often times and usage are refreshed |
CHANGE_CHECK_MS | 10 s | How often other sessions are checked for changes |
LIGHT (lib.js) | – | Status light colours |
$.store, kept on your machine by Claude Code): each session's name, status and step progress, plus the latest usage reading. This is how the panes of different sessions see each other.checklist.md / TASKS.md in the working folder.claude plugin validate .
claude plugin test .
Tests are in tests/ and use the claude-code/testing kit that ships with Claude Code. .claude-plugin/types/ is generated by Claude Code and is not checked in.
hooks/register.js 966 lines1// session-dashboard: Sessions pane — a timeline of the current session's steps, a list of other sessions with status lights, and usage pinned at the bottom. Above the prompt there is only a button that opens the pane.
2// Step data comes from the plugin's `progress` tool (preferred), falling back to checklist.md / TASKS.md in the working folder.
3// Cross-session data lives in $.store (shared by every session on this machine); each session writes only its own keys, so sessions never overwrite each other.
4// Rendering (ui.render) is read-only; cleanup and publishing happen on the heartbeat or in event hooks.
5import { setLang, t } from './i18n.js'
6import {
7 etaText, estimateRemainingMin, folderName, jumpUrl, liveSessions, mergeProgress, parseTaskSteps,
8 STALE_MS, stepStats, svgTimelineNode, svgThinBar, limitColor, tasksPath, CHECKLIST_FILES, othersSignature, thinBar, titleFromTranscript, usageSegments,
9 desktopRecordMatches, currentStepLabel, splitHidden, COLORS, ago,
10 actionLabel, pushAction, showActivity, summarizeBackground,
11 ROWS, FALLBACK_BUDGET, usageRows, fitSteps, othersRows,
12 LIGHT, statusOf, rightTime, svgOtherLine, svgSectionDivider, svgSessionGap, timelineItems, cleanTitle, nameUnits, wrapByWidth, touchesChecklist, nodeHeight, isProjectSession, projectTag, clientRowMode, sortByUrgency, groupSessions, hoverInfo, svgAlertIcon, conversationDigest, todosToInput,
13} from './lib.js'
14
15// ===== Tunables (edit here) =====
16const PANE_ID = 'session-dashboard'
17const KEY_PREFIX = 'session:' // $.store: per-session summary (shown in other sessions' panes)
18const HIDDEN_PREFIX = 'hidden:' // $.store: one entry { at } per hidden session (no whole-object read-modify-write, so sessions cannot overwrite each other)
19const LEGACY_HIDDEN_KEY = 'hidden' // Legacy single-object hidden record; still read, and migrated to per-session keys on the heartbeat
20const USAGE_KEY = 'usage:last' // $.store: latest usage reading (account-wide; used by new sessions that have no reading yet)
21const USAGE_STALE_MS = 5 * 60 * 1000 // When showing another session's reading older than this, label it with the reading time
22const PROGRESS_PREFIX = 'progress:' // $.store: the full step list each session reported through the progress tool
23const HEARTBEAT_MS = 30 * 1000 // How often to publish own state, re-read TASKS.md and prune stale data
24const CHANGE_CHECK_MS = 10 * 1000 // How often to check other sessions for changes (redraw only on change)
25const TIME_REDRAW_MS = 60 * 1000 // How often time labels (~18m, 3m ago) and usage are redrawn (1 minute by design)
26const FOCUS_REFRESH_MS = 10 * 1000 // How often to check Desktop's "last focused" time (drives the finished-unread light)
27const TITLE_REFRESH_MS = 60 * 1000 // How often to re-read the session name (a rename shows up within 60 s)
28const TRANSCRIPT_MAX_BYTES = 4 * 1024 * 1024 // $.fs.read per-file limit is 4 MiB (official Limits table)
29const PROGRESS_TOOL = 'mcp__session-dashboard__progress'
30const TODO_TOOL = 'TodoWrite' // Claude's built-in todo list; its input is { todos: [{ content, status }] }
31const ACTIVITY_PUBLISH_MS = 10 * 1000 // Activity is written to the shared store at most once every 10 s
32const AUTO_OPEN = true // Open the pane automatically when a session starts
33const PANE_BUTTON_LABEL = '☰ Sessions' // Label of the open-pane button above the prompt
34// Auto-naming: after turn RENAME_AFTER_TURNS, a small model picks a name of at most TITLE_MAX units, once per session; manually renamed sessions are left alone
35const AUTO_RENAME = true // Set to false to turn auto-naming off
36const RENAME_AFTER_TURNS = 2 // The user asked for 2 (2026-10-20): 3 turns felt too long
37const TITLE_MAX = 6 // Longest name in units; a name with a "-purpose" suffix may add SUFFIX_MAX more (user's rule, 2026-10-19: the noun for the thing, nothing else)
38const SUFFIX_MAX = 3
39const PROJECT_TAG_CHARS = 2 // Sessions started by the project system get "-<first N characters of the folder name>" (user's rule, 2026-10-21)
40const RENAME_MODEL = 'haiku'
41const RENAME_TOOL = 'mcp__ccd_session_mgmt__set_session_title' // Desktop's official rename tool (records the title source as "tool")
42const RENAMED_PREFIX = 'renamed:' // $.store: sessions already auto-named (guarantees a single attempt, no retry on failure)
43const TASK_LABEL_MAX = 12 // Max length of the current-task summary (edit here)
44const NAME_RESERVED_CELLS = 16 // Cells taken on an other-session name line by ✕, the light and the right-hand time (approx.)
45const OWNS_PREFIX = 'checklist:' // $.store: sessions that wrote a checklist file themselves (only those show it as their steps)
46const NODE_WRAP_MARGIN = 3 // Cells taken off the estimated text width so wrapped lines are not under-counted (2026-10-21: a 3-line note was drawn with a gap)
47const STEP_RESERVED_CELLS = 6 // Cells taken by the timeline node and gap to the left of a step's text
48const CLICK_LOG_KEY = 'click-log' // Last clicks on session blocks, kept so a real click in the app can be checked afterwards
49const CLICK_LOG_MAX = 20
50const CLIENT_GRACE_MS = 12000 // How long a session block may take to report that its region runs before plain rows are drawn instead (the app gives up on a region after 10 s)
51const HOVER_BG = '#88888833' // Row background while the pointer is on any part of a session (translucent gray works in light and dark)
52const SECTION_GAP = 3 // Blank lines between the current session and "other sessions" (shrinks first when space is tight)
53
54// Icon and text colour per step status (terminal; Desktop draws timeline dots)
55const STEP_LOOK = {
56 done: { icon: '✓', color: 'green' },
57 running: { icon: '●', color: 'cyan' },
58 warn: { icon: '⚠', color: 'yellow' },
59 bad: { icon: '⛔', color: 'red' },
60 todo: { icon: '○', color: undefined },
61}
62
63// State of this session; reset when the module reloads, refilled by session.start
64const me = {
65 id: '', cwd: '', isWorking: false, workStartedAt: null, finishedAt: null, seenAt: null,
66 activity: null, activityPublishedAt: 0, background: null, firstSeen: null, queuedHinted: false,
67 title: null, desktopId: null, desktopFile: null, titleCheckedAt: 0,
68 lastFocusedAt: null, focusFileMtime: 0, timers: [], titleSource: null, fromProject: false, pendingTitle: null, taskLabel: null, lastSignature: null, ownsChecklist: false,
69}
70
71// ---------- Reading files ----------
72
73/** Read checklist.md in the working folder (falling back to TASKS.md) and convert it to steps; null if neither exists. */
74async function readTaskSteps($, cwd) {
75 for (const name of CHECKLIST_FILES) {
76 try {
77 return parseTaskSteps(await $.fs.read(tasksPath(cwd, name)))
78 } catch {}
79 }
80 return null
81}
82
83/** Redraw only when other sessions or the hidden list changed; ever-changing values such as the heartbeat time do not count. */
84async function redrawIfChanged($) {
85 const now = await $.clock.now()
86 const keys = await $.store.keys()
87 const sig = othersSignature(await loadOthers($, now), keys.filter((k) => k.startsWith(HIDDEN_PREFIX)))
88 if (me.lastSignature !== null && sig !== me.lastSignature) $.ui.invalidate('ui.render')
89 me.lastSignature = sig
90}
91
92/** Read and parse a JSON file; null on failure. */
93async function readJson($, path) {
94 try {
95 return JSON.parse(await $.fs.read(path))
96 } catch {
97 return null
98 }
99}
100
101/** List all Desktop session record files (%APPDATA%\Claude\claude-code-sessions\<acc>\<org>\local_*.json), newest first. */
102async function listDesktopRecords($) {
103 const appData = await $.env.get('APPDATA')
104 if (!appData) return []
105 const root = appData + '\\Claude\\claude-code-sessions'
106 const files = []
107 try {
108 for (const a of await $.fs.list(root)) {
109 if (a.kind !== 'dir') continue
110 for (const b of await $.fs.list(root + '\\' + a.name)) {
111 if (b.kind !== 'dir') continue
112 const dir = root + '\\' + a.name + '\\' + b.name
113 for (const f of await $.fs.list(dir)) {
114 if (f.kind === 'file' && f.name.startsWith('local_') && f.name.endsWith('.json')) files.push({ path: dir + '\\' + f.name, mtimeMs: f.mtimeMs })
115 }
116 }
117 }
118 } catch {
119 return []
120 }
121 return files.sort((x, y) => y.mtimeMs - x.mtimeMs)
122}
123
124/** Find this session's record in the Desktop app: try the remembered path first, otherwise scan all records newest first and stop at the first match (no cap on how many are scanned). */
125async function findDesktopRecord($) {
126 if (me.desktopFile) {
127 const record = await readJson($, me.desktopFile)
128 if (desktopRecordMatches(record, me.id)) return record
129 me.desktopFile = null
130 }
131 for (const f of await listDesktopRecords($)) {
132 const record = await readJson($, f.path)
133 if (desktopRecordMatches(record, me.id)) {
134 me.desktopFile = f.path
135 return record
136 }
137 }
138 return null
139}
140
141/** Get the name from the transcript (~/.claude/projects/<project>/<id>.jsonl); give up if the file exceeds 4 MiB (never read the whole file). */
142async function transcriptTitle($) {
143 const home = await $.env.get('USERPROFILE')
144 if (!home) return null
145 const projects = home + '\\.claude\\projects'
146 try {
147 for (const d of await $.fs.list(projects)) {
148 if (d.kind !== 'dir') continue
149 const path = projects + '\\' + d.name + '\\' + me.id + '.jsonl'
150 if (!(await $.fs.exists(path))) continue
151 const stat = await $.fs.stat(path)
152 if (stat.size > TRANSCRIPT_MAX_BYTES) return null
153 return titleFromTranscript(await $.fs.read(path))
154 }
155 } catch {
156 return null
157 }
158 return null
159}
160
161/** Refresh the session name, Desktop id and last-focused time: Desktop record → transcript → folder name. At most once per TITLE_REFRESH_MS. */
162async function refreshTitle($, now) {
163 if (now - me.titleCheckedAt < TITLE_REFRESH_MS) return
164 me.titleCheckedAt = now
165 const record = await findDesktopRecord($)
166 if (record) {
167 me.title = typeof record.title === 'string' && record.title.trim() !== '' ? record.title.trim() : null
168 me.desktopId = record.sessionId ?? null
169 me.titleSource = record.titleSource ?? null
170 me.fromProject = isProjectSession(record)
171 if (typeof record.lastFocusedAt === 'number') me.lastFocusedAt = record.lastFocusedAt
172 }
173 if (!me.title) me.title = await transcriptTitle($)
174}
175
176/**
177 * Check Desktop's "last focused" time (lastFocusedAt). Measured (2026-10-08): switching to a session writes it to that session's record file within 1 s,
178 * but staying on the same session never updates it again. Re-read only when the file's mtime changed, to avoid reading several hundred KB every 10 s.
179 * Returns whether it changed.
180 */
181async function refreshFocus($) {
182 if (!me.desktopFile) return false
183 try {
184 const stat = await $.fs.stat(me.desktopFile)
185 if (stat.mtimeMs === me.focusFileMtime) return false
186 me.focusFileMtime = stat.mtimeMs
187 const record = await readJson($, me.desktopFile)
188 if (typeof record?.lastFocusedAt === 'number' && record.lastFocusedAt !== me.lastFocusedAt) {
189 me.lastFocusedAt = record.lastFocusedAt
190 return true
191 }
192 } catch {
193 // Unreadable: keep the previous value
194 }
195 return false
196}
197
198/** Current steps of this session: progress-tool data first, otherwise TASKS.md. */
199async function currentSteps($) {
200 const progress = me.id ? await $.store.get(PROGRESS_PREFIX + me.id) : null
201 if (progress && Array.isArray(progress.steps) && progress.steps.length > 0) return { progress, steps: progress.steps, source: 'tool' }
202 // A checklist in the working folder may belong to another session in the same folder, or be a general to-do list:
203 // show it only when this session has written to it
204 const steps = me.ownsChecklist ? await readTaskSteps($, me.cwd) : null
205 return { progress: null, steps: steps ?? [], source: steps ? 'tasks' : null }
206}
207
208// ---------- Shared store ----------
209
210/** Write own summary to the shared store for other sessions' panes. */
211/** Store a full step list for this session (empty clears it) and redraw; makeInput(prev) builds the progress-tool input. */
212async function saveProgress($, makeInput) {
213 const now = await $.clock.now()
214 const prev = await $.store.get(PROGRESS_PREFIX + me.id)
215 const progress = mergeProgress(prev, makeInput(prev), now)
216 if (progress.steps.length === 0) await $.store.delete(PROGRESS_PREFIX + me.id)
217 else await $.store.set(PROGRESS_PREFIX + me.id, progress)
218 await publish($)
219 $.ui.invalidate('ui.render')
220 return progress
221}
222
223async function publish($) {
224 if (!me.id) return // After /clear and before the new id is adopted, do not publish, so no ghost data is written under the old id
225 const now = await $.clock.now()
226 await refreshTitle($, now)
227 const { progress, steps, source } = await currentSteps($)
228 await $.store.set(KEY_PREFIX + me.id, {
229 id: me.id,
230 name: me.title ?? folderName(me.cwd),
231 desktopId: me.desktopId,
232 isWorking: me.isWorking,
233 lastSeen: now,
234 firstSeen: me.firstSeen,
235 workStartedAt: me.workStartedAt,
236 finishedAt: me.finishedAt,
237 lastFocusedAt: me.lastFocusedAt,
238 seenAt: me.seenAt,
239 hasToolSteps: source === 'tool',
240 background: me.background,
241 activity: me.activity ? { startedAt: me.activity.startedAt, current: me.activity.actions[0]?.label ?? null } : null,
242 stats: stepStats(steps),
243 eta: source === 'tool' ? etaText(estimateRemainingMin(progress, now)) : null,
244 stepLabel: currentStepLabel(steps),
245 // Shown under the row when the pointer is on it in other sessions' panes
246 alertNote: steps.find((step) => (step.status === 'bad' || step.status === 'warn') && step.note)?.note ?? null,
247 lastDoneLabel: [...steps].reverse().find((step) => step.status === 'done')?.title ?? null,
248 })
249}
250
251/** Load other sessions (read-only; stale ones are skipped, deletion is left to prune on the heartbeat). */
252async function loadOthers($, now) {
253 const entries = []
254 for (const key of await $.store.keys()) {
255 if (!key.startsWith(KEY_PREFIX)) continue
256 const entry = await $.store.get(key)
257 if (!entry || typeof entry.lastSeen !== 'number' || now - entry.lastSeen > STALE_MS) continue
258 // Old records left behind by this session's own previous ids do not count as "other sessions" either
259 if (entry.id !== me.id && !(me.desktopId && entry.desktopId === me.desktopId)) entries.push(entry)
260 }
261 return liveSessions(entries, now)
262}
263
264/** Names of every other session in the store (stale ones too: a finished session's name still counts as taken). */
265async function otherNames($) {
266 const names = new Set()
267 for (const key of await $.store.keys()) {
268 if (!key.startsWith(KEY_PREFIX)) continue
269 const entry = await $.store.get(key)
270 if (entry?.id !== me.id && !(me.desktopId && entry?.desktopId === me.desktopId) && typeof entry?.name === 'string' && entry.name.trim()) names.add(entry.name.trim())
271 }
272 return [...names]
273}
274
275/** Load hidden records { [id]: { at } }: per-session keys plus the legacy single-object record. */
276async function loadHidden($) {
277 const merged = { ...((await $.store.get(LEGACY_HIDDEN_KEY)) ?? {}) }
278 for (const key of await $.store.keys()) {
279 if (!key.startsWith(HIDDEN_PREFIX)) continue
280 const h = await $.store.get(key)
281 if (h && typeof h.at === 'number') merged[key.slice(HIDDEN_PREFIX.length)] = h
282 }
283 return merged
284}
285
286/** Heartbeat cleanup: delete stale sessions, drop hidden records that are due to be unhidden, and migrate the legacy hidden record to per-session keys. */
287async function prune($, now) {
288 const all = []
289 for (const key of await $.store.keys()) {
290 if (!key.startsWith(KEY_PREFIX)) continue
291 const entry = await $.store.get(key)
292 if (!entry || typeof entry.lastSeen !== 'number' || now - entry.lastSeen > STALE_MS) await $.store.delete(key)
293 else all.push(entry)
294 }
295 const legacy = await $.store.get(LEGACY_HIDDEN_KEY)
296 if (legacy && typeof legacy === 'object') {
297 for (const [id, h] of Object.entries(legacy)) await $.store.set(HIDDEN_PREFIX + id, h)
298 await $.store.delete(LEGACY_HIDDEN_KEY)
299 }
300 const { unhide } = splitHidden(all, await loadHidden($))
301 for (const id of unhide) await $.store.delete(HIDDEN_PREFIX + id)
302}
303
304/** Heartbeat: publish own state, then prune. */
305async function heartbeat($) {
306 await publish($)
307 await prune($, await $.clock.now())
308}
309
310/**
311 * Whether this is the session currently being looked at: its "last focused" time is the newest of all sessions.
312 * Used at the moment work finishes: if the session was watched to completion, the "finished, unread" light should not turn on.
313 */
314async function isFrontSession($, now) {
315 await refreshFocus($)
316 if (typeof me.lastFocusedAt !== 'number') return false
317 for (const s of await loadOthers($, now)) {
318 if (typeof s.lastFocusedAt === 'number' && s.lastFocusedAt > me.lastFocusedAt) return false
319 }
320 return true
321}
322
323/** The turn has really ended (no background work): record the finish time; if the session is in front, also mark it as seen. */
324async function markFinished($) {
325 const now = await $.clock.now()
326 me.finishedAt = now
327 me.seenAt = (await isFrontSession($, now)) ? now : me.seenAt
328}
329
330/** Set working / idle. */
331async function setWorking($, isWorking) {
332 me.isWorking = isWorking
333 if (isWorking) {
334 me.workStartedAt = await $.clock.now()
335 me.activity = { startedAt: me.workStartedAt, actions: [] }
336 me.background = null
337 me.finishedAt = null
338 } else {
339 me.activity = null
340 }
341}
342
343/** Re-register under the new id after /clear, /resume or /branch. */
344async function adoptSessionId($) {
345 me.id = await $.session.id()
346 me.cwd = await $.session.cwd()
347 me.isWorking = false
348 me.activity = null
349 me.background = null
350 me.finishedAt = null
351 me.seenAt = null
352 me.ownsChecklist = false
353 me.firstSeen = await $.clock.now()
354 me.titleCheckedAt = 0
355 me.desktopFile = null
356 me.focusFileMtime = 0
357}
358
359/**
360 * Auto-naming: after turn RENAME_AFTER_TURNS, pick a name of at most TITLE_MAX units from the conversation, exactly once (the marker is written before the call, so a failure is not retried).
361 * How: prefer Desktop's official rename tool (the app code confirms the title source is recorded as "tool"); if it cannot be called, wait for the next submitted prompt and
362 * set it via UserPromptSubmit's sessionTitle (works for terminal sessions; whether Desktop honours it is unverified). A manually renamed session (titleSource = user) is left alone; a session started by the project system gets "-<project>" appended.
363 */
364async function maybeRename($) {
365 if (!AUTO_RENAME || !me.id) return
366 if (await $.store.get(RENAMED_PREFIX + me.id)) return
367 if ((await $.session.turns()) < RENAME_AFTER_TURNS) return
368 await $.store.set(RENAMED_PREFIX + me.id, { at: await $.clock.now() })
369 me.titleCheckedAt = 0
370 await refreshTitle($, await $.clock.now())
371 if (me.titleSource === 'user') return
372 const convo = conversationDigest(await $.session.messages()) // Uses the whole session, not just the last few messages
373 const taken = await otherNames($)
374 let title = ''
375 try {
376 const task = t('renameTask') + (taken.length ? t('existingNames', taken) : '')
377 title = await askShortName($, task, convo, TITLE_MAX + (taken.length ? SUFFIX_MAX : 0))
378 // Same name as another session: ask once for a "-purpose" suffix so the two can be told apart
379 if (title && taken.includes(title)) title = (await askShortName($, t('duplicateName', title), convo, TITLE_MAX + SUFFIX_MAX)) || title
380 } catch {
381 return
382 }
383 if (!title) return
384 // The project page's own name lives in the cloud and cannot be read, so a project session is named from its content plus which project it belongs to
385 if (me.fromProject) {
386 const tag = projectTag(me.cwd, PROJECT_TAG_CHARS)
387 if (tag && !title.endsWith('-' + tag)) title = title + '-' + tag
388 }
389 try {
390 // A missing tool throws; a rejection (e.g. permissions) returns deny / isError. Both count as failure and take the fallback
391 const res = await $.tool.call({ tool: RENAME_TOOL, session_id: 'self', title })
392 if (res?.deny || res?.isError) throw new Error(String(res.deny ?? res.result ?? 'rejected'))
393 $.ui.log('session-dashboard: renamed to "' + title + '" (Desktop rename tool)', { to: 'debug' })
394 } catch (err) {
395 me.pendingTitle = title
396 $.ui.log('session-dashboard: Desktop rename tool failed (' + String(err) + '), falling back to sessionTitle', { to: 'debug' })
397 }
398 me.title = title
399 await publish($)
400}
401
402/**
403 * Ask the small model for a complete name of at most max units (an English word counts as 1 unit). An over-long name is not truncated; the model is asked once more;
404 * if the retry is still too long, the shorter of the two complete names is used.
405 */
406async function askShortName($, task, prompt, max) {
407 const rule = t('nameRule', max)
408 const ask = async (system, text) => {
409 const reply = await $.model.complete({ model: RENAME_MODEL, maxTokens: 40, system, prompt: text })
410 return reply?.isAnswered ? cleanTitle(reply.text) : ''
411 }
412 const first = await ask(task + rule, prompt)
413 if (!first || nameUnits(first) <= max) return first
414 const second = await ask(t('shortenTask') + rule, t('tooLong', first, nameUnits(first)))
415 return second && nameUnits(second) < nameUnits(first) ? second : first
416}
417
418/** Condense the submitted prompt to at most TASK_LABEL_MAX units, shown in the pane as "what it is doing"; on failure the label stays "working". */
419async function summarizeTask($, prompt) {
420 try {
421 const label = await askShortName($, t('summaryTask'), prompt.slice(0, 1000), TASK_LABEL_MAX)
422 if (label) {
423 me.taskLabel = label
424 $.ui.invalidate('ui.render')
425 }
426 } catch {}
427}
428
429// ---------- Actions ----------
430
431/** Open the pane; asked=true means it was requested explicitly (command or button) and takes keyboard focus. A failed open only shows a toast and never aborts the hook. */
432async function openPane($, asked) {
433 const pane = { id: PANE_ID, title: 'Sessions' }
434 try {
435 const opened = await $.ui.open(asked ? { ...pane, focus: true } : pane)
436 // When the mod opens the pane itself and there is no room, the pane is queued; hint once how to open it manually
437 if (!asked && opened && opened.isPlaced === false && !me.queuedHinted) {
438 me.queuedHinted = true
439 $.ui.toast(t('queuedHint'), { timeoutMs: 8000 })
440 }
441 } catch (err) {
442 if (asked) $.ui.toast(t('paneOpenFailed', String(err)))
443 }
444}
445
446/** Jump to another Desktop session via the Desktop app's own claude:// link, which Windows hands to the app. */
447async function jumpTo($, url, name) {
448 try {
449 await $.process.run(['rundll32.exe', 'url.dll,FileProtocolHandler', url])
450 } catch (err) {
451 $.ui.toast(t('jumpFailed', name, String(err)))
452 }
453}
454
455/** Hide another session (takes effect in every pane) without touching the session itself. One key per session, so sessions cannot overwrite each other. */
456async function hideProject($, id) {
457 await $.store.set(HIDDEN_PREFIX + id, { at: await $.clock.now() })
458 $.ui.invalidate('ui.render')
459}
460
461
462/**
463 * Usage reading (read-only): rateLimits only exists after this session receives its first reply (official typing: "empty … before the first reading").
464 * The quota is account-wide; with no reading of its own, a session uses the latest one in the shared store (saved on session.measure), dropping entries past their reset time.
465 * Returns { list, at, own }.
466 */
467async function readRateLimits($, now) {
468 const { rateLimits } = await $.session.usage()
469 if (Array.isArray(rateLimits) && rateLimits.length > 0) return { list: rateLimits, at: now, own: true }
470 const cached = await $.store.get(USAGE_KEY)
471 const list = Array.isArray(cached?.rateLimits) ? cached.rateLimits : []
472 return { list: list.filter((r) => !r.resetsAt || new Date(r.resetsAt).getTime() > now), at: cached?.at ?? now, own: false }
473}
474
475// ---------- Rendering (read-only) ----------
476
477/** Wrap the Svg in a keyed Box (Svg itself takes no key) so tests and redraws can identify it. */
478function svgBox(els, key, source, alt, size) {
479 const { Box, Svg } = els
480 // With a size the drawing keeps it: without one it is scaled down to whatever width its slot is squeezed to
481 return size
482 ? Box({ key, flexShrink: 0, children: [Svg({ source, alt, width: size.width, height: size.height })] })
483 : Box({ key, children: [Svg({ source, alt })] })
484}
485
486/**
487 * One timeline segment: a dot with connector lines above and below on the left (Svg on Desktop, characters and "│" in the terminal), a title plus one note line on the right.
488 * Every segment is exactly ROWS.step rows tall, so the lines of adjacent segments meet.
489 */
490function timelineRow(els, isDesktop, item, i, columns) {
491 const { Box, Text } = els
492 const step = item.step
493 const title = step ? step.title : item.text
494 const note = step ? (item.kind === 'running' ? (step.note ?? t('inProgress')) : step.note) : undefined
495 const noteColor = item.kind === 'bad' ? 'red' : item.kind === 'warn' ? 'yellow' : undefined
496 const isMeta = !step // "N steps done" / "N more steps"
497 let marker
498 if (isDesktop && els.Svg) {
499 // The node is as tall as the text beside it, so the connector still reaches the next node when a title wraps
500 // Estimate the text's lines on the narrow side: a node taller than its text only adds space, one shorter leaves a gap in the line
501 const cells = Math.max(8, (columns ?? 40) - STEP_RESERVED_CELLS - NODE_WRAP_MARGIN)
502 const lines = wrapByWidth(title, cells).length + (note ? wrapByWidth(note, cells).length : 0)
503 const height = nodeHeight(lines)
504 marker = svgBox(els, 'node-' + i, svgTimelineNode(item.kind, item.label, item.top, item.bottom, height), title, { width: 28, height })
505 } else {
506 const icon = { done: '✓', collapsed: '✓', running: '●', warn: '!', bad: '!', todo: '○', more: '┆' }[item.kind] ?? '○'
507 const color = { done: 'green', collapsed: 'green', running: 'cyan', warn: 'yellow', bad: 'red' }[item.kind]
508 marker = Box({ flexDirection: 'column', children: [
509 Text({ color, dimColor: !color, children: [icon] }),
510 Text({ dimColor: true, children: [item.bottom ? '│' : ' '] }),
511 ] })
512 }
513 const text = [Text({
514 bold: item.kind === 'running',
515 color: isMeta && item.kind === 'collapsed' ? 'green' : undefined,
516 dimColor: item.kind === 'todo' || item.kind === 'more',
517 wrap: 'wrap',
518 children: [title],
519 })]
520 if (note) text.push(Text({ key: 'note-' + i, color: noteColor, dimColor: !noteColor, wrap: 'wrap', children: [note] }))
521 return Box({ key: 'step-' + i, flexDirection: 'row', columnGap: 1, alignItems: 'center', children: [marker, Box({ flexDirection: 'column', flexGrow: 1, flexShrink: 1, children: text })] })
522}
523
524/** With no reported steps, show a single line: task summary (the prompt condensed by AI) · elapsed time; no file names or tool actions. */
525function activityRow(els, activity, now) {
526 const elapsed = Math.floor(Math.max(0, now - activity.startedAt) / 60000)
527 return els.Text({ key: 'activity', color: 'cyan', wrap: 'wrap', children: [(me.taskLabel ?? t('working')) + ' · ' + elapsed + 'm'] })
528}
529
530/** Background work is also a single line: the turn ended, but background commands or subagents are still running. */
531function backgroundRow(els) {
532 return els.Text({ key: 'background', color: 'cyan', wrap: 'wrap', children: [(me.taskLabel ?? t('working')) + ' · ' + t('background')] })
533}
534
535/** Current-session block: bold name (remaining time on the right) plus the latest 5 steps. maxRows is the number of rows available to this block. */
536async function currentSection($, els, isDesktop, now, maxRows, columns) {
537 const { Box, Text } = els
538 const { progress, steps, source } = await currentSteps($)
539 const title = me.title ?? folderName(me.cwd)
540 const eta = steps.length === 0 ? '' : source === 'tool' ? etaText(estimateRemainingMin(progress, now)) : t('fromChecklist')
541 const rows = [
542 Box({
543 flexDirection: 'row', justifyContent: 'space-between', columnGap: 1,
544 children: [Text({ bold: true, wrap: 'wrap', children: [title] }), Text({ dimColor: true, children: [eta] })],
545 }),
546 ]
547 if (progress?.task && maxRows >= 6) rows.push(Text({ dimColor: true, wrap: 'wrap', children: [progress.task] }))
548 if (showActivity(me.activity, source === 'tool', now)) rows.push(activityRow(els, me.activity, now))
549 else if (me.background && source !== 'tool') rows.push(backgroundRow(els))
550 else if (steps.length === 0) rows.push(Text({ dimColor: true, children: [t('noSteps')] }))
551 // Timeline: "N steps done" → latest 5 steps → "N more steps", all joined into one line
552 const fit = fitSteps(steps, Math.max(0, maxRows - rows.length))
553 timelineItems(fit).forEach((item, i) => rows.push(timelineRow(els, isDesktop, item, i, columns)))
554 return rows
555}
556
557/** Section divider: a thick solid line with "other sessions" embedded in the middle (Svg on Desktop, ━ in the terminal). */
558function sectionDivider(els, isDesktop, columns) {
559 if (isDesktop && els.Svg) return svgBox(els, 'section-divider', svgSectionDivider(t('othersTitle')), t('othersTitle'))
560 const side = '━'.repeat(Math.max(2, Math.floor(((columns ?? 40) - t('othersTitle').length - 4) / 2)))
561 return els.Text({ key: 'section-divider', dimColor: true, wrap: 'truncate-end', children: [side + ' ' + t('othersTitle') + ' ' + side] })
562}
563
564/** How many cells fit on one line of an other-session name. */
565const nameCells = (columns) => Math.max(8, (columns ?? 40) - NAME_RESERVED_CELLS)
566
567/**
568 * One row per other session (always 2 lines):
569 * Line 1: ⊘ + light + name (click to jump) + time on the right; line 2 (Desktop): progress bar + faint divider. While working, only the bar is drawn, with no text.
570 */
571function otherRow($, els, isDesktop, s, now, columns) {
572 const { Box, Button, Text } = els
573 const stats = s.stats ?? { done: 0, total: 0, pct: 0 }
574 const pct = stats.total > 0 ? stats.pct : null
575 const status = statusOf(s)
576 const url = jumpUrl(s.desktopId)
577 const hide = Button({ key: 'hide-' + s.id, label: '✕', plain: true, dimColor: true, onPress: () => hideProject($, s.id) })
578 if (isDesktop && els.Client && url && useClientRows($, now)) return clientRow(els, s, now, status, pct, url, hide)
579 // Severe problems use a red triangle icon (⚠ in the terminal); other statuses use a light dot
580 const dot = status === 'bad'
581 ? (isDesktop && els.Svg ? svgBox(els, 'alert-' + s.id, svgAlertIcon(), t('severeAlt')) : Text({ key: 'light-' + s.id, color: 'red', children: ['⚠'] }))
582 : Text({ key: 'light-' + s.id, color: LIGHT[status], children: [status === 'idle' ? '○' : '●'] })
583 // Long names wrap: button labels do not wrap by themselves, so the name is split into stacked buttons and every line stays clickable
584 const nameLines = wrapByWidth(s.name, nameCells(columns))
585 const name = !url
586 ? Text({ key: 'other-' + s.id, bold: true, wrap: 'wrap', children: [s.name] })
587 : Box({ flexDirection: 'column', flexShrink: 1, children: nameLines.map((line, n) =>
588 Button({ key: 'jump-' + s.id + (n === 0 ? '' : '-' + n), label: line, plain: true, onPress: () => jumpTo($, url, s.name) })) })
589 const line1 = Box({
590 flexDirection: 'row', justifyContent: 'space-between', columnGap: 1,
591 children: [
592 Box({ flexDirection: 'row', columnGap: 1, flexShrink: 1, alignItems: 'flex-start', children: [hide, dot, name] }),
593 // The time column keeps its width and stays on one line; the name is what wraps
594 Box({ flexShrink: 0, children: [timeLabel(els, s, url, [pct === null ? '' : pct + '%', rightTime(s, now)].filter(Boolean).join(' · '), () => jumpTo($, url, s.name))] }),
595 ],
596 })
597 // The progress bar extends almost to the right edge (same width as the usage bars); the terminal uses a text bar sized to the pane width
598 const line2 = isDesktop && els.Svg
599 ? svgBox(els, 'line2-' + s.id, svgOtherLine(pct), pct === null ? s.name : s.name + ' ' + pct + '%')
600 : Text({ key: 'line2-' + s.id, color: 'cyan', children: [pct === null ? ' ' : thinBar(pct, Math.max(8, (columns ?? 40) - 4))] })
601 const info = hoverInfo(s)
602 const infoText = info ? t(info.kind === 'stuck' ? 'hoverStuck' : info.kind === 'doing' ? 'hoverDoing' : 'hoverDone', info.text) : null
603 // Drawn hidden and revealed while the pointer is anywhere on this session's block (the keyed row Box is the hover scope; this Box has no key, or it would be its own scope)
604 const hoverLine = infoText ? Box({ display: 'none', hover: { display: 'flex' }, children: [Text({ dimColor: true, wrap: 'wrap', children: [infoText] })] }) : null
605 // The keyed outer Box is the hover scope (pointer anywhere on this session); the inner Box fills it and takes the background
606 return Box({ key: 'proj-' + s.id, flexDirection: 'column', children: [
607 Box({ flexDirection: 'column', hover: { backgroundColor: HOVER_BG }, children: [line1, line2, hoverLine].filter(Boolean) }),
608 ] })
609}
610
611/** Desktop: the whole block (name, bar, time) is one Client region (hooks/row.js), so a click anywhere on it jumps and the hover background is one piece. ✕ stays outside so untracking never jumps. */
612function clientRow(els, s, now, status, pct, url, hide) {
613 const { Box, Client } = els
614 rowTargets.set(s.id, { url, name: s.name })
615 return Box({ key: 'proj-' + s.id, flexDirection: 'row', columnGap: 1, alignItems: 'flex-start', children: [
616 hide,
617 // The region takes the room left beside ✕ and never more: sized by its content it pushed the whole pane wider than the window
618 Box({ flexGrow: 1, flexShrink: 1, minWidth: 0, overflow: 'hidden', children: [Client({ key: 'jump-' + s.id, module: './row.js', width: '100%', props: {
619 name: s.name,
620 glyph: status === 'bad' ? '▲' : status === 'idle' ? '○' : '●',
621 light: LIGHT[status],
622 right: [pct === null ? '' : pct + '%', rightTime(s, now)].filter(Boolean).join(' · '),
623 pct,
624 barColor: COLORS.running,
625 track: COLORS.track,
626 hoverBg: HOVER_BG,
627 jumpingLabel: t('jumping'),
628 } })] }),
629 ] })
630}
631
632/** Whether the Client regions work in this pane; module state, reset on each load. */
633const clientProbe = { supported: true, ready: false, failed: false, firstDrawAt: null }
634
635function useClientRows($, now) {
636 if (!clientRowMode(clientProbe, now, CLIENT_GRACE_MS)) return false
637 if (clientProbe.firstDrawAt === null && !clientProbe.ready) {
638 clientProbe.firstDrawAt = now
639 // Draw again once the grace is over, so a region that never started is replaced by plain rows without waiting for other changes
640 $.clock.after(CLIENT_GRACE_MS + 100, () => { if (!clientProbe.ready) $.ui.invalidate('ui.render') })
641 }
642 return true
643}
644
645/** Where each drawn block jumps to, filled while drawing; a click only sends the block's key, so the link never comes from the click itself. */
646const rowTargets = new Map()
647
648/** A click on a session block (hooks/row.js): log it, then jump. */
649async function onRowMessage($, e) {
650 const id = String(e.element).replace(/^jump-/, '')
651 const target = rowTargets.get(id)
652 if (!target || !e.data || e.data.jump !== true) return
653 try {
654 const log = (await $.store.get(CLICK_LOG_KEY)) ?? []
655 await $.store.set(CLICK_LOG_KEY, [...log, { at: await $.clock.now(), id, name: target.name }].slice(-CLICK_LOG_MAX))
656 } catch {}
657 await jumpTo($, target.url, target.name)
658}
659
660/** The time on the right of a row: a button too when the session can be jumped to, so the whole row is clickable. */
661function timeLabel(els, s, url, text, onPress) {
662 if (!url || !text) return els.Text({ dimColor: true, wrap: 'truncate-end', children: [text] })
663 return els.Button({ key: 'jump-' + s.id + '-time', label: text, plain: true, dimColor: true, onPress })
664}
665
666/** Group header above sessions that share a name before "-". */
667function groupHeader(els, item) {
668 return els.Box({ key: 'group-' + item.key, children: [els.Text({ dimColor: true, wrap: 'truncate-end', children: ['▾ ' + t('groupLabel', item.name, item.count)] })] })
669}
670
671/**
672 * Usage (pinned to the bottom of the pane): Session limit / Weekly limit, "used% · resets in 2h", 4px bar; a stale reading from another session is labelled with its reading time.
673 * compact = when the pane is very short, each limit takes 1 line (text only, colour shows the level) so there is still room above.
674 */
675async function usageSection($, els, isDesktop, now, compact = false) {
676 const { Box, Text } = els
677 const reading = await readRateLimits($, now)
678 const segments = usageSegments(reading.list, now)
679 if (segments.length === 0) return [Text({ dimColor: true, children: [t('usageEmpty')] })]
680 const staleTag = !reading.own && now - reading.at > USAGE_STALE_MS ? ' · read ' + ago(reading.at, now) : ''
681 return segments.map((seg, i) => {
682 const fill = limitColor(seg.pct)
683 const termColor = fill === COLORS.bad ? 'red' : fill === COLORS.warn ? 'yellow' : 'cyan'
684 if (compact) {
685 return Box({ key: 'limit-compact-' + seg.label, flexDirection: 'row', justifyContent: 'space-between', children: [
686 Text({ children: [seg.label] }),
687 Text({ color: isDesktop ? fill : termColor, children: [seg.pct + '%' + (seg.reset ? ' · ' + seg.reset : '') + (i === 0 ? staleTag : '')] }),
688 ] })
689 }
690 return Box({
691 key: 'limit-' + seg.label, flexDirection: 'column',
692 children: [
693 Box({ flexDirection: 'row', justifyContent: 'space-between', children: [
694 Text({ children: [seg.label] }),
695 Text({ dimColor: true, children: [seg.pct + '%' + (seg.reset ? ' · ' + seg.reset : '') + (i === 0 ? staleTag : '')] }),
696 ] }),
697 isDesktop && els.Svg
698 ? svgBox(els, 'limit-bar-' + seg.label, svgThinBar(seg.pct, fill), seg.label + ' ' + seg.pct + '%')
699 : Text({ color: termColor, children: [thinBar(seg.pct)] }),
700 ],
701 })
702 })
703}
704
705// ---------- Events ----------
706
707const toolSpec = () => ({
708 name: 'progress',
709 description: t('toolDescription'),
710 inputSchema: {
711 type: 'object',
712 properties: {
713 task: { type: 'string', description: t('toolTask') },
714 steps: {
715 type: 'array',
716 maxItems: 5,
717 description: t('toolSteps'),
718 items: {
719 type: 'object',
720 properties: {
721 title: { type: 'string', description: t('toolStepTitle') },
722 status: { type: 'string', enum: ['done', 'running', 'warn', 'bad', 'todo'] },
723 note: { type: 'string', description: t('toolStepNote') },
724 },
725 required: ['title', 'status'],
726 },
727 },
728 },
729 required: ['steps'],
730 },
731})
732
733export function register(on) {
734 // Open the pane first and push slow work such as the name lookup to the background (looking up the name first blocked session.start for about 1 s)
735 on('session.start', async ($, e, next) => {
736 // UI language: env var SESSION_DASHBOARD_LANG (default English; zh-TW for Traditional Chinese). The name must be a literal.
737 setLang(await $.env.get('SESSION_DASHBOARD_LANG').catch(() => undefined))
738 me.id = await $.session.id()
739 me.cwd = await $.session.cwd()
740 me.isWorking = false
741 me.titleCheckedAt = 0
742 me.firstSeen = me.firstSeen ?? (await $.clock.now())
743 me.ownsChecklist = !!(await $.store.get(OWNS_PREFIX + me.id))
744 if (AUTO_OPEN) await openPane($, false)
745 me.timers = [
746 // Registering the tool waits until it is actually usable (measured at about 0.9 s), so it also runs in the background and does not block session start
747 $.clock.after(0, async () => {
748 await $.command.register({ name: 'dashboard', description: t('commandDescription'), immediate: true })
749 await $.tool.register(toolSpec())
750 }),
751 $.clock.after(0, () => heartbeat($)),
752 $.clock.every(HEARTBEAT_MS, () => heartbeat($)),
753 $.clock.after(0, () => redrawIfChanged($)),
754 $.clock.every(CHANGE_CHECK_MS, () => redrawIfChanged($)),
755 $.clock.every(TIME_REDRAW_MS, () => $.ui.invalidate('ui.render')),
756 $.clock.every(FOCUS_REFRESH_MS, async () => {
757 if (await refreshFocus($)) await publish($)
758 }),
759 ]
760 return next(e)
761 })
762
763 // The Desktop view attaches later than session.start, and a pane opened before that is not shown, so open it again on attach
764 on('session.attach', async ($, e, next) => {
765 const result = await next(e)
766 if (AUTO_OPEN) await openPane($, false)
767 return result
768 })
769
770 // After /clear, /resume or /branch (session.start does not fire again): re-register under the new id
771 on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
772 const result = await next(e)
773 await adoptSessionId($)
774 await heartbeat($)
775 $.ui.invalidate('ui.render')
776 return result
777 })
778
779 // Record every tool action (except the progress tool itself); observe only, never block; write to the store at most once per ACTIVITY_PUBLISH_MS
780 on('tool.call', async ($, e, next) => {
781 if (!me.ownsChecklist && touchesChecklist(e)) {
782 me.ownsChecklist = true
783 if (me.id) await $.store.set(OWNS_PREFIX + me.id, { at: await $.clock.now() })
784 $.ui.invalidate('ui.render')
785 }
786 if (me.activity && e.tool !== PROGRESS_TOOL) {
787 const now = await $.clock.now()
788 me.activity = { ...me.activity, actions: pushAction(me.activity.actions, actionLabel(e), now) }
789 if (now - me.activityPublishedAt >= ACTIVITY_PUBLISH_MS) {
790 me.activityPublishedAt = now
791 await publish($)
792 }
793 $.ui.invalidate('ui.render')
794 }
795 return next(e)
796 })
797
798 // Claude reports step progress
799 on('tool.call', { tool: PROGRESS_TOOL }, async ($, e) => {
800 const progress = await saveProgress($, () => ({ task: e.task, steps: e.steps }))
801 const stats = stepStats(progress.steps)
802 return { result: progress.steps.length === 0 ? t('progressCleared') : t('progressUpdated', stats.done, stats.total) }
803 })
804
805 // The built-in todo list is mirrored into the pane on every update; only the warn/bad marks still come from the progress tool
806 on('tool.call', { tool: TODO_TOOL }, async ($, e, next) => {
807 // Mirroring is best effort: a store failure must never block the todo tool itself
808 if (me.id && Array.isArray(e.todos)) { try { await saveProgress($, (prev) => todosToInput(e.todos, prev?.steps)) } catch {} }
809 return next(e)
810 })
811
812 // Read the background task list when a turn ends: Claude ends the turn after pushing work to the background, which must not count as idle (official docs: tell "done" apart from "waiting on background work")
813 on('classic.Stop', async ($, e, next) => {
814 me.background = summarizeBackground(e.background_tasks)
815 if (me.background) me.finishedAt = null
816 else if (!me.isWorking && me.finishedAt === null) await markFinished($)
817 await publish($)
818 $.ui.invalidate('ui.render')
819 return next(e)
820 })
821
822 on('turn.start', async ($, e, next) => {
823 await setWorking($, true)
824 await publish($)
825 $.ui.invalidate('ui.render')
826 return next(e)
827 })
828
829 on('turn.complete', async ($, e, next) => {
830 await setWorking($, false)
831 if (!me.background) await markFinished($)
832 await publish($)
833 $.ui.invalidate('ui.render')
834 $.clock.after(0, () => maybeRename($)) // Runs in the background so it does not delay the end of the turn
835 return next(e)
836 })
837
838 // Fallback when the rename tool cannot be called: attach sessionTitle on the next submitted prompt
839 on('classic.UserPromptSubmit', async ($, e, next) => {
840 const result = await next(e)
841 me.taskLabel = null
842 if (typeof e.prompt === 'string' && e.prompt.trim() !== '') $.clock.after(0, () => summarizeTask($, e.prompt))
843 if (!me.pendingTitle) return result
844 const sessionTitle = me.pendingTitle
845 me.pendingTitle = null
846 return { ...result, sessionTitle }
847 })
848
849 // When usage changes, save a copy for new sessions that have no reading yet (account-wide)
850 on('session.measure', async ($, e, next) => {
851 if (Array.isArray(e.rateLimits) && e.rateLimits.length > 0) {
852 await $.store.set(USAGE_KEY, { rateLimits: e.rateLimits, at: await $.clock.now() })
853 }
854 // No immediate redraw: usage is refreshed together with the per-minute redraw (by design)
855 return next(e)
856 })
857
858 // End: delete own data. On /clear and /resume the process keeps running, so stop publishing under the old id and wait for classic.SessionStart to adopt the new one;
859 // on a real exit, cancel the timers
860 on('session.end', async ($, e, next) => {
861 if (me.id) {
862 await $.store.delete(KEY_PREFIX + me.id)
863 await $.store.delete(PROGRESS_PREFIX + me.id)
864 await $.store.delete(OWNS_PREFIX + me.id)
865 }
866 me.id = ''
867 if (e.reason !== 'clear' && e.reason !== 'resume') {
868 for (const t of me.timers) t?.cancel?.()
869 me.timers = []
870 }
871 return next(e)
872 })
873
874 // A block whose region failed (did not load, stopped answering): the engine would draw its long error line in its place; draw plain rows instead for the rest of this session
875 on('ui.fault', async ($, e, next) => {
876 if (String(e.module ?? '').endsWith('row.js')) {
877 clientProbe.failed = true
878 $.ui.invalidate('ui.render')
879 }
880 return next(e)
881 })
882
883 on('ui.message', async ($, e, next) => {
884 if (e.module !== './row.js' && !String(e.module).endsWith('row.js')) return next(e)
885 if (e.data && e.data.ready === true) { clientProbe.ready = true; return {} }
886 await onRowMessage($, e)
887 return {}
888 })
889
890 // The terminal uses /dashboard; Desktop's / menu does not list mod commands, so the button above the prompt is used instead
891 on('command.run', { command: 'dashboard' }, async ($) => {
892 await openPane($, true)
893 return {}
894 })
895
896 // Above the prompt: only the open-pane button; whatever later mods (e.g. next-steps) render goes below it
897 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
898 if (e.props.hasSurvey) return next(e)
899 const below = await next(e)
900 const { Box, Button } = $.ui.resolve(e)
901 // The button is an explicit action, so the pane opens at any width and on Desktop
902 const open = Button({ key: 'open-sessions', label: PANE_BUTTON_LABEL, plain: true, dimColor: true, onPress: () => openPane($, true) })
903 const button = open // An untracked session comes back when the user opens it, so no "show hidden" button is needed
904 return below ? Box({ flexDirection: 'column', children: [button, below] }) : button
905 })
906
907 // Sessions pane (single page): compute available rows → usage (pinned to the bottom) → other sessions get their guaranteed rows → the rest goes to the current session's latest 5 steps
908 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
909 if (e.requestId !== PANE_ID) return next(e)
910 const els = $.ui.resolve(e)
911 rowTargets.clear() // only the blocks drawn this time can be clicked
912 const { Box, Text } = els
913 const isDesktop = e.surface !== 'terminal'
914 const now = await $.clock.now()
915 const budget = e.props.scroll?.bodyRows || FALLBACK_BUDGET
916 let usageList = await usageSection($, els, isDesktop, now)
917 const usageCount = usageList.length === 1 && usageList[0].type === 'Text' ? 0 : usageList.length
918 // When the pane is very short (after the full usage block, not even name + 1 step fits), switch to compact usage: 1 line per limit
919 const compact = usageCount > 0 && budget - usageRows(usageCount) - 1 < 1 + ROWS.step
920 if (compact) usageList = await usageSection($, els, isDesktop, now, true)
921 const usageUsed = compact ? usageCount : usageRows(usageCount)
922 const contentRows = Math.max(1, budget - usageUsed - 1)
923 const { visible: unsorted } = splitHidden(await loadOthers($, now), await loadHidden($))
924 const visible = sortByUrgency(unsorted)
925 const items = groupSessions(visible)
926 const headerRows = items.filter((item) => item.type === 'header').length
927 // All other sessions are listed (no limit, by design); the current session keeps at least name + 1 step, and the pane becomes scrollable if that does not fit
928 const currentMin = 1 + ROWS.step
929 const shown = visible.length
930 const wrapExtra = visible.reduce((n, s) => n + wrapByWidth(s.name, nameCells(e.props.bodyColumns)).length - 1, 0)
931 const othersNeed = othersRows(shown, shown) + wrapExtra + headerRows
932 const overflow = contentRows - othersNeed < currentMin
933 // SECTION_GAP blank lines between the current session and "other sessions"; this gap shrinks first when space is tight
934 const gap = shown > 0 ? Math.max(0, Math.min(SECTION_GAP, contentRows - othersNeed - currentMin)) : 0
935 const current = await currentSection($, els, isDesktop, now, overflow ? currentMin : contentRows - othersNeed - gap, e.props.bodyColumns)
936 const children = [Box({ flexDirection: 'column', children: current })]
937 if (shown > 0) {
938 for (let g = 0; g < gap; g++) children.push(Text({ key: 'section-gap-' + g, children: [' '] }))
939 const rows = []
940 let first = true
941 for (const item of items) {
942 if (item.type === 'header') {
943 rows.push(groupHeader(els, item))
944 first = true // no divider right under a header
945 continue
946 }
947 const s = item.s
948 // 1 blank line between sessions, with a faint thin line drawn inside it
949 if (!first) rows.push(isDesktop && els.Svg ? svgBox(els, 'gap-' + s.id, svgSessionGap(), '') : Text({ key: 'gap-' + s.id, children: [' '] }))
950 first = false
951 rows.push(otherRow($, els, isDesktop, s, now, e.props.bodyColumns))
952 }
953 children.push(sectionDivider(els, isDesktop, e.props.bodyColumns), Box({ flexDirection: 'column', children: rows }))
954 }
955 // When it does not fit, do not fix the height or clip; let the pane show its own scrollbar
956 const content = overflow
957 ? Box({ key: 'content', flexDirection: 'column', flexShrink: 0, children })
958 : Box({ key: 'content', flexDirection: 'column', flexGrow: 1, flexShrink: 1, children })
959 const usage = Box({ key: 'usage', flexDirection: 'column', flexShrink: 0, rowGap: compact ? 0 : 1, children: usageList })
960 // Fill the available height with usage at the bottom; overflow:hidden is only a last resort, the content never exceeds it anyway
961 return overflow
962 ? Box({ flexDirection: 'column', rowGap: 1, children: [content, usage] })
963 : Box({ flexDirection: 'column', rowGap: 1, height: budget, children: [content, usage] })
964 })
965}
966hooks/i18n.js 130 lines1// UI strings. English is the default; set the env var SESSION_DASHBOARD_LANG=zh-TW
2// (for example in the "env" block of ~/.claude/settings.json) for Traditional Chinese.
3// To add a language, add a block below with the same keys.
4
5export const DEFAULT_LANG = 'en'
6
7export const STRINGS = {
8 en: {
9 othersTitle: 'Other sessions',
10 queuedHint: 'Not enough room for the pane. Press ☰ Sessions above the prompt to open it',
11 paneOpenFailed: (err) => 'Could not open the Sessions pane: ' + err,
12 jumpFailed: (name, err) => 'Could not jump to "' + name + '": ' + err,
13 working: 'Working',
14 background: 'background',
15 inProgress: 'In progress…',
16 noSteps: 'No steps in progress',
17 fromChecklist: 'from checklist',
18 usageEmpty: 'Usage: no data yet',
19 severeAlt: 'Severe problem',
20 hoverStuck: (text) => 'Needs you: ' + text,
21 hoverDoing: (text) => 'Doing: ' + text,
22 hoverDone: (text) => 'Done: ' + text,
23 jumping: '↗ Switching…',
24 groupLabel: (name, n) => name + ' (' + n + ')',
25 doneCollapsed: (n) => n + ' done',
26 moreSteps: (n) => n + ' more',
27 commandDescription: 'Open the Sessions pane',
28 progressCleared: 'Cleared the steps on the pane',
29 progressUpdated: (done, total) => 'Pane updated: ' + done + '/' + total + ' done',
30 actEdit: (file) => 'Edit ' + file,
31 actRead: (file) => 'Read ' + file,
32 actRun: (d) => (d ? 'Run: ' + d : 'Run a command'),
33 actSearch: 'Search the code',
34 actWeb: 'Look something up online',
35 actAgent: (d) => (d ? 'Subagent: ' + d : 'Start a subagent'),
36 actTool: (tool) => 'Use ' + tool,
37 bgShell: 'Background command',
38 bgSubagent: 'Subagent',
39 bgMonitor: 'Monitor',
40 bgWorkflow: 'Workflow',
41 bgOther: 'Background work',
42 digestUser: 'User: ',
43 digestClaude: 'Claude: ',
44 renameTask: 'Name this conversation after the thing being worked on, in the language the user writes in: only the noun that best represents it (e.g. "Login page", "API docs"), no verbs and no adjectives',
45 existingNames: (names) => '\nOther sessions are named: ' + names.join(', ') + '. If this conversation is about the same thing as one of them (e.g. split off from it), name it "<that name>-<purpose>", the purpose also a noun only, e.g. "Admin site-login".',
46 duplicateName: (name) => 'The name "' + name + '" is already used by another session. Reply with "' + name + '-<purpose>" instead, the purpose a noun only.',
47 summaryTask: 'Condense the user request into a short phrase that says what to do, in the language the user writes in',
48 nameRule: (max) => '. At most ' + max + ' words (one English word counts as 1, one CJK character counts as 1). It must be a complete phrase, never cut off mid-way, and as short as possible. Reply with the name only: no quotes, no punctuation, no explanation.',
49 shortenTask: 'Rewrite this name to be shorter',
50 tooLong: (name, units) => 'The name "' + name + '" is ' + units + ' words, which is too long.',
51 toolDescription:
52 'Report the step-by-step progress of the current task to the Sessions pane. Call it when a multi-step task starts, when a step finishes, when you are blocked, and when the task is done; pass the full step list every time. ' +
53 'Split a task into at most 5 steps and keep each title to a few words (for example "Rework usage bar"), with no detail; a note is one sentence. ' +
54 'status: done, running, warn (a problem the user must handle), bad (a severe problem that may stop the work), todo. For warn and bad, the note says in one sentence what the user needs to do. ' +
55 'Passing an empty steps list clears the pane.',
56 toolTask: 'One-line name for the whole task (optional, a few words)',
57 toolSteps: 'At most 5 steps',
58 toolStepTitle: 'Step name, a few words',
59 toolStepNote: 'For warn/bad: one sentence on the problem and what the user needs to do',
60 },
61 'zh-TW': {
62 othersTitle: '其他 session',
63 queuedHint: '面板空間不夠,點輸入框上方的 ☰ Sessions 打開',
64 paneOpenFailed: (err) => 'Sessions 面板開不起來:' + err,
65 jumpFailed: (name, err) => '跳不到「' + name + '」:' + err,
66 working: '工作中',
67 background: '背景',
68 inProgress: '進行中…',
69 noSteps: '目前沒有進行中的步驟',
70 fromChecklist: '依清單',
71 usageEmpty: '用量:尚無資料',
72 severeAlt: '嚴重問題',
73 hoverStuck: (text) => '要你處理:' + text,
74 hoverDoing: (text) => '正在:' + text,
75 hoverDone: (text) => '做完:' + text,
76 jumping: '↗ 切換中…',
77 groupLabel: (name, n) => name + '(' + n + ')',
78 doneCollapsed: (n) => '已完成 ' + n + ' 步',
79 moreSteps: (n) => '還有 ' + n + ' 步',
80 commandDescription: '打開 Sessions 面板',
81 progressCleared: '已清除面板上的步驟',
82 progressUpdated: (done, total) => '已更新面板:' + done + '/' + total + ' 完成',
83 actEdit: (file) => '修改 ' + file,
84 actRead: (file) => '讀取 ' + file,
85 actRun: (d) => (d ? '執行指令:' + d : '執行指令'),
86 actSearch: '搜尋程式碼',
87 actWeb: '查網路資料',
88 actAgent: (d) => (d ? '派子代理:' + d : '派子代理'),
89 actTool: (tool) => '使用 ' + tool,
90 bgShell: '背景指令',
91 bgSubagent: '子代理',
92 bgMonitor: '監看',
93 bgWorkflow: '工作流程',
94 bgOther: '背景工作',
95 digestUser: '使用者:',
96 digestClaude: 'Claude:',
97 renameTask: '你替對話取一個繁體中文名稱:只寫在做的那個東西,用最能代表它的名詞(例:登入頁、API文件),不要動詞、不要形容詞',
98 existingNames: (names) => '\n其他 session 的名字:' + names.join('、') + '。如果這個對話跟其中一個是同一件事(例如從它分出來的),取名為「那個名字-用途」,用途也只用名詞,例:網站後台-登入。',
99 duplicateName: (name) => '「' + name + '」已經有別的 session 用了,請改成「' + name + '-用途」,用途只用名詞。只回名稱本身。',
100 summaryTask: '把使用者的請求濃縮成繁體中文,說出要做什麼即可',
101 nameRule: (max) => ',' + max + ' 個字以內(英文一個單字算 1 個字)。要完整、不要寫到一半,能短就短。只回名稱本身,不要引號、標點或解釋。',
102 shortenTask: '把名稱改寫得更短',
103 tooLong: (name, units) => '原本的名稱「' + name + '」有 ' + units + ' 個字,太長了。',
104 toolDescription:
105 '把目前任務的步驟進度回報到使用者的 Sessions 面板。多步驟任務開始時、每完成一步、卡住時、整件做完時呼叫;每次都傳完整的步驟清單。' +
106 '一個任務最多拆成 5 步,抓大方向就好;步驟名稱約 12 字以內、講大概即可(例如「改用量顯示」),不要寫細節;note 只寫一句話。' +
107 'status:done 完成、running 進行中、warn 有問題需要使用者處理、bad 嚴重問題可能停住(兩者的 note 都用一句話說明要使用者做什麼)、todo 還沒開始。' +
108 '傳空的 steps 會清掉面板上的步驟。',
109 toolTask: '整個任務的一句話名稱(選填,約 15 字以內)',
110 toolSteps: '最多 5 步',
111 toolStepTitle: '步驟名稱,約 12 字以內、講大概即可',
112 toolStepNote: 'warn/bad 時一句話說明問題與需要使用者做什麼',
113 },
114}
115
116let current = DEFAULT_LANG
117
118/** Pick the language from a locale-like code ("zh-TW", "zh_TW.UTF-8", "en"); unknown codes fall back to English. */
119export function setLang(code) {
120 const c = String(code ?? '').toLowerCase()
121 current = c.startsWith('zh') ? 'zh-TW' : DEFAULT_LANG
122 return current
123}
124
125/** Look up a UI string in the current language; function entries take arguments. */
126export function t(key, ...args) {
127 const entry = STRINGS[current][key] ?? STRINGS[DEFAULT_LANG][key]
128 return typeof entry === 'function' ? entry(...args) : entry
129}
130hooks/lib.js 771 lines1// Pure logic for session-dashboard: never touches $, so it can be unit-tested directly.
2import { t } from './i18n.js'
3
4// ===== Tunables (edit here) =====
5export const STALE_MS = 10 * 60 * 1000 // A session with no heartbeat for this long is treated as closed (crashed sessions get cleaned up too)
6export const BAR_WIDTH = 10 // Number of cells in the progress bar
7export const WARN_PCT = 50 // Usage >= this value is shown in yellow
8export const DANGER_PCT = 80 // Usage >= this value is shown in red
9
10// The kind names in $.session.usage().rateLimits (see SessionRateLimit in .claude-plugin/types/claude-code/index.d.ts)
11const WINDOW_LABELS = { five_hour: 'Session limit', seven_day: 'Weekly limit' }
12
13// TASKS.md checkbox lines: - [ ] / - [x] / * [X], indentation allowed
14const TASK_LINE = /^\s*[-*+]\s+\[( |x|X)\]\s+(.*)$/
15
16/** Percentage → "▓▓▓░░░" progress bar; values outside 0–100 are clamped. */
17export function bar(pct, width = BAR_WIDTH) {
18 const clamped = Math.max(0, Math.min(100, Number(pct) || 0))
19 const filled = Math.round((clamped / 100) * width)
20 return '▓'.repeat(filled) + '░'.repeat(width - filled)
21}
22
23/** Color for a usage percentage; undefined means the default color. */
24export function pctColor(pct) {
25 if (pct >= DANGER_PCT) return 'red'
26 if (pct >= WARN_PCT) return 'yellow'
27 return undefined
28}
29
30const pad2 = (n) => String(n).padStart(2, '0')
31
32/** Reset time (legacy format, kept for compatibility): HH:MM on the same day, otherwise M/D HH:MM. */
33export function formatReset(iso, nowMs) {
34 if (!iso) return ''
35 const t = new Date(iso)
36 if (Number.isNaN(t.getTime())) return ''
37 const hm = pad2(t.getHours()) + ':' + pad2(t.getMinutes())
38 const now = new Date(nowMs)
39 const sameDay = t.getFullYear() === now.getFullYear() && t.getMonth() === now.getMonth() && t.getDate() === now.getDate()
40 return sameDay ? hm : (t.getMonth() + 1) + '/' + t.getDate() + ' ' + hm
41}
42
43/**
44 * rateLimits → segments of the usage row, in the order 5h, weekly.
45 * Returns [{ label, pct, text, color }]; an empty array when there are no readings.
46 */
47export function usageSegments(rateLimits, nowMs) {
48 const list = Array.isArray(rateLimits) ? rateLimits : []
49 const segments = []
50 for (const kind of Object.keys(WINDOW_LABELS)) {
51 const w = list.find((r) => r && r.kind === kind)
52 if (!w || typeof w.percentUsed !== 'number') continue
53 const pct = w.percentUsed
54 const reset = relativeReset(w.resetsAt, nowMs)
55 const label = WINDOW_LABELS[kind]
56 segments.push({
57 label,
58 pct,
59 reset,
60 color: pctColor(pct),
61 text: label + ' ' + bar(pct) + ' ' + pct + '%' + (reset ? ' · ' + reset : ''),
62 })
63 }
64 return segments
65}
66
67/** The last path segment is the project name (handles both / and \). */
68/** Tag that marks which project a project-system session belongs to: the first `chars` characters of its folder name. */
69/**
70 * Whether other sessions are drawn as Client regions: yes once one has reported it runs; yes while the first one is still within `graceMs` of being drawn;
71 * no after that (the desktop app's region runtime never started, so plain rows are drawn instead), and no when the surface has no Client at all.
72 */
73export function clientRowMode(probe, now, graceMs) {
74 if (!probe.supported || probe.failed) return false
75 if (probe.ready) return true
76 return probe.firstDrawAt === null || now - probe.firstDrawAt < graceMs
77}
78
79export function projectTag(cwd, chars = 2) {
80 return [...folderName(cwd)].slice(0, chars).join('')
81}
82
83export function folderName(cwd) {
84 const parts = String(cwd ?? '').split(/[\\/]+/).filter(Boolean)
85 return parts.length ? parts[parts.length - 1] : String(cwd ?? '')
86}
87
88/** Builds the checklist file path from the working folder (default TASKS.md), keeping cwd's original separator. */
89export function tasksPath(cwd, name = 'TASKS.md') {
90 const sep = String(cwd).includes('\\') ? '\\' : '/'
91 return String(cwd).replace(/[\\/]+$/, '') + sep + name
92}
93
94// Step checklist files, searched in order (edit here): the global CLAUDE.md specifies checklist.md, older projects still use TASKS.md
95export const CHECKLIST_FILES = ['checklist.md', 'TASKS.md']
96
97/** Fingerprint deciding whether the panel needs a redraw: only visible state (status light, name, progress); constantly changing values such as the heartbeat time are excluded. */
98export function othersSignature(entries, hiddenKeys = []) {
99 const shown = (entries ?? []).map((s) => [s.id, s.name, statusOf(s), s.stats?.pct ?? null, s.stats?.total ?? 0, s.eta ?? null, s.stepLabel ?? null])
100 return JSON.stringify([shown, [...hiddenKeys].sort()])
101}
102
103/**
104 * Keeps the sessions that are still alive, sorted by "first seen" time (earliest on top); the order never changes with heartbeats or work status afterwards, to avoid misclicks.
105 * Summaries from older versions without firstSeen go last, then ordered by id for stability.
106 */
107export function liveSessions(entries, nowMs, staleMs = STALE_MS) {
108 const first = (s) => (typeof s.firstSeen === 'number' ? s.firstSeen : Number.MAX_SAFE_INTEGER)
109 // When one Desktop session has changed its CLI session id (priorCliSessionIds), the old entry lingers until it expires; keep only the one with the most recent heartbeat, and use the earlier firstSeen so its position doesn't jump
110 const byDesktop = new Map()
111 const rest = []
112 for (const s of entries) {
113 if (!s || typeof s.lastSeen !== 'number' || nowMs - s.lastSeen > staleMs) continue
114 if (!s.desktopId) { rest.push(s); continue }
115 const prev = byDesktop.get(s.desktopId)
116 if (!prev) { byDesktop.set(s.desktopId, s); continue }
117 const [keep, drop] = s.lastSeen >= prev.lastSeen ? [s, prev] : [prev, s]
118 byDesktop.set(s.desktopId, { ...keep, firstSeen: Math.min(first(keep), first(drop)) })
119 }
120 return [...rest, ...byDesktop.values()]
121 .sort((a, b) => (first(a) - first(b)) || String(a.id).localeCompare(String(b.id)))
122}
123
124// ===== Step progress =====
125
126export const STEP_STATUSES = ['done', 'running', 'warn', 'bad', 'todo']
127
128/** Step identity: title + occurrence number among same-titled steps (each same-titled step keeps its own timing). */
129function stepKeys(steps) {
130 const seen = new Map()
131 return steps.map((s) => {
132 const n = (seen.get(s.title) ?? 0) + 1
133 seen.set(s.title, n)
134 return s.title + '#' + n
135 })
136}
137
138/**
139 * Merges the step list sent by the progress tool with the previous record to derive timing info.
140 * Every call sends the full list (idempotent); steps are matched by "title + occurrence number", recording when a step was first seen as non-todo and when it became done.
141 * Returns { task, startedAt, updatedAt, steps: [{ title, status, note, startedAt, doneAt }] }
142 */
143export function mergeProgress(prev, input, nowMs) {
144 const prevSteps = prev?.steps ?? []
145 const old = new Map(stepKeys(prevSteps).map((k, i) => [k, prevSteps[i]]))
146 const raw = (Array.isArray(input?.steps) ? input.steps : [])
147 .filter((s) => s && typeof s.title === 'string' && s.title.trim() !== '')
148 .map((s) => ({ ...s, title: s.title.trim() }))
149 const keys = stepKeys(raw)
150 const steps = raw.map((s, i) => {
151 const status = STEP_STATUSES.includes(s.status) ? s.status : 'todo'
152 const was = old.get(keys[i])
153 const startedAt = was?.startedAt ?? (status !== 'todo' ? nowMs : undefined)
154 const doneAt = status === 'done' ? (was?.doneAt ?? nowMs) : undefined
155 const note = typeof s.note === 'string' && s.note.trim() !== '' ? s.note.trim() : undefined
156 return { title: s.title, status, note, startedAt, doneAt }
157 })
158 // A whole new batch of tasks (none of the old steps remain) restarts the timer
159 const sameTask = keys.some((k) => old.has(k))
160 return {
161 task: typeof input?.task === 'string' && input.task.trim() !== '' ? input.task.trim() : (sameTask ? prev?.task : undefined),
162 startedAt: sameTask && prev?.startedAt ? prev.startedAt : nowMs,
163 updatedAt: nowMs,
164 steps,
165 }
166}
167
168const TODO_STATUS = { completed: 'done', in_progress: 'running', pending: 'todo' }
169
170/**
171 * Built-in todo list (TodoWrite: [{ content, status }]) → progress-tool input, so the pane follows the todos without a separate report.
172 * The todo list has no "needs you" state: a step the progress tool marked warn/bad keeps that mark (and note) until the todo is completed.
173 */
174export function todosToInput(todos, prevSteps) {
175 const flagged = new Map((prevSteps ?? []).filter((s) => s.status === 'warn' || s.status === 'bad').map((s) => [s.title, s]))
176 const steps = (Array.isArray(todos) ? todos : [])
177 .filter((td) => td && typeof td.content === 'string' && td.content.trim() !== '')
178 .map((td) => {
179 const title = td.content.trim()
180 const status = TODO_STATUS[td.status] ?? 'todo'
181 const mark = status !== 'done' ? flagged.get(title) : undefined
182 return mark ? { title, status: mark.status, note: mark.note } : { title, status }
183 })
184 return { steps }
185}
186
187/**
188 * TASKS.md → step list (fallback when Claude didn't call the progress tool).
189 * [x] = done; a [ ] containing BLOCKED = warn (the text after BLOCKED becomes the note); the first other [ ] = running; the rest are todo.
190 */
191/** Tidy a checklist item for display: drop URLs (with the brackets around them) and Markdown backticks. */
192// Desktop's beta project system names the sessions it starts "Remote Control session (from a project)" (seen in the session records, 2026-10-19)
193const PROJECT_TITLE_MARK = '(from a project)'
194
195/** Whether a Desktop session record belongs to a session started by the project system (its first title carries PROJECT_TITLE_MARK). */
196export function isProjectSession(record) {
197 const titles = [record?.title, ...(Array.isArray(record?.previousTitles) ? record.previousTitles : [])]
198 return titles.some((title) => typeof title === 'string' && title.includes(PROJECT_TITLE_MARK))
199}
200
201export function cleanStepText(text) {
202 return String(text ?? '')
203 .replace(/[((]\s*https?:\/\/[^\s))]*\s*[))]/g, '')
204 .replace(/https?:\/\/\S+/g, '')
205 .replace(/`/g, '')
206 .replace(/\s+/g, ' ')
207 .trim()
208}
209
210/** Whether a tool call writes one of the checklist files (CHECKLIST_FILES); reading one does not count. */
211export function touchesChecklist(e) {
212 const tool = String(e?.tool ?? '')
213 const isChecklist = (s) => CHECKLIST_FILES.some((name) => String(s ?? '').toLowerCase().includes(name.toLowerCase()))
214 if (['Edit', 'Write', 'MultiEdit'].includes(tool)) return isChecklist(String(e.file_path ?? '').split(/[\\/]/).pop())
215 if (tool === 'Bash' || tool === 'PowerShell') return isChecklist(e.command)
216 return false
217}
218
219export function parseTaskSteps(md) {
220 const steps = []
221 let runningAssigned = false
222 for (const line of String(md ?? '').split(/\r?\n/)) {
223 const m = line.match(TASK_LINE)
224 if (!m) continue
225 const text = cleanStepText(m[2])
226 if (m[1] !== ' ') {
227 steps.push({ title: text, status: 'done' })
228 continue
229 }
230 // CRITICAL (or its Chinese equivalent in the regex) = bad (red), BLOCKED = warn (orange)
231 const blocked = text.match(/^(.*?)\s*(BLOCKED|CRITICAL|嚴重)[::]?\s*(.*)$/)
232 if (blocked) {
233 steps.push({ title: blocked[1].trim() || text, status: blocked[2] === 'BLOCKED' ? 'warn' : 'bad', note: blocked[3].trim() || undefined })
234 } else if (!runningAssigned) {
235 steps.push({ title: text, status: 'running' })
236 runningAssigned = true
237 } else {
238 steps.push({ title: text, status: 'todo' })
239 }
240 }
241 return steps
242}
243
244/** Step stats: done count, total, percentage, whether any step is warn. */
245export function stepStats(steps) {
246 const list = Array.isArray(steps) ? steps : []
247 const done = list.filter((s) => s.status === 'done').length
248 const total = list.length
249 return {
250 done, total,
251 pct: total === 0 ? 0 : Math.round((done / total) * 100),
252 hasWarn: list.some((s) => s.status === 'warn' || s.status === 'bad'),
253 hasBad: list.some((s) => s.status === 'bad'),
254 }
255}
256
257/** Name of the step in progress: the first running one, otherwise the first unfinished one; null when all are done. */
258export function currentStepLabel(steps) {
259 const list = Array.isArray(steps) ? steps : []
260 return (list.find((s) => s.status === 'running') ?? list.find((s) => s.status !== 'done'))?.title ?? null
261}
262
263const WEEKDAYS_EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
264
265/** Relative reset time (abbreviated English): "resets in 25m", "resets in 2h", or "resets Fri" when more than a day away. */
266export function relativeReset(iso, nowMs) {
267 if (!iso) return ''
268 const t = new Date(iso)
269 if (Number.isNaN(t.getTime())) return ''
270 const min = Math.max(0, Math.round((t.getTime() - nowMs) / 60000))
271 if (min < 60) return 'resets in ' + min + 'm'
272 if (min < 24 * 60) return 'resets in ' + Math.round(min / 60) + 'h'
273 return 'resets ' + WEEKDAYS_EN[t.getDay()]
274}
275
276/**
277 * Estimated remaining time (minutes) = average duration of completed steps × remaining step count.
278 * Returns null when no step is done yet or there is no timing data (shown as "estimating").
279 */
280export function estimateRemainingMin(progress, nowMs) {
281 const steps = progress?.steps ?? []
282 const done = steps.filter((s) => s.status === 'done' && typeof s.doneAt === 'number')
283 const remaining = steps.filter((s) => s.status !== 'done').length
284 if (done.length === 0 || typeof progress?.startedAt !== 'number') return null
285 if (remaining === 0) return 0
286 const lastDone = Math.max(...done.map((s) => s.doneAt))
287 const avgMs = Math.max(0, lastDone - progress.startedAt) / done.length
288 return Math.max(1, Math.ceil((avgMs * remaining) / 60000))
289}
290
291/** Remaining time (abbreviated English): "~18m", "~1h 15m"; null = cannot estimate yet (returns an empty string), 0 = finished. */
292export function etaText(min) {
293 if (min === null || min === undefined) return ''
294 if (min === 0) return 'done'
295 if (min < 60) return '~' + min + 'm'
296 const m = min % 60
297 return '~' + Math.floor(min / 60) + 'h' + (m ? ' ' + m + 'm' : '')
298}
299
300/** Thin progress bar for the terminal (Desktop draws an Svg instead). */
301export function thinBar(pct, width = BAR_WIDTH) {
302 const clamped = Math.max(0, Math.min(100, Number(pct) || 0))
303 const filled = Math.round((clamped / 100) * width)
304 return '▰'.repeat(filled) + '▱'.repeat(width - filled)
305}
306
307// ===== Desktop graphics (Svg); color codes come from the Claude desktop sidebar design mockup =====
308
309// Colors (edit here)
310export const COLORS = { done: '#2f8f4e', warn: '#e07a10', bad: '#c8222b', running: '#0088b0', todo: '#a9a5a3', track: '#8883', line: '#8885' }
311export const LIMIT_WARN_PCT = 80 // Usage >= this value turns the bar orange
312export const LIMIT_BAD_PCT = 85 // Usage above this value turns the bar red (user's request, 2026-10-24)
313
314/** Usage bar color: blue normally, orange when high, red when nearly full. */
315export function limitColor(pct) {
316 if (pct > LIMIT_BAD_PCT) return COLORS.bad
317 if (pct >= LIMIT_WARN_PCT) return COLORS.warn
318 return COLORS.running
319}
320
321/** 4px thin progress bar (mockup style: square corners, light gray track). */
322export function svgThinBar(pct, fill, width = 280, height = 4) {
323 const w = Math.round((Math.max(0, Math.min(100, Number(pct) || 0)) / 100) * width)
324 return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
325 `<rect width="${width}" height="${height}" fill="${COLORS.track}"/>` +
326 (w > 0 ? `<rect width="${w}" height="${height}" fill="${fill}"/>` : '') + '</svg>'
327}
328
329const NODE_LINE_PX = 24 // Height of one text row beside a node (px); NODE_HEIGHT is two rows (edit here)
330
331/** Height of a timeline node whose text takes `lines` rows, so the connector still reaches the next node when a title wraps. */
332export function nodeHeight(lines) {
333 return Math.max(NODE_HEIGHT, lines * NODE_LINE_PX)
334}
335
336export const NODE_HEIGHT = 48 // Height of each timeline node (px). Must be ≥ the height of one text row (title + one line of description) so the lines of adjacent nodes connect (edit here)
337const LINE_DONE = '#2f8f4e'
338const LINE_TODO = '#ffffff40'
339
340/**
341 * One timeline node: the dot sits in the center, with a connector segment above and below.
342 * kind: done / running / todo / warn / bad / collapsed (N steps done) / more (N more steps).
343 * label: text inside the dot (✓, step number, !, …). top / bottom: colors of the upper and lower segments, null = not drawn (the first node has no upper line, the last has no lower line).
344 */
345export function svgTimelineNode(kind, label, top, bottom, height = NODE_HEIGHT) {
346 const cx = 14
347 const cy = height / 2
348 const r = 11
349 const parts = []
350 if (top) parts.push(`<rect x="${cx - 1.5}" y="0" width="3" height="${cy}" fill="${top}"/>`)
351 if (bottom) parts.push(`<rect x="${cx - 1.5}" y="${cy}" width="3" height="${height - cy}" fill="${bottom}"/>`)
352 const fill = { done: COLORS.done, collapsed: COLORS.done, running: COLORS.running, warn: COLORS.warn, bad: COLORS.bad }[kind]
353 if (kind === 'running') parts.push(`<circle cx="${cx}" cy="${cy}" r="${r + 3}" fill="${COLORS.running}" fill-opacity="0.25"/>`)
354 if (fill) {
355 parts.push(`<circle cx="${cx}" cy="${cy}" r="${r}" fill="${fill}"/>`)
356 } else {
357 // Not started / N more steps: hollow circle (filled with the background color first to cover the line passing through); "N more steps" uses a dashed stroke
358 parts.push(`<circle cx="${cx}" cy="${cy}" r="${r}" fill="#1f1f1e" stroke="${COLORS.todo}" stroke-width="2"${kind === 'more' ? ' stroke-dasharray="3 3"' : ''}/>`)
359 }
360 const color = fill ? '#ffffff' : COLORS.todo
361 parts.push(`<text x="${cx}" y="${cy + 4}" font-size="11" font-weight="600" text-anchor="middle" font-family="system-ui,sans-serif" fill="${color}">${esc(label)}</text>`)
362 return `<svg xmlns="http://www.w3.org/2000/svg" width="28" height="${height}" viewBox="0 0 28 ${height}">${parts.join('')}</svg>`
363}
364
365/**
366 * Lays out the fitSteps result as a list of timeline nodes: [N steps done] → shown steps → [N more steps].
367 * Each node carries its upper/lower line colors: green when both adjacent nodes are completed kinds (done / collapsed), otherwise gray; the first node has no upper line and the last has no lower line.
368 */
369export function timelineItems(fit) {
370 const items = []
371 if (fit.doneCollapsed > 0) items.push({ kind: 'collapsed', label: '✓', text: t('doneCollapsed', fit.doneCollapsed) })
372 for (const { step, index } of fit.shown) {
373 const kind = STEP_STATUSES.includes(step.status) ? step.status : 'todo'
374 const label = kind === 'done' ? '✓' : kind === 'warn' || kind === 'bad' ? '!' : String(index + 1)
375 items.push({ kind, label, step, index })
376 }
377 if (fit.more > 0) items.push({ kind: 'more', label: '…', text: t('moreSteps', fit.more) })
378 const isDone = (it) => it && (it.kind === 'done' || it.kind === 'collapsed')
379 const seg = (a, b) => (a && b ? (isDone(a) && isDone(b) ? LINE_DONE : LINE_TODO) : null)
380 return items.map((it, i) => ({ ...it, top: seg(items[i - 1], it), bottom: seg(it, items[i + 1]) }))
381}
382
383// ===== Desktop session records and jump links =====
384
385// Desktop jump links only accept ids of this form (taken from the Desktop app's link handler)
386const DESKTOP_ID = /^local_[A-Za-z0-9-]{1,64}$/
387
388/** Builds a jump link for a Desktop session id; returns null when the id format is invalid. */
389export function jumpUrl(desktopId) {
390 // Same form as the link the desktop app gives for a session (2026-10-21); the older claude://code/continue?session= form switched noticeably slower
391 return DESKTOP_ID.test(String(desktopId ?? '')) ? 'claude://claude.ai/epitaxy/' + desktopId : null
392}
393
394/** Whether a Desktop session record (%APPDATA%\Claude\claude-code-sessions\…\local_*.json) belongs to this Claude Code session. */
395export function desktopRecordMatches(record, cliId) {
396 if (!record || !cliId) return false
397 return record.cliSessionId === cliId || (Array.isArray(record.priorCliSessionIds) && record.priorCliSessionIds.includes(cliId))
398}
399
400/** Takes the last title from the transcript (jsonl): custom-title first, ai-title only if there is none. */
401export function titleFromTranscript(text) {
402 const s = String(text ?? '')
403 const last = (re) => {
404 let found = null
405 for (const m of s.matchAll(re)) found = m[1]
406 return found
407 }
408 const raw = last(/"customTitle":"((?:[^"\\]|\\.)*)"/g) ?? last(/"aiTitle":"((?:[^"\\]|\\.)*)"/g)
409 if (raw === null) return null
410 try {
411 return JSON.parse('"' + raw + '"')
412 } catch {
413 return raw
414 }
415}
416
417// ===== Second line of other sessions, and dividers =====
418
419/** Second line of another session (Desktop): the progress bar stretches almost to the right edge (same width as the usage bars and dividers); the percentage moves to the first line. */
420export function svgOtherLine(pct, width = 280) {
421 if (typeof pct !== 'number') return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="16" viewBox="0 0 ${width} 16"></svg>`
422 const w = Math.round((Math.max(0, Math.min(100, pct)) / 100) * width)
423 return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="16" viewBox="0 0 ${width} 16">` +
424 `<rect x="0" y="6" width="${width}" height="4" rx="2" fill="${COLORS.track}"/>` +
425 (w > 0 ? `<rect x="0" y="6" width="${w}" height="4" rx="2" fill="${COLORS.running}"/>` : '') + '</svg>'
426}
427
428/** Blank row between other sessions (Desktop): a very faint thin line in the middle. */
429export function svgSessionGap(width = 280) {
430 return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="16" viewBox="0 0 ${width} 16"><rect x="0" y="8" width="${width}" height="1" fill="#ffffff18"/></svg>`
431}
432
433/** Escapes & < > before putting text into an Svg, so names or titles can't break the image. */
434const esc = (t) => String(t).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
435
436/** Section divider (Desktop): thick solid line with the title text embedded in the middle. */
437export function svgSectionDivider(label, width = 280) {
438 const textW = 84
439 const side = Math.max(10, Math.round((width - textW) / 2))
440 return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="16" viewBox="0 0 ${width} 16">` +
441 `<rect x="0" y="7" width="${side - 6}" height="3" fill="#ffffff66"/>` +
442 `<text x="${width / 2}" y="12" font-size="11" text-anchor="middle" font-family="system-ui,sans-serif" fill="#9a988f">${esc(label)}</text>` +
443 `<rect x="${width - side + 6}" y="7" width="${side - 6}" height="3" fill="#ffffff66"/></svg>`
444}
445
446// ===== Show the current action automatically when no steps are reported =====
447
448export const ACTIVITY_AFTER_MS = 60 * 1000 // When a turn runs longer than this without reporting through the progress tool, show the current action automatically (edit here)
449export const ACTIVITY_KEEP = 3 // Keep only this many most recent actions
450
451const baseName = (p) => folderName(p)
452const short = (s, n = 40) => {
453 const t = String(s ?? '').replace(/\s+/g, ' ').trim()
454 return t.length > n ? t.slice(0, n - 1) + '…' : t
455}
456
457// Text that looks like a path, command, or secret key (not shown; a generic name is used instead)
458const UNSAFE_TEXT = [
459 /[A-Za-z]:[\\/]/, // Windows path C:\ or C:/
460 /(^|\s)[~.]?\/[\w.-]+\//, // Unix path /a/b/, ~/x/, ./x/
461 /\|\||\||&&|;|>|<|`|\$\(/, // Pipes, chaining, redirection, subcommands
462 /(^|\s)--?[A-Za-z]/, // Command flags -x, --flag
463 /=/, // Assignment (environment variables, argument values)
464 /[A-Za-z0-9_\-]{24,}/, // Long alphanumeric run, likely a key or hash
465]
466
467/** Shows the description only when it is safe (truncated), otherwise returns fallback; keeps paths, commands, and keys off the panel. */
468export function safeText(text, fallback, max = 40) {
469 const t = String(text ?? '').replace(/\s+/g, ' ').trim()
470 if (!t || UNSAFE_TEXT.some((re) => re.test(t))) return fallback
471 return t.length > max ? t.slice(0, max - 1) + '…' : t
472}
473
474/**
475 * Tool call → a human-readable action name. Uses only the file name and the tool's own short description (sanitized first);
476 * never shows the full path or the command contents (which may contain passwords or keys).
477 */
478export function actionLabel(e) {
479 const tool = String(e?.tool ?? '')
480 if (['Edit', 'Write', 'NotebookEdit', 'MultiEdit'].includes(tool)) return t('actEdit', baseName(e.file_path ?? e.notebook_path ?? ''))
481 if (tool === 'Read') return t('actRead', baseName(e.file_path ?? ''))
482 if (tool === 'Bash' || tool === 'PowerShell') {
483 return t('actRun', safeText(e.description, ''))
484 }
485 if (tool === 'Grep' || tool === 'Glob') return t('actSearch')
486 if (tool === 'WebFetch' || tool === 'WebSearch') return t('actWeb')
487 if (tool === 'Agent' || tool === 'Task') {
488 return t('actAgent', safeText(e.description, ''))
489 }
490 return t('actTool', tool)
491}
492
493/** Puts the new action first and keeps only the most recent ACTIVITY_KEEP entries. */
494export function pushAction(actions, label, at) {
495 return [{ label, at }, ...(Array.isArray(actions) ? actions : [])].slice(0, ACTIVITY_KEEP)
496}
497
498/** Elapsed time (abbreviated English): "1m 12s", or "9s" under 1 minute. */
499export function formatElapsed(ms) {
500 const sec = Math.max(0, Math.floor(ms / 1000))
501 const m = Math.floor(sec / 60)
502 return m > 0 ? m + 'm ' + (sec % 60) + 's' : sec + 's'
503}
504
505/** Whether to show automatic activity: working, past the threshold, and no progress-tool steps in this turn. */
506export function showActivity(activity, hasToolSteps, nowMs, afterMs = ACTIVITY_AFTER_MS) {
507 return !!activity && typeof activity.startedAt === 'number' && !hasToolSteps && nowMs - activity.startedAt >= afterMs
508}
509
510// ===== Single-page layout (count rows first and draw only what fits, instead of relying on truncation) =====
511
512// Estimated rows per element (edit here). Desktop dots / thin bars are images whose real height can't be measured, so estimate conservatively: better to leave blank space than get a scrollbar
513export const ROWS = { step: 2, other: 2, limit: 2 }
514export const FALLBACK_BUDGET = 12 // Conservative value used when the available row count is unknown
515
516/** Rows of the usage block: 2 rows per bar, 1 blank row between bars; 1 row when there is no data. */
517export function usageRows(count) {
518 return count === 0 ? 1 : count * ROWS.limit + (count - 1)
519}
520
521export const WINDOW_SIZE = 5 // Max steps shown in the current-step area (centered on the current step; edit here)
522
523/**
524 * Centered on the "current step" (the first running one, otherwise the first unfinished one), takes the nearest WINDOW_SIZE steps (2 before + current + 2 after; near an edge, the other side is extended).
525 * When they don't fit, shrinks from the end farthest from the center; the current step is always kept.
526 * Returns { doneCollapsed (completed steps not shown), shown: [{ step, index }], more (unfinished steps not shown) }, with total rows ≤ maxRows.
527 */
528export function fitSteps(steps, maxRows) {
529 const list = Array.isArray(steps) ? steps : []
530 const n = list.length
531 const doneTotal = list.filter((s) => s.status === 'done').length
532 let center = list.findIndex((s) => s.status === 'running')
533 if (center === -1) center = list.findIndex((s) => s.status !== 'done')
534 if (center === -1) return { doneCollapsed: doneTotal, shown: [], more: 0 } // All done
535 const half = Math.floor(WINDOW_SIZE / 2)
536 let lo = Math.max(0, center - half)
537 let hi = Math.min(n - 1, lo + WINDOW_SIZE - 1)
538 lo = Math.max(0, hi - WINDOW_SIZE + 1)
539 const cost = (a, b) => {
540 const inside = list.slice(a, b + 1)
541 const doneOut = doneTotal - inside.filter((s) => s.status === 'done').length
542 const moreOut = (n - doneTotal) - inside.filter((s) => s.status !== 'done').length
543 return (inside.length + (doneOut > 0 ? 1 : 0) + (moreOut > 0 ? 1 : 0)) * ROWS.step
544 }
545 while (lo <= hi && cost(lo, hi) > maxRows) {
546 if (lo === hi) { lo = hi + 1; break } // Not even the current step fits
547 if (center - lo >= hi - center) lo++
548 else hi--
549 }
550 const shown = lo <= hi ? list.slice(lo, hi + 1).map((step, i) => ({ step, index: lo + i })) : []
551 if (shown.length === 0) return { doneCollapsed: 0, shown: [], more: 0 } // Not even the current step fits, so the collapsed nodes aren't drawn either (they each take ROWS.step rows)
552 const doneCollapsed = doneTotal - shown.filter((x) => x.step.status === 'done').length
553 const more = (n - doneTotal) - shown.filter((x) => x.step.status !== 'done').length
554 return { doneCollapsed, shown, more }
555}
556
557
558/** Rows of the other-sessions block: 1 divider + ROWS.other rows each + 1 blank row between them + 1 row for "…N more". */
559export function othersRows(shown, total) {
560 if (shown === 0) return 0
561 return 1 + shown * ROWS.other + (shown - 1) + (total > shown ? 1 : 0)
562}
563
564/** Title cleanup: strips quotes, punctuation, and line breaks. */
565export function cleanTitle(text) {
566 // Only strips quotes, punctuation, and extra lines; never truncates (a name cut in half is unreadable). Overlong names are left to nameUnits to detect, then the model is asked to rename
567 return String(text ?? '').split(/\r?\n/)[0].replace(/["'「」『』《》“”‘’*`#]/g, '').replace(/[。..!!??::]+$/, '').trim()
568}
569
570/** Name length: one English word (or a run of digits) counts as 1 unit, each CJK character counts as 1 unit, whitespace and symbols don't count. */
571export function nameUnits(text) {
572 return (String(text ?? '').match(/[A-Za-z0-9]+(?:[-_.'][A-Za-z0-9]+)*|[^\sA-Za-z0-9\p{P}\p{S}]/gu) ?? []).length
573}
574
575// ===== Status lights =====
576
577// Light colors (edit here): problem needing attention = red light, severe problem = red triangle icon, in progress = blue, finished but unread = orange, seen = gray hollow; there is no green light by design
578// Order of other sessions: what needs the user first, then finished-but-unseen, then working, then seen
579const URGENCY_RANK = { bad: 0, warn: 0, unread: 1, working: 2, idle: 3 }
580
581/** Most recent activity time of a session, used to order sessions within one urgency level. */
582function lastActivity(s) {
583 return Math.max(s?.finishedAt ?? 0, s?.workStartedAt ?? 0, s?.firstSeen ?? 0)
584}
585
586/** Sort other sessions by urgency (URGENCY_RANK), the most recently active first within a level. */
587export function sortByUrgency(list) {
588 return [...list].sort((a, b) => (URGENCY_RANK[statusOf(a)] - URGENCY_RANK[statusOf(b)]) || (lastActivity(b) - lastActivity(a)) || String(a.id).localeCompare(String(b.id)))
589}
590
591/** Group key of a session name: the part before the first "-" (the naming rule puts the purpose after it). */
592export function groupKey(name) {
593 return String(name ?? '').split('-')[0].trim()
594}
595
596/**
597 * Lay out sorted sessions as rows: sessions that need the user stay at the top, ungrouped;
598 * the rest are grouped by groupKey when 2 or more share it, the group placed where its first member falls.
599 * Returns items { type: 'header', key, name, count } or { type: 'row', s }.
600 */
601export function groupSessions(sorted) {
602 const urgent = sorted.filter((s) => URGENCY_RANK[statusOf(s)] === 0)
603 const rest = sorted.filter((s) => URGENCY_RANK[statusOf(s)] !== 0)
604 const counts = new Map()
605 for (const s of rest) counts.set(groupKey(s.name), (counts.get(groupKey(s.name)) ?? 0) + 1)
606 const items = urgent.map((s) => ({ type: 'row', s }))
607 const placed = new Set()
608 for (const s of rest) {
609 const key = groupKey(s.name)
610 if ((counts.get(key) ?? 0) < 2) { items.push({ type: 'row', s }); continue }
611 if (placed.has(key)) continue
612 placed.add(key)
613 const members = rest.filter((m) => groupKey(m.name) === key)
614 items.push({ type: 'header', key, name: key, count: members.length }, ...members.map((m) => ({ type: 'row', s: m })))
615 }
616 return items
617}
618
619/** The one line shown under a session while the pointer is on it: { kind: 'stuck' | 'doing' | 'done', text }, or null when there is nothing to say. */
620export function hoverInfo(s) {
621 const status = statusOf(s)
622 if (status === 'bad' || status === 'warn') {
623 const text = s.alertNote || s.stepLabel
624 return text ? { kind: 'stuck', text } : null
625 }
626 if (status === 'working') {
627 const text = s.stepLabel || s.activity?.current
628 return text ? { kind: 'doing', text } : null
629 }
630 return s.lastDoneLabel ? { kind: 'done', text: s.lastDoneLabel } : null
631}
632
633export const LIGHT = { bad: '#c8222b', warn: '#c8222b', working: '#0088b0', unread: '#e07a10', idle: '#77756f' }
634
635/** Icon for a severe problem (work may be unable to continue): red-outlined rounded triangle + exclamation mark, replacing the status dot. */
636export function svgAlertIcon(color = LIGHT.bad, size = 16) {
637 return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24">`
638 + `<path d="M12 3.5 L21.5 20 H2.5 Z" fill="none" stroke="${color}" stroke-width="2.2" stroke-linejoin="round"/>`
639 + `<path d="M12 9.5 V14" stroke="${color}" stroke-width="2.2" stroke-linecap="round"/>`
640 + `<circle cx="12" cy="17.2" r="1.3" fill="${color}"/></svg>`
641}
642
643/** Status of another session: bad / warn / working (including background) / unread (finished but not opened yet) / idle. */
644export function statusOf(s) {
645 const stats = s?.stats ?? {}
646 if (stats.hasBad) return 'bad'
647 if (stats.hasWarn) return 'warn'
648 if (s?.isWorking || s?.background) return 'working'
649 const seen = Math.max(s?.lastFocusedAt ?? 0, s?.seenAt ?? 0)
650 if (typeof s?.finishedAt === 'number' && s.finishedAt > seen) return 'unread'
651 return 'idle'
652}
653
654/** Right-side time: while working, shows the remaining time if it can be computed; once stopped, shows how long ago it finished (using the work end time, not the heartbeat time). */
655export function rightTime(s, nowMs) {
656 const busy = s?.isWorking || s?.background
657 if (busy) return s?.hasToolSteps && s?.eta ? s.eta : ''
658 return typeof s?.finishedAt === 'number' ? ago(s.finishedAt, nowMs) : ''
659}
660
661// ===== Background work =====
662
663// type of background_tasks (official BackgroundTaskSummary) → the localized fallback name (i18n key) used when there is no description
664const BG_TYPE_KEY = { shell: 'bgShell', subagent: 'bgSubagent', monitor: 'bgMonitor', workflow: 'bgWorkflow' }
665
666/**
667 * background_tasks from classic.Stop → { count, current }; returns null when empty or missing.
668 * Uses only the sanitized description, never the command contents (which may contain passwords or keys).
669 */
670export function summarizeBackground(tasks) {
671 const list = Array.isArray(tasks) ? tasks.filter((t) => t && typeof t === 'object') : []
672 if (list.length === 0) return null
673 const first = list[0]
674 const fallback = t(BG_TYPE_KEY[first.type] ?? 'bgOther')
675 return { count: list.length, current: safeText(first.description, fallback) }
676}
677
678// ===== Hide other projects =====
679
680/**
681 * Splits other sessions into "visible" and "hidden" according to the hide record ({ [sessionId]: { at } }).
682 * This is an "untrack": after ✕ is pressed the session is no longer shown; it only comes back once that session has been opened afterwards (lastFocusedAt > the untrack time),
683 * and is then listed in unhide so the caller can clear the record. Starting a new turn on its own or finishing background work does not bring it back.
684 * hiddenCount only counts sessions that are still open (others already excludes expired ones).
685 */
686export function splitHidden(others, hidden) {
687 const map = hidden && typeof hidden === 'object' ? hidden : {}
688 const visible = []
689 const unhide = []
690 let hiddenCount = 0
691 for (const s of others) {
692 const h = map[s.id]
693 if (!h) {
694 visible.push(s)
695 } else if (typeof s.lastFocusedAt === 'number' && s.lastFocusedAt > h.at) {
696 visible.push(s)
697 unhide.push(s.id)
698 } else {
699 hiddenCount += 1
700 }
701 }
702 return { visible, hiddenCount, unhide }
703}
704
705/** How long ago (abbreviated English): "just now", "40m ago", "2h 5m ago", "1d 3h ago". */
706export function ago(ms, nowMs) {
707 const min = Math.max(0, Math.floor((nowMs - ms) / 60000))
708 if (min < 1) return 'just now'
709 if (min < 60) return min + 'm ago'
710 // Only the largest unit, rounded down: a rough idea is enough (user's request, 2026-10-23)
711 const h = Math.floor(min / 60)
712 if (h < 24) return h + 'h ago'
713 return Math.floor(h / 24) + 'd ago'
714}
715
716// ===== Auto-naming looks at the whole session =====
717
718/**
719 * Condenses the whole session into text for a small model to name it: every user message (up to 300 chars each) + the first Claude reply right after it (up to 150 chars);
720 * the tool activity in between is left out (too much would push out the earlier topic). When over budget chars, keeps the first 2 turns (the topic is usually at the start) and the most recent turns.
721 */
722export function conversationDigest(messages, budget = 6000) {
723 const turns = []
724 for (const m of messages ?? []) {
725 if (!m || typeof m.text !== 'string' || m.text.trim() === '') continue
726 if (m.role === 'user') turns.push({ user: m.text.trim().slice(0, 300), reply: null })
727 else if (turns.length > 0 && turns.at(-1).reply === null) turns.at(-1).reply = m.text.trim().slice(0, 150)
728 }
729 const lines = turns.map((turn) => t('digestUser') + turn.user + (turn.reply ? '\n' + t('digestClaude') + turn.reply : ''))
730 const join = (list) => list.join('\n')
731 if (join(lines).length <= budget) return join(lines)
732 const head = lines.slice(0, 2)
733 const tail = []
734 for (let i = lines.length - 1; i >= 2; i--) {
735 if (join([...head, '…', lines[i], ...tail]).length > budget) break
736 tail.unshift(lines[i])
737 }
738 return join([...head, '…', ...tail]).slice(0, budget)
739}
740
741// ===== Wrapping long text =====
742
743/** Wraps by display width: CJK characters count as 2 cells, others as 1; drops no characters, for name buttons where "every line must be clickable". */
744export function wrapByWidth(text, cells) {
745 const width = (str) => [...str].reduce((n, ch) => n + (ch.codePointAt(0) > 0x2e7f ? 2 : 1), 0)
746 const lines = []
747 let line = ''
748 for (const ch of String(text ?? '')) {
749 if (width(line + ch) > cells && line !== '') {
750 // A space that does not fit ends the line (it hangs past the edge, unseen) instead of starting the next one
751 if (ch === ' ') {
752 lines.push(line + ch)
753 line = ''
754 continue
755 }
756 // Otherwise break after the last space when there is one, so English words stay whole
757 const cut = line.lastIndexOf(' ')
758 if (cut >= 0 && cut < line.length - 1) {
759 lines.push(line.slice(0, cut + 1))
760 line = line.slice(cut + 1)
761 } else {
762 lines.push(line)
763 line = ''
764 }
765 }
766 line += ch
767 }
768 if (line !== '' || lines.length === 0) lines.push(line)
769 return lines
770}
771hooks/row.js 65 lines1/**
2 * One other session's block on Desktop, drawn as a Client region so the whole block (name, bar, time) is one click target with one hover background.
3 * A Button only takes a text label and an absolutely placed Box passes the pointer to its parent, so neither can make the drawn bar clickable; a Client region gets every pointer event itself.
4 *
5 * props: { name, glyph, light, right, pct (number | null), barColor, track, hoverBg, jumpingLabel }
6 */
7export default function SessionRow(p, surface) {
8 const { Box, Text } = surface.elements
9 const state = surface.state ?? {}
10 const hover = state.hover === true
11 const jumping = state.jumping === true
12 const set = (change) => surface.setState({ ...state, ...change })
13 // Tell the hooks module once that this region really runs: the desktop app can fail to start the region's runtime, and the pane then falls back to plain rows
14 if (state.ready !== true) { surface.post({ ready: true }); set({ ready: true }) }
15 // One listener; a later call replaces the earlier one, so setting it on every draw is safe
16 surface.onPointer((e) => {
17 if (e.type === 'enter' && !hover) set({ hover: true })
18 else if (e.type === 'leave' && hover) set({ hover: false })
19 // Jump on release inside the block, so pressing and dragging away cancels like a normal button.
20 // The app takes a few seconds to switch, so the block answers at once, here, without waiting for the hooks module, and ignores more clicks meanwhile
21 else if (e.type === 'up' && e.button === 'left' && isInside(e, surface) && surface.state?.jumping !== true) {
22 surface.setState({ ...(surface.state ?? {}), jumping: true })
23 surface.post({ jump: true })
24 const stop = surface.every(JUMP_FEEDBACK_MS, () => { stop(); surface.setState({ ...(surface.state ?? {}), jumping: false }) })
25 }
26 })
27 const right = jumping ? p.jumpingLabel : p.right
28 const line1 = Box({ flexDirection: 'row', justifyContent: 'space-between', columnGap: 1, children: [
29 Box({ flexDirection: 'row', columnGap: 1, flexShrink: 1, children: [
30 Text({ color: p.light, children: [p.glyph] }),
31 Text({ bold: true, wrap: 'wrap', children: [p.name] }),
32 ] }),
33 right ? Text({ dimColor: !hover && !jumping, wrap: 'truncate-end', children: [right] }) : null,
34 ].filter(Boolean) })
35 // The bar is a row of thin line glyphs (done part, then faint track): a Client has no Svg, and a coloured Box is at least one text row tall, which looked too thick
36 const bar = typeof p.pct === 'number'
37 // One line of text with two coloured spans: as two side-by-side Texts the done part shrank first and was cut with "…" in the middle of the bar.
38 // A line glyph can be drawn wider than one cell, so the line is kept a little short and cut at its end ('truncate-end'; the desktop app ignores plain 'truncate' and wrapped the rest onto a new line)
39 ? Box({ overflow: 'hidden', children: [Text({ wrap: 'truncate-end', children: barParts(p, barCells(surface.columns)).map(([text, color]) => Text({ color, children: [text] })) })] })
40 : Text({ children: [' '] })
41 // Nothing is added under the pointer: an extra line made the block taller, the rows below moved, and a click landed on the next session (2026-10-23)
42 return Box({ flexDirection: 'column', backgroundColor: hover || jumping ? p.hoverBg : undefined, children: [line1, bar] })
43}
44
45const JUMP_FEEDBACK_MS = 8000 // How long "switching…" stays; the app usually switches within about 5 s (measured 2026-10-21/22)
46const BAR_GLYPH = '━' // Thin horizontal line; repeated it reads as one continuous line
47const BAR_FALLBACK_CELLS = 40 // Bar width before the region has been laid out once
48const BAR_WIDTH_SHARE = 0.85 // Share of the region's cells the bar fills: leaves room for glyphs drawn wider than a cell (the bar wrapped at 100%, 2026-10-22)
49
50/** [text, colour] pieces of the bar for `cells` columns: the done part, then the remaining track. */
51function barParts(p, cells) {
52 const done = Math.round((Math.max(0, Math.min(100, p.pct)) / 100) * cells)
53 return [[BAR_GLYPH.repeat(done), p.barColor], [BAR_GLYPH.repeat(cells - done), p.track]].filter(([text]) => text)
54}
55
56/** How many line glyphs the bar gets: the region's width less a margin, since a glyph may be drawn a little wider than one cell. */
57function barCells(columns) {
58 if (!columns) return BAR_FALLBACK_CELLS
59 return Math.max(4, Math.floor(columns * BAR_WIDTH_SHARE))
60}
61
62function isInside(e, surface) {
63 return e.x >= 0 && e.y >= 0 && (surface.columns === 0 || e.x < surface.columns) && (surface.rows === 0 || e.y < surface.rows)
64}
65