@mrciphersmith/roomyx 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,21 @@
1
1
  #!/usr/bin/env bun
2
+ import { existsSync, writeFileSync } from "node:fs";
2
3
  import { join } from "node:path";
3
4
  import { createCliRenderer } from "@opentui/core";
4
5
  import { RoomClient } from "./mcp-client";
5
6
  import { ChatView } from "./screens/chat-view";
6
- import { AgentModal } from "./screens/agent-modal";
7
7
  import type { RosterEntry } from "../log/types";
8
8
  import { resolveConnectionUrl } from "../installer/resolve-connection";
9
- import { IDLE, ownerPromptLine, stepOwnerPrompt } from "./owner-prompt";
9
+ import { IDLE, OPENED, ownerPromptLine, stepOwnerPrompt } from "./owner-prompt";
10
10
  import type { OwnerPromptState } from "./owner-prompt";
11
+ import { resolveAction } from "./keymap";
12
+ import type { Action } from "./keymap";
13
+ import { livenessLine } from "./liveness";
14
+ import { exportBaseName, nextFreeExportPath } from "./export-name";
15
+ import { createShutdown } from "./shutdown";
16
+ import { CLOSED, opened, searchPromptLine, stepSearchPrompt } from "./search-prompt";
17
+ import type { SearchPromptState } from "./search-prompt";
18
+ import type { ConnectionStatus } from "./mcp-client";
11
19
  import { ArgError, parseArgs, renderFlags } from "../cli/args";
12
20
  import type { FlagValues } from "../cli/args";
13
21
  import { CLIENT_FLAGS } from "../cli/specs";
@@ -44,50 +52,225 @@ export async function runClient(flags: FlagValues): Promise<void> {
44
52
 
45
53
  const renderer = await createCliRenderer({ targetFps: 30 });
46
54
 
47
- const modal = new AgentModal(renderer, {
48
- width: Math.floor(renderer.terminalWidth * 0.7),
49
- height: Math.floor(renderer.terminalHeight * 0.7),
50
- });
51
-
55
+ // Selecting a participant filters the stream in place instead of opening a
56
+ // window over it. The modal this replaces could not be scrolled, did not
57
+ // compose with search, cost a keypress to leave, and was pinned at hardcoded
58
+ // coordinates across the roster it had been opened from.
52
59
  const chatView = new ChatView(renderer, {
53
60
  width: renderer.terminalWidth,
54
61
  height: renderer.terminalHeight,
55
- onSelectAgent: (agent: RosterEntry) => {
56
- void roomClient.getAgentDetail(agent.id).then((detail) => modal.show(detail));
57
- },
62
+ onSelectAgent: (agent: RosterEntry) => applyFilter(agent),
58
63
  });
59
64
 
60
65
  renderer.root.add(chatView.node);
61
- renderer.root.add(modal.node);
66
+
67
+ let filtered: RosterEntry | null = null;
68
+ let matchCursor = -1;
69
+
70
+ function applyFilter(agent: RosterEntry | null): void {
71
+ filtered = agent;
72
+ chatView.setFilter(agent?.id ?? null);
73
+ matchCursor = -1;
74
+ chatView.scrollToBottom();
75
+ refreshFooter();
76
+ }
77
+
78
+ let messageCount = 0;
79
+ let lastMessageAt: number | null = null;
80
+ let connection: ConnectionStatus = "connecting";
81
+ let participants = 0;
82
+
83
+ function refreshFooter(): void {
84
+ const liveness = livenessLine({ status: connection, messageCount, lastMessageAt, now: Date.now() });
85
+ // On a terminal too narrow for the roster, the footer is the only place
86
+ // that still says how many people are in the room.
87
+ const here = chatView.isRosterVisible() || participants === 0 ? "" : `${participants} here · `;
88
+ // A filter or a search that is on but invisible is the worst of both: the
89
+ // pane looks like a quiet room. `less` prints a single `&` for the same
90
+ // reason, and k9s puts the live filter in the view title.
91
+ const filterNote = filtered === null ? "" : `filter: ${filtered.name} · `;
92
+ const query = chatView.transcript.currentQuery();
93
+ const total = chatView.transcript.matches().length;
94
+ // `matchCursor` is -1 until a match has been jumped to, and `applyFilter`
95
+ // resets it — so this printed "0/2", a match number that does not exist.
96
+ // Before a position is known, say how many there are.
97
+ const position = matchCursor >= 0 ? `${matchCursor + 1}/${total}` : `${total} matches`;
98
+ const searchNote = query === "" ? "" : `/${query} ${total === 0 ? "no matches" : position} · `;
99
+ chatView.footer.setLiveness(`${filterNote}${searchNote}${here}${liveness}`);
100
+ // Only say something when the reader is *not* where new messages land —
101
+ // a permanent "at bottom" would be another word that always says the same
102
+ // thing, which is the habit this footer exists to break.
103
+ chatView.footer.setScrollNote(chatView.isAtBottom() ? null : "scrolled up · G to follow");
104
+ }
62
105
 
63
106
  const roomClient = new RoomClient(
64
107
  { url },
65
108
  {
66
- onConnectionChange: (status) => chatView.setConnectionStatus(status),
109
+ onConnectionChange: (status) => {
110
+ const previous = connection;
111
+ connection = status;
112
+ chatView.setConnectionStatus(status);
113
+ // Also into the transcript, not only the footer: a repainted footer
114
+ // row is never spoken by a screen reader and never survives a `tee`.
115
+ if (previous !== status && previous !== "connecting") {
116
+ chatView.appendSystemLine(status === "connected" ? "reconnected" : "disconnected, retrying");
117
+ }
118
+ refreshFooter();
119
+ },
120
+ // The room answered and the answer was an error — usually a malformed
121
+ // line in the log. It reaches the transcript, where it is readable and
122
+ // survives a scroll, rather than being thrown away.
123
+ onToolError: (message) => {
124
+ chatView.appendSystemLine(message);
125
+ refreshFooter();
126
+ },
67
127
  onStateUpdate: (state) => {
68
128
  chatView.setGoalContract(state.goal_contract);
69
129
  chatView.setRoster(state.roster);
130
+ participants = state.roster.length;
131
+ refreshFooter();
132
+ },
133
+ onNewMessages: (messages) => {
134
+ chatView.appendMessages(messages);
135
+ if (messages.length > 0) {
136
+ messageCount += messages.length;
137
+ lastMessageAt = Date.now();
138
+ }
139
+ refreshFooter();
70
140
  },
71
- onNewMessages: (messages) => chatView.appendMessages(messages),
72
141
  },
73
142
  );
74
143
  roomClient.start();
75
144
 
145
+ // The footer carries an age, so it has to repaint on its own — otherwise
146
+ // "last 4s ago" would sit there unchanged through a silence, which is the
147
+ // exact failure it was added to prevent.
148
+ const footerTimer = setInterval(refreshFooter, 1000);
149
+ refreshFooter();
150
+
76
151
  let prompt: OwnerPromptState = IDLE;
77
152
 
78
153
  function showPrompt(): void {
79
154
  chatView.statusBar.setNotice(ownerPromptLine(prompt));
80
155
  }
81
156
 
157
+ function openOwnerPrompt(): void {
158
+ prompt = OPENED;
159
+ showPrompt();
160
+ }
161
+
162
+ // The ordering and the re-entry guard live in `./shutdown` so they can be
163
+ // tested; see that file for why the order is the fix. `q`, Ctrl-C and all
164
+ // three signals share this one exit.
165
+ const shutdown = createShutdown({
166
+ stopClient: async () => {
167
+ clearInterval(footerTimer);
168
+ await roomClient.stop();
169
+ },
170
+ destroyRenderer: () => renderer.destroy(),
171
+ exit: (code) => process.exit(code),
172
+ });
173
+
174
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) {
175
+ process.on(signal, () => shutdown(0));
176
+ }
177
+
178
+ let search: SearchPromptState = CLOSED;
179
+
180
+ function showSearch(): void {
181
+ chatView.statusBar.setNotice(searchPromptLine(search));
182
+ }
183
+
184
+ function jumpTo(index: number | null): void {
185
+ if (index === null) {
186
+ chatView.statusBar.setNotice(`no match for "${chatView.transcript.currentQuery()}"`);
187
+ matchCursor = -1;
188
+ } else {
189
+ matchCursor = chatView.transcript.matches().indexOf(index);
190
+ chatView.scrollToEntry(index);
191
+ chatView.statusBar.setNotice(null);
192
+ }
193
+ refreshFooter();
194
+ }
195
+
196
+ /**
197
+ * Where `n` and `N` start counting from: the match cursor if a search is
198
+ * already underway, otherwise the end of the transcript, so the first `n`
199
+ * after a fresh `/` wraps to the earliest match rather than jumping from
200
+ * wherever the last search happened to leave off.
201
+ */
202
+ function currentEntryIndex(): number {
203
+ const matches = chatView.transcript.matches();
204
+ const at = matches[matchCursor];
205
+ return at ?? -1;
206
+ }
207
+
208
+ /**
209
+ * Writes what is on screen to a file and names the path.
210
+ *
211
+ * Claude Code's transcript viewer dumps into the terminal's own scrollback so
212
+ * tmux copy-mode and the terminal's find can reach it. roomyx cannot leave
213
+ * the alternate screen safely while the room is still streaming into it, so
214
+ * it writes a file instead — same purpose, which is to get the text somewhere
215
+ * the reader's existing tools already work.
216
+ *
217
+ * It never overwrites: `wx` fails if the path exists and the loop takes the
218
+ * next free suffix. Silently replacing an export someone took a minute ago is
219
+ * exactly the kind of small theft a keystroke should not be able to commit.
220
+ */
221
+ function exportTranscript(): void {
222
+ const base = exportBaseName(filtered?.id ?? null);
223
+ const target = nextFreeExportPath(process.cwd(), base, existsSync);
224
+ if (!target.ok) {
225
+ chatView.statusBar.setNotice(
226
+ target.reason === "exhausted"
227
+ ? `${base}.txt and 99 numbered siblings all exist — nothing written`
228
+ : "refusing to write outside the working directory",
229
+ );
230
+ return;
231
+ }
232
+ try {
233
+ // `wx` creates or fails; it never truncates.
234
+ writeFileSync(target.path, `${chatView.transcript.toText()}\n`, { encoding: "utf8", flag: "wx" });
235
+ // The name, not the absolute path: the status bar is one line and
236
+ // truncates, and an absolute path under a deep working directory gets cut
237
+ // exactly where the filename would have been. The file is in the
238
+ // directory the client was started from, which the containment check
239
+ // above now guarantees rather than assumes.
240
+ chatView.statusBar.setNotice(`written to ./${target.name}`);
241
+ } catch (error) {
242
+ chatView.statusBar.setNotice(
243
+ `could not write ./${target.name} — ${error instanceof Error ? error.message : String(error)}`,
244
+ );
245
+ }
246
+ }
247
+
82
248
  renderer.keyInput.on("keypress", (event) => {
83
- if (modal.isVisible()) {
84
- if (event.name === "escape") modal.hide();
249
+ // The help overlay swallows the keyboard, so a key pressed at a screen
250
+ // explaining the keys does not also fire the thing it explains.
251
+ if (chatView.help.isVisible()) {
252
+ if (event.name === "escape" || event.sequence === "?") chatView.help.hide();
253
+ return;
254
+ }
255
+
256
+ if (search.open) {
257
+ const stepped = stepSearchPrompt(search, event);
258
+ search = stepped.state;
259
+ showSearch();
260
+ if (stepped.action.type === "search") {
261
+ chatView.setQuery(stepped.action.query);
262
+ chatView.statusBar.setNotice(null);
263
+ if (stepped.action.query !== "") jumpTo(chatView.transcript.nextMatch(-1));
264
+ else refreshFooter();
265
+ } else if (stepped.action.type === "cancel") {
266
+ chatView.statusBar.setNotice(null);
267
+ }
85
268
  return;
86
269
  }
87
270
 
88
271
  // The prompt owns the keyboard while it is open — otherwise typing "q"
89
272
  // into a veto would quit the client.
90
- if (prompt.stage !== "idle" || (event.name === "o" && !event.ctrl)) {
273
+ if (prompt.stage !== "idle") {
91
274
  const stepped = stepOwnerPrompt(prompt, event);
92
275
  prompt = stepped.state;
93
276
  showPrompt();
@@ -115,15 +298,39 @@ export async function runClient(flags: FlagValues): Promise<void> {
115
298
  // Any other key clears a leftover result line and falls through.
116
299
  chatView.statusBar.setNotice(null);
117
300
 
118
- if (event.name === "up") chatView.roster.moveSelection(-1);
119
- else if (event.name === "down") chatView.roster.moveSelection(1);
120
- else if (event.name === "return") chatView.roster.confirmSelection();
121
- else if (event.name === "q" || (event.name === "c" && event.ctrl)) {
122
- void roomClient.stop().finally(() => {
123
- renderer.destroy();
124
- process.exit(0);
125
- });
126
- }
301
+ const action = resolveAction(event);
302
+ if (action === null) return;
303
+
304
+ // One row per action rather than a chain of conditions, so the set of
305
+ // things a key can do is a list you can read, and adding one cannot
306
+ // accidentally shadow an earlier branch.
307
+ const half = Math.max(1, Math.floor(chatView.pageSize() / 2));
308
+ const handlers: Record<Action, () => void> = {
309
+ "scroll.lineUp": () => chatView.scrollByLines(-1),
310
+ "scroll.lineDown": () => chatView.scrollByLines(1),
311
+ "scroll.pageUp": () => chatView.scrollByLines(-chatView.pageSize()),
312
+ "scroll.pageDown": () => chatView.scrollByLines(chatView.pageSize()),
313
+ "scroll.halfUp": () => chatView.scrollByLines(-half),
314
+ "scroll.halfDown": () => chatView.scrollByLines(half),
315
+ "scroll.top": () => chatView.scrollToTop(),
316
+ "scroll.bottom": () => chatView.scrollToBottom(),
317
+ "roster.prev": () => chatView.roster.moveSelection(-1),
318
+ "roster.next": () => chatView.roster.moveSelection(1),
319
+ "roster.open": () => chatView.roster.confirmSelection(),
320
+ "filter.clear": () => applyFilter(null),
321
+ "search.open": () => {
322
+ search = opened();
323
+ showSearch();
324
+ },
325
+ "search.next": () => jumpTo(chatView.transcript.nextMatch(currentEntryIndex())),
326
+ "search.previous": () => jumpTo(chatView.transcript.previousMatch(currentEntryIndex())),
327
+ "owner.prompt": () => openOwnerPrompt(),
328
+ "transcript.export": () => exportTranscript(),
329
+ "help.toggle": () => chatView.help.toggle(),
330
+ "app.quit": () => shutdown(0),
331
+ };
332
+ handlers[action]();
333
+ refreshFooter();
127
334
  });
128
335
  }
129
336
 
@@ -0,0 +1,157 @@
1
+ import type { ParsedKey } from "@opentui/core";
2
+
3
+ /**
4
+ * The keymap as data, in one place.
5
+ *
6
+ * It used to be an `else if` chain inside the keypress handler in `index.ts`,
7
+ * which is why the map could be wrong without being visibly wrong: there was
8
+ * no artefact anyone could read to answer "what keys does this have?". Adding
9
+ * a binding meant editing behaviour; now it means adding a row, and the footer
10
+ * and any future help screen are generated from the same rows rather than
11
+ * written by hand beside them. A footer that can disagree with the dispatcher
12
+ * is worse than no footer.
13
+ */
14
+ export type Action =
15
+ | "scroll.lineUp"
16
+ | "scroll.lineDown"
17
+ | "scroll.pageUp"
18
+ | "scroll.pageDown"
19
+ | "scroll.halfUp"
20
+ | "scroll.halfDown"
21
+ | "scroll.top"
22
+ | "scroll.bottom"
23
+ | "roster.prev"
24
+ | "roster.next"
25
+ | "roster.open"
26
+ | "filter.clear"
27
+ | "search.open"
28
+ | "search.next"
29
+ | "search.previous"
30
+ | "owner.prompt"
31
+ | "transcript.export"
32
+ | "help.toggle"
33
+ | "app.quit";
34
+
35
+ /**
36
+ * Printable keys match on `sequence` rather than on `name` + `shift`, because
37
+ * whether `G` arrives as name "G" or as name "g" with shift set depends on the
38
+ * terminal and on whether the kitty protocol is in play. The sequence is the
39
+ * one field that says the same thing either way.
40
+ */
41
+ type KeyPattern = { seq: string } | { name: string; ctrl?: boolean };
42
+
43
+ export interface Binding {
44
+ action: Action;
45
+ patterns: KeyPattern[];
46
+ /** How the key is written for a reader, e.g. "↑/↓". */
47
+ keys: string;
48
+ /** What it does, in one or two words. */
49
+ hint: string;
50
+ /** Whether it earns a place in the compact footer. */
51
+ footer: boolean;
52
+ /**
53
+ * Which hints survive a narrow terminal. Higher goes first. Without this the
54
+ * footer dropped all of its hints at once the moment it did not fit — which
55
+ * happened on an empty room and on any scrolled room, the two states where a
56
+ * newcomer most needs to be told which keys exist.
57
+ */
58
+ footerRank?: number;
59
+ }
60
+
61
+ export const BINDINGS: Binding[] = [
62
+ // The transcript owns the arrows. Every pager anyone has used binds them to
63
+ // the content — less, tmux copy-mode, k9s. Before this they moved the roster
64
+ // selection, so four keypresses on a room taller than the pane moved one
65
+ // caret and nothing else, which reads as a frozen pane rather than as a
66
+ // keymap you have to learn.
67
+ { action: "scroll.lineUp", patterns: [{ name: "up" }], keys: "↑/↓", hint: "scroll", footer: true, footerRank: 0 },
68
+ { action: "scroll.lineDown", patterns: [{ name: "down" }], keys: "↑/↓", hint: "scroll", footer: false },
69
+ { action: "scroll.pageUp", patterns: [{ name: "pageup" }], keys: "PgUp/PgDn", hint: "page", footer: true, footerRank: 5 },
70
+ { action: "scroll.pageDown", patterns: [{ name: "pagedown" }], keys: "PgUp/PgDn", hint: "page", footer: false },
71
+ { action: "scroll.halfUp", patterns: [{ name: "u", ctrl: true }], keys: "^U/^D", hint: "half page", footer: false },
72
+ { action: "scroll.halfDown", patterns: [{ name: "d", ctrl: true }], keys: "^U/^D", hint: "half page", footer: false },
73
+ { action: "scroll.top", patterns: [{ seq: "g" }], keys: "g/G", hint: "top/bottom", footer: false },
74
+ { action: "scroll.bottom", patterns: [{ seq: "G" }], keys: "g/G", hint: "top/bottom", footer: false },
75
+
76
+ // The roster keeps a selection, so it needs its own movement keys. j/k is
77
+ // what the same fingers already use for lists in vim, lazygit and k9s.
78
+ { action: "roster.prev", patterns: [{ seq: "k" }], keys: "j/k", hint: "roster", footer: true, footerRank: 2 },
79
+ { action: "roster.next", patterns: [{ seq: "j" }], keys: "j/k", hint: "roster", footer: false },
80
+ // Enter filters the stream to the selected participant in place, rather than
81
+ // opening a window over it. A modal costs a keypress to leave, cannot be
82
+ // scrolled, does not compose with search, and — as the review found — was
83
+ // pinned at hardcoded coordinates across the roster it was opened from.
84
+ { action: "roster.open", patterns: [{ name: "return" }], keys: "Enter", hint: "filter", footer: true, footerRank: 4 },
85
+ { action: "filter.clear", patterns: [{ name: "escape" }], keys: "Esc", hint: "clear", footer: false },
86
+
87
+ // `/` then `n`/`N` is the search anyone already has in their fingers, from
88
+ // less, vim, tmux copy-mode and every pager in between.
89
+ { action: "search.open", patterns: [{ seq: "/" }], keys: "/", hint: "search", footer: true, footerRank: 6 },
90
+ { action: "search.next", patterns: [{ seq: "n" }], keys: "n/N", hint: "next match", footer: false },
91
+ { action: "search.previous", patterns: [{ seq: "N" }], keys: "n/N", hint: "next match", footer: false },
92
+
93
+ // `:` is the free key and already means "I am about to type a command"
94
+ // everywhere. `o` means *open* everywhere, so it was borrowed rather than
95
+ // chosen; it still works, undocumented, so a script or a habit from 0.5.0
96
+ // does not break on upgrade — but the footer teaches `:`.
97
+ { action: "owner.prompt", patterns: [{ seq: ":" }, { seq: "o" }], keys: ":", hint: "command", footer: true, footerRank: 3 },
98
+
99
+ // Writes what is on screen to a file. Claude Code's transcript viewer dumps
100
+ // into the terminal's own scrollback so tmux copy-mode and the terminal's
101
+ // find can reach it; roomyx cannot leave the alternate screen safely mid-run,
102
+ // so it writes a file and names the path instead. Same purpose — get the text
103
+ // somewhere the reader's existing tools work on it.
104
+ { action: "transcript.export", patterns: [{ seq: "w" }], keys: "w", hint: "write out", footer: false },
105
+
106
+ { action: "help.toggle", patterns: [{ seq: "?" }], keys: "?", hint: "keys", footer: true, footerRank: 7 },
107
+
108
+ { action: "app.quit", patterns: [{ seq: "q" }, { name: "c", ctrl: true }], keys: "q", hint: "quit", footer: true, footerRank: 1 },
109
+ ];
110
+
111
+ function matches(pattern: KeyPattern, event: ParsedKey): boolean {
112
+ // A printable-sequence binding must not fire while ctrl is held: ctrl+letter
113
+ // is a different key, and most terminals send it as a control character
114
+ // rather than as the letter — but not all, and a matcher that only looked at
115
+ // the sequence would have let Ctrl-Q quit.
116
+ if ("seq" in pattern) return !event.ctrl && event.sequence === pattern.seq;
117
+ return event.name === pattern.name && event.ctrl === (pattern.ctrl ?? false);
118
+ }
119
+
120
+ export function resolveAction(event: ParsedKey): Action | null {
121
+ for (const binding of BINDINGS) {
122
+ if (binding.patterns.some((pattern) => matches(pattern, event))) return binding.action;
123
+ }
124
+ return null;
125
+ }
126
+
127
+ /**
128
+ * The footer's key hints, in binding order, trimmed to fit `width` by dropping
129
+ * the least useful ones first rather than dropping all of them at once.
130
+ * Returns "" when not even one hint fits.
131
+ */
132
+ export function footerHints(width = Number.POSITIVE_INFINITY): string {
133
+ const entries = BINDINGS.filter((binding) => binding.footer).map((binding, order) => ({
134
+ order,
135
+ rank: binding.footerRank ?? 0,
136
+ text: `${binding.keys} ${binding.hint}`,
137
+ }));
138
+
139
+ const render = (kept: typeof entries) =>
140
+ kept
141
+ .slice()
142
+ .sort((a, b) => a.order - b.order)
143
+ .map((entry) => entry.text)
144
+ .join(" · ");
145
+
146
+ let kept = entries;
147
+ while (kept.length > 0 && render(kept).length > width) {
148
+ let worst = 0;
149
+ for (let i = 1; i < kept.length; i += 1) {
150
+ const candidate = kept[i];
151
+ const current = kept[worst];
152
+ if (candidate && current && candidate.rank > current.rank) worst = i;
153
+ }
154
+ kept = kept.filter((_, i) => i !== worst);
155
+ }
156
+ return render(kept);
157
+ }
@@ -0,0 +1,56 @@
1
+ import type { ConnectionStatus } from "./mcp-client";
2
+
3
+ /**
4
+ * What the footer says about whether the room is alive.
5
+ *
6
+ * The rule came out of the review room, and it overturned both of the opening
7
+ * positions. A permanent `[connected]` chip is not read after the first
8
+ * minute — a word that has always said the same thing stops being a signal,
9
+ * which is exactly why a dead room looked like a live one: the header differed
10
+ * by a single word in the same ink. Removing the chip outright was no better,
11
+ * because it leaves a slot nobody has ever seen occupied.
12
+ *
13
+ * So: print a fact that *moves*. A message count and the age of the last
14
+ * message. When the number stops, the silence finally means something, and it
15
+ * means it without anyone having to notice a word change.
16
+ *
17
+ * Pure on purpose — it takes the current time rather than reading a clock, so
18
+ * the wording is testable without a renderer, a server or a fake timer.
19
+ */
20
+ export interface LivenessInput {
21
+ status: ConnectionStatus;
22
+ messageCount: number;
23
+ /** Epoch ms of the last message that arrived, or null if none has. */
24
+ lastMessageAt: number | null;
25
+ now: number;
26
+ }
27
+
28
+ export function formatAge(seconds: number): string {
29
+ if (seconds < 60) return `${seconds}s`;
30
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
31
+ return `${Math.floor(seconds / 3600)}h`;
32
+ }
33
+
34
+ export function livenessLine(input: LivenessInput): string {
35
+ const { status, messageCount, lastMessageAt, now } = input;
36
+ const age = lastMessageAt === null ? null : Math.max(0, Math.floor((now - lastMessageAt) / 1000));
37
+
38
+ if (status === "disconnected") {
39
+ // The one state that must not be quiet. It leads, it names itself, and it
40
+ // carries the age so the reader can tell a room that just dropped from one
41
+ // that has been dead for ten minutes.
42
+ return age === null ? "DISCONNECTED — retrying" : `DISCONNECTED — retrying · last message ${formatAge(age)} ago`;
43
+ }
44
+
45
+ if (status === "connecting") return "connecting…";
46
+
47
+ if (messageCount === 0) {
48
+ // Not trouble — unproven. A person watching a healthy room seconds after
49
+ // starting it concluded "it hung", and they were wrong. Say what is being
50
+ // waited for.
51
+ return "connected · waiting for the first message";
52
+ }
53
+
54
+ const plural = messageCount === 1 ? "message" : "messages";
55
+ return age === null ? `${messageCount} ${plural}` : `${messageCount} ${plural} · last ${formatAge(age)} ago`;
56
+ }