@narumitw/pi-chat 0.0.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,436 @@
1
+ import { randomBytes, randomUUID } from "node:crypto";
2
+ import type { ChatIdentity } from "./identity.js";
3
+ import { formatIdentityLabel, normalizeNickname, uniqueIdentityTags } from "./identity.js";
4
+ import {
5
+ createChatMessage,
6
+ createHello,
7
+ PeerRateLimiter,
8
+ type ProtocolMessage,
9
+ type RoomDescriptor,
10
+ verifyHello,
11
+ } from "./protocol.js";
12
+
13
+ const MAX_TRANSCRIPT = 256;
14
+ const MAX_SEEN_MESSAGES = 1024;
15
+ const MAX_PROTOCOL_VIOLATIONS = 3;
16
+
17
+ export interface TransportPeer {
18
+ publicKey: Buffer;
19
+ send(message: ProtocolMessage): void;
20
+ close(): void;
21
+ }
22
+
23
+ export interface ChatTransportListener {
24
+ onPeer(peer: TransportPeer): void;
25
+ onMessage(peer: TransportPeer, message: ProtocolMessage): void;
26
+ onDisconnect(peer: TransportPeer): void;
27
+ onError(error: Error): void;
28
+ }
29
+
30
+ export interface ChatTransport {
31
+ start(listener: ChatTransportListener, signal?: AbortSignal): Promise<void>;
32
+ connectPeer?(publicKey: Buffer): void;
33
+ stop(): Promise<void>;
34
+ }
35
+
36
+ export interface TranscriptEntry {
37
+ id: string;
38
+ author: "local" | "remote";
39
+ label: string;
40
+ publicKey: string;
41
+ text: string;
42
+ sentAt: number;
43
+ delivery?: "broadcast" | "not-delivered";
44
+ deliveredTo?: number;
45
+ }
46
+
47
+ export interface ParticipantSnapshot {
48
+ publicKey: string;
49
+ label: string;
50
+ nickname: string;
51
+ muted: boolean;
52
+ }
53
+
54
+ export interface ChatSnapshot {
55
+ state: "connecting" | "connected" | "degraded" | "disconnected";
56
+ room: RoomDescriptor;
57
+ localLabel: string;
58
+ peers: ParticipantSnapshot[];
59
+ transcript: TranscriptEntry[];
60
+ unread: number;
61
+ composerOpen: boolean;
62
+ lastError?: string;
63
+ }
64
+
65
+ export interface ChatSessionOptions {
66
+ room: RoomDescriptor;
67
+ identity: ChatIdentity;
68
+ nickname: string;
69
+ transport: ChatTransport;
70
+ now?: () => number;
71
+ onChange?: (snapshot: ChatSnapshot) => void;
72
+ }
73
+
74
+ interface PeerState {
75
+ peer: TransportPeer;
76
+ authenticated: boolean;
77
+ nickname?: string;
78
+ muted: boolean;
79
+ violations: number;
80
+ limiter: PeerRateLimiter;
81
+ }
82
+
83
+ export class ChatSession {
84
+ private readonly room: RoomDescriptor;
85
+ private readonly identity: ChatIdentity;
86
+ private nickname: string;
87
+ private readonly transport: ChatTransport;
88
+ private readonly now: () => number;
89
+ private readonly onChange?: (snapshot: ChatSnapshot) => void;
90
+ private readonly peers = new Map<string, PeerState>();
91
+ private readonly transcript: TranscriptEntry[] = [];
92
+ private readonly seen = new Set<string>();
93
+ private readonly seenOrder: string[] = [];
94
+ private readonly listeners = new Set<(snapshot: ChatSnapshot) => void>();
95
+ private state: ChatSnapshot["state"] = "disconnected";
96
+ private unread = 0;
97
+ private viewOpen = false;
98
+ private lastError: string | undefined;
99
+ private generation = 0;
100
+ private leavePromise: Promise<void> | undefined;
101
+
102
+ constructor(options: ChatSessionOptions) {
103
+ const nickname = normalizeNickname(options.nickname);
104
+ if (!nickname) throw new Error("Pi Chat nickname is invalid.");
105
+ this.room = options.room;
106
+ this.identity = options.identity;
107
+ this.nickname = nickname;
108
+ this.transport = options.transport;
109
+ this.now = options.now ?? Date.now;
110
+ this.onChange = options.onChange;
111
+ }
112
+
113
+ async start(signal?: AbortSignal): Promise<void> {
114
+ if (this.state !== "disconnected" || this.leavePromise) {
115
+ throw new Error("Pi Chat session has already started.");
116
+ }
117
+ const owner = ++this.generation;
118
+ this.state = "connecting";
119
+ this.emit();
120
+ try {
121
+ await this.transport.start(
122
+ {
123
+ onPeer: (peer) => this.onPeer(owner, peer),
124
+ onMessage: (peer, message) => this.onMessage(owner, peer, message),
125
+ onDisconnect: (peer) => this.onDisconnect(owner, peer),
126
+ onError: (error) => this.onError(owner, error),
127
+ },
128
+ signal,
129
+ );
130
+ signal?.throwIfAborted();
131
+ if (owner !== this.generation) return;
132
+ this.state = "connected";
133
+ this.emit();
134
+ } catch (error) {
135
+ if (owner === this.generation) {
136
+ this.state = "disconnected";
137
+ this.lastError = safeError(error);
138
+ this.emit();
139
+ }
140
+ await this.transport.stop().catch(() => undefined);
141
+ throw error;
142
+ }
143
+ }
144
+
145
+ send(text: string): { id: string; deliveredTo: number } {
146
+ if (this.state !== "connected" && this.state !== "degraded") {
147
+ throw new Error("Pi Chat is not connected.");
148
+ }
149
+ const id = randomUUID();
150
+ const message = createChatMessage(text, this.now(), id);
151
+ let deliveredTo = 0;
152
+ for (const state of this.peers.values()) {
153
+ if (!state.authenticated || state.muted) continue;
154
+ try {
155
+ state.peer.send(message);
156
+ deliveredTo += 1;
157
+ } catch {
158
+ state.violations += 1;
159
+ }
160
+ }
161
+ this.pushTranscript({
162
+ id,
163
+ author: "local",
164
+ label: formatIdentityLabel(this.nickname, this.identity.publicKey),
165
+ publicKey: this.identity.publicKey.toString("hex"),
166
+ text,
167
+ sentAt: message.sentAt,
168
+ delivery: deliveredTo > 0 ? "broadcast" : "not-delivered",
169
+ deliveredTo,
170
+ });
171
+ this.emit();
172
+ return { id, deliveredTo };
173
+ }
174
+
175
+ updateNickname(value: string): void {
176
+ const nickname = normalizeNickname(value);
177
+ if (!nickname) throw new Error("Pi Chat nickname is invalid.");
178
+ this.nickname = nickname;
179
+ for (const state of this.peers.values()) {
180
+ if (!state.authenticated) continue;
181
+ try {
182
+ state.peer.send({ v: 1, type: "nickname-update", nickname });
183
+ } catch {
184
+ state.violations += 1;
185
+ }
186
+ }
187
+ this.emit();
188
+ }
189
+
190
+ mute(publicKey: Uint8Array): void {
191
+ const state = this.peers.get(keyId(publicKey));
192
+ if (!state) return;
193
+ state.muted = true;
194
+ this.emit();
195
+ }
196
+
197
+ toggleMute(publicKey: Uint8Array): boolean | undefined {
198
+ const state = this.peers.get(keyId(publicKey));
199
+ if (!state?.authenticated) return undefined;
200
+ state.muted = !state.muted;
201
+ this.emit();
202
+ return state.muted;
203
+ }
204
+
205
+ subscribe(listener: (snapshot: ChatSnapshot) => void): () => void {
206
+ this.listeners.add(listener);
207
+ return () => this.listeners.delete(listener);
208
+ }
209
+
210
+ setViewOpen(open: boolean): void {
211
+ if (this.viewOpen === open) return;
212
+ this.viewOpen = open;
213
+ if (open) this.unread = 0;
214
+ this.emit();
215
+ }
216
+
217
+ leave(): Promise<void> {
218
+ if (this.leavePromise) return this.leavePromise;
219
+ this.leavePromise = this.leaveOwned();
220
+ return this.leavePromise;
221
+ }
222
+
223
+ snapshot(): ChatSnapshot {
224
+ const authenticated: Array<[string, PeerState, string]> = [];
225
+ for (const [publicKey, value] of this.peers) {
226
+ if (value.authenticated && value.nickname) {
227
+ authenticated.push([publicKey, value, value.nickname]);
228
+ }
229
+ }
230
+ const tags = uniqueIdentityTags([
231
+ this.identity.publicKey,
232
+ ...authenticated.map(([, value]) => value.peer.publicKey),
233
+ ]);
234
+ const localKey = this.identity.publicKey.toString("hex");
235
+ const peers = authenticated
236
+ .map(([publicKey, value, nickname]) => ({
237
+ publicKey,
238
+ nickname,
239
+ label: `${nickname}~${tags.get(publicKey) ?? formatIdentityLabel(nickname, value.peer.publicKey).split("~").at(-1)}`,
240
+ muted: value.muted,
241
+ }))
242
+ .sort((left, right) => left.label.localeCompare(right.label));
243
+ return {
244
+ state: this.state,
245
+ room: this.room,
246
+ localLabel: `${this.nickname}~${tags.get(localKey) ?? formatIdentityLabel(this.nickname, this.identity.publicKey).split("~").at(-1)}`,
247
+ peers,
248
+ transcript: this.transcript.map((entry) => {
249
+ const tag = tags.get(entry.publicKey);
250
+ const nickname = entry.label.split("~", 1)[0] ?? entry.label;
251
+ return { ...entry, label: tag ? `${nickname}~${tag}` : entry.label };
252
+ }),
253
+ unread: this.unread,
254
+ composerOpen: this.viewOpen,
255
+ ...(this.lastError ? { lastError: this.lastError } : {}),
256
+ };
257
+ }
258
+
259
+ private onPeer(owner: number, peer: TransportPeer): void {
260
+ if (owner !== this.generation || this.state === "disconnected") {
261
+ peer.close();
262
+ return;
263
+ }
264
+ const id = keyId(peer.publicKey);
265
+ const previous = this.peers.get(id);
266
+ if (previous && previous.peer !== peer) previous.peer.close();
267
+ const state: PeerState = {
268
+ peer,
269
+ authenticated: false,
270
+ muted: previous?.muted ?? false,
271
+ violations: 0,
272
+ limiter: new PeerRateLimiter({ burst: 3, refillPerSecond: 1, now: this.now }),
273
+ };
274
+ this.peers.set(id, state);
275
+ try {
276
+ peer.send(
277
+ createHello(
278
+ this.room,
279
+ this.nickname,
280
+ this.identity.publicKey,
281
+ peer.publicKey,
282
+ randomBytes(16),
283
+ ),
284
+ );
285
+ } catch {
286
+ peer.close();
287
+ this.peers.delete(id);
288
+ }
289
+ }
290
+
291
+ private onMessage(owner: number, peer: TransportPeer, message: ProtocolMessage): void {
292
+ if (owner !== this.generation) return;
293
+ const id = keyId(peer.publicKey);
294
+ const state = this.peers.get(id);
295
+ if (!state || state.peer !== peer) return;
296
+ if (!state.authenticated) {
297
+ const hello = verifyHello(message, this.room, peer.publicKey, this.identity.publicKey);
298
+ if (!hello) {
299
+ this.violate(id, state);
300
+ return;
301
+ }
302
+ state.authenticated = true;
303
+ state.nickname = hello.nickname;
304
+ const knownPeers = [...this.peers.values()]
305
+ .filter((candidate) => candidate !== state && candidate.authenticated)
306
+ .map((candidate) => candidate.peer.publicKey.toString("hex"));
307
+ if (knownPeers.length > 0) {
308
+ state.peer.send({ v: 1, type: "peer-list", publicKeys: knownPeers.slice(0, 16) });
309
+ }
310
+ for (const candidate of this.peers.values()) {
311
+ if (candidate !== state && candidate.authenticated) {
312
+ candidate.peer.send({ v: 1, type: "peer-list", publicKeys: [id] });
313
+ }
314
+ }
315
+ this.emit();
316
+ return;
317
+ }
318
+ if (message.type === "hello") return;
319
+ if (message.type === "peer-list") {
320
+ for (const publicKey of message.publicKeys) {
321
+ if (publicKey !== this.identity.publicKey.toString("hex") && !this.peers.has(publicKey)) {
322
+ this.transport.connectPeer?.(Buffer.from(publicKey, "hex"));
323
+ }
324
+ }
325
+ return;
326
+ }
327
+ if (message.type === "goodbye") {
328
+ this.peers.delete(id);
329
+ peer.close();
330
+ this.emit();
331
+ return;
332
+ }
333
+ if (message.type === "nickname-update") {
334
+ const nickname = normalizeNickname(message.nickname);
335
+ if (!nickname) this.violate(id, state);
336
+ else {
337
+ state.nickname = nickname;
338
+ this.emit();
339
+ }
340
+ return;
341
+ }
342
+ if (message.type !== "chat" || state.muted) return;
343
+ if (!state.limiter.accept()) {
344
+ this.violate(id, state);
345
+ return;
346
+ }
347
+ const seenId = `${id}:${message.id}`;
348
+ if (this.seen.has(seenId)) return;
349
+ this.remember(seenId);
350
+ this.pushTranscript({
351
+ id: message.id,
352
+ author: "remote",
353
+ label: formatIdentityLabel(state.nickname ?? "peer", peer.publicKey),
354
+ publicKey: id,
355
+ text: message.text,
356
+ sentAt: message.sentAt,
357
+ });
358
+ if (!this.viewOpen) this.unread += 1;
359
+ this.emit();
360
+ }
361
+
362
+ private onDisconnect(owner: number, peer: TransportPeer): void {
363
+ if (owner !== this.generation) return;
364
+ const id = keyId(peer.publicKey);
365
+ if (this.peers.get(id)?.peer === peer) {
366
+ this.peers.delete(id);
367
+ this.emit();
368
+ }
369
+ }
370
+
371
+ private onError(owner: number, error: Error): void {
372
+ if (owner !== this.generation) return;
373
+ this.state = "degraded";
374
+ this.lastError = safeError(error);
375
+ this.emit();
376
+ }
377
+
378
+ private violate(id: string, state: PeerState): void {
379
+ state.violations += 1;
380
+ if (state.violations > MAX_PROTOCOL_VIOLATIONS) {
381
+ state.peer.close();
382
+ this.peers.delete(id);
383
+ this.emit();
384
+ }
385
+ }
386
+
387
+ private remember(id: string): void {
388
+ this.seen.add(id);
389
+ this.seenOrder.push(id);
390
+ if (this.seenOrder.length > MAX_SEEN_MESSAGES) {
391
+ const removed = this.seenOrder.shift();
392
+ if (removed) this.seen.delete(removed);
393
+ }
394
+ }
395
+
396
+ private pushTranscript(entry: TranscriptEntry): void {
397
+ this.transcript.push(entry);
398
+ if (this.transcript.length > MAX_TRANSCRIPT) this.transcript.shift();
399
+ }
400
+
401
+ private async leaveOwned(): Promise<void> {
402
+ this.generation += 1;
403
+ for (const state of this.peers.values()) {
404
+ if (state.authenticated) {
405
+ try {
406
+ state.peer.send({ v: 1, type: "goodbye" });
407
+ } catch {
408
+ // Best-effort departure notice.
409
+ }
410
+ }
411
+ state.peer.close();
412
+ }
413
+ this.peers.clear();
414
+ await this.transport.stop().catch((error) => {
415
+ this.lastError = safeError(error);
416
+ });
417
+ this.state = "disconnected";
418
+ this.unread = 0;
419
+ this.transcript.length = 0;
420
+ this.emit();
421
+ }
422
+
423
+ private emit(): void {
424
+ const snapshot = this.snapshot();
425
+ this.onChange?.(snapshot);
426
+ for (const listener of this.listeners) listener(snapshot);
427
+ }
428
+ }
429
+
430
+ function keyId(publicKey: Uint8Array): string {
431
+ return Buffer.from(publicKey).toString("hex");
432
+ }
433
+
434
+ function safeError(error: unknown): string {
435
+ return error instanceof Error ? error.message : String(error);
436
+ }
@@ -0,0 +1,256 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ type Component,
4
+ Editor,
5
+ type EditorTheme,
6
+ type Focusable,
7
+ Key,
8
+ matchesKey,
9
+ sliceByColumn,
10
+ type TUI,
11
+ truncateToWidth,
12
+ visibleWidth,
13
+ wrapTextWithAnsi,
14
+ } from "@earendil-works/pi-tui";
15
+ import type { ChatSnapshot } from "./chat-session.js";
16
+ import { sanitizeChatText, sanitizeSingleLine } from "./text.js";
17
+
18
+ export interface ChatViewOptions {
19
+ tui: TUI;
20
+ theme: Theme;
21
+ getSnapshot(): ChatSnapshot;
22
+ send(text: string): { id: string; deliveredTo: number };
23
+ initialDraft?: string;
24
+ onDraftChange?(text: string): void;
25
+ setViewOpen(open: boolean): void;
26
+ subscribe?(listener: () => void): () => void;
27
+ signal?: AbortSignal;
28
+ onReturnToPi(): void;
29
+ onClose(): void;
30
+ }
31
+
32
+ export class ChatView implements Component, Focusable {
33
+ private readonly editor: Editor;
34
+ private readonly tui: TUI;
35
+ private readonly theme: Theme;
36
+ private readonly options: ChatViewOptions;
37
+ private scrollOffset = 0;
38
+ private lastContentRows = 0;
39
+ private lastViewportRows = 1;
40
+ private followBottom = true;
41
+ private messageStatus: { kind: "success" | "warning"; text: string } | undefined;
42
+ private finished = false;
43
+ private _focused = false;
44
+ private readonly unsubscribe: () => void;
45
+ private removeAbort = () => {};
46
+
47
+ constructor(options: ChatViewOptions) {
48
+ this.options = options;
49
+ this.tui = options.tui;
50
+ this.theme = options.theme;
51
+ const editorTheme: EditorTheme = {
52
+ borderColor: (text) => this.theme.fg("accent", text),
53
+ selectList: {
54
+ selectedPrefix: (text) => this.theme.fg("accent", text),
55
+ selectedText: (text) => this.theme.fg("accent", text),
56
+ description: (text) => this.theme.fg("muted", text),
57
+ scrollInfo: (text) => this.theme.fg("dim", text),
58
+ noMatch: (text) => this.theme.fg("warning", text),
59
+ },
60
+ };
61
+ this.editor = new Editor(this.tui, editorTheme);
62
+ if (options.initialDraft) this.editor.setText(options.initialDraft);
63
+ this.unsubscribe = options.subscribe?.(() => this.tui.requestRender()) ?? (() => undefined);
64
+ this.editor.onChange = () => {
65
+ this.messageStatus = undefined;
66
+ this.options.onDraftChange?.(this.editor.getExpandedText());
67
+ };
68
+ this.editor.onSubmit = (text) => {
69
+ const message = text.trim();
70
+ if (!message) {
71
+ this.messageStatus = { kind: "warning", text: "Message cannot be empty" };
72
+ this.tui.requestRender();
73
+ return;
74
+ }
75
+ if (this.options.getSnapshot().peers.length === 0) {
76
+ this.editor.setText(text);
77
+ this.messageStatus = {
78
+ kind: "warning",
79
+ text: "No direct peers — message kept. Wait for connection or Esc to return.",
80
+ };
81
+ this.tui.requestRender();
82
+ return;
83
+ }
84
+ try {
85
+ const result = this.options.send(message);
86
+ if (result.deliveredTo === 0) {
87
+ this.editor.setText(text);
88
+ this.messageStatus = {
89
+ kind: "warning",
90
+ text: "No direct peers accepted it — message kept for retry.",
91
+ };
92
+ } else {
93
+ this.editor.setText("");
94
+ this.followBottom = true;
95
+ this.messageStatus = {
96
+ kind: "success",
97
+ text: `Sent to ${result.deliveredTo} direct peer${result.deliveredTo === 1 ? "" : "s"}`,
98
+ };
99
+ }
100
+ } catch (error) {
101
+ this.editor.setText(text);
102
+ this.messageStatus = { kind: "warning", text: safeDisplayError(error) };
103
+ }
104
+ this.tui.requestRender();
105
+ };
106
+ this.options.setViewOpen(true);
107
+ if (options.signal) {
108
+ const abort = () => this.finish(false, true);
109
+ options.signal.addEventListener("abort", abort, { once: true });
110
+ this.removeAbort = () => options.signal?.removeEventListener("abort", abort);
111
+ if (options.signal.aborted) abort();
112
+ }
113
+ }
114
+
115
+ get focused(): boolean {
116
+ return this._focused;
117
+ }
118
+
119
+ set focused(value: boolean) {
120
+ this._focused = value;
121
+ this.editor.focused = value;
122
+ }
123
+
124
+ render(width: number): string[] {
125
+ const safeWidth = Math.max(1, width);
126
+ const snapshot = this.options.getSnapshot();
127
+ const editorLines = this.editor.render(safeWidth);
128
+ const availableRows = Math.max(3, Math.min(16, Math.floor(this.tui.terminal.rows * 0.75)));
129
+ const viewportRows = Math.max(0, availableRows - editorLines.length - 2);
130
+ const content = renderTranscript(snapshot, safeWidth, this.theme);
131
+ this.lastContentRows = content.length;
132
+ this.lastViewportRows = viewportRows;
133
+ if (this.followBottom) this.scrollOffset = this.maxScroll();
134
+ this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, this.maxScroll()));
135
+ const peerCount = snapshot.peers.length;
136
+ const header = truncateToWidth(
137
+ this.theme.fg(
138
+ "accent",
139
+ this.theme.bold(
140
+ `CHAT INPUT → ${sanitizeSingleLine(snapshot.room.label)} · ${peerCount === 0 ? "waiting for peers" : `${peerCount} direct peer${peerCount === 1 ? "" : "s"}`}`,
141
+ ),
142
+ ),
143
+ safeWidth,
144
+ );
145
+ const footer = truncateToWidth(
146
+ this.theme.fg(
147
+ this.messageStatus?.kind === "warning"
148
+ ? "warning"
149
+ : this.messageStatus?.kind === "success"
150
+ ? "success"
151
+ : "dim",
152
+ this.messageStatus?.text ??
153
+ "Enter sends · configured newline key inserts a line · Esc returns to Pi/LLM",
154
+ ),
155
+ safeWidth,
156
+ );
157
+ const lines = [
158
+ header,
159
+ ...content.slice(this.scrollOffset, this.scrollOffset + viewportRows),
160
+ footer,
161
+ ...editorLines,
162
+ ];
163
+ return lines.slice(-availableRows).map((line) => truncateToWidth(line, safeWidth));
164
+ }
165
+
166
+ handleInput(data: string): void {
167
+ if (this.finished) return;
168
+ if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
169
+ this.close();
170
+ return;
171
+ }
172
+ if (matchesKey(data, Key.pageUp)) {
173
+ this.scrollOffset = Math.max(0, this.scrollOffset - this.lastViewportRows);
174
+ this.followBottom = false;
175
+ this.tui.requestRender();
176
+ return;
177
+ }
178
+ if (matchesKey(data, Key.pageDown)) {
179
+ this.scrollOffset = Math.min(this.maxScroll(), this.scrollOffset + this.lastViewportRows);
180
+ this.followBottom = this.scrollOffset === this.maxScroll();
181
+ this.tui.requestRender();
182
+ return;
183
+ }
184
+ this.editor.handleInput(data);
185
+ this.tui.requestRender();
186
+ }
187
+
188
+ invalidate(): void {
189
+ this.editor.invalidate();
190
+ }
191
+
192
+ dispose(): void {
193
+ this.finish(false, false);
194
+ }
195
+
196
+ private maxScroll(): number {
197
+ return Math.max(0, this.lastContentRows - this.lastViewportRows);
198
+ }
199
+
200
+ private close(): void {
201
+ this.finish(true, true);
202
+ }
203
+
204
+ private finish(returnedToPi: boolean, closeHost: boolean): void {
205
+ if (this.finished) return;
206
+ this.finished = true;
207
+ this.removeAbort();
208
+ this.removeAbort = () => {};
209
+ this.unsubscribe();
210
+ this.options.setViewOpen(false);
211
+ if (returnedToPi) this.options.onReturnToPi();
212
+ if (closeHost) this.options.onClose();
213
+ }
214
+ }
215
+
216
+ function renderTranscript(snapshot: ChatSnapshot, width: number, theme: Theme): string[] {
217
+ if (snapshot.transcript.length === 0) {
218
+ const empty =
219
+ snapshot.peers.length === 0
220
+ ? "You are alone; waiting for peers."
221
+ : "No messages yet. Start the conversation below.";
222
+ return wrapTextWithAnsi(theme.fg("muted", empty), width);
223
+ }
224
+ const lines: string[] = [];
225
+ for (const entry of snapshot.transcript) {
226
+ const label = sanitizeSingleLine(entry.label);
227
+ const delivery =
228
+ entry.author === "local" && entry.delivery === "not-delivered"
229
+ ? " · not delivered"
230
+ : entry.author === "local" && entry.deliveredTo !== undefined
231
+ ? ` · broadcast to ${entry.deliveredTo}`
232
+ : "";
233
+ lines.push(...wrapTextWithAnsi(theme.fg("accent", `${label}${delivery}`), width));
234
+ for (const rawLine of sanitizeChatText(entry.text).split("\n")) {
235
+ for (const line of hardWrapExact(rawLine, Math.max(1, width - 2))) {
236
+ lines.push(truncateToWidth(` ${line}`, width));
237
+ }
238
+ }
239
+ }
240
+ return lines;
241
+ }
242
+
243
+ function hardWrapExact(value: string, width: number): string[] {
244
+ if (!value) return [" "];
245
+ const columns = visibleWidth(value);
246
+ const lines: string[] = [];
247
+ for (let column = 0; column < columns; column += width) {
248
+ lines.push(sliceByColumn(value, column, width));
249
+ }
250
+ return lines.length > 0 ? lines : [" "];
251
+ }
252
+
253
+ function safeDisplayError(error: unknown): string {
254
+ const message = error instanceof Error ? error.message : String(error);
255
+ return sanitizeSingleLine(message).slice(0, 200);
256
+ }