@loka1/pi-orchestra 0.0.0-stage → 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,497 @@
1
+ /**
2
+ * Interactive browser for runs, tasks and workers.
3
+ *
4
+ * A pi widget cannot take keyboard focus, so navigation lives in
5
+ * `ctx.ui.custom()`. This module owns only the components; the command in
6
+ * `orchestra.ts` supplies items and performs the actions the component returns.
7
+ */
8
+
9
+ import { getSelectListTheme } from "@earendil-works/pi-coding-agent";
10
+ import { Key, SelectList, type SelectListTheme, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
11
+ import type { BrowseItem, BrowseScope, BrowseSort } from "../lib/format.ts";
12
+ import { shortId } from "../lib/format.ts";
13
+
14
+ export type BrowseResult =
15
+ | { kind: "close" }
16
+ | { kind: "open"; item: BrowseItem }
17
+ | { kind: "message"; item: BrowseItem }
18
+ | { kind: "stop"; item: BrowseItem }
19
+ | { kind: "stopMany"; items: BrowseItem[] }
20
+ | { kind: "retry"; items: BrowseItem[] }
21
+ | { kind: "copy"; items: BrowseItem[] }
22
+ | { kind: "follow"; item: BrowseItem }
23
+ | { kind: "log"; item: BrowseItem }
24
+ | { kind: "diff"; item: BrowseItem }
25
+ | { kind: "join"; item: BrowseItem }
26
+ | { kind: "useRun"; item: BrowseItem };
27
+
28
+ export interface BrowseSession {
29
+ scope: BrowseScope;
30
+ filter: string;
31
+ selectedId?: string;
32
+ sort?: BrowseSort;
33
+ /** Ids ticked with space, for bulk actions. */
34
+ marked?: string[];
35
+ }
36
+
37
+ export interface BrowseHooks {
38
+ items: (scope: BrowseScope, filter: string, sort: BrowseSort) => BrowseItem[];
39
+ title: () => string;
40
+ initial?: Partial<BrowseSession>;
41
+ /** Called once while mounted so the host can repaint the component on state changes. */
42
+ onMount?: (repaint: () => void) => void;
43
+ }
44
+
45
+ const SCOPES: BrowseScope[] = ["tasks", "workers", "runs"];
46
+
47
+ interface Theme {
48
+ fg: (color: string, text: string) => string;
49
+ bold: (text: string) => string;
50
+ }
51
+
52
+ /**
53
+ * Page/home/end keys, matched defensively: different terminals send different
54
+ * sequences, and a user keybinding may have moved the default action.
55
+ */
56
+ function navKey(
57
+ data: string,
58
+ keybindings: { matches(data: string, action: string): boolean },
59
+ ): "pageUp" | "pageDown" | "home" | "end" | undefined {
60
+ // CSI with modifiers: \x1b[5~, \x1b[5;2~, \x1b[5;5~ (ctrl), \x1b[[5~ …
61
+ if (keybindings.matches(data, "tui.select.pageUp") || matchesKey(data, Key.pageUp) || /^\x1b\[\[?5[;0-9]*~$/.test(data)) {
62
+ return "pageUp";
63
+ }
64
+ if (keybindings.matches(data, "tui.select.pageDown") || matchesKey(data, Key.pageDown) || /^\x1b\[\[?6[;0-9]*~$/.test(data)) {
65
+ return "pageDown";
66
+ }
67
+ if (
68
+ matchesKey(data, Key.home) ||
69
+ /^\x1b\[(H|1~|7~|1;\d+H|7;\d+~)$/.test(data)
70
+ ) {
71
+ return "home";
72
+ }
73
+ if (matchesKey(data, Key.end) || /^\x1b\[(F|4~|8~|1;\d+F|8;\d+~)$/.test(data)) {
74
+ return "end";
75
+ }
76
+ return undefined;
77
+ }
78
+
79
+ function statusColor(item: BrowseItem): string {
80
+ if (item.status === "question") return "warning";
81
+ if (item.status === "running" || item.status === "starting") return "accent";
82
+ if (item.status === "timeout" || item.status === "failed" || item.status === "lost") return "error";
83
+ if (item.status === "done" || item.status === "settled") return "success";
84
+ return "muted";
85
+ }
86
+
87
+ export function createBrowseComponent(
88
+ tui: { requestRender(force?: boolean): void; terminal: { rows: number; columns: number } },
89
+ theme: Theme,
90
+ keybindings: { matches(data: string, action: string): boolean },
91
+ done: (result: BrowseResult) => void,
92
+ hooks: BrowseHooks,
93
+ ) {
94
+ const session: BrowseSession = {
95
+ scope: hooks.initial?.scope ?? "tasks",
96
+ filter: hooks.initial?.filter ?? "",
97
+ selectedId: hooks.initial?.selectedId,
98
+ sort: hooks.initial?.sort ?? "priority",
99
+ marked: hooks.initial?.marked ?? [],
100
+ };
101
+ let marked = new Set<string>(session.marked ?? []);
102
+ const currentItems = () => hooks.items(session.scope, session.filter, session.sort ?? "priority");
103
+
104
+ let searching = false;
105
+ let list: SelectList | undefined;
106
+ let pageSize = 10;
107
+ let signature = "";
108
+ let cachedWidth = -1;
109
+ let cachedLines: string[] | undefined;
110
+ const invalidate = () => {
111
+ cachedWidth = -1;
112
+ cachedLines = undefined;
113
+ };
114
+
115
+ const repaintSoon = () => {
116
+ invalidate();
117
+ tui.requestRender();
118
+ };
119
+
120
+ hooks.onMount?.(repaintSoon);
121
+
122
+ function rebuild(force = false): SelectList {
123
+ const items = currentItems();
124
+ const nextSignature = `${session.scope}|${session.filter}|${session.sort}|${[...marked].sort().join(",")}|${items
125
+ .map((item) => `${item.id}:${item.status}`)
126
+ .join(",")}`;
127
+ if (list && !force && nextSignature === signature) return list;
128
+ signature = nextSignature;
129
+
130
+ const previous = list?.getSelectedItem()?.value ?? session.selectedId;
131
+ const maxVisible = Math.max(5, Math.min(20, (tui.terminal?.rows ?? 30) - 10));
132
+ pageSize = maxVisible;
133
+ const next = new SelectList(
134
+ items.map((item) => ({
135
+ value: item.id,
136
+ label: `${marked.has(item.id) ? "▣" : item.glyph} ${fitLabel(item.title)}`,
137
+ description: `${item.status}${item.meta ? ` · ${item.meta}` : ""}`,
138
+ })),
139
+ maxVisible,
140
+ getSelectListTheme() as SelectListTheme,
141
+ );
142
+ next.onSelect = (selected) => {
143
+ const item = items.find((candidate) => candidate.id === selected.value);
144
+ if (item) done({ kind: "open", item });
145
+ };
146
+ next.onCancel = () => done({ kind: "close" });
147
+ next.onSelectionChange = (selected) => {
148
+ session.selectedId = selected.value;
149
+ };
150
+ if (previous) {
151
+ const index = items.findIndex((item) => item.id === previous);
152
+ if (index >= 0) next.setSelectedIndex(index);
153
+ }
154
+ list = next;
155
+ return next;
156
+ }
157
+
158
+ function statusBar(): string {
159
+ const scope = SCOPES.map((value) => (value === session.scope ? theme.bold(value) : theme.fg("dim", value))).join(
160
+ theme.fg("dim", " · "),
161
+ );
162
+ const search = searching
163
+ ? theme.fg("accent", `search: ${session.filter || "…"}`)
164
+ : session.filter
165
+ ? theme.fg("accent", `filter: ${session.filter}`)
166
+ : theme.fg("dim", "/ search");
167
+ return `${scope} ${search}`;
168
+ }
169
+
170
+ function footer(): string {
171
+ const keys = searching
172
+ ? "type to filter · enter keep · esc clear"
173
+ : `↑↓ · ⏎ · j join · d log · D diff · space mark${marked.size ? `(${marked.size})` : ""} · x stop · r retry · c copy · s/t · tab · q`;
174
+ return theme.fg("dim", keys);
175
+ }
176
+
177
+ function handleInput(data: string): void {
178
+ const active = list ?? rebuild(true);
179
+
180
+ // Search mode owns printable input and backspace.
181
+ if (searching) {
182
+ if (keybindings.matches(data, "tui.select.cancel")) {
183
+ searching = false;
184
+ session.filter = "";
185
+ rebuild(true);
186
+ repaintSoon();
187
+ return;
188
+ }
189
+ if (keybindings.matches(data, "tui.select.confirm")) {
190
+ searching = false;
191
+ repaintSoon();
192
+ return;
193
+ }
194
+ if (matchesKey(data, Key.backspace)) {
195
+ session.filter = session.filter.slice(0, -1);
196
+ rebuild(true);
197
+ repaintSoon();
198
+ return;
199
+ }
200
+ if (data.length === 1 && data >= " " && data !== "\u001b") {
201
+ session.filter += data;
202
+ rebuild(true);
203
+ repaintSoon();
204
+ return;
205
+ }
206
+ return;
207
+ }
208
+
209
+ if (keybindings.matches(data, "tui.select.cancel")) {
210
+ if (session.filter) {
211
+ session.filter = "";
212
+ rebuild(true);
213
+ repaintSoon();
214
+ return;
215
+ }
216
+ done({ kind: "close" });
217
+ return;
218
+ }
219
+ if (keybindings.matches(data, "tui.select.confirm")) {
220
+ const selected = active.getSelectedItem();
221
+ if (!selected) return;
222
+ const item = currentItems().find((candidate) => candidate.id === selected.value);
223
+ if (item) done({ kind: "open", item });
224
+ return;
225
+ }
226
+ if (matchesKey(data, Key.tab)) {
227
+ const index = SCOPES.indexOf(session.scope);
228
+ session.scope = SCOPES[(index + 1) % SCOPES.length] as BrowseScope;
229
+ rebuild(true);
230
+ repaintSoon();
231
+ return;
232
+ }
233
+ if (data === "/") {
234
+ searching = true;
235
+ repaintSoon();
236
+ return;
237
+ }
238
+ if (data === "s" || data === "t") {
239
+ session.sort = data === "s" ? "cost" : "time";
240
+ rebuild(true);
241
+ repaintSoon();
242
+ return;
243
+ }
244
+ if (keybindings.matches(data, "tui.select.up")) {
245
+ active.handleInput(data);
246
+ repaintSoon();
247
+ return;
248
+ }
249
+ if (keybindings.matches(data, "tui.select.down")) {
250
+ active.handleInput(data);
251
+ repaintSoon();
252
+ return;
253
+ }
254
+ // Movement is computed here rather than delegated, so page/home/end behave the
255
+ // same whatever the terminal sends and whatever the keybinding is called.
256
+ const nav = navKey(data, keybindings);
257
+ if (nav) {
258
+ const items = currentItems();
259
+ if (items.length > 0) {
260
+ const current = active.getSelectedItem();
261
+ const index = current ? Math.max(0, items.findIndex((entry) => entry.id === current.value)) : 0;
262
+ const step = pageSize;
263
+ const target =
264
+ nav === "home"
265
+ ? 0
266
+ : nav === "end"
267
+ ? items.length - 1
268
+ : nav === "pageUp"
269
+ ? index - step
270
+ : index + step;
271
+ active.setSelectedIndex(Math.max(0, Math.min(items.length - 1, target)));
272
+ }
273
+ repaintSoon();
274
+ return;
275
+ }
276
+ if (data === "g" || data === "G") {
277
+ const items = currentItems();
278
+ if (items.length > 0) active.setSelectedIndex(data === "g" ? 0 : items.length - 1);
279
+ repaintSoon();
280
+ return;
281
+ }
282
+ if (data === "\u0004" || data === "\u0006") {
283
+ // ctrl+d / ctrl+f: half page down / down a page
284
+ const items = currentItems();
285
+ const current = active.getSelectedItem();
286
+ const index = current ? Math.max(0, items.findIndex((entry) => entry.id === current.value)) : 0;
287
+ const step = data === "\u0004" ? Math.max(1, Math.floor(pageSize / 2)) : pageSize;
288
+ active.setSelectedIndex(Math.max(0, Math.min(items.length - 1, index + step)));
289
+ repaintSoon();
290
+ return;
291
+ }
292
+ if (data === "\u0015" || data === "\u0002") {
293
+ // ctrl+u / ctrl+b: half page up / up a page
294
+ const items = currentItems();
295
+ const current = active.getSelectedItem();
296
+ const index = current ? Math.max(0, items.findIndex((entry) => entry.id === current.value)) : 0;
297
+ const step = data === "\u0015" ? Math.max(1, Math.floor(pageSize / 2)) : pageSize;
298
+ active.setSelectedIndex(Math.max(0, Math.min(items.length - 1, index - step)));
299
+ repaintSoon();
300
+ return;
301
+ }
302
+
303
+ const selected = active.getSelectedItem();
304
+ const item = selected ? currentItems().find((candidate) => candidate.id === selected.value) : undefined;
305
+ // Bulk actions use the marked set when there is one, otherwise the cursor row.
306
+ const targets = (): BrowseItem[] => {
307
+ const items = currentItems();
308
+ const picked = items.filter((candidate) => marked.has(candidate.id));
309
+ if (picked.length > 0) return picked;
310
+ return item ? [item] : [];
311
+ };
312
+
313
+ switch (data) {
314
+ case " ":
315
+ if (!item) return;
316
+ if (marked.has(item.id)) marked.delete(item.id);
317
+ else marked.add(item.id);
318
+ session.marked = [...marked];
319
+ rebuild(true);
320
+ repaintSoon();
321
+ return;
322
+ case "c": {
323
+ const picked = targets();
324
+ if (picked.length > 0) done({ kind: "copy", items: picked });
325
+ return;
326
+ }
327
+ case "m": {
328
+ if (marked.size === 0 && item) done({ kind: "message", item });
329
+ else if (marked.size > 1) done({ kind: "message", item: targets()[0] as BrowseItem });
330
+ else if (item) done({ kind: "message", item });
331
+ return;
332
+ }
333
+ case "r": {
334
+ const picked = targets();
335
+ if (picked.length > 0) done({ kind: "retry", items: picked });
336
+ return;
337
+ }
338
+ case "x": {
339
+ const picked = targets();
340
+ if (picked.length === 0) return;
341
+ if (picked.length === 1) done({ kind: "stop", item: picked[0] as BrowseItem });
342
+ else done({ kind: "stopMany", items: picked });
343
+ return;
344
+ }
345
+ case "f":
346
+ if (item) done({ kind: "follow", item });
347
+ return;
348
+ case "d":
349
+ if (item) done({ kind: "log", item });
350
+ return;
351
+ case "D":
352
+ if (item) done({ kind: "diff", item });
353
+ return;
354
+ case "j":
355
+ if (item) done({ kind: "join", item });
356
+ return;
357
+ case "o":
358
+ if (item) done({ kind: "useRun", item });
359
+ return;
360
+ case "q":
361
+ done({ kind: "close" });
362
+ return;
363
+ default:
364
+ return;
365
+ }
366
+ }
367
+
368
+ return {
369
+ render(width: number): string[] {
370
+ if (cachedLines && cachedWidth === width) return cachedLines;
371
+ const active = rebuild();
372
+ const heading = truncateToWidth(theme.bold(hooks.title()), width);
373
+ const body = active.render(Math.max(20, width));
374
+ const lines = [heading, statusBar(), "", ...body, "", footer()];
375
+ cachedWidth = width;
376
+ cachedLines = lines.map((line) => truncateToWidth(line, width));
377
+ return cachedLines;
378
+ },
379
+ handleInput,
380
+ invalidate,
381
+ };
382
+ }
383
+
384
+ // ---------------------------------------------------------------------------
385
+ // detail view
386
+ // ---------------------------------------------------------------------------
387
+
388
+ export interface DetailOptions {
389
+ title: string;
390
+ lines: () => string[];
391
+ /** Start at the tail and keep following (used for the live log pager). */
392
+ follow?: boolean;
393
+ onMount?: (repaint: () => void) => void;
394
+ }
395
+
396
+ export function createDetailComponent(
397
+ tui: { requestRender(force?: boolean): void; terminal: { rows: number; columns: number } },
398
+ theme: Theme,
399
+ keybindings: { matches(data: string, action: string): boolean },
400
+ done: (result: { kind: "back" | "close" }) => void,
401
+ options: DetailOptions,
402
+ ) {
403
+ let offset = 0;
404
+ let following = options.follow ?? false;
405
+ let cachedWidth = -1;
406
+ let cachedLines: string[] | undefined;
407
+
408
+ const invalidate = () => {
409
+ cachedWidth = -1;
410
+ cachedLines = undefined;
411
+ };
412
+ const repaintSoon = () => {
413
+ invalidate();
414
+ tui.requestRender();
415
+ };
416
+ options.onMount?.(repaintSoon);
417
+
418
+ const windowSize = () => Math.max(5, (tui.terminal?.rows ?? 30) - 6);
419
+
420
+ return {
421
+ render(width: number): string[] {
422
+ if (cachedLines && cachedWidth === width) return cachedLines;
423
+ const all = options.lines();
424
+ const size = windowSize();
425
+ if (following) offset = Math.max(0, all.length - size);
426
+ offset = Math.max(0, Math.min(offset, Math.max(0, all.length - size)));
427
+ const view = all.slice(offset, offset + size);
428
+ const scrollParts: string[] = [];
429
+ if (all.length > size) scrollParts.push(` ${offset + 1}-${offset + view.length}/${all.length}`);
430
+ scrollParts.push(following ? "follow: on" : "follow: off");
431
+ const scroll = theme.fg("dim", scrollParts.join(" · "));
432
+ const lines = [
433
+ truncateToWidth(theme.bold(options.title), width),
434
+ scroll,
435
+ "",
436
+ ...view.map((line) => truncateToWidth(line, width)),
437
+ "",
438
+ theme.fg("dim", "↑↓ scroll · pgup/pgdn · home/end · g/G · ctrl+d/u · f follow · esc back"),
439
+ ];
440
+ cachedWidth = width;
441
+ cachedLines = lines;
442
+ return lines;
443
+ },
444
+ handleInput(data: string): void {
445
+ if (keybindings.matches(data, "tui.select.cancel") || data === "q" || data === "h") {
446
+ done({ kind: "back" });
447
+ return;
448
+ }
449
+ const size = windowSize();
450
+ if (data === "f") {
451
+ // Follow the tail (live) or freeze the view where it is.
452
+ following = !following;
453
+ if (following) offset = Number.MAX_SAFE_INTEGER;
454
+ repaintSoon();
455
+ return;
456
+ }
457
+ const nav = navKey(data, keybindings);
458
+ if (keybindings.matches(data, "tui.select.up")) {
459
+ following = false;
460
+ offset -= 1;
461
+ } else if (keybindings.matches(data, "tui.select.down")) {
462
+ following = false;
463
+ offset += 1;
464
+ } else if (nav === "pageUp") {
465
+ following = false;
466
+ offset -= size;
467
+ } else if (nav === "pageDown" || data === " ") {
468
+ following = false;
469
+ offset += size;
470
+ } else if (nav === "home" || data === "g") {
471
+ following = false;
472
+ offset = 0;
473
+ } else if (nav === "end" || data === "G") {
474
+ following = true;
475
+ offset = Number.MAX_SAFE_INTEGER;
476
+ } else if (data === "\u0004" || data === "\u0006") {
477
+ // ctrl+d / ctrl+f: half page down / page down
478
+ following = false;
479
+ offset += data === "\u0004" ? Math.max(1, Math.floor(size / 2)) : size;
480
+ } else if (data === "\u0015" || data === "\u0002") {
481
+ following = false;
482
+ offset -= data === "\u0015" ? Math.max(1, Math.floor(size / 2)) : size;
483
+ } else return;
484
+ repaintSoon();
485
+ },
486
+ invalidate,
487
+ };
488
+ }
489
+
490
+ function fitLabel(text: string): string {
491
+ const flat = text.replace(/\s+/g, " ").trim();
492
+ return flat.length > 64 ? `${flat.slice(0, 63)}…` : flat;
493
+ }
494
+
495
+ export function detailTitle(item: BrowseItem): string {
496
+ return `${item.glyph} ${item.title} [${shortId(item.id)} ${item.status}]`;
497
+ }