SLOPSHOPPER

summary

Toggle a summary pane (/summary) of skill runs, subagents and teammates, edited files, failed tool calls and recent work

panespinnerguardcommandpromptmodel
★ 9v0.1.0MITupdated 2026-10-21ysoftman/myenv/.claude/mods/summary
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · summary
│ ┃ summary ✕ › fix the failing auth test and add an audit log call │ ┃ SUMMARY 📝 summarizing │ ┃ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ⏺ Read(src/auth.ts) │ ┃ ╭─────────────────────────────────────────── ⎿ Read 6 lines │ ┃ │ alerts ⏺ Update(src/auth.ts) │ ┃ │ ✗ 0s ago Bash src/auth.test.ts: ⎿ Added 2 lines, removed 1 line │ ┃ ╰─────────────────────────────────────────── ⏺ Bash(bun test) │ ┃ ╭─────────────────────────────────────────── ⎿ 3 pass, 1 fail │ ┃ │ recent │ ┃ │ ⠦ summarizing… ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ 0s ago · 42s · 8k │ ┃ ╰─────────────────────────────────────────── ✻ Worked for 42s · done 4:20 PM │ ┃ ╭─────────────────────────────────────────── │ ┃ │ agents & jobs › /summary │ ┃ │ nothing running or scheduled │ ┃ ╰─────────────────────────────────────────── │ ┃ ╭─────────────────────────────────────────── │ ┃ │ files 3 edited · 0 uncommitted │ ┃ │ · 1× src/cache.ts │ ┃ │ · 1× src/audit.ts │ ┃ │ · 1× src/auth.ts │ ┃ ╰─────────────────────────────────────────── │ ┃ ╭─────────────────────────────────────────── │ ┃ │ git ? (no upstream) · 0 uncommitted │ ┃ │ no commit yet │ ┃ ╰─────────────────────────────────────────── ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · summary
SUMMARY 📝 summarizing ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ╭──────────────────────────────────────────────────────╮ │ alerts │ │ ✗ 0s ago Bash src/auth.test.ts: │ ╰──────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────╮ │ recent │ │ ⠦ summarizing… │ │ 0s ago · 42s · 8k │ ╰──────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────╮ │ agents & jobs │ │ nothing running or scheduled │ ╰──────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────╮ │ files 3 edited · 0 uncommitted │ │ · 1× src/cache.ts │ │ · 1× src/audit.ts │ │ · 1× src/auth.ts │ ╰──────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────╮ │ git ? (no upstream) · 0 uncommitted │ │ no commit yet │ ╰──────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────╮ │ skills │ │ no skill yet │ ╰──────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────╮ │ turn time 1 turn · avg 42s · max 42s │ │ █ │ ╰──────────────────────────────────────────────────────╯ toggle ctrl+x tab focus /summary help ⚠ shortcuts not set · you can ask Claude "set up shortcuts per the summary mod README" or add to ~/.claude/keybindings.json (merge into existing blocks): "Chat": "ctrl+x s": "command:summary" "Global": "ctrl+<": "pane:previous", "ctrl+>": "pane:next" also "ctrl+shift+," / "ctrl+shift+." if your terminal sends those 7ホ コラ ン セ ミ 9 ハ チ キソ セ ク コメ ロ ソタ ロヌ 9 ル カ 3 メ ネ 8ハ ハ ツ フ ルケ 2 メル ネ 8 ヘ ノ クヘケ ウモロタト オ ヘユ チ 6 ケア キ wake up, neo... the matrix resumes when claude works█ シ 2エ2カケ リメ3
README

summary mod

Claude Code 세션에서 지금 무슨 일이 일어나고 있는지 한 패널에 모아 보여 주는 mod 다.

박스내용
헤더진행 중인 일: ⏳ 메인 턴, 🔧 스킬, 🤖 서브에이전트, 📝 recent 요약 생성
recent끝난 턴마다 한 줄 요약 (haiku), 경과·소요 시간, 토큰
agents & jobs서브에이전트, background shell, session cron
files세션이 고친 파일과 git 상태 (1× Edit 횟수, · shell·서브에이전트가 바꾼 파일)
git브랜치, upstream, ahead/behind, 최근 커밋, 현재 브랜치의 열린 PR (아래 "PR 줄")
skills실행한 스킬과 모델
turn time메인 턴마다 걸린 시간 sparkline

PR 줄

git 박스에 현재 브랜치의 열린 PR 을 한 줄로 보여 준다. 예: PR #12 ✅ approved · CI ✔ · 💬 2 unresolved

항목표시
draft✎ draft
리뷰✅ approved, ❌ changes requested, 👀 review required
CI (마지막 커밋의 check 종합)CI ✔, CI ✗ failed, CI ⋯ running, check 가 없으면 생략
미해결 리뷰 스레드💬 N unresolved, 0 이면 생략

approve 됐고 draft 가 아니며 CI 가 통과했거나 없으면 ⇢ ready: merge it in the web UI 와 PR URL 을 덧붙인다. 머지는 사람이 GitHub 웹 UI 에서 한다.

  • gh 로그인과 GitHub (Enterprise 포함) remote 가 필요하다. remote 는 gh 처럼 upstream, github, origin 순으로 골라 그 호스트로 gh api graphql 을 한 번 부른다. gh 가 없거나 인증이 안 됐거나 열린 PR 이 없으면 줄을 그리지 않는다.
  • 필수 리뷰 규칙이 없는 저장소(reviewDecision 없음)는 최신 리뷰에 approve 가 있고 change request 가 없으면 approved 로 본다.
  • 남의 fork 에서 같은 브랜치 이름으로 연 PR 은 빼고, 내 fork 에서 연 PR 은 보여 준다.
  • 네트워크 호출이라 세션 시작과 턴이 끝날 때 읽되, 직전 조회 후 60초가 안 됐으면 건너뛴다. Bash 로 git push 나 gh pr ... 를 실행한 직후, 브랜치가 바뀐 뒤 처음 끝나는 턴에는 바로 읽는다. 쉬는 동안 받은 approve 는 다음 턴이 끝날 때 보인다.

설치

이 폴더를 plugin 디렉터리로 로드한다. 둘 중 하나를 쓴다.

  • ~/.claude/settings.json 의 env.CLAUDE_CODE_PLUGIN_DIRS 에 이 폴더 경로를 넣는다 (여러 개면 : 로 구분).
  • claude --plugin-dir <이 폴더> 로 실행한다.

myenv 의 installclaudecode.sh 는 .claude/mods/* 를 CLAUDE_CODE_PLUGIN_DIRS 에 넣고, 아래 단축키도 그 키나 action 이 비어 있을 때만 keybindings.json 에 넣어 준다(예전 app:toggleDiffPreSession 바인딩은 옮겨 준다).

Claude Code 2.1.296 에서 확인했다 (PR 줄은 2.1.299).

사용

Claude 를 시작하면 패널이 바로 열린다. 다만 엔진은 요청 없이 연 패널을 터미널이 144칸(전에 열어 두고 손으로 닫지 않았다면 110칸) 이상일 때만 그린다. 그보다 좁으면 터미널을 넓히거나 /summary 를 실행할 때 보인다. /reload-plugins 때는 다시 열지 않는다.

  • /summary: 패널 열기/닫기. 다른 탭에 가려져 있으면 닫지 않고 앞으로 꺼낸다. 출력은 남기지 않는다.
  • /summary help: 사용법. 단축키를 설정하지 않았으면 설정 방법도 보여 준다.

단축키

plugin 은 단축키를 직접 등록할 수 없어, 각자 ~/.claude/keybindings.json 에 추가해야 한다. command:<이름> action 은 그 슬래시 명령을 입력한 것처럼 실행하므로 /summary 를 키에 묶는다.

{
  "$schema": "https://www.schemastore.org/claude-code-keybindings.json",
  "bindings": [
    { "context": "Chat", "bindings": { "ctrl+x s": "command:summary" } },
    {
      "context": "Global",
      "bindings": {
        "ctrl+<": "pane:previous",
        "ctrl+shift+,": "pane:previous",
        "ctrl+>": "pane:next",
        "ctrl+shift+.": "pane:next"
      }
    }
  ]
}

이미 keybindings.json 이 있으면 파일을 덮어쓰지 말고, "Chat"·"Global" 블록의 bindings 에 위 줄만 추가한다(블록이 없으면 추가하고, 이미 다른 키에 묶은 action 이나 다른 action 에 쓰는 키는 건너뛴다). 예전에 넣은 "Global" 의 "ctrl+x s": "app:toggleDiffPreSession" 은 지운다.

바인딩하기 전에는 패널 하단과 프롬프트 아래 힌트 줄에 /summary 가 보이고, 바인딩하면 그 키가 보인다. 빠진 바인딩이 있으면 패널 하단에 넣을 줄과 함께 설정 안내가 나온다. Claude 에게 "set up shortcuts per the summary mod README"(또는 "summary mod README 대로 단축키 설정해줘") 라고 하면 위 바인딩을 대신 넣어 준다. 다른 키에 묶어도 그 키가 안내에 표시된다.

패널 탭 이동은 엔진 action pane:previous/pane:next 로 한다. 모든 mod 의 패널을 순서대로 돌고, 기본 키가 없어 "Global" 블록에 "ctrl+<": "pane:previous", "ctrl+>": "pane:next" 처럼 묶는다(터미널에 따라 ctrl+shift+,/ctrl+shift+. 로 들어오므로 함께 묶어 둔다). 묶으면 패널 하단에 그 키가 tabs 로 보인다.

Source 9 files
hooks/register.tsx 1057 lines
1import type { ClassicHookInputs, EngineInterface, Register } from "claude-code";
2import { atom, read, update } from "claude-code";
3import type {
4	AgentRow,
5	Alert,
6	BackgroundTask,
7	Commit,
8	FileTouch,
9	RepoState,
10	SessionCron,
11	SkillRun,
12	TurnMark,
13	WorkItem,
14} from "../types";
15import {
16	clip,
17	cut,
18	firstLine,
19	newTokens,
20	pathOf,
21	short,
22	totalTokens,
23} from "./format";
24import { paneView } from "./pane";
25import { readPullRequest } from "./pr";
26import {
27	newRain,
28	RAIN,
29	RAIN_MS,
30	RAIN_ROWS,
31	rainCells,
32	rainMessage,
33	rainSpeed,
34} from "./rain";
35import {
36	end,
37	isBusy,
38	isLive,
39	isOpenRun,
40	RUN_END,
41	STATUS,
42	sync,
43	TURN_END,
44} from "./status";
45import { PANE, RECENT_SHOWN, SHOWN } from "./theme";
46
47const agents = atom({ plugin: "summary", key: "agents" } as const, []);
48
49const now = atom({ plugin: "summary", key: "now" } as const, 0);
50
51const recent = atom({ plugin: "summary", key: "recent" } as const, []);
52
53const files = atom({ plugin: "summary", key: "files" } as const, []);
54
55const dirty = atom({ plugin: "summary", key: "dirty" } as const, 0);
56
57const alerts = atom({ plugin: "summary", key: "alerts" } as const, []);
58
59const skillRuns = atom({ plugin: "summary", key: "runs" } as const, []);
60
61const mainModel = atom({ plugin: "summary", key: "model" } as const, "");
62
63const paneShown = atom({ plugin: "summary", key: "shown" } as const, false);
64
65const chord = atom({ plugin: "summary", key: "chord" } as const, "");
66
67const tabs = atom({ plugin: "summary", key: "tabs" } as const, "");
68
69// a reload raises session.start again, so the pane opens on its own only once
70const autoOpened = atom(
71	{ plugin: "summary", key: "autoOpened" } as const,
72	false,
73);
74
75const seen = atom({ plugin: "summary", key: "seen" } as const, []);
76
77// when the main turn in progress began; 0 while Claude is idle
78const working = atom({ plugin: "summary", key: "working" } as const, 0);
79
80// background work and session crons as the last stop reported them
81const tasks = atom({ plugin: "summary", key: "tasks" } as const, []);
82
83const crons = atom({ plugin: "summary", key: "crons" } as const, []);
84
85const turns = atom({ plugin: "summary", key: "turns" } as const, []);
86
87const repo = atom({ plugin: "summary", key: "repo" } as const, {
88	ahead: 0,
89	behind: 0,
90	commits: [],
91});
92
93const pullRequest = atom({ plugin: "summary", key: "pr" } as const, null);
94
95const FILES_MAX = 20;
96
97const TURNS_MAX = 200;
98
99const EDIT_TOOLS = new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
100
101// a subagent's spawn lasts its whole run, its own calls bring their spans;
102// the rest wait on the user, who may be editing meanwhile
103const NO_SPAN = new Set([
104	"Agent",
105	"Task",
106	"SubagentHandback",
107	"Workflow",
108	"AskUserQuestion",
109	"EnterPlanMode",
110	"ExitPlanMode",
111]);
112
113// a file's mtime and the clock may round apart
114const SLACK_MS = 1_000;
115
116// gh goes over the network, so the PR is read at most once a minute
117const PR_MS = 60_000;
118
119const PR_CHANGE = /\bgit\s+(?:-C\s+\S+\s+)?push\b|\bgh\s+pr\b/;
120
121// while a tool call of Claude's ran; open while it runs or a shell it left does
122type Span = { from: number; to?: number; id?: string; use?: string };
123
124const line = (s: string) => cut(s.split("\n")[0] ?? "", 120);
125
126const SUMMARY =
127	"You write one-line entries for a log of finished work. Given what the user asked and the " +
128	"coding assistant's final reply, say what the assistant did in at most 40 characters, in the " +
129	"language of the reply, as a terse phrase. Describe the action taken, not the content it " +
130	"reported. No quotes, no markdown, no trailing period.";
131
132const patch = async (
133	$: EngineInterface,
134	id: string,
135	fn: (a: AgentRow) => AgentRow | undefined,
136) => {
137	if ((await read($, agents)).some((a) => a.id === id && fn(a) !== undefined)) {
138		await update($, agents, (list) =>
139			list.map((a) => (a.id === id ? (fn(a) ?? a) : a)),
140		);
141	}
142};
143
144const summarize = async ($: EngineInterface, ask: string, answer: string) => {
145	try {
146		const done = await $.model.complete({
147			model: "haiku",
148			system: SUMMARY,
149			prompt: `User asked:\n${ask}\n\nAssistant replied:\n${answer}`,
150			maxTokens: 60,
151			timeoutMs: 20_000,
152		});
153		const line = done.isAnswered ? done.text.split("\n")[0]?.trim() : undefined;
154		return line ? cut(line, 60) : firstLine(answer);
155	} catch {
156		return firstLine(answer);
157	}
158};
159
160let prAt = Number.NEGATIVE_INFINITY;
161let prBranch: string | undefined;
162let prRun: Promise<unknown> = Promise.resolve();
163
164// a checkout reads the new branch's PR without waiting
165const refreshPr = (
166	$: EngineInterface,
167	root: string | undefined,
168	force = false,
169) => {
170	const run = prRun.then(async () => {
171		const { branch } = await read($, repo);
172		const t = await $.clock.now();
173		if (!force && branch === prBranch && t - prAt < PR_MS) {
174			return;
175		}
176		prAt = t;
177		prBranch = branch;
178		const next =
179			root === undefined || branch === undefined
180				? null
181				: await readPullRequest($, root, branch);
182		if (JSON.stringify(next) !== JSON.stringify(await read($, pullRequest))) {
183			await update($, pullRequest, () => next);
184		}
185	});
186	prRun = run.catch(() => undefined);
187	return prRun;
188};
189
190// "## main...origin/main [ahead 1, behind 2]", the head line of `status -b`,
191// and the last commits: the first `ahead` of them are not pushed yet.
192const refreshRepo = async ($: EngineInterface, root: string, head: string) => {
193	const m =
194		/^## (?:No commits yet on )?(.+?)(?:\.\.\.(\S+))?(?: \[(.*)\])?$/.exec(
195			head,
196		);
197	const count = (word: string) =>
198		Number(new RegExp(`${word} (\\d+)`).exec(m?.[3] ?? "")?.[1] ?? 0);
199	const log = await $.process
200		.run(
201			[
202				"git",
203				"-C",
204				root,
205				"log",
206				"-n",
207				String(SHOWN),
208				"--format=%h%x09%ct%x09%s",
209			],
210			{
211				timeoutMs: 5_000,
212			},
213		)
214		.catch(() => undefined);
215	const commits: Commit[] =
216		log?.exitCode === 0
217			? log.stdout
218					.split("\n")
219					.map((l) => l.split("\t"))
220					.filter((f) => f.length >= 3)
221					.map(([hash = "", at = "0", ...subject]) => ({
222						hash,
223						at: Number(at) * 1000,
224						subject: subject.join("\t"),
225					}))
226			: [];
227	const next: RepoState = {
228		...(m?.[1] === undefined ? {} : { branch: m[1] }),
229		...(m?.[2] === undefined ? {} : { upstream: m[2] }),
230		ahead: count("ahead"),
231		behind: count("behind"),
232		commits,
233	};
234	if (JSON.stringify(next) !== JSON.stringify(await read($, repo))) {
235		await update($, repo, () => next);
236	}
237};
238
239// One read at a time: two at once could prune a span the other still judges by.
240let reading: Promise<unknown> = Promise.resolve();
241
242const refreshGit = (
243	$: EngineInterface,
244	root: string | undefined,
245	spans: Span[],
246) => {
247	const run = reading.then(() => readGit($, root, spans));
248	reading = run.catch(() => undefined);
249	return run;
250};
251
252// A path that turned dirty joins files when it changed while one of Claude's
253// tool calls ran; one gone or moved has no telling mtime, so any call since the
254// last read does.
255const readGit = async (
256	$: EngineInterface,
257	root: string | undefined,
258	spans: Span[],
259) => {
260	if (root === undefined) {
261		return;
262	}
263	const at = await $.clock.now();
264	const run = await $.process
265		.run(
266			[
267				"git",
268				"-C",
269				root,
270				"status",
271				"--porcelain=v1",
272				"--branch",
273				"--untracked-files=all",
274			],
275			{
276				timeoutMs: 5_000,
277			},
278		)
279		.catch(() => undefined);
280	if (run === undefined || run.exitCode !== 0) {
281		return;
282	}
283	const lines = run.stdout.split("\n");
284	await refreshRepo($, root, lines[0]?.startsWith("## ") ? lines[0] : "");
285	const status = new Map(
286		lines
287			.filter((l) => l.length > 3 && !l.startsWith("## "))
288			.map(
289				(l) =>
290					[
291						l.slice(3).split(" -> ").at(-1) ?? "",
292						l.slice(0, 2).trim(),
293					] as const,
294			),
295	);
296	if ((await read($, dirty)) !== status.size) {
297		await update($, dirty, () => status.size);
298	}
299	const before = await read($, seen);
300	const paths = [...status.keys()];
301	if (JSON.stringify(paths) !== JSON.stringify(before)) {
302		await update($, seen, () => paths);
303	}
304	const known = new Set([
305		...before,
306		...(await read($, files)).map((f) => f.path),
307	]);
308	const fresh = paths.filter(
309		(p) => !known.has(p) && !known.has(`${root}/${p}`),
310	);
311	const ours = (mtimeMs: number | undefined) =>
312		mtimeMs === undefined
313			? spans.length > 0
314			: spans.some(
315					(w) =>
316						mtimeMs >= w.from - SLACK_MS &&
317						mtimeMs <= (w.to ?? Number.POSITIVE_INFINITY) + SLACK_MS,
318				);
319	const changed = await Promise.all(
320		fresh.map(async (p) => {
321			const code = status.get(p) ?? "";
322			// git mv, mv and cp -p keep the old mtime
323			if (/[RC]/.test(code)) {
324				return ours(undefined);
325			}
326			const own = await $.fs.stat(`${root}/${p}`).catch(() => undefined);
327			if (own === undefined || ours(own.mtimeMs)) {
328				return ours(own?.mtimeMs);
329			}
330			if (code !== "??") {
331				return false;
332			}
333			// a new path landing in a folder changes the folder
334			const folder = await $.fs
335				.stat(`${root}/${p}`.replace(/\/[^/]*$/, ""))
336				.catch(() => undefined);
337			return folder !== undefined && ours(folder.mtimeMs);
338		}),
339	);
340	const added: FileTouch[] = fresh
341		.filter((_, i) => changed[i])
342		.map((p) => ({ path: `${root}/${p}`, edits: 0 }));
343	// read again: an Edit may have joined while the stats ran
344	const list = await read($, files);
345	const next = [
346		...added.filter((f) => !list.some((g) => g.path === f.path)),
347		...list,
348	]
349		.slice(0, FILES_MAX)
350		.map(({ status: _, ...f }) => {
351			const s = f.path.startsWith(`${root}/`)
352				? status.get(f.path.slice(root.length + 1))
353				: undefined;
354			return s === undefined ? f : { ...f, status: s };
355		});
356	if (JSON.stringify(next) !== JSON.stringify(list)) {
357		await update($, files, () => next);
358	}
359	// a file that turns dirty later changes later too, so closed spans go
360	const open = spans.filter((w) => w.to === undefined || w.to >= at);
361	spans.splice(0, spans.length, ...open);
362};
363
364const record = async (
365	$: EngineInterface,
366	tool: string,
367	agentId: string | undefined,
368	path: string | undefined,
369	ran: { deny?: string; isError?: true; text?: string },
370) => {
371	const failed = ran.deny !== undefined || ran.isError === true;
372	if (!failed && EDIT_TOOLS.has(tool) && path !== undefined) {
373		const stat = await $.fs
374			.stat(path, { resolve: true })
375			.catch(() => undefined);
376		const real = stat?.realPath ?? path;
377		await update($, files, (list) => {
378			const hit = list.find((f) => f.path === real);
379			return [
380				{ ...hit, path: real, edits: (hit?.edits ?? 0) + 1 },
381				...list.filter((f) => f.path !== real),
382			].slice(0, FILES_MAX);
383		});
384	}
385	if (failed && tool !== "SubagentHandback") {
386		const agent =
387			agentId === undefined
388				? undefined
389				: (await read($, agents)).find((a) => a.id === agentId)?.label;
390		const alert: Alert = {
391			at: await $.clock.now(),
392			tool,
393			reason: cut(
394				firstLine((ran.deny ?? ran.text ?? "").trim() || "error"),
395				120,
396			),
397			...(agent === undefined ? {} : { agent }),
398		};
399		await update($, alerts, (list) => [alert, ...list].slice(0, SHOWN));
400	}
401};
402
403type StopInput = ClassicHookInputs["Stop"];
404
405const syncBackground = async (
406	$: EngineInterface,
407	list: StopInput["background_tasks"] = [],
408	scheduled: StopInput["session_crons"] = [],
409) => {
410	// subagents already have rows of their own, from agent.spawn
411	const nextTasks: BackgroundTask[] = list
412		.filter((b) => b.type !== "subagent" && b.agent_type === undefined)
413		.map((b) => ({
414			id: b.id,
415			type: b.type,
416			status: b.status,
417			label: line(
418				b.command ??
419					(b.server === undefined
420						? (b.name ?? b.description)
421						: `${b.server} ${b.tool ?? ""}`),
422			),
423		}));
424	const nextCrons: SessionCron[] = scheduled.map((c) => ({
425		id: c.id,
426		schedule: c.schedule,
427		recurring: c.recurring,
428		prompt: line(c.prompt),
429	}));
430	if (JSON.stringify(nextTasks) !== JSON.stringify(await read($, tasks))) {
431		await update($, tasks, () => nextTasks);
432	}
433	if (JSON.stringify(nextCrons) !== JSON.stringify(await read($, crons))) {
434		await update($, crons, () => nextCrons);
435	}
436};
437
438// a shell the stop no longer reports running closes its span
439const afterStop = async (
440	$: EngineInterface,
441	e: StopInput | ClassicHookInputs["SubagentStop"],
442	spans: Span[],
443) => {
444	await syncBackground($, e.background_tasks, e.session_crons);
445	const running = new Set(
446		(await read($, tasks))
447			.filter((b) => b.status === "running")
448			.map((b) => b.id),
449	);
450	const t = await $.clock.now();
451	for (const w of spans) {
452		if (w.id !== undefined && w.to === undefined && !running.has(w.id)) {
453			w.to = t;
454		}
455	}
456};
457
458const discover = async ($: EngineInterface, id: string, model: string) => {
459	if ((await read($, agents)).some((a) => a.id === id)) {
460		return;
461	}
462	const info = (await $.agent.list()).find((a) => a.id === id);
463	if (info === undefined) {
464		return;
465	}
466	const row: AgentRow = {
467		id,
468		label: clip(info.name ?? info.type),
469		model: short(model),
470		description: info.description,
471		startedAt: await $.clock.now(),
472		status: "running",
473		listed: true,
474		...(info.name === undefined ? {} : { name: info.name }),
475	};
476	await update($, agents, (list) =>
477		list.some((a) => a.id === id) ? list : [...list, row],
478	);
479	await update($, now, () => row.startedAt);
480};
481
482const patchOpen = async ($: EngineInterface, fn: (r: SkillRun) => SkillRun) => {
483	const last = (await read($, skillRuns)).at(-1);
484	if (
485		last !== undefined &&
486		isOpenRun(last) &&
487		JSON.stringify(fn(last)) !== JSON.stringify(last)
488	) {
489		await update($, skillRuns, (l) => [...l.slice(0, -1), fn(last)]);
490	}
491};
492
493const openRun = async (
494	$: EngineInterface,
495	skills: string[],
496	model: string,
497	effort?: string,
498) => {
499	if (isOpenRun((await read($, skillRuns)).at(-1))) {
500		await patchOpen($, (r) => ({ ...r, skills }));
501		return;
502	}
503	const run: SkillRun = {
504		skills,
505		model,
506		...(effort === undefined ? {} : { effort }),
507		startedAt: await $.clock.now(),
508	};
509	await update($, skillRuns, (l) => [...l, run].slice(-SHOWN));
510};
511
512const isPaneShown = async ($: EngineInterface) =>
513	(await $.ui.panes()).some((p) => p.id === PANE && p.isShown);
514
515const setShown = async ($: EngineInterface, isShown: boolean) => {
516	if ((await read($, paneShown)) !== isShown) {
517		await update($, paneShown, () => isShown);
518	}
519};
520
521const syncChord = async ($: EngineInterface) => {
522	const bound = await boundKeys($);
523	const keyOf = (action: string) =>
524		bound.find(([, a]) => a === action)?.[0] ?? "";
525	const key = keyOf(`command:${PANE}`);
526	if ((await read($, chord)) !== key) {
527		await update($, chord, () => key);
528	}
529	const tabKeys = [keyOf("pane:previous"), keyOf("pane:next")]
530		.filter(Boolean)
531		.join(" ");
532	if ((await read($, tabs)) !== tabKeys) {
533		await update($, tabs, () => tabKeys);
534	}
535	return key;
536};
537
538// Shown: close. Open behind another pane's tab: the engine only retitles an
539// open id, while a newly opened pane becomes the shown tab, so reopen it.
540const toggle = async (
541	$: EngineInterface,
542	root: string | undefined,
543	spans: Span[],
544) => {
545	const pane = (await $.ui.panes()).find((p) => p.id === PANE);
546	if (pane?.isShown) {
547		await $.ui.close({ id: PANE });
548		await setShown($, false);
549		return false;
550	}
551	if (pane !== undefined) {
552		await $.ui.close({ id: PANE });
553	}
554	await $.ui.open({ id: PANE, title: "summary", columns: 60 });
555	await setShown($, true);
556	await syncChord($);
557	await refreshGit($, root, spans);
558	return true;
559};
560
561const hintOf = (key: string) => key || `/${PANE}`;
562
563const usage = (key: string, tabKeys: string) =>
564	[
565		`/${PANE}  open or close the summary pane${key === "" ? "" : ` (${key})`}`,
566		`/${PANE} help  this help`,
567		...(tabKeys === "" ? [] : [`${tabKeys}  previous/next pane tab`]),
568		...(key !== "" && tabKeys !== ""
569			? []
570			: [
571					"",
572					'Shortcuts are not registered by the mod. Ask Claude "set up shortcuts per the summary mod README",',
573					"or add them to ~/.claude/keybindings.json yourself, merging into the existing blocks:",
574					...(key === ""
575						? [
576								`  "Chat":   "ctrl+x s": "command:${PANE}"   open/close the pane`,
577							]
578						: []),
579					...(tabKeys === ""
580						? [
581								'  "Global": "ctrl+<": "pane:previous", "ctrl+>": "pane:next"   pane tabs',
582								'            also "ctrl+shift+," / "ctrl+shift+." if your terminal sends those',
583							]
584						: []),
585					"Any other key works too; the hints follow the key you bind.",
586				]),
587	].join("\n");
588
589const boundKeys = async ($: EngineInterface) => {
590	try {
591		const { bindings = [] } = JSON.parse(
592			await $.fs.read(`${await $.env.get("HOME")}/.claude/keybindings.json`),
593		) as {
594			bindings?: { context?: string; bindings?: Record<string, unknown> }[];
595		};
596		return bindings.flatMap((b) => Object.entries(b.bindings ?? {}));
597	} catch {
598		return [];
599	}
600};
601
602export const register: Register = (on) => {
603	let loaded: string[] = [];
604	let worked = false;
605	let ask = "";
606	let draining = false;
607	let tick = 0;
608	let root: string | undefined;
609	const rain = newRain();
610	// the tokens the last main model call took
611	let stepTokens = 0;
612	// The hint line's isWorking, the engine's own word on a running turn;
613	// undefined until the line draws after a (re)load.
614	let hintWorking: boolean | undefined;
615	const spans: Span[] = [];
616
617	on("session.start", async ($, e, next) => {
618		const key = await syncChord($);
619		const top = await $.process
620			.run(["git", "rev-parse", "--show-toplevel"], { timeoutMs: 5_000 })
621			.catch(() => undefined);
622		root = top?.exitCode === 0 ? top.stdout.trim() : undefined;
623		await refreshGit($, root, spans);
624		void refreshPr($, root);
625		if (e.isInteractive && !(await read($, autoOpened))) {
626			await update($, autoOpened, () => true);
627			await $.ui.open({ id: PANE, title: "summary", columns: 60 });
628		}
629		await setShown($, await isPaneShown($));
630		$.clock.every(100, async () => {
631			// a render hook only reads, so the hint line's word lands here
632			if (
633				hintWorking !== undefined &&
634				hintWorking !== (await read($, working)) > 0
635			) {
636				const t = await $.clock.now();
637				await update($, working, () => (hintWorking ? t : 0));
638			}
639			// a click on another pane's tab hides this one without an event
640			await setShown($, await isPaneShown($));
641			if (!(await read($, paneShown))) {
642				return;
643			}
644			tick++;
645			const list = await read($, agents);
646			const busy = isBusy(
647				list,
648				await read($, skillRuns),
649				await read($, recent),
650			);
651			const since = await read($, working);
652			const running = list.filter((a) => a.status === "running");
653			rain.pace = rainSpeed(
654				[
655					...(since > 0 ? [await read($, mainModel)] : []),
656					...running.map((a) => a.model),
657				],
658				running.length,
659				stepTokens,
660			);
661			// a turn alone redraws once a second for its elapsed time
662			if (busy || tick % (since > 0 ? 10 : 100) === 0) {
663				$.ui.invalidate("ui.render");
664			}
665		});
666		// The rain repaints its Raster in place: a redraw of the whole pane folds
667		// to one per 100 ms, a blit runs at the surface's frame rate.
668		$.clock.every(RAIN_MS, async () => {
669			if (rain.columns === 0 || !(await read($, paneShown))) {
670				return;
671			}
672			const now = await $.clock.now();
673			rain.t += Math.min(now - rain.at, 1000) * rain.pace;
674			rain.at = now;
675			// idle, the rain clock stands still and only the message moves
676			if (rain.pace === 0) {
677				if (!rain.wasIdle) {
678					rain.wasIdle = true;
679					rain.idleSince = now;
680				}
681				const message = rainMessage(rain.columns, rain.idleSince, now);
682				if (message === rain.lastMessage) {
683					return;
684				}
685				rain.lastMessage = message;
686				await $.ui
687					.blit({
688						requestId: PANE,
689						key: RAIN,
690						cells: rainCells(rain.t, rain.columns, RAIN_ROWS, message),
691					})
692					.catch(() => undefined);
693				return;
694			}
695			rain.wasIdle = false;
696			rain.lastMessage = "";
697			await $.ui
698				.blit({
699					requestId: PANE,
700					key: RAIN,
701					cells: rainCells(rain.t, rain.columns, RAIN_ROWS),
702				})
703				.catch(() => undefined);
704		});
705		$.clock.every(1500, async () => {
706			const item = (await read($, recent)).find((w) => w.text === undefined);
707			if (draining || item === undefined) {
708				return;
709			}
710			draining = true;
711			try {
712				const text = await summarize($, item.ask ?? "", item.answer ?? "");
713				await update($, recent, (list) =>
714					list.map(({ ask: _ask, answer: _answer, ...w }) =>
715						w.id === item.id ? { ...w, text } : w,
716					),
717				);
718			} finally {
719				draining = false;
720			}
721		});
722		// commits and pushes from another terminal show up too
723		$.clock.every(15_000, async () => {
724			if (await read($, paneShown)) {
725				await refreshGit($, root, spans);
726			}
727		});
728		$.clock.every(1000, async () => {
729			const rows = await read($, agents);
730			if (!rows.some(isLive)) {
731				return;
732			}
733			const t = await $.clock.now();
734			const live = new Map(
735				(await $.agent.list()).map((a) => [a.id, STATUS[a.status]]),
736			);
737			if (rows.some((a) => sync(a, live.get(a.id), t) !== a)) {
738				await update($, agents, (list) =>
739					list.map((a) => sync(a, live.get(a.id), t)),
740				);
741			}
742			if ((await read($, agents)).some((a) => a.status === "running")) {
743				await update($, now, () => t);
744			}
745		});
746
747		await $.command.register({
748			name: PANE,
749			description: `Open or close the summary pane${key === "" ? "" : ` (${key})`} · help: usage`,
750			argumentHint: "[help]",
751			immediate: true,
752		});
753
754		return next(e);
755	});
756
757	on("agent.spawn", async ($, e, next) => {
758		const ran = await next(e);
759		if (ran.agentId === undefined) {
760			return ran;
761		}
762		const row: AgentRow = {
763			id: ran.agentId,
764			label: clip(e.name ?? e.subagentType),
765			model: short(ran.model),
766			description: e.description,
767			startedAt: await $.clock.now(),
768			status: "running",
769			...(e.name === undefined ? {} : { name: e.name }),
770		};
771		await update($, agents, (list) => [
772			...list.filter((a) => a.id !== row.id),
773			row,
774		]);
775		await update($, now, () => row.startedAt);
776
777		return ran;
778	}).catch((_, e, next) => next(e));
779
780	on("turn.step", async function* ($, e, next) {
781		if (e.agentId !== undefined) {
782			await discover($, e.agentId, e.model);
783			return yield* next(e);
784		}
785		const effort = e.effort === undefined ? undefined : String(e.effort);
786		if (loaded.length > 0) {
787			await openRun($, [...loaded], short(e.model), effort);
788		}
789		const step = yield* next(e);
790		if (step.usage !== null) {
791			stepTokens = totalTokens(step.usage);
792		}
793		const answered = short(step.usage?.model ?? e.model);
794		if (loaded.length > 0) {
795			await patchOpen($, (r) => ({ ...r, model: answered }));
796		}
797		const tag = [answered, effort].filter((v) => v !== undefined).join(" · ");
798		if ((await read($, mainModel)) !== tag) {
799			await update($, mainModel, () => tag);
800		}
801
802		return step;
803	});
804
805	on("tool.call", { tool: "Skill" }, async (_, e, next) => {
806		const ran = await next(e);
807		if (
808			e.agentId === undefined &&
809			ran.deny === undefined &&
810			ran.isError !== true
811		) {
812			loaded = [...new Set([...loaded, e.skill])];
813		}
814
815		return ran;
816	}).catch((_, e, next) => next(e));
817
818	on("tool.call", async ($, e, next) => {
819		const tool = String(e.tool);
820		const id = e.agentId;
821		worked ||= id === undefined;
822		const span: Span = { from: await $.clock.now(), use: e.tool_use_id };
823		if (root !== undefined && !NO_SPAN.has(tool)) {
824			spans.push(span);
825		}
826		// a refused or read-only call changed nothing
827		let idle = false;
828		try {
829			const [, ran] = await Promise.all([
830				id === undefined || tool === "SubagentHandback"
831					? undefined
832					: patch($, id, (a) =>
833							a.status === "running" && a.tool === tool
834								? undefined
835								: { ...a, status: "running", tool },
836						),
837				next(e),
838			]);
839			idle = ran.deny !== undefined || ran.isReadOnly === true;
840			await record($, tool, id, pathOf(e), ran);
841
842			return ran;
843		} finally {
844			span.to = await $.clock.now();
845			if (idle && spans.includes(span)) {
846				spans.splice(spans.indexOf(span), 1);
847			}
848		}
849	}).catch((_, e, next) => next(e));
850
851	// a shell left running shows at once, and what it changes stays ours
852	on("tool.call", { tool: "Bash" }, async ($, e, next) => {
853		const from = await $.clock.now();
854		const ran = await next(e);
855		const shell =
856			ran.isError === true ? undefined : ran.result?.backgroundTaskId;
857		if (shell !== undefined) {
858			if (root !== undefined) {
859				spans.push({ from, id: shell, use: e.tool_use_id });
860			}
861			const row: BackgroundTask = {
862				id: shell,
863				type: "shell",
864				status: "running",
865				label: line(e.command),
866			};
867			await update($, tasks, (list) =>
868				list.some((b) => b.id === shell) ? list : [...list, row],
869			);
870		}
871		if (ran.deny === undefined && PR_CHANGE.test(e.command)) {
872			void refreshPr($, root, true);
873		}
874
875		return ran;
876	}).catch((_, e, next) => next(e));
877
878	on("tool.call", { tool: "TaskStop" }, async ($, e, next) => {
879		const ran = await next(e);
880		const task = e.task_id ?? e.shell_id;
881		if (ran.deny !== undefined || ran.isError === true || task === undefined) {
882			return ran;
883		}
884		const t = await $.clock.now();
885		for (const w of spans) {
886			if (w.id === task && w.to === undefined) {
887				w.to = t;
888			}
889		}
890		if ((await read($, tasks)).some((b) => b.id === task)) {
891			await update($, tasks, (list) => list.filter((b) => b.id !== task));
892		}
893		const hit = (a: AgentRow) =>
894			a.status !== "killed" && (a.id === task || a.name === task);
895		if ((await read($, agents)).some(hit)) {
896			await update($, agents, (list) =>
897				list.map((a) =>
898					hit(a) ? { ...a, status: "killed", endedAt: end(a, t) } : a,
899				),
900			);
901		}
902
903		return ran;
904	}).catch((_, e, next) => next(e));
905
906	on("turn.complete", async ($, e, next) => {
907		const id = e.agentId;
908		if (id !== undefined && !(await $.agent.list()).some((a) => a.id === id)) {
909			const endedAt = await $.clock.now();
910			await patch($, id, (a) =>
911				isLive(a) && !a.listed
912					? { ...a, status: TURN_END[e.reason], endedAt }
913					: undefined,
914			);
915		}
916		if (id !== undefined) {
917			await refreshGit($, root, spans);
918		}
919		if (id === undefined) {
920			const mark: TurnMark = { ms: e.durationMs, ok: e.reason === "answer" };
921			await update($, turns, (list) => [...list, mark].slice(-TURNS_MAX));
922			if (loaded.length > 0) {
923				const endedAt = await $.clock.now();
924				await patchOpen($, (r) => ({
925					...r,
926					endedAt,
927					result: RUN_END[e.reason],
928				}));
929				loaded = [];
930			}
931			if (worked && e.reason === "answer" && e.answer.trim() !== "") {
932				const item: WorkItem = {
933					id: e.turnId,
934					at: await $.clock.now(),
935					durationMs: e.durationMs,
936					...(e.usage === undefined ? {} : { tokens: newTokens(e.usage) }),
937					ask,
938					answer: e.answer.slice(0, 4000),
939				};
940				await update($, recent, (list) =>
941					[item, ...list.filter((w) => w.id !== item.id)].slice(
942						0,
943						RECENT_SHOWN,
944					),
945				);
946			}
947			if (worked) {
948				await refreshGit($, root, spans);
949			}
950			worked = false;
951		}
952		void refreshPr($, root);
953
954		return next(e);
955	});
956
957	// A stop carries the session's background work and crons; a finished task
958	// or a fired cron wakes the session, so the next stop brings the change.
959	on("classic.Stop", async ($, e, next) => {
960		await afterStop($, e, spans);
961		return next(e);
962	}).catch((_, e, next) => next(e));
963
964	// the time a call waited on a permission prompt is not its run
965	on("classic.PostToolUse", async ($, e, next) => {
966		if (e.duration_ms !== undefined) {
967			const start = (await $.clock.now()) - e.duration_ms;
968			for (const w of spans) {
969				if (w.use === e.tool_use_id && w.from < start) {
970					w.from = start;
971				}
972			}
973		}
974		return next(e);
975	}).catch((_, e, next) => next(e));
976
977	on("classic.SubagentStop", async ($, e, next) => {
978		await afterStop($, e, spans);
979		return next(e);
980	}).catch((_, e, next) => next(e));
981
982	on("prompt.submit", async ($, e, next) => {
983		if (e.turnId === undefined) {
984			ask = e.text.slice(0, 1000);
985			const name = /^\/([\w:.-]+)(?=\s|$)/.exec(e.text)?.[1];
986			const isCommand =
987				name !== undefined &&
988				(await $.command.list()).some((c) => c.name === name);
989			loaded = isCommand ? [name] : [];
990		}
991		if (e.origin.kind === "composer" || e.origin.kind === "bridge") {
992			await update($, agents, (list) => list.filter(isLive));
993			if ((await read($, alerts)).length > 0) {
994				await update($, alerts, () => []);
995			}
996		}
997
998		return next(e);
999	}).catch((_, e, next) => next(e));
1000
1001	on("command.run", { command: PANE }, async ($, e) => {
1002		if (e.args.trim() === "help") {
1003			return { text: usage(await syncChord($), await read($, tabs)) };
1004		}
1005		// no text, so a "command:summary" shortcut leaves nothing in the transcript
1006		await toggle($, root, spans);
1007		return {};
1008	}).catch((_, e, next) => next(e));
1009
1010	on("ui.close", { id: PANE }, async ($, e, next) => {
1011		const closed = await next(e);
1012		await setShown($, false);
1013
1014		return closed;
1015	}).catch((_, e, next) => next(e));
1016
1017	// The hint under the prompt carries the toggle hint as dim tail text, so the
1018	// band above the prompt stays free.
1019	on("ui.render", { component: "PromptHint" }, async ($, e, next) => {
1020		hintWorking = e.props.isWorking;
1021		if (await read($, paneShown)) {
1022			return next(e);
1023		}
1024		const key = await read($, chord);
1025		const tail = [e.props.tail, key === "" ? `/${PANE}` : `${key} ${PANE}`]
1026			.filter(Boolean)
1027			.join(" · ");
1028		return next({ ...e, props: { ...e.props, tail } });
1029	});
1030
1031	on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) =>
1032		paneView({
1033			e,
1034			els: $.ui.resolve(e),
1035			t: await $.clock.now(),
1036			root,
1037			rain,
1038			hint: hintOf(await read($, chord)),
1039			tabKeys: await read($, tabs),
1040			onToggle: () => toggle($, root, spans),
1041			list: await read($, agents),
1042			runs: await read($, skillRuns),
1043			work: await read($, recent),
1044			touched: await read($, files),
1045			uncommitted: await read($, dirty),
1046			git: await read($, repo),
1047			pr: await read($, pullRequest),
1048			warnings: await read($, alerts),
1049			tag: await read($, mainModel),
1050			since: await read($, working),
1051			bg: await read($, tasks),
1052			scheduled: await read($, crons),
1053			marks: await read($, turns),
1054		}),
1055	);
1056};
1057
hooks/format.ts 67 lines
1import type { ModelUsage } from "claude-code";
2
3export const totalTokens = (u: ModelUsage) =>
4	u.input_tokens +
5	u.output_tokens +
6	u.cache_read_input_tokens +
7	u.cache_creation_input_tokens;
8
9// what a turn took in and wrote, leaving out what the prompt cache served
10export const newTokens = (u: ModelUsage) =>
11	u.input_tokens + u.output_tokens + u.cache_creation_input_tokens;
12
13export const LABEL_MAX = 20;
14
15export const elapsed = (ms: number) => {
16	const s = Math.max(0, Math.round(ms / 1000));
17	return s < 60
18		? `${s}s`
19		: `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
20};
21
22export const clip = (s: string) =>
23	s.length > LABEL_MAX ? `${s.slice(0, LABEL_MAX - 1)}…` : s;
24
25export const cut = (s: string, n: number) =>
26	s.length > n ? `${s.slice(0, n - 1)}…` : s;
27
28export const firstLine = (answer: string) =>
29	cut(
30		answer
31			.split("\n")
32			.map((l) =>
33				l
34					.replace(/^[#>*\-\s]+/, "")
35					.replace(/[*`]/g, "")
36					.trim(),
37			)
38			.find((l) => l !== "") ?? "done",
39		60,
40	);
41
42export const ago = (ms: number) => {
43	const s = Math.max(0, Math.round(ms / 1000));
44	return s < 60
45		? `${s}s`
46		: s < 3600
47			? `${Math.floor(s / 60)}m`
48			: `${Math.floor(s / 3600)}h`;
49};
50
51export const kilo = (n: number) =>
52	n < 1000 ? `${n}` : `${Math.round(n / 1000)}k`;
53
54export const tail = (s: string, n: number) =>
55	s.length > n ? `…${s.slice(s.length - n + 1)}` : s;
56
57export const pathOf = (e: object) => {
58	const { file_path, notebook_path } = e as {
59		file_path?: unknown;
60		notebook_path?: unknown;
61	};
62	const path = file_path ?? notebook_path;
63	return typeof path === "string" ? path : undefined;
64};
65
66export const short = (model: string) => model.replace(/^.*claude-/, "");
67
hooks/pane.tsx 562 lines
1import type { Elements, RenderInput } from "claude-code";
2import type {
3	AgentRow,
4	Alert,
5	BackgroundTask,
6	FileTouch,
7	PullRequest,
8	RepoState,
9	SessionCron,
10	SkillRun,
11	TurnMark,
12	WorkItem,
13} from "../types";
14import { hhmm, nextFire } from "./cron";
15import { ago, elapsed, kilo, tail } from "./format";
16import { isMergeable } from "./pr";
17import type { Rain } from "./rain";
18import { RAIN, RAIN_ROWS, rainCells, rainMessage } from "./rain";
19import { end, isBusy, isLive, isOpenRun } from "./status";
20import {
21	C,
22	CHECKS,
23	COLOR,
24	GIT_COLOR,
25	GLOW,
26	ICON,
27	modelColor,
28	ORDER,
29	PANE,
30	REVIEW,
31	RUN,
32	SHOWN,
33	SPARK,
34	SPINNER,
35} from "./theme";
36
37// Everything the pane draws, read by register (only it may touch $).
38export type PaneValues = {
39	e: RenderInput<"Pane">;
40	els: Elements[RenderInput<"Pane">["surface"]];
41	t: number;
42	root: string | undefined;
43	rain: Rain;
44	hint: string;
45	tabKeys: string;
46	onToggle: () => unknown;
47	list: AgentRow[];
48	runs: SkillRun[];
49	work: WorkItem[];
50	touched: FileTouch[];
51	uncommitted: number;
52	git: RepoState;
53	pr: PullRequest | null;
54	warnings: Alert[];
55	tag: string;
56	since: number;
57	bg: BackgroundTask[];
58	scheduled: SessionCron[];
59	marks: TurnMark[];
60};
61
62export const paneView = ({
63	e,
64	els,
65	t,
66	root,
67	rain,
68	hint,
69	tabKeys,
70	onToggle,
71	list,
72	runs,
73	work,
74	touched,
75	uncommitted,
76	git,
77	pr,
78	warnings,
79	tag,
80	since,
81	bg,
82	scheduled,
83	marks,
84}: PaneValues) => {
85	const { Box, Button, Link, Text } = els;
86	const frame = Math.floor(t / 100);
87	const spin = SPINNER[frame % SPINNER.length];
88	const busy = isBusy(list, runs, work);
89	const glow = busy ? (GLOW[frame % GLOW.length] ?? C.mauve) : C.mauve;
90	const width = Math.max(30, e.props.bodyColumns);
91	const rule = width - 2;
92	const at = busy ? (frame % (rule + 6)) - 3 : -3;
93	const lit = [at, at + 3].map((n) => Math.min(rule, Math.max(0, n))) as [
94		number,
95		number,
96	];
97	const spark = marks.slice(-(width - 4));
98	const longest = Math.max(1, ...spark.map((m) => m.ms));
99	// live agents first, then background work, crons and the latest finished,
100	// drawn in that order
101	const finished = list.filter((a) => !isLive(a)).reverse();
102	const keep = new Set<AgentRow | BackgroundTask | SessionCron>(
103		[...list.filter(isLive), ...bg, ...scheduled, ...finished].slice(0, SHOWN),
104	);
105	const liveShown = list.filter((a) => isLive(a) && keep.has(a));
106	const doneShown = finished.filter((a) => keep.has(a));
107	const shown = [...liveShown, ...doneShown];
108	const bgShown = bg.filter((b) => keep.has(b));
109	const cronsShown = scheduled.filter((c) => keep.has(c));
110	const more = list.length + bg.length + scheduled.length - keep.size;
111	const labelWidth = Math.max(
112		0,
113		...shown.map((a) => a.label.length),
114		...bgShown.map((b) => b.type.length),
115	);
116	const modelWidth = Math.max(0, ...shown.map((a) => a.model.length));
117	const pathWidth = width - 4 - 3 - 4;
118	const shortPath = (p: string) =>
119		root !== undefined && p.startsWith(`${root}/`)
120			? p.slice(root.length + 1)
121			: p;
122	const counts = ORDER.map(
123		(s) => [s, list.filter((a) => a.status === s).length] as const,
124	);
125	if ("Raster" in els) {
126		rain.columns = width;
127	}
128	// docked, the pane fills its height so the rain sits on the bottom edge;
129	// inline, the frame fits the tree and would grow to bodyRows instead
130	const floor =
131		e.props.placement === "dock" ? e.props.scroll.bodyRows : undefined;
132	const skill = runs.at(-1);
133	const agentsRunning = list.filter((a) => a.status === "running").length;
134	// what keeps Claude busy, one mark each, in the colors of their boxes
135	const status = [
136		...(since > 0
137			? [{ color: C.peach, text: `⏳ working ${elapsed(t - since)}` }]
138			: []),
139		...(isOpenRun(skill) && skill !== undefined
140			? [
141					{
142						color: C.blue,
143						text: `🔧 ${skill.skills.join(", ")} ${elapsed(t - skill.startedAt)}`,
144					},
145				]
146			: []),
147		...(agentsRunning > 0
148			? [
149					{
150						color: C.mauve,
151						text: `🤖 ${agentsRunning} agent${agentsRunning === 1 ? "" : "s"}`,
152					},
153				]
154			: []),
155		...(work.some((w) => w.text === undefined)
156			? [{ color: C.green, text: "📝 summarizing" }]
157			: []),
158	];
159	const agentRow = (a: AgentRow) => (
160		<Text wrap="truncate-end">
161			<Text color={COLOR[a.status]}>
162				{a.status === "running" ? spin : ICON[a.status]}
163			</Text>{" "}
164			<Text color={C.text} dimColor={a.status !== "running"}>
165				{a.label.padEnd(labelWidth)}
166			</Text>{" "}
167			<Text color={modelColor(a.model)} dimColor={a.status !== "running"}>
168				{a.model.padEnd(modelWidth)}
169			</Text>{" "}
170			<Text color={C.overlay} dimColor={a.status !== "running"}>
171				{elapsed(end(a, t) - a.startedAt).padStart(6)}
172			</Text>{" "}
173			<Text color={C.subtext} dimColor>
174				{a.description}
175				{a.status === "running" && a.tool !== undefined ? ` · ${a.tool}` : ""}
176			</Text>
177		</Text>
178	);
179	// a PR read for the branch before a checkout is not this one's
180	const pull = pr !== null && pr.branch === git.branch ? pr : undefined;
181	const prMarks =
182		pull === undefined
183			? []
184			: [
185					...(pull.isDraft ? [{ color: C.overlay, text: "✎ draft" }] : []),
186					REVIEW[pull.review],
187					...(pull.ci === undefined ? [] : [CHECKS[pull.ci]]),
188					...(pull.unresolved > 0
189						? [{ color: C.peach, text: `💬 ${pull.unresolved} unresolved` }]
190						: []),
191				];
192	const keycap = (k: string) => (
193		<Text backgroundColor={C.surface0} color={C.lavender}>{` ${k} `}</Text>
194	);
195
196	return (
197		<Box
198			flexDirection="column"
199			width={width}
200			{...(floor === undefined ? {} : { minHeight: floor })}
201		>
202			<Box paddingX={1} justifyContent="space-between">
203				<Box gap={2}>
204					<Text bold color={glow}>
205						SUMMARY
206					</Text>
207					{status.length > 0 && (
208						<Text wrap="truncate-end">
209							{status.map((m, i) => (
210								<Text color={m.color}>{`${i > 0 ? "  " : ""}${m.text}`}</Text>
211							))}
212						</Text>
213					)}
214				</Box>
215				<Text color={modelColor(tag)}>{tag}</Text>
216			</Box>
217			<Box paddingX={1}>
218				<Text>
219					<Text color={C.surface0}>{"━".repeat(lit[0])}</Text>
220					<Text color={C.lavender}>{"━".repeat(lit[1] - lit[0])}</Text>
221					<Text color={C.surface0}>{"━".repeat(rule - lit[1])}</Text>
222				</Text>
223			</Box>
224			{warnings.length > 0 && (
225				<Box
226					flexDirection="column"
227					borderStyle="round"
228					borderColor={C.red}
229					paddingX={1}
230				>
231					<Text bold color={C.red}>
232						alerts
233					</Text>
234					{warnings.map((a) => (
235						<Text wrap="truncate-end">
236							<Text color={C.red}>✗</Text>{" "}
237							<Text color={C.overlay}>{`${ago(t - a.at)} ago`.padEnd(7)}</Text>{" "}
238							<Text color={C.peach}>{a.tool}</Text>
239							{a.agent !== undefined && (
240								<Text color={C.overlay}>{` @${a.agent}`}</Text>
241							)}
242							<Text color={C.subtext}>{`  ${a.reason}`}</Text>
243						</Text>
244					))}
245				</Box>
246			)}
247			<Box
248				flexDirection="column"
249				borderStyle="round"
250				borderColor={C.green}
251				paddingX={1}
252			>
253				<Text bold color={C.green}>
254					recent
255				</Text>
256				{work.length === 0 && (
257					<Text color={C.overlay}>no finished work yet</Text>
258				)}
259				{work.map((w, i) => (
260					<Box flexDirection="column">
261						<Box gap={1}>
262							{w.text === undefined ? (
263								<Text color={C.peach}>{spin}</Text>
264							) : (
265								<Text color={C.green}>✓</Text>
266							)}
267							<Text
268								bold={i === 0}
269								dimColor={i > 0}
270								color={w.text === undefined ? C.subtext : C.text}
271							>
272								{w.text ?? "summarizing…"}
273							</Text>
274						</Box>
275						<Box paddingLeft={2}>
276							<Text color={C.overlay} dimColor>
277								{[
278									`${ago(t - w.at)} ago`,
279									elapsed(w.durationMs),
280									...(w.tokens === undefined ? [] : [kilo(w.tokens)]),
281								].join(" · ")}
282							</Text>
283						</Box>
284					</Box>
285				))}
286			</Box>
287			<Box
288				flexDirection="column"
289				borderStyle="round"
290				borderColor={C.surface1}
291				paddingX={1}
292			>
293				<Text>
294					<Text bold color={C.mauve}>
295						{"agents & jobs"}
296					</Text>
297					{counts
298						.filter(([, n]) => n > 0)
299						.map(([s, n]) => (
300							<Text color={COLOR[s]}>{`  ${ICON[s]} ${n} ${s}`}</Text>
301						))}
302					{bg.length > 0 && <Text color={C.sky}>{`  ${bg.length} bg`}</Text>}
303					{scheduled.length > 0 && (
304						<Text color={C.lavender}>{`  ${scheduled.length} scheduled`}</Text>
305					)}
306				</Text>
307				{list.length + bg.length + scheduled.length === 0 && (
308					<Text color={C.overlay}>nothing running or scheduled</Text>
309				)}
310				{liveShown.map(agentRow)}
311				{bgShown.map((b) => (
312					<Text wrap="truncate-end">
313						<Text color={b.status === "running" ? C.yellow : C.overlay}>
314							{b.status === "running" ? "●" : "○"}
315						</Text>{" "}
316						<Text color={C.sky}>{b.type.padEnd(labelWidth)}</Text>{" "}
317						<Text color={C.subtext}>{b.label}</Text>
318					</Text>
319				))}
320				{cronsShown.map((c) => {
321					const at = nextFire(c.schedule, t);
322					return (
323						<Text wrap="truncate-end">
324							<Text color={C.lavender}>{c.recurring ? "↻" : "◷"}</Text>{" "}
325							<Text color={C.text}>
326								{at === undefined
327									? c.schedule
328									: `${hhmm(at, t)} in ${ago(at - t)}`}
329							</Text>{" "}
330							<Text color={C.subtext}>{c.prompt}</Text>
331						</Text>
332					);
333				})}
334				{doneShown.map(agentRow)}
335				{more > 0 && <Text color={C.overlay}>{`+${more} more`}</Text>}
336			</Box>
337			<Box
338				flexDirection="column"
339				borderStyle="round"
340				borderColor={C.surface1}
341				paddingX={1}
342			>
343				<Text>
344					<Text bold color={C.yellow}>
345						files
346					</Text>
347					<Text color={C.overlay}>
348						{`  ${touched.length} edited · ${uncommitted} uncommitted`}
349					</Text>
350				</Text>
351				{touched.length === 0 && (
352					<Text color={C.overlay}>no file edited yet</Text>
353				)}
354				{touched.slice(0, SHOWN).map((f) => (
355					<Text>
356						<Text
357							color={
358								f.status === undefined
359									? C.overlay
360									: (GIT_COLOR[f.status] ?? C.peach)
361							}
362						>
363							{(f.status ?? "·").padEnd(2)}
364						</Text>{" "}
365						<Text color={C.overlay}>
366							{(f.edits > 0 ? `${f.edits}×` : "·").padStart(3)}
367						</Text>{" "}
368						<Text color={C.text}>{tail(shortPath(f.path), pathWidth)}</Text>
369					</Text>
370				))}
371				{touched.length > SHOWN && (
372					<Text color={C.overlay}>{`+${touched.length - SHOWN} more`}</Text>
373				)}
374			</Box>
375			<Box
376				flexDirection="column"
377				borderStyle="round"
378				borderColor={C.surface1}
379				paddingX={1}
380			>
381				<Text>
382					<Text bold color={C.peach}>
383						git
384					</Text>
385					<Text color={C.overlay}>
386						{root === undefined
387							? "  not a repository"
388							: `  ${git.branch ?? "?"}${
389									git.upstream === undefined
390										? ` (no upstream) · ${uncommitted} uncommitted`
391										: ` → ${git.upstream} · ${uncommitted} uncommitted · ↑${git.ahead} ↓${git.behind}`
392								}`}
393					</Text>
394				</Text>
395				{pull !== undefined && (
396					<Text wrap="truncate-end">
397						<Text color={C.lavender}>{`PR #${pull.number}`}</Text>
398						{prMarks.map((m, i) => (
399							<Text color={m.color}>{`${i === 0 ? " " : " · "}${m.text}`}</Text>
400						))}
401					</Text>
402				)}
403				{pull !== undefined && isMergeable(pull) && (
404					<Box flexDirection="column" paddingLeft={2}>
405						<Text color={C.green} wrap="truncate-end">
406							⇢ ready: merge it in the web UI
407						</Text>
408						<Text color={C.blue}>
409							<Link href={pull.url} />
410						</Text>
411					</Box>
412				)}
413				{git.commits.length === 0 && (
414					<Text color={C.overlay}>no commit yet</Text>
415				)}
416				{git.commits.map((c, i) => (
417					<Text wrap="truncate-end">
418						{git.upstream === undefined ? (
419							<Text color={C.overlay}>·</Text>
420						) : i < git.ahead ? (
421							<Text color={C.yellow}>↑</Text>
422						) : (
423							<Text color={C.green}>✓</Text>
424						)}{" "}
425						<Text color={C.overlay}>{c.hash}</Text>{" "}
426						<Text color={C.overlay} dimColor>
427							{ago(t - c.at).padStart(3)}
428						</Text>{" "}
429						<Text color={i < git.ahead ? C.text : C.subtext}>{c.subject}</Text>
430					</Text>
431				))}
432			</Box>
433			<Box
434				flexDirection="column"
435				borderStyle="round"
436				borderColor={C.surface1}
437				paddingX={1}
438			>
439				<Text bold color={C.blue}>
440					skills
441				</Text>
442				{runs.length === 0 ? (
443					<Text color={C.overlay}>no skill yet</Text>
444				) : (
445					[...runs].reverse().map((r) => (
446						<Text wrap="truncate-end">
447							{r.result === undefined ? (
448								<Text color={C.peach}>{spin}</Text>
449							) : (
450								<Text color={RUN[r.result].color}>{RUN[r.result].icon}</Text>
451							)}{" "}
452							<Text
453								bold={r.result === undefined}
454								color={r.result === undefined ? C.text : C.subtext}
455							>
456								{r.skills.join(", ")}
457							</Text>{" "}
458							<Text color={modelColor(r.model)}>
459								{[r.model, r.effort].filter((v) => v !== undefined).join(" · ")}
460							</Text>{" "}
461							<Text color={C.overlay}>
462								{elapsed((r.endedAt ?? t) - r.startedAt)}
463							</Text>
464						</Text>
465					))
466				)}
467			</Box>
468			<Box
469				flexDirection="column"
470				borderStyle="round"
471				borderColor={C.surface1}
472				paddingX={1}
473			>
474				<Text>
475					<Text bold color={C.sky}>
476						turn time
477					</Text>
478					{marks.length > 0 && (
479						<Text color={C.overlay}>
480							{`  ${marks.length} turn${marks.length === 1 ? "" : "s"} · avg ${elapsed(
481								marks.reduce((n, m) => n + m.ms, 0) / marks.length,
482							)} · max ${elapsed(Math.max(...marks.map((m) => m.ms)))}`}
483						</Text>
484					)}
485				</Text>
486				{spark.length === 0 ? (
487					<Text color={C.overlay}>no turn yet</Text>
488				) : (
489					<Text>
490						{spark.map((m) => (
491							<Text color={m.ok ? C.green : C.red}>
492								{SPARK[Math.max(0, Math.ceil((m.ms / longest) * 8) - 1)]}
493							</Text>
494						))}
495					</Text>
496				)}
497			</Box>
498			<Box paddingX={1} columnGap={2} flexWrap="wrap">
499				<Button plain key="toggle" onPress={onToggle}>
500					{keycap(hint)}
501					<Text color={C.subtext}> close</Text>
502				</Button>
503				<Text>
504					{keycap("ctrl+x tab")}
505					<Text color={C.subtext}> focus</Text>
506				</Text>
507				{tabKeys !== "" && (
508					<Text>
509						{keycap(tabKeys)}
510						<Text color={C.subtext}> tabs</Text>
511					</Text>
512				)}
513				{keycap(`/${PANE} help`)}
514			</Box>
515			{/* hint falls back to the slash command while no key is bound */}
516			{(hint === `/${PANE}` || tabKeys === "") && (
517				<Box flexDirection="column" paddingX={1}>
518					<Text color={C.yellow}>
519						{
520							'⚠ shortcuts not set · you can ask Claude "set up shortcuts per the summary mod README"'
521						}
522					</Text>
523					<Text color={C.subtext}>
524						or add to ~/.claude/keybindings.json (merge into existing blocks):
525					</Text>
526					{hint === `/${PANE}` && (
527						<Text color={C.subtext}>
528							{`  "Chat": "ctrl+x s": "command:${PANE}"`}
529						</Text>
530					)}
531					{tabKeys === "" && (
532						<Text color={C.subtext}>
533							{'  "Global": "ctrl+<": "pane:previous", "ctrl+>": "pane:next"'}
534						</Text>
535					)}
536					{tabKeys === "" && (
537						<Text color={C.subtext}>
538							{
539								'  also "ctrl+shift+," / "ctrl+shift+." if your terminal sends those'
540							}
541						</Text>
542					)}
543				</Box>
544			)}
545			<Box flexGrow={1} />
546			{"Raster" in els && (
547				<els.Raster
548					key={RAIN}
549					columns={width}
550					rows={RAIN_ROWS}
551					cells={rainCells(
552						rain.t,
553						width,
554						RAIN_ROWS,
555						rain.pace === 0 ? rainMessage(width, rain.idleSince, t) : undefined,
556					)}
557				/>
558			)}
559		</Box>
560	);
561};
562
hooks/pr.ts 159 lines
1import type { EngineInterface } from "claude-code";
2import type { PullRequest } from "../types";
3
4const QUERY = `query($owner: String!, $name: String!, $branch: String!) {
5  viewer { login }
6  repository(owner: $owner, name: $name) {
7    pullRequests(headRefName: $branch, states: [OPEN], first: 5, orderBy: {field: CREATED_AT, direction: DESC}) {
8      nodes {
9        number url isDraft reviewDecision isCrossRepository
10        headRepositoryOwner { login }
11        latestReviews(first: 20) { nodes { state } }
12        commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
13        reviewThreads(first: 100) { nodes { isResolved } }
14      }
15    }
16  }
17}`;
18
19type Node = {
20	number: number;
21	url: string;
22	isDraft: boolean;
23	reviewDecision: string | null;
24	isCrossRepository: boolean;
25	headRepositoryOwner: { login: string } | null;
26	latestReviews: { nodes: { state: string }[] };
27	commits: {
28		nodes: { commit: { statusCheckRollup: { state: string } | null } }[];
29	};
30	reviewThreads: { nodes: { isResolved: boolean }[] };
31};
32
33type Reply = {
34	data?: {
35		viewer?: { login: string };
36		repository?: { pullRequests: { nodes: Node[] } } | null;
37	};
38};
39
40const CI: Record<string, PullRequest["ci"]> = {
41	SUCCESS: "success",
42	FAILURE: "failure",
43	ERROR: "failure",
44	PENDING: "pending",
45	EXPECTED: "pending",
46};
47
48// gh picks the repository the same way: upstream, github, then origin
49const REMOTES = ["upstream", "github", "origin"];
50
51export const remoteRepo = (config: string) => {
52	const urls = new Map(
53		config
54			.split("\n")
55			.map((l) => /^remote\.(.+)\.url (.+)$/.exec(l))
56			.filter((m) => m !== null)
57			.map((m) => [m[1], m[2]] as const),
58	);
59	const url = [...REMOTES.map((r) => urls.get(r)), ...urls.values()].find(
60		(u) => u !== undefined,
61	);
62	const m =
63		/^(?:[\w+.-]+:\/\/)?(?:[^@/]+@)?([^/:]+)(?::\d+)?[:/]([^/]+)\/([^/]+?)(?:\.git)?\/?$/.exec(
64			url ?? "",
65		);
66	if (m === null) {
67		return undefined;
68	}
69	const [, host = "", owner = "", name = ""] = m;
70	return { host, owner, name };
71};
72
73// a fork's PR with the same branch name is someone else's, unless it is ours
74export const toPullRequest = (
75	branch: string,
76	stdout: string,
77): PullRequest | null => {
78	const { data } = JSON.parse(stdout) as Reply;
79	const me = data?.viewer?.login;
80	const pr = data?.repository?.pullRequests.nodes.find(
81		(n) => !n.isCrossRepository || n.headRepositoryOwner?.login === me,
82	);
83	if (pr === undefined) {
84		return null;
85	}
86	const reviews = pr.latestReviews.nodes.map((r) => r.state);
87	const decision =
88		pr.reviewDecision ??
89		(reviews.includes("CHANGES_REQUESTED")
90			? "CHANGES_REQUESTED"
91			: reviews.includes("APPROVED")
92				? "APPROVED"
93				: undefined);
94	const ci = CI[pr.commits.nodes[0]?.commit.statusCheckRollup?.state ?? ""];
95	return {
96		branch,
97		number: pr.number,
98		url: pr.url,
99		isDraft: pr.isDraft,
100		review:
101			decision === "APPROVED"
102				? "approved"
103				: decision === "CHANGES_REQUESTED"
104					? "changes"
105					: "pending",
106		...(ci === undefined ? {} : { ci }),
107		unresolved: pr.reviewThreads.nodes.filter((t) => !t.isResolved).length,
108	};
109};
110
111export const isMergeable = (pr: PullRequest) =>
112	pr.review === "approved" &&
113	!pr.isDraft &&
114	(pr.ci === undefined || pr.ci === "success");
115
116export async function readPullRequest(
117	$: EngineInterface,
118	root: string,
119	branch: string,
120) {
121	const config = await $.process
122		.run(["git", "-C", root, "config", "--get-regexp", "^remote\\..*\\.url$"], {
123			timeoutMs: 5_000,
124		})
125		.catch(() => undefined);
126	const repo = remoteRepo(config?.exitCode === 0 ? config.stdout : "");
127	if (repo === undefined) {
128		return null;
129	}
130	const run = await $.process
131		.run(
132			[
133				"gh",
134				"api",
135				"graphql",
136				"--hostname",
137				repo.host,
138				"-f",
139				`owner=${repo.owner}`,
140				"-f",
141				`name=${repo.name}`,
142				"-f",
143				`branch=${branch}`,
144				"-f",
145				`query=${QUERY}`,
146			],
147			{ cwd: root, timeoutMs: 15_000 },
148		)
149		.catch(() => undefined);
150	if (run?.exitCode !== 0) {
151		return null;
152	}
153	try {
154		return toPullRequest(branch, run.stdout);
155	} catch {
156		return null;
157	}
158}
159
hooks/rain.ts 152 lines
1import { C, rgb } from "./theme";
2
3export const RAIN = "rain";
4
5export const RAIN_ROWS = 6;
6
7export const RAIN_MS = 33; // ~30 fps
8
9export const RAIN_MAX_SPEED = 3;
10
11export const RAIN_GLYPHS = [
12	..."アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン0123456789",
13].map((g) => g.codePointAt(0) ?? 0x20);
14
15export const RAIN_FADE = [
16	C.text,
17	C.green,
18	C.green,
19	C.teal,
20	C.teal,
21	C.surface2,
22	C.surface1,
23].map(rgb);
24
25export const TERMINAL_DEFAULT = 0x01000000;
26
27// Idle, the rain stands still in faded colors and a message types itself out
28// on its middle row: the first that fits, ASCII (a Raster takes width-1 code
29// points only), then a blinking cursor.
30export const RAIN_IDLE = [
31	"wake up, neo... the matrix resumes when claude works",
32	"the matrix resumes when claude works",
33	"awaiting signal",
34];
35
36export const RAIN_TYPE_MS = 40;
37
38export const RAIN_BLINK_MS = 530;
39
40// the message as typed by now, padded to its full length so it stays put
41export const rainMessage = (columns: number, since: number, now: number) => {
42	const full = RAIN_IDLE.find((m) => m.length + 3 <= columns) ?? "";
43	const typed = Math.min(full.length, Math.floor((now - since) / RAIN_TYPE_MS));
44	const cursor =
45		typed < full.length || Math.floor(now / RAIN_BLINK_MS) % 2 === 0
46			? "█"
47			: " ";
48	return `${full.slice(0, typed)}${cursor}`.padEnd(full.length + 1);
49};
50
51export const hash = (n: number) => {
52	const h = Math.imul(n ^ (n >>> 16), 0x45d9f3b);
53	const k = Math.imul(h ^ (h >>> 16), 0x45d9f3b);
54	return (k ^ (k >>> 16)) >>> 0;
55};
56
57export const modelWeight = (model: string) =>
58	model.startsWith("opus") ? 1.5 : model.startsWith("haiku") ? 0.6 : 1;
59
60// How fast the rain falls, a multiple of its base speed: the biggest model at
61// work, +25% an agent running (up to +150%) and the last model call's tokens
62// (x1 at 10k, x1.5 at 100k, x2 from 1M), capped; 0 with no model at work.
63export const rainSpeed = (models: string[], agents: number, tokens: number) =>
64	models.length === 0
65		? 0
66		: Math.min(
67				RAIN_MAX_SPEED,
68				Math.max(...models.map(modelWeight)) *
69					(1 + Math.min(1.5, agents * 0.25)) *
70					(1 + Math.min(1, Math.log10(Math.max(1, tokens / 10_000)) / 2)),
71			);
72
73// Raster cells for the clock at t, faded and carrying the idle message when one
74// is given. Each column's drop gets its speed (rows a second), trail and gap
75// from the column index, so the clock alone draws it.
76export const rainCells = (
77	t: number,
78	columns: number,
79	rows: number,
80	message?: string,
81) => {
82	const words = new Uint32Array(columns * rows * 3).fill(TERMINAL_DEFAULT);
83	for (let c = 0; c < columns; c++) {
84		const trail = 4 + (hash(c * 3 + 1) % (RAIN_FADE.length - 3));
85		const period = rows + trail + (hash(c * 3 + 2) % 12);
86		const speed = 8 + (hash(c * 3) % 9);
87		const head = (Math.floor((t / 1000) * speed) + hash(c * 7 + 5)) % period;
88		for (let r = 0; r < rows; r++) {
89			const d = head - r;
90			const i = (r * columns + c) * 3;
91			if (d < 0 || d >= trail) {
92				words[i] = 0x20;
93				continue;
94			}
95			const flicker = Math.floor(t / (d === 0 ? 50 : 300));
96			words[i] =
97				RAIN_GLYPHS[hash(c * 131 + r * 17 + flicker) % RAIN_GLYPHS.length] ??
98				0x20;
99			words[i + 1] =
100				message === undefined
101					? (RAIN_FADE[d === 0 ? 0 : d + RAIN_FADE.length - trail] ??
102						TERMINAL_DEFAULT)
103					: rgb(d === 0 ? C.surface2 : C.surface1);
104		}
105	}
106	if (message !== undefined) {
107		const r = Math.floor(rows / 2);
108		const from = Math.max(0, Math.floor((columns - message.length) / 2));
109		// a blank cell either side keeps the rain off the words
110		for (
111			let c = Math.max(0, from - 1);
112			c <= Math.min(columns - 1, from + message.length);
113			c++
114		) {
115			const i = (r * columns + c) * 3;
116			const ch = message.codePointAt(c - from);
117			words[i] = c >= from && ch !== undefined ? ch : 0x20;
118			words[i + 1] = rgb(C.green);
119		}
120	}
121	// the engine's runtime has toBase64 (its Raster docs use it); TS lib lags
122	return (
123		new Uint8Array(words.buffer) as Uint8Array & { toBase64(): string }
124	).toBase64();
125};
126
127// What the rain keeps between frames, made per register so a reload or a
128// test starts it over: the pane reads it, the blit timer advances it.
129export type Rain = {
130	// the mounted Raster's width; a blit for another width is refused
131	columns: number;
132	// rainSpeed's latest, 0 while nothing works
133	pace: number;
134	// the rain's own clock, so a change of speed does not jump it
135	t: number;
136	at: number;
137	// when the rain last stopped; 0 has the message typed out in full
138	idleSince: number;
139	wasIdle: boolean;
140	lastMessage: string;
141};
142
143export const newRain = (): Rain => ({
144	columns: 0,
145	pace: 0,
146	t: 0,
147	at: 0,
148	idleSince: 0,
149	wasIdle: true,
150	lastMessage: "",
151});
152
hooks/status.ts 62 lines
1import type { AgentStatus, TurnCompleteReason } from "claude-code";
2import type { AgentRow, SkillRun, WorkItem } from "../types";
3
4export const STATUS: Record<AgentStatus, AgentRow["status"]> = {
5	pending: "running",
6	running: "running",
7	waiting: "running",
8	idle: "idle",
9	completed: "done",
10	failed: "failed",
11	killed: "killed",
12};
13
14export const TURN_END: Record<TurnCompleteReason, AgentRow["status"]> = {
15	answer: "done",
16	aborted: "killed",
17	refusal: "failed",
18	error: "failed",
19};
20
21export const RUN_END: Record<TurnCompleteReason, SkillRun["result"]> = {
22	answer: "done",
23	aborted: "aborted",
24	refusal: "failed",
25	error: "failed",
26};
27
28export const isLive = (a: AgentRow) =>
29	a.status === "running" || a.status === "idle";
30
31export const end = (a: AgentRow, t: number) =>
32	a.status === "running" ? t : (a.endedAt ?? t);
33
34export const sync = (
35	a: AgentRow,
36	live: AgentRow["status"] | undefined,
37	t: number,
38): AgentRow => {
39	if (
40		!isLive(a) ||
41		(live === undefined && !a.listed) ||
42		(live === a.status && a.listed)
43	) {
44		return a;
45	}
46	const status = live ?? "done";
47	return {
48		...a,
49		listed: true,
50		status,
51		...(status === "running" ? {} : { endedAt: end(a, t) }),
52	};
53};
54
55export const isOpenRun = (r: SkillRun | undefined) =>
56	r !== undefined && r.result === undefined;
57
58export const isBusy = (list: AgentRow[], runs: SkillRun[], work: WorkItem[]) =>
59	list.some((a) => a.status === "running") ||
60	(runs.length > 0 && runs.at(-1)?.result === undefined) ||
61	work.some((w) => w.text === undefined);
62
hooks/theme.ts 111 lines
1import type { AgentRow, PullRequest, SkillRun } from "../types";
2
3export const PANE = "summary";
4
5// rows each box lists at most, so the pane fits a terminal's height
6export const SHOWN = 3;
7export const RECENT_SHOWN = 5;
8
9export const SPARK = "▁▂▃▄▅▆▇█";
10
11export const C = {
12	text: "#cdd6f4",
13	subtext: "#a6adc8",
14	overlay: "#7f849c",
15	surface2: "#585b70",
16	surface1: "#45475a",
17	surface0: "#313244",
18	mauve: "#cba6f7",
19	pink: "#f5c2e7",
20	lavender: "#b4befe",
21	blue: "#89b4fa",
22	sky: "#89dceb",
23	teal: "#94e2d5",
24	green: "#a6e3a1",
25	yellow: "#f9e2af",
26	peach: "#fab387",
27	red: "#f38ba8",
28};
29
30export const SPINNER = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏";
31
32export const GLOW = [
33	C.mauve,
34	C.pink,
35	C.lavender,
36	C.blue,
37	C.sky,
38	C.blue,
39	C.lavender,
40	C.pink,
41];
42
43// head first; a drop's trail always ends on the last color
44export const rgb = (hex: string) => Number.parseInt(hex.slice(1), 16);
45
46export const ICON: Record<AgentRow["status"], string> = {
47	running: "●",
48	idle: "○",
49	done: "✓",
50	failed: "✗",
51	killed: "■",
52};
53
54export const COLOR: Record<AgentRow["status"], string> = {
55	running: C.yellow,
56	idle: C.overlay,
57	done: C.green,
58	failed: C.red,
59	killed: C.red,
60};
61
62export const GIT_COLOR: Record<string, string> = {
63	M: C.yellow,
64	A: C.green,
65	D: C.red,
66	R: C.blue,
67	"??": C.teal,
68};
69
70export const RUN: Record<
71	NonNullable<SkillRun["result"]>,
72	{ icon: string; color: string }
73> = {
74	done: { icon: "✓", color: C.green },
75	failed: { icon: "✗", color: C.red },
76	aborted: { icon: "■", color: C.overlay },
77};
78
79export const REVIEW: Record<
80	PullRequest["review"],
81	{ text: string; color: string }
82> = {
83	approved: { text: "✅ approved", color: C.green },
84	changes: { text: "❌ changes requested", color: C.red },
85	pending: { text: "👀 review required", color: C.yellow },
86};
87
88export const CHECKS: Record<
89	NonNullable<PullRequest["ci"]>,
90	{ text: string; color: string }
91> = {
92	success: { text: "CI ✔", color: C.green },
93	failure: { text: "CI ✗ failed", color: C.red },
94	pending: { text: "CI ⋯ running", color: C.yellow },
95};
96
97export const ORDER: AgentRow["status"][] = [
98	"running",
99	"idle",
100	"done",
101	"failed",
102	"killed",
103];
104
105export const modelColor = (model: string) =>
106	model.startsWith("opus")
107		? C.peach
108		: model.startsWith("haiku")
109			? C.teal
110			: C.blue;
111
hooks/cron.ts 56 lines
1// One cron field (`*`, `5`, `1-5`, `*/10`, `0,6`) against a value.
2export const cronMatches = (field: string, v: number, lo: number, hi: number) =>
3	field.split(",").some((part) => {
4		const [range = "", every = "1"] = part.split("/");
5		const [from = Number.NaN, to = from] =
6			range === "*"
7				? [lo, hi]
8				: range.includes("-")
9					? range.split("-").map(Number)
10					: [Number(range), part.includes("/") ? hi : Number(range)];
11		return v >= from && v <= to && (v - from) % Number(every) === 0;
12	});
13
14// The next minute after now a five-field cron fires, in local time; undefined
15// past a week and a day or for what does not parse.
16export const nextFire = (schedule: string, now: number) => {
17	const [minute, hour, dom, month, dow, ...rest] = schedule.trim().split(/\s+/);
18	if (
19		minute === undefined ||
20		hour === undefined ||
21		dom === undefined ||
22		month === undefined ||
23		dow === undefined ||
24		rest.length > 0
25	) {
26		return undefined;
27	}
28	const d = new Date(now);
29	d.setSeconds(0, 0);
30	for (let i = 0; i < 8 * 24 * 60; i++) {
31		d.setMinutes(d.getMinutes() + 1);
32		const day = d.getDay();
33		const byDom = cronMatches(dom, d.getDate(), 1, 31);
34		const byDow =
35			cronMatches(dow, day, 0, 7) || (day === 0 && cronMatches(dow, 7, 0, 7));
36		if (
37			cronMatches(minute, d.getMinutes(), 0, 59) &&
38			cronMatches(hour, d.getHours(), 0, 23) &&
39			cronMatches(month, d.getMonth() + 1, 1, 12) &&
40			// both day fields set: either may match, as cron has it
41			(dom !== "*" && dow !== "*" ? byDom || byDow : byDom && byDow)
42		) {
43			return d.getTime();
44		}
45	}
46	return undefined;
47};
48
49export const hhmm = (ms: number, now: number) => {
50	const d = new Date(ms);
51	const time = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
52	return ms - now < 86_400_000
53		? time
54		: `${d.getMonth() + 1}/${d.getDate()} ${time}`;
55};
56
types/index.d.ts 114 lines
1export type AgentRow = {
2	id: string;
3	label: string;
4	name?: string;
5	model: string;
6	description: string;
7	startedAt: number;
8	endedAt?: number;
9	status: "running" | "idle" | "done" | "failed" | "killed";
10	tool?: string;
11	listed?: boolean;
12};
13
14export type WorkItem = {
15	id: string;
16	at: number;
17	durationMs: number;
18	tokens?: number;
19	text?: string;
20	ask?: string;
21	answer?: string;
22};
23
24export type FileTouch = {
25	path: string;
26	edits: number;
27	status?: string;
28};
29
30export type Alert = {
31	at: number;
32	tool: string;
33	reason: string;
34	agent?: string;
35};
36
37export type SkillRun = {
38	skills: string[];
39	model: string;
40	effort?: string;
41	startedAt: number;
42	endedAt?: number;
43	result?: "done" | "failed" | "aborted";
44};
45
46export type BackgroundTask = {
47	id: string;
48	type: string;
49	status: string;
50	label: string;
51};
52
53export type SessionCron = {
54	id: string;
55	schedule: string;
56	recurring: boolean;
57	prompt: string;
58};
59
60export type Commit = {
61	hash: string;
62	at: number;
63	subject: string;
64};
65
66export type RepoState = {
67	branch?: string;
68	upstream?: string;
69	ahead: number;
70	behind: number;
71	commits: Commit[];
72};
73
74export type PullRequest = {
75	branch: string;
76	number: number;
77	url: string;
78	isDraft: boolean;
79	review: "approved" | "changes" | "pending";
80	ci?: "success" | "failure" | "pending";
81	unresolved: number;
82};
83
84export type TurnMark = {
85	ms: number;
86	ok: boolean;
87};
88
89declare module "claude-code" {
90	interface PluginState {
91		summary: {
92			agents: AgentRow[];
93			now: number;
94			recent: WorkItem[];
95			files: FileTouch[];
96			dirty: number;
97			alerts: Alert[];
98			runs: SkillRun[];
99			model: string;
100			shown: boolean;
101			chord: string;
102			tabs: string;
103			seen: string[];
104			working: number;
105			tasks: BackgroundTask[];
106			crons: SessionCron[];
107			turns: TurnMark[];
108			repo: RepoState;
109			pr: PullRequest | null;
110			autoOpened: boolean;
111		};
112	}
113}
114