@danypops/pi-packed 0.16.1 → 0.18.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.
@@ -1,63 +1,65 @@
1
1
  /**
2
- * tui.ts — /packed's default panel. Mnemonics follow lazy.nvim's own
3
- * convention (folke/lazy.nvim lua/lazy/view/config.lua): uppercase acts on
4
- * every row, lowercase acts on the row under the cursor -- U/u update,
5
- * X/x was lazy's delete key (clean); here that pairing is single-target
6
- * only (x remove -- there is no safe "remove every installed package"
7
- * bulk analog, so no X is bound). Adds d disable/enable this package's
8
- * extensions, c jump to full resource config, f find/install new
9
- * packages, s settings. The panel itself is a real bordered (rounded)
10
- * floating overlay (`ctx.ui.custom` with overlay:true, Malevich's
11
- * Envelope for the box), positioned at 40% of terminal height (pi-tui's
12
- * own row percentage, not a fixed row count -- scales with the real
13
- * terminal, unlike the anchor:"top-center"+offsetY this replaced, which
14
- * was pinned 1 row below the absolute top on any terminal size). Enter
15
- * opens a second, smaller overlay action menu on top of it. U's batch
16
- * update stays on this same package list -- an indeterminate spinner
17
- * (Malevich's Spinner, extracted upstream from this panel's original need
18
- * once no embeddable one existed anywhere) renders inline next to the row
19
- * currently updating, settling into a real ✓/✗ plus a bounded tail of
20
- * that row's own actual captured stdout/stderr once it finishes, never a
21
- * determinate bar (a single subprocess call has no knowable percentage).
22
- * Rows render through Malevich's Table (real column-aligned
23
- * Package/Version/status cells, per-row selection styling baked into each
24
- * cell since Table's own cellStyle is column-wide, not row-wide) inside
25
- * this panel's own scroll-window slice -- Table deliberately owns no
26
- * pagination of its own, so the visible-window-around-selectedIndex math
27
- * stays here. u/x/d and the Enter action menu all run their whole
28
- * approve+mutate+confirmReload flow inline, without ever closing this
29
- * overlay first -- every confirm() along the way (mutation approval,
30
- * confirmReload's separate reload gate) renders as a real Malevich Dialog
31
- * on this SAME overlay, dispatched by literal y/n keys, instead of
32
- * ctx.ui.confirm's own separate native dialog (arrow-select only, and a
33
- * genuinely different overlay stacked on top -- confirmed live as a real
34
- * user complaint). Declining a reload defers it: the mutation itself
35
- * already happened, and the panel stays open with refreshed rows instead
36
- * of ending the session. Every non-"changed" settle point (already up to
37
- * date, pinned, deferred, a genuine failure) shows its own real reason on
38
- * that row too via the same settled map U's batch path uses, not only as
39
- * a scrollback toast -- confirmed live as a real bug: a single-row update
40
- * that turned out to be a no-op gave zero acknowledgment on the panel
41
- * itself. All data flows through the packed CLI (thin seam).
2
+ * tui.ts — /packed's one panel, four tabs. Mnemonics follow lazy.nvim's
3
+ * own convention (folke/lazy.nvim lua/lazy/view/config.lua): uppercase
4
+ * acts on every row, lowercase acts on the row under the cursor -- U/u
5
+ * update, X/x was lazy's delete key (clean); here that pairing is
6
+ * single-target only (x remove -- there is no safe "remove every
7
+ * installed package" bulk analog, so no X is bound). Adds d disable/
8
+ * enable this package's extensions, c jump to Config (scoped to the
9
+ * selected row), f jump to Find, s jump to Settings.
10
+ *
11
+ * All four (Packages/Find/Config/Settings) live inside ONE
12
+ * `ctx.ui.custom` floating overlay for the panel's whole lifetime --
13
+ * Malevich's Envelope for the box (rounded border), TabbedContainer for
14
+ * the persistent tab bar + active-tab content swap, and (on top of that)
15
+ * a Dialog swapped in for any y/n decision, the same content-replacement
16
+ * stacking Envelope's own setContent already provides, generalized one
17
+ * level further here. This replaced each tab opening its own separate
18
+ * screen (Find/Config: a second, visually distinct ctx.ui.custom with no
19
+ * Envelope at all; Settings: Pi's own native ctx.ui.select/confirm) --
20
+ * confirmed live as a real user complaint ("Find, Settings, Config all
21
+ * open a different TUI"). Left/Right cycle tabs; Escape returns to
22
+ * Packages from anywhere else, or closes the whole panel from Packages
23
+ * itself -- unless the active tab's own capturesEscape()/
24
+ * capturesHorizontalArrows() says it wants that key for itself right now
25
+ * (an active text filter, an in-flight mutation, or Find's always-on
26
+ * query box), in which case it's delegated straight through instead.
27
+ *
28
+ * Packages itself: an indeterminate spinner (Malevich's Spinner) renders
29
+ * inline next to the row currently updating, settling into a real ✓/✗
30
+ * plus a bounded tail of that row's own actual captured stdout/stderr
31
+ * once it finishes, never a determinate bar (a single subprocess call has
32
+ * no knowable percentage). Rows render through Malevich's Table (real
33
+ * column-aligned Package/Version/status cells, per-row selection styling
34
+ * baked into each cell since Table's own cellStyle is column-wide, not
35
+ * row-wide) inside this tab's own scroll-window slice -- Table
36
+ * deliberately owns no pagination of its own, so the visible-window-
37
+ * around-selectedIndex math stays here. u/x/d and the Enter action menu
38
+ * all run their whole approve+mutate+confirmReload flow inline, via the
39
+ * shared TabHost's inlineCtx -- every confirm() along the way renders as
40
+ * a real Malevich Dialog on this SAME overlay, dispatched by literal y/n
41
+ * keys, instead of ctx.ui.confirm's own separate native dialog. Every
42
+ * non-"changed" settle point (already up to date, pinned, deferred, a
43
+ * genuine failure) shows its own real reason on that row too via the same
44
+ * settled map U's batch path uses, not only as a scrollback toast. All
45
+ * data flows through the packed CLI (thin seam).
42
46
  */
43
47
  import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
44
48
  import { DynamicBorder, rawKeyHint } from "@earendil-works/pi-coding-agent";
45
49
  import { Container, Input, Spacer, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
46
- import { Dialog, Envelope, Menu, Spinner, Table, type MenuItem, type TableColumn, type TextMeasure } from "malevich-tui-components";
50
+ import { Dialog, Envelope, Menu, Spinner, Table, TabbedContainer, type Component, type MenuItem, type TextMeasure } from "malevich-tui-components";
47
51
  import { filterRows, mergeRows, nextMode, visibleRows } from "./model.js";
48
52
  import type { Row, ViewMode } from "./model.js";
49
53
  import type { Natives, PackageResources } from "./packed.js";
50
54
  import { approvePackageOperation } from "./tools.js";
51
- import { showPackedSettings } from "./security-tui.js";
52
- import { showResourceConfig, applyResourceToggle } from "./resource-config.js";
53
- import { showDiscoverPanel } from "./discover.js";
54
- import { dialogTheme, menuTheme } from "./menu-theme.js";
55
+ import { createSettingsTab, SettingsTab } from "./security-tui.js";
56
+ import { createConfigTab, ConfigTab, applyResourceToggle } from "./resource-config.js";
57
+ import { createFindTab, FindTab } from "./discover.js";
58
+ import { dialogTheme, menuTheme, tabBarTheme } from "./menu-theme.js";
55
59
  import { confirmReload } from "./reload.js";
60
+ import type { TabHost } from "./tab-host.js";
56
61
 
57
- interface PanelAction {
58
- type: "config" | "find" | "refresh" | "settings";
59
- row?: Row;
60
- }
62
+ export type PackedTabKey = "packages" | "find" | "config" | "settings";
61
63
 
62
64
  /** Outcome of a confirmed row action, resolved after any real mutation and
63
65
  * reload decision -- "changed" means the daemon state changed and Pi has
@@ -369,86 +371,347 @@ async function showActionMenu(ctx: ExtensionCommandContext, row: Row): Promise<"
369
371
  );
370
372
  }
371
373
 
372
- export async function showPackedPanel(ctx: ExtensionCommandContext, natives: Natives): Promise<void> {
373
- if (!ctx.hasUI) {
374
- ctx.ui.notify("/packed requires interactive mode", "warning");
375
- return;
374
+ interface PackagesTabTheme { fg(color: string, s: string): string; bold(s: string): string; }
375
+
376
+ /** Packages -- the panel's default/"home" tab. A real Component (not the
377
+ * panel's own top-level ctx.ui.custom owner anymore); the shared TabHost
378
+ * gives it inline approval/reload dialogs and a way to signal the overlay
379
+ * should close once a mutation actually replaces the session. */
380
+ export class PackagesTab implements Component {
381
+ private rows: Row[];
382
+ private mode: ViewMode = "all";
383
+ private readonly searchInput = new Input();
384
+ private searchActive = false;
385
+ private filtered: Row[];
386
+ private selectedIndex = 0;
387
+ // Set only while U's batch update (or a single row's own u/x/d) is
388
+ // running -- blocks input for the duration (the mutation/installer owns
389
+ // input until it finishes). Which specific row currently shows a spinner
390
+ // vs. a settled ✓/✗ is settled's own job, not this -- a just-finished row
391
+ // must show its glyph immediately, even for the instant before the next
392
+ // row's "start" event reassigns this to the next name.
393
+ private updatingRowName: string | undefined;
394
+ private readonly spinner = new Spinner();
395
+ private readonly settled = new Map<string, { ok: boolean; tail: string | undefined }>();
396
+ private readonly table: Table;
397
+ private readonly maxVisible = 20;
398
+
399
+ constructor(
400
+ private readonly natives: Natives,
401
+ private readonly host: TabHost,
402
+ private readonly theme: PackagesTabTheme,
403
+ measure: TextMeasure,
404
+ initialRows: Row[],
405
+ /** c on a row, or the Enter action menu's "Configure resources" --
406
+ * switches the shared TabbedContainer to Config, seeded with that
407
+ * row's own name as its filter. f/s switch tabs with no filter. */
408
+ private readonly switchTab: (target: "find" | "config" | "settings", configFilter?: string) => void,
409
+ ) {
410
+ this.rows = initialRows;
411
+ this.filtered = visibleRows(this.rows, this.mode);
412
+ this.table = new Table({
413
+ columns: [
414
+ { header: "Package", key: "name" },
415
+ { header: "Version", key: "version" },
416
+ { header: "", key: "status" },
417
+ ],
418
+ rows: [],
419
+ measure,
420
+ headerStyle: (s) => theme.fg("muted", s),
421
+ });
376
422
  }
377
423
 
378
- let { rows, error } = await loadRows(natives);
379
- if (error) {
380
- ctx.ui.notify(`packed unavailable: ${error}`, "error");
381
- return;
424
+ /** An active filter or an in-flight mutation means Escape/Left-Right
425
+ * belong to this tab (clearing the filter; blocking navigation away
426
+ * mid-mutation), not the host's own back/tab-cycle handling. Packages
427
+ * never uses Left/Right for itself otherwise. */
428
+ capturesEscape(): boolean {
429
+ return this.searchActive || this.updatingRowName !== undefined;
430
+ }
431
+
432
+ /** Same condition as capturesEscape -- an active filter or an in-flight
433
+ * mutation means every printable key (including a letter that would
434
+ * otherwise be a global tab-jump mnemonic) belongs to this tab right now.
435
+ * Packages itself never needs this check at the host level (see
436
+ * renderUnifiedPanel's own dispatcher), but implementing it keeps this
437
+ * tab's own contract honest and consistent with the other three. */
438
+ capturesMnemonics(): boolean {
439
+ return this.searchActive || this.updatingRowName !== undefined;
440
+ }
441
+
442
+ invalidate(): void {
443
+ this.table.invalidate();
444
+ }
445
+
446
+ private applyFilter(): void {
447
+ this.filtered = filterRows(visibleRows(this.rows, this.mode), this.searchInput.getValue());
448
+ this.selectedIndex = 0;
382
449
  }
383
450
 
384
- // A deferred reload means the mutation itself genuinely happened but
385
- // ctx.reload() was declined -- the session is still alive, so refresh
386
- // rows (real on-disk versions) and keep the panel open, same as "refresh".
387
- async function refreshRows(): Promise<void> {
388
- ({ rows, error } = await loadRows(natives));
389
- if (error) ctx.ui.notify(`refresh failed: ${error}`, "error");
451
+ private statusLine(): string {
452
+ if (this.updatingRowName) return "updating…";
453
+ const outdated = this.rows.filter((r) => r.hasUpdate).length;
454
+ return outdated > 0 ? `${outdated} update(s)` : "up to date";
390
455
  }
391
456
 
392
- // Panel loop: actions resolve the component, run outside it, then reopen.
393
- // Every mutation (u/x/d, U, and whatever the Enter action menu picks) is
394
- // handled entirely inside renderPanel itself -- approval and reload
395
- // confirms render inline on the same already-open overlay -- and never
396
- // reaches here; only non-mutation navigation resolves this loop.
397
- for (;;) {
398
- const action = await renderPanel(ctx, natives, rows);
399
- if (!action) return; // closed
400
-
401
- if (action.type === "refresh") {
402
- await refreshRows();
403
- continue;
457
+ render(width: number): string[] {
458
+ const { theme } = this;
459
+ const hint = this.searchActive
460
+ ? rawKeyHint("esc", "clear")
461
+ : rawKeyHint("enter", "menu") +
462
+ theme.fg("muted", " · ") +
463
+ rawKeyHint("u/U", "update/all") +
464
+ theme.fg("muted", " · ") +
465
+ rawKeyHint("x", "remove") +
466
+ theme.fg("muted", " · ") +
467
+ rawKeyHint("d", "disable") +
468
+ theme.fg("muted", " · ") +
469
+ rawKeyHint("c", "config") +
470
+ theme.fg("muted", " · ") +
471
+ rawKeyHint("r", "refresh");
472
+ const line1 = truncateToWidth(hint, width, "");
473
+ const dot = "·";
474
+ const line2 = truncateToWidth(
475
+ theme.fg("muted", `${this.statusLine()} ${dot} view: ${this.mode} ${dot} / filter ${dot} v view ${dot} ${this.rows.length} installed`),
476
+ width,
477
+ "",
478
+ );
479
+ const lines: string[] = [line1, line2];
480
+ if (this.searchActive) lines.push(...this.searchInput.render(width));
481
+ lines.push("");
482
+ if (this.filtered.length === 0) {
483
+ lines.push(theme.fg("muted", " No packages"));
484
+ return lines;
404
485
  }
486
+ // No scrolling of its own (Malevich's Table is deliberately
487
+ // unopinionated about pagination) -- the visible window around
488
+ // selectedIndex stays this tab's own job.
489
+ const start = Math.max(0, Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filtered.length - this.maxVisible));
490
+ const end = Math.min(start + this.maxVisible, this.filtered.length);
491
+ this.table.setRows(
492
+ this.filtered.slice(start, end).map((row, offset) => {
493
+ const i = start + offset;
494
+ const selected = i === this.selectedIndex;
495
+ const cursor = selected ? theme.fg("accent", "❯ ") : " ";
496
+ const name = selected ? theme.bold(row.name) : row.name;
497
+ // A settled row shows its real outcome even for the instant before
498
+ // the next row's "start" event moves updatingRowName off it --
499
+ // settled always wins over "still spinning".
500
+ const rowSettled = this.settled.get(row.name);
501
+ const isUpdating = !rowSettled && this.updatingRowName === row.name;
502
+ const status = isUpdating
503
+ ? theme.fg("accent", `${this.spinner.glyph()} updating…`)
504
+ : rowSettled
505
+ ? theme.fg(rowSettled.ok ? "success" : "error", `${rowSettled.ok ? "✓" : "✗"}${rowSettled.tail ? ` ${rowSettled.tail}` : ""}`)
506
+ : row.hasUpdate ? theme.fg("warning", `↑${row.latest}`) : "";
507
+ return { name: `${cursor}${name}`, version: theme.fg("dim", row.version), status };
508
+ }),
509
+ );
510
+ lines.push(...this.table.render(width));
511
+ const hasScroll = start > 0 || end < this.filtered.length;
512
+ lines.push(theme.fg("dim", ` ${hasScroll ? `${this.selectedIndex + 1}/${this.filtered.length} ` : ""}${this.mode}`));
513
+ return lines;
514
+ }
405
515
 
406
- if (action.type === "settings") {
407
- await showPackedSettings(ctx, natives);
408
- continue; // settings never changes package rows -- reopen as-is
516
+ handleInput(data: string): void {
517
+ if (this.updatingRowName) return; // the mutation/installer owns input until it finishes
518
+
519
+ if (this.searchActive) {
520
+ if (data === "\x1b") {
521
+ this.searchActive = false;
522
+ this.searchInput.setValue?.("");
523
+ this.applyFilter();
524
+ } else if (data === "\r") {
525
+ this.searchActive = false;
526
+ } else {
527
+ this.searchInput.handleInput(data);
528
+ this.applyFilter();
529
+ }
530
+ this.host.requestRender();
531
+ return;
409
532
  }
410
533
 
411
- if (action.type === "find") {
412
- await showDiscoverPanel(ctx, natives);
413
- continue; // a successful install already reloaded; a no-op returns here
534
+ switch (data) {
535
+ case "\x1b[A":
536
+ this.selectedIndex = (this.selectedIndex - 1 + this.filtered.length) % Math.max(this.filtered.length, 1);
537
+ break;
538
+ case "\x1b[B":
539
+ this.selectedIndex = (this.selectedIndex + 1) % Math.max(this.filtered.length, 1);
540
+ break;
541
+ case "v": // Tab is now reserved globally for sweeping between menus (TabbedContainer)
542
+ this.mode = nextMode(this.mode);
543
+ this.applyFilter();
544
+ break;
545
+ case "/":
546
+ this.searchActive = true;
547
+ break;
548
+ case "r":
549
+ void this.refresh();
550
+ return;
551
+ case "s":
552
+ this.switchTab("settings");
553
+ return;
554
+ case "f":
555
+ this.switchTab("find");
556
+ return;
557
+ case "U":
558
+ void this.runUpdateAllInline();
559
+ return;
560
+ case "u": {
561
+ const row = this.filtered[this.selectedIndex];
562
+ if (row?.hasUpdate) void this.runRowActionInline({ type: "update", row });
563
+ return;
564
+ }
565
+ case "x": {
566
+ const row = this.filtered[this.selectedIndex];
567
+ if (row) void this.runRowActionInline({ type: "remove", row });
568
+ return;
569
+ }
570
+ case "d": {
571
+ const row = this.filtered[this.selectedIndex];
572
+ if (row) void this.runRowActionInline({ type: "disable", row });
573
+ return;
574
+ }
575
+ case "c": {
576
+ const row = this.filtered[this.selectedIndex];
577
+ if (row) this.switchTab("config", row.name);
578
+ return;
579
+ }
580
+ case "\r": {
581
+ const row = this.filtered[this.selectedIndex];
582
+ if (!row) return;
583
+ void (async () => {
584
+ const choice = await showActionMenu(this.host.inlineCtx, row);
585
+ if (choice === "update" || choice === "remove" || choice === "disable") void this.runRowActionInline({ type: choice, row });
586
+ else if (choice === "config") this.switchTab("config", row.name);
587
+ })();
588
+ return;
589
+ }
590
+ default:
591
+ return;
414
592
  }
593
+ this.host.requestRender();
594
+ }
415
595
 
416
- await showResourceConfig(ctx, natives, action.row?.name);
417
- // showResourceConfig already handles its own reload prompt
596
+ private async refresh(): Promise<void> {
597
+ const reloaded = await loadRows(this.natives);
598
+ if (reloaded.error) this.host.ctx.ui.notify(`refresh failed: ${reloaded.error}`, "error");
599
+ else this.rows = reloaded.rows;
600
+ this.applyFilter();
601
+ this.host.requestRender();
418
602
  }
419
- }
420
603
 
421
- function renderPanel(ctx: ExtensionCommandContext, natives: Natives, initialRows: Row[]): Promise<PanelAction | undefined> {
422
- return ctx.ui.custom<PanelAction | undefined>((tui, theme, _kb, done) => {
423
- let rows = initialRows;
424
- let mode: ViewMode = "all";
425
- const searchInput = new Input();
426
- let searchActive = false;
427
- let filtered = visibleRows(rows, mode);
428
- let selectedIndex = 0;
429
- // Set only while U's batch update is running -- blocks input for the
430
- // whole batch (the installer owns input until it finishes), same as
431
- // before. The list stays fully visible throughout. Which specific row
432
- // currently shows a spinner vs. a settled ✓/✗ is settled's own job
433
- // (below), not this -- a just-finished row must show its glyph
434
- // immediately, even for the instant before the next row's "start"
435
- // event reassigns this to the next name.
436
- let updatingRowName: string | undefined;
437
- const spinner = new Spinner();
438
- const settled = new Map<string, { ok: boolean; tail: string | undefined }>();
439
-
440
- const maxVisible = 20;
441
-
442
- function applyFilter(): void {
443
- filtered = filterRows(visibleRows(rows, mode), searchInput.getValue());
444
- selectedIndex = 0;
604
+ /** u/x/d and the Enter action menu all funnel through here: approval and
605
+ * reload confirms render inline (via host.inlineCtx) on this same
606
+ * overlay, never closing it first. */
607
+ private async runRowActionInline(action: { type: "update" | "remove" | "disable"; row: Row }): Promise<void> {
608
+ this.updatingRowName = action.row.name;
609
+ this.host.requestRender();
610
+ // A non-"changed" settle point (already up to date, pinned, deferred, a
611
+ // genuine failure) shows its own real reason on this row, the same
612
+ // settled map U's batch path already renders -- not just a scrollback
613
+ // toast.
614
+ const onSettled = (result: PackageChoiceSettled) => this.settled.set(action.row.name, { ok: result.ok, tail: result.message });
615
+ const outcome = action.type === "disable"
616
+ ? await applyDisableExtensions(action.row, this.natives, this.host.inlineCtx)
617
+ : await applyPackageChoice(action.type === "update" ? `Update to ${action.row.latest}` : "Remove", action.row, this.natives, this.host.inlineCtx, onSettled);
618
+ this.updatingRowName = undefined;
619
+ if (outcome === "changed") {
620
+ this.host.onSessionReplaced(); // ctx.reload() already replaced the session
621
+ return;
445
622
  }
623
+ const reloaded = await loadRows(this.natives);
624
+ if (reloaded.error) this.host.ctx.ui.notify(`refresh failed: ${reloaded.error}`, "error");
625
+ else this.rows = reloaded.rows;
626
+ this.applyFilter();
627
+ this.host.requestRender();
628
+ }
629
+
630
+ /** U -- runs the whole approve+update+notify+reload flow without ever
631
+ * closing this tab or replacing the list: each row's own settled outcome
632
+ * (spinner while in flight, then a real ✓/✗ plus a bounded tail of its
633
+ * actual captured output) appears inline next to that row. Rows refresh
634
+ * in place afterward unless a reload already ended the session. */
635
+ private async runUpdateAllInline(): Promise<void> {
636
+ const outdated = this.rows.filter((row) => row.hasUpdate);
637
+ this.settled.clear();
638
+ const outcome = await approveAndRunUpdateAll(outdated, this.natives, this.host.inlineCtx, (batch, approved) => {
639
+ this.spinner.start(() => this.host.requestRender());
640
+ return performUpdateAll(batch, this.natives, approved, (event) => {
641
+ this.updatingRowName = event.row.name;
642
+ if (event.phase === "done" && event.result) {
643
+ this.settled.set(event.row.name, { ok: event.result.ok, tail: logTail(event.result.output) });
644
+ }
645
+ this.host.requestRender();
646
+ }).finally(() => this.spinner.stop());
647
+ });
648
+ this.updatingRowName = undefined;
649
+ if (outcome === "changed") {
650
+ this.host.onSessionReplaced(); // ctx.reload() already replaced the session
651
+ return;
652
+ }
653
+ const reloaded = await loadRows(this.natives);
654
+ if (reloaded.error) this.host.ctx.ui.notify(`refresh failed: ${reloaded.error}`, "error");
655
+ else this.rows = reloaded.rows;
656
+ this.settled.clear(); // fresh state for a subsequent batch
657
+ this.applyFilter();
658
+ this.host.requestRender();
659
+ }
660
+ }
661
+
662
+ interface TabScope {
663
+ /** True while this tab wants Escape for itself right now (an active
664
+ * filter, an in-flight mutation) instead of the host's own "back to
665
+ * Packages, or close from Packages" handling. Defaults to false. */
666
+ capturesEscape?(): boolean;
667
+ /** True while this tab wants Left/Right for itself right now (Find's
668
+ * always-on query cursor) instead of the host's own tab-cycling via
669
+ * TabbedContainer. Tab/Shift-Tab have no such exception -- nothing needs
670
+ * a literal Tab character for itself, so they always sweep between
671
+ * menus. Defaults to false. */
672
+ capturesHorizontalArrows?(): boolean;
673
+ /** True while this tab wants every printable character for itself (an
674
+ * active filter, an in-flight mutation, or Find's permanent query box)
675
+ * instead of the host's own mnemonic letter-jump (p/f/c/s). Defaults to
676
+ * false. Never consulted while Packages itself is active -- Packages'
677
+ * own f/c/s bindings already do the same jump (c additionally scopes
678
+ * Config to the selected row), so the generic host-level jump only
679
+ * matters for reaching a tab from one of the OTHER three. */
680
+ capturesMnemonics?(): boolean;
681
+ }
682
+
683
+ export async function showPackedPanel(
684
+ ctx: ExtensionCommandContext,
685
+ natives: Natives,
686
+ opts?: { initialTab?: PackedTabKey; initialConfigFilter?: string },
687
+ ): Promise<void> {
688
+ if (!ctx.hasUI) {
689
+ ctx.ui.notify("/packed requires interactive mode", "warning");
690
+ return;
691
+ }
692
+
693
+ const { rows, error } = await loadRows(natives);
694
+ if (error) {
695
+ ctx.ui.notify(`packed unavailable: ${error}`, "error");
696
+ return;
697
+ }
698
+
699
+ await renderUnifiedPanel(ctx, natives, rows, opts?.initialTab ?? "packages", opts?.initialConfigFilter);
700
+ }
446
701
 
702
+ function renderUnifiedPanel(
703
+ ctx: ExtensionCommandContext,
704
+ natives: Natives,
705
+ initialRows: Row[],
706
+ initialTab: PackedTabKey,
707
+ initialConfigFilter: string | undefined,
708
+ ): Promise<void> {
709
+ return ctx.ui.custom<void>((tui, theme, _kb, done) => {
447
710
  // A y/n decision rendered as this SAME overlay's own content (via a real
448
711
  // Malevich Dialog, dispatched by literal key press) instead of
449
- // ctx.ui.confirm's separate native dialog -- confirmed live as a real
450
- // user complaint: ctx.ui.confirm opens as its own distinct overlay on
451
- // top of this one ("a new window"), arrow-select only, no y/n keys.
712
+ // ctx.ui.confirm's separate native dialog -- shared by every tab via
713
+ // host.inlineCtx below, exactly like the panel's own approval/reload
714
+ // dialogs always have been.
452
715
  let pendingDialog: Dialog | undefined;
453
716
 
454
717
  function confirmInline(title: string, message: string): Promise<boolean> {
@@ -466,194 +729,75 @@ function renderPanel(ctx: ExtensionCommandContext, natives: Natives, initialRows
466
729
  { label: "No", key: "n", action: () => settle(false) },
467
730
  ],
468
731
  theme: dialogTheme(theme),
732
+ framed: false, // this overlay's own Envelope already draws a border; a second rule would double up on it
469
733
  });
470
734
  tui.requestRender();
471
735
  });
472
736
  }
473
737
 
474
- // Every confirm() call inside a mutation flow driven from this open
475
- // overlay (approvePackageOperation's own approval, confirmReload's
476
- // separate reload gate) routes through confirmInline instead of the
477
- // real ctx.ui.confirm -- notify/reload/etc. stay the genuine ctx.
478
738
  const inlineCtx: ExtensionCommandContext = { ...ctx, hasUI: true, ui: { ...ctx.ui, confirm: confirmInline } };
739
+ const host: TabHost = {
740
+ ctx,
741
+ inlineCtx,
742
+ requestRender: () => tui.requestRender(),
743
+ onSessionReplaced: () => done(undefined),
744
+ };
479
745
 
480
- /** u/x/d and the Enter action menu all funnel through here: approval and
481
- * reload confirms render inline (via inlineCtx/confirmInline) on this
482
- * same overlay, never closing it first the way done()-dispatch used to. */
483
- async function runRowActionInline(action: { type: "update" | "remove" | "disable"; row: Row }): Promise<void> {
484
- updatingRowName = action.row.name;
485
- tui.requestRender();
486
- // A non-"changed" settle point (already up to date, pinned, deferred,
487
- // a genuine failure) shows its own real reason on this row, the same
488
- // settled map U's batch path already renders -- not just a scrollback
489
- // toast, which was the whole bug: nothing on the panel itself ever
490
- // acknowledged that a single-row action had even run.
491
- const onSettled = (result: PackageChoiceSettled) => settled.set(action.row.name, { ok: result.ok, tail: result.message });
492
- const outcome = action.type === "disable"
493
- ? await applyDisableExtensions(action.row, natives, inlineCtx)
494
- : await applyPackageChoice(action.type === "update" ? `Update to ${action.row.latest}` : "Remove", action.row, natives, inlineCtx, onSettled);
495
- updatingRowName = undefined;
496
- if (outcome === "changed") {
497
- done(undefined); // ctx.reload() already replaced the session
498
- return;
499
- }
500
- const reloaded = await loadRows(natives);
501
- if (reloaded.error) ctx.ui.notify(`refresh failed: ${reloaded.error}`, "error");
502
- else rows = reloaded.rows;
503
- applyFilter();
504
- tui.requestRender();
505
- }
746
+ const measure: TextMeasure = { visibleWidth, truncateToWidth };
506
747
 
507
- /** U -- runs the whole approve+update+notify+reload flow without ever
508
- * closing this panel or replacing the list: each row's own settled
509
- * outcome (spinner while in flight, then a real ✓/✗ plus a bounded tail
510
- * of its actual captured output) appears inline next to that row, via
511
- * updatingRowName/spinner/settled, which list's own render checks. Rows
512
- * refresh in place afterward unless a reload already ended the session. */
513
- async function runUpdateAllInline(): Promise<void> {
514
- const outdated = rows.filter((row) => row.hasUpdate);
515
- settled.clear();
516
- const outcome = await approveAndRunUpdateAll(outdated, natives, inlineCtx, (batch, approved) => {
517
- spinner.start(() => tui.requestRender());
518
- return performUpdateAll(batch, natives, approved, (event) => {
519
- updatingRowName = event.row.name;
520
- if (event.phase === "done" && event.result) {
521
- settled.set(event.row.name, { ok: event.result.ok, tail: logTail(event.result.output) });
522
- }
523
- tui.requestRender();
524
- }).finally(() => spinner.stop());
525
- });
526
- updatingRowName = undefined;
527
- if (outcome === "changed") {
528
- done(undefined); // ctx.reload() already replaced the session
529
- return;
530
- }
531
- const reloaded = await loadRows(natives);
532
- if (reloaded.error) ctx.ui.notify(`refresh failed: ${reloaded.error}`, "error");
533
- else rows = reloaded.rows;
534
- settled.clear(); // fresh state for a subsequent batch
535
- applyFilter();
536
- tui.requestRender();
537
- }
748
+ const packagesTab = new PackagesTab(natives, host, theme, measure, initialRows, (target, configFilter) => {
749
+ if (target === "config" && configFilter !== undefined) configTab.setFilter(configFilter);
750
+ tabbedContainer.setActive(target);
751
+ });
538
752
 
539
- function panelTitle(): string {
540
- if (updatingRowName) return "Packages · updating…";
541
- const outdated = rows.filter((r) => r.hasUpdate).length;
542
- return outdated > 0 ? `Packages · ${outdated} update(s)` : "Packages";
543
- }
753
+ const findTab = createFindTab(natives, host, theme);
544
754
 
545
- const header = {
546
- invalidate() {},
547
- render(width: number): string[] {
548
- const hint = searchActive
549
- ? rawKeyHint("esc", "clear")
550
- : rawKeyHint("enter", "menu") +
551
- theme.fg("muted", " · ") +
552
- rawKeyHint("u/U", "update/all") +
553
- theme.fg("muted", " · ") +
554
- rawKeyHint("x", "remove") +
555
- theme.fg("muted", " · ") +
556
- rawKeyHint("d", "disable") +
557
- theme.fg("muted", " · ") +
558
- rawKeyHint("c", "config") +
559
- theme.fg("muted", " · ") +
560
- rawKeyHint("f", "find") +
561
- theme.fg("muted", " · ") +
562
- rawKeyHint("s", "settings") +
563
- theme.fg("muted", " · ") +
564
- rawKeyHint("esc", "close");
565
- const line1 = truncateToWidth(hint, width, "");
566
- const dot = "·";
567
- const line2 = truncateToWidth(
568
- theme.fg("muted", `view: ${mode} ${dot} / filter ${dot} tab view ${dot} r refresh ${dot} ${rows.length} installed`),
569
- width,
570
- "",
571
- );
572
- return [line1, line2];
573
- },
574
- };
755
+ // Config/Settings both need theme (only available once this factory
756
+ // runs) so they're constructed here rather than before the overlay
757
+ // opens; both load their own data asynchronously in the background and
758
+ // render their own "Loading…" state until it resolves -- no
759
+ // placeholder-swap machinery needed.
760
+ const configTab = new ConfigTab(natives, host, theme, initialTab === "config" ? initialConfigFilter : undefined);
761
+ void configTab.load().then(() => tui.requestRender());
575
762
 
576
- // pi-tui's own visibleWidth/truncateToWidth are ANSI-aware (they strip
577
- // escape codes for measurement, matching the pair Malevich's TextMeasure
578
- // port expects) -- rows below bake selection/status styling directly
579
- // into each cell's text since Table's own cellStyle is column-wide, not
580
- // per-row.
581
- const measure: TextMeasure = { visibleWidth, truncateToWidth };
582
- const columns: TableColumn[] = [
583
- { header: "Package", key: "name" },
584
- { header: "Version", key: "version" },
585
- { header: "", key: "status" },
586
- ];
587
- const table = new Table({ columns, rows: [], measure, headerStyle: (s) => theme.fg("muted", s) });
588
-
589
- const list = {
590
- invalidate() {},
591
- render(width: number): string[] {
592
- const lines: string[] = [];
593
- if (searchActive) lines.push(...searchInput.render(width));
594
- lines.push("");
595
- if (filtered.length === 0) {
596
- lines.push(theme.fg("muted", " No packages"));
597
- return lines;
598
- }
599
- // No scrolling of its own (Malevich's Table is deliberately
600
- // unopinionated about pagination) -- the visible window around
601
- // selectedIndex stays this panel's own job, same as before.
602
- const start = Math.max(0, Math.min(selectedIndex - Math.floor(maxVisible / 2), filtered.length - maxVisible));
603
- const end = Math.min(start + maxVisible, filtered.length);
604
- table.setRows(
605
- filtered.slice(start, end).map((row, offset) => {
606
- const i = start + offset;
607
- const selected = i === selectedIndex;
608
- const cursor = selected ? theme.fg("accent", "❯ ") : " ";
609
- const name = selected ? theme.bold(row.name) : row.name;
610
- // A settled row shows its real outcome even for the instant
611
- // before the next row's "start" event moves updatingRowName
612
- // off it -- settled always wins over "still spinning".
613
- const rowSettled = settled.get(row.name);
614
- const isUpdating = !rowSettled && updatingRowName === row.name;
615
- const status = isUpdating
616
- ? theme.fg("accent", `${spinner.glyph()} updating…`)
617
- : rowSettled
618
- ? theme.fg(rowSettled.ok ? "success" : "error", `${rowSettled.ok ? "✓" : "✗"}${rowSettled.tail ? ` ${rowSettled.tail}` : ""}`)
619
- : row.hasUpdate ? theme.fg("warning", `↑${row.latest}`) : "";
620
- return { name: `${cursor}${name}`, version: theme.fg("dim", row.version), status };
621
- }),
622
- );
623
- lines.push(...table.render(width));
624
- const hasScroll = start > 0 || end < filtered.length;
625
- lines.push(theme.fg("dim", ` ${hasScroll ? `${selectedIndex + 1}/${filtered.length} ` : ""}${mode}`));
626
- return lines;
627
- },
763
+ const settingsTab = new SettingsTab(natives, host, theme);
764
+ void settingsTab.load().then(() => tui.requestRender());
765
+
766
+ const tabByKey: Record<PackedTabKey, Component & TabScope> = {
767
+ packages: packagesTab,
768
+ find: findTab,
769
+ config: configTab,
770
+ settings: settingsTab,
628
771
  };
629
772
 
630
- // Real bordered box (rounded corners), not just a horizontal rule --
631
- // title carries the live update badge/status instead of a header line.
773
+ const tabbedContainer = new TabbedContainer({
774
+ tabs: [
775
+ { key: "packages", label: "Packages", content: tabByKey.packages },
776
+ { key: "find", label: "Find", content: tabByKey.find },
777
+ { key: "config", label: "Config", content: tabByKey.config },
778
+ { key: "settings", label: "Settings", content: tabByKey.settings },
779
+ ],
780
+ theme: tabBarTheme(theme),
781
+ initialKey: initialTab,
782
+ });
783
+
632
784
  // measure must be explicit: Envelope's own default is ASCII-only (raw
633
- // .length, blind to ANSI escape codes) and every line below is styled
634
- // through theme.fg/theme.bold -- without this, Envelope pads each line
635
- // against its own escape-code-inflated "length" instead of its real
636
- // visible width, so the right border lands at a different column on
637
- // every line depending on how much styling that particular line has.
785
+ // .length, blind to ANSI escape codes) and every tab's own content is
786
+ // styled through theme.fg/theme.bold -- without this, Envelope pads
787
+ // each line against its own escape-code-inflated "length" instead of
788
+ // its real visible width, so the right border lands at a different
789
+ // column on every line depending on how much styling it carries.
638
790
  const envelope = new Envelope({
639
- title: panelTitle(),
791
+ title: "packed",
640
792
  borderStyle: "rounded",
641
793
  style: (s) => theme.fg("border", s),
642
794
  titleStyle: (s) => theme.bold(theme.fg("accent", s)),
643
795
  measure,
644
796
  });
645
- const body = {
646
- invalidate() { header.invalidate(); list.invalidate(); },
647
- render(width: number): string[] {
648
- return [...header.render(width), "", ...list.render(width)];
649
- },
650
- };
651
- envelope.setContent(body);
652
797
 
653
798
  return {
654
799
  render(width: number): string[] {
655
- envelope.setTitle(panelTitle());
656
- envelope.setContent(pendingDialog ?? body);
800
+ envelope.setContent(pendingDialog ?? tabbedContainer);
657
801
  return envelope.render(width);
658
802
  },
659
803
  invalidate: () => envelope.invalidate(),
@@ -663,85 +807,49 @@ function renderPanel(ctx: ExtensionCommandContext, natives: Natives, initialRows
663
807
  tui.requestRender();
664
808
  return;
665
809
  }
666
- if (updatingRowName) return; // the mutation/installer owns input until it finishes
667
-
668
- if (searchActive) {
669
- if (data === "\x1b") {
670
- searchActive = false;
671
- searchInput.setValue?.("");
672
- applyFilter();
673
- } else if (data === "\r") {
674
- searchActive = false;
675
- } else {
676
- searchInput.handleInput(data);
677
- applyFilter();
678
- }
810
+ const activeKey = tabbedContainer.getActiveKey() as PackedTabKey;
811
+ const activeTab = tabByKey[activeKey];
812
+ // Each host-level key is checked against that tab's own capture flag
813
+ // independently -- conflating them would, e.g., let Find's always-on
814
+ // capturesHorizontalArrows() also swallow Escape into the query box
815
+ // instead of navigating back.
816
+ if (data === "\x1b" && !(activeTab.capturesEscape?.() ?? false)) {
817
+ if (activeKey !== "packages") tabbedContainer.setActive("packages");
818
+ else { done(undefined); return; }
679
819
  tui.requestRender();
680
820
  return;
681
821
  }
682
-
683
- switch (data) {
684
- case "\x1b[A": // up
685
- selectedIndex = (selectedIndex - 1 + filtered.length) % Math.max(filtered.length, 1);
686
- break;
687
- case "\x1b[B": // down
688
- selectedIndex = (selectedIndex + 1) % Math.max(filtered.length, 1);
689
- break;
690
- case "\t":
691
- mode = nextMode(mode);
692
- applyFilter();
693
- break;
694
- case "/":
695
- searchActive = true;
696
- break;
697
- case "r":
698
- done({ type: "refresh" });
699
- return;
700
- case "s":
701
- done({ type: "settings" });
702
- return;
703
- case "f":
704
- done({ type: "find" });
705
- return;
706
- case "U":
707
- void runUpdateAllInline();
708
- return;
709
- case "u": {
710
- const row = filtered[selectedIndex];
711
- if (row?.hasUpdate) void runRowActionInline({ type: "update", row });
712
- return;
713
- }
714
- case "x": {
715
- const row = filtered[selectedIndex];
716
- if (row) void runRowActionInline({ type: "remove", row });
717
- return;
718
- }
719
- case "d": {
720
- const row = filtered[selectedIndex];
721
- if (row) void runRowActionInline({ type: "disable", row });
722
- return;
723
- }
724
- case "c": {
725
- const row = filtered[selectedIndex];
726
- if (row) done({ type: "config", row });
727
- return;
728
- }
729
- case "\r": {
730
- const row = filtered[selectedIndex];
731
- if (!row) return;
732
- void (async () => {
733
- const choice = await showActionMenu(ctx, row);
734
- if (choice === "update" || choice === "remove" || choice === "disable") void runRowActionInline({ type: choice, row });
735
- else if (choice === "config") done({ type: "config", row });
736
- })();
822
+ // Tab/Shift-Tab always sweep between menus -- nothing needs a literal
823
+ // Tab character for itself (Packages'/Config's own former Tab bindings
824
+ // moved to v once Tab was claimed globally; see the mnemonics.test.ts
825
+ // conflict check for why that reassignment was necessary).
826
+ if (data === "\t" || data === "\x1b[Z") {
827
+ tabbedContainer.handleInput(data);
828
+ tui.requestRender();
829
+ return;
830
+ }
831
+ if ((data === "\x1b[C" || data === "\x1b[D") && !(activeTab.capturesHorizontalArrows?.() ?? false)) {
832
+ tabbedContainer.handleInput(data); // owns Left/Right cycling itself
833
+ tui.requestRender();
834
+ return;
835
+ }
836
+ // The first letter of each tab's label is a jump mnemonic
837
+ // (Packages/Find/Config/Settings -> p/f/c/s), highlighted in the tab
838
+ // bar itself -- but only reachable FROM one of the other three tabs.
839
+ // Packages' own f/c/s bindings already do the same jump (c
840
+ // additionally scopes Config to the selected row); letting the
841
+ // generic version fire there too would just be redundant, not wrong,
842
+ // but skipping it keeps this one dispatcher the single source of
843
+ // truth for "which code path actually owns key X" per active tab.
844
+ if (activeKey !== "packages" && data.length === 1) {
845
+ const target = tabbedContainer.resolveMnemonic(data);
846
+ if (target && target !== activeKey && !(activeTab.capturesMnemonics?.() ?? false)) {
847
+ tabbedContainer.setActive(target as PackedTabKey);
848
+ tui.requestRender();
737
849
  return;
738
850
  }
739
- case "\x1b":
740
- done(undefined);
741
- return;
742
- default:
743
- return;
744
851
  }
852
+ activeTab.handleInput?.(data);
745
853
  tui.requestRender();
746
854
  },
747
855
  };