A side pane with this session's subagents, background shells and the repo's worktrees, with alerts when they finish or fail.

A side pane with this session's subagents, background shells and the repo's worktrees.
FLEET · deployer
AGENTS 2 running · 1 done · 0 failed
▶ rust-reviewer 6m12s
review plan · Bash cargo clippy
✓ Explore 2m03s · 10:42
map snapshot callers
BACKGROUND
▶ uv run python sim.py 38m12s
▓▓▓▓░░░░░░ 40% ~52m · month 12/30
▶ ./retrain.sh d57 21m40s
⚠ no output 6m · fitting fold 3
▶ until grep -q DONE log; … 9m02s
waiting
✓ cargo build 41s · 10:38
WORKTREES
main clean
p31-snap ●3 changed ↑2
Elapsed times tick live; a finished agent or shell also shows when it finished (with the date when not today).
Each running background shell shows its last line of output. When that line holds a count (14/30) or a percentage, a bar and an ETA at the rate seen so far (after 30 s of movement); after 5 minutes with no output, ⚠ no output 6m and one toast. A wait loop (until …; do …; done, a while that sleeps) shows waiting and is never counted as stalled. Under the list, a stop <shell> button per running shell stops it through the TaskStop tool, as the model would.
claude plugin install fleet@vampik-plugins
/fleet toggles the pane any time. Once an agent or shell has run (or while the pane is open), a line above the prompt shows fleet 2▶ 1✓ 0✗ · bg 2 · sim.py 40% ~52m · retrain.sh d57 ⚠ 6m show: click show/hide, or focus the band (ctrl+x tab) and press f.paplay, freedesktop sounds) on a failure and on all done.idleMinutes, through telegram-notifier's bot (TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID).Named agents (agent teams) go idle between turns: they show as done without a toast.
Marking a shell lost relies on the classic Stop hook, which does not run where an organization manages Claude Code (only plugins the organization lists run classic hooks there): a shell that ends without a notification may stay shown as running.
agent.spawn and tool.call record agents and their last tool, and each background shell with the output file its result names; every 5 s while one runs, the file is checked and its last 4 KB read when it grew; $.agent.list() is polled every 2 s while any runs; a turn's end and task notifications report finishes at once; at each turn's end a background shell no longer in the engine's in-flight list is marked lost (?), its exit unknown; worktrees come from git worktree list every 15 s while the pane is shown.
| Option | Default | |
|---|---|---|
autoOpen | true | open the pane at 2+ running agents |
sound | true | chime on failure and all done |
telegram | true | Telegram summary when away |
idleMinutes | 5 | away after this long since your last prompt |
Needs function hooks (CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1).
hooks/register.tsx 564 lines1import { atom, read, update } from "claude-code";
2import type { EngineInterface, Register } from "claude-code";
3
4import type { FleetAgent, FleetShell, FleetState } from "../types";
5import {
6 applyStatuses,
7 emptyFleet,
8 endShell,
9 endToast,
10 fmtLeft,
11 isFailed,
12 isLive,
13 isWaiter,
14 lastLine,
15 liveCount,
16 loseShells,
17 mayNotify,
18 nextProgress,
19 outputFileOf,
20 parseNotification,
21 parseProgress,
22 parseStatus,
23 parseWorktrees,
24 quietMs,
25 shellName,
26 shellNotes,
27 STALL_MS,
28 statusLine,
29 summary,
30 toolLabel,
31 trim,
32} from "./core.ts";
33import { drawFleet, type FleetView } from "./view.tsx";
34
35const PANE = "fleet";
36const ENDED = new Set(["completed", "failed", "killed"]);
37const TOAST_GAP_MS = 2_100;
38const SHELL_POLL_MS = 5_000;
39/** Bytes of a shell's output read for its last line. */
40const TAIL_BYTES = "4096";
41
42const fleet = atom({ plugin: "fleet", key: "fleet" } as const, emptyFleet());
43const pane = atom({ plugin: "fleet", key: "pane" } as const, false);
44const lastPrompt = atom({ plugin: "fleet", key: "lastPrompt" } as const, 0);
45
46/** What the module keeps outside `$.state`; a reload starts it over. */
47type Tracker = {
48 autoOpen: boolean;
49 sound: boolean;
50 telegram: boolean;
51 idleMs: number;
52 repo: string;
53 root: string | undefined;
54 /** Whether the surface docks a pane beside the transcript, as the band last drew; unknown until then. */
55 docks: boolean | undefined;
56 poll: { cancel: () => void } | undefined;
57 /** The look at live shells' output, while any has an output file. */
58 shellPoll: { cancel: () => void } | undefined;
59 /** When the band was last redrawn for a stalled shell's quiet time. */
60 quietDrawnAt: number;
61};
62
63function chime($: EngineInterface, sound: "complete" | "dialog-error") {
64 // $.audio has no player on a Linux terminal; paplay does
65 void $.process
66 .run(["paplay", `/usr/share/sounds/freedesktop/stereo/${sound}.oga`])
67 .catch(() => undefined);
68}
69
70async function sendTelegram($: EngineInterface, text: string): Promise<void> {
71 const none = () => undefined;
72 const token = await $.env.get("TELEGRAM_BOT_TOKEN").catch(none);
73 const chat = await $.env.get("TELEGRAM_CHAT_ID").catch(none);
74 if (!token || !chat) return;
75 const res = await $.http
76 .fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
77 method: "POST",
78 headers: { "Content-Type": "application/json" },
79 body: JSON.stringify({ chat_id: chat, text }),
80 })
81 .catch(none);
82 if (!res?.ok)
83 $.ui.log(`fleet: Telegram send failed (${res?.status ?? "no response"})`, {
84 to: "debug",
85 });
86}
87
88/** Whether the engine draws the pane: `isShown` is false behind other tabs, so not asked. */
89async function isPaneDrawn($: EngineInterface): Promise<boolean> {
90 const panes = await $.ui.panes().catch(() => []);
91 return panes.some((p) => p.id === PANE && p.isPlaced);
92}
93
94async function refreshTrees($: EngineInterface, t: Tracker): Promise<void> {
95 if (!t.root) return;
96 const list = await $.process
97 .run(["git", "worktree", "list", "--porcelain"], { cwd: t.root })
98 .catch(() => undefined);
99 if (!list || list.exitCode !== 0) return;
100 const trees = await Promise.all(
101 parseWorktrees(list.stdout).map(async (w) => {
102 const st = await $.process
103 .run(["git", "status", "--porcelain=v1", "--branch"], { cwd: w.path })
104 .catch(() => undefined);
105 const counts =
106 st && st.exitCode === 0
107 ? parseStatus(st.stdout)
108 : { changed: 0, ahead: 0, behind: 0 };
109 return { ...w, ...counts };
110 }),
111 );
112 await update($, fleet, (f) => ({ ...f, trees }));
113}
114
115/** One toast for everything that just ended (a toast replaces the plugin's last); a chime for a failure. */
116function announce(
117 $: EngineInterface,
118 t: Tracker,
119 agents: FleetAgent[],
120 shells: FleetShell[],
121) {
122 const ended = [
123 // a teammate gone idle is no finish
124 ...agents
125 .filter((a) => ENDED.has(a.status))
126 .map((a) => ({ ...a, name: a.type, what: a.description })),
127 ...shells.map((s) => ({ ...s, name: "shell", what: s.command })),
128 ].map((x) => ({
129 text: endToast(x.name, x.what, x.status, x.endedAt! - x.startedAt),
130 isFailed: isFailed(x.status),
131 }));
132 if (ended.length === 0) return;
133 $.ui.toast(
134 ended.length === 1
135 ? ended[0]!.text
136 : `${ended.length} finished: ${[
137 ...ended.slice(0, 3).map((x) => x.text),
138 ...(ended.length > 3 ? [`+${ended.length - 3} more`] : []),
139 ].join("; ")}`,
140 );
141 if (t.sound && ended.some((x) => x.isFailed)) chime($, "dialog-error");
142}
143
144/** When nothing is live any more: the all-done alert, and the batch closes. */
145async function settle($: EngineInterface, t: Tracker): Promise<void> {
146 const f = await read($, fleet);
147 if (liveCount(f) > 0) return;
148 t.poll?.cancel();
149 t.poll = undefined;
150 if (f.batchStart === undefined) return;
151
152 const batch = f.batchStart;
153 const size =
154 f.agents.filter((a) => a.startedAt >= batch).length +
155 f.shells.filter((s) => s.startedAt >= batch).length;
156 const now = await $.clock.now();
157 const text = summary(f, t.repo, now);
158 await update($, fleet, ({ batchStart: _, ...g }) => ({
159 ...g,
160 autoOpened: false,
161 }));
162 // one item's own toast says it all; the all-done alert is for a batch
163 if (size >= 2) {
164 // the engine drops a toast within 2 s of the last, and the last item's just showed
165 const done = text.split("\n").slice(1, 3).join(" · ");
166 $.clock.after(TOAST_GAP_MS, () => $.ui.toast(done));
167 if (t.sound) chime($, "complete");
168 }
169 if (t.telegram && now - (await read($, lastPrompt)) >= t.idleMs)
170 await sendTelegram($, text);
171}
172
173/** One look at `$.agent.list()`: status changes, their alerts, maybe all done. */
174async function tick($: EngineInterface, t: Tracker): Promise<void> {
175 const list = await $.agent.list().catch(() => undefined);
176 if (!list) return;
177 const statuses = Object.fromEntries(list.map((a) => [a.id, a.status]));
178 let ended: FleetAgent[] = [];
179 await update($, fleet, (f) => {
180 const r = applyStatuses(f.agents, statuses, Date.now());
181 ended = r.ended;
182 return { ...f, agents: r.agents };
183 });
184 announce($, t, ended, []);
185 await settle($, t);
186}
187
188function ensurePoll($: EngineInterface, t: Tracker) {
189 if (!t.poll) t.poll = $.clock.every(2000, () => void tick($, t));
190}
191
192/** One look at each live shell's output: its last line, progress, or a stall. */
193async function watchShells($: EngineInterface, t: Tracker): Promise<void> {
194 const live = (await read($, fleet)).shells.filter(
195 (s) => isLive(s.status) && s.outputFile,
196 );
197 if (live.length === 0) {
198 t.shellPoll?.cancel();
199 t.shellPoll = undefined;
200 return;
201 }
202 const now = await $.clock.now();
203 const patches = new Map<string, Partial<FleetShell>>();
204 const stalled: FleetShell[] = [];
205 for (const s of live) {
206 const st = await $.fs.stat(s.outputFile!).catch(() => undefined);
207 if (st?.kind === "file" && st.size !== s.size) {
208 const tail = await $.process
209 .run(["tail", "-c", TAIL_BYTES, s.outputFile!])
210 .catch(() => undefined);
211 const line = tail?.exitCode === 0 ? lastLine(tail.stdout) : undefined;
212 patches.set(s.id, {
213 size: st.size,
214 outputAt: now,
215 stalled: false,
216 ...(line
217 ? { line, progress: nextProgress(s.progress, parseProgress(line), now) }
218 : {}),
219 });
220 } else if (!s.waiter && !s.stalled && quietMs(s, now) >= STALL_MS) {
221 patches.set(s.id, { stalled: true });
222 stalled.push(s);
223 }
224 }
225 if (patches.size > 0)
226 await update($, fleet, (f) => ({
227 ...f,
228 shells: f.shells.map((s) =>
229 patches.has(s.id) ? { ...s, ...patches.get(s.id) } : s,
230 ),
231 }));
232 for (const s of stalled)
233 $.ui.toast(
234 `⚠ ${shellName(s.command)} · no output for ${fmtLeft(quietMs(s, now))}`,
235 );
236 // the band's quiet minutes move with no state change: a redraw a minute
237 if (live.some((s) => s.stalled) && now - t.quietDrawnAt >= 60_000) {
238 t.quietDrawnAt = now;
239 $.ui.invalidate("ui.render");
240 }
241}
242
243function ensureShellPoll($: EngineInterface, t: Tracker) {
244 if (!t.shellPoll)
245 t.shellPoll = $.clock.every(SHELL_POLL_MS, () => void watchShells($, t));
246}
247
248/** Stops a background shell the way the model would, through TaskStop. */
249async function stopShell($: EngineInterface, id: string): Promise<void> {
250 await $.tool
251 .call({ tool: "TaskStop", task_id: id } as never)
252 .catch(() => $.ui.toast(`fleet: could not stop ${id}`));
253}
254
255/** A task notification or a turn's end: one agent or shell reached `status`. */
256async function endTask(
257 $: EngineInterface,
258 t: Tracker,
259 id: string,
260 status: string,
261): Promise<void> {
262 let agents: FleetAgent[] = [];
263 let shell: FleetShell | undefined;
264 await update($, fleet, (f) => {
265 const now = Date.now();
266 const a = applyStatuses(f.agents, { [id]: status }, now);
267 const s = endShell(f.shells, id, status, now);
268 agents = a.ended;
269 shell = s.ended;
270 return { ...f, agents: a.agents, shells: s.shells };
271 });
272 announce($, t, agents, shell ? [shell] : []);
273 await settle($, t);
274}
275
276async function openPane($: EngineInterface, t: Tracker) {
277 const opened = await $.ui.open({ id: PANE, title: `Fleet · ${t.repo}` });
278 // an unasked open on a narrow terminal waits undrawn: still "show"
279 await update($, pane, () => opened.isPlaced);
280 void refreshTrees($, t);
281 return opened;
282}
283
284/** Closes the pane if the stored state says shown (undefined), opens it if not (how it opened). */
285async function togglePane($: EngineInterface, t: Tracker) {
286 if (await read($, pane)) {
287 await $.ui.close({ id: PANE });
288 await update($, pane, () => false);
289 return undefined;
290 }
291 return openPane($, t);
292}
293
294const textOf = (content: unknown): string =>
295 typeof content === "string"
296 ? content
297 : Array.isArray(content)
298 ? content
299 .filter((b) => b?.type === "text" && typeof b.text === "string")
300 .map((b) => b.text as string)
301 .join("\n")
302 : "";
303
304export const register: Register = (on, options) => {
305 const t: Tracker = {
306 autoOpen: options.autoOpen !== false,
307 sound: options.sound !== false,
308 telegram: options.telegram !== false,
309 idleMs:
310 (typeof options.idleMinutes === "number" && options.idleMinutes >= 0
311 ? options.idleMinutes
312 : 5) * 60_000,
313 repo: "",
314 root: undefined,
315 docks: undefined,
316 poll: undefined,
317 shellPoll: undefined,
318 quietDrawnAt: 0,
319 };
320
321 on("session.start", async ($, e, next) => {
322 const r = await next(e);
323 await $.command.register({
324 name: "fleet",
325 description:
326 "Show or hide the pane with this session's agents, background shells and worktrees",
327 });
328 const top = await $.process
329 .run(["git", "rev-parse", "--show-toplevel"])
330 .catch(() => undefined);
331 t.root = top?.exitCode === 0 ? top.stdout.trim() : undefined;
332 const cwd = await $.session.cwd().catch(() => "");
333 t.repo = (t.root ?? cwd).split("/").pop() || "session";
334 // the session's start counts as a prompt; a reload keeps the last one
335 const started = await $.clock.now();
336 await update($, lastPrompt, (at) => at || started);
337 // a reload keeps an open pane
338 const drawn = await isPaneDrawn($);
339 await update($, pane, () => drawn);
340 $.clock.every(15_000, async () => {
341 let shown = await read($, pane);
342 // a waiting pane gets drawn once the terminal widens
343 if (!shown && (await isPaneDrawn($))) {
344 shown = true;
345 await update($, pane, () => true);
346 }
347 if (shown) await refreshTrees($, t);
348 });
349 // a reload while agents or shells run: pick the polls up again
350 const f = await read($, fleet);
351 if (f.agents.some((a) => isLive(a.status))) ensurePoll($, t);
352 if (f.shells.some((s) => isLive(s.status) && s.outputFile))
353 ensureShellPoll($, t);
354 return r;
355 });
356
357 on("session.end", async ($, e, next) => {
358 if (e.reason === "clear") {
359 t.poll?.cancel();
360 t.poll = undefined;
361 t.shellPoll?.cancel();
362 t.shellPoll = undefined;
363 await update($, fleet, (f) => ({ ...emptyFleet(), trees: f.trees }));
364 }
365 return next(e);
366 });
367
368 on("command.run", { command: "fleet" }, async ($) => {
369 const opened = await togglePane($, t);
370 return {
371 text: !opened
372 ? "Fleet pane closed."
373 : opened.isPlaced
374 ? "Fleet pane opened."
375 : "Fleet pane is waiting for a wider terminal.",
376 };
377 });
378
379 on("prompt.submit", async ($, e, next) => {
380 if (e.origin.kind === "composer") {
381 const at = await $.clock.now();
382 await update($, lastPrompt, () => at);
383 }
384 return next(e);
385 });
386
387 on("agent.spawn", async ($, e, next) => {
388 const r = await next(e);
389 if (r.deny !== undefined || !r.agentId) return r;
390 const agent: FleetAgent = {
391 id: r.agentId,
392 type: e.subagentType,
393 description: e.description,
394 model: r.model,
395 startedAt: Date.now(),
396 status: "running",
397 tools: 0,
398 ...(e.isTeammate ? { teammate: true } : {}),
399 };
400 let open = false;
401 await update($, fleet, (f) => {
402 const agents = trim([...f.agents, agent]);
403 const live = agents.filter((a) => isLive(a.status)).length;
404 // unasked, only where the pane is a sidebar; not marked opened, so a later spawn may still
405 open = t.autoOpen && t.docks === true && !f.autoOpened && live >= 2;
406 return {
407 ...f,
408 agents,
409 batchStart: f.batchStart ?? agent.startedAt,
410 autoOpened: f.autoOpened || open,
411 };
412 });
413 ensurePoll($, t);
414 if (open && !(await read($, pane))) void openPane($, t);
415 return r;
416 });
417
418 on("tool.call", async ($, e, next) => {
419 if (e.agentId) {
420 const id = e.agentId;
421 const label = toolLabel(String(e.tool), e);
422 await update($, fleet, (f) =>
423 f.agents.some((a) => a.id === id)
424 ? {
425 ...f,
426 agents: f.agents.map((a) =>
427 a.id === id ? { ...a, lastTool: label, tools: a.tools + 1 } : a,
428 ),
429 }
430 : f,
431 );
432 }
433 const r = await next(e);
434 if (e.tool !== "Bash" || r.deny !== undefined) return r;
435 const taskId = (r.result as { backgroundTaskId?: string } | undefined)
436 ?.backgroundTaskId;
437 if (!taskId) return r;
438 const outputFile = outputFileOf(r.text);
439 const shell: FleetShell = {
440 id: taskId,
441 command: e.command,
442 startedAt: Date.now(),
443 status: "running",
444 ...(outputFile ? { outputFile } : {}),
445 ...(isWaiter(e.command) ? { waiter: true } : {}),
446 };
447 await update($, fleet, (f) => ({
448 ...f,
449 shells: trim([...f.shells.filter((s) => s.id !== taskId), shell]),
450 batchStart: f.batchStart ?? shell.startedAt,
451 }));
452 if (outputFile) ensureShellPoll($, t);
453 return r;
454 });
455
456 // a background task's notification: a shell or an agent finished
457 on("session.append", async ($, e, next) => {
458 const r = await next(e);
459 if (!mayNotify(e.message)) return r;
460 const note = parseNotification(textOf(e.message.content));
461 if (note) await endTask($, t, note.id, note.status);
462 return r;
463 });
464
465 // a main turn's end lists the tasks still in flight: a live shell missing
466 // from it ended with no notification (a restart, a kill), so it is lost
467 on("classic.Stop", async ($, e, next) => {
468 const r = await next(e);
469 if (!e.background_tasks) return r;
470 const inFlight = new Set(e.background_tasks.map((b) => b.id));
471 await update($, fleet, (f) => ({
472 ...f,
473 shells: loseShells(f.shells, inFlight, Date.now()),
474 }));
475 await settle($, t);
476 return r;
477 });
478
479 on("turn.complete", async ($, e, next) => {
480 const r = await next(e);
481 if (!e.agentId) return r;
482 const f = await read($, fleet);
483 const a = f.agents.find((x) => x.id === e.agentId);
484 if (a && !a.teammate && isLive(a.status))
485 await endTask(
486 $,
487 t,
488 a.id,
489 e.isAborted ? "killed" : e.reason === "error" ? "failed" : "completed",
490 );
491 return r;
492 });
493
494 on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
495 const f = await read($, fleet);
496 const view: FleetView = {
497 repo: t.repo,
498 width: e.props.bodyColumns,
499 agents: f.agents,
500 shells: f.shells,
501 trees: f.trees,
502 };
503 if (e.surface === "terminal" || e.surface === "desktop") {
504 const { Box, Button, Client, Text } = $.ui.resolve(e);
505 const live = f.shells.filter((s) => isLive(s.status));
506 return (
507 <Box flexDirection="column">
508 <Client key="fleet-body" module="./pane.tsx" props={view} />
509 {live.length > 0 && <Text> </Text>}
510 {live.map((s) => (
511 <Button
512 key={`fleet-stop-${s.id}`}
513 dimColor
514 onPress={() => stopShell($, s.id)}
515 >
516 {`stop ${shellName(s.command)}`}
517 </Button>
518 ))}
519 </Box>
520 );
521 }
522 return drawFleet($.ui.resolve(e), view, Date.now());
523 });
524
525 // its own line under the other bands: the counts and a show/hide toggle
526 on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
527 if (e.viewport?.isFullscreen !== undefined)
528 t.docks = e.viewport.isFullscreen;
529 const f = await read($, fleet);
530 const open = await read($, pane);
531 const now = await $.clock.now();
532 const empty = f.agents.length === 0 && f.shells.length === 0;
533 if (e.props.hasSurvey || (empty && !open)) return next(e);
534 const below = await next(e);
535 const { Box, Button, Text } = $.ui.resolve(e);
536 return (
537 <Box flexDirection="column">
538 {below}
539 <Box flexDirection="row" columnGap={2} marginTop={1}>
540 <Text dimColor>
541 {[statusLine(f) ?? "fleet", ...shellNotes(f.shells, now)].join(
542 " · ",
543 )}
544 </Text>
545 <Button
546 key="fleet-toggle"
547 hotkey="f"
548 dimColor
549 onPress={() => togglePane($, t)}
550 >
551 {open ? "hide" : "show"}
552 </Button>
553 </Box>
554 </Box>
555 );
556 });
557
558 on("ui.close", { id: PANE }, async ($, e, next) => {
559 const r = await next(e);
560 await update($, pane, () => false);
561 return r;
562 });
563};
564hooks/core.ts 372 lines1/**
2 * core.ts — the pure half of fleet: status transitions, parsing git and task
3 * notifications, and the words of the toasts, status line and summary.
4 */
5
6import type {
7 FleetAgent,
8 FleetProgress,
9 FleetShell,
10 FleetState,
11 FleetTree,
12} from "../types";
13
14/** Most agents and shells kept; the oldest ended ones fall off. */
15export const KEEP = 40;
16
17export const emptyFleet = (): FleetState => ({
18 agents: [],
19 shells: [],
20 trees: [],
21 autoOpened: false,
22});
23
24/** Still going: not started, running a turn, or held. */
25export const isLive = (status: string) =>
26 status === "pending" || status === "running" || status === "waiting";
27
28export const isFailed = (status: string) =>
29 status === "failed" || status === "killed";
30
31/** 45s, 6m12s, 1h04m */
32export function fmtElapsed(ms: number): string {
33 const total = Math.max(0, Math.floor(ms / 1000));
34 const h = Math.floor(total / 3600);
35 const m = Math.floor((total % 3600) / 60);
36 const s = total % 60;
37 if (h > 0) return `${h}h${String(m).padStart(2, "0")}m`;
38 return m > 0 ? `${m}m${String(s).padStart(2, "0")}s` : `${s}s`;
39}
40
41const MONTHS = [
42 "Jan",
43 "Feb",
44 "Mar",
45 "Apr",
46 "May",
47 "Jun",
48 "Jul",
49 "Aug",
50 "Sep",
51 "Oct",
52 "Nov",
53 "Dec",
54];
55
56const pad = (n: number) => String(n).padStart(2, "0");
57
58/** 16:42, with "Oct 4 " in front when it is not today. */
59export function fmtClock(at: number, now: number): string {
60 const d = new Date(at);
61 const clock = `${pad(d.getHours())}:${pad(d.getMinutes())}`;
62 return d.toDateString() === new Date(now).toDateString()
63 ? clock
64 : `${MONTHS[d.getMonth()]} ${d.getDate()} ${clock}`;
65}
66
67/** Keeps every live item and the newest ended ones, `keep` in all. */
68export function trim<T extends { status: string; startedAt: number }>(
69 items: T[],
70 keep = KEEP,
71): T[] {
72 if (items.length <= keep) return items;
73 const ended = items.filter((i) => !isLive(i.status));
74 const drop = new Set(ended.slice(0, items.length - keep));
75 return items.filter((i) => !drop.has(i));
76}
77
78const firstWord = (v: unknown) =>
79 typeof v === "string" ? v.trim().split(/\s+/).slice(0, 3).join(" ") : "";
80const baseName = (v: unknown) =>
81 typeof v === "string" ? (v.split("/").pop() ?? "") : "";
82
83/** A tool call in a few words: "Bash cargo clippy", "Read apply.rs", "Grep snapshot_". */
84export function toolLabel(tool: string, input: unknown): string {
85 const i = (input ?? {}) as Record<string, unknown>;
86 let arg = "";
87 if (tool === "Bash") arg = firstWord(i.command);
88 else if (typeof i.file_path === "string") arg = baseName(i.file_path);
89 else if (typeof i.pattern === "string") arg = i.pattern;
90 else if (typeof i.description === "string") arg = i.description;
91 const label = arg ? `${tool} ${arg}` : tool;
92 return label.length > 40 ? `${label.slice(0, 39)}…` : label;
93}
94
95/**
96 * Whether a kept row may carry a task notification: a user row when the
97 * session is idle, a queued_command attachment when a running turn absorbs it.
98 */
99export const mayNotify = (m: { type: string; name?: string }) =>
100 m.type === "user" || (m.type === "attachment" && m.name === "queued_command");
101
102/** A task notification's id and status, from the row's text. */
103export function parseNotification(
104 text: string,
105): { id: string; status: string } | undefined {
106 if (!text.includes("<task-notification>")) return undefined;
107 const id = /<task-id>([^<]+)<\/task-id>/.exec(text)?.[1]?.trim();
108 const status = /<status>([^<]+)<\/status>/.exec(text)?.[1]?.trim();
109 return id && status ? { id, status } : undefined;
110}
111
112/**
113 * Applies statuses (from `$.agent.list()`, a notification, a turn's end) to
114 * the agents; answers the new list and the agents that just ended.
115 */
116export function applyStatuses(
117 agents: FleetAgent[],
118 statuses: Record<string, string>,
119 now: number,
120): { agents: FleetAgent[]; ended: FleetAgent[] } {
121 const ended: FleetAgent[] = [];
122 const next = agents.map((a) => {
123 const status = statuses[a.id];
124 if (status === undefined || status === a.status) return a;
125 // a resumed agent goes live again under the same id
126 if (isLive(status)) {
127 const { endedAt: _, ...rest } = a;
128 return { ...rest, status };
129 }
130 const changed = { ...a, status, endedAt: a.endedAt ?? now };
131 if (isLive(a.status)) ended.push(changed);
132 return changed;
133 });
134 return { agents: next, ended };
135}
136
137/** A shell the engine stopped tracking with no notification: its exit is unknown. */
138export const LOST = "lost";
139
140/**
141 * Marks a shell ended by its task id; answers it, or undefined if it is not a
142 * live or lost one. A lost one's late notification still sets its real status.
143 */
144export function endShell(
145 shells: FleetShell[],
146 id: string,
147 status: string,
148 now: number,
149): { shells: FleetShell[]; ended?: FleetShell } {
150 let ended: FleetShell | undefined;
151 const next = shells.map((s) => {
152 if (s.id !== id || !(isLive(s.status) || s.status === LOST)) return s;
153 ended = { ...s, status, endedAt: s.endedAt ?? now };
154 return ended;
155 });
156 return { shells: next, ended };
157}
158
159/** Marks lost each live shell the engine no longer has in flight. */
160export function loseShells(
161 shells: FleetShell[],
162 inFlight: ReadonlySet<string>,
163 now: number,
164): FleetShell[] {
165 return shells.map((s) =>
166 isLive(s.status) && !inFlight.has(s.id)
167 ? { ...s, status: LOST, endedAt: now }
168 : s,
169 );
170}
171
172export const liveCount = (f: FleetState) =>
173 f.agents.filter((a) => isLive(a.status)).length +
174 f.shells.filter((s) => isLive(s.status)).length;
175
176/** "✓ rust-reviewer · review apply · 6m12s" or "✗ Explore failed · map callers · 2m03s" */
177export function endToast(
178 name: string,
179 what: string,
180 status: string,
181 ms: number,
182): string {
183 const head = isFailed(status) ? `✗ ${name} ${status}` : `✓ ${name}`;
184 return [head, what, fmtElapsed(ms)].filter(Boolean).join(" · ");
185}
186
187/** The batch's counts on the band line above the prompt: "fleet 2▶ 1✓ 0✗ · bg 1" */
188export function statusLine(f: FleetState): string | undefined {
189 const batch = f.batchStart;
190 if (batch === undefined) return undefined;
191 const agents = f.agents.filter((a) => a.startedAt >= batch);
192 const run = agents.filter((a) => isLive(a.status)).length;
193 const fail = agents.filter((a) => isFailed(a.status)).length;
194 const done = agents.length - run - fail;
195 const bg = f.shells.filter((s) => isLive(s.status)).length;
196 return `fleet ${run}▶ ${done}✓ ${fail}✗${bg ? ` · bg ${bg}` : ""}`;
197}
198
199/** The all-done message: how many, how long, what failed, which shells. */
200export function summary(f: FleetState, repo: string, now: number): string {
201 const batch = f.batchStart ?? now;
202 const agents = f.agents.filter((a) => a.startedAt >= batch);
203 const shells = f.shells.filter((s) => s.startedAt >= batch);
204 const failed = agents.filter((a) => isFailed(a.status));
205 const lines = [`🤖 fleet · ${repo}`];
206 if (agents.length) {
207 lines.push(
208 `All ${agents.length} agent${agents.length === 1 ? "" : "s"} done in ${fmtElapsed(now - batch)}`,
209 );
210 const fails = failed.length
211 ? ` ✗ ${failed.length} failed (${failed.map((a) => `${a.type}: ${a.description}`).join("; ")})`
212 : "";
213 lines.push(`✓ ${agents.length - failed.length} completed${fails}`);
214 } else {
215 lines.push(`All done in ${fmtElapsed(now - batch)}`);
216 }
217 // no command text leaves the device: any word of it may hold a secret
218 if (shells.length) {
219 const bad = shells.filter((s) => isFailed(s.status)).length;
220 const lost = shells.filter((s) => s.status === LOST).length;
221 lines.push(
222 `Background shells: ✓ ${shells.length - bad - lost}${bad ? ` ✗ ${bad}` : ""}${lost ? ` ? ${lost}` : ""}`,
223 );
224 }
225 return lines.join("\n");
226}
227
228/** `git worktree list --porcelain` → each tree's path and branch (or short head). */
229export function parseWorktrees(
230 porcelain: string,
231): { path: string; name: string }[] {
232 const trees: { path: string; name: string }[] = [];
233 for (const block of porcelain.split(/\n\n+/)) {
234 const path = /^worktree (.+)$/m.exec(block)?.[1];
235 if (!path || /^bare$/m.test(block)) continue;
236 const branch = /^branch refs\/heads\/(.+)$/m.exec(block)?.[1];
237 const head = /^HEAD ([0-9a-f]{7})/m.exec(block)?.[1];
238 trees.push({ path, name: branch ?? `(${head ?? "detached"})` });
239 }
240 return trees;
241}
242
243/** `git status --porcelain=v1 --branch` → changed files and ahead/behind of upstream. */
244export function parseStatus(
245 porcelain: string,
246): Pick<FleetTree, "changed" | "ahead" | "behind"> {
247 const lines = porcelain.split("\n").filter(Boolean);
248 const head = lines[0]?.startsWith("## ") ? lines.shift()! : "";
249 return {
250 changed: lines.length,
251 ahead: Number(/ahead (\d+)/.exec(head)?.[1] ?? 0),
252 behind: Number(/behind (\d+)/.exec(head)?.[1] ?? 0),
253 };
254}
255
256/** No output for this long marks a live shell stalled. */
257export const STALL_MS = 5 * 60_000;
258
259/** The output file a background Bash result names. */
260export function outputFileOf(text: string | undefined): string | undefined {
261 return /Output is being written to: (\S+?\.output)\b/.exec(text ?? "")?.[1];
262}
263
264/** Escape sequences: OSC (titles, links, clipboard), then CSI (colours, cursor), then any other ESC pair. */
265const ESCAPES = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?|\x1b\[[0-?]*[ -/]*[@-~]|\x1b[\s\S]?/g;
266/** Control characters left once lines are split: none of them reaches the screen. */
267const CONTROLS = /[\x00-\x1f\x7f-\x9f]/g;
268
269/**
270 * The last non-blank line of an output tail: a `\r`-redrawn bar's last frame,
271 * every escape sequence and control character dropped, since the output is
272 * the shell's and goes on screen.
273 */
274export function lastLine(tail: string): string | undefined {
275 return tail
276 .replace(ESCAPES, "")
277 .split(/\r\n|\r|\n/)
278 .map((l) => l.replace(CONTROLS, "").trim())
279 .filter(Boolean)
280 .at(-1);
281}
282
283/**
284 * The fraction done a line says: "47%" or "month 14/30". A slash inside a
285 * date or a path (2026/10/12, src/10/12) is no count.
286 */
287export function parseProgress(line: string): number | undefined {
288 const pct = /(\d{1,3}(?:\.\d+)?)\s*%/.exec(line);
289 if (pct && Number(pct[1]) <= 100) return Number(pct[1]) / 100;
290 for (const m of line.matchAll(/(?<![\d./-])(\d+)\s*\/\s*(\d+)(?![\d./-])/g)) {
291 const done = Number(m[1]);
292 const total = Number(m[2]);
293 if (total >= 2 && done <= total) return done / total;
294 }
295 return undefined;
296}
297
298/** A new reading: kept from where it started, restarted when it goes back (a new phase). */
299export function nextProgress(
300 prev: FleetProgress | undefined,
301 frac: number | undefined,
302 now: number,
303): FleetProgress | undefined {
304 if (frac === undefined) return prev;
305 if (!prev || frac < prev.frac) return { frac, firstAt: now, firstFrac: frac };
306 return { ...prev, frac };
307}
308
309/** Time left at the rate seen so far; undefined until 30 s of movement. */
310export function etaMs(p: FleetProgress, now: number): number | undefined {
311 const dt = now - p.firstAt;
312 const df = p.frac - p.firstFrac;
313 if (dt < 30_000 || df <= 0) return undefined;
314 return ((1 - p.frac) * dt) / df;
315}
316
317/** 38m, 1h10m, <1m */
318export function fmtLeft(ms: number): string {
319 const m = Math.round(ms / 60_000);
320 if (m < 1) return "<1m";
321 return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h${pad(m % 60)}m`;
322}
323
324/** A wait loop: `until …; do …; done`, or a `while` that sleeps. */
325export const isWaiter = (command: string) =>
326 /\buntil\b[\s\S]*\bdo\b|\bwhile\b[\s\S]*\bsleep\b/.test(command);
327
328const SETUP = /^(cd|export|set|source|\.)(\s|$)/;
329const ASSIGN = /^[A-Za-z_][A-Za-z0-9_]*=/;
330
331/** A shell in a few words: the first real step's program and argument, "retrain.sh d57". */
332export function shellName(command: string): string {
333 const step =
334 command
335 .split(/&&|\|\||;|\n/)
336 .map((s) => s.trim())
337 .find((s) => s && !SETUP.test(s) && !s.split(/\s+/).every((w) => ASSIGN.test(w))) ??
338 command.trim();
339 const name = step
340 .split(/\s+/)
341 .filter((w) => !ASSIGN.test(w))
342 .slice(0, 2)
343 .map((w) => w.split("/").pop())
344 .join(" ");
345 return name.length > 20 ? `${name.slice(0, 19)}…` : name;
346}
347
348/** How quiet a live shell has been. */
349export const quietMs = (s: FleetShell, now: number) =>
350 now - (s.outputAt ?? s.startedAt);
351
352/** A live shell's state in a few words, or undefined when there is nothing to say. */
353export function shellNote(s: FleetShell, now: number): string | undefined {
354 if (s.waiter) return "waiting";
355 if (s.stalled) return `⚠ no output ${fmtLeft(quietMs(s, now))}`;
356 if (!s.progress) return undefined;
357 const left = etaMs(s.progress, now);
358 return `${Math.floor(s.progress.frac * 100)}%${left === undefined ? "" : ` ~${fmtLeft(left)}`}`;
359}
360
361/** The band's progress items: "sim.py 47% ~38m", "retrain.sh d57 ⚠ 6m". */
362export function shellNotes(shells: FleetShell[], now: number): string[] {
363 return shells
364 .filter((s) => isLive(s.status) && !s.waiter)
365 .flatMap((s) => {
366 const name = shellName(s.command);
367 if (s.stalled) return [`${name} ⚠ ${fmtLeft(quietMs(s, now))}`];
368 const note = shellNote(s, now);
369 return note ? [`${name} ${note}`] : [];
370 });
371}
372hooks/view.tsx 169 lines1/**
2 * view.tsx — the pane's body, drawn from a snapshot and a time. The hook draws
3 * it once where a surface has no Client; the Client redraws it every second.
4 */
5
6import type { FleetAgent, FleetShell, FleetTree } from "../types";
7import {
8 etaMs,
9 fmtClock,
10 fmtElapsed,
11 fmtLeft,
12 isFailed,
13 isLive,
14 LOST,
15 quietMs,
16} from "./core.ts";
17
18export type FleetView = {
19 repo: string;
20 width: number;
21 agents: FleetAgent[];
22 shells: FleetShell[];
23 trees: FleetTree[];
24};
25
26/** The two elements the body uses, from `$.ui.resolve(e)` or `surface.elements`. */
27type Elements = { Box: any; Text: any };
28
29const fit = (s: string, n: number) =>
30 s.length > n ? `${s.slice(0, Math.max(1, n - 1))}…` : s.padEnd(n);
31
32/** "6m12s" while live; "6m12s · 16:42" once ended, with when it ended. */
33const timing = (i: { startedAt: number; endedAt?: number }, now: number) =>
34 i.endedAt === undefined
35 ? fmtElapsed(now - i.startedAt)
36 : `${fmtElapsed(i.endedAt - i.startedAt)} · ${fmtClock(i.endedAt, now)}`;
37
38/** Live ones first, then the most recently ended. */
39const order = <
40 T extends { status: string; startedAt: number; endedAt?: number },
41>(
42 items: T[],
43) =>
44 [...items].sort(
45 (a, b) =>
46 Number(isLive(b.status)) - Number(isLive(a.status)) ||
47 (b.endedAt ?? b.startedAt) - (a.endedAt ?? a.startedAt),
48 );
49
50function mark(Text: any, status: string) {
51 if (isLive(status)) return <Text color="cyan">▶</Text>;
52 if (status === LOST) return <Text dimColor>?</Text>;
53 return isFailed(status) ? (
54 <Text color="red">✗</Text>
55 ) : (
56 <Text color="green">✓</Text>
57 );
58}
59
60/** "▓▓▓▓░░░░░░" */
61const bar = (frac: number, n = 10) => {
62 const full = Math.max(0, Math.min(n, Math.round(frac * n)));
63 return "▓".repeat(full) + "░".repeat(n - full);
64};
65
66/** A live shell's second line: waiting, stalled, or its progress, then its last output line. */
67function shellDetail(Text: any, s: FleetShell, now: number, w: number) {
68 const line = s.line ?? "";
69 if (s.waiter)
70 return <Text dimColor>{fit(` waiting${line ? ` · ${line}` : ""}`, w).trimEnd()}</Text>;
71 if (s.stalled) {
72 const head = ` ⚠ no output ${fmtLeft(quietMs(s, now))}`;
73 return (
74 <Text>
75 <Text color="yellow">{head}</Text>
76 <Text dimColor>{fit(line ? ` · ${line}` : "", Math.max(0, w - head.length)).trimEnd()}</Text>
77 </Text>
78 );
79 }
80 if (s.progress) {
81 const left = etaMs(s.progress, now);
82 const head = ` ${bar(s.progress.frac)} ${Math.floor(s.progress.frac * 100)}%${left === undefined ? "" : ` ~${fmtLeft(left)}`}`;
83 return (
84 <Text>
85 <Text color="cyan">{head}</Text>
86 <Text dimColor>{fit(` · ${line}`, Math.max(0, w - head.length)).trimEnd()}</Text>
87 </Text>
88 );
89 }
90 return <Text dimColor>{fit(` ${line}`, w).trimEnd()}</Text>;
91}
92
93export function drawFleet(els: Elements, v: FleetView, now: number) {
94 const { Box, Text } = els;
95 const w = Math.max(24, v.width);
96 const name = Math.min(18, w - 10);
97 const run = v.agents.filter((a) => isLive(a.status)).length;
98 const fail = v.agents.filter((a) => isFailed(a.status)).length;
99 const done = v.agents.length - run - fail;
100
101 return (
102 <Box flexDirection="column">
103 <Text>
104 <Text bold>FLEET</Text>
105 <Text dimColor>{` · ${v.repo}`}</Text>
106 </Text>
107 <Text> </Text>
108 <Text
109 dimColor
110 >{`AGENTS ${run} running · ${done} done · ${fail} failed`}</Text>
111 {v.agents.length === 0 && <Text dimColor> none yet</Text>}
112 {order(v.agents).map((a) => (
113 <Box key={a.id} flexDirection="column">
114 <Text>
115 {mark(Text, a.status)}
116 {` ${fit(a.type, name)} ${timing(a, now)}`}
117 </Text>
118 <Text dimColor>
119 {" " +
120 fit(
121 isLive(a.status) && a.lastTool
122 ? `${a.description} · ${a.lastTool}`
123 : a.description,
124 w - 3,
125 ).trimEnd()}
126 </Text>
127 </Box>
128 ))}
129 {v.shells.length > 0 && <Text> </Text>}
130 {v.shells.length > 0 && <Text dimColor>BACKGROUND</Text>}
131 {order(v.shells).map((s) => {
132 const time = timing(s, now);
133 const row = (
134 <Text>
135 {mark(Text, s.status)}
136 {` ${fit(s.command, Math.max(8, w - 4 - time.length))} ${time}`}
137 </Text>
138 );
139 if (!isLive(s.status) || (!s.line && !s.waiter && !s.stalled))
140 return (
141 <Box key={s.id} flexDirection="column">
142 {row}
143 </Box>
144 );
145 return (
146 <Box key={s.id} flexDirection="column">
147 {row}
148 {shellDetail(Text, s, now, w)}
149 </Box>
150 );
151 })}
152 {v.trees.length > 0 && <Text> </Text>}
153 {v.trees.length > 0 && <Text dimColor>WORKTREES</Text>}
154 {v.trees.map((t) => (
155 <Text key={t.path}>
156 {` ${fit(t.name, name)} `}
157 {t.changed ? (
158 <Text color="yellow">{`●${t.changed} changed`}</Text>
159 ) : (
160 <Text dimColor>clean</Text>
161 )}
162 {t.ahead ? ` ↑${t.ahead}` : ""}
163 {t.behind ? ` ↓${t.behind}` : ""}
164 </Text>
165 ))}
166 </Box>
167 );
168}
169hooks/pane.tsx 15 lines1import type { ClientModule } from "claude-code";
2
3import { drawFleet, type FleetView } from "./view.tsx";
4
5/** The pane's body, redrawn every second so elapsed times tick with no hook call. */
6const FleetPane: ClientModule<FleetView, number> = (props, surface) => {
7 if (surface.state === undefined) {
8 surface.every(1000, () => surface.setState(Date.now()));
9 surface.setState(Date.now());
10 }
11 return drawFleet(surface.elements, props, surface.state ?? Date.now());
12};
13
14export default FleetPane;
15types/index.d.ts 69 lines1export type FleetAgent = {
2 id: string;
3 type: string;
4 description: string;
5 model?: string;
6 startedAt: number;
7 endedAt?: number;
8 /** AgentStatus, as `$.agent.list()` or a task notification last said */
9 status: string;
10 /** The last tool it called, short: "Bash cargo clippy" */
11 lastTool?: string;
12 tools: number;
13 /** A teammate goes idle between turns, so its turn's end is no finish */
14 teammate?: boolean;
15};
16
17/** A fraction done, and where the reading started, for the ETA. */
18export type FleetProgress = {
19 frac: number;
20 firstAt: number;
21 firstFrac: number;
22};
23
24export type FleetShell = {
25 id: string;
26 command: string;
27 startedAt: number;
28 endedAt?: number;
29 status: string;
30 /** The file the engine writes the shell's output to */
31 outputFile?: string;
32 /** The output file's size at the last look */
33 size?: number;
34 /** When the output last grew (ms) */
35 outputAt?: number;
36 /** The last non-blank line of output */
37 line?: string;
38 progress?: FleetProgress;
39 /** A wait loop (`until …; do sleep`): quiet by design, never stalled */
40 waiter?: boolean;
41 /** No output for the stall time; set once, cleared by new output */
42 stalled?: boolean;
43};
44
45export type FleetTree = {
46 name: string;
47 path: string;
48 changed: number;
49 ahead: number;
50 behind: number;
51};
52
53export type FleetState = {
54 agents: FleetAgent[];
55 shells: FleetShell[];
56 trees: FleetTree[];
57 /** When the current batch's first item started; unset between batches */
58 batchStart?: number;
59 /** Whether this batch already opened the pane by itself */
60 autoOpened: boolean;
61};
62
63declare module "claude-code" {
64 interface PluginState {
65 /** pane: whether the fleet pane is open (shown or a tab); lastPrompt: when the person last sent a prompt (ms), for the away check */
66 fleet: { fleet: FleetState; pane: boolean; lastPrompt: number };
67 }
68}
69