SLOPSHOPPER

pr-pane

Sessions of this project, their worktrees and PRs, with check-ins, in a side pane.

panecommandtoastprocesstimer
★ 8v0.1.3MITupdated 2026-10-14Nongfsq/frank-claude-cockpit/pr-pane
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · pr-pane
│ ┃ pr-pane ✕ › fix the failing auth test and add an audit log call │ ┃ Session list unavailable: undefined is not │ ┃ an object (evaluating ⏺ Read(src/auth.ts) │ ┃ 'result.content.find') ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ r: ↻ refresh ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /sessions │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · pr-pane
Session list unavailable: undefined is not an object (evaluating 'result.content.find') r: ↻ refresh
README

Claude Code Cockpit

Two mods for Claude Code for people who run many sessions at once: one line above the prompt that tells you what this session is costing, and one pane beside the chat that tells you what every other session is doing.

<img src="docs/demo-light.gif" alt="A walkthrough: click the bar to see the context breakdown, click PRs to open the sessions pane, open a session, ask about it, ask about everything in flight, ask about the done ones while Claude is still replying, unfold them.">

Unofficial. Not affiliated with Anthropic.

What you get

context-card: one line above the prompt

<img src="docs/card-light.png" alt="The context card with its breakdown open.">

On the lineMeaning
27% 272.3k / 1MHow full the context window is. Turns amber at 60%, red at 80%.
● ◐ ○The prompt cache: fresh, past half its life, expired. Sending a message on an expired cache re-reads the whole context at full price.
The thin barThe same percentage, colored by what is using it.
weekly 20% ↻ 4d 21hYour plan's weekly usage and when it resets, read live from your account.
PRsOpens the sessions pane. A number beside it counts sessions waiting on you.

Click anywhere on the line to open the breakdown (messages, tools, MCP, skills, system, memory), the cache's minutes left, and where auto-compact will run. Click again to close it.

pr-pane: the sessions pane

<img src="docs/sessions-light.png" alt="The sessions pane docked beside the chat.">

Every session in the same sidebar group, sorted by what it needs from you:

SectionWhat is in it
Needs youCI failing, conflicts, changes requested, ready to merge, or idle with nothing to show.
WorkingSessions running right now.
DoneMerged or closed. Folded until you click the heading; its Ask works either way.
Loose worktreesWorktrees no session holds, and whether they have uncommitted changes.

Each row has one time, on the right: how long it has been in the state its status names (working for 47m, merged 2h ago).

ControlWhat it does
Click a sessionShows its worktree, branch, PR and activity.
Ask hereAsks, in the session you are in, for that session's status. Claude reads the other session's transcript and checks its PR; the other session is not messaged or interrupted.
Ask N workingThe same, for every session that is running; with none running, Ask N open asks about every unfinished one.
Ask on the Done headingAsks what the finished sessions changed, how they ended, and what they left to follow up.
#45, PR ↗Opens the pull request on GitHub.
↻Refreshes now. The pane also refreshes itself every 15 seconds.
A section headingFolds or unfolds the section.

An Ask pressed while Claude is still replying in your session waits on a line under the header, After this turn: ask about …, with Cancel, and is sent when the reply ends. One waits at a time: pressing Ask again replaces it.

Outside any project, the pane shows every project's sessions as one overview.

Install

Both mods together, from this repository:

/plugin marketplace add Nongfsq/frank-claude-cockpit
/plugin install context-card@frank-claude-cockpit
/plugin install pr-pane@frank-claude-cockpit

Or copy the two folders into ~/.claude/skills/ and start a new session:

git clone https://github.com/Nongfsq/frank-claude-cockpit
cp -R frank-claude-cockpit/context-card frank-claude-cockpit/pr-pane ~/.claude/skills/

Install both: the PRs button lives in context-card and appears only when pr-pane is present.

Requirements

  • A recent Claude Code. These mods use the hooks-module API (ui.render, $.state); they were built and tested on 2.1.286.
  • context-card's weekly usage needs a Claude subscription login. With an API key the card still shows context, without the weekly figure.
  • pr-pane needs the Claude desktop app, which is where the session list comes from; in a plain terminal it says the list is unavailable. PR and CI state come from the gh CLI, logged in.

What leaves your machine

  • context-card asks api.anthropic.com for your own plan usage with the login Claude Code already holds, at most once every two minutes however many sessions are open: one session asks and the rest read its answer from ~/.claude/cache/context-card-usage.json. That request uses no tokens.
  • pr-pane runs git and gh locally, in the project's folder.
  • Each Ask sends one prompt in your current session, so it costs what a prompt costs there.

Nothing else is sent anywhere.

Development

claude plugin validate context-card
claude plugin test context-card
claude plugin test pr-pane

Types for an editor: run /plugin-types inside a mod's folder.

The demo above is a scripted page, docs/demo/index.html; open it in a browser to watch it loop, or add ?theme=light. To re-record it, both themes, as GIF and MP4, with the sessions screenshot cropped from the last frame:

cd docs/demo && npm i puppeteer-core
for theme in dark light; do
  rm -rf frames && node record.mjs frames $theme 15
  ffmpeg -y -framerate 15 -i frames/f%04d.png -vf "scale=1200:-1:flags=lanczos,split[a][b];[a]palettegen=max_colors=128:stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle" ../demo-$theme.gif
  ffmpeg -y -framerate 15 -i frames/f%04d.png -vf "scale=1800:-2:flags=lanczos" -c:v libx264 -pix_fmt yuv420p -crf 23 -movflags +faststart ../demo-$theme.mp4
  ffmpeg -y -i frames/$(ls frames | tail -1) -vf "crop=2280:1240:60:36" ../sessions-$theme.png
done
rm -rf frames

Support

If this project is useful to you, you can buy me a coffee.

<a href="https://buymeacoffee.com/frankmenger"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me a Coffee" height="44"></a>

License

MIT

Source 2 files
hooks/register.tsx 629 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Board, Kind, Loose, Report, Row } from '../types'
5
6const PANE = 'pr-pane'
7const TITLE = 'Sessions'
8const SERVER = 'ccd_session_mgmt'
9const POLL_MS = 15_000
10const PULLS_MS = 120_000
11const DONE_LIMIT = 8
12
13const board = atom({ plugin: 'pr-pane', key: 'board' } as const, null)
14const error = atom({ plugin: 'pr-pane', key: 'error' } as const, null)
15const isLoading = atom({ plugin: 'pr-pane', key: 'isLoading' } as const, false)
16const attention = atom({ plugin: 'pr-pane', key: 'attention' } as const, 0)
17const reports = atom({ plugin: 'pr-pane', key: 'reports' } as const, {})
18const checkedAt = atom({ plugin: 'pr-pane', key: 'checkedAt' } as const, 0)
19const expanded = atom({ plugin: 'pr-pane', key: 'expanded' } as const, [])
20// When each running session was first seen running, so a row can say how long its current run has lasted.
21const runs = atom({ plugin: 'pr-pane', key: 'runs' } as const, {})
22const openSections = atom({ plugin: 'pr-pane', key: 'openSections' } as const, ['needs', 'working'])
23const queuedAsk = atom({ plugin: 'pr-pane', key: 'queuedAsk' } as const, null)
24
25// Theme keys, so both themes stay legible. Color means attention; merged gets the theme's own merged hue.
26const TONES: Record<Kind, string | undefined> = {
27  ready: 'success',
28  waiting: 'warning',
29  fix: 'error',
30  working: 'suggestion',
31  merged: 'merged',
32  closed: undefined,
33}
34const NEEDS: Kind[] = ['fix', 'ready', 'waiting']
35
36type Session = {
37  sessionId: string
38  title: string
39  cwd: string
40  branch?: string
41  isRunning: boolean
42  prNumber?: number
43  prState?: 'OPEN' | 'MERGED' | 'CLOSED'
44  lastActivityAt: string
45  group?: { id: string; name: string } | null
46}
47
48type OpenPull = {
49  number: number
50  isDraft: boolean
51  reviewDecision: string
52  mergeable: string
53  url: string
54  statusCheckRollup: { conclusion?: string; status?: string; state?: string }[]
55}
56
57const FAILED = ['FAILURE', 'ERROR', 'CANCELLED', 'TIMED_OUT', 'ACTION_REQUIRED', 'STARTUP_FAILURE']
58
59const checksOf = (rollup: OpenPull['statusCheckRollup']) => {
60  if (rollup.some(c => FAILED.includes(c.conclusion ?? '') || FAILED.includes(c.state ?? ''))) return 'fail'
61  if (rollup.some(c => (c.status !== undefined && c.status !== 'COMPLETED') || c.state === 'PENDING')) return 'pending'
62
63  return 'pass'
64}
65
66// Lifts a task id out of an AI-written title: "Fix TASK-183: unify recovery" → TASK-183, "unify recovery".
67const splitTitle = (title: string) => {
68  const match = title.match(/^(?:\S+\s+){0,3}?([A-Z][A-Z0-9]+-\d+)\s*[::\-–]?\s*(.+)$/)
69
70  return match ? { tag: match[1]!, name: match[2]! } : { tag: '', name: title }
71}
72
73const kindOf = (s: Session, pull: OpenPull | undefined): { kind: Kind; status: string } => {
74  if (s.prState === 'MERGED') return { kind: 'merged', status: 'merged' }
75  if (s.prState === 'CLOSED') return { kind: 'closed', status: 'closed' }
76
77  const checks = pull === undefined ? 'pass' : checksOf(pull.statusCheckRollup ?? [])
78
79  if (s.isRunning) return { kind: 'working', status: checks === 'pending' ? 'working · CI running' : 'working' }
80  if (s.prState !== 'OPEN') return { kind: 'waiting', status: 'no report yet' }
81  if (pull === undefined) return { kind: 'waiting', status: 'PR open' }
82  if (checks === 'fail') return { kind: 'fix', status: 'CI failing' }
83  if (pull.mergeable === 'CONFLICTING') return { kind: 'fix', status: 'conflicts' }
84  if (pull.reviewDecision === 'CHANGES_REQUESTED') return { kind: 'fix', status: 'changes requested' }
85  if (pull.isDraft) return { kind: 'waiting', status: 'draft' }
86  if (checks === 'pending') return { kind: 'working', status: 'CI running' }
87  if (pull.reviewDecision === 'REVIEW_REQUIRED') return { kind: 'waiting', status: 'needs review' }
88
89  return { kind: 'ready', status: 'ready to merge' }
90}
91
92const ago = (ms: number) => {
93  const seconds = Math.max(0, Math.round(ms / 1000))
94
95  if (seconds < 60) return `${seconds}s`
96  if (seconds < 3600) return `${Math.floor(seconds / 60)}m`
97  if (seconds < 86_400) return `${Math.floor(seconds / 3600)}h`
98
99  return `${Math.floor(seconds / 86_400)}d`
100}
101
102const cut = (text: string, max: number) => (text.length > max ? `${text.slice(0, Math.max(1, max - 1))}…` : text)
103const basename = (path: string) => path.replace(/\/+$/, '').split('/').pop() ?? path
104
105const mcpJson = async ($: EngineInterface, tool: string, args: Record<string, unknown>) => {
106  const result = await $.mcp.call(SERVER, tool, args)
107  const text = result.content.find(block => block.type === 'text')?.text ?? ''
108
109  if (result.isError) {
110    throw new Error(text.split('\n')[0] || `${tool} failed`)
111  }
112
113  // An empty list comes back as a sentence ("No other sessions found in group ..."), not as `[]`.
114  if (tool === 'list_sessions' && !text.trimStart().startsWith('[')) {
115    return []
116  }
117
118  return JSON.parse(text) as unknown
119}
120
121const run = async ($: EngineInterface, argv: string[], cwd?: string) => {
122  const result = await $.process.run(argv, { cwd, timeoutMs: 20_000 })
123
124  return { ok: result.exitCode === 0, out: result.stdout.trim() }
125}
126
127let ghPath: string | null = null
128
129// gh may be off the host's PATH; fall back to Homebrew's location.
130const gh = async ($: EngineInterface, args: string[], cwd: string) => {
131  for (const candidate of ghPath === null ? ['gh', '/opt/homebrew/bin/gh', '/usr/local/bin/gh'] : [ghPath]) {
132    try {
133      const result = await run($, [candidate, ...args], cwd)
134      ghPath = candidate
135
136      return result
137    } catch {
138      continue
139    }
140  }
141
142  return { ok: false, out: '' }
143}
144
145let pulls = new Map<number, OpenPull>()
146let repoName = ''
147let pullsAt = 0
148
149const refreshPulls = async ($: EngineInterface, root: string, now: number) => {
150  const [repo, list] = await Promise.all([
151    gh($, ['repo', 'view', '--json', 'nameWithOwner', '-q', '.nameWithOwner'], root),
152    gh($, ['pr', 'list', '--state', 'open', '--limit', '50', '--json', 'number,isDraft,reviewDecision,mergeable,statusCheckRollup,url'], root),
153  ])
154
155  repoName = repo.ok ? repo.out : repoName
156  pulls = list.ok ? new Map((JSON.parse(list.out) as OpenPull[]).map(p => [p.number, p] as const)) : pulls
157  pullsAt = now
158}
159
160const looseWorktrees = async ($: EngineInterface, root: string, taken: Set<string>): Promise<Loose[]> => {
161  const listed = await run($, ['git', 'worktree', 'list', '--porcelain'], root)
162
163  if (!listed.ok) {
164    return []
165  }
166
167  const paths = listed.out
168    .split('\n\n')
169    .filter(block => !block.includes('\nprunable'))
170    .map(block => block.split('\n').find(line => line.startsWith('worktree '))?.slice(9) ?? '')
171    .filter(path => path.startsWith(`${root}/`) && !taken.has(path))
172    .slice(0, 10)
173
174  const found = await Promise.all(
175    paths.map(async path => {
176      const status = await run($, ['git', '-C', path, 'status', '--porcelain']).catch(() => null)
177
178      return status?.ok ? { path, name: basename(path), dirty: status.out === '' ? 0 : status.out.split('\n').length } : null
179    }),
180  )
181
182  return found.filter((tree): tree is Loose => tree !== null)
183}
184
185const refresh = async ($: EngineInterface, force = false) => {
186  if (await read($, isLoading)) {
187    return
188  }
189
190  await update($, isLoading, () => true)
191
192  try {
193    const me = (await mcpJson($, 'get_session', { session_id: 'self' })) as Session
194    const group = me.group ?? null
195    const listed = (await mcpJson($, 'list_sessions', group === null ? { limit: 50 } : { group: group.id, limit: 50 })) as Session[]
196    const common = await run($, ['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'], me.cwd)
197    const root = common.ok ? common.out.replace(/\/\.git$/, '') : ''
198    // Outside any project (no group, no repo) the pane is an overview of every project's sessions.
199    const isOverview = group === null && root === ''
200    const sessions = isOverview ? listed : group === null ? listed.filter(s => s.cwd.startsWith(root)) : listed
201    const now = await $.clock.now()
202
203    if (root !== '' && (force || now - pullsAt >= PULLS_MS)) {
204      await refreshPulls($, root, now)
205    }
206
207    const seen: Record<string, number> = await read($, runs)
208    const running = Object.fromEntries(sessions.filter(s => s.isRunning).map(s => [s.sessionId, seen[s.sessionId] ?? now]))
209    await update($, runs, () => running)
210
211    const rows: Row[] = sessions.map(s => {
212      const pull = s.prNumber === undefined ? undefined : pulls.get(s.prNumber)
213      const { tag, name } = splitTitle(s.title)
214
215      return {
216        id: s.sessionId,
217        tag,
218        name,
219        worktree: basename(s.cwd),
220        branch: s.branch ?? '',
221        ...kindOf(s, pull),
222        pr: s.prNumber ?? 0,
223        prUrl: pull?.url ?? (s.prNumber !== undefined && repoName !== '' ? `https://github.com/${repoName}/pull/${s.prNumber}` : ''),
224        isRunning: s.isRunning,
225        lastActivityAt: s.lastActivityAt,
226        since: running[s.sessionId] ?? Date.parse(s.lastActivityAt),
227        project: isOverview ? (s.group?.name ?? basename(s.cwd.split('/.claude/worktrees/')[0] ?? s.cwd)) : '',
228      }
229    })
230
231    const taken = new Set([me.cwd, ...sessions.map(s => s.cwd)])
232    const loose = root === '' ? [] : await looseWorktrees($, root, taken)
233    const next: Board = {
234      group: isOverview ? 'All projects' : (group?.name ?? basename(root)),
235      me: { id: me.sessionId, title: me.title },
236      rows,
237      loose,
238      at: now,
239    }
240
241    await update($, board, () => next)
242    await update($, attention, () => rows.filter(row => NEEDS.includes(row.kind)).length)
243    await update($, error, () => null)
244  } catch (cause) {
245    await update($, error, () => `Session list unavailable: ${cause instanceof Error ? cause.message : String(cause)}`)
246  } finally {
247    await update($, isLoading, () => false)
248  }
249}
250
251const isDone = (row: Row) => row.kind === 'merged' || row.kind === 'closed'
252
253// Whether this session's own turn is running, set by the turn hooks below. The engine holds a plugin's prompt
254// until the turn ends and shows nothing meanwhile, so an Ask pressed then is held in the pane instead, in view
255// and cancellable, one at a time, and sent when the turn ends.
256let isTurnRunning = false
257
258// Asks about other sessions in this one: the prompt lands in this session's own chat, and Claude reads their
259// transcripts to answer, so the sessions asked about are not interrupted.
260const askHere = async ($: EngineInterface, rows: Row[]) => {
261  if (rows.length === 0) {
262    return
263  }
264
265  const list = rows.map(row => `- "${row.tag === '' ? row.name : `${row.tag} ${row.name}`}" (session ${row.id}${row.pr > 0 ? `, PR #${row.pr}` : ''})`)
266  // Finished sessions have no progress to report: the question about them is what they left behind.
267  const isFinished = rows.every(isDone)
268  const text =
269    `Report ${isFinished ? 'the outcome' : 'the status'} of ${rows.length === 1 ? 'this session' : 'these sessions'} without messaging ${rows.length === 1 ? 'it' : 'them'}: ` +
270    `read each one's recent transcript with the ccd_session_mgmt list_events tool, and check its PR${isFinished ? '' : ' and CI'} if it has one.\n` +
271    `${list.join('\n')}\n` +
272    (isFinished
273      ? `For each, in one or two lines: what it changed, how it ended (merged or closed), and anything it left to follow up.`
274      : `For each, in one or two lines: what it is doing now, how far along it is, any blocker, and whether it is ready to merge.`)
275
276  const label = rows.length === 1 ? rows[0]!.name : `${rows.length} sessions`
277
278  if (isTurnRunning) {
279    await update($, queuedAsk, () => ({ text, label }))
280
281    return
282  }
283
284  await send($, text)
285}
286
287const send = async ($: EngineInterface, text: string) => {
288  const now = await $.clock.now()
289  await update($, checkedAt, () => now)
290
291  try {
292    const sent = await $.prompt.submit({ text, asUser: true })
293
294    if (sent.drop !== undefined) $.ui.toast(`Ask was not sent: ${sent.drop}`)
295  } catch (cause) {
296    $.ui.toast(`Ask failed: ${cause instanceof Error ? cause.message : String(cause)}`)
297  }
298}
299
300// The sessions worth asking about: the ones working now, or failing that the unfinished idle ones.
301const askable = (rows: Row[]) => {
302  const working = rows.filter(row => row.kind === 'working')
303
304  return working.length > 0 ? working : rows.filter(row => !isDone(row))
305}
306
307const checkIn = async ($: EngineInterface) => {
308  const data = await read($, board)
309
310  if (data !== null) {
311    await askHere($, askable(data.rows))
312  }
313}
314
315const toggleRow = async ($: EngineInterface, id: string) =>
316  update($, expanded, was => (was.includes(id) ? was.filter(one => one !== id) : [...was, id]))
317
318const toggleSection = async ($: EngineInterface, id: string) =>
319  update($, openSections, was => (was.includes(id) ? was.filter(one => one !== id) : [...was, id]))
320
321// Toggles the pane: the context card's Sessions button and a typed /sessions both land here.
322const togglePane = async ($: EngineInterface) => {
323  const panes = await $.ui.panes()
324
325  if (panes.some(pane => pane.id === PANE && pane.isPlaced)) {
326    await $.ui.close({ id: PANE })
327
328    return
329  }
330
331  const opened = await $.ui.open({ id: PANE, title: TITLE })
332
333  if (!opened.isPlaced) $.ui.toast(`Sessions pane did not open: ${opened.reason ?? 'no reason given'}`)
334
335  await refresh($, true)
336}
337
338/** Runs the toggle, and says why on screen when it fails rather than doing nothing. */
339const pressPane = async ($: EngineInterface) => {
340  try {
341    await togglePane($)
342  } catch (cause) {
343    $.ui.toast(`Sessions pane failed: ${cause instanceof Error ? cause.message : String(cause)}`)
344  }
345}
346
347export const register: Register = on => {
348  let ticker: { cancel: () => void } | null = null
349
350  on('session.start', async ($, e, next) => {
351    await $.command.register({ name: 'sessions', description: 'Show the sessions of this project and what each needs' })
352    await $.command.register({ name: 'prs', description: 'Same as /sessions' })
353    await refresh($, true)
354    ticker?.cancel()
355    ticker = $.clock.every(POLL_MS, () => void refresh($))
356
357    return next(e)
358  })
359
360  on('session.end', ($, e, next) => {
361    ticker?.cancel()
362    ticker = null
363
364    return next(e)
365  })
366
367  on('turn.start', ($, e, next) => {
368    isTurnRunning = true
369
370    return next(e)
371  })
372
373  on('turn.complete', async ($, e, next) => {
374    if (e.agentId === undefined) {
375      isTurnRunning = false
376      void refresh($)
377      const held = await read($, queuedAsk)
378
379      if (held !== null) {
380        await update($, queuedAsk, () => null)
381        void send($, held.text)
382      }
383    }
384
385    return next(e)
386  })
387
388  // A report a check-in asked for: keep its first line beside the session it names.
389  on('session.receive', async ($, e, next) => {
390    const match = e.text.match(/\[status (local_[A-Za-z0-9-]+)\]\s*([^\n]*)/)
391
392    if (match !== null) {
393      const now = await $.clock.now()
394      const id = match[1]!
395      const reply = cut(match[2]!.trim(), 200)
396      await update($, reports, was => ({ ...was, [id]: { askedAt: was[id]?.askedAt ?? now, reply, repliedAt: now } }))
397    }
398
399    return next(e)
400  })
401
402  on('command.run', { command: 'sessions' }, async $ => {
403    await pressPane($)
404
405    return {}
406  })
407
408  // The context card's PRs button: it counts its presses in its own state, and each write toggles the pane.
409  on('state.set', { plugin: 'context-card', key: 'paneAsk' }, async ($, e, next) => {
410    const result = await next(e)
411    void pressPane($)
412
413    return result
414  })
415
416  on('command.run', { command: 'prs' }, async $ => {
417    await pressPane($)
418
419    return {}
420  })
421
422  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
423    const { Box, Button, Link, Text } = $.ui.resolve(e)
424    const now = await $.clock.now()
425    const data = await read($, board)
426    const problem = await read($, error)
427    const traces: Record<string, Report> = await read($, reports)
428    const asked = await read($, checkedAt)
429    const open: string[] = await read($, expanded)
430    const sections: string[] = await read($, openSections)
431    const held = await read($, queuedAsk)
432    const columns = e.props.bodyColumns ?? 60
433    const isNarrow = columns < 44
434    const isDesktop = e.surface === 'desktop'
435    // The grid every line sits on: a mark column, then a tag column that the detail labels share, then the text.
436    // A cell is about one monospace character on both surfaces; desktop's proportional text runs narrower than
437    // its cell count, so its tag column needs one cell less of gap than the terminal's.
438    const MARK = 2
439    const longestTag = Math.max(0, ...(data?.rows ?? []).map(row => row.tag.length))
440    const tagColumn = isDesktop ? Math.max(9, longestTag + 1) : Math.max(10, longestTag + 2)
441    const hasTags = !isNarrow && longestTag > 0
442    const titleRoom = Math.max(12, columns - MARK - (hasTags ? tagColumn : 0) - 6)
443    const keys = (hotkey: string) => (isDesktop ? {} : { hotkey })
444
445    // Desktop: a label-less control laid over a whole line, so a click anywhere on it presses, with no hover block.
446    const cover = (key: string, onPress: () => void) => (
447      <Box position="absolute" top={0} left={0} right={0} bottom={0} overflow="hidden">
448        {/* Wider than any line, so the overlay clips the control and its label is never cut with an ellipsis. */}
449        <Box width={1200} flexShrink={0}>
450          <Button key={key} plain label={'\u00A0'.repeat(600)} hover={{ backgroundColor: '#00000000' }} onPress={onPress} />
451        </Box>
452      </Box>
453    )
454
455    if (data === null) {
456      return (
457        <Box flexDirection="column" rowGap={1} paddingX={1}>
458          <Text dimColor>{problem ?? 'Loading sessions…'}</Text>
459          <Button key="refresh" plain {...(e.surface === 'desktop' ? {} : { hotkey: 'r' })} label="↻ refresh" onPress={() => void refresh($, true)} />
460        </Box>
461      )
462    }
463
464    const needs = data.rows.filter(row => NEEDS.includes(row.kind)).sort((a, b) => NEEDS.indexOf(a.kind) - NEEDS.indexOf(b.kind))
465    const working = data.rows.filter(row => row.kind === 'working')
466    const done = data.rows.filter(isDone).slice(0, DONE_LIMIT)
467    const targets = askable(data.rows)
468    const targetLabel = `${targets.length} ${targets.some(row => row.kind === 'working') ? 'working' : 'open'}`
469
470    const sessionRow = (row: Row) => {
471      const isOpen = open.includes(row.id)
472      const trace = traces[row.id]
473      const hasReply = trace !== undefined && trace.repliedAt > 0
474      const tone = TONES[row.kind]
475      // One time per row, always how long it has been in the state its status names.
476      const age = ago(now - row.since)
477      const quiet = now - Date.parse(row.lastActivityAt)
478      const toggle = () => void toggleRow($, row.id)
479
480      return (
481        <Box key={`row-${row.id}`} flexDirection="column" marginBottom={isOpen ? 1 : 0}>
482          <Box key={`head-${row.id}`} flexDirection="row" position="relative">
483            <Box width={MARK} flexShrink={0}>
484              <Text color={tone} dimColor={tone === undefined}>
485                {row.kind === 'working' ? '◐' : '●'}
486              </Text>
487            </Box>
488            {hasTags && row.tag !== '' ? (
489              <Box width={tagColumn} flexShrink={0}>
490                <Text dimColor>{row.tag}</Text>
491              </Box>
492            ) : null}
493            {isDesktop ? (
494              <Text bold={isOpen} wrap="truncate-end">
495                {row.name}
496              </Text>
497            ) : (
498              <Button key={`title-${row.id}`} plain label={cut(row.name, titleRoom)} onPress={toggle} />
499            )}
500            <Box flexGrow={1} />
501            <Text dimColor>{age}</Text>
502            {isDesktop ? cover(`title-${row.id}`, toggle) : null}
503          </Box>
504          <Box flexDirection="row" columnGap={2} paddingLeft={MARK}>
505            <Text color={tone} dimColor={tone === undefined} wrap="truncate-end">
506              {row.status}
507            </Text>
508            {row.pr > 0 && row.prUrl !== '' ? <Link href={row.prUrl} label={`#${row.pr}`} /> : null}
509            {row.pr > 0 && row.prUrl === '' ? <Text dimColor>{`#${row.pr}`}</Text> : null}
510            <Box flexGrow={1} />
511            {row.project === '' ? null : <Text dimColor wrap="truncate-end">{row.project}</Text>}
512          </Box>
513          {hasReply ? (
514            <Box flexDirection="row" paddingLeft={MARK}>
515              <Box width={2} flexShrink={0}>
516                <Text color="success">↩</Text>
517              </Box>
518              <Text wrap="truncate-end">{trace.reply}</Text>
519              <Box flexGrow={1} />
520              <Text dimColor>{ago(now - trace.repliedAt)}</Text>
521            </Box>
522          ) : null}
523          {isOpen ? (
524            <Box flexDirection="column" rowGap={1} paddingLeft={MARK} marginTop={1}>
525              <Box flexDirection="column">
526                {[
527                  ['worktree', row.worktree],
528                  ['branch', row.branch],
529                  ['PR', row.pr > 0 ? `#${row.pr} · ${row.status}` : 'none yet'],
530                  ['activity', row.isRunning ? `working ${age}${quiet >= 60_000 ? ` · quiet ${ago(quiet)}` : ''}` : `idle ${age}`],
531                ].map(([label, value]) => (
532                  <Box key={`${row.id}-${label}`} flexDirection="row">
533                    <Box width={tagColumn} flexShrink={0}>
534                      <Text dimColor>{label}</Text>
535                    </Box>
536                    <Text wrap="truncate-end">{value}</Text>
537                  </Box>
538                ))}
539              </Box>
540              <Box flexDirection="row" columnGap={2}>
541                <Button key={`ask-${row.id}`} variant="secondary" label="Ask here" onPress={() => void askHere($, [row])} />
542                {row.prUrl === '' ? null : <Link href={row.prUrl} label="PR ↗" />}
543              </Box>
544            </Box>
545          ) : null}
546        </Box>
547      )
548    }
549
550    // A section's heading is its own switch: bold while open, dim while folded, and no arrow.
551    // `ask` puts a control at the end of the heading, outside the heading's own switch so each presses alone.
552    const section = (id: string, label: string, n: number, body: () => unknown, ask?: () => void) => {
553      const isOpen = sections.includes(id)
554      const toggle = () => void toggleSection($, id)
555
556      return n === 0 ? null : (
557        <Box key={`section-${id}`} flexDirection="column" marginTop={1}>
558          <Box flexDirection="row" columnGap={2}>
559            <Box key={`heading-${id}`} flexDirection="row" columnGap={1} flexGrow={1} position="relative">
560              {isDesktop ? (
561                <Text bold={isOpen} dimColor={!isOpen}>
562                  {label}
563                </Text>
564              ) : (
565                <Button key={`section-${id}`} plain label={isOpen ? label : `${label} …`} onPress={toggle} />
566              )}
567              <Text dimColor>{n}</Text>
568              {isDesktop ? cover(`section-${id}`, toggle) : null}
569            </Box>
570            {ask === undefined ? null : <Button key={`ask-${id}`} plain label="Ask" onPress={ask} />}
571          </Box>
572          {isOpen ? body() : null}
573        </Box>
574      )
575    }
576
577    // The freshness note gives way first in a narrow pane: squeezed, it wrapped onto two lines beside a cut name.
578    // Cells left after the padding, the whole group name, the Ask button with its frame, ↻ and the gaps.
579    const freshness = asked > 0 ? `asked ${ago(now - asked)} ago` : `live · ${ago(now - data.at)}`
580    const freshnessRoom = columns - 2 - data.group.length - (targets.length === 0 ? 0 : `Ask ${targetLabel}`.length + 6) - 3 - 2
581
582    return (
583      <Box flexDirection="column" paddingX={1}>
584        <Box flexDirection="row" columnGap={2} alignItems="center">
585          <Text bold wrap="truncate-end">
586            {data.group}
587          </Text>
588          {freshness.length <= freshnessRoom ? <Text dimColor>{freshness}</Text> : null}
589          <Box flexGrow={1} />
590          {targets.length === 0 ? null : (
591            <Button key="checkin" variant="secondary" {...keys('c')} label={`Ask ${targetLabel}`} onPress={() => void checkIn($)} />
592          )}
593          <Button key="refresh" plain {...keys('r')} label="↻" onPress={() => void refresh($, true)} />
594        </Box>
595
596        {held === null ? null : (
597          <Box flexDirection="row" columnGap={2}>
598            <Text color="warning" wrap="truncate-end">{`After this turn: ask about ${held.label}`}</Text>
599            <Box flexGrow={1} />
600            <Button key="cancel-ask" plain label="Cancel" onPress={() => void update($, queuedAsk, () => null)} />
601          </Box>
602        )}
603
604        {problem === null ? null : <Text color="error">{problem}</Text>}
605
606        {data.rows.length === 0 ? (
607          <Box marginTop={1}>
608            <Text dimColor>No other sessions in this group yet.</Text>
609          </Box>
610        ) : null}
611        {section('needs', 'Needs you', needs.length, () => needs.map(sessionRow))}
612        {section('working', 'Working', working.length, () => working.map(sessionRow))}
613        {section('done', 'Done', done.length, () => done.map(sessionRow), () => void askHere($, done))}
614        {section('loose', 'Loose worktrees', data.loose.length, () =>
615          data.loose.map(tree => (
616            <Box key={`loose-${tree.path}`} flexDirection="row" columnGap={2} paddingLeft={MARK}>
617              <Text wrap="truncate-end">{tree.name}</Text>
618              <Box flexGrow={1} />
619              <Text color={tree.dirty > 0 ? 'warning' : undefined} dimColor={tree.dirty === 0}>
620                {tree.dirty > 0 ? `${tree.dirty} changed` : 'clean'}
621              </Text>
622            </Box>
623          )),
624        )}
625      </Box>
626    )
627  })
628}
629
types/index.d.ts 62 lines
1/** What a session row needs next, which decides its section and color. */
2export type Kind = 'ready' | 'waiting' | 'fix' | 'working' | 'merged' | 'closed'
3
4export type Row = {
5  /** The desktop app's session id (`local_...`). */
6  id: string
7  /** A task id lifted from the title (`TASK-183`), or empty. */
8  tag: string
9  /** The title without its task id and verb. */
10  name: string
11  worktree: string
12  branch: string
13  kind: Kind
14  /** One short status phrase (`ready to merge`, `CI failing`). */
15  status: string
16  pr: number
17  prUrl: string
18  isRunning: boolean
19  /** ISO time of the session's last activity. */
20  lastActivityAt: string
21  /** Epoch ms its current state began: the run for a running session, the last activity otherwise. */
22  since: number
23  /** The session's project, shown only in the all-projects overview; empty otherwise. */
24  project: string
25}
26
27export type Loose = { path: string; name: string; dirty: number }
28
29export type Board = {
30  group: string
31  /** This session's own id and title, so check-ins can name where to reply. */
32  me: { id: string; title: string }
33  rows: Row[]
34  loose: Loose[]
35  /** Epoch ms of the last successful refresh. */
36  at: number
37}
38
39/** An Ask pressed while this session's turn ran, held here and sent when the turn ends. */
40export type QueuedAsk = { text: string; label: string }
41
42/** A check-in's trace per session: when it was asked, and what it answered. */
43export type Report = { askedAt: number; reply: string; repliedAt: number }
44
45declare module 'claude-code' {
46  interface PluginState {
47    'context-card': { paneAsk: number }
48    'pr-pane': {
49      board: Board | null
50      error: string | null
51      isLoading: boolean
52      attention: number
53      reports: Record<string, Report>
54      checkedAt: number
55      runs: Record<string, number>
56      expanded: string[]
57      openSections: string[]
58      queuedAsk: QueuedAsk | null
59    }
60  }
61}
62