@linxiraos/pi-tui 1.4.4 → 1.4.6

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 (116) hide show
  1. package/CHANGELOG.md +29 -27
  2. package/dist/types/app-keybindings.d.ts +5 -0
  3. package/dist/types/chrome/context-map.d.ts +15 -0
  4. package/dist/types/chrome/context-presentation.d.ts +48 -0
  5. package/dist/types/chrome/context-view-model.d.ts +77 -0
  6. package/dist/types/components/image.d.ts +20 -0
  7. package/dist/types/components/loader.d.ts +1 -1
  8. package/dist/types/native/blobs.d.ts +9 -0
  9. package/dist/types/overlays/advisor-config.d.ts +6 -0
  10. package/dist/types/overlays/agent-hub-projection.d.ts +3 -1
  11. package/dist/types/overlays/ask-dialog.d.ts +12 -3
  12. package/dist/types/overlays/btw-history-panel.d.ts +16 -2
  13. package/dist/types/overlays/btw-history.d.ts +7 -0
  14. package/dist/types/overlays/btw-panel.d.ts +2 -0
  15. package/dist/types/overlays/context-viewer-format.d.ts +42 -0
  16. package/dist/types/overlays/context-viewer-overview.d.ts +70 -0
  17. package/dist/types/overlays/context-viewer.d.ts +25 -0
  18. package/dist/types/overlays/hook-input.d.ts +1 -0
  19. package/dist/types/overlays/mcp-add-wizard.d.ts +2 -0
  20. package/dist/types/overlays/pause-screen.d.ts +13 -3
  21. package/dist/types/overlays/running-subagent-badge.d.ts +7 -1
  22. package/dist/types/prompt/macos-spelling.d.ts +2 -2
  23. package/dist/types/render/hyperlink.d.ts +15 -2
  24. package/dist/types/render/output-pane.d.ts +1 -1
  25. package/dist/types/render/render-utils.d.ts +7 -1
  26. package/dist/types/status-line/component.d.ts +2 -2
  27. package/dist/types/status-line/context-usage.d.ts +15 -30
  28. package/dist/types/terminal-capabilities.d.ts +7 -0
  29. package/dist/types/theme/symbols.d.ts +1 -1
  30. package/dist/types/tools/ask.d.ts +4 -0
  31. package/dist/types/tools/edit.d.ts +3 -1
  32. package/dist/types/tools/fetch.d.ts +1 -0
  33. package/dist/types/tools/github.d.ts +3 -0
  34. package/dist/types/tools/grouped-file-output.d.ts +2 -0
  35. package/dist/types/tools/mcp.d.ts +3 -3
  36. package/dist/types/tools/read.d.ts +3 -0
  37. package/dist/types/tools/wait.d.ts +16 -2
  38. package/dist/types/tui.d.ts +2 -0
  39. package/dist/types/vim.d.ts +39 -0
  40. package/package.json +9 -9
  41. package/src/app-keybindings.d.ts +5 -0
  42. package/src/app-keybindings.ts +5 -0
  43. package/src/chat/bash-execution.ts +7 -1
  44. package/src/chat/read-tool-group.ts +1 -2
  45. package/src/chat/skill-message.ts +2 -6
  46. package/src/chrome/context-map.ts +62 -0
  47. package/src/chrome/context-presentation.ts +26 -0
  48. package/src/chrome/context-view-model.ts +73 -0
  49. package/src/chrome/transcript-container.ts +89 -59
  50. package/src/components/editor.ts +455 -13
  51. package/src/components/image.d.ts +20 -0
  52. package/src/components/image.ts +83 -18
  53. package/src/components/loader.d.ts +1 -1
  54. package/src/components/loader.ts +1 -1
  55. package/src/components/markdown.ts +109 -7
  56. package/src/hotkeys-markdown.ts +1 -0
  57. package/src/native/blobs.d.ts +9 -0
  58. package/src/native/blobs.ts +3 -2
  59. package/src/overlays/advisor-config.ts +9 -2
  60. package/src/overlays/agent-hub-projection.d.ts +3 -1
  61. package/src/overlays/agent-hub-projection.ts +6 -5
  62. package/src/overlays/agent-hub.ts +51 -42
  63. package/src/overlays/ask-dialog.ts +125 -35
  64. package/src/overlays/btw-history-panel.ts +124 -12
  65. package/src/overlays/btw-history.ts +11 -0
  66. package/src/overlays/btw-panel.ts +8 -4
  67. package/src/overlays/context-viewer-format.ts +145 -0
  68. package/src/overlays/context-viewer-overview.ts +381 -0
  69. package/src/overlays/context-viewer.ts +728 -0
  70. package/src/overlays/hook-input.ts +2 -0
  71. package/src/overlays/mcp-add-wizard.ts +5 -0
  72. package/src/overlays/pause-screen.ts +166 -33
  73. package/src/overlays/running-subagent-badge.ts +12 -1
  74. package/src/overlays/settings-defs.ts +1 -0
  75. package/src/overlays/usage-dashboard.ts +15 -2
  76. package/src/prompt/macos-spelling.ts +24 -15
  77. package/src/render/hyperlink.d.ts +15 -2
  78. package/src/render/hyperlink.ts +41 -18
  79. package/src/render/output-pane.d.ts +1 -1
  80. package/src/render/output-pane.ts +60 -17
  81. package/src/render/render-utils.d.ts +7 -1
  82. package/src/render/render-utils.ts +11 -2
  83. package/src/setup/scenes/sign-in.ts +6 -0
  84. package/src/status-line/component.ts +6 -4
  85. package/src/status-line/context-usage.ts +56 -582
  86. package/src/terminal-capabilities.d.ts +7 -0
  87. package/src/terminal-capabilities.ts +10 -0
  88. package/src/theme/symbols.d.ts +1 -1
  89. package/src/theme/symbols.ts +16 -0
  90. package/src/tools/ask.d.ts +4 -0
  91. package/src/tools/ask.ts +4 -0
  92. package/src/tools/ast-grep.ts +3 -2
  93. package/src/tools/bash.ts +5 -23
  94. package/src/tools/edit.d.ts +3 -1
  95. package/src/tools/edit.ts +8 -4
  96. package/src/tools/fetch.d.ts +1 -0
  97. package/src/tools/fetch.ts +1 -0
  98. package/src/tools/find.ts +3 -10
  99. package/src/tools/github.d.ts +3 -0
  100. package/src/tools/github.ts +23 -3
  101. package/src/tools/glob.ts +4 -3
  102. package/src/tools/grep.ts +3 -4
  103. package/src/tools/grouped-file-output.d.ts +2 -0
  104. package/src/tools/grouped-file-output.ts +8 -2
  105. package/src/tools/mcp.d.ts +3 -3
  106. package/src/tools/mcp.ts +27 -9
  107. package/src/tools/native-view.ts +2 -2
  108. package/src/tools/read.d.ts +3 -0
  109. package/src/tools/read.ts +3 -1
  110. package/src/tools/vibe.ts +14 -3
  111. package/src/tools/wait.d.ts +16 -2
  112. package/src/tools/wait.ts +16 -2
  113. package/src/tui.d.ts +2 -0
  114. package/src/tui.ts +59 -19
  115. package/src/vim.d.ts +39 -0
  116. package/src/vim.ts +313 -22
@@ -0,0 +1,62 @@
1
+ /** Pure occupancy calculations for contiguous token segments, independent of themes and renderers. */
2
+ export interface ContextMapSegment<T> {
3
+ readonly id: T;
4
+ readonly tokens: number;
5
+ }
6
+
7
+ export interface ContextMapCell<T> {
8
+ readonly id: T;
9
+ readonly full: boolean;
10
+ }
11
+
12
+ /**
13
+ * Lays `segments` out in order over a `columns` × `rows` grid representing `windowTokens`; each cell takes the
14
+ * segment covering most of it and is `full` at 70% coverage or more. Returns `[]` when the window or grid
15
+ * size is unusable, and omits cells no segment touches.
16
+ */
17
+ export function planContextMap<T>(
18
+ segments: readonly ContextMapSegment<T>[],
19
+ windowTokens: number,
20
+ columns: number,
21
+ rows: number,
22
+ ): ContextMapCell<T>[] {
23
+ if (
24
+ !Number.isFinite(windowTokens) ||
25
+ windowTokens <= 0 ||
26
+ !Number.isInteger(columns) ||
27
+ !Number.isInteger(rows) ||
28
+ columns <= 0 ||
29
+ rows <= 0
30
+ )
31
+ return [];
32
+ const cellCount = columns * rows;
33
+ const tokensPerCell = windowTokens / cellCount;
34
+ const ranges: { id: T; start: number; end: number }[] = [];
35
+ let cursor = 0;
36
+ for (const segment of segments) {
37
+ if (!Number.isFinite(segment.tokens) || segment.tokens <= 0) continue;
38
+ const end = Math.min(windowTokens, cursor + segment.tokens);
39
+ if (end > cursor) ranges.push({ id: segment.id, start: cursor, end });
40
+ cursor = end;
41
+ if (cursor >= windowTokens) break;
42
+ }
43
+ const cells: ContextMapCell<T>[] = [];
44
+ let first = 0;
45
+ for (let index = 0; index < cellCount; index++) {
46
+ const start = index * tokensPerCell;
47
+ const end = (index + 1) * tokensPerCell;
48
+ while (first < ranges.length && ranges[first]!.end <= start) first++;
49
+ let winner: T | undefined;
50
+ let overlap = 0;
51
+ for (let part = first; part < ranges.length && ranges[part]!.start < end; part++) {
52
+ const range = ranges[part]!;
53
+ const covered = Math.min(end, range.end) - Math.max(start, range.start);
54
+ if (covered > overlap) {
55
+ overlap = covered;
56
+ winner = range.id;
57
+ }
58
+ }
59
+ if (winner !== undefined) cells.push({ id: winner, full: overlap / tokensPerCell >= 0.7 });
60
+ }
61
+ return cells;
62
+ }
@@ -0,0 +1,26 @@
1
+ import type { ThemeColor } from "../theme";
2
+ import type { SymbolKey } from "../theme/symbols";
3
+ import type { ContextCategoryId } from "./context-view-model";
4
+
5
+ /** Shared category styles for maps and interactive legends; resolve glyphs at render time. */
6
+ const SYSTEM = { color: "accent", symbol: "context.content" } as const;
7
+ const DETAILS = { color: "customMessageLabel", symbol: "context.content" } as const;
8
+ const TOOLS = { color: "warning", symbol: "context.content" } as const;
9
+ const SKILLS = { color: "success", symbol: "context.content" } as const;
10
+ const MESSAGES = { color: "userMessageText", symbol: "context.messages" } as const;
11
+ const OUTPUT = { color: "muted", symbol: "context.messages" } as const;
12
+ export const CONTEXT_PRESENTATION = {
13
+ "system-prompt": SYSTEM,
14
+ skills: SKILLS,
15
+ "built-in-tools": TOOLS,
16
+ "custom-tools": DETAILS,
17
+ // Shares the System Prompt color; the message glyph tells them apart in the map.
18
+ "user-messages": { color: "accent", symbol: "context.messages" },
19
+ "assistant-messages": MESSAGES,
20
+ "assistant-thinking": DETAILS,
21
+ "tool-calls": TOOLS,
22
+ "tool-output": OUTPUT,
23
+ buffer: { color: "warning", symbol: "context.buffer" },
24
+ free: { color: "dim", symbol: "context.free" },
25
+ } as const satisfies Record<ContextPresentationId, { color: ThemeColor; symbol: SymbolKey }>;
26
+ export type ContextPresentationId = ContextCategoryId | "buffer" | "free";
@@ -0,0 +1,73 @@
1
+ /** Context snapshot shapes shared by the session snapshot builder and the context viewer. */
2
+ import type { ContextBreakdown } from "../status-line/context-usage";
3
+
4
+ interface ContextCategoryDescriptor {
5
+ readonly id: string;
6
+ readonly label: string;
7
+ /** Overview row label when the Overview weight differs from the category's content. */
8
+ readonly overviewLabel?: string;
9
+ /** Listed with its weight but never opened. */
10
+ readonly openable?: false;
11
+ }
12
+
13
+ /** Context categories in display order. */
14
+ export const CONTEXT_CATEGORIES = [
15
+ // The Overview weight excludes the Skills listing; content views keep complete system blocks.
16
+ { id: "system-prompt", label: "System Prompt", overviewLabel: "System Prompt (excluding Skills)" },
17
+ // An estimate of the prompt's skill listing, without entries of its own.
18
+ { id: "skills", label: "Skills", openable: false },
19
+ { id: "built-in-tools", label: "Built-in Tools" },
20
+ { id: "custom-tools", label: "Custom Tools" },
21
+ { id: "user-messages", label: "User / Developer Messages" },
22
+ { id: "assistant-messages", label: "Assistant Messages" },
23
+ { id: "assistant-thinking", label: "Assistant Thinking" },
24
+ { id: "tool-calls", label: "Tool Calls" },
25
+ { id: "tool-output", label: "Tool Output" },
26
+ ] as const satisfies readonly ContextCategoryDescriptor[];
27
+
28
+ export type ContextCategoryId = (typeof CONTEXT_CATEGORIES)[number]["id"];
29
+
30
+ const DESCRIPTORS_BY_ID = new Map<ContextCategoryId, ContextCategoryDescriptor>(
31
+ CONTEXT_CATEGORIES.map(descriptor => [descriptor.id, descriptor]),
32
+ );
33
+
34
+ /** Descriptor of a category id: its label, optional Overview label, and whether it can be opened. */
35
+ export function contextCategoryDescriptor(id: ContextCategoryId): ContextCategoryDescriptor {
36
+ return DESCRIPTORS_BY_ID.get(id)!;
37
+ }
38
+
39
+ export interface ContextThinkingGroup {
40
+ readonly id: string;
41
+ readonly label: string;
42
+ readonly tokens: number;
43
+ readonly interrupted?: boolean;
44
+ }
45
+
46
+ export interface ContextViewEntry {
47
+ readonly id: string;
48
+ readonly label: string;
49
+ readonly text: string;
50
+ /** Aggregation weight for the unscaled replay estimate; shared blocks contribute through their group. */
51
+ readonly tokens: number;
52
+ readonly interrupted?: boolean;
53
+ readonly thinkingGroup?: ContextThinkingGroup;
54
+ readonly path?: string;
55
+ readonly info?: string;
56
+ readonly timestamp?: number;
57
+ readonly callId?: string;
58
+ }
59
+
60
+ export interface ContextViewCategory {
61
+ id: ContextCategoryId;
62
+ key?: string;
63
+ label: string;
64
+ /** Overview attribution weight, not reported usage; may differ from the entry sum (e.g. Skills subtraction). */
65
+ tokens: number;
66
+ entries: ContextViewEntry[];
67
+ children?: ContextViewCategory[];
68
+ }
69
+
70
+ export interface ContextViewData {
71
+ readonly breakdown: ContextBreakdown;
72
+ readonly categories: readonly ContextViewCategory[];
73
+ }
@@ -1,7 +1,7 @@
1
1
  import { type Component, Container, type HistoryBatch } from "../tui";
2
2
  import * as logger from "@linxiraos/pi-utils/logger";
3
3
  import { popLoopPhase, pushLoopPhase } from "@linxiraos/pi-utils";
4
- import { renderForScrollback } from "../components/image";
4
+ import { measureRender, renderForScrollback } from "../components/image";
5
5
  import { col } from "../native/describe";
6
6
  import type { NativeNode } from "../native/node";
7
7
  import { isNativeSettled, settleNative } from "../native/settle";
@@ -97,13 +97,6 @@ interface TranscriptEntry {
97
97
  * state for emitted-row slicing but never emits another mid-stream row.
98
98
  */
99
99
  stableFrozen: boolean;
100
- /**
101
- * Cached "renders at least one image line" result for the settled-image
102
- * flush, keyed by width and image protocol (the probe upgrade re-encodes
103
- * text-fallback blocks into graphics). Rows of a settled block are frozen,
104
- * so a hit is exact.
105
- */
106
- imageScan: { width: number; protocol: string | null; hasImageRows: boolean } | undefined;
107
100
  /**
108
101
  * Head rows of a settled block already in native history while the rest
109
102
  * stays live: pressure commits only the rows that left the screen, so no
@@ -166,6 +159,17 @@ const RETIREMENT_BUDGET_MS = 8;
166
159
  const EMPTY_ROWS: readonly string[] = [];
167
160
  const EMPTY_STABLE_ROWS: readonly TranscriptStableRow[] = [];
168
161
 
162
+ /** A block's full-allocation render taken by {@link TranscriptContainer}'s walk-order measurement. */
163
+ interface MeasuredBlock {
164
+ rows: readonly string[];
165
+ /** Whether the render observed a budgeted image; see {@link measureRender}. */
166
+ images: boolean;
167
+ /** Whether a budgeted image in the block is demoted to its text fallback. */
168
+ demoted: boolean;
169
+ /** Whether a budgeted image has no slot yet from a full pass. */
170
+ unresolved: boolean;
171
+ }
172
+
169
173
  function isFinalized(component: Component): boolean {
170
174
  const block = component as Component & FinalizableBlock;
171
175
  return (block.isTranscriptBlockFinalized?.() ?? true) && block.isTranscriptBlockPending?.() !== true;
@@ -289,7 +293,7 @@ export class TranscriptContainer extends Container {
289
293
  * composition, with no block mutation possible in between; replaying the
290
294
  * first measurement spares every block its second render per frame.
291
295
  */
292
- #frameRows = new Map<TranscriptEntry, readonly string[]>();
296
+ #frameRows = new Map<TranscriptEntry, MeasuredBlock>();
293
297
  #frameRowsWidth = 0;
294
298
  #releaseFailures = new WeakSet<Component>();
295
299
  /** The `children` array `#entries` last mirrored; see {@link #syncEntries}. */
@@ -311,7 +315,6 @@ export class TranscriptContainer extends Container {
311
315
  stableRowCountByWidth: new Map(),
312
316
  emitted: 0,
313
317
  stableFrozen: false,
314
- imageScan: undefined,
315
318
  split: undefined,
316
319
  });
317
320
  // `children` is public and may be edited externally; re-check the whole
@@ -518,41 +521,54 @@ export class TranscriptContainer extends Container {
518
521
  this.#settleFinalized();
519
522
  let total = 0;
520
523
  for (const { entry, index } of this.#liveEntries()) {
521
- const block = this.#liveBlockRows(entry, index, width);
524
+ const block = this.#liveBlock(entry, index, width).rows;
522
525
  if (block.length > 0) total += block.length + (total > 0 ? 1 : 0);
523
526
  if (total > limit) break;
524
527
  }
525
528
  return total;
526
529
  }
527
530
 
528
- /** One live block's un-emitted rows at `width`, rendered against its full-height allocation. */
529
- #liveBlockRows(entry: TranscriptEntry, index: number, width: number): readonly string[] {
530
- const rows = this.#measuredRows(entry, width);
531
+ /** One live block's un-emitted rows at `width`, measured against its full-height allocation. */
532
+ #liveBlock(entry: TranscriptEntry, index: number, width: number): MeasuredBlock {
533
+ const measured = this.#measure(entry, width);
531
534
  const emitted = this.#projectedEmittedRowCount(entry, index, width);
532
- return emitted === 0 ? rows : rows.slice(emitted);
535
+ return emitted === 0
536
+ ? measured
537
+ : {
538
+ rows: measured.rows.slice(emitted),
539
+ images: measured.images,
540
+ demoted: measured.demoted,
541
+ unresolved: measured.unresolved,
542
+ };
533
543
  }
534
544
 
535
545
  /**
536
546
  * One block's blank-trimmed render at its full-height allocation. Inside an
537
547
  * open frame the first measurement of each block is replayed to later ones,
538
548
  * leaving whatever allocation the viewport has since rendered it at.
549
+ *
550
+ * Measurements run in walk order, not display order, so they render under
551
+ * {@link measureRender}: a block whose images they observed must render
552
+ * again in display order before its rows are laid out.
539
553
  */
540
- #measuredRows(entry: TranscriptEntry, width: number): readonly string[] {
541
- if (this.#openFrame === undefined) {
542
- this.#setAllocation(entry.component, Number.MAX_SAFE_INTEGER, this.#lastFrame);
543
- return this.#renderEntry(entry, width);
544
- }
554
+ #measure(entry: TranscriptEntry, width: number): MeasuredBlock {
555
+ if (this.#openFrame === undefined) return this.#measureEntry(entry, width);
545
556
  if (this.#frameRowsWidth !== width) {
546
557
  this.#frameRows.clear();
547
558
  this.#frameRowsWidth = width;
548
559
  }
549
- let rows = this.#frameRows.get(entry);
550
- if (rows === undefined) {
551
- this.#setAllocation(entry.component, Number.MAX_SAFE_INTEGER, this.#lastFrame);
552
- rows = this.#renderEntry(entry, width);
553
- this.#frameRows.set(entry, rows);
560
+ let measured = this.#frameRows.get(entry);
561
+ if (measured === undefined) {
562
+ measured = this.#measureEntry(entry, width);
563
+ this.#frameRows.set(entry, measured);
554
564
  }
555
- return rows;
565
+ return measured;
566
+ }
567
+
568
+ #measureEntry(entry: TranscriptEntry, width: number): MeasuredBlock {
569
+ this.#setAllocation(entry.component, Number.MAX_SAFE_INTEGER, this.#lastFrame);
570
+ const { value: rows, images, demoted, unresolved } = measureRender(() => this.#renderEntry(entry, width));
571
+ return { rows, images, demoted, unresolved };
556
572
  }
557
573
 
558
574
  #closeFrame(): void {
@@ -614,6 +630,7 @@ export class TranscriptContainer extends Container {
614
630
  // show — the whole ledger on a resumed session's first paint (#12933).
615
631
  const shown: Array<{ entry: TranscriptEntry; index: number }> = [];
616
632
  const blocks: (readonly string[])[] = [];
633
+ const measuredImages: boolean[] = [];
617
634
  let unrendered = 0;
618
635
  for (let cursor = live.length - 1; cursor >= 0; cursor--) {
619
636
  if (shown.length > capacity) {
@@ -621,15 +638,15 @@ export class TranscriptContainer extends Container {
621
638
  break;
622
639
  }
623
640
  const candidate = live[cursor]!;
624
- const block = this.#liveBlockRows(candidate.entry, candidate.index, width);
625
- if (block.length === 0) continue;
641
+ const block = this.#liveBlock(candidate.entry, candidate.index, width);
642
+ if (block.rows.length === 0) continue;
626
643
  shown.push(candidate);
627
- blocks.push(block);
644
+ blocks.push(block.rows);
645
+ measuredImages.push(block.images);
628
646
  }
629
647
  shown.reverse();
630
648
  blocks.reverse();
631
- let total = 0;
632
- for (const block of blocks) total += block.length + (total > 0 ? 1 : 0);
649
+ measuredImages.reverse();
633
650
  if (shown.length === 0) {
634
651
  this.#lastViewportSpans = [];
635
652
  return EMPTY_ROWS;
@@ -639,6 +656,19 @@ export class TranscriptContainer extends Container {
639
656
  // emergency layout consults them only where it must.
640
657
  return this.#renderEmergency(shown, live.slice(0, unrendered), width, capacity, frame);
641
658
  }
659
+ // The walk ran newest-first, so the images it measured claimed no
660
+ // display slot (see #measure). Render those blocks again oldest-first:
661
+ // the image budget keeps the newest images live by observation order.
662
+ for (let blockIndex = 0; blockIndex < shown.length; blockIndex++) {
663
+ if (!measuredImages[blockIndex]) continue;
664
+ const { entry, index } = shown[blockIndex]!;
665
+ this.#setAllocation(entry.component, Number.MAX_SAFE_INTEGER, frame);
666
+ blocks[blockIndex] = this.#renderEntry(entry, width).slice(
667
+ this.#projectedEmittedRowCount(entry, index, width),
668
+ );
669
+ }
670
+ let total = 0;
671
+ for (const block of blocks) total += block.length + (total > 0 ? 1 : 0);
642
672
  if (total <= capacity) {
643
673
  const output: string[] = [];
644
674
  const owners: (Component | undefined)[] = [];
@@ -786,7 +816,7 @@ export class TranscriptContainer extends Container {
786
816
  // Only a render publishes a block's stable rows, so the head renders
787
817
  // before its progressive-append eligibility is read.
788
818
  const head = this.#entries[this.#frontier];
789
- if (head !== undefined) this.#measuredRows(head, width);
819
+ if (head !== undefined) this.#measure(head, width);
790
820
  const appendHead =
791
821
  policy === "pressure" &&
792
822
  head?.mode === "appendOnly" &&
@@ -810,7 +840,7 @@ export class TranscriptContainer extends Container {
810
840
  let fits = true;
811
841
  for (let cursor = live.length - 1; cursor >= 0; cursor--) {
812
842
  const candidate = live[cursor]!;
813
- const height = this.#liveBlockRows(candidate.entry, candidate.index, width).length;
843
+ const height = this.#liveBlock(candidate.entry, candidate.index, width).rows.length;
814
844
  if (height > 0) liveRows += height + (liveRows > 0 ? 1 : 0);
815
845
  if (fits) {
816
846
  const next = height > 0 ? tailRows + height + (tailRows > 0 ? 1 : 0) : tailRows;
@@ -940,11 +970,13 @@ export class TranscriptContainer extends Container {
940
970
  width: number,
941
971
  visible: number,
942
972
  ): { rows: readonly string[]; split: RowSplit } | "whole" | undefined {
943
- const measured = this.#measuredRows(entry, width);
973
+ const measured = this.#measure(entry, width).rows;
944
974
  const start = this.#emittedRowCount(entry, width);
945
975
  const cut = measured.length - visible;
946
976
  if (cut <= start) return undefined;
947
- const scrollback = renderForScrollback(() => this.#renderEntry(entry, width));
977
+ // The boundary block stays live, so the viewport renders it in display
978
+ // order; this render precedes the retired blocks and must claim no slot.
979
+ const scrollback = measureRender(() => renderForScrollback(() => this.#renderEntry(entry, width))).value;
948
980
  if (scrollback.length !== measured.length) return undefined;
949
981
  const total = cutBelowWholeImage(scrollback, cut);
950
982
  if (total >= scrollback.length) return "whole";
@@ -1153,7 +1185,7 @@ export class TranscriptContainer extends Container {
1153
1185
  * content stays live: it can repeat committed text but never drop any.
1154
1186
  */
1155
1187
  #splitRowCount(entry: TranscriptEntry, split: RowSplit, width: number): number {
1156
- const rendered = this.#measuredRows(entry, width);
1188
+ const rendered = this.#measure(entry, width).rows;
1157
1189
  if (split.located?.rendered === rendered) return split.located.count;
1158
1190
  let count = 0;
1159
1191
  if (
@@ -1355,10 +1387,10 @@ export class TranscriptContainer extends Container {
1355
1387
  const entry = this.#entries[this.#frontier]!;
1356
1388
  if (entry.state !== "settled") return;
1357
1389
  if (entry.split !== undefined) {
1358
- if (this.#splitRowCount(entry, entry.split, width) < this.#measuredRows(entry, width).length) return;
1390
+ if (this.#splitRowCount(entry, entry.split, width) < this.#measure(entry, width).rows.length) return;
1359
1391
  } else {
1360
1392
  if (entry.mode !== "appendOnly") return;
1361
- const rendered = this.#measuredRows(entry, width);
1393
+ const rendered = this.#measure(entry, width).rows;
1362
1394
  if (entry.emitted !== entry.stableRows.length) return;
1363
1395
  if (this.#renderStablePrefix(entry, entry.emitted, width).length !== rendered.length) return;
1364
1396
  }
@@ -1423,7 +1455,7 @@ export class TranscriptContainer extends Container {
1423
1455
  let hiddenBelow = 0;
1424
1456
  for (const candidate of behind) {
1425
1457
  if (candidate.entry.state !== "active") continue;
1426
- if (this.#liveBlockRows(candidate.entry, candidate.index, width).length > 0) hiddenBelow++;
1458
+ if (this.#liveBlock(candidate.entry, candidate.index, width).rows.length > 0) hiddenBelow++;
1427
1459
  }
1428
1460
  let behindEmergency: { candidate: { entry: TranscriptEntry; index: number }; row: string } | null | undefined;
1429
1461
  const findBehindEmergency = () => {
@@ -1434,7 +1466,7 @@ export class TranscriptContainer extends Container {
1434
1466
  if (candidate.entry.state !== "settled") continue;
1435
1467
  const block = candidate.entry.component as Component & FinalizableBlock;
1436
1468
  if (block.renderTranscriptBlockEmergencyRow === undefined) continue;
1437
- if (this.#liveBlockRows(candidate.entry, candidate.index, width).length === 0) continue;
1469
+ if (this.#liveBlock(candidate.entry, candidate.index, width).rows.length === 0) continue;
1438
1470
  const row = block.renderTranscriptBlockEmergencyRow(width);
1439
1471
  if (row === undefined) continue;
1440
1472
  behindEmergency = { candidate, row };
@@ -1541,28 +1573,27 @@ export class TranscriptContainer extends Container {
1541
1573
  for (let index = this.#frontier; index < this.#entries.length; index++) {
1542
1574
  const entry = this.#entries[index]!;
1543
1575
  if (entry.state !== "settled") break;
1544
- if (this.#hasImageRows(entry, width)) last = index;
1576
+ const state = this.#imageFlushState(entry, width);
1577
+ // Retiring "through" a held block would take it along: stop before it.
1578
+ if (state === "hold") break;
1579
+ if (state === "flush") last = index;
1545
1580
  }
1546
1581
  return last < 0 ? -1 : last + 1;
1547
1582
  }
1548
1583
 
1549
- /** Whether the block's measured rows carry an image sequence (cached per width and protocol). */
1550
- #hasImageRows(entry: TranscriptEntry, width: number): boolean {
1551
- const protocol = TERMINAL.imageProtocol;
1552
- const cached = entry.imageScan;
1553
- if (cached !== undefined && cached.width === width && cached.protocol === protocol) return cached.hasImageRows;
1554
- let hasImageRows = false;
1555
- if (protocol !== null) {
1556
- const rows = this.#measuredRows(entry, width);
1557
- for (let index = 0; index < rows.length; index++) {
1558
- if (TERMINAL.isImageLine(rows[index]!)) {
1559
- hasImageRows = true;
1560
- break;
1561
- }
1562
- }
1563
- }
1564
- entry.imageScan = { width, protocol, hasImageRows };
1565
- return hasImageRows;
1584
+ /**
1585
+ * Whether the block's measured rows carry live graphics that must reach
1586
+ * scrollback early ("flush"), image rows that must keep their viewport rows
1587
+ * ("hold"), or no image at all ("none"). A demoted image renders as its text
1588
+ * fallback, which needs no graphics commit, and an image whose budget slot is
1589
+ * not known yet must wait for a full pass to decide. Re-measured per call
1590
+ * because both answers change with the budget's split.
1591
+ */
1592
+ #imageFlushState(entry: TranscriptEntry, width: number): "none" | "flush" | "hold" {
1593
+ if (TERMINAL.imageProtocol === null) return "none";
1594
+ const measured = this.#measure(entry, width);
1595
+ if (!measured.images) return "none";
1596
+ return measured.demoted || measured.unresolved ? "hold" : "flush";
1566
1597
  }
1567
1598
 
1568
1599
  #liveEntries(): Array<{ entry: TranscriptEntry; index: number }> {
@@ -1609,7 +1640,6 @@ export class TranscriptContainer extends Container {
1609
1640
  stableRowCountByWidth: new Map(),
1610
1641
  emitted: 0,
1611
1642
  stableFrozen: false,
1612
- imageScan: undefined,
1613
1643
  split: undefined,
1614
1644
  },
1615
1645
  );