@linxiraos/pi-tui 1.1.7 → 1.1.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.
package/CHANGELOG.md CHANGED
@@ -2,14 +2,10 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
- ## [1.1.7] - 2026-09-01
5
+ ## [1.1.8] - 2026-09-04
6
6
 
7
- - 同步上游 OMP v18.0.11(`b8ce33a58911c26bed1d84f0db9a5e2e727c49a2`)。
8
-
9
- ## [1.1.6] - 2026-08-30
10
-
11
- - 同步上游 OMP v18.0.10(`33cc6b9a043a`)。
12
- - 同步上游 OMP v18.0.9(`cc14e04f075d`)。
7
+ - Restored the sidebar gutter engine + `SidebarComponent` + `/sidebar` command (Zeta-only surface dropped by an earlier upstream merge).
8
+ - OMP sync v18.1.2–v18.1.5: sub-frame history ownership (the frame provider owns history), CoW worktree cloning support, and renderer fixes.
13
9
 
14
10
  ## [1.1.3] - 2026-08-25
15
11
 
@@ -57,6 +57,11 @@ export interface EditorTextAssistProvider {
57
57
  /** Return replacement candidates for the misspelled word at the cursor. */
58
58
  getWordReplacements?(lines: string[], cursorLine: number, cursorCol: number): EditorWordReplacements | null | Promise<EditorWordReplacements | null>;
59
59
  }
60
+ /** What the paste transport knew about the input burst before the editor inserts the payload. */
61
+ export interface PasteOptions {
62
+ /** A submit keypress arrived in the same input burst and will be dispatched right after the paste. */
63
+ submitAfterPaste?: boolean;
64
+ }
60
65
  export declare class Editor implements Component, Focusable {
61
66
  #private;
62
67
  /** Focusable interface - set by TUI when focus changes */
@@ -89,8 +94,9 @@ export declare class Editor implements Component, Focusable {
89
94
  * the editor inserts nothing and records no undo state, leaving insertion to the host (e.g. a
90
95
  * "wrap in a code block / XML / attach as file" menu for very large pastes), which re-inserts
91
96
  * via {@link insertPaste} or {@link insertText}. Return `false` (or leave unset) for the
92
- * default collapse-to-marker behavior. `lineCount` is the sanitized paste's line count. */
93
- onLargePaste?: (text: string, lineCount: number) => boolean;
97
+ * default collapse-to-marker behavior. `lineCount` is the sanitized paste's line count;
98
+ * `options` carries what the paste transport knew about the burst. */
99
+ onLargePaste?: (text: string, lineCount: number, options: PasteOptions) => boolean;
94
100
  onAutocompleteCancel?: () => void;
95
101
  disableSubmit: boolean;
96
102
  constructor(theme: EditorTheme);
@@ -210,7 +216,7 @@ export declare class Editor implements Component, Focusable {
210
216
  /** Drop any volatile preview, then insert `text` as a single undoable edit. */
211
217
  commitVolatileText(text: string): void;
212
218
  /** Apply terminal paste semantics to text from non-bracketed paste transports. */
213
- pasteText(text: string): void;
219
+ pasteText(text: string, options?: PasteOptions): void;
214
220
  /** Insert `content` as a collapsed `[Paste #N]` marker (stored for expansion on submit via
215
221
  * {@link getExpandedText}). Hosts that intercept large pastes through {@link onLargePaste} use
216
222
  * this to re-insert a (possibly transformed) paste without re-triggering the interception hook. */
@@ -29,9 +29,9 @@ export declare const DEFAULT_MAX_INLINE_IMAGES = 8;
29
29
  *
30
30
  * The budget keeps the most recent `cap` images live and demotes older ones to
31
31
  * their text fallback. Demotion needs a full redraw (so off-screen rows are
32
- * rewritten) plus an explicit graphics purge of the demoted ids {@link Image}
33
- * reports display order via {@link observe}, and the TUI drives the purge +
34
- * redraw on the frame after a new image pushes the count past the cap.
32
+ * rewritten) plus an explicit graphics purge of the demoted ids. {@link Image}
33
+ * reports display order via {@link observe}; when that reveals a stricter split,
34
+ * the TUI repeats the pass before emitting its terminal frame.
35
35
  *
36
36
  * `cap <= 0` disables budgeting: every image stays a live graphic.
37
37
  */
@@ -67,9 +67,8 @@ export declare class ImageBudget {
67
67
  */
68
68
  observe(imageId: number): boolean;
69
69
  /**
70
- * End a render pass. Returns true when this frame must purge graphics and
71
- * fully repaint to apply a stricter budget; read the ids via
72
- * {@link takePurgeIds}.
70
+ * End a render pass. Returns true when the pass discovered a stricter budget
71
+ * and must be repeated before its terminal frame is emitted.
73
72
  */
74
73
  endPass(): boolean;
75
74
  /** Image ids to delete from the terminal this frame; clears the pending set. */
@@ -63,7 +63,7 @@ export type KeyId = BaseKey | ModifiedKeyId<BaseKey>;
63
63
  * modifier methods return precisely-typed concatenations (e.g. `Key.ctrl("c")`
64
64
  * is `"ctrl+c"`, not just `string`). This mirrors the upstream
65
65
  * `@mariozechner/pi-tui` `Key` export verbatim so plugins built against any
66
- * scope alias (`@mariozechner`, `@earendil-works`, `@oh-my-pi`) keep working
66
+ * scope alias (`@mariozechner`, `@earendil-works`, `@linxiraos`) keep working
67
67
  * once the specifier shim remaps them to this package.
68
68
  */
69
69
  export declare const Key: {
@@ -26,12 +26,12 @@ export interface KittyGraphicsFeatures {
26
26
  * Whether the detected terminal renders Kitty Unicode placeholders (`U=1` +
27
27
  * U+10EEEE with row/column diacritics).
28
28
  *
29
- * Kitty and Ghostty advertise placeholder support directly. A tmux session
29
+ * Kitty and Ghostty advertise placeholder support directly. A multiplexer
30
30
  * cannot use cursor-positioned placements because the outer terminal does not
31
- * know pane scroll/reflow state, so an explicit `PI_FORCE_IMAGE_PROTOCOL=kitty`
32
- * also opts into placeholders there — matching `timg -pk`. Automatic tmux
33
- * fallback stays off because the unknown outer terminal may render U+10EEEE as
34
- * literal PUA boxes (#1877).
31
+ * know pane scroll/reflow state. An explicit `PI_FORCE_IMAGE_PROTOCOL=kitty`
32
+ * opts into placeholders under any multiplexer — matching `timg -pk`.
33
+ * Automatic Herdr fallback stays off because its pane marker does not prove
34
+ * that the experimental Kitty renderer is enabled.
35
35
  *
36
36
  * `PI_NO_KITTY_PLACEHOLDERS=1` and `PI_KITTY_PLACEHOLDERS=0` remain hard
37
37
  * opt-outs; `PI_KITTY_PLACEHOLDERS=1` explicitly opts in anywhere else.
@@ -43,7 +43,12 @@ export type StdinBufferOptions = {
43
43
  };
44
44
  export type StdinBufferEventMap = {
45
45
  data: [string];
46
- paste: [string];
46
+ /**
47
+ * A completed bracketed paste. `enter` carries an Enter keypress that shared
48
+ * the paste's stdin read, so the terminal can dispatch paste and submit to
49
+ * the same focused component before a paste-triggered overlay can take focus.
50
+ */
51
+ paste: [content: string, enter?: string];
47
52
  };
48
53
  /**
49
54
  * Buffers stdin input and emits complete sequences via the 'data' event.
@@ -1,4 +1,5 @@
1
1
  import type { HangulCompatibilityJamoWidth } from "./utils.js";
2
+ export * from "./terminal-multiplexer.js";
2
3
  export { isInsideTmux, wrapTmuxPassthrough } from "./tmux.js";
3
4
  export declare enum ImageProtocol {
4
5
  Kitty = "\u001B_G",
@@ -48,8 +49,6 @@ export declare class TerminalInfo {
48
49
  formatNotification(message: string | TerminalNotification): string;
49
50
  sendNotification(message: string | TerminalNotification): void;
50
51
  }
51
- /** Detect terminal multiplexers where scrollback clearing and height-change redraws are hostile. */
52
- export declare function isInsideTerminalMultiplexer(env?: NodeJS.ProcessEnv): boolean;
53
52
  /**
54
53
  * Whether the agent process is running inside a Zellij session. Read fresh on
55
54
  * each call (like {@link isInsideTmux}) so a session attached/detached mid-run
@@ -86,9 +85,15 @@ export declare function synchronizedOutputUserOverride(env?: NodeJS.ProcessEnv):
86
85
  * 2. Positive `TERM_FEATURES` advertisement (`Sy`) — survives SSH/mux wrapping.
87
86
  * 3. Windows Terminal (1.24+) via `WT_SESSION`, on native win32 and the
88
87
  * WSL/SSH-fronted host alike.
89
- * 4. Known direct terminals with confirmed support. SSH does *not* disable
88
+ * 4. Herdr panes. Herdr is otherwise treated as a multiplexer so leaked
89
+ * kitty/ghostty identities cannot enable placeholder graphics, but its
90
+ * pane VTE is libghostty and already suppresses compositing while DEC 2026
91
+ * is set. Leaving sync off lets CUP-diff paints and split write(2) chunks
92
+ * composite as dirty-row patches — the live viewport tears, with the top
93
+ * frozen while only the bottom refreshes.
94
+ * 5. Known direct terminals with confirmed support. SSH does *not* disable —
90
95
  * DEC 2026 passes through SSH when the outer terminal honors it.
91
- * 5. Everything else starts off, including risky multiplexers; the runtime
96
+ * 6. Everything else starts off, including risky multiplexers; the runtime
92
97
  * DECRQM probe upgrades any of them when the terminal actually reports
93
98
  * `?2026` supported (current zellij, tmux master, foot, contour, mintty…).
94
99
  */
@@ -165,9 +170,9 @@ export declare function isPaseoEmbedder(env?: NodeJS.ProcessEnv): boolean;
165
170
  /**
166
171
  * Resolve the image protocol for a non-forced runtime: static per-terminal
167
172
  * support (with Warp's platform carve-out), then the multiplexer fallback,
168
- * then the Paseo embedder carve-out. `isTTY` is injectable because the
169
- * fallback only fires on a real TTY — a piped subprocess cannot exercise
170
- * that path, so regression tests call this directly.
173
+ * then host carve-outs. `isTTY` is injectable because the fallback only fires
174
+ * on a real TTY — a piped subprocess cannot exercise that path, so regression
175
+ * tests call this directly.
171
176
  */
172
177
  export declare function resolveImageProtocol(terminalId: TerminalId, env?: NodeJS.ProcessEnv, isTTY?: boolean): ImageProtocol | null;
173
178
  /** Resolve terminal identity from environment markers used by common emulators. */
@@ -0,0 +1,4 @@
1
+ /** True when this process is running inside a Herdr pane. */
2
+ export declare function isInsideHerdr(env?: NodeJS.ProcessEnv): boolean;
3
+ /** Detect whether a terminal multiplexer owns the current screen grid. */
4
+ export declare function isInsideTerminalMultiplexer(env?: NodeJS.ProcessEnv): boolean;
@@ -20,33 +20,50 @@
20
20
  */
21
21
  export declare function chunkForConPTY(data: string, maxChunkBytes?: number): string[];
22
22
  /**
23
- * Turns an unbounded, never-draining stdout writable buffer into a bounded
24
- * disconnect signal.
23
+ * Backlog at or below which stdout is healthy again: the pump has kept up, the
24
+ * TUI resumes composing frames, and a {@link StdoutStallWatchdog} episode ends.
25
+ * The TUI render gate (`TUI.#MAX_PENDING_OUTPUT_BYTES`) is this same value, so
26
+ * the watchdog stays armed across the entire range where frames are deferred —
27
+ * otherwise a consumer that wedges between this level and the arm cap is never
28
+ * re-sampled and the session freezes instead of disconnecting (#10434 review).
29
+ */
30
+ export declare const STDOUT_BACKLOG_CLEAR_BYTES: number;
31
+ /**
32
+ * Bounds a never-draining stdout backlog without killing a single large but
33
+ * actively-draining frame.
25
34
  *
26
35
  * `process.stdout.write()` returns `false` once its buffer exceeds the stream
27
- * high-water mark; the bytes stay queued and are only freed when the consumer
28
- * drains (the `drain` event). While the consumer keeps up, writes are accepted
29
- * and nothing accumulates. When it stalls, every subsequent write piles onto
30
- * the buffer a stalled-but-alive PTY reader never throws, so the write path
31
- * has no other signal that output is going nowhere. This guard sums the bytes
32
- * queued since backpressure began and reports when that backlog crosses the
33
- * cap, at which point the caller treats the terminal as disconnected.
36
+ * high-water mark, and the off-thread pump's `pending()` climbs the same way;
37
+ * a stalled-but-alive PTY reader never throws, so the byte count is the only
38
+ * signal that output is going nowhere. Tripping on the instantaneous count
39
+ * alone is wrong: a legitimate oversized frame (a resume repaint of dozens of
40
+ * inline screenshots, #10430) briefly exceeds the cap and then drains.
41
+ *
42
+ * An episode starts when the backlog first exceeds `armBytes` and lasts until
43
+ * it drains back to `clearBytes` (healthy). The backlog can fall below
44
+ * `armBytes` while still unhealthy, so the episode must outlive that dip
45
+ * (#10434): during it the watchdog declares the terminal disconnected only when
46
+ * the backlog makes no drain progress (no new low-water mark) for `stallMs` —
47
+ * a draining terminal keeps lowering the mark and never trips, while a wedged
48
+ * one (#6854) still tears down within the window.
34
49
  *
35
50
  * Exported for unit testing; `ProcessTerminal` is the sole production user.
36
51
  */
37
- export declare class OutputBacklogGuard {
52
+ export declare class StdoutStallWatchdog {
38
53
  #private;
39
- private readonly capBytes;
40
- constructor(capBytes?: number);
41
- /** True once a refused write started a backlog that has not yet drained. */
42
- get tracking(): boolean;
54
+ private readonly armBytes;
55
+ private readonly clearBytes;
56
+ private readonly stallMs;
57
+ constructor(armBytes?: number, clearBytes?: number, stallMs?: number);
58
+ /** True while an episode is active and the backlog must be polled to completion. */
59
+ get armed(): boolean;
43
60
  /**
44
- * Record one `stdout.write()`: `accepted` is that call's return value and
45
- * `bytes` its encoded size. Returns true when the pending backlog now
46
- * exceeds the cap and the terminal should be treated as disconnected.
61
+ * Feed the current pending-byte count and clock reading. Returns true once an
62
+ * armed episode has gone `stallMs` with no drain progress, at which point the
63
+ * caller treats the terminal as disconnected.
47
64
  */
48
- record(accepted: boolean, bytes: number): boolean;
49
- /** Called on the stdout `drain` event: the buffer emptied, backlog cleared. */
65
+ sample(pending: number, nowMs: number): boolean;
66
+ /** Episode ended (drained) or terminal torn down: stop watching. */
50
67
  reset(): void;
51
68
  }
52
69
  /** Record alternate-screen state (called by the TUI on `?1049h`/`?1049l` writes). */
@@ -82,6 +99,13 @@ export interface TerminalStartOptions {
82
99
  }
83
100
  /** Identity of an accepted explicit terminal appearance refresh request. */
84
101
  export type TerminalAppearanceRequestToken = number;
102
+ /**
103
+ * Fired once per DEC private mode when DECRQM support resolves.
104
+ * `confirmed` is false when only the DA1 sentinel arrived.
105
+ * `status` is the DECRPM value (0 unrecognized, 1/2 set/reset, 3 permanently
106
+ * set, 4 permanently reset) when the terminal answered DECRQM.
107
+ */
108
+ export type PrivateModeReportHandler = (mode: number, supported: boolean, confirmed?: boolean, status?: number) => void;
85
109
  export interface Terminal {
86
110
  start(onInput: (data: string) => void, onResize: () => void, onDisconnect?: () => void, options?: TerminalStartOptions): void;
87
111
  /**
@@ -160,8 +184,9 @@ export interface Terminal {
160
184
  * status resolves. `confirmed` is false when the terminal answered the DA1
161
185
  * sentinel without answering DECRQM, which proves only that querying support
162
186
  * is unavailable — not that the private mode itself is unsupported.
187
+ * `status` is the DECRPM value when the terminal answered DECRQM.
163
188
  */
164
- onPrivateModeReport?(callback: (mode: number, supported: boolean, confirmed?: boolean) => void): void;
189
+ onPrivateModeReport?(callback: PrivateModeReportHandler): void;
165
190
  }
166
191
  /**
167
192
  * True when stdout flows through a ConPTY pseudo-console (native win32, or
@@ -206,7 +231,7 @@ export declare class ProcessTerminal implements Terminal {
206
231
  * probes remain direct. Suppressed while inactive, headless, or after teardown.
207
232
  */
208
233
  refreshAppearance(requestToken?: TerminalAppearanceRequestToken): TerminalAppearanceRequestToken | void;
209
- onPrivateModeReport(callback: (mode: number, supported: boolean, confirmed?: boolean) => void): void;
234
+ onPrivateModeReport(callback: PrivateModeReportHandler): void;
210
235
  start(onInput: (data: string) => void, onResize: () => void, onDisconnect?: () => void, options?: TerminalStartOptions): void;
211
236
  enableInput(): void;
212
237
  drainInput(maxMs?: number, idleMs?: number): Promise<void>;
@@ -285,6 +285,24 @@ export declare class TUI extends Container {
285
285
  * plus a full redraw on the frame after a new image exceeds the cap.
286
286
  */
287
287
  setMaxInlineImages(cap: number): void;
288
+ /**
289
+ * Yield `width` columns from the right edge of the terminal as a sidebar
290
+ * margin, repainted per frame from the gutter component (see
291
+ * {@link setGutterComponent}). The main area composes and paints at
292
+ * `terminal.columns - width`, which keeps every committed row — and
293
+ * therefore native scrollback — free of gutter text. `null` restores
294
+ * full-width rendering. Frames where that would drop the main area below
295
+ * {@link MIN_MAIN_AREA_COLUMNS}, or where a fullscreen-capable overlay is
296
+ * visible, ignore the reservation and paint at the physical width.
297
+ */
298
+ setMainWidth(width: number | null): void;
299
+ /**
300
+ * Component rendered into the right-hand margin created by
301
+ * {@link setMainWidth}. Its rows are painted viewport-only via absolute
302
+ * cursor addressing inside each frame's synchronized block; they never enter
303
+ * the composed frame or scrollback. `null` clears the margin.
304
+ */
305
+ setGutterComponent(component: Component | null): void;
288
306
  /** Return how settled resizes refresh native scrollback. */
289
307
  getResizeScrollback(): ResizeScrollbackMode;
290
308
  /** Set how settled resizes refresh native scrollback. */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@linxiraos/pi-tui",
4
- "version": "1.1.7",
4
+ "version": "1.1.8",
5
5
  "description": "Terminal User Interface library with differential rendering for efficient text-based applications",
6
6
  "homepage": "https://linxira-os.github.io/zeta/",
7
7
  "author": "Stencil Labs, Inc.",
@@ -37,8 +37,8 @@
37
37
  "fmt": "biome format --write ."
38
38
  },
39
39
  "dependencies": {
40
- "@linxiraos/pi-natives": "1.1.7",
41
- "@linxiraos/pi-utils": "1.1.7"
40
+ "@linxiraos/pi-natives": "1.1.8",
41
+ "@linxiraos/pi-utils": "1.1.8"
42
42
  },
43
43
  "devDependencies": {
44
44
  "kitty-vt-wasm": "^0.2.0"
@@ -382,7 +382,7 @@ function buildSlashCommandCompletions(
382
382
  // Equal text-match scores fall back to usage frequency, then to the
383
383
  // stable registry order.
384
384
  .sort((a, b) => b.score - a.score || b.usage - a.usage)
385
- .map(({ score: _, usage: _usage, ...rest }) => rest)
385
+ .map(({ score: _score, usage: _usage, ...rest }) => rest)
386
386
  );
387
387
  }
388
388
 
@@ -467,6 +467,12 @@ export interface EditorTextAssistProvider {
467
467
  type HistoryCursorAnchor = "start" | "end";
468
468
  type AutocompleteRequest = { kind: "regular"; explicitTab: boolean } | { kind: "force" };
469
469
 
470
+ /** What the paste transport knew about the input burst before the editor inserts the payload. */
471
+ export interface PasteOptions {
472
+ /** A submit keypress arrived in the same input burst and will be dispatched right after the paste. */
473
+ submitAfterPaste?: boolean;
474
+ }
475
+
470
476
  export class Editor implements Component, Focusable {
471
477
  #state: EditorState = {
472
478
  lines: [""],
@@ -581,8 +587,9 @@ export class Editor implements Component, Focusable {
581
587
  * the editor inserts nothing and records no undo state, leaving insertion to the host (e.g. a
582
588
  * "wrap in a code block / XML / attach as file" menu for very large pastes), which re-inserts
583
589
  * via {@link insertPaste} or {@link insertText}. Return `false` (or leave unset) for the
584
- * default collapse-to-marker behavior. `lineCount` is the sanitized paste's line count. */
585
- onLargePaste?: (text: string, lineCount: number) => boolean;
590
+ * default collapse-to-marker behavior. `lineCount` is the sanitized paste's line count;
591
+ * `options` carries what the paste transport knew about the burst. */
592
+ onLargePaste?: (text: string, lineCount: number, options: PasteOptions) => boolean;
586
593
  onAutocompleteCancel?: () => void;
587
594
  disableSubmit: boolean = false;
588
595
 
@@ -2148,8 +2155,8 @@ export class Editor implements Component, Focusable {
2148
2155
  }
2149
2156
 
2150
2157
  /** Apply terminal paste semantics to text from non-bracketed paste transports. */
2151
- pasteText(text: string): void {
2152
- this.#handlePaste(text);
2158
+ pasteText(text: string, options: PasteOptions = {}): void {
2159
+ this.#handlePaste(text, options);
2153
2160
  }
2154
2161
 
2155
2162
  /** Insert `content` as a collapsed `[Paste #N]` marker (stored for expansion on submit via
@@ -2289,7 +2296,7 @@ export class Editor implements Component, Focusable {
2289
2296
  }
2290
2297
  }
2291
2298
 
2292
- #handlePaste(pastedText: string): void {
2299
+ #handlePaste(pastedText: string, options: PasteOptions = {}): void {
2293
2300
  let filteredText = this.#sanitizePastedText(pastedText);
2294
2301
 
2295
2302
  // If pasting a file path (starts with /, ~, or .) and the character before
@@ -2311,7 +2318,7 @@ export class Editor implements Component, Focusable {
2311
2318
  // Let the host intercept marker-sized pastes (e.g. the large-paste menu). When it takes
2312
2319
  // over, the editor inserts nothing and records no undo state — the host re-inserts via
2313
2320
  // `insertPaste`/`insertText` once the user chooses.
2314
- if (isMarkerSized && this.onLargePaste?.(filteredText, pastedLines.length)) {
2321
+ if (isMarkerSized && this.onLargePaste?.(filteredText, pastedLines.length, options)) {
2315
2322
  return;
2316
2323
  }
2317
2324
 
@@ -73,9 +73,9 @@ function nextImageIdSeed(): number {
73
73
  *
74
74
  * The budget keeps the most recent `cap` images live and demotes older ones to
75
75
  * their text fallback. Demotion needs a full redraw (so off-screen rows are
76
- * rewritten) plus an explicit graphics purge of the demoted ids {@link Image}
77
- * reports display order via {@link observe}, and the TUI drives the purge +
78
- * redraw on the frame after a new image pushes the count past the cap.
76
+ * rewritten) plus an explicit graphics purge of the demoted ids. {@link Image}
77
+ * reports display order via {@link observe}; when that reveals a stricter split,
78
+ * the TUI repeats the pass before emitting its terminal frame.
79
79
  *
80
80
  * `cap <= 0` disables budgeting: every image stays a live graphic.
81
81
  */
@@ -87,6 +87,8 @@ export class ImageBudget {
87
87
  #idToKey = new Map<number, string>();
88
88
  /** Display-order image ids observed during the in-flight pass. */
89
89
  #passIds: number[] = [];
90
+ /** Per-id suppression decision from the first observation in this pass. */
91
+ #passSuppression = new Map<number, boolean>();
90
92
  /**
91
93
  * Suppress threshold reflected in the frame currently on the terminal: images
92
94
  * at display indices `[0, #onTerminal)` are shown as text there.
@@ -104,7 +106,7 @@ export class ImageBudget {
104
106
  /** Image ids whose data is believed to be loaded in the terminal's store. */
105
107
  #transmitted = new Set<number>();
106
108
  /** Transmit sequences (full base64) to write once, before this frame's placements. */
107
- #pendingTransmits: string[] = [];
109
+ #pendingTransmits = new Map<number, string>();
108
110
  // True while the in-flight pass is a partial/throwaway pass (the
109
111
  // non-multiplexer resize viewport fast path) that walks only the visible
110
112
  // tail, bottom-up. Such a pass cannot derive display order from observe()
@@ -185,6 +187,7 @@ export class ImageBudget {
185
187
  */
186
188
  beginPass(stable = false): void {
187
189
  this.#passIds.length = 0;
190
+ this.#passSuppression.clear();
188
191
  this.#stablePass = stable;
189
192
  this.#applyingReset = !stable && this.#cap > 0 && this.#planned > this.#onTerminal;
190
193
  }
@@ -199,47 +202,49 @@ export class ImageBudget {
199
202
  * (`#suppressedIds`) keyed by id — order- and partiality-independent.
200
203
  */
201
204
  observe(imageId: number): boolean {
205
+ const existing = this.#passSuppression.get(imageId);
206
+ if (existing !== undefined) return existing;
202
207
  if (this.#stablePass) {
203
208
  const suppressed = this.#cap > 0 && this.#suppressedIds.has(imageId);
209
+ this.#passSuppression.set(imageId, suppressed);
204
210
  if (suppressed) this.#forgetKeyForId(imageId);
205
211
  return suppressed;
206
212
  }
207
213
  const index = this.#passIds.length;
208
214
  this.#passIds.push(imageId);
209
215
  const suppressed = this.#cap > 0 && index < this.#planned;
216
+ this.#passSuppression.set(imageId, suppressed);
210
217
  if (suppressed) this.#forgetKeyForId(imageId);
211
218
  return suppressed;
212
219
  }
213
220
 
214
221
  /**
215
- * End a render pass. Returns true when this frame must purge graphics and
216
- * fully repaint to apply a stricter budget; read the ids via
217
- * {@link takePurgeIds}.
222
+ * End a render pass. Returns true when the pass discovered a stricter budget
223
+ * and must be repeated before its terminal frame is emitted.
218
224
  */
219
225
  endPass(): boolean {
220
226
  const total = this.#passIds.length;
221
227
  this.#lastTotal = total;
222
- let reset = false;
223
228
  if (this.#applyingReset) {
224
229
  for (let i = this.#onTerminal; i < this.#planned && i < total; i++) {
225
230
  const id = this.#passIds[i];
226
- this.#purgeIds.push(id);
227
- // d=I frees the data too, so the image must re-transmit if it returns.
231
+ // A transmit queued by a discarded discovery pass never reached
232
+ // the terminal, so cancel it instead of transmitting then purging.
233
+ if (!this.#pendingTransmits.delete(id)) this.#purgeIds.push(id);
228
234
  this.#transmitted.delete(id);
229
235
  this.#deletePlacementState(id);
230
236
  this.#forgetKeyForId(id);
231
237
  }
232
238
  this.#onTerminal = this.#planned;
233
239
  this.#applyingReset = false;
234
- reset = true;
235
240
  }
236
- this.#reconcile(total);
241
+ const retry = this.#reconcile(total);
237
242
  // Snapshot the committed display-order suppression by id: the prefix
238
243
  // [0, #onTerminal) is what the terminal currently shows as text. Partial
239
244
  // passes replay this per id (see #stablePass) instead of re-deriving it
240
245
  // from a reversed, tail-only walk.
241
246
  this.#suppressedIds = new Set(this.#passIds.slice(0, this.#onTerminal));
242
- return reset;
247
+ return retry;
243
248
  }
244
249
 
245
250
  /** Image ids to delete from the terminal this frame; clears the pending set. */
@@ -256,7 +261,7 @@ export class ImageBudget {
256
261
  const ids = [...this.#transmitted];
257
262
  this.#transmitted.clear();
258
263
  this.#purgeIds = [];
259
- this.#pendingTransmits = [];
264
+ this.#pendingTransmits.clear();
260
265
  this.#keyToId.clear();
261
266
  this.#idToKey.clear();
262
267
  this.#placementState.clear();
@@ -393,12 +398,12 @@ export class ImageBudget {
393
398
  enqueueTransmit(imageId: number, sequence: string): void {
394
399
  if (this.#transmitted.has(imageId)) return;
395
400
  this.#transmitted.add(imageId);
396
- this.#pendingTransmits.push(sequence);
401
+ this.#pendingTransmits.set(imageId, sequence);
397
402
  }
398
403
 
399
404
  /** Whether a frame has image data queued but not yet written to the terminal. */
400
405
  hasPendingTransmits(): boolean {
401
- return this.#pendingTransmits.length > 0;
406
+ return this.#pendingTransmits.size > 0;
402
407
  }
403
408
 
404
409
  /**
@@ -410,7 +415,7 @@ export class ImageBudget {
410
415
  get quiescent(): boolean {
411
416
  return (
412
417
  this.#lastTotal === 0 &&
413
- this.#pendingTransmits.length === 0 &&
418
+ this.#pendingTransmits.size === 0 &&
414
419
  this.#purgeIds.length === 0 &&
415
420
  this.#planned === this.#onTerminal
416
421
  );
@@ -418,9 +423,9 @@ export class ImageBudget {
418
423
 
419
424
  /** Transmit sequences to write before this frame's placements; clears the queue. */
420
425
  takeTransmits(): readonly string[] {
421
- if (this.#pendingTransmits.length === 0) return EMPTY_TRANSMITS;
422
- const sequences = this.#pendingTransmits;
423
- this.#pendingTransmits = [];
426
+ if (this.#pendingTransmits.size === 0) return EMPTY_TRANSMITS;
427
+ const sequences = [...this.#pendingTransmits.values()];
428
+ this.#pendingTransmits.clear();
424
429
  return sequences;
425
430
  }
426
431
 
@@ -433,9 +438,9 @@ export class ImageBudget {
433
438
  * re-emit together; keeps no base64 in budget state (the transmit-once design).
434
439
  */
435
440
  forgetTransmitted(): void {
436
- if (this.#transmitted.size === 0 && this.#pendingTransmits.length === 0) return;
441
+ if (this.#transmitted.size === 0 && this.#pendingTransmits.size === 0) return;
437
442
  this.#transmitted.clear();
438
- this.#pendingTransmits = [];
443
+ this.#pendingTransmits.clear();
439
444
  }
440
445
 
441
446
  #forgetKeyForId(id: number): void {
@@ -445,15 +450,16 @@ export class ImageBudget {
445
450
  if (this.#keyToId.get(key) === id) this.#keyToId.delete(key);
446
451
  }
447
452
 
448
- #reconcile(total: number): void {
453
+ #reconcile(total: number): boolean {
449
454
  const desired = this.#cap > 0 ? Math.max(0, total - this.#cap) : 0;
450
455
  if (desired === this.#planned) {
451
456
  // Budget relaxed without a stricter frame (cap raised or images
452
457
  // removed): surviving graphics are untouched and re-exposed rows
453
458
  // repaint normally, so just track the looser threshold.
454
459
  if (this.#planned < this.#onTerminal) this.#onTerminal = this.#planned;
455
- return;
460
+ return false;
456
461
  }
462
+ const retry = desired > this.#onTerminal;
457
463
  this.#planned = desired;
458
464
  // More images must be demoted than the terminal shows: schedule the purge +
459
465
  // full-redraw frame. Fewer: no ghosts to clear, so just catch the tracking
@@ -461,6 +467,7 @@ export class ImageBudget {
461
467
  // render is needed to apply the new threshold.
462
468
  if (desired <= this.#onTerminal) this.#onTerminal = desired;
463
469
  this.#requestRender();
470
+ return retry;
464
471
  }
465
472
  }
466
473