@linxiraos/pi-tui 1.4.12 → 1.5.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.
Files changed (94) hide show
  1. package/CHANGELOG.md +31 -44
  2. package/dist/types/chat/messages.d.ts +2 -0
  3. package/dist/types/chat/spotlight.d.ts +8 -3
  4. package/dist/types/chat/transcript-render-helpers.d.ts +5 -0
  5. package/dist/types/components/editor.d.ts +4 -1
  6. package/dist/types/hotkeys-markdown.d.ts +2 -0
  7. package/dist/types/html-form/data.d.ts +56 -0
  8. package/dist/types/html-form/dialog.d.ts +51 -0
  9. package/dist/types/html-form/media.d.ts +28 -0
  10. package/dist/types/html-form/paginate.d.ts +43 -0
  11. package/dist/types/html-form/parse.d.ts +99 -0
  12. package/dist/types/overlays/ask-dialog.d.ts +11 -6
  13. package/dist/types/overlays/copy-targets.d.ts +8 -6
  14. package/dist/types/overlays/hook-editor.d.ts +3 -1
  15. package/dist/types/overlays/hub-frame.d.ts +2 -0
  16. package/dist/types/overlays/model-hub.d.ts +2 -0
  17. package/dist/types/overlays/team-hub.d.ts +150 -0
  18. package/dist/types/render/row-moves.d.ts +41 -0
  19. package/dist/types/status-line/component.d.ts +5 -0
  20. package/dist/types/status-line/host.d.ts +2 -2
  21. package/dist/types/status-line/schema.d.ts +1 -1
  22. package/dist/types/status-line/types.d.ts +8 -0
  23. package/dist/types/tools/ask.d.ts +11 -49
  24. package/dist/types/tools/autoresearch.d.ts +2 -2
  25. package/dist/types/tools/eval.d.ts +4 -0
  26. package/dist/types/tools/grouped-file-output.d.ts +2 -0
  27. package/dist/types/tools/shell-viz.d.ts +6 -2
  28. package/dist/types/tools/xd-url.d.ts +6 -0
  29. package/dist/types/windows-input-mode.d.ts +8 -0
  30. package/package.json +9 -9
  31. package/src/charts/table-data.ts +18 -5
  32. package/src/chat/chat-transcript-builder.ts +27 -10
  33. package/src/chat/image-loading.ts +55 -0
  34. package/src/chat/messages.d.ts +2 -0
  35. package/src/chat/messages.ts +3 -0
  36. package/src/chat/spotlight.d.ts +8 -3
  37. package/src/chat/spotlight.ts +23 -11
  38. package/src/chat/tool-execution.ts +5 -0
  39. package/src/chat/transcript-render-helpers.d.ts +5 -0
  40. package/src/chat/transcript-render-helpers.ts +13 -0
  41. package/src/chrome/transcript-container.ts +1 -1
  42. package/src/components/editor.d.ts +4 -1
  43. package/src/components/editor.ts +3 -2
  44. package/src/components/markdown.ts +70 -12
  45. package/src/hotkeys-markdown.ts +5 -1
  46. package/src/html-form/data.d.ts +56 -0
  47. package/src/html-form/data.ts +177 -0
  48. package/src/html-form/dialog.ts +1450 -0
  49. package/src/html-form/media.ts +105 -0
  50. package/src/html-form/paginate.ts +99 -0
  51. package/src/html-form/parse.d.ts +99 -0
  52. package/src/html-form/parse.ts +568 -0
  53. package/src/lang-from-path.ts +1 -0
  54. package/src/latex-block.ts +3 -3
  55. package/src/latex-to-unicode.ts +18 -5
  56. package/src/overlays/ask-dialog.ts +69 -52
  57. package/src/overlays/copy-targets.d.ts +8 -6
  58. package/src/overlays/copy-targets.ts +25 -46
  59. package/src/overlays/hook-editor.ts +16 -15
  60. package/src/overlays/hub-frame.ts +8 -1
  61. package/src/overlays/model-hub.ts +12 -2
  62. package/src/overlays/spotlight-sheet.ts +18 -18
  63. package/src/overlays/team-hub.ts +901 -0
  64. package/src/render/row-moves.d.ts +41 -0
  65. package/src/render/row-moves.ts +109 -0
  66. package/src/setup/wizard-overlay.ts +7 -3
  67. package/src/status-line/component.ts +19 -0
  68. package/src/status-line/footer.ts +2 -2
  69. package/src/status-line/host.ts +2 -2
  70. package/src/status-line/presets.ts +6 -6
  71. package/src/status-line/schema.ts +2 -1
  72. package/src/status-line/segments.ts +31 -4
  73. package/src/status-line/startup.ts +1 -1
  74. package/src/status-line/types.ts +8 -0
  75. package/src/stdin-buffer.ts +15 -1
  76. package/src/terminal-capabilities.ts +12 -3
  77. package/src/terminal.ts +41 -3
  78. package/src/tools/ask.d.ts +11 -49
  79. package/src/tools/ask.ts +201 -606
  80. package/src/tools/autoresearch.ts +2 -2
  81. package/src/tools/debug.ts +31 -38
  82. package/src/tools/eval.d.ts +4 -0
  83. package/src/tools/eval.ts +4 -0
  84. package/src/tools/grep.ts +38 -16
  85. package/src/tools/grouped-file-output.d.ts +2 -0
  86. package/src/tools/grouped-file-output.ts +5 -0
  87. package/src/tools/shell-viz-render.ts +37 -6
  88. package/src/tools/shell-viz.d.ts +6 -2
  89. package/src/tools/shell-viz.ts +19 -6
  90. package/src/tools/xd-url.d.ts +6 -0
  91. package/src/tools/xd-url.ts +19 -1
  92. package/src/tui.ts +129 -1
  93. package/src/windows-input-mode.d.ts +8 -0
  94. package/src/windows-input-mode.ts +13 -0
@@ -0,0 +1,901 @@
1
+ /**
2
+ * Team Hub overlay: the TUI surface for a Team.
3
+ *
4
+ * It is a UI, not an Agent: no team-root session, no AGENTS.md, no transcript.
5
+ * The left pane lists database rooms and the PM/engineer roster; the right pane
6
+ * shows one room's ordered `room_events` (or the selected engineer's real
7
+ * worktrees). Posting writes a room event through the same database service the
8
+ * CLI uses. Missing data stays honest: an empty team shows no invented rooms,
9
+ * agents, or statuses.
10
+ */
11
+
12
+ import { Input } from "../components/input";
13
+ import { HubFrame, type SidebarEntry, type SidebarStyle } from "./hub-frame";
14
+ import { matchesSelectDown, matchesSelectUp } from "../keybinding-matchers";
15
+ import { formatKeyHint, formatKeyHints } from "../app-keybindings";
16
+ import { matchesKey } from "../keys";
17
+ import { theme } from "../theme/theme";
18
+ import { padding, replaceTabs, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "../utils";
19
+ import type { Component } from "../tui";
20
+ import type { TUI } from "../tui";
21
+
22
+ // ── Data contract (the coding-agent builds this from the real Team DB) ──────
23
+
24
+ export type TeamHubRoomKind = "pm" | "coordination" | "room";
25
+
26
+ export interface TeamHubRoom {
27
+ id: string;
28
+ name: string;
29
+ kind: TeamHubRoomKind;
30
+ pmId: string | null;
31
+ pmName: string | null;
32
+ memberCount: number;
33
+ /** Latest host-assigned event sequence, or null for a room with no events. */
34
+ lastSeq: number | null;
35
+ lastSentAt: number | null;
36
+ }
37
+
38
+ export interface TeamHubMember {
39
+ agentId: string;
40
+ role: string;
41
+ /** Display label resolved from a real PM/engineer row, never an absolute path. */
42
+ label: string;
43
+ }
44
+
45
+ export interface TeamHubEvent {
46
+ seq: number;
47
+ /** Unix seconds, assigned by the host. */
48
+ sentAt: number;
49
+ senderAgentId: string;
50
+ senderLabel: string;
51
+ kind: string;
52
+ body: string;
53
+ replyTo: number | null;
54
+ }
55
+
56
+ export interface TeamHubRoomView {
57
+ room: TeamHubRoom;
58
+ members: TeamHubMember[];
59
+ events: TeamHubEvent[];
60
+ }
61
+
62
+ export interface TeamHubWorktree {
63
+ id: string;
64
+ kind: "home" | "task";
65
+ name: string;
66
+ branch: string;
67
+ path: string;
68
+ }
69
+
70
+ export interface TeamHubPm {
71
+ id: string;
72
+ name: string;
73
+ engineerCount: number;
74
+ }
75
+
76
+ export interface TeamHubEngineer {
77
+ id: string;
78
+ name: string;
79
+ pmId: string;
80
+ pmName: string;
81
+ execution: "normal" | "vibe";
82
+ worktrees: TeamHubWorktree[];
83
+ }
84
+
85
+ export interface TeamHubSnapshot {
86
+ teamId: string;
87
+ teamName: string;
88
+ /** False when the marker exists but the global Team database has no team row. */
89
+ dbAvailable: boolean;
90
+ /** Honest explanation (missing DB row, requested room gone, …). */
91
+ warning?: string;
92
+ pms: TeamHubPm[];
93
+ engineers: TeamHubEngineer[];
94
+ rooms: TeamHubRoom[];
95
+ selectedRoom: TeamHubRoomView | null;
96
+ }
97
+
98
+ /** What the overlay needs from the host; the coding-agent supplies real DB I/O. */
99
+ export interface TeamHubDataSource {
100
+ load(options?: { room?: string; preferPmId?: string }): Promise<TeamHubSnapshot>;
101
+ post(input: { room: string; body: string; sender?: string }): Promise<{ seq: number }>;
102
+ }
103
+
104
+ export interface TeamHubDeps {
105
+ source: TeamHubDataSource;
106
+ onDone: () => void;
107
+ requestRender: () => void;
108
+ /** TUI handle for terminal height and input focus; tests may omit it. */
109
+ ui?: TUI;
110
+ /** Focus the Hub on this PM on first load (a PM-root launch). */
111
+ initialPmId?: string;
112
+ /** Open Agent Hub (subagent control stays there); omitted in a standalone Hub. */
113
+ openAgentHub?: () => void;
114
+ }
115
+
116
+ // ── Pure helpers (tested directly, no terminal) ─────────────────────────────
117
+
118
+ export type TeamHubEntryKind = "separator" | "label" | "room" | "pm" | "engineer";
119
+
120
+ export interface TeamHubSidebarEntry extends SidebarEntry<TeamHubEntryKind> {
121
+ roomName?: string;
122
+ agentId?: string;
123
+ pmId?: string;
124
+ }
125
+
126
+ const ROOM_KIND_LABEL: Record<TeamHubRoomKind, string> = {
127
+ pm: "PM",
128
+ coordination: "shared",
129
+ room: "custom",
130
+ };
131
+
132
+ /** Rooms in display order: shared first, then PM rooms, then arbitrary rooms. */
133
+ export function sortTeamHubRooms(rooms: readonly TeamHubRoom[]): TeamHubRoom[] {
134
+ const rank: Record<TeamHubRoomKind, number> = { coordination: 0, pm: 1, room: 2 };
135
+ return [...rooms].sort((left, right) => {
136
+ const byKind = rank[left.kind] - rank[right.kind];
137
+ return byKind !== 0 ? byKind : left.name.localeCompare(right.name);
138
+ });
139
+ }
140
+
141
+ /** Events are always displayed in ascending host `seq` order. */
142
+ export function orderTeamHubEvents(events: readonly TeamHubEvent[]): TeamHubEvent[] {
143
+ return [...events].sort((left, right) => left.seq - right.seq);
144
+ }
145
+
146
+ /** New events since this Hub opened (or since the room was last viewed). */
147
+ export function teamHubUnread(room: TeamHubRoom, baseline: ReadonlyMap<string, number>): number {
148
+ const seen = baseline.get(room.id);
149
+ if (room.lastSeq === null || seen === undefined) return 0;
150
+ return Math.max(0, room.lastSeq - seen);
151
+ }
152
+
153
+ function roomAnnotation(room: TeamHubRoom, unread: number): string {
154
+ const kind = ROOM_KIND_LABEL[room.kind];
155
+ const owner = room.kind === "pm" && room.pmName ? ` ${room.pmName}` : "";
156
+ const members = `${room.memberCount} member${room.memberCount === 1 ? "" : "s"}`;
157
+ const last = room.lastSeq === null ? "no events" : `#${room.lastSeq}`;
158
+ const unreadSuffix = unread > 0 ? ` +${unread}` : "";
159
+ return `${kind}${owner} · ${members} · ${last}${unreadSuffix}`;
160
+ }
161
+
162
+ function engineerAnnotation(engineer: TeamHubEngineer): string {
163
+ const worktrees = engineer.worktrees.length;
164
+ const wt = worktrees === 0 ? "no worktree" : `${worktrees} wt`;
165
+ return `${engineer.execution} · ${wt}`;
166
+ }
167
+
168
+ /**
169
+ * Flatten the snapshot into sidebar rows. A filter matches room/agent labels and
170
+ * annotations; section labels disappear while filtering so only matches remain.
171
+ */
172
+ export function buildTeamHubEntries(
173
+ snapshot: TeamHubSnapshot | undefined,
174
+ filter = "",
175
+ baseline: ReadonlyMap<string, number> = new Map(),
176
+ ): TeamHubSidebarEntry[] {
177
+ if (!snapshot) return [];
178
+ const query = filter.trim().toLowerCase();
179
+ const matches = (label: string, annotation: string): boolean =>
180
+ query.length === 0 || `${label} ${annotation}`.toLowerCase().includes(query);
181
+
182
+ const entries: TeamHubSidebarEntry[] = [];
183
+ const rooms = sortTeamHubRooms(snapshot.rooms).filter(room =>
184
+ matches(`#${room.name}`, roomAnnotation(room, teamHubUnread(room, baseline))),
185
+ );
186
+ if (rooms.length > 0) {
187
+ if (!query) entries.push({ id: "label:rooms", kind: "label", label: "ROOMS" });
188
+ for (const room of rooms) {
189
+ entries.push({
190
+ id: `room:${room.name}`,
191
+ kind: "room",
192
+ label: `#${room.name}`,
193
+ annotation: roomAnnotation(room, teamHubUnread(room, baseline)),
194
+ roomName: room.name,
195
+ });
196
+ }
197
+ }
198
+
199
+ const pms = snapshot.pms
200
+ .slice()
201
+ .sort((left, right) => left.name.localeCompare(right.name))
202
+ .filter(pm => {
203
+ const engineers = snapshot.engineers.filter(engineer => engineer.pmId === pm.id);
204
+ const annotation = `${pm.engineerCount} engineers`;
205
+ return (
206
+ matches(`PM ${pm.name}`, annotation) ||
207
+ engineers.some(engineer => matches(engineer.name, engineerAnnotation(engineer)))
208
+ );
209
+ });
210
+ if (pms.length > 0) {
211
+ if (!query) entries.push({ id: "label:people", kind: "label", label: "PMS & ENGINEERS" });
212
+ for (const pm of pms) {
213
+ entries.push({
214
+ id: `pm:${pm.id}`,
215
+ kind: "pm",
216
+ label: `PM ${pm.name}`,
217
+ annotation: `${pm.engineerCount} engineers`,
218
+ pmId: pm.id,
219
+ agentId: pm.id,
220
+ });
221
+ for (const engineer of snapshot.engineers
222
+ .filter(row => row.pmId === pm.id)
223
+ .sort((left, right) => left.name.localeCompare(right.name))) {
224
+ const annotation = engineerAnnotation(engineer);
225
+ if (!matches(engineer.name, annotation)) continue;
226
+ entries.push({
227
+ id: `engineer:${engineer.id}`,
228
+ kind: "engineer",
229
+ label: ` ${engineer.name}`,
230
+ annotation,
231
+ pmId: pm.id,
232
+ agentId: engineer.id,
233
+ });
234
+ }
235
+ }
236
+ }
237
+ return entries;
238
+ }
239
+
240
+ /** Move the selection by `delta`, skipping section labels and separators. */
241
+ export function moveTeamHubSelection(
242
+ entries: readonly TeamHubSidebarEntry[],
243
+ currentId: string | undefined,
244
+ delta: number,
245
+ ): string | undefined {
246
+ const selectable = entries.filter(entry => entry.kind !== "label" && entry.kind !== "separator");
247
+ if (selectable.length === 0) return undefined;
248
+ let index = selectable.findIndex(entry => entry.id === currentId);
249
+ if (index < 0) index = delta >= 0 ? -1 : 0;
250
+ const next = (index + delta + selectable.length * 2) % selectable.length;
251
+ return selectable[next]?.id;
252
+ }
253
+
254
+ /** First room of a scope, used by `g` (shared) and PM-focused launches. */
255
+ export function selectTeamHubRoom(
256
+ rooms: readonly TeamHubRoom[],
257
+ scope: "shared" | "pm",
258
+ pmId?: string,
259
+ ): TeamHubRoom | undefined {
260
+ const ordered = sortTeamHubRooms(rooms);
261
+ if (scope === "shared") {
262
+ return ordered.find(room => room.kind === "coordination") ?? ordered.find(room => room.kind === "room");
263
+ }
264
+ if (pmId) {
265
+ const owned = ordered.filter(room => room.pmId === pmId);
266
+ if (owned.length > 0) return owned[0];
267
+ }
268
+ return ordered.find(room => room.kind === "pm");
269
+ }
270
+
271
+ /** `p`: the next room owned by `pmId`, wrapping; undefined when the PM owns none. */
272
+ export function nextTeamHubPmRoom(
273
+ rooms: readonly TeamHubRoom[],
274
+ currentRoom: string | undefined,
275
+ pmId: string | undefined,
276
+ ): TeamHubRoom | undefined {
277
+ const owned = sortTeamHubRooms(rooms).filter(room => (pmId ? room.pmId === pmId : room.kind === "pm"));
278
+ if (owned.length === 0) return undefined;
279
+ const index = owned.findIndex(room => room.name === currentRoom);
280
+ return owned[(index + 1) % owned.length] ?? owned[0];
281
+ }
282
+
283
+ /** Filter room events for `/` (body, sender, kind, or sequence). */
284
+ export function filterTeamHubEvents(events: readonly TeamHubEvent[], filter: string): TeamHubEvent[] {
285
+ const query = filter.trim().toLowerCase();
286
+ if (!query) return [...events];
287
+ return events.filter(event => {
288
+ const haystack = `${event.seq} ${event.senderLabel} ${event.kind} ${event.body}`.toLowerCase();
289
+ return haystack.includes(query);
290
+ });
291
+ }
292
+
293
+ function pad2(value: number): string {
294
+ return value.toString().padStart(2, "0");
295
+ }
296
+
297
+ /** `HH:MM` for today, `MM-DD HH:MM` otherwise. Pure for tests. */
298
+ export function formatTeamHubTime(sentAt: number, now: Date = new Date()): string {
299
+ const date = new Date(sentAt * 1000);
300
+ const clock = `${pad2(date.getHours())}:${pad2(date.getMinutes())}`;
301
+ const sameDay =
302
+ date.getFullYear() === now.getFullYear() &&
303
+ date.getMonth() === now.getMonth() &&
304
+ date.getDate() === now.getDate();
305
+ return sameDay ? clock : `${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${clock}`;
306
+ }
307
+
308
+ export interface TeamHubEventParts {
309
+ time: string;
310
+ sender: string;
311
+ reply: string | null;
312
+ body: string;
313
+ }
314
+
315
+ /** Plain single-line breakdown of an event; the renderer styles each part. */
316
+ export function describeTeamHubEvent(event: TeamHubEvent, now: Date = new Date()): TeamHubEventParts {
317
+ return {
318
+ time: formatTeamHubTime(event.sentAt, now),
319
+ sender: event.senderLabel,
320
+ reply: event.replyTo === null ? null : `↳#${event.replyTo}`,
321
+ body: event.body.replace(/[\r\n\t]+/g, " ").trim(),
322
+ };
323
+ }
324
+
325
+ /** Width-aware plain text for one event (used by tests and non-themed hosts). */
326
+ export function formatTeamHubEvent(event: TeamHubEvent, width: number, now: Date = new Date()): string[] {
327
+ const parts = describeTeamHubEvent(event, now);
328
+ const head = `${parts.time} ${parts.sender}${parts.reply ? ` ${parts.reply}` : ""} `;
329
+ const bodyWidth = Math.max(8, width - visibleWidth(head));
330
+ return wrapTextWithAnsi(parts.body || "(empty)", bodyWidth).map((line, index) =>
331
+ index === 0 ? `${head}${line}` : `${padding(visibleWidth(head))}${line}`,
332
+ );
333
+ }
334
+
335
+ // ── Component ───────────────────────────────────────────────────────────────
336
+
337
+ type HubFocus = "roster" | "events" | "composer";
338
+
339
+ function filterInput(): Input {
340
+ const input = new Input();
341
+ input.prompt = "";
342
+ return input;
343
+ }
344
+
345
+ export class TeamHubOverlayComponent implements Component {
346
+ readonly #deps: TeamHubDeps;
347
+ readonly #frame: HubFrame;
348
+ readonly #filter = filterInput();
349
+ #snapshot: TeamHubSnapshot | undefined;
350
+ #entries: TeamHubSidebarEntry[] = [];
351
+ #selectedId: string | undefined;
352
+ #focus: HubFocus = "roster";
353
+ #filterEditing = false;
354
+ #loading = false;
355
+ #error: string | undefined;
356
+ #warning: string | undefined;
357
+ #notice: string | undefined;
358
+ #composer: Input | undefined;
359
+ #composerRoom: string | undefined;
360
+ #senderIndex = 0;
361
+ #detailAgentId: string | undefined;
362
+ #focusedPmId: string | undefined;
363
+ #baseline = new Map<string, number>();
364
+ #eventScroll = 0;
365
+ #generation = 0;
366
+ #disposed = false;
367
+ #lastLoad: Promise<void> = Promise.resolve();
368
+
369
+ constructor(deps: TeamHubDeps) {
370
+ this.#deps = deps;
371
+ this.#focusedPmId = deps.initialPmId;
372
+ this.#frame = new HubFrame(
373
+ "Team Hub",
374
+ { min: 28, max: 46 },
375
+ (width, rows) => this.#renderSidebar(width, rows),
376
+ (width, height) => this.#renderBody(width, height),
377
+ { bodyMinWidth: 30 },
378
+ );
379
+ void this.#reload();
380
+ }
381
+
382
+ /** Resolves after the latest database read settles (initial load or refresh). */
383
+ get ready(): Promise<void> {
384
+ return this.#lastLoad;
385
+ }
386
+
387
+ dispose(): void {
388
+ this.#disposed = true;
389
+ this.#generation++;
390
+ }
391
+
392
+ invalidate(): void {
393
+ this.#frame.invalidate();
394
+ }
395
+
396
+ // ── data ────────────────────────────────────────────────────────────────
397
+
398
+ #currentRoomName(): string | undefined {
399
+ return this.#snapshot?.selectedRoom?.room.name;
400
+ }
401
+
402
+ #selectedEntry(): TeamHubSidebarEntry | undefined {
403
+ return this.#entries.find(entry => entry.id === this.#selectedId);
404
+ }
405
+
406
+ #selectedRoom(): TeamHubRoomView | undefined {
407
+ return this.#snapshot?.selectedRoom ?? undefined;
408
+ }
409
+
410
+ #reload(roomName?: string): Promise<void> {
411
+ const promise = this.#load(roomName);
412
+ this.#lastLoad = promise;
413
+ return promise;
414
+ }
415
+
416
+ async #load(roomName?: string): Promise<void> {
417
+ if (this.#disposed) return;
418
+ const generation = ++this.#generation;
419
+ this.#loading = true;
420
+ this.#error = undefined;
421
+ this.#warning = undefined;
422
+ this.#requestRender();
423
+ try {
424
+ const snapshot = await this.#deps.source.load({
425
+ room: roomName ?? this.#currentRoomName(),
426
+ preferPmId: this.#focusedPmId ?? this.#deps.initialPmId,
427
+ });
428
+ if (this.#disposed || generation !== this.#generation) return;
429
+ this.#snapshot = snapshot;
430
+ this.#warning = snapshot.warning;
431
+ this.#frame.setTitle(`Team Hub · ${snapshot.teamName}`);
432
+ this.#initializeBaseline(snapshot);
433
+ this.#markSelectedRoomSeen();
434
+ this.#entries = buildTeamHubEntries(snapshot, this.#filter.getValue(), this.#baseline);
435
+ this.#ensureSelection();
436
+ } catch (error) {
437
+ if (this.#disposed || generation !== this.#generation) return;
438
+ this.#error = error instanceof Error ? error.message : String(error);
439
+ } finally {
440
+ if (!this.#disposed && generation === this.#generation) {
441
+ this.#loading = false;
442
+ this.#requestRender();
443
+ }
444
+ }
445
+ }
446
+
447
+ /** Existing events are the baseline; only events arriving while the Hub is open read as new. */
448
+ #initializeBaseline(snapshot: TeamHubSnapshot): void {
449
+ for (const room of snapshot.rooms) {
450
+ if (!this.#baseline.has(room.id)) this.#baseline.set(room.id, room.lastSeq ?? 0);
451
+ }
452
+ }
453
+
454
+ #markSelectedRoomSeen(): void {
455
+ const room = this.#selectedRoom()?.room;
456
+ if (room && room.lastSeq !== null) this.#baseline.set(room.id, room.lastSeq);
457
+ }
458
+
459
+ #ensureSelection(): void {
460
+ if (this.#selectedId && this.#entries.some(entry => entry.id === this.#selectedId)) return;
461
+ const selectedRoom = this.#snapshot?.selectedRoom?.room;
462
+ if (selectedRoom) {
463
+ const id = `room:${selectedRoom.name}`;
464
+ if (this.#entries.some(entry => entry.id === id)) {
465
+ this.#selectedId = id;
466
+ return;
467
+ }
468
+ }
469
+ const first = this.#entries.find(entry => entry.kind !== "label" && entry.kind !== "separator");
470
+ this.#selectedId = first?.id;
471
+ }
472
+
473
+ #select(id: string | undefined): void {
474
+ if (!id || id === this.#selectedId) {
475
+ this.#requestRender();
476
+ return;
477
+ }
478
+ this.#selectedId = id;
479
+ const entry = this.#selectedEntry();
480
+ this.#eventScroll = 0;
481
+ if (entry?.kind === "room") {
482
+ this.#detailAgentId = undefined;
483
+ if (entry.roomName && entry.roomName !== this.#currentRoomName()) {
484
+ void this.#reload(entry.roomName);
485
+ } else {
486
+ this.#markSelectedRoomSeen();
487
+ }
488
+ } else if (entry?.kind === "engineer") {
489
+ this.#detailAgentId = entry.agentId;
490
+ if (entry.pmId) this.#focusedPmId = entry.pmId;
491
+ } else if (entry?.kind === "pm") {
492
+ this.#detailAgentId = undefined;
493
+ this.#focusedPmId = entry.pmId;
494
+ }
495
+ this.#requestRender();
496
+ }
497
+
498
+ #requestRender(): void {
499
+ this.#deps.requestRender();
500
+ }
501
+
502
+ #terminalRows(): number {
503
+ return this.#deps.ui?.terminal?.rows || process.stdout.rows || 40;
504
+ }
505
+
506
+ // ── input ───────────────────────────────────────────────────────────────
507
+
508
+ handleInput(data: string): void {
509
+ if (this.#filterEditing) {
510
+ this.#handleFilterInput(data);
511
+ return;
512
+ }
513
+ if (this.#composer) {
514
+ this.#handleComposerInput(data);
515
+ return;
516
+ }
517
+
518
+ if (matchesKey(data, "escape")) {
519
+ if (this.#filter.getValue()) {
520
+ this.#clearFilter();
521
+ return;
522
+ }
523
+ if (this.#focus === "events") {
524
+ this.#focus = "roster";
525
+ this.#requestRender();
526
+ return;
527
+ }
528
+ if (this.#detailAgentId) {
529
+ this.#detailAgentId = undefined;
530
+ this.#requestRender();
531
+ return;
532
+ }
533
+ this.#deps.onDone();
534
+ return;
535
+ }
536
+ if (matchesKey(data, "tab")) {
537
+ this.#focus = this.#focus === "roster" ? "events" : "roster";
538
+ this.#requestRender();
539
+ return;
540
+ }
541
+ if (matchesKey(data, "left") || data === "h") {
542
+ this.#focus = "roster";
543
+ this.#requestRender();
544
+ return;
545
+ }
546
+ if (matchesKey(data, "right") || data === "l") {
547
+ this.#focus = "events";
548
+ this.#requestRender();
549
+ return;
550
+ }
551
+ if (data === "j" || matchesSelectDown(data)) {
552
+ if (this.#focus === "roster") {
553
+ this.#select(moveTeamHubSelection(this.#entries, this.#selectedId, 1));
554
+ } else {
555
+ this.#scrollEvents(1);
556
+ }
557
+ return;
558
+ }
559
+ if (data === "k" || matchesSelectUp(data)) {
560
+ if (this.#focus === "roster") {
561
+ this.#select(moveTeamHubSelection(this.#entries, this.#selectedId, -1));
562
+ } else {
563
+ this.#scrollEvents(-1);
564
+ }
565
+ return;
566
+ }
567
+ if (matchesKey(data, "pageUp")) {
568
+ this.#scrollEvents(5);
569
+ return;
570
+ }
571
+ if (matchesKey(data, "pageDown")) {
572
+ this.#scrollEvents(-5);
573
+ return;
574
+ }
575
+ if (matchesKey(data, "enter") || data === "\r" || data === "\n") {
576
+ const entry = this.#selectedEntry();
577
+ if (entry?.kind === "room") {
578
+ this.#focus = "events";
579
+ this.#markSelectedRoomSeen();
580
+ this.#entries = buildTeamHubEntries(this.#snapshot, this.#filter.getValue(), this.#baseline);
581
+ this.#requestRender();
582
+ } else if (entry?.kind === "engineer") {
583
+ this.#focus = "events";
584
+ this.#detailAgentId = entry.agentId;
585
+ this.#requestRender();
586
+ }
587
+ return;
588
+ }
589
+ if (data === "g") {
590
+ const room = this.#snapshot ? selectTeamHubRoom(this.#snapshot.rooms, "shared") : undefined;
591
+ if (room) this.#select(`room:${room.name}`);
592
+ else this.#setNotice("No shared coordination room exists in this team.");
593
+ return;
594
+ }
595
+ if (data === "p") {
596
+ const pmId = this.#focusedPmId ?? this.#selectedRoom()?.room.pmId ?? this.#snapshot?.pms[0]?.id;
597
+ const room = this.#snapshot
598
+ ? nextTeamHubPmRoom(this.#snapshot.rooms, this.#selectedRoom()?.room.name, pmId)
599
+ : undefined;
600
+ if (room) this.#select(`room:${room.name}`);
601
+ else this.#setNotice(pmId ? `PM "${pmId}" owns no room.` : "No PM rooms exist in this team.");
602
+ return;
603
+ }
604
+ if (data === "s") {
605
+ this.#openComposer();
606
+ return;
607
+ }
608
+ if (data === "a") {
609
+ if (this.#deps.openAgentHub) this.#deps.openAgentHub();
610
+ else this.#setNotice("Agent Hub is available inside a coding session; this Hub is standalone.");
611
+ return;
612
+ }
613
+ if (data === "r") {
614
+ this.#notice = undefined;
615
+ void this.#reload(this.#currentRoomName());
616
+ return;
617
+ }
618
+ if (data === "/") {
619
+ this.#filterEditing = true;
620
+ this.#requestRender();
621
+ return;
622
+ }
623
+ }
624
+
625
+ #setNotice(message: string): void {
626
+ this.#notice = message;
627
+ this.#requestRender();
628
+ }
629
+
630
+ #scrollEvents(delta: number): void {
631
+ this.#eventScroll = Math.max(0, this.#eventScroll + delta);
632
+ this.#requestRender();
633
+ }
634
+
635
+ // ── filter ──────────────────────────────────────────────────────────────
636
+
637
+ #handleFilterInput(data: string): void {
638
+ if (matchesKey(data, "escape")) {
639
+ this.#clearFilter();
640
+ return;
641
+ }
642
+ if (matchesKey(data, "enter") || data === "\r" || data === "\n") {
643
+ this.#filterEditing = false;
644
+ this.#requestRender();
645
+ return;
646
+ }
647
+ this.#filter.handleInput(data);
648
+ this.#entries = buildTeamHubEntries(this.#snapshot, this.#filter.getValue(), this.#baseline);
649
+ this.#ensureSelection();
650
+ this.#requestRender();
651
+ }
652
+
653
+ #clearFilter(): void {
654
+ this.#filter.setValue("");
655
+ this.#filterEditing = false;
656
+ this.#entries = buildTeamHubEntries(this.#snapshot, "", this.#baseline);
657
+ this.#ensureSelection();
658
+ this.#requestRender();
659
+ }
660
+
661
+ // ── composer ────────────────────────────────────────────────────────────
662
+
663
+ #openComposer(): void {
664
+ if (this.#detailAgentId) {
665
+ this.#setNotice("Select a room first, then press s to post.");
666
+ return;
667
+ }
668
+ const room = this.#selectedRoom();
669
+ if (!room) {
670
+ this.#setNotice("Select a room first, then press s to post.");
671
+ return;
672
+ }
673
+ if (room.members.length === 0) {
674
+ this.#setNotice(`Room "#${room.room.name}" has no members; add a member before posting.`);
675
+ return;
676
+ }
677
+ this.#notice = undefined;
678
+ this.#composerRoom = room.room.name;
679
+ const ownerIndex = room.room.pmId ? room.members.findIndex(member => member.agentId === room.room.pmId) : -1;
680
+ const pmIndex = room.members.findIndex(member => member.role === "pm");
681
+ this.#senderIndex = ownerIndex >= 0 ? ownerIndex : pmIndex >= 0 ? pmIndex : 0;
682
+ const input = new Input();
683
+ input.prompt = "> ";
684
+ input.onSubmit = value => void this.#submit(value);
685
+ this.#composer = input;
686
+ this.#focus = "composer";
687
+ this.#requestRender();
688
+ }
689
+
690
+ #closeComposer(): void {
691
+ this.#composer = undefined;
692
+ this.#composerRoom = undefined;
693
+ this.#focus = "roster";
694
+ this.#requestRender();
695
+ }
696
+
697
+ #handleComposerInput(data: string): void {
698
+ if (matchesKey(data, "escape")) {
699
+ this.#closeComposer();
700
+ return;
701
+ }
702
+ if (matchesKey(data, "tab") || matchesKey(data, "shift+tab")) {
703
+ const room = this.#selectedRoom();
704
+ if (room && room.members.length > 0) {
705
+ const delta = matchesKey(data, "shift+tab") ? -1 : 1;
706
+ this.#senderIndex = (this.#senderIndex + delta + room.members.length) % room.members.length;
707
+ this.#requestRender();
708
+ }
709
+ return;
710
+ }
711
+ this.#composer?.handleInput(data);
712
+ this.#requestRender();
713
+ }
714
+
715
+ async #submit(value: string): Promise<void> {
716
+ const body = value.trim();
717
+ const room = this.#selectedRoom();
718
+ if (!room) return;
719
+ if (!body) {
720
+ this.#setNotice("Message body must not be empty.");
721
+ return;
722
+ }
723
+ const sender = room.members[this.#senderIndex];
724
+ if (!sender) {
725
+ this.#setNotice("Select a room member as the sender (Tab) before posting.");
726
+ return;
727
+ }
728
+ const roomName = this.#composerRoom ?? room.room.name;
729
+ try {
730
+ const result = await this.#deps.source.post({ room: roomName, body, sender: sender.agentId });
731
+ this.#notice = `Posted #${result.seq} to #${roomName} as ${sender.label}.`;
732
+ this.#closeComposer();
733
+ await this.#reload(roomName);
734
+ } catch (error) {
735
+ this.#setNotice(error instanceof Error ? error.message : String(error));
736
+ }
737
+ }
738
+
739
+ // ── render ──────────────────────────────────────────────────────────────
740
+
741
+ #renderSidebar(width: number, rows: number): string[] {
742
+ return this.#frame.renderSidebar(
743
+ this.#entries,
744
+ width,
745
+ rows,
746
+ {
747
+ id: this.#selectedId ?? "",
748
+ focused: this.#focus === "roster",
749
+ follow: true,
750
+ clamp: false,
751
+ },
752
+ entry => this.#sidebarStyle(entry),
753
+ );
754
+ }
755
+
756
+ #sidebarStyle(entry: TeamHubSidebarEntry): SidebarStyle {
757
+ switch (entry.kind) {
758
+ case "label":
759
+ return { icon: "", annotation: "", muted: true };
760
+ case "room":
761
+ return { icon: "", annotation: entry.annotation ?? "" };
762
+ case "pm":
763
+ return { icon: "◆", annotation: entry.annotation ?? "" };
764
+ case "engineer":
765
+ return { icon: "·", annotation: entry.annotation ?? "", muted: false };
766
+ default:
767
+ return { icon: "", annotation: "" };
768
+ }
769
+ }
770
+
771
+ #renderBody(width: number, height: number | undefined): readonly string[] {
772
+ const rows = Math.max(1, Math.floor(height ?? this.#terminalRows() - 4));
773
+ const lines: string[] = [];
774
+ const push = (line = ""): void => {
775
+ lines.push(truncateToWidth(replaceTabs(line), width));
776
+ };
777
+
778
+ if (this.#error) push(theme.fg("error", this.#error));
779
+ else if (this.#warning) push(theme.fg("warning", this.#warning));
780
+ else if (this.#notice) push(theme.fg("warning", this.#notice));
781
+ else if (this.#loading) push(theme.fg("dim", "Loading team data…"));
782
+ else push();
783
+
784
+ if (this.#filterEditing || this.#filter.getValue()) {
785
+ const prefix = theme.fg("dim", "filter: ");
786
+ const field = this.#filter.render(Math.max(1, width - visibleWidth(prefix)))[0] ?? "";
787
+ push(`${prefix}${field}`);
788
+ }
789
+
790
+ const reserved = this.#composer ? 3 : 0;
791
+ const available = Math.max(1, rows - lines.length - reserved);
792
+ const agent = this.#detailAgent();
793
+ if (agent) {
794
+ for (const line of this.#renderEngineer(agent, width)) push(line);
795
+ } else if (this.#snapshot?.selectedRoom) {
796
+ for (const line of this.#renderRoom(this.#snapshot.selectedRoom, width, available)) push(line);
797
+ } else if (this.#snapshot && this.#snapshot.rooms.length === 0) {
798
+ push(theme.fg("dim", "No rooms in this team yet."));
799
+ push(theme.fg("dim", "Create one: zetacode team room create <name> --pm <pm>"));
800
+ } else {
801
+ push(theme.fg("dim", "No room selected."));
802
+ }
803
+
804
+ if (this.#composer) {
805
+ const room = this.#selectedRoom();
806
+ const sender = room?.members[this.#senderIndex];
807
+ push("");
808
+ push(
809
+ `${theme.fg("dim", "to ")}#${this.#composerRoom ?? ""} ${theme.fg("dim", "from ")}${sender?.label ?? "—"}`,
810
+ );
811
+ push(this.#composer.render(width)[0] ?? "");
812
+ }
813
+
814
+ while (lines.length < rows) lines.push("");
815
+ return lines.slice(0, rows);
816
+ }
817
+
818
+ #detailAgent(): TeamHubEngineer | undefined {
819
+ if (!this.#detailAgentId) return undefined;
820
+ return this.#snapshot?.engineers.find(engineer => engineer.id === this.#detailAgentId);
821
+ }
822
+
823
+ #renderEngineer(engineer: TeamHubEngineer, width: number): string[] {
824
+ const lines: string[] = [];
825
+ lines.push(theme.bold(theme.fg("accent", engineer.name)));
826
+ lines.push(
827
+ `${theme.fg("dim", "PM:")} ${engineer.pmName} ${theme.fg("dim", "execution:")} ${engineer.execution}`,
828
+ );
829
+ if (engineer.worktrees.length === 0) {
830
+ lines.push(theme.fg("dim", "No registered worktree. Add one: zetacode team worktree add <task> …"));
831
+ return lines;
832
+ }
833
+ for (const worktree of engineer.worktrees) {
834
+ if (lines.length > 0) lines.push("");
835
+ lines.push(`${theme.bold(worktree.kind)} ${worktree.name}`);
836
+ lines.push(theme.fg("dim", `branch ${worktree.branch}`));
837
+ lines.push(truncateToWidth(worktree.path, width));
838
+ }
839
+ return lines;
840
+ }
841
+
842
+ #renderRoom(room: TeamHubRoomView, width: number, available: number): string[] {
843
+ const lines: string[] = [];
844
+ const title = `#${room.room.name}`;
845
+ const kind = ROOM_KIND_LABEL[room.room.kind];
846
+ const owner = room.room.kind === "pm" && room.room.pmName ? ` · PM ${room.room.pmName}` : "";
847
+ const last = room.room.lastSeq === null ? "no events" : `last #${room.room.lastSeq}`;
848
+ lines.push(
849
+ `${theme.bold(theme.fg("accent", title))} ${theme.fg("dim", `${kind}${owner} · ${room.room.memberCount} members · ${last}`)}`,
850
+ );
851
+ const members = room.members.length > 0 ? room.members.map(member => member.label).join(", ") : "no members";
852
+ lines.push(theme.fg("dim", `members: ${members}`));
853
+ lines.push("");
854
+
855
+ const filtered = filterTeamHubEvents(orderTeamHubEvents(room.events), this.#filter.getValue());
856
+ if (filtered.length === 0) {
857
+ lines.push(theme.fg("dim", room.events.length === 0 ? "No events yet." : "No events match the filter."));
858
+ return lines;
859
+ }
860
+ const eventLines = filtered.flatMap(event => this.#renderEvent(event, width));
861
+ const headerRows = lines.length;
862
+ const bodyRows = Math.max(1, available - headerRows);
863
+ const maxStart = Math.max(0, eventLines.length - bodyRows);
864
+ const start = Math.max(0, maxStart - this.#eventScroll);
865
+ lines.push(...eventLines.slice(start, start + bodyRows));
866
+ return lines;
867
+ }
868
+
869
+ #renderEvent(event: TeamHubEvent, width: number): string[] {
870
+ const parts = describeTeamHubEvent(event);
871
+ const head = `${theme.fg("dim", parts.time)} ${theme.bold(theme.fg("accent", parts.sender))}${
872
+ parts.reply ? ` ${theme.fg("dim", parts.reply)}` : ""
873
+ } `;
874
+ const bodyWidth = Math.max(8, width - visibleWidth(head));
875
+ const body = wrapTextWithAnsi(parts.body || "(empty)", bodyWidth);
876
+ return body.map((line, index) => (index === 0 ? `${head}${line}` : `${padding(visibleWidth(head))}${line}`));
877
+ }
878
+
879
+ #renderFooter(width: number): string {
880
+ const filter = this.#filter.getValue() ? `/${this.#filter.getValue()} · ` : "";
881
+ const hint =
882
+ `${filter}${formatKeyHints(["j", "k"])}:select ${formatKeyHint("enter")}:open ${formatKeyHint("tab")}:pane ` +
883
+ `${formatKeyHint("g")}:shared ${formatKeyHint("p")}:PM ${formatKeyHint("s")}:send ` +
884
+ `${formatKeyHint("a")}:Agent Hub ${formatKeyHint("r")}:refresh /:filter ${formatKeyHint("escape")}:back`;
885
+ return theme.fg("dim", truncateToWidth(hint, Math.max(10, width)));
886
+ }
887
+
888
+ render(width: number): readonly string[] {
889
+ const termHeight = this.#terminalRows();
890
+ const frame = this.#frame.render(width, termHeight, this.#entries, this.#renderFooter(width - 4));
891
+ const lines = frame.map(line => truncateToWidth(line, width));
892
+ if (lines.length <= termHeight) return lines;
893
+ // Tiny terminals can fall below the fixed chrome floor; keep the title and
894
+ // the footer instead of spilling into scrollback.
895
+ const footerLines = Math.min(3, lines.length);
896
+ return [...lines.slice(0, Math.max(0, termHeight - footerLines)), ...lines.slice(-footerLines)].slice(
897
+ 0,
898
+ Math.max(1, termHeight),
899
+ );
900
+ }
901
+ }