SLOPSHOPPER

clux

Claude Code ↔ tmux notifications — status bar alerts when tasks finish or need input

panespinnertoastprocesstimer
v5.5.0MITupdated 2026-10-21ai-advanced-futures/clux/plugins/clux
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · clux
│ ┃ notifications ✕ › fix the failing auth test and add an audit log call │ ┃ Notifications · 0 | Filters · 0 │ ┃ q: hide j: down k: up x: remove f: filters ⏺ Read(src/auth.ts) │ ┃ No notifications. ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ 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 │ │ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⟨Claude Code's own drawing⟩ & sessions & notifs

Draws

Pane · notifications
Notifications · 0 | Filters · 0 q: hide j: down k: up x: remove f: filters No notifications.
Pane · sessions
Background sessions · 0 [ Hide ] No background sessions for this repository.
README

clux

tmux status bar notifications for Claude Code. See when a task finishes or needs you.

Quick start

Start Claude Code inside tmux. Run:

/plugin marketplace add ai-advanced-futures/clux
/plugin install clux@clux

Restart Claude Code. Run:

/clux:setup

/clux:setup asks a few short questions and shows each change before it writes it. To check the result, run /clux:validate. It changes nothing.

After a plugin update, run /clux:upgrade. It keeps your setup answers and asks no questions. When a newer clux is available, it gives the commands to update the plugin.

Requirements

tmux and bash ≥ 4.0. jq and flock are recommended. Python ≥ 3.10 and perl are only for the companion terminal (macOS and most Linux systems have perl). Without perl, terminal.sh gives exit code 2 and clux terminal needs perl.

Mirror mode

/clux:follow on makes all terminals that are attached to tmux show the same session. When you change session in one terminal, the others go with it. /clux:follow off stops it.

Background sessions pane

/clux:sessions opens one pane for the background sessions of the current repository. /clux:sessions again closes it. ctrl+x b does the same from anywhere, also while you write a message. Your draft stays in the composer.

Background sessions · 3                      [ Hide ]
1: tenant-registry-p1   ● needs input  choose: YAML crosswalk or SQL table?
2: ce-db-roster         ● working      #41 Running the migration tests
3: mods-research        ● done         #28 #29 10 daily uses + gh-account mod
  • Each row shows the name, the status (needs input, working, unknown, done, failed, stopped), the PRs as links, and the description. The description is the question of a session that needs input, else what the session does now or the result it gave.
  • The first row has the focus when the pane opens. The Up and Down arrows (or Tab) move the focus. Enter, or the number of a row (1 to 9), puts the @name of that session in the message box at the cursor, and closes the pane. Then you can write, for example, ask @fabric-giants for its status. When the message box has a draft, Claude Code opens the pane without the keyboard. The pane then says ctrl+x tab: move into the list. Press ctrl+x tab to move into it. Esc gives the keyboard back to the prompt.
  • clux draws nothing above the prompt. At the right end of the prompt footer, a dim sessions label opens the pane. When a session needs input, the label changes to the count, for example 1 needs input.
  • When a session writes needs input:, the footer label counts it. The pane shows no toast and plays no sound.
  • A session counts when its folder or its worktree is in the repository, also a worktree that git worktree list names. The session that shows the pane is not in the list. A working session that has not written its state for 30 minutes shows as unknown.

The pane is a function-hooks mod (hooks/sessions/). It needs Claude Code 2.1.291 or later. ctrl+x b is the chord of the app:cycleDiffBase action, which Claude Code uses only in the diff panel. To use a different chord, bind it to app:cycleDiffBase in ~/.claude/keybindings.json (context Global).

Notifications pane

/clux:notifications opens one pane for the clux notification queue — the list the tmux status bar and the prefix + M popup show. Each tmux server has its own queue, so a server shows only the notifications of its own sessions (see the reference). /clux:notifications again closes it. ctrl+x n does the same from anywhere, also while you write a message, after you bind it (see below).

Notifications · 3  |  Filters · 2 q: hide  j: down  k: up  x: remove  f: filters
main:editor Task done
⚡ agents / pr-flow needs you
main:tests 8/8 green
  • j and k move the focus, and so do the Down and Up arrows and Tab. Enter goes to the tmux window of the focused row (or to the agents pane of an agent row), takes the row out of the queue, and closes the pane. x takes the focused row out and keeps the pane open. q closes the pane. Esc gives the keyboard back to the prompt and keeps the pane open.
  • The keys work only while the pane has the keyboard. When the message box has a draft, Claude Code opens the pane without it, and the pane says ctrl+x tab: move into the list. Press ctrl+x tab to move in.
  • At the right end of the prompt footer, a dim notifs label opens the pane. When the queue is not empty, the label shows the count, for example 3 notifs.
  • clux reads the queue file every 2 seconds. The tmux status bar shows a new notification sooner, because tmux runs its own job on its own interval.
  • Enter works also when Claude Code itself does not run in tmux (for example a background session): tmux moves its attached client to the window. With no tmux server, Enter says it could not jump, and x still works.
  • The prefix + M popup shows the short text of each notification, without the ids after |||. In the popup, Ctrl-X deletes the selected notification, and the popup stays open. Enter goes to the notification, and Esc closes the popup.

The pane is a function-hooks mod (hooks/notifications/). It needs Claude Code 2.1.291 or later. The keys of this pane and the keys of the prefix + M popup both run scripts/notification-line.sh, so a jump means the same thing in both.

ctrl+x n needs one line in ~/.claude/keybindings.json, because Claude Code gives a plugin no default key. Add it to the Global context:

{ "context": "Global", "bindings": { "ctrl+x n": "app:toggleDiffPreSession" } }

The pane borrows the app:toggleDiffPreSession action, which Claude Code uses only for the diff view. While the diff view is open, the key can act on the diff view instead of the pane. To use a different key, bind that key to app:toggleDiffPreSession.

Notification filters

A file in a repo can hide some clux notifications. clux reads <main repo root>/.claude/clux-filters.local. All the worktrees of the repo use the same file. Each line is one rule:

# clux notification filters. Regex type: grep -E, case-sensitive.
allow ^feat-
deny  wip
  • The regex (grep -E, case-sensitive) matches the Claude session name, the name that the sessions pane shows. When a session has no name, the name is the folder name.
  • deny hides the notifications of the sessions that match. allow lets only the sessions that match notify. When the file has an allow rule, the name must match one allow rule and no deny rule. The order of the lines has no effect.
  • A hidden notification makes no sound, no desktop banner, no queue line and no bell. A new rule does not remove the lines that are already in the queue.
  • clux ignores blank lines and lines that start with #. It also ignores a line that is not a rule, and the Filters view shows that line in red.
  • When git does not ignore the file, clux adds it to .git/info/exclude.

In the notifications pane, f opens the Filters view and n goes back. The view shows the file path and one row for each rule:

Notifications · 3  |  Filters · 2
q: hide n: notifications j: down k: up a: add e: edit t: allow/deny x: remove
/code/app/.claude/clux-filters.local
allow  ^feat-
deny   wip
  • a opens a box with allow . Type the rule, then push Enter. e, or Enter on a row, edits the focused rule. t changes allow to deny, or deny to allow. x removes the focused rule. Esc closes the box with no change.
  • When grep refuses the regex, the pane shows the grep error, and the box stays open with your text.
  • grep -E has no \d: GNU grep reads \d as a plain d. The pane refuses a new rule with \d. Use [0-9].
  • Outside a git repo, the view shows Not in a git repo.

In the clux session bar, a session with a window whose active pane is in a repo with one or more valid rules shows ⊘ after the session name. To change the text, set @clux-filter-mark. An empty value turns the mark off:

set -g @clux-filter-mark 'filters on'

Companion terminal

The clux:terminal skill gives Claude one tmux pane that you can see. Claude runs commands in it. A Clef model examines each command before it runs. A dangerous command waits for your y. You run one Clef server and name it with CLUX_CLEF_URL:

export CLUX_CLEF_URL=http://127.0.0.1:8765

The reference gives the server command, the Tailscale setup for more than one machine, and CLUX_CLEF_KEY.

Background sessions. A Claude Code session with no tmux pane (claude --bg, or a session that a claude agents dashboard starts) also gets a companion. It opens as a new window, clux-terminal <id>, in the tmux session of the dashboard. With no dashboard, it opens on a private tmux server, and Claude gives you the line to attach to it. The companion closes when the session ends, also after a crash.

For more detail, read the reference.

More

MIT license.

Source 7 files
hooks/register.tsx 22 lines
1// The one hooks module of clux.
2//
3// `hooks.json` takes a single `modules` entry for each plugin — `claude
4// plugin validate` says so plainly: "hooks.json `modules` names one hooks
5// module per plugin; a second entry is refused" — so this file composes the
6// panes instead. Each pane keeps its own folder and its own `register`.
7//
8// The order is load-bearing. Two `ui.render` hooks on `SessionMode` chain,
9// and the one registered FIRST is the outermost: it draws `next(e)` before
10// its own label. Notifications first therefore leaves the sessions label on
11// the left of the footer and puts the notifications label on the right.
12
13import type { Register } from 'claude-code'
14
15import { register as notifications } from './notifications/register'
16import { register as sessions } from './sessions/register'
17
18export const register: Register = (on, options) => {
19  notifications(on, options)
20  sessions(on, options)
21}
22
hooks/notifications/register.tsx 558 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { FilterEditing, FilterRow, NotifRow } from '../../types'
5import { editValue, parseList, rowText, splitRule, validCount } from './filters'
6import { toRows } from './lines'
7
8const PANE = 'notifications'
9const TITLE = 'Notifications'
10// commands/notifications.md declares it; the hook below answers it.
11const COMMAND = 'clux:notifications'
12// The chord that toggles the pane, also with a draft in the composer. No
13// engine action runs a plugin command, so the mod borrows this one, as the
14// sessions pane borrows app:cycleDiffBase. It has no default key: the person
15// binds one in ~/.claude/keybindings.json (clux suggests "ctrl+x n").
16const TOGGLE_ACTION = 'app:toggleDiffPreSession'
17// The status bar of tmux shows a new notification sooner, on its own
18// interval; this is one file read.
19const POLL_MS = 2000
20
21const notifications = atom({ plugin: 'clux', key: 'notifications' } as const, [])
22// The Filters view: which view shows, the filter file of the session's repo,
23// its rules, and the rule box. The notifications atom does not change.
24const filters = atom({ plugin: 'clux', key: 'filters' } as const, {
25  view: 'notifications',
26  file: '',
27  rules: [],
28  editing: null,
29})
30
31// The poll loop of this session: the queue path, read one time at the start.
32const loop: { queue?: string; timer?: Timer; isPolling: boolean } = { isPolling: false }
33
34// The plugin's own copy of the script, so the pane works from `--plugin-dir`
35// with no /clux:setup. The tmux keys run the copy in ~/.config/clux/scripts/.
36const script = ($: EngineInterface) => `${$.plugin.root}/scripts/notification-line.sh`
37// The filter file has one owner, as the queue line has: the hook, the status
38// bar and this pane all run notify-filter.sh, so the pane parses no rule and
39// checks no regex itself.
40const filterScript = ($: EngineInterface) => `${$.plugin.root}/scripts/notify-filter.sh`
41
42// One source for the queue path: the script resolves the three tiers.
43async function queuePath($: EngineInterface): Promise<string> {
44  const answer = await $.process.run([script($), 'path']).catch(() => undefined)
45  const path = answer?.exitCode === 0 ? answer.stdout.trim() : ''
46  if (path !== '') return path
47  return `${await $.env.get('HOME')}/.config/tmux/claude_notification`
48}
49
50// A missing queue file is an empty list. The poll takes no lock: a writer can
51// leave the file empty for a moment, and the next poll draws the right list.
52async function poll($: EngineInterface) {
53  const queue = loop.queue
54  if (!queue) return
55  const text = await $.fs.read(queue).catch(() => '')
56  const list = toRows(typeof text === 'string' ? text : '')
57  const before = await read($, notifications)
58  if (JSON.stringify(list) !== JSON.stringify(before)) {
59    await update($, notifications, () => list)
60  }
61}
62
63// One verb of notify-filter.sh on the session cwd, through runScript.
64async function runFilter($: EngineInterface, verb: string, args: string[] = []) {
65  const cwd = await $.session.cwd()
66  return runScript($, [filterScript($), verb, cwd, ...args], `filter ${verb}`)
67}
68
69// The filter file path, read one time at the start. '' when the cwd is not in
70// a git repo: then the pane polls no list.
71async function filterPath($: EngineInterface): Promise<string> {
72  const answer = await runFilter($, 'path')
73  return answer?.exitCode === 0 ? answer.stdout.trim() : ''
74}
75
76// The rules, in both views: the header counts them. A list that fails keeps
77// the rows the last poll drew.
78async function pollFilters($: EngineInterface) {
79  const state = await read($, filters)
80  if (state.file === '') return
81  const answer = await runFilter($, 'list')
82  if (answer?.exitCode !== 0) return
83  const rules = parseList(answer.stdout)
84  if (JSON.stringify(rules) !== JSON.stringify(state.rules)) {
85    await update($, filters, s => ({ ...s, rules }))
86  }
87}
88
89// Esc in the rule box gives the keys to the prompt, and no hook hears it. The
90// pane then draws no box; this clears the box from the state too, so the box
91// does not come back when the pane takes the keys again.
92async function closeLostBox($: EngineInterface) {
93  if (!(await read($, filters)).editing) return
94  const pane = (await $.ui.panes()).find(p => p.id === PANE)
95  if (pane?.isFocused) return
96  await update($, filters, s => ({ ...s, editing: null }))
97}
98
99// One poll at a time, so a slow poll and the next tick never overlap.
100async function tick($: EngineInterface) {
101  if (loop.isPolling) return
102  loop.isPolling = true
103  try {
104    await closeLostBox($)
105    await poll($)
106    await pollFilters($)
107  } catch (error) {
108    $.ui.log(`clux notifications: poll failed: ${String(error)}`, { to: 'debug' })
109  } finally {
110    loop.isPolling = false
111  }
112}
113
114// The row the ring sits on, one for each view: its own index and its own key
115// prefix, so the two views never move each other's ring. The `ui.focus` hook
116// below and `focusAt` write the index, apart from `openPane` and `showView`,
117// which put it back on the first row.
118type Ring = { prefix: string; index: number }
119const rowRing: Ring = { prefix: 'row:', index: 0 }
120const ruleRing: Ring = { prefix: 'rule:', index: 0 }
121
122// Asked (a command, a press) it seats at any width; `focus` hands it the
123// keys. A pane that opens new puts the ring on the first row, so the index
124// of both rings goes back to 0: the pane can open new in either view. A pane
125// that is already open keeps its ring where the person put it, so the index
126// keeps its value too: a reset there would make `x` remove the first row
127// while the ring shows another.
128async function openPane($: EngineInterface) {
129  const isOpen = (await $.ui.panes()).some(pane => pane.id === PANE)
130  if (!isOpen) {
131    rowRing.index = 0
132    ruleRing.index = 0
133  }
134  await tick($)
135  return $.ui.open({ id: PANE, title: TITLE, focus: true })
136}
137
138// A script that cannot start, or that overruns its budget, resolves to
139// undefined, and so reads as a failure exactly as a non-zero exit does; the
140// reason goes to the debug log, never to the person. The budget is RUN_MS:
141// the engine default is 30 s, too long for a key press when tmux does not
142// answer.
143const RUN_MS = 5000
144
145async function runScript($: EngineInterface, argv: string[], label: string) {
146  return $.process.run(argv, { timeoutMs: RUN_MS }).catch(error => {
147    $.ui.log(`clux notifications: ${label} failed: ${String(error)}`, { to: 'debug' })
148    return undefined
149  })
150}
151
152// One verb of the shared script on one line.
153async function runLine($: EngineInterface, verb: 'jump' | 'remove', row: NotifRow) {
154  const answer = await runScript($, [script($), verb, row.line], verb)
155  return answer?.exitCode === 0
156}
157
158// Enter on a row. The jump leaves tmux on another window, so the pane closes:
159// a pane that stays open shows the list of the window the person just left.
160// The remove is needed because the status bar removes only the top line. An
161// agent line needs no remove: the jump of an agent line removes it.
162//
163// The script runs also when Claude Code is not in tmux (a background
164// session has no TMUX): with no current client, tmux moves the client it
165// picks itself. With no tmux server, the script exits 1, the pane and the row
166// both stay, and the person can still press `x`.
167async function jumpTo($: EngineInterface, row: NotifRow) {
168  if (!(await runLine($, 'jump', row))) {
169    $.ui.toast(`Could not jump to ${row.text}.`)
170    return
171  }
172  // The jump is done, so the pane closes also when the remove fails; the
173  // person learns that the row stays in the queue.
174  if (row.kind === 'window' && !(await runLine($, 'remove', row))) {
175    $.ui.toast('The queue is busy. The notification stays in the queue.')
176  }
177  await $.ui.close({ id: PANE })
178  await tick($)
179}
180
181// Move the ring. The pane may not hold the keys, and then the engine refuses
182// the move: the person sees nothing, the index keeps its value, and the
183// reason goes to the debug log. `j`, `k` and `x` all follow this rule, in
184// both views.
185//
186// A move that lands sets the index there. The engine does not give a
187// plugin's own `$.ui.focus` to that plugin's `ui.focus` hook (the debug log
188// says "ui.focus skipped: re-entry"), so the hook below never sees it.
189async function askFocus($: EngineInterface, key: string): Promise<boolean> {
190  const moved = await $.ui
191    .focus({ requestId: PANE, key })
192    .catch(error => ({ deny: String(error) }))
193  if (moved.deny) {
194    $.ui.log(`clux notifications: the ring stayed off ${key}: ${moved.deny}`, { to: 'debug' })
195    return false
196  }
197  return true
198}
199
200async function focusAt($: EngineInterface, ring: Ring, index: number) {
201  if (await askFocus($, `${ring.prefix}${index}`)) ring.index = index
202}
203
204// `j` and `k`: one row on, limited to the list. A poll can make the list
205// shorter with no key press, so the upper limit is read from the list the
206// last poll wrote. A move by 0 puts the ring back inside a shorter list.
207async function move($: EngineInterface, ring: Ring, by: number) {
208  const length = ring === rowRing
209    ? (await read($, notifications)).length
210    : (await read($, filters)).rules.length
211  if (length === 0) return
212  await focusAt($, ring, Math.min(length - 1, Math.max(0, ring.index + by)))
213}
214
215// The focused row, limited to the list the last poll wrote.
216function at<T>(list: T[], ring: Ring): T | undefined {
217  return list[Math.min(ring.index, list.length - 1)]
218}
219
220// `x`: the queue keeps a notification until the person has read it somewhere
221// else, so this is the way to drop one from the pane. The index is limited
222// to the list the last poll wrote, the same limit `j` and `k` use, because a
223// poll can make the list shorter with no key press.
224async function removeRow($: EngineInterface) {
225  const row = at(await read($, notifications), rowRing)
226  if (!row) return
227  if (!(await runLine($, 'remove', row))) {
228    $.ui.toast('The queue is busy. Try again.')
229    return
230  }
231  await tick($)
232  // The ring stays at the same place, so taking the last row out moves it up
233  // one. An empty list draws "No notifications." and has no row key at all.
234  await move($, rowRing, 0)
235}
236
237// --- The Filters view -------------------------------------------------------
238
239// The key of the rule box, and the toasts of a rule the pane refuses.
240const INPUT_KEY = 'filter-input'
241const BAD_KIND = 'A rule starts with allow or deny.'
242const STALE = 'The file changed. Try again.'
243// The red word before the raw line of an invalid row.
244const INVALID_MARK = 'invalid '
245
246// `f` and `n`. A view opens with its ring on its first row, and the rule box
247// closes.
248async function showView($: EngineInterface, view: 'notifications' | 'filters') {
249  await update($, filters, s => ({ ...s, view, editing: null }))
250  const ring = view === 'filters' ? ruleRing : rowRing
251  ring.index = 0
252  await move($, ring, 0)
253}
254
255// What an answer of add, set or remove means for the person. 0 'ok': the
256// file changed, so the list is read again. 3 'stale': the line moved under
257// the pane, so the list is read again. Any other answer is 'failed'; for 2
258// the script refused the rule, and the first line of its stderr says why.
259// Only this function reads the exit codes.
260async function settle(
261  $: EngineInterface,
262  answer: Awaited<ReturnType<typeof runFilter>>,
263): Promise<'ok' | 'stale' | 'failed'> {
264  if (answer?.exitCode === 0) {
265    await pollFilters($)
266    return 'ok'
267  }
268  if (answer?.exitCode === 3) {
269    await pollFilters($)
270    $.ui.toast(STALE)
271    return 'stale'
272  }
273  if (answer?.exitCode === 2) {
274    $.ui.toast(answer.stderr.split('\n')[0]?.trim() || 'The rule was not saved.')
275    return 'failed'
276  }
277  $.ui.toast('The filter file did not change.')
278  return 'failed'
279}
280
281// The rule box takes the keys. In a test, and while the pane does not hold
282// the keys, the engine refuses: the box is drawn all the same.
283async function openBox($: EngineInterface, editing: NonNullable<FilterEditing>) {
284  await update($, filters, s => ({ ...s, editing }))
285  await askFocus($, INPUT_KEY)
286}
287
288// `a`: a new rule, `allow ` ready in the box.
289async function addRule($: EngineInterface) {
290  await openBox($, { mode: 'add', value: 'allow ' })
291}
292
293// `e`, or Enter on a row: the box holds the rule, to replace its line.
294async function editRule($: EngineInterface, index?: number) {
295  if (index !== undefined) ruleRing.index = index
296  const row = at((await read($, filters)).rules, ruleRing)
297  if (!row) return
298  await openBox($, { mode: 'set', n: row.n, value: editValue(row) })
299}
300
301// Enter in the box. A refused rule keeps the box open with what the person
302// typed; a stale line closes it, because its line number is no longer true.
303async function submitRule($: EngineInterface, value: string) {
304  const { editing } = await read($, filters)
305  if (!editing) return
306  // The box can close while the script runs (Esc, or `n`). A refused rule
307  // then keeps it closed.
308  const keep = () => update($, filters, s => (s.editing ? { ...s, editing: { ...s.editing, value } } : s))
309  const rule = splitRule(value)
310  if (!rule) {
311    $.ui.toast(BAD_KIND)
312    await keep()
313    return
314  }
315  const answer = editing.mode === 'add'
316    ? await runFilter($, 'add', [rule.kind, rule.regex])
317    : await runFilter($, 'set', [String(editing.n), rule.kind, rule.regex])
318  const outcome = await settle($, answer)
319  if (outcome === 'ok' || outcome === 'stale') {
320    await update($, filters, s => ({ ...s, editing: null }))
321    return
322  }
323  await keep()
324}
325
326// `t`: allow becomes deny and deny becomes allow, with the same regex. An
327// invalid row has no kind to change: `e` mends it.
328async function toggleRule($: EngineInterface) {
329  const row = at((await read($, filters)).rules, ruleRing)
330  if (!row || row.kind === 'invalid') return
331  await settle($, await runFilter($, 'set', [String(row.n), row.kind === 'allow' ? 'deny' : 'allow', row.text]))
332}
333
334// `x`: the focused line goes. The ring stays at the same place, so taking
335// the last row out moves it up one.
336async function removeRule($: EngineInterface) {
337  const row = at((await read($, filters)).rules, ruleRing)
338  if (!row) return
339  if ((await settle($, await runFilter($, 'remove', [String(row.n)]))) !== 'ok') return
340  await move($, ruleRing, 0)
341}
342
343// The row index in a ring key such as `row:3`, or undefined for another key.
344function indexAfter(key: string, prefix: string): number | undefined {
345  if (!key.startsWith(prefix)) return undefined
346  const index = Number(key.slice(prefix.length))
347  return Number.isInteger(index) && index >= 0 ? index : undefined
348}
349
350export const register: Register = on => {
351  // The matcher does two jobs. A `-p` run or the SDK has no person at the
352  // prompt and no pane to show; and the sessions pane already registers
353  // `session.start` with no matcher, and two unmatched hooks on one event in
354  // one module are refused by the engine.
355  on('session.start', { isInteractive: true }, async ($, e, next) => {
356    try {
357      loop.queue = await queuePath($)
358      const file = await filterPath($)
359      await update($, filters, s => ({ ...s, file }))
360      await tick($)
361      loop.timer?.cancel()
362      loop.timer = $.clock.every(POLL_MS, () => void tick($))
363    } catch (error) {
364      $.ui.log(`clux notifications: start failed: ${String(error)}`, { to: 'debug' })
365    }
366
367    return next(e)
368  })
369
370  // `/clux:notifications` alone toggles the pane: it closes a pane that
371  // shows, and opens one that is closed or a tab behind another. `on` and
372  // `off` set it.
373  on('command.run', { command: COMMAND }, async ($, e) => {
374    const arg = e.args.trim()
375    const isShown = (await $.ui.panes()).some(pane => pane.id === PANE && pane.isShown)
376    if (arg === 'off' || (arg !== 'on' && isShown)) {
377      await $.ui.close({ id: PANE })
378      return { text: 'Notifications pane closed.' }
379    }
380    await openPane($)
381
382    return { text: 'Notifications pane opened. Press Enter to go to a notification, or x to remove it.' }
383  }).catch(($, e, next) => {
384    $.ui.log(`clux notifications: command failed: ${String(next.error)}`, { to: 'debug' })
385    return { text: 'The notifications pane did not respond. Try the command again.' }
386  })
387
388  // The ring records the row it lands on, then moves on: a `ui.focus` hook
389  // that does not call `next` keeps the ring where it was, so Tab, the
390  // arrows, `j`, `k` and `x` would all move nothing. A header button, or one
391  // of the engine's own stops (the close mark, with no `element`), leaves
392  // the index as it was, so `x` still acts on the row last focused.
393  //
394  // The rule box closes when the ring leaves it for a row or a button: a box
395  // the person left holds no edit they can see through. Esc gives the keys
396  // to the prompt instead, and `closeLostBox` closes the box then.
397  on('ui.focus', { requestId: PANE }, async ($, e, next) => {
398    const key = e.element ?? ''
399    rowRing.index = indexAfter(key, rowRing.prefix) ?? rowRing.index
400    ruleRing.index = indexAfter(key, ruleRing.prefix) ?? ruleRing.index
401    if (key !== INPUT_KEY && (await read($, filters)).editing) {
402      await update($, filters, s => ({ ...s, editing: null }))
403    }
404
405    return next(e)
406  }).catch(($, e, next) => (next.called ? {} : next(e)))
407
408  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
409    const elements = $.ui.resolve(e)
410    const { Box, Text, Button } = elements
411    // The mobile surface draws no Input: there the rule box is not drawn,
412    // and the rules are read only.
413    const Input = 'Input' in elements ? elements.Input : undefined
414    const list = await read($, notifications)
415    const state = await read($, filters)
416    const isFilters = state.view === 'filters'
417    const hasRepo = state.file !== ''
418    // The row text is cut to the pane, so one long notification cannot
419    // reflow the list.
420    const width = Math.max(8, e.props.bodyColumns - 1)
421    // Esc in the rule box gives the keys to the prompt, not to the ring, so
422    // no `ui.focus` closes the box. A pane without the keys draws no box, and
423    // its first row has the `autoFocus`, so the pane can take the keys again.
424    // Drawing is pure: `closeLostBox` clears the state.
425    const editing = e.props.isFocused ? state.editing : null
426
427    return (
428      <Box flexDirection="column">
429        {/* The two views, the one that shows in bold. */}
430        <Box>
431          <Text bold={!isFilters}>{TITLE} · {list.length}</Text>
432          <Text>  |  </Text>
433          <Text bold={isFilters}>Filters · {validCount(state.rules)}</Text>
434        </Box>
435        {/* The keys go on a line of their own, and wrap in a narrow pane, so
436            the counts above never wrap. Only the keys of the view that shows:
437            a hotkey of the other view would act on rows the person cannot
438            see. Claude Code draws a plain Button with a hotkey as "j: down". */}
439        <Box flexWrap="wrap" columnGap={1}>
440          {/* Over the footer's label: the chord closes an open pane, and `q`
441              closes it while the pane has the keys. Plain, so it reads
442              "q: hide", as the other keys do. Both views draw it. */}
443          <Button
444            key="close-notifications"
445            plain
446            hotkey="q"
447            label="hide"
448            action={TOGGLE_ACTION}
449            onPress={() => $.ui.close({ id: PANE })}
450          />
451          {isFilters ? [
452            <Button key="view-notifications" plain hotkey="n" label="notifications" onPress={() => showView($, 'notifications')} />,
453            hasRepo && [
454              <Button key="rule-down" plain hotkey="j" label="down" onPress={() => move($, ruleRing, 1)} />,
455              <Button key="rule-up" plain hotkey="k" label="up" onPress={() => move($, ruleRing, -1)} />,
456              <Button key="rule-add" plain hotkey="a" label="add" onPress={() => addRule($)} />,
457              <Button key="rule-edit" plain hotkey="e" label="edit" onPress={() => editRule($)} />,
458              <Button key="rule-toggle" plain hotkey="t" label="allow/deny" onPress={() => toggleRule($)} />,
459              <Button key="rule-remove" plain hotkey="x" label="remove" onPress={() => removeRule($)} />,
460            ],
461          ] : [
462            <Button key="nav-down" plain hotkey="j" label="down" onPress={() => move($, rowRing, 1)} />,
463            <Button key="nav-up" plain hotkey="k" label="up" onPress={() => move($, rowRing, -1)} />,
464            <Button key="row-remove" plain hotkey="x" label="remove" onPress={() => removeRow($)} />,
465            <Button key="view-filters" plain hotkey="f" label="filters" onPress={() => showView($, 'filters')} />,
466          ]}
467        </Box>
468        {isFilters ? (
469          hasRepo ? [
470            <Text key="filter-file" dimColor>{state.file.slice(0, width)}</Text>,
471            state.rules.length === 0 && (
472              <Text key="no-filters" dimColor>No filters. a: add a rule.</Text>
473            ),
474            // A Button draws no color of its own, so an invalid row draws its
475            // text as red children: the word, then the raw line, cut so that
476            // the two fit the pane. The label still names the row. Enter on a
477            // row edits it. While the box is open it has the `autoFocus`, so
478            // a pane that takes the keys again lands in the box.
479            ...state.rules.map((row, i) => {
480              const isInvalid = row.kind === 'invalid'
481              const label = rowText(row).slice(0, isInvalid ? Math.max(1, width - INVALID_MARK.length) : width)
482              return (
483                <Button
484                  key={`rule:${i}`}
485                  autoFocus={i === 0 && !editing ? true : undefined}
486                  plain
487                  label={label}
488                  onPress={() => editRule($, i)}
489                >
490                  {isInvalid ? [
491                    <Text key="invalid-mark" color="red">{INVALID_MARK}</Text>,
492                    <Text key="invalid-line" color="red">{label}</Text>,
493                  ] : label}
494                </Button>
495              )
496            }),
497            editing && Input && (
498              <Input
499                key={INPUT_KEY}
500                autoFocus
501                // The box draws the colon after the label.
502                label={editing.mode === 'add' ? 'new rule' : `line ${editing.n}`}
503                placeholder="allow|deny <regex>"
504                value={editing.value}
505                submitLabel="save"
506                onSubmit={(value: string) => submitRule($, value)}
507              />
508            ),
509          ] : <Text dimColor>Not in a git repo.</Text>
510        ) : [
511          // Claude Code opens a pane without the keys while the message box
512          // has a draft, and a mod cannot take them: the person moves in.
513          !e.props.isFocused && list.length > 0 && (
514            <Text key="move-in" dimColor>ctrl+x tab: move into the list</Text>
515          ),
516          list.length === 0 && <Text key="no-notifications" dimColor>No notifications.</Text>,
517          ...list.map((row, i) => (
518            <Button
519              key={`row:${i}`}
520              autoFocus={i === 0 ? true : undefined}
521              plain
522              label={row.text.slice(0, width)}
523              onPress={() => jumpTo($, row)}
524            />
525          )),
526        ]}
527      </Box>
528    )
529  })
530
531  // No band: one label at the end of the prompt footer, so a click opens the
532  // pane while it is closed, and the chord has a Button to press. It is dim
533  // until the queue has something in it.
534  //
535  // `next(e)` draws first, so the sessions label stays on the left. The
536  // separator needs no condition: the sessions hook always draws its own
537  // label, so `next(e)` is never empty.
538  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
539    const list = await read($, notifications)
540    const { Box, Text, Button } = $.ui.resolve(e)
541
542    return (
543      <Box>
544        {await next(e)}
545        <Text dimColor> & </Text>
546        <Button
547          key="open-notifications"
548          plain
549          dimColor={list.length === 0}
550          label={list.length > 0 ? `${list.length} notifs` : 'notifs'}
551          action={TOGGLE_ACTION}
552          onPress={() => openPane($)}
553        />
554      </Box>
555    )
556  })
557}
558
hooks/sessions/register.tsx 251 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { BgSession, BgStatus } from '../../types'
5import {
6  LABEL,
7  isFresh,
8  mentionText,
9  sortSessions,
10  toSession,
11  worktreePaths,
12} from './jobs'
13
14const PANE = 'sessions'
15// commands/sessions.md declares it; the hook below answers it.
16const COMMAND = 'clux:sessions'
17// The chord that toggles the pane, also with a draft in the composer. No
18// engine action runs a plugin command, so the mod borrows this one: its
19// engine handler is mounted only in the diff panel, where it keeps its job.
20const TOGGLE_ACTION = 'app:cycleDiffBase'
21const TITLE = 'Background sessions'
22const POLL_MS = 5000
23// Read the worktree list again after this many polls (one minute).
24const ROOTS_EVERY = 12
25
26const sessions = atom({ plugin: 'clux', key: 'sessions' } as const, [])
27
28const COLOR: Record<BgStatus, string> = {
29  'needs-input': 'warning',
30  working: 'suggestion',
31  unknown: 'inactive',
32  done: 'success',
33  failed: 'error',
34  stopped: 'inactive',
35}
36
37// What a poll needs. Only `roots` changes, when a worktree is added.
38type Scope = { dir: string; roots: string[]; selfId: string }
39
40async function jobsDir($: EngineInterface): Promise<string> {
41  const config = await $.env.get('CLAUDE_CONFIG_DIR')
42  if (config) return `${config}/jobs`
43  return `${await $.env.get('HOME')}/.claude/jobs`
44}
45
46// The main working tree and every worktree of the repository, also a
47// worktree outside the main tree; the session's folder outside git. Each
48// root also as the path it lands on, for a root behind a symbolic link.
49async function repoRoots($: EngineInterface): Promise<string[]> {
50  const repo = await $.session.repo().catch(() => null)
51  let paths = [await $.session.cwd()]
52  if (repo) {
53    const listed = await $.process
54      .run(['git', '-C', repo.root, 'worktree', 'list', '--porcelain'])
55      .catch(() => undefined)
56    paths = [repo.root, ...(listed?.exitCode === 0 ? worktreePaths(listed.stdout) : [])]
57  }
58  const real = await Promise.all(
59    paths.map(path =>
60      $.fs.stat(path, { resolve: true }).then(stat => stat.realPath, () => undefined),
61    ),
62  )
63  return [...new Set([...paths, ...real.filter((path): path is string => !!path)])]
64}
65
66async function readSessions($: EngineInterface, scope: Scope, now: number) {
67  const entries = await $.fs.list(scope.dir).catch(() => [])
68  const texts = await Promise.all(
69    entries
70      .filter(entry => entry.kind === 'dir')
71      .map(async entry => ({
72        id: entry.name,
73        text: await $.fs.read(`${scope.dir}/${entry.name}/state.json`).catch(() => ''),
74      })),
75  )
76  const found = texts.flatMap(({ id, text }) => {
77    if (typeof text !== 'string' || text === '') return []
78    const session = toSession(id, text, scope.roots, scope.selfId, now)
79    return session && isFresh(session, now) ? [session] : []
80  })
81
82  return sortSessions(found)
83}
84
85async function poll($: EngineInterface, scope: Scope) {
86  const now = await $.clock.now()
87  const list = await readSessions($, scope, now)
88  const before = await read($, sessions)
89  if (JSON.stringify(list) !== JSON.stringify(before)) {
90    await update($, sessions, () => list)
91  }
92}
93
94// Asked (a command, a press) it seats at any width; `focus` hands it the keys.
95function openPane($: EngineInterface) {
96  return $.ui.open({ id: PANE, title: TITLE, focus: true })
97}
98
99// Selecting a session puts its @name in the message box at the cursor. The
100// pane closes first, so the keys go back to the box for the next word.
101async function mention($: EngineInterface, session: BgSession) {
102  const draft = await $.prompt.read().catch(() => undefined)
103  if (!draft) {
104    $.ui.toast(`Could not put @${session.name} in the message box.`)
105    return
106  }
107  const { text, cursor } = draft
108  const handle = mentionText(session.name, text.slice(0, cursor))
109  await $.ui.close({ id: PANE })
110  const filled = await $.prompt.fill({ text: handle, mode: 'insert' }).catch(() => undefined)
111  if (!filled?.isFilled) $.ui.toast(`Could not put @${session.name} in the message box.`)
112}
113
114const countNeeds = (list: readonly BgSession[]) =>
115  list.filter(s => s.status === 'needs-input').length
116
117// The poll loop of this session: set at the start, read by each tick.
118const loop: { scope?: Scope; timer?: Timer; isPolling: boolean; polls: number } = {
119  isPolling: false,
120  polls: 0,
121}
122
123// One poll at a time, so a slow poll and the next tick never overlap.
124async function tick($: EngineInterface) {
125  const scope = loop.scope
126  if (!scope || loop.isPolling) return
127  loop.isPolling = true
128  try {
129    loop.polls += 1
130    if (loop.polls % ROOTS_EVERY === 0) scope.roots = await repoRoots($)
131    await poll($, scope)
132  } catch (error) {
133    $.ui.log(`clux sessions: poll failed: ${String(error)}`, { to: 'debug' })
134  } finally {
135    loop.isPolling = false
136  }
137}
138
139export const register: Register = on => {
140  on('session.start', async ($, e, next) => {
141    // A `-p` run or the SDK has no person at the prompt and no pane to show.
142    if (!e.isInteractive) return next(e)
143    try {
144      loop.scope = {
145        dir: await jobsDir($),
146        roots: await repoRoots($),
147        selfId: await $.session.id(),
148      }
149      await tick($)
150      loop.timer?.cancel()
151      loop.timer = $.clock.every(POLL_MS, () => void tick($))
152    } catch (error) {
153      $.ui.log(`clux sessions: start failed: ${String(error)}`, { to: 'debug' })
154    }
155
156    return next(e)
157  })
158
159  // `/clux:sessions` alone toggles the pane: it closes a pane that shows, and
160  // opens one that is closed or a tab behind another. `on` and `off` set it.
161  on('command.run', { command: COMMAND }, async ($, e) => {
162    const arg = e.args.trim()
163    const isShown = (await $.ui.panes()).some(pane => pane.id === PANE && pane.isShown)
164    if (arg === 'off' || (arg !== 'on' && isShown)) {
165      await $.ui.close({ id: PANE })
166      return { text: 'Background sessions pane closed.' }
167    }
168    await tick($)
169    await openPane($)
170
171    return { text: 'Background sessions pane opened. Press Enter or a number to put a session in the message box.' }
172  }).catch(($, e, next) => {
173    $.ui.log(`clux sessions: command failed: ${String(next.error)}`, { to: 'debug' })
174    return { text: 'The background sessions pane did not respond. Try the command again.' }
175  })
176
177  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
178    const { Box, Text, Button, Link } = $.ui.resolve(e)
179    const list = await read($, sessions)
180    const nameWidth = Math.min(28, Math.max(8, ...list.map(s => s.name.length)))
181
182    return (
183      <Box flexDirection="column">
184        <Box>
185          <Text bold>{TITLE} · {list.length} </Text>
186          {/* Over the footer's label: the chord closes an open pane. */}
187          <Button
188            key="close-sessions"
189            label="Hide"
190            action={TOGGLE_ACTION}
191            onPress={() => $.ui.close({ id: PANE })}
192          />
193        </Box>
194        {/* Claude Code opens a pane without the keys while the message box
195            has a draft, and a mod cannot take them: the person moves in. */}
196        {!e.props.isFocused && list.length > 0 && (
197          <Text dimColor>ctrl+x tab: move into the list</Text>
198        )}
199        {list.length === 0 && (
200          <Text dimColor>No background sessions for this repository.</Text>
201        )}
202        {list.map((s, i) => (
203          // Name, status and PRs keep their width; the description is cut.
204          <Box key={`row-${s.id}`}>
205            <Box flexShrink={0}>
206              <Button
207                key={`mention-${s.id}`}
208                autoFocus={i === 0 ? true : undefined}
209                plain
210                hotkey={i < 9 ? String(i + 1) : undefined}
211                label={s.name.slice(0, nameWidth).padEnd(nameWidth)}
212                onPress={() => mention($, s)}
213              />
214              <Text color={COLOR[s.status]}> ● {LABEL[s.status].padEnd(12)}</Text>
215              {s.prs.map(pr => (
216                <Link key={`pr-${s.id}-${pr.id}`} href={pr.href} label={`#${pr.id} `} />
217              ))}
218            </Box>
219            <Box flexShrink={1} minWidth={0}>
220              <Text dimColor wrap="truncate-end">{s.line}</Text>
221            </Box>
222          </Box>
223        ))}
224      </Box>
225    )
226  })
227
228  // No band: one label at the end of the prompt footer, so the chord has a
229  // Button to press while the pane is closed. It is dim until a question waits.
230  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
231    const needs = countNeeds(await read($, sessions))
232    const { Box, Text, Button } = $.ui.resolve(e)
233
234    // The footer is one instance: draw what the hooks below draw, then this.
235    return (
236      <Box>
237        {await next(e)}
238        {e.props.modes.length > 0 && <Text dimColor> & </Text>}
239        <Button
240          key="open-sessions"
241          plain
242          dimColor={needs === 0}
243          label={needs > 0 ? `${needs} needs input` : 'sessions'}
244          action={TOGGLE_ACTION}
245          onPress={() => openPane($)}
246        />
247      </Box>
248    )
249  })
250}
251
hooks/notifications/filters.ts 53 lines
1// Pure helpers: the output of `notify-filter.sh list` as rows, and the text
2// of the rule box as a rule. No `$` here, so the tests can call these
3// directly.
4//
5// There is deliberately NO regex check here. scripts/notify-filter.sh owns
6// the parse of the file and the regex type (grep -E); a second copy in
7// TypeScript is the copy that disagrees with the hook (for example on \d).
8
9import type { FilterRow } from '../../types'
10
11// One row for each "<n>\t<kind>\t<text>" line, in file order. The text is the
12// rest of the line, tabs and all. A line of another shape is skipped.
13export function parseList(stdout: string): FilterRow[] {
14  return stdout.split('\n').flatMap(line => {
15    const [num, kind, ...rest] = line.split('\t')
16    if (rest.length === 0) return []
17    const n = Number(num)
18    if (!Number.isInteger(n) || n < 1) return []
19    if (kind !== 'allow' && kind !== 'deny' && kind !== 'invalid') return []
20    return [{ n, kind, text: rest.join('\t') }]
21  })
22}
23
24// The rules that count: an invalid line hides nothing.
25export function validCount(rows: FilterRow[]): number {
26  return rows.filter(row => row.kind !== 'invalid').length
27}
28
29// What a row reads: "allow  ^feat-", the regexes in one column. An invalid
30// row reads as the raw line.
31export function rowText(row: FilterRow): string {
32  return row.kind === 'invalid' ? row.text : `${row.kind.padEnd(5)}  ${row.text}`
33}
34
35// The text the rule box opens with for `e`: "<kind> <regex>", or the raw line
36// of an invalid row, so the person can mend it.
37export function editValue(row: FilterRow): string {
38  return row.kind === 'invalid' ? row.text : `${row.kind} ${row.text}`
39}
40
41// The rule box text as a rule: the first word, then the rest, with the spaces
42// at the start and the end removed. Null when the first word is not allow or
43// deny. An empty regex is still a rule here: the script refuses it, and says
44// why.
45export function splitRule(text: string): { kind: 'allow' | 'deny'; regex: string } | null {
46  const trimmed = text.trim()
47  const space = trimmed.search(/\s/)
48  const word = space === -1 ? trimmed : trimmed.slice(0, space)
49  const regex = space === -1 ? '' : trimmed.slice(space).trim()
50  if (word !== 'allow' && word !== 'deny') return null
51  return { kind: word, regex }
52}
53
hooks/notifications/lines.ts 30 lines
1// Pure helpers: the notification queue file as rows. No `$` here, so the
2// tests can call these directly.
3//
4// There is deliberately NO target parse here. scripts/notification-line.sh
5// owns that, and a second copy in TypeScript is the copy that goes out of
6// step. These functions only cut the id marker off the text a person reads.
7
8import type { NotifRow } from '../../types'
9
10// What the person reads: the part before the ||| id marker. show-notification.sh
11// cuts the same marker for the status bar.
12export function displayText(line: string): string {
13  const triple = line.indexOf('|||')
14  return triple === -1 ? line : line.slice(0, triple)
15}
16
17// One row for each line that is not empty, in file order. The row keeps the
18// whole line, because `jump` and `remove` take the line exactly as it is.
19export function toRows(text: string): NotifRow[] {
20  return text.split('\n').flatMap(line =>
21    line === ''
22      ? []
23      : [{
24          line,
25          text: displayText(line),
26          kind: line.includes('|||agent:') ? ('agent' as const) : ('window' as const),
27        }],
28  )
29}
30
hooks/sessions/jobs.ts 135 lines
1// Pure helpers: turn a background job's state.json into one row of the
2// sessions pane. No `$` here, so the tests can call these directly.
3
4import type { BgPr, BgSession, BgStatus } from '../../types'
5
6// Finished sessions older than this drop off the list.
7const KEEP_FINISHED_MS = 3 * 24 * 60 * 60 * 1000
8// A working session writes its state every few seconds. With no write for
9// this long it has probably stopped without a last write.
10const STALE_WORKING_MS = 30 * 60 * 1000
11
12type JobState = {
13  state?: string
14  tempo?: string
15  name?: string
16  detail?: string
17  needs?: string
18  output?: { result?: string } | null
19  children?: { id?: string; href?: string; kind?: string }[]
20  cwd?: string
21  worktreePath?: string
22  sessionId?: string
23  updatedAt?: string
24}
25
26const ORDER: Record<BgStatus, number> = {
27  'needs-input': 0,
28  working: 1,
29  unknown: 2,
30  done: 3,
31  failed: 4,
32  stopped: 5,
33}
34
35export const LABEL: Record<BgStatus, string> = {
36  'needs-input': 'needs input',
37  working: 'working',
38  unknown: 'unknown',
39  done: 'done',
40  failed: 'failed',
41  stopped: 'stopped',
42}
43
44// A state this mod does not know shows as unknown, so the row stays visible.
45function statusOf(job: JobState, updatedAt: number, now: number): BgStatus {
46  if (job.state === 'blocked' || job.tempo === 'blocked') return 'needs-input'
47  if (job.state === 'working' || job.state === 'running') {
48    return now - updatedAt > STALE_WORKING_MS ? 'unknown' : 'working'
49  }
50  if (job.state === 'done') return 'done'
51  if (job.state === 'failed') return 'failed'
52  if (job.state === 'stopped') return 'stopped'
53  return 'unknown'
54}
55
56function prsOf(job: JobState): BgPr[] {
57  return (job.children ?? []).flatMap(child =>
58    child.kind === 'pr' && child.id && child.href
59      ? [{ id: child.id, href: child.href }]
60      : [],
61  )
62}
63
64// True when `path` is `root` or a folder below it.
65export function isUnder(path: string | undefined, root: string): boolean {
66  if (!path) return false
67  const base = root.replace(/\/+$/, '')
68  return path === base || path.startsWith(base + '/')
69}
70
71// One state.json as a row, or undefined when it is not under one of the
72// repository's worktrees, is this session itself, or does not parse.
73export function toSession(
74  id: string,
75  text: string,
76  roots: readonly string[],
77  selfId: string,
78  now: number,
79): BgSession | undefined {
80  let job: JobState
81  try {
82    job = JSON.parse(text) as JobState
83  } catch {
84    return undefined
85  }
86  if (job.sessionId && job.sessionId === selfId) return undefined
87  const isOurs = roots.some(
88    root => isUnder(job.cwd, root) || isUnder(job.worktreePath, root),
89  )
90  if (!isOurs) return undefined
91  const updatedAt = Date.parse(job.updatedAt ?? '') || 0
92  const status = statusOf(job, updatedAt, now)
93  // The description: the question of a session that needs input, what the
94  // session does now, or the result it gave.
95  const line =
96    status === 'stopped' ? ''
97    : status === 'needs-input' ? (job.needs || job.detail || '')
98    : (job.detail || job.output?.result || '')
99
100  return {
101    id,
102    name: job.name || id,
103    status,
104    prs: prsOf(job),
105    line: line.replace(/\s+/g, ' ').trim(),
106    updatedAt,
107  }
108}
109
110export function isFresh(session: BgSession, now: number): boolean {
111  const isLive = session.status === 'needs-input' || session.status === 'working'
112  return isLive || now - session.updatedAt < KEEP_FINISHED_MS
113}
114
115export function sortSessions(list: readonly BgSession[]): BgSession[] {
116  return [...list].sort(
117    (a, b) => ORDER[a.status] - ORDER[b.status] || b.updatedAt - a.updatedAt,
118  )
119}
120
121// The worktree paths that `git worktree list --porcelain` prints.
122export function worktreePaths(porcelain: string): string[] {
123  return porcelain
124    .split('\n')
125    .filter(line => line.startsWith('worktree '))
126    .map(line => line.slice('worktree '.length))
127}
128
129// The text that names a session in the message box: its @name and a space,
130// with a space before it when the cursor follows a word.
131export function mentionText(name: string, before: string): string {
132  const gap = before === '' || /\s$/.test(before) ? '' : ' '
133  return `${gap}@${name} `
134}
135
types/index.d.ts 57 lines
1export type BgStatus = 'needs-input' | 'working' | 'unknown' | 'done' | 'failed' | 'stopped'
2
3export type BgPr = { id: string; href: string }
4
5export type BgSession = {
6  id: string
7  name: string
8  status: BgStatus
9  prs: BgPr[]
10  line: string
11  updatedAt: number
12}
13
14// One line of the clux notification queue, as the notifications pane draws
15// it. `line` is the whole line, the argument of notification-line.sh; `text`
16// is what the person reads. The pane does not draw `kind`: the text of an
17// agent line already starts with its marker. Enter reads it: the jump of an
18// agent line removes the line, so only a window line needs a `remove`.
19export type NotifRow = {
20  line: string
21  text: string
22  kind: 'agent' | 'window'
23}
24
25// One line of the repo filter file, as `notify-filter.sh list` prints it.
26// `n` is the line number in the file, the argument of `set` and `remove`.
27// `text` is the regex, or the raw line for an `invalid` row.
28export type FilterRow = {
29  n: number
30  kind: 'allow' | 'deny' | 'invalid'
31  text: string
32}
33
34// The rule box under the list: closed, adding a rule, or replacing line `n`.
35// `value` is the text the box shows; after a refused rule it holds what the
36// person typed, so a redraw does not lose it.
37export type FilterEditing = null | { mode: 'add'; value: string } | { mode: 'set'; n: number; value: string }
38
39// The Filters view of the notifications pane. `file` is the filter file path,
40// or '' when the session cwd is not in a git repo.
41export type FiltersState = {
42  view: 'notifications' | 'filters'
43  file: string
44  rules: FilterRow[]
45  editing: FilterEditing
46}
47
48declare module 'claude-code' {
49  interface PluginState {
50    'clux': {
51      sessions: BgSession[]
52      notifications: NotifRow[]
53      filters: FiltersState
54    }
55  }
56}
57