SLOPSHOPPER

inbox-pane

claude-inbox's sections in a pane beside the transcript, with its keys.

panecommandtoaststatusprocesstimer
★ 4v0.2.0MITupdated 2026-10-26jordanbyron/claude-inbox/mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · inbox-pane
│ ┃ Inbox ✕ › fix the failing auth test and add an audit log call │ ┃ claude-inbox nothing running │ ┃ claude-inbox is not running: starting ⏺ Read(src/auth.ts) │ ┃ claude-inbox --headless. ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ ctrl+x tab takes you here ⎿ Added 2 lines, removed 1 line │ ┃ j: k: g: n: p: z: h: l: x: u: t: s: y: o: w: ⏺ 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 │ │ › /inbox │ ⎿ inbox-pane: Inbox pane open on terminal. ctrl+x tab focuses it; │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Inbox
claude-inbox nothing running claude-inbox is not running: starting claude-inbox --headless. ctrl+x tab takes you here j: k: g: n: p: z: h: l: x: u: t: s: y: o: w: q:
README

claude-inbox

An inbox for Claude Code's background sessions. It lists what claude agents lists and adds snooze, settle, pinning and each session's pull request.

Inspired by T3 Code's functionality and inbox-style UX, I wanted a better way to manage my Claude agents, so I built this.

claude-inbox with one working session, one snoozed and the settled section folded

Install

Requires Ruby 3.2+ and claude on PATH.

gem install claude-inbox
claude-inbox

claude-inbox update installs the latest release.

Put arguments you want on every launch in ~/.config/claude-inbox/config.

To add the pane to every Claude Code session:

claude-inbox install

The inbox offers to do this once, the first time it starts without the pane. claude-inbox install --force also replaces any other copy of the pane.

Claude Code pane

The same inbox as a pane inside Claude Code, docked beside the transcript in a fullscreen terminal.

The inbox pane docked beside a Claude Code transcript

/inbox opens it, ctrl+x tab focuses it and esc leaves. The keys are the ones below, with ge for G, n p for Tab Shift+Tab, and no a, P, X, Ctrl-x, /, R or U, and s has no 5. Enter, or a click on a row, switches to the session when you attached through claude-inbox.

It opens when a session starts. To stop that, set pluginConfigs.inbox-pane.options.openOnStart to false in ~/.claude/settings.json.

Sections

  1. Pinned. Rows you pinned with t. Snoozing a pinned row moves it to Snoozed, marked ★, until it wakes back into Pinned.
  2. Needs you. Blocked or failed sessions, or ones whose pull request has failing checks or changes requested, that you haven't attached to yet.
  3. Active. Everything else that's running or not yet settled, including interactive terminals.
  4. Snoozed. Sorted by wake time. Collapsed.
  5. Settled. Settled with x, or every pull request is merged or closed. Collapsed.

--sort=activity puts the session that spoke most recently first in every section but Snoozed, read from its transcript. Put it in the config file to keep it.

Under each row is what the session is waiting on, what it produced, or its status line. A row with a pull request shows it as #885 open, #885 merged and so on, with ✗ checks, changes requested or conflicts after it when something is wrong, and +2 after it when the session has two more. A steady ◌ with idle · 1 shell means the agent stopped and is waiting on a shell or sub-agent it started. A blue ● marks a session you haven't attached to since it got blocked or finished; one you have attached to since is dimmed, unless /color tints it. The age after the badge is how long since the session last said anything, read from its transcript: a working row that spoke 30s ago is still talking, one silent for 2h is not.

Keys

Vim bindings. Arrows and the mouse work too.

KeyAction
j kmove down / up
gg Gfirst / last row
Ctrl-d Ctrl-uhalf page down / up (Ctrl-f Ctrl-b full page)
Enter lattach (← or Ctrl+Z returns here), adopt a remote session, or expand Snoozed / Settled
Tab Shift+Tabnext / previous section
hcollapse the current fold
za zo zctoggle / open / close the fold under the cursor
nnew session
Npair a phone
tpin / unpin
ssnooze: 1 15m · 2 1h · 3 tomorrow 9am · 4 until woken · 5 custom
uwake a snoozed session, or bring back a settled one
xsettle by hand
aset a local alias
oopen the pull request in the browser; with several, o again opens the one that matters, 1… another
wopen the session at claude.ai/code
ycopy the pull request url, or the session's address; with several, y again copies the one that matters, 1… another
Plink a pull request by hand (empty clears)
Xstop the session; Enter resumes it later
Ctrl-xdelete the session, transcript and worktree for good
/filter by name, directory, prompt, status or pull request (#885 or its title); Enter keeps it, Esc clears
Rpoll now
Uupdate claude-inbox when the header says a newer one is out
qquit

X and Ctrl-x both ask for y first.

New session

n opens a form for the prompt, name, directory, model, effort, permissions, worktree, Remote Control and color, which tints the row as /color would. Tab moves between fields, Ctrl-S starts the session and Ctrl-O starts it and attaches. Option-S or Option-O by mistake only says which key you meant; it no longer reads as Esc and asks to discard the prompt.

Paste an image on macOS, or drop a file into the prompt, and refer to it as [Image #1]. Type / for a menu of your skills.

Type in Directory to pick from recent and trusted directories; Ctrl-U lists them all.

How sessions move

A snoozed session wakes when its timer runs out, when you press u, or when it becomes blocked or failed.

Attaching to a needs-you session moves it to Active until its state, or its pull request's health, changes again.

A session settles when you press x or when all its pull requests are merged or closed. A session without a pull request only settles by hand.

With --reap, the inbox deletes background sessions that have been idle for 14 days, with claude rm. Working, pinned and snoozed sessions are kept, and claude rm refuses a worktree with unpushed commits. Each deletion is logged to ~/.config/claude-inbox/reaped.log.

Remote Control

Sessions with Remote Control show ⇅, and w opens them at claude.ai/code. A session started from your phone through claude remote-control can't be attached directly, so Enter offers to adopt it as a background session.

Starting sessions from your phone

With --listen-lan, a phone on your network can start sessions.

The inbox beside the phone form, pairing and then starting a session

  1. Run claude-inbox --listen-lan.
  2. Press N, then c to copy the pairing URL.
  3. Open it on the phone in Safari and tap Share, then Add to Home Screen.
  4. Open the Inbox icon, paste the URL again and tap Pair.

LAN mode is plain HTTP. Use it only on a network you control, and press r in the N dialog if the URL leaks. docs/remote-start.md covers ssh, the JSON API and an iOS Shortcut.

Pull requests

Pull requests show up when a session's transcript links to them. Install gh to keep their state current. Use P to link one by hand, and /#885 to find the session behind a pull request.

Notifications

--notify sends a macOS notification through terminal-notifier when a session needs you or finishes. brew install terminal-notifier first; the first launch asks permission to notify.

Usage bars

The header can show your 5-hour and 7-day rate limit usage:

session ██░░░░░░░░ 24% · 3h left  week ████░░░░░░ 41% · 2d left

This needs a Pro or Max account. Add these lines to your status line script, just after it reads stdin. Run /statusline first if you don't have one.

input=$(cat)
limits=$(echo "$input" | jq -c '.rate_limits // empty')
[ -n "$limits" ] && echo "$limits" > ~/.claude/rate_limits.json.tmp && mv ~/.claude/rate_limits.json.tmp ~/.claude/rate_limits.json

Contributing

See CONTRIBUTING.md.

Source 2 files
hooks/register.tsx 574 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Folds, InboxRow, Pending, Section } from '../types'
5
6const PANE = 'inbox'
7const OPEN = { id: PANE, title: 'Inbox', columns: 48 } as const
8const POLL_MS = 500
9// Older than this and the writer has quit: it rewrites every 5 s even when nothing changed.
10const STALE_S = 30
11// How long a headless start gets to produce a fresh snapshot before another is tried.
12const RESTART_S = 60
13// A chord's first key waits this long for its second.
14const CHORD_MS = 5000
15// How long an attached inbox gets to take a switch request before the pane gives up on it.
16const SWITCH_MS = 3000
17// The gem's files, under HOME. The snapshot is read; the actions directory and switch.json
18// take the pane's requests, which the gem applies: nothing here edits the gem's own state.
19const SNAPSHOT = '.config/claude-inbox/snapshot.json'
20const ACTIONS = '.config/claude-inbox/actions'
21const SWITCH = '.config/claude-inbox/switch.json'
22// The sessions to switch to; the one this pane sits in is lifted out into `current`.
23const rows = atom({ plugin: 'inbox-pane', key: 'rows' } as const, [])
24const current = atom({ plugin: 'inbox-pane', key: 'current' } as const, null)
25const writtenAt = atom({ plugin: 'inbox-pane', key: 'writtenAt' } as const, 0)
26const newer = atom({ plugin: 'inbox-pane', key: 'update' } as const, null)
27const cursor = atom({ plugin: 'inbox-pane', key: 'cursor' } as const, 0)
28const folds = atom({ plugin: 'inbox-pane', key: 'folds' } as const, { snoozed: true, settled: true })
29const pending = atom({ plugin: 'inbox-pane', key: 'pending' } as const, null)
30
31export type SnapshotRow = {
32  id?: string
33  session?: string
34  label?: string
35  state?: string
36  actionable?: boolean
37  waiting?: boolean
38  unread?: boolean
39  line?: string
40  wake_at?: number | 'until_woken'
41  last_message_at?: number
42  remote?: string
43  color?: string
44  pr?: { short?: string; state?: string; url?: string }
45}
46type Snapshot = { written_at?: number; update?: string; sections?: Partial<Record<Section, SnapshotRow[]>> }
47// This session, as the gem's files name it, and the headless inbox this module may start.
48type Host = { session: string; command: string; headlessStartedAt: number; isHeadlessRunning: boolean }
49type Fold = keyof Folds
50type Item = { kind: 'row'; row: InboxRow } | { kind: 'fold'; section: Fold; count: number }
51type Snooze = 'm15' | 'h1' | 'tomorrow_9am' | 'until_woken'
52type Action = { action: 'settle' | 'wake' | 'pin'; id: string } | { action: 'snooze'; id: string; choice: Snooze }
53
54const ORDER: Section[] = ['pinned', 'needs_you', 'active', 'snoozed', 'settled']
55const TITLE: Record<Section, string> = { pinned: 'Pinned', needs_you: 'Needs you', active: 'Active', snoozed: 'Snoozed', settled: 'Settled' }
56const GLYPH: Record<string, string> = { blocked: '?', failed: '✗', working: '◐', idle: '◌', done: '✓', stopped: '✓' }
57const COLOR: Record<string, string> = { blocked: 'red', failed: 'red', working: 'green', idle: 'cyan' }
58const PR_COLOR: Record<string, string> = { open: 'green', draft: 'yellow', merged: 'magenta', closed: 'red' }
59// `/color`'s names as a label's background. A Button keeps the terminal's own ink, light on a dark
60// theme, so each is a deep 256-color shade of the hue the gem's Palette draws rather than the hue itself.
61const TINT: Record<string, string> = {
62  red: '#870000', green: '#005f00', yellow: '#875f00', blue: '#005f87', purple: '#5f0087', cyan: '#005f5f', orange: '#af5f00', pink: '#87005f',
63}
64const SNOOZE: Record<string, { choice: Snooze; label: string }> = {
65  '1': { choice: 'm15', label: '15m' },
66  '2': { choice: 'h1', label: '1h' },
67  '3': { choice: 'tomorrow_9am', label: 'tomorrow 9am' },
68  '4': { choice: 'until_woken', label: 'until woken' },
69}
70// What each chord's second key does, drawn under the footer while it waits.
71const MENU: Record<NonNullable<Pending>, [string, string][]> = {
72  g: [
73    ['g', 'first'],
74    ['e', 'last'],
75  ],
76  z: [
77    ['a', 'toggle the fold'],
78    ['o', 'open it'],
79    ['c', 'close it'],
80  ],
81  s: [
82    ['1', '15 minutes'],
83    ['2', '1 hour'],
84    ['3', 'tomorrow 9am'],
85    ['4', 'until woken'],
86  ],
87}
88
89function isFold(section: Section): section is Fold {
90  return section === 'snoozed' || section === 'settled'
91}
92
93// The Button drawn for an item, its label: the ring walks these with the arrows, a click presses one.
94function itemKey(item: Item): string {
95  return item.kind === 'fold' ? `fold:${item.section}` : `row:${item.row.id ?? item.row.label}`
96}
97
98// The Button drawn for a row's pull request, a click on which opens it.
99function prKey(item: Item): string | undefined {
100  return item.kind === 'row' && item.row.pr ? `pr:${itemKey(item)}` : undefined
101}
102
103// The visible box drawn for an item, what the pane scrolls to.
104function viewKey(item: Item): string {
105  return `view:${itemKey(item)}`
106}
107
108// The session the pane sits in leads, in a group of its own.
109function groupsOf(list: InboxRow[], folded: Folds, current: InboxRow | null): { section: Section | null; items: Item[] }[] {
110  const lead = current ? [{ section: null, items: [{ kind: 'row', row: current } as Item] }] : []
111  return lead.concat(
112    ORDER.flatMap(section => {
113      const own = list.filter(row => row.section === section)
114      if (own.length === 0) return []
115      const items: Item[] = isFold(section) && folded[section] ? [{ kind: 'fold', section, count: own.length }] : own.map(row => ({ kind: 'row', row }))
116      return [{ section, items }]
117    }),
118  )
119}
120
121async function listed($: EngineInterface): Promise<Item[]> {
122  return groupsOf(await read($, rows), await read($, folds), await read($, current)).flatMap(group => group.items)
123}
124
125// The stored cursor may point past a list that has shrunk since it was set.
126function onList(flat: Item[], at: number): number {
127  return Math.min(at, Math.max(0, flat.length - 1))
128}
129
130async function readJson<T>($: EngineInterface, path: string, fallback: T): Promise<T> {
131  try {
132    return JSON.parse(await $.fs.read(path)) as T
133  } catch {
134    return fallback
135  }
136}
137
138export function rowOf(section: Section, one: SnapshotRow): InboxRow {
139  const pr = one.pr?.short && one.pr.url ? { short: one.pr.short, state: one.pr.state ?? '', url: one.pr.url } : undefined
140  return {
141    section,
142    id: one.id,
143    session: one.session,
144    label: one.label ?? one.id ?? '',
145    state: one.state ?? 'unknown',
146    actionable: one.actionable === true,
147    isWaiting: one.waiting === true,
148    isUnread: one.unread === true,
149    line: one.line,
150    wakeAt: one.wake_at,
151    lastMessageAt: one.last_message_at,
152    remote: one.remote,
153    color: one.color,
154    pr,
155  }
156}
157
158function wakeLabel(wakeAt: number | 'until_woken'): string {
159  if (wakeAt === 'until_woken') return 'until woken'
160  const at = new Date(wakeAt * 1000)
161  return `${String(at.getHours()).padStart(2, '0')}:${String(at.getMinutes()).padStart(2, '0')}`
162}
163
164function ago(seconds: number): string {
165  if (seconds < 60) return 'just now'
166  if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`
167  if (seconds < 86_400) return `${Math.floor(seconds / 3600)}h ago`
168  return `${Math.floor(seconds / 86_400)}d ago`
169}
170
171async function inboxFile($: EngineInterface, path: string): Promise<string> {
172  return `${(await $.env.get('HOME')) ?? ''}/${path}`
173}
174
175async function nowS($: EngineInterface): Promise<number> {
176  return Math.floor((await $.clock.now()) / 1000)
177}
178
179// Read each time: it is the transcript's name, which the daemon reports as sessionId,
180// and a /clear may mint a new one mid-session.
181async function sessionId($: EngineInterface, host: Host): Promise<string> {
182  return $.session.id().catch(() => host.session)
183}
184
185// Leaves one request for the inbox to apply; its poller takes it within half a second
186// and the next snapshot shows the row where the gem's own rules put it.
187async function ask($: EngineInterface, host: Host, action: Action): Promise<void> {
188  const actions = await inboxFile($, ACTIONS)
189  const at = Math.floor(await $.clock.now())
190  await $.fs.write(`${actions}/${host.session}-${at}.json`, JSON.stringify({ ...action, at }))
191}
192
193// Asks the inbox attached to this session for another one. It takes the file when it
194// does; a file still there after SWITCH_MS, and still ours, means no inbox is attached to
195// this session.
196async function requestSwitch($: EngineInterface, host: Host, id: string): Promise<void> {
197  await handBackKeys($)
198  const path = await inboxFile($, SWITCH)
199  const from = await sessionId($, host)
200  const at = await nowS($)
201  await $.fs.write(path, JSON.stringify({ id, from, at }))
202  $.ui.toast(`switching to ${id}…`)
203  $.clock.after(SWITCH_MS, () => {
204    void readJson<{ from?: string; at?: number } | null>($, path, null).then(async left => {
205      if (left === null || left.from !== from || left.at !== at) return
206      await $.fs.write(path, '')
207      $.ui.toast('no inbox is attached to this session: run claude-inbox, attach from it, and press Enter here')
208    })
209  })
210}
211
212// Every key that takes the person out of the pane, to another session or the browser, calls
213// this first: the pane would keep the keys while they are away, and their typing on coming
214// back would land in it. The engine has no blur: reopening without `focus` is the one way
215// to give the keys to the prompt.
216async function handBackKeys($: EngineInterface): Promise<void> {
217  await $.ui.close({ id: PANE })
218  await $.ui.open(OPEN)
219}
220
221async function openInBrowser($: EngineInterface, url: string): Promise<void> {
222  await handBackKeys($)
223  await $.process.run(['open', url])
224}
225
226// Only while no inbox writes the snapshot; the gem's writer lock turns a second one away.
227function startHeadless($: EngineInterface, host: Host, now: number): void {
228  if (host.isHeadlessRunning || now - host.headlessStartedAt < RESTART_S) return
229  host.headlessStartedAt = now
230  host.isHeadlessRunning = true
231  void (async () => {
232    try {
233      const child = $.process.spawn({ argv: [host.command, '--headless'] })
234      for await (const piece of child) {
235        if ('text' in piece) $.ui.log(`${host.command} --headless: ${piece.text.trim()}`, { to: 'debug' })
236      }
237    } catch (error) {
238      $.ui.log(`${host.command} --headless did not start: ${String(error)}`, { to: 'debug' })
239    } finally {
240      host.isHeadlessRunning = false
241    }
242  })()
243}
244
245async function poll($: EngineInterface, host: Host): Promise<void> {
246  const file = await inboxFile($, SNAPSHOT)
247  const now = await nowS($)
248  const snapshot = await readJson<Snapshot | null>($, file, null)
249  const written = snapshot?.written_at ?? 0
250  if (snapshot !== null) {
251    const all = ORDER.flatMap(section => (snapshot.sections?.[section] ?? []).map(one => rowOf(section, one)))
252    const id = await sessionId($, host)
253    await update($, current, () => all.find(one => one.session === id) ?? null)
254    await update($, rows, () => all.filter(one => one.session !== id))
255    await update($, newer, () => snapshot.update ?? null)
256  }
257  await update($, writtenAt, () => written)
258  if (now - written > STALE_S) startHeadless($, host, now)
259}
260
261// Puts the ring on the item's Button, so Enter acts on it, and scrolls it into view.
262async function ringOn($: EngineInterface, item: Item): Promise<void> {
263  await $.ui.focus({ requestId: PANE, key: itemKey(item) }).catch(() => undefined)
264  await $.ui.scroll({ in: PANE, to: { key: viewKey(item) }, block: 'nearest' }).catch(() => undefined)
265}
266
267// Moves the cursor and keeps it on screen.
268async function moveTo($: EngineInterface, flat: Item[], to: number): Promise<void> {
269  const at = Math.max(0, Math.min(flat.length - 1, to))
270  await update($, cursor, () => at)
271  await update($, pending, () => null)
272  const item = flat[at]
273  if (item) await ringOn($, item)
274}
275
276async function setFold($: EngineInterface, list: InboxRow[], current: InboxRow | null, name: Fold | undefined, open: boolean): Promise<void> {
277  await update($, pending, () => null)
278  if (!name) return
279  const folded = await update($, folds, f => ({ ...f, [name]: !open }))
280  // The item under the cursor may have just become a fold, or the fold its rows.
281  const groups = groupsOf(list, folded, current)
282  const at = groups.findIndex(group => group.section === name)
283  if (at >= 0) await moveTo($, groups.flatMap(group => group.items), groups.slice(0, at).flatMap(group => group.items).length)
284}
285
286async function startChord($: EngineInterface, key: Pending): Promise<void> {
287  await update($, pending, () => key)
288  $.clock.after(CHORD_MS, () => void update($, pending, now => (now === key ? null : now)))
289}
290
291export const register: Register = (on, options) => {
292  const command = typeof options.command === 'string' && options.command !== '' ? options.command : 'claude-inbox'
293  const host: Host = { session: 'pane', command, headlessStartedAt: 0, isHeadlessRunning: false }
294
295  on('session.start', async ($, e, next) => {
296    await $.command.register({ name: 'inbox', description: 'Open the inbox of background sessions' })
297    const started = await next(e)
298    host.session = await $.session.id()
299    // A pinned line outlives a reload, so an earlier version's is cleared here.
300    $.ui.status(undefined)
301    void poll($, host)
302    $.clock.every(POLL_MS, () => void poll($, host))
303    if (options.openOnStart === false) return started
304    const opened = await $.ui.open(OPEN)
305    if (!opened.isPlaced) $.ui.log(`inbox: /inbox opens the pane (${opened.reason})`, { to: 'debug' })
306    return started
307  })
308
309  on('command.run', { command: 'inbox' }, async $ => {
310    void poll($, host)
311    const opened = await $.ui.open({ ...OPEN, focus: true })
312    const surfaces = (await $.session.surfaces()).join(', ') || 'none'
313    if (!opened.isPlaced) return { text: `Inbox pane not drawn: ${opened.reason}. Surfaces: ${surfaces}.` }
314    return { text: `Inbox pane open on ${surfaces}. ctrl+x tab focuses it; the keys are claude-inbox's.` }
315  })
316
317  // The ring walks the items' Buttons and nothing else: entering the pane it lands on
318  // the cursor's item, the arrows move it to the next, and the cursor follows.
319  on('ui.focus', { requestId: PANE }, async ($, e, next) => {
320    const flat = await listed($)
321    const was = onList(flat, await read($, cursor))
322    if (e.element === undefined) {
323      const item = flat[was]
324      return item ? next({ ...e, element: itemKey(item) }) : next(e)
325    }
326    // A PR chip's Button sits in the ring between its row and the next: the ring arrives on it going down
327    // from its own row, so it passes on to the next; going up, or by a click, it lands on its own row.
328    const chipOf = flat.findIndex(item => prKey(item) === e.element)
329    const at = chipOf < 0 ? flat.findIndex(item => itemKey(item) === e.element) : chipOf === was ? Math.min(chipOf + 1, flat.length - 1) : chipOf
330    if (at < 0) return {}
331    await update($, cursor, () => at)
332    return next({ ...e, element: itemKey(flat[at]!) })
333  })
334
335  // An arrow in a focused pane scrolls its body a row while the tree is taller than the
336  // window, and only walks the ring once it cannot: so the person's single-row scroll
337  // moves the cursor instead, and the wheel, the page keys and the pane's own scrolls pass.
338  on('ui.scroll', { requestId: PANE }, async ($, e, next) => {
339    if (e.origin.kind !== 'person' || e.pointer !== undefined || Math.abs(e.by) !== 1) return next(e)
340    const flat = await listed($)
341    const at = onList(flat, await read($, cursor))
342    await moveTo($, flat, at + e.by)
343    return {}
344  })
345
346  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
347    const { Box, Text, Button } = $.ui.resolve(e)
348    const list = await read($, rows)
349    const viewing = await read($, current)
350    const folded = await read($, folds)
351    const chord = await read($, pending)
352    const written = await read($, writtenAt)
353    const release = await read($, newer)
354    const now = await nowS($)
355    const ageS = now - written
356    const groups = groupsOf(list, folded, viewing)
357    const flat = groups.flatMap(group => group.items)
358    const at = onList(flat, await read($, cursor))
359    const selected = flat[at]
360    const row = selected?.kind === 'row' ? selected.row : undefined
361    const section = selected?.kind === 'fold' ? selected.section : row === viewing ? undefined : row?.section
362    const fold = section && isFold(section) ? section : undefined
363    const heads = groups.map(group => flat.indexOf(group.items[0] as Item))
364    const notice =
365      written === 0
366        ? `claude-inbox is not running: starting ${command} --headless.`
367        : ageS > STALE_S
368          ? `claude-inbox stopped ${ago(ageS)}; rows are stale.`
369          : null
370
371    // The gem's header chips, compact: a glyph and a count per section that has rows.
372    const count = (of: (one: InboxRow) => boolean) => list.filter(of).length
373    const chips: [number, string, string | undefined][] = [
374      [count(one => one.section === 'pinned'), '★', 'cyan'],
375      [count(one => one.section === 'needs_you'), '●', 'red'],
376      [count(one => one.section === 'active' && one.state === 'working' && !one.isWaiting), '✻', 'yellow'],
377      [count(one => one.section === 'active' && one.isWaiting), '◌', 'yellow'],
378      [count(one => one.section === 'snoozed'), 'z', 'magenta'],
379      [count(one => one.section === 'settled'), '◦', undefined],
380    ]
381
382    const onRow = (action: 'settle' | 'wake' | 'pin', verb: string) => () => {
383      if (!row?.id || !row.actionable) return $.ui.toast('nothing here can be changed from the pane')
384      void ask($, host, { action, id: row.id }).then(() => $.ui.toast(`${verb} ${row.label}`))
385    }
386    const key = (hotkey: string, onPress: () => void) => <Button key={hotkey} hotkey={hotkey} plain label="" onPress={onPress} />
387    // Enter or a click on an item: the cursor lands on it, a fold opens, a row the inbox can
388    // attach to asks for the switch.
389    const enter = (item: Item) => () => {
390      void moveTo($, flat, flat.indexOf(item))
391      if (item.kind === 'fold') return void setFold($, list, viewing, item.section, true)
392      if (item.row === viewing) return $.ui.toast('you are in this session')
393      if (!item.row.id || !item.row.actionable) return $.ui.toast('this session cannot be attached')
394      void requestSwitch($, host, item.row.id)
395    }
396    // The click's focus may have walked the ring past the row, so the cursor is put back on it.
397    const openPr = (item: Item) => () => {
398      if (item.kind !== 'row' || !item.row.pr) return
399      const url = item.row.pr.url
400      void moveTo($, flat, flat.indexOf(item)).then(() => openInBrowser($, url))
401    }
402
403    // Only the keys a chord allows are mounted while it waits, so any other key is a no-op.
404    const keys =
405      chord === 'g'
406        ? [key('g', () => void moveTo($, flat, 0)), key('e', () => void moveTo($, flat, flat.length - 1))]
407        : chord === 'z'
408          ? [
409              key('a', () => void setFold($, list, viewing, fold, fold ? folded[fold] : false)),
410              key('o', () => void setFold($, list, viewing, fold, true)),
411              key('c', () => void setFold($, list, viewing, fold, false)),
412            ]
413          : chord === 's'
414            ? Object.entries(SNOOZE).map(([digit, { choice, label }]) =>
415                key(digit, () => {
416                  if (!row?.id || !row.actionable) return $.ui.toast('nothing here can be snoozed')
417                  void ask($, host, { action: 'snooze', id: row.id, choice }).then(() => {
418                    void update($, pending, () => null)
419                    $.ui.toast(`snoozed ${row.label} ${label}`)
420                  })
421                }),
422              )
423            : [
424                key('j', () => void moveTo($, flat, at + 1)),
425                key('k', () => void moveTo($, flat, at - 1)),
426                key('g', () => void startChord($, 'g')),
427                key('n', () => void moveTo($, flat, heads.find(h => h > at) ?? heads[0] ?? 0)),
428                key('p', () => void moveTo($, flat, heads.filter(h => h < at).pop() ?? heads[heads.length - 1] ?? 0)),
429                key('z', () => void startChord($, 'z')),
430                key('h', () => void setFold($, list, viewing, fold, false)),
431                key('l', selected ? enter(selected) : () => undefined),
432                key('x', onRow('settle', 'settled')),
433                key('u', onRow('wake', 'woke')),
434                key('t', onRow('pin', 'pinned')),
435                key('s', () => void startChord($, 's')),
436                key('y', () => {
437                  if (!row) return $.ui.toast('nothing to copy')
438                  const text = row.pr?.url ?? row.remote ?? row.id ?? row.label
439                  void $.ui.copy({ text, surface: e.surface }).then(copied => $.ui.toast(copied.isCopied ? `copied ${text}` : 'no clipboard here'))
440                }),
441                key('o', () => (row?.pr ? void openInBrowser($, row.pr.url) : $.ui.toast('no pull request linked'))),
442                key('w', () => (row?.remote ? void openInBrowser($, row.remote) : $.ui.toast('no claude.ai/code page for this session'))),
443                key('q', () => void $.ui.close({ id: PANE })),
444              ]
445
446    return (
447      <Box flexDirection="column">
448        {/* The engine draws its close mark on a row of its own above the body, so the header can't share it. */}
449        <Box columnGap={2}>
450          <Text color="cyan" bold>
451            claude-inbox
452          </Text>
453          {chips.filter(([n]) => n > 0).map(([n, glyph, color]) => (
454            <Text color={color} dimColor={color === undefined}>
455              {glyph} {n}
456            </Text>
457          ))}
458          {list.length === 0 && viewing === null && <Text dimColor>nothing running</Text>}
459        </Box>
460        {notice !== null && <Text color="yellow">{notice}</Text>}
461        {/* No key for it: the pane cannot replace the process under Claude Code, so it names the command. */}
462        {notice === null && release !== null && <Text dimColor>{release} · claude-inbox update</Text>}
463        {notice === null && flat.length === 0 && <Text dimColor>No sessions.</Text>}
464        {groups.map(group => (
465          <Box flexDirection="column" marginTop={1}>
466            <Text bold dimColor>
467              {group.section === null ? 'This session' : `${TITLE[group.section]} · ${list.filter(one => one.section === group.section).length}`}
468            </Text>
469            {group.items.map(item => {
470              const isHere = item === selected
471              if (item.kind === 'fold') {
472                return (
473                  <Box key={viewKey(item)}>
474                    <Text color={isHere ? 'yellow' : undefined}>{isHere ? '› ' : '  '}</Text>
475                    <Button key={itemKey(item)} plain dimColor label={`▸ ${item.count} folded · za opens`} onPress={enter(item)} autoFocus={isHere || undefined} />
476                  </Box>
477                )
478              }
479              const one = item.row
480              const isQuiet = isFold(one.section)
481              // A finished or blocked row you have attached to since dims, as the gem's Active section draws it,
482              // unless it is tinted: faint ink on a /color background is unreadable.
483              const isRead = !isQuiet && one.actionable && ['done', 'stopped', 'blocked', 'failed'].includes(one.state) && !one.isUnread
484              // A blue dot asks for a look in every state, as the gem draws it: the glyph already says needs you
485              // in red. A terminal cannot be attached to, so it is never read and keeps its dot while it waits.
486              const needsYou = one.state === 'blocked' || one.state === 'failed'
487              const dot = !isQuiet && (one.isUnread || (needsYou && !one.actionable))
488              const text = one.wakeAt !== undefined ? `${one.label} · ${wakeLabel(one.wakeAt)}` : one.label
489              const tint = one.color ? TINT[one.color] : undefined
490              return (
491                <Box key={viewKey(item)} flexDirection="column">
492                  <Box>
493                    {/* Only the label gives way to a long row: a squeezed glyph wraps under itself. */}
494                    <Box flexShrink={0}>
495                      <Text color={isHere ? 'yellow' : 'blue'}>{isHere ? '› ' : dot ? '● ' : '  '}</Text>
496                      <Text color={COLOR[one.state]} dimColor={isQuiet || one.state === 'done'}>
497                        {GLYPH[one.state] ?? '·'}{' '}
498                      </Text>
499                    </Box>
500                    {/* A Button cannot truncate, so its Box clips a long label to the row. A Button takes no
501                        color either, so a session's /color is the Box's background rather than the label's ink. */}
502                    <Box key={`label:${itemKey(item)}`} height={1} flexShrink={1} overflow="hidden" backgroundColor={tint}>
503                      <Button
504                        key={itemKey(item)}
505                        plain
506                        dimColor={(isQuiet || isRead) && !isHere && tint === undefined}
507                        label={text}
508                        onPress={enter(item)}
509                        autoFocus={isHere || undefined}
510                      >
511                        {/* An unread row is bold, as a mail client marks one; a Button has no weight of its own. */}
512                        {one.isUnread && !isQuiet ? <Text bold>{text}</Text> : text}
513                      </Button>
514                    </Box>
515                    {/* Takes what a short label leaves, so the PR and age sit at the right edge on every row;
516                        the label's own box would stretch a /color tint across it. */}
517                    <Box flexGrow={1} />
518                    {/* The label gives up its cells to the PR chip, which would otherwise wrap under it. The chip is
519                        a Button rather than a Link: a terminal without OSC 8 cannot click a Link, and prints its URL. */}
520                    {one.pr ? (
521                      <Box flexShrink={0}>
522                        <Box marginLeft={1}>
523                          <Button key={prKey(item)} plain label={one.pr.short} onPress={openPr(item)}>
524                            <Text underline color={isQuiet ? undefined : PR_COLOR[one.pr.state]} dimColor={isQuiet}>
525                              {one.pr.short}
526                            </Text>
527                          </Button>
528                        </Box>
529                        <Text color={isQuiet ? undefined : PR_COLOR[one.pr.state]} dimColor={isQuiet}>
530                          {' '}
531                          {one.pr.state}
532                        </Text>
533                      </Box>
534                    ) : null}
535                    {one.lastMessageAt !== undefined ? (
536                      <Box flexShrink={0}>
537                        <Text dimColor> {ago(now - one.lastMessageAt)}</Text>
538                      </Box>
539                    ) : null}
540                  </Box>
541                  {!isQuiet && one.line !== undefined ? (
542                    <Box paddingLeft={4}>
543                      <Text dimColor wrap="truncate-end">↳ {one.line}</Text>
544                    </Box>
545                  ) : null}
546                </Box>
547              )
548            })}
549          </Box>
550        ))}
551        <Box flexDirection="column" marginTop={1}>
552          {!e.props.isFocused && <Text dimColor>ctrl+x tab takes you here</Text>}
553          {e.props.isFocused && chord === null && <Text dimColor>esc leaves</Text>}
554          {e.props.isFocused && chord !== null && (
555            <Box flexDirection="column">
556              <Text dimColor>{chord}…</Text>
557              {MENU[chord].map(([key, what]) => (
558                <Text dimColor>
559                  {'  '}
560                  <Text bold>{key}</Text> {what}
561                </Text>
562              ))}
563            </Box>
564          )}
565        </Box>
566        {/* Drawn nowhere: the hotkeys. */}
567        <Box height={0} overflow="hidden">
568          {keys}
569        </Box>
570      </Box>
571    )
572  })
573}
574
types/index.d.ts 33 lines
1export type Section = 'pinned' | 'needs_you' | 'active' | 'snoozed' | 'settled'
2
3// One row of the gem's snapshot.json, as its Snapshot class writes it.
4export type InboxRow = {
5  section: Section
6  id?: string
7  // The daemon's sessionId, the name $.session.id() gives the session the pane sits in.
8  session?: string
9  label: string
10  state: string
11  actionable: boolean
12  isWaiting: boolean
13  isUnread: boolean
14  line?: string
15  wakeAt?: number | 'until_woken'
16  lastMessageAt?: number
17  remote?: string
18  color?: string
19  pr?: { short: string; state: string; url: string }
20}
21
22export type Folds = { snoozed: boolean; settled: boolean }
23
24// The first key of a chord (g, z, s) waiting for its second; null between chords.
25export type Pending = 'g' | 'z' | 's' | null
26
27declare module 'claude-code' {
28  interface PluginState {
29    // `update` is the gem's notice for a newer release ("v0.6.0 available"), null while this one is the latest.
30    'inbox-pane': { rows: InboxRow[]; current: InboxRow | null; writtenAt: number; update: string | null; cursor: number; folds: Folds; pending: Pending }
31  }
32}
33