The all-in-one Claude Code plugin. Talk with your squad, share code, and keep live rooms (usage, git, weather, lo-fi and more) next to your session. Zero…

See which friends are online and chat with them in a side pane while you work in Claude Code. Chat never reaches Claude: it isn't in the conversation and uses no model tokens.

In Claude Code:
/plugin install squad-chat --marketplace chrisluo5311/squad-chat
Then /reload-plugins (or restart Claude Code), and connect to your squad's server (below). Or from a shell:
claude plugin marketplace add chrisluo5311/squad-chat
claude plugin install squad-chat@squad-chat
Requires:
PATH (node --version). squad-chat tells you if it's missing or too old.Each group of friends shares its own free Supabase project. Get its URL and publishable key from whoever hosts it, or host one yourself (instructions). Then set them in /config under squad-chat, or:
echo '{"supabase_url":"https://abcd1234.supabase.co","supabase_key":"sb_publishable_..."}' \
| claude plugin configure squad-chat@squad-chat --values-stdin
/chat opens the pane./room our-team some-passcode in the pane. Friends join with the same line.Before your chat rooms, built-in tabs need no server or sign-in: Usage (context, rate limits, cost, tool timings), Git (your branch, its PR and checks, through the gh CLI), Agents (every Claude Code session and its subagents), Focus (a Pomodoro timer), Habits (daily habits, each with its streak), Toolbox (Base64, JWT, UUID, hashes, Unix times, cron and more), Pet (Clawd), Snippets and Monitor. Clipboard, Weather, Tech News, Stocks, Ping, Lo-fi and Docker wait until you add them with /chat rooms +clipboard and the like. The docs show each one.
In a terminal 110 columns wide or more (fullscreen), the pane docks on the right. In a narrower one it sits above the prompt. While the pane is closed, a line above the prompt shows the room, who's online and what's unread, with an Open button.
| Command | What it does |
|---|---|
/chat | Open the pane |
/say <message> | Send a message to the current room from the prompt |
/room | List your rooms |
/room <name> | Switch to a room you're in |
/room <name> <passcode> | Create a room, or join a friend's |
/room leave <name> | Leave a room (rejoin any time with its passcode) |
/room delete <name> | Delete a room you created, with all its messages, for everyone. Asks you to run it twice. |
/who | Who's online, across all your rooms |
/chat-login <email>, then /chat-login <code> | Sign in by email from the prompt instead of the pane |
/chat-login <name> | Sign in with just a name, where the server allows it |
/chat-share [#room] | Share the text you selected, or else the last code block in Claude's reply, to the current room or the one you name. You see it first, then /chat-share send posts it (or /chat-share cancel). |
/chat-share diff [path] [#room] | Share your uncommitted changes (git diff HEAD), all of them or one file's |
/chat-share to #room | Send what's waiting in the preview to another of your rooms instead. /chat-share send #room picks the room and posts in one go. In the pane, the preview's ‹ › arrows step through your rooms. |
/chat-logout | Sign out on this computer |
/chat notify on / off | Toast when someone writes @yourname (off by default) |
/chat dnd on / off / auto | Do not disturb: no toasts, a quiet band and status line, and friends see you as busy. auto turns it on while Claude works on something longer than 30 seconds, then sums up what you missed. |
/chat usage / git / agents / focus / habits / toolbox / clipboard / pet / snippet / monitor / weather / news / stock / ping / lofi / docker | Open the pane on a built-in room |
/chat band [room] | Show another room in the band above the prompt without opening the pane. ‹ and › on the band do the same, one room at a time. |
/chat rooms <list> | Which built-in rooms have tabs (usage, git, agents, focus, habits, toolbox, clipboard, pet, snippet, monitor, weather, news, stock, ping, lofi, docker, all or none, or +name / -name). Clipboard, Weather, Tech News, Stocks, Ping, Lo-fi and Docker are off until you add them. |
/focus start / pause / skip / reset / <focus min> [break min] | The Focus room's Pomodoro timer, with a chime when focus or a break ends |
/habit add <name> [x<times>] / done / undo / remove / rename <old> -> <new> | The Habits room's goals, each checked off once a day (or a number of times) with its streak |
/tool <name> [input] | One of the Toolbox room's tools: /tool uuid 5, /tool hash hello, /tool time 1739000000 |
/chat store / install <id> / update [id] / uninstall <id> | Rooms from the room store: list, install (a look first), update, remove |
/chat set <room> [<setting> <value>] | Show or change a room's settings, such as /chat set weather cities Taipei, Tokyo |
/chat-share usage / git / agents / habits / snippet [#room] | Share a snapshot of a built-in room to a chat room |
/snippet add <text> | Save the text as a snippet. Snippets are numbered 1, 2, 3 and on |
/snippet add | Save the selection, or else Claude's last code block, to the Snippets room |
/snippet rename <old> -> <new> / delete <name> | Rename or delete a saved snippet |
/snippet copy <name> / share <name> [#room] | Copy a saved snippet, or share it to a chat room after a look |
/lofi play [name] / pause / next / vol <0-100> / add <url or path> / import | The Lo-fi room's player and list, from the prompt |
The pane's input box takes /room, /who, /dnd, /share, /snippet, /lofi, /set, /usage, /git, /agents, /chat (the store commands included) and /logout too.
/say, /room and /chat-login, the arguments are replaced with a placeholder before Claude Code saves the command, and command answers are notices the model never reads.git and gh in its folder as you (gh talks to GitHub with your own sign-in). They send nothing of yours anywhere. Each session keeps a small heartbeat in /tmp/squad-chat-<uid>/sessions/, readable only by you (folder name, branch, model, recent tool names with a few words each, secrets masked, never prompts or output), so the Agents room can show every session. The Clipboard room, once you add it, reads the clipboard every 2 seconds and keeps the last 30 items in this session's memory only, masks anything that looks like a secret, and never shares them.~/.config/squad-chat/session.json, readable only by you. /chat-logout removes it.@ (ann@example.com → ann). Friends see it, plus whether you're online. They never see your email.squad-chat connects only to the places below. Each room's room.json lists its hosts under permissions.hosts, and the bridge refuses any other host for that room, settings included. The Ping room is the one exception: it checks only the servers you type into it, and a room can't start with any.
| What | Where it connects | What it sends |
|---|---|---|
| Chat | Your squad's Supabase project, the URL you set in supabase_url | Your sign-in, messages, presence and what you share |
| Git room | GitHub, through your own gh CLI | Read-only requests about this repository: its pull requests and checks, workflow runs, your issues and its open Dependabot alerts |
| Weather (off until added) | api.open-meteo.com, geocoding-api.open-meteo.com, air-quality-api.open-meteo.com | The city names you set |
| Tech News (off until added) | hacker-news.firebaseio.com and the feeds www.ithome.com.tw, www.theverge.com, feeds.arstechnica.com, techcrunch.com | Nothing beyond the request |
| Stocks (off until added) | mis.twse.com.tw, query1.finance.yahoo.com | The symbols on your watchlist |
| Lo-fi (off until added) | ice2.somafm.com and www.youtube.com, played by your own mpv (and yt-dlp for YouTube), started only when you press play | Nothing beyond the stream request. Tracks you add play from wherever you point them |
| Ping (off until added) | Only the servers you add: a ping, a TCP connection or one HTTP(S) GET each, every 30 seconds while the room is shown and every minute otherwise | Nothing beyond the check. The results stay in ~/.config/squad-chat/room-data/ping/ |
| Room store | raw.githubusercontent.com/chrisluo5311/squad-chat/main/rooms | Nothing beyond the request. A room installs only after you see its hosts and confirm |
Nothing goes to Claude, to Anthropic or to the author of squad-chat.
Every program is named in the code, with fixed arguments, and none comes from a room or from the network.
| Program | When | Why |
|---|---|---|
node --version, then node bridge/dist/bridge.mjs | When Claude Code starts | Checks for Node 22 or newer, then starts the bridge, the one process that talks to Supabase and the room hosts above |
git, gh | Git room, /chat-share diff | Reads this folder's branch, diff, pull requests and checks |
pbpaste, wl-paste or xclip | Clipboard room, only once you add it | Reads the clipboard every 2 seconds |
vm_stat, sysctl, netstat, df, pmset, ioreg, macmon (Mac), nvidia-smi (Linux) | Monitor room | Reads CPU, memory, disk, network, battery and GPU figures. No shell, no sudo |
docker (ps, images, volume ls, network ls, stats, logs) | Docker room, only once you add it | Reads what Docker has, every 5 seconds while the room is on show. Read only. logs goes through /bin/sh only to keep the container's stderr |
ping (/sbin/ping on a Mac) | Ping room, only for the hosts you add | Sends 3 packets to each, the host passed as one argument after --. No shell, no sudo |
mpv, and yt-dlp for YouTube | Lo-fi room, only when you press play | Plays the stream. A short /bin/sh loop around mpv stops it when the bridge exits, and downloads nothing to run |
The mod watches Claude Code events to draw its rooms. It never asks for permissions, never changes a permission decision, and never adds to the conversation.
| Event | What it does |
|---|---|
turn.start, turn.step, turn.complete, tool.call, agent.spawn, session.measure | Measures timings, tokens and tool names for the Usage and Agents rooms, then passes each event on unchanged |
session.append | For /say, /room and /chat-login only, replaces the arguments with a placeholder before the transcript stores them, so messages and passcodes stay out of it |
command.run | Answers squad-chat's own slash commands |
ui.*, clock, branch, pr, session.start, session.end | Draws the pane and band, registers the commands, and stops the bridge when the session ends |
/chat-share reads your mouse selection, Claude's last code block or git diff. It shows you the preview, and sends to your room only when you confirm.
The mod starts a small Node process (bridge/dist/bridge.mjs) that holds the connection to Supabase: sign-in, Realtime presence and messages, and catching up after network drops. The mod talks to it over a private Unix socket. Source and tests: github.com/chrisluo5311/squad-chat.
MIT
hooks/squad-chat.mjs 1399 lines1// squad-chat: friends' presence and a group chat in a side pane. Chat text
2// never reaches the model.
3//
4// Everything that touches the engine ($) lives in this file, since $ is never
5// followed across an import. The other files are plain logic:
6// state.mjs the state built from the bridge's events
7// commands.mjs slash commands and the pane's input box
8// views.mjs the pane
9// sysviews.mjs the built-in rooms (Usage, Git, Agents), with widgets.mjs
10// fnviews.mjs function rooms, drawn from the manifests the bridge loads
11// metrics.mjs this session's numbers, github.mjs the Git room's data,
12// sessions.mjs heartbeats shared with the other sessions on this computer
13// focus.mjs, habits.mjs, toolbox.mjs, clipboard.mjs, pet.mjs the Focus, Habits, Toolbox, Clipboard and Pet rooms
14
15import { state, applyEvent, resetBridgeState, currentRoom, bandRoom, roomMessages, statusText, isQuiet, missedText, activeView, DEFAULT_ROOMS, ROOM_ID, roomIds, enabledRooms, isFnRoom } from "./state.mjs";
16import { PRIVATE_ARGS, TOOL_USAGE, login, logout, rename, room, who, dnd, share, shareItem, snippet, lofi, chatAdmin, retargetShare, sendMessage, paneInput } from "./commands.mjs";
17import { paneView, bandView } from "./views.mjs";
18import { applyMeasure, applyTurnUsage, recordTurnContext, usageSnapshot, restoreUsage, toolStarted, toolEnded, turnStarted, turnEnded, agentSpawned, applyAgentList, agentCounts, runningCalls, stepPrompt, stepToolResult, stepStarted, stepToolUse, stepEnded, applyOverhead, wantsOverhead, toolSummary } from "./metrics.mjs";
19import { fetchGit, diffGit } from "./github.mjs";
20import { heartbeat, beatKey } from "./sessions.mjs";
21import { createFocus, isRunning, start as focusStart, pause as focusPause, skip as focusSkip, reset as focusReset, adjust as focusAdjust, setLengths, tickFocus, focusSettings, focusTimer, restoreFocus, focusStatus, focusBadge, dayOf } from "./focus.mjs";
22import { createHabits, habitWords, habitsSaved, restoreHabits, markHabit, toggleHabit, deleteHabit, undeleteHabit } from "./habits.mjs";
23import { createToolbox, toolWords, pickTool, rerun as toolAgain, setInput as setToolInput, MAX_INPUT as MAX_TOOL_INPUT } from "./toolbox.mjs";
24import { createClipboard, addClip, removeClip, CLIP_READERS } from "./clipboard.mjs";
25import { createPet, petMood, petFrameMs, petTick, petNote, petRound, petSaved, restorePet, MOODS } from "./pet.mjs";
26
27state.focus = createFocus();
28state.habits = createHabits();
29state.toolbox = createToolbox();
30state.clipboard = createClipboard();
31state.pet = createPet();
32
33const PANE_ID = "squad-chat";
34const UNDO_MS = 10_000; // how long Cancel stays beside "Removed …"
35const NOTICE_MS = 5_000; // how long a notice over the box stays
36
37const MIN_NODE_MAJOR = 22;
38const MAX_BACKOFF_MS = 30_000;
39const TYPING_PING_MS = 2_000;
40const LONG_TURN_MS = 30_000; // a Claude turn this long turns "auto" do not disturb on
41const GIT_SHOWN_MS = 60_000; // how often the Git room refreshes while it's on show
42const GIT_HIDDEN_MS = 5 * 60_000; // and otherwise (for its tab's badge and the toasts)
43const BEAT_IDLE_MS = 10_000; // a heartbeat at least this often, so others don't drop us
44const PUSHED = /\b(git\s+push|gh\s+pr\s+(create|merge|ready|close|review))\b/;
45
46// ---------------------------------------------------------------- the bridge
47
48let bridgeStarted = false;
49
50function randomToken() {
51 const bytes = new Uint8Array(24);
52 crypto.getRandomValues(bytes);
53 return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
54}
55
56function unavailable($, detail) {
57 state.bridge = "unavailable";
58 state.detail = detail;
59 $.ui.invalidate("ui.render");
60}
61
62async function nodeProblem($) {
63 try {
64 const { exitCode, stdout } = await $.process.run(["node", "--version"], { timeoutMs: 10_000 });
65 const major = Number(/^v(\d+)/.exec(stdout.trim())?.[1]);
66 if (exitCode !== 0 || !major) return "could not run `node --version`";
67 if (major < MIN_NODE_MAJOR) return `squad-chat needs Node ${MIN_NODE_MAJOR} or newer (found ${stdout.trim()})`;
68 return null;
69 } catch (err) {
70 return `squad-chat needs Node ${MIN_NODE_MAJOR}+ on PATH (${err?.message ?? err})`;
71 }
72}
73
74// Runs bridge/dist/bridge.mjs for the life of the module, restarting it with
75// backoff. Leaving the loop, or the module unloading, kills the child.
76// The squad's server comes from the plugin's options (userConfig). An unset
77// one is left out, so a SQUAD_SUPABASE_* variable in the environment (local
78// development) still applies.
79function serverEnv(options) {
80 const env = {};
81 if (options?.supabase_url) env.SQUAD_SUPABASE_URL = String(options.supabase_url).trim();
82 if (options?.supabase_key) env.SQUAD_SUPABASE_KEY = String(options.supabase_key).trim();
83 return env;
84}
85
86async function runBridge($, options) {
87 const problem = await nodeProblem($);
88 if (problem) return unavailable($, problem);
89
90 let backoff = 1000;
91 while (!state.ended) {
92 state.token = randomToken();
93 resetBridgeState();
94 const startedAt = await $.clock.now();
95 let buffered = "";
96 try {
97 const child = $.process.spawn({
98 argv: ["node", `${$.plugin.root}/bridge/dist/bridge.mjs`],
99 env: { SQUAD_BRIDGE_TOKEN: state.token, SQUAD_ROOMS_DIR: `${$.plugin.root}/rooms`, ...serverEnv(options) },
100 });
101 for await (const { stream, text } of child) {
102 if (stream === "stderr") { $.ui.log(`squad-chat bridge: ${text.trimEnd()}`, { to: "debug" }); continue; }
103 buffered += text;
104 let nl;
105 while ((nl = buffered.indexOf("\n")) >= 0) {
106 const line = buffered.slice(0, nl).trim();
107 buffered = buffered.slice(nl + 1);
108 if (!line) continue;
109 let event;
110 try { event = JSON.parse(line); }
111 catch { $.ui.log(`squad-chat bridge: unparsable line: ${line.slice(0, 120)}`, { to: "debug" }); continue; }
112 if (event.type === "fnrooms") {
113 lastVisible = ""; // a new bridge knows nothing yet
114 for (const bad of event.invalid ?? []) $.ui.log(`squad-chat: room ${bad.dir} skipped: ${bad.errors.join("; ")}`, { to: "debug" });
115 }
116 if (applyEvent(event)) {
117 // Someone else wrote: Clawd waves, and notes who and where (never what).
118 // A message that comes in while the chat is scrolled up leaves the view where it is.
119 if (event.type === "message" && !event.backfill && event.message?.room === state.chatScroll.room && state.chatScroll.back > 0) state.chatScroll.back += 1;
120 if (event.type === "message" && event.counted && !event.message?.mine) {
121 state.pet.waveAt = Date.now();
122 petNote(state.pet, "👋", `${event.message.user} wrote in #${event.message.slug}`);
123 }
124 afterChange($);
125 }
126 // A new or restarted bridge starts out available: tell it again.
127 if (event.type === "auth" && event.state === "signed_in" && isQuiet()) sendStatus($);
128 }
129 }
130 } catch (err) {
131 // Cannot start: no process noun on this surface (desktop), or no node.
132 return unavailable($, `cannot start the chat bridge: ${err?.message ?? err}`);
133 }
134 if (state.ended || state.bridge === "unconfigured") return; // nothing to retry until options change
135 if ((await $.clock.now()) - startedAt > 60_000) backoff = 1000;
136 resetBridgeState();
137 state.bridge = "restarting";
138 state.detail = `bridge stopped; retrying in ${Math.round(backoff / 1000)}s`;
139 $.ui.invalidate("ui.render");
140 await $.clock.sleep(backoff);
141 backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
142 }
143}
144
145// One control request; resolves the bridge's JSON answer or throws its error.
146async function callBridge($, path, body) {
147 if (!state.socket) {
148 throw new Error(state.bridge === "unavailable" ? state.detail : "chat is still connecting, try again in a moment");
149 }
150 const res = await $.http.fetch(`http://bridge${path}`, {
151 method: body === undefined ? "GET" : "POST",
152 headers: { "content-type": "application/json", "x-squad-token": state.token },
153 body: body === undefined ? undefined : JSON.stringify(body),
154 socketPath: state.socket,
155 });
156 let data = {};
157 try { data = JSON.parse(res.text || "{}"); } catch { /* keep {} */ }
158 if (!res.ok) throw new Error(data.error || `bridge answered ${res.status}`);
159 return data;
160}
161
162// ---------------------------------------------------------------- keeping chat out of the model
163
164// Claude Code records a slash command as a user row the model reads on later
165// turns ("<command-name>/say</command-name> ... <command-args>TEXT</command-args>").
166// For commands that carry messages, emails, codes or passcodes, the args are
167// replaced before the row is stored or sent.
168const ARGS = /<command-args>[\s\S]*?<\/command-args>/g;
169const REDACTED = "<command-args>[squad-chat input, hidden from Claude]</command-args>";
170const NAME = /<command-name>\/(?:squad-chat:)?([\w-]+)<\/command-name>/;
171
172function blockTexts(content) {
173 if (typeof content === "string") return [content];
174 return (content ?? []).filter((b) => b?.type === "text").map((b) => b.text ?? "");
175}
176
177function privateCommand(message) {
178 return blockTexts(message?.content).some((t) => PRIVATE_ARGS.has(NAME.exec(t)?.[1]));
179}
180
181function redact(content) {
182 if (typeof content === "string") return content.replace(ARGS, REDACTED);
183 return content.map((b) => (b?.type === "text" ? { ...b, text: String(b.text ?? "").replace(ARGS, REDACTED) } : b));
184}
185
186// ---------------------------------------------------------------- pane and commands
187
188// The band shows the room with the newest message: Open goes to that room.
189async function openFromBand($) {
190 const room = activeView() === "chat" && state.auth === "signed_in" ? bandRoom() : null;
191 if (room && room.id !== state.current) await callBridge($, "/room/select", { room: room.id }).catch(() => {});
192 await openPane($);
193}
194
195async function openPane($) {
196 const opened = await $.ui.open({ id: PANE_ID, title: "Squad Chat", focus: true, rows: 12, columns: 52 });
197 if (opened?.isPlaced === false) $.ui.toast("squad-chat: widen the terminal to see the chat pane");
198}
199
200// After any state change: redraw, refresh the status line, and toast an
201// @mention when the person asked for that (/chat notify on).
202function afterChange($) {
203 $.ui.invalidate("ui.render");
204 syncRooms($);
205 $.ui.status(statusText());
206 if (state.mention) {
207 const m = state.mention;
208 state.mention = null;
209 if (state.notify) $.ui.toast(`💬 ${m.user} in #${m.slug}: ${m.body.slice(0, 80)}`);
210 }
211 // A function room's alert (Monitor's "CPU at 96°C"): toasted unless quiet.
212 while (state.fnToasts.length) {
213 const text = state.fnToasts.shift();
214 if (!isQuiet()) $.ui.toast(text);
215 }
216}
217
218// ---------------------------------------------------------------- function rooms
219
220// Tell the bridge which function rooms have tabs and which is on show, so it
221// runs their providers (and polls the one on show more often). Only on change.
222let lastVisible = "";
223function syncRooms($) {
224 if (!state.socket || !state.fn.size) return;
225 const enabled = enabledRooms().filter(isFnRoom);
226 const view = activeView();
227 const shown = state.paneShown && isFnRoom(view) ? view : null;
228 const key = JSON.stringify([enabled, shown]);
229 if (key === lastVisible) return;
230 lastVisible = key;
231 callBridge($, "/fnroom/visible", { enabled, shown }).catch((err) => {
232 lastVisible = "";
233 $.ui.log(`squad-chat: rooms: ${err?.message ?? err}`, { to: "debug" });
234 });
235}
236
237async function refreshRoom($, id) {
238 try {
239 await callBridge($, "/fnroom/refresh", { room: id });
240 } catch (err) {
241 state.notice = err?.message ?? String(err);
242 $.ui.invalidate("ui.render");
243 }
244}
245
246// A function room's button (Lo-fi's ⏯, a row's ▶): one of its provider's
247// actions. The bridge runs the room again after it, which redraws.
248async function roomAction($, room, { provider, action, args }) {
249 try {
250 await callBridge($, "/fnroom/action", { room, ...(provider ? { provider } : {}), action, args });
251 } catch (err) {
252 state.notice = err?.message ?? String(err);
253 $.ui.invalidate("ui.render");
254 }
255}
256
257// A room's setting changed from its cards: a row's ✕ ("-Tokyo") or a row
258// picked, as "/set <key> <value>" would.
259async function setRoomSetting($, room, key, value) {
260 try {
261 const r = await callBridge($, "/fnroom/settings", { room, key, value });
262 const fn = state.fn.get(room);
263 if (fn && r?.values) fn.settings = r.values;
264 } catch (err) {
265 state.notice = err?.message ?? String(err);
266 }
267 $.ui.invalidate("ui.render");
268}
269
270// A function room's ⇪: held for a look, like any snippet.
271function shareItemFromPane($, item) {
272 const say = (text) => { state.notice = text; $.ui.invalidate("ui.render"); };
273 try { shareItem(item, say, { inPane: true }); } catch (err) { say(err?.message ?? String(err)); }
274 $.ui.invalidate("ui.render");
275}
276
277// ---------------------------------------------------------------- do not disturb
278
279function sendStatus($) {
280 callBridge($, "/status", { status: isQuiet() ? "busy" : "available" })
281 .catch((err) => $.ui.log(`squad-chat: could not set status: ${err?.message ?? err}`, { to: "debug" }));
282}
283
284// Do not disturb may have started or ended: tell the room, and on the way
285// out sum up what came in meanwhile (a toast, for people who asked for them).
286let wasQuiet = false;
287function quietChanged($) {
288 const quiet = isQuiet();
289 if (quiet === wasQuiet) return;
290 wasQuiet = quiet;
291 if (state.auth === "signed_in") sendStatus($);
292 if (!quiet) {
293 const summary = missedText();
294 if (summary && state.notify) $.ui.toast(summary);
295 state.missed = { messages: 0, mentions: 0 };
296 }
297 afterChange($);
298}
299
300async function setDnd($, mode) {
301 state.dnd = mode;
302 await $.store.set("dnd", mode);
303 quietChanged($);
304}
305
306// ---------------------------------------------------------------- sharing snippets
307
308// What /chat-share reads from the session: the mouse selection, Claude's replies,
309// and `git diff` in the session's folder. Reading only: nothing is added to
310// the conversation.
311function shareSources($, { inPane = false } = {}) {
312 return {
313 inPane,
314 // Claude Code 2.1.287 has no selection to read: share the last code block.
315 selection: async () => { try { return (await $.ui.selection())?.text; } catch { return undefined; } },
316 messages: () => $.session.messages(),
317 diff: async (path) => {
318 const cwd = await $.session.cwd();
319 const argv = ["git", "diff", "HEAD", "--no-color", "--no-ext-diff", "--", ...(path ? [path] : [])];
320 const r = await $.process.run(argv, { cwd, timeoutMs: 15_000 });
321 if (r.exitCode !== 0) throw new Error(`git diff: ${r.stderr.trim().split("\n")[0] || `exit ${r.exitCode}`}`);
322 if (r.isStdoutTruncated) throw new Error(`Too big to share. Share one file with ${inPane ? "/share" : "/chat-share"} diff <path>.`);
323 return r.stdout;
324 },
325 };
326}
327
328// The preview card's Send and Cancel: like typing "/share send" in the box,
329// without touching what's typed there.
330async function shareFromPane($, verb) {
331 const say = (text) => { state.notice = text; $.ui.invalidate("ui.render"); };
332 try {
333 await share((path, body) => callBridge($, path, body), verb, say, shareSources($, { inPane: true }));
334 } catch (err) {
335 say(err?.message ?? String(err));
336 }
337 $.ui.invalidate("ui.render");
338}
339
340// Copy from a command: at the prompt, or typed in the pane's box.
341async function copyText($, text, say) {
342 const r = await $.ui.copy({ text });
343 say(r?.isCopied ? "Copied." : `Couldn't copy${r?.reason ? `: ${r.reason}` : ""}.`);
344}
345
346async function copySnippet($, text, surface) {
347 const r = await $.ui.copy({ text, ...(surface ? { surface } : {}) });
348 state.notice = r?.isCopied ? "Copied." : `Couldn't copy${r?.reason ? `: ${r.reason}` : ""}.`;
349 $.ui.invalidate("ui.render");
350}
351
352// Tell the bridge the current room is read up to its newest message. Runs
353// when the pane has the keyboard and when the person sends from it.
354let marking = false;
355async function markRead($) {
356 const room = currentRoom();
357 const newest = roomMessages().at(-1)?.id ?? 0;
358 if (marking || !room || (!room.unread && newest <= room.last_read_id)) return;
359 marking = true;
360 // Remember where they'd read up to, so the pane can draw a "new" line there.
361 if (!state.dividerAt.has(room.id) && room.last_read_id > 0) state.dividerAt.set(room.id, room.last_read_id);
362 try {
363 await callBridge($, "/read", { room: room.id, last_id: newest });
364 room.last_read_id = Math.max(room.last_read_id, newest);
365 room.unread = 0;
366 afterChange($);
367 } catch (err) {
368 $.ui.log(`squad-chat: could not mark read: ${err?.message ?? err}`, { to: "debug" });
369 } finally {
370 marking = false;
371 }
372}
373
374// When the tabs change (join, leave, switch a room or a built-in room), the
375// pane's focus ring leaves the input box, and what the person types next
376// falls through to the prompt: it would go to Claude. After a change they
377// started in the pane, wait for the new tabs to be drawn, then put the ring
378// back on the box.
379async function keepFocusAcrossRoomChange($, before) {
380 for (let waited = 0; waited < 2000; waited += 50) {
381 if (state.current !== before.current || state.rooms.length !== before.count || state.view !== before.view) break;
382 await $.clock.sleep(50);
383 }
384 await $.clock.sleep(80); // let the new tree draw first
385 await $.ui.open({ id: PANE_ID, title: "Squad Chat", focus: true });
386 await $.ui.focus({ requestId: PANE_ID, key: "compose" });
387}
388
389// While a message is being typed in the pane, tell the room every couple of
390// seconds. Commands and sign-in steps aren't messages, so they stay quiet.
391let lastTypingPing = 0;
392function typingPing($, value) {
393 const text = String(value ?? "").trimStart();
394 if (!text || text.startsWith("/") || state.auth !== "signed_in" || !currentRoom()) return;
395 const now = Date.now();
396 if (now - lastTypingPing < TYPING_PING_MS) return;
397 lastTypingPing = now;
398 callBridge($, "/typing", { room: state.current }).catch(() => { /* a missed ping only hides a hint */ });
399}
400
401// Empty the box after a submit. A field holds what's typed until the hook
402// draws another value, and typing doesn't redraw (it would flicker), so the
403// value last drawn is often "" already and drawing "" again changes nothing:
404// the desktop kept the words sent. So the text sent is drawn first, then "".
405function clearBox($, sent) {
406 state.draft = String(sent ?? "");
407 $.ui.invalidate("ui.render");
408 void (async () => {
409 await $.clock.sleep(120);
410 if (state.draft === String(sent ?? "")) { state.draft = ""; $.ui.invalidate("ui.render"); }
411 })().catch(() => { state.draft = ""; });
412}
413
414// The chat's own scroll: `by` messages older (+) or newer (-), or 0 for the
415// newest.
416function scrollChat($, by) {
417 const c = state.chatScroll;
418 const max = Math.max(0, roomMessages().length - 1);
419 const back = by === 0 ? 0 : Math.min(max, Math.max(0, c.back + by));
420 if (back === c.back) return;
421 c.back = back;
422 $.ui.invalidate("ui.render");
423}
424
425async function submitFromPane($, value) {
426 const say = (text) => { state.notice = text; $.ui.invalidate("ui.render"); };
427 const before = { current: state.current, count: state.rooms.length, view: state.view };
428 clearBox($, value);
429 state.notice = "";
430 lastTypingPing = 0;
431 try {
432 await paneInput((path, body) => callBridge($, path, body), value, say, {
433 setDnd: (mode) => setDnd($, mode),
434 sources: shareSources($, { inPane: true }),
435 setView: (view) => setView($, view),
436 refreshGit: () => refreshGit($),
437 refreshRoom: (id) => refreshRoom($, id),
438 copy: (text) => copyText($, text, say),
439 saveRooms: (list) => saveSysRooms($, list),
440 roomInput: (view, text, say, opts) => roomInput($, view, text, say, opts),
441 });
442 state.dividerAt.clear(); // they've replied: everything above is read
443 state.chatScroll.back = 0; // and they see what they just sent
444 await markRead($); // they're looking at the room they just wrote in
445 } catch (err) {
446 say(err?.message ?? String(err));
447 }
448 if (/^\/room\b/.test(String(value).trim()) || state.view !== before.view) {
449 try { await keepFocusAcrossRoomChange($, before); } catch { /* the box is one click away */ }
450 } else if (paneSurface === "terminal") {
451 // What's typed can add or take away buttons in the room (Focus's "start"
452 // brings ⏭ and ↺), and on the terminal a pane whose buttons change loses
453 // the keyboard to the prompt, where the next words would go to Claude:
454 // once the new tree is drawn, the box takes it back. The desktop's field
455 // takes the keyboard by a click, and is left as the person left it.
456 focusAfterDraw($, "compose");
457 }
458}
459
460// The desktop header's join: the field in front takes the keyboard, and
461// the fields fold back after 5 seconds with nothing typed.
462const JOIN_IDLE_MS = 5_000;
463let joinIdle = null;
464function armJoinIdle($) {
465 joinIdle?.cancel?.();
466 joinIdle = null;
467 if (!state.join) return;
468 Promise.resolve($.clock.after(JOIN_IDLE_MS, () => {
469 joinIdle = null;
470 if (state.join && !state.join.busy) { state.join = null; focusAfterDraw($, "compose"); }
471 })).then((t) => { joinIdle = t; }, () => { /* no timer: ✕ still folds it */ });
472}
473// A pressed button that the press takes away (+ join turning into its
474// field, ✕ folding the fields, a room added from the "+" list) took the
475// pane's focus with it, so the next click only gave the focus back. Once
476// the new tree is drawn, the focus goes where the person carries on.
477function focusAfterDraw($, key) {
478 $.ui.invalidate("ui.render");
479 void (async () => {
480 await $.clock.sleep(80); // let the new tree draw first
481 // The pane lost the keyboard with the element: take it back, then put
482 // the ring on the element (focus alone moves it only inside a pane that has it).
483 await $.ui.open({ id: PANE_ID, title: "Squad Chat", focus: true });
484 await $.ui.focus({ requestId: PANE_ID, key });
485 })().catch(() => { /* a click away */ });
486}
487function closeJoin($) {
488 joinIdle?.cancel?.();
489 joinIdle = null;
490 state.join = null;
491 focusAfterDraw($, "compose");
492}
493function joinFocus($, key) {
494 armJoinIdle($);
495 focusAfterDraw($, key);
496}
497
498// Join (or make) the room named in the header's fields, as /room does: in
499// it, the fields close and the chat shows it; refused, the passcode field
500// stays with the reason under it.
501async function joinFromPane($, value) {
502 const j = state.join;
503 if (!j) return;
504 const passcode = String(value ?? "").trim();
505 const joined = state.rooms.some((r) => r.slug === j.name.toLowerCase());
506 if (!passcode && !joined) { state.join = { ...j, error: "Type the room's passcode." }; return joinFocus($, "join-pass"); }
507 const before = { current: state.current, count: state.rooms.length, view: state.view };
508 j.busy = true; // not folded away while the server answers
509 try {
510 await room((path, body) => callBridge($, path, body), `${j.name} ${passcode}`.trim(), () => {});
511 } catch (err) {
512 state.join = { ...j, busy: false, draft: "", error: err?.message ?? String(err) };
513 return joinFocus($, "join-pass");
514 }
515 closeJoin($);
516 state.notice = "";
517 if (state.view !== "chat") await setView($, "chat");
518 else $.ui.invalidate("ui.render");
519 try { await keepFocusAcrossRoomChange($, before); } catch { /* the box is one click away */ }
520}
521
522async function selectRoom($, id) {
523 const before = { current: state.current, count: state.rooms.length, view: state.view };
524 try {
525 await callBridge($, "/room/select", { room: id });
526 } catch (err) {
527 state.notice = err?.message ?? String(err);
528 $.ui.invalidate("ui.render");
529 return;
530 }
531 try { await keepFocusAcrossRoomChange($, before); } catch { /* the box is one click away */ }
532}
533
534// ---------------------------------------------------------------- the built-in rooms
535
536async function setView($, view) {
537 state.view = view;
538 state.notice = "";
539 await $.store.set("view", view);
540 if (view === "git") void refreshGit($, { ifOlderThan: 15_000 });
541 if (view === "usage") void refreshUsage($);
542 afterChange($);
543}
544
545// The band shows the room on show; ‹ › and /chat band move it along the
546// rooms with tabs (and the chat, once you're in a room) with the pane shut.
547function bandRooms() {
548 return [...enabledRooms(), ...(state.auth === "signed_in" && currentRoom() ? ["chat"] : [])];
549}
550async function cycleBand($, dir) {
551 const list = bandRooms();
552 if (!list.length) return;
553 const at = list.indexOf(activeView());
554 // From a view not in the list, › goes to the first and ‹ to the last.
555 const next = at < 0 ? (dir > 0 ? 0 : list.length - 1) : (at + dir + list.length) % list.length;
556 await setView($, list[next]);
557}
558
559async function saveSysRooms($, list) {
560 state.sysRooms = list;
561 await $.store.set("sysRooms", list);
562 afterChange($);
563}
564
565// The engine's figures, asked for directly: on opening the room, and for
566// the context breakdown (estimated locally, so it costs nothing).
567// This session's tokens and chart, kept per session across reloads, and
568// dropped once a session has been idle for a week.
569const USAGE_PREFIX = "usage:";
570const USAGE_KEEP_MS = 7 * 86_400_000;
571async function restoreSessionUsage($) {
572 try {
573 const now = Date.now();
574 for (const key of await $.store.keys()) {
575 if (!key.startsWith(USAGE_PREFIX)) continue;
576 const saved = await $.store.get(key);
577 if (key === USAGE_PREFIX + state.sessionId) restoreUsage(state.usage, saved);
578 else if (!(now - (saved?.at ?? 0) < USAGE_KEEP_MS)) await $.store.delete(key);
579 }
580 } catch (err) {
581 $.ui.log(`squad-chat: could not restore usage: ${err?.message ?? err}`, { to: "debug" });
582 }
583}
584
585async function refreshUsage($) {
586 try {
587 // The breakdown when it's open, and now and then for the Requests card's bedrock.
588 const breakdown = state.usage.showBreakdown || wantsOverhead(state.usage);
589 const u = await $.session.usage(breakdown ? { breakdown: "summary" } : {});
590 applyMeasure(state.usage, u, Date.now());
591 if (u?.context?.breakdown) {
592 state.usage.breakdown = u.context.breakdown;
593 applyOverhead(state.usage, u.context.breakdown);
594 }
595 afterChange($);
596 } catch (err) {
597 $.ui.log(`squad-chat: could not read usage: ${err?.message ?? err}`, { to: "debug" });
598 }
599}
600
601function toggleBreakdown($) {
602 state.usage.showBreakdown = !state.usage.showBreakdown;
603 $.ui.invalidate("ui.render");
604 if (state.usage.showBreakdown) void refreshUsage($);
605}
606
607let gitBusy = false;
608async function refreshGit($, { ifOlderThan = 0 } = {}) {
609 if (gitBusy || !state.sysRooms.includes("git")) return;
610 if (ifOlderThan && Date.now() - state.git.fetchedAt < ifOlderThan) return;
611 gitBusy = true;
612 const prev = state.git;
613 if (!prev.fetchedAt) { state.git = { ...prev, status: "loading" }; $.ui.invalidate("ui.render"); }
614 try {
615 const cwd = await $.session.cwd();
616 const run = (argv) => $.process.run(argv, { cwd, timeoutMs: 15_000 });
617 const next = await fetchGit(run, prev);
618 state.git = next;
619 for (const text of diffGit(prev, next)) if (!isQuiet()) $.ui.toast(text);
620 } catch (err) {
621 state.git = { ...prev, status: "error", error: err?.message ?? String(err), stale: prev.status === "ok" };
622 } finally {
623 gitBusy = false;
624 }
625 afterChange($);
626}
627
628// Something in this session moved: redraw while a built-in room is on show
629// (the tabs' badges change in the chat too), and tell the other sessions.
630function sysChanged($) {
631 $.ui.invalidate("ui.render");
632 if (state.sysRooms.includes("agents")) beat($, false);
633}
634
635let lastBeat = { key: "", at: 0 };
636let cwdCache = null;
637function beat($, force) {
638 if (!state.sessionId) return;
639 const now = Date.now();
640 state.self = heartbeat(state.usage, { id: state.sessionId, cwd: cwdCache, branch: state.git.local?.branch, now });
641 const key = beatKey(state.self);
642 if (!force && key === lastBeat.key && now - lastBeat.at < BEAT_IDLE_MS) return;
643 if (!force && key !== lastBeat.key && now - lastBeat.at < 1000) return; // the next tick sends it
644 if (!state.socket) return;
645 lastBeat = { key, at: now };
646 callBridge($, "/sessions/beat", state.self).catch((err) => $.ui.log(`squad-chat: heartbeat: ${err?.message ?? err}`, { to: "debug" }));
647}
648
649function liveNow() {
650 const u = state.usage;
651 if (u.activity.state !== "idle" || runningCalls(u).length || agentCounts(u).running) return true;
652 if (activeView() === "agents") return state.sessions.some((s) => (s.activity?.state && s.activity.state !== "idle") || (s.agents ?? []).length);
653 if (activeView() === "git") return state.git.runs.some((r) => r.status !== "completed");
654 if (activeView() === "focus") return isRunning(state.focus);
655 return false;
656}
657
658// ---------------------------------------------------------------- Focus, Clipboard, Pet
659
660// The Focus room's lengths and today's count are every session's; the
661// running timer is this session's, kept so a reload carries on. Pet's mood
662// choice is every session's.
663const FOCUS_TIMER_PREFIX = "focus:";
664async function restoreRooms($) {
665 try {
666 const now = await $.clock.now();
667 const timer = state.sessionId ? await $.store.get(FOCUS_TIMER_PREFIX + state.sessionId) : null;
668 restoreFocus(state.focus, await $.store.get("focus"), timer, now);
669 restoreHabits(state.habits, await $.store.get("habits"));
670 restorePet(state.pet, await $.store.get("pet"));
671 state.pet.lastBusyAt = Date.now();
672 state.focusStatus = focusStatus(now);
673 } catch (err) {
674 $.ui.log(`squad-chat: could not restore the rooms: ${err?.message ?? err}`, { to: "debug" });
675 }
676}
677
678async function saveFocus($) {
679 try {
680 await $.store.set("focus", focusSettings(state.focus));
681 if (state.sessionId) {
682 const key = FOCUS_TIMER_PREFIX + state.sessionId;
683 if (state.focus.phase === "idle") await $.store.delete(key);
684 else await $.store.set(key, focusTimer(state.focus));
685 }
686 } catch (err) {
687 $.ui.log(`squad-chat: could not save the timer: ${err?.message ?? err}`, { to: "debug" });
688 }
689}
690
691// The lengths and today's count are every session's, and another session
692// may have saved since this one read them: read them again before a change,
693// so one session's save doesn't undo another's.
694async function syncFocus($, now) {
695 try {
696 restoreFocus(state.focus, await $.store.get("focus"), null, now);
697 } catch (err) {
698 $.ui.log(`squad-chat: could not read the timer's settings: ${err?.message ?? err}`, { to: "debug" });
699 }
700}
701
702// A change to the timer, on the settings as they are now.
703async function changeFocus($, fn) {
704 const now = await $.clock.now();
705 await syncFocus($, now);
706 fn(state.focus, now);
707 focusChanged($, now);
708}
709
710// The timer changed: show it, keep it.
711function focusChanged($, now) {
712 state.focusStatus = focusStatus(now);
713 afterChange($);
714 void saveFocus($);
715}
716
717// A press or a typed word: start, pause, skip or reset, on the engine's clock.
718const FOCUS_DO = {
719 start: focusStart,
720 resume: focusStart,
721 go: focusStart,
722 pause: focusPause,
723 skip: focusSkip,
724 reset: focusReset,
725};
726async function focusAct($, verb) {
727 await changeFocus($, (f, now) => FOCUS_DO[verb](f, now));
728}
729
730// A phase ran out: the chime, a toast (a timer you set rings even while
731// quiet), and the next phase.
732function focusEnded($, ended, now) {
733 const f = state.focus;
734 if (ended === "focus") petRound(state.pet);
735 else petNote(state.pet, "☕", "Break's over");
736 savePet($);
737 const asset = ended === "focus" ? "sounds/focus-done.wav" : "sounds/break-done.wav";
738 $.audio.play({ asset }).catch((err) => $.ui.log(`squad-chat: chime: ${err?.message ?? err}`, { to: "debug" }));
739 $.ui.toast(ended === "focus"
740 ? `🍅 Focus done (${f.done} today). Break for ${f.rest} min.`
741 : "☕ Break's over. ▶ in the Focus room starts the next round.");
742 focusChanged($, now);
743}
744
745// The Habits room's goals and days are every session's: read again before
746// a change, so one session's save doesn't undo another's, then kept. One
747// change at a time: two presses that overlap would both read the store
748// before either saved, and the second would put back what the first changed.
749let habitsBusy = Promise.resolve();
750function changeHabits($, fn) {
751 const run = habitsBusy.then(() => changeHabitsNow($, fn));
752 habitsBusy = run.catch(() => {});
753 return run;
754}
755
756async function changeHabitsNow($, fn) {
757 // The wall clock, as the drawing has it: a day is the calendar's.
758 const now = Date.now();
759 try { restoreHabits(state.habits, await $.store.get("habits")); } catch (err) {
760 $.ui.log(`squad-chat: could not read the habits: ${err?.message ?? err}`, { to: "debug" });
761 }
762 const said = fn(state.habits, now);
763 afterChange($);
764 try { await $.store.set("habits", habitsSaved(state.habits)); } catch (err) {
765 $.ui.log(`squad-chat: could not save the habits: ${err?.message ?? err}`, { to: "debug" });
766 }
767 return said;
768}
769
770// Words typed in a room of the mod's own: Focus's start, pause, skip, reset
771// or minutes; Habits' add, done, undo, remove, rename or a habit's name;
772// Toolbox's tool names and what they run on; Clipboard's clear; Pet's moods. True when taken; `say` answers. `typed`
773// is the room's own box, where a new habit needs no "add".
774async function roomInput($, view, text, say = () => {}, { typed = false } = {}) {
775 const word = text.trim().toLowerCase();
776 if (view === "habits") {
777 const said = await changeHabits($, (h, now) => habitWords(h, text, now, { typed }));
778 if (said == null) return false;
779 say(said);
780 return true;
781 }
782 if (view === "toolbox") {
783 const said = await toolWords(state.toolbox, text, Date.now(), { typed });
784 if (said == null) return false;
785 if (said) say(said);
786 $.ui.invalidate("ui.render");
787 return true;
788 }
789 if (view === "focus") {
790 if (Object.hasOwn(FOCUS_DO, word)) { await focusAct($, word); return true; }
791 const now = await $.clock.now();
792 await syncFocus($, now);
793 if (setLengths(state.focus, word)) { focusChanged($, now); return true; }
794 return false;
795 }
796 if (view === "clipboard" && word === "clear") { clearClips($); return true; }
797 if (view === "pet" && (word === "auto" || MOODS.includes(word))) { setPetMode($, word); return true; }
798 return false;
799}
800
801function savePet($) {
802 $.store.set("pet", petSaved(state.pet))
803 .catch((err) => $.ui.log(`squad-chat: could not save the pet: ${err?.message ?? err}`, { to: "debug" }));
804}
805function setPetMode($, mode) {
806 state.pet.mode = mode;
807 savePet($);
808 $.ui.invalidate("ui.render");
809}
810
811// The clipboard, read every couple of seconds while the room has a tab.
812// The first reader that runs is kept; when none does, the room says so.
813const CLIP_EVERY_MS = 2_000;
814const CLIP_RETRY_MS = 30_000; // while no reader works: tried again this often
815// A reader that ran but had nothing to give: wl-paste and xclip exit 1 until
816// something is copied.
817const CLIP_EMPTY = /nothing is copied|no selection|not available/i;
818const CLIP_ENV = { LC_ALL: "en_US.UTF-8", LANG: "en_US.UTF-8" };
819let clipBusy = false;
820let clipAt = 0;
821async function readClipboard($, now) {
822 const c = state.clipboard;
823 if (clipBusy || now - clipAt < (c.error ? CLIP_RETRY_MS : CLIP_EVERY_MS)) return;
824 clipBusy = true;
825 clipAt = now;
826 try {
827 for (const argv of c.reader ? [c.reader] : CLIP_READERS) {
828 let r;
829 // pbpaste writes in the locale's charset, and with none set it writes
830 // "?" for every character outside ASCII: ask for UTF-8.
831 try { r = await $.process.run(argv, { timeoutMs: 2_000, env: CLIP_ENV }); } catch { continue; }
832 const empty = r.exitCode !== 0 && CLIP_EMPTY.test(String(r.stderr ?? ""));
833 if (r.exitCode !== 0 && !empty && !c.reader) continue;
834 c.reader = argv;
835 if (c.error) { c.error = ""; $.ui.invalidate("ui.render"); }
836 if (r.exitCode === 0 && addClip(c, r.stdout, now)) $.ui.invalidate("ui.render");
837 return;
838 }
839 if (!c.error) {
840 c.error = "Can't read the clipboard here: install wl-clipboard or xclip (macOS has pbpaste).";
841 $.ui.invalidate("ui.render");
842 }
843 } finally {
844 clipBusy = false;
845 }
846}
847
848// The clipboard read once, when the Toolbox's paste is pressed: the text,
849// or null when there's no reader here.
850async function readClipOnce($) {
851 const c = state.clipboard;
852 for (const argv of c.reader ? [c.reader] : CLIP_READERS) {
853 let r;
854 try { r = await $.process.run(argv, { timeoutMs: 2_000, env: CLIP_ENV }); } catch { continue; }
855 if (r.exitCode !== 0 && !c.reader) continue;
856 c.reader = argv;
857 return r.exitCode === 0 ? String(r.stdout ?? "") : "";
858 }
859 return null;
860}
861
862// The Toolbox's buttons: a tool picked, run again, a result copied, a
863// secret shown, the clipboard pasted in.
864async function toolAct($, fn) {
865 try { await fn(state.toolbox, Date.now()); } catch (err) {
866 $.ui.log(`squad-chat: the toolbox: ${err?.message ?? err}`, { to: "debug" });
867 }
868 $.ui.invalidate("ui.render");
869}
870
871// A notice over the box goes NOTICE_MS after it's first drawn, unless
872// another has taken its place. One with Cancel beside it goes with its undo.
873let noticeDrawn = "";
874function fadeNotice($) {
875 if (state.notice === noticeDrawn) return;
876 const text = noticeDrawn = state.notice;
877 if (!text) return;
878 $.clock.sleep(NOTICE_MS).then(() => {
879 if (state.notice !== text || state.undo?.text === text) return;
880 state.notice = "";
881 $.ui.invalidate("ui.render");
882 }).catch(() => {});
883}
884
885async function copyTool($, text, surface) {
886 await copySnippet($, text, surface);
887 if (state.notice !== "Copied.") return;
888 const at = Date.now();
889 state.toolbox.copiedAt = at;
890 // The band says "copied" for a moment, then goes back to the result.
891 $.clock.sleep(5_000).then(() => { if (state.toolbox.copiedAt === at) $.ui.invalidate("ui.render"); }).catch(() => {});
892}
893
894async function pasteTool($) {
895 const text = await readClipOnce($);
896 if (text == null) { state.notice = "Can't read the clipboard here: install wl-clipboard or xclip (macOS has pbpaste)."; return $.ui.invalidate("ui.render"); }
897 if (!text.trim()) { state.notice = "The clipboard is empty."; return $.ui.invalidate("ui.render"); }
898 const cut = setToolInput(state.toolbox, text);
899 state.notice = cut ? `Pasted the first ${MAX_TOOL_INPUT.toLocaleString("en-US")} characters.` : "";
900 await toolAct($, (tb, now) => toolAgain(tb, now));
901}
902
903function clearClips($) {
904 state.clipboard.items = [];
905 $.ui.invalidate("ui.render");
906}
907
908async function copyClip($, id, surface) {
909 const item = state.clipboard.items.find((x) => x.id === id);
910 if (item) await copySnippet($, item.text, surface);
911}
912
913// The terminal draws Clawd a frame per redraw: while the Pet room is on
914// show there, redraw as fast as its frames go. The desktop animates itself.
915let paneSurface = null;
916async function petLoop($) {
917 for (;;) {
918 const shown = paneSurface === "terminal" && state.paneShown && activeView() === "pet";
919 await $.clock.sleep(shown ? Math.max(100, petFrameMs()) : 1000);
920 if (state.ended) return;
921 if (shown) $.ui.invalidate("ui.render");
922 }
923}
924
925// What a built-in room's drawing changes with as time passes. Usage moves by
926// the second only while a subagent runs (its spinner and timer); otherwise
927// the session's span and the spend buckets move by the minute. A redraw a
928// second for nothing made the desktop's input box flicker all through a turn.
929// Habits, Toolbox, Clipboard and Pet have nothing that moves by the second
930// (Clawd's frames have a loop of their own), so they keep to the minute too.
931let lastFrame = "";
932const BY_MINUTE = new Set(["habits", "toolbox", "clipboard", "pet"]);
933export function frameKey(view, now) {
934 if (BY_MINUTE.has(view) || (view === "usage" && !agentCounts(state.usage).running)) return `${view}:${Math.floor(now / 60_000)}`;
935 return `${view}:${Math.floor(now / 1000)}`;
936}
937
938// One loop for the built-in rooms: a redraw a second while something runs
939// (spinners, timers), the agents' statuses, the heartbeat, and the Git poll.
940async function tick($) {
941 for (;;) {
942 await $.clock.sleep(1000);
943 if (state.ended) return;
944 if (!state.sysRooms.length) continue;
945 const view = activeView();
946 if (agentCounts(state.usage).running) {
947 try { if (applyAgentList(state.usage, await $.agent.list(), Date.now())) sysChanged($); } catch { /* the next tick */ }
948 }
949 if (view !== "chat" && liveNow()) {
950 const key = frameKey(view, Date.now());
951 if (key !== lastFrame) { lastFrame = key; $.ui.invalidate("ui.render"); }
952 }
953 if (state.sysRooms.includes("agents")) beat($, false);
954 if (state.sysRooms.includes("git")) {
955 const shown = view === "git" && state.paneShown;
956 void refreshGit($, { ifOlderThan: shown ? GIT_SHOWN_MS : GIT_HIDDEN_MS });
957 }
958 await roomsTick($);
959 }
960}
961
962// Each second, for the mod's own rooms: the timer (its end, the status
963// line, the tab's badge), the clipboard, and Clawd's mood.
964let lastRoomsKey = "";
965let lastPetSave = 0;
966async function roomsTick($) {
967 const now = await $.clock.now();
968 // A round about to count: on today's count as every session has it.
969 if (isRunning(state.focus) && now >= state.focus.endsAt) await syncFocus($, now);
970 const ended = tickFocus(state.focus, now);
971 if (ended) focusEnded($, ended, now);
972 const status = focusStatus(now);
973 if (status !== state.focusStatus) { state.focusStatus = status; $.ui.status(statusText()); }
974 if (state.sysRooms.includes("clipboard")) void readClipboard($, now);
975 const u = state.usage;
976 // Clawd keeps to the wall clock, as its drawing does.
977 const wall = Date.now();
978 const busy = u.activity.state !== "idle" || agentCounts(u).running > 0;
979 // The checks count once the Git room has looked (null until then).
980 const failing = state.git?.status === "ok" ? !!state.git.pr?.checks?.fail : null;
981 const noted = petTick(state.pet, { busy, failing, now: wall });
982 // Kept when something happened, and a minute at a time while you work.
983 if (noted || (busy && wall - lastPetSave > 60_000)) { lastPetSave = wall; savePet($); }
984 // Redraw when the badge or Clawd's mood changes (Clawd walks by the
985 // input box in every room), and at midnight, when every habit is undone
986 // again: its tab's count, its band and its ✓s.
987 const key = JSON.stringify([focusBadge(now)?.text ?? null, state.sysRooms.includes("pet") ? [petMood(wall), state.pet.log.length, state.pet.log[0]?.at] : null,
988 state.sysRooms.includes("habits") ? dayOf(wall) : null]);
989 if (key !== lastRoomsKey) { lastRoomsKey = key; $.ui.invalidate("ui.render"); }
990}
991
992// Runs a command body. Its answer and any error go to the transcript as a
993// notice the model never sees; the command itself returns nothing.
994async function answer($, fn) {
995 // One notice per line: a single notice draws newlines as junk.
996 const say = (text) => { for (const line of String(text).split("\n")) $.ui.log(line); };
997 try {
998 await fn((path, body) => callBridge($, path, body), say);
999 } catch (err) {
1000 say(err?.message ?? String(err)); // the engine already labels notices "squad-chat:"
1001 }
1002 return {};
1003}
1004
1005const COMMANDS = [
1006 { name: "chat", description: "squad-chat: open the pane: chat, or a room such as Usage, Git, Agents, Focus or Snippets (notify, dnd, rooms: settings)", argumentHint: "[usage|git|agents|focus|habits|toolbox|clipboard|pet|snippet|monitor|weather|news|stock|lofi|docker|ping | band <room> | rooms <list> | set <room> <setting> <value> | store [words] | install|update|uninstall <room> | notify on|off | dnd on|off|auto]" },
1007 { name: "say", description: "squad-chat: send a message to the current room", argumentHint: "<message>" },
1008 { name: "room", description: "squad-chat: list, switch, join/create, leave or delete rooms", argumentHint: "[name] [passcode] | leave <name> | delete <name>" },
1009 { name: "who", description: "squad-chat: who's online" },
1010 { name: "chat-login", description: "squad-chat: sign in with an emailed code", argumentHint: "<email> | <code>" },
1011 { name: "chat-share", description: "squad-chat: share the selected text, Claude's last code block, your diff, or a Usage/Git/Agents snapshot to the room", argumentHint: "[diff [path] | usage | git | agents] [#room] | to #room | send [#room] | cancel" },
1012 { name: "chat-name", description: "squad-chat: change your display name", argumentHint: "<new name>" },
1013 { name: "chat-logout", description: "squad-chat: sign out on this computer" },
1014 { name: "lofi", description: "squad-chat: music in the background (lo-fi streams, YouTube, your files) through mpv, in the Lo-fi room", argumentHint: "play [name] | pause | next | prev | stop | vol <0-100> | add <url or path> | remove <name> | import" },
1015 { name: "focus", description: "squad-chat: a Pomodoro timer in the Focus room, with a chime when focus or a break ends", argumentHint: "start | pause | skip | reset | <focus min> [break min]" },
1016 { name: "habit", description: "squad-chat: daily habits in the Habits room, each with its streak", argumentHint: "add <name> [x<times a day>] | done <name> | undo <name> | remove <name> | rename <old> -> <new>" },
1017 { name: "tool", description: "squad-chat: developer tools in the Toolbox room: Base64, URL, JWT, UUID, hashes, Unix times, cron, JSON …", argumentHint: "<tool> [input] | base64|url|html|jwt|uuid|ulid|hash|password|lorem|time|base|cron|json|escape|count|case" },
1018 { name: "snippet", description: "squad-chat: save code you reuse (the selection, or Claude's last code block), then copy or share it from the Snippet room", argumentHint: "add <name> | rename <old> -> <new> | delete <name> | copy <name> | share <name> [#room]" },
1019];
1020
1021export function register(on, options) {
1022 on("session.start", async ($, e, next) => {
1023 const r = await next(e);
1024 // One by one: a name Claude Code refuses (one of its own, say) costs that
1025 // command, not the chat.
1026 for (const command of COMMANDS) {
1027 try { await $.command.register({ ...command, immediate: true }); }
1028 catch (err) { $.ui.log(`squad-chat: /${command.name} unavailable: ${err?.message ?? err}`, { to: "debug" }); }
1029 }
1030 state.notify = (await $.store.get("notify")) === true;
1031 const savedDnd = await $.store.get("dnd");
1032 state.dnd = ["on", "off", "auto"].includes(savedDnd) ? savedDnd : "off";
1033 wasQuiet = isQuiet(); // already in effect: no summary for a reload
1034 const savedRooms = await $.store.get("sysRooms");
1035 if (Array.isArray(savedRooms)) state.sysRooms = savedRooms.filter((x) => typeof x === "string" && ROOM_ID.test(x));
1036 // A room that's new in this version gets a tab once, even for people who
1037 // chose their tabs before it existed. Taken away, it stays away.
1038 const offered = await $.store.get("roomsOffered");
1039 const seen = Array.isArray(offered) ? offered : Array.isArray(savedRooms) ? ["usage", "git", "agents"] : [...DEFAULT_ROOMS];
1040 const fresh = DEFAULT_ROOMS.filter((x) => !seen.includes(x));
1041 if (fresh.length) {
1042 state.sysRooms = [...state.sysRooms, ...fresh.filter((x) => !state.sysRooms.includes(x))];
1043 await $.store.set("sysRooms", state.sysRooms);
1044 }
1045 if (!Array.isArray(offered) || fresh.length) await $.store.set("roomsOffered", [...new Set([...seen, ...DEFAULT_ROOMS])]);
1046 const savedView = await $.store.get("view");
1047 if (savedView === "chat" || (typeof savedView === "string" && ROOM_ID.test(savedView))) state.view = savedView;
1048 try { state.sessionId = String(await $.session.id()); } catch { state.sessionId = null; }
1049 await restoreSessionUsage($);
1050 await restoreRooms($);
1051 try { cwdCache = await $.session.cwd(); } catch { cwdCache = null; }
1052 try { state.usage.model = (await $.session.model()) || state.usage.model; } catch { /* the first turn tells */ }
1053 beat($, false); // this session's own row in the Agents room, before any heartbeat goes out
1054 if (state.sysRooms.includes("usage")) void refreshUsage($); // numbers right away after a reload
1055 if (!bridgeStarted) {
1056 bridgeStarted = true;
1057 void runBridge($, options);
1058 tick($).catch(() => { /* unloaded mid-sleep */ });
1059 petLoop($).catch(() => { /* unloaded mid-sleep */ });
1060 }
1061 return r;
1062 });
1063
1064 on("command.run", { command: "chat" }, ($, e) => answer($, async (call, say) => {
1065 const args = String(e.args ?? "").trim();
1066 const asked = args.toLowerCase();
1067 if (asked === "chat" || roomIds().includes(asked)) {
1068 const view = asked;
1069 if (view !== "chat" && !state.sysRooms.includes(view)) return say(`The ${view} room is hidden. Bring it back with /chat rooms +${view}.`);
1070 await setView($, view);
1071 return openPane($);
1072 }
1073 // "/chat band git": the band above the prompt shows Git, the pane stays shut.
1074 const band = /^band\b\s*(\S*)$/i.exec(args);
1075 if (band) {
1076 const want = band[1].toLowerCase();
1077 const list = bandRooms();
1078 if (!want) return say(`The band shows ${activeView()}. /chat band <room> switches it: ${list.join(", ")}. ‹ › on the band do it too.`);
1079 if (!list.includes(want)) return say(`No room called ${want} with a tab. There are ${list.join(", ")}.`);
1080 await setView($, want);
1081 return say(`The band shows ${want}.`);
1082 }
1083 const admin = chatAdmin(call, args, say, { saveRooms: (list) => saveSysRooms($, list) });
1084 if (admin) return admin;
1085 const d = /^dnd\b\s*(.*)$/i.exec(args);
1086 if (d) return dnd(d[1], say, (mode) => setDnd($, mode));
1087 const m = /^notify\s+(on|off)$/i.exec(args);
1088 if (!m) return openPane($);
1089 state.notify = m[1].toLowerCase() === "on";
1090 await $.store.set("notify", state.notify);
1091 say(state.notify ? "Will toast when someone @mentions you." : "Mention toasts off.");
1092 }));
1093 on("command.run", { command: "say" }, ($, e) => answer($, (call, say) => sendMessage(call, e.args, say)));
1094 on("command.run", { command: "room" }, ($, e) => answer($, (call, say) => room(call, e.args, say)));
1095 on("command.run", { command: "who" }, ($) => answer($, (call, say) => who(say)));
1096 on("command.run", { command: "chat-login" }, ($, e) => answer($, async (call, say) => {
1097 if (!String(e.args ?? "").trim()) await openPane($);
1098 await login(call, e.args, say);
1099 }));
1100 on("command.run", { command: "chat-share" }, ($, e) => answer($, (call, say) => share(call, e.args, say, shareSources($))));
1101 on("command.run", { command: "chat-name" }, ($, e) => answer($, (call, say) => rename(call, e.args, say)));
1102 on("command.run", { command: "chat-logout" }, ($) => answer($, (call, say) => logout(call, say)));
1103 on("command.run", { command: "lofi" }, ($, e) => answer($, (call, say) => lofi(call, e.args, say, {
1104 setView: async (view) => { await setView($, view); await openPane($); },
1105 })));
1106 on("command.run", { command: "focus" }, ($, e) => answer($, async (call, say) => {
1107 const args = String(e.args ?? "").trim();
1108 if (!state.sysRooms.includes("focus")) return say("The Focus room is hidden. Bring it back with /chat rooms +focus.");
1109 if (args && !(await roomInput($, "focus", args))) return say("/focus takes start, pause, skip, reset, or the minutes: /focus 50 10.");
1110 if (!args) { await setView($, "focus"); return openPane($); }
1111 const f = state.focus;
1112 say(f.phase === "idle" ? `Focus ${f.work} min, break ${f.rest} min.` : `${state.focusStatus} · ${f.work}/${f.rest} min`);
1113 }));
1114 on("command.run", { command: "habit" }, ($, e) => answer($, async (call, say) => {
1115 const args = String(e.args ?? "").trim();
1116 if (!state.sysRooms.includes("habits")) return say("The Habits room is hidden. Bring it back with /chat rooms +habits.");
1117 if (!args) { await setView($, "habits"); return openPane($); }
1118 if (!(await roomInput($, "habits", args, say))) say("/habit takes add <name>, done <name>, undo <name>, remove <name> or rename <old> -> <new>.");
1119 }));
1120 on("command.run", { command: "tool" }, ($, e) => answer($, async (call, say) => {
1121 const args = String(e.args ?? "").trim();
1122 if (!state.sysRooms.includes("toolbox")) return say("The Toolbox room is hidden. Bring it back with /chat rooms +toolbox.");
1123 if (args && !(await roomInput($, "toolbox", args, say))) return say(TOOL_USAGE);
1124 await setView($, "toolbox");
1125 return openPane($);
1126 }));
1127 on("command.run", { command: "snippet" }, ($, e) => answer($, (call, say) => snippet(call, e.args, say, {
1128 sources: shareSources($),
1129 copy: (text) => copyText($, text, say),
1130 setView: async (view) => { await setView($, view); await openPane($); },
1131 })));
1132
1133 on("ui.render", { component: "Pane" }, ($, e, next) => {
1134 if (e.requestId !== PANE_ID) return next(e);
1135 fadeNotice($);
1136 const props = e.props ?? {};
1137 state.paneFocused = props.isFocused === true;
1138 paneSurface = e.surface;
1139 if (state.paneFocused) void markRead($);
1140 if (!state.paneShown) { state.paneShown = true; syncRooms($); }
1141 // The pane draws lines and charts as Svg where a surface paints them; the
1142 // terminal keeps its glyphs, so it is drawn as though it had no Svg.
1143 const els = $.ui.resolve(e);
1144 return paneView(e.surface === "terminal" ? { ...els, Svg: undefined } : els, { ...props, surface: e.surface }, {
1145 onInput: (value) => { state.draft = value; typingPing($, value); },
1146 onSubmit: (value) => { void submitFromPane($, value); },
1147 onSelectRoom: (id) => { void (async () => { if (state.view !== "chat") await setView($, "chat"); await selectRoom($, id); })(); },
1148 onSelectView: (view) => {
1149 void (async () => {
1150 const before = { current: state.current, count: state.rooms.length, view: state.view };
1151 await setView($, view);
1152 try { await keepFocusAcrossRoomChange($, before); } catch { /* the box is one click away */ }
1153 })();
1154 },
1155 onShare: (verb) => { void shareFromPane($, verb); },
1156 onToggleAddRoom: () => { state.addingRoom = !state.addingRoom; focusAfterDraw($, "add-room"); },
1157 onAddRoom: (id) => { state.addingRoom = false; void submitFromPane($, `/chat rooms +${id}`).then(() => focusAfterDraw($, "compose")); },
1158 onJoinStart: () => { state.join = { step: "name", name: "" }; joinFocus($, "join-name"); },
1159 // What's typed, kept for the buttons beside the field (no redraw: the
1160 // field holds its own text); each key pushes the fold back 5 seconds.
1161 onJoinTyping: (value) => { if (state.join) { state.join.draft = value; armJoinIdle($); } },
1162 onJoinName: (value) => {
1163 const name = String(value ?? "").trim().replace(/^#/, "");
1164 if (!name || /\s/.test(name)) { state.join = { step: "name", name, error: name ? "A room's name is one word." : "Type a room's name." }; return joinFocus($, "join-name"); }
1165 state.join = { step: "pass", name };
1166 joinFocus($, "join-pass");
1167 },
1168 onJoinPass: (value) => { void joinFromPane($, value); },
1169 onJoinBack: () => { state.join = { step: "name", name: state.join?.name ?? "" }; joinFocus($, "join-name"); },
1170 onJoinCancel: () => closeJoin($),
1171 onShareTarget: (id) => {
1172 const r = retargetShare(id);
1173 state.notice = typeof r === "string" ? r : "";
1174 $.ui.invalidate("ui.render");
1175 },
1176 onCopy: (text, surface) => { void copySnippet($, text, surface); },
1177 onShareItem: (item) => shareItemFromPane($, item),
1178 onAction: (room, act) => { void roomAction($, room, act); },
1179 onRedraw: () => $.ui.invalidate("ui.render"),
1180 onSetSetting: (room, key, value) => { void setRoomSetting($, room, key, value); },
1181 onRefresh: () => { void refreshGit($); },
1182 onToggleBreakdown: () => toggleBreakdown($),
1183 onToggleSession: (id) => { if (!state.collapsed.delete(id)) state.collapsed.add(id); $.ui.invalidate("ui.render"); },
1184 // The desktop's messages are tall: three a press there, five on the terminal.
1185 onChatScroll: (dir) => scrollChat($, dir === 0 ? 0 : dir * (paneSurface === "terminal" ? 5 : 3)),
1186 onCycleFilter: () => { state.feedFilter = { all: "here", here: "errors", errors: "all" }[state.feedFilter]; $.ui.invalidate("ui.render"); },
1187 onFocusStart: () => { void focusAct($, "start"); },
1188 onFocusPause: () => { void focusAct($, "pause"); },
1189 onFocusSkip: () => { void focusAct($, "skip"); },
1190 onFocusReset: () => { void focusAct($, "reset"); },
1191 onFocusAdjust: (which, dir) => { void changeFocus($, (f) => focusAdjust(f, which, dir)); },
1192 onHabitToggle: (id) => { void changeHabits($, (h, now) => { toggleHabit(h, id, now); }); },
1193 // ✕ deletes at once; Cancel beside the notice puts it back for 10 seconds.
1194 onHabitDelete: (id) => {
1195 void changeHabits($, (h) => {
1196 const done = deleteHabit(h, id);
1197 if (!done) return;
1198 const undo = { text: done.said, label: "Cancel", until: Date.now() + UNDO_MS, kept: done.kept };
1199 state.notice = done.said;
1200 state.undo = undo;hooks/state.mjs 317 lines1// The mod's one state object, built from the bridge's events. The module's
2// variables start over on every reload; the bridge restarts with it and
3// replays what the state needs (auth, rooms, recent history).
4
5import { createUsage } from "./metrics.mjs";
6import { emptyGit } from "./github.mjs";
7
8export const MAX_MESSAGES = 100; // per room
9
10// The built-in rooms, in tab order. They need no server and no sign-in.
11export const SYS_ROOMS = ["usage", "git", "agents", "focus", "habits", "toolbox", "clipboard", "pet"];
12// Function rooms come from the bridge (manifests in rooms/<id>/room.json).
13// These have tabs until /chat rooms says otherwise. Clipboard reads what
14// you copy, so it waits to be asked for.
15export const DEFAULT_ROOMS = [...SYS_ROOMS.filter((id) => id !== "clipboard"), "snippet", "monitor"];
16export const ROOM_ID = /^[a-z][a-z0-9-]{1,23}$/;
17
18export const state = {
19 bridge: "starting", // starting | ready | restarting | unavailable | unconfigured
20 detail: "", // why the bridge isn't ready
21 socket: null,
22 token: null,
23 auth: "starting", // starting | signed_out | code_sent | signed_in
24 email: null, // where the code went
25 user: null, // { id, name, email }
26 rooms: [], // [{ id, slug, last_read_id, unread }]
27 current: null, // room id
28 messages: new Map(), // room id → [{ id, user, user_id, mine, body, at }] sorted by id
29 online: new Map(), // room id → [{ user_id, name }]
30 typing: new Map(), // room id → [{ user_id, name }] typing there now
31 roomStatus: new Map(), // room id → SUBSCRIBED | CHANNEL_ERROR | ...
32 friends: [], // [{ user_id, name, online, rooms }]
33 notice: "", // last error or hint, shown in the pane
34 undo: null, // { text, label, until }: a button beside that notice that takes it back, for a while
35 draft: "", // what's typed in the pane's input box, kept across redraws
36 paneFocused: false, // the pane holds the keyboard: messages there count as read
37 paneShown: false, // the pane is drawn (the Git room polls faster then)
38 notify: false, // toast @mentions (/chat notify on), kept in $.store
39 mention: null, // newest unseen message that @mentions me, until toasted
40 dnd: "off", // do not disturb: off | on | auto (while Claude works), kept in $.store
41 working: false, // a long Claude turn is running (what "auto" waits for)
42 missed: { messages: 0, mentions: 0 }, // what came in while quiet, for the summary
43 pendingShare: null, // a snippet shown for a look before /share send
44 dividerAt: new Map(), // room id → read marker when the pane last caught up: the "new" line
45 // The built-in rooms.
46 view: "chat", // chat, a built-in room or a function room: what the pane shows, kept in $.store
47 sysRooms: [...DEFAULT_ROOMS], // which built-in and function rooms have tabs (/chat rooms), kept in $.store
48 fn: new Map(), // function room id → { manifest, settings, data: { provider: data }, at, error, stale }
49 fnInvalid: [], // manifests the bridge refused: [{ dir, errors }]
50 fnToasts: [], // function rooms' new alerts, waiting to be toasted
51 usage: createUsage(), // this session's numbers (metrics.mjs)
52 git: emptyGit(), // the Git room's snapshot (github.mjs)
53 focus: null, // the Focus room's timer (focus.mjs), set when the mod loads
54 habits: null, // the Habits room's goals and days (habits.mjs), likewise
55 toolbox: null, // the Toolbox room's tool, input and result (toolbox.mjs), likewise
56 clipboard: null, // the Clipboard room's history (clipboard.mjs), likewise
57 pet: null, // the Pet room's Clawd (pet.mjs), likewise
58 focusStatus: "", // "🍅 18:42" for the status line while a timer runs, kept by the mod
59 sessionId: null,
60 self: null, // this session's latest heartbeat (sessions.mjs)
61 sessions: [], // other sessions' heartbeats, from the bridge
62 feedFilter: "all", // the Agents room's feed: all | here | errors
63 collapsed: new Set(), // sessions whose agent trees are folded in the Agents room
64 addingRoom: false, // the desktop header's "+" is open: the rooms without a tab
65 join: null, // the desktop header's "+ join": { step: "name" | "pass", name, error }
66 moreOpen: new Set(), // VS Code's lists opened past their rows ("room:widget"), for this session
67 dockScroll: { view: null, offset: 0, max: 0 },
68 chatScroll: { room: null, back: 0 }, // the chat scrolled up: `back` of the newest messages hidden below // the docked room's cards, scrolled past `offset` rows
69 ended: false,
70};
71
72// Every room there is besides the chat: built-in first, then the function
73// rooms in the order the bridge found them.
74export function roomIds() {
75 return [...SYS_ROOMS, ...state.fn.keys()];
76}
77
78export function isFnRoom(id) {
79 return state.fn.has(id);
80}
81
82// The rooms with tabs, in tab order.
83export function enabledRooms() {
84 return roomIds().filter((id) => state.sysRooms.includes(id));
85}
86
87// What the pane shows: a built-in or function room, or the chat (a hidden
88// room's tab, or a function room the bridge hasn't reported, falls back to
89// the chat).
90export function activeView() {
91 return state.view !== "chat" && enabledRooms().includes(state.view) ? state.view : "chat";
92}
93
94export function currentRoom() {
95 return state.rooms.find((r) => r.id === state.current) ?? null;
96}
97
98export function roomMessages(roomId = state.current) {
99 return state.messages.get(roomId) ?? [];
100}
101
102export function totalUnread() {
103 return state.rooms.reduce((n, r) => n + (r.unread ?? 0), 0);
104}
105
106// "@ann" or "@Ann," mentions ann, not "@anna".
107export function mentions(body, name) {
108 if (!name) return false;
109 const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
110 return new RegExp(`(^|[^\\w@])@${escaped}(?![\\w-])`, "i").test(body);
111}
112
113// Do not disturb holds right now: switched on, or "auto" and Claude is busy.
114export function isQuiet() {
115 return state.dnd === "on" || (state.dnd === "auto" && state.working);
116}
117
118// The status line: unread counts, or nothing. While quiet, a 🔕 says so.
119// The built-in rooms add a word only when something needs a look: context
120// nearly full, or this branch's checks failing.
121export function statusText() {
122 const extra = sysStatus();
123 if (state.auth !== "signed_in") return extra || undefined;
124 const unread = state.rooms.filter((r) => r.unread > 0);
125 const counts = unread.map((r) => `#${r.slug} ${r.unread}`).join(" · ");
126 if (isQuiet()) return [`🔕 ${counts || "do not disturb"}`, extra].filter(Boolean).join(" · ");
127 if (!unread.length) return extra || undefined;
128 return [`💬 ${counts}`, extra].filter(Boolean).join(" · ");
129}
130
131function sysStatus() {
132 const bits = [];
133 const ctx = state.usage.context?.percent;
134 if (state.sysRooms.includes("usage") && ctx >= 80) bits.push(`◔ ${Math.round(ctx)}%`);
135 if (state.sysRooms.includes("git") && state.git.status === "ok" && state.git.pr?.checks.fail) bits.push("✗ CI");
136 if (state.focusStatus) bits.push(state.focusStatus);
137 return bits.join(" · ");
138}
139
140// "💬 Missed 5 messages · 1 @mention", or "" for nothing. Short enough for
141// one line of a toast.
142export function missedText() {
143 const { messages, mentions: at } = state.missed;
144 if (!messages) return "";
145 const s = (n) => (n === 1 ? "" : "s");
146 return `💬 Missed ${messages} message${s(messages)}${at ? ` · ${at} @mention${s(at)}` : ""}`;
147}
148
149// "sam is typing…" for a room, or "".
150export function typingText(roomId = state.current) {
151 const names = (state.typing.get(roomId) ?? []).filter((u) => u.user_id !== state.user?.id).map((u) => u.name);
152 if (!names.length) return "";
153 if (names.length === 1) return `${names[0]} is typing…`;
154 if (names.length === 2) return `${names[0]} and ${names[1]} are typing…`;
155 return "several people are typing…";
156}
157
158// The latest message in a room (the current one unless said), for the band.
159export function lastMessage(roomId = state.current) {
160 return roomMessages(roomId).at(-1) ?? null;
161}
162
163// The room the band shows: the one with the newest message, whichever room
164// that is. Message ids grow across all rooms. With no messages anywhere, the
165// current room.
166export function bandRoom() {
167 let best = null;
168 for (const r of state.rooms) {
169 const id = lastMessage(r.id)?.id ?? -Infinity;
170 if (id > (best?.id ?? -Infinity)) best = { room: r, id };
171 }
172 return best?.room ?? currentRoom();
173}
174
175function addMessage(m) {
176 const list = state.messages.get(m.room) ?? [];
177 if (list.some((x) => x.id === m.id)) return false;
178 // Live and catch-up copies can interleave: keep the list in id order.
179 let i = list.length;
180 while (i > 0 && list[i - 1].id > m.id) i--;
181 list.splice(i, 0, m);
182 if (list.length > MAX_MESSAGES) list.splice(0, list.length - MAX_MESSAGES);
183 state.messages.set(m.room, list);
184 return true;
185}
186
187// Applies one bridge event; returns true when the pane should redraw.
188export function applyEvent(event) {
189 switch (event.type) {
190 case "ready":
191 state.socket = event.socket;
192 // Without a server the bridge runs for the Agents room's heartbeats alone.
193 if (event.chat === false) return true;
194 state.bridge = "ready";
195 state.detail = "";
196 return true;
197 case "auth":
198 state.auth = event.state;
199 state.user = event.user ?? null;
200 if (event.state === "code_sent") state.email = event.email;
201 if (event.state === "signed_in") state.notice = "";
202 if (event.state === "signed_out") {
203 state.email = null;
204 state.messages.clear();
205 state.online.clear();
206 state.typing.clear();
207 state.friends = [];
208 if (event.reason) state.notice = event.reason;
209 }
210 return true;
211 case "rooms": {
212 const known = new Set(event.rooms.map((r) => r.id));
213 for (const id of [...state.messages.keys()]) if (!known.has(id)) state.messages.delete(id);
214 if (event.current !== state.current) {
215 state.notice = ""; // it was about the old room
216 state.dividerAt.clear();
217 }
218 state.rooms = event.rooms;
219 state.current = event.current;
220 return true;
221 }
222 case "message": {
223 const m = event.message;
224 if (!addMessage(m)) return false;
225 // The bridge keeps the unread count (it knows the read marker and what
226 // it has already counted); a focused pane marks the room read at once.
227 const room = state.rooms.find((r) => r.id === m.room);
228 if (room && typeof event.unread === "number") room.unread = event.unread;
229 const seen = m.room === state.current && state.paneFocused;
230 const mentioned = event.counted && !seen && (!m.kind || m.kind === "text") && mentions(m.body, state.user?.name);
231 if (isQuiet()) {
232 // Nothing pops up now: count it for the summary instead.
233 if (event.counted && !seen) state.missed.messages++;
234 if (mentioned) state.missed.mentions++;
235 } else if (mentioned) state.mention = m;
236 return true;
237 }
238 case "presence":
239 state.online.set(event.room, event.online);
240 return true;
241 case "typing":
242 state.typing.set(event.room, event.users);
243 return true;
244 case "name":
245 // Someone changed their name: messages already here show the new one.
246 for (const list of state.messages.values()) {
247 for (const m of list) if (m.user_id === event.user_id) m.user = event.name;
248 }
249 return true;
250 case "friends":
251 state.friends = event.friends;
252 return true;
253 case "status":
254 state.roomStatus.set(event.room, event.status);
255 return true;
256 case "fnrooms": {
257 const next = new Map();
258 for (const manifest of event.rooms ?? []) {
259 const had = state.fn.get(manifest.id);
260 next.set(manifest.id, { manifest, settings: had?.settings ?? {}, data: had?.data ?? {}, at: had?.at ?? {}, error: had?.error ?? {}, stale: had?.stale ?? {} });
261 }
262 state.fn = next;
263 state.fnInvalid = event.invalid ?? [];
264 return true;
265 }
266 case "fnsettings": {
267 const room = state.fn.get(event.id);
268 if (!room) return false;
269 room.settings = event.values ?? {};
270 return true;
271 }
272 case "fnroom": {
273 const room = state.fn.get(event.id);
274 if (!room) return false;
275 // A failed run with nothing to show (a new bridge has no cache yet)
276 // keeps what this pane already has, marked stale.
277 const keep = event.error && event.data == null && room.data[event.provider] != null;
278 if (!keep) {
279 room.data[event.provider] = event.data;
280 room.at[event.provider] = event.at;
281 }
282 room.error[event.provider] = event.error ?? null;
283 room.stale[event.provider] = keep || !!event.stale;
284 // A provider's alerts ({ id, text }) toast once each, until they clear.
285 if (Array.isArray(event.data?.alerts)) {
286 const was = room.alerted ?? new Set();
287 const now = event.data.alerts.filter((a) => a?.id && a.text);
288 for (const a of now) if (!was.has(`${event.provider}/${a.id}`)) state.fnToasts.push(String(a.text).slice(0, 120));
289 room.alerted = new Set(now.map((a) => `${event.provider}/${a.id}`));
290 }
291 return true;
292 }
293 case "sessions":
294 state.sessions = (event.sessions ?? []).filter((x) => x?.id && x.id !== state.sessionId);
295 return true;
296 case "error":
297 if (event.code === "unconfigured") {
298 state.bridge = "unconfigured";
299 state.detail = event.message;
300 return true;
301 }
302 state.notice = event.message;
303 return true;
304 default:
305 return false;
306 }
307}
308
309// Forget what only a live bridge can vouch for (it is gone or restarting).
310export function resetBridgeState() {
311 state.socket = null;
312 state.auth = "starting";
313 state.roomStatus.clear();
314 state.online.clear();
315 state.typing.clear();
316}
317hooks/commands.mjs 682 lines1// What the person types: slash commands, and the pane's input box (which
2// also takes the same commands, so a passcode or sign-in code typed there
3// never reaches the transcript at all).
4//
5// The hooks module hands in `call(path, body)`, a bridge request, and
6// `say(text)`, the answer: $.ui.log for slash commands (shown, never sent to
7// the model), the pane's notice line for the input box.
8
9import { state, currentRoom, activeView, roomIds, enabledRooms, isFnRoom } from "./state.mjs";
10import { lastCodeBlock, looksLikeDiff, snippetTitle, findSecret, tooBig, displayLines, MAX_TEXT } from "./share.mjs";
11import { snapshotText, hasSnapshot, snapshotKind } from "./sysviews.mjs";
12
13// Commands whose arguments must never reach the model: messages, emails,
14// sign-in codes, room passcodes, snippets.
15export const PRIVATE_ARGS = new Set(["say", "room", "chat-login", "chat-share", "snippet", "lofi", "tool"]);
16
17const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
18const CODE = /^\d[\d\s]{4,12}\d$/;
19
20const NAME = /^[A-Za-z0-9_-]{1,24}$/;
21
22// Sign in with an email (a code follows by email) or, where the server
23// allows it, with just a name (an anonymous account).
24export async function login(call, arg, say) {
25 arg = String(arg ?? "").trim();
26 if (state.auth === "signed_in") return say(`Already signed in as ${state.user?.name}. /chat-logout first to switch accounts.`);
27 if (EMAIL.test(arg)) {
28 await call("/login/start", { email: arg });
29 return say(`Code sent to ${arg}. Type it here (or /chat-login <code>).`);
30 }
31 if (CODE.test(arg)) {
32 if (state.auth !== "code_sent") return say("Ask for a code first: /chat-login <email>");
33 // The answer carries the user: the auth event on stdout may land later.
34 const r = await call("/login/verify", { code: arg.replace(/\s+/g, "") });
35 return say(`Signed in as ${r.user?.name ?? "you"}.`);
36 }
37 if (NAME.test(arg) && state.auth !== "code_sent") {
38 const r = await call("/login/name", { name: arg });
39 return say(`Signed in as ${r.user?.name ?? arg}.`);
40 }
41 return say(state.auth === "code_sent"
42 ? `Enter the code emailed to ${state.email}, or another email address.`
43 : "Sign in with your email (/chat-login you@example.com) or a name of 1-24 letters, digits, - or _.");
44}
45
46// A new display name for this account, unique on the server.
47export async function rename(call, arg, say) {
48 arg = String(arg ?? "").trim().replace(/^@/, "");
49 requireSignedIn();
50 if (!arg) return say(`You're ${state.user?.name}. Change it with /chat-name <new name>.`);
51 if (!NAME.test(arg)) return say("A name is 1-24 letters, digits, - or _.");
52 const r = await call("/name", { name: arg });
53 return say(`You're now ${r.name}.`);
54}
55
56let pendingLogout = 0; // until when a second /chat-logout confirms
57
58export async function logout(call, say) {
59 if (state.auth !== "signed_in") return say("Not signed in.");
60 // An account without an email can't be signed back into: ask twice.
61 if (state.user?.anonymous && Date.now() > pendingLogout) {
62 pendingLogout = Date.now() + 30_000;
63 return say(`You signed in with just a name, so signing out loses "${state.user.name}" and your rooms for good. Run /chat-logout again within 30 seconds to confirm.`);
64 }
65 pendingLogout = 0;
66 await call("/logout", {});
67 return say("Signed out.");
68}
69
70export async function room(call, args, say) {
71 const [slug, ...rest] = String(args ?? "").trim().split(/\s+/).filter(Boolean);
72 const passcode = rest.join(" ") || undefined;
73 requireSignedIn();
74 if (!slug) {
75 if (!state.rooms.length) return say("No rooms yet. Create or join one: /room <name> <passcode>");
76 const list = state.rooms.map((r) => `${r.id === state.current ? "▸" : " "} #${r.slug}${r.unread ? ` (${r.unread} unread)` : ""}`);
77 return say(`Rooms:\n${list.join("\n")}`);
78 }
79 // "/room leave <name>" and "/room delete <name>". A room literally called
80 // "leave" or "delete" is still reachable as "/room #leave".
81 if ((slug === "leave" || slug === "delete") && rest.length) return manageRoom(call, slug, rest[0], say);
82
83 const name = slug.replace(/^#/, "").toLowerCase();
84 const joined = state.rooms.find((r) => r.slug === name);
85 if (joined && !passcode) {
86 await call("/room/select", { room: joined.id });
87 return say(`Now in #${name}.`);
88 }
89 const r = await call("/room", { slug: name, passcode });
90 return say(`Now in #${r.slug}.`);
91}
92
93const CONFIRM_MS = 30_000;
94let pendingDelete = null; // { slug, until }: a delete waiting for its second ask
95
96async function manageRoom(call, action, ref, say) {
97 const name = ref.replace(/^#/, "").toLowerCase();
98 const target = state.rooms.find((r) => r.slug === name);
99 if (!target) return say(`You're not in a room called #${name}.`);
100 if (action === "leave") {
101 await call("/room/leave", { room: target.id });
102 return say(`Left #${name}. Rejoin any time with its passcode.`);
103 }
104 // Deleting is for everyone and can't be undone: ask twice.
105 const now = Date.now();
106 if (!pendingDelete || pendingDelete.slug !== name || now > pendingDelete.until) {
107 pendingDelete = { slug: name, until: now + CONFIRM_MS };
108 return say(`This deletes #${name} and all its messages for everyone in it. Run /room delete ${name} again within 30 seconds to confirm.`);
109 }
110 pendingDelete = null;
111 await call("/room/delete", { room: target.id });
112 return say(`Deleted #${name}.`);
113}
114
115export function who(say) {
116 requireSignedIn();
117 if (!state.friends.length) return say("No friends yet: people show up here once you share a room.");
118 const lines = state.friends.map((f) => `${f.busy ? "◐" : f.online ? "●" : "○"} ${f.name}${f.busy ? " (busy)" : ""} ${f.rooms.map((s) => `#${s}`).join(" ")}`);
119 const n = state.friends.filter((f) => f.online).length;
120 return say(`${n} of ${state.friends.length} online\n${lines.join("\n")}`);
121}
122
123const DND_MODES = {
124 on: "Do not disturb is on: no toasts, and your friends see you as busy. /chat dnd off to end it.",
125 off: "Do not disturb is off.",
126 auto: "Do not disturb turns on by itself while Claude works on something longer than 30 seconds.",
127};
128
129// "/chat dnd [on|off|auto]". `setDnd(mode)` keeps the choice and tells the room.
130export async function dnd(args, say, setDnd) {
131 const mode = String(args ?? "").trim().toLowerCase();
132 if (!mode) return say(`Do not disturb: ${state.dnd}. Change it with /chat dnd on, off or auto.`);
133 if (!(mode in DND_MODES)) return say("Use /chat dnd on, off or auto.");
134 await setDnd(mode);
135 return say(DND_MODES[mode]);
136}
137
138// "/chat rooms usage,git,snippet": which built-in and function rooms have
139// tabs. "all" or "none" too, and "+snippet" or "-git" to add or drop one.
140// `save(list)` keeps the choice.
141export async function sysRooms(args, say, save) {
142 const arg = String(args ?? "").trim().toLowerCase();
143 const known = roomIds();
144 const names = () => enabledRooms().join(", ") || "none";
145 if (!arg) return say(`Rooms with tabs: ${names()}. There are ${known.join(", ")}. Change with /chat rooms ${known.join(",")}, all, none, +name or -name.`);
146 const words = arg === "all" ? [...known] : arg === "none" ? [] : arg.split(/[\s,]+/).filter(Boolean);
147 const unknown = words.map((w) => w.replace(/^[+-]/, "")).filter((x) => !known.includes(x));
148 if (unknown.length) return say(`No room called ${unknown.join(", ")}. There are ${known.join(", ")}.`);
149 let list;
150 if (words.length && words.every((w) => /^[+-]/.test(w))) {
151 const set = new Set(state.sysRooms);
152 for (const w of words) (w[0] === "+" ? set.add(w.slice(1)) : set.delete(w.slice(1)));
153 list = [...set];
154 } else list = words.map((w) => w.replace(/^\+/, ""));
155 // Keep rooms the bridge hasn't reported yet as they were.
156 const pending = state.sysRooms.filter((x) => !known.includes(x));
157 const before = enabledRooms();
158 await save([...known.filter((x) => list.includes(x)), ...pending]);
159 // A room that goes online says where, the moment it gets a tab.
160 const online = enabledRooms().filter((id) => !before.includes(id) && state.fn.get(id)?.manifest.permissions?.hosts?.length)
161 .map((id) => { const m = state.fn.get(id).manifest; return `${m.name} reaches ${m.permissions.hosts.join(", ")}.`; });
162 return say([enabledRooms().length ? `Rooms with tabs: ${names()}.` : "Room tabs hidden.", ...online].join("\n"));
163}
164
165// ---------------------------------------------------------------- the room store
166
167const CONFIRM_STORE_MS = 60_000;
168let pendingStore = null; // { what: "install" | "update" | "uninstall", id, sha256, until }
169
170const confirmed = (what, id) => pendingStore && pendingStore.what === what && pendingStore.id === id && Date.now() < pendingStore.until;
171
172// "/chat store [words]": the rooms other people wrote, and which you have.
173export async function roomStore(call, args, say) {
174 const q = String(args ?? "").trim().toLowerCase();
175 const { rooms } = await call("/store/list", { refresh: q === "refresh" });
176 const shown = rooms.filter((r) => !q || q === "refresh" || `${r.id} ${r.name} ${r.description}`.toLowerCase().includes(q));
177 if (!shown.length) return say(q ? `No room in the store matches "${q}".` : "The store is empty.");
178 const mark = (r) => (r.shipped ? "comes with squad-chat" : !r.compatible ? `needs squad-chat ${r.minSquadChat}` : r.update ? `installed ${r.installed}, update to ${r.version}` : r.installed ? "installed" : "");
179 return say([
180 `Room store: ${shown.length} room${shown.length === 1 ? "" : "s"}`,
181 ...shown.map((r) => ` ${r.icon} ${r.id} · ${r.name} ${r.version}${mark(r) ? ` (${mark(r)})` : ""}: ${r.description}`),
182 "Install one with /chat install <id>.",
183 ].join("\n"));
184}
185
186function describeRoom(r) {
187 return [
188 `${r.icon} ${r.name} ${r.version}${r.author ? ` by ${r.author}` : ""}`,
189 ...(r.description ? [` ${r.description}`] : []),
190 r.hosts.length ? ` Reaches: ${r.hosts.join(", ")}` : " Reaches nothing on the network.",
191 ...(r.settings?.length ? [` Settings: ${r.settings.join(", ")}`] : []),
192 ];
193}
194
195// "/chat install <id>": a look first (what it is, where it reaches), then
196// the same command again to install. It gets a tab.
197export async function installRoom(call, args, say, addTab) {
198 const id = String(args ?? "").trim().toLowerCase();
199 if (!id) return say("Which room? /chat store lists them.");
200 if (confirmed("install", id)) {
201 const { sha256 } = pendingStore;
202 pendingStore = null;
203 const r = await call("/store/install", { id, sha256 });
204 await addTab?.(id);
205 return say(`Installed ${r.name}. Its tab is there now: /chat ${id}.`);
206 }
207 const r = await call("/store/preview", { id });
208 if (r.installed && !r.update) return say(`${r.name} ${r.installed} is installed and up to date.`);
209 pendingStore = { what: "install", id, sha256: r.sha256, until: Date.now() + CONFIRM_STORE_MS };
210 return say([...describeRoom(r), `Run /chat install ${id} again within a minute to install it.`].join("\n"));
211}
212
213// "/chat update [id]": which rooms have a newer version, or update one. A
214// version that reaches new hosts asks first.
215export async function updateRoom(call, args, say) {
216 const id = String(args ?? "").trim().toLowerCase();
217 if (!id) {
218 const { rooms } = await call("/store/list", { refresh: true });
219 const due = rooms.filter((r) => r.update && r.compatible);
220 if (!due.length) return say("Every room you installed is up to date.");
221 return say([...due.map((r) => ` ${r.icon} ${r.id}: ${r.installed} → ${r.version}`), "Update one with /chat update <id>."].join("\n"));
222 }
223 if (confirmed("update", id)) {
224 const { sha256 } = pendingStore;
225 pendingStore = null;
226 const r = await call("/store/install", { id, sha256 });
227 return say(`Updated ${r.name} to ${r.version}.`);
228 }
229 const r = await call("/store/preview", { id });
230 if (!r.installed) return say(`${r.name} isn't installed: /chat install ${id}.`);
231 if (!r.update) return say(`${r.name} ${r.installed} is up to date.`);
232 if (r.hostsChanged) {
233 pendingStore = { what: "update", id, sha256: r.sha256, until: Date.now() + CONFIRM_STORE_MS };
234 return say([`${r.name} ${r.version} reaches different hosts: ${r.hosts.join(", ") || "none"}${r.newHosts.length ? ` (new: ${r.newHosts.join(", ")})` : ""}.`, `Run /chat update ${id} again within a minute to update it.`].join("\n"));
235 }
236 const done = await call("/store/install", { id, sha256: r.sha256 });
237 return say(`Updated ${done.name} to ${done.version}.`);
238}
239
240// "/chat uninstall <id>": removes an installed room, its settings and data.
241export async function uninstallRoom(call, args, say, dropTab) {
242 const id = String(args ?? "").trim().toLowerCase();
243 if (!id) return say("Which room? /chat store marks the ones installed.");
244 if (!confirmed("uninstall", id)) {
245 const name = state.fn.get(id)?.manifest.name ?? id;
246 pendingStore = { what: "uninstall", id, until: Date.now() + CONFIRM_STORE_MS };
247 return say(`This removes ${name}, its settings and what it keeps. Run /chat uninstall ${id} again within a minute to do it.`);
248 }
249 pendingStore = null;
250 const r = await call("/store/uninstall", { id });
251 await dropTab?.(id);
252 return say(`Uninstalled ${r.name}.`);
253}
254
255// "/chat set|store|install|update|uninstall|rooms …", the same at the
256// prompt and in the pane. `saveRooms(list)` saves which rooms have tabs:
257// an installed room gets one, an uninstalled one loses it. Returns false
258// for anything else.
259export function chatAdmin(call, args, say, { saveRooms } = {}) {
260 const m = /^(set|store|install|update|uninstall|rooms)\b\s*(.*)$/i.exec(String(args ?? "").trim());
261 if (!m) return false;
262 const verb = m[1].toLowerCase();
263 const rest = m[2];
264 const addTab = (id) => (state.sysRooms.includes(id) ? null : saveRooms?.([...state.sysRooms, id]));
265 const dropTab = (id) => saveRooms?.(state.sysRooms.filter((x) => x !== id));
266 if (verb === "set") return roomSettings(call, rest, say);
267 if (verb === "store") return roomStore(call, rest, say);
268 if (verb === "install") return installRoom(call, rest, say, addTab);
269 if (verb === "update") return updateRoom(call, rest, say);
270 if (verb === "uninstall") return uninstallRoom(call, rest, say, dropTab);
271 return sysRooms(rest, say, saveRooms);
272}
273
274// A setting's value as typed back: "Taipei, Tokyo", "on".
275function showSetting(v) {
276 if (Array.isArray(v)) return v.length ? v.join(", ") : "(none)";
277 if (typeof v === "boolean") return v ? "on" : "off";
278 return String(v ?? "");
279}
280
281// "/chat set weather cities Taipei, Tokyo": a function room's settings.
282// Without a value it shows them; "+Osaka" or "-Tokyo" changes a list,
283// "default" puts one back. In the pane, "/set cities …" is for the room on
284// show (`room`).
285export async function roomSettings(call, args, say, { room: here = null } = {}) {
286 const words = String(args ?? "").trim().split(/\s+/).filter(Boolean);
287 const id = here ?? (words.shift() ?? "").toLowerCase();
288 const c = here ? "/set" : `/chat set ${id}`;
289 const withSettings = roomIds().filter((x) => state.fn.get(x)?.manifest.settings);
290 if (!isFnRoom(id)) return say(here ? "Open a room with settings first." : `Which room? ${withSettings.length ? `These have settings: ${withSettings.join(", ")}.` : "No room has settings."} /chat set <room> <setting> <value>`);
291 const room = state.fn.get(id);
292 const schema = room.manifest.settings ?? {};
293 const keys = Object.keys(schema);
294 if (!keys.length) return say(`${room.manifest.name} has no settings.`);
295 const [key, ...rest] = words;
296 if (!key) {
297 return say([`${room.manifest.name} settings:`, ...keys.map((k) => ` ${k}: ${showSetting(room.settings[k] ?? schema[k].default)}`), `Change one with ${c} <setting> <value>.`].join("\n"));
298 }
299 const k = key.toLowerCase();
300 if (!keys.includes(k)) return say(`${room.manifest.name} has no setting ${key}. It has ${keys.join(", ")}.`);
301 const st = schema[k];
302 if (!rest.length) {
303 const how = st.type === "list" ? (st.add ? "one or more to add, split by commas, -one to drop" : "a list split by commas, +one to add, -one to drop") : st.type === "enum" ? st.values.join(", ") : st.type === "bool" ? "on or off" : st.type;
304 return say(`${st.label ?? k}: ${showSetting(room.settings[k] ?? st.default)}. Set it with ${c} ${k} <${how}>, or ${c} ${k} default.`);
305 }
306 const r = await call("/fnroom/settings", { room: id, key: k, value: rest.join(" ") });
307 room.settings = r.values ?? room.settings;
308 return say(`${st.label ?? k}: ${showSetting(room.settings[k])}.`);
309}
310
311const SHARE_HOLD_MS = 120_000; // a preview waits this long for a send
312
313// "/chat-share" (what's selected, or the last code block in Claude's reply),
314// "/chat-share diff [path]", then "/chat-share send" or "/chat-share cancel".
315// A "#room" anywhere picks one of your other rooms; the current one otherwise.
316// (A path that starts with "#" can be written "./#name".)
317// In the pane's box it's "/share" (Claude Code's own /share is taken).
318// Nothing goes out without a look first. `sources` reads the session: selection(),
319// messages() and diff(path), each from the hooks module.
320export async function share(call, args, say, sources) {
321 const words = String(args ?? "").trim().split(/\s+/).filter(Boolean);
322 const targets = words.filter((w) => w.startsWith("#"));
323 const [verb, ...rest] = words.filter((w) => !w.startsWith("#"));
324 const c = sources.inPane ? "/share" : "/chat-share";
325 requireSignedIn();
326 if (targets.length > 1) return say("Pick one room to share to.");
327 if (targets.length && verb === "cancel") return say(`${c} cancel takes no room.`);
328 // "/share to #room" points what's waiting at another room, "/share send #room" sends it there.
329 if (verb === "to" || (verb === "send" && targets.length)) {
330 if (!targets.length) return say(`Name the room: ${c} to #room.`);
331 const r = retargetShare(targets[0].slice(1));
332 if (typeof r === "string") return say(r);
333 if (verb === "to") return say(`It will go to #${r.slug}. ${c} send to post it.`);
334 }
335 if (verb === "cancel") {
336 const had = state.pendingShare;
337 state.pendingShare = null;
338 return say(had ? "Dropped it." : "Nothing waiting to share.");
339 }
340 if (verb === "send") return sendShare(call, say, c);
341 let room = currentRoom();
342 if (targets.length) {
343 const name = targets[0].slice(1).toLowerCase();
344 room = state.rooms.find((r) => r.slug === name);
345 if (!room) return say(`You're not in #${name}. Join it first: /room ${name} <passcode>`);
346 }
347 if (!room) return say("Join a room first: /room <name> <passcode>");
348
349 let snippet;
350 if (roomIds().includes(verb) && !hasSnapshot(verb)) {
351 return say(`The ${verb} room has nothing to share${verb === "clipboard" ? ": what you copied stays on this computer" : ""}.`);
352 } else if (roomIds().includes(verb)) {
353 // A card goes as a snippet tagged with the room, a line as plain chat.
354 const body = snapshotText(verb).trimEnd();
355 if (!body.trim()) return say(`The ${verb} room has nothing to share yet.`);
356 snippet = snapshotKind(verb) === "text"
357 ? { kind: "text", body: body.length > MAX_TEXT ? `${body.slice(0, MAX_TEXT - 1)}…` : body }
358 : { kind: "code", lang: verb.slice(0, 20), body };
359 } else if (verb === "diff") {
360 const body = String(await sources.diff(rest.join(" ")) ?? "").replace(/\n$/, "");
361 if (!body.trim()) return say(rest.length ? `No uncommitted changes in ${rest.join(" ")}.` : "No uncommitted changes to share.");
362 snippet = { kind: "diff", lang: "diff", body };
363 } else if (verb) {
364 return say(`Use ${c} [#room], ${c} diff [path] [#room], ${c} ${roomIds().join("|")} [#room], ${c} to #room, ${c} send [#room] or ${c} cancel.`);
365 } else {
366 const selected = String(await sources.selection() ?? "").replace(/^(\s*\n)+/, "").trimEnd();
367 if (selected.trim()) snippet = looksLikeDiff(selected) ? { kind: "diff", lang: "diff", body: selected } : { kind: "code", lang: null, body: selected };
368 else {
369 const block = lastCodeBlock(await sources.messages());
370 if (!block?.body.trim()) return say(`Select some text first, or ask Claude for some code. ${c} diff shares your uncommitted changes.`);
371 snippet = { kind: "code", ...block };
372 }
373 }
374 return stageShare(snippet, room, say, { inPane: sources.inPane, c });
375}
376
377// Holds a snippet for a look before it goes to `room`: the pane draws a
378// preview card, a slash command answers with a few lines of it.
379function stageShare(snippet, room, say, { inPane = false, c = inPane ? "/share" : "/chat-share" } = {}) {
380 const big = tooBig(snippet.body);
381 if (big) return say(`Too big to share: ${big}.${snippet.kind === "diff" ? ` Share one file with ${c} diff <path>.` : " Select a smaller part."}`);
382
383 const secret = findSecret(snippet.body);
384 state.pendingShare = { ...snippet, room: room.id, slug: room.slug, secret, confirmed: false, until: Date.now() + SHARE_HOLD_MS };
385 // The pane draws its own preview card: say only what needs saying.
386 if (inPane) return secret ? say(`⚠ It looks like it has ${secret}. Check it before you send.`) : undefined;
387 const preview = displayLines(snippet.body, snippet.kind).slice(0, 3).map((l) => ` │ ${l.slice(0, 100)}`);
388 return say([
389 `Ready to share to #${room.slug}: ${snippetTitle(snippet)}`,
390 ...preview,
391 ...(secret ? [`⚠ It looks like it has ${secret}. Check it before you send.`] : []),
392 `${c} send to post it, ${c} to #room to pick another room, ${c} cancel to drop it.`,
393 ].join("\n"));
394}
395
396// Something from a function room (a saved snippet's ⇪) to share: held for a
397// look like any snippet, for the current room or `target` ("#room").
398export function shareItem(item, say, { inPane = false, target = null } = {}) {
399 requireSignedIn();
400 let room = currentRoom();
401 if (target) {
402 const name = target.replace(/^#/, "").toLowerCase();
403 room = state.rooms.find((r) => r.slug === name);
404 if (!room) return say(`You're not in #${name}. Join it first: /room ${name} <passcode>`);
405 }
406 if (!room) return say("Join a room first: /room <name> <passcode>");
407 return stageShare({ kind: "code", lang: item.lang ?? null, body: String(item.body ?? "") }, room, say, { inPane });
408}
409
410// ---------------------------------------------------------------- the Snippet room
411
412const SNIPPET_HELP = "Use /snippet add <text> (or /snippet add alone for the selection or Claude's last code block), /snippet rename <old> -> <new>, /snippet delete <name>, /snippet copy <name> or /snippet share <name> [#room].";
413
414// "/snippet add <text>" saves the text, "/snippet add" what's selected or
415// else the last code block in Claude's reply. The list stays on this
416// computer, in the Snippet room.
417// `copy(text)` puts text on the clipboard, `setView(id)` shows a room.
418// A snippet's name as said back: "#2" for a numbered one, "deploy" in quotes.
419const unhash = (name) => String(name).replace(/^#(?=\d+$)/, "");
420const label = (name) => (/^\d+$/.test(name) ? `#${name}` : `"${name}"`);
421
422export async function snippet(call, args, say, { sources, copy, setView, inPane = false } = {}) {
423 const [verb = "", ...rest] = String(args ?? "").trim().split(/\s+/).filter(Boolean);
424 const name = rest.filter((w) => !(verb.toLowerCase() === "share" && w.startsWith("#"))).join(" ");
425 if (!isFnRoom("snippet")) return say("The Snippet room hasn't loaded yet. Try again in a moment.");
426 const act = (action, a) => call("/fnroom/action", { room: "snippet", provider: "list", action, args: a });
427 const find = async (n) => {
428 if (!n) return null;
429 let items = state.fn.get("snippet")?.data.list?.items;
430 if (!items) items = (await call("/fnroom/refresh", { room: "snippet" })).data?.list?.items ?? [];
431 const want = n.replace(/^#(?=\d+$)/, "").toLowerCase(); // "#2" is snippet 2
432 return items.find((x) => x.name.toLowerCase() === want) ?? null;
433 };
434 switch (verb.toLowerCase()) {
435 case "": {
436 if (!state.sysRooms.includes("snippet")) return say("The Snippet room is hidden. Bring it back with /chat rooms +snippet.");
437 return setView?.("snippet");
438 }
439 case "add": case "save": {
440 // "/snippet add <text>" saves the text typed after "add", its lines
441 // kept; "/snippet add" alone, what's selected or else Claude's last
442 // code block. Snippets are numbered: the next is one past the highest.
443 const typed = String(args ?? "").trim().replace(/^\S+\s*/, "").trimEnd();
444 const selected = typed ? "" : String(await sources.selection() ?? "").replace(/^(\s*\n)+/, "").trimEnd();
445 const block = typed ? { body: typed, lang: null }
446 : selected.trim() ? { body: selected, lang: null } : lastCodeBlock(await sources.messages());
447 if (!block?.body?.trim()) return say("Type it after the command (/snippet add <text>), select some text, or ask Claude for some code.");
448 let items = state.fn.get("snippet")?.data.list?.items;
449 if (!items) items = (await call("/fnroom/refresh", { room: "snippet" })).data?.list?.items ?? [];
450 const named = String(1 + Math.max(0, ...items.map((x) => (/^\d+$/.test(x.name) ? Number(x.name) : 0))));
451 const r = await act("add", { name: named, body: block.body, lang: block.lang ?? null });
452 const lines = r.item.body.split("\n").length;
453 const secret = findSecret(r.item.body);
454 return say(`Saved ${label(r.item.name)}${r.item.lang ? ` (${r.item.lang})` : ""}, ${lines} line${lines === 1 ? "" : "s"}.${secret ? ` ⚠ It looks like it has ${secret}. It stays on this computer, but check it before you share it.` : ""}`);
455 }
456 case "delete": case "remove": case "rm": {
457 if (!name) return say("Which one? /snippet delete <name or #number>");
458 const r = await act("delete", { name: unhash(name) });
459 return say(`Deleted ${label(r.item.name)}.`);
460 }
461 case "rename": case "mv": {
462 const m = /^(.+?)\s*(?:->|→)\s*(.+)$/.exec(name) ?? (rest.length === 2 ? [null, rest[0], rest[1]] : null);
463 if (!m) return say("Use /snippet rename <old name> -> <new name>");
464 const r = await act("rename", { name: unhash(m[1].trim()), to: m[2].trim() });
465 return say(`Renamed it "${r.item.name}".`);
466 }
467 case "copy": case "cp": {
468 const item = await find(name);
469 if (!item) return say(name ? `No snippet called "${name}".` : "Which one? /snippet copy <name>");
470 return copy?.(item.body);
471 }
472 case "share": {
473 const item = await find(name);
474 if (!item) return say(name ? `No snippet called "${name}".` : "Which one? /snippet share <name> [#room]");
475 return shareItem(item, say, { inPane, target: rest.find((w) => w.startsWith("#")) ?? null });
476 }
477 default:
478 return say(SNIPPET_HELP);
479 }
480}
481
482// ---------------------------------------------------------------- the Lo-fi room
483
484const LOFI_HELP = "Use /lofi play [name], pause, next, prev, stop, vol <0-100>, add <url, file or folder> [# name], remove <name>, restore (the stations you removed) or import (Pixel Play's playlist).";
485
486// "/lofi add <url or path>", "/lofi play Groove Salad", "/lofi vol 40": the
487// Lo-fi room's player, from the prompt or the pane.
488export async function lofi(call, args, say, { setView } = {}) {
489 const text = String(args ?? "").trim();
490 const [verb = "", ...rest] = text.split(/\s+/).filter(Boolean);
491 const arg = rest.join(" ");
492 if (!isFnRoom("lofi")) return say("The Lo-fi room hasn't loaded yet. Try again in a moment.");
493 const act = (action, a = {}) => call("/fnroom/action", { room: "lofi", provider: "p", action, args: a });
494 switch (verb.toLowerCase()) {
495 case "": {
496 if (!state.sysRooms.includes("lofi")) return say("The Lo-fi room is hidden. Bring it back with /chat rooms +lofi.");
497 return setView?.("lofi");
498 }
499 case "play": {
500 const r = await act("play", arg ? { name: arg } : {});
501 return say(r.playing ? `Playing ${r.playing}.` : "Playing.");
502 }
503 case "pause": case "stop": case "next": case "prev":
504 await act(verb.toLowerCase());
505 return undefined;
506 case "vol": case "volume": {
507 if (!/^\d{1,3}$/.test(arg)) return say("Use /lofi vol <0-100>.");
508 await act("volume", { level: Number(arg) });
509 return say(`Volume ${arg}.`);
510 }
511 case "add": {
512 const [target, ...name] = arg.split(" # ");
513 if (!target.trim()) return say("Add what? /lofi add <url, file or folder> [# name]");
514 const r = await act("add", { target: target.trim(), name: name.join(" # ").trim() || undefined });
515 return say(r.added > 1 ? `Added ${r.added} tracks.` : `Added "${r.first}".`);
516 }
517 case "remove": case "rm": {
518 if (!arg) return say("Which one? /lofi remove <name>");
519 const r = await act("remove", { name: arg });
520 return say(`Removed "${r.removed}".${r.hidden ? " /lofi restore brings it back." : ""}`);
521 }
522 case "restore": {
523 const r = await act("restore", {});
524 return say(r.restored ? `Brought back ${r.restored} station${r.restored === 1 ? "" : "s"}.` : "No stations were removed.");
525 }
526 case "import": {
527 const r = await act("import");
528 return say(r.added ? `Added ${r.added} from Pixel Play's playlist.` : "Everything in Pixel Play's playlist is already here.");
529 }
530 default:
531 return say(LOFI_HELP);
532 }
533}
534
535// Points the waiting snippet at another of your rooms, by slug or id.
536// Returns the room, or what went wrong.
537export function retargetShare(nameOrId) {
538 const p = state.pendingShare;
539 if (!p || Date.now() > p.until) return "Nothing waiting to share.";
540 const name = String(nameOrId).toLowerCase();
541 const room = state.rooms.find((r) => r.id === nameOrId || r.slug === name);
542 if (!room) return `You're not in #${name}. Join it first: /room ${name} <passcode>`;
543 if (room.id !== p.room) Object.assign(p, { room: room.id, slug: room.slug, confirmed: false });
544 return room;
545}
546
547async function sendShare(call, say, c) {
548 const p = state.pendingShare;
549 if (!p || Date.now() > p.until) {
550 state.pendingShare = null;
551 return say(`Nothing waiting to share. Start with ${c} or ${c} diff.`);
552 }
553 if (!state.rooms.some((r) => r.id === p.room)) {
554 state.pendingShare = null;
555 return say(`You're no longer in #${p.slug}.`);
556 }
557 // A likely secret takes a second send.
558 if (p.secret && !p.confirmed) {
559 p.confirmed = true;
560 return say(`This looks like it has ${p.secret}. Run ${c} send again to post it anyway, or ${c} cancel.`);
561 }
562 await call("/send", { text: p.body, room: p.room, kind: p.kind, ...(p.lang ? { lang: p.lang } : {}) });
563 state.pendingShare = null;
564 return say(`Shared to #${p.slug}.`);
565}
566
567export async function sendMessage(call, text, say) {
568 const body = String(text ?? "").trim();
569 if (!body) return;
570 requireSignedIn();
571 if (!currentRoom()) return say("Join a room first: /room <name> <passcode>");
572 await call("/send", { text: body, room: state.current });
573}
574
575function requireSignedIn() {
576 if (state.auth === "starting" || state.bridge !== "ready") {
577 throw new Error(state.bridge === "unavailable" ? state.detail : "Chat is still connecting, try again in a moment.");
578 }
579 if (state.auth !== "signed_in") {
580 throw new Error(state.auth === "code_sent"
581 ? `Enter the code emailed to ${state.email} first.`
582 : "Sign in first: /chat-login you@example.com");
583 }
584}
585
586function showView(view, say, setView) {
587 if (!state.sysRooms.includes(view)) return say(`The ${view} room is hidden. Bring it back with /chat rooms +${view}.`);
588 return setView?.(view);
589}
590
591export const TOOL_USAGE = "/tool takes a tool's name, then what it runs on: /tool uuid 5, /tool hash hello, /tool time 1739000000.";
592
593const HELP = "/room [name] [passcode] · /room leave|delete <name> · /who · /name <new name> · /dnd on|off|auto · /share [diff|usage|git|agents|snippet] [#room] · /share to #room · /snippet add|rename|delete|copy|share · /lofi play|pause|next|add|import · /focus start|pause|skip|reset|<min> <min> · /habit add|done|undo|remove|rename · /tool <name> [input] · /set <setting> <value> (in a room with settings) · /usage · /git · /agents · /focus · /habit · /tool · /clipboard · /pet · /chat · /logout · anything else is a message";
594
595// The pane's input box: commands, the sign-in steps, or a message.
596// `setView(id)` shows a built-in or function room ("chat" for the chat),
597// `refreshGit()` fetches the Git room again, `refreshRoom(id)` a function
598// room, `copy(text)` puts text on the clipboard, `saveRooms(list)` saves
599// which rooms have tabs, `roomInput(view, text, say)` takes words typed in a
600// built-in room of the mod's (Focus's "start" or "50 10"), true if it did.
601export async function paneInput(call, value, say, { setDnd, sources, setView, refreshGit, refreshRoom, copy, saveRooms, roomInput } = {}) {
602 const text = String(value ?? "").trim();
603 if (!text) return;
604 const view = activeView();
605 if (view === "git" && /^r(efresh)?$/i.test(text)) return refreshGit?.();
606 if (!text.startsWith("/") && await roomInput?.(view, text, say, { typed: true })) return;
607 if (isFnRoom(view) && /^r(efresh)?$/i.test(text)) return refreshRoom?.(view);
608 // A room's own keys: "p" in Lo-fi plays or pauses.
609 const key = isFnRoom(view) && text.length === 1 ? state.fn.get(view).manifest.layout.keys?.[text.toLowerCase()] : null;
610 if (key) return call("/fnroom/action", { room: view, action: key, args: {} });
611 // A room that adds through an action ({ action, field }): what's typed,
612 // a URL or a path in Lo-fi, goes to it whole. "/Users/me/song.mp3" is a
613 // path, not a command: a command's name has no "/" or "." in it.
614 const adds = isFnRoom(view) ? state.fn.get(view).manifest.layout.add : null;
615 if (adds && typeof adds === "object" && !/^\/[\w-]+(\s|$)/.test(text)) {
616 const [target, ...name] = text.split(" # ");
617 const r = await call("/fnroom/action", { room: view, action: adds.action, args: { [adds.field]: target.trim(), name: name.join(" # ").trim() || undefined } });
618 if (r?.added > 1) return say(`Added ${r.added} tracks.`);
619 return r?.first ? say(`Added "${r.first}".`) : undefined;
620 }
621 const m = /^\/([\w-]+)\s*([\s\S]*)$/.exec(text);
622 if (m) {
623 const [, cmd, args] = m;
624 switch (cmd) {
625 case "usage": case "git": case "agents": case "clipboard": case "pet": return showView(cmd, say, setView);
626 case "focus":
627 // "/focus 50 10" or "/focus start" does it without leaving the room on show.
628 if (args.trim()) return (await roomInput?.("focus", args.trim())) ? undefined : say("/focus takes start, pause, skip, reset, or the minutes: /focus 50 10.");
629 return showView(cmd, say, setView);
630 case "habit": case "habits":
631 // "/habit add Run" does it without leaving the room on show.
632 if (args.trim()) return (await roomInput?.("habits", args.trim(), say)) ? undefined : say("/habit takes add <name>, done <name>, undo <name>, remove <name> or rename <old> -> <new>.");
633 return showView("habits", say, setView);
634 case "tool": case "tools": case "toolbox":
635 // "/tool hash hello" runs it and shows the room.
636 if (args.trim() && !(await roomInput?.("toolbox", args.trim(), say))) return say(TOOL_USAGE);
637 return showView("toolbox", say, setView);
638 case "chat": {
639 // "/chat git" typed here does what it does at the prompt.
640 const [sub, ...more] = args.trim().toLowerCase().split(/\s+/).filter(Boolean);
641 if (!sub || sub === "chat") return setView?.("chat");
642 if (roomIds().includes(sub)) return showView(sub, say, setView);
643 if (sub === "dnd") return dnd(more.join(" "), say, setDnd);
644 const admin = chatAdmin(call, args, say, { saveRooms });
645 if (admin) return admin;
646 return say(`Here, /chat takes ${roomIds().join(", ")}, dnd, rooms, set, store, install, update or uninstall. Type it at the prompt for the rest.`);
647 }
648 case "room": return room(call, args, say);
649 case "who": return who(say);
650 case "login": case "chat-login": return login(call, args, say);
651 case "logout": case "chat-logout": return logout(call, say);
652 case "name": case "chat-name": return rename(call, args, say);
653 case "say": return sendMessage(call, args, say);
654 case "dnd": return dnd(args, say, setDnd);
655 case "share": return share(call, args, say, sources);
656 case "snippet": return snippet(call, args, say, { sources, copy, setView, inPane: true });
657 case "lofi": return lofi(call, args, say, { setView });
658 case "set": return roomSettings(call, args, say, { room: isFnRoom(view) ? view : null });
659 case "help": return say(HELP);
660 default:
661 if (isFnRoom(cmd)) return showView(cmd, say, setView);
662 return say(`Unknown command /${cmd}. Try /help.`);
663 }
664 }
665 // A room whose layout names an "add" list: what's typed goes into it
666 // ("TSLA" in Stocks, or "TSLA, NVDA"), as /set <list> +TSLA would.
667 const addTo = isFnRoom(view) ? state.fn.get(view).manifest.layout.add : null;
668 if (typeof addTo === "string") {
669 // A list that adds what has no sign ("add": true, Weather's cities)
670 // takes the text whole, split only by commas: "New York" is one city.
671 if (state.fn.get(view).manifest.settings?.[addTo]?.add) return roomSettings(call, `${addTo} ${text}`, say, { room: view });
672 for (const one of text.split(/[,\s]+/).filter(Boolean)) await roomSettings(call, `${addTo} +${one}`, say, { room: view });
673 return;
674 }
675 // In the Snippets room, what's typed (not a command) is a new snippet.
676 if (view === "snippet") return snippet(call, `add ${String(value ?? "").replace(/^\s*\n/, "").trimEnd()}`, say, { sources, copy, setView, inPane: true });
677 if (view !== "chat") return say(`This is the ${view} room: type a command (/help), or pick a chat room to talk.`);
678 // The pane itself shows each sign-in step, so only errors (thrown) need words.
679 if (state.auth === "signed_out" || state.auth === "code_sent") return login(call, text, () => {});
680 return sendMessage(call, text, say);
681}
682hooks/views.mjs 1043 lines1// The chat pane and the band, drawn from state alone (no $ here: the engine
2// follows $ only within the hooks module's own file).
3//
4// Docked (fullscreen, wide terminal):
5// title bar · tabs (built-in rooms, then chat rooms) · FRIENDS card ·
6// room card with grouped messages · input box · key hints
7// A built-in room (Usage, Git, Agents) takes the space under the tabs with
8// its own cards (sysviews.mjs).
9// Inline (above the prompt): one header line, the last few messages, input.
10// Band (pane not up): one line with an Open button.
11
12import { state, currentRoom, roomMessages, lastMessage, bandRoom, totalUnread, typingText, isQuiet, activeView, enabledRooms, roomIds } from "./state.mjs";
13import { theme, palette, nameColor, glyph } from "./theme.mjs";
14import { snippetTitle, snapshotCard, oneLine, displayLines } from "./share.mjs";
15import { cells, rowsFor } from "./widgets.mjs";
16import { roomMeta, sysDock, sysInline, sysBandPieces, sysBadge, sysBandDesktop, textW, hasSnapshot } from "./sysviews.mjs";
17import { petBeside } from "./pet.mjs";
18import { fnHint, fnPlaceholder, fnBandDesktop, fnMeta, fnAdds } from "./fnviews.mjs";
19import * as K from "./bandkit.mjs";
20import { capsule, cycleButtons, CYCLE_CELLS, draw, value as pValue, sub as pSub, msg as pMsg, chip as pChip } from "./bands.mjs";
21import { usageBandDesktop } from "./usageband.mjs";
22
23const GROUP_GAP_MS = 5 * 60_000; // same sender within 5 minutes: one group
24
25// ---------------------------------------------------------------- small helpers
26
27function formatTime(iso) {
28 const d = new Date(iso);
29 return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
30}
31
32function dayKey(iso) {
33 const d = new Date(iso);
34 return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
35}
36
37function dayLabel(iso, now = new Date()) {
38 const d = new Date(iso);
39 const start = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
40 const days = Math.round((start(now) - start(d)) / 86_400_000);
41 if (days === 0) return "Today";
42 if (days === 1) return "Yesterday";
43 return d.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" });
44}
45
46function connection() {
47 if (state.bridge === "unavailable") return { color: theme.error, text: `${glyph.on} unavailable` };
48 if (state.bridge === "unconfigured") return { color: theme.warn, text: `${glyph.off} no server` };
49 if (state.bridge !== "ready") return { color: theme.warn, text: `${glyph.off} ${state.bridge}` };
50 if (state.auth === "code_sent") return { color: theme.warn, text: `${glyph.off} code sent` };
51 if (state.auth !== "signed_in") return { color: theme.muted, text: `${glyph.off} ${state.auth === "starting" ? "connecting" : "signed out"}` };
52 const room = currentRoom();
53 if (!room) return { color: theme.online, text: `${glyph.on} connected` };
54 const status = state.roomStatus.get(room.id);
55 if (status === "SUBSCRIBED" && isQuiet()) return { color: theme.amber, text: `${glyph.busy} busy` };
56 if (status === "SUBSCRIBED") return { color: theme.online, text: `${glyph.on} live` };
57 return { color: theme.warn, text: `${glyph.off} ${status ? "reconnecting" : "joining"}` };
58}
59
60function displayName(m) {
61 return m.mine ? "you" : m.user;
62}
63
64// ---------------------------------------------------------------- messages
65
66// The room's messages as rows: date separators, the "new" divider, a header
67// per group of messages from one sender, and the bodies. Each row knows how
68// many terminal rows it takes at `width`, so the newest ones can be fitted.
69// A bubble is as wide as its text (plus a cell of padding each side), up to
70// about three quarters of the room's width; longer text wraps inside it.
71function bubbleWidth(body, width) {
72 const max = Math.max(12, Math.floor(width * 0.78));
73 const longest = Math.max(...String(body).split("\n").map(cells));
74 return Math.min(max, longest + 2);
75}
76
77function messageRows(list, width, dividerAt) {
78 const rows = [];
79 let prev = null;
80 let dividerShown = false;
81 for (const m of list) {
82 const newDay = !prev || dayKey(prev.at) !== dayKey(m.at);
83 if (newDay) rows.push({ kind: "day", key: `d${m.id}`, text: dayLabel(m.at), height: 1 });
84 const isNew = dividerAt > 0 && !dividerShown && m.id > dividerAt && !m.mine;
85 if (isNew) {
86 rows.push({ kind: "new", key: `n${m.id}`, height: 1 });
87 dividerShown = true;
88 }
89 const sameGroup = prev && !newDay && !isNew && prev.user_id === m.user_id
90 && Date.parse(m.at) - Date.parse(prev.at) < GROUP_GAP_MS;
91 if (!sameGroup) rows.push({ kind: "head", key: `h${m.id}`, m, height: 2 }); // a blank row, then the header
92 if (m.kind === "code" || m.kind === "diff") {
93 const lines = snippetLines(snippetParts(m).body, m.kind);
94 const gap = sameGroup ? 1 : 0; // a blank row from the message above
95 rows.push({ kind: "snippet", key: `m${m.id}`, m, ...lines, gap, height: gap + 1 + lines.shown.length + (lines.more ? 1 : 0) });
96 } else {
97 const bubble = bubbleWidth(m.body, width);
98 rows.push({ kind: "body", key: `m${m.id}`, m, bubble, height: rowsFor(m.body, bubble - 2) });
99 }
100 prev = m;
101 }
102 return rows;
103}
104
105// The desktop's phone layout: the time goes small under the last message of
106// each group instead of beside the name, so each group gets a row after it.
107function withGroupTimes(rows) {
108 const out = [];
109 rows.forEach((r, i) => {
110 // A bubble right under another of the same group sits a little below it.
111 const prev = rows[i - 1];
112 out.push(r.kind === "body" && (prev?.kind === "body" || prev?.kind === "snippet") ? { ...r, gapAbove: true } : r);
113 const next = rows[i + 1];
114 const ends = (r.kind === "body" || r.kind === "snippet") && (!next || next.kind === "head" || next.kind === "day" || next.kind === "new");
115 if (ends) out.push({ kind: "time", key: `t${r.m.id}`, m: r.m, height: 1 });
116 });
117 return out;
118}
119
120// A room's card, shared: its room's color.
121const CARD_COLORS = { usage: theme.usage, git: theme.git, agents: theme.agents, monitor: palette.teal, ping: palette.sand };
122
123// What a snippet draws: a title, and the lines under it. A room's card takes
124// its title from its first line and wears its room's color.
125function snippetParts(m) {
126 const card = snapshotCard(m);
127 return card ? { ...card, color: CARD_COLORS[m.lang] } : { title: `📎 ${snippetTitle(m)}`, body: m.body, color: null };
128}
129
130// A snippet shows its first lines, one terminal row each (never wrapped, so
131// its height is known), and how many more there are. Copy takes it all.
132const SNIPPET_ROWS = 8;
133function snippetLines(body, kind = "code", max = SNIPPET_ROWS) {
134 const all = displayLines(body, kind);
135 return { shown: all.slice(0, max), more: Math.max(0, all.length - max) };
136}
137
138function diffColor(line) {
139 if (line.startsWith("▸ ")) return theme.muted;
140 if (line.startsWith("@@")) return theme.sky;
141 if (line.startsWith("+")) return theme.online;
142 if (line.startsWith("-")) return theme.error;
143 return theme.theirText;
144}
145
146// A card's line: its label dimmed, a bar's fill in the room's color and its
147// track dimmed, and Ping's days as its list draws them (▮ up, ▪ slow, ▯ down).
148const DAY_MARKS = { "▮": theme.online, "▪": theme.amber, "▯": theme.error };
149function cardLine(els, key, line, color) {
150 const { Box, Text } = els;
151 const m = /^\S(?:.*?\S)?( {2,})/.exec(line);
152 const label = m && m[0].length <= 12 ? m[0] : "";
153 const bits = [
154 ...(label ? [{ text: label, color: theme.muted }] : []),
155 ...line.slice(label.length).split(/([━╸]+|─+|▮+|▪+|▯+)/).filter(Boolean)
156 .map((t) => ({ text: t, color: DAY_MARKS[t[0]] ?? (/^[━╸]/.test(t) ? color : t.startsWith("─") ? theme.muted : theme.theirText) })),
157 ];
158 return Box({ key, flexDirection: "row", overflow: "hidden", children: bits.map((b, i) => (i === bits.length - 1
159 ? Box({ key: `b${i}`, flexGrow: 1, flexShrink: 1, minWidth: 0, children: [Text({ key: "t", wrap: "truncate-end", color: b.color, children: b.text })] })
160 : Box({ key: `b${i}`, flexShrink: 0, children: [Text({ key: "t", color: b.color, children: b.text })] }))) });
161}
162
163// The snippet's lines on a dark fill, diffs colored line by line, a card's
164// labels and bars by its room.
165function snippetBody(els, { kind, shown, more, color = null }) {
166 const { Text } = els;
167 return [
168 ...shown.map((line, i) => (color && line ? cardLine(els, `l${i}`, line, color)
169 : Text({ key: `l${i}`, wrap: "truncate-end", color: kind === "diff" ? diffColor(line) : theme.theirText, children: line || " " }))),
170 ...(more ? [Text({ key: "more", color: theme.muted, children: `… ${more} more line${more === 1 ? "" : "s"}` })] : []),
171 ];
172}
173
174// The newest rows that fit in `capacity` terminal rows, never starting
175// with message bodies whose sender header didn't fit.
176function fitRows(rows, capacity) {
177 const shown = [];
178 let used = 0;
179 let i = rows.length - 1;
180 for (; i >= 0; i--) {
181 if (used + rows[i].height > capacity && shown.length) break;
182 used += rows[i].height;
183 shown.unshift(rows[i]);
184 }
185 // A snippet that would open the view without its sender's header (it, or
186 // the header, didn't fit) shows fewer lines under a header instead of
187 // leaving the space empty. First the snippet that didn't fit, else the one
188 // that lost its header.
189 const shrink = (at) => {
190 const row = rows[at];
191 let room = capacity - used;
192 if (shown[0] === row) room += row.height;
193 const own = rows[at - 1]?.kind === "head";
194 const head = own ? rows[at - 1] : { kind: "head", key: `h${row.m.id}-cut`, m: row.m, height: 2 };
195 const gap = own ? row.gap : 0; // a header of its own sits right above it
196 const all = displayLines(snippetParts(row.m).body, row.m.kind);
197 const lines = room - head.height - gap - 1; // below its title
198 const fit = all.length <= lines ? all.length : lines - 1; // keep a row for "… more"
199 if (fit < 2) return false;
200 if (shown[0] === row) { shown.shift(); used -= row.height; }
201 const more = all.length - fit;
202 const cut = { ...row, gap, shown: all.slice(0, fit), more, height: gap + 1 + fit + (more ? 1 : 0) };
203 shown.unshift(head, cut);
204 used += head.height + cut.height;
205 return true;
206 };
207 if (!(i >= 0 && rows[i].kind === "snippet" && shrink(i)) && shown[0]?.kind === "snippet" && shown.length > 1) shrink(i + 1);
208 // Don't open on a group that has lost its header: start at the next one.
209 while (shown.length > 1 && (shown[0].kind === "body" || shown[0].kind === "snippet")) shown.shift();
210 return shown;
211}
212
213function drawRow(els, row, width, onCopy) {
214 const { Box, Text, Button } = els;
215 switch (row.kind) {
216 case "snippet": {
217 // Full width whoever sent it: code reads left to right. A room's card
218 // has its title on a bar of the room's color.
219 const parts = snippetParts(row.m);
220 return Box({ key: row.key, flexShrink: 0, flexDirection: "column", marginTop: row.gap, backgroundColor: theme.theirBubble, children: [
221 Box({ key: "head", flexDirection: "row", justifyContent: "space-between", gap: 1, paddingX: 1, ...(parts.color ? { backgroundColor: parts.color } : {}), children: [
222 Text({ key: "t", bold: true, color: parts.color ? theme.onAccent : theme.amber, wrap: "truncate-end", children: parts.title }),
223 onCopy ? Button({ key: "copy", plain: true, label: "Copy", onPress: (press) => onCopy(row.m.body, press?.surface) }) : null,
224 ].filter(Boolean) }),
225 Box({ key: "body", flexDirection: "column", paddingX: 1, children: snippetBody(els, { kind: row.m.kind, shown: row.shown, more: row.more, color: parts.color }) }),
226 ] });
227 }
228 case "day":
229 return Box({ key: row.key, flexShrink: 0, justifyContent: "center", children: [
230 Text({ key: "t", color: theme.muted, children: `${glyph.rule.repeat(3)} ${row.text} ${glyph.rule.repeat(3)}` }),
231 ] });
232 case "new":
233 // The terminal counts its columns for the rule. The desktop's font is
234 // proportional, where a count of "─" ran past the row and wrapped, so
235 // there the rule is a drawn line that stretches to the room left.
236 if (els.Svg) {
237 const W = 1000;
238 return Box({ key: row.key, flexShrink: 0, flexDirection: "row", alignItems: "center", columnGap: 1, children: [
239 Text({ key: "t", color: theme.accent, bold: true, children: "new" }),
240 Box({ key: "r", flexGrow: 1, width: 0, minWidth: 1, overflow: "hidden", children: [
241 els.Svg({ key: "line", alt: "new messages", height: 2, source: `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="2" viewBox="0 0 ${W} 2" preserveAspectRatio="none"><rect width="${W}" height="2" fill="${theme.accent}"/></svg>` }),
242 ] }),
243 ] });
244 }
245 return Box({ key: row.key, flexShrink: 0, flexDirection: "row", children: [
246 Text({ key: "t", color: theme.accent, bold: true, children: "new " }),
247 Text({ key: "r", color: theme.accent, children: glyph.rule.repeat(Math.max(4, width - 4)) }),
248 ] });
249 case "time":
250 return Box({ key: row.key, flexShrink: 0, flexDirection: "row", justifyContent: row.m.mine ? "flex-end" : "flex-start", paddingX: 1, children: [
251 Text({ key: "t", color: theme.muted, children: formatTime(row.m.at) }),
252 ] });
253 case "head":
254 // The desktop, like a phone: their name over their bubbles, nothing
255 // over yours (they're at the right, in your color), the time under.
256 if (els.Svg) {
257 return Box({ key: row.key, flexShrink: 0, flexDirection: "row", marginTop: 1, paddingX: 1, children: row.m.mine ? [] : [
258 Text({ key: "n", bold: true, color: nameColor(row.m.user_id), wrap: "truncate-end", children: displayName(row.m) }),
259 ] });
260 }
261 // Theirs: "name 12:04" on the left. Yours: "12:04 you" on the right.
262 return Box({ key: row.key, flexShrink: 0, flexDirection: "row", gap: 1, marginTop: 1,
263 justifyContent: row.m.mine ? "flex-end" : "flex-start", children: row.m.mine ? [
264 Text({ key: "t", color: theme.muted, children: formatTime(row.m.at) }),
265 Text({ key: "n", bold: true, color: theme.you, children: "you" }),
266 ] : [
267 Text({ key: "n", bold: true, color: nameColor(row.m.user_id), wrap: "truncate-end", children: displayName(row.m) }),
268 Text({ key: "t", color: theme.muted, children: formatTime(row.m.at) }),
269 ] });
270 default: {
271 // A bubble: yours on the right in the accent, theirs on the left in grey.
272 const mine = row.m.mine;
273 const fill = mine ? theme.mineBubble : theme.theirBubble;
274 // The desktop rounds each bubble with an outline in its own fill, which
275 // also keeps two bubbles in a row apart. Its font is proportional, so
276 // the bubble takes its words' width there, not a count of cells.
277 const round = els.Svg ? { borderStyle: "round", borderColor: fill } : { width: row.bubble };
278 // A gap of a few pixels (a Box is rows tall, so it's an empty drawing).
279 const gap = row.gapAbove && els.Svg ? els.Svg({ key: "gap", source: K.svg(1, 6, ""), alt: "gap", width: 1, height: 6 }) : null;
280 const line = Box({ key: gap ? "line" : row.key, flexShrink: 0, flexDirection: "row", justifyContent: mine ? "flex-end" : "flex-start", children: [
281 Box({ key: "bubble", flexDirection: "column", ...round, flexShrink: 1, paddingX: 1,
282 backgroundColor: fill, children: [
283 Text({ key: "b", wrap: "wrap", color: mine ? theme.mineText : theme.theirText, children: row.m.body }),
284 ] }),
285 ] });
286 return gap ? Box({ key: row.key, flexShrink: 0, flexDirection: "column", children: [gap, line] }) : line;
287 }
288 }
289}
290
291// ---------------------------------------------------------------- building blocks
292
293// A rounded card, full width: a bold label and right-aligned meta on its
294// first row. `grow` makes it take the pane's spare height, its content kept
295// at the bottom (a chat reads upward from the input).
296function card(els, { key, title, titleColor, meta, metaColor, metaNode, children, grow = false, marginTop = 0 }) {
297 const { Box, Text } = els;
298 const head = Box({ key: "head", flexDirection: "row", justifyContent: "space-between", gap: 1, children: [
299 Text({ key: "title", bold: true, color: titleColor, wrap: "truncate-end", children: title }),
300 metaNode ?? (meta ? Text({ key: "meta", color: metaColor ?? theme.muted, children: meta }) : null),
301 ].filter(Boolean) });
302 // A growing card takes the height left and no more (minHeight 0: left to
303 // its content, it would grow past the pane and make the pane scroll), its
304 // newest rows at the bottom and the oldest cut off at the top.
305 const body = grow
306 ? [Box({ key: "body", flexDirection: "column", flexGrow: 1, flexShrink: 1, minHeight: 0, justifyContent: "flex-end", overflow: "hidden", children })]
307 : children;
308 return Box({
309 key, flexDirection: "column", borderStyle: "round", borderColor: theme.border, paddingX: 1, marginTop,
310 flexGrow: grow ? 1 : 0, flexShrink: grow ? 1 : 0, ...(grow ? { minHeight: 0 } : {}), children: [head, ...body],
311 });
312}
313
314function titleBar(els) {
315 const { Box, Text } = els;
316 const conn = connection();
317 const who = state.auth === "signed_in" && state.user ? state.user.name : null;
318 return Box({ key: "titlebar", flexDirection: "row", justifyContent: "space-between", children: [
319 Box({ key: "brand", flexDirection: "row", gap: 1, children: [
320 Text({ key: "logo", color: theme.accent, bold: true, children: `${glyph.brand} squad-chat` }),
321 who ? Text({ key: "me", color: theme.muted, wrap: "truncate-end", children: who }) : null,
322 ].filter(Boolean) }),
323 Text({ key: "conn", color: conn.color, children: conn.text }),
324 ] });
325}
326
327// The tabs: built-in and function rooms first, each in its own color, then
328// a thin rule and the chat rooms. The tab on show is filled with its color;
329// the others are pressable and carry a badge when something there is worth
330// a glance. When the labels would wrap, the rooms not on show are drawn as
331// their icon alone.
332function roomTabs(els, handlers, width) {
333 const { Box, Text, Button } = els;
334 const view = activeView();
335 const compact = tabRows(width, false) > 1;
336 const tabs = [];
337 for (const id of enabledRooms()) {
338 const meta = roomMeta(id);
339 const badge = view === id ? null : sysBadge(id);
340 if (view === id) {
341 tabs.push(Text({ key: `sys-${id}`, bold: true, color: theme.onAccent, backgroundColor: meta.color, children: ` ${meta.icon} ${meta.label} ` }));
342 continue;
343 }
344 const tab = Button({ key: `sys-${id}`, plain: true, label: compact ? ` ${meta.icon}` : ` ${meta.icon} ${meta.label}`, dimColor: !badge, onPress: () => handlers.onSelectView?.(id) });
345 tabs.push(badge ? Box({ key: `sysbox-${id}`, flexDirection: "row", gap: 1, children: [tab, Text({ key: "badge", bold: true, color: badge.color, children: badge.text })] }) : tab);
346 }
347 const chatTabs = [];
348 if (state.auth === "signed_in" && state.rooms.length) {
349 for (const r of state.rooms) {
350 if (r.id === state.current && view === "chat") {
351 chatTabs.push(Text({ key: `tab-${r.id}`, bold: true, color: theme.onAccent, backgroundColor: theme.accent, children: ` #${r.slug} ` }));
352 continue;
353 }
354 const tab = Button({ key: `tab-${r.id}`, plain: true, label: ` #${r.slug}`, dimColor: !r.unread, onPress: () => handlers.onSelectRoom(r.id) });
355 chatTabs.push(r.unread
356 ? Box({ key: `tabbox-${r.id}`, flexDirection: "row", gap: 1, children: [tab, Text({ key: "badge", bold: true, color: theme.amber, children: String(r.unread) })] })
357 : tab);
358 }
359 } else if (enabledRooms().length) {
360 // Signed out or no room yet: one tab back to the chat's own screens.
361 chatTabs.push(view === "chat"
362 ? Text({ key: "tab-chat", bold: true, color: theme.onAccent, backgroundColor: theme.accent, children: " # chat " })
363 : Button({ key: "tab-chat", plain: true, dimColor: true, label: " # chat", onPress: () => handlers.onSelectView?.("chat") }));
364 }
365 const rule = tabs.length && chatTabs.length ? [Text({ key: "rule", color: theme.muted, children: glyph.bar })] : [];
366 return Box({ key: "tabs", flexDirection: "row", flexWrap: "wrap", columnGap: 1, children: [...tabs, ...rule, ...chatTabs] });
367}
368
369// How many rows the tabs take at `width`: they wrap like words. `compact`
370// as roomTabs decides it, unless given.
371// The desktop's header: the ◆ and the built-in rooms as icons on one line
372// (the one shown with its name), a "+" after them that lists the rooms
373// without a tab to add, and live at the end; the chat rooms on a line of
374// their own under it, with "+ join".
375function headerDesk(els, handlers) {
376 const { Box, Text, Button } = els;
377 const view = activeView();
378 const conn = connection();
379 const lines = [];
380 // A pill: rounded, filled, its words set in it. A Text's ground is square
381 // on the desktop, so the tab shown and the badges are drawings (they're
382 // not pressed: the tab shown is already shown, a badge rides its tab).
383 const pill = (key, text, fill, ink, { bold = true, h = 22 } = {}) => {
384 const t = String(text).replace(/[<&>"]/g, "");
385 const tw = Math.ceil(textW(t) * (13 / 11.5)) + [...t].filter((ch) => cells(ch) === 1 && !/[\x20-\x7e]/.test(ch)).length * 4;
386 const W = tw + 16;
387 return els.Svg({ key, alt: t, width: W, height: h, source: `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${h}" viewBox="0 0 ${W} ${h}" font-family="-apple-system, system-ui, sans-serif">`
388 + `<rect width="${W}" height="${h}" rx="${h / 2.6}" fill="${fill}"/>`
389 + `<text x="8" y="${h / 2 + 4.5}" font-size="13" font-weight="${bold ? 600 : 400}" fill="${ink}" textLength="${tw}" lengthAdjust="spacingAndGlyphs">${t}</text></svg>` });
390 };
391 const hex = (c, fallback) => (/^#[0-9a-f]{6}$/i.test(c ?? "") ? c : fallback);
392 const tabs = enabledRooms().map((id) => {
393 const meta = roomMeta(id);
394 if (view === id) return pill(`sys-${id}`, `${meta.icon} ${meta.label}`, hex(meta.color, theme.accent), theme.onAccent);
395 const badge = sysBadge(id);
396 const tab = Button({ key: `sys-${id}`, plain: true, label: ` ${meta.icon}`, dimColor: !badge, onPress: () => handlers.onSelectView?.(id) });
397 return badge ? Box({ key: `sysbox-${id}`, flexDirection: "row", alignItems: "center", columnGap: 1, children: [tab, pill("badge", badge.text, hex(badge.color, theme.amber), theme.onAccent, { h: 18 })] }) : tab;
398 });
399 lines.push(Box({ key: "titlebar", flexDirection: "row", alignItems: "center", columnGap: 1, children: [
400 Text({ key: "logo", color: theme.accent, bold: true, children: glyph.brand }),
401 Box({ key: "tabs", flexDirection: "row", flexWrap: "wrap", alignItems: "center", columnGap: 1, flexShrink: 1, minWidth: 0, children: [
402 ...tabs,
403 Button({ key: "add-room", plain: true, dimColor: !state.addingRoom, label: " +", onPress: () => handlers.onToggleAddRoom?.() }),
404 ] }),
405 Box({ key: "push", flexGrow: 1, minWidth: 1 }),
406 Text({ key: "conn", color: conn.color, children: conn.text }),
407 ] }));
408 // A few pixels between the lines (a Box is rows tall: an empty drawing).
409 const gap = (key) => els.Svg({ key, source: K.svg(1, 6, ""), alt: "gap", width: 1, height: 6 });
410 if (state.addingRoom) {
411 // The rooms without a tab: one press gives each its tab, as
412 // /chat rooms +name does (a room that reaches the web says where).
413 const hidden = roomIds().filter((id) => !enabledRooms().includes(id));
414 lines.push(gap("gap-add"));
415 lines.push(Box({ key: "add-rooms", flexDirection: "row", flexWrap: "wrap", alignItems: "center", columnGap: 2, children: [
416 Text({ key: "l", color: theme.muted, children: hidden.length ? "add a room" : "Every room has a tab. More come from /chat store." }),
417 ...hidden.map((id) => {
418 const meta = roomMeta(id);
419 return Button({ key: `add-${id}`, plain: true, label: `+ ${meta.icon} ${meta.label}`, onPress: () => handlers.onAddRoom?.(id) });
420 }),
421 Button({ key: "add-close", plain: true, dimColor: true, label: "✕", onPress: () => handlers.onToggleAddRoom?.() }),
422 ] }));
423 }
424 // Each chat room a chip: the desktop's own button, rounded and a line
425 // tall (an outlined Box takes a row above and below), its unread count in
426 // the accent beside the name. The one shown is a drawn pill, outlined in
427 // the accent; "+ join" a dim button.
428 const outlined = (key, text) => {
429 const t = String(text).replace(/[<&>"]/g, "");
430 const tw = Math.ceil(textW(t) * (13 / 11.5));
431 const W = tw + 20, h = 24;
432 return els.Svg({ key, alt: t, width: W, height: h, source: `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${h}" viewBox="0 0 ${W} ${h}" font-family="-apple-system, system-ui, sans-serif">`
433 + `<rect x="0.75" y="0.75" width="${W - 1.5}" height="${h - 1.5}" rx="7" fill="none" stroke="${theme.accent}" stroke-width="1.5"/>`
434 + `<text x="10" y="16.5" font-size="13" font-weight="600" fill="${theme.accent}" textLength="${tw}" lengthAdjust="spacingAndGlyphs">${t}</text></svg>` });
435 };
436 const chats = [];
437 if (state.auth === "signed_in") {
438 for (const r of state.rooms) {
439 if (r.id === state.current && view === "chat") { chats.push(outlined(`tab-${r.id}`, `#${r.slug}`)); continue; }
440 // A Button holds only its label (older releases refuse Text inside it):
441 // the unread count is a pill beside the chip.
442 const chipBtn = Button({ key: `tab-${r.id}`, label: `#${r.slug}`, onPress: () => handlers.onSelectRoom(r.id) });
443 chats.push(r.unread
444 ? Box({ key: `chipbox-${r.id}`, flexDirection: "row", alignItems: "center", columnGap: 1, children: [chipBtn, pill("badge", String(r.unread), theme.accent, theme.onAccent, { h: 18 })] })
445 : chipBtn);
446 }
447 // "+ join" opens one field at a time to its right: the room's name, then
448 // (Enter, or next) its passcode with the name as a chip before it.
449 // It stays where it is and opens the fields to its right; pressed
450 // again it folds them. A button a press takes away took the pane's focus
451 // with it (the next click only gave it back), so the buttons here stay:
452 // a plain one (the desktop's own chip lost clicks to a redraw), and one
453 // "next →" that turns into "Join" under the same key.
454 const j = state.join;
455 chats.push(Button({ key: "join-room", plain: true, dimColor: !j, label: "+ join", onPress: () => (j ? handlers.onJoinCancel?.() : handlers.onJoinStart?.()) }));
456 if (j) {
457 if (j.step === "pass") chats.push(Button({ key: "join-back", label: `#${j.name}`, onPress: () => handlers.onJoinBack?.() }));
458 // The field's own submit button shows only while it has the focus, so
459 // a click elsewhere hid it and moved what came after it: the button
460 // here is drawn always, and reads what was typed (onInput).
461 chats.push(j.step === "name"
462 ? els.Input({ key: "join-name", placeholder: "room name", ...(j.name ? { value: j.name } : {}), onInput: (v) => handlers.onJoinTyping?.(v), onSubmit: (v) => handlers.onJoinName?.(v) })
463 : els.Input({ key: "join-pass", placeholder: "passcode", onInput: (v) => handlers.onJoinTyping?.(v), onSubmit: (v) => handlers.onJoinPass?.(v) }));
464 chats.push(Button({ key: "join-go", plain: true, label: j.step === "name" ? "next →" : "Join", onPress: () => (state.join?.step === "name"
465 ? handlers.onJoinName?.(state.join?.draft ?? state.join?.name ?? "")
466 : handlers.onJoinPass?.(state.join?.draft ?? "")) }));
467 chats.push(Button({ key: "join-cancel", plain: true, dimColor: true, label: "✕", onPress: () => handlers.onJoinCancel?.() }));
468 }
469 } else {
470 chats.push(view === "chat"
471 ? outlined("tab-chat", "# chat")
472 : Button({ key: "tab-chat", dimColor: true, label: "# chat", onPress: () => handlers.onSelectView?.("chat") }));
473 }
474 lines.push(gap("gap-chats"));
475 lines.push(Box({ key: "chats", flexDirection: "row", flexWrap: "wrap", alignItems: "center", columnGap: 1, children: [
476 Text({ key: "l", color: theme.muted, children: "chats" }),
477 ...chats,
478 ] }));
479 if (state.join?.error) lines.push(Text({ key: "join-error", color: theme.error, wrap: "wrap", children: `✗ ${state.join.error}` }));
480 return lines;
481}
482
483function tabRows(width, compact = tabRows(width, false) > 1) {
484 const view = activeView();
485 const widths = enabledRooms().map((id) => {
486 const badge = view === id ? null : sysBadge(id);
487 const meta = roomMeta(id);
488 const label = view === id ? ` ${meta.icon} ${meta.label} ` : compact ? ` ${meta.icon}` : ` ${meta.icon} ${meta.label}`;
489 return cells(label) + (badge ? 1 + cells(badge.text) : 0);
490 });
491 if (widths.length) widths.push(1); // the rule
492 if (state.auth === "signed_in" && state.rooms.length) {
493 for (const r of state.rooms) widths.push(cells(` #${r.slug} `) + (r.unread ? 1 + String(r.unread).length : 0));
494 } else if (widths.length) widths.push(8);
495 let rows = 1;
496 let used = 0;
497 for (const w of widths) {
498 if (used && used + 1 + w > width) { rows++; used = w; } else used += (used ? 1 : 0) + w;
499 }
500 return rows;
501}
502
503function friendsCard(els, width) {
504 const { Box, Text } = els;
505 const friends = state.friends;
506 const online = friends.filter((f) => f.online).length;
507 const chips = friends.map((f) => Box({ key: f.user_id, flexDirection: "row", children: [
508 Text({ key: "dot", color: f.busy ? theme.amber : f.online ? theme.online : theme.muted, children: `${f.busy ? glyph.busy : f.online ? glyph.on : glyph.off} ` }),
509 Text({ key: "name", color: f.online ? undefined : theme.muted, children: f.busy ? `${f.name} (busy)` : f.name }),
510 ] }));
511 // The desktop: each friend a chip, a round initial in their color (grey
512 // while away), the name, and a dot: green online, amber busy, grey away.
513 // One drawing, so it's a slim pill: a bordered Box takes a row above and
514 // below. The drawing can't measure words, so the name is set to the width
515 // guessed for it (textLength), at 13 px from the 11.5 px guess.
516 const deskChip = (f) => {
517 const c = f.online ? nameColor(f.user_id) : "#5A5955";
518 const dot = f.busy ? theme.amber : f.online ? theme.online : "#5A5955";
519 const esc = (t) => String(t).replace(/[<&>"]/g, "");
520 const initial = esc((String(f.name).match(/[\p{L}\p{N}]/u)?.[0] ?? "?").toUpperCase());
521 const name = esc(f.busy ? `${f.name} (busy)` : f.name);
522 const nw = Math.ceil(textW(name) * (13 / 11.5));
523 const W = 3 + 20 + 7 + nw + 8 + 8 + 10, H = 26;
524 const source = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" font-family="-apple-system, system-ui, sans-serif">`
525 + `<rect x="0.5" y="0.5" width="${W - 1}" height="${H - 1}" rx="${(H - 1) / 2}" fill="#262624" stroke="#3A3936"/>`
526 + `<circle cx="13" cy="13" r="10" fill="${c}"/>`
527 + `<text x="13" y="17" text-anchor="middle" font-size="11" font-weight="700" fill="#1F1E1D">${initial}</text>`
528 + `<text x="30" y="17.5" font-size="13" fill="${f.online ? "#E8E6E1" : "#8F8D87"}" textLength="${nw}" lengthAdjust="spacingAndGlyphs">${name}</text>`
529 + `<circle cx="${W - 14}" cy="13" r="4" fill="${dot}"/></svg>`;
530 return els.Svg({ key: f.user_id, source, alt: `${name} ${f.busy ? "busy" : f.online ? "online" : "away"}`, width: W, height: H });
531 };
532 const body = friends.length
533 ? Box({ key: "list", flexDirection: "row", flexWrap: "wrap", columnGap: els.Svg ? 1 : 2, rowGap: 0, children: els.Svg ? friends.map(deskChip) : chips })
534 : Text({ key: "none", color: theme.muted, children: "Share a room's name and passcode to add friends." });
535 const textLen = friends.reduce((n, f) => n + f.name.length + (f.busy ? 7 : 0) + 4, 0);
536 const height = 3 + (friends.length ? rowsFor("x".repeat(textLen), width - 4) : rowsFor("Share a room's name and passcode to add friends.", width - 4));
537 return { node: card(els, { key: "friends", title: "FRIENDS", meta: `${online}/${friends.length} online`, marginTop: 1, children: [body] }), height };
538}
539
540// The terminal lights the frame while the pane holds the keyboard. The
541// desktop's field draws its own focus, and a tree that changed with focus
542// there made the box blink as focus moved, so it stays one color and the
543// field waits for a click instead of taking the focus on every draw. The
544// desktop draws its field at a width of its own, and Clawd sits in the room
545// the frame has past it when the Pet room has a tab.
546function inputBox(els, mode, { onSubmit, onInput }, focused, surface, columns = 0) {
547 const { Box, Text, Input } = els;
548 const terminal = surface !== "desktop";
549 return Box({ key: "compose-box", flexDirection: "row", alignItems: "center", marginTop: 1, flexShrink: 0, borderStyle: "round", borderColor: terminal && !focused ? theme.border : theme.accent, paddingX: 1, children: [
550 Text({ key: "prompt", color: theme.accent, bold: true, children: `${glyph.prompt} ` }),
551 // The desktop's field keeps its own width: Clawd's track takes what's left.
552 Box({ key: "field", flexGrow: terminal ? 1 : 0, ...(terminal ? {} : { flexShrink: 0 }), minWidth: 0, children: [
553 Input({ key: "compose", placeholder: mode.placeholder, submitLabel: mode.label, value: state.draft ?? "", ...(terminal ? { autoFocus: true } : {}), onInput, onSubmit }),
554 ] }),
555 // Clawd walks the room after the field, or sits at its end.
556 ...(terminal ? [] : (() => {
557 const clawd = petBeside(els, { columns });
558 return [clawd.fills ? null : Box({ key: "push", flexGrow: 1, minWidth: 1 }), clawd.row];
559 })()),
560 ].filter(Boolean) });
561}
562
563// The hints under the box keep their row: a cut ("truncate-end") text can
564// otherwise be squeezed by the column as the chat card shrinks, and the
565// desktop drew it cut off at the bottom.
566function hints(els, text) {
567 const { Box, Text } = els;
568 return Box({ key: "hints", flexShrink: 0, children: [Text({ key: "t", color: theme.muted, wrap: "truncate-end", children: text })] });
569}
570
571// "sam is typing…", in the row the key hints use, so nothing moves.
572function typingLine(els, text) {
573 const { Box, Text } = els;
574 return Box({ key: "hints", flexShrink: 0, children: [Text({ key: "t", color: theme.muted, italic: true, wrap: "truncate-end", children: `${glyph.typing} ${text}` })] });
575}
576
577// The notice, and beside it the button that takes back what it says was
578// done (a habit deleted: Cancel), while that can still be taken back.
579function notice(els, handlers) {
580 const { Box, Text, Button } = els;
581 if (!state.notice) return null;
582 const text = Text({ key: "notice", color: theme.warn, wrap: "wrap", children: state.notice });
583 const undo = state.undo;
584 if (!handlers || !undo || undo.text !== state.notice || Date.now() >= undo.until) return text;
585 return Box({ key: "notice-row", flexDirection: "row", alignItems: "center", columnGap: 1, children: [
586 Box({ key: "t", flexShrink: 1, minWidth: 0, children: [text] }),
587 Button({ key: "notice-undo", label: undo.label, onPress: () => handlers.onUndo?.() }),
588 ] });
589}
590
591// What the input box is for right now.
592const SYS_INPUT = {
593 usage: { placeholder: "/git · /agents · /share usage [#room] · /help", label: "run" },
594 git: { placeholder: "r to refresh · /share git [#room] · /help", label: "run" },
595 agents: { placeholder: "/usage · /git · /share agents [#room] · /help", label: "run" },
596 focus: { placeholder: "start · pause · skip · reset · 50 10 sets the minutes", label: "run" },
597 habits: { placeholder: "a new habit: Read 30 min, or Water x8 for 8 times a day", label: "add" },
598 toolbox: { placeholder: "text for the tool, a tool's name, or /tool hash hello", label: "run" },
599 clipboard: { placeholder: "clear · /help", label: "run" },
600 pet: { placeholder: "auto, or a mood: vibe typing wave cheer sleepy …", label: "run" },
601};
602function inputMode() {
603 const view = activeView();
604 if (view === "snippet" || fnAdds(view)) return { placeholder: fnPlaceholder(view), label: "add" }; // what's typed there is saved
605 if (view !== "chat") return SYS_INPUT[view] ?? { placeholder: fnPlaceholder(view), label: "run" };
606 if (state.bridge !== "ready") return null;
607 if (state.auth === "signed_out") return { placeholder: "you@example.com, or a name", label: "continue" };
608 if (state.auth === "code_sent") return { placeholder: "8-digit code from the email", label: "sign in" };
609 if (state.auth !== "signed_in") return null;
610 if (!currentRoom()) return { placeholder: "/room <name> <passcode>", label: "join" };
611 return { placeholder: "Message", label: "send" };
612}
613
614// Screens before there's a room to show: sign-in steps, errors, waiting.
615function setupCard(els, width) {
616 const { Text } = els;
617 const line = (key, children, extra = {}) => Text({ key, wrap: "wrap", children, ...extra });
618 if (state.bridge === "unavailable") {
619 return card(els, { key: "setup", marginTop: 1, title: "CAN'T START", titleColor: theme.error, children: [line("why", state.detail)] });
620 }
621 if (state.bridge === "unconfigured") {
622 return card(els, { key: "setup", marginTop: 1, title: "CONNECT A SERVER", titleColor: theme.accent, children: [
623 line("a", "squad-chat talks to your squad's own Supabase server."),
624 line("b", "Ask whoever runs it for the URL and publishable key, or host one yourself (see the README)."),
625 line("c", "Then set them in /config under squad-chat, or run:", { color: theme.muted }),
626 line("d", "claude plugin configure squad-chat@squad-chat", { color: theme.accent }),
627 ] });
628 }
629 if (state.bridge !== "ready" || state.auth === "starting") {
630 return card(els, { key: "setup", marginTop: 1, title: "CONNECTING", meta: "…", children: [line("wait", state.detail || "Starting the chat in the background.", { color: theme.muted })] });
631 }
632 if (state.auth === "signed_out") {
633 return card(els, { key: "setup", marginTop: 1, title: "SIGN IN", meta: "step 1 of 2", children: [
634 line("a", "Chat with your friends while you code."),
635 line("b", "Enter your email to get a sign-in code, or just pick a name if your server allows it.", { color: theme.muted }),
636 ] });
637 }
638 if (state.auth === "code_sent") {
639 return card(els, { key: "setup", marginTop: 1, title: "SIGN IN", meta: "step 2 of 2", children: [
640 line("a", `Code sent to ${state.email}.`),
641 line("b", "Type it below. Wrong address? Enter another email.", { color: theme.muted }),
642 ] });
643 }
644 return card(els, { key: "setup", marginTop: 1, title: "JOIN A ROOM", children: [
645 line("a", "Create a room, or join a friend's with its passcode:"),
646 line("b", "/room <name> <passcode>", { color: theme.accent }),
647 line("c", "Share the name and passcode with whoever you want in it.", { color: theme.muted }),
648 ] });
649}
650
651// ---------------------------------------------------------------- the pane
652
653// `els` is the surface's element table ($.ui.resolve(e)), `props` the Pane's.
654export function paneView(els, props, handlers) {
655 return props.placement === "inline" ? inlineView(els, props, handlers) : dockView(els, props, handlers);
656}
657
658function dockView(els, props, handlers) {
659 const { Box, Text } = els;
660 const width = Math.max(24, (props.bodyColumns || 48));
661 const bodyRows = props.scroll?.bodyRows || 30;
662 const room = currentRoom();
663 const mode = inputMode();
664 const view = activeView();
665 const desk = props.surface === "desktop" && els.Svg;
666 const parts = desk ? headerDesk(els, handlers) : [titleBar(els)];
667 let used = desk ? parts.length : 1;
668
669 if (desk) {
670 // A room's first card sits half a row below the header (a Box is rows
671 // tall, so the gap is an empty drawing); the chat's first card keeps its margin.
672 if (view !== "chat") parts.push(els.Svg({ key: "gap-tabs", source: K.svg(1, 10, ""), alt: "gap", width: 1, height: 10 }));
673 } else if (enabledRooms().length || (state.auth === "signed_in" && state.rooms.length)) {
674 parts.push(roomTabs(els, handlers, width));
675 used += tabRows(width);
676 // The desktop sets a room's first card half a row below its tabs. A Box
677 // is rows tall, so the gap is an empty drawing, sized in pixels; the
678 // chat's first card keeps its own margin.
679 if (props.surface === "desktop" && els.Svg && view !== "chat") {
680 parts.push(els.Svg({ key: "gap-tabs", source: K.svg(1, 10, ""), alt: "gap", width: 1, height: 10 }));
681 }
682 }
683
684 if (view !== "chat") {
685 const n = notice(els, handlers);
686 const pending = shareCard(els, handlers, width);
687 const tail = 1 + 3 + 1 + (n ? rowsFor(state.notice, width) : 0) + (pending?.height ?? 0); // gap + input box + hints + notice + preview
688 // The desktop scrolls the pane itself (its own bar, the wheel and the
689 // trackpad), so there every card is drawn whole and nothing is windowed;
690 // the terminal keeps the cards in a window that fits, with its own bar.
691 const capacity = props.surface === "desktop" ? 1000 : Math.max(4, bodyRows - used - tail - 1); // one row the dock reserves
692 // The room's own scroll: it starts at the top, and cards taller than the
693 // window are laid out a cell narrower to leave the scrollbar its column.
694 if (state.dockScroll.view !== view) state.dockScroll = { view, offset: 0, max: 0 };
695 const scroll = state.dockScroll;
696 let cards = sysDock(els, view, width, capacity, { ...handlers, scroll });
697 if (scroll.max) cards = sysDock(els, view, width - 1, capacity, { ...handlers, scroll });
698 scroll.offset = Math.min(scroll.offset, scroll.max);
699 parts.push(...cards);
700 parts.push(Box({ key: "spacer", flexGrow: 1 }));
701 if (pending) parts.push(pending.node);
702 if (n) parts.push(n);
703 parts.push(inputBox(els, mode, handlers, props.isFocused, props.surface, props.bodyColumns));
704 parts.push(sysHints(els, view, handlers));
705 } else if (state.auth === "signed_in" && room) {
706 const friends = friendsCard(els, width);
707 parts.push(friends.node);
708 used += 1 + friends.height;
709
710 const n = notice(els);
711 const pending = shareCard(els, handlers, width);
712 const tail = 1 + 3 + 1 + (n ? rowsFor(state.notice, width) : 0) + (pending?.height ?? 0); // gap + input box + hints + notice + preview
713 // The gap above the card, its border and head, and one row the dock reserves (its close mark).
714 const capacity = Math.max(3, bodyRows - used - tail - 1 - 3 - 1);
715 const here = (state.online.get(room.id) ?? []).filter((u) => u.user_id !== state.user?.id).length;
716 const list = roomMessages();
717 // Scrolled up (the wheel over the chat, or ▲): the newest `back` stay
718 // below the window. The desktop's rows are taller than the cells counted
719 // here: it gets more than fit, and the card cuts the oldest off at its top.
720 if (state.chatScroll.room !== room.id) state.chatScroll = { room: room.id, back: 0 };
721 const back = Math.min(state.chatScroll.back, Math.max(0, list.length - 1));
722 const upTo = back ? list.slice(0, list.length - back) : list;
723 const fitted = fitRows(messageRows(upTo, width - 4, state.dividerAt?.get(room.id) ?? 0), els.Svg ? capacity * 3 : capacity);
724 // How many are above the window: counted on the terminal. The desktop's
725 // card cuts its top off unseen, so there ▲ shows while anything at all
726 // is above the newest drawn, uncounted.
727 const firstShown = fitted.find((r) => r.m)?.m.id;
728 const older = els.Svg ? (upTo.length > 1 ? -1 : 0) : Math.max(0, list.findIndex((m) => m.id === firstShown));
729 const rows = els.Svg ? withGroupTimes(fitted) : fitted;
730 const body = list.length
731 ? rows.map((r) => drawRow(els, r, width - 4, handlers.onCopy)) // inside the card's border and padding
732 : [Text({ key: "empty", color: theme.muted, children: "No messages yet. Say hi!" })];
733 // ▲ shows older messages, ↓ goes back to the newest; who's here after them.
734 const metaNode = Box({ key: "meta", flexDirection: "row", alignItems: "center", columnGap: 1, flexShrink: 0, children: [
735 older ? els.Button({ key: "chat-older", plain: true, dimColor: true, label: older > 0 ? `▲ ${older} older` : "▲ older", onPress: () => handlers.onChatScroll?.(1) }) : null,
736 back ? els.Button({ key: "chat-newest", plain: true, label: `↓ ${back} newer`, onPress: () => handlers.onChatScroll?.(0) }) : null,
737 Text({ key: "here", color: here ? theme.online : theme.muted, children: here ? `${here} here` : "just you" }),
738 ].filter(Boolean) });
739 parts.push(card(els, {
740 key: "room", title: `#${room.slug}`, titleColor: theme.accent, marginTop: 1, metaNode,
741 children: body, grow: true,
742 }));
743 if (pending) parts.push(pending.node);
744 if (n) parts.push(n);
745 if (mode) parts.push(inputBox(els, mode, handlers, props.isFocused, props.surface, props.bodyColumns));
746 const typing = typingText(room.id);
747 parts.push(typing ? typingLine(els, typing) : hints(els, "enter send · esc back · /room · /who · /help"));
748 } else {
749 parts.push(setupCard(els, width));
750 const n = notice(els);
751 if (n) parts.push(n);
752 if (mode) parts.push(inputBox(els, mode, handlers, props.isFocused, props.surface, props.bodyColumns));
753 if (mode) parts.push(hints(els, state.auth === "signed_in" ? "you can type /room right here" : "enter to continue · esc back"));
754 }
755
756 // Fill the dock's height so the input sits at the bottom.
757 return Box({ flexDirection: "column", height: bodyRows, children: parts });
758}
759
760const SYS_HINTS = {
761 usage: "Context ▸ breaks it down",
762 git: "↻ or r refreshes · ⧉ copies a link",
763 agents: "▾ folds a session · all ▾ filters the feed",
764 focus: "a chime when focus or a break ends",
765 habits: "✓ checks off today · ✕ deletes · rename <old> -> <new>",
766 toolbox: "⧉ copies · kept in memory, never shared",
767 clipboard: "⧉ copies again · kept in memory, never shared",
768 pet: "Clawd follows what goes on, or keeps one mood",
769};
770
771// A built-in room's hints, after a Share button that posts its snapshot
772// (the preview card picks the room).
773function sysHints(els, view, handlers) {
774 const { Box, Text, Button } = els;
775 const share = hasSnapshot(view);
776 return Box({ key: "hints", flexDirection: "row", gap: 1, flexShrink: 0, children: [
777 share ? Box({ key: "share", flexShrink: 0, children: [
778 Button({ key: "share-snapshot", plain: true, label: "⇪ Share", onPress: () => handlers.onShare?.(view) }),
779 ] }) : null,
780 Text({ key: "t", color: theme.muted, wrap: "truncate-end", children: `${share ? "· " : ""}${(els.Svg && view === "git" ? "↻ or r refreshes · ↗ opens a link" : SYS_HINTS[view]) ?? fnHint(view)}` }),
781 ].filter(Boolean) });
782}
783
784// Where a waiting snippet goes: "‹ #room ›", stepping through your rooms
785// (wrapping at either end), then its place in the list and who's there.
786function shareTargets(els, p, handlers) {
787 const { Box, Text, Button } = els;
788 const n = state.rooms.length;
789 if (n < 2) return null;
790 const i = Math.max(0, state.rooms.findIndex((r) => r.id === p.room));
791 const step = (d) => handlers.onShareTarget?.(state.rooms[(i + d + n) % n].id);
792 const here = (state.online.get(p.room) ?? []).filter((u) => u.user_id !== state.user?.id).length;
793 return Box({ key: "to", flexDirection: "row", alignItems: "center", gap: 1, children: [
794 Text({ key: "label", color: theme.muted, children: "to" }),
795 Box({ key: "stepper", flexDirection: "row", flexShrink: 0, children: [
796 Button({ key: "to-prev", plain: true, label: "‹", onPress: () => step(-1) }),
797 Text({ key: "room", bold: true, children: ` #${p.slug} ` }),
798 Button({ key: "to-next", plain: true, label: "›", onPress: () => step(1) }),
799 ] }),
800 Text({ key: "pos", color: theme.muted, wrap: "truncate-end", children: `${i + 1} / ${n} · ` }),
801 Text({ key: "here", color: here ? theme.online : theme.muted, wrap: "truncate-end", children: here ? `${here} here` : "just you" }),
802 ] });
803}
804
805// A snippet waiting for a look before it goes out: where it goes, Send and Cancel.
806const PREVIEW_ROWS = 5;
807function shareCard(els, handlers, width = 48) {
808 const p = state.pendingShare;
809 if (!p || Date.now() > p.until) return null;
810 const { Box, Text, Button } = els;
811 const targets = shareTargets(els, p, handlers);
812 // A line of chat shows as it will read, a card with its title bar, other
813 // snippets their first lines.
814 let preview, rows;
815 if (p.kind === "text") {
816 preview = Box({ key: "text", paddingX: 1, backgroundColor: theme.theirBubble, children: [Text({ key: "t", color: theme.theirText, children: p.body })] });
817 rows = rowsFor(p.body, width - 6);
818 } else {
819 const parts = snippetParts(p);
820 const lines = snippetLines(parts.body, p.kind, PREVIEW_ROWS);
821 preview = Box({ key: "code", flexDirection: "column", backgroundColor: theme.theirBubble, children: [
822 parts.color ? Box({ key: "head", paddingX: 1, backgroundColor: parts.color, children: [Text({ key: "t", bold: true, color: theme.onAccent, wrap: "truncate-end", children: parts.title })] }) : null,
823 Box({ key: "body", flexDirection: "column", paddingX: 1, children: snippetBody(els, { kind: p.kind, ...lines, color: parts.color }) }),
824 ].filter(Boolean) });
825 rows = (parts.color ? 1 : 0) + lines.shown.length + (lines.more ? 1 : 0);
826 }
827 const children = [
828 preview,
829 p.secret ? Text({ key: "secret", color: theme.warn, wrap: "truncate-end", children: `⚠ looks like it has ${p.secret}` }) : null,
830 targets,
831 Box({ key: "actions", flexDirection: "row", gap: 2, marginTop: 1, children: [
832 Button({ key: "send", label: `Send to #${p.slug}`, variant: "primary", onPress: () => handlers.onShare?.("send") }),
833 Button({ key: "cancel", label: "Cancel", onPress: () => handlers.onShare?.("cancel") }),
834 ] }),
835 ].filter(Boolean);
836 const height = 1 + 3 + rows + (p.secret ? 1 : 0) + (targets ? 1 : 0) + 1 + 1; // the gap above it, and one above the buttons
837 return { node: card(els, { key: "share", marginTop: 1, title: "SHARE?", titleColor: theme.amber, meta: snippetTitle(p), children }), height };
838}
839
840// The compact pane's one line for a waiting snippet.
841function pendingLine(els) {
842 const p = state.pendingShare;
843 if (!p || Date.now() > p.until) return null;
844 const to = state.rooms.length > 1 ? ", /share to #room" : "";
845 return els.Text({ key: "share", color: theme.amber, wrap: "truncate-end", children: `📎 ${snippetTitle(p)} for #${p.slug}: /share send${to} or /share cancel` });
846}
847
848// Above the prompt: as little as reads well.
849function inlineView(els, props, handlers) {
850 const { Box, Text } = els;
851 const width = Math.max(24, (props.bodyColumns || 48));
852 const room = currentRoom();
853 const mode = inputMode();
854 const conn = connection();
855 const view = activeView();
856 const parts = [];
857
858 if (view !== "chat") {
859 parts.push(...sysInline(els, view, width, handlers));
860 const share = pendingLine(els);
861 if (share) parts.push(share);
862 } else if (state.auth === "signed_in" && room) {
863 const names = (state.online.get(room.id) ?? []).filter((u) => u.user_id !== state.user?.id).map((u) => u.name);
864 // Where the pane draws pictures (VS Code) the room is picked from a menu
865 // of the rooms joined, each with its unread count. The terminal has /room.
866 const { Select } = els;
867 const pick = els.Svg && Select && state.rooms.length > 1;
868 parts.push(Box({ key: "header", flexDirection: "row", flexWrap: "nowrap", alignItems: "center", justifyContent: "space-between", children: [
869 Box({ key: "left", flexDirection: "row", flexWrap: "nowrap", alignItems: "center", columnGap: 1, flexShrink: 1, minWidth: 0, children: [
870 pick
871 ? Text({ key: "brand", bold: true, color: theme.accent, children: glyph.brand })
872 : Text({ key: "room", bold: true, color: theme.accent, children: `${glyph.brand} #${room.slug}` }),
873 pick ? Select({ key: "room-pick", value: room.id, options: state.rooms.map((r) => ({ value: r.id, label: `#${r.slug}${r.unread ? ` · ${r.unread} new` : ""}` })), onSelect: (id) => handlers.onSelectRoom(id) }) : null,
874 Text({ key: "online", color: names.length ? theme.online : theme.muted, wrap: "truncate-end", children: names.length ? `${glyph.on} ${names.join(", ")}` : "just you" }),
875 ].filter(Boolean) }),
876 Text({ key: "conn", color: conn.color, children: conn.text }),
877 ] }));
878 const list = roomMessages().slice(-5);
879 if (!list.length) parts.push(Text({ key: "empty", color: theme.muted, children: "No messages yet. Say hi!" }));
880 // A name column, filled only where the sender changes.
881 const nameWidth = Math.min(12, Math.max(...list.map((m) => displayName(m).length), 3));
882 let prevUser = null;
883 for (const m of list) {
884 const name = m.user_id === prevUser ? "" : displayName(m).slice(0, nameWidth);
885 prevUser = m.user_id;
886 parts.push(Box({ key: `m${m.id}`, flexDirection: "row", flexWrap: "nowrap", columnGap: 1, children: [
887 Box({ key: "n", width: nameWidth, flexShrink: 0, children: [
888 Text({ key: "t", bold: true, color: m.mine ? theme.you : nameColor(m.user_id), children: name }),
889 ] }),
890 Text({ key: "b", wrap: "truncate-end", children: oneLine(m) }),
891 ] }));
892 }
893 const typing = typingText(room.id);
894 if (typing) parts.push(typingLine(els, typing));
895 const share = pendingLine(els);
896 if (share) parts.push(share);
897 } else {
898 parts.push(titleBar(els));
899 parts.push(setupCard(els, width));
900 }
901 const n = notice(els);
902 if (n) parts.push(n);
903 if (mode) {
904 const { Input } = els;
905 parts.push(Box({ key: "compose-row", flexDirection: "row", marginTop: 0, children: [
906 Text({ key: "prompt", color: theme.accent, bold: true, children: `${glyph.prompt} ` }),
907 Box({ key: "field", flexGrow: 1, children: [
908 Input({ key: "compose", placeholder: mode.placeholder, submitLabel: mode.label, value: state.draft ?? "", autoFocus: true, onInput: handlers.onInput, onSubmit: handlers.onSubmit }),
909 ] }),
910 ] }));
911 }
912 return Box({ flexDirection: "column", children: parts });
913}
914
915// ---------------------------------------------------------------- the band
916
917// The chat room on the desktop: faces of who's online, what's new, and the
918// latest message (or who's typing).
919function chatBandDesktop(els, { onOpen, onCycle, columns }) {
920 const room = bandRoom();
921 const others = (state.online.get(room.id) ?? []).filter((u) => u.user_id !== state.user?.id);
922 const live = state.bridge === "ready" && state.roomStatus.get(room.id) === "SUBSCRIBED";
923 const unreadHere = room.unread ?? 0;
924 const unreadElsewhere = totalUnread() - unreadHere;
925 const sections = [];
926 if (!live) sections.push({ key: "live", color: theme.warn, parts: [pValue("○ reconnecting", theme.warn)] });
927 else {
928 const faces = others.map((u) => ({ initial: String(u.name ?? "?").trim().charAt(0).toUpperCase() || "?", color: nameColor(u.user_id) }));
929 sections.push({ key: "online", color: theme.online, parts: [
930 faces.length ? draw(K.faces(faces), `${faces.length} online`) : null,
931 pValue(String(others.length)),
932 pSub("online"),
933 ], tip: others.length ? [`${others.length} online in #${room.slug}`, ...others.slice(0, 6).map((u) => u.name)] : [`Nobody else in #${room.slug} right now`] });
934 }
935 if (isQuiet()) {
936 const n = unreadHere + unreadElsewhere;
937 sections.push({ key: "quiet", color: theme.muted, parts: [pSub(`${glyph.quiet} ${n ? `${n} new · ` : ""}do not disturb`)] });
938 } else {
939 if (unreadHere || unreadElsewhere) {
940 sections.push({ key: "new", color: theme.accent, parts: [
941 unreadHere ? pChip(`${unreadHere} new`, theme.accent, theme.onAccent) : null,
942 unreadElsewhere ? pSub(`+${unreadElsewhere} elsewhere`) : null,
943 ] });
944 }
945 const typing = typingText(room.id);
946 const last = lastMessage(room.id);
947 if (typing) sections.push({ key: "msg", color: theme.muted, grow: true, parts: [draw(K.typing(theme.muted), typing), pMsg(typing, { dim: true })] });
948 else if (last) {
949 const who = last.mine ? theme.you : nameColor(last.user_id);
950 sections.push({ key: "msg", color: who, grow: true, parts: [pValue(displayName(last), who), pMsg(oneLine(last))] });
951 }
952 }
953 return capsule(els, { room: `${glyph.brand} #${room.slug}`, color: theme.accent, sections, onOpen, onCycle, columns });
954}
955
956// A band's text. The terminal cuts it to its columns, which are exact there.
957// VS Code counts columns in a proportional font's "0"s, too few for the room
958// the text has, so it draws all of it and the row ends it with "…" where the
959// band runs out, as wide or narrow as the panel is.
960function bandMsg(els, view, props, meta, onCycle) {
961 const { Box, Text } = els;
962 const terminal = props.surface === "terminal";
963 const pieces = sysBandPieces(view, terminal ? Math.max(20, (props.bodyColumns || 100) - cells(`${meta.icon} ${meta.label}`) - 16 - (onCycle ? CYCLE_CELLS : 0)) : 0);
964 const text = (p, wrap) => Text({ key: "t", color: p.color, bold: p.bold, wrap, children: p.text });
965 if (terminal) return pieces.map((p, i) => Box({ key: `p${i}`, flexShrink: 0, children: [text(p)] }));
966 // Each piece sits beside a box of the ones after it, which gives way
967 // first: the band shortens from its end, one piece at a time, and only the
968 // piece where it runs out shows "…". Shrink weights alone squeezed them all.
969 const rest = (i) => i >= pieces.length ? [] : [
970 Box({ key: `p${i}`, flexShrink: 1, minWidth: 0, children: [text(pieces[i], "truncate-end")] }),
971 ...(i + 1 < pieces.length ? [Box({ key: `r${i + 1}`, flexDirection: "row", flexWrap: "nowrap", flexShrink: 10000, minWidth: 0, overflow: "hidden", children: rest(i + 1) })] : []),
972 ];
973 return rest(0);
974}
975
976// One line above the prompt while the pane can't be seen (terminal too
977// narrow, or the pane closed): room, who's online, unread, the latest message.
978// The desktop draws it as a capsule of small drawings (bands.mjs).
979export function bandView(els, props, { onOpen, onCycle }) {
980 const { Box, Text, Button } = els;
981 const view = activeView();
982 if (props.surface === "desktop" && els.Svg) {
983 const fit = { onOpen, onCycle, columns: props.bodyColumns || 100 };
984 const desk = view === "chat" ? chatBandDesktop(els, fit)
985 : view === "usage" ? usageBandDesktop(els, props, { onOpen, onCycle })
986 : fnMeta(view) ? fnBandDesktop(view, els, fit)
987 : sysBandDesktop(view, els, fit);
988 if (desk) return desk;
989 }
990 if (view !== "chat") {
991 const meta = roomMeta(view);
992 // VS Code wraps a row that doesn't fit: these give way instead.
993 return Box({ flexDirection: "row", flexWrap: "nowrap", children: [
994 Box({ key: "line", flexDirection: "row", flexWrap: "nowrap", columnGap: 1, flexGrow: 1, flexShrink: 1, minWidth: 0, children: [
995 Box({ key: "room", flexShrink: 0, children: [Text({ key: "t", bold: true, color: meta.color, children: `${meta.icon} ${meta.label}` })] }),
996 Box({ key: "sep", flexShrink: 0, children: [Text({ key: "t", color: theme.muted, children: glyph.bar })] }),
997 Box({ key: "msg", flexDirection: "row", flexWrap: "nowrap", flexShrink: 1, flexGrow: 1, minWidth: 0, overflow: "hidden", children: bandMsg(els, view, props, meta, onCycle) }),
998 ] }),
999 Box({ key: "open-box", flexDirection: "row", columnGap: 1, flexShrink: 0, marginLeft: 1, children: [
1000 ...cycleButtons(els, onCycle),
1001 Button({ key: "open", label: "Open", variant: "primary", onPress: onOpen }),
1002 ] }),
1003 ] });
1004 }
1005 const room = bandRoom();
1006 const here = (state.online.get(room?.id) ?? []).filter((u) => u.user_id !== state.user?.id).length;
1007 const unreadHere = room.unread ?? 0;
1008 const unreadElsewhere = totalUnread() - unreadHere;
1009 const live = state.bridge === "ready" && state.roomStatus.get(room.id) === "SUBSCRIBED";
1010 const last = lastMessage(room.id);
1011 const typing = typingText(room.id);
1012 // Everything but the message keeps its size; the message gives way.
1013 const fixed = (key, children, style = {}) => Box({ key, flexShrink: 0, children: [Text({ key: "t", children, ...style })] });
1014 const bits = [
1015 fixed("room", `${glyph.brand} #${room.slug}`, { bold: true, color: theme.accent }),
1016 fixed("online", live ? `${glyph.on} ${here}` : `${glyph.off} reconnecting`, { color: live ? (here ? theme.online : theme.muted) : theme.warn }),
1017 ];
1018 if (isQuiet()) {
1019 // Do not disturb: counts stay, in grey, and no message text pulls the eye.
1020 const n = unreadHere + unreadElsewhere;
1021 bits.push(fixed("quiet", `${glyph.quiet} ${n ? `${n} new · ` : ""}do not disturb`, { color: theme.muted }));
1022 bits.push(Box({ key: "msg", flexGrow: 1, children: [] }));
1023 } else {
1024 if (unreadHere) bits.push(fixed("unread", ` ${unreadHere} new `, { bold: true, color: theme.onAccent, backgroundColor: theme.accent }));
1025 if (unreadElsewhere) bits.push(fixed("elsewhere", `+${unreadElsewhere}`, { color: theme.muted }));
1026 if (typing) {
1027 bits.push(fixed("sep", glyph.bar, { color: theme.muted }));
1028 bits.push(Box({ key: "msg", flexShrink: 1, flexGrow: 1, minWidth: 0, children: [Text({ key: "t", color: theme.muted, italic: true, wrap: "truncate-end", children: typing })] }));
1029 } else if (last) {
1030 bits.push(fixed("sep", glyph.bar, { color: theme.muted }));
1031 bits.push(fixed("who", displayName(last), { bold: true, color: last.mine ? theme.you : nameColor(last.user_id) }));
1032 bits.push(Box({ key: "msg", flexShrink: 1, flexGrow: 1, minWidth: 0, children: [Text({ key: "t", wrap: "truncate-end", children: oneLine(last) })] }));
1033 }
1034 }
1035 return Box({ flexDirection: "row", children: [
1036 Box({ key: "line", flexDirection: "row", columnGap: 1, flexGrow: 1, flexShrink: 1, children: bits }),
1037 Box({ key: "open-box", flexDirection: "row", columnGap: 1, flexShrink: 0, marginLeft: 1, children: [
1038 ...cycleButtons(els, onCycle),
1039 Button({ key: "open", label: "Open", variant: "primary", onPress: onOpen }),
1040 ] }),
1041 ] });
1042}
1043hooks/metrics.mjs 511 lines1// This session's numbers for the Usage and Agents rooms: what the engine
2// measures (context, rate limits, cost), what each turn used (tokens, cache),
3// how long each tool call took, and which subagents ran. Plain logic: the
4// hooks module feeds it from session.measure, turn.complete, tool.call and
5// agent.spawn.
6
7import { findSecret } from "./share.mjs";
8
9const COST_SAMPLES = 240; // about two hours at one sample per 30 s
10const SAMPLE_EVERY_MS = 30_000;
11const DURATIONS = 200; // per tool, for the percentiles
12const FEED = 40; // newest tool calls kept for the live feed
13const BURN_WINDOW_MS = 15 * 60_000;
14
15export function createUsage() {
16 return {
17 measured: false,
18 context: null, // { tokens, window, percent }
19 breakdown: null, // the /context breakdown, fetched when asked for
20 showBreakdown: false,
21 rateLimits: [], // [{ kind, percentUsed, resetsAt }]
22 hasLimits: false, // ever reported a window (a subscription, not an API key)
23 ctxHistory: [], // context tokens after each main-loop turn, oldest first (the band's chart)
24 cost: null, // { usd }
25 startedAt: null,
26 model: null,
27 costSamples: [], // [{ at, usd }]
28 tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
29 tools: new Map(), // tool name → { count, errors, durations }
30 calls: new Map(), // call key → feed entry, while it runs
31 feed: [], // [{ key, tool, agentId, summary, at, ms, isError, done }], oldest first
32 agents: new Map(), // agent id → { id, type, description, status, parentId, startedAt, endedAt, tools }
33 callsNamed: 0, // tool calls named by their results, so the strata redraw
34 steps: [], // the main loop's requests, oldest first (see stepStarted)
35 overhead: null, // { tokens, biggest: { name, tokens } }: what every request carries before the conversation
36 overheadAt: 0, // stepN when it was last read
37 stepIn: [], // what the next request carries that the last one didn't: [{ kind, label, chars }]
38 stepN: 0,
39 activity: { state: "idle", tool: null, since: 0 }, // idle | thinking | tool
40 };
41}
42
43// ---------------------------------------------------------------- engine figures
44
45// A session.measure event or a $.session.usage() answer.
46export function applyMeasure(u, m, now) {
47 if (!m) return false;
48 u.measured = true;
49 if (m.context) u.context = { tokens: m.context.tokens, window: m.context.window, percent: m.context.percent };
50 if (Array.isArray(m.rateLimits)) {
51 u.rateLimits = m.rateLimits;
52 if (m.rateLimits.length) u.hasLimits = true; // a subscription: its windows always show
53 }
54 if (typeof m.startedAt === "number") u.startedAt = m.startedAt;
55 if (m.cost && typeof m.cost.usd === "number") {
56 u.cost = { usd: m.cost.usd };
57 const last = u.costSamples.at(-1);
58 if (!last || last.usd !== m.cost.usd || now - last.at >= SAMPLE_EVERY_MS) {
59 u.costSamples.push({ at: now, usd: m.cost.usd });
60 if (u.costSamples.length > COST_SAMPLES) u.costSamples.splice(0, u.costSamples.length - COST_SAMPLES);
61 }
62 }
63 return true;
64}
65
66// The context's fill after a main-loop turn, for the band's chart.
67const CTX_HISTORY = 12;
68export function recordTurnContext(u) {
69 const t = u.context?.tokens;
70 if (t == null) return false;
71 u.ctxHistory.push(t);
72 if (u.ctxHistory.length > CTX_HISTORY) u.ctxHistory.splice(0, u.ctxHistory.length - CTX_HISTORY);
73 return true;
74}
75
76// What the band needs back after a reload (the module starts over, the
77// session does not): the tokens so far and the context after each turn.
78export function usageSnapshot(u, at) {
79 return { at, tokens: { ...u.tokens }, ctxHistory: [...u.ctxHistory] };
80}
81
82export function restoreUsage(u, saved) {
83 if (!saved || typeof saved !== "object") return false;
84 const t = saved.tokens ?? {};
85 for (const k of ["input", "output", "cacheRead", "cacheWrite"]) if (Number.isFinite(t[k])) u.tokens[k] = Math.max(u.tokens[k], t[k]);
86 if (Array.isArray(saved.ctxHistory) && !u.ctxHistory.length) u.ctxHistory = saved.ctxHistory.filter(Number.isFinite).slice(-CTX_HISTORY);
87 return true;
88}
89
90// What one turn used (turn.complete's `usage`), the main loop's or a subagent's.
91export function applyTurnUsage(u, usage) {
92 if (!usage) return false;
93 u.tokens.input += usage.input_tokens ?? 0;
94 u.tokens.output += usage.output_tokens ?? 0;
95 u.tokens.cacheRead += usage.cache_read_input_tokens ?? 0;
96 u.tokens.cacheWrite += usage.cache_creation_input_tokens ?? 0;
97 if (usage.model) u.model = usage.model;
98 return true;
99}
100
101export function totalTokens(u) {
102 const t = u.tokens;
103 return t.input + t.output + t.cacheRead + t.cacheWrite;
104}
105
106// The windows to show, 5-hour and 7-day first and always (a window that just
107// reset has no reading until the next reply: its percent is null), then any
108// others the account has. None at all for an account without windows.
109const MAIN_WINDOWS = ["five_hour", "seven_day"];
110export function limitWindows(u) {
111 if (!u.hasLimits && !u.rateLimits.length) return [];
112 const main = MAIN_WINDOWS.map((kind) => u.rateLimits.find((l) => l.kind === kind) ?? { kind, percentUsed: null });
113 return [...main, ...u.rateLimits.filter((l) => !MAIN_WINDOWS.includes(l.kind))];
114}
115
116// The share of input read from the prompt cache, 0-100, or null before any.
117export function cacheRatio(u) {
118 const t = u.tokens;
119 const input = t.input + t.cacheRead + t.cacheWrite;
120 return input ? (t.cacheRead / input) * 100 : null;
121}
122
123// Dollars per hour over the last quarter hour, or null with too little to go on.
124export function burnRate(u, now) {
125 const recent = u.costSamples.filter((s) => now - s.at <= BURN_WINDOW_MS);
126 if (recent.length < 2) return null;
127 const first = recent[0];
128 const last = recent.at(-1);
129 const hours = (last.at - first.at) / 3_600_000;
130 if (hours < 5 / 60) return null; // a few minutes say little about an hour
131 return (last.usd - first.usd) / hours;
132}
133
134// Spend per bucket over the last `n` buckets, oldest first: the sparkline.
135export function spendSeries(u, now, n = 12, bucketMs = 5 * 60_000) {
136 const out = new Array(n).fill(0);
137 const s = u.costSamples;
138 for (let i = 1; i < s.length; i++) {
139 const back = Math.floor((now - s[i].at) / bucketMs);
140 if (back < 0 || back >= n) continue;
141 out[n - 1 - back] += Math.max(0, s[i].usd - s[i - 1].usd);
142 }
143 return out;
144}
145
146// ---------------------------------------------------------------- tool calls
147
148// A few words on what a call is about, with anything that looks like a
149// secret masked: the command for Bash, a file's name, a search pattern.
150export function toolSummary(tool, input = {}) {
151 const base = (p) => String(p ?? "").split("/").filter(Boolean).at(-1) ?? "";
152 let s;
153 switch (tool) {
154 // A leading "cd <dir> &&" says where, not what: the command after it is the news.
155 case "Bash": s = String(input.command ?? "").replace(/^\s*cd\s+(?:"[^"]*"|'[^']*'|\S+)\s*(?:&&|;)\s*/, ""); break;
156 case "Read": case "Write": case "Edit": case "NotebookEdit": s = base(input.file_path ?? input.notebook_path); break;
157 case "Grep": s = input.pattern ? `"${input.pattern}"` : ""; break;
158 case "Glob": s = input.pattern; break;
159 case "WebFetch": s = input.url; break;
160 case "WebSearch": s = input.query; break;
161 case "Agent": case "Task": s = input.description; break;
162 default: s = input.description ?? input.command ?? input.query ?? "";
163 }
164 s = String(s ?? "").replace(/\s+/g, " ").trim();
165 if (findSecret(s)) return "(hidden: looks secret)";
166 return s.slice(0, 80);
167}
168
169let seq = 0;
170
171export function toolStarted(u, { tool, agentId, input, at }) {
172 const key = `c${++seq}`;
173 const entry = { key, tool, agentId: agentId ?? null, summary: toolSummary(tool, input), at, ms: null, isError: false, done: false };
174 u.calls.set(key, entry);
175 u.feed.push(entry);
176 if (u.feed.length > FEED) u.feed.splice(0, u.feed.length - FEED);
177 if (agentId) {
178 // Only agents the session spawned or lists: the engine's own loops
179 // (compaction, memory) carry ids nothing else names.
180 const a = u.agents.get(agentId);
181 if (a) a.tools.set(tool, (a.tools.get(tool) ?? 0) + 1);
182 } else {
183 u.activity = { state: "tool", tool, since: at };
184 }
185 return key;
186}
187
188export function toolEnded(u, key, { at, isError = false }) {
189 const entry = u.calls.get(key);
190 if (!entry) return false;
191 u.calls.delete(key);
192 entry.ms = Math.max(0, at - entry.at);
193 entry.isError = isError;
194 entry.done = true;
195 const t = u.tools.get(entry.tool) ?? { count: 0, errors: 0, durations: [] };
196 t.count++;
197 if (isError) t.errors++;
198 t.durations.push(entry.ms);
199 if (t.durations.length > DURATIONS) t.durations.shift();
200 u.tools.set(entry.tool, t);
201 if (!entry.agentId && u.activity.state === "tool") u.activity = { state: "thinking", tool: null, since: at };
202 return true;
203}
204
205export function percentile(values, p) {
206 if (!values.length) return null;
207 const sorted = [...values].sort((a, b) => a - b);
208 const i = Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1));
209 return sorted[i];
210}
211
212// One row per tool, the most time spent first.
213export function toolRows(u) {
214 return [...u.tools.entries()].map(([name, t]) => ({
215 name,
216 count: t.count,
217 errors: t.errors,
218 p50: percentile(t.durations, 50),
219 p95: percentile(t.durations, 95),
220 total: t.durations.reduce((a, b) => a + b, 0),
221 })).sort((a, b) => b.total - a.total || b.count - a.count);
222}
223
224export function runningCalls(u) {
225 return [...u.calls.values()];
226}
227
228// ---------------------------------------------------------------- turns
229
230export function turnStarted(u, at) {
231 u.activity = { state: "thinking", tool: null, since: at };
232}
233
234export function turnEnded(u, at) {
235 u.activity = { state: "idle", tool: null, since: at };
236}
237
238// ---------------------------------------------------------------- requests
239
240// Each request the main loop sends the model (one prompt takes several: a
241// tool's answer goes back in a new one), with the API's own usage for it,
242// what it carried that was new (the prompt, tool results) and what it
243// answered with. The engine gives one total per request, so the growth since
244// the request before is split across its new pieces by size: an estimate,
245// which is what tells you that a Read took 6k and a Bash 200.
246const STEPS = 30;
247
248export function stepPrompt(u, text) {
249 if (text) u.stepIn.push({ kind: "prompt", label: "prompt", chars: String(text).length });
250}
251
252// A tool's answer, named by what it was about ("Read metrics.mjs") so the
253// card can say which one without numbering requests.
254export function stepToolResult(u, tool, chars, summary = "") {
255 const about = summary && !summary.startsWith("(hidden") ? ` ${summary.length > 24 ? `${summary.slice(0, 23)}…` : summary}` : "";
256 u.stepIn.push({ kind: "tool", label: `${tool}${about}`, chars: Math.max(0, chars) });
257 // The request that called it learns what the call was about, so its
258 // output can be named by it ("Claude's Edit pane.ts").
259 const call = u.steps.at(-1)?.tools.find((c) => c.tool === tool && c.about == null);
260 if (call) { call.about = about; u.callsNamed++; }
261}
262
263export function stepStarted(u, { turnId, index = 0, at }) {
264 const step = { n: ++u.stepN, turnId, index, at, status: "streaming", input: null, output: null, cacheRead: 0, added: u.stepIn, grown: null, tools: [], stopReason: null, isCompacted: false };
265 u.stepIn = [];
266 u.steps.push(step);
267 if (u.steps.length > STEPS) u.steps.splice(0, u.steps.length - STEPS);
268 return step;
269}
270
271export function stepToolUse(step, name) {
272 if (step && name) step.tools.push({ tool: name, about: null });
273}
274
275// A request that failed (no usage: the stream broke or was dropped) hands
276// what it carried to the next, which sends it again.
277export function stepEnded(u, step, usage, stopReason) {
278 if (!step) return false;
279 step.stopReason = stopReason ?? null;
280 if (!usage) {
281 step.status = "failed";
282 u.stepIn = [...step.added, ...u.stepIn];
283 step.added = [];
284 return true;
285 }
286 step.status = "done";
287 step.input = (usage.input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
288 step.output = usage.output_tokens ?? 0;
289 step.cacheRead = usage.cache_read_input_tokens ?? 0;
290 // Grown since the last request that came back, a failed one between them aside.
291 const prev = u.steps.slice(0, u.steps.indexOf(step)).findLast((s) => s.status === "done") ?? null;
292 if (prev?.input != null && prev.output != null) {
293 if (step.input < prev.input) step.isCompacted = true;
294 else step.grown = Math.max(0, step.input - prev.input - prev.output);
295 }
296 if (step.grown != null) splitBySize(step.added, step.grown);
297 return true;
298}
299
300// Spreads `total` over `pieces` by their characters; the parts sum to it.
301function splitBySize(pieces, total) {
302 const sum = pieces.reduce((n, p) => n + Math.max(1, p.chars), 0);
303 let left = total;
304 pieces.forEach((p, i) => {
305 p.tokens = i === pieces.length - 1 ? left : Math.round((total * Math.max(1, p.chars)) / sum);
306 left -= p.tokens;
307 });
308}
309
310// What every request carries before the conversation, from the /context
311// breakdown: its used rows (system prompt, tools, MCP tools, memory files,
312// skills, agents) less the conversation itself.
313const NOT_OVERHEAD = /messages|free space|autocompact|reserved/i;
314export function applyOverhead(u, breakdown) {
315 const rows = (breakdown?.categories ?? []).filter((c) => (c.kind ? c.kind === "used" : true) && !c.isDeferred && c.tokens > 0 && !NOT_OVERHEAD.test(c.name));
316 if (!rows.length) return false;
317 const biggest = rows.reduce((a, b) => (b.tokens > a.tokens ? b : a));
318 u.overhead = { tokens: rows.reduce((n, c) => n + c.tokens, 0), biggest: { name: biggest.name, tokens: biggest.tokens } };
319 u.overheadAt = u.stepN;
320 return true;
321}
322
323// Whether to read the breakdown again: never read, or a few requests old.
324export function wantsOverhead(u) {
325 return u.steps.length > 0 && (!u.overhead || u.stepN - u.overheadAt >= 8);
326}
327
328// The context as strata, for the Requests card: one column per request (what
329// it sent), then one for the next (the context now). Each thing that came
330// into the conversation is a layer from the request that first carried it
331// on, so a tool result read once is seen riding along in every column after.
332// The few biggest get layers of their own; the rest is "conversation". Under
333// them all is the bedrock: what was already there when the first column was
334// sent, the overhead every request carries and any conversation from before
335// we started watching, drawn apart since to scale it would flatten what
336// comes after (a session hours long has hundreds of k of it). Column heights
337// are the API's own figures.
338const NAMED = 4;
339// Worked out again only when a request starts or ends or the overhead is
340// read: a redraw draws the card and its tips from one, not one each.
341const strataSeen = new WeakMap(); // usage → { sig, byCols: Map }
342export function strata(u, maxCols = 12) {
343 const sig = `${u.stepN}:${u.callsNamed}:${u.steps.map((s) => s.status[0]).join("")}:${u.overhead?.tokens ?? ""}`;
344 let seen = strataSeen.get(u);
345 if (seen?.sig !== sig) strataSeen.set(u, seen = { sig, byCols: new Map() });
346 if (!seen.byCols.has(maxCols)) seen.byCols.set(maxCols, layered(u, maxCols));
347 return seen.byCols.get(maxCols);
348}
349
350function layered(u, maxCols) {
351 let from = 0;
352 const done = u.steps.filter((s) => s.status === "done" && s.input != null);
353 done.forEach((s, i) => { if (s.isCompacted) from = i; });
354 const since = done.slice(from);
355 if (!since.length) return null;
356 const first = since[0];
357 const firstAdded = first.added.reduce((n, p) => n + (p.tokens ?? Math.round(p.chars / 4)), 0);
358 const start = Math.max(0, first.input - firstAdded);
359 const bed = Math.min(u.overhead?.tokens ?? start, start);
360 const items = [];
361 since.forEach((s, k) => {
362 for (const p of s.added) {
363 const tokens = p.tokens ?? Math.round(p.chars / 4);
364 items.push({ name: p.kind === "prompt" ? "your prompt" : p.label, kind: p.kind, n: s.n, enter: k, tokens });
365 }
366 if (s.output) items.push({ name: s.tools.length ? toolCallsName(s.tools) : "Claude's reply", kind: "answer", n: s.n, enter: k + 1, tokens: s.output });
367 });
368 const named = [...items].filter((it) => it.tokens >= 300).sort((a, b) => b.tokens - a.tokens).slice(0, NAMED).sort((a, b) => a.enter - b.enter || a.n - b.n);
369 const last = since.at(-1);
370 const all = [...since.map((s, k) => ({ label: k ? "older" : "first", k, total: s.input })), { label: "next", k: since.length, total: last.input + (last.output ?? 0) }];
371 const cols = all.slice(-maxCols);
372 // Named by what they are; two alike ("Claude's reply") are told apart by count.
373 const seen = new Map();
374 const layers = named.map((it) => {
375 const k = (seen.get(it.name) ?? 0) + 1;
376 seen.set(it.name, k);
377 return { name: k > 1 ? `${it.name} (${k})` : it.name, kind: it.kind, sizes: cols.map((c) => (c.k >= it.enter ? it.tokens : 0)) };
378 });
379 const talk = cols.map((c, i) => Math.max(0, c.total - start - layers.reduce((n, l) => n + l.sizes[i], 0)));
380 return {
381 bedrock: bed,
382 bedrockKnown: !!u.overhead,
383 earlier: start - bed,
384 cols: cols.map((c) => ({ label: c.label, above: Math.max(0, c.total - start) })),
385 layers: [{ name: "conversation", kind: "talk", sizes: talk }, ...layers],
386 compacted: from > 0 || first.isCompacted,
387 sent: since.length,
388 };
389}
390
391// A request's tool calls, named by the one that wrote the most: a Write or an
392// Edit carries its content, the rest little more than a path or a command.
393const WRITES = new Set(["Write", "Edit", "NotebookEdit"]);
394function toolCallsName(calls) {
395 const top = calls.find((c) => WRITES.has(c.tool)) ?? calls[0];
396 const more = calls.length > 1 ? ` and ${calls.length - 1} more` : "";
397 return `Claude's ${top.tool}${top.about ?? ""}${more}`;
398}
399
400// Two or three things worth knowing, in plain words: how much of a request
401// is the overhead, the biggest thing riding along, and what the next one sends.
402export function contextTips(u) {
403 const st = strata(u);
404 if (!st) return [];
405 const tips = [];
406 const last = u.steps.filter((s) => s.status === "done" && s.input != null).at(-1);
407 if (st.bedrockKnown && last?.input) {
408 const pct = Math.round((st.bedrock / last.input) * 100);
409 const big = u.overhead.biggest;
410 tips.push({ icon: "⚙", parts: [["Fixed overhead", true], [` (${fmtK(st.bedrock)}): sent with every request, ${pct}% of the last request.`, false], ...(big ? [[` Biggest: ${big.name} (${fmtK(big.tokens)}).`, false]] : [])] });
411 }
412 const top = st.layers.slice(1).reduce((a, l) => (!a || l.sizes.at(-1) > a.sizes.at(-1) ? l : a), null);
413 const tok = top?.sizes.at(-1) ?? 0;
414 if (top && tok >= 1000) {
415 const rides = top.sizes.slice(0, -1).filter((n) => n > 0).length;
416 const what = top.name.charAt(0).toUpperCase() + top.name.slice(1);
417 // Said so it can't read as fetched again: it came in once, and is resent,
418 // with what that has added up to.
419 const once = top.kind === "answer" ? "written once" : top.kind === "prompt" ? "sent once" : /^Read\b/.test(top.name) ? "read once" : "came back once";
420 const resent = rides ? `resent ${rides} time${rides === 1 ? "" : "s"} so far (${fmtK(rides * tok)} sent in all).` : "resent with every request from now on.";
421 tips.push({ icon: "⇠", parts: [[what, true], [` (${fmtK(tok)}): ${once}, ${resent}`, false]] });
422 }
423 const next = st.bedrock + st.earlier + (st.cols.at(-1)?.above ?? 0);
424 const pct = u.context?.percent;
425 tips.push({ icon: "→", parts: [["The next request sends ", false], [fmtK(next), true], [Number.isFinite(pct) ? `, ${Math.round(pct)}% of the window.` : ".", false], ...(pct >= 80 ? [[" Compaction is near.", false]] : [])] });
426 return tips;
427}
428
429function fmtK(n) {
430 if (n < 1000) return String(Math.round(n));
431 return n < 10_000 ? `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k` : `${Math.round(n / 1000)}k`;
432}
433
434// ---------------------------------------------------------------- subagents
435
436function agentEntry(u, id, at) {
437 let a = u.agents.get(id);
438 if (!a) {
439 a = { id, type: "agent", description: "", status: "running", parentId: null, startedAt: at, endedAt: null, tools: new Map() };
440 u.agents.set(id, a);
441 }
442 return a;
443}
444
445export function agentSpawned(u, { id, type, description, parentId, at }) {
446 if (!id) return false;
447 const a = agentEntry(u, id, at);
448 a.type = type || a.type;
449 a.description = description || a.description;
450 a.parentId = parentId ?? a.parentId;
451 a.startedAt = Math.min(a.startedAt, at);
452 return true;
453}
454
455const ENDED = new Set(["completed", "failed", "killed"]);
456
457// $.agent.list(): the engine's word on each agent's status.
458export function applyAgentList(u, list, now) {
459 let changed = false;
460 for (const info of list ?? []) {
461 const a = agentEntry(u, info.id, now);
462 const was = a.status;
463 a.type = info.type || a.type;
464 a.description = info.description || a.description;
465 a.parentId = info.parentId ?? a.parentId;
466 a.status = info.status;
467 if (ENDED.has(info.status) && !a.endedAt) a.endedAt = now;
468 if (was !== a.status) changed = true;
469 }
470 return changed;
471}
472
473// Agents in tree order: each one followed by those it spawned, newest first
474// at each level. Each row carries its depth and whether it is the last child.
475export function agentTree(u) {
476 const all = [...u.agents.values()];
477 // An agent whose parent isn't known is drawn at the top level.
478 const parentOf = (a) => (a.parentId && u.agents.has(a.parentId) ? a.parentId : null);
479 const out = [];
480 const walk = (pid, depth) => {
481 const list = all.filter((a) => parentOf(a) === pid).sort((a, b) => b.startedAt - a.startedAt);
482 list.forEach((a, i) => {
483 out.push({ agent: a, depth, last: i === list.length - 1 });
484 walk(a.id, depth + 1);
485 });
486 };
487 walk(null, 0);
488 return out;
489}
490
491export function agentCounts(u) {
492 let running = 0;
493 let done = 0;
494 for (const a of u.agents.values()) {
495 if (ENDED.has(a.status)) done++;
496 else running++;
497 }
498 return { running, done };
499}
500
501export function isEnded(status) {
502 return ENDED.has(status);
503}
504
505// The tool an agent used most: "Read ×14".
506export function topTool(agent) {
507 let best = null;
508 for (const [name, n] of agent.tools) if (!best || n > best[1]) best = [name, n];
509 return best ? `${best[0]} ×${best[1]}` : "";
510}
511hooks/github.mjs 308 lines1// The Git room's data: the local branch from `git status`, and pull requests,
2// reviews, Actions runs, issues and Dependabot alerts from the `gh` CLI,
3// signed in as the person already is. Nothing is stored and no token passes
4// through here. `run(argv)` comes from the hooks module ($.process.run).
5
6const PR_FIELDS = "number,title,state,isDraft,url,author,headRefName,reviewDecision,statusCheckRollup,updatedAt";
7const PR_VIEW_FIELDS = `${PR_FIELDS},mergeable,mergeStateStatus,reviews,reviewRequests`;
8
9export function emptyGit() {
10 return {
11 status: "idle", // idle | loading | ok | no-gh | no-auth | no-repo | error
12 error: "",
13 fetchedAt: 0,
14 stale: false, // the last refresh failed: what's shown is older
15 me: null, // the gh login
16 repo: null, // { name, url }
17 local: null, // { branch, ahead, behind, changed }
18 pr: null, // this branch's pull request
19 prs: [], // open pull requests
20 reviewMe: [], // numbers of open PRs that ask for my review
21 runs: [], // recent Actions runs
22 issues: [], // open issues assigned to me
23 alerts: null, // Dependabot alerts, or null when not readable
24 log: [], // the newest commits of every branch, laid out as a graph (layoutGraph)
25 };
26}
27
28// ---------------------------------------------------------------- parsing
29
30// `git status --porcelain=v2 --branch`
31export function parseGitStatus(out) {
32 const local = { branch: null, ahead: 0, behind: 0, changed: 0, upstream: null, unpushed: null };
33 for (const line of String(out).split("\n")) {
34 if (line.startsWith("# branch.head ")) local.branch = line.slice(14).trim();
35 else if (line.startsWith("# branch.upstream ")) local.upstream = line.slice(18).trim();
36 else if (line.startsWith("# branch.ab ")) {
37 const m = /\+(\d+) -(\d+)/.exec(line);
38 if (m) { local.ahead = Number(m[1]); local.behind = Number(m[2]); }
39 } else if (/^[12u?] /.test(line)) local.changed++;
40 }
41 if (local.branch === "(detached)") local.branch = "detached";
42 return local;
43}
44
45const FAILED = new Set(["FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE", "ERROR"]);
46
47// A PR's checks as counts: passed, failed, still running.
48export function checks(rollup) {
49 const c = { pass: 0, fail: 0, pending: 0, total: 0 };
50 for (const item of rollup ?? []) {
51 c.total++;
52 if (item.__typename === "StatusContext" || item.state) {
53 if (item.state === "SUCCESS") c.pass++;
54 else if (FAILED.has(item.state)) c.fail++;
55 else c.pending++;
56 continue;
57 }
58 if (item.status !== "COMPLETED") c.pending++;
59 else if (FAILED.has(item.conclusion)) c.fail++;
60 else c.pass++;
61 }
62 return c;
63}
64
65function prModel(p) {
66 return {
67 number: p.number,
68 title: p.title ?? "",
69 state: p.state ?? "OPEN",
70 draft: !!p.isDraft,
71 url: p.url,
72 author: p.author?.login ?? "",
73 branch: p.headRefName ?? "",
74 decision: p.reviewDecision || null, // APPROVED | CHANGES_REQUESTED | REVIEW_REQUIRED
75 checks: checks(p.statusCheckRollup),
76 updatedAt: Date.parse(p.updatedAt) || 0,
77 };
78}
79
80// `gh pr view` adds who reviewed (each person's latest word) and who's asked.
81export function parsePrView(p) {
82 const pr = prModel(p);
83 const latest = new Map();
84 for (const r of p.reviews ?? []) {
85 const who = r.author?.login;
86 if (!who || r.state === "COMMENTED" || r.state === "PENDING") continue;
87 latest.set(who, r.state);
88 }
89 pr.reviews = [...latest].map(([login, state]) => ({ login, state }));
90 pr.requested = (p.reviewRequests ?? []).map((r) => r.login ?? r.name ?? r.slug).filter(Boolean);
91 pr.mergeable = p.mergeable ?? "UNKNOWN"; // MERGEABLE | CONFLICTING | UNKNOWN
92 pr.mergeState = p.mergeStateStatus ?? "UNKNOWN"; // CLEAN | BLOCKED | BEHIND | DIRTY | UNSTABLE | ...
93 return pr;
94}
95
96export function parsePrList(list) {
97 return (list ?? []).map(prModel);
98}
99
100// Recent runs, the newest of each workflow on each branch only: an older
101// run that a newer one replaced (a failure since fixed) no longer counts.
102export function parseRuns(list) {
103 const seen = new Set();
104 return (list ?? []).filter((r) => {
105 const key = `${r.workflowName || r.name}\u0000${r.headBranch}`;
106 if (seen.has(key)) return false;
107 seen.add(key);
108 return true;
109 }).map((r) => ({
110 id: r.databaseId,
111 name: r.workflowName || r.name || "workflow",
112 branch: r.headBranch ?? "",
113 status: r.status, // queued | in_progress | completed
114 conclusion: r.conclusion || null, // success | failure | cancelled | skipped
115 startedAt: Date.parse(r.createdAt) || 0,
116 updatedAt: Date.parse(r.updatedAt) || 0,
117 url: r.url,
118 }));
119}
120
121export function parseIssues(list) {
122 return (list ?? []).map((i) => ({
123 number: i.number,
124 title: i.title ?? "",
125 url: i.url,
126 labels: (i.labels ?? []).map((l) => l.name),
127 updatedAt: Date.parse(i.updatedAt) || 0,
128 }));
129}
130
131export function parseAlerts(list) {
132 return (list ?? []).map((a) => ({
133 number: a.number,
134 pkg: a.dependency?.package?.name ?? a.security_vulnerability?.package?.name ?? "dependency",
135 severity: a.security_advisory?.severity ?? a.security_vulnerability?.severity ?? "unknown",
136 url: a.html_url,
137 }));
138}
139
140// `git log` over every branch and remote, one record a commit (fields split
141// by \x1f, records by \x1e): hash, parents, refs, subject, commit time.
142export const LOG_FORMAT = "%H%x1f%P%x1f%D%x1f%s%x1f%ct%x1e";
143export function parseLog(out) {
144 return String(out ?? "").split("\x1e").map((r) => r.replace(/^\n/, "")).filter((r) => r.includes("\x1f")).map((r) => {
145 const [hash, parents, refs, subject, ct] = r.split("\x1f");
146 let head = null;
147 const names = String(refs ?? "").split(",").map((x) => x.trim()).filter(Boolean).flatMap((x) => {
148 if (x.startsWith("HEAD -> ")) { head = x.slice(8); return [head]; }
149 if (x === "HEAD" || x.endsWith("/HEAD") || x.startsWith("tag: ")) return x.startsWith("tag: ") ? [x.slice(5)] : [];
150 return [x];
151 });
152 return { hash, parents: String(parents ?? "").split(" ").filter(Boolean), refs: names, head, subject: subject ?? "", at: Number(ct) * 1000 || 0 };
153 });
154}
155
156// Lanes for a graph of `commits` (newest first): each row's commit column,
157// the lanes coming in at its top and going out at its bottom (a lane holds
158// the hash it waits for), so a drawing can run a line from each lane above
159// to where that hash is below. Lanes past `maxLanes` are dropped.
160export function layoutGraph(commits, maxLanes = 6) {
161 let lanes = [];
162 return commits.map((c) => {
163 const before = lanes.slice();
164 let col = lanes.indexOf(c.hash);
165 if (col < 0) { col = lanes.indexOf(null); if (col < 0) col = lanes.length; }
166 const after = lanes.map((h) => (h === c.hash ? null : h));
167 after[col] = c.parents[0] ?? null;
168 for (const p of c.parents.slice(1)) {
169 if (after.includes(p)) continue;
170 const free = after.indexOf(null);
171 if (free >= 0) after[free] = p; else after.push(p);
172 }
173 while (after.length && after.at(-1) == null) after.pop();
174 lanes = after.slice(0, maxLanes);
175 return { ...c, col: Math.min(col, maxLanes - 1), before: before.slice(0, maxLanes), after: lanes.slice() };
176 });
177}
178
179// ---------------------------------------------------------------- fetching
180
181const NO_AUTH = /gh auth login|not logged in|authentication|HTTP 401/i;
182const NO_PR = /no pull requests found|no open pull requests/i;
183const NO_REMOTE = /no git remotes|none of the git remotes|not a github|could not determine/i;
184
185function json(out) {
186 try { return JSON.parse(out || "null"); } catch { return null; }
187}
188
189// Everything the room shows, fetched in parallel. `prev` is the last good
190// snapshot: on a failed refresh it stays, marked stale.
191export async function fetchGit(run, prev = emptyGit()) {
192 const next = { ...emptyGit(), me: prev.me };
193 let status;
194 try {
195 status = await run(["git", "status", "--porcelain=v2", "--branch"]);
196 } catch (err) {
197 return { ...prev, status: "error", error: `git: ${err?.message ?? err}`, stale: prev.status === "ok" };
198 }
199 if (status.exitCode !== 0) {
200 return /not a git repository/i.test(status.stderr)
201 ? { ...emptyGit(), status: "no-repo" }
202 : { ...prev, status: "error", error: firstLine(status.stderr) || "git status failed", stale: prev.status === "ok" };
203 }
204 next.local = parseGitStatus(status.stdout);
205 // The newest commits of every branch and remote, for the desktop's graph.
206 try {
207 const log = await run(["git", "log", "--branches", "--remotes", "--tags", "--date-order", "-n", "10", `--format=${LOG_FORMAT}`]);
208 next.log = log.exitCode === 0 ? layoutGraph(parseLog(log.stdout)) : prev.log ?? [];
209 } catch { next.log = prev.log ?? []; }
210 // A branch that was never pushed has nothing to be ahead of: count its
211 // commits past the main branch instead.
212 if (!next.local.upstream && next.local.branch && next.local.branch !== "detached") {
213 next.local.unpushed = await unpushed(run);
214 }
215
216 const gh = (args) => run(["gh", ...args]).then((r) => r, (err) => ({ thrown: err }));
217 const [repo, me] = await Promise.all([
218 gh(["repo", "view", "--json", "nameWithOwner,url"]),
219 prev.me ? Promise.resolve(null) : gh(["api", "user", "--jq", ".login"]),
220 ]);
221 if (repo.thrown) return { ...emptyGit(), local: next.local, log: next.log, status: "no-gh" };
222 if (repo.exitCode !== 0) {
223 if (NO_AUTH.test(repo.stderr)) return { ...emptyGit(), local: next.local, log: next.log, status: "no-auth" };
224 if (NO_REMOTE.test(repo.stderr)) return { ...emptyGit(), local: next.local, log: next.log, status: "ok", fetchedAt: Date.now(), error: "no GitHub remote" };
225 return { ...prev, local: next.local, status: "error", error: firstLine(repo.stderr) || "gh failed", stale: prev.status === "ok" };
226 }
227 const r = json(repo.stdout);
228 next.repo = { name: r?.nameWithOwner ?? "", url: r?.url ?? "" };
229 if (me && me.exitCode === 0) next.me = me.stdout.trim() || null;
230
231 const [view, list, mine, runs, issues, alerts] = await Promise.all([
232 gh(["pr", "view", "--json", PR_VIEW_FIELDS]),
233 gh(["pr", "list", "--state", "open", "--limit", "8", "--json", PR_FIELDS]),
234 gh(["pr", "list", "--state", "open", "--search", "review-requested:@me", "--json", "number"]),
235 gh(["run", "list", "--limit", "12", "--json", "databaseId,name,workflowName,headBranch,status,conclusion,createdAt,updatedAt,url"]),
236 gh(["issue", "list", "--state", "open", "--assignee", "@me", "--limit", "6", "--json", "number,title,url,labels,updatedAt"]),
237 gh(["api", "repos/{owner}/{repo}/dependabot/alerts?state=open&per_page=5"]),
238 ]);
239 const ok = (x) => !x.thrown && x.exitCode === 0;
240 if (!ok(list)) {
241 return { ...prev, local: next.local, repo: next.repo, status: "error", error: firstLine(list.stderr ?? list.thrown?.message) || "gh pr list failed", stale: prev.status === "ok" };
242 }
243 next.pr = ok(view) ? parsePrView(json(view.stdout) ?? {}) : null;
244 if (!ok(view) && !NO_PR.test(view.stderr ?? "")) next.pr = prev.pr; // a hiccup: keep what we had
245 next.prs = parsePrList(json(list.stdout));
246 next.reviewMe = ok(mine) ? (json(mine.stdout) ?? []).map((p) => p.number) : prev.reviewMe;
247 next.runs = ok(runs) ? parseRuns(json(runs.stdout)) : prev.runs;
248 next.issues = ok(issues) ? parseIssues(json(issues.stdout)) : prev.issues;
249 // No access to alerts (not an admin, or turned off): leave the section out.
250 next.alerts = ok(alerts) ? parseAlerts(json(alerts.stdout)) : null;
251 next.status = "ok";
252 next.fetchedAt = Date.now();
253 return next;
254}
255
256async function unpushed(run) {
257 for (const base of ["origin/HEAD", "origin/main", "origin/master"]) {
258 try {
259 const r = await run(["git", "rev-list", "--count", `${base}..HEAD`]);
260 if (r.exitCode === 0) return Number(r.stdout.trim()) || 0;
261 } catch { return null; }
262 }
263 return null;
264}
265
266function firstLine(text) {
267 return String(text ?? "").trim().split("\n")[0].slice(0, 120);
268}
269
270// ---------------------------------------------------------------- what changed
271
272// Toast-worthy changes between two good snapshots, as short lines.
273export function diffGit(prev, next) {
274 if (prev?.status !== "ok" || next?.status !== "ok" || !prev.fetchedAt) return [];
275 const out = [];
276 const a = prev.pr;
277 const b = next.pr;
278 if (a && b && a.number === b.number) {
279 if (b.checks.fail > a.checks.fail) out.push(`✗ Checks failed on #${b.number}`);
280 else if (a.checks.pending > 0 && b.checks.pending === 0 && b.checks.fail === 0 && b.checks.total) out.push(`✓ All checks passed on #${b.number}`);
281 if (b.decision !== a.decision && b.decision === "APPROVED") out.push(`✓ #${b.number} was approved`);
282 if (b.decision !== a.decision && b.decision === "CHANGES_REQUESTED") out.push(`● Changes requested on #${b.number}`);
283 if (b.state !== a.state && b.state === "MERGED") out.push(`✓ #${b.number} was merged`);
284 if (b.mergeable !== a.mergeable && b.mergeable === "CONFLICTING") out.push(`✗ #${b.number} has a merge conflict`);
285 }
286 for (const n of next.reviewMe) {
287 if (prev.reviewMe.includes(n)) continue;
288 const pr = next.prs.find((p) => p.number === n);
289 out.push(`● ${pr?.author || "Someone"} asked for your review on #${n}${pr ? ` ${pr.title}` : ""}`);
290 }
291 return out;
292}
293
294// Needs a look: this branch's checks failed, or someone wants your review.
295export function gitAttention(g) {
296 if (g?.status !== "ok") return false;
297 return (g.pr?.checks.fail ?? 0) > 0 || g.reviewMe.length > 0 || g.pr?.mergeable === "CONFLICTING";
298}
299
300export function ghStatusText(g) {
301 switch (g.status) {
302 case "no-gh": return "The Git room reads GitHub through the gh CLI. Install it (brew install gh), then gh auth login.";
303 case "no-auth": return "gh isn't signed in. Run gh auth login in a terminal, then press r here.";
304 case "no-repo": return "This session's folder isn't a git repository.";
305 default: return "";
306 }
307}
308hooks/sessions.mjs 72 lines1// Every Claude Code session on this computer, for the Agents room. Each
2// session's mod sends a small heartbeat to its bridge, the bridge keeps it as
3// a file next to the others', and every bridge reports the set back (a
4// "sessions" event). Only what the room draws goes in: no prompts, no output.
5
6import { agentTree, topTool } from "./metrics.mjs";
7
8const FEED_SHARED = 12;
9
10// This session's heartbeat, from its own figures.
11export function heartbeat(u, { id, cwd, branch, now }) {
12 const project = String(cwd ?? "").split("/").filter(Boolean).at(-1) ?? "session";
13 return {
14 v: 1,
15 id,
16 project,
17 cwd,
18 branch: branch ?? null,
19 model: u.model,
20 activity: u.activity,
21 cost: u.cost?.usd ?? null,
22 context: u.context?.percent ?? null,
23 agents: agentTree(u).map(({ agent: a, depth, last }) => ({
24 id: a.id, type: a.type, description: a.description, status: a.status,
25 startedAt: a.startedAt, endedAt: a.endedAt, top: topTool(a), depth, last,
26 })),
27 feed: u.feed.slice(-FEED_SHARED).map((f) => ({
28 key: f.key, tool: f.tool, agent: f.agentId ? (u.agents.get(f.agentId)?.type ?? "agent") : null,
29 summary: f.summary, at: f.at, ms: f.ms, isError: f.isError, done: f.done,
30 })),
31 updatedAt: now,
32 };
33}
34
35// What changed enough to send now (rather than at the next idle beat).
36export function beatKey(hb) {
37 return JSON.stringify([hb.activity, hb.agents.map((a) => a.status), hb.feed.at(-1)?.key, hb.feed.at(-1)?.done, Math.round((hb.cost ?? 0) * 100)]);
38}
39
40// Sessions in the order the room lists them: this one, then busy ones, then
41// the rest by when they last did something.
42export function orderSessions(own, others) {
43 const list = [own, ...others.filter((s) => s && s.id !== own?.id)].filter(Boolean);
44 const busy = (s) => ((s.activity?.state && s.activity.state !== "idle") || (s.agents ?? []).some((a) => !["completed", "failed", "killed"].includes(a.status)) ? 1 : 0);
45 return list.sort((a, b) => (a === own ? -1 : b === own ? 1 : 0) || busy(b) - busy(a) || (b.activity?.since ?? 0) - (a.activity?.since ?? 0));
46}
47
48// One feed across sessions, newest last, each row naming its session.
49export function mergedFeed(sessions, { filter = "all", ownId, limit = 12 } = {}) {
50 const rows = [];
51 for (const s of sessions) {
52 if (filter === "here" && s.id !== ownId) continue;
53 for (const f of s.feed ?? []) rows.push({ ...f, session: s.project, sessionId: s.id });
54 }
55 const kept = (filter === "errors" ? rows.filter((r) => r.isError) : rows).sort((a, b) => a.at - b.at);
56 // A run of the same finished call (a subagent reading file after file
57 // with one name) reads as one row with a count.
58 const out = [];
59 for (const r of kept) {
60 const prev = out.at(-1);
61 if (prev && prev.done && r.done && !r.isError && !prev.isError && prev.sessionId === r.sessionId
62 && prev.agent === r.agent && prev.tool === r.tool && prev.summary === r.summary) {
63 prev.times = (prev.times ?? 1) + 1;
64 prev.at = r.at;
65 prev.ms = r.ms;
66 continue;
67 }
68 out.push({ ...r });
69 }
70 return out.slice(-limit);
71}
72hooks/focus.mjs 461 lines1// The Focus room: a Pomodoro timer. Focus for a while, then a break, each
2// ending with a chime (the mod plays it). A focus round that runs out starts
3// its break at once; a break that runs out waits for ▶. The lengths and the
4// day's count are kept in $.store, a running timer per session, so a reload
5// carries on where it was.
6//
7// Plain logic and drawing: the mod owns the clock, the sound and the store.
8
9import { state } from "./state.mjs";
10import { theme } from "./theme.mjs";
11import { line, card, stackCards, meter } from "./widgets.mjs";
12import * as K from "./bandkit.mjs";
13import { draw, value, sub } from "./bands.mjs";
14
15export const FOCUS_META = { icon: "◷", label: "Focus", color: "#E58FA8" };
16const BREAK_COLOR = theme.online;
17
18export const WORK = { min: 5, max: 120, step: 5 };
19export const REST = { min: 1, max: 60, step: 1 };
20
21export function createFocus() {
22 return {
23 work: 25, // minutes of focus
24 rest: 5, // minutes of break
25 phase: "idle", // idle | focus | break
26 endsAt: 0, // while running: when the phase ends (ms)
27 left: 0, // while paused: what was left (ms)
28 span: 0, // while running: the phase's length when it began (ms)
29 paused: false,
30 day: "", // the local day `done` and `focusedMs` count
31 done: 0, // focus rounds finished today
32 focusedMs: 0, // focused today, finished rounds only
33 cheerAt: 0, // when the last focus round ended (the pet cheers)
34 history: {}, // "2026-10-12" → focus rounds finished that day, the last year
35 };
36}
37
38// "2026-10-12" in local time: the day the count belongs to.
39export function dayOf(now) {
40 const d = new Date(now);
41 return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
42}
43
44const DAY = /^\d{4}-\d{2}-\d{2}$/;
45const KEEP_DAYS = 371; // 53 weeks
46
47// The day `n` days before `now`'s (noon, so a DST change can't skip one).
48export function daysBefore(now, n) {
49 const d = new Date(now);
50 d.setHours(12, 0, 0, 0);
51 d.setDate(d.getDate() - n);
52 return dayOf(d.getTime());
53}
54
55// The day after "2026-10-12" (noon again, for DST).
56export function dayAfter(day) {
57 const [y, m, d] = day.split("-").map(Number);
58 return dayOf(new Date(y, m - 1, d + 1, 12).getTime());
59}
60
61// Days in a row with a finished round, up to today (or yesterday, when
62// today has none yet), and the longest run kept. Walks only the days that
63// had a round, as the band asks for it every second.
64export function streaks(f, now) {
65 const oldest = daysBefore(now, KEEP_DAYS);
66 const days = Object.keys(f.history).filter((day) => day >= oldest && f.history[day] > 0).sort();
67 const had = new Set(days);
68 const has = (n) => had.has(daysBefore(now, n));
69 let current = 0;
70 for (let n = has(0) ? 0 : 1; has(n); n++) current++;
71 let best = 0, run = 0, prev = "";
72 for (const day of days) {
73 run = prev && dayAfter(prev) === day ? run + 1 : 1;
74 best = Math.max(best, run);
75 prev = day;
76 }
77 return { current, best };
78}
79
80function rollDay(f, now) {
81 const day = dayOf(now);
82 if (f.day !== day) { f.day = day; f.done = 0; f.focusedMs = 0; }
83}
84
85const phaseMs = (f, phase = f.phase) => (phase === "break" ? f.rest : f.work) * 60_000;
86// The running phase's own length: −/+ meanwhile is for the next one.
87const spanMs = (f) => f.span || phaseMs(f);
88
89export function isRunning(f) {
90 return f.phase !== "idle" && !f.paused;
91}
92
93// What's left of the phase, in ms (the whole focus length while idle).
94export function remaining(f, now) {
95 if (f.phase === "idle") return phaseMs(f, "focus");
96 if (f.paused) return f.left;
97 return Math.max(0, f.endsAt - now);
98}
99
100// How far through the phase, 0 to 1.
101export function progress(f, now) {
102 if (f.phase === "idle") return 0;
103 return Math.min(1, Math.max(0, 1 - remaining(f, now) / spanMs(f)));
104}
105
106// "18:42", or "1:05:00" past an hour.
107export function clock(ms) {
108 const s = Math.ceil(ms / 1000);
109 const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
110 const mm = String(m).padStart(h ? 2 : 1, "0"), ss = String(sec).padStart(2, "0");
111 return h ? `${h}:${mm}:${ss}` : `${mm.padStart(2, "0")}:${ss}`;
112}
113
114// ▶: start a focus round, or carry on after a pause.
115export function start(f, now) {
116 rollDay(f, now);
117 if (f.paused) { f.paused = false; f.endsAt = now + f.left; f.left = 0; return; }
118 if (f.phase === "idle") { f.phase = "focus"; f.span = phaseMs(f); f.endsAt = now + f.span; }
119}
120
121export function pause(f, now) {
122 if (!isRunning(f)) return;
123 f.left = Math.max(0, f.endsAt - now);
124 f.paused = true;
125}
126
127// ↺: back to idle, the round not counted.
128export function reset(f) {
129 f.phase = "idle";
130 f.paused = false;
131 f.endsAt = 0;
132 f.left = 0;
133 f.span = 0;
134}
135
136// The phase is over: a focus round counts and its break starts; a break
137// goes back to idle. Returns what ended ("focus" or "break").
138function finish(f, now, { counted }) {
139 const ended = f.phase;
140 if (ended === "focus") {
141 rollDay(f, now);
142 if (counted) {
143 f.done += 1;
144 f.focusedMs += spanMs(f);
145 f.cheerAt = now;
146 f.history[f.day] = (f.history[f.day] ?? 0) + 1;
147 const oldest = daysBefore(now, KEEP_DAYS);
148 for (const day of Object.keys(f.history)) if (day < oldest) delete f.history[day];
149 }
150 f.phase = "break";
151 f.paused = false;
152 f.span = phaseMs(f, "break");
153 f.endsAt = now + f.span;
154 f.left = 0;
155 } else reset(f);
156 return ended;
157}
158
159// ⏭: end the phase now. A focus round skipped doesn't count.
160export function skip(f, now) {
161 if (f.phase === "idle") return null;
162 return finish(f, now, { counted: false });
163}
164
165// Once a second: the phase that ran out, or null.
166export function tickFocus(f, now) {
167 if (!isRunning(f) || now < f.endsAt) return null;
168 return finish(f, now, { counted: true });
169}
170
171// −/+ on a length. A running phase keeps its end; the new length is for the next.
172export function adjust(f, which, dir) {
173 const r = which === "rest" ? REST : WORK;
174 const v = Math.min(r.max, Math.max(r.min, f[which] + dir * r.step));
175 f[which] = v;
176}
177
178// "50 10", "50/10" or "50": the lengths, typed. True when it was that.
179export function setLengths(f, text) {
180 const m = /^(\d{1,3})(?:\s*[\s/]\s*(\d{1,3}))?$/.exec(String(text ?? "").trim());
181 if (!m) return false;
182 f.work = Math.min(WORK.max, Math.max(WORK.min, Number(m[1])));
183 if (m[2]) f.rest = Math.min(REST.max, Math.max(REST.min, Number(m[2])));
184 return true;
185}
186
187// What's kept in $.store: the lengths and today's count (shared by every
188// session), and the running timer (this session's).
189export function focusSettings(f) {
190 return { work: f.work, rest: f.rest, day: f.day, done: f.done, focusedMs: f.focusedMs, history: f.history };
191}
192export function focusTimer(f) {
193 return { phase: f.phase, endsAt: f.endsAt, left: f.left, paused: f.paused, span: f.span };
194}
195
196// A running phase whose end passed this long ago ran out while no session
197// was there to see it: it isn't counted or chimed for, only let go.
198const STALE_MS = 60_000;
199export function restoreFocus(f, settings, timer, now) {
200 if (settings && typeof settings === "object") {
201 if (Number.isFinite(settings.work)) f.work = Math.min(WORK.max, Math.max(WORK.min, settings.work));
202 if (Number.isFinite(settings.rest)) f.rest = Math.min(REST.max, Math.max(REST.min, settings.rest));
203 if (typeof settings.day === "string") { f.day = settings.day; f.done = settings.done | 0; f.focusedMs = settings.focusedMs | 0; }
204 if (settings.history && typeof settings.history === "object") {
205 f.history = Object.fromEntries(Object.entries(settings.history).filter(([day, n]) => DAY.test(day) && Number.isInteger(n) && n > 0));
206 }
207 }
208 if (timer && ["focus", "break"].includes(timer.phase)) {
209 const paused = timer.paused === true;
210 const endsAt = Number(timer.endsAt) || 0;
211 if (paused || now - endsAt < STALE_MS) {
212 f.phase = timer.phase;
213 f.paused = paused;
214 f.endsAt = endsAt;
215 f.left = Number(timer.left) || 0;
216 f.span = Number(timer.span) || 0;
217 }
218 }
219 rollDay(f, now);
220}
221
222// ---------------------------------------------------------------- drawing
223
224const phaseWord = (f) => (f.phase === "break" ? "break" : f.phase === "focus" ? "focus" : "ready");
225const phaseColor = (f) => (f.phase === "break" ? BREAK_COLOR : FOCUS_META.color);
226export const spent = (ms) => {
227 const m = Math.round(ms / 60_000);
228 return m >= 60 ? `${Math.floor(m / 60)}h ${m % 60}m` : `${m}m`;
229};
230
231// The ring, drawn: the track, the arc gone so far, the time and the phase.
232function ring(els, f, now) {
233 const size = 132, r = 54, c = 2 * Math.PI * r;
234 const color = phaseColor(f);
235 const left = c * (1 - progress(f, now));
236 const sub = f.phase === "idle" ? `${f.work} / ${f.rest} min` : `${phaseWord(f)}${f.paused ? " · paused" : ""}`;
237 const source = `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" font-family="-apple-system, system-ui, sans-serif">`
238 + `<circle cx="66" cy="66" r="${r}" fill="none" stroke="rgba(127,127,127,0.25)" stroke-width="9"/>`
239 + (f.phase === "idle" ? "" : `<circle cx="66" cy="66" r="${r}" fill="none" stroke="${color}" stroke-width="9" stroke-linecap="round" stroke-dasharray="${c.toFixed(1)}" stroke-dashoffset="${left.toFixed(1)}" transform="rotate(-90 66 66)"/>`)
240 + `<text x="66" y="70" text-anchor="middle" font-size="28" font-weight="600" fill="${f.paused ? "#9A968F" : "#ECE7E1"}">${clock(remaining(f, now))}</text>`
241 + `<text x="66" y="92" text-anchor="middle" font-size="12" fill="#9A968F">${sub}</text></svg>`;
242 return els.Svg({ key: "ring", source, alt: `${clock(remaining(f, now))} ${sub}`, width: size, height: size });
243}
244
245function controls(els, f, handlers) {
246 const { Box, Button } = els;
247 const main = f.phase === "idle" ? { label: "▶ Start", fn: "onFocusStart" }
248 : f.paused ? { label: "▶ Resume", fn: "onFocusStart" }
249 : { label: "⏸ Pause", fn: "onFocusPause" };
250 return Box({ key: "controls", flexDirection: "row", justifyContent: "center", columnGap: 1, children: [
251 Button({ key: "focus-main", label: main.label, variant: "primary", onPress: () => handlers[main.fn]?.() }),
252 f.phase === "idle" ? null : Button({ key: "focus-skip", label: f.phase === "focus" ? "⏭ Break" : "⏭ Skip", onPress: () => handlers.onFocusSkip?.() }),
253 f.phase === "idle" ? null : Button({ key: "focus-reset", label: "↺", onPress: () => handlers.onFocusReset?.() }),
254 ].filter(Boolean) });
255}
256
257function timerCard(els, f, w, handlers, now) {
258 const { Box, Text } = els;
259 const color = phaseColor(f);
260 const rows = [];
261 if (els.Svg) {
262 rows.push(Box({ key: "ring-row", flexDirection: "row", justifyContent: "center", children: [ring(els, f, now)] }));
263 } else {
264 rows.push(line(els, "time", [
265 { text: clock(remaining(f, now)), bold: true, color: f.paused ? theme.muted : color },
266 { text: ` ${phaseWord(f)}${f.paused ? " · paused" : ""}`, color: theme.muted, grow: true },
267 ]));
268 rows.push(meter(els, { key: "bar", label: f.phase === "break" ? "Break" : "Focus", pct: progress(f, now) * 100, width: w, color, right: `${Math.round(spanMs(f) / 60_000)} min` }));
269 }
270 rows.push(controls(els, f, handlers));
271 const meta = f.done ? `${f.done} done today` : "none done today";
272 return { name: "Timer", node: card(els, { key: "timer", title: f.phase === "break" ? "BREAK" : "FOCUS", color, meta, rows }), height: 3 + (els.Svg ? 7 : rows.length) };
273}
274
275function lengthRow(els, key, label, value, handlers) {
276 const { Box, Text, Button } = els;
277 return Box({ key, flexDirection: "row", alignItems: "center", children: [
278 Box({ key: "l", flexGrow: 1, children: [Text({ key: "t", children: label })] }),
279 // The value in a box of its own width, so −, the value and + line up
280 // from one row to the next whatever the number.
281 Box({ key: "ctl", flexDirection: "row", alignItems: "center", columnGap: 1, flexShrink: 0, children: [
282 Button({ key: `${key}-less`, label: "−", onPress: () => handlers.onFocusAdjust?.(key, -1) }),
283 Box({ key: "v", width: 8, flexShrink: 0, justifyContent: "center", children: [Text({ key: "t", bold: true, children: `${value} min` })] }),
284 Button({ key: `${key}-more`, label: "+", onPress: () => handlers.onFocusAdjust?.(key, 1) }),
285 ] }),
286 ] });
287}
288
289function settingsCard(els, f, handlers) {
290 const rows = [lengthRow(els, "work", "Focus", f.work, handlers), lengthRow(els, "rest", "Break", f.rest, handlers)];
291 const meta = f.focusedMs ? `${spent(f.focusedMs)} focused today` : "";
292 return { name: "Settings", node: card(els, { key: "settings", title: "SETTINGS", color: FOCUS_META.color, meta, rows }), height: 3 + rows.length };
293}
294
295// The streak, as GitHub draws contributions: a column a week, Sunday at
296// the top, today last, each day's square darker the more rounds it had.
297const LEVELS = [0.18, 0.4, 0.62, 0.84, 1];
298function level(n) {
299 return n <= 0 ? 0 : n === 1 ? 1 : n <= 3 ? 2 : n <= 5 ? 3 : 4;
300}
301function streakGrid(f, now, weeks) {
302 const today = new Date(now).getDay(); // 0 Sunday
303 const cols = [];
304 for (let wk = weeks - 1; wk >= 0; wk--) {
305 const col = [];
306 for (let dow = 0; dow < 7; dow++) {
307 const back = wk * 7 + (today - dow);
308 col.push(back < 0 ? null : f.history[daysBefore(now, back)] ?? 0);
309 }
310 cols.push(col);
311 }
312 return cols;
313}
314
315// A month's short name over the week it starts in, as GitHub sets them; one
316// too close to the last (the first column's, mostly) is left out.
317function monthLabels(now, weeks, step) {
318 const today = new Date(now).getDay();
319 let out = "", lastMonth = -1, lastX = -99;
320 for (let wk = weeks - 1, x = 0; wk >= 0; wk--, x++) {
321 const d = new Date(now);
322 d.setHours(12, 0, 0, 0);
323 d.setDate(d.getDate() - (wk * 7 + today)); // the week's Sunday
324 const m = d.getMonth();
325 if (m !== lastMonth && x * step - lastX >= 30) {
326 out += `<text x="${x * step}" y="10" font-size="10" fill="#9A968F">${d.toLocaleDateString("en-US", { month: "short" })}</text>`;
327 lastX = x * step;
328 }
329 lastMonth = m;
330 }
331 return out;
332}
333
334function streakCard(els, f, w, now) {
335 const { Box, Text } = els;
336 const { current, best } = streaks(f, now);
337 const meta = current ? `🔥 ${current} day${current === 1 ? "" : "s"} · best ${best}` : best ? `best ${best} days` : "";
338 const rose = FOCUS_META.color;
339 let rows;
340 if (els.Svg) {
341 // GitHub's: the months along the top, the squares, then the total and a
342 // Less-to-More legend under them.
343 const weeks = Math.max(12, Math.min(26, Math.floor((w * 8) / 14)));
344 const cell = 11, gap = 3, step = cell + gap, top = 15;
345 const grid = streakGrid(f, now, weeks);
346 const squares = grid.flatMap((col, x) => col.map((n, y) => (n == null ? "" : `<rect x="${x * step}" y="${top + y * step}" width="${cell}" height="${cell}" rx="2.5" fill="${n ? rose : "#8F8D87"}" fill-opacity="${LEVELS[level(n ?? 0)]}"/>`))).join("");
347 const W = weeks * step - gap, H = top + 7 * step - gap;
348 const total = grid.flat().reduce((a, n) => a + (n ?? 0), 0);
349 const legend = `<svg xmlns="http://www.w3.org/2000/svg" width="112" height="14" viewBox="0 0 112 14" font-family="-apple-system, system-ui, sans-serif">`
350 + `<text x="0" y="11" font-size="11" fill="#9A968F">Less</text>`
351 + LEVELS.map((o, i) => `<rect x="${28 + i * 12}" y="2" width="10" height="10" rx="2" fill="${i ? rose : "#8F8D87"}" fill-opacity="${o}"/>`).join("")
352 + `<text x="${28 + 5 * 12 + 2}" y="11" font-size="11" fill="#9A968F">More</text></svg>`;
353 rows = [
354 els.Svg({ key: "streak", source: `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" font-family="-apple-system, system-ui, sans-serif">${monthLabels(now, weeks, step)}${squares}</svg>`, alt: `${total} focus rounds in the last ${weeks} weeks`, width: W, height: H }),
355 Box({ key: "foot", flexDirection: "row", alignItems: "center", children: [
356 Box({ key: "sum", flexGrow: 1, children: [Text({ key: "t", color: theme.muted, children: `${total} round${total === 1 ? "" : "s"} in ${weeks} weeks` })] }),
357 els.Svg({ key: "legend", source: legend, alt: "Less to more rounds", width: 112, height: 14 }),
358 ] }),
359 ];
360 } else {
361 // A square and a space a day: as many weeks as the card holds.
362 const weeks = Math.max(4, Math.min(26, Math.floor((w - 1) / 2)));
363 const grid = streakGrid(f, now, weeks);
364 rows = Array.from({ length: 7 }, (_, dow) => Box({ key: `d${dow}`, flexDirection: "row", children: grid.map((col, x) => {
365 const n = col[dow];
366 return Text({ key: `c${x}`, color: n ? rose : theme.muted, dimColor: !n || level(n) < 2, children: n == null ? " " : n ? "■ " : "· " });
367 }) }));
368 }
369 return { name: "Streak", node: card(els, { key: "streak", title: "STREAK", color: FOCUS_META.color, meta, rows }), height: 3 + (els.Svg ? 8 : 7) };
370}
371
372export function focusDock(els, w, capacity, handlers, now) {
373 const f = state.focus;
374 return stackCards(els, [timerCard(els, f, w, handlers, now), settingsCard(els, f, handlers), streakCard(els, f, w, now)], capacity, handlers.scroll);
375}
376
377export function focusInline(els, w, handlers, now) {
378 const f = state.focus;
379 const { Box, Button } = els;
380 return [
381 line(els, "head", [
382 { text: `${FOCUS_META.icon} ${FOCUS_META.label}`, bold: true, color: FOCUS_META.color },
383 { text: ` ${clock(remaining(f, now))}`, bold: true, color: phaseColor(f) },
384 { text: ` ${phaseWord(f)}${f.paused ? " · paused" : ""}`, color: theme.muted, grow: true },
385 { text: `${f.done} today`, color: theme.muted },
386 ]),
387 meter(els, { key: "bar", label: `${f.work}/${f.rest} min`, pct: progress(f, now) * 100, width: w, color: phaseColor(f) }),
388 controls(els, f, handlers),
389 ];
390}
391
392const hhmm = (ms) => { const d = new Date(ms); return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`; };
393const phaseLabel = (f) => (f.phase === "break" ? "☕ Break" : f.phase === "focus" ? "🍅 Focus" : "Ready");
394// What comes after the phase on show.
395function nextText(f, now) {
396 if (f.phase === "break") return `next: round ${f.done + 1} · ${f.work} min`;
397 if (f.phase === "focus") return f.paused ? `${f.rest} min break after` : `ends ${hhmm(now + remaining(f, now))}`;
398 return `${f.work} / ${f.rest} min`;
399}
400
401// The terminal's band: "☕ Break 03:12 · 🔥 5 days · next: round 4 · 25 min".
402export function focusBandPieces() {
403 const f = state.focus;
404 const now = Date.now();
405 const { current } = streaks(f, now);
406 const sep = { text: " · ", color: theme.muted };
407 return [
408 { text: phaseLabel(f), color: phaseColor(f), bold: true },
409 f.phase === "idle" ? null : { text: ` ${clock(remaining(f, now))}${f.paused ? " ⏸" : ""}`, color: phaseColor(f), bold: true },
410 current ? sep : null,
411 current ? { text: `🔥 ${current} day${current === 1 ? "" : "s"}`, color: theme.amber, bold: true } : null,
412 sep,
413 { text: nextText(f, now), color: theme.muted },
414 ].filter(Boolean);
415}
416
417// The desktop's band, as sections for the capsule: the phase and its time,
418// ten cells for how far it has gone, the streak with this week's days, and
419// what comes next. The capsule takes the phase's color: green in a break.
420export function focusBandDesk(now = Date.now()) {
421 const f = state.focus;
422 const color = phaseColor(f);
423 const { current, best } = streaks(f, now);
424 const pct = progress(f, now) * 100;
425 const week = Array.from({ length: 7 }, (_, i) => f.history[daysBefore(now, 6 - i)] ?? 0);
426 const squares = { source: K.svg(63, 9, week.map((n, i) => `<rect x="${i * 9}" y="1" width="7" height="7" rx="1.5" fill="${n ? FOCUS_META.color : "#8F8D87"}" fill-opacity="${LEVELS[level(n)]}"/>`).join("")), width: 63, height: 9 };
427 const sections = [
428 { key: "phase", color, parts: [value(phaseLabel(f), color), f.phase === "idle" ? null : value(`${clock(remaining(f, now))}${f.paused ? " ⏸" : ""}`)],
429 tip: [`Focus ${f.work} min · Break ${f.rest} min`, `${f.done} round${f.done === 1 ? "" : "s"} done today`] },
430 f.phase === "idle" ? null : { key: "progress", color, parts: [draw(K.cells(pct, color, { n: 10 }), `${Math.round(pct)}% through`)] },
431 { key: "streak", color: theme.amber, parts: [current ? value(`🔥 ${current} day${current === 1 ? "" : "s"}`, theme.amber) : sub("no streak yet"), draw(squares, "This week"), sub("this week")],
432 tip: [current ? `${current} day${current === 1 ? "" : "s"} in a row` : "Finish a round today to start one", `best ${best} day${best === 1 ? "" : "s"}`] },
433 { key: "next", color, parts: [sub(nextText(f, now))] },
434 ];
435 return { color, sections: sections.filter(Boolean) };
436}
437
438export function focusStatus(now = Date.now()) {
439 const f = state.focus;
440 if (f.phase === "idle") return "";
441 return `${f.phase === "break" ? "☕" : "🍅"} ${clock(remaining(f, now))}${f.paused ? " ⏸" : ""}`;
442}
443
444// The tab's badge from another room: minutes left while running.
445export function focusBadge(now = Date.now()) {
446 const f = state.focus;
447 if (f.phase === "idle") return null;
448 return { text: f.paused ? "⏸" : `${Math.ceil(remaining(f, now) / 60_000)}m`, color: phaseColor(f) };
449}
450
451export function focusSnapshot(now = Date.now()) {
452 const f = state.focus;
453 const left = clock(remaining(f, now));
454 const head = f.phase === "idle" ? `Ready to focus (${f.work} / ${f.rest} min).`
455 : f.phase === "break" ? `On a break, ${left} left${f.paused ? ", paused" : ""}.`
456 : `Focusing, ${left} to go of ${Math.round(spanMs(f) / 60_000)} min${f.paused ? ", paused" : ""}.`;
457 const today = f.done ? `${f.done} round${f.done === 1 ? "" : "s"} today, ${spent(f.focusedMs)} focused.` : "No rounds yet today.";
458 const { current } = streaks(f, now);
459 return `◷ ${head} ${today}${current ? ` 🔥 ${current}-day streak.` : ""}`;
460}
461hooks/habits.mjs 490 lines1// The Habits room: goals checked off once a day, or a number of times a day
2// ("Water x8"), each with its streak drawn as GitHub draws contributions.
3// The goals and their days are kept in $.store, the same in every session.
4//
5// Plain logic and drawing: the mod owns the store and the clock.
6
7import { state } from "./state.mjs";
8import { theme } from "./theme.mjs";
9import { line, card, stackCards, cells } from "./widgets.mjs";
10import * as K from "./bandkit.mjs";
11import { draw, value, sub, msg } from "./bands.mjs";
12import { dayOf, daysBefore } from "./focus.mjs";
13
14export const HABITS_META = { icon: "✓", label: "Habits", color: "#6FC2B5" };
15const TEAL = HABITS_META.color;
16const GREY = "#8F8D87";
17
18export const MAX_HABITS = 12;
19const MAX_NAME = 24;
20const MAX_TARGET = 99;
21const KEEP_DAYS = 371; // 53 weeks
22const DAY = /^\d{4}-\d{2}-\d{2}$/;
23
24export function createHabits() {
25 return {
26 goals: [], // [{ id: "h1", name: "Read 30 min", target: 1 }], in the order added
27 history: {}, // goal id → { "2026-10-13": times done that day }, the last year
28 };
29}
30
31// ---------------------------------------------------------------- the goals
32
33const count = (h, g, day) => h.history[g.id]?.[day] ?? 0;
34const doneOn = (h, g, day) => count(h, g, day) >= g.target;
35
36// How many of the goals are done today, and the ones that aren't.
37export function today(h, now) {
38 const day = dayOf(now);
39 const left = h.goals.filter((g) => !doneOn(h, g, day));
40 return { done: h.goals.length - left.length, total: h.goals.length, left, day };
41}
42
43// The days kept, today first: back[n] is the day n days before today's.
44// Worked out once a day, not once a square and a streak each redraw.
45let keptFor = "", kept = [];
46function daysBack(now) {
47 const today = dayOf(now);
48 if (today !== keptFor) {
49 kept = Array.from({ length: KEEP_DAYS + 1 }, (_, n) => daysBefore(now, n));
50 keptFor = today;
51 }
52 return kept;
53}
54
55// Days in a row with the goal met, up to today (or yesterday, when today
56// isn't done yet), and the longest run kept.
57export function habitStreaks(h, g, now) {
58 const days = daysBack(now);
59 const met = (n) => n < days.length && doneOn(h, g, days[n]);
60 let current = 0;
61 for (let n = met(0) ? 0 : 1; met(n); n++) current++;
62 let best = 0, run = 0;
63 for (let n = days.length - 1; n >= 0; n--) {
64 run = met(n) ? run + 1 : 0;
65 best = Math.max(best, run);
66 }
67 return { current, best };
68}
69
70// Two names are the same habit when they read the same: case, spaces,
71// full-width letters and digits (as an IME types them) and a stop at the
72// end don't count. "Read 30 min", "read30min." and "Read 30 min" are one.
73export const nameKey = (name) => String(name ?? "").normalize("NFKC").toLowerCase().replace(/\s+/g, "").replace(/[.。!!??,,、;;::~~]+$/, "");
74const sameName = (h, name, except = null) => h.goals.find((g) => g !== except && nameKey(g.name) === nameKey(name));
75
76// A goal by its number (1, 2 …), its name, or the start of one name.
77export function findHabit(h, text) {
78 const want = String(text ?? "").trim().toLowerCase();
79 if (!want) return null;
80 if (/^\d+$/.test(want)) return h.goals[Number(want) - 1] ?? null;
81 const exact = sameName(h, want);
82 if (exact) return exact;
83 const starts = h.goals.filter((g) => g.name.toLowerCase().startsWith(want));
84 return starts.length === 1 ? starts[0] : null;
85}
86
87// "Water x8" (or ×8, *8): a name and how many times a day; once otherwise.
88// An x counts only after a space, so "Inbox 0" and "Relax 5" stay names.
89// Full-width text (an IME's "Water x8") reads as the half-width it shows.
90const COUNTED = /^(.*?\S)(?:\s+[x×*]|\s*[×*])\s*(\d{1,2})$/i;
91function parseGoal(text) {
92 const t = String(text ?? "").normalize("NFKC").trim();
93 const m = COUNTED.exec(t);
94 const name = (m ? m[1] : t).trim().replace(/\s+/g, " ");
95 const target = m ? Math.min(MAX_TARGET, Math.max(1, Number(m[2]))) : 1;
96 return { name, target };
97}
98
99function nextId(h) {
100 const used = h.goals.map((g) => Number(g.id.slice(1)) || 0);
101 return `h${Math.max(0, ...used) + 1}`;
102}
103
104// Each returns what to say: the change made, or why it wasn't.
105export function addHabit(h, text) {
106 const { name, target } = parseGoal(text);
107 if (!name) return "Name the habit: add Read 30 min, or add Water x8 for one done 8 times a day.";
108 if ([...name].length > MAX_NAME) return `A habit's name is ${MAX_NAME} characters at most.`;
109 const taken = sameName(h, name);
110 if (taken) return `There's already a habit called ${taken.name}.`;
111 if (h.goals.length >= MAX_HABITS) return `${MAX_HABITS} habits at most: remove one first.`;
112 h.goals.push({ id: nextId(h), name, target });
113 return `Added ${name}${target > 1 ? `, ${target} times a day` : ""}.`;
114}
115
116export function removeHabit(h, text) {
117 const g = findHabit(h, text);
118 if (!g) return noSuch(h, text);
119 return dropGoal(h, g);
120}
121
122function dropGoal(h, g) {
123 h.goals = h.goals.filter((x) => x !== g);
124 delete h.history[g.id];
125 return `Removed ${g.name} and its streak.`;
126}
127
128// "Read -> Read 20 min", or "Water -> Water x10" to change the count too.
129export function renameHabit(h, text) {
130 const [from, to] = String(text ?? "").split(/\s*(?:->|→)\s*/);
131 const g = findHabit(h, from);
132 if (!g) return noSuch(h, from);
133 const next = parseGoal(to);
134 if (!next.name) return "Rename with old -> new: rename Read -> Read 20 min.";
135 if ([...next.name].length > MAX_NAME) return `A habit's name is ${MAX_NAME} characters at most.`;
136 const taken = sameName(h, next.name, g);
137 if (taken) return `There's already a habit called ${taken.name}.`;
138 const was = g.name;
139 g.name = next.name;
140 if (COUNTED.test(to.normalize("NFKC").trim())) g.target = next.target;
141 return `${was} is now ${g.name}${g.target > 1 ? `, ${g.target} times a day` : ""}.`;
142}
143
144// Today's count, a step up or down, kept between none and the goal's.
145export function markHabit(h, id, dir, now) {
146 const g = h.goals.find((x) => x.id === id);
147 if (!g) return null;
148 const day = dayOf(now);
149 const days = (h.history[g.id] ??= {});
150 const n = Math.min(g.target, Math.max(0, (days[day] ?? 0) + dir));
151 if (n) days[day] = n;
152 else delete days[day];
153 const oldest = daysBack(now).at(-1);
154 for (const d of Object.keys(days)) if (d < oldest) delete days[d];
155 return g;
156}
157
158// ✕ on a card: the habit and its days go. Returns what to say and what
159// Cancel needs to put it back, or null. By its id: a name such as "2"
160// would read as the second habit.
161export function deleteHabit(h, id) {
162 const index = h.goals.findIndex((x) => x.id === id);
163 if (index < 0) return null;
164 const goal = { ...h.goals[index] };
165 const days = { ...(h.history[id] ?? {}) };
166 return { said: dropGoal(h, h.goals[index]), kept: { goal, days, index } };
167}
168
169// Cancel after ✕: the habit back where it was, with its days. A name taken
170// since (or no room left) keeps it gone; an id taken since gets a new one.
171export function undeleteHabit(h, { goal, days, index }) {
172 const taken = sameName(h, goal.name);
173 if (taken) return `There's already a habit called ${taken.name}.`;
174 if (h.goals.length >= MAX_HABITS) return `${MAX_HABITS} habits at most: remove one first.`;
175 const id = h.goals.some((g) => g.id === goal.id) ? nextId(h) : goal.id;
176 h.goals.splice(Math.min(index, h.goals.length), 0, { ...goal, id });
177 h.history[id] = { ...days };
178 return `${goal.name} is back.`;
179}
180
181// ✓ on a goal done once a day: done, or not after all.
182export function toggleHabit(h, id, now) {
183 const g = h.goals.find((x) => x.id === id);
184 if (!g) return null;
185 return markHabit(h, id, doneOn(h, g, dayOf(now)) ? -g.target : 1, now);
186}
187
188function noSuch(h, text) {
189 const names = h.goals.map((g, i) => `${i + 1} ${g.name}`).join(", ");
190 return h.goals.length ? `No habit called ${String(text ?? "").trim()}. There are ${names}.` : "No habits yet: add Read 30 min.";
191}
192
193// Words typed in the room's box (`typed`), or after /habit. Returns what to
194// say, or null when the words weren't for the room.
195export function habitWords(h, text, now, { typed = false } = {}) {
196 const t = String(text ?? "").trim();
197 const m = /^(add|new|remove|rm|delete|rename|done|check|undo)\b\s*([\s\S]*)$/i.exec(t);
198 if (!m) {
199 // In the box, anything else is a new habit: the button says add.
200 if (typed) return addHabit(h, t);
201 // After /habit, a habit's own name checks it off (another time, for a counted one).
202 const g = findHabit(h, t);
203 if (!g || /^\d+$/.test(t)) return null;
204 return doneWord(h, g, 1, now);
205 }
206 const [, verb, rest] = m;
207 // In the box a habit may start with one of these words ("Check email"):
208 // the word is a command only when what follows fits it.
209 if (typed) {
210 const v = verb.toLowerCase();
211 const fits = v === "add" ? !!rest.trim() : v === "rename" ? /->|→/.test(rest) : v === "new" ? false : !!findHabit(h, rest);
212 if (!fits) return addHabit(h, t);
213 }
214 switch (verb.toLowerCase()) {
215 case "add": case "new": return addHabit(h, rest);
216 case "remove": case "rm": case "delete": return rest ? removeHabit(h, rest) : "Say which: remove Run.";
217 case "rename": return renameHabit(h, rest);
218 case "done": case "check": case "undo": {
219 const g = findHabit(h, rest);
220 if (!g) return noSuch(h, rest);
221 return doneWord(h, g, verb.toLowerCase() === "undo" ? -1 : 1, now);
222 }
223 }
224 return null;
225}
226
227function doneWord(h, g, dir, now) {
228 markHabit(h, g.id, dir, now);
229 const n = count(h, g, dayOf(now));
230 const { current } = habitStreaks(h, g, now);
231 if (g.target > 1) return `${g.name}: ${n}/${g.target} today${n >= g.target && current ? ` · 🔥 ${current}` : ""}.`;
232 return n ? `${g.name} done${current ? ` · 🔥 ${current} day${current === 1 ? "" : "s"}` : ""}.` : `${g.name} not done today.`;
233}
234
235// What's kept in $.store, and read back from it.
236export function habitsSaved(h) {
237 return { goals: h.goals, history: h.history };
238}
239
240export function restoreHabits(h, saved) {
241 if (!saved || typeof saved !== "object") return;
242 const goals = Array.isArray(saved.goals) ? saved.goals : [];
243 h.goals = goals
244 .filter((g) => g && typeof g.id === "string" && /^h\d+$/.test(g.id) && typeof g.name === "string" && g.name.trim())
245 .slice(0, MAX_HABITS)
246 .map((g) => ({ id: g.id, name: g.name.trim().slice(0, 64), target: Math.min(MAX_TARGET, Math.max(1, Number(g.target) | 0 || 1)) }));
247 const history = saved.history && typeof saved.history === "object" ? saved.history : {};
248 h.history = Object.fromEntries(h.goals.map((g) => [g.id, Object.fromEntries(Object.entries(history[g.id] ?? {})
249 .filter(([day, n]) => DAY.test(day) && Number.isInteger(n) && n > 0))]));
250}
251
252// ---------------------------------------------------------------- drawing
253
254// The squares' shades, Less to More, as GitHub has them: a count of the
255// day's goal in four steps, a goal done once a day in one.
256const LEVELS = [0.16, 0.35, 0.55, 0.78, 1];
257const level = (n, target) => (n <= 0 ? 0 : target === 1 ? 4 : Math.max(1, Math.min(4, Math.ceil((n / target) * 4))));
258const flame = (n) => `🔥 ${n} day${n === 1 ? "" : "s"}`;
259
260// The weeks as columns, Sunday at the top, today's week last: each day's
261// count, or null for the days after today.
262function grid(h, g, now, weeks) {
263 const dow = new Date(now).getDay();
264 const days = daysBack(now);
265 const cols = [];
266 for (let wk = weeks - 1; wk >= 0; wk--) {
267 const col = [];
268 for (let d = 0; d < 7; d++) {
269 const back = wk * 7 + (dow - d);
270 col.push(back < 0 ? null : count(h, g, days[back]));
271 }
272 cols.push(col);
273 }
274 return cols;
275}
276
277// A month's short name over the week it starts in; one too close to the
278// last is left out, as GitHub does.
279function monthLabels(now, weeks, step, left) {
280 const dow = new Date(now).getDay();
281 let out = "", lastMonth = -1, lastX = -99;
282 for (let wk = weeks - 1, x = 0; wk >= 0; wk--, x++) {
283 const d = new Date(now);
284 d.setHours(12, 0, 0, 0);
285 d.setDate(d.getDate() - (wk * 7 + dow));
286 const m = d.getMonth();
287 if (m !== lastMonth && x * step - lastX >= 28) {
288 out += `<text x="${left + x * step}" y="10" font-size="10" fill="#9A968F">${d.toLocaleDateString("en-US", { month: "short" })}</text>`;
289 lastX = x * step;
290 }
291 lastMonth = m;
292 }
293 return out;
294}
295
296// The weeks that fit the card: the day names take a little of the width.
297const weeksFor = (w) => Math.max(12, Math.min(26, Math.floor((w * 8 - 28) / 14)));
298
299function heatmap(els, h, g, w, now) {
300 const weeks = weeksFor(w);
301 const cell = 11, gap = 3, step = cell + gap, top = 15, left = 28;
302 const cols = grid(h, g, now, weeks);
303 const last = cols.length - 1, dow = new Date(now).getDay();
304 const squares = cols.flatMap((col, x) => col.map((n, y) => {
305 if (n == null) return "";
306 const L = level(n, g.target);
307 // Today's square is ringed, so the column it's in reads as this week.
308 const ring = x === last && y === dow ? ' stroke="#ECE7E1" stroke-width="1.2"' : "";
309 return `<rect x="${left + x * step}" y="${top + y * step}" width="${cell}" height="${cell}" rx="2.5" fill="${L ? TEAL : GREY}" fill-opacity="${LEVELS[L]}"${ring}/>`;
310 })).join("");
311 const names = ["Mon", "Wed", "Fri"].map((t, i) => `<text x="0" y="${top + (1 + i * 2) * step + 9}" font-size="10" fill="#9A968F">${t}</text>`).join("");
312 const W = left + weeks * step - gap, H = top + 7 * step - gap;
313 const met = cols.flat().filter((n) => n != null && n >= g.target).length;
314 const source = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" font-family="-apple-system, system-ui, sans-serif">${monthLabels(now, weeks, step, left)}${names}${squares}</svg>`;
315 return { node: els.Svg({ key: "grid", source, alt: `${g.name}: ${met} day${met === 1 ? "" : "s"} done in the last ${weeks} weeks`, width: W, height: H }), met, weeks };
316}
317
318// Less to More for a counted goal; missed and done for the rest.
319function legend(els, g) {
320 const body = g.target > 1
321 ? `<text x="0" y="11" font-size="11" fill="#9A968F">Less</text>`
322 + LEVELS.map((o, i) => `<rect x="${28 + i * 12}" y="2" width="10" height="10" rx="2" fill="${i ? TEAL : GREY}" fill-opacity="${o}"/>`).join("")
323 + `<text x="${28 + 5 * 12 + 2}" y="11" font-size="11" fill="#9A968F">More</text>`
324 : `<rect x="0" y="2" width="10" height="10" rx="2" fill="${GREY}" fill-opacity="${LEVELS[0]}"/><text x="14" y="11" font-size="11" fill="#9A968F">missed</text>`
325 + `<rect x="62" y="2" width="10" height="10" rx="2" fill="${TEAL}"/><text x="76" y="11" font-size="11" fill="#9A968F">done</text>`;
326 const width = 120;
327 return els.Svg({ key: "legend", source: K.svg(width, 14, body).replace("<svg ", '<svg font-family="-apple-system, system-ui, sans-serif" '), alt: g.target > 1 ? "Less to more" : "Missed or done", width, height: 14 });
328}
329
330// ✓ for a goal done once a day (✓ again takes it back); − and +1 for a counted one.
331function buttons(els, h, g, handlers, now) {
332 const { Box, Button } = els;
333 const done = doneOn(h, g, dayOf(now));
334 const kids = g.target > 1
335 ? [
336 count(h, g, dayOf(now)) ? Button({ key: `habit-${g.id}-less`, label: "−", onPress: () => handlers.onHabitMark?.(g.id, -1) }) : null,
337 Button({ key: `habit-${g.id}-do`, label: done ? "✓" : "+1", variant: done ? "primary" : undefined, onPress: () => handlers.onHabitMark?.(g.id, done ? 0 : 1) }),
338 ]
339 : [Button({ key: `habit-${g.id}-do`, label: "✓", variant: done ? "primary" : undefined, onPress: () => handlers.onHabitToggle?.(g.id) })];
340 return Box({ key: "btns", flexDirection: "row", columnGap: 1, flexShrink: 0, children: kids.filter(Boolean) });
341}
342
343function habitCard(els, h, g, w, handlers, now) {
344 const { Box, Text } = els;
345 const { current, best } = habitStreaks(h, g, now);
346 const n = count(h, g, dayOf(now));
347 const metaNode = Box({ key: "meta", flexDirection: "row", alignItems: "center", columnGap: 1, flexShrink: 0, children: [
348 g.target > 1 ? Text({ key: "n", color: theme.muted, children: `${n}/${g.target}` }) : null,
349 current ? Text({ key: "s", color: theme.amber, bold: true, children: flame(current) }) : null,
350 best ? Text({ key: "b", color: theme.muted, children: `best ${best}` }) : null,
351 buttons(els, h, g, handlers, now),
352 els.Button({ key: `habit-${g.id}-delete`, plain: true, dimColor: true, label: "✕", onPress: () => handlers.onHabitDelete?.(g.id) }),
353 ].filter(Boolean) });
354 let rows;
355 if (els.Svg) {
356 const map = heatmap(els, h, g, w, now);
357 rows = [
358 map.node,
359 Box({ key: "foot", flexDirection: "row", alignItems: "center", children: [
360 Box({ key: "sum", flexGrow: 1, children: [Text({ key: "t", color: theme.muted, wrap: "truncate-end", children: `${map.met} day${map.met === 1 ? "" : "s"} in ${map.weeks} weeks` })] }),
361 legend(els, g),
362 ] }),
363 ];
364 } else {
365 // A square and a space a day: as many weeks as the card holds.
366 const weeks = Math.max(4, Math.min(26, Math.floor((w - 1) / 2)));
367 const cols = grid(h, g, now, weeks);
368 rows = Array.from({ length: 7 }, (_, d) => Box({ key: `d${d}`, flexDirection: "row", children: cols.map((col, x) => {
369 const v = col[d];
370 const L = v == null ? 0 : level(v, g.target);
371 return Text({ key: `c${x}`, color: L ? TEAL : theme.muted, dimColor: !L || L < 3, children: v == null ? " " : L ? "■ " : "· " });
372 }) }));
373 }
374 return { name: g.id, node: card(els, { key: `habit-${g.id}`, title: g.name.toUpperCase(), color: TEAL, metaNode, rows }), height: 3 + (els.Svg ? 8 : 7) };
375}
376
377function emptyCard(els) {
378 const { Text } = els;
379 const rows = [
380 Text({ key: "a", children: "No habits yet." }),
381 Text({ key: "b", color: theme.muted, wrap: "wrap", children: "Type add Read 30 min, or add Water x8 for one done 8 times a day." }),
382 ];
383 return { name: "empty", node: card(els, { key: "habits-empty", title: "HABITS", color: TEAL, rows }), height: 3 + 3 };
384}
385
386export function habitsDock(els, w, capacity, handlers, now) {
387 const h = state.habits;
388 if (!h.goals.length) return stackCards(els, [emptyCard(els)], capacity, handlers.scroll);
389 return stackCards(els, h.goals.map((g) => habitCard(els, h, g, w, handlers, now)), capacity, handlers.scroll);
390}
391
392// The inline pane: today's count, then a line a goal with its streak and its button.
393export function habitsInline(els, w, handlers, now) {
394 const h = state.habits;
395 const t = today(h, now);
396 const head = line(els, "head", [
397 { text: `${HABITS_META.icon} ${HABITS_META.label}`, bold: true, color: TEAL },
398 { text: t.total ? ` ${t.done}/${t.total} today` : " add Read 30 min to start", color: theme.muted, grow: true },
399 ]);
400 return [head, ...h.goals.map((g) => {
401 const { current } = habitStreaks(h, g, now);
402 const n = count(h, g, t.day);
403 return line(els, `g-${g.id}`, [
404 { text: g.name, grow: true, color: doneOn(h, g, t.day) ? TEAL : undefined },
405 g.target > 1 ? { text: ` ${n}/${g.target} `, color: theme.muted } : null,
406 { text: current ? ` 🔥 ${current} ` : " ", color: theme.amber, bold: true },
407 { node: buttons(els, h, g, handlers, now) },
408 ]);
409 })];
410}
411
412// The goals not done yet: "Water 5/8, Run". With `width`, as many as fit
413// and "+3 more" for the rest.
414const leftName = (h, g, day) => (g.target > 1 ? `${g.name} ${count(h, g, day)}/${g.target}` : g.name);
415function leftText(h, t, sepr, width = Infinity) {
416 const names = t.left.map((g) => leftName(h, g, t.day));
417 let out = "";
418 for (let i = 0; i < names.length; i++) {
419 const next = (out ? out + sepr : "") + names[i];
420 const more = i + 1 < names.length ? `${sepr}+${names.length - i - 1} more` : "";
421 if (out && cells(next + more) > width) return `${out}${sepr}+${names.length - i} more`;
422 out = next;
423 }
424 return out;
425}
426
427// The goals' streaks, longest first, the ones running only.
428function running(h, now) {
429 return h.goals.map((g) => ({ g, ...habitStreaks(h, g, now) })).filter((x) => x.current).sort((a, b) => b.current - a.current);
430}
431
432// The terminal's band, after the room's name: "3/5 today · 🔥 Meditate 27 ·
433// Read 12 · left: Water 5/8, Run", the list cut to `width` with "+3 more".
434export function habitsBandPieces(width = 0) {
435 const h = state.habits;
436 const now = Date.now();
437 const t = today(h, now);
438 const sep = { text: " · ", color: theme.muted };
439 if (!t.total) return [{ text: "no habits yet: add one in the room", color: theme.muted }];
440 const top = running(h, now).slice(0, 2);
441 const pieces = [
442 { text: `${t.done}/${t.total} today`, color: TEAL, bold: true },
443 top.length ? sep : null,
444 top.length ? { text: `🔥 ${top.map((x) => `${x.g.name} ${x.current}`).join(" · ")}`, color: theme.amber, bold: true } : null,
445 sep,
446 ].filter(Boolean);
447 const used = pieces.reduce((n, p) => n + cells(p.text), 0);
448 const room = width ? Math.max(12, width - used - cells("left: ")) : Infinity;
449 pieces.push({ text: t.left.length ? `left: ${leftText(h, t, ", ", room)}` : "all done today", color: theme.muted });
450 return pieces;
451}
452
453// The desktop's band, as sections for the capsule: today's count with a
454// square a goal, the longest streak running, and what's left.
455export function habitsBandDesk(now = Date.now()) {
456 const h = state.habits;
457 const t = today(h, now);
458 if (!t.total) return { color: TEAL, sections: [{ key: "empty", color: TEAL, parts: [sub("no habits yet: add one in the room")] }] };
459 const dots = h.goals.map((g, i) => `<rect x="${i * 9}" y="1" width="7" height="7" rx="1.5" fill="${doneOn(h, g, t.day) ? TEAL : GREY}" fill-opacity="${doneOn(h, g, t.day) ? 1 : LEVELS[0]}"/>`).join("");
460 const squares = { source: K.svg(h.goals.length * 9 - 2, 9, dots), width: h.goals.length * 9 - 2, height: 9 };
461 const top = running(h, now)[0];
462 const sections = [
463 { key: "today", color: TEAL, parts: [value(`${HABITS_META.icon} ${t.done}/${t.total}`, TEAL), draw(squares, `${t.done} of ${t.total} done today`)],
464 tip: h.goals.map((g) => `${doneOn(h, g, t.day) ? "✓" : "○"} ${g.name}${g.target > 1 ? ` ${count(h, g, t.day)}/${g.target}` : ""}`) },
465 { key: "streak", color: theme.amber, parts: top ? [value(`🔥 ${top.current}`, theme.amber), sub(top.g.name)] : [sub("no streak yet")],
466 tip: top ? [`${top.g.name}: ${top.current} day${top.current === 1 ? "" : "s"} in a row`, `best ${top.best} day${top.best === 1 ? "" : "s"}`] : ["Check a habit off today to start one"] },
467 // What's left gives way to the rest: cut short, never left out.
468 { key: "left", color: TEAL, grow: true, parts: [t.left.length ? msg(`${t.left.length} left: ${leftText(h, t, " · ")}`, { dim: true }) : sub("all done today")],
469 tip: t.left.length ? [`${t.left.length} left today`, ...t.left.map((g) => leftName(h, g, t.day))] : null },
470 ];
471 return { color: TEAL, sections };
472}
473
474// The tab's badge from another room: how many are left today.
475export function habitsBadge(now = Date.now()) {
476 const t = today(state.habits, now);
477 return t.total && t.left.length ? { text: String(t.left.length), color: TEAL } : null;
478}
479
480// A line of chat for Share.
481export function habitsSnapshot(now = Date.now()) {
482 const h = state.habits;
483 const t = today(h, now);
484 if (!t.total) return `${HABITS_META.icon} No habits set up yet.`;
485 const top = running(h, now).slice(0, 3).map((x) => `${x.g.name} ${x.current} day${x.current === 1 ? "" : "s"}`);
486 const left = t.left.length ? ` Left: ${leftText(h, t, ", ")}.` : " All done today.";
487 return `${HABITS_META.icon} ${t.done} of ${t.total} habits done today.${top.length ? ` 🔥 ${top.join(", ")}.` : ""}${left}`;
488}
489
490hooks/toolbox.mjs 327 lines1// The Toolbox room: small tools a developer reaches for (Base64, JWT, UUID,
2// hashes, Unix times, cron …), picked from a menu and run on what's typed.
3// What's typed and what comes out live in this session's memory only: they
4// are never kept, and the room is never shared to a chat.
5//
6// Plain logic and drawing: the tools are in toolkit.mjs, and the mod reads
7// the clipboard and copies.
8
9import { state } from "./state.mjs";
10import { theme } from "./theme.mjs";
11import { line, card, stackCards, cells, clip, inlineCut } from "./widgets.mjs";
12import * as K from "./bandkit.mjs";
13import { draw, label, value, sub, msg, chip } from "./bands.mjs";
14import { TOOLS, GROUPS, TOOL_IDS, findTool, runTool, detectClip } from "./toolkit.mjs";
15
16export const TOOLBOX_META = { icon: "⚒", label: "Toolbox", color: "#D9A877" };
17const SAND = TOOLBOX_META.color;
18const COPIED_MS = 5_000; // how long the band says "copied"
19const SOON_MS = 10 * 60_000; // a JWT on the clipboard this close to its exp marks the tab
20const MASK = "••••••••••••";
21const BLOCK_LINES = 12; // a block result's lines shown before "+3 more lines"
22export const MAX_INPUT = 200_000; // characters a tool runs on: a paste past this is cut
23
24export function createToolbox() {
25 return {
26 tool: "uuid", // the tool on show
27 input: "", // what it runs on
28 out: null, // its last result (toolkit.mjs)
29 at: 0, // when it ran
30 used: false, // a tool has run in this session: the band says what
31 reveal: false, // a secret result drawn plainly
32 copiedAt: 0, // ⧉ pressed: the band says so for a moment
33 clipSeen: null, // the newest clipboard item when it ran: one copied since is newer
34 runs: 0, // runs started: only the latest one's result is kept
35 };
36}
37
38// What a tool runs on, cut to MAX_INPUT. True when it was cut.
39export function setInput(tb, text) {
40 const t = String(text ?? "").trim();
41 tb.input = t.length > MAX_INPUT ? t.slice(0, MAX_INPUT) : t;
42 return t.length > MAX_INPUT;
43}
44
45// Run the tool on show again: on a new input, a new tool, or ↻. A run
46// that ends after a newer one began (a long hash, then UUID picked) is
47// dropped, so a card never shows another tool's rows.
48export async function rerun(tb, now, { used = true } = {}) {
49 const run = ++tb.runs;
50 const out = await runTool(tb.tool, tb.input, now);
51 if (run !== tb.runs) return tb.out;
52 tb.out = out;
53 tb.at = now;
54 tb.reveal = false;
55 if (used) { tb.used = true; tb.clipSeen = state.clipboard?.items?.[0]?.id ?? null; }
56 return tb.out;
57}
58
59// A tool from the menu: shown, and run on nothing (a generator makes its
60// first batch) or on what was there, when the tool reads text.
61export async function pickTool(tb, id, now) {
62 if (!TOOLS[id]) return null;
63 const was = tb.tool;
64 tb.tool = id;
65 // Options for one generator ("5 v7") mean nothing to another tool.
66 if (was !== id && (TOOLS[id].generates || TOOLS[was]?.generates)) tb.input = "";
67 return rerun(tb, now, { used: !!TOOLS[id].generates || !!tb.input });
68}
69
70// Words typed in the room's box, or after /tool. A tool's name alone shows
71// it; "/tool hash hello" picks one and runs it; anything else typed in the
72// box is the input for the tool on show. Returns what to say ("" when the
73// room shows it), or null when the words weren't for the room.
74export async function toolWords(tb, text, now, { typed = false } = {}) {
75 const t = String(text ?? "").trim();
76 if (!t) return null;
77 const [first, ...rest] = t.split(/\s+/);
78 const id = findTool(first);
79 if (id && (!typed || !rest.length)) {
80 tb.tool = id;
81 setInput(tb, t.slice(first.length));
82 await rerun(tb, now, { used: !!TOOLS[id].generates || !!tb.input });
83 return "";
84 }
85 if (!typed) return null;
86 setInput(tb, t);
87 await rerun(tb, now);
88 return "";
89}
90
91// The text a result row copies, and how it's drawn.
92const copyOf = (r) => (r.copy === false ? null : r.copy ?? r.text);
93const shown = (tb, r) => (r.secret && !tb.reveal ? MASK : r.text);
94const tone = (t) => (t === "ok" ? theme.online : t === "bad" ? theme.error : theme.amber);
95
96// ---------------------------------------------------------------- the menu
97
98const groupTools = (g) => TOOL_IDS.filter((id) => TOOLS[id].group === g);
99const LABEL_W = 9;
100
101// How many rows a group's buttons take at `w`: a button is its label and a
102// space each side, a cell apart.
103function chipRows(ids, w, desk) {
104 const room = Math.max(10, w - 4 - LABEL_W);
105 let rows = 1, used = 0;
106 for (const id of ids) {
107 const need = cells(TOOLS[id].label) + (desk ? 4 : 4) + 1;
108 if (used && used + need > room) { rows++; used = 0; }
109 used += need;
110 }
111 return rows;
112}
113
114function menuCard(els, tb, w, handlers) {
115 const { Box, Text, Button } = els;
116 const desk = !!els.Svg;
117 let height = 3;
118 const rows = GROUPS.map((g) => {
119 const ids = groupTools(g);
120 height += chipRows(ids, w, desk);
121 return Box({ key: `g-${g}`, flexDirection: "row", children: [
122 Box({ key: "l", width: LABEL_W, flexShrink: 0, children: [Text({ key: "t", color: theme.muted, children: g.toUpperCase() })] }),
123 Box({ key: "chips", flexDirection: "row", flexWrap: "wrap", columnGap: 1, flexGrow: 1, flexShrink: 1, minWidth: 0, children: ids.map((id) => Button({
124 key: `tool-${id}`,
125 label: TOOLS[id].label,
126 ...(id === tb.tool ? { variant: "primary" } : { plain: true, dimColor: false }),
127 onPress: () => handlers.onToolPick?.(id),
128 })) }),
129 ] });
130 });
131 return { name: "Tools", node: card(els, { key: "tb-menu", title: "TOOLS", color: SAND, meta: String(TOOL_IDS.length), rows }), height };
132}
133
134// ---------------------------------------------------------------- the tool
135
136function resultRow(els, tb, r, i, w, handlers, labelW) {
137 const { Box, Text, Button } = els;
138 const copy = copyOf(r);
139 const btn = copy != null ? Button({ key: `tool-copy-${i}`, plain: true, label: "⧉", onPress: (press) => handlers.onToolCopy?.(copy, press?.surface) }) : null;
140 const lab = labelW ? { text: r.label, width: labelW, color: theme.muted } : null;
141 if (r.block) {
142 const lines = shown(tb, r).split("\n");
143 const keep = lines.slice(0, BLOCK_LINES);
144 const more = lines.length - keep.length;
145 const body = [...keep.map((t, k) => Text({ key: `l${k}`, wrap: "wrap", color: r.dim ? theme.muted : undefined, children: t || " " })),
146 more > 0 ? Text({ key: "more", color: theme.muted, children: `+ ${more} more line${more === 1 ? "" : "s"}` }) : null].filter(Boolean);
147 const rowsUsed = keep.reduce((n, t) => n + Math.max(1, Math.ceil(cells(t) / Math.max(10, w - 6 - labelW))), 0) + (more > 0 ? 1 : 0);
148 return { rows: rowsUsed, node: Box({ key: `r${i}`, flexDirection: "row", columnGap: 1, children: [
149 lab ? line(els, "lab", [lab]) : null,
150 Box({ key: "body", flexDirection: "column", flexGrow: 1, flexShrink: 1, minWidth: 0, children: body }),
151 btn,
152 ].filter(Boolean) }) };
153 }
154 return { rows: 1, node: line(els, `r${i}`, [
155 lab,
156 { text: shown(tb, r), grow: true, color: r.secret && !tb.reveal ? theme.amber : r.dim ? theme.muted : undefined },
157 btn ? { node: btn } : null,
158 ], { gap: 1 }) };
159}
160
161function toolCard(els, tb, w, handlers) {
162 const { Box, Text, Button } = els;
163 const tool = TOOLS[tb.tool];
164 const out = tb.out ?? { rows: [], note: tool.hint };
165 const rows = [];
166 let height = 3;
167 // What it ran on, for a tool that reads text: its start, as much as a line holds.
168 if (!tool.generates && tb.input) {
169 rows.push(line(els, "in", [{ text: "in", width: 3, color: theme.muted }, { text: tb.input.slice(0, Math.max(40, w * 2)).replace(/\s+/g, " "), grow: true, color: theme.muted }], { gap: 1 }));
170 height++;
171 }
172 if (out.error) { rows.push(Text({ key: "err", color: theme.warn, wrap: "wrap", children: out.error })); height += Math.ceil(cells(out.error) / Math.max(10, w - 4)); }
173 const labelW = Math.min(10, Math.max(0, ...out.rows.map((r) => cells(r.label))));
174 out.rows.forEach((r, i) => {
175 const got = resultRow(els, tb, r, i, w, handlers, labelW);
176 rows.push(got.node);
177 height += got.rows;
178 });
179 if (out.status) { rows.push(Text({ key: "status", color: tone(out.status.tone), children: `● ${out.status.text}` })); height++; }
180 // A note under the results ("of 5 bytes"); with none yet, what to type.
181 const foot = out.note ?? (!out.rows.length && !out.error ? tool.hint : null);
182 if (foot && !out.rows.length) {
183 rows.push(Text({ key: "hint", color: theme.muted, wrap: "wrap", children: foot }));
184 height += Math.ceil(cells(foot) / Math.max(10, w - 4));
185 } else if (foot || out.copyAll) {
186 rows.push(line(els, "foot", [
187 { text: foot ?? "", grow: true, color: theme.muted },
188 out.copyAll ? { node: Button({ key: "tool-copy-all", plain: true, label: "⧉ all", onPress: (press) => handlers.onToolCopy?.(out.copyAll, press?.surface) }) } : null,
189 ], { gap: 1 }));
190 height++;
191 }
192 const secret = out.rows.some((r) => r.secret);
193 const metaNode = Box({ key: "meta", flexDirection: "row", alignItems: "center", columnGap: 1, flexShrink: 0, children: [
194 out.mode ? Text({ key: "mode", color: theme.muted, children: out.mode }) : null,
195 secret ? Button({ key: "tool-reveal", plain: true, dimColor: true, label: tb.reveal ? "hide" : "show", onPress: () => handlers.onToolReveal?.() }) : null,
196 tool.generates
197 ? Button({ key: "tool-again", plain: true, label: tb.out ? "↻ again" : "↻ make", onPress: () => handlers.onToolAgain?.() })
198 : Button({ key: "tool-paste", plain: true, label: "⧉ paste", onPress: () => handlers.onToolPaste?.() }),
199 ].filter(Boolean) });
200 return { name: tool.label, node: card(els, { key: "tb-tool", title: tool.label.toUpperCase(), color: SAND, metaNode, rows }), height };
201}
202
203export function toolboxDock(els, w, capacity, handlers) {
204 const tb = state.toolbox;
205 return stackCards(els, [menuCard(els, tb, w, handlers), toolCard(els, tb, w, handlers)], capacity, handlers.scroll);
206}
207
208// The inline pane: the tool on show and its first results. Where the pane
209// draws pictures (VS Code) the tool is picked from a menu in the head, and
210// a button beside it makes another batch or pastes what's copied, so
211// nothing has to be typed but the tool's own text.
212export function toolboxInline(els, w, handlers) {
213 const { Select, Button } = els;
214 const tb = state.toolbox;
215 const tool = TOOLS[tb.tool];
216 const out = tb.out;
217 const pick = els.Svg && Select;
218 const head = line(els, "head", [
219 { text: `${TOOLBOX_META.icon} ${TOOLBOX_META.label}`, bold: true, color: SAND },
220 pick ? { text: " " } : null,
221 pick ? { node: Select({ key: "tool-pick", value: tb.tool, options: TOOL_IDS.map((id) => ({ value: id, label: TOOLS[id].label })), onSelect: (id) => handlers.onToolPick?.(id) }) } : null,
222 { text: pick ? (out?.mode ? ` ${out.mode}` : "") : ` ${tool.label}${out?.mode ? ` ${out.mode}` : ""}`, color: theme.muted, grow: true },
223 pick ? { node: tool.generates
224 ? Button({ key: "tool-again", plain: true, label: out ? "↻ again" : "↻ make", onPress: () => handlers.onToolAgain?.() })
225 : Button({ key: "tool-paste", plain: true, label: "⧉ paste", onPress: () => handlers.onToolPaste?.() }) } : null,
226 ]);
227 // Nothing run yet, or a tool waiting for text: what to type.
228 if (!out || !out.rows.length) {
229 const why = out?.error ? { text: out.error, color: theme.warn } : { text: out?.note ?? tool.hint, color: theme.muted };
230 return [head, els.Text({ key: "hint", color: why.color, wrap: "wrap", children: why.text })];
231 }
232 const labelW = Math.min(10, Math.max(0, ...out.rows.map((r) => cells(r.label))));
233 const { shown, node } = inlineCut(els, "tool-more", out.rows, 3, { open: state.moreOpen.has("toolbox:in"), onToggle: () => handlers.onToggleMore?.("toolbox:in") });
234 return [head, ...shown.map((r, i) => resultRow(els, tb, { ...r, block: false, text: r.text.split("\n")[0] }, i, w, handlers, labelW).node), node].filter(Boolean);
235}
236
237// ---------------------------------------------------------------- the band
238
239// What the band is about: the last tool run, or what's on the clipboard
240// (read by the Clipboard room, when it has a tab), whichever is newer.
241function subject(now) {
242 const tb = state.toolbox;
243 const latest = state.sysRooms?.includes("clipboard") ? state.clipboard?.items?.[0] : null;
244 const seen = latest ? detectClip(latest.text, now) : null;
245 if (seen && (!tb.used || latest.id !== tb.clipSeen)) return { clip: seen };
246 if (tb.used && tb.out && !tb.out.error && tb.out.band) return { tool: TOOLS[tb.tool], out: tb.out };
247 return null;
248}
249
250const bandText = (b) => (b.secret ? MASK : String(b.text).replace(/\s+/g, " "));
251const copied = (now) => now - state.toolbox.copiedAt < COPIED_MS;
252
253// The terminal's band, after the room's name.
254export function toolboxBandPieces(width = 0, now = Date.now()) {
255 const s = subject(now);
256 const sep = { text: " · ", color: theme.muted };
257 if (!s) return [{ text: `${TOOL_IDS.length} tools`, color: SAND, bold: true }, sep, { text: "try UUID · Hash · Time · JWT", color: theme.muted }];
258 if (s.clip) {
259 const c = s.clip;
260 if (c.kind === "JWT") return [{ text: "clipboard: JWT", color: SAND, bold: true }, sep,
261 { text: c.state.tone === "bad" ? `✕ ${c.state.text}` : `● ${c.state.text}`, color: tone(c.state.tone) }, sep,
262 { text: [c.alg, c.role ? `role ${c.role}` : null].filter(Boolean).join(" · "), color: theme.muted }];
263 return [{ text: "clipboard: ts", color: SAND, bold: true }, sep, { text: `${c.raw} → ${localOf(c.ms)}`, color: undefined }, sep, { text: c.ago, color: theme.muted }];
264 }
265 const b = s.out.band;
266 const head = `${s.tool.label} ${b.meta}`;
267 const tail = copied(now) ? "✓ copied" : "";
268 const room = width ? Math.max(8, width - cells(head) - 3 - (tail ? cells(tail) + 3 : 0)) : 60;
269 return [{ text: head, color: SAND, bold: true }, sep, { text: clip(bandText(b), room), color: b.secret ? theme.amber : undefined },
270 tail ? sep : null, tail ? { text: tail, color: theme.online } : null].filter(Boolean);
271}
272
273function localOf(ms) {
274 const d = new Date(ms);
275 const p = (n) => String(n).padStart(2, "0");
276 return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
277}
278
279// A hammer and a wrench: the room's mark on the desktop band.
280const MARK = { source: K.svg(16, 16, `<path d="M3 13.5 9.2 7.3" stroke="${SAND}" stroke-width="2.2" stroke-linecap="round"/><path d="M8 3.2a3.2 3.2 0 0 0 4.6 4.3l.9.9-1.5 1.5-.9-.9A3.2 3.2 0 0 1 7 4.3l1.6 1.6 1.3-1.3z" fill="${SAND}"/><path d="M12.5 13.5 9.5 10.5" stroke="${SAND}" stroke-width="2" stroke-linecap="round" stroke-opacity="0.6"/>`), width: 16, height: 16 };
281// A short line, a dot where `pct` of the way is: how much of a JWT's life is gone.
282const lifeBar = (pct, color) => K.progress(pct, color, { w: 34 });
283
284// The desktop's band, as sections for the capsule. Kept short, so the
285// capsule ends well before ‹ › and Open: three sections at most, and the
286// result itself cut to a few dozen characters.
287export function toolboxBandDesk(now = Date.now()) {
288 const s = subject(now);
289 if (!s) return { color: SAND, sections: [
290 { key: "tools", color: SAND, parts: [draw(MARK, "Toolbox"), value(String(TOOL_IDS.length)), sub("tools")], tip: GROUPS.map((g) => `${g}: ${groupTools(g).map((id) => TOOLS[id].label).join(", ")}`) },
291 { key: "try", color: SAND, parts: [sub("try UUID · Hash · Time · JWT")] },
292 ] };
293 if (s.clip) {
294 const c = s.clip;
295 if (c.kind === "JWT") {
296 const color = tone(c.state.tone);
297 const life = c.state.left == null ? null : c.state.left <= 0 ? 100 : 100 - Math.min(100, (c.state.left / (60 * 60_000)) * 100);
298 return { color: SAND, sections: [
299 { key: "kind", color: SAND, parts: [draw(MARK, "Toolbox"), label("clipboard"), chip("JWT", SAND, theme.onAccent)] },
300 { key: "exp", color, parts: [life == null ? null : draw(lifeBar(life, color), "time left"), value(c.state.text.replace(/^valid for /, ""), color), c.state.tone === "ok" ? sub("left") : null],
301 tip: [`JWT · ${c.alg}`, typeof c.exp === "number" ? `exp ${localOf(c.exp * 1000)}` : "no exp", "Open the room to read the claims"] },
302 { key: "alg", color: SAND, parts: [label(c.alg), c.role ? sub(`role ${c.role}`) : null] },
303 ] };
304 }
305 return { color: SAND, sections: [
306 { key: "kind", color: SAND, parts: [draw(MARK, "Toolbox"), label("clipboard"), chip("ts", SAND, theme.onAccent)] },
307 { key: "when", color: theme.usage, parts: [draw(K.icon("clock", theme.usage), "time"), value(localOf(c.ms))], tip: [c.raw, c.ago] },
308 ] };
309 }
310 const b = s.out.band;
311 const sections = [
312 { key: "tool", color: SAND, parts: [draw(MARK, "Toolbox"), value(s.tool.label), sub(b.meta)] },
313 { key: "out", color: b.secret ? theme.amber : SAND, grow: true, parts: [b.secret ? value(MASK, theme.amber) : msg(clip(bandText(b), 40))],
314 tip: b.secret ? null : [s.tool.label, ...s.out.rows.slice(0, 5).map((r) => clip(`${r.label ? `${r.label} ` : ""}${r.text.split("\n")[0]}`, 48))] },
315 ];
316 if (copied(now)) sections.push({ key: "copied", color: theme.online, parts: [value("✓ copied", theme.online)] });
317 else if (s.out.strength) sections.push({ key: "strength", color: tone(s.out.status?.tone), parts: [value(s.out.strength, tone(s.out.status?.tone))] });
318 return { color: SAND, sections };
319}
320
321// The tab's mark from another room: a JWT on the clipboard about to expire.
322export function toolboxBadge(now = Date.now()) {
323 const s = subject(now);
324 const left = s?.clip?.kind === "JWT" ? s.clip.state.left : null;
325 return left != null && left > 0 && left < SOON_MS ? { text: "!", color: theme.amber } : null;
326}
327hooks/clipboard.mjs 154 lines1// The Clipboard room: what was copied lately, newest first, to copy again.
2// The mod reads the clipboard every couple of seconds while the room has a
3// tab (pbpaste on a Mac, wl-paste or xclip on Linux). The history lives in
4// this session's memory only and is gone when the session ends. Anything
5// that looks like a secret is drawn masked, though ⧉ still copies it, and a
6// room's history is never shared to a chat.
7//
8// Plain logic and drawing: the mod runs the reader.
9
10import { state } from "./state.mjs";
11import { theme } from "./theme.mjs";
12import { line, card, stackCards, clip, age, cells, inlineCut } from "./widgets.mjs";
13import { findSecret } from "./share.mjs";
14import { value, sub, msg } from "./bands.mjs";
15
16export const CLIP_META = { icon: "⧉", label: "Clipboard", color: "#6FC2B5" };
17export const MAX_CLIPS = 30;
18export const MAX_CLIP_CHARS = 20_000; // past this an item is kept cut, and says so
19
20// The readers to try, in order; the first that works is kept.
21export const CLIP_READERS = [
22 ["pbpaste"],
23 ["wl-paste", "--no-newline"],
24 ["xclip", "-selection", "clipboard", "-o"],
25];
26
27export function createClipboard() {
28 return {
29 items: [], // [{ id, text, at, secret, cut }], newest first
30 reader: null, // the argv that worked
31 seen: null, // what the clipboard held at the last read
32 error: "", // no reader works here
33 seq: 0,
34 };
35}
36
37// What the reader just read. Only a change counts: the clipboard holds an
38// item you dropped until something else is copied, and it mustn't come
39// back. A new text goes on top; one already in the list moves to the top
40// (copying an item again from the room does that). Whitespace alone is left
41// out. True when the list changed.
42export function addClip(c, raw, now) {
43 const text = String(raw ?? "");
44 if (text === c.seen) return false;
45 c.seen = text;
46 if (!text.trim()) return false;
47 const cut = text.length > MAX_CLIP_CHARS;
48 const kept = cut ? text.slice(0, MAX_CLIP_CHARS) : text;
49 if (c.items[0]?.text === kept) return false;
50 const was = c.items.findIndex((x) => x.text === kept);
51 if (was >= 0) {
52 const [item] = c.items.splice(was, 1);
53 c.items.unshift({ ...item, at: now });
54 return true;
55 }
56 c.items.unshift({ id: `c${++c.seq}`, text: kept, at: now, secret: findSecret(kept), cut });
57 if (c.items.length > MAX_CLIPS) c.items.length = MAX_CLIPS;
58 return true;
59}
60
61export function removeClip(c, id) {
62 c.items = c.items.filter((x) => x.id !== id);
63}
64
65// One line of an item: its first line that has something on it, or masked.
66export function clipPreview(item, width) {
67 if (item.secret) return `•••••••• ${item.secret}`;
68 const first = item.text.split("\n").find((l) => l.trim()) ?? "";
69 return clip(first.replace(/\s+/g, " ").trim(), width);
70}
71
72function clipMeta(item, now) {
73 const lines = item.text.split("\n").length;
74 return [age(item.at, now), lines > 1 ? `${lines} lines` : `${item.text.length} chars`, item.cut ? "cut" : null].filter(Boolean).join(" · ");
75}
76
77// An item: its first line over how old and long it is, its ⧉ ✕ at the
78// right. `one` puts it all on one line, as the inline pane does. The row
79// never wraps: VS Code wrapped a long one's buttons under it.
80function itemRow(els, item, w, handlers, now, { one = false } = {}) {
81 const { Box, Text, Button } = els;
82 const meta = clipMeta(item, now);
83 const text = Text({ key: "t", wrap: "truncate-end", color: item.secret ? theme.amber : undefined, italic: !!item.secret, children: clipPreview(item, els.Svg ? 200 : Math.max(10, w - 8 - (one ? cells(meta) + 1 : 0))) }); // VS Code: the row cuts it
84 return Box({ key: item.id, flexDirection: "row", flexWrap: "nowrap", alignItems: "center", columnGap: 1, children: [
85 Box({ key: "text", flexDirection: one ? "row" : "column", flexWrap: "nowrap", columnGap: 1, flexGrow: 1, flexShrink: 1, minWidth: 0, children: one ? [
86 Box({ key: "tb", flexGrow: 1, flexShrink: 1, minWidth: 0, children: [text] }),
87 Box({ key: "mb", flexShrink: 0, children: [Text({ key: "m", color: theme.muted, children: meta })] }),
88 ] : [
89 text,
90 Text({ key: "m", color: theme.muted, wrap: "truncate-end", children: meta }),
91 ] }),
92 Box({ key: "acts", flexDirection: "row", flexWrap: "nowrap", flexShrink: 0, columnGap: 1, children: [
93 Button({ key: `copy-${item.id}`, plain: true, label: "⧉", onPress: (press) => handlers.onClipCopy?.(item.id, press?.surface) }),
94 Button({ key: `drop-${item.id}`, plain: true, dimColor: true, label: "✕", onPress: () => handlers.onClipRemove?.(item.id) }),
95 ] }),
96 ] });
97}
98
99export function clipboardDock(els, w, capacity, handlers, now) {
100 const c = state.clipboard;
101 const { Text, Button, Box } = els;
102 let rows;
103 if (c.error) rows = [Text({ key: "err", color: theme.warn, wrap: "wrap", children: c.error })];
104 else if (!c.items.length) rows = [Text({ key: "empty", color: theme.muted, wrap: "wrap", children: "Copy something anywhere and it shows up here." })];
105 else {
106 // Two rows an item on the terminal: keep to what fits.
107 const room = els.Svg ? c.items.length : Math.max(1, Math.floor((capacity - 3) / 2));
108 rows = c.items.slice(0, room).map((item) => itemRow(els, item, w, handlers, now));
109 if (c.items.length > room) rows.push(Text({ key: "more", color: theme.muted, children: `+ ${c.items.length - room} more` }));
110 }
111 const metaNode = c.items.length ? Box({ key: "meta", flexDirection: "row", columnGap: 1, flexShrink: 0, children: [
112 Text({ key: "n", color: theme.muted, children: `${c.items.length} item${c.items.length === 1 ? "" : "s"}` }),
113 Button({ key: "clip-clear", plain: true, dimColor: true, label: "Clear", onPress: () => handlers.onClipClear?.() }),
114 ] }) : null;
115 const height = 3 + (c.items.length ? rows.length * 2 : 1);
116 return stackCards(els, [{ name: "Clipboard", node: card(els, { key: "clips", title: "COPIED LATELY", color: CLIP_META.color, metaNode, rows }), height }], capacity, handlers.scroll);
117}
118
119export function clipboardInline(els, w, handlers, now) {
120 const c = state.clipboard;
121 const head = line(els, "head", [
122 { text: `${CLIP_META.icon} ${CLIP_META.label}`, bold: true, color: CLIP_META.color },
123 { text: ` ${c.items.length} item${c.items.length === 1 ? "" : "s"}`, color: theme.muted, grow: true },
124 ]);
125 if (c.error) return [head, els.Text({ key: "err", color: theme.warn, wrap: "wrap", children: c.error })];
126 const { shown, node } = inlineCut(els, "clip-more", c.items, 3, { open: state.moreOpen.has("clipboard:in"), onToggle: () => handlers.onToggleMore?.("clipboard:in") });
127 return [head, ...shown.map((item) => itemRow(els, item, w, handlers, now, { one: true })), node].filter(Boolean);
128}
129
130export function clipboardBandPieces() {
131 const c = state.clipboard;
132 if (c.error) return [{ text: "can't read the clipboard here", color: theme.warn }];
133 if (!c.items.length) return [{ text: "nothing copied yet", color: theme.muted }];
134 return [
135 { text: `${c.items.length} copied`, color: CLIP_META.color, bold: true },
136 { text: " · latest ", color: theme.muted },
137 { text: clipPreview(c.items[0], 40), color: c.items[0].secret ? theme.amber : undefined },
138 ];
139}
140
141// The desktop's band: how many are kept, then the newest one's first line,
142// cut to the room left (masked when it looks secret). Hover lists the three newest.
143export function clipboardBandDesk() {
144 const c = state.clipboard;
145 const color = CLIP_META.color;
146 if (c.error) return { color, sections: [{ key: "err", color: theme.warn, parts: [sub("can't read the clipboard here")], tip: [c.error] }] };
147 if (!c.items.length) return { color, sections: [{ key: "none", color, parts: [sub("nothing copied yet")] }] };
148 return { color, sections: [
149 { key: "count", color, parts: [value(String(c.items.length), color), sub("copied")] },
150 { key: "latest", color, grow: true, parts: [sub("latest"), msg(clipPreview(c.items[0], 80))],
151 tip: ["Copied lately", ...c.items.slice(0, 3).map((x) => clipPreview(x, 48))] },
152 ] };
153}
154hooks/pet.mjs 385 lines1// The Pet room: Clawd's corner. On the desktop Clawd is a vector drawing
2// (clawdsvg.mjs) that moves by CSS, standing in a little corner with what
3// it shared with you today, a bond that grows as you work, and a short log
4// of what it noticed. A small Clawd also walks by the pane's input box in
5// every room. The terminal draws the pixel stickers in half blocks, a frame
6// per redraw.
7//
8// Left on "auto", Clawd follows what goes on: typing while Claude works,
9// cheering when a focus round ends, vibing through a break, waving at a new
10// message, puzzled by failing checks, asleep after a quiet while.
11//
12// Plain logic and drawing: the mod feeds it (petTick, petNote) and keeps it.
13
14import { state } from "./state.mjs";
15import { theme } from "./theme.mjs";
16import { card, stackCards, stretchBar, clip, xml } from "./widgets.mjs";
17import { dayOf, spent as span } from "./focus.mjs";
18import { PALETTE, STICKERS } from "./petframes.mjs";
19import { clawdSvg, cornerSvg, walkSvg } from "./clawdsvg.mjs";
20import { draw, chip } from "./bands.mjs";
21
22export const PET_META = { icon: "✿", label: "Pet", color: "#D97757" };
23export const MOODS = Object.keys(STICKERS);
24// Where Clawd goes by the input box. Each pace follows the mood: a trot while
25// Claude types, an easy walk otherwise, curled up in the corner when sleepy.
26export const WALKS = [
27 { id: "off", label: "Off" },
28 { id: "sit", label: "Sit" },
29 { id: "stroll", label: "Stroll" },
30 { id: "stopgo", label: "Stop & go" },
31];
32export const MOOD_LABEL = {
33 vibe: "Vibing", typing: "Typing", wave: "Hi!", cheer: "Yay!",
34 confused: "Huh?", wink: "Wink", surprised: "Whoa!", sleepy: "Sleepy",
35};
36// How Clawd feels, for the corner's stats.
37const FEELING = {
38 vibe: "Chill", typing: "Busy", wave: "Happy", cheer: "Excited",
39 confused: "Puzzled", wink: "Cheeky", surprised: "Startled", sleepy: "Sleepy",
40};
41const SLEEP_AFTER_MS = 10 * 60_000;
42const CHEER_MS = 12_000;
43const WAVE_MS = 8_000;
44const LOG_KEEP = 20;
45const XP_PER_LEVEL = 20;
46const XP_ROUND = 3; // a finished focus round
47const XP_TOGETHER_MS = 10 * 60_000; // and every ten minutes Claude works
48const WORKED_NOTE_MS = 5 * 60_000; // a stretch this long gets a line in the log
49
50export function createPet() {
51 return {
52 mode: "auto", // "auto", or a mood kept on
53 walk: "stroll", // Clawd by the input box (desktop): off | sit | stroll | stopgo
54 lastBusyAt: 0, // when this session last worked (Claude, a tool, an agent)
55 busySince: 0, // when the stretch of work going on now began
56 waveAt: 0, // when a message from someone else last came in
57 day: "", // the day `togetherMs` counts
58 togetherMs: 0, // Claude worked that long today, with Clawd watching
59 xp: 0, // the bond: rounds and time together
60 xpMs: 0, // time together not yet turned into xp
61 log: [], // [{ at, icon, text }], newest first
62 lastMood: "",
63 failing: false, // this branch's checks were failing at the last look (kept, so a reload doesn't note it again)
64 };
65}
66
67// ---------------------------------------------------------------- bond and log
68
69export function level(p) {
70 return 1 + Math.floor(p.xp / XP_PER_LEVEL);
71}
72export function bondPct(p) {
73 return ((p.xp % XP_PER_LEVEL) / XP_PER_LEVEL) * 100;
74}
75
76// A line in Clawd's log: "🎉 Finished a focus round".
77export function petNote(p, icon, text, at = Date.now()) {
78 p.log.unshift({ at, icon, text: String(text).slice(0, 80) });
79 if (p.log.length > LOG_KEEP) p.log.length = LOG_KEEP;
80}
81
82export function petRound(p, at = Date.now()) {
83 p.xp += XP_ROUND;
84 petNote(p, "🎉", "Finished a focus round", at);
85}
86
87// Once a second: time together, a stretch of work ending, checks turning
88// red, dozing off. `busy` is whether this session works now; `failing` is
89// null while the checks aren't known yet (before the Git room's first
90// fetch), which leaves what was last seen. True when something worth
91// keeping changed.
92export function petTick(p, { busy, failing, now = Date.now(), step = 1000 }) {
93 let changed = false;
94 const day = dayOf(now);
95 if (p.day !== day) { p.day = day; p.togetherMs = 0; changed = true; }
96 if (busy) {
97 p.lastBusyAt = now;
98 if (!p.busySince) p.busySince = now;
99 p.togetherMs += step;
100 p.xpMs += step;
101 if (p.xpMs >= XP_TOGETHER_MS) { p.xpMs -= XP_TOGETHER_MS; p.xp += 1; changed = true; }
102 } else if (p.busySince) {
103 const worked = now - p.busySince;
104 if (worked >= WORKED_NOTE_MS) { petNote(p, "⌨️", `Worked with Claude for ${span(worked)}`, now); changed = true; }
105 p.busySince = 0;
106 }
107 if (failing != null) {
108 if (failing && !p.failing) { petNote(p, "😵", "Checks failed on this branch", now); changed = true; }
109 if (p.failing !== !!failing) { p.failing = !!failing; changed = true; }
110 }
111 const mood = petMood(now);
112 if (mood !== p.lastMood) {
113 if (mood === "sleepy" && p.mode === "auto" && p.lastMood) { petNote(p, "💤", "Dozed off", now); changed = true; }
114 p.lastMood = mood;
115 }
116 return changed;
117}
118
119// What's kept in $.store: the choices, the bond, today's time and the log.
120export function petSaved(p) {
121 return { mode: p.mode, walk: p.walk, xp: p.xp, xpMs: p.xpMs, day: p.day, togetherMs: p.togetherMs, log: p.log, failing: p.failing };
122}
123export function restorePet(p, saved) {
124 if (!saved || typeof saved !== "object") return;
125 if (saved.mode === "auto" || MOODS.includes(saved.mode)) p.mode = saved.mode;
126 if (WALKS.some((w) => w.id === saved.walk)) p.walk = saved.walk;
127 else if (saved.walk === "edge") p.walk = "stroll"; // the top edge is gone
128 else if (saved.beside === false) p.walk = "off"; // kept before Clawd walked
129 if (typeof saved.failing === "boolean") p.failing = saved.failing;
130 if (Number.isFinite(saved.xp)) p.xp = Math.max(0, saved.xp | 0);
131 if (Number.isFinite(saved.xpMs)) p.xpMs = Math.max(0, saved.xpMs);
132 if (typeof saved.day === "string") { p.day = saved.day; p.togetherMs = Math.max(0, Number(saved.togetherMs) || 0); }
133 if (Array.isArray(saved.log)) {
134 p.log = saved.log.filter((x) => x && Number.isFinite(x.at) && typeof x.text === "string").slice(0, LOG_KEEP)
135 .map((x) => ({ at: x.at, icon: String(x.icon ?? "").slice(0, 4), text: x.text.slice(0, 80) }));
136 }
137}
138
139// ---------------------------------------------------------------- pixel frames (the terminal)
140
141const grids = new Map();
142function frameGrid(mood, i) {
143 const k = `${mood}:${i}`;
144 if (!grids.has(k)) {
145 const rows = STICKERS[mood].frames[i].split("/").map((r) => r.replace(/(\d+)(.)/g, (_, n, ch) => ch.repeat(Number(n))));
146 while (rows.length < 32) rows.push(".".repeat(32));
147 grids.set(k, rows);
148 }
149 return grids.get(k);
150}
151
152const boxes = new Map();
153function stickerBox(mood) {
154 if (!boxes.has(mood)) {
155 let x0 = 32, y0 = 32, x1 = -1, y1 = -1;
156 STICKERS[mood].frames.forEach((_, i) => frameGrid(mood, i).forEach((row, y) => {
157 for (let x = 0; x < row.length; x++) {
158 if (row[x] === ".") continue;
159 x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, y); y1 = Math.max(y1, y);
160 }
161 }));
162 boxes.set(mood, { x0, y0, w: x1 - x0 + 1, h: y1 - y0 + 1 });
163 }
164 return boxes.get(mood);
165}
166
167// Two pixel rows a cell, "▀" in the upper color on the lower. Runs of one
168// look are one Text.
169export function stickerCells(els, mood, now = Date.now()) {
170 const { Box, Text } = els;
171 const s = STICKERS[mood];
172 const grid = frameGrid(mood, Math.floor(now / s.ms) % s.frames.length);
173 const b = stickerBox(mood);
174 const rows = [];
175 for (let y = b.y0 - (b.y0 % 2); y <= b.y0 + b.h - 1; y += 2) {
176 const runs = [];
177 for (let x = b.x0; x < b.x0 + b.w; x++) {
178 const top = grid[y]?.[x] ?? ".", bot = grid[y + 1]?.[x] ?? ".";
179 const look = top === "." && bot === "." ? { ch: " " }
180 : top === "." ? { ch: "▄", color: PALETTE[bot] }
181 : { ch: "▀", color: PALETTE[top], bg: bot === "." ? undefined : PALETTE[bot] };
182 const last = runs.at(-1);
183 if (last && last.color === look.color && last.bg === look.bg && last.ch[0] === look.ch) last.ch += look.ch;
184 else runs.push({ ...look });
185 }
186 rows.push(Box({ key: `r${y}`, flexDirection: "row", children: runs.map((r, i) => Text({ key: `c${i}`, color: r.color, ...(r.bg ? { backgroundColor: r.bg } : {}), children: r.ch })) }));
187 }
188 return rows;
189}
190
191// ---------------------------------------------------------------- mood
192
193// What Clawd does now: the mood kept on, or one that fits the moment.
194export function petMood(now = Date.now()) {
195 const p = state.pet;
196 if (p.mode !== "auto" && STICKERS[p.mode]) return p.mode;
197 const u = state.usage;
198 const f = state.focus;
199 if (f?.cheerAt && now - f.cheerAt < CHEER_MS) return "cheer";
200 if (u.activity?.state && u.activity.state !== "idle") return "typing";
201 if (state.git?.pr?.checks?.fail) return "confused";
202 if (p.waveAt && now - p.waveAt < WAVE_MS) return "wave";
203 if (f?.phase === "break" && !f.paused) return "vibe";
204 if (f?.phase === "focus" && !f.paused) return "typing";
205 if (now - (p.lastBusyAt || now) > SLEEP_AFTER_MS) return "sleepy";
206 return "vibe";
207}
208
209// ---------------------------------------------------------------- drawing
210
211function stat(els, key, label, value) {
212 const { Box, Text } = els;
213 return Box({ key, flexDirection: "column", alignItems: "center", flexGrow: 1, children: [
214 Text({ key: "l", color: theme.muted, children: label }),
215 Text({ key: "v", bold: true, children: value }),
216 ] });
217}
218
219function cornerCard(els, now) {
220 const { Box, Text } = els;
221 const p = state.pet;
222 const mood = petMood(now);
223 const art = els.Svg
224 ? Box({ key: "art", flexDirection: "row", justifyContent: "center", children: [els.Svg({ key: "corner", source: cornerSvg(mood), alt: `Clawd: ${MOOD_LABEL[mood]}`, width: 320, height: 180 })] })
225 : Box({ key: "art", flexDirection: "column", alignItems: "center", children: stickerCells(els, mood, now) });
226 const rounds = state.focus?.done ?? 0;
227 const rows = [
228 art,
229 Box({ key: "stats", flexDirection: "row", marginTop: 1, children: [
230 stat(els, "together", "Together", span(p.togetherMs)),
231 stat(els, "focus", "Focus today", `${rounds} 🍅`),
232 stat(els, "mood", "Mood", FEELING[mood]),
233 ] }),
234 ];
235 if (els.Svg) rows.push(Box({ key: "bond", flexDirection: "row", marginTop: 1, children: [stretchBar(els, "bar", bondPct(p), "#E58FA8", { thick: true })] }));
236 rows.push(Text({ key: "bond-l", color: theme.muted, children: `Bond ${Math.round(bondPct(p))}% to Lv ${level(p) + 1}` }));
237 const artRows = els.Svg ? 9 : Math.ceil((stickerBox(mood).h + 1) / 2);
238 return { name: "Corner", node: card(els, { key: "pet", title: "CLAWD'S CORNER", color: PET_META.color, meta: `Lv ${level(p)}`, rows }), height: 3 + artRows + 2 + 2 + (els.Svg ? 2 : 0) };
239}
240
241// When, as "10:42", or a weekday for an older line.
242function when(at, now) {
243 const d = new Date(at);
244 if (now - at > 20 * 3_600_000) return d.toLocaleDateString("en-US", { weekday: "short" });
245 return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
246}
247
248// What Clawd noticed lately: small and dim, so the corner stays the point.
249function logCard(els, w, now, max) {
250 const { Text } = els;
251 const p = state.pet;
252 const items = p.log.slice(0, max);
253 let rows;
254 if (!items.length) rows = [Text({ key: "empty", color: theme.muted, children: "Nothing yet. Clawd notes what happens while you work." })];
255 else if (els.Svg) {
256 // Drawn, so the lines can be set smaller than the pane's text.
257 const lh = 17, H = items.length * lh;
258 const lines = items.map((x, i) => `<text x="0" y="${i * lh + 12}" font-size="11.5" fill="#9A968F">${when(x.at, now)}</text>`
259 + `<text x="40" y="${i * lh + 12}" font-size="11.5" fill="#BDB8B0">${xml(`${x.icon} ${clip(x.text, 56)}`)}</text>`).join("");
260 rows = [els.Svg({ key: "log", source: `<svg xmlns="http://www.w3.org/2000/svg" width="420" height="${H}" viewBox="0 0 420 ${H}" font-family="-apple-system, system-ui, sans-serif">${lines}</svg>`, alt: items.map((x) => x.text).join(" · "), width: 420, height: H })];
261 } else {
262 rows = items.map((x, i) => Text({ key: `l${i}`, color: theme.muted, wrap: "truncate-end", children: `${when(x.at, now)} ${x.icon} ${x.text}` }));
263 }
264 return { name: "Lately", node: card(els, { key: "log", title: "LATELY", color: theme.muted, rows }), height: 3 + rows.length };
265}
266
267function moodCard(els, handlers) {
268 const { Box, Button, Text } = els;
269 const p = state.pet;
270 const choice = (key, label, on, press) => Button({ key, plain: true, dimColor: !on, label: on ? `● ${label}` : `○ ${label}`, onPress: press });
271 const rows = [
272 Box({ key: "moods", flexDirection: "row", flexWrap: "wrap", columnGap: 2, children: [
273 choice("pet-auto", "Auto", p.mode === "auto", () => handlers.onPetMode?.("auto")),
274 ...MOODS.map((m) => choice(`pet-${m}`, MOOD_LABEL[m], p.mode === m, () => handlers.onPetMode?.(m))),
275 ] }),
276 ];
277 if (els.Svg) {
278 rows.push(Box({ key: "walk", flexDirection: "row", flexWrap: "wrap", columnGap: 2, children: [
279 Text({ key: "l", color: theme.muted, children: "By the input box" }),
280 ...WALKS.map((w) => choice(`walk-${w.id}`, w.label, p.walk === w.id, () => handlers.onPetWalk?.(w.id))),
281 ] }));
282 }
283 return { name: "Mood", node: card(els, { key: "moods", title: "MOOD", color: PET_META.color, meta: p.mode === "auto" ? "follows along" : "kept on", rows }), height: 3 + 3 + rows.length };
284}
285
286export function petDock(els, w, capacity, handlers, now) {
287 return stackCards(els, [cornerCard(els, now), logCard(els, w, now, 4), moodCard(els, handlers)], capacity, handlers.scroll);
288}
289
290// The inline pane. Where it draws pictures (VS Code) Clawd sits at the left
291// and beside it its mood is picked from a menu (Auto, or one kept on), over
292// the last thing it noticed. The terminal keeps its sticker, and its box.
293export function petInline(els, w, handlers, now) {
294 const mood = petMood(now);
295 const { Box, Text, Select } = els;
296 const p = state.pet;
297 if (els.Svg && Select) {
298 const last = p.log[0];
299 return [Box({ key: "pet-row", flexDirection: "row", flexWrap: "nowrap", alignItems: "center", columnGap: 2, children: [
300 els.Svg({ key: "pet", source: clawdSvg(mood, 72), alt: `Clawd: ${MOOD_LABEL[mood]}`, width: 72, height: 72 }),
301 Box({ key: "side", flexDirection: "column", flexGrow: 1, flexShrink: 1, minWidth: 0, children: [
302 Box({ key: "head", flexDirection: "row", flexWrap: "nowrap", columnGap: 1, children: [
303 Text({ key: "n", bold: true, color: PET_META.color, children: `${PET_META.icon} Clawd` }),
304 Text({ key: "m", children: MOOD_LABEL[mood] }),
305 Text({ key: "lv", color: theme.muted, children: `Lv ${level(p)}` }),
306 ] }),
307 Box({ key: "mood", flexDirection: "row", flexWrap: "nowrap", alignItems: "center", columnGap: 1, children: [
308 Select({ key: "pet-mode", label: "Mood", value: p.mode, options: [{ value: "auto", label: "Auto" }, ...MOODS.map((m) => ({ value: m, label: MOOD_LABEL[m] }))], onSelect: (m) => handlers.onPetMode?.(m) }),
309 Text({ key: "how", color: theme.muted, wrap: "truncate-end", children: p.mode === "auto" ? "follows along" : "kept on" }),
310 ] }),
311 last ? Text({ key: "last", color: theme.muted, wrap: "truncate-end", children: `${when(last.at, now)} ${last.icon} ${last.text}` }) : null,
312 ].filter(Boolean) }),
313 ] })];
314 }
315 return [
316 Box({ key: "head", flexDirection: "row", columnGap: 1, children: [
317 Text({ key: "n", bold: true, color: PET_META.color, children: `${PET_META.icon} Clawd` }),
318 Text({ key: "m", children: MOOD_LABEL[mood] }),
319 Text({ key: "lv", color: theme.muted, children: `Lv ${level(state.pet)}` }),
320 ] }),
321 ...(els.Svg ? [els.Svg({ key: "pet", source: clawdSvg(mood, 72), alt: `Clawd: ${MOOD_LABEL[mood]}`, width: 72, height: 72 })] : stickerCells(els, mood, now)),
322 ];
323}
324
325export function petBandPieces() {
326 const mood = petMood();
327 const last = state.pet.log[0];
328 return [
329 { text: "Clawd ", color: PET_META.color, bold: true },
330 { text: MOOD_LABEL[mood] },
331 { text: ` · Lv ${level(state.pet)}`, color: theme.muted },
332 last ? { text: ` · ${last.icon} ${last.text}`, color: theme.muted } : null,
333 ].filter(Boolean);
334}
335
336// Clawd by the input box, as the walk asks (desktop only, with a Pet tab):
337// `row` takes the room after the field's buttons (sitting at its end, or a
338// track it walks along), null when not in use. A track is one drawing as wide as its slot, Clawd
339// moved inside it by SVG animation, so nothing redraws while it walks.
340// The desktop sets a fixed-size drawing at the width it's given, held to its
341// slot. A track has no width of its own, so it's given more than the pane
342// could have (from its columns) and the slot holds it to the room there is.
343const PX_PER_COLUMN = 10;
344export function petBeside(els, { columns = 0, now = Date.now() } = {}) {
345 const p = state.pet;
346 const wide = Math.max(600, Math.round((columns || 80) * PX_PER_COLUMN));
347 const none = { row: null, fills: false }; // fills: the row takes the room itself
348 if (!els.Svg || p.walk === "off" || !state.sysRooms.includes("pet")) return none;
349 const mood = petMood(now);
350 const alt = `Clawd: ${MOOD_LABEL[mood]}`;
351 if (p.walk === "sit") return { ...none, row: els.Svg({ key: `beside-${mood}`, source: clawdSvg(mood, 40, { crop: true }), alt, width: 40, height: 40 }) };
352 // From nothing (width 0), growing into the room left: the drawing inside is
353 // wider than any pane, and must not push the field narrower.
354 return { ...none, fills: true, row: els.Box({ key: "clawd-walk", flexGrow: 1, width: 0, minWidth: 1, overflow: "hidden", children: [
355 els.Svg({ key: "track", source: walkSvg(mood, p.walk, 40), alt, width: wide, height: 40 }),
356 ] }) };
357}
358
359// While the terminal shows the room, it redraws as fast as the frames go.
360export function petFrameMs(now = Date.now()) {
361 return STICKERS[petMood(now)].ms;
362}
363
364// What Clawd says when nothing new happened: its mood, in words.
365const SAYS = {
366 vibe: "Just vibing", typing: "Working with Claude", wave: "Hi there!", cheer: "We did it!",
367 confused: "Huh, the checks?", wink: "Looking good", surprised: "Whoa!", sleepy: "Zzz…",
368};
369const NEWS_MS = 15 * 60_000;
370
371// The desktop's band: Clawd, small and moving, saying the latest thing it
372// noticed (in the last quarter hour), or else how it feels.
373export function petBandDesk(now = Date.now()) {
374 const p = state.pet;
375 const mood = petMood(now);
376 const news = p.log[0] && now - p.log[0].at < NEWS_MS ? p.log[0] : null;
377 const says = news ? `${news.icon} ${news.text}` : SAYS[mood];
378 return { color: PET_META.color, sections: [
379 { key: "clawd", color: PET_META.color, parts: [
380 draw({ source: clawdSvg(mood, 24, { crop: true }), width: 24, height: 24 }, `Clawd: ${MOOD_LABEL[mood]}`),
381 chip(clip(says, 48), "#3A3836", "#ECE7E1"),
382 ], tip: [`Clawd · ${MOOD_LABEL[mood]} · Lv ${level(p)}`, ...p.log.slice(news ? 1 : 0, 3).map((x) => `${x.icon} ${x.text}`)] },
383 ] };
384}
385