SLOPSHOPPER

peer

Watch and drive peer rooms from Claude Code, and deliver room messages to main as they come

panespinnerrowsguardcommandtoast
★ 5v0.1.56no licenseupdated 2026-10-18r13v/peer/plugin
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · peer
│ ┃ peer ✕ › fix the failing auth test and add an audit log call │ ┃ No active peer room in this checkout. Start │ ┃ one with /peer:peer TASK. ● peer: peer watch stopped: no output │ ┃ ⏺ Read(src/auth.ts) │ ┃ new room: task ⏎ start ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ peer watch stopped: no output; retrying ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /room │ ⎿ peer: peer: pane opened │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⟨Claude Code's own drawing⟩ 👀 Peer

Draws

Pane · peer
No active peer room in this checkout. Start one with /peer:peer TASK. new room: task ⏎ start peer watch stopped: no output; retrying
README

peer for Claude Code

The peer plugin shows a session's peer rooms in Claude Code: in the Code tab of the desktop app, in the terminal and in VS Code. A session's rooms are the ones it started with peer start, leads with peer wait --as main or joined with a peer join command of its own; after a rewind or a resume the plugin finds them again in the conversation; another session's rooms in the same checkout stay out of it, and the peer TUI shows them all. Outside a Git checkout, the plugin shows nothing.

  • /peer:peer TASK starts the work: the plugin's own skill runs peer skills flow, and as main, Claude reads the room through the plugin instead of peer wait. With the plugin, Claude Code does not need the standalone peer skill.
  • Pane. It opens by itself when a room is active and there is room for it, and from the footer button.
  • One row of tabs: Chat, a tab for each member, ● while its agent runs and ○ once it stopped, and ⏹ end at the right. A member's tab shows its model and state, a kick button and its log: its text, its commands and their results. Kick and end act on a second press: the first turns the button into confirm for three seconds.
  • New room. A pane without a room shows a task field; with a room, + new room in the row of tabs shows it. A task sent with Enter runs /peer:peer TASK, and the pane shows the task in place of the field until the room starts. Where the surface has no fields, + new room puts /peer:peer in the prompt box instead.
  • Keys. While the pane holds the keyboard (ctrl+x tab or a click): 1 chat, 2 boards, 3–9 the members' tabs, n new room, e end, k kick on a member's tab; end and kick still take a second press.
  • Replay. A member's tab with file edits in its log has replay N edits (r): one step per edit, with h and l to go back and on. A step shows the file and the file's uncommitted diff in the member's checkout (its worktree, if it has one) now, not the step's own diff: the log keeps an edit's path, and cuts its input at 200 characters, so an edit whose input was cut is left out.
  • Chat shows the newest message first. Each message is a card in its author's color, the time first, with Markdown, code blocks and links to the checkout's files, such as main.go:42. Notices from peer take one line, and a long message shows its first lines until you expand it. A timeline shows who wrote when (not in the terminal). The pane shows each new message unless you hold its keyboard.
  • Boards. The pane's boards tab lists the boards of the room it shows, from peer board list: each with its title, a link to open it in the browser (start peer if the link does not open) and a preview. The preview is a schematic of the frames, nodes and edges that the plugin lays out itself, so a board nobody opened in the browser has one too; in the terminal, the same schematic drawn in cells (frames as boxes, cards as blocks of their color, without edges) and a list of frames with their node and open-thread counts. See docs/BOARD.md.
  • Footer button. At the right of the prompt footer, 👀 Peer is always there, with or without a room. It shows the number of messages in the session's rooms that came since the pane last showed them, opens the pane, and closes it when the pane already shows.
  • Delivery to main. When Claude Code is main of a room, the plugin reads the room for main and puts each batch of messages into the chat as a turn of its own: right away while Claude is idle, and right after the running turn while it works. These rows are hidden in the chat, since the toast, the pane and the footer's count show the messages; in the terminal and VS Code, ctrl+o shows them as the model reads them. Main does not run peer wait; the plugin answers a wait for the room itself, so the room has only one reader as main.
  • Messages in the transcript. A Bash row that only runs peer send ID --as ROLE [--to ROLE] --text TEXT is drawn as the message card, in its author's color. A line the shell changes first ($, ` `, \, <, >`, more commands) keeps its row, so a card shows only what was sent.
  • /room opens or closes the pane. In the prompt box, @ offers the members of the room the pane shows.
  • Delivery turns. While Claude reads a delivery, the spinner says how many messages and from whom; after it, the empty prompt box suggests Tell ROLE: for the last author (Tab takes it).
  • Permission dialog. For peer end and peer kick, a line under the dialog says which members' agents still run or which agent the kick stops.
  • Toasts when a member joins, exits or is kicked, and when a room ends. The plugin raises no system notifications.

The plugin's version is the CLI's: each release of peer sets it, so claude plugin update brings the plugin that goes with the new CLI. The plugin runs peer watch, peer memberlog and peer ack from your PATH, so it needs a peer with these commands. After each delivery, peer ack moves main's cursor just past the last message in the chat, so a peer wait run after the plugin is turned off gets the rest. When peer ack fails, for example with an older peer earlier on PATH, the pane shows why in red; the plugin tries that room again and goes on delivering the other rooms.

Install

claude plugin marketplace add r13v/peer
claude plugin install peer@r13v

If you installed the standalone skill for Claude Code before, remove it there and keep it for the other agents:

npx skills remove peer -g -a claude-code

To install peer itself, see the main README.

Develop

claude plugin validate plugin
claude plugin test plugin
claude --plugin-dir plugin

See a change in a running session

The installed plugin runs the copy that claude plugin install or claude plugin update made, so an edit in the checkout reaches it only with a release. To see an edit at once, load plugin from the checkout into the session.

  1. Disable the installed plugin: claude plugin disable peer@r13v. Two copies would both read a room for main, which breaks one reader per role, and both would draw a footer button.
  2. Load the checkout's plugin:
  3. Terminal: claude --plugin-dir plugin from the checkout. The session watches the folder: a saved file reloads the hooks module.
  4. Desktop app (Code tab), new session: name the absolute path of plugin in CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json. Each new session loads it when it starts.
  5. Desktop app, running session: ask Claude to live-reload the plugin from this checkout. Claude loads its plugin-authoring skill and links plugin into the session's mods folder, ~/.claude/dev-mods/SESSION_ID/; Claude Code then asks once "Enable hot reloading for this session?". Choose Enable for this session: the plugin loads when the turn ends, and each later edit reloads it when the turn that made the edit ends.
  6. When you are done, run claude plugin enable peer@r13v and remove the link or the CLAUDE_CODE_PLUGIN_DIRS entry.

A reload starts the module again: its own variables, such as queued deliveries, start empty. Rooms lose no messages, because peer ack keeps main's cursor in the store.

Check against a new Claude Code

Claude Code updates can break the plugin. Two checks catch it:

  • Typecheck (npm run typecheck:plugin) checks the hooks module and the tests against the types that Claude Code writes into plugin/.claude-plugin/types (claude-code and claude-code-tools, not claude-code-mcp, which depends on the machine's MCP servers). Only an interactive load of the plugin writes them, not claude -p, and the first line of claude-code/index.d.ts names the Claude Code that wrote them. When that is not claude --version, scripts/typecheck-plugin.ts loads the plugin once in a pseudo-terminal, as a session that is not logged in, with a temporary HOME, waits for the new types (a few seconds) and stops that session. So the typecheck always uses the types of the installed CLI, and nothing is copied or committed. Without claude on PATH it checks the types there are, or prints SKIPPED.
  • Tests (npm run test:plugin) run plugin/tests/*.test.ts in the kit inside the claude binary, without a login. They catch changes of the hook API and of the plugin's logic. They do not catch engine semantics: everything below the plugin is a stub of the test. engine.test.ts pins the hooks that keep one reader as main: the plugin answers main's peer wait and denies a line that mixes it with other commands.

npm run engine-check runs both once per claude --version and committed plugin tree (git rev-parse HEAD:plugin). It keeps the plugin trees that passed under this CLI in ~/.cache/peer/engine-checked, one line each, and drops those of an older CLI: a new commit of the plugin or a pull is checked again under the same CLI, while worktrees with different plugins do not check again in turn; --force checks again. Uncommitted edits are for the pre-commit typecheck. A checkout without node_modules prints one line and skips the check, since tsc comes from there. On a failure it prints the step and the last 30 lines of its output and exits 1. PEER_ENGINE_CHECK set in the environment skips the check, so a Claude Code session that a step starts does not run it again.

The Claude Code workflow runs claude plugin validate, the typecheck and the tests against the latest Claude Code every day and on demand, so a release that breaks the plugin fails there before you update; GitHub mails the failure.

To run engine-check when a session starts, add a hook to your own ~/.claude/settings.json. It runs in the session's own checkout, $CLAUDE_PROJECT_DIR, so a worktree checks its own plugin against the types it has the CLI write; a hard-coded path would check another checkout's code. A project's .claude/settings.local.json is not committed, so new worktrees do not have it; and the file test skips other repositories. Claude Code puts the hook's output into the session only on exit 0, hence || true:

"hooks": { "SessionStart": [{ "hooks": [{ "type": "command", "command": "cd \"$CLAUDE_PROJECT_DIR\" && [ -f scripts/engine-check.ts ] && node scripts/engine-check.ts || true", "timeout": 180 }] }] }
Source 3 files
hooks/register.tsx 1882 lines
1import type { EngineInterface as Engine, Register } from "claude-code"
2
3import type {
4	PeerBoard,
5	PeerBoardRef,
6	PeerLogEntry,
7	PeerMark,
8	PeerMember,
9	PeerMessage,
10	PeerRoom,
11	PeerState,
12} from "../types"
13import {
14	boardRaster,
15	boardStats,
16	boardSvg,
17	frameLines,
18} from "./board-preview.ts"
19
20const PANE = "peer"
21const EVERYONE = "*"
22// BOARDS is the tab value of the room's boards; ":" keeps it apart from roles.
23const BOARDS = ":boards"
24// ICON stands for peer in the prompt footer.
25const ICON = "👀"
26// SKILL is the plugin's slash command that starts a room.
27const SKILL = "peer:peer"
28
29// All of the plugin's session state is one value: the engine lists the
30// values a module reads and writes, so each reference is a literal.
31const STATE = { plugin: "peer", key: "state" } as const
32
33const INITIAL: PeerState = {
34	rooms: {},
35	messages: {},
36	selected: null,
37	tab: "chat",
38	confirm: null,
39	led: [],
40	own: [],
41	watchError: null,
42	ackErrors: {},
43	log: [],
44	// delivered marks, per led room, the last message for main that is in
45	// the chat, so a reload goes on from it.
46	delivered: {},
47	// notified lists the led rooms whose end main has been told about.
48	notified: [],
49	expanded: [],
50	seen: {},
51}
52
53const rooms = "rooms"
54const messages = "messages"
55const selected = "selected"
56const tab = "tab"
57const confirm = "confirm"
58const led = "led"
59const own = "own"
60const watchError = "watchError"
61const ackErrors = "ackErrors"
62const log = "log"
63const delivered = "delivered"
64const notified = "notified"
65const expanded = "expanded"
66const seen = "seen"
67
68const HANDOFF =
69	"The peer plugin reads this room for main and puts its messages into this chat as a turn of their own, once this session is free. Do not run peer wait for this room; go on with the task."
70
71// Module variables start over on a reload; everything drawn is in $.state.
72let isReady = false
73// watch's last failure, so the transcript tells of each kind once, and its
74// pause before the next try.
75let lastWatchError = ""
76let watchRetry = 2500
77let isStarted = false
78let isPumping = false
79let isPumpWanted = false
80// The rooms restore found this session started, led once watch is ready.
81let toLead: string[] = []
82// Whether the person holds the pane's keyboard: then a new message does not
83// scroll it, so what they read stays put.
84let isPaneFocused = false
85// The host's offset from UTC in minutes: the module's environment does not
86// know the host's time zone, so times are shifted by hand.
87let utcOffset = 0
88// The checkout's files, so a message's file:line becomes a link.
89let files = { repo: "", paths: new Set<string>() }
90// The boards of each room, with their board.json once read, while the
91// boards tab shows; error says why the list could not be read.
92type BoardView = { ref: PeerBoardRef; board?: PeerBoard; error?: string }
93let boardViews: Record<string, { boards: BoardView[]; error?: string }> = {}
94// The pane's new room field: whether a room's pane shows it, and the task
95// sent from it until its turn ends or a room starts.
96let isComposing = false
97let startingTask = ""
98let isStartingTurn = false
99// The rooms by id as watch last printed them, for drawings that must not
100// read the state: a transcript row that read it would be drawn again on
101// every write.
102let roomIndex: Record<string, PeerRoom> = {}
103// What the running turn reads when it is a delivery: the spinner's line,
104// and the author the prompt box suggests answering once it ends.
105let deliveryNote = ""
106let deliveryAuthor = ""
107// What each queued delivery's turn will read, by its text, made from the
108// messages themselves: a message's text never names an author here.
109const deliveries = new Map<string, { line: string; author: string }>()
110// The member whose edits the pane replays, the step it shows, and that
111// step's file diff once git printed it.
112let replay: { role: string; index: number } | null = null
113let replayDiff: {
114	key: string
115	text: string
116	error?: string
117	isLoaded?: boolean
118} | null = null
119
120// starting sets the task the pane shows as starting and draws the pane.
121function starting($: Engine, task: string) {
122	startingTask = task
123	isStartingTurn = false
124	$.ui.invalidate("ui.render")
125}
126
127// normalize fills in the fields a state lacks; a state without own takes
128// the rooms it led as its own.
129function normalize(value: Partial<PeerState> | undefined): PeerState {
130	return { ...INITIAL, ...value, own: value?.own ?? value?.led ?? [] }
131}
132
133// get reads a field of the plugin's state; while a drawing reads it, a
134// later put draws that drawing again.
135async function get<K extends keyof PeerState>(
136	$: Engine,
137	field: K,
138): Promise<PeerState[K]> {
139	const { value } = await $.state.get(STATE)
140	return normalize(value)[field]
141}
142
143// snapshot reads the whole state at once: a drawing reads it once, not
144// once per field.
145async function snapshot($: Engine): Promise<PeerState> {
146	const { value } = await $.state.get(STATE)
147	return normalize(value)
148}
149
150// put applies fn to a field and writes the state, again when another write
151// came first. A write that changes nothing is skipped, since each write
152// draws every drawing that reads the state again.
153async function put<K extends keyof PeerState>(
154	$: Engine,
155	field: K,
156	fn: (old: PeerState[K]) => PeerState[K],
157) {
158	for (;;) {
159		const { value, version } = await $.state.get(STATE)
160		const old = normalize(value)
161		const next = fn(old[field])
162		if (next === old[field]) return
163		const written = await $.state.set(
164			STATE,
165			{ ...old, [field]: next },
166			{ ifVersion: version },
167		)
168		if (written.isSet) return
169	}
170}
171
172// begin starts the session's background work once; session.start calls it,
173// and so do the first hooks of a mod loaded into a running session.
174async function begin($: Engine) {
175	if (isStarted) return
176	isStarted = true
177	// A pane left open by the module before a reload is drawn by this one.
178	$.ui.invalidate("ui.render")
179	await restore($)
180	await $.command
181		.register({
182			name: "room",
183			description: "peer: open or close the pane of this session's room",
184			immediate: true,
185		})
186		.catch(() => ({}))
187	watch($)
188	$.clock.every(3000, () => void refresh($))
189	void loadOffset($)
190	$.clock.every(60_000, () => void loadFiles($))
191	void loadFiles($)
192}
193
194// restore finds this session's rooms in its conversation when its state
195// starts empty while the chat goes on, as after a rewind or a resume: a
196// room joined there is its own again, and one started there is led again
197// once watch is ready.
198async function restore($: Engine) {
199	if ((await $.state.get(STATE)).value !== undefined) return
200	const found = await $.session.messages().catch(() => [])
201	if ("deny" in found) return
202	const joined: string[] = []
203	for (const use of found.flatMap((m) => m.toolUses)) {
204		if (
205			use.tool !== "Bash" ||
206			use.isError ||
207			typeof use.input.command !== "string"
208		)
209			continue
210		const all = shellCommands(use.input.command)
211		const commands = all
212			.map(peerArgs)
213			.filter((args): args is string[] => args !== null)
214		const stdout = (use.result as { stdout?: string } | undefined)?.stdout ?? ""
215		const [cmd, id, role] = commands[0] ?? []
216		if (
217			all.length === 1 &&
218			cmd === "join" &&
219			id &&
220			role &&
221			joinedRoom(stdout, id, role)
222		)
223			joined.push(id)
224		const room = commands.some((args) => args[0] === "start")
225			? await startedRoom(stdout)
226			: null
227		if (room) toLead.push(room.id)
228	}
229	const mine = [...new Set([...joined, ...toLead])]
230	if (mine.length > 0) await put($, own, () => mine)
231}
232
233// loadOffset reads the host's UTC offset, as +0300, and draws the times again.
234async function loadOffset($: Engine) {
235	try {
236		const { stdout } = await $.process.run(["date", "+%z"], { timeoutMs: 5000 })
237		const match = /^([+-])(\d\d)(\d\d)$/.exec(stdout.trim())
238		if (!match) return
239		utcOffset =
240			(match[1] === "-" ? -1 : 1) * (Number(match[2]) * 60 + Number(match[3]))
241		$.ui.invalidate("ui.render")
242	} catch {
243		// times stay in UTC
244	}
245}
246
247async function loadFiles($: Engine) {
248	try {
249		const repo = current(await snapshot($))?.repo ?? (await $.session.cwd())
250		const { exitCode, stdout } = await $.process.run(
251			["git", "-C", repo, "ls-files"],
252			{ timeoutMs: 10_000 },
253		)
254		if (exitCode === 0)
255			files = { repo, paths: new Set(stdout.split("\n").filter(Boolean)) }
256	} catch {
257		// no links until the next try
258	}
259}
260
261// toNewest scrolls the pane to its top, where the newest message is.
262function toNewest($: Engine) {
263	void $.ui.scroll({ in: PANE, to: "start" }).catch(() => ({}))
264}
265
266function peer($: Engine, argv: string[], timeoutMs = 30_000) {
267	return $.process.run(["peer", ...argv], { timeoutMs })
268}
269
270// activeRooms lists this session's active rooms, the ones it leads first,
271// then the newest first. Other sessions' rooms of the checkout are theirs:
272// the plugin does not show them.
273function activeRooms(st: PeerState) {
274	const isLed = (room: PeerRoom) => (st.led.includes(room.id) ? 0 : 1)
275	return Object.values(st.rooms)
276		.filter((room) => !room.ended_at && st.own.includes(room.id))
277		.sort(
278			(a, b) => isLed(a) - isLed(b) || b.started_at.localeCompare(a.started_at),
279		)
280}
281
282// current is the room the pane shows: the one picked, else the first active.
283function current(st: PeerState) {
284	const picked =
285		st.selected && st.own.includes(st.selected)
286			? st.rooms[st.selected]
287			: undefined
288	return picked ?? activeRooms(st)[0] ?? null
289}
290
291async function openPane($: Engine) {
292	const opened = await $.ui
293		.open({ id: PANE, title: "peer" })
294		.catch(() => ({ isPlaced: false }))
295	if (opened.isPlaced) toNewest($)
296	return opened
297}
298
299// togglePane closes the pane where it shows, and opens it otherwise.
300async function togglePane($: Engine) {
301	const isShown = (await $.ui.panes()).some(
302		(pane) => pane.id === PANE && pane.isShown,
303	)
304	if (isShown) {
305		await $.ui.close({ id: PANE })
306		return "closed"
307	}
308	const { isPlaced } = await openPane($)
309	return isPlaced ? "opened" : "not placed"
310}
311
312// unseen counts the messages in the session's rooms that came since the
313// pane last showed them.
314function unseen(st: PeerState) {
315	return activeRooms(st).reduce(
316		(sum, room) =>
317			sum + (st.messages[room.id] ?? []).length - (st.seen[room.id] ?? 0),
318		0,
319	)
320}
321
322// watch keeps rooms and messages current from peer watch, which reads
323// the store without moving anyone's cursor.
324function watch($: Engine) {
325	void (async () => {
326		let buffer = ""
327		let stderr = ""
328		try {
329			for await (const { stream, text } of $.process.spawn({
330				argv: ["peer", "watch"],
331			})) {
332				if (stream === "stderr") {
333					stderr += text
334					continue
335				}
336				buffer += text
337				const lines = buffer.split("\n")
338				buffer = lines.pop() ?? ""
339				await apply($, lines)
340			}
341		} catch (err) {
342			stderr += String(err)
343		}
344		const reason = stderr.trim().slice(0, 300) || "no output"
345		// A session outside a Git checkout has no rooms: that is not an error,
346		// and a cd into a checkout is picked up by the next try.
347		const isOutside = /inside the shared Git checkout/.test(reason)
348		if (!isOutside && reason !== lastWatchError)
349			$.ui.log(`peer watch stopped: ${reason}`, { to: "transcript" })
350		lastWatchError = reason
351		const isOldCli = /usage|unknown|not found|no such file/i.test(stderr)
352		const failure = isOldCli
353			? "peer watch failed: update the peer CLI (peer update or brew upgrade --cask peer)"
354			: `peer watch stopped: ${reason.slice(0, 200)}; retrying`
355		await put($, watchError, () => (isOutside ? null : failure))
356		watchRetry = Math.min(watchRetry * 2, 60_000)
357		$.clock.after(watchRetry, () => watch($))
358	})()
359}
360
361async function apply($: Engine, lines: string[]) {
362	const roomEvents: PeerRoom[] = []
363	const newMessages: Record<string, PeerMessage[]> = {}
364	let ready = false
365	for (const line of lines) {
366		if (!line.trim()) continue
367		let event: { event?: string; room?: unknown; message?: PeerMessage }
368		try {
369			event = JSON.parse(line)
370		} catch {
371			continue
372		}
373		if (
374			event.event === "room" &&
375			event.room &&
376			typeof event.room === "object"
377		) {
378			roomEvents.push(event.room as PeerRoom)
379		} else if (
380			event.event === "message" &&
381			typeof event.room === "string" &&
382			event.message
383		) {
384			const list = newMessages[event.room] ?? []
385			list.push(event.message)
386			newMessages[event.room] = list
387		} else if (event.event === "ready") {
388			ready = true
389		}
390	}
391	const before = await get($, rooms)
392	const known = await get($, messages)
393	// A restarted watch replays the transcript: keep each message once.
394	const fresh: Record<string, PeerMessage[]> = {}
395	for (const [id, list] of Object.entries(newMessages)) {
396		const ids = new Set((known[id] ?? []).map((m) => m.id))
397		const added = list.filter((m) => !ids.has(m.id))
398		if (added.length > 0) fresh[id] = added
399	}
400	if (roomEvents.length > 0) {
401		await put($, rooms, (all) => {
402			const next = { ...all }
403			for (const room of roomEvents) next[room.id] = room
404			return next
405		})
406	}
407	if (Object.keys(fresh).length > 0) {
408		await put($, messages, (all) => {
409			const next = { ...all }
410			for (const [id, list] of Object.entries(fresh))
411				next[id] = [...(next[id] ?? []), ...list]
412			return next
413		})
414	}
415	await put($, watchError, (old) => (old === null ? old : null))
416	if (ready) {
417		watchRetry = 2500
418		lastWatchError = ""
419	}
420	if (isReady) {
421		const mine = new Set(await get($, own))
422		for (const room of roomEvents) {
423			const was = before[room.id]
424			if (!mine.has(room.id)) continue
425			if (room.ended_at && was && !was.ended_at)
426				$.ui.toast(`peer: room ${room.id} ended`)
427		}
428		for (const [id, list] of Object.entries(fresh)) {
429			if (!mine.has(id)) continue
430			for (const m of list) {
431				if (m.from === "peer") $.ui.toast(`${id}: ${m.text}`)
432			}
433		}
434		const st = await snapshot($)
435		if (!isPaneFocused && st.tab === "chat" && fresh[current(st)?.id ?? ""])
436			toNewest($)
437	}
438	if (ready) {
439		// A watch started after a room ended does not list it: read the rest
440		// of a led room's transcript, then its state, from log and status.
441		const listed = new Set(roomEvents.map((room) => room.id))
442		const isLed = new Set(await get($, led))
443		const mine = new Set(await get($, own))
444		for (const room of Object.values(await get($, rooms))) {
445			if (room.ended_at || listed.has(room.id) || !mine.has(room.id)) continue
446			if (isLed.has(room.id) && !(await readLog($, room.id))) continue
447			const { exitCode, stdout } = await peer($, ["status", room.id])
448			if (exitCode === 0 && stdout.trim()) {
449				const status = JSON.parse(stdout) as PeerRoom
450				await put($, rooms, (all) => ({ ...all, [status.id]: status }))
451			}
452		}
453		if (!isReady) {
454			// Lead the restored rooms now that their messages are in: lead
455			// marks what main read against them.
456			const all = await get($, rooms)
457			for (const id of toLead)
458				if (all[id] && !all[id].ended_at) await lead($, id)
459			toLead = []
460			isReady = true
461			if (activeRooms(await snapshot($)).length > 0) void openPane($)
462		}
463	}
464	roomIndex = await get($, rooms)
465	void pump($)
466}
467
468// readLog adds a room's whole transcript from peer log to the messages,
469// for what a watch may not have printed yet; it says whether it could.
470async function readLog($: Engine, id: string) {
471	const { exitCode, stdout, isStdoutTruncated } = await peer($, [
472		"log",
473		id,
474		"--json",
475	])
476	if (exitCode !== 0) return false
477	if (isStdoutTruncated) {
478		await put(
479			$,
480			watchError,
481			() =>
482				`the transcript of ${id} is over 4 MiB; read its end with peer log ${id}`,
483		)
484		return false
485	}
486	const list = stdout
487		.split("\n")
488		.filter((line) => line.trim())
489		.map((line) => JSON.parse(line) as PeerMessage)
490	await put($, messages, (all) => {
491		const ids = new Set((all[id] ?? []).map((m) => m.id))
492		return {
493			...all,
494			[id]: [...(all[id] ?? []), ...list.filter((m) => !ids.has(m.id))],
495		}
496	})
497	return true
498}
499
500// lead makes this session main's reader for room id. Messages come from
501// peer watch's transcript, not from wait, so a reload or a failed delivery
502// loses none; main's cursor moves only after a delivery. A reload between
503// a queued turn and its mark brings that batch again: at least once, not
504// exactly once.
505async function lead($: Engine, id: string, isNew = false) {
506	await put($, own, (list) => (list.includes(id) ? list : [...list, id]))
507	if ((await get($, led)).includes(id)) return
508	if (!(id in (await get($, delivered)))) {
509		// From a new room, deliver everything; otherwise start after what main
510		// already read with wait, which status counts as not unread.
511		let mark: PeerMark | null = null
512		if (!isNew) {
513			const { stdout } = await peer($, ["status", id])
514			const unread =
515				(JSON.parse(stdout || "{}") as PeerRoom).members?.find(
516					(m) => m.role === "main",
517				)?.unread ?? 0
518			const list = forMain((await get($, messages))[id] ?? [])
519			const last = list[list.length - unread - 1]
520			mark = last ? { id: last.id, at: last.at } : null
521		}
522		await put($, delivered, (all) => ({ ...all, [id]: mark }))
523	}
524	await put($, led, (list) => [...list, id])
525	void pump($)
526}
527
528function forMain(list: PeerMessage[]) {
529	return list.filter(
530		(m) => m.from !== "main" && (m.to === "main" || m.to === EVERYONE),
531	)
532}
533
534// after returns the messages of list that come after mark.
535function after(list: PeerMessage[], mark: PeerMark | null) {
536	if (!mark) return list
537	const i = list.findIndex((m) => m.id === mark.id)
538	if (i >= 0) return list.slice(i + 1)
539	const at = Date.parse(mark.at)
540	return list.filter((m) => Date.parse(m.at) > at)
541}
542
543// pump puts what is new for main in each led room into the chat, in order;
544// a mark moves only once its batch is there, and a failure is tried again.
545async function pump($: Engine) {
546	if (!isReady) return
547	// A call made while a pump runs is not dropped: that pump runs once more.
548	if (isPumping) {
549		isPumpWanted = true
550		return
551	}
552	isPumping = true
553	isPumpWanted = false
554	let hasFailed = false
555	try {
556		for (const id of await get($, led)) {
557			// A room that fails is tried again later; the rooms after it go on.
558			try {
559				await pumpRoom($, id)
560			} catch {
561				hasFailed = true
562			}
563		}
564	} catch {
565		hasFailed = true
566	} finally {
567		isPumping = false
568	}
569	if (hasFailed) $.clock.after(3000, () => void pump($))
570	if (isPumpWanted) void pump($)
571}
572
573// pumpRoom puts what is new for main in led room id into the chat, then
574// tells main that the room ended once it has.
575async function pumpRoom($: Engine, id: string) {
576	// watch can print a room's end before its last messages: read the
577	// whole transcript once the room has ended, before the end note.
578	const hasEnded = Boolean((await get($, rooms))[id]?.ended_at)
579	if (hasEnded && !(await readLog($, id))) throw new Error("no log")
580	for (;;) {
581		const pending = after(
582			forMain((await get($, messages))[id] ?? []),
583			(await get($, delivered))[id] ?? null,
584		)
585		const batch = pending.slice(0, 16)
586		const last = batch[batch.length - 1]
587		if (!last) break
588		if (!(await deliver($, id, batch))) throw new Error("not delivered")
589		await put($, delivered, (all) => ({
590			...all,
591			[id]: { id: last.id, at: last.at },
592		}))
593		await ack($, id, last)
594	}
595	// Ack the saved mark too: an ack that failed before a reload is
596	// tried again here.
597	await ack($, id, (await get($, delivered))[id] ?? null)
598	const room = (await get($, rooms))[id]
599	if (hasEnded && room) {
600		if (!(await get($, notified)).includes(id)) {
601			const reason = room.ended_reason ? ` (${room.ended_reason})` : ""
602			const note = `peer room ${id} has ended${reason}. Its members no longer read or answer messages.`
603			if (!(await deliver($, id, [], note))) throw new Error("not delivered")
604			await put($, notified, (list) => [...list, id])
605		}
606		await put($, led, (list) => list.filter((one) => one !== id))
607	}
608}
609
610// ack moves main's cursor just past mark, the last message in the chat, so
611// unread counts stay right and a wait run after the plugin is turned off
612// misses nothing. A failed ack throws, and the pump tries again later.
613async function ack($: Engine, id: string, mark: PeerMark | null) {
614	if (!mark) return
615	const { exitCode, stderr } = await peer($, [
616		"ack",
617		id,
618		"--as",
619		"main",
620		"--upto",
621		mark.id,
622	])
623	if (exitCode !== 0) {
624		// An old peer CLI has no ack and prints its usage.
625		const reason = /usage|unknown/i.test(stderr)
626			? "update the peer CLI (peer update or brew upgrade --cask peer)"
627			: stderr.trim().slice(0, 200) || `exit code ${exitCode}`
628		const text = `peer ack failed for ${id}: ${reason}`
629		await put($, ackErrors, (all) =>
630			all[id] === text ? all : { ...all, [id]: text },
631		)
632		throw new Error("not acked")
633	}
634	await put($, ackErrors, (all) => {
635		if (!(id in all)) return all
636		const { [id]: _, ...rest } = all
637		return rest
638	})
639}
640
641// deliver queues one batch, or a note, as a turn of its own: the session
642// runs it once it is idle, so no message lands in a turn that is ending.
643// It says whether the turn was queued.
644async function deliver(
645	$: Engine,
646	id: string,
647	list: PeerMessage[],
648	note?: string,
649) {
650	const body = list
651		.map(
652			(m) =>
653				`[${m.from} → ${m.to === EVERYONE ? "all" : m.to} · ${clock(m.at, true)}]\n${m.text}`,
654		)
655		.join("\n\n")
656	const text =
657		note ??
658		`peer room ${id}: ${list.length} new message${list.length === 1 ? "" : "s"} for main, delivered by the peer plugin; you do not run peer wait for this room.\n\n${body}`
659	deliveries.set(text, deliverySummary(id, list, Boolean(note)))
660	const submitted = await $.prompt.submit({ text })
661	const isQueued = !("drop" in submitted && submitted.drop)
662	if (!isQueued) deliveries.delete(text)
663	return isQueued
664}
665
666// refresh keeps the footer's count and the shown log or boards tab current
667// while the pane is placed.
668async function refresh($: Engine) {
669	const pane = (await $.ui.panes()).find(
670		(one) => one.id === PANE && one.isPlaced,
671	)
672	if (!pane) return
673	const st = await snapshot($)
674	const room = current(st)
675	if (!room) return
676	// What the pane shows counts as read for the footer's count.
677	const count = (st.messages[room.id] ?? []).length
678	if (pane.isShown && st.seen[room.id] !== count)
679		await put($, seen, (all) => ({ ...all, [room.id]: count }))
680	const shown = await get($, tab)
681	if (shown === BOARDS) await loadBoards($, room)
682	else if (shown !== "chat") await loadLog($, room)
683}
684
685// loadBoards lists the boards that room's commands used, from peer board
686// list in its checkout, and reads each board.json whose mtime or revision
687// changed since the last read.
688async function loadBoards($: Engine, room: PeerRoom) {
689	const { exitCode, stdout, stderr } = await $.process.run(
690		["peer", "board", "list"],
691		{ cwd: room.repo, timeoutMs: 30_000 },
692	)
693	if (exitCode !== 0) {
694		const error = /usage|unknown/i.test(stderr)
695			? "peer board failed: update the peer CLI (peer update or brew upgrade --cask peer)"
696			: `peer board list failed: ${stderr.trim().slice(0, 200)}`
697		boardViews = { ...boardViews, [room.id]: { boards: [], error } }
698		$.ui.invalidate("ui.render")
699		return
700	}
701	let refs: PeerBoardRef[] = []
702	try {
703		refs = (JSON.parse(stdout) as { boards?: PeerBoardRef[] }).boards ?? []
704	} catch {
705		// an empty list
706	}
707	const before = boardViews[room.id]?.boards ?? []
708	const boards: BoardView[] = []
709	for (const ref of refs.filter((one) => one.rooms?.includes(room.id))) {
710		const old = before.find((view) => view.ref.path === ref.path)
711		// mtime has whole seconds: revision tells two writes in one second apart.
712		const isSame =
713			old?.board &&
714			old.ref.mtime === ref.mtime &&
715			old.ref.revision === ref.revision
716		if (ref.error)
717			boards.push({ ref, error: ref.error.message ?? ref.error.error })
718		else if (isSame) boards.push({ ...old, ref })
719		else boards.push(await readBoard($, ref))
720	}
721	boardViews = { ...boardViews, [room.id]: { boards } }
722	$.ui.invalidate("ui.render")
723}
724
725async function readBoard($: Engine, ref: PeerBoardRef): Promise<BoardView> {
726	try {
727		const text = await $.fs.read(`${ref.path}/board.json`)
728		return { ref, board: JSON.parse(text as string) as PeerBoard }
729	} catch (err) {
730		return {
731			ref,
732			error: `cannot read board.json: ${String(err).slice(0, 200)}`,
733		}
734	}
735}
736
737// loadLog reads the log of the member whose tab is shown.
738async function loadLog($: Engine, room: PeerRoom) {
739	const role = await get($, tab)
740	if (role === "chat") return
741	const { exitCode, stdout } = await peer($, ["memberlog", room.id, role])
742	if (exitCode !== 0) return
743	const entries: PeerLogEntry[] = []
744	for (const line of stdout.split("\n")) {
745		try {
746			if (line.trim()) entries.push(JSON.parse(line))
747		} catch {
748			// skip a line that is not JSON
749		}
750	}
751	await put($, log, () => entries.slice(-200))
752}
753
754function state(m: PeerMember) {
755	if (m.kicked) return "kicked"
756	if (m.exited) return "exited"
757	if (m.pid) return "running"
758
759	return m.role === "main" ? "leads" : "joined"
760}
761
762export const register: Register = (on) => {
763	on("session.start", async ($, e, next) => {
764		const started = await next(e)
765		await begin($)
766		return started
767	})
768
769	on("turn.start", async ($, e, next) => {
770		await begin($)
771		if (startingTask) isStartingTurn = true
772		// A delivery's turn names what it reads on the spinner.
773		const queued = [...deliveries.keys()].find((text) => e.text.includes(text))
774		const note = queued === undefined ? null : deliveries.get(queued)
775		if (queued !== undefined) deliveries.delete(queued)
776		const line = note?.line ?? ""
777		deliveryAuthor = note?.author ?? ""
778		if (line !== deliveryNote) {
779			deliveryNote = line
780			$.ui.invalidate("ui.render")
781		}
782		return next(e)
783	})
784
785	// The turn that ran the pane's /peer:peer is over: a room it started has
786	// cleared the task already, else the field shows again. After a
787	// delivery, the empty prompt box suggests telling its last author.
788	on("turn.complete", async ($, e, next) => {
789		if (isStartingTurn) starting($, "")
790		const done = await next(e)
791		// A subagent's turn ends inside the delivery's turn.
792		if (e.agentId) return done
793		const author = deliveryAuthor
794		if (deliveryNote) {
795			deliveryNote = ""
796			$.ui.invalidate("ui.render")
797		}
798		deliveryAuthor = ""
799		if (author)
800			void $.prompt.suggest({ text: `Tell ${author}: ` }).catch(() => ({}))
801		return done
802	})
803
804	on("ui.render", { component: "Spinner" }, (_, e, next) =>
805		deliveryNote
806			? next({ ...e, props: { ...e.props, message: deliveryNote } })
807			: next(e),
808	)
809
810	// /room opens or closes the pane, as the footer's button does.
811	on("command.run", { command: "room" }, async ($) => {
812		await begin($)
813		const done = await togglePane($)
814		if (done !== "not placed") return { text: `peer: pane ${done}` }
815		return { text: "peer: there is no room for the pane here" }
816	})
817
818	// @ROLE in the prompt box offers the members of the room the pane shows.
819	on("prompt.autocomplete", { token: /^@/ }, async ($, e, next) => {
820		const found = await next(e)
821		const room = current(await snapshot($))
822		if (!room || room.ended_at) return found
823		const prefix = e.token.slice(1)
824		const roles = room.members
825			.filter(
826				(m) => m.role !== "main" && !m.kicked && m.role.startsWith(prefix),
827			)
828			.map((m) => ({
829				text: `@${m.role}`,
830				description: `${m.worker ? "worker" : "member"} of ${room.id}`,
831			}))
832		return { suggestions: [...found.suggestions, ...roles] }
833	})
834
835	on("tool.call", { tool: "Bash" }, async ($, e, next) => {
836		await begin($)
837		const all = shellCommands(e.command)
838		const commands = all
839			.map(peerArgs)
840			.filter((args): args is string[] => args !== null)
841		const wait = commands.find((args) => args[0] === "wait" && asMain(args))
842		if (wait?.[1] && all.length > 1 && (await get($, led)).includes(wait[1])) {
843			// Answering the whole line would skip its other commands.
844			return { deny: `Run the other commands without peer wait. ${HANDOFF}` }
845		}
846		if (wait?.[1] && all.length === 1) {
847			const id = wait[1]
848			const room = (await get($, rooms))[id]
849			// led first: rooms comes from watch and can lag behind a start.
850			if ((await get($, led)).includes(id) || (room && !room.ended_at)) {
851				await lead($, id)
852				return {
853					result: {
854						stdout: JSON.stringify({ status: "timeout", note: HANDOFF }),
855						stderr: "",
856						interrupted: false,
857					},
858				}
859			}
860			return next(e)
861		}
862		// The permission dialog of a peer end or kick says who it stops.
863		const stop = commands.find(
864			(args) => (args[0] === "end" || args[0] === "kick") && args[1],
865		)
866		const effect = stop && stopNote(roomIndex[stop[1] ?? ""], stop)
867		if (effect) {
868			try {
869				$.ui.notice(e.tool_use_id, effect)
870			} catch {
871				// no dialog for this call
872			}
873		}
874		const startedAt = new Date(Date.now() - 1000).toISOString()
875		const ran = await next(e)
876		if (ran.deny !== undefined || ran.isError) return ran
877		// Main ended the room itself, so it needs no note that it ended.
878		for (const args of commands) {
879			if (args[0] === "end" && args[1] && asMain(args))
880				await put($, notified, (list) => [...list, args[1] ?? ""])
881		}
882		// A room this session joins as a member is its own too: a peer join on
883		// a line of its own that printed the room with that role. On a longer
884		// line, another command can print the room after a failed join.
885		const stdout = (ran.result as { stdout?: string } | undefined)?.stdout ?? ""
886		const [cmd, id, role] = commands[0] ?? []
887		if (
888			all.length === 1 &&
889			cmd === "join" &&
890			id &&
891			role &&
892			joinedRoom(stdout, id, role)
893		) {
894			await put($, own, (list) => (list.includes(id) ? list : [...list, id]))
895		}
896		const start = commands.find((args) => args[0] === "start" && args[1])
897		if (!start) return ran
898		const room =
899			(await startedRoom(stdout)) ??
900			(await newRoom($, start[1] ?? "", startedAt))
901		if (!room) return ran
902		await put($, selected, () => room.id)
903		await lead($, room.id, true)
904		starting($, "")
905		void openPane($)
906		return { ...ran, context: [HANDOFF] }
907	})
908
909	on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
910		isPaneFocused = e.props.isFocused
911		const st = await snapshot($)
912		const els = $.ui.resolve(e)
913		const { Box, Text, Button, Markdown, Code } = els
914		const room = current(st)
915		// starter starts a new room with the plugin's skill: the person writes
916		// the task in the field and presses Enter, and the field gives way to
917		// the task until its room starts. A surface without Input gets a
918		// button that puts /peer:peer in the prompt box instead. The padding
919		// leaves room for the field's focus ring.
920		let starter = (
921			<Text dimColor>Starting a room: {clip(startingTask, 200)}</Text>
922		)
923		if (!startingTask)
924			starter =
925				"Input" in els ? (
926					<Box paddingY="xs" paddingX="xs">
927						<els.Input
928							key="new-room"
929							label="new room"
930							placeholder="task"
931							submitLabel="start"
932							autoFocus
933							onSubmit={(task) => {
934								if (!task.trim()) return
935								isComposing = false
936								starting($, task.trim())
937								$.command
938									.run({ command: SKILL, args: task.trim() })
939									.catch((err) => {
940										starting($, "")
941										$.ui.toast(`peer: ${String(err).slice(0, 200)}`)
942									})
943							}}
944						/>
945					</Box>
946				) : (
947					<Box>
948						<Button
949							key="new-room"
950							label="+ new room"
951							hotkey="n"
952							variant="secondary"
953							onPress={async () => {
954								const { isFilled } = await $.prompt.fill({ text: `/${SKILL} ` })
955								if (!isFilled) $.ui.toast(`peer: type /${SKILL} TASK`)
956							}}
957						/>
958					</Box>
959				)
960		if (!room) {
961			return (
962				<Box flexDirection="column" gap={1}>
963					<Text dimColor>
964						No active peer room in this checkout. Start one with /peer:peer
965						TASK.
966					</Text>
967					{starter}
968					{st.watchError && <Text color="red">{st.watchError}</Text>}
969					{Object.entries(st.ackErrors).map(([id, text]) => (
970						<Text key={`ack-${id}`} color="red">
971							{text}
972						</Text>
973					))}
974				</Box>
975			)
976		}
977		const active = activeRooms(st)
978		const isOpen = !room.ended_at
979		const all = st.messages[room.id] ?? []
980		// A kicked member keeps its tab, ○, for its log.
981		const others = room.members.filter((m) => m.role !== "main")
982		// A member's tab from another room shows this room's chat.
983		const isTab = st.tab === BOARDS || others.some((m) => m.role === st.tab)
984		const shown = isTab ? st.tab : "chat"
985		const pending = st.confirm
986
987		// armed draws a button that acts on its second press: the first turns
988		// it into confirm, and three seconds without the second turn it back.
989		const armed = (
990			what: string,
991			key: string,
992			label: string,
993			hotkey: string,
994			argv: string[],
995		) =>
996			pending === what ? (
997				<Button
998					key={key}
999					label="confirm"
1000					hotkey={hotkey}
1001					variant="primary"
1002					onPress={async () => {
1003						await put($, confirm, () => null)
1004						const { exitCode, stderr } = await peer($, argv)
1005						if (exitCode !== 0) $.ui.toast(`peer: ${stderr.trim()}`)
1006					}}
1007				/>
1008			) : (
1009				<Button
1010					key={key}
1011					label={label}
1012					hotkey={hotkey}
1013					variant="secondary"
1014					onPress={async () => {
1015						await put($, confirm, () => what)
1016						$.clock.after(
1017							3000,
1018							() => void put($, confirm, (now) => (now === what ? null : now)),
1019						)
1020					}}
1021				/>
1022			)
1023
1024		// One row: the chat, the boards, a tab per member and, at the right, the
1025		// new room and end buttons; the new room button shows the field. A member's tab shows its log.
1026		const pick = (one: string) => async () => {
1027			replay = null
1028			await put($, tab, () => one)
1029			if (one === "chat") toNewest($)
1030			else if (one === BOARDS) await loadBoards($, room)
1031			else await loadLog($, room)
1032		}
1033		// Every tab is a button of one size, so a switch moves nothing; the
1034		// dot is part of the label, so it is pressed with the rest: ● runs, ○
1035		// has stopped, as every member of an ended room has.
1036		const dot = (isOn: boolean) => (isOn ? "●" : "○")
1037		const boardList = boardViews[room.id]
1038		const header = (
1039			<Box flexDirection="column" gap={1}>
1040				{active.length > 1 && "Select" in els && (
1041					<els.Select
1042						key="room"
1043						label="room"
1044						value={room.id}
1045						options={active.map((one) => ({ value: one.id }))}
1046						onSelect={(value) => put($, selected, () => value)}
1047					/>
1048				)}
1049				<Box gap={1} flexWrap="wrap">
1050					<Button
1051						key="tab-chat"
1052						label={`${dot(isOpen)} chat`}
1053						hotkey="1"
1054						variant={shown === "chat" ? "primary" : "secondary"}
1055						onPress={pick("chat")}
1056					/>
1057					<Button
1058						key="tab-boards"
1059						label="boards"
1060						hotkey="2"
1061						variant={shown === BOARDS ? "primary" : "secondary"}
1062						onPress={pick(BOARDS)}
1063					/>
1064					{others.map((m, i) => (
1065						<Button
1066							key={`tab-${m.role}`}
1067							label={`${dot(isOpen && !m.exited && !m.kicked)} ${m.role}`}
1068							hotkey={i < 7 ? String(i + 3) : undefined}
1069							variant={shown === m.role ? "primary" : "secondary"}
1070							onPress={pick(m.role)}
1071						/>
1072					))}
1073					<Box flexGrow={1} />
1074					{"Input" in els && (
1075						<Button
1076							key="new-room-open"
1077							label="+ new room"
1078							hotkey="n"
1079							variant={isComposing ? "primary" : "secondary"}
1080							onPress={() => {
1081								isComposing = !isComposing
1082								$.ui.invalidate("ui.render")
1083							}}
1084						/>
1085					)}
1086					{isOpen &&
1087						armed("end", "end", "⏹ end", "e", ["end", room.id, "--as", "user"])}
1088				</Box>
1089				{(isComposing || startingTask || !("Input" in els)) && starter}
1090				{st.watchError && <Text color="red">{st.watchError}</Text>}
1091				{Object.entries(st.ackErrors).map(([id, text]) => (
1092					<Text key={`ack-${id}`} color="red">
1093						{text}
1094					</Text>
1095				))}
1096			</Box>
1097		)
1098
1099		let body: JSX.Element
1100		if (shown === "chat") {
1101			// Newest first: the chat grows down from the tabs.
1102			const list = all.slice(-60).reverse()
1103			body = (
1104				<Box flexDirection="column" gap={1}>
1105					{e.surface !== "terminal" && "Svg" in els && list.length > 0 && (
1106						<els.Svg
1107							source={timeline(room, list)}
1108							alt={`Message timeline of ${room.id}`}
1109						/>
1110					)}
1111					{list.length === 0 && <Text dimColor>No messages yet.</Text>}
1112					{groups(list).map((group) =>
1113						group.notices ? (
1114							// One line reads in time order, though the lines run newest first.
1115							<Box key={`notice-${group.notices[0]?.id}`} gap={1}>
1116								<Text dimColor>
1117									{clock(group.notices[group.notices.length - 1]?.at ?? "")}
1118								</Text>
1119								<Text dimColor>
1120									{clip(
1121										[...group.notices]
1122											.reverse()
1123											.map((m) => m.text)
1124											.join(" · "),
1125										2000,
1126									)}
1127								</Text>
1128							</Box>
1129						) : (
1130							message(group.message)
1131						),
1132					)}
1133				</Box>
1134			)
1135		} else if (shown === BOARDS) {
1136			body = (
1137				<Box flexDirection="column" gap={1}>
1138					{boardList?.error && <Text color="red">{boardList.error}</Text>}
1139					{boardList?.boards.length === 0 && (
1140						<Text dimColor>
1141							No boards in this room yet. Agents make one with peer board
1142							create.
1143						</Text>
1144					)}
1145					{boardList?.boards.map((view) => boardCard(view))}
1146					{(boardList?.boards.length ?? 0) > 0 && (
1147						<Text dimColor>If a link does not open, start `peer`.</Text>
1148					)}
1149				</Box>
1150			)
1151		} else {
1152			const member = room.members.find((m) => m.role === shown)
1153			const steps = editSteps(st.log)
1154			const isReplaying = replay?.role === shown && steps.length > 0
1155			body = (
1156				<Box flexDirection="column" gap={1}>
1157					{member && (
1158						<Box gap={1}>
1159							<Text dimColor>
1160								{[member.agent, member.model, member.effort]
1161									.filter(Boolean)
1162									.join(" / ") || "joined by hand"}{" "}
1163								· {state(member)}
1164								{member.worktree ? ` · worktree ${member.worktree}` : ""}
1165								{member.branch ? ` · ${member.branch}` : ""}
1166							</Text>
1167							<Box flexGrow={1} />
1168							{steps.length > 0 && (
1169								<Button
1170									key="replay"
1171									label={isReplaying ? "log" : `replay ${steps.length} edits`}
1172									hotkey="r"
1173									variant={isReplaying ? "primary" : "secondary"}
1174									onPress={() => {
1175										replay = isReplaying ? null : { role: shown, index: 0 }
1176										$.ui.invalidate("ui.render")
1177									}}
1178								/>
1179							)}
1180							{isOpen &&
1181								!member.kicked &&
1182								armed(`kick:${member.role}`, "kick", "kick", "k", [
1183									"kick",
1184									room.id,
1185									member.role,
1186									"--as",
1187									"user",
1188								])}
1189						</Box>
1190					)}
1191					{isReplaying && member && replayView(room, member, steps)}
1192					{st.log.length === 0 && <Text dimColor>No log yet.</Text>}
1193					{!isReplaying &&
1194						st.log
1195							.slice(-80)
1196							.reverse()
1197							.map((entry, i) => (
1198								// biome-ignore lint/suspicious/noArrayIndexKey: log entries have no id; the list is redrawn whole.
1199								<Box key={`log-${i}`} gap={1}>
1200									<Text dimColor>
hooks/board-preview.ts 803 lines
1import type { PeerBoard, PeerBoardNode } from "../types"
2
3// SVG_LIMIT is the most characters the Svg element takes.
4const SVG_LIMIT = 131_072
5// The schematic is drawn 1:1 up to WIDTH px, then scaled down to it.
6const WIDTH = 720
7const PAD = 12
8const GAP = 16
9// LABEL_GAP parts two layers that a labeled edge joins, so the label sits
10// between them and not on a box.
11const LABEL_GAP = 30
12const FONT = 11
13const LINE = 14
14const HEADER = 22
15const CARD_W = 160
16const CARD_PAD = 8
17const MAX_LINES = 4
18// An average sans-serif glyph is about 0.6 em wide.
19const GLYPH = FONT * 0.6
20const CARD_FILL: Record<string, string> = {
21	gray: "#8883",
22	yellow: "#e5c07b66",
23	green: "#98c37966",
24	blue: "#4c8dff55",
25	purple: "#b48cff55",
26	red: "#e0606066",
27}
28
29type Box = { x: number; y: number; w: number; h: number }
30
31// label is a node's first line: a card's text, an image's caption or a
32// frame's title.
33function label(node: PeerBoardNode) {
34	const text = node.text ?? node.caption ?? node.title ?? ""
35	const first = text.split("\n")[0]?.trim() || node.type
36
37	return fit(first, 40)
38}
39
40// fit cuts text to n glyphs, ending a cut line with "…". Glyphs are code
41// points, so a cut never splits a surrogate pair.
42function fit(text: string, n: number) {
43	const glyphs = Array.from(text)
44
45	return glyphs.length > n
46		? `${glyphs.slice(0, Math.max(0, n - 1)).join("")}…`
47		: text
48}
49
50// wrap breaks a card's text into lines of at most n glyphs, by words, and
51// keeps MAX_LINES of them; a cut ends with "…".
52function wrap(text: string, n: number) {
53	const lines: string[][] = []
54	for (const paragraph of text.split("\n")) {
55		let line: string[] = []
56		for (const word of paragraph.split(/\s+/).filter(Boolean)) {
57			let rest = Array.from(word)
58			while (rest.length > 0) {
59				const room = line.length > 0 ? n - line.length - 1 : n
60				if (rest.length <= room) {
61					line = line.length > 0 ? [...line, " ", ...rest] : rest
62					rest = []
63				} else if (line.length > 0) {
64					lines.push(line)
65					line = []
66				} else {
67					lines.push(rest.slice(0, n))
68					rest = rest.slice(n)
69				}
70			}
71		}
72		lines.push(line)
73	}
74	while (lines.length > 1 && lines.at(-1)?.length === 0) lines.pop()
75	const kept = lines.slice(0, MAX_LINES)
76	if (lines.length > MAX_LINES) {
77		kept[MAX_LINES - 1] = [...(kept[MAX_LINES - 1] ?? []).slice(0, n - 1), "…"]
78	}
79
80	return kept.map((line) => line.join(""))
81}
82
83// ranks gives each item its layer: the longest path to it along the
84// links. A link that closes a cycle is skipped, so a cycle still ends.
85function ranks(ids: string[], links: [string, string][]) {
86	const out = new Map(ids.map((id) => [id, [] as string[]]))
87	for (const [from, to] of links) {
88		if (from !== to) out.get(from)?.push(to)
89	}
90	const state = new Map<string, "open" | "done">()
91	const kept = new Map(ids.map((id) => [id, [] as string[]]))
92	const order: string[] = []
93	const visit = (id: string) => {
94		state.set(id, "open")
95		for (const to of out.get(id) ?? []) {
96			if (state.get(to) === "open") continue
97			kept.get(id)?.push(to)
98			if (!state.has(to)) visit(to)
99		}
100		state.set(id, "done")
101		order.push(id)
102	}
103	for (const id of ids) if (!state.has(id)) visit(id)
104
105	const rank = new Map(ids.map((id) => [id, 0]))
106	for (const id of order.reverse()) {
107		for (const to of kept.get(id) ?? []) {
108			rank.set(to, Math.max(rank.get(to) ?? 0, (rank.get(id) ?? 0) + 1))
109		}
110	}
111
112	return rank
113}
114
115// schematic lays the board out without its stored geometry, so a board
116// nobody opened in the browser still has a picture: each frame holds its
117// children in layers along the edges between them, a layer wraps when it
118// is wider than the drawing, and the top frames go by order.
119function schematic(board: PeerBoard) {
120	const byId = new Map(board.nodes.map((node) => [node.id, node]))
121	const parentOf = (node: PeerBoardNode) =>
122		node.parentId && byId.get(node.parentId)?.type === "frame"
123			? node.parentId
124			: ""
125	const kids = new Map<string, PeerBoardNode[]>()
126	for (const node of board.nodes) {
127		const list = kids.get(parentOf(node)) ?? []
128		list.push(node)
129		kids.set(parentOf(node), list)
130	}
131	// lift gives the ancestor of id that is a direct child of container.
132	const lift = (id: string, container: string) => {
133		const seen = new Set<string>()
134		for (let node = byId.get(id); node && !seen.has(node.id); ) {
135			seen.add(node.id)
136			const parent = parentOf(node)
137			if (parent === container) return node.id
138			if (parent === "") return null
139			node = byId.get(parent)
140		}
141		return null
142	}
143	const open = openThreads(board)
144	const lines = new Map<string, string[]>()
145	const size = new Map<string, { w: number; h: number }>()
146	const rel = new Map<string, { x: number; y: number }>()
147	const arrange = (container: string, depth: number) => {
148		const own = (kids.get(container) ?? []).filter((node) => !size.has(node.id))
149		const items = [
150			...own
151				.filter((node) => node.type === "frame")
152				.sort((a, b) => (a.order ?? 0) - (b.order ?? 0)),
153			...own.filter((node) => node.type !== "frame"),
154		]
155		for (const node of items) {
156			if (node.type === "frame") {
157				size.set(node.id, { w: 0, h: 0 })
158				const inner = arrange(node.id, depth + 1)
159				// A labeled loop on a card in the frame gets room on the right.
160				const loops = board.edges
161					.filter(
162						(edge) =>
163							edge.label &&
164							edge.from === edge.to &&
165							byId.get(edge.from)?.type !== "frame" &&
166							parentOf(byId.get(edge.from) as PeerBoardNode) === node.id,
167					)
168					.map(
169						(edge) =>
170							14 + Math.min(40, Array.from(edge.label ?? "").length) * 6,
171					)
172				size.set(node.id, {
173					w: Math.max(inner.w + 2 * PAD + Math.max(0, ...loops), CARD_W),
174					h: HEADER + inner.h + PAD,
175				})
176			} else {
177				const text =
178					node.type === "image" ? node.caption || "image" : (node.text ?? "")
179				const wrapped = wrap(text, Math.floor((CARD_W - 2 * CARD_PAD) / GLYPH))
180				lines.set(node.id, wrapped)
181				// A card with open threads keeps a row under its text for the badge.
182				const badge = open.has(node.id) ? LINE : 0
183				size.set(node.id, {
184					w: CARD_W,
185					h: wrapped.length * LINE + 2 * CARD_PAD + badge,
186				})
187			}
188		}
189		const ids = items.map((node) => node.id)
190		const links: [string, string][] = []
191		const labeled: [string, string][] = []
192		for (const edge of board.edges) {
193			const from = lift(edge.from, container)
194			const to = lift(edge.to, container)
195			if (from && to) links.push([from, to])
196			if (from && to && edge.label) labeled.push([from, to])
197		}
198		const rank = ranks(ids, links)
199		const roomy = new Set(
200			labeled
201				.filter(([a, b]) => rank.get(a) !== rank.get(b))
202				.map(([a, b]) => Math.min(rank.get(a) ?? 0, rank.get(b) ?? 0)),
203		)
204		const layers: string[][] = []
205		for (const id of ids) {
206			const r = rank.get(id) ?? 0
207			layers[r] = [...(layers[r] ?? []), id]
208		}
209		const row = Math.max(CARD_W, WIDTH - 2 * PAD * (depth + 1))
210		// A labeled edge between a frame and its own content gets a row under
211		// the title bar for its label.
212		const extra =
213			container &&
214			board.edges.some(
215				(edge) =>
216					edge.label &&
217					((edge.from === container && lift(edge.to, container)) ||
218						(edge.to === container && lift(edge.from, container))),
219			)
220				? 14
221				: 0
222		const left = container ? PAD : 0
223		const top = container ? HEADER + extra : 0
224		let y = 0
225		let w = 0
226		for (const [r, layer] of layers.entries()) {
227			if (!layer) continue
228			let x = 0
229			let tall = 0
230			for (const id of layer) {
231				const s = size.get(id) ?? { w: 0, h: 0 }
232				if (x > 0 && x + s.w > row) {
233					y += tall + GAP
234					x = 0
235					tall = 0
236				}
237				rel.set(id, { x: left + x, y: top + y })
238				x += s.w + GAP
239				tall = Math.max(tall, s.h)
240				w = Math.max(w, x - GAP)
241			}
242			y += tall + (roomy.has(r) ? LABEL_GAP : GAP)
243		}
244		y -= roomy.has(layers.length - 1) ? LABEL_GAP : GAP
245
246		return { w, h: Math.max(0, y) + extra }
247	}
248	const whole = arrange("", 0)
249	const boxes = new Map<string, Box>()
250	const place = (node: PeerBoardNode): Box | null => {
251		const known = boxes.get(node.id)
252		if (known) return known
253		const at = rel.get(node.id)
254		const s = size.get(node.id)
255		if (!at || !s) return null
256		const parent = parentOf(node)
257		const origin = parent ? place(byId.get(parent) as PeerBoardNode) : null
258		const box = {
259			x: (origin?.x ?? 0) + at.x,
260			y: (origin?.y ?? 0) + at.y,
261			w: s.w,
262			h: s.h,
263		}
264		boxes.set(node.id, box)
265
266		return box
267	}
268	for (const node of board.nodes) place(node)
269
270	return { boxes, lines, whole, open }
271}
272
273type Point = { x: number; y: number }
274
275// openThreads counts the open threads on each frame, node and edge by its
276// id; a thread counts on its own target only.
277function openThreads(board: PeerBoard) {
278	const open = new Map<string, number>()
279	for (const thread of board.threads) {
280		const id = thread.target.id
281		if (!thread.resolved && id) open.set(id, (open.get(id) ?? 0) + 1)
282	}
283
284	return open
285}
286
287const center = (b: Box): Point => ({ x: b.x + b.w / 2, y: b.y + b.h / 2 })
288
289// reach is the step along d from at to the side of [lo, hi] it heads to.
290function reach(d: number, lo: number, hi: number, at: number) {
291	if (d > 0) return (hi - at) / d
292	if (d < 0) return (lo - at) / d
293
294	return Number.POSITIVE_INFINITY
295}
296
297// exit is where the line from o, a point in box b, toward p leaves b.
298function exit(b: Box, o: Point, p: Point) {
299	const dx = p.x - o.x
300	const dy = p.y - o.y
301	const t = Math.min(
302		reach(dx, b.x, b.x + b.w, o.x),
303		reach(dy, b.y, b.y + b.h, o.y),
304		1,
305	)
306
307	return { x: o.x + dx * t, y: o.y + dy * t }
308}
309
310// crosses tells whether the segment from p to q passes through the inside
311// of box b (Liang–Barsky clipping on b shrunk by one unit).
312function crosses(p: Point, q: Point, b: Box) {
313	let lo = 0
314	let hi = 1
315	const dx = q.x - p.x
316	const dy = q.y - p.y
317	const sides: [number, number][] = [
318		[-dx, p.x - (b.x + 1)],
319		[dx, b.x + b.w - 1 - p.x],
320		[-dy, p.y - (b.y + 1)],
321		[dy, b.y + b.h - 1 - p.y],
322	]
323	for (const [n, d] of sides) {
324		if (n === 0) {
325			if (d < 0) return false
326		} else if (n < 0) {
327			lo = Math.max(lo, d / n)
328		} else {
329			hi = Math.min(hi, d / n)
330		}
331	}
332
333	return lo < hi
334}
335
336const round = (n: number) => Math.round(n * 10) / 10
337
338// overlaps tells whether boxes a and b share some area.
339const overlaps = (a: Box, b: Box) =>
340	a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
341
342// inside tells whether box a lies within box b.
343const inside = (a: Box, b: Box) =>
344	a.x >= b.x && a.y >= b.y && a.x + a.w <= b.x + b.w && a.y + a.h <= b.y + b.h
345
346// boardSvg draws the board's schematic: frames as titled boxes, cards and
347// images with their wrapped text clipped to the box, and edges as arrows
348// between the boxes' borders. Edges between one pair of boxes are drawn
349// side by side; an edge that would cross another card goes around it on
350// the right; a loop is an arc on its box. Each box and edge has a <title>
351// with its full text for a reader of the markup, and an open thread a
352// "💬 N" badge. The stored
353// positions are not used. A drawing over the Svg limit keeps the frames
354// only; null for an empty board or when even the frames do not fit.
355export function boardSvg(board: PeerBoard): string | null {
356	if (board.nodes.length === 0) return null
357
358	const { boxes, lines, whole, open } = schematic(board)
359	const badge = (id: string) => (open.has(id) ? `💬 ${open.get(id)}` : "")
360	const frame = (node: PeerBoardNode, i: number) => {
361		const b = boxes.get(node.id) as Box
362		const mark = badge(node.id)
363		// The badge has a fixed slot at the right of the title bar; the title
364		// is clipped before it.
365		const slot = b.x + b.w - PAD
366		const room = mark ? slot - 40 - (b.x + PAD) : b.w - 2 * PAD
367		const title = fit(label(node), Math.floor(room / GLYPH))
368		const count = mark
369			? `<text x="${slot}" y="${b.y + 15}" text-anchor="end" font-size="10" fill="#888">${mark}</text>`
370			: ""
371
372		// A title of wide glyphs is clipped to the frame like a card's text.
373		return `<g><title>${esc(node.title ?? "")}</title><rect x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="6" fill="#8881" stroke="#888"/><clipPath id="f${i}"><rect x="${b.x}" y="${b.y}" width="${b.x + PAD + room - b.x}" height="${HEADER}"/></clipPath><text x="${b.x + PAD}" y="${b.y + 15}" clip-path="url(#f${i})" font-weight="600" fill="#888">${esc(title)}</text>${count}</g>`
374	}
375	const card = (node: PeerBoardNode, i: number) => {
376		const b = boxes.get(node.id) as Box
377		const fill = CARD_FILL[node.color ?? "gray"] ?? "#8883"
378		const dash = node.type === "image" ? ' stroke-dasharray="4 3"' : ""
379		const text = (lines.get(node.id) ?? [])
380			.map(
381				(line, n) =>
382					`<tspan x="${b.x + CARD_PAD}" y="${b.y + CARD_PAD + 11 + n * LINE}">${esc(line)}</tspan>`,
383			)
384			.join("")
385		const full = node.type === "image" ? node.caption : node.text
386		const mark = badge(node.id)
387		const count = mark
388			? `<text x="${b.x + b.w - CARD_PAD}" y="${b.y + b.h - CARD_PAD}" text-anchor="end" font-size="10" fill="#888">${mark}</text>`
389			: ""
390
391		return `<g><title>${esc(full || node.type)}</title><rect x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="6" fill="${fill}" stroke="#888"${dash}/><clipPath id="c${i}"><rect x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}"/></clipPath><text clip-path="url(#c${i})" fill="#888">${text}</text>${count}</g>`
392	}
393	const shown = board.nodes.filter((node) => boxes.has(node.id))
394	const cardBoxes = shown
395		.filter((node) => node.type !== "frame")
396		.map((node) => [node.id, boxes.get(node.id) as Box] as const)
397	const frameBoxes = shown
398		.filter((node) => node.type === "frame")
399		.map((node) => boxes.get(node.id) as Box)
400	// Edges of one unordered pair are spread across the line between the
401	// pair's centers, measured in the pair's own direction, so an edge and
402	// its reverse do not draw on one line.
403	const pairs = new Map<string, string[]>()
404	for (const edge of board.edges) {
405		const key = [edge.from, edge.to].sort().join(" ")
406		pairs.set(key, [...(pairs.get(key) ?? []), edge.id])
407	}
408	let right = whole.w
409	const tag = (x: number, y: number, text: string, anchor: string, n = 24) =>
410		`<text x="${round(x)}" y="${round(y)}" text-anchor="${anchor}" font-size="10" fill="#888">${esc(fit(text, n))}</text>`
411	type Spot = { x: number; y: number; anchor: "start" | "end" | "middle" }
412	// put draws a label at the first of the spots where it touches no card,
413	// no frame's title bar and no frame's border, cut to fit inside the
414	// frame around the spot; a label with no free spot, or room for less
415	// than six glyphs, is left out, and its edge's <title> keeps it. A
416	// label with a home box stays inside it.
417	const put = (spots: Spot[], text: string, home?: Box) => {
418		for (const spot of spots) {
419			const around = frameBoxes
420				.filter((f) => inside({ ...spot, w: 0, h: 0 }, f))
421				.sort((f, g) => f.w * f.h - g.w * g.h)[0]
422			const lo = around ? around.x + 4 : Number.NEGATIVE_INFINITY
423			const hi = around ? around.x + around.w - 4 : Number.POSITIVE_INFINITY
424			const room = {
425				start: hi - spot.x,
426				end: spot.x - lo,
427				middle: 2 * Math.min(hi - spot.x, spot.x - lo),
428			}[spot.anchor]
429			const cut = fit(text, Math.min(40, Math.floor(room / 6)))
430			const glyphs = Array.from(cut).length
431			if (glyphs < Math.min(6, Array.from(text).length)) continue
432			const w = glyphs * 6
433			const shift = { start: 0, end: w, middle: w / 2 }[spot.anchor]
434			const r = { x: spot.x - shift, y: spot.y - 9, w, h: 11 }
435			const free =
436				(!home || inside(r, home)) &&
437				cardBoxes.every(([, box]) => !overlaps(r, box)) &&
438				frameBoxes.every((f) =>
439					inside(r, f)
440						? !overlaps(r, { x: f.x, y: f.y, w: f.w, h: HEADER })
441						: !overlaps(r, f),
442				)
443			if (free) {
444				right = Math.max(right, r.x + w)
445				return tag(spot.x, spot.y, cut, spot.anchor, 40)
446			}
447		}
448
449		return ""
450	}
451	const byId = new Map(board.edges.map((edge) => [edge.id, edge]))
452	// heading is an arrow for the way an edge runs on the drawing.
453	const heading = (from: Box, to: Box) => {
454		if (inside(to, from)) return "↓"
455		if (inside(from, to)) return "↑"
456		const dx = center(to).x - center(from).x
457		const dy = center(to).y - center(from).y
458		if (Math.abs(dx) > Math.abs(dy)) return dx > 0 ? "→" : "←"
459
460		return dy > 0 ? "↓" : "↑"
461	}
462	// groupLabel is one label for all the edges of a pair, each with the
463	// arrow of its way when there are several, so no two labels overlap.
464	const groupLabel = (group: string[]) => {
465		const labeled = group
466			.map((id) => byId.get(id))
467			.filter((edge) => edge?.label)
468		if (labeled.length === 0) return ""
469		if (group.length === 1) return labeled[0]?.label ?? ""
470
471		return labeled
472			.map(
473				(edge) =>
474					`${heading(boxes.get(edge?.from ?? "") as Box, boxes.get(edge?.to ?? "") as Box)} ${edge?.label}`,
475			)
476			.join(" · ")
477	}
478	const arrow = (points: Point[]) =>
479		points.length === 2
480			? `<line x1="${round(points[0]?.x ?? 0)}" y1="${round(points[0]?.y ?? 0)}" x2="${round(points[1]?.x ?? 0)}" y2="${round(points[1]?.y ?? 0)}" stroke="#888" marker-end="url(#arrow)"/>`
481			: `<polyline points="${points.map((p) => `${round(p.x)},${round(p.y)}`).join(" ")}" fill="none" stroke="#888" marker-end="url(#arrow)"/>`
482	const edges = board.edges.map((edge) => {
483		const a = boxes.get(edge.from)
484		const b = boxes.get(edge.to)
485		if (!a || !b) return ""
486		const title = edge.label ? `<title>${esc(edge.label)}</title>` : ""
487		if (edge.from === edge.to) {
488			// A loop is a small arc low on the box's right side, inside the gap
489			// to the next box or the frame's border; a detour enters higher.
490			const x = a.x + a.w
491			const y = a.y + a.h - 12
492			const loop = `<path d="M${x},${y - 7} C${x + 13},${y - 9} ${x + 13},${y + 9} ${x},${y + 7}" fill="none" stroke="#888" marker-end="url(#arrow)"/>`
493			const home = frameBoxes
494				.filter((f) => f !== a && inside(a, f))
495				.sort((f, g) => f.w * f.h - g.w * g.h)[0]
496			const text = edge.label
497				? put([{ x: x + 14, y: y + 3, anchor: "start" }], edge.label, home)
498				: ""
499
500			return `<g>${title}${loop}${text}</g>`
501		}
502		const [first, second] = [edge.from, edge.to].sort()
503		const group = pairs.get([first, second].join(" ")) ?? []
504		const index = group.indexOf(edge.id)
505		// Edges of a pair are spread 6 units apart, inside the smaller box,
506		// so many edges of one pair still start and end on their boxes.
507		const limit = Math.max(0, Math.min(a.w, a.h, b.w, b.h) / 2 - 4)
508		const spread = (k: number) =>
509			Math.max(-limit, Math.min(limit, (k - (group.length - 1) / 2) * 6))
510		const shift = spread(index)
511		const half = spread(group.length - 1)
512		// Only the pair's first edge draws the pair's label.
513		const label = index === 0 ? groupLabel(group) : ""
514		// A frame and a node inside it: the arrow runs between the frame's
515		// title bar and the node's top.
516		if (inside(b, a) || inside(a, b)) {
517			const inner = inside(b, a) ? b : a
518			const outer = inner === b ? a : b
519			const x = inner.x + inner.w / 2 + shift
520			const bar = { x, y: outer.y + HEADER - 2 }
521			const top = { x, y: inner.y }
522			const points = inner === b ? [bar, top] : [top, bar]
523			const y = (bar.y + top.y) / 2 + 3
524			const middle = inner.x + inner.w / 2
525			const text = label
526				? put(
527						[
528							{ x: middle + half + 4, y, anchor: "start" },
529							{ x: middle - half - 4, y, anchor: "end" },
530						],
531						label,
532					)
533				: ""
534
535			return `<g>${title}${arrow(points)}${text}</g>`
536		}
537		const p = center(boxes.get(first ?? "") as Box)
538		const q = center(boxes.get(second ?? "") as Box)
539		const length = Math.hypot(q.x - p.x, q.y - p.y) || 1
540		const normal = { x: -(q.y - p.y) / length, y: (q.x - p.x) / length }
541		const ca = {
542			x: center(a).x + normal.x * shift,
543			y: center(a).y + normal.y * shift,
544		}
545		const cb = {
546			x: center(b).x + normal.x * shift,
547			y: center(b).y + normal.y * shift,
548		}
549		const from = exit(a, ca, cb)
550		const to = exit(b, cb, ca)
551		const others = cardBoxes.filter(
552			([id]) => id !== edge.from && id !== edge.to,
553		)
554		const blocked = others.filter(([, box]) => crosses(from, to, box))
555		if (blocked.length > 0) {
556			// Around on the right: out of a's right side, down a lane right of
557			// everything in the way and of the frames around it, into b's
558			// right side. Each edge of the pair has its own lane and rows.
559			const near = [a, b, ...blocked.map(([, box]) => box)]
560			const lane =
561				Math.max(
562					...near.map((box) => box.x + box.w),
563					...frameBoxes
564						.filter((f) => near.some((box) => inside(box, f)))
565						.map((f) => f.x + f.w),
566				) +
567				10 +
568				index * 6
569			// It leaves and enters near the boxes' tops, clear of a loop low
570			// on their right side.
571			const ya = a.y + 5 + Math.min(index * 6, a.h / 2 - 8)
572			const yb = b.y + 5 + Math.min(index * 6, b.h / 2 - 8)
573			const points = [
574				{ x: a.x + a.w, y: ya },
575				{ x: lane, y: ya },
576				{ x: lane, y: yb },
577				{ x: b.x + b.w, y: yb },
578			]
579			const clear = points
580				.slice(1)
581				.every((pt, n) =>
582					others.every(([, box]) => !crosses(points[n] as Point, pt, box)),
583				)
584			if (clear) {
585				right = Math.max(right, lane + 4)
586				const at = lane + (group.length - 1 - index) * 6 + 4
587				const y = (center(a).y + center(b).y) / 2
588				const text = label ? put([{ x: at, y, anchor: "start" }], label) : ""
589
590				return `<g>${title}${arrow(points)}${text}</g>`
591			}
592		}
593		// The pair's label sits beside the bundle of its lines: right of a
594		// steep one, over a flat one.
595		const base = {
596			x:
597				(exit(a, center(a), center(b)).x + exit(b, center(b), center(a)).x) / 2,
598			y:
599				(exit(a, center(a), center(b)).y + exit(b, center(b), center(a)).y) / 2,
600		}
601		const steep = Math.abs(q.y - p.y) >= Math.abs(q.x - p.x)
602		const spots: Spot[] = steep
603			? [
604					{ x: base.x + half + 4, y: base.y + 3, anchor: "start" },
605					{ x: base.x - half - 4, y: base.y + 3, anchor: "end" },
606				]
607			: [
608					{ x: base.x, y: base.y - half - 4, anchor: "middle" },
609					{ x: base.x, y: base.y + half + 12, anchor: "middle" },
610				]
611		const text = label ? put(spots, label) : ""
612
613		return `<g>${title}${arrow([from, to])}${text}</g>`
614	})
615	const width = right + 2 * PAD
616	const height = whole.h + 2 * PAD
617	const shownWidth = Math.min(WIDTH, width)
618	const shownHeight = Math.max(40, Math.round((shownWidth * height) / width))
619	const svg = (body: string) =>
620		`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${-PAD} ${-PAD} ${width} ${height}" width="${shownWidth}" height="${shownHeight}" font-family="sans-serif" font-size="${FONT}"><defs><marker id="arrow" viewBox="0 0 8 8" refX="8" refY="4" markerWidth="6" markerHeight="6" orient="auto"><path d="M0,0L8,4L0,8z" fill="#888"/></marker></defs>${body}</svg>`
621	const frames = shown.filter((node) => node.type === "frame").map(frame)
622	const cards = shown.filter((node) => node.type !== "frame").map(card)
623	const full = svg([...frames, ...edges, ...cards].join(""))
624	if (full.length <= SVG_LIMIT) return full
625
626	const framesOnly = svg(frames.join(""))
627
628	return framesOnly.length <= SVG_LIMIT ? framesOnly : null
629}
630
631// boardStats counts a board's frames, its cards and images, and its open
632// threads, for the line under the board's title.
633export function boardStats(board: PeerBoard) {
634	const frames = board.nodes.filter((node) => node.type === "frame").length
635	const nodes = board.nodes.length - frames
636	const threads = board.threads.filter((thread) => !thread.resolved).length
637
638	return `${plural(frames, "frame")} · ${plural(nodes, "node")} · ${plural(threads, "open thread")}`
639}
640
641// frameLines lists the frames by order, each with its count of direct
642// child nodes and of open threads on the frame and those nodes, then the
643// nodes outside any frame.
644export function frameLines(board: PeerBoard) {
645	const open = board.threads.filter((thread) => !thread.resolved)
646	const frames = board.nodes
647		.filter((node) => node.type === "frame")
648		.sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
649	const lines = frames.map((frame) => {
650		const children = board.nodes.filter((node) => node.parentId === frame.id)
651		const ids = new Set([frame.id, ...children.map((node) => node.id)])
652		const threads = open.filter(
653			(thread) => thread.target.id && ids.has(thread.target.id),
654		).length
655
656		return `${label(frame)} · ${plural(children.length, "node")} · ${plural(threads, "open thread")}`
657	})
658	const loose = board.nodes.filter(
659		(node) => node.type !== "frame" && !node.parentId,
660	).length
661	if (loose > 0) lines.push(`${plural(loose, "node")} outside frames`)
662
663	return lines
664}
665
666// RASTER_FILL is a card's color as a terminal cell's background, the
667// schematic's fill without its alpha.
668const RASTER_FILL: Record<string, number> = {
669	gray: 0x4a4a4a,
670	yellow: 0xe5c07b,
671	green: 0x98c379,
672	blue: 0x4c8dff,
673	purple: 0xb48cff,
674	red: 0xe06060,
675}
676// DEFAULT is the terminal's own color in a Raster cell.
677const DEFAULT = 0x01000000
678const RASTER_ROWS = 24
679
680// boardRaster draws the schematic as terminal cells, columns wide: frames
681// as boxes with their titles, cards as blocks of their color with their
682// first line. A cell is half as wide as it is tall, so rows are half the
683// columns' scale. It returns null for an empty board.
684export function boardRaster(board: PeerBoard, columns: number) {
685	if (board.nodes.length === 0) return null
686	const { boxes, whole } = schematic(board)
687	if (whole.w <= 0 || whole.h <= 0) return null
688	const sx = (columns - 1) / whole.w
689	const sy = Math.min(sx / 2, (RASTER_ROWS - 1) / whole.h)
690	const rows = Math.max(1, Math.ceil(whole.h * sy) + 1)
691	const glyph = new Uint32Array(columns * rows).fill(0x20)
692	const fg = new Uint32Array(columns * rows).fill(DEFAULT)
693	const bg = new Uint32Array(columns * rows).fill(DEFAULT)
694	const put = (c: number, r: number, code: number, color = DEFAULT) => {
695		if (c < 0 || r < 0 || c >= columns || r >= rows) return
696		glyph[r * columns + c] = code
697		fg[r * columns + c] = color
698	}
699	const write = (
700		c: number,
701		r: number,
702		text: string,
703		n: number,
704		color: number,
705	) => {
706		for (const [i, ch] of Array.from(fit(text, n)).entries())
707			put(c + i, r, cell(ch), color)
708	}
709	const span = (b: Box) => {
710		const c0 = Math.floor(b.x * sx)
711		const r0 = Math.floor(b.y * sy)
712		return {
713			c0,
714			r0,
715			c1: Math.max(c0 + 1, Math.floor((b.x + b.w) * sx)),
716			r1: Math.max(r0, Math.floor((b.y + b.h) * sy)),
717		}
718	}
719	// Outer frames first, so a nested frame and the cards draw over them.
720	const frames = board.nodes
721		.filter((node) => node.type === "frame" && boxes.has(node.id))
722		.sort((a, b) => {
723			const p = boxes.get(a.id) as Box
724			const q = boxes.get(b.id) as Box
725			return q.w * q.h - p.w * p.h
726		})
727	for (const node of frames) {
728		const { c0, r0, c1, r1 } = span(boxes.get(node.id) as Box)
729		for (let c = c0 + 1; c < c1; c++) {
730			put(c, r0, 0x2500, 0x888888)
731			put(c, r1, 0x2500, 0x888888)
732		}
733		for (let r = r0 + 1; r < r1; r++) {
734			put(c0, r, 0x2502, 0x888888)
735			put(c1, r, 0x2502, 0x888888)
736		}
737		put(c0, r0, 0x250c, 0x888888)
738		put(c1, r0, 0x2510, 0x888888)
739		put(c0, r1, 0x2514, 0x888888)
740		put(c1, r1, 0x2518, 0x888888)
741		write(c0 + 2, r0, label(node), c1 - c0 - 3, 0xbbbbbb)
742	}
743	for (const node of board.nodes) {
744		const b = boxes.get(node.id)
745		if (node.type === "frame" || !b) continue
746		const { c0, r0, c1, r1 } = span(b)
747		const fill = RASTER_FILL[node.color ?? "gray"] ?? 0x4a4a4a
748		const ink = fill === 0x4a4a4a ? 0xeeeeee : 0x111111
749		for (let r = r0; r <= Math.max(r0, r1 - 1); r++)
750			for (let c = c0; c < c1; c++) {
751				put(c, r, 0x20)
752				if (c < columns && r < rows) bg[r * columns + c] = fill
753			}
754		write(c0, r0, label(node), c1 - c0, ink)
755	}
756	const words = new Uint32Array(columns * rows * 3)
757	for (let i = 0; i < columns * rows; i++) {
758		words[i * 3] = glyph[i] ?? 0x20
759		words[i * 3 + 1] = fg[i] ?? DEFAULT
760		words[i * 3 + 2] = bg[i] ?? DEFAULT
761	}
762	return { columns, rows, cells: base64(new Uint8Array(words.buffer)) }
763}
764
765// cell gives a glyph a Raster takes, one printable width-1 BMP character:
766// Latin, Greek, Cyrillic, punctuation and arrows are kept, the rest,
767// such as CJK and emoji, show as "?".
768function cell(ch: string) {
769	const code = ch.codePointAt(0) ?? 0x3f
770	const isKept =
771		(code >= 0x20 && code <= 0x7e) ||
772		(code >= 0xa0 && code <= 0x24ff && !(code >= 0x300 && code <= 0x36f))
773
774	return isKept ? code : 0x3f
775}
776
777const BASE64 =
778	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
779
780// base64 encodes bytes as standard padded base64, which a Raster's cells are.
781function base64(bytes: Uint8Array) {
782	let out = ""
783	for (let i = 0; i < bytes.length; i += 3) {
784		const a = bytes[i] ?? 0
785		const b = bytes[i + 1] ?? 0
786		const c = bytes[i + 2] ?? 0
787		out += BASE64[a >> 2]
788		out += BASE64[((a & 3) << 4) | (b >> 4)]
789		out += i + 1 < bytes.length ? BASE64[((b & 15) << 2) | (c >> 6)] : "="
790		out += i + 2 < bytes.length ? BASE64[c & 63] : "="
791	}
792
793	return out
794}
795
796function plural(n: number, noun: string) {
797	return `${n} ${noun}${n === 1 ? "" : "s"}`
798}
799
800function esc(text: string) {
801	return text.replace(/[<>&"]/g, (c) => `&#${c.charCodeAt(0)};`)
802}
803
types/index.d.ts 103 lines
1export type PeerMember = {
2	role: string
3	agent?: string
4	exited?: boolean
5	worker?: boolean
6	model?: string
7	effort?: string
8	worktree?: string
9	branch?: string
10	base?: string
11	kicked?: boolean
12	pid?: number
13	unread?: number
14}
15
16export type PeerRoom = {
17	id: string
18	repo: string
19	members: PeerMember[]
20	started_at: string
21	ended_at?: string
22	ended_reason?: string
23}
24
25export type PeerMessage = {
26	id: string
27	at: string
28	from: string
29	to: string
30	text: string
31}
32
33export type PeerLogEntry = { at?: string; kind: string; text: string }
34
35export type PeerMark = { id: string; at: string }
36
37// PeerBoardRef is one entry of `peer board list`; see docs/BOARD_API.md.
38export type PeerBoardRef = {
39	key: string
40	path: string
41	url: string
42	title?: string
43	revision?: number
44	rooms?: string[]
45	mtime?: string
46	error?: { error: string; message?: string }
47}
48
49// PeerBoard is the part of board.json the preview draws.
50export type PeerBoard = {
51	title: string
52	nodes: PeerBoardNode[]
53	edges: { id: string; from: string; to: string; label?: string }[]
54	threads: {
55		target: { kind: string; id?: string }
56		resolved: boolean
57	}[]
58}
59
60export type PeerBoardNode = {
61	id: string
62	type: "card" | "image" | "frame"
63	parentId?: string
64	text?: string
65	color?: string
66	caption?: string
67	title?: string
68	order?: number
69	x?: number
70	y?: number
71	w?: number
72	h?: number
73}
74
75export type PeerState = {
76	rooms: Record<string, PeerRoom>
77	messages: Record<string, PeerMessage[]>
78	selected: string | null
79	// 'chat', ':boards', or the role whose log the pane shows.
80	tab: string
81	confirm: string | null
82	led: string[]
83	// own lists the rooms of this session, the only ones the plugin shows:
84	// started or led here, or joined from here; a room stays once it ends.
85	own: string[]
86	watchError: string | null
87	// ackErrors holds, per led room, why main's cursor could not move.
88	ackErrors: Record<string, string>
89	log: PeerLogEntry[]
90	delivered: Record<string, PeerMark | null>
91	notified: string[]
92	// Pane: messages shown whole, and messages per room when the pane was
93	// last on screen.
94	expanded: string[]
95	seen: Record<string, number>
96}
97
98declare module "claude-code" {
99	interface PluginState {
100		peer: { state: PeerState }
101	}
102}
103