@oh-my-pi/pi-tui 18.8.6 → 18.8.8

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 (103) hide show
  1. package/CHANGELOG.md +45 -79
  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/execution-shared.d.ts +6 -5
  6. package/dist/types/chat/user-message.d.ts +2 -0
  7. package/dist/types/components/box.d.ts +1 -0
  8. package/dist/types/components/disclosure.d.ts +1 -0
  9. package/dist/types/components/image.d.ts +1 -0
  10. package/dist/types/components/key-value-list.d.ts +1 -0
  11. package/dist/types/components/layout/row.d.ts +1 -0
  12. package/dist/types/components/layout/stack.d.ts +1 -0
  13. package/dist/types/components/markdown.d.ts +1 -0
  14. package/dist/types/components/scroll-view.d.ts +1 -0
  15. package/dist/types/components/section.d.ts +1 -0
  16. package/dist/types/components/table.d.ts +1 -0
  17. package/dist/types/components/text.d.ts +1 -0
  18. package/dist/types/components/truncated-text.d.ts +1 -0
  19. package/dist/types/keybinding-matchers.d.ts +3 -0
  20. package/dist/types/native/blobs.d.ts +3 -1
  21. package/dist/types/overlays/annotation-overlay.d.ts +12 -0
  22. package/dist/types/overlays/annotation-types.d.ts +2 -0
  23. package/dist/types/overlays/hook-selector.d.ts +9 -4
  24. package/dist/types/overlays/model-browser.d.ts +2 -2
  25. package/dist/types/overlays/model-hub.d.ts +21 -4
  26. package/dist/types/overlays/session-observer-registry.d.ts +2 -0
  27. package/dist/types/overlays/session-selector.d.ts +1 -1
  28. package/dist/types/overlays/usage-dashboard.d.ts +3 -1
  29. package/dist/types/render/output-pane.d.ts +1 -0
  30. package/dist/types/render/render-utils.d.ts +1 -0
  31. package/dist/types/render/tool-card.d.ts +6 -0
  32. package/dist/types/render/width-aware-text.d.ts +2 -0
  33. package/dist/types/status-line/types.d.ts +1 -1
  34. package/dist/types/terminal.d.ts +10 -2
  35. package/dist/types/theme/symbols.d.ts +1 -1
  36. package/dist/types/tools/eval.d.ts +1 -1
  37. package/dist/types/tools/native-view.d.ts +47 -0
  38. package/dist/types/tools/renderer.d.ts +15 -2
  39. package/dist/types/tools/write.d.ts +1 -1
  40. package/dist/types/tools/yield.d.ts +22 -0
  41. package/dist/types/tui.d.ts +31 -0
  42. package/dist/types/vim.d.ts +19 -5
  43. package/package.json +9 -9
  44. package/src/chat/advisor-message.ts +11 -0
  45. package/src/chat/assistant-message.ts +6 -0
  46. package/src/chat/compaction-summary-message.ts +8 -0
  47. package/src/chat/execution-shared.ts +42 -25
  48. package/src/chat/read-tool-group.ts +6 -4
  49. package/src/chat/skill-message.ts +6 -0
  50. package/src/chat/table-chart.ts +17 -20
  51. package/src/chat/tool-execution.ts +27 -2
  52. package/src/chat/user-message.ts +14 -0
  53. package/src/chrome/transcript-container.ts +32 -1
  54. package/src/components/box.ts +5 -0
  55. package/src/components/disclosure.ts +8 -0
  56. package/src/components/editor.ts +182 -5
  57. package/src/components/image.ts +7 -5
  58. package/src/components/key-value-list.ts +4 -0
  59. package/src/components/layout/row.ts +7 -0
  60. package/src/components/layout/stack.ts +7 -0
  61. package/src/components/markdown.ts +8 -0
  62. package/src/components/scroll-view.ts +5 -0
  63. package/src/components/section.ts +5 -0
  64. package/src/components/table.ts +4 -0
  65. package/src/components/text.ts +7 -0
  66. package/src/components/truncated-text.ts +5 -0
  67. package/src/keybinding-matchers.ts +6 -2
  68. package/src/native/backend.ts +16 -15
  69. package/src/native/blobs.ts +43 -10
  70. package/src/native/reconcile.ts +4 -0
  71. package/src/overlays/agent-hub.ts +7 -3
  72. package/src/overlays/annotation-overlay.ts +87 -6
  73. package/src/overlays/annotation-types.ts +2 -0
  74. package/src/overlays/hook-selector.ts +12 -5
  75. package/src/overlays/model-browser.ts +3 -3
  76. package/src/overlays/model-hub.ts +107 -27
  77. package/src/overlays/session-observer-registry.ts +10 -2
  78. package/src/overlays/session-selector.ts +29 -19
  79. package/src/overlays/snapcompact-shape-preview.ts +2 -3
  80. package/src/overlays/usage-dashboard.ts +70 -23
  81. package/src/prompt/attachment-chips.ts +13 -10
  82. package/src/prompt/composer.ts +1 -0
  83. package/src/render/output-pane.ts +6 -0
  84. package/src/render/render-utils.ts +11 -0
  85. package/src/render/tool-card.ts +15 -0
  86. package/src/render/width-aware-text.ts +5 -0
  87. package/src/status-line/segments.ts +3 -0
  88. package/src/status-line/types.ts +1 -1
  89. package/src/terminal.ts +24 -3
  90. package/src/theme/symbols.ts +5 -0
  91. package/src/tools/bash.ts +92 -42
  92. package/src/tools/edit.ts +142 -120
  93. package/src/tools/eval.ts +149 -123
  94. package/src/tools/fetch.ts +5 -6
  95. package/src/tools/index.ts +2 -0
  96. package/src/tools/mcp.ts +15 -2
  97. package/src/tools/native-view.ts +102 -1
  98. package/src/tools/read.ts +7 -5
  99. package/src/tools/renderer.ts +15 -2
  100. package/src/tools/write.ts +70 -56
  101. package/src/tools/yield.ts +225 -0
  102. package/src/tui.ts +93 -0
  103. package/src/vim.ts +333 -18
@@ -177,6 +177,12 @@ export class UserMessageComponent extends Container implements ReactionTarget {
177
177
  this.addChild(markdown);
178
178
  }
179
179
 
180
+ override releaseRenderCaches(): void {
181
+ this.#zoneSource = undefined;
182
+ this.#zoneLines = undefined;
183
+ super.releaseRenderCaches();
184
+ }
185
+
180
186
  setReaction(emoji: string): void {
181
187
  if (this.#reaction === emoji) return;
182
188
  this.#reaction = emoji;
@@ -337,6 +343,10 @@ class SyntheticSummary implements Component {
337
343
  this.#summary = summary;
338
344
  }
339
345
 
346
+ releaseRenderCaches(): void {
347
+ this.#cache = undefined;
348
+ }
349
+
340
350
  invalidate(): void {
341
351
  this.#cache = undefined;
342
352
  }
@@ -425,6 +435,10 @@ export class CollapsedSyntheticMessageComponent implements Component {
425
435
  this.#disclosure.invalidate();
426
436
  }
427
437
 
438
+ releaseRenderCaches(): void {
439
+ this.#disclosure.releaseRenderCaches();
440
+ }
441
+
428
442
  dispose(): void {
429
443
  this.#disclosure.dispose();
430
444
  }
@@ -206,6 +206,7 @@ export class TranscriptContainer extends Container {
206
206
  */
207
207
  #frameRows = new Map<TranscriptEntry, readonly string[]>();
208
208
  #frameRowsWidth = 0;
209
+ #releaseFailures = new WeakSet<Component>();
209
210
  /** The `children` array `#entries` last mirrored; see {@link #syncEntries}. */
210
211
  #syncedChildren: Component[] | undefined;
211
212
  /** Forces the next {@link #syncEntries} to compare every entry, not just the live tail. */
@@ -583,7 +584,10 @@ export class TranscriptContainer extends Container {
583
584
  popLoopPhase();
584
585
  }
585
586
  this.#replayPending = false;
586
- if (rows.length === 0) return undefined;
587
+ if (rows.length === 0) {
588
+ this.#releaseCommittedRenderCaches();
589
+ return undefined;
590
+ }
587
591
  const batch: HistoryBatch = { id: this.#nextBatchId++, rows, kind: "replay" };
588
592
  this.#offered = { batch, kind: "replay" };
589
593
  return batch;
@@ -747,6 +751,8 @@ export class TranscriptContainer extends Container {
747
751
  this.#retireEntry(this.#entries[index]!);
748
752
  }
749
753
  this.#frontier = offered.end;
754
+ } else {
755
+ this.#releaseCommittedRenderCaches();
750
756
  }
751
757
  this.#offered = undefined;
752
758
  if (this.#replayRequested) this.#startReplay();
@@ -766,6 +772,7 @@ export class TranscriptContainer extends Container {
766
772
  const entry = this.#entries[index]!;
767
773
  this.#setAllocation(entry.component, Number.MAX_SAFE_INTEGER, this.#lastFrame);
768
774
  const block = trimBlankEdges(entry.component.render(width));
775
+ if (entry.state === "committed") this.#releaseRenderCaches(entry);
769
776
  if (block.length === 0) continue;
770
777
  if (rows.length > 0) rows.unshift("");
771
778
  rows.unshift(...block);
@@ -813,6 +820,7 @@ export class TranscriptContainer extends Container {
813
820
  for (const entry of this.#entries) {
814
821
  this.#setAllocation(entry.component, Number.MAX_SAFE_INTEGER, this.#lastFrame);
815
822
  const block = this.#renderEntry(entry, width);
823
+ if (entry.state === "committed") this.#releaseRenderCaches(entry);
816
824
  if (block.length === 0) continue;
817
825
  if (rows.length > 0) rows.push("");
818
826
  this.#childStartRows.set(entry.component, rows.length);
@@ -1054,6 +1062,29 @@ export class TranscriptContainer extends Container {
1054
1062
  entry.stableRows = EMPTY_STABLE_ROWS;
1055
1063
  entry.renderedStableByWidth = new Map();
1056
1064
  entry.stableRowCountByWidth = new Map();
1065
+ this.#frameRows.delete(entry);
1066
+ this.#releaseRenderCaches(entry);
1067
+ }
1068
+
1069
+ #releaseCommittedRenderCaches(): void {
1070
+ for (let index = 0; index < this.#frontier; index++) {
1071
+ this.#releaseRenderCaches(this.#entries[index]!);
1072
+ }
1073
+ }
1074
+
1075
+ #releaseRenderCaches(entry: TranscriptEntry): void {
1076
+ const release = entry.component.releaseRenderCaches;
1077
+ if (release === undefined) return;
1078
+ try {
1079
+ release.call(entry.component);
1080
+ } catch (err) {
1081
+ if (this.#releaseFailures.has(entry.component)) return;
1082
+ this.#releaseFailures.add(entry.component);
1083
+ logger.warn("Transcript block failed to release render caches", {
1084
+ component: entry.component.constructor.name,
1085
+ error: String(err),
1086
+ });
1087
+ }
1057
1088
  }
1058
1089
 
1059
1090
  #startReplay(): void {
@@ -135,6 +135,11 @@ export class Box implements Component {
135
135
  }
136
136
  }
137
137
 
138
+ releaseRenderCaches(): void {
139
+ this.#invalidateCache();
140
+ for (const child of this.children) child.releaseRenderCaches?.();
141
+ }
142
+
138
143
  /**
139
144
  * A `card` when the box has a border or background: the background token
140
145
  * picks tone/role (user message, tool state, selection), a border colour
@@ -100,6 +100,14 @@ export class Disclosure implements Component {
100
100
  this.#body?.invalidate?.();
101
101
  }
102
102
 
103
+ releaseRenderCaches(): void {
104
+ this.#cache = undefined;
105
+ this.#boundedCache = undefined;
106
+ this.#summary?.releaseRenderCaches?.();
107
+ this.#collapsedBody?.releaseRenderCaches?.();
108
+ this.#body?.releaseRenderCaches?.();
109
+ }
110
+
103
111
  dispose(): void {
104
112
  if (this.#disposed) return;
105
113
  this.#disposed = true;
@@ -83,6 +83,7 @@ const VIM_MODE_LABELS: Record<VimMode, string | undefined> = {
83
83
  normal: "NORMAL",
84
84
  visual: "VISUAL",
85
85
  "visual-line": "VISUAL",
86
+ replace: "REPLACE",
86
87
  };
87
88
 
88
89
  const PASSTHROUGH_COLOR = (text: string): string => text;
@@ -672,7 +673,9 @@ export class Editor implements Component, Focusable {
672
673
  // Emacs-style kill ring
673
674
  #killRing = new KillRing();
674
675
  /** Previous edit, for kill/yank chaining, undo coalescing, and the provisional space after a Tab word accept. */
675
- #lastAction: "kill" | "yank" | "type-word" | "accept-word" | null = null;
676
+ #lastAction: "kill" | "yank" | "type-word" | "accept-word" | "replace" | null = null;
677
+ /** Graphemes overwritten in the current `R` session, so Backspace can restore them. */
678
+ #replaceLog: { line: number; col: number; removed: string; text: string }[] = [];
676
679
 
677
680
  // Character jump mode
678
681
  #jumpMode: "forward" | "backward" | null = null;
@@ -2252,18 +2255,43 @@ export class Editor implements Component, Focusable {
2252
2255
  return this.isShowingAutocomplete() ? false : this.#runVimKey("escape", vim);
2253
2256
  }
2254
2257
  if (vim.mode === "insert") return false;
2258
+ if (vim.mode === "replace") {
2259
+ if (canonical === "backspace" || matchesKey(data, "backspace") || matchesKey(data, "shift+backspace")) {
2260
+ this.#replaceBackspace();
2261
+ return true;
2262
+ }
2263
+ const replacing = extractPrintableText(data);
2264
+ if (replacing) {
2265
+ for (const seg of segmenter.segment(replacing)) this.#overwriteReplaceGrapheme(seg.segment);
2266
+ return true;
2267
+ }
2268
+ }
2255
2269
 
2270
+ // `f`/`t`/`r` are waiting for a character. Space is that character; arrows and other named
2271
+ // keys cancel, instead of being rewritten to `h`/`l` and inserted or searched for.
2272
+ const awaitingTarget = /[fFtTr]$/.test(vim.pendingText);
2273
+ if (awaitingTarget && (canonical === "space" || data === " ")) return this.#runVimKey(" ", vim);
2256
2274
  const mapped = canonical === undefined ? undefined : VIM_NAV_KEYS[canonical];
2275
+ if (awaitingTarget && mapped !== undefined) return this.#runVimKey("escape", vim);
2257
2276
  if (mapped !== undefined) return this.#runVimKey(mapped, vim);
2258
2277
 
2259
- // Control chords carry no printable text and stay with the host.
2278
+ // Control chords, Enter, and Tab carry no printable text and stay with the host. A half-typed
2279
+ // command (`r`, `f`, `d`) is cancelled first, like character-jump mode, so it cannot outlive a
2280
+ // submit and swallow the first key of the next prompt.
2260
2281
  const printable = extractPrintableText(data);
2261
- if (!printable) return false;
2282
+ if (!printable) {
2283
+ if (vim.pending) this.#runVimKey("escape", vim);
2284
+ return false;
2285
+ }
2262
2286
 
2263
2287
  // Batched stdin can deliver several keystrokes at once, so replay the run one grapheme at a
2264
- // time. A command that drops out of Normal mode part-way (`iabc`) turns the rest of the run
2265
- // back into literal text rather than swallowing it.
2288
+ // time. A command that drops out of Normal mode part-way (`iabc`, `Rxx`) turns the rest of
2289
+ // the run into literal text or replace-mode overwrites rather than more Normal commands.
2266
2290
  for (const seg of segmenter.segment(printable)) {
2291
+ if (vim.mode === "replace") {
2292
+ this.#overwriteReplaceGrapheme(seg.segment);
2293
+ continue;
2294
+ }
2267
2295
  if (this.#runVimKey(seg.segment, vim)) continue;
2268
2296
  this.#insertCharacter(printable.slice(seg.index));
2269
2297
  return true;
@@ -2284,11 +2312,22 @@ export class Editor implements Component, Focusable {
2284
2312
  if (vim.mode !== before || vim.pendingText !== pendingBefore || this.vimSelectedLines !== selectedLinesBefore) {
2285
2313
  this.onVimModeChange?.(vim.mode);
2286
2314
  }
2315
+ if (before === "replace" && vim.mode !== "replace") this.#replaceLog.length = 0;
2316
+ if (vim.mode === "replace" && before !== "replace") this.#replaceLog.length = 0;
2287
2317
  return true;
2288
2318
  }
2289
2319
 
2290
2320
  #applyVimCommands(commands: readonly VimCommand[]): void {
2291
2321
  for (const command of commands) {
2322
+ // A delete or other edit in replace mode invalidates Backspace restores. Motions do not.
2323
+ if (
2324
+ this.#vim?.mode === "replace" &&
2325
+ command.kind !== "move" &&
2326
+ command.kind !== "mode" &&
2327
+ command.kind !== "yank"
2328
+ ) {
2329
+ this.#replaceLog.length = 0;
2330
+ }
2292
2331
  switch (command.kind) {
2293
2332
  case "move":
2294
2333
  this.#moveVimCursor(command.to);
@@ -2320,12 +2359,133 @@ export class Editor implements Component, Focusable {
2320
2359
  case "undo":
2321
2360
  this.#applyUndo();
2322
2361
  break;
2362
+ case "replace":
2363
+ this.#replaceVimSpan(command.from, command.to, command.text);
2364
+ break;
2365
+ case "join":
2366
+ this.#joinVimLines(command.fromLine, command.lines);
2367
+ break;
2368
+ case "indent":
2369
+ this.#indentVimLines(command.fromLine, command.toLine, command.out);
2370
+ break;
2323
2371
  }
2324
2372
  }
2325
2373
  this.#clampVimCursor();
2326
2374
  this.invalidate();
2327
2375
  }
2328
2376
 
2377
+ #replaceVimSpan(from: VimPosition, to: VimPosition, text: string): void {
2378
+ const line = this.#state.lines[from.line] ?? "";
2379
+ if (this.#spanCutsAtomicToken(line, from.col, to.col)) return;
2380
+ this.#recordUndoState();
2381
+ this.#lastAction = null;
2382
+ this.#state.lines[from.line] = line.slice(0, from.col) + text + line.slice(to.col);
2383
+ this.#state.cursorLine = from.line;
2384
+ let last = from.col;
2385
+ for (const seg of segmenter.segment(text)) last = from.col + seg.index;
2386
+ this.#setCursorCol(last);
2387
+ this.#afterVimEdit();
2388
+ }
2389
+
2390
+ #overwriteReplaceGrapheme(grapheme: string): void {
2391
+ const lineIdx = this.#state.cursorLine;
2392
+ const line = this.#state.lines[lineIdx] ?? "";
2393
+ const col = this.#state.cursorCol;
2394
+ if (this.#atomicTokenAt(line, col)) return;
2395
+ // Any other edit since the last overwrite (setText, `x`, paste) resets `#lastAction`, which
2396
+ // makes the logged columns meaningless; start a fresh undo step and a fresh log.
2397
+ if (this.#lastAction !== "replace") {
2398
+ this.#recordUndoState();
2399
+ this.#replaceLog.length = 0;
2400
+ }
2401
+ this.#lastAction = "replace";
2402
+ // Editing a recalled prompt makes it a draft, so Up/Down at an edge move the cursor again
2403
+ // instead of navigating history over the overwritten text (same as `#afterVimEdit`).
2404
+ this.#historyIndex = -1;
2405
+ const end = col >= line.length ? col : nextGraphemeStart(line, col);
2406
+ const removed = line.slice(col, end);
2407
+ this.#state.lines[lineIdx] = line.slice(0, col) + grapheme + line.slice(end);
2408
+ this.#replaceLog.push({ line: lineIdx, col, removed, text: grapheme });
2409
+ this.#setCursorCol(col + grapheme.length);
2410
+ this.#notifyChange();
2411
+ }
2412
+
2413
+ #replaceBackspace(): void {
2414
+ if (this.#lastAction !== "replace") {
2415
+ this.#replaceLog.length = 0;
2416
+ return;
2417
+ }
2418
+ const entry = this.#replaceLog.pop();
2419
+ if (!entry) return;
2420
+ const line = this.#state.lines[entry.line] ?? "";
2421
+ const stillThere = line.slice(entry.col, entry.col + entry.text.length) === entry.text;
2422
+ const atCursor = this.#state.cursorLine === entry.line && this.#state.cursorCol === entry.col + entry.text.length;
2423
+ if (!stillThere) return;
2424
+ if (!atCursor) {
2425
+ this.#replaceLog.push(entry);
2426
+ return;
2427
+ }
2428
+ this.#state.lines[entry.line] =
2429
+ line.slice(0, entry.col) + entry.removed + line.slice(entry.col + entry.text.length);
2430
+ this.#setCursorCol(entry.col);
2431
+ this.#notifyChange();
2432
+ }
2433
+
2434
+ #joinVimLines(fromLine: number, span: number): void {
2435
+ const start = Math.max(0, Math.min(fromLine, this.#state.lines.length - 1));
2436
+ const last = Math.min(start + Math.max(span, 2) - 1, this.#state.lines.length - 1);
2437
+ if (last <= start) return;
2438
+ this.#recordUndoState();
2439
+ let text = this.#state.lines[start] ?? "";
2440
+ let cursor = text.length;
2441
+ for (let i = start + 1; i <= last; i++) {
2442
+ const raw = this.#state.lines[i] ?? "";
2443
+ let trim = /^[ \t]*/.exec(raw)?.[0].length ?? 0;
2444
+ const token = this.#atomicTokenAt(raw, 0);
2445
+ if (token && token.start < trim) trim = token.start;
2446
+ const next = raw.slice(trim);
2447
+ const at = text.length;
2448
+ if (i === start + 1) cursor = at;
2449
+ // Vim join: no extra space after whitespace, before `)`, or for an empty line; two spaces after `.!?`.
2450
+ const gap =
2451
+ text.length === 0 || next.length === 0 || /[ \t]$/.test(text) || next.startsWith(")")
2452
+ ? ""
2453
+ : /[.!?]$/.test(text)
2454
+ ? " "
2455
+ : " ";
2456
+ text += gap + next;
2457
+ }
2458
+ this.#state.lines.splice(start, last - start + 1, text);
2459
+ this.#state.cursorLine = start;
2460
+ this.#setCursorCol(cursor);
2461
+ this.#lastAction = null;
2462
+ this.#afterVimEdit();
2463
+ }
2464
+
2465
+ #indentVimLines(fromLine: number, toLine: number, out: boolean): void {
2466
+ const first = Math.max(0, Math.min(fromLine, this.#state.lines.length - 1));
2467
+ const last = Math.max(first, Math.min(toLine, this.#state.lines.length - 1));
2468
+ // Two spaces, not Vim's shiftwidth of 8: a prompt draft should not jump a tab stop. A leading tab shifts by one tab so the line keeps its own indent style.
2469
+ // Empty lines stay empty, as in Vim, so shifting a paragraph never leaves trailing blanks.
2470
+ const next = this.#state.lines.slice(first, last + 1).map(line => {
2471
+ const text = line ?? "";
2472
+ if (!out) return text.length === 0 ? text : (text.startsWith("\t") ? "\t" : " ") + text;
2473
+ if (text.startsWith("\t")) return text.slice(1);
2474
+ const spaces = /^ */.exec(text)?.[0].length ?? 0;
2475
+ return text.slice(Math.min(2, spaces));
2476
+ });
2477
+ if (next.every((line, i) => line === (this.#state.lines[first + i] ?? ""))) return;
2478
+ this.#recordUndoState();
2479
+ for (let i = first; i <= last; i++) this.#state.lines[i] = next[i - first] ?? "";
2480
+ this.#state.cursorLine = first;
2481
+ const landed = this.#state.lines[first] ?? "";
2482
+ let col = 0;
2483
+ while (col < landed.length && /\s/.test(landed.charAt(col))) col++;
2484
+ this.#setCursorCol(col);
2485
+ this.#lastAction = null;
2486
+ this.#afterVimEdit();
2487
+ }
2488
+
2329
2489
  #moveVimCursor(to: VimPosition): void {
2330
2490
  this.#state.cursorLine = Math.max(0, Math.min(to.line, this.#state.lines.length - 1));
2331
2491
  const line = this.#state.lines[this.#state.cursorLine] ?? "";
@@ -3409,6 +3569,23 @@ export class Editor implements Component, Focusable {
3409
3569
  return undefined;
3410
3570
  }
3411
3571
 
3572
+ /** True when `[from, to)` overlaps a placeholder. Counted `r` must no-op rather than split it.
3573
+ * One pass over the line's matches, so a long counted replace stays linear. */
3574
+ #spanCutsAtomicToken(line: string, from: number, to: number): boolean {
3575
+ const re = this.#getAtomicTokenRe();
3576
+ if (re === undefined) return false;
3577
+ re.lastIndex = 0;
3578
+ for (;;) {
3579
+ const match = re.exec(line);
3580
+ if (match === null || match.index >= to) return false;
3581
+ if (match[0].length === 0) {
3582
+ re.lastIndex = match.index + 1;
3583
+ continue;
3584
+ }
3585
+ if (match.index + match[0].length > from) return true;
3586
+ }
3587
+ }
3588
+
3412
3589
  /** Expand the half-open range [start, end) so it never cuts through an atomic
3413
3590
  * placeholder token: a boundary landing inside a token pulls the whole token in. */
3414
3591
  #expandRangeOverAtomicTokens(line: string, start: number, end: number): { start: number; end: number } {
@@ -10,8 +10,7 @@ import {
10
10
  renderImage,
11
11
  TERMINAL,
12
12
  } from "../terminal-capabilities";
13
- import { registerNativeBlob } from "../native/blobs";
14
- import { node } from "../native/describe";
13
+ import { nativeImageNode } from "../native/blobs";
15
14
  import type { DescribeContext, NativeNode } from "../native/node";
16
15
  import type { Component } from "../tui";
17
16
 
@@ -826,6 +825,11 @@ export class Image implements Component {
826
825
  this.#cachedWidth = undefined;
827
826
  }
828
827
 
828
+ releaseRenderCaches(): void {
829
+ this.#cachedLines = undefined;
830
+ this.#cachedWidth = undefined;
831
+ }
832
+
829
833
  /**
830
834
  * SIXEL sequence for a target size. A new size starts the encode off the JS
831
835
  * thread and answers `undefined` until it settles; the settled encode
@@ -865,11 +869,9 @@ export class Image implements Component {
865
869
  */
866
870
  describe(_cx: DescribeContext): NativeNode {
867
871
  if (this.#native) return this.#native;
868
- const blob = registerNativeBlob(Buffer.from(this.#base64Data, "base64"), this.#mimeType);
869
872
  const maxW = this.#options.maxWidthCells;
870
873
  const maxH = this.#options.maxHeightCells;
871
- this.#native = node("image", {
872
- blob,
874
+ this.#native = nativeImageNode(Buffer.from(this.#base64Data, "base64"), this.#mimeType, {
873
875
  alt: imageFallback(this.#mimeType, this.#dimensions, this.#options.filename),
874
876
  w: this.#dimensions.widthPx,
875
877
  h: this.#dimensions.heightPx,
@@ -54,6 +54,10 @@ export class KeyValueList implements Component {
54
54
  this.#native = undefined;
55
55
  }
56
56
 
57
+ releaseRenderCaches(): void {
58
+ this.#cache = undefined;
59
+ }
60
+
57
61
  /** An aligned `kv` grid; label width and value wrapping are the terminal's. */
58
62
  describe(_cx: DescribeContext): NativeNode {
59
63
  this.#native ??= node("kv", {
@@ -168,6 +168,13 @@ export class Row implements Component, MouseRoutable {
168
168
  }
169
169
  }
170
170
 
171
+ releaseRenderCaches(): void {
172
+ this.#memo = undefined;
173
+ for (const child of uniqueLayoutComponents(this.#children.map(item => item.content))) {
174
+ child.releaseRenderCaches?.();
175
+ }
176
+ }
177
+
171
178
  dispose(): void {
172
179
  for (const child of uniqueLayoutComponents(this.#children.map(item => item.content))) {
173
180
  child.dispose?.();
@@ -140,6 +140,13 @@ export class Stack implements Component, MouseRoutable {
140
140
  }
141
141
  }
142
142
 
143
+ releaseRenderCaches(): void {
144
+ this.#memo = undefined;
145
+ for (const child of uniqueLayoutComponents(this.#children.map(item => item.content))) {
146
+ child.releaseRenderCaches?.();
147
+ }
148
+ }
149
+
143
150
  dispose(): void {
144
151
  for (const child of uniqueLayoutComponents(this.#children.map(item => item.content))) {
145
152
  child.dispose?.();
@@ -2016,6 +2016,14 @@ export class Markdown implements Component {
2016
2016
  this.#cachedLines = undefined;
2017
2017
  }
2018
2018
 
2019
+ releaseRenderCaches(): void {
2020
+ this.invalidate();
2021
+ this.#dropStreamPrefix();
2022
+ this.#streamingHighlightCache = undefined;
2023
+ this.#fastTail = undefined;
2024
+ this.#lastTailCapture = undefined;
2025
+ }
2026
+
2019
2027
  /**
2020
2028
  * The unrendered source as an `md` node, `stream` while the streaming
2021
2029
  * (transient) cache is on. Append-only growth yields a fresh node of the
@@ -408,6 +408,11 @@ export class ScrollView implements Component {
408
408
  this.#child?.invalidate?.();
409
409
  }
410
410
 
411
+ releaseRenderCaches(): void {
412
+ this.#cache = undefined;
413
+ this.#child?.releaseRenderCaches?.();
414
+ }
415
+
411
416
  /** Permanently release a wrapped child's timers, subscriptions, and other resources. */
412
417
  dispose(): void {
413
418
  if (this.#disposed) return;
@@ -51,6 +51,11 @@ export class Section implements Component {
51
51
  this.#cache = undefined;
52
52
  }
53
53
 
54
+ releaseRenderCaches(): void {
55
+ this.#cache = undefined;
56
+ if (isComponent(this.#options.body)) this.#options.body.releaseRenderCaches?.();
57
+ }
58
+
54
59
  dispose(): void {
55
60
  if (this.#disposed) return;
56
61
  this.#disposed = true;
@@ -117,6 +117,10 @@ export class Table implements Component {
117
117
  this.#native = undefined;
118
118
  }
119
119
 
120
+ releaseRenderCaches(): void {
121
+ this.#cache = undefined;
122
+ }
123
+
120
124
  /**
121
125
  * A native `table`. Column priorities carry over unchanged (lower gives
122
126
  * way first); truncating columns truncate at the end, the rest keep
@@ -109,6 +109,13 @@ export class Text implements Component {
109
109
  this.#cachedLines = undefined;
110
110
  }
111
111
 
112
+ releaseRenderCaches(): void {
113
+ this.#cachedText = undefined;
114
+ this.#cachedWidth = undefined;
115
+ this.#cachedWidthConfigEpoch = undefined;
116
+ this.#cachedLines = undefined;
117
+ }
118
+
112
119
  /**
113
120
  * Wrapped text; styling re-derived from the styled source so a theme swap
114
121
  * re-resolves tokens. A background fill becomes the node's tone.
@@ -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;
@@ -53,11 +53,15 @@ export function matchesSelectPageDown(data: string): boolean {
53
53
  return getKeybindings().matches(data, "tui.select.pageDown");
54
54
  }
55
55
 
56
+ /** Effective external-editor key: the first bound key, or Ctrl+G when unbound. */
57
+ export function appExternalEditorKey(): KeyId {
58
+ return getKeybindings().getKeys("app.editor.external")[0] ?? "ctrl+g";
59
+ }
60
+
56
61
  /** Match the external-editor keybinding, falling back to Ctrl+G when unbound. */
57
62
  export function matchesAppExternalEditor(data: string): boolean {
58
63
  const keybindings = getKeybindings();
59
- const externalEditorKeys = keybindings.getKeys("app.editor.external");
60
- if (externalEditorKeys.length > 0) {
64
+ if (keybindings.getKeys("app.editor.external").length > 0) {
61
65
  return keybindings.matches(data, "app.editor.external");
62
66
  }
63
67
  return matchesKey(data, "ctrl+g");
@@ -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