@mrciphersmith/roomyx 0.5.0 → 0.6.1

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.
@@ -16,6 +16,41 @@ export interface RoomClientEvents {
16
16
  onStateUpdate?(state: RoomState): void;
17
17
  onNewMessages?(messages: MessageEnvelope[]): void;
18
18
  onConnectionChange?(status: ConnectionStatus): void;
19
+ /**
20
+ * The server answered, and the answer was an error. Distinct from a
21
+ * connection change on purpose: the room is reachable and the poll loop keeps
22
+ * running, so reporting this as a disconnect told the operator to check the
23
+ * network when the actual problem — usually a malformed line in their log —
24
+ * was named in text that was being thrown away.
25
+ */
26
+ onToolError?(message: string): void;
27
+ }
28
+
29
+ /**
30
+ * The server replied and the reply was an error. Carries the server's own text,
31
+ * which used to be discarded: `callTool` ran `JSON.parse` over it, the parse
32
+ * threw, and both poll loops caught it as a lost connection.
33
+ */
34
+ export class ToolError extends Error {}
35
+
36
+ /** Reconnect delay ceiling. Without one, a persistent fault polls forever at 1s. */
37
+ const MAX_BACKOFF_MS = 30_000;
38
+
39
+ /**
40
+ * Ends a session on the server as well as locally.
41
+ *
42
+ * `client.close()` aborts the local controller and tells the server nothing.
43
+ * `terminateSession()` is what sends the HTTP DELETE the server needs to drop
44
+ * its transport — and it had no callers anywhere, so every connect this client
45
+ * ever made left a session behind that the room server retained for its whole
46
+ * life, and that stayed a fully routable handle to the room.
47
+ */
48
+ async function endSession(
49
+ client: Client | undefined,
50
+ transport: StreamableHTTPClientTransport | undefined,
51
+ ): Promise<void> {
52
+ await transport?.terminateSession().catch(() => undefined);
53
+ await client?.close().catch(() => undefined);
19
54
  }
20
55
 
21
56
  /**
@@ -31,16 +66,33 @@ export class RoomClient {
31
66
  private readonly events: RoomClientEvents;
32
67
 
33
68
  private client: Client | undefined;
69
+ private transport: StreamableHTTPClientTransport | undefined;
34
70
  private status: ConnectionStatus = "connecting";
35
71
  private sinceSeq = 0;
36
72
  private stopped = false;
37
73
  private stateTimer: ReturnType<typeof setTimeout> | undefined;
38
74
  private transcriptTimer: ReturnType<typeof setTimeout> | undefined;
75
+ private reconnectTimer: ReturnType<typeof setTimeout> | undefined;
76
+ private backoffMs: number;
77
+ /**
78
+ * Bumped on every disconnect. Each poll loop captures the generation it was
79
+ * started under and exits silently once it is stale.
80
+ *
81
+ * Without it, one dropped connection produced two: `handleDisconnect` was
82
+ * reachable independently from both loops, each scheduled its own
83
+ * `connect()`, and each `connect()` started a *fresh* pair of loops without
84
+ * stopping the running ones — so the loop count doubled per fault. Measured
85
+ * from a single malformed log line: one connection became 510 in ten seconds.
86
+ */
87
+ private generation = 0;
88
+ /** The last tool-error text reported, so a persistent fault is said once. */
89
+ private lastToolError: string | undefined;
39
90
 
40
91
  constructor(options: RoomClientOptions, events: RoomClientEvents) {
41
92
  this.url = options.url;
42
93
  this.stateIntervalMs = options.stateIntervalMs ?? 3000;
43
94
  this.transcriptIntervalMs = options.transcriptIntervalMs ?? 1000;
95
+ this.backoffMs = this.transcriptIntervalMs;
44
96
  this.events = events;
45
97
  }
46
98
 
@@ -51,19 +103,18 @@ export class RoomClient {
51
103
 
52
104
  async stop(): Promise<void> {
53
105
  this.stopped = true;
106
+ this.generation += 1;
54
107
  clearTimeout(this.stateTimer);
55
108
  clearTimeout(this.transcriptTimer);
56
- await this.client?.close().catch(() => undefined);
109
+ clearTimeout(this.reconnectTimer);
110
+ // Cleared, not just cancelled: `scheduleConnect` uses this field as its
111
+ // single-flight token, so a client stopped with a reconnect pending could
112
+ // never schedule another one — `start()` returned immediately and the
113
+ // client was inert for good.
114
+ this.reconnectTimer = undefined;
115
+ await endSession(this.client, this.transport);
57
116
  this.client = undefined;
58
- }
59
-
60
- getLastSeenSeq(): number {
61
- return this.sinceSeq;
62
- }
63
-
64
- /** On-demand call for the agent modal — not part of the poll loop. */
65
- async getAgentDetail(agentId: string): Promise<import("../log/types").AgentDetail> {
66
- return this.callTool("room.get_agent_detail", { agent_id: agentId });
117
+ this.transport = undefined;
67
118
  }
68
119
 
69
120
  private setStatus(status: ConnectionStatus): void {
@@ -72,9 +123,15 @@ export class RoomClient {
72
123
  this.events.onConnectionChange?.(status);
73
124
  }
74
125
 
126
+ /**
127
+ * Single-flight: a reconnect already pending is not scheduled again, and the
128
+ * handle is kept so `stop()` can cancel it. Both were missing — the timer was
129
+ * discarded, so nothing could tell that a reconnect was already on its way.
130
+ */
75
131
  private scheduleConnect(delayMs: number): void {
76
- if (this.stopped) return;
77
- setTimeout(() => {
132
+ if (this.stopped || this.reconnectTimer !== undefined) return;
133
+ this.reconnectTimer = setTimeout(() => {
134
+ this.reconnectTimer = undefined;
78
135
  void this.connect();
79
136
  }, delayMs);
80
137
  }
@@ -84,20 +141,31 @@ export class RoomClient {
84
141
  this.setStatus("connecting");
85
142
  try {
86
143
  const client = new Client({ name: "roomyx-client", version: "0.1.0" });
87
- await client.connect(new StreamableHTTPClientTransport(new URL(this.url)));
144
+ const transport = new StreamableHTTPClientTransport(new URL(this.url));
145
+ await client.connect(transport);
88
146
  if (this.stopped) {
89
147
  // stop() ran while this connection was in flight; this.client was
90
148
  // still undefined for it to close, so close the one it never saw.
91
- await client.close().catch(() => undefined);
149
+ await endSession(client, transport);
92
150
  return;
93
151
  }
152
+ // Close whatever we were holding before replacing it. A reconnect used
153
+ // to drop the previous Client on the floor, leaking its socket.
154
+ const previous = this.client;
155
+ const previousTransport = this.transport;
94
156
  this.client = client;
157
+ this.transport = transport;
158
+ if (previous) void endSession(previous, previousTransport);
159
+
160
+ this.backoffMs = this.transcriptIntervalMs;
95
161
  this.setStatus("connected");
96
- this.pollState();
97
- this.pollTranscript();
162
+ const generation = this.generation;
163
+ this.pollState(generation);
164
+ this.pollTranscript(generation);
98
165
  } catch {
99
166
  this.setStatus("disconnected");
100
- this.scheduleConnect(this.transcriptIntervalMs);
167
+ this.scheduleConnect(this.backoffMs);
168
+ this.backoffMs = Math.min(this.backoffMs * 2, MAX_BACKOFF_MS);
101
169
  }
102
170
  }
103
171
 
@@ -113,46 +181,105 @@ export class RoomClient {
113
181
  private async callTool<T>(name: string, args: Record<string, unknown>): Promise<T> {
114
182
  if (!this.client) throw new Error("not connected");
115
183
  const result = await this.client.callTool({ name, arguments: args });
116
- const content = result.content as Array<{ type: string; text: string }>;
117
- return JSON.parse(content[0]?.text ?? "null") as T;
184
+ const content = result.content as Array<{ type: string; text: string }> | undefined;
185
+ const text = content?.[0]?.text;
186
+
187
+ // `isError` was never read, so a tool-level failure arrived as prose that
188
+ // `JSON.parse` then choked on — indistinguishable, to the caller, from the
189
+ // transport dropping.
190
+ if (result.isError === true) throw new ToolError(text ?? `${name} failed with no message`);
191
+ if (text === undefined) throw new ToolError(`${name} returned no content`);
192
+
193
+ try {
194
+ return JSON.parse(text) as T;
195
+ } catch {
196
+ // Not an error result, but not JSON either. Still the server's answer,
197
+ // not a lost connection.
198
+ throw new ToolError(`${name} returned a response that is not JSON: ${text.slice(0, 200)}`);
199
+ }
118
200
  }
119
201
 
120
- private pollState(): void {
121
- if (this.stopped) return;
202
+ /**
203
+ * A tool error leaves the loop running: the room is reachable, the poll can
204
+ * be retried, and the operator gets the server's own text instead of a
205
+ * connection diagnosis that is simply wrong.
206
+ */
207
+ private handleToolError(error: unknown, resume: () => void): boolean {
208
+ if (!(error instanceof ToolError)) return false;
209
+ // Reported once per distinct message, not once per poll. A tool error is
210
+ // usually a property of the file rather than a transient — a log line the
211
+ // reader's schema refuses stays refused — so the loop reported the same
212
+ // sentence about eighty times a minute, each one a transcript entry
213
+ // allocating a renderable it never freed. That is the pool exhaustion this
214
+ // same round fixed elsewhere, re-entered through a different door.
215
+ if (error.message !== this.lastToolError) {
216
+ this.lastToolError = error.message;
217
+ this.events.onToolError?.(error.message);
218
+ }
219
+ resume();
220
+ return true;
221
+ }
222
+
223
+ private pollState(generation: number): void {
224
+ if (this.isStale(generation)) return;
225
+ const again = () => {
226
+ this.stateTimer = setTimeout(() => this.pollState(generation), this.stateIntervalMs);
227
+ };
122
228
  this.callTool<RoomState>("room.get_state", {})
123
229
  .then((state) => {
124
- if (this.stopped) return;
230
+ if (this.isStale(generation)) return;
231
+ this.lastToolError = undefined;
125
232
  this.events.onStateUpdate?.(state);
126
- this.stateTimer = setTimeout(() => this.pollState(), this.stateIntervalMs);
233
+ again();
127
234
  })
128
- .catch(() => {
129
- if (this.stopped) return;
235
+ .catch((error: unknown) => {
236
+ if (this.isStale(generation)) return;
237
+ if (this.handleToolError(error, again)) return;
130
238
  this.handleDisconnect();
131
239
  });
132
240
  }
133
241
 
134
- private pollTranscript(): void {
135
- if (this.stopped) return;
242
+ private pollTranscript(generation: number): void {
243
+ if (this.isStale(generation)) return;
244
+ const again = () => {
245
+ this.transcriptTimer = setTimeout(() => this.pollTranscript(generation), this.transcriptIntervalMs);
246
+ };
136
247
  this.callTool<MessageEnvelope[]>("room.get_transcript", { since_seq: this.sinceSeq })
137
248
  .then((messages) => {
138
- if (this.stopped) return;
249
+ if (this.isStale(generation)) return;
139
250
  if (messages.length > 0) {
140
251
  this.sinceSeq = Math.max(this.sinceSeq, ...messages.map((m) => m.seq));
141
252
  this.events.onNewMessages?.(messages);
142
253
  }
143
- this.transcriptTimer = setTimeout(() => this.pollTranscript(), this.transcriptIntervalMs);
254
+ again();
144
255
  })
145
- .catch(() => {
146
- if (this.stopped) return;
256
+ .catch((error: unknown) => {
257
+ if (this.isStale(generation)) return;
258
+ if (this.handleToolError(error, again)) return;
147
259
  this.handleDisconnect();
148
260
  });
149
261
  }
150
262
 
263
+ /** Stopped, or superseded by a later connection. */
264
+ private isStale(generation: number): boolean {
265
+ return this.stopped || generation !== this.generation;
266
+ }
267
+
151
268
  private handleDisconnect(): void {
152
269
  if (this.stopped) return;
270
+ // Bumping the generation is what stops the sibling loop, which clearing a
271
+ // single-slot timer handle could not: after the first doubling the handle
272
+ // belonged to a different, still-healthy loop.
273
+ this.generation += 1;
153
274
  clearTimeout(this.stateTimer);
154
275
  clearTimeout(this.transcriptTimer);
276
+ const previous = this.client;
277
+ const previousTransport = this.transport;
278
+ this.client = undefined;
279
+ this.transport = undefined;
280
+ if (previous) void endSession(previous, previousTransport);
155
281
  this.setStatus("disconnected");
156
- this.scheduleConnect(this.transcriptIntervalMs);
282
+ this.scheduleConnect(this.backoffMs);
283
+ this.backoffMs = Math.min(this.backoffMs * 2, MAX_BACKOFF_MS);
157
284
  }
158
285
  }
@@ -36,6 +36,9 @@ const KIND_BY_LETTER: Record<string, OwnerCommandKind> = {
36
36
 
37
37
  export const IDLE: OwnerPromptState = { stage: "idle" };
38
38
 
39
+ /** The state the prompt starts in once the keymap has decided to open it. */
40
+ export const OPENED: OwnerPromptState = { stage: "kind" };
41
+
39
42
  /** The status line to show for a state, or null to leave the bar alone. */
40
43
  export function ownerPromptLine(state: OwnerPromptState): string | null {
41
44
  if (state.stage === "idle") return null;
@@ -56,8 +59,12 @@ export function stepOwnerPrompt(
56
59
  const none = (next: OwnerPromptState) => ({ state: next, action: { type: "none" } as OwnerPromptAction });
57
60
 
58
61
  if (state.stage === "idle") {
59
- // `o` opens the prompt. Everything else belongs to the view's own keys.
60
- return key.name === "o" && !key.ctrl ? none({ stage: "kind" }) : none(state);
62
+ // Idle never opens itself. Which key opens the prompt is the keymap's
63
+ // decision and it is written down in exactly one place (`keymap.ts`); this
64
+ // machine used to hardcode `o` as well, so the two could disagree — and
65
+ // when the opening key changed, one of them would have been left behind
66
+ // still answering to the old one.
67
+ return none(state);
61
68
  }
62
69
 
63
70
  if (key.name === "escape") {
@@ -1,25 +1,43 @@
1
- import { BoxRenderable, ScrollBoxRenderable } from "@opentui/core";
2
- import type { RenderContext } from "@opentui/core";
1
+ import { BoxRenderable, ScrollBoxRenderable, TextRenderable } from "@opentui/core";
2
+ import type { Renderable, RenderContext } from "@opentui/core";
3
3
  import type { GoalContract, MessageEnvelope, RosterEntry } from "../../log/types";
4
4
  import { StatusBar } from "../components/status-bar";
5
5
  import { RosterSidebar } from "../components/roster-sidebar";
6
+ import { Footer } from "../components/footer";
7
+ import { HelpOverlay } from "../components/help-overlay";
6
8
  import { createMessageRow } from "../components/message-row";
9
+ import { Transcript } from "../transcript";
10
+ import type { Entry } from "../transcript";
7
11
  import type { ConnectionStatus } from "../mcp-client";
8
12
 
13
+ /**
14
+ * Terminal width at or above which the roster gets its 24 columns. Below it,
15
+ * those columns are worth more to the transcript than to a list of names.
16
+ */
17
+ export const ROSTER_BREAKPOINT = 80;
18
+
9
19
  /**
10
20
  * Main screen: StatusBar on top, RosterSidebar on the left, a scrolling
11
- * message stream on the right. Uses ScrollBoxRenderable's built-in
12
- * `stickyScroll`/`stickyStart: "bottom"` for AC8 (don't yank the view when
13
- * the user has scrolled up to read history) instead of hand-rolling
14
- * scroll-position math.
21
+ * message stream on the right, Footer along the bottom, help overlay on top of
22
+ * everything when asked for.
23
+ *
24
+ * The view renders from a `Transcript` rather than owning its messages, which
25
+ * is what makes filtering and searching possible at all — it used to push
26
+ * renderables into the scroll box and keep no record of what it had drawn, so
27
+ * there was nothing to filter and nothing to search.
15
28
  */
16
29
  export class ChatView {
17
30
  readonly node: BoxRenderable;
18
31
  readonly statusBar: StatusBar;
19
32
  readonly roster: RosterSidebar;
33
+ readonly footer: Footer;
34
+ readonly help: HelpOverlay;
35
+ readonly transcript = new Transcript();
20
36
  private readonly scroll: ScrollBoxRenderable;
21
37
  private readonly ctx: RenderContext;
22
38
  private rosterById = new Map<string, RosterEntry>();
39
+ private rows: Renderable[] = [];
40
+ private readonly rosterVisible: boolean;
23
41
 
24
42
  constructor(ctx: RenderContext, options: { width: number; height: number; onSelectAgent?: (agent: RosterEntry) => void }) {
25
43
  this.ctx = ctx;
@@ -30,11 +48,43 @@ export class ChatView {
30
48
  const body = new BoxRenderable(ctx, { flexDirection: "row", flexGrow: 1 });
31
49
  this.node.add(body);
32
50
 
51
+ // Below the breakpoint the roster is hidden and the stream takes the whole
52
+ // width. At 72 columns the roster was spending a third of the terminal on
53
+ // three short names while the messages wrapped to 46 — and a fixed
54
+ // 24-column gutter is also where non-Latin names die, since three CJK
55
+ // characters are six cells and not three.
56
+ //
57
+ // A breakpoint rather than a hard minimum, and auto rather than a flag:
58
+ // atuin degrades its own layout on a short terminal the same way, and
59
+ // charm's crush hides its sidebar below 120x30 outright. The participants
60
+ // are still reachable — the footer says how many there are, and widening
61
+ // the terminal brings the list back.
62
+ this.rosterVisible = options.width >= ROSTER_BREAKPOINT;
33
63
  this.roster = new RosterSidebar(ctx, { width: 24, onSelect: options.onSelectAgent });
34
- body.add(this.roster.node);
64
+ if (this.rosterVisible) body.add(this.roster.node);
35
65
 
36
- this.scroll = new ScrollBoxRenderable(ctx, { flexGrow: 1, stickyScroll: true, stickyStart: "bottom" });
66
+ // `horizontalScrollbarOptions: { visible: false }` is the whole fix for
67
+ // the first message vanishing. The horizontal scrollbar occupies a
68
+ // viewport row whether or not it has anything to scroll, which leaves
69
+ // `maxScrollTop` at 1 on a pane that is not full — so sticky-bottom
70
+ // scrolls down by one and takes seq 1 with it. Found by bisection rather
71
+ // than by reading: `scrollX: false` and the `contentOptions` variants were
72
+ // measured and do nothing.
73
+ //
74
+ // Nothing here scrolls horizontally anyway; message bodies wrap.
75
+ this.scroll = new ScrollBoxRenderable(ctx, {
76
+ flexGrow: 1,
77
+ stickyScroll: true,
78
+ stickyStart: "bottom",
79
+ horizontalScrollbarOptions: { visible: false },
80
+ });
37
81
  body.add(this.scroll);
82
+
83
+ this.footer = new Footer(ctx, { width: options.width });
84
+ this.node.add(this.footer.node);
85
+
86
+ this.help = new HelpOverlay(ctx, { width: options.width, height: options.height });
87
+ this.node.add(this.help.node);
38
88
  }
39
89
 
40
90
  setConnectionStatus(status: ConnectionStatus): void {
@@ -52,8 +102,120 @@ export class ChatView {
52
102
 
53
103
  appendMessages(messages: MessageEnvelope[]): void {
54
104
  for (const message of messages) {
55
- const fromName = this.rosterById.get(message.from)?.name ?? message.from;
56
- this.scroll.add(createMessageRow(this.ctx, message, fromName));
105
+ this.appendEntry({
106
+ kind: "message",
107
+ message,
108
+ fromName: this.rosterById.get(message.from)?.name ?? message.from,
109
+ });
110
+ }
111
+ }
112
+
113
+ /**
114
+ * A state change written into the transcript itself, not only into the
115
+ * footer. A footer is repainted at a fixed row with the cursor parked
116
+ * elsewhere, so a screen reader never speaks it and a `tee`'d session never
117
+ * records it — it is invisible in exactly the way that matters. A line in
118
+ * the stream lands in speech, in scrollback and in the log at once.
119
+ */
120
+ appendSystemLine(text: string): void {
121
+ this.appendEntry({ kind: "system", text });
122
+ }
123
+
124
+ /** Null clears the filter and brings the whole room back. */
125
+ setFilter(participantId: string | null): void {
126
+ this.transcript.setFilter(participantId);
127
+ this.rebuild();
128
+ }
129
+
130
+ /** Empty clears the search. */
131
+ setQuery(query: string): void {
132
+ this.transcript.setQuery(query);
133
+ }
134
+
135
+ /** Puts the entry at `index` in the transcript's visible list at the top of the viewport. */
136
+ scrollToEntry(index: number): void {
137
+ const row = this.rows[index];
138
+ if (row === undefined) return;
139
+ const offset = row.y - this.scroll.content.y;
140
+ this.scroll.scrollTop = Math.max(0, Math.min(this.maxScrollTop(), offset));
141
+ }
142
+
143
+ /** False on a terminal too narrow to justify the 24-column gutter. */
144
+ isRosterVisible(): boolean {
145
+ return this.rosterVisible;
146
+ }
147
+
148
+ /** True when the reader is parked at the newest message. */
149
+ isAtBottom(): boolean {
150
+ return this.scroll.scrollTop >= this.maxScrollTop() - 1;
151
+ }
152
+
153
+ scrollByLines(lines: number): void {
154
+ this.scroll.scrollTop = Math.max(0, Math.min(this.maxScrollTop(), this.scroll.scrollTop + lines));
155
+ }
156
+
157
+ scrollToTop(): void {
158
+ this.scroll.scrollTop = 0;
159
+ }
160
+
161
+ scrollToBottom(): void {
162
+ this.scroll.scrollTop = this.maxScrollTop();
163
+ }
164
+
165
+ /** Viewport height in rows, for page-sized movement. */
166
+ pageSize(): number {
167
+ return Math.max(1, this.scroll.viewport.height);
168
+ }
169
+
170
+ private appendEntry(entry: Entry): void {
171
+ const before = this.transcript.visible().length;
172
+ this.transcript.append(entry);
173
+ const after = this.transcript.visible();
174
+ // Appending stays incremental while the new entry is visible under the
175
+ // current filter, and touches nothing when it is not. Rebuilding the whole
176
+ // pane on every poll would recreate every row in the room once a second.
177
+ if (after.length === before + 1) this.addRow(after.length - 1);
178
+ }
179
+
180
+ private addRow(index: number): void {
181
+ const entry = this.transcript.visible()[index];
182
+ if (entry === undefined) return;
183
+
184
+ const separate = index > 0;
185
+ const row =
186
+ entry.kind === "system"
187
+ ? new TextRenderable(this.ctx, {
188
+ content: `— ${entry.text} —`,
189
+ wrapMode: "word",
190
+ marginTop: separate ? 1 : 0,
191
+ })
192
+ : createMessageRow(this.ctx, entry.message, entry.fromName, {
193
+ // Consecutive turns from one speaker share a header. A real room
194
+ // had the same nine-character prefix nine times running, which
195
+ // hides the one thing a header is for: telling you the speaker
196
+ // changed.
197
+ showHeader: this.transcript.startsRun(index),
198
+ separate,
199
+ });
200
+
201
+ this.rows.push(row);
202
+ this.scroll.add(row);
203
+ }
204
+
205
+ private rebuild(): void {
206
+ for (const row of this.rows) {
207
+ this.scroll.remove(row);
208
+ // See roster-sidebar.ts: `remove()` unlinks without freeing, and the
209
+ // native renderable pool is finite. A dozen filter toggles on a long room
210
+ // were enough to exhaust it.
211
+ row.destroyRecursively();
57
212
  }
213
+ this.rows = [];
214
+ const count = this.transcript.visible().length;
215
+ for (let index = 0; index < count; index += 1) this.addRow(index);
216
+ }
217
+
218
+ private maxScrollTop(): number {
219
+ return Math.max(0, this.scroll.scrollHeight - this.scroll.viewport.height);
58
220
  }
59
221
  }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The `/` search line, as a pure state machine.
3
+ *
4
+ * Same shape and the same reason as `owner-prompt.ts`: keeping the typing rules
5
+ * out of the keypress handler is what lets them be tested without a terminal,
6
+ * and it is why "a `q` typed into a search is text, not a quit" is a property
7
+ * you can assert rather than a thing you hope someone remembered.
8
+ *
9
+ * Which key *opens* the prompt is not decided here — that lives in `keymap.ts`,
10
+ * in one place. The owner prompt used to hardcode its own opening key as well
11
+ * as having one in the dispatcher, and the two could have drifted apart.
12
+ */
13
+ export interface SearchPromptState {
14
+ open: boolean;
15
+ buffer: string;
16
+ }
17
+
18
+ export const CLOSED: SearchPromptState = { open: false, buffer: "" };
19
+
20
+ export function opened(initial = ""): SearchPromptState {
21
+ return { open: true, buffer: initial };
22
+ }
23
+
24
+ export type SearchPromptAction =
25
+ | { type: "none" }
26
+ | { type: "cancel" }
27
+ | { type: "search"; query: string };
28
+
29
+ export interface PromptKey {
30
+ name: string;
31
+ sequence?: string;
32
+ ctrl?: boolean;
33
+ }
34
+
35
+ export function searchPromptLine(state: SearchPromptState): string | null {
36
+ if (!state.open) return null;
37
+ return `/${state.buffer}▌ (Enter to search, Esc to cancel)`;
38
+ }
39
+
40
+ export function stepSearchPrompt(
41
+ state: SearchPromptState,
42
+ key: PromptKey,
43
+ ): { state: SearchPromptState; action: SearchPromptAction } {
44
+ if (!state.open) return { state, action: { type: "none" } };
45
+
46
+ if (key.name === "escape") return { state: CLOSED, action: { type: "cancel" } };
47
+
48
+ if (key.name === "return") {
49
+ // An empty query clears the search rather than matching everything, which
50
+ // is what `//` does in the pagers this borrows from.
51
+ return { state: CLOSED, action: { type: "search", query: state.buffer } };
52
+ }
53
+
54
+ if (key.name === "backspace") {
55
+ return { state: { open: true, buffer: state.buffer.slice(0, -1) }, action: { type: "none" } };
56
+ }
57
+
58
+ // Only real printable input extends the buffer. Without the length check an
59
+ // arrow key, whose sequence is an escape sequence, would type its whole
60
+ // control sequence into the query.
61
+ const char = key.sequence ?? "";
62
+ if (!key.ctrl && char.length === 1 && char >= " ") {
63
+ return { state: { open: true, buffer: state.buffer + char }, action: { type: "none" } };
64
+ }
65
+
66
+ return { state, action: { type: "none" } };
67
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The client's ordered exit, as a unit that can be tested.
3
+ *
4
+ * It used to live inside `runClient`, which no test reaches — that file builds
5
+ * a renderer on import, so it cannot run without a real terminal. The
6
+ * consequence was measured rather than suspected: inverting the order below,
7
+ * and separately deleting the `stopped` guards in `mcp-client.ts`, both left
8
+ * `test/client-shutdown.test.ts` green. The file written to protect the fix did
9
+ * not fail when the fix was removed.
10
+ *
11
+ * **The order is the fix.** Stop polling before tearing the renderer down. The
12
+ * other way round, an in-flight poll loses its connection during teardown,
13
+ * calls `handleDisconnect`, and writes "disconnected" into a text buffer the
14
+ * renderer has already destroyed — `TextBuffer is destroyed`, ten frames of
15
+ * stack, at someone who just closed a window.
16
+ *
17
+ * Idempotence is the other half: a second signal arriving mid-teardown must not
18
+ * start a second one.
19
+ */
20
+ export interface ShutdownSteps {
21
+ stopClient: () => Promise<void>;
22
+ destroyRenderer: () => void;
23
+ exit: (code: number) => void;
24
+ }
25
+
26
+ export function createShutdown(steps: ShutdownSteps): (code: number) => void {
27
+ let shuttingDown = false;
28
+ return (code: number): void => {
29
+ if (shuttingDown) return;
30
+ shuttingDown = true;
31
+ void steps
32
+ .stopClient()
33
+ .catch(() => undefined)
34
+ .finally(() => {
35
+ steps.destroyRenderer();
36
+ steps.exit(code);
37
+ });
38
+ };
39
+ }