@oh-my-pi/pi-tui 18.8.5 → 18.8.7

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 (76) hide show
  1. package/CHANGELOG.md +30 -16
  2. package/README.md +7 -5
  3. package/dist/types/chat/assistant-message.d.ts +1 -0
  4. package/dist/types/chat/compaction-summary-message.d.ts +1 -0
  5. package/dist/types/chat/user-message.d.ts +2 -0
  6. package/dist/types/components/box.d.ts +1 -0
  7. package/dist/types/components/disclosure.d.ts +1 -0
  8. package/dist/types/components/image.d.ts +1 -0
  9. package/dist/types/components/key-value-list.d.ts +1 -0
  10. package/dist/types/components/layout/row.d.ts +1 -0
  11. package/dist/types/components/layout/stack.d.ts +1 -0
  12. package/dist/types/components/markdown.d.ts +1 -0
  13. package/dist/types/components/scroll-view.d.ts +1 -0
  14. package/dist/types/components/section.d.ts +1 -0
  15. package/dist/types/components/table.d.ts +1 -0
  16. package/dist/types/components/text.d.ts +1 -0
  17. package/dist/types/components/truncated-text.d.ts +1 -0
  18. package/dist/types/native/blobs.d.ts +3 -1
  19. package/dist/types/overlays/session-selector.d.ts +6 -2
  20. package/dist/types/render/output-pane.d.ts +1 -0
  21. package/dist/types/render/render-utils.d.ts +1 -0
  22. package/dist/types/render/tool-card.d.ts +6 -0
  23. package/dist/types/render/width-aware-text.d.ts +2 -0
  24. package/dist/types/terminal.d.ts +10 -2
  25. package/dist/types/theme/theme.d.ts +1 -1
  26. package/dist/types/theme/tui-adapters.d.ts +3 -0
  27. package/dist/types/tools/write.d.ts +1 -1
  28. package/dist/types/tools/yield.d.ts +22 -0
  29. package/dist/types/tui.d.ts +11 -0
  30. package/package.json +13 -9
  31. package/src/chat/advisor-message.ts +11 -0
  32. package/src/chat/assistant-message.ts +8 -2
  33. package/src/chat/compaction-summary-message.ts +8 -0
  34. package/src/chat/read-tool-group.ts +6 -4
  35. package/src/chat/skill-message.ts +6 -0
  36. package/src/chat/table-chart.ts +17 -20
  37. package/src/chat/tool-execution.ts +18 -0
  38. package/src/chat/user-message.ts +14 -0
  39. package/src/chrome/transcript-container.ts +32 -1
  40. package/src/components/box.ts +5 -0
  41. package/src/components/disclosure.ts +8 -0
  42. package/src/components/image.ts +7 -5
  43. package/src/components/key-value-list.ts +4 -0
  44. package/src/components/layout/row.ts +7 -0
  45. package/src/components/layout/stack.ts +7 -0
  46. package/src/components/markdown.ts +190 -8
  47. package/src/components/scroll-view.ts +5 -0
  48. package/src/components/section.ts +5 -0
  49. package/src/components/table.ts +4 -0
  50. package/src/components/text.ts +7 -0
  51. package/src/components/truncated-text.ts +5 -0
  52. package/src/native/backend.ts +16 -15
  53. package/src/native/blobs.ts +43 -10
  54. package/src/native/reconcile.ts +4 -0
  55. package/src/overlays/model-hub.ts +39 -4
  56. package/src/overlays/session-selector.ts +40 -22
  57. package/src/overlays/snapcompact-shape-preview.ts +2 -3
  58. package/src/prompt/attachment-chips.ts +13 -10
  59. package/src/prompt/tips.txt +2 -1
  60. package/src/prompt/welcome.ts +46 -9
  61. package/src/render/output-pane.ts +6 -0
  62. package/src/render/render-utils.ts +11 -0
  63. package/src/render/tool-card.ts +15 -0
  64. package/src/render/width-aware-text.ts +5 -0
  65. package/src/terminal.ts +24 -3
  66. package/src/theme/theme.ts +1 -0
  67. package/src/theme/tui-adapters.ts +68 -0
  68. package/src/tools/bash.ts +10 -11
  69. package/src/tools/edit.ts +142 -120
  70. package/src/tools/fetch.ts +5 -6
  71. package/src/tools/index.ts +2 -0
  72. package/src/tools/mcp.ts +15 -2
  73. package/src/tools/read.ts +7 -5
  74. package/src/tools/write.ts +70 -56
  75. package/src/tools/yield.ts +225 -0
  76. package/src/tui.ts +25 -0
@@ -41,6 +41,11 @@ export class TruncatedText implements Component {
41
41
  this.#cachedLines = undefined;
42
42
  }
43
43
 
44
+ releaseRenderCaches(): void {
45
+ this.#cachedWidth = -1;
46
+ this.#cachedLines = undefined;
47
+ }
48
+
44
49
  /** First line only, clamped to one visual line with an end ellipsis. */
45
50
  describe(_cx: DescribeContext): NativeNode {
46
51
  if (this.#native) return this.#native;
@@ -305,8 +305,8 @@ export class NativeBackend {
305
305
  #paletteKey: string | undefined;
306
306
  /** Serialized palette last sent, to skip resends of an unchanged theme. */
307
307
  #paletteSent: string | undefined;
308
- /** Blobs handled on this connection: asked about in a `blobs` query, or sent (or held by the terminal). */
309
- #blobs = new Map<string, "asked" | "sent">();
308
+ /** Pending delivery owns bytes until sent or confirmed held; settled descriptions may already be released. */
309
+ #blobs = new Map<string, NativeBlob | "sent">();
310
310
  /** `blobs` queries sent, oldest first: the terminal answers each once, in order. */
311
311
  #blobQueries: BlobQuery[] = [];
312
312
  /** The next pass with new blobs asks the terminal which it holds (a fresh connection). */
@@ -663,13 +663,13 @@ export class NativeBackend {
663
663
  }
664
664
  const dir = Bun.env.TERN_BLOB_DIR;
665
665
  if (dir) {
666
- for (const blob of fresh) this.#blobs.set(blob.id, "asked");
666
+ for (const blob of fresh) this.#blobs.set(blob.id, blob);
667
667
  void this.#cacheBlobs(dir, fresh);
668
668
  return;
669
669
  }
670
670
  if (this.#askHeld) {
671
671
  this.#askHeld = false;
672
- this.#askBlobs(fresh.map(blob => blob.id));
672
+ this.#askBlobs(fresh);
673
673
  return;
674
674
  }
675
675
  for (const blob of fresh) this.#sendBlob(blob);
@@ -680,13 +680,14 @@ export class NativeBackend {
680
680
  const epoch = this.#blobEpoch;
681
681
  await Promise.all(blobs.map(blob => cacheBlob(dir, blob)));
682
682
  if (epoch !== this.#blobEpoch) return;
683
- const ids = blobs.map(blob => blob.id).filter(id => this.#blobs.get(id) === "asked");
684
- if (ids.length > 0) this.#askBlobs(ids);
683
+ const pending = blobs.filter(blob => this.#blobs.get(blob.id) === blob);
684
+ if (pending.length > 0) this.#askBlobs(pending);
685
685
  }
686
686
 
687
- /** Ask the terminal which of `ids` it holds; the reply (or its absence) settles them. */
688
- #askBlobs(ids: readonly string[]): void {
689
- for (const id of ids) this.#blobs.set(id, "asked");
687
+ /** Ask the terminal which of `blobs` it holds; the reply (or its absence) settles them. */
688
+ #askBlobs(blobs: readonly NativeBlob[]): void {
689
+ for (const blob of blobs) this.#blobs.set(blob.id, blob);
690
+ const ids = blobs.map(blob => blob.id);
690
691
  const query: BlobQuery = { ids, timer: undefined };
691
692
  query.timer = this.#scheduler.scheduleRender(() => {
692
693
  query.timer = undefined;
@@ -707,16 +708,16 @@ export class NativeBackend {
707
708
  #onBlobsReply(have: readonly string[]): void {
708
709
  const query = this.#blobQueries.shift();
709
710
  for (const id of have) {
710
- if (this.#blobs.get(id) !== "asked") continue;
711
- this.#blobs.set(id, "sent");
711
+ const blob = this.#blobs.get(id);
712
+ if (blob === undefined || blob === "sent") continue;
712
713
  // The bytes went another way; a recording still carries them so a replay without them shows the image.
713
- const blob = this.#recordPath ? getNativeBlob(id) : undefined;
714
- if (blob) {
714
+ if (this.#recordPath) {
715
715
  const body = Buffer.from(blob.bytes.buffer, blob.bytes.byteOffset, blob.bytes.byteLength).toString(
716
716
  "base64",
717
717
  );
718
718
  this.#record("out", "b", blobParams(blob), body);
719
719
  }
720
+ this.#blobs.set(id, "sent");
720
721
  }
721
722
  if (!query?.timer) return;
722
723
  query.timer.cancel();
@@ -727,8 +728,8 @@ export class NativeBackend {
727
728
  /** Send inline every id of `ids` still waiting on a query. */
728
729
  #sendMissing(ids: readonly string[]): void {
729
730
  for (const id of ids) {
730
- const blob = this.#blobs.get(id) === "asked" ? getNativeBlob(id) : undefined;
731
- if (blob) this.#sendBlob(blob);
731
+ const blob = this.#blobs.get(id);
732
+ if (blob !== undefined && blob !== "sent") this.#sendBlob(blob);
732
733
  }
733
734
  }
734
735
 
@@ -18,7 +18,13 @@ export interface NativeBlob {
18
18
  readonly bytes: Uint8Array;
19
19
  }
20
20
 
21
- const blobs = new Map<string, NativeBlob>();
21
+ const blobs = new Map<string, WeakRef<NativeBlob>>();
22
+ const registeredBlobs = new Map<string, NativeBlob>();
23
+ const releasedBlobs = new FinalizationRegistry<{ id: string; reference: WeakRef<NativeBlob> }>(({ id, reference }) => {
24
+ if (blobs.get(id) === reference) blobs.delete(id);
25
+ });
26
+ // Props spreads preserve ownership; wire serialization omits symbol keys.
27
+ const kBlob = Symbol("native.blob");
22
28
  // Registration usually repeats with the same bytes object on every describe;
23
29
  // the tag skips rehashing it.
24
30
  const kBlobId = Symbol("native.blobId");
@@ -27,19 +33,42 @@ interface BlobTagged {
27
33
  [kBlobId]?: string;
28
34
  }
29
35
 
30
- /** Register `bytes` and return their content address (sha256 hex) for `image.p.blob`. */
31
- export function registerNativeBlob(bytes: Uint8Array, mime: string): string {
36
+ function getOrCreateBlob(bytes: Uint8Array, mime: string): NativeBlob {
32
37
  const known = (bytes as BlobTagged)[kBlobId];
33
- if (known !== undefined) return known;
34
- const id = new Bun.CryptoHasher("sha256").update(bytes).digest("hex");
38
+ const id = known ?? new Bun.CryptoHasher("sha256").update(bytes).digest("hex");
35
39
  (bytes as BlobTagged)[kBlobId] = id;
36
- if (!blobs.has(id)) blobs.set(id, { id, mime, bytes });
37
- return id;
40
+ let blob = blobs.get(id)?.deref();
41
+ if (!blob) {
42
+ blob = { id, mime, bytes };
43
+ const reference = new WeakRef(blob);
44
+ blobs.set(id, reference);
45
+ releasedBlobs.register(blob, { id, reference });
46
+ }
47
+ return blob;
48
+ }
49
+
50
+ /** Register bytes for process-lifetime, id-only use. Prefer {@link nativeImageNode} for owned images. */
51
+ export function registerNativeBlob(bytes: Uint8Array, mime: string): string {
52
+ const blob = getOrCreateBlob(bytes, mime);
53
+ registeredBlobs.set(blob.id, blob);
54
+ return blob.id;
38
55
  }
39
56
 
40
57
  /** A registered blob by id. */
41
58
  export function getNativeBlob(id: string): NativeBlob | undefined {
42
- return blobs.get(id);
59
+ return blobs.get(id)?.deref();
60
+ }
61
+
62
+ /** An image whose props own its bytes, including while hidden, unmounted, or awaiting upload. */
63
+ export function nativeImageNode(
64
+ bytes: Uint8Array,
65
+ mime: string,
66
+ p?: Omit<TspProps<"image">, "blob" | "builtin">,
67
+ key?: string,
68
+ ): NativeNode {
69
+ const blob = getOrCreateBlob(bytes, mime);
70
+ const props = { ...p, blob: blob.id, [kBlob]: blob };
71
+ return node("image", props, undefined, key);
43
72
  }
44
73
 
45
74
  /**
@@ -53,9 +82,13 @@ export function base64ImageNode(
53
82
  p?: Omit<TspProps<"image">, "blob" | "builtin" | "w" | "h">,
54
83
  key?: string,
55
84
  ): NativeNode {
56
- const blob = registerNativeBlob(Buffer.from(data, "base64"), mimeType);
57
85
  const size = getImageDimensions(data, mimeType);
58
- return node("image", size ? { ...p, blob, w: size.widthPx, h: size.heightPx } : { ...p, blob }, undefined, key);
86
+ return nativeImageNode(
87
+ Buffer.from(data, "base64"),
88
+ mimeType,
89
+ size ? { ...p, w: size.widthPx, h: size.heightPx } : p,
90
+ key,
91
+ );
59
92
  }
60
93
 
61
94
  /** `image` nodes for base64 payloads, one per slot key, rebuilt only when the slot's payload changes. */
@@ -30,6 +30,7 @@
30
30
  import * as logger from "@oh-my-pi/pi-utils/logger";
31
31
  import { TSP_TEXT_KINDS, type TspKind, type TspNode, type TspOp, type TspScrollBy } from "@oh-my-pi/pi-wire";
32
32
  import { type Component, Container, CURSOR_MARKER } from "../tui";
33
+ import { getNativeBlob } from "./blobs";
33
34
  import { normalizeIconProps } from "./icons";
34
35
  import type { DescribeContext, NativeChild, NativeNode, NativeRevealAt } from "./node";
35
36
  import { isNativeSettled } from "./settle";
@@ -291,6 +292,7 @@ export class Reconciler {
291
292
  this.#prevPortals = portals;
292
293
  this.#regions = next;
293
294
  for (const entry of this.#dels) this.#deleteEntry(entry);
295
+ this.#dels = [];
294
296
  // Parked to survive a parent/child swap but absent from the new description.
295
297
  for (const state of this.#parked) {
296
298
  if (!state.parked) continue;
@@ -711,6 +713,8 @@ export class Reconciler {
711
713
  owner: Owner,
712
714
  entries: readonly Entry[],
713
715
  ): Readonly<Record<string, unknown>> | undefined {
716
+ // Dereferencing pins the blob through this synchronous reconcile/upload job, even after settling drops its node.
717
+ if (node.k === "image" && node.p?.blob) getNativeBlob(node.p.blob);
714
718
  return normalizeIconProps(node.k, this.#resolveRefs(node, owner, entries));
715
719
  }
716
720
 
@@ -1991,7 +1991,13 @@ export class ModelHubComponent implements Component {
1991
1991
 
1992
1992
  if (rolesView) {
1993
1993
  const printable = extractPrintableText(data);
1994
- if (this.#focus === "scope" && printable !== undefined && printable.trim().length > 0) {
1994
+ // Typing searches the catalog from the sidebar, and from the rows
1995
+ // while a query is live (the picker shows its search field only
1996
+ // then); otherwise the rows' letter commands own printable keys.
1997
+ const typed = printable !== undefined && printable.trim().length > 0;
1998
+ const editsQuery =
1999
+ this.#browser.query.length > 0 && (printable !== undefined || matchesKey(data, "backspace"));
2000
+ if ((this.#focus === "scope" && typed) || editsQuery) {
1995
2001
  this.#setActiveEntry("all");
1996
2002
  this.#focus = "list";
1997
2003
  this.#browser.handleInput(data);
@@ -2434,9 +2440,14 @@ export class ModelHubComponent implements Component {
2434
2440
  Math.max(0, active),
2435
2441
  );
2436
2442
  const { names, active: activePreset } = this.#presets();
2443
+ // p/P type into a live query instead of switching presets.
2444
+ const presetKeys =
2445
+ this.#browser.query.length > 0
2446
+ ? formatKeyHints(["ctrl+left", "ctrl+right"])
2447
+ : `${formatKeyHints(["ctrl+left", "ctrl+right"])} · ${formatKeyHints(["p", "shift+p"])}`;
2437
2448
  const preset =
2438
2449
  names.length > 0
2439
- ? ` ${theme.fg("dim", "Preset:")} ${activePreset ? theme.fg("accent", activePreset) : theme.fg("muted", "custom")} ${theme.fg("dim", `${formatKeyHints(["ctrl+left", "ctrl+right"])} · ${formatKeyHints(["p", "shift+p"])}`)}`
2450
+ ? ` ${theme.fg("dim", "Preset:")} ${activePreset ? theme.fg("accent", activePreset) : theme.fg("muted", "custom")} ${theme.fg("dim", presetKeys)}`
2440
2451
  : "";
2441
2452
  return truncateToWidth(
2442
2453
  ` ${theme.fg("dim", "Roles:")} ${track} ${theme.fg("dim", formatKeyHints(["alt+left", "alt+right"]))}${preset}`,
@@ -2741,6 +2752,10 @@ export class ModelHubComponent implements Component {
2741
2752
  this.#presets().names.length > 0 ? ` · ${formatKeyHints(["ctrl+left", "ctrl+right"])} preset` : "";
2742
2753
  return `${upDown} providers · ${enterRight} roles · ${altLeftRight} tabs${presets} · ${cancel} close`;
2743
2754
  }
2755
+ // A live query takes printable keys and backspace, so the letter commands rest.
2756
+ if (this.#browser.query.length > 0) {
2757
+ return `${upDown} rows · ${enter} pick · type to search · ${left} providers · ${cancel} close`;
2758
+ }
2744
2759
  const row = this.#rolesRows[this.#roleIndex];
2745
2760
  const compaction =
2746
2761
  this.#callbacks.onCompactionPointChange && this.#roleRowModel()
@@ -3228,7 +3243,9 @@ export class ModelHubComponent implements Component {
3228
3243
  size: "lg",
3229
3244
  layout: "rows",
3230
3245
  preview: "side",
3231
- query: this.#browser.query,
3246
+ // The Roles rows' letter commands own printable keys until a query
3247
+ // is live, so the sheet offers no search field to type into.
3248
+ query: rolesView && this.#browser.query.length === 0 ? null : this.#browser.query,
3232
3249
  cursor: this.#browser.cursor,
3233
3250
  placeholder: "Search models…",
3234
3251
  scopes: this.#pickerScopes(),
@@ -3486,8 +3503,15 @@ export class ModelHubComponent implements Component {
3486
3503
  }
3487
3504
  if (rolesView) {
3488
3505
  const row = this.#rolesRows[this.#roleIndex];
3506
+ // A live query takes the letter keys: those buttons keep working but lose their keycaps.
3507
+ const searching = this.#browser.query.length > 0;
3489
3508
  const roleAction = (action: RolesAction, label: string, key: string, primary = false) =>
3490
- pickerAction(`roles:${action}`, label, key, primary ? { primary: true } : undefined);
3509
+ pickerAction(
3510
+ `roles:${action}`,
3511
+ label,
3512
+ searching && key !== "enter" ? undefined : key,
3513
+ primary ? { primary: true } : undefined,
3514
+ );
3491
3515
  const actions: (TspPickerAction | undefined)[] = [];
3492
3516
  const compaction =
3493
3517
  this.#callbacks.onCompactionPointChange && this.#roleRowModel()
@@ -4042,6 +4066,17 @@ export class ModelHubComponent implements Component {
4042
4066
  cancel("close"),
4043
4067
  ];
4044
4068
  }
4069
+ // A live query takes printable keys and backspace, so the letter commands rest.
4070
+ if (this.#browser.query.length > 0) {
4071
+ return [
4072
+ upDown("rows"),
4073
+ keys("pick", "enter"),
4074
+ search,
4075
+ keys("providers", "left"),
4076
+ presetHint,
4077
+ cancel("close"),
4078
+ ];
4079
+ }
4045
4080
  const row = this.#rolesRows[this.#roleIndex];
4046
4081
  const compaction =
4047
4082
  this.#callbacks.onCompactionPointChange && this.#roleRowModel() ? keys("compaction limit", "k") : undefined;
@@ -525,12 +525,12 @@ class SessionList<T extends SessionSelectorEntry> implements Component {
525
525
  readonly #getCurrentSessionPath: () => string | undefined;
526
526
  readonly #historyMatcher?: SessionHistoryMatcher;
527
527
  #historyMergeTimer: NodeJS.Timeout | undefined;
528
- /** Re-render hook for async list updates (fuzzy scan chunks, history merge). */
528
+ /** Re-render hook for async list updates (fuzzy scan completion, history merge). */
529
529
  onRequestRender?: () => void;
530
530
 
531
531
  // ── Incremental search state ──────────────────────────────────────────
532
532
  // The menu's visible list is always composed from these three inputs (see
533
- // #composeFiltered), so late-arriving fuzzy chunks and the debounced
533
+ // #composeFiltered), so a late-finishing fuzzy scan and the debounced
534
534
  // history merge can land in any order without clobbering each other.
535
535
  /** Recency-ranked sessions whose text contains every query token verbatim. */
536
536
  #literalRanked: RankedSessionMatch<T>[] = [];
@@ -543,8 +543,8 @@ class SessionList<T extends SessionSelectorEntry> implements Component {
543
543
  #scanTimer: NodeJS.Timeout | undefined;
544
544
  /**
545
545
  * True once the user moved the selection for the current query; blocks the
546
- * history merge from reordering the list under their cursor. (Fuzzy chunks
547
- * only append below the literal group, which never shifts existing rows.)
546
+ * history merge from reordering the list under their cursor. (The fuzzy scan
547
+ * only appends below the literal group, which never shifts existing rows.)
548
548
  */
549
549
  #selectionMoved = false;
550
550
  /** True after a nonempty query; empty refilter restores current only then. */
@@ -687,38 +687,48 @@ class SessionList<T extends SessionSelectorEntry> implements Component {
687
687
  // Fuzzy pass: building a fuzzy index per session is too expensive to run
688
688
  // across a huge listing inside one keystroke, so scan a bounded slice now
689
689
  // and spill the remainder into async chunks.
690
- this.#scanFuzzySlice(this.#scanGeneration, tokens, rest, 0, FUZZY_SCAN_INLINE_COUNT);
690
+ const inlineEnd = Math.min(rest.length, FUZZY_SCAN_INLINE_COUNT);
691
+ this.#scoreFuzzy(tokens, rest, 0, inlineEnd);
691
692
  this.#composeFiltered();
693
+ if (inlineEnd < rest.length) {
694
+ this.#scheduleFuzzyScan(this.#scanGeneration, tokens, rest, inlineEnd, this.#fuzzyRanked.length);
695
+ }
692
696
  // New query rebuilds ranking from scratch. Same-query refilter (delete)
693
- // and async compose (fuzzy chunks / history merge) only clamp so an
697
+ // and async compose (fuzzy scan / history merge) only clamp so an
694
698
  // arrow selection survives. A live-session index > 0 would otherwise
695
699
  // land on a lower-ranked match after the first keystroke.
696
700
  if (queryChanged) this.#menu.setSelectedIndex(0);
697
701
  this.#scheduleHistoryMerge(query);
698
702
  }
699
703
 
700
- /**
701
- * Score up to `budget` sessions from `rest[start..]` (indexes into the
702
- * unfiltered list), then schedule the remainder on a macrotask so pending
703
- * input events run first. Chunks that added matches recompose the visible
704
- * list and request a render; a stale generation aborts silently.
705
- */
706
- #scanFuzzySlice(generation: number, tokens: string[], rest: number[], start: number, budget: number): void {
704
+ /** Fuzzy-score `rest[start..end)` (indexes into the unfiltered list) into {@link #fuzzyRanked}. */
705
+ #scoreFuzzy(tokens: string[], rest: number[], start: number, end: number): void {
707
706
  const all = this.#allSessions;
708
- const end = Math.min(rest.length, start + budget);
709
707
  for (let i = start; i < end; i++) {
710
708
  const index = rest[i]!;
711
709
  const session = all[index]!;
712
710
  const match = scoreFuzzySession(session, index, tokens, new FuzzyText(sessionTextLower(session)));
713
711
  if (match) this.#fuzzyRanked.push(match);
714
712
  }
715
- if (end >= rest.length) return;
713
+ }
714
+
715
+ /**
716
+ * Score `rest[start..]` in {@link FUZZY_SCAN_CHUNK_COUNT}-session macrotask
717
+ * chunks so pending input runs between them, then recompose the visible
718
+ * list once if the scan matched more than the `shown` fuzzy hits already
719
+ * composed. Publishing per chunk reorders the list dozens of times per
720
+ * keystroke on a large listing, and the native picker replays its
721
+ * row-arrival animation on every reorder. A stale generation aborts silently.
722
+ */
723
+ #scheduleFuzzyScan(generation: number, tokens: string[], rest: number[], start: number, shown: number): void {
716
724
  this.#scanTimer = setTimeout(() => {
717
725
  this.#scanTimer = undefined;
718
726
  if (generation !== this.#scanGeneration) return;
719
- const before = this.#fuzzyRanked.length;
720
- this.#scanFuzzySlice(generation, tokens, rest, end, FUZZY_SCAN_CHUNK_COUNT);
721
- if (this.#fuzzyRanked.length > before) {
727
+ const end = Math.min(rest.length, start + FUZZY_SCAN_CHUNK_COUNT);
728
+ this.#scoreFuzzy(tokens, rest, start, end);
729
+ if (end < rest.length) {
730
+ this.#scheduleFuzzyScan(generation, tokens, rest, end, shown);
731
+ } else if (this.#fuzzyRanked.length > shown) {
722
732
  this.#composeFiltered();
723
733
  this.onRequestRender?.();
724
734
  }
@@ -740,7 +750,7 @@ class SessionList<T extends SessionSelectorEntry> implements Component {
740
750
  tokenizeSessionQuery(this.#searchInput.getValue()),
741
751
  this.#literalRanked,
742
752
  );
743
- // Async chunks and the history merge only clamp the cursor so an arrow
753
+ // The fuzzy scan and the history merge only clamp the cursor so an arrow
744
754
  // selection survives recomposition; the query path resets explicitly.
745
755
  const keepIndex = Math.min(this.#menu.selectedIndex, Math.max(0, composed.length - 1));
746
756
  this.#menu.setItems(composed, keepIndex >= 0 ? composed[keepIndex]?.path : undefined);
@@ -1330,7 +1340,11 @@ export interface SessionSelectorOptions<T extends SessionSelectorEntry = Session
1330
1340
  title?: string;
1331
1341
  /** Fixed scope label, or false to omit the scope suffix. */
1332
1342
  scopeLabel?: string | false;
1333
- /** Show each session's working directory in the list. */
1343
+ /**
1344
+ * Show each session's working directory in the list. Defaults to on when
1345
+ * the session files live in more than one directory (e.g. the folder scope
1346
+ * merging a repository's worktrees).
1347
+ */
1334
1348
  showCwd?: boolean;
1335
1349
  /**
1336
1350
  * Reads the live terminal height so the visible window fits the viewport.
@@ -1374,6 +1388,7 @@ export class SessionSelectorComponent<T extends SessionSelectorEntry = SessionSe
1374
1388
  #onRequestRender?: () => void;
1375
1389
  readonly #loadAllSessions?: () => Promise<T[]>;
1376
1390
  #folderSessions: T[];
1391
+ readonly #folderShowCwd: boolean;
1377
1392
  #globalSessions: T[] | null = null;
1378
1393
  #scope: "folder" | "all" = "folder";
1379
1394
  #toggling = false;
@@ -1440,6 +1455,9 @@ export class SessionSelectorComponent<T extends SessionSelectorEntry = SessionSe
1440
1455
  this.#onDelete = options.onDelete;
1441
1456
  this.#loadAllSessions = options.loadAllSessions;
1442
1457
  this.#folderSessions = sessions;
1458
+ // Storage directory, not recorded cwd: one folder's sessions may record
1459
+ // symlink aliases of the same path, which must not turn the column on.
1460
+ this.#folderShowCwd = options.showCwd ?? new Set(sessions.map(session => path.dirname(session.path))).size > 1;
1443
1461
  this.#globalSessions = options.allSessions ?? null;
1444
1462
  this.#getTerminalRows = options.getTerminalRows ?? (() => 24);
1445
1463
  this.#fillHeight = options.fillHeight ?? false;
@@ -1457,7 +1475,7 @@ export class SessionSelectorComponent<T extends SessionSelectorEntry = SessionSe
1457
1475
  // projects' history (issue #3099).
1458
1476
  this.#sessionList = new SessionList(
1459
1477
  sessions,
1460
- options.showCwd ?? false,
1478
+ this.#folderShowCwd,
1461
1479
  options.historyMatcher,
1462
1480
  options.getTerminalRows,
1463
1481
  options.pinnedIds,
@@ -1530,7 +1548,7 @@ export class SessionSelectorComponent<T extends SessionSelectorEntry = SessionSe
1530
1548
  this.#sessionList.setSessions(global, true);
1531
1549
  } else {
1532
1550
  this.#scope = "folder";
1533
- this.#sessionList.setSessions(this.#folderSessions, false);
1551
+ this.#sessionList.setSessions(this.#folderSessions, this.#folderShowCwd);
1534
1552
  }
1535
1553
  this.title = this.#headerLabel();
1536
1554
  this.#onRequestRender?.();
@@ -31,7 +31,7 @@ import { theme } from "../theme/theme";
31
31
  import sampleDoc from "./snapcompact-shape-preview-doc.md" with { type: "text" };
32
32
  import type { DescribeContext, NativeNode } from "../native/node";
33
33
  import { col, node, span, text } from "../native/describe";
34
- import { registerNativeBlob } from "../native/blobs";
34
+ import { nativeImageNode } from "../native/blobs";
35
35
 
36
36
  /** Mini-frame edge in px — a small page from the real rasterizer ≈ a zoomed crop. */
37
37
  const SRC_FRAME_PX = 128;
@@ -100,8 +100,7 @@ export class SnapcompactShapePreview implements Component {
100
100
  else if (entry.state === "rendering") sample = node("spinner", { label: [span("rendering sample…", "dim")] });
101
101
  else if (entry.state === "failed") sample = text([span("(sample render failed)", "dim")]);
102
102
  else {
103
- sample = node("image", {
104
- blob: registerNativeBlob(entry.bytes, "image/png"),
103
+ sample = nativeImageNode(entry.bytes, "image/png", {
105
104
  alt: `snapcompact ${label} sample`,
106
105
  w: entry.edgePx,
107
106
  h: entry.edgePx,
@@ -12,7 +12,7 @@ import {
12
12
  visibleWidth,
13
13
  } from "../index";
14
14
  import { fileHyperlink } from "../render/hyperlink";
15
- import { registerNativeBlob } from "../native/blobs";
15
+ import { nativeImageNode } from "../native/blobs";
16
16
  import { node, row, span } from "../native/describe";
17
17
  import { plainText } from "../native/spans";
18
18
  import type { DescribeContext, NativeNode } from "../native/node";
@@ -33,12 +33,9 @@ const RESET_FG = "\x1b[39m";
33
33
  * (pastes are usually re-encoded JPEG/WebP) convert before transmit — the same pipeline
34
34
  * the transcript uses. `null` = conversion in flight or failed. */
35
35
  const kImagePng = Symbol("omp.imagePng");
36
- /** Content address of the draft image's decoded bytes, registered once for TSP `image` nodes. */
37
- const kImageBlob = Symbol("omp.imageBlob");
38
36
 
39
37
  interface ImageContentWithPng extends ImageContent {
40
38
  [kImagePng]?: ImageContent | null;
41
- [kImageBlob]?: string;
42
39
  }
43
40
 
44
41
  /**
@@ -57,7 +54,9 @@ export class AttachmentChipsBand implements Component {
57
54
  private readonly requestRender: () => void,
58
55
  ) {}
59
56
 
60
- #native: { chips: readonly ComposerChipDescriptor[]; node: NativeNode } | undefined;
57
+ #native:
58
+ | { chips: readonly ComposerChipDescriptor[]; node: NativeNode; images: ReadonlyMap<ImageContent, NativeNode> }
59
+ | undefined;
61
60
 
62
61
  /**
63
62
  * A wrapping `row` of chip `card`s (`omp.composer.chip`) titled with the
@@ -69,6 +68,7 @@ export class AttachmentChipsBand implements Component {
69
68
  const chips = this.editor.composerChips();
70
69
  if (this.#native?.chips === chips) return this.#native.node;
71
70
  const cards: NativeNode[] = [];
71
+ const images = new Map<ImageContent, NativeNode>();
72
72
  for (const chip of chips) {
73
73
  const icon = theme.symbol(
74
74
  chip.kind === "paste" ? "chip.paste" : chip.kind === "video" ? "chip.video" : "chip.image",
@@ -86,11 +86,14 @@ export class AttachmentChipsBand implements Component {
86
86
  } else {
87
87
  const dims = this.#imageDims(chip.image);
88
88
  caption = dims ? `${dims.width}x${dims.height}` : "";
89
- const image = chip.image as ImageContentWithPng;
90
- const blob = image[kImageBlob] ?? registerNativeBlob(Buffer.from(image.data, "base64"), image.mimeType);
91
- image[kImageBlob] = blob;
89
+ const image = chip.image;
90
+ const native =
91
+ images.get(image) ??
92
+ this.#native?.images.get(image) ??
93
+ nativeImageNode(Buffer.from(image.data, "base64"), image.mimeType);
94
+ images.set(image, native);
92
95
  content = node("image", {
93
- blob,
96
+ ...native.p,
94
97
  alt: title,
95
98
  w: dims?.width,
96
99
  h: dims?.height,
@@ -106,7 +109,7 @@ export class AttachmentChipsBand implements Component {
106
109
  );
107
110
  }
108
111
  const described = row(cards, { gap: "sm", wrap: true, role: "omp.composer.chips", hidden: cards.length === 0 });
109
- this.#native = { chips, node: described };
112
+ this.#native = { chips, node: described, images };
110
113
  return described;
111
114
  }
112
115
 
@@ -30,4 +30,5 @@ Turn on `/advisor` to attach a second model that reviews every turn and quietly
30
30
  Try starting your prompt with a ->, and writing a list (1. Do X, 2. Do Y)
31
31
  Press {key:shift+tab} to cycle through reasoning effort levels
32
32
  omp can reconfigure and extend itself — ask any questions you have!
33
- Lint/type errors piling up? `omp cleanse` (or /cleanse right here) hunts project diagnostics and fixes them with parallel subagents — {key:escape} cancels
33
+ Lint/type errors piling up? `omp cleanse` (or /cleanse right here) hunts project diagnostics and fixes them with parallel subagents — {key:escape} cancels
34
+ [NO-TERN] Psst, omp has a natural habitat 🐦 [tern](https://scl.so/tern)
@@ -5,21 +5,32 @@ import { editorKey } from "../chrome/keybinding-hints";
5
5
  import { getKeybindings, type Keybinding } from "../keybindings";
6
6
  import { card, col, keyed, node, row, span, text } from "../native/describe";
7
7
  import type { DescribeContext, NativeChild, NativeNode } from "../native/node";
8
- import { plainLine } from "../native/spans";
8
+ import { compactText, plainText } from "../native/spans";
9
9
  import { isNativeRendering } from "../native/state";
10
+ import { isHyperlinkEnabled, urlHyperlink, urlLinkSpan } from "../render/hyperlink";
10
11
  import { TERMINAL } from "../terminal-capabilities";
11
12
  import { theme } from "../theme/theme";
12
13
  import type { Component } from "../tui";
13
14
  import { padding, replaceTabs, visibleWidth, wrapTextWithAnsi } from "../utils";
14
15
  import tipsText from "./tips.txt" with { type: "text" };
15
16
 
16
- /** Tips embedded at build time, one per line; blanks dropped. Key placeholders
17
+ /** Leading marker for a tip that pitches Tern: shown only while no TSP surface
18
+ * is live, since a live one means the user is already in Tern. */
19
+ const NO_TERN_TIP_MARKER = /^\[NO-TERN\]\s*/;
20
+
21
+ /** tips.txt lines embedded at build time; blanks dropped. Key placeholders
17
22
  * (see {@link expandTipKeys}) stay raw until render time. */
18
- const TIPS: readonly string[] = tipsText
23
+ const TIP_LINES: readonly string[] = tipsText
19
24
  .split("\n")
20
25
  .map(line => line.trim())
21
26
  .filter(line => line.length > 0);
22
27
 
28
+ /** Tips for the classic renderer: every tip, {@link NO_TERN_TIP_MARKER} stripped. */
29
+ const TIPS: readonly string[] = TIP_LINES.map(line => line.replace(NO_TERN_TIP_MARKER, ""));
30
+
31
+ /** Tips for a live TSP surface: those marked {@link NO_TERN_TIP_MARKER} dropped. */
32
+ const TSP_TIPS: readonly string[] = TIP_LINES.filter(line => !NO_TERN_TIP_MARKER.test(line));
33
+
23
34
  /** Trailing marker that flags a tip as a "what's new" callout. Stripped before
24
35
  * wrapping (with any preceding whitespace) and replaced by {@link NEW_TAG_TEXT}
25
36
  * painted as a shimmering rainbow. Non-global so `.test` stays stateless. */
@@ -107,6 +118,31 @@ function expandTipKeys(tip: string): string {
107
118
  });
108
119
  }
109
120
 
121
+ /** Markdown-style links in tips.txt: `[Tern](https://scl.so/tern)` shows the label, linked to the URL. */
122
+ const TIP_LINK = /\[([^\]]+)\]\(([^\s)]+)\)/g;
123
+
124
+ /** Tip links as underlined OSC 8 labels, or `label (url)` where the terminal cannot link. */
125
+ function linkTipText(tip: string): string {
126
+ const linkable = isHyperlinkEnabled();
127
+ return tip.replace(TIP_LINK, (_link, label: string, url: string) =>
128
+ linkable ? urlHyperlink(url, theme.underline(label)) : `${label} (${url})`,
129
+ );
130
+ }
131
+
132
+ /** The tip as native text: escapes dropped, links as `href` spans. */
133
+ function tipSpans(tip: string): TspSpan[] {
134
+ const spans: TspSpan[] = [];
135
+ let cursor = 0;
136
+ for (const match of tip.matchAll(TIP_LINK)) {
137
+ const [link, label, url] = match;
138
+ if (match.index > cursor) spans.push(span(plainText(tip.slice(cursor, match.index))));
139
+ spans.push(urlLinkSpan(url, label));
140
+ cursor = match.index + link.length;
141
+ }
142
+ if (cursor < tip.length) spans.push(span(plainText(tip.slice(cursor))));
143
+ return spans;
144
+ }
145
+
110
146
  /**
111
147
  * The welcome tip as lines of at most `width` columns: `Tip:` and the body
112
148
  * wrapped together, with no indent, so the banner can center each line.
@@ -117,7 +153,7 @@ export function renderWelcomeTip(tip: string, width: number, phase = 0): string[
117
153
  if (width - visibleWidth(label) < 8) return [];
118
154
 
119
155
  const isNew = NEW_TIP_MARKER.test(tip);
120
- const body = expandTipKeys(isNew ? tip.replace(NEW_TIP_MARKER, "") : tip);
156
+ const body = linkTipText(expandTipKeys(isNew ? tip.replace(NEW_TIP_MARKER, "") : tip));
121
157
 
122
158
  // Trailing spaces left by the wrap would count toward the width the banner centers.
123
159
  const wrapped = wrapTextWithAnsi(replaceTabs(`${label}${body}`), width).map(line => line.trimEnd());
@@ -164,9 +200,10 @@ export class WelcomeComponent implements Component {
164
200
  #animTimer: Timer | null = null;
165
201
  #requestRender: (() => void) | null = null;
166
202
  // Tip randomness is latched once so the tip is stable across renders, but
167
- // the nerdfont-nag gate re-reads the live preset: the startup prepaint can
168
- // run under the default "unicode" preset before settings resolve the real
169
- // one, and a memoized nag would survive the switch to "nerd".
203
+ // the nerdfont-nag gate re-reads the live preset and the pool re-reads the
204
+ // live TSP state: the startup prepaint can run under the default "unicode"
205
+ // preset before settings resolve the real one, and an optimistic Tern start
206
+ // falls back to the classic renderer when `hello` never confirms.
170
207
  #nagRoll: number | undefined;
171
208
  #tipRoll: number | undefined;
172
209
  // Render cache: the welcome box is the first transcript-area component, so
@@ -183,7 +220,7 @@ export class WelcomeComponent implements Component {
183
220
  if (theme.getSymbolPreset() === "unicode" && this.#nagRoll < 0.1) {
184
221
  return "Please use nerdfont 😭.";
185
222
  }
186
- return pickWeightedTip(TIPS, this.#tipRoll) || undefined;
223
+ return pickWeightedTip(isNativeRendering() ? TSP_TIPS : TIPS, this.#tipRoll) || undefined;
187
224
  }
188
225
 
189
226
  invalidate(): void {
@@ -237,7 +274,7 @@ export class WelcomeComponent implements Component {
237
274
  const body: NativeChild[] = [lockupRow];
238
275
  if (tip) {
239
276
  const isNew = NEW_TIP_MARKER.test(tip);
240
- const tipText = plainLine(expandTipKeys(isNew ? tip.replace(NEW_TIP_MARKER, "") : tip));
277
+ const tipText = compactText(tipSpans(expandTipKeys(isNew ? tip.replace(NEW_TIP_MARKER, "") : tip)));
241
278
  const tipRow: NativeChild[] = [
242
279
  node("icon", { name: "lightbulb", role: "omp.welcome.tip-icon" }),
243
280
  text(tipText, { wrap: "word", role: "omp.welcome.tip-text" }),
@@ -302,6 +302,12 @@ export class OutputPane implements Component {
302
302
  this.#text.invalidate();
303
303
  }
304
304
 
305
+ releaseRenderCaches(): void {
306
+ this.#renderKey = "";
307
+ this.#text.setText("");
308
+ this.#text.releaseRenderCaches();
309
+ }
310
+
305
311
  #appendToTail(text: string): void {
306
312
  if (!text) return;
307
313
  if (this.#lines.length === 0) this.#lines.push("");