SLOPSHOPPER

session-fleet

Fleet board of live sessions, a needs-you beacon, and a worktree claim guard, shared across sessions

panebandguardcommandtoastprompt
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-fleet
│ ┃ fleet ✕ › fix the failing auth test and add an audit log call │ ┃ 1 live · 0 waiting on you │ ┃ ⏺ Read(src/auth.ts) │ ┃ ╭─────────────────────────────────────────── ⎿ Read 6 lines │ ┃ │ ○ app fix the failing auth test (this se ⏺ Update(src/auth.ts) │ ┃ │ /work/app ⎿ Added 2 lines, removed 1 line │ ┃ │ no branch ⏺ Bash(bun test) │ ┃ │ $ cat .env · 0s ago ⎿ 3 pass, 1 fail │ ┃ │ [ ✎ Rename ] │ ┃ ╰─────────────────────────────────────────── ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /fleet │ ⎿ session-fleet: Fleet board hidden. │ │ ▸ Fleet board · 1 live ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
▸ Fleet board · 1 live ⟨Claude Code's own drawing⟩
Pane · fleet
1 live · 0 waiting on you ╭──────────────────────────────────────────────────────────╮ │ ○ app fix the failing auth test (this session) │ │ /work/app │ │ no branch │ │ $ cat .env · 0s ago │ │ [ ✎ Rename ] │ ╰──────────────────────────────────────────────────────────╯
README

Claude Code mods for running a lot of sessions at once

Five Claude Code mods built from how I actually use Claude Code: four to six sessions at a time, mostly in one repo, a lot of PRs going to production, and a pile of rules I keep forgetting to check.

Claude built all five. The full story, with screenshots, videos and the bugs a real run caught, is on my site: I asked Claude to read 30 of my Claude Code sessions and build the mods I needed

The session-fleet pane listing two live sessions, one waiting on a permission prompt

The prompt

This is what I gave Claude Code. It read my last 30 sessions, came back with ten ideas, and built all ten as these five mods.

look at the last 30 sessions and see how we use claude to work - then look at https://code.claude.com/docs/en/plugins/mods/overview and suggest 10 possible mods for our workflow that would help me be better informed as to what each session is doing.

Run it on your own sessions. Your ten ideas will probably come out different from mine, and I'd like to see them.

The five mods

ModWhat it gives youCommands
session-fleetA board of every live session, a "needs you" row when another session is blocked on you, and a guard when two sessions write to the same worktree/fleet
ship-trackerA row per PR: CI → merged → production deployment → live, a warning when a merge never deploys, and a receipt line after every answer/ship-track <pr>
session-hygieneConfigurable tripwires (typecheck before push, review before push, mutation-check new tests and more), plus a handoff card of loose ends from earlier sessions/handoff, /handoff clear
session-activityA ledger of everything that left the machine, a hold on database writes, and what each session is waiting on/ledger, /waiting
context-gaugeContext fill in the status line, warnings before compaction, and a snapshot of in-flight work that survives compaction/context-log

They work on their own. Install any one, or all five.

Install

You need a Claude Code version with mods (see the mods docs), git, and for ship-tracker and the handoff card, the GitHub CLI signed in.

A mod is code that runs with your permissions inside Claude Code. Read it before you install it. Each one is a single hooks/register.tsx file, and claude plugin validate <folder> lists exactly which events it hooks and what it calls.

From the marketplace

In a Claude Code session:

/plugin marketplace add bennewton999/claude-code-mods
/plugin install session-fleet@bennewton-mods
/plugin install ship-tracker@bennewton-mods
/plugin install session-hygiene@bennewton-mods
/plugin install session-activity@bennewton-mods
/plugin install context-gauge@bennewton-mods

Then /reload-plugins, or start a new session.

From a clone

git clone https://github.com/bennewton999/claude-code-mods ~/claude-code-mods

Load them in every session by adding the folders to env in ~/.claude/settings.json (colon-separated):

{
  "env": {
    "CLAUDE_CODE_PLUGIN_DIRS": "/Users/you/claude-code-mods/session-fleet:/Users/you/claude-code-mods/ship-tracker:/Users/you/claude-code-mods/session-hygiene:/Users/you/claude-code-mods/session-activity:/Users/you/claude-code-mods/context-gauge",
    "CLAUDE_CODE_PLUGIN_DIR_WATCH": "1"
  }
}

Or try one for a single session:

claude --plugin-dir ~/claude-code-mods/session-fleet

CLAUDE_CODE_PLUGIN_DIR_WATCH makes desktop app sessions hot-reload a mod when its files change (an interactive terminal session already does). A session reads it at startup, so sessions that were already open pick up the mods, and the watch, after one restart.

What each one does

session-fleet

Every session writes one record to a key-value store that all sessions on the machine share ($.store), with a heartbeat every 30 seconds. Three minutes without a heartbeat and the session counts as gone.

  • Fleet board. A pane with a card for every live session: a status dot, its name (the first prompt until you rename it; there's no session title API), the worktrees it's touching, branch, PR, last action and how long ago. Waiting sessions sort to the top, and a worktree two live sessions share gets a ⚠. The board opens when a session starts; /fleet or the toggle above the prompt shows and hides it.
  • Switch and rename. In the desktop app, each card for another session has a Switch → button that jumps to it, the same as clicking it in the sidebar. Terminal sessions have no Switch button. ✎ Rename gives a session a name that every session's board shows; saving it empty goes back to the first prompt.
  • Project pills. Each session gets a pill naming its repo. To name and color your own projects, set projectPills to Label:regex:color entries separated by ;, the regex tested against the repo folder name:
  "pluginConfigs": {
    "session-fleet": {
      "options": { "projectPills": "Work:acme|billing:#2563eb; Blog:blog:#059669" }
    }
  }
  • Needs you. When another session is blocked on you, its card gets a yellow ⚑ NEEDS YOU badge and border, and a row with the same badge shows above your prompt with the reason, how long it has waited and a Switch → button, plus a toast. "Blocked" means a permission prompt, a question dialog, or a turn that ended with a question mark. That last one is a guess.
  • Worktree guard. The first session to edit a file or run a mutating git command (commit, checkout, rebase, push…) in a worktree claims it. A second live session that tries gets a Proceed or Stop question naming the other session, its branch and last action. Claims let go after 30 minutes idle.

The needs-you row above the prompt The worktree guard question

ship-tracker

  • Picks up PRs from gh pr output, or add one with /ship-track 1107 or /ship-track owner/repo#1107.
  • Every 45 seconds it reads the PR state and checks from GitHub. After the merge, it finds the GitHub deployment for the merge commit in the Production environment. Live means that deployment succeeded.
  • Merged for 15 minutes with no production deployment? The row says no prod deploy!. That's the silent Vercel git-trigger failure that got me before.
  • A receipt line after every answer: duration, tool calls, files edited, shell commands, outward actions (push, PR, MCP writes) and context fill.

Two PRs in the ship band

session-hygiene

Tripwires for rules you keep forgetting. When one trips you get a transcript line and a toast, and Claude gets a reminder with the tool result so it can act on it.

Every rule is a plugin option. You set them on the install screen, or later in /config. Out of the box only the two generic rules are on; the rest stay off until you point them at your repos.

OptionDefaultWhat it does
holdEnvSourcingonAsks Run it or Stop before a command sources a .env file into the shell
mutationCheckTestsonWhen Claude writes a new test file, reminds it to prove the test fails without the code it covers
reviewBeforePushoffFlags a git push with edits made since the last local /code-review
uncheckedReposnonePath fragments (/my-app/) of repos whose CI doesn't typecheck or build. There it flags a push after TypeScript edits with no typecheck, and a merge after package.json or next.config changes with no local build
middlewareRouteReposnoneNext.js repos whose src/middleware.ts allowlists routes. A new top-level src/app/<route>/page.tsx gets a reminder to add it
bannedStringsnoneCase-insensitive text that should never be written into a file
supabaseoffAsks before a command uses a service-role key; after apply_migration, reminds Claude to run NOTIFY pgrst, 'reload schema' and to revoke default grants on new tables

If you load the mod from a clone instead of the marketplace, set the same options in ~/.claude/settings.json:

{
  "pluginConfigs": {
    "session-hygiene": {
      "options": {
        "uncheckedRepos": ["/my-app/"],
        "bannedStrings": ["lorem ipsum"],
        "supabase": true
      }
    }
  }
}

The handoff card: after each turn a session saves its open loops (open PRs, uncommitted or unpushed worktrees, a question it left you). A new session lists loops from sessions that ended or went quiet, re-checked live first. /handoff shows them again, /handoff clear dismisses them.

A tripwire, and Claude responding to it The handoff card in a new session

session-activity

  • /ledger lists everything that left the machine: MCP write tools, git push, gh pr create and merge, gh api writes, Vercel deploys, curl writes, publishes, SQL writes. A button switches to all sessions in the last 24 hours. Reads stay out of it.
  • Database write hold. Any execute_sql that writes (INSERT, UPDATE, DELETE, DDL, GRANT…) stops for a Run it or Stop question. SELECTs and NOTIFY pass. Words inside comments and quoted strings don't count.
  • Waiting-on. The spinner shows pending background work (Thinking · 2 bg · agent 3m…), and a row above the prompt lists background commands, agents, workflows and monitors still running after Claude stops. /waiting lists them, /waiting clear resets.

The ledger pane

context-gauge

  • The status line shows ctx 62% · 124k/200k · compacted 1×.
  • Toasts at 70% and 85%, and from 80% a row above the prompt with a Compact now button.
  • Before any compaction it snapshots what's in flight (task, latest request, files edited, PR links, last actions), asks the summarizer to keep it, logs it, and hands it back to Claude with your next prompt.
  • /context-log lists every compaction this session with its snapshot.

The context log after a compaction

Privacy

Everything these mods record stays on your machine in Claude Code's per-plugin store. The only network calls are gh requests to GitHub for PR and deployment state (ship-tracker, and the handoff card's re-check).

Known issues

  • Tested in the terminal. The desktop app's Code tab should draw the same panes and rows, but I haven't seen it yet.
  • In one long session, /ledger reported the pane as opened but it never drew. It works in fresh sessions; the built-in diff pane seemed to be in front of it.
  • The mods API is still early access, so an update to Claude Code can break things here.
  • The needs-you "ended with a question" check is a heuristic and will be wrong sometimes.

Who made this

I'm Ben Newton. I write about building with AI at benenewton.com, and I'm building BlackOps Center, the platform that runs my site, my posts and the notes these Claude sessions write into. If you want to see it, start at blackopscenter.com/start.

Claude Code wrote the mods with its built-in plugin-authoring skill. Issues and PRs are welcome.

MIT licensed.

Source 1 files
hooks/register.tsx 642 lines
1import type { EngineInterface as Engine, Register, Timer } from 'claude-code'
2
3// session-fleet: one registry of live sessions in $.store (shared by every
4// session on the machine), read three ways:
5//   1. a pane listing every live session, opened at every session start.
6//      Click anywhere on another desktop session's card to switch to it; click
7//      a session's name to rename it (kept in the store, shared). Pills tag
8//      the project. The band's toggle or /fleet shows and hides it
9//   2. the band above the prompt flags other sessions that are waiting on you,
10//      and always carries the board's show/hide toggle
11//   3. edits and mutating git in a worktree another live session claimed first
12//      are held with a question naming that session
13
14const PANE = 'fleet'
15const PREFIX = 's:'
16const NAME = 'name:' // a rename from the board, by session id; outside PREFIX
17const LEGACY_AUTO_OPEN = 'pref:autoOpen'
18const ALIVE_MS = 3 * 60_000 // no heartbeat for this long = session is gone
19const CLAIM_MS = 30 * 60_000 // a worktree untouched for this long is released
20const PRUNE_MS = 24 * 60 * 60_000
21const BEAT_MS = 30_000
22const REDRAW_MS = 5_000
23
24type Phase = 'working' | 'idle' | 'waiting'
25
26type Claim = { since: number; lastTouch: number }
27
28type Rec = {
29  id: string
30  task: string
31  cwd: string
32  branch: string | null
33  pr: string | null
34  phase: Phase
35  waitingWhy: string | null
36  waitingSince: number | null
37  last: string
38  lastAt: number
39  beat: number
40  claims: Record<string, Claim>
41  hostId?: string | null // desktop app session id (local_…), null in a terminal
42}
43
44const GIT_MUTATION =
45  /\bgit\b(?:\s+-C\s+\S+)?\s+(commit|checkout|switch|reset|rebase|merge|pull|push|stash|add|rm|mv|restore|cherry-pick|revert|am|apply|clean|worktree\s+remove)\b/
46const HUMAN = new Set(['composer', 'bridge', 'sdk'])
47
48const me: Rec = {
49  id: '',
50  task: '',
51  cwd: '',
52  branch: null,
53  pr: null,
54  phase: 'idle',
55  waitingWhy: null,
56  waitingSince: null,
57  last: 'started',
58  lastAt: 0,
59  beat: 0,
60  claims: {},
61  hostId: null,
62}
63
64let lastWrite = 0
65let lastRepoRefresh = 0
66let timers: Timer[] = []
67let editing: string | null = null // the session id whose name is being edited
68const toplevelCache = new Map<string, string | null>()
69const allowed = new Set<string>() // worktrees the user said to proceed in
70const toasted = new Map<string, number>() // other session id -> waitingSince toasted
71
72const short = (s: string, n: number) => {
73  const one = s.replace(/\s+/g, ' ').trim()
74  return one.length > n ? one.slice(0, n - 1) + '…' : one
75}
76
77const home = (p: string) => p.replace(/^\/Users\/[^/]+/, '~')
78
79const shortTree = (p: string) => {
80  const wt = p.match(/\.claude\/worktrees\/([^/]+)$/)
81  if (wt) return `${(p.split('/.claude/')[0] ?? '').split('/').pop()}:${wt[1]}`
82  return home(p)
83}
84
85// Which project a session works in, from its newest worktree or its cwd
86const repoName = (p: string) => (p.split('/.claude/worktrees/')[0] ?? p).split('/').filter(Boolean).pop() ?? ''
87
88type Pill = { label: string; fg: string; bg: string }
89type PillRule = { label: string; test: RegExp; bg: string }
90
91const OTHER_BG = '#4b5563'
92let pillRules: PillRule[] = []
93
94// The projectPills option: `Label:regex:color` entries separated by `;`
95function parseRules(spec: string): PillRule[] {
96  const rules: PillRule[] = []
97  for (const entry of spec.split(';')) {
98    const [label, pattern, color] = entry.split(':').map(x => x.trim())
99    if (!label || !pattern) continue
100    try {
101      rules.push({ label, test: new RegExp(pattern, 'i'), bg: color || OTHER_BG })
102    } catch {
103      // a bad regex skips its entry
104    }
105  }
106  return rules
107}
108
109function pill(r: Rec, now: number): Pill | null {
110  const trees = Object.entries(r.claims)
111    .filter(([, c]) => now - c.lastTouch < CLAIM_MS)
112    .sort((a, b) => b[1].lastTouch - a[1].lastTouch)
113  const dir = trees[0]?.[0] ?? r.cwd
114  const name = repoName(dir)
115  if (!name || /^\/Users\/[^/]+\/?$/.test(dir)) return null // home dir: no project
116  const rule = pillRules.find(p => p.test.test(name))
117  return { label: rule?.label ?? name, fg: 'white', bg: rule?.bg ?? OTHER_BG }
118}
119
120const ago = (now: number, t: number) => {
121  const s = Math.max(0, Math.round((now - t) / 1000))
122  if (s < 60) return `${s}s`
123  if (s < 3600) return `${Math.round(s / 60)}m`
124  return `${Math.round(s / 3600)}h`
125}
126
127// The needs-you badge: black on solid yellow, readable in light and dark
128const NEEDS_FG = '#000000'
129const NEEDS_BG = '#facc15'
130
131// A failed lookup reads as closed, so the needs-you band still draws
132const isPaneOpen = async ($: Engine) => {
133  try {
134    return (await $.ui.panes()).some(p => p.id === PANE)
135  } catch {
136    return false
137  }
138}
139
140async function openBoard($: Engine) {
141  const r = await $.ui.open({ id: PANE, title: 'Session fleet' })
142  $.ui.invalidate('ui.render')
143  return r
144}
145
146async function closeBoard($: Engine) {
147  await $.ui.close({ id: PANE })
148  $.ui.invalidate('ui.render')
149}
150
151async function toggleBoard($: Engine) {
152  if (await isPaneOpen($)) await closeBoard($)
153  else await openBoard($)
154}
155
156const nameOf = async ($: Engine, r: Rec) =>
157  ((await $.store.get(NAME + r.id)) as string | undefined) || r.task || '(no prompt yet)'
158
159async function rename($: Engine, id: string, value: string) {
160  const v = value.replace(/\s+/g, ' ').trim()
161  if (v) await $.store.set(NAME + id, v.slice(0, 80))
162  else await $.store.delete(NAME + id) // empty: back to the first prompt
163  editing = null
164  $.ui.invalidate('ui.render')
165}
166
167async function save($: Engine, force = false) {
168  const now = await $.clock.now()
169  if (!force && now - lastWrite < 2000) return
170  lastWrite = now
171  me.beat = now
172  if (!me.id) return
173  await $.store.set(PREFIX + me.id, me)
174}
175
176async function all($: Engine): Promise<Rec[]> {
177  const keys = (await $.store.keys()).filter((k: string) => k.startsWith(PREFIX))
178  const recs: Rec[] = []
179  const now = await $.clock.now()
180  for (const k of keys) {
181    const r = (await $.store.get(k)) as Rec | undefined
182    if (!r) continue
183    if (now - r.beat > PRUNE_MS) {
184      await $.store.delete(k)
185      await $.store.delete(NAME + r.id)
186      continue
187    }
188    recs.push(r)
189  }
190  return recs
191}
192
193const isAlive = (r: Rec, now: number) => now - r.beat < ALIVE_MS
194
195async function toplevel($: Engine, dir: string): Promise<string | null> {
196  let d = dir
197  for (let i = 0; i < 6 && d && d !== '/'; i++) {
198    if (toplevelCache.has(d)) return toplevelCache.get(d) ?? null
199    try {
200      if (await $.fs.exists(d)) {
201        const r = await $.process.run(['git', '-C', d, 'rev-parse', '--show-toplevel'], {
202          timeoutMs: 5000,
203        })
204        const top = r.exitCode === 0 ? r.stdout.trim() : null
205        toplevelCache.set(d, top)
206        return top
207      }
208    } catch {
209      return null
210    }
211    d = d.slice(0, d.lastIndexOf('/')) || '/'
212  }
213  return null
214}
215
216const dirname = (p: string) => p.slice(0, p.lastIndexOf('/')) || '/'
217
218// Which worktree a tool call writes to, or null when it is not a guarded write.
219async function target($: Engine, e: { tool: string } & Record<string, unknown>): Promise<string | null> {
220  const fp = (e.file_path ?? e.notebook_path) as string | undefined
221  if (['Edit', 'Write', 'NotebookEdit', 'MultiEdit'].includes(e.tool) && typeof fp === 'string') {
222    return toplevel($, dirname(fp))
223  }
224  if (e.tool === 'Bash' && typeof e.command === 'string' && GIT_MUTATION.test(e.command)) {
225    const cmd = e.command
226    const dashC = cmd.match(/git\s+-C\s+("[^"]+"|'[^']+'|\S+)/)
227    const cd = cmd.match(/(?:^|&&|;)\s*cd\s+("[^"]+"|'[^']+'|\S+)/)
228    const raw = (dashC?.[1] ?? cd?.[1])?.replace(/^["']|["']$/g, '')
229    const base = me.cwd || (await $.session.cwd())
230    const homeDir = base.match(/^\/Users\/[^/]+/)?.[0] ?? '/Users'
231    const abs = raw?.startsWith('~') ? homeDir + raw.slice(1) : raw
232    const dir = abs ? (abs.startsWith('/') ? abs : `${base}/${abs}`) : base
233    return toplevel($, dir)
234  }
235  return null
236}
237
238function describe(e: { tool: string } & Record<string, unknown>): string {
239  if (e.tool === 'Bash' && typeof e.command === 'string') return `$ ${short(e.command, 48)}`
240  const fp = (e.file_path ?? e.notebook_path) as string | undefined
241  if (typeof fp === 'string') return `${e.tool} ${fp.split('/').pop()}`
242  if (e.tool.startsWith('mcp__')) return e.tool.split('__').pop() ?? e.tool
243  return e.tool
244}
245
246async function refreshRepo($: Engine) {
247  const now = await $.clock.now()
248  if (now - lastRepoRefresh < 120_000) return
249  lastRepoRefresh = now
250  // The worktree touched most recently, else the session's own directory
251  const trees = Object.entries(me.claims).sort((a, b) => b[1].lastTouch - a[1].lastTouch)
252  const dir = trees[0]?.[0] ?? (await toplevel($, me.cwd))
253  if (!dir) {
254    me.branch = null
255    me.pr = null
256    return
257  }
258  try {
259    const b = await $.process.run(['git', '-C', dir, 'rev-parse', '--abbrev-ref', 'HEAD'], {
260      timeoutMs: 5000,
261    })
262    me.branch = b.exitCode === 0 ? b.stdout.trim() : null
263    if (me.branch && !['main', 'master', 'HEAD'].includes(me.branch)) {
264      const pr = await $.process.run(
265        ['gh', 'pr', 'view', '--json', 'number,state', '-q', '"#" + (.number|tostring) + " " + .state'],
266        { cwd: dir, timeoutMs: 10_000 },
267      )
268      me.pr = pr.exitCode === 0 ? pr.stdout.trim().toLowerCase().replace(/ open$/, '') : null
269    } else {
270      me.pr = null
271    }
272  } catch {
273    // git or gh unavailable: keep what we had
274  }
275  await save($, true)
276}
277
278async function setPhase($: Engine, phase: Phase, why: string | null = null) {
279  const now = await $.clock.now()
280  me.phase = phase
281  me.waitingWhy = phase === 'waiting' ? why : null
282  me.waitingSince = phase === 'waiting' ? (me.waitingSince ?? now) : null
283  await save($, true)
284  $.ui.invalidate('ui.render')
285}
286
287// Toast when another session starts waiting; redraw the pane and band.
288async function tick($: Engine) {
289  const now = await $.clock.now()
290  for (const r of await all($)) {
291    if (r.id === me.id || !isAlive(r, now) || r.phase !== 'waiting' || !r.waitingSince) continue
292    if (toasted.get(r.id) === r.waitingSince) continue
293    toasted.set(r.id, r.waitingSince)
294    $.ui.toast(`Needs you: ${r.task || r.id.slice(0, 8)} (${r.waitingWhy ?? 'waiting'})`, {
295      timeoutMs: 8000,
296    })
297  }
298  $.ui.invalidate('ui.render')
299}
300
301// Show another desktop session: the app's own deep link, as a sidebar click
302async function switchTo($: Engine, r: Rec) {
303  if (!r.hostId || !/^[\w-]+$/.test(r.hostId)) return
304  try {
305    const res = await $.process.run(['open', `claude://claude.ai/epitaxy/${r.hostId}`], { timeoutMs: 5000 })
306    if (res.exitCode !== 0) $.ui.toast(`Could not switch to ${r.task || r.id.slice(0, 8)}`)
307  } catch {
308    $.ui.toast(`Could not switch to ${r.task || r.id.slice(0, 8)}`)
309  }
310}
311
312export const register: Register = (on, options) => {
313  pillRules = parseRules(typeof options.projectPills === 'string' ? options.projectPills : '')
314
315  on('session.start', async ($, e, next) => {
316    me.id = await $.session.id()
317    me.cwd = await $.session.cwd()
318    const prior = (await $.store.get(PREFIX + me.id)) as Rec | undefined
319    if (prior) Object.assign(me, prior, { phase: 'idle', waitingWhy: null, waitingSince: null })
320    if (!me.task) {
321      try {
322        const first = (await $.session.messages()).find(
323          m => m.role === 'user' && m.text && !m.text.startsWith('<'),
324        )
325        if (first) me.task = short(first.text, 70)
326      } catch {
327        // no transcript yet
328      }
329    }
330    me.lastAt = me.lastAt || (await $.clock.now())
331    try {
332      const env = await $.process.run(['printenv', 'CLAUDE_CODE_HOST_SESSION_ID'], { timeoutMs: 3000 })
333      me.hostId = env.exitCode === 0 && env.stdout.trim() ? env.stdout.trim() : null
334    } catch {
335      me.hostId = null
336    }
337    await save($, true)
338    void refreshRepo($)
339
340    await $.command.register({
341      name: 'fleet',
342      description: 'Show or hide the session fleet board',
343    })
344    await $.store.delete(LEGACY_AUTO_OPEN)
345    if (!(await isPaneOpen($))) void openBoard($)
346
347    for (const t of timers) t.cancel()
348    timers = [
349      $.clock.every(BEAT_MS, () => void save($, true)),
350      $.clock.every(REDRAW_MS, () => void tick($)),
351    ]
352    return next(e)
353  })
354
355  on('session.end', async ($, e, next) => {
356    for (const t of timers) t.cancel()
357    timers = []
358    if (me.id) await $.store.delete(PREFIX + me.id)
359    return next(e)
360  })
361
362  on('command.run', { command: 'fleet' }, async $ => {
363    await toggleBoard($)
364    return { text: (await isPaneOpen($)) ? 'Fleet board shown.' : 'Fleet board hidden.' }
365  })
366
367  // The band's toggle label follows the pane, however it closed
368  on('ui.close', async ($, e, next) => {
369    const r = await next(e)
370    if (e.id === PANE) {
371      editing = null
372      $.ui.invalidate('ui.render')
373    }
374    return r
375  })
376
377  on('prompt.submit', async ($, e, next) => {
378    // The desktop app stamps typed prompts `unclassified`; good enough for a first title
379    const human = !e.origin || HUMAN.has(e.origin.kind) || (!me.task && e.origin.kind === 'unclassified')
380    if (human && !me.task && !e.text.startsWith('<')) me.task = short(e.text, 70)
381    await setPhase($, 'working')
382    return next(e)
383  })
384
385  on('classic.PermissionRequest', async ($, e, next) => {
386    await setPhase($, 'waiting', `permission: ${short(e.tool_name, 30)}`)
387    return next(e)
388  })
389
390  on('tool.call', async ($, e, next) => {
391    if (e.agentId !== undefined) return next(e)
392    const call = e as unknown as { tool: string } & Record<string, unknown>
393    const now = await $.clock.now()
394    me.last = describe(call)
395    me.lastAt = now
396
397    // Any shell command run inside a worktree counts as working there (no guard)
398    if (call.tool === 'Bash' && !(await target($, call))) {
399      const here = await toplevel($, me.cwd || (await $.session.cwd()))
400      if (here) me.claims[here] = { since: me.claims[here]?.since ?? now, lastTouch: now }
401    }
402
403    // Worktree claim guard
404    const tree = await target($, call)
405    if (tree) {
406      const mine = me.claims[tree]
407      const rivals = (await all($)).filter(
408        r =>
409          r.id !== me.id &&
410          isAlive(r, now) &&
411          r.claims[tree] &&
412          now - r.claims[tree].lastTouch < CLAIM_MS &&
413          (!mine || r.claims[tree].since < mine.since),
414      )
415      if (rivals.length > 0 && !allowed.has(tree)) {
416        const r = rivals[0]!
417        const rc = r.claims[tree]!
418        const who = `"${r.task || r.id.slice(0, 8)}"${r.branch ? ` on ${r.branch}` : ''}`
419        await setPhase($, 'waiting', `worktree clash: ${shortTree(tree)}`)
420        let answer = 'Stop'
421        try {
422          answer = await $.ui.ask(
423            `Session ${who} claimed ${shortTree(tree)} ${ago(now, rc.since)} ago (last: ${r.last}, ${ago(now, r.lastAt)} ago). Write there anyway?`,
424            {
425              header: 'Worktree',
426              options: ['Proceed for this session', 'Stop'],
427            },
428          )
429        } catch (err) {
430          // Dismissed, or nobody to ask. Only a true headless run (no surfaces and
431          // not a desktop session) proceeds; the desktop app reports no surfaces
432          // to the mod, so there an unanswerable ask must stop, not wave it through.
433          const surfaces = await $.session.surfaces()
434          $.ui.log(
435            `session-fleet: guard ask failed (${String(err)}); surfaces=[${surfaces.join(',')}] hostId=${me.hostId ?? 'null'}`,
436            { to: 'debug' },
437          )
438          answer = surfaces.length === 0 && !me.hostId ? 'Proceed for this session' : 'Stop'
439        }
440        await setPhase($, 'working')
441        if (answer !== 'Proceed for this session') {
442          return {
443            deny: `session-fleet: another live session (${who}, last action "${r.last}") is working in ${tree}. Ask the user before writing there, or use a separate worktree.`,
444          }
445        }
446        allowed.add(tree)
447      }
448      me.claims[tree] = { since: mine?.since ?? now, lastTouch: now }
449    }
450    // Release claims nobody has touched for a while
451    for (const [k, c] of Object.entries(me.claims)) if (now - c.lastTouch > CLAIM_MS) delete me.claims[k]
452
453    const asking = e.tool === 'AskUserQuestion'
454    if (asking) await setPhase($, 'waiting', 'question')
455    else await save($)
456
457    const ran = await next(e)
458    if (asking || me.phase === 'waiting') await setPhase($, 'working')
459    return ran
460  })
461
462  on('turn.complete', async ($, e, next) => {
463    if (e.agentId !== undefined) return next(e)
464    const tail = e.answer.trim().slice(-400)
465    const question = /\?\s*(\*\*)?\s*$/.test(tail) || /\?\s*\n[^\n]{0,80}$/.test(tail)
466    if (question) {
467      const q = tail.split(/(?<=[.!\n])\s+/).filter(s => s.includes('?')).pop() ?? 'question'
468      await setPhase($, 'waiting', `asked: ${short(q, 60)}`)
469    } else {
470      await setPhase($, 'idle')
471    }
472    void refreshRepo($)
473    return next(e)
474  })
475
476  // 2. Needs-you beacon above the prompt
477  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
478    const below = await next(e)
479    if (e.props.hasSurvey) return below
480    const now = await $.clock.now()
481    const recs = await all($)
482    const live = recs.filter(r => isAlive(r, now))
483    const waiting = live.filter(r => r.id !== me.id && r.phase === 'waiting')
484    const { Box, Text, Button } = $.ui.resolve(e)
485    const paneShown = await isPaneOpen($)
486    const toggle = (
487      <Button
488        key="toggle-fleet"
489        label={paneShown ? `▾ Hide fleet board` : `▸ Fleet board · ${live.length} live`}
490        plain
491        dimColor
492        onPress={() => void toggleBoard($)}
493      />
494    )
495    if (waiting.length === 0)
496      return (
497        <Box flexDirection="column">
498          <Box>{toggle}</Box>
499          {below}
500        </Box>
501      )
502    const width = Math.max(30, (e.props.bodyColumns ?? 80) - 20)
503    const names = new Map<string, string>()
504    for (const r of waiting) names.set(r.id, await nameOf($, r))
505    return (
506      <Box flexDirection="column">
507        {waiting.slice(0, 3).map(r => (
508          <Box key={r.id} gap={1}>
509            <Text color={NEEDS_FG} backgroundColor={NEEDS_BG} bold>
510              {' ⚑ NEEDS YOU '}
511            </Text>
512            <Text>
513              {short(
514                `${names.get(r.id)} · ${r.waitingWhy ?? 'waiting'} · ${ago(now, r.waitingSince ?? r.lastAt)}`,
515                width - 16,
516              )}
517            </Text>
518            {r.hostId && (
519              <Button key={`band-go-${r.id}`} label="Switch →" variant="primary" onPress={() => void switchTo($, r)} />
520            )}
521          </Box>
522        ))}
523        <Box gap={1}>
524          {waiting.length > 3 && <Text dimColor>+{waiting.length - 3} more</Text>}
525          {toggle}
526        </Box>
527        {below}
528      </Box>
529    )
530  })
531
532  // 1. Fleet board pane
533  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
534    const els = $.ui.resolve(e)
535    const { Box, Text, Button } = els
536    const Input = 'Input' in els ? els.Input : null // mobile draws no field
537    const now = await $.clock.now()
538    const order: Record<Phase, number> = { waiting: 0, working: 1, idle: 2 }
539    const live = (await all($))
540      .filter(r => isAlive(r, now))
541      .sort((a, b) => order[a.phase] - order[b.phase] || b.lastAt - a.lastAt)
542    const cols = Math.max(30, e.props.bodyColumns ?? 60)
543    const dot: Record<Phase, string> = { waiting: '⚑', working: '●', idle: '○' }
544    const color: Record<Phase, string> = { waiting: 'yellow', working: 'green', idle: 'gray' }
545    const names = new Map<string, string>()
546    for (const r of live) names.set(r.id, await nameOf($, r))
547
548    // Worktrees held by more than one live session
549    const holders = new Map<string, number>()
550    for (const r of live)
551      for (const [t, c] of Object.entries(r.claims))
552        if (now - c.lastTouch < CLAIM_MS) holders.set(t, (holders.get(t) ?? 0) + 1)
553
554    return (
555      <Box flexDirection="column" gap={1}>
556        <Text dimColor>
557          {live.length} live · {live.filter(r => r.phase === 'waiting').length} waiting on you
558        </Text>
559        {live.map(r => {
560          const trees = Object.entries(r.claims)
561            .filter(([, c]) => now - c.lastTouch < CLAIM_MS)
562            .map(([t]) => (holders.get(t)! > 1 ? `⚠ ${shortTree(t)}` : shortTree(t)))
563          const where = trees.length ? trees.join(', ') : home(r.cwd)
564          const name = names.get(r.id)!
565          const canSwitch = !!r.hostId && r.id !== me.id
566          const waitingOnMe = r.phase === 'waiting'
567          const p = pill(r, now)
568          const startRename = () => {
569            editing = r.id
570            $.ui.invalidate('ui.render')
571            void $.ui.focus({ requestId: PANE, key: `rename-${r.id}` }).catch(() => undefined)
572          }
573          return (
574            <Box
575              key={`card-${r.id}`}
576              flexDirection="column"
577              paddingX={1}
578              borderStyle="round"
579              borderColor={waitingOnMe ? NEEDS_BG : 'gray'}
580            >
581              {waitingOnMe && (
582                <Box gap={1}>
583                  <Text color={NEEDS_FG} backgroundColor={NEEDS_BG} bold>
584                    {' ⚑ NEEDS YOU '}
585                  </Text>
586                  <Text color="yellow" bold>
587                    {short(`${r.waitingWhy ?? 'waiting'} · ${ago(now, r.waitingSince ?? r.lastAt)}`, cols - 20)}
588                  </Text>
589                </Box>
590              )}
591              <Box gap={1}>
592                <Text color={color[r.phase]}>{dot[r.phase]}</Text>
593                {p ? <Text color={p.fg} backgroundColor={p.bg} bold>{` ${p.label} `}</Text> : null}
594                <Text bold>{short(name, cols - 24)}</Text>
595                {r.id === me.id && <Text dimColor>(this session)</Text>}
596              </Box>
597              <Text dimColor>{`  ${short(where, cols - 4)}`}</Text>
598              <Text dimColor>{`  ${short([r.branch, r.pr].filter(Boolean).join(' · ') || 'no branch', cols - 4)}`}</Text>
599              <Text dimColor>{`  ${short(`${r.last} · ${ago(now, r.lastAt)} ago`, cols - 4)}`}</Text>
600              {editing === r.id && Input ? (
601                <Box gap={1} key={`edit-${r.id}`}>
602                  <Input
603                    key={`rename-${r.id}`}
604                    value={name === '(no prompt yet)' ? '' : name}
605                    placeholder="Session name (empty resets it)"
606                    submitLabel="Save"
607                    autoFocus
608                    onSubmit={(v: string) => void rename($, r.id, v)}
609                  />
610                  <Button
611                    key={`cancel-${r.id}`}
612                    label="Cancel"
613                    variant="secondary"
614                    onPress={() => {
615                      editing = null
616                      $.ui.invalidate('ui.render')
617                    }}
618                  />
619                </Box>
620              ) : (
621                <Box gap={1}>
622                  {canSwitch && (
623                    <Button
624                      key={`go-${r.id}`}
625                      label={waitingOnMe ? 'Switch → answer it' : 'Switch →'}
626                      variant="primary"
627                      onPress={() => void switchTo($, r)}
628                    />
629                  )}
630                  {Input && (
631                    <Button key={`name-${r.id}`} label="✎ Rename" variant="secondary" onPress={startRename} />
632                  )}
633                </Box>
634              )}
635            </Box>
636          )
637        })}
638      </Box>
639    )
640  })
641}
642