SLOPSHOPPER

sessions-sidebar

Sidebar listing every Claude Code session open on this machine

paneguardcommandtoastpromptprocess
v0.1.0no licenseupdated 2026-10-20narley/sessions-sidebar
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · sessions-sidebar
│ ┃ sessions-sidebar ✕ › fix the failing auth test and add an audit log call │ ┃ │ ┃ ⌂ No repo ▾ ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ ▾ Live 0 ⌕ ≡ ⏺ Update(src/auth.ts) │ ┃ All 0 · Worktrees 0 · Ad hoc 0 ⎿ Added 2 lines, removed 1 line │ ┃ ──────────────────────────────────────────── ⏺ Bash(bun test) │ ┃ ──────────── ⎿ 3 pass, 1 fail │ ┃ │ ┃ None ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ ▾ Closed 0 ⌕ ✻ Worked for 42s · done 4:20 PM │ ┃ All 0 · Worktrees 0 · Ad hoc 0 │ ┃ ──────────────────────────────────────────── › /sessions-sidebar │ ┃ ──────────── ⎿ sessions-sidebar: Sessions sidebar closed. │ ┃ │ ┃ None │ ┃ │ ┃ ▸ Done 0 │ ┃ ──────────────────────────────────────────── │ ┃ ──────────── │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · sessions-sidebar
⌂ No repo ▾ ▾ Live 0 ⌕ ≡ All 0 · Worktrees 0 · Ad hoc 0 ──────────────────────────────────────────────────────── None ▾ Closed 0 ⌕ All 0 · Worktrees 0 · Ad hoc 0 ──────────────────────────────────────────────────────── None ▸ Done 0 ──────────────────────────────────────────────────────── ──────────────────────────────────────────────────────── [ + New Session ] ──────────────────────────────────────────────────────── 5h ━━━╺━━━━━━ 31% resets NaNm
Source 2 files
hooks/register.tsx 3466 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type {
5  CheckoutRow,
6  KindFilter,
7  ClosedRow,
8  DetailLevel,
9  DormantRow,
10  RepoOption,
11  Section,
12  SessionRow,
13} from '../types'
14
15const PANE = 'sessions-sidebar'
16// the width the person settled on; one they drag the dock to still wins, kept by Claude Code
17const PANE_COLUMNS = 45
18const REFRESH_MS = 3000
19const rows = atom({ plugin: 'sessions-sidebar', key: 'rows' } as const, [])
20const dormantRows = atom({ plugin: 'sessions-sidebar', key: 'dormant' } as const, [])
21const closedRows = atom({ plugin: 'sessions-sidebar', key: 'closed' } as const, [])
22const checkoutRows = atom({ plugin: 'sessions-sidebar', key: 'checkout' } as const, [])
23// Ad hoc lists its sessions used this recently; older ones are offered in pages from a menu
24const RECENT_MS = 7 * 24 * 3_600_000
25const OLDER_PAGE_SIZE = 10
26// what the older sessions' menu is filtered by, as typed; this sidebar's own
27const olderSearch = atom({ plugin: 'sessions-sidebar', key: 'olderSearch' } as const, '')
28// the repos the sidebar shows, and every repo there is to pick from
29const repoChoice = atom({ plugin: 'sessions-sidebar', key: 'repos' } as const, {
30  selected: [],
31  options: [],
32})
33// what the repo menu is filtered by, as typed; this sidebar's own
34const repoSearch = atom({ plugin: 'sessions-sidebar', key: 'repoSearch' } as const, '')
35// each section's search as typed, while its ⌕ has it open; this sidebar's own
36const sectionSearches = atom({ plugin: 'sessions-sidebar', key: 'searches' } as const, {})
37// ids of closed sessions moved to Archived, shared by every session's sidebar
38const archivedIds = atom({ plugin: 'sessions-sidebar', key: 'archived' } as const, [])
39const SECTIONS: Section[] = ['live', 'dormant', 'closed']
40// how a section starts until someone folds or opens it: Done only grows, and is the least looked at
41const IS_COLLAPSED_BY_DEFAULT: Record<Section, boolean> = {
42  live: false,
43  dormant: false,
44  closed: true,
45}
46// which of a section's two kinds it lists: those with a worktree, and ad hoc ones without
47const KIND_FILTERS: { id: KindFilter; label: string }[] = [
48  { id: 'all', label: 'All' },
49  { id: 'worktrees', label: 'Worktrees' },
50  { id: 'adhoc', label: 'Ad hoc' },
51]
52// each section's, shared by every session's sidebar like the detail level; absent is all
53const sectionFilters = atom({ plugin: 'sessions-sidebar', key: 'filters' } as const, {})
54// New Session's picker while open: the profile's default model, each model's saved effort, and the
55// effort picked for this launch (absent: each keeps its saved one); this sidebar's own
56const newSessionMenu = atom({ plugin: 'sessions-sidebar', key: 'newSession' } as const, null)
57// what New Session offers, by the alias `claude --model` takes and the key settings saves effort under
58const NEW_SESSION_MODELS = [
59  { model: 'opus[1m]', family: 'opus', label: 'Opus 5.5 1M', settingsKey: 'claude-opus-5-5' },
60  { model: 'sonnet', family: 'sonnet', label: 'Sonnet 5.5', settingsKey: 'claude-sonnet-5-5' },
61  { model: 'fable', family: 'fable', label: 'Fable 5.1', settingsKey: 'claude-fable-5-1' },
62  { model: 'haiku', family: 'haiku', label: 'Haiku 4.5', settingsKey: 'claude-haiku-4-5' },
63]
64const EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max']
65const DEFAULT_COLLAPSED = SECTIONS.filter(section => IS_COLLAPSED_BY_DEFAULT[section])
66const collapsedSections = atom(
67  { plugin: 'sessions-sidebar', key: 'collapsed' } as const,
68  DEFAULT_COLLAPSED,
69)
70// how much each live session shows, shared by every session's sidebar
71const DETAIL_LEVELS: DetailLevel[] = ['compact', 'standard', 'full']
72const detailLevel = atom({ plugin: 'sessions-sidebar', key: 'detail' } as const, 'full')
73// how many blocks (a heading, a session) the list is scrolled past
74const listOffset = atom({ plugin: 'sessions-sidebar', key: 'offset' } as const, 0)
75// flips each PULSE_MS while a session runs ioi-autopilot, swapping its card's colours
76const PULSE_MS = 1000
77const pulse = atom({ plugin: 'sessions-sidebar', key: 'pulse' } as const, false)
78// the account's 5h and 7d windows and this session's prompt cache, drawn above New Session
79const usageInfo = atom({ plugin: 'sessions-sidebar', key: 'usage' } as const, { limits: [] })
80// the one question the sidebar is asking, drawn under the row its key names
81const question = atom({ plugin: 'sessions-sidebar', key: 'question' } as const, null)
82// this session's agents at work, which its row's agents line offers to show in the main view
83const ownAgents = atom({ plugin: 'sessions-sidebar', key: 'agents' } as const, [])
84// set by each render, read by the scroll hook, which has no layout of its own to clamp against
85let maxListOffset = 0
86
87// shape of <config dir>/sessions/<pid>.json, the engine's registry of running sessions
88type RegisteredSession = {
89  pid: number
90  sessionId: string
91  cwd: string
92  startedAt: number
93  kind: string
94  name?: string
95  status?: string
96  // set while Remote Control is on, null once it is turned off
97  bridgeSessionId?: string | null
98  // how it was started: `cli` in a terminal, `sdk-py`/`sdk-ts` when a script drives it
99  entrypoint?: string
100  // a background session's (kind `bg`) id, as `claude attach` and `claude stop` take it
101  jobId?: string
102}
103
104type Worktree = { path: string; branch?: string; repo: string; isMain: boolean }
105
106const baseName = (path: string) => path.split('/').filter(Boolean).pop() ?? path
107
108const placeOf = (cwd: string) => {
109  const worktree = /\/\.claude\/worktrees\/([^/]+)/.exec(cwd)
110
111  return worktree ? `worktree ${worktree[1]}` : baseName(cwd)
112}
113
114const isInside = (path: string, dir: string) => path === dir || path.startsWith(`${dir}/`)
115
116// a row matches while one of its texts holds the query, case aside
117const holds = (query: string, texts: readonly (string | undefined)[]) => {
118  const wanted = query.trim().toLowerCase()
119
120  return wanted === '' || texts.some(text => text?.toLowerCase().includes(wanted) ?? false)
121}
122
123const liveTexts = (one: SessionRow) => [one.name, one.branch, one.place]
124
125const ticketOf = (text: string | undefined) =>
126  text === undefined ? undefined : /^(\d+)(?:-|$)/.exec(text)?.[1]
127
128const configDirOf = async ($: EngineInterface) =>
129  (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${await $.env.get('HOME')}/.claude`
130
131// how Claude Code names a folder's transcript directory under <config dir>/projects
132const projectKeyOf = (path: string) => path.replace(/[^A-Za-z0-9]/g, '-')
133
134const transcriptOf = (configDir: string, one: RegisteredSession) =>
135  `${configDir}/projects/${projectKeyOf(one.cwd)}/${one.sessionId}.jsonl`
136
137const tailOf = async ($: EngineInterface, configDir: string, one: RegisteredSession) =>
138  (
139    await $.process
140      .run(['tail', '-c', '262144', transcriptOf(configDir, one)])
141      .catch(() => undefined)
142  )?.stdout ?? ''
143
144// the registry keeps the launch folder; the transcript's newest cwd is where the session works now
145const currentCwdIn = (tail: string, one: RegisteredSession) =>
146  [...tail.matchAll(/"cwd":"([^"]+)"/g)].at(-1)?.[1] ?? one.cwd
147
148type CacheWrites = { ephemeral_1h_input_tokens?: number; ephemeral_5m_input_tokens?: number }
149
150// the prompt cache lives for its lifetime (1h or 5m, by the kind of cache write the responses made)
151// past the last API response
152const cacheExpiryIn = (tail: string) => {
153  const responses = tail.split('\n').flatMap(line => {
154    if (!line.includes('"type":"assistant"') || !line.includes('"cache_creation"')) return []
155    try {
156      const entry = JSON.parse(line) as {
157        timestamp?: string
158        message?: { usage?: { cache_creation?: CacheWrites } }
159      }
160
161      return entry.timestamp === undefined ? [] : [entry]
162    } catch {
163      return []
164    }
165  })
166  const last = responses.at(-1)
167  if (last?.timestamp === undefined) return undefined
168  const isHourLong = responses.some(
169    one => (one.message?.usage?.cache_creation?.ephemeral_1h_input_tokens ?? 0) > 0,
170  )
171
172  return Date.parse(last.timestamp) + (isHourLong ? 3_600_000 : 300_000)
173}
174
175const worktreesOf = async ($: EngineInterface, cwd: string): Promise<Worktree[]> => {
176  const listed = await $.process
177    .run(['git', '-C', cwd, 'worktree', 'list', '--porcelain'])
178    .catch(() => undefined)
179  if (listed === undefined || listed.exitCode !== 0) return []
180
181  // git always lists the main worktree first
182  const blocks = listed.stdout.trim().split(/\n\n+/)
183  const repo = /^worktree (.+)$/m.exec(blocks[0] ?? '')?.[1] ?? cwd
184
185  return blocks.flatMap((block, index) => {
186    const path = /^worktree (.+)$/m.exec(block)?.[1]
187    if (path === undefined || /^prunable/m.test(block)) return []
188
189    return [
190      { path, repo, isMain: index === 0, branch: /^branch refs\/heads\/(.+)$/m.exec(block)?.[1] },
191    ]
192  })
193}
194
195// a folder's repo: the main checkout git lists first, a Claude worktree's though it is gone; a
196// folder outside git is its own, and one that is gone has none
197const repoOf = async ($: EngineInterface, cwd: string) => {
198  const folder = cwd.replace(/\/\.claude\/worktrees\/.*$/, '')
199  const [main] = await worktreesOf($, folder)
200  if (main !== undefined) return main.repo
201
202  return (await $.fs.exists(folder).catch(() => false)) ? folder : undefined
203}
204
205// ponytail: a transcript folder's name cannot be read back as a path, so its repo comes from the cwd
206// of its newest transcript, found once per folder; one with no transcript yet is tried again
207const repoOfProject = new Map<string, string | undefined>()
208
209const projectFoldersOf = async ($: EngineInterface, projects: string) => {
210  const folders = (await $.fs.list(projects).catch(() => [])).filter(entry => entry.kind === 'dir')
211  const unknown = await Promise.all(
212    folders
213      .filter(entry => !repoOfProject.has(entry.name))
214      .map(async entry => {
215        const newest = (await $.fs.list(`${projects}/${entry.name}`).catch(() => []))
216          .filter(file => file.kind === 'file' && file.name.endsWith('.jsonl'))
217          .sort((a, b) => b.mtimeMs - a.mtimeMs)[0]
218
219        return {
220          name: entry.name,
221          transcript: newest === undefined ? undefined : `${projects}/${entry.name}/${newest.name}`,
222        }
223      }),
224  )
225  const transcripts = unknown.flatMap(one => (one.transcript === undefined ? [] : [one.transcript]))
226  const found =
227    transcripts.length === 0
228      ? ''
229      : (
230          await $.process
231            .run(['grep', '-m', '1', '-o', '-H', '"cwd":"[^"]*"', ...transcripts])
232            .catch(() => undefined)
233        )?.stdout
234  const cwdOf = new Map(
235    [...(found ?? '').matchAll(/^(.+?):"cwd":"([^"]*)"$/gm)].map(match => [match[1], match[2]]),
236  )
237  await Promise.all(
238    unknown.map(async one => {
239      const cwd = cwdOf.get(one.transcript ?? '')
240      if (cwd !== undefined) repoOfProject.set(one.name, await repoOf($, cwd))
241    }),
242  )
243
244  return folders.flatMap(entry => {
245    const repo = repoOfProject.get(entry.name)
246
247    return repo === undefined ? [] : [{ dir: `${projects}/${entry.name}`, repo }]
248  })
249}
250
251// which session started each background one, as that session recorded it the moment its shell ran
252// `claude --bg`: { <job id>: <session id> }, shared by every sidebar
253const launchesFileOf = (configDir: string) => `${configDir}/sessions-sidebar/launches.json`
254
255// after one of this session's shell commands: the background sessions it started are those whose
256// id its output shows, or, when it ran `claude --bg` and printed none, those registered while it ran
257const recordLaunches = async (
258  $: EngineInterface,
259  { since, command, stdout }: { since: number; command: string; stdout: string },
260) => {
261  const configDir = await configDirOf($)
262  const dir = `${configDir}/sessions`
263  const until = await $.clock.now()
264  const jobs = (
265    await Promise.all(
266      (await $.fs.list(dir).catch(() => []))
267        .filter(entry => entry.name.endsWith('.json'))
268        .map(entry =>
269          $.fs
270            .read(`${dir}/${entry.name}`)
271            .then(text => JSON.parse(String(text)) as RegisteredSession)
272            .catch(() => undefined),
273        ),
274    )
275  ).flatMap(one => (one?.kind === 'bg' && one.jobId !== undefined ? [one] : []))
276  // a session that only lists or greps them sees their ids too: those are no launch; nor is a
277  // command that merely names a .claude path and --bg, so claude must be the command word
278  const isLaunch = /(?:^|[\s;&|(])claude\s[^;&|\n]*--(?:bg|background)\b/.test(command)
279  const shown = jobs.filter(
280    one =>
281      one.jobId !== undefined &&
282      (isLaunch
283        ? stdout.includes(one.jobId)
284        : new RegExp(`\\bbackgrounded\\s*·\\s*${one.jobId}\\b`).test(stdout)),
285  )
286  // a worker can register a moment after `claude --bg` has printed its id (the first launch also
287  // starts the background service), so an id printed as backgrounded counts on its own
288  const printed = [...stdout.matchAll(/\bbackgrounded\s*·\s*([0-9a-f]{8})\b/g)].flatMap(match =>
289    match[1] === undefined ? [] : [match[1]],
290  )
291  const started = [
292    ...new Set([
293      ...(shown.length > 0 || printed.length > 0 || !isLaunch
294        ? shown
295        : jobs.filter(one => one.startedAt >= since - 1000 && one.startedAt <= until + 1000)
296      ).flatMap(one => (one.jobId === undefined ? [] : [one.jobId])),
297      ...printed,
298    ]),
299  ]
300  if (started.length === 0) return
301
302  const own = await $.session.id()
303  const saved: unknown = await $.fs
304    .read(launchesFileOf(configDir))
305    .then(text => JSON.parse(String(text)) as unknown)
306    .catch(() => ({}))
307  // a job's link lasts as long as its job, which a resumed worker keeps, so the file stays small;
308  // the first session to record a job keeps it, as a launcher sees its worker's id first
309  const entries = Object.entries(typeof saved === 'object' && saved !== null ? saved : {})
310  const isKept = await Promise.all(
311    entries.map(
312      ([id]) =>
313        jobs.some(one => one.jobId === id) ||
314        $.fs.exists(`${configDir}/jobs/${id}`).catch(() => false),
315    ),
316  )
317  const kept = Object.fromEntries(entries.filter((_, index) => isKept[index]))
318  const added = started.filter(id => !(id in kept))
319  if (added.length === 0) return
320
321  await $.fs.write(
322    launchesFileOf(configDir),
323    JSON.stringify({ ...kept, ...Object.fromEntries(added.map(id => [id, own])) }),
324  )
325}
326
327// which transcript started each background session: what `claude --bg` prints varies (`backgrounded ·
328// <id>`, or `<id> <name> busy …`), so it is whichever live transcript holds the id; at launch only
329// the launcher knows it, and if more do by the time this looks, the one that wrote it first. Found
330// once per id; one not found yet is looked for again
331const launcherOfJob = new Map<string, string>()
332
333const findLaunchers = async (
334  $: EngineInterface,
335  jobIds: readonly string[],
336  transcripts: readonly string[],
337) => {
338  const unknown = jobIds.filter(id => !launcherOfJob.has(id))
339  if (unknown.length === 0 || transcripts.length === 0) return
340
341  const found =
342    (
343      await $.process
344        .run(['grep', '-o', '-H', '-F', ...unknown.flatMap(id => ['-e', id]), ...transcripts])
345        .catch(() => undefined)
346    )?.stdout ?? ''
347  const holders = [...found.matchAll(/^(.+):([0-9a-f]{8})$/gm)]
348  await Promise.all(
349    unknown.map(async id => {
350      const files = [
351        ...new Set(
352          holders.flatMap(match => (match[2] === id && match[1] !== undefined ? [match[1]] : [])),
353        ),
354      ]
355      const first =
356        files.length < 2
357          ? files[0]
358          : (
359              await Promise.all(
360                files.map(async file => {
361                  const line =
362                    (
363                      await $.process
364                        .run(['grep', '-m', '1', '-F', id, file])
365                        .catch(() => undefined)
366                    )?.stdout ?? ''
367
368                  return { file, at: /"timestamp":"([^"]+)"/.exec(line)?.[1] ?? '~' }
369                }),
370              )
371            ).sort((a, b) => a.at.localeCompare(b.at))[0]?.file
372      if (first !== undefined) launcherOfJob.set(id, first)
373    }),
374  )
375}
376
377// a session belongs to the linked worktree it works inside, else the one in its repo named after
378// its ticket (sessions often sit in the repo while working on a worktree), else the main checkout
379const worktreeOf = (cwd: string, name: string | undefined, worktrees: readonly Worktree[]) => {
380  const containing = worktrees
381    .filter(tree => isInside(cwd, tree.path))
382    .sort((a, b) => b.path.length - a.path.length)
383  const ticket = ticketOf(name)
384
385  return (
386    containing.find(tree => !tree.isMain) ??
387    worktrees.find(
388      tree =>
389        !tree.isMain &&
390        tree.repo === containing[0]?.repo &&
391        ticket !== undefined &&
392        (ticketOf(baseName(tree.path)) ?? ticketOf(tree.branch)) === ticket,
393    ) ??
394    containing[0]
395  )
396}
397
398// a run starts with /ioi-autopilot or the model's Skill call and ends with its final DM (ready,
399// done but not ready, or stopped: "#2447 ready for final human review"), written before it is sent;
400// the skill's own text spells it `#<ticket>`, so a number must follow the #. Runs from before
401// 2026-10-16 ended by moving the ticket to stage:: review, which the skill names in backticks, bare
402// or as `"add_labels=stage:: review"`, so a quote must follow it, and no backtick after that
403const AUTOPILOT_MARKERS =
404  '"(content|text)":"<command-message>ioi-autopilot</command-message>|"name":"Skill","input":\\{"skill":"ioi-autopilot"|#[0-9]+ (ready for final human review|done, not ready for review|needs you)|stage:: review\\\\*"[^`]'
405
406// since 2.1.299 a transcript also keeps copies of its API requests (`api-request-*` lines), which
407// repeat earlier messages out of order: a run's start among them would read as a new run, so the
408// marks on those lines are dropped
409const REQUEST_COPY = '{"type":"api-request-'
410
411// /color appends its choice to the transcript, the last one wins; the effort is the last response's,
412// which /effort changes from the next one on, from the whole transcript, as a tail can hold none
413// (big tool results, or a resume's "No response requested.")
414const COLOR_MARK = '"agentColor":"'
415const EFFORT_MARK = '"effort":"'
416const TRANSCRIPT_MARKS = `^\\${REQUEST_COPY}|${AUTOPILOT_MARKERS}|${COLOR_MARK}[a-z]+"|${EFFORT_MARK}(low|medium|high|xhigh|max)"`
417
418// greps bytes $2..$3 of $1 for $4 once they end a line (else exits 3): a line still being written
419// would split a request copy from its marks, and the next read starts where this one ended
420const GREP_ADDED_BYTES =
421  '[ -z "$(tail -c +"$3" "$1" | head -c 1)" ] || exit 3; ' +
422  'tail -c +"$(($2 + 1))" "$1" | head -c "$(($3 - $2))" | grep -n -o -E "$4" || [ $? -eq 1 ]'
423
424type TranscriptMarks = {
425  offset: number
426  hasAutopilot: boolean
427  isAutopilot: boolean
428  color?: string
429  effort?: string
430}
431
432const NO_MARKS: TranscriptMarks = { offset: 0, hasAutopilot: false, isAutopilot: false }
433
434// ponytail: transcripts grow past 80 MB and each sidebar reads its own every refresh, so only the
435// bytes added since the last read are grepped; the module's own, so a reload reads each once again
436const marksCache = new Map<string, TranscriptMarks>()
437
438const transcriptMarksOf = async (
439  $: EngineInterface,
440  transcript: string,
441): Promise<TranscriptMarks> => {
442  const size = await $.fs
443    .stat(transcript)
444    .then(stat => stat.size)
445    .catch(() => undefined)
446  if (size === undefined) return NO_MARKS
447  const known = marksCache.get(transcript)
448  // a transcript that shrank was rewritten: read it again from the start
449  const from = known !== undefined && known.offset <= size ? known : NO_MARKS
450  if (from.offset === size) return from
451
452  const found = await $.process
453    .run([
454      'sh',
455      '-c',
456      GREP_ADDED_BYTES,
457      'marks',
458      transcript,
459      String(from.offset),
460      String(size),
461      TRANSCRIPT_MARKS,
462    ])
463    .catch(() => undefined)
464  if (found?.exitCode !== 0) return from
465
466  const matches = [...found.stdout.matchAll(/^(\d+):(.*)$/gm)]
467  const copies = new Set(matches.flatMap(([, line, text]) => (text === REQUEST_COPY ? [line] : [])))
468  const lastOf = (mark: string) =>
469    matches.findLast(([, , text]) => text?.startsWith(mark))?.[2]?.split('"')[3]
470  const runMarks = matches.flatMap(([, line, text = '']) =>
471    text === REQUEST_COPY ||
472    copies.has(line) ||
473    text.startsWith(COLOR_MARK) ||
474    text.startsWith(EFFORT_MARK)
475      ? []
476      : [text],
477  )
478  const marks = {
479    offset: size,
480    hasAutopilot: from.hasAutopilot || runMarks.some(mark => mark.includes('ioi-autopilot')),
481    isAutopilot: runMarks.at(-1)?.includes('ioi-autopilot') ?? from.isAutopilot,
482    color: lastOf(COLOR_MARK) ?? from.color,
483    effort: lastOf(EFFORT_MARK) ?? from.effort,
484  }
485  marksCache.set(transcript, marks)
486
487  return marks
488}
489
490// what /color offers; `default` takes the colour away
491const SESSION_COLORS = ['red', 'blue', 'green', 'yellow', 'purple', 'orange', 'pink', 'cyan']
492
493// before its first response, the effort a session started at: CLAUDE_CODE_EFFORT_LEVEL, its
494// --effort, or the one saved for its model, else for every model
495const startingEffortOf = async (
496  $: EngineInterface,
497  { configDir, own, model }: { configDir: string; own: RegisteredSession; model?: string },
498) => {
499  const fromEnv = await $.env.get('CLAUDE_CODE_EFFORT_LEVEL')
500  if (fromEnv !== undefined) return fromEnv
501
502  const args = await $.process
503    .run(['ps', '-ww', '-o', 'args=', '-p', String(own.pid)])
504    .catch(() => undefined)
505  const fromFlag = /--effort[ =](\S+)/.exec(args?.stdout ?? '')?.[1]
506  if (fromFlag !== undefined) return fromFlag
507
508  const settings = await $.fs
509    .read(`${configDir}/settings.json`)
510    .then(
511      text =>
512        JSON.parse(String(text)) as {
513          effortLevel?: string
514          modelSettings?: Record<string, { effortLevel?: string } | undefined>
515        },
516    )
517    .catch(() => undefined)
518
519  // settings key the model without its context-window suffix ([1m])
520  return (
521    settings?.modelSettings?.[(model ?? '').replace(/\[.*\]$/, '')]?.effortLevel ??
522    settings?.effortLevel
523  )
524}
525
526// `model` as /model shows it, `color` as /color set it and `effort` as the last response ran, so
527// another session's sidebar can draw its avatar
528type OwnState = {
529  running: number
530  isAutopilot: boolean
531  hasAutopilot: boolean
532  model?: string
533  color?: string
534  effort?: string
535  cost?: number
536  context?: { percent: number; window: number }
537}
538
539// $.agent.list and the transcript are cheap only to the session itself, so each one publishes its
540// own state for the others' sidebars
541const stateFileOf = (configDir: string, sessionId: string) =>
542  `${configDir}/sessions-sidebar/state/${sessionId}.json`
543
544const readState = ($: EngineInterface, configDir: string, sessionId: string): Promise<OwnState> =>
545  $.fs
546    .read(stateFileOf(configDir, sessionId))
547    .then(text => JSON.parse(String(text)) as Partial<OwnState>)
548    .then(state => ({
549      running: state.running ?? 0,
550      isAutopilot: state.isAutopilot ?? false,
551      hasAutopilot: state.hasAutopilot ?? state.isAutopilot ?? false,
552      model: state.model,
553      color: state.color,
554      effort: state.effort,
555      cost: state.cost,
556      context: state.context,
557    }))
558    .catch(() => ({ running: 0, isAutopilot: false, hasAutopilot: false }))
559
560// $.agent.list leaves out a workflow's agents; like the status line, count those of runs not yet
561// finished (a run writes workflows/<run>.json at its end) that wrote in the last minute
562const WORKFLOW_AGENT_ACTIVE_MS = 60_000
563
564const runningWorkflowAgents = async ($: EngineInterface, sessionDir: string) => {
565  const runsDir = `${sessionDir}/subagents/workflows`
566  const [runs, now] = await Promise.all([$.fs.list(runsDir).catch(() => []), $.clock.now()])
567  const counts = await Promise.all(
568    runs
569      .filter(run => run.kind === 'dir')
570      .map(async run => {
571        if (await $.fs.exists(`${sessionDir}/workflows/${run.name}.json`).catch(() => false)) {
572          return 0
573        }
574        const files = await $.fs.list(`${runsDir}/${run.name}`).catch(() => [])
575
576        return files.filter(
577          file =>
578            /^agent-.+\.jsonl$/.test(file.name) && now - file.mtimeMs <= WORKFLOW_AGENT_ACTIVE_MS,
579        ).length
580      }),
581  )
582
583  return counts.reduce((sum, count) => sum + count, 0)
584}
585
586const publishOwnState = async (
587  $: EngineInterface,
588  configDir: string,
589  own: RegisteredSession | undefined,
590): Promise<OwnState> => {
591  if (own === undefined) return { running: 0, isAutopilot: false, hasAutopilot: false }
592
593  const transcript = transcriptOf(configDir, own)
594  const [agents, workflowAgents, marks, model, usage] = await Promise.all([
595    $.agent.list().catch(() => []),
596    runningWorkflowAgents($, transcript.replace(/\.jsonl$/, '')),
597    transcriptMarksOf($, transcript),
598    $.session.model().catch(() => undefined),
599    $.session.usage().catch(() => undefined),
600  ])
601  // one held on its own background work (a test run) or a plan's approval is still at work
602  const atWork = agents.filter(agent => agent.status === 'running' || agent.status === 'waiting')
603  // a label per agent, as a question's answer is its text
604  const labelled = atWork.map((agent, index) => {
605    const label = `${agent.description} · ${agent.type}`
606    const before = atWork
607      .slice(0, index)
608      .filter(other => `${other.description} · ${other.type}` === label).length
609
610    return { id: agent.id, label: before === 0 ? label : `${label} (${before + 1})` }
611  })
612  if (JSON.stringify(labelled) !== JSON.stringify(await read($, ownAgents))) {
613    await update($, ownAgents, () => labelled)
614  }
615  const usd = usage?.cost?.usd
616  const percent = usage?.context.percent
617  const state = {
618    running: atWork.length + workflowAgents,
619    isAutopilot: marks.isAutopilot,
620    hasAutopilot: marks.hasAutopilot,
621    model,
622    color: SESSION_COLORS.find(known => known === marks.color),
623    effort: marks.effort ?? (await startingEffortOf($, { configDir, own, model })),
624    // to the cent, so the file is rewritten as often as the figure drawn changes
625    cost: usd === undefined ? undefined : Math.round(usd * 100) / 100,
626    // absent until the live window's first response, and again just after a compaction
627    context:
628      usage === undefined || percent === undefined
629        ? undefined
630        : { percent, window: usage.context.window },
631  }
632  const published = await readState($, configDir, own.sessionId)
633  if (JSON.stringify(state) !== JSON.stringify(published)) {
634    await $.fs.write(stateFileOf(configDir, own.sessionId), JSON.stringify(state))
635  }
636
637  return state
638}
639
640// ponytail: grepping every transcript takes ~1 s, so each one is read once per change; a session's
641// own module keeps this, so a long-lived session holds one entry per transcript in the repo
642const transcriptCache = new Map<
643  string,
644  { mtimeMs: number; name?: string; worktree?: string; cost?: number }
645>()
646
647// named sessions not running whose worktree is gone; a session's worktree is the first it worked in
648const loadClosedSessions = async (
649  $: EngineInterface,
650  {
651    folders,
652    worktrees,
653    liveIds,
654    liveNames,
655  }: {
656    // the transcript folders of the repos shown
657    folders: readonly { dir: string; repo: string }[]
658    worktrees: readonly Worktree[]
659    liveIds: ReadonlySet<string>
660    liveNames: ReadonlySet<string | undefined>
661  },
662): Promise<{
663  closed: ClosedRow[]
664  checkout: CheckoutRow[]
665  costOfTicket: ReadonlyMap<string, number>
666  spend: { week: number; repo: number }
667}> => {
668  const transcripts = (
669    await Promise.all(
670      folders.map(async ({ dir, repo }) =>
671        (await $.fs.list(dir).catch(() => []))
672          .filter(entry => entry.kind === 'file' && entry.name.endsWith('.jsonl'))
673          .map(entry => ({
674            path: `${dir}/${entry.name}`,
675            sessionId: entry.name.replace(/\.jsonl$/, ''),
676            mtimeMs: entry.mtimeMs,
677            repo,
678          })),
679      ),
680    )
681  )
682    .flat()
683    .filter(one => !liveIds.has(one.sessionId))
684    .sort((a, b) => b.mtimeMs - a.mtimeMs)
685
686  const stale = transcripts.filter(one => transcriptCache.get(one.path)?.mtimeMs !== one.mtimeMs)
687  const names = await Promise.all(
688    stale.map(one =>
689      $.fs
690        .read(one.path.replace(/\.jsonl$/, '/custom-title.json'))
691        .then(text => (JSON.parse(String(text)) as { customTitle?: string }).customTitle)
692        .catch(() => undefined),
693    ),
694  )
695  // a background session has no title of its own: its job keeps the name it was started with
696  const configDir = await configDirOf($)
697  const jobNames = new Map(
698    (
699      await Promise.all(
700        (await $.fs.list(`${configDir}/jobs`).catch(() => []))
701          .filter(entry => entry.kind === 'dir')
702          .map(entry =>
703            $.fs
704              .read(`${configDir}/jobs/${entry.name}/state.json`)
705              .then(text => JSON.parse(String(text)) as { sessionId?: unknown; name?: unknown })
706              .catch(() => undefined),
707          ),
708      )
709    ).flatMap(job =>
710      typeof job?.sessionId === 'string' && typeof job.name === 'string'
711        ? [[job.sessionId, job.name] as const]
712        : [],
713    ),
714  )
715  const named = stale.filter(
716    (one, index) => (names[index] ?? jobNames.get(one.sessionId)) !== undefined,
717  )
718  const firsts =
719    named.length === 0
720      ? ''
721      : (
722          await $.process
723            .run([
724              'grep',
725              '-o',
726              '-H',
727              '-m',
728              '1',
729              '-E',
730              '"cwd":"[^"]*/\\.claude/worktrees/[^/"]+',
731              ...named.map(one => one.path),
732            ])
733            .catch(() => undefined)
734        )?.stdout
735  // Claude Code saves a session's running /cost total as it goes; the last one is what it cost
736  // every one, named or not, for the footer's totals; the first scan reads them all (~2 s for
737  // 375 transcripts), then only those that changed
738  const costs =
739    stale.length === 0
740      ? ''
741      : (
742          await $.process
743            .run([
744              'grep',
745              '-o',
746              '-H',
747              '-E',
748              '"totalCostUSD":[0-9.eE+-]+',
749              ...stale.map(one => one.path),
750            ])
751            .catch(() => undefined)
752        )?.stdout
753  // a failed grep is retried next refresh rather than cached as "no worktree"
754  if (firsts !== undefined && costs !== undefined) {
755    const firstWorktreeOf = new Map(
756      [...firsts.matchAll(/^(.+?):"cwd":"(.+)$/gm)].map(match => [match[1], match[2]]),
757    )
758    // in file order, so each transcript's last total wins
759    const costOf = new Map(
760      [...costs.matchAll(/^(.+?):"totalCostUSD":(.+)$/gm)].map(match => [
761        match[1],
762        Number(match[2]),
763      ]),
764    )
765    stale.forEach((one, index) =>
766      transcriptCache.set(one.path, {
767        mtimeMs: one.mtimeMs,
768        name: names[index],
769        worktree: firstWorktreeOf.get(one.path),
770        cost: costOf.get(one.path),
771      }),
772    )
773  }
774
775  // by repo and ticket: two repos may each have a 123
776  const ticketsWithWorktree = new Set(
777    worktrees
778      .filter(tree => !tree.isMain)
779      .map(tree => `${tree.repo}#${ticketOf(baseName(tree.path)) ?? ticketOf(tree.branch)}`),
780  )
781  const now = await $.clock.now()
782  const spend = transcripts.reduce(
783    (sum, one) => {
784      const cost = transcriptCache.get(one.path)?.cost ?? 0
785
786      return {
787        week: sum.week + (now - one.mtimeMs <= RECENT_MS ? cost : 0),
788        repo: sum.repo + cost,
789      }
790    },
791    { week: 0, repo: 0 },
792  )
793  const titled = transcripts.flatMap(one => {
794    const { name: title, worktree, cost } = transcriptCache.get(one.path) ?? {}
795    const name = title ?? jobNames.get(one.sessionId)
796    if (name === undefined) return []
797    if (worktree !== undefined && worktrees.some(tree => tree.path === worktree)) return []
798    const ticket = ticketOf(name)
799    // a worktree for its ticket still exists: it shows as live or dormant instead
800    if (ticket !== undefined && ticketsWithWorktree.has(`${one.repo}#${ticket}`)) return []
801
802    return [
803      {
804        sessionId: one.sessionId,
805        name,
806        place: placeOf(worktree ?? one.repo),
807        repo: one.repo,
808        transcript: one.path,
809        hasWorktree: worktree !== undefined,
810        isRecent: now - one.mtimeMs <= RECENT_MS,
811        modifiedAt: one.mtimeMs,
812        cost,
813      },
814    ]
815  })
816  // newest first; a name reused by an older session shows once
817  const unique = titled.filter(
818    (one, index) => titled.findIndex(other => other.name === one.name) === index,
819  )
820
821  return {
822    closed: unique.filter(one => one.hasWorktree).map(({ hasWorktree, ...one }) => one),
823    // one resumed under its old name is live, its new transcript id aside
824    checkout: unique
825      .filter(one => !one.hasWorktree && !liveNames.has(one.name))
826      .map(({ hasWorktree, ...one }) => one),
827    spend,
828    // a dormant worktree's cost: the newest session in its repo titled after its ticket, the one its
829    // ↻ resumes; by `<repo>#<ticket>`
830    costOfTicket: new Map(
831      [...transcripts].reverse().flatMap(one => {
832        const { name, cost } = transcriptCache.get(one.path) ?? {}
833        const ticket = ticketOf(name)
834
835        return ticket === undefined || cost === undefined
836          ? []
837          : [[`${one.repo}#${ticket}`, cost] as const]
838      }),
839    ),
840  }
841}
842
843const loadSessions = async (
844  $: EngineInterface,
845): Promise<{
846  live: SessionRow[]
847  dormant: DormantRow[]
848  closed: ClosedRow[]
849  checkout: CheckoutRow[]
850  cacheExpiresAt?: number
851  spend?: { week: number; repo: number }
852  repos: { selected: string[]; options: RepoOption[] }
853}> => {
854  const configDir = await configDirOf($)
855  const dir = `${configDir}/sessions`
856  const entries = await $.fs.list(dir).catch(() => [])
857  const parsed = await Promise.all(
858    entries
859      .filter(entry => entry.name.endsWith('.json'))
860      .map(entry =>
861        $.fs
862          .read(`${dir}/${entry.name}`)
863          .then(text => JSON.parse(String(text)) as RegisteredSession)
864          .catch(() => undefined),
865      ),
866  )
867  // a script's headless run (the Agent SDK) registers too, inside its parent's tab: not a session
868  // of its own to list or switch to; a background one (claude --bg) is, through `claude attach`
869  const registered = parsed.filter(
870    (one): one is RegisteredSession =>
871      (one?.kind === 'interactive' || one?.kind === 'bg') &&
872      typeof one.pid === 'number' &&
873      !(one.entrypoint ?? 'cli').startsWith('sdk'),
874  )
875  if (registered.length === 0) {
876    return { live: [], dormant: [], closed: [], checkout: [], repos: { selected: [], options: [] } }
877  }
878
879  // ponytail: a crashed session's file stays until its pid is reused; compare procStart if that bites
880  const ps = await $.process
881    .run(['ps', '-o', 'pid=', '-p', registered.map(one => one.pid).join(',')])
882    .catch(() => undefined)
883  const alive = new Set((ps?.stdout ?? '').split(/\s+/).filter(Boolean).map(Number))
884  // this session is always alive, so an empty set means ps could not see anything: keep all
885  const isLivenessKnown = alive.size > 0
886  const live = registered
887    .filter(one => !isLivenessKnown || alive.has(one.pid))
888    .sort((a, b) => a.startedAt - b.startedAt)
889  const [current, tails, folders, saved] = await Promise.all([
890    $.session.id(),
891    Promise.all(live.map(one => tailOf($, configDir, one))),
892    projectFoldersOf($, `${configDir}/projects`),
893    $.fs
894      .read(reposFileOf(configDir))
895      .then((text): unknown => JSON.parse(String(text)))
896      .catch(() => undefined),
897  ])
898  const cwds = live.map((one, index) => currentCwdIn(tails[index] ?? '', one))
899  // a background session runs no sidebar of its own: its model, effort and cost come from its
900  // transcript, its colour from its job, and the session that started it from the transcripts
901  const background = live.filter(one => one.kind === 'bg')
902  const [jobColors, launches] = await Promise.all([
903    Promise.all(
904      background.map(one =>
905        $.fs
906          .read(`${configDir}/jobs/${one.jobId}/state.json`)
907          .then(text => (JSON.parse(String(text)) as { color?: string }).color)
908          .catch(() => undefined),
909      ),
910    ),
911    $.fs
912      .read(launchesFileOf(configDir))
913      .then(text => JSON.parse(String(text)) as Record<string, string>)
914      .catch((): Record<string, string> => ({})),
915  ])
916  // workers started some other way (a script that runs claude --bg) are looked for in transcripts
917  await findLaunchers(
918    $,
919    background.flatMap(one =>
920      one.jobId === undefined || launches[one.jobId] !== undefined ? [] : [one.jobId],
921    ),
922    live.filter(one => one.kind !== 'bg').map(one => transcriptOf(configDir, one)),
923  )
924  const launcherOf = (jobId: string | undefined) =>
925    jobId === undefined
926      ? undefined
927      : live.find(one =>
928          launches[jobId] !== undefined
929            ? one.sessionId === launches[jobId]
930            : transcriptOf(configDir, one) === launcherOfJob.get(jobId),
931        )?.pid
932  const lastIn = (text: string, pattern: RegExp) => [...text.matchAll(pattern)].at(-1)?.[1]
933  // where each was launched and where it works now: a session can move on to another repo
934  const worktreeLists = await Promise.all(
935    [...new Set([...live.map(one => one.cwd), ...cwds])].map(cwd => worktreesOf($, cwd)),
936  )
937  const ownIndex = live.findIndex(one => one.sessionId === current)
938  const ownState = await publishOwnState(
939    $,
940    configDir,
941    live.find(one => one.sessionId === current),
942  )
943  const states = await Promise.all(
944    live.map(one =>
945      one.sessionId === current ? ownState : readState($, configDir, one.sessionId),
946    ),
947  )
948  const worktrees = [...new Map(worktreeLists.flat().map(tree => [tree.path, tree])).values()]
949  const trees = live.map((one, index) => worktreeOf(cwds[index] ?? one.cwd, one.name, worktrees))
950  // a session outside git counts its folder as its repo
951  const rowRepos = live.map((one, index) => trees[index]?.repo ?? cwds[index] ?? one.cwd)
952  const liveRepos = [...new Set([...worktrees.map(tree => tree.repo), ...rowRepos])]
953  // with no choice saved, the repos the live sessions run in
954  const selected = isPathList(saved) ? saved : liveRepos
955  // a live session's own worktrees as they are, so a dormant one is told apart by identity
956  const selectedWorktrees = (
957    await Promise.all(
958      selected.map(repo => {
959        const known = worktrees.filter(tree => tree.repo === repo)
960
961        return known.length > 0 ? known : worktreesOf($, repo)
962      }),
963    )
964  ).flat()
965  const { closed, checkout, costOfTicket, spend } = await loadClosedSessions($, {
966    folders: folders.filter(one => selected.includes(one.repo)),
967    worktrees: selectedWorktrees,
968    liveIds: new Set(live.map(one => one.sessionId)),
969    liveNames: new Set(live.map(one => one.name)),
970  })
971
972  return {
973    closed,
974    checkout,
975    spend,
976    repos: {
977      selected,
978      // the busiest first, then by name
979      options: [...new Set([...liveRepos, ...folders.map(one => one.repo)])]
980        .map(path => ({ path, live: rowRepos.filter(repo => repo === path).length }))
981        .sort((a, b) => b.live - a.live || baseName(a.path).localeCompare(baseName(b.path))),
982    },
983    cacheExpiresAt: ownIndex === -1 ? undefined : cacheExpiryIn(tails[ownIndex] ?? ''),
984    live: live.map((one, index) => {
985      const tree = trees[index]
986      const place = placeOf(tree?.path ?? cwds[index] ?? one.cwd)
987
988      const tail = tails[index] ?? ''
989      const isBackground = one.kind === 'bg'
990      // a background session publishes its state like any other once its own mod has run; until
991      // then its transcript tells
992      const savedCost = isBackground ? lastIn(tail, /"totalCostUSD":([0-9.eE+-]+)/g) : undefined
993
994      return {
995        pid: one.pid,
996        sessionId: one.sessionId,
997        name: one.name ?? place,
998        status: one.status ?? 'idle',
999        place,
1000        branch: tree?.branch,
1001        repo: rowRepos[index] ?? one.cwd,
1002        worktree:
1003          tree === undefined || tree.isMain ? undefined : { path: tree.path, repo: tree.repo },
1004        // a busy session's own loop is an agent at work too
1005        agents: (one.status === 'busy' ? 1 : 0) + (states[index]?.running ?? 0),
1006        // a batch's orchestrator never moves a ticket to review itself: its workers say how it goes
1007        autopilot: !(states[index]?.hasAutopilot ?? false)
1008          ? undefined
1009          : (states[index]?.isAutopilot ?? false) &&
1010              !Object.values(launches).includes(one.sessionId)
1011            ? 'running'
1012            : 'done',
1013        model:
1014          states[index]?.model ??
1015          (isBackground ? lastIn(tail, /"model":"(claude-[^"]+)"/g) : undefined),
1016        color: isBackground ? jobColors[background.indexOf(one)] : states[index]?.color,
1017        effort:
1018          states[index]?.effort ??
1019          (isBackground ? lastIn(tail, /"effort":"(low|medium|high|xhigh|max)"/g) : undefined),
1020        cost:
1021          states[index]?.cost ??
1022          (savedCost === undefined ? undefined : Math.round(Number(savedCost) * 100) / 100),
1023        context: states[index]?.context,
1024        jobId: isBackground ? one.jobId : undefined,
1025        // a worker resumed in a tab runs as a plain session, its job id still its id's first 8
1026        launchedBy: launcherOf(one.jobId ?? one.sessionId.slice(0, 8)),
1027        // Remote Control is on; whether a phone has it open is not told to mods
1028        isRemote: typeof one.bridgeSessionId === 'string',
1029        isCurrent: one.sessionId === current,
1030      }
1031    }),
1032    dormant: selectedWorktrees
1033      .filter(tree => !tree.isMain && !trees.includes(tree))
1034      .map(tree => ({
1035        path: tree.path,
1036        repo: tree.repo,
1037        name: tree.branch ?? baseName(tree.path),
1038        branch: tree.branch,
1039        place: placeOf(tree.path),
1040        cost: costOfTicket.get(
1041          `${tree.repo}#${ticketOf(baseName(tree.path)) ?? ticketOf(tree.branch)}`,
1042        ),
1043      }))
1044      .sort((a, b) => a.name.localeCompare(b.name)),
1045  }
1046}
1047
1048// the collapsed sections, shared so every session's sidebar folds the same way
1049const collapsedFileOf = (configDir: string) => `${configDir}/sessions-sidebar/collapsed.json`
1050
1051// the file maps each section to whether it is folded, so one added later starts as its default;
1052// an older copy is the list of folded sections among the three there were then
1053const collapsedOf = (saved: unknown): Section[] => {
1054  const isFolded: Partial<Record<Section, boolean>> = Array.isArray(saved)
1055    ? {
1056        live: saved.includes('live'),
1057        dormant: saved.includes('dormant'),
1058        closed: saved.includes('closed'),
1059      }
1060    : typeof saved === 'object' && saved !== null
1061      ? saved
1062      : {}
1063
1064  return SECTIONS.filter(section => isFolded[section] ?? IS_COLLAPSED_BY_DEFAULT[section])
1065}
1066
1067// written before the atom, so a refresh reading the file in between cannot fold it back
1068const toggleSection = async ($: EngineInterface, section: Section) => {
1069  const sections = await read($, collapsedSections)
1070  const toggled = sections.includes(section)
1071    ? sections.filter(one => one !== section)
1072    : [...sections, section]
1073  await $.fs.write(
1074    collapsedFileOf(await configDirOf($)),
1075    JSON.stringify(Object.fromEntries(SECTIONS.map(one => [one, toggled.includes(one)]))),
1076  )
1077  await update($, collapsedSections, () => toggled)
1078}
1079
1080const archivedFileOf = (configDir: string) => `${configDir}/sessions-sidebar/archived.json`
1081
1082const detailFileOf = (configDir: string) => `${configDir}/sessions-sidebar/detail.json`
1083
1084// the repos picked, shared by every session's sidebar; absent until the first pick
1085const reposFileOf = (configDir: string) => `${configDir}/sessions-sidebar/repos.json`
1086
1087const isPathList = (value: unknown): value is string[] =>
1088  Array.isArray(value) && value.every(one => typeof one === 'string')
1089
1090const filtersFileOf = (configDir: string) => `${configDir}/sessions-sidebar/filters.json`
1091
1092const setSectionFilter = async ($: EngineInterface, section: Section, filter: KindFilter) => {
1093  const changed = { ...(await read($, sectionFilters)), [section]: filter }
1094  await $.fs.write(filtersFileOf(await configDirOf($)), JSON.stringify(changed))
1095  await update($, sectionFilters, () => changed)
1096}
1097
1098const isKindFilter = (value: unknown): value is KindFilter =>
1099  KIND_FILTERS.some(one => one.id === value)
1100
1101const setDetailLevel = async ($: EngineInterface, level: DetailLevel) => {
1102  await $.fs.write(detailFileOf(await configDirOf($)), JSON.stringify(level))
1103  await update($, detailLevel, () => level)
1104}
1105
1106const setArchived = async (
1107  $: EngineInterface,
1108  sessionIds: readonly string[],
1109  isArchived: boolean,
1110) => {
1111  const ids = await read($, archivedIds)
1112  const others = ids.filter(one => !sessionIds.includes(one))
1113  const changed = isArchived ? [...others, ...sessionIds] : others
1114  await $.fs.write(archivedFileOf(await configDirOf($)), JSON.stringify(changed))
1115  await update($, archivedIds, () => changed)
1116}
1117
1118// 3d 4h, 2h 15m, 38m: a minute's resolution, so the footer redraws at most once a minute
1119const durationText = (ms: number) => {
1120  const minutes = Math.max(0, Math.round(ms / 60_000))
1121  const days = Math.floor(minutes / 1440)
1122  const hours = Math.floor((minutes % 1440) / 60)
1123
1124  return days > 0 ? `${days}d ${hours}h` : hours > 0 ? `${hours}h ${minutes % 60}m` : `${minutes}m`
1125}
1126
1127// the 7d window resets days away, so its weekday and time beat a countdown; `date` formats it in the
1128// local zone like the status line does, once per reset
1129const weekdayTimeOf = new Map<string, Promise<string | undefined>>()
1130
1131const weekdayTime = ($: EngineInterface, resetsAt: string) => {
1132  const known = weekdayTimeOf.get(resetsAt)
1133  if (known !== undefined) return known
1134
1135  const seconds = String(Math.floor(Date.parse(resetsAt) / 1000))
1136  const formatted = $.process
1137    .run(['date', '-r', seconds, '+%a %H:%M'])
1138    .then(ran => (ran.exitCode === 0 && ran.stdout.trim() !== '' ? ran.stdout.trim() : undefined))
1139    .catch(() => undefined)
1140  weekdayTimeOf.set(resetsAt, formatted)
1141
1142  return formatted
1143}
1144
1145// the live sessions as the last refresh saw them, kept only by the session that sends the alerts:
1146// the longest running with a tab of its own, which every sidebar picks alike. Unset until it has
1147// looked once, so a reload or a session newly sending alerts nothing it never saw change
1148let lastSeen: ReadonlyMap<string, SessionRow> | undefined
1149let hasToldNoChannel = false
1150
1151// desktop alerts for what no tab tells of itself: a background session that waits for an answer or
1152// finishes, an autopilot run handed over for review, and a batch none of whose workers runs on.
1153// A tab's own session alerts through Warp
1154const alertChanges = async ($: EngineInterface, live: readonly SessionRow[]) => {
1155  const isSender = live.find(one => one.jobId === undefined)?.isCurrent ?? false
1156  const before = lastSeen
1157  lastSeen = isSender ? new Map(live.map(one => [one.sessionId, one])) : undefined
1158  if (before === undefined) return
1159
1160  const changed = live.flatMap(one => {
1161    const was = before.get(one.sessionId)
1162    if (was === undefined) return []
1163    if (was.autopilot === 'running' && one.autopilot === 'done') {
1164      return [{ title: one.name, text: 'Autopilot done: its ticket went to review' }]
1165    }
1166    if (one.jobId === undefined || was.status === one.status) return []
1167    if (one.status === 'waiting')
1168      return [{ title: one.name, text: 'Waiting for you, in the background' }]
1169    if (was.status === 'busy' && one.status === 'idle') {
1170      return [{ title: one.name, text: 'Finished, in the background' }]
1171    }
1172
1173    return []
1174  })
1175  const isBatchRunning = (rows: Iterable<SessionRow>, launcher: SessionRow) =>
1176    [...rows].some(one => one.launchedBy === launcher.pid && one.autopilot === 'running')
1177  const batches = live.flatMap(launcher =>
1178    before.has(launcher.sessionId) &&
1179    isBatchRunning(before.values(), launcher) &&
1180    !isBatchRunning(live, launcher)
1181      ? [{ title: launcher.name, text: 'Autopilot batch done' }]
1182      : [],
1183  )
1184  for (const alert of [...changed, ...batches]) {
1185    const sent = await $.ui.notify(alert.text, { title: alert.title }).catch(() => undefined)
1186    if (sent?.isSent === false && sent.reason === 'no-channel' && !hasToldNoChannel) {
1187      hasToldNoChannel = true
1188      $.ui.toast('Session alerts need a channel: /config, Notifications, iTerm2 (Warp shows those)')
1189    }
1190  }
1191}
1192
1193const refresh = async ($: EngineInterface) => {
1194  const configDir = await configDirOf($)
1195  const [
1196    { live, dormant, closed, checkout, cacheExpiresAt, spend, repos },
1197    collapsed,
1198    archived,
1199    detail,
1200    filters,
types/index.d.ts 107 lines
1export type SessionRow = {
2  pid: number
3  sessionId: string
4  name: string
5  status: string
6  place: string
7  branch?: string
8  // the main checkout of the repo it works in; outside git, its folder
9  repo: string
10  // the linked worktree it works in, and the repo that owns it; absent in the main checkout
11  worktree?: { path: string; repo: string }
12  agents: number
13  // a session that ran ioi-autopilot: `running` until its run hands over for review (a batch
14  // until its workers do), `done` after
15  autopilot?: 'running' | 'done'
16  // the main loop's model, as /model shows it
17  model?: string
18  // the session's colour as /color set it; absent when it has none
19  color?: string
20  // the effort its last response ran at; absent before its first
21  effort?: string
22  // what it has cost so far in US dollars, as /cost totals it
23  cost?: number
24  // how full its context window is, as the status line reads it; absent before its first response
25  context?: { percent: number; window: number }
26  // Remote Control is on
27  isRemote: boolean
28  // a background session's (claude --bg) id; it has no tab, `claude attach` opens it
29  jobId?: string
30  // the live session that started it, by pid, when its transcript shows the launch
31  launchedBy?: number
32  isCurrent: boolean
33}
34
35export type DormantRow = {
36  path: string
37  repo: string
38  name: string
39  branch?: string
40  place: string
41  // what the session titled after its ticket last saved as its cost, in US dollars
42  cost?: number
43}
44
45// how much each live session shows: its name line alone; with worktree, branch and context; with all
46export type DetailLevel = 'compact' | 'standard' | 'full'
47
48export type Section = 'live' | 'dormant' | 'closed'
49
50// what a section lists: both kinds, those with a worktree only, or the ad hoc ones only
51export type KindFilter = 'all' | 'worktrees' | 'adhoc'
52
53// a repo there are sessions of, by its main checkout's path, with how many run in it now
54export type RepoOption = { path: string; live: number }
55
56export type ClosedRow = {
57  sessionId: string
58  name: string
59  place: string
60  repo: string
61  transcript: string
62  // what it last saved as its cost, in US dollars
63  cost?: number
64  // used in the last week
65  isRecent: boolean
66  modifiedAt: number
67}
68
69// a named session that only ever worked in its repo's main checkout, now not running
70export type CheckoutRow = ClosedRow
71
72declare module 'claude-code' {
73  interface PluginState {
74    'sessions-sidebar': {
75      rows: SessionRow[]
76      dormant: DormantRow[]
77      closed: ClosedRow[]
78      checkout: CheckoutRow[]
79      collapsed: Section[]
80      archived: string[]
81      offset: number
82      pulse: boolean
83      usage: {
84        limits: { label: string; percent: number; resetsIn?: string }[]
85        cache?: { isWarm: boolean; left: string }
86        // what every session not running saved as its cost: those used in the last week, and all
87        spend?: { week: number; repo: number }
88      }
89      question: { key: string; text: string; options: string[] } | null
90      olderSearch: string
91      searches: Partial<Record<Section, string>>
92      detail: DetailLevel
93      filters: Partial<Record<Section, KindFilter>>
94      newSession: {
95        defaultModel?: string
96        // each model's saved effort, by its --model alias
97        saved: Record<string, string | undefined>
98        effort?: string
99      } | null
100      repos: { selected: string[]; options: RepoOption[] }
101      repoSearch: string
102      // this session's own agents at work, by $.agent.list()'s id, each label told apart
103      agents: { id: string; label: string }[]
104    }
105  }
106}
107