@aragon-agent/cli 0.6.33 → 0.6.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +2305 -2242
  2. package/README.md +119 -18
  3. package/dist/agent/controller.d.ts +29 -0
  4. package/dist/agent/controller.js +42 -1
  5. package/dist/agent/kit-apply.d.ts +56 -0
  6. package/dist/agent/kit-apply.js +209 -0
  7. package/dist/agent/model-profile-settings.d.ts +28 -0
  8. package/dist/agent/model-profile-settings.js +142 -29
  9. package/dist/agent/reducer.d.ts +1 -1
  10. package/dist/commands/builtins.js +4 -0
  11. package/dist/commands/kit-command.d.ts +20 -0
  12. package/dist/commands/kit-command.js +131 -0
  13. package/dist/commands/perf.d.ts +10 -0
  14. package/dist/commands/perf.js +1 -1
  15. package/dist/config/kit-resolution.d.ts +93 -0
  16. package/dist/config/kit-resolution.js +226 -0
  17. package/dist/config/model-kits.d.ts +224 -0
  18. package/dist/config/model-kits.js +302 -0
  19. package/dist/config/model-profile-store.d.ts +25 -0
  20. package/dist/config/model-profiles.d.ts +41 -3
  21. package/dist/config/model-profiles.js +46 -5
  22. package/dist/config/schema.d.ts +16 -0
  23. package/dist/input/keymap.js +18 -4
  24. package/dist/ui/App.js +135 -15
  25. package/dist/ui/Header.d.ts +9 -1
  26. package/dist/ui/Header.js +8 -2
  27. package/dist/ui/PromptInput.js +1 -1
  28. package/dist/ui/ScrollbackShell.d.ts +38 -13
  29. package/dist/ui/ScrollbackShell.js +4 -3
  30. package/dist/ui/StatusBar.d.ts +13 -0
  31. package/dist/ui/StatusBar.js +10 -3
  32. package/dist/ui/TeamPanel.d.ts +12 -0
  33. package/dist/ui/TeamPanel.js +10 -31
  34. package/dist/ui/Transcript.js +22 -2
  35. package/dist/ui/entries/TeamCard.d.ts +18 -2
  36. package/dist/ui/entries/TeamCard.js +47 -13
  37. package/dist/ui/layout/header-hints.d.ts +11 -1
  38. package/dist/ui/layout/header-hints.js +35 -3
  39. package/dist/ui/layout/kit-chip.d.ts +50 -0
  40. package/dist/ui/layout/kit-chip.js +81 -0
  41. package/dist/ui/layout/virtual-window.js +9 -0
  42. package/dist/ui/overlays/HelpOverlay.js +7 -0
  43. package/dist/ui/overlays/KitEditor.d.ts +23 -0
  44. package/dist/ui/overlays/KitEditor.js +101 -0
  45. package/dist/ui/overlays/KitManager.d.ts +23 -0
  46. package/dist/ui/overlays/KitManager.js +104 -0
  47. package/dist/ui/overlays/KitPicker.d.ts +49 -0
  48. package/dist/ui/overlays/KitPicker.js +58 -0
  49. package/dist/ui/overlays/ModelProfilePicker.js +16 -6
  50. package/dist/ui/overlays/SettingsScreen.js +139 -16
  51. package/dist/ui/overlays/kit-picker-state.d.ts +87 -0
  52. package/dist/ui/overlays/kit-picker-state.js +136 -0
  53. package/dist/ui/overlays/kit-settings-state.d.ts +129 -0
  54. package/dist/ui/overlays/kit-settings-state.js +267 -0
  55. package/dist/ui/overlays/model-profile-state.d.ts +26 -3
  56. package/dist/ui/overlays/model-profile-state.js +59 -6
  57. package/dist/ui/scrollback/LiveTail.d.ts +44 -10
  58. package/dist/ui/scrollback/LiveTail.js +20 -4
  59. package/dist/ui/scrollback/limits.d.ts +16 -0
  60. package/dist/ui/scrollback/limits.js +16 -0
  61. package/dist/ui/scrollback/live-preview.js +10 -3
  62. package/dist/ui/scrollback/overflow-print.d.ts +108 -0
  63. package/dist/ui/scrollback/overflow-print.js +120 -0
  64. package/dist/ui/scrollback/renderer.d.ts +11 -1
  65. package/dist/ui/scrollback/renderer.js +53 -25
  66. package/dist/ui/scrollback/tail-anchor.d.ts +68 -0
  67. package/dist/ui/scrollback/tail-anchor.js +77 -0
  68. package/dist/ui/scrollback/tail-window.d.ts +21 -8
  69. package/dist/ui/scrollback/tail-window.js +26 -10
  70. package/dist/ui/scrollback/use-scrollback-view.d.ts +38 -10
  71. package/dist/ui/scrollback/use-scrollback-view.js +372 -85
  72. package/dist/ui/team-status.d.ts +141 -0
  73. package/dist/ui/team-status.js +224 -0
  74. package/dist/ui/transcript-text.js +13 -4
  75. package/dist/ui/use-wheel-routing.js +2 -2
  76. package/package.json +2 -2
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * `useScrollbackView` — the promotion pipeline of native-scroll mode
3
- * (tui-native-terminal-scroll §4.4 / §6.2, tui-full-height-live-region D3/D4/D7/D8).
3
+ * (tui-native-terminal-scroll §4.4 / §6.2, tui-full-height-live-region D3/D4/D7/D8,
4
+ * tui-final-reply-truncated-unscrollable A-prime).
4
5
  *
5
6
  * `App` calls it ALWAYS (hooks cannot be conditional); `enabled: false` makes every
6
7
  * effect a no-op and keeps `scrollMode: 'app'` byte-identical to the pre-feature
@@ -12,8 +13,15 @@
12
13
  * writer. Entries still on screen are never printed - at `H = rows - 1` a printed
13
14
  * row is pushed back off the top by the next frame, and a second copy in the
14
15
  * scrollback would be a duplicate the user meets by scrolling up (I-F8).
15
- * 2. Computes the live-region budget, the window and the tail rows for the shell.
16
- * 3. Flushes the window before either reset path (`/clear`, `--resume`) and on exit,
16
+ * 2. Gives way at the TOP (tui-final-reply-truncated-unscrollable). The window is still
17
+ * counted in ENTRIES, so a settled answer taller than the box used to sit inside the
18
+ * window forever, clipped by `justifyContent="flex-end"`, in a mode whose wheel only
19
+ * scrolls the terminal's scrollback: the clipped rows existed nowhere the user could
20
+ * reach. The rows the box hides are now measured (`overflow-print.ts`) and printed, so
21
+ * `scrollback + screen` covers every row exactly once. Screen unchanged, reachability
22
+ * fixed.
23
+ * 3. Computes the live-region budget, the window and the tail rows for the shell.
24
+ * 4. Flushes the window before either reset path (`/clear`, `--resume`) and on exit,
17
25
  * so "on screen but not printed yet" can never become "lost" (D8 / I-F12).
18
26
  *
19
27
  * THE HEADER AND THE OPENER ARE NOT PRINTED HERE ANY MORE (D3/D4). They are slots of
@@ -27,20 +35,31 @@
27
35
  * issued from inside the main tree's commit (a layout effect) is deferred until that
28
36
  * commit finishes, so its frame would not exist when the effect reads it. A microtask
29
37
  * runs after the commit has unwound, where the offscreen render is synchronous again.
30
- * Everything the pass needs is read from refs for that reason.
31
38
  *
32
- * `printedIds` is the ONLY authority on "already printed" (RV-7). The cursor is just
33
- * a hint for where to resume scanning: entries leave the list by retain-ring
34
- * trimming AND by reducer deletion (empty settled assistants, abandoned tool
35
- * cards), so an id-keyed cursor can dangle, and then the only correct answer is to
36
- * rescan and let `printedIds` skip.
39
+ * THE PASS READS THE COMMITTED FRAME, NOT THE LATEST RENDER. `latest` is refreshed during
40
+ * render, so it can be a frame ahead of the screen; `committed` is written by a layout
41
+ * effect and therefore describes exactly the frame the user is looking at. With
42
+ * entry-granular bookkeeping the difference was harmless (printing was idempotent per
43
+ * entry); with ROW-granular bookkeeping it would slice this frame's picture with another
44
+ * frame's row numbers, and the result is a duplicate or a hole.
45
+ *
46
+ * `printed` is the ONLY authority on "already printed" (RV-7): a `Map` from entry id to
47
+ * the leading rows already handed to the writer, and the width they were measured at. The
48
+ * cursor is just a hint for where to resume scanning: entries leave the list by retain-ring
49
+ * trimming AND by reducer deletion (empty settled assistants, abandoned tool cards), so an
50
+ * id-keyed cursor can dangle, and then the only correct answer is to rescan and let
51
+ * `printed` skip.
37
52
  */
38
- import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react';
53
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef } from 'react';
54
+ import { estimateEntryRows } from '../layout/virtual-window.js';
55
+ import { isLiveTeamCard } from '../team-status.js';
39
56
  import { buildScrollbackBudget } from './budget.js';
40
57
  import { buildLivePreview } from './live-preview.js';
41
58
  import { SCROLLBACK_LIMITS } from './limits.js';
59
+ import { capPrintedRows, planOverflowPrint, reflowSeamRow, } from './overflow-print.js';
42
60
  import { createEntryRenderer } from './renderer.js';
43
- import { isExcluded, settleAllEntries } from './settled-boundary.js';
61
+ import { isEntryStable, isExcluded, settleAllEntries } from './settled-boundary.js';
62
+ import { resolveTailAnchor } from './tail-anchor.js';
44
63
  import { printBoundary, selectTailWindow } from './tail-window.js';
45
64
  export function createScrollbackBridge(parts) {
46
65
  return {
@@ -63,34 +82,57 @@ function printableBefore(entries, index) {
63
82
  }
64
83
  /**
65
84
  * Ids leave `entries` by retain-ring trimming and never come back (ids are unique
66
- * per session), so `printedIds` is trimmed to the live list once it grows well past
85
+ * per session), so both row maps are trimmed to the live list once they grow well past
67
86
  * it. Only ids still present can be re-evaluated, so dropping the rest is lossless.
68
87
  */
69
- function pruneEntryIds(printed, entries) {
70
- if (printed.size <= Math.max(2000, entries.length * 3))
88
+ function pruneEntryIds(entries, printed, heights) {
89
+ const bound = Math.max(2000, entries.length * 3);
90
+ if (printed.size <= bound && heights.size <= bound)
71
91
  return;
72
92
  const live = new Set(entries.map((entry) => entry.id));
73
- for (const id of printed)
93
+ for (const id of [...printed.keys()])
74
94
  if (!live.has(id))
75
95
  printed.delete(id);
96
+ // Height keys are `id|cols|expanded|thinking`; only the id part decides liveness.
97
+ for (const key of [...heights.keys()]) {
98
+ if (!live.has(key.slice(0, key.indexOf('|'))))
99
+ heights.delete(key);
100
+ }
101
+ }
102
+ /** The word the expanded-copy header uses for one entry kind. */
103
+ function expandedLabel(entry) {
104
+ if (entry.kind === 'tool')
105
+ return entry.name;
106
+ // The escape hatch exists for the Agent's ANSWER (known limitation 2 promised it), so the
107
+ // header says what the user pressed Ctrl+O for instead of the internal kind name.
108
+ if (entry.kind === 'assistant')
109
+ return 'answer';
110
+ return entry.kind;
76
111
  }
77
112
  export function useScrollbackView(args) {
78
- const { enabled, bridge, entries, runActive, theme, caps, density, thinkingVisible, reducedMotion, rows, cols, overlayOpen, draftRows, popupRows, statusExpanded, forceInactive = false, itemCount, panelEnabled, teamRowsNatural, } = args;
113
+ const { enabled, bridge, entries, runActive, theme, caps, density, thinkingVisible, reducedMotion, rows, cols, overlayOpen, draftRows, popupRows, statusExpanded, forceInactive = false, itemCount, panelEnabled, teamRowsNatural, expandedToolIds, } = args;
79
114
  const contentCols = Math.max(1, cols - 1);
80
- // Everything the asynchronous pass reads travels here, refreshed on every render.
115
+ // Everything the asynchronous EXIT and RESET paths read travels here, refreshed on every
116
+ // render (see `committed` for why the promotion pass does not read it).
81
117
  const latest = useRef({
82
- entries, runActive, contentCols,
118
+ entries, runActive, contentCols, previewCols: contentCols, expandedToolIds,
83
119
  options: { theme, caps, density, thinkingVisible, reducedMotion },
84
120
  });
85
121
  latest.current = {
86
- entries, runActive, contentCols,
122
+ entries, runActive, contentCols, previewCols: latest.current.previewCols, expandedToolIds,
87
123
  options: { theme, caps, density, thinkingVisible, reducedMotion },
88
124
  };
89
125
  const rendererRef = useRef(null);
90
- const printedIds = useRef(new Set());
126
+ /** THE authority on "already printed" (RV-7), per entry and per row. */
127
+ const printed = useRef(new Map());
128
+ /** Measured heights, `id|cols|expanded|thinking` -> rows. Only STABLE entries are stored. */
129
+ const heights = useRef(new Map());
91
130
  /** A resume hint only (RV-7): the id of the last entry the previous pass covered. */
92
131
  const cursorRef = useRef(null);
93
132
  const pendingReset = useRef(null);
133
+ const headRowsRef = useRef(0);
134
+ /** Guards the "measure, then re-render so the anchor can use it" nudge against a loop. */
135
+ const nudgedRef = useRef(null);
94
136
  // Band hysteresis (release-gate-and-native-panels §6.7): the writer re-lays out the
95
137
  // canvas on every batch, so a band that shrank for two frames would make everything
96
138
  // above the composer jump.
@@ -99,6 +141,9 @@ export function useScrollbackView(args) {
99
141
  const heldGeometry = useRef({ rows, cols });
100
142
  const pumpQueued = useRef(false);
101
143
  const mountedRef = useRef(true);
144
+ const committed = useRef(null);
145
+ /** Bumped when a measurement has to reach `LiveTail` before the next pass may print. */
146
+ const [measureEpoch, bumpMeasureEpoch] = useReducer((n) => n + 1, 0);
102
147
  const ensureRenderer = useCallback(() => {
103
148
  if (!rendererRef.current)
104
149
  rendererRef.current = createEntryRenderer(latest.current.options);
@@ -110,38 +155,124 @@ export function useScrollbackView(args) {
110
155
  return;
111
156
  bridge.drain.enqueue(rowsToPrint, { id, kind });
112
157
  }, [bridge]);
113
- /** Promote `list[start..end)`; returns true when it stopped early because the feed is full. */
114
- const promote = useCallback((list, end, limit) => {
115
- const renderer = ensureRenderer();
158
+ const heightKey = useCallback((entry, colsNow, expanded) => `${entry.id}|${colsNow}|${expanded ? 1 : 0}|${thinkingVisible ? 1 : 0}`, [thinkingVisible]);
159
+ /** Rows of one entry at `colsNow`, measured once per (id, cols, flags) and cached. */
160
+ const measure = useCallback((entry, prev, colsNow, expanded) => {
161
+ const key = heightKey(entry, colsNow, expanded);
162
+ const cached = heights.current.get(key);
163
+ if (cached !== undefined)
164
+ return cached;
165
+ const measured = ensureRenderer().renderEntryRows(entry, prev, colsNow, expanded).length;
166
+ heights.current.set(key, measured);
167
+ return measured;
168
+ }, [ensureRenderer, heightKey]);
169
+ /**
170
+ * Which width the REMAINDER of an entry must be printed at.
171
+ *
172
+ * Row numbers are width-relative, so a recorded width that this frame still legitimately
173
+ * renders at is the only width whose row numbers can be trusted (`known`); anything else
174
+ * is a reflow, and the caller starts over behind a seam row.
175
+ */
176
+ const resolvePrintWidth = useCallback((state, wanted, known) => {
177
+ if (!state || state.cols === wanted)
178
+ return wanted;
179
+ return known.includes(state.cols) ? state.cols : wanted;
180
+ }, []);
181
+ /**
182
+ * Print everything of `list[index]` that is not in the scrollback yet, in ONE go.
183
+ *
184
+ * The entry has left the region, so all of it may print; what is left is the remainder
185
+ * behind the rows the top give-way already printed (`printed.rows`). A width change makes
186
+ * those row numbers meaningless, so it prints a seam and starts over - a bounded
187
+ * repetition instead of a hole.
188
+ */
189
+ const printRemainder = useCallback((list, index, wantedCols, known, expanded) => {
190
+ const entry = list[index];
191
+ const state = printed.current.get(entry.id);
192
+ if (state?.done)
193
+ return;
194
+ const width = resolvePrintWidth(state, wantedCols, known);
195
+ const restart = state !== undefined && state.cols !== width;
196
+ const from = restart ? 0 : state?.rows ?? 0;
197
+ const body = ensureRenderer().renderEntryRows(entry, printableBefore(list, index), width, expanded.includes(entry.id));
198
+ const seam = restart ? reflowSeamRow(state.rows, state.cols, width) : null;
199
+ const tail = body.slice(from);
200
+ const capped = capPrintedRows(tail, from);
201
+ enqueue(seam === null ? capped : [seam, ...capped], entry.id, entry.kind);
202
+ printed.current.set(entry.id, { rows: body.length, cols: width, done: true });
203
+ }, [enqueue, ensureRenderer, resolvePrintWidth]);
204
+ /** Expanded ids of a frame, as a list so a callback does not depend on the object. */
205
+ const expandedIdsOf = useCallback((ids) => Object.keys(ids).filter((id) => ids[id] === true), []);
206
+ /** The window as full-list indices (excluded entries already dropped), oldest first. */
207
+ const windowItemsOf = useCallback((frame, start) => {
208
+ const items = [];
209
+ for (let i = start; i < frame.entries.length; i += 1) {
210
+ const entry = frame.entries[i];
211
+ if (!isExcluded(entry))
212
+ items.push({ index: i, entry });
213
+ }
214
+ return items;
215
+ }, []);
216
+ /**
217
+ * The window's measured rows, or `undefined` when the measurement cannot be trusted.
218
+ *
219
+ * TWO conditions, both structural rather than defensive. Every entry must be STABLE: an
220
+ * entry the reducer may still rewrite has a height that changes, and printing part of it
221
+ * would put a version of the answer into the scrollback that can never be corrected. And
222
+ * the caller has already checked that the wall does not sit before the window: rows
223
+ * behind an unprintable entry would land out of conversation order (I-S3), which is the
224
+ * one mistake an append-only medium cannot take back.
225
+ */
226
+ const measureWindow = useCallback((frame, items) => {
227
+ const last = frame.entries.length - 1;
228
+ for (const item of items) {
229
+ if (!isEntryStable(item.entry, frame.runActive, item.index === last))
230
+ return undefined;
231
+ }
232
+ const expanded = expandedIdsOf(frame.expandedToolIds);
233
+ return items.map((item) => {
234
+ const state = printed.current.get(item.entry.id);
235
+ const comparable = state !== undefined && state.cols === frame.previewCols && !state.done;
236
+ return {
237
+ entry: item.entry,
238
+ rows: measure(item.entry, printableBefore(frame.entries, item.index), frame.previewCols, expanded.includes(item.entry.id)),
239
+ printed: comparable ? state.rows : 0,
240
+ stable: true,
241
+ };
242
+ });
243
+ }, [expandedIdsOf, measure]);
244
+ /** Promote `list[start..end)`; reports when it stopped early because the feed is full. */
245
+ const promote = useCallback((frame, end, limit, known) => {
246
+ const list = frame.entries;
247
+ const expanded = expandedIdsOf(frame.expandedToolIds);
116
248
  let start = 0;
117
249
  const cursor = cursorRef.current;
118
250
  if (cursor && list[cursor.index]?.id === cursor.id)
119
251
  start = cursor.index + 1;
120
- let promoted = 0;
252
+ let used = 0;
121
253
  let lastIndex = start - 1;
122
254
  const remember = () => {
123
255
  cursorRef.current = lastIndex >= 0 ? { id: list[lastIndex].id, index: lastIndex } : null;
124
256
  };
125
257
  for (let i = start; i < end; i += 1) {
126
258
  const entry = list[i];
127
- if (isExcluded(entry) || printedIds.current.has(entry.id)) {
259
+ // A partially printed entry is NOT finished: it is processed until `done`, so a row
260
+ // range the give-way left behind is still picked up here (P-5).
261
+ if (isExcluded(entry) || printed.current.get(entry.id)?.done === true) {
128
262
  lastIndex = i;
129
263
  continue;
130
264
  }
131
- if (promoted >= limit) {
265
+ if (used >= limit) {
132
266
  remember();
133
- return true;
267
+ return { limited: true, used };
134
268
  }
135
- const rowsToPrint = renderer.renderEntry(entry, printableBefore(list, i), latest.current.contentCols);
136
- enqueue(rowsToPrint, entry.id, entry.kind);
137
- // A rendered-to-nothing entry is registered too, or it would be retried forever.
138
- printedIds.current.add(entry.id);
139
- promoted += 1;
269
+ printRemainder(list, i, frame.contentCols, known, expanded);
270
+ used += 1;
140
271
  lastIndex = i;
141
272
  }
142
273
  remember();
143
- return false;
144
- }, [ensureRenderer, enqueue]);
274
+ return { limited: false, used };
275
+ }, [expandedIdsOf, printRemainder]);
145
276
  /**
146
277
  * THE ONE PRINT LOOP (RV-P0-2 / RV-P2-12): every not-yet-printed entry of `list`,
147
278
  * oldest first, with no per-pass limit.
@@ -160,24 +291,24 @@ export function useScrollbackView(args) {
160
291
  const flushUnprinted = useCallback((list) => {
161
292
  if (!bridge)
162
293
  return;
163
- const renderer = ensureRenderer();
294
+ const known = [latest.current.contentCols, latest.current.previewCols];
295
+ const expanded = expandedIdsOf(latest.current.expandedToolIds);
164
296
  for (const entry of settleAllEntries(list)) {
165
- if (printedIds.current.has(entry.id))
297
+ if (printed.current.get(entry.id)?.done === true)
166
298
  continue;
167
- enqueue(renderer.renderEntry(entry, printableBefore(list, list.indexOf(entry)), latest.current.contentCols), entry.id, entry.kind);
168
- printedIds.current.add(entry.id);
299
+ printRemainder(list, list.indexOf(entry), latest.current.contentCols, known, expanded);
169
300
  }
170
- }, [bridge, ensureRenderer, enqueue]);
301
+ }, [bridge, expandedIdsOf, printRemainder]);
171
302
  const applyPendingReset = useCallback(() => {
172
303
  const reset = pendingReset.current;
173
304
  if (!reset || latest.current.entries === reset.captured)
174
305
  return;
175
306
  pendingReset.current = null;
176
307
  // ORDER IS THE CONTRACT (AC-F16): flush the OLD list, then the separator, then
177
- // forget what was printed. Clearing `printedIds` first would make the flush print
308
+ // forget what was printed. Clearing `printed` first would make the flush print
178
309
  // the whole conversation a second time.
179
310
  flushUnprinted(reset.captured);
180
- printedIds.current = new Set();
311
+ printed.current = new Map();
181
312
  cursorRef.current = null;
182
313
  enqueue([reset.kind === 'clear' ? CLEARED_ROW : RESTORED_ROW], `reset:${Date.now()}`, 'notice');
183
314
  }, [enqueue, flushUnprinted]);
@@ -188,56 +319,109 @@ export function useScrollbackView(args) {
188
319
  pumpQueued.current = true;
189
320
  queueMicrotask(() => pumpRef.current());
190
321
  }, []);
322
+ const continueOnDrain = useCallback(() => {
323
+ if (!bridge)
324
+ return;
325
+ bridge.drain.onDrained = () => {
326
+ bridge.drain.onDrained = null;
327
+ schedulePump();
328
+ };
329
+ bridge.requestFlush();
330
+ }, [bridge, schedulePump]);
331
+ /**
332
+ * TOP GIVE-WAY: print the rows the box hides, when it hides them from the TOP.
333
+ *
334
+ * The order of the two decisions is not cosmetic. `frame.anchor` is what the SCREEN is
335
+ * doing; `planOverflowPrint` answers what is off it. Printing while the frame is
336
+ * `top`-anchored would print the rows the user is looking at (Ink clips the BOTTOM in that
337
+ * branch) and leave the ones they cannot see - a duplicate and a hole at once. So a frame
338
+ * whose anchor the measurement contradicts is nudged once and the print waits for the
339
+ * frame that agrees.
340
+ *
341
+ * @returns How many segments were enqueued.
342
+ */
343
+ const printOverflow = useCallback((frame, allowance) => {
344
+ if (frame.tailRows <= 0)
345
+ return 0;
346
+ const maxEntries = SCROLLBACK_LIMITS.liveTailMaxEntries;
347
+ const { start } = selectTailWindow(frame.entries, maxEntries);
348
+ // The wall before the window is still a wall: the give-way would print rows that come
349
+ // after an unprintable entry (I-S3 / A12).
350
+ if (printBoundary(frame.entries, frame.runActive, maxEntries) < start)
351
+ return 0;
352
+ const items = windowItemsOf(frame, start);
353
+ if (items.length === 0)
354
+ return 0;
355
+ const measured = measureWindow(frame, items);
356
+ if (!measured)
357
+ return 0;
358
+ const total = measured.reduce((sum, item) => sum + item.rows, 0);
359
+ if (frame.measuredRows !== total) {
360
+ // `LiveTail` anchored this frame from an estimate (or from an older measurement).
361
+ // Hand it the number, once per distinct picture, and print on the frame that agrees.
362
+ const nudgeKey = `${start}|${items.length}|${total}`;
363
+ if (nudgedRef.current !== nudgeKey) {
364
+ nudgedRef.current = nudgeKey;
365
+ bumpMeasureEpoch();
366
+ }
367
+ }
368
+ if (frame.anchor !== 'bottom')
369
+ return 0;
370
+ const plan = planOverflowPrint(measured, frame.tailRows);
371
+ const expanded = expandedIdsOf(frame.expandedToolIds);
372
+ let used = 0;
373
+ for (const segment of plan.segments) {
374
+ if (used >= allowance) {
375
+ continueOnDrain();
376
+ return used;
377
+ }
378
+ const item = measured[segment.index];
379
+ const state = printed.current.get(item.entry.id);
380
+ // The segment's row numbers live in the box's index space, so the rows must be
381
+ // rendered and printed at that width; a stale recorded width restarts behind a seam.
382
+ const restart = state !== undefined && state.cols !== frame.previewCols;
383
+ const from = restart ? 0 : state?.rows ?? 0;
384
+ const body = ensureRenderer().renderEntryRows(item.entry, printableBefore(frame.entries, items[segment.index].index), frame.previewCols, expanded.includes(item.entry.id));
385
+ const slice = body.slice(from, Math.max(from, segment.toRow));
386
+ const out = capPrintedRows(slice, from);
387
+ const seam = restart ? reflowSeamRow(state.rows, state.cols, frame.previewCols) : null;
388
+ enqueue(seam === null ? out : [seam, ...out], item.entry.id, item.entry.kind);
389
+ const capped = out.length !== slice.length;
390
+ const finished = capped || segment.toRow >= item.rows;
391
+ printed.current.set(item.entry.id, {
392
+ rows: finished ? item.rows : segment.toRow,
393
+ cols: frame.previewCols,
394
+ done: finished,
395
+ });
396
+ headRowsRef.current += out.length;
397
+ used += 1;
398
+ }
399
+ return used;
400
+ }, [continueOnDrain, enqueue, ensureRenderer, expandedIdsOf, measureWindow, windowItemsOf]);
191
401
  /** The promotion pass. Runs in a microtask (see the file header). */
192
402
  pumpRef.current = () => {
193
403
  pumpQueued.current = false;
194
- if (!mountedRef.current || !bridge)
404
+ const frame = committed.current;
405
+ if (!mountedRef.current || !bridge || !frame)
195
406
  return;
196
407
  applyPendingReset();
197
- const { entries: list, runActive: active } = latest.current;
408
+ const known = [frame.contentCols, frame.previewCols];
198
409
  const limit = Math.max(1, SCROLLBACK_LIMITS.feedCapacity - bridge.drain.pendingEntries() - 1);
199
410
  // `printBoundary` = min(settled, window start): the region keeps what it shows.
200
- const end = printBoundary(list, active, SCROLLBACK_LIMITS.liveTailMaxEntries);
201
- const more = promote(list, end, limit);
202
- pruneEntryIds(printedIds.current, list);
203
- if (more) {
411
+ const end = printBoundary(frame.entries, frame.runActive, SCROLLBACK_LIMITS.liveTailMaxEntries);
412
+ const promoted = promote(frame, end, limit, known);
413
+ pruneEntryIds(frame.entries, printed.current, heights.current);
414
+ if (promoted.limited) {
204
415
  // Continue once the writer has consumed what is queued (a restored transcript
205
416
  // longer than the feed is promoted in waves rather than folded into a marker).
206
- bridge.drain.onDrained = () => {
207
- bridge.drain.onDrained = null;
208
- schedulePump();
209
- };
210
- bridge.requestFlush();
417
+ continueOnDrain();
418
+ return;
211
419
  }
420
+ // ORDER: everything that has left the window is older than everything in it, so the
421
+ // give-way only ever runs in a pass that promoted everything it had to.
422
+ if (printOverflow(frame, Math.max(0, limit - promoted.used)) > 0)
423
+ bridge.requestFlush();
212
424
  };
213
- useLayoutEffect(() => {
214
- if (enabled && bridge)
215
- schedulePump();
216
- }, [enabled, bridge, entries, runActive, schedulePump]);
217
- const settleAll = useCallback(() => {
218
- flushUnprinted(latest.current.entries);
219
- }, [flushUnprinted]);
220
- // Shutdown hook for the exit paths. `restore()` runs it AFTER the tree is gone
221
- // (normal exit) or while it is alive (signal), so it renders synchronously and then
222
- // releases the offscreen instance. The unmount cleanup deliberately renders nothing:
223
- // it runs inside the main tree's commit, where an offscreen render is deferred.
224
- const settleAllRef = useRef(settleAll);
225
- settleAllRef.current = settleAll;
226
- useEffect(() => {
227
- mountedRef.current = true;
228
- if (!enabled || !bridge)
229
- return undefined;
230
- bridge.settleAllNow = () => {
231
- try {
232
- settleAllRef.current();
233
- }
234
- finally {
235
- rendererRef.current?.dispose();
236
- rendererRef.current = null;
237
- }
238
- };
239
- return () => { mountedRef.current = false; };
240
- }, [enabled, bridge]);
241
425
  // --- Live region budget and the tail window. ------------------------------
242
426
  // The window is the last K printable entries, settled or not (D6/D7). `slice` +
243
427
  // `tailWindowStart` is `tail-window.ts`'s definition, and `printBoundary` uses the
@@ -281,12 +465,88 @@ export function useScrollbackView(args) {
281
465
  }
282
466
  // Print keeps `contentCols`; only the live tail gives up the rail's columns (I-5).
283
467
  const previewCols = budget ? budget.previewCols : contentCols;
468
+ const tailRows = budget ? budget.liveTailRows : 0;
469
+ // `previewCols` is only known after the budget, so the copy above carries the PREVIOUS
470
+ // frame's value; this line hands the exit and reset paths the current one. The promotion
471
+ // pass does not read it - it reads `committed`, written below.
472
+ latest.current.previewCols = previewCols;
473
+ const lastIndex = entries.length - 1;
474
+ const indexById = useMemo(() => new Map(entries.map((entry, index) => [entry.id, index])), [entries]);
475
+ /**
476
+ * The window's measured height, when every entry in it is stable AND already measured at
477
+ * this geometry. This is the number `LiveTail` anchors with, and the number the pump
478
+ * compares itself against, so both agree about which frame the user is looking at.
479
+ */
480
+ const measuredTailRows = useMemo(() => {
481
+ if (!enabled || tailRows <= 0 || tailEntries.length === 0)
482
+ return undefined;
483
+ let total = 0;
484
+ for (const entry of tailEntries) {
485
+ if (!isEntryStable(entry, runActive, indexById.get(entry.id) === lastIndex)) {
486
+ return undefined;
487
+ }
488
+ const cached = heights.current.get(heightKey(entry, previewCols, expandedToolIds[entry.id] === true));
489
+ if (cached === undefined)
490
+ return undefined;
491
+ total += cached;
492
+ }
493
+ return total;
494
+ // `heights` is a ref and `measureEpoch` is what fills it; every OTHER dependency is an
495
+ // input of the cache key, so a stale answer is impossible.
496
+ // eslint-disable-next-line react-hooks/exhaustive-deps
497
+ }, [enabled, tailRows, tailEntries, runActive, indexById, lastIndex, previewCols,
498
+ expandedToolIds, thinkingVisible, measureEpoch, heightKey]);
499
+ const anchor = resolveTailAnchor({
500
+ entries: tailEntries,
501
+ budgetRows: tailRows,
502
+ rowOf: (entry) => estimateEntryRows(entry, previewCols, density, expandedToolIds[entry.id] === true, thinkingVisible),
503
+ measuredRows: measuredTailRows,
504
+ });
284
505
  const liveTailLines = useMemo(() => enabled && budget && budget.liveTailRows > 0
285
506
  ? buildLivePreview({
286
507
  unsettled: tailEntries, cols: previewCols, rows: budget.liveTailRows,
287
508
  thinkingVisible,
288
509
  })
289
510
  : [], [enabled, budget, tailEntries, previewCols, thinkingVisible]);
511
+ // THE COMMIT HOOK. Every commit records the frame the screen is showing, so the microtask
512
+ // pass can never slice this frame's picture with another frame's numbers. It is the last
513
+ // layout effect in this hook on purpose: everything above is render-time state.
514
+ useLayoutEffect(() => {
515
+ committed.current = {
516
+ entries, runActive, contentCols, previewCols, tailRows, anchor, measuredRows: measuredTailRows,
517
+ expandedToolIds,
518
+ };
519
+ });
520
+ // Only a content change (or a measurement that must reach `LiveTail`) needs a pass; a
521
+ // resize is the writer's business, exactly as before.
522
+ useLayoutEffect(() => {
523
+ if (enabled && bridge)
524
+ schedulePump();
525
+ }, [enabled, bridge, entries, runActive, measureEpoch, schedulePump]);
526
+ const settleAll = useCallback(() => {
527
+ flushUnprinted(latest.current.entries);
528
+ }, [flushUnprinted]);
529
+ // Shutdown hook for the exit paths. `restore()` runs it AFTER the tree is gone
530
+ // (normal exit) or while it is alive (signal), so it renders synchronously and then
531
+ // releases the offscreen instance. The unmount cleanup deliberately renders nothing:
532
+ // it runs inside the main tree's commit, where an offscreen render is deferred.
533
+ const settleAllRef = useRef(settleAll);
534
+ settleAllRef.current = settleAll;
535
+ useEffect(() => {
536
+ mountedRef.current = true;
537
+ if (!enabled || !bridge)
538
+ return undefined;
539
+ bridge.settleAllNow = () => {
540
+ try {
541
+ settleAllRef.current();
542
+ }
543
+ finally {
544
+ rendererRef.current?.dispose();
545
+ rendererRef.current = null;
546
+ }
547
+ };
548
+ return () => { mountedRef.current = false; };
549
+ }, [enabled, bridge]);
290
550
  const reprintExpanded = useCallback((entryId) => {
291
551
  if (!enabled || !bridge)
292
552
  return false;
@@ -295,12 +555,35 @@ export function useScrollbackView(args) {
295
555
  if (index < 0)
296
556
  return false;
297
557
  const entry = list[index];
298
- const body = ensureRenderer().renderEntry(entry, undefined, latest.current.contentCols, true);
299
- if (body.length === 0)
558
+ // A LIVE DISPATCH CARD IS REFUSED, NOT PRINTED (tui-subagent-double-roster A-2').
559
+ // `Ctrl+O` arrives mid-dispatch, `EntryView` suppresses this card, and a copy
560
+ // printed here would be a FROZEN SNAPSHOT of a card the roster is still rewriting -
561
+ // permanently in the scrollback, because printed is forever.
562
+ if (isLiveTeamCard(entry))
300
563
  return false;
301
- enqueue([`-- expanded: ${entry.kind === 'tool' ? entry.name : entry.kind} --`, ...body], `expanded:${entryId}:${Date.now()}`, entry.kind);
564
+ // THE COPY IS RENDERED IN A MICROTASK, NOT IN THE KEY HANDLER THAT ASKED FOR IT.
565
+ // `Ctrl+O` arrives on the stdin stream, and an offscreen render issued from there is
566
+ // SCHEDULED rather than flushed - the reconciler sees a pending update, the frame the
567
+ // caller reads back is still empty, and the copy degrades to
568
+ // `[aragon] entry ... could not be rendered`. A microtask runs after the input handler
569
+ // has unwound, where the offscreen render is synchronous again: the same rule the
570
+ // promotion pass follows (see the file header). The answer is therefore "this entry
571
+ // exists and a copy is on its way", which is what the caller's toast needs.
572
+ //
573
+ // THE ID IS STABLE ON PURPOSE. `expanded:<entryId>` makes the copy greppable and keeps
574
+ // the key purely user-driven; it is not a dedupe key, because the drain is a FIFO that
575
+ // never coalesces, so a second press prints a second copy - the behaviour the tool cards
576
+ // have always had, and the reason the stable id is safe to use here.
577
+ queueMicrotask(() => {
578
+ if (!mountedRef.current || !bridge)
579
+ return;
580
+ const body = ensureRenderer().renderEntry(entry, undefined, latest.current.contentCols, true);
581
+ if (body.length === 0)
582
+ return;
583
+ enqueue([`-- expanded: ${expandedLabel(entry)} --`, ...body], `expanded:${entryId}`, entry.kind);
584
+ });
302
585
  return true;
303
- }, [enabled, bridge, ensureRenderer, enqueue]);
586
+ }, [bridge, enabled, enqueue, ensureRenderer]);
304
587
  const notifyReset = useCallback((kind) => {
305
588
  if (!enabled)
306
589
  return;
@@ -309,6 +592,10 @@ export function useScrollbackView(args) {
309
592
  pendingReset.current = { kind, captured: latest.current.entries };
310
593
  }, [enabled]);
311
594
  return {
312
- budget, liveTailLines, tailEntries, windowStart, reprintExpanded, settleAll, notifyReset,
595
+ budget, liveTailLines, tailEntries, windowStart, measuredTailRows,
596
+ // A GETTER, like `perfRef`'s `scrollbar`: the counter moves in a microtask, so a value
597
+ // captured at render time would report the frame BEFORE the one `/perf` is asked about.
598
+ get headRows() { return headRowsRef.current; },
599
+ reprintExpanded, settleAll, notifyReset,
313
600
  };
314
601
  }