@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.
@@ -0,0 +1,124 @@
1
+ import { BoxRenderable, TextRenderable } from "@opentui/core";
2
+ import type { RenderContext } from "@opentui/core";
3
+ import { BINDINGS } from "../keymap";
4
+
5
+ /**
6
+ * The full keymap on demand, behind `?`.
7
+ *
8
+ * The footer teaches the handful of keys worth permanent space; this is where
9
+ * the rest live, so `Ctrl-U`, `g`/`G`, `/` and the export key do not have to be
10
+ * discovered by reading the source. Every mature keyboard TUI in the survey has
11
+ * one — k9s, lazygit, gitui, gemini-cli, grok-build — and all of them put it on
12
+ * `?`.
13
+ *
14
+ * The rows are generated from the same `BINDINGS` table the dispatcher and the
15
+ * footer use, so a help screen that advertises a key the tool does not have is
16
+ * not something anyone has to remember to prevent.
17
+ *
18
+ * It is placed over the whole view rather than at hardcoded coordinates. The
19
+ * participant modal it replaces was pinned at `top: 2, left: 2` and, being 70%
20
+ * of the terminal wide, lay across the roster it had been opened from — leaving
21
+ * a selection arrow pointing at a name it had covered.
22
+ */
23
+ export const HELP_WIDTH = 46;
24
+
25
+ const CLOSE_HINT = "? or Esc closes";
26
+
27
+ /** One row per distinct action label, in binding order, deduplicated. */
28
+ export function bindingRows(): string[] {
29
+ const seen = new Set<string>();
30
+ const lines: string[] = [];
31
+ for (const binding of BINDINGS) {
32
+ const label = `${binding.keys} ${binding.hint}`;
33
+ if (seen.has(label)) continue;
34
+ seen.add(label);
35
+ lines.push(`${binding.keys.padEnd(12)} ${binding.hint}`);
36
+ }
37
+ return lines;
38
+ }
39
+
40
+ /**
41
+ * The body of the overlay for a box `contentRows` tall, title and close hint
42
+ * included.
43
+ *
44
+ * The previous version sized the box as `min(rows + 5, height - 2)` and drew
45
+ * its full content regardless. A box does not clip: content past the last row
46
+ * is painted *into the bottom border* and then over whatever is under the box.
47
+ * Below 20 rows that reproduced, exactly, the defect the comment above that
48
+ * line said had been fixed:
49
+ *
50
+ * H=19 └─?─or─Esc─closes────────────────────────────┘
51
+ * H=17 └─q────────────quit──────────────────────────┘
52
+ *
53
+ * and at 17 the close hint was gone altogether while the overlay still
54
+ * swallowed every key, so the reader was in a mode with no visible way out and
55
+ * — with no resize handling — no way to grow the terminal out of it either.
56
+ *
57
+ * So the content is chosen to fit. The close hint is never the line that gets
58
+ * dropped: it is the one thing a reader trapped in a mode has to be told.
59
+ */
60
+ export function helpBody(contentRows: number): string[] {
61
+ const rows = bindingRows();
62
+ if (contentRows <= 0) return [];
63
+ if (contentRows === 1) return [CLOSE_HINT];
64
+ if (contentRows === 2) return ["keys", CLOSE_HINT];
65
+
66
+ // title + hint are fixed; everything between is bindings, and a truncation
67
+ // says how much it hid rather than simply ending.
68
+ const forBindings = contentRows - 2;
69
+ if (rows.length <= forBindings) {
70
+ return ["keys", ...rows, ...Array<string>(forBindings - rows.length).fill(""), CLOSE_HINT];
71
+ }
72
+ const shown = rows.slice(0, forBindings - 1);
73
+ return ["keys", ...shown, `… ${rows.length - shown.length} more, widen the terminal`, CLOSE_HINT];
74
+ }
75
+
76
+ export class HelpOverlay {
77
+ readonly node: BoxRenderable;
78
+
79
+ constructor(ctx: RenderContext, options: { width: number; height: number }) {
80
+ // Two rows of border, and never taller than the pane it sits in.
81
+ const boxHeight = Math.max(3, Math.min(bindingRows().length + 4, options.height - 2));
82
+ const body = helpBody(boxHeight - 2);
83
+
84
+ this.node = new BoxRenderable(ctx, {
85
+ position: "absolute",
86
+ top: 1,
87
+ left: Math.max(0, Math.floor((options.width - HELP_WIDTH) / 2)),
88
+ width: Math.min(HELP_WIDTH, options.width),
89
+ height: boxHeight,
90
+ flexDirection: "column",
91
+ border: true,
92
+ visible: false,
93
+ zIndex: 20,
94
+ backgroundColor: "#000000",
95
+ paddingLeft: 1,
96
+ paddingRight: 1,
97
+ });
98
+
99
+ body.forEach((line, index) => {
100
+ const isTitle = index === 0 && line === "keys";
101
+ const isHint = index === body.length - 1 && line === CLOSE_HINT;
102
+ this.node.add(
103
+ new TextRenderable(ctx, {
104
+ content: line,
105
+ fg: isTitle ? "#ffffff" : isHint ? "#8a8a8a" : "#c6c6c6",
106
+ attributes: isTitle ? 1 : 0,
107
+ height: 1,
108
+ }),
109
+ );
110
+ });
111
+ }
112
+
113
+ toggle(): void {
114
+ this.node.visible = !this.node.visible;
115
+ }
116
+
117
+ hide(): void {
118
+ this.node.visible = false;
119
+ }
120
+
121
+ isVisible(): boolean {
122
+ return this.node.visible;
123
+ }
124
+ }
@@ -1,11 +1,76 @@
1
- import { TextRenderable } from "@opentui/core";
1
+ import { BoxRenderable, TextRenderable } from "@opentui/core";
2
2
  import type { RenderContext } from "@opentui/core";
3
3
  import type { MessageEnvelope } from "../../log/types";
4
4
 
5
- /** One chat message as its own Renderable row (see roster-sidebar.ts's header comment for why per-row, not one blob). */
6
- export function createMessageRow(ctx: RenderContext, message: MessageEnvelope, fromName: string): TextRenderable {
7
- return new TextRenderable(ctx, {
8
- content: `${fromName}: ${message.body}`,
9
- height: 1,
5
+ /**
6
+ * One chat message: a header line naming the speaker, and the body indented
7
+ * under it.
8
+ *
9
+ * It used to be a single `Name: body` line, wrapped, in one colour and one
10
+ * weight. Sixteen of those is a grey wall — a continuation line and a new turn
11
+ * are indistinguishable, and nine consecutive turns from one speaker repeat
12
+ * the same nine-character prefix while telling you nothing. The indent is what
13
+ * makes a wrapped line read as a continuation instead of as a new turn.
14
+ *
15
+ * Two earlier defects this file carried, kept written down because both were
16
+ * invisible from the code: `height: 1` with the default `wrapMode: "none"`
17
+ * clipped every message at the pane width — in a room of arguing agents that
18
+ * is most of them, and the part that got cut was the end, where the claim
19
+ * usually is. And `kind` / `in_reply_to` were written by the dispatcher and
20
+ * rendered by nothing, so the challenge/answer structure that is the point of
21
+ * the log schema was visible in the log and invisible in the viewer of it.
22
+ *
23
+ * The tag stays ASCII on purpose: `↩` and `→` are East-Asian-ambiguous, so
24
+ * their width depends on the reader's terminal, and a wrong guess shifts the
25
+ * whole wrapped row.
26
+ */
27
+ export const SPEAKER_FG = "#ffffff";
28
+ export const TAG_FG = "#8a8a8a";
29
+ export const BODY_FG = "#c6c6c6";
30
+
31
+ export interface MessageRowOptions {
32
+ /**
33
+ * False when the previous message was from the same speaker — the body then
34
+ * joins the turn above it instead of repeating a header nobody reads.
35
+ */
36
+ showHeader: boolean;
37
+ /** False for the first row, which needs no separating blank line above it. */
38
+ separate: boolean;
39
+ }
40
+
41
+ function tagFor(message: MessageEnvelope): string {
42
+ return [message.kind, message.in_reply_to === undefined ? null : `re #${message.in_reply_to}`]
43
+ .filter((part): part is string => Boolean(part))
44
+ .join(" ");
45
+ }
46
+
47
+ export function createMessageRow(
48
+ ctx: RenderContext,
49
+ message: MessageEnvelope,
50
+ fromName: string,
51
+ options: MessageRowOptions = { showHeader: true, separate: false },
52
+ ): BoxRenderable {
53
+ const row = new BoxRenderable(ctx, {
54
+ flexDirection: "column",
55
+ marginTop: options.separate ? 1 : 0,
10
56
  });
57
+
58
+ if (options.showHeader) {
59
+ const header = new BoxRenderable(ctx, { flexDirection: "row", height: 1 });
60
+ header.add(new TextRenderable(ctx, { content: fromName, fg: SPEAKER_FG, attributes: 1, height: 1 }));
61
+ const tag = tagFor(message);
62
+ if (tag) header.add(new TextRenderable(ctx, { content: ` ${tag}`, fg: TAG_FG, height: 1 }));
63
+ row.add(header);
64
+ }
65
+
66
+ row.add(
67
+ new TextRenderable(ctx, {
68
+ content: message.body,
69
+ fg: BODY_FG,
70
+ wrapMode: "word",
71
+ marginLeft: 2,
72
+ }),
73
+ );
74
+
75
+ return row;
11
76
  }
@@ -2,6 +2,34 @@ import { BoxRenderable, TextRenderable } from "@opentui/core";
2
2
  import type { RenderContext } from "@opentui/core";
3
3
  import type { RosterEntry } from "../../log/types";
4
4
 
5
+ /**
6
+ * Clips a label to `width` columns, marking the cut.
7
+ *
8
+ * The row is a `TextRenderable` with `height: 1` in a fixed-width box, and the
9
+ * default word wrapping put an over-long label on a second line that `height: 1`
10
+ * then clipped — so the overflow was not trimmed at the column edge, the whole
11
+ * trailing word vanished. A single-token name of 23 characters rendered a
12
+ * completely blank row, while `j`/`k` still moved onto it and Enter still
13
+ * filtered by it: a filter attributed to a participant whose name was nowhere
14
+ * on screen.
15
+ *
16
+ * Counted in code units, which is what the box is laid out in. That is wrong
17
+ * for wide characters and is recorded as such — the display-cell arithmetic is
18
+ * deferred with the resize work that will need the same primitive — but a name
19
+ * cut one column early is a different order of problem from a name that is not
20
+ * drawn at all.
21
+ */
22
+ function clip(label: string, width: number): string {
23
+ if (width <= 0) return "";
24
+ if (label.length <= width) return label;
25
+ return width === 1 ? "…" : `${label.slice(0, width - 1)}…`;
26
+ }
27
+
28
+ /** Same ids, same names, same order — the only thing a rebuild would change. */
29
+ function sameRoster(a: RosterEntry[], b: RosterEntry[]): boolean {
30
+ return a.length === b.length && a.every((entry, i) => entry.id === b[i]?.id && entry.name === b[i]?.name);
31
+ }
32
+
5
33
  /**
6
34
  * Roster list — one Renderable row per participant, not a single joined-text
7
35
  * blob (per-row rows are required for OpenTUI mouse targeting and keep the
@@ -13,20 +41,43 @@ export class RosterSidebar {
13
41
  private rows: TextRenderable[] = [];
14
42
  private selectedIndex = 0;
15
43
  private onSelect: ((agent: RosterEntry) => void) | undefined;
44
+ private readonly width: number;
16
45
 
17
46
  constructor(
18
47
  private readonly ctx: RenderContext,
19
48
  options: { width: number; onSelect?: (agent: RosterEntry) => void },
20
49
  ) {
50
+ this.width = options.width;
21
51
  this.node = new BoxRenderable(ctx, { width: options.width, flexDirection: "column" });
22
52
  this.onSelect = options.onSelect;
23
53
  }
24
54
 
25
55
  setRoster(roster: RosterEntry[]): void {
56
+ // `onStateUpdate` calls this on every `room.get_state` poll — every three
57
+ // seconds — whether or not anything changed, and a room's roster changes
58
+ // approximately never. Rebuilding it anyway was not merely wasteful: see
59
+ // the destroy below.
60
+ if (sameRoster(this.roster, roster)) return;
61
+
26
62
  this.roster = roster;
27
- for (const row of this.rows) this.node.remove(row);
63
+ for (const row of this.rows) {
64
+ this.node.remove(row);
65
+ // `remove()` unlinks; it does not free. The native yoga node and the
66
+ // TextBuffer are released only by `destroy()`, and the native pool is
67
+ // finite — so this was a ceiling, not a slow leak. Measured at five
68
+ // leaked renderables per poll with an unchanged five-person roster: an
69
+ // idle attached client exhausted the pool and died in about 2.7 hours,
70
+ // then reported it as a lost connection.
71
+ row.destroyRecursively();
72
+ }
28
73
  this.rows = roster.map((agent, index) => {
29
- const row = new TextRenderable(this.ctx, { content: this.rowLabel(agent, index), height: 1 });
74
+ const row = new TextRenderable(this.ctx, {
75
+ content: this.rowLabel(agent, index),
76
+ height: 1,
77
+ // Explicit, rather than relying on `height: 1` to hide a wrap. That
78
+ // reliance is what turned an overflow into a vanished row.
79
+ wrapMode: "none",
80
+ });
30
81
  this.node.add(row);
31
82
  return row;
32
83
  });
@@ -45,7 +96,10 @@ export class RosterSidebar {
45
96
  }
46
97
 
47
98
  private rowLabel(agent: RosterEntry, index: number): string {
48
- return `${index === this.selectedIndex ? "> " : " "}${agent.name}`;
99
+ const marker = index === this.selectedIndex ? "> " : " ";
100
+ // One column kept clear on the right, so a full-width name cannot abut the
101
+ // message stream with no separating gap.
102
+ return `${marker}${clip(agent.name, this.width - marker.length - 1)}`;
49
103
  }
50
104
 
51
105
  private highlightSelected(): void {
@@ -12,7 +12,11 @@ export class StatusBar {
12
12
  private notice: string | null = null;
13
13
 
14
14
  constructor(ctx: RenderContext) {
15
- this.node = new TextRenderable(ctx, { content: "", height: 1 });
15
+ // Same reason as the roster rows: with the default word wrapping, an
16
+ // over-long line went to a second row that `height: 1` clipped, taking the
17
+ // whole trailing word with it. This line carries the goal statement and
18
+ // every owner-command result, including the reason an export failed.
19
+ this.node = new TextRenderable(ctx, { content: "", height: 1, wrapMode: "none" });
16
20
  this.render();
17
21
  }
18
22
 
@@ -0,0 +1,57 @@
1
+ import { join, resolve, sep } from "node:path";
2
+
3
+ /**
4
+ * Where a transcript export is allowed to land, and under what name.
5
+ *
6
+ * Pure on purpose: it takes an `exists` predicate rather than touching the
7
+ * filesystem, so the never-overwrite loop and the containment check are
8
+ * testable without a terminal, a room or a temp directory. The version inside
9
+ * `runClient` was reachable by no test at all — a mutation that changed its
10
+ * `wx` to `w`, making it silently overwrite, left all 201 tests passing.
11
+ */
12
+
13
+ const MAX_ATTEMPTS = 100;
14
+
15
+ /**
16
+ * A participant id is text from the room log — chosen by whoever wrote that
17
+ * log, which is the dispatcher or any agent that can append to it. Interpolated
18
+ * into a filename and handed to `join`, an id of `../../../../../tmp/pwned`
19
+ * made the operator's `w` keypress write to `/tmp/pwned.txt` while the status
20
+ * bar reported `./roomyx-transcript-…`, telling them the opposite of what had
21
+ * happened.
22
+ *
23
+ * So the id is reduced to characters that cannot mean anything to a path, and
24
+ * the result is checked against the working directory anyway. Two independent
25
+ * defences, because the first is a transformation and the second is a fact.
26
+ */
27
+ export function exportBaseName(filterId: string | null): string {
28
+ if (filterId === null) return "roomyx-transcript";
29
+ const slug = filterId.replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
30
+ return slug === "" ? "roomyx-transcript-filtered" : `roomyx-transcript-${slug}`;
31
+ }
32
+
33
+ export type ExportTarget =
34
+ | { ok: true; path: string; name: string }
35
+ | { ok: false; reason: "exhausted" | "escapes-cwd" };
36
+
37
+ /**
38
+ * The first free `<base>.txt`, `<base>-1.txt`, … under `cwd`.
39
+ *
40
+ * Never overwrites: silently replacing an export someone took a minute ago is
41
+ * the kind of small theft a keystroke should not be able to commit. Returns a
42
+ * reason rather than throwing, so the caller can say which of the two things
43
+ * went wrong.
44
+ */
45
+ export function nextFreeExportPath(cwd: string, base: string, exists: (path: string) => boolean): ExportTarget {
46
+ const root = resolve(cwd);
47
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
48
+ const name = `${base}${attempt === 0 ? "" : `-${attempt}`}.txt`;
49
+ const path = join(root, name);
50
+ // The fact, checked after the transformation rather than instead of it.
51
+ if (path !== join(root, name) || !resolve(path).startsWith(root + sep)) {
52
+ return { ok: false, reason: "escapes-cwd" };
53
+ }
54
+ if (!exists(path)) return { ok: true, path, name };
55
+ }
56
+ return { ok: false, reason: "exhausted" };
57
+ }