@causyne/agent 1.20.84 → 1.20.86

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.84",
3
+ "version": "1.20.86",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
@@ -9,6 +9,7 @@
9
9
  // Pure JS over ./theme.js and ./text.js. No dependency, no shell.
10
10
 
11
11
  import readline from 'readline';
12
+ import { compactSuccessfulToolResult } from './toolActivityPolicy.js';
12
13
  import {
13
14
  paint, bold, dim, badge, GLYPHS, terminalWidth, HAS_COLOR, fileLink,
14
15
  safeLink, HAS_HYPERLINKS
@@ -1051,7 +1052,7 @@ export class ChatRenderer {
1051
1052
  const detailText = detail ? paint('ink', truncate(detail, Math.max(10, width - used - 12), GLYPHS.ellipsis)) : '';
1052
1053
 
1053
1054
  this.write(`${paint('muted', GLYPHS.arrow)} ${index} ${name} ${detailText}`);
1054
- }, { step, tool: msg.tool });
1055
+ }, { step, tool: msg.tool, verb: verb || msg.tool, detail });
1055
1056
  }
1056
1057
 
1057
1058
  onStepComplete(msg) {
@@ -1065,6 +1066,23 @@ export class ChatRenderer {
1065
1066
  // result the user finished with ten turns ago.
1066
1067
  this.captureLastOutput(result);
1067
1068
 
1069
+ const tail = this.transcript?.frames?.at(-1);
1070
+ if (compactSuccessfulToolResult(this.stepCount, result, tail, msg?.tool)) {
1071
+ const { step, verb, detail, tool } = tail.meta;
1072
+ const completedElapsed = elapsed;
1073
+ this.updateTailFrame('step', () => {
1074
+ const width = this.width();
1075
+ const index = paint('muted', String(step).padStart(2, '0'));
1076
+ const name = paint('accent', padEnd(verb || tool, STATUS_GUTTER));
1077
+ const used = 2 + 2 + 1 + Math.max(visibleWidth(verb || tool), STATUS_GUTTER) + 1;
1078
+ const tailText = completedElapsed ? ` ${dim(completedElapsed)}` : '';
1079
+ const detailWidth = Math.max(5, width - used - visibleWidth(tailText) - 10);
1080
+ const detailText = detail ? paint('ink', truncate(detail, detailWidth, GLYPHS.ellipsis)) : '';
1081
+ this.write(`${paint('success', GLYPHS.check)} ${index} ${name} ${detailText}${tailText}`);
1082
+ }, { ...tail.meta, success: true, elapsed: completedElapsed });
1083
+ return;
1084
+ }
1085
+
1068
1086
  this.frame('result', () => {
1069
1087
  if (result.success) {
1070
1088
  const elapsedText = elapsed ? ` ${dim(elapsed)}` : '';
@@ -1154,10 +1172,13 @@ export class ChatRenderer {
1154
1172
  if (wrapped.length > PREVIEW_LINES + 1) break;
1155
1173
  }
1156
1174
 
1157
- for (const line of wrapped.slice(0, PREVIEW_LINES)) {
1175
+ // A long tool-heavy run needs a concise preview. Full output remains
1176
+ // available through the existing Ctrl+O expansion path and spill files.
1177
+ const previewLimit = this.stepCount >= 12 ? 5 : PREVIEW_LINES;
1178
+ for (const line of wrapped.slice(0, previewLimit)) {
1158
1179
  this.write(` ${paint('rule', GLYPHS.vLine)} ${dim(line)}`);
1159
1180
  }
1160
- const clipped = wrapped.length > PREVIEW_LINES || source.length < payload.length;
1181
+ const clipped = wrapped.length > previewLimit || source.length < payload.length;
1161
1182
  if (clipped) this.write(this.clipHint(result.spillPath));
1162
1183
  }
1163
1184
 
@@ -78,10 +78,17 @@ export function sessionSidebarRows(facts, height) {
78
78
  const completed = facts.plan.filter(item => item.status === 'completed').length;
79
79
  line();
80
80
  styled(bold(`Plan ${completed}/${facts.plan.length}`));
81
- for (const item of facts.plan) {
81
+ const planItems = facts.plan.length <= 6 ? facts.plan : [
82
+ ...facts.plan.filter(item => item.status === 'in_progress').slice(0, 2),
83
+ ...facts.plan.filter(item => item.status !== 'in_progress' && item.status !== 'completed').slice(0, 3),
84
+ ...facts.plan.filter(item => item.status === 'completed').slice(-2)
85
+ ].slice(0, 6);
86
+ for (const item of planItems) {
82
87
  const mark = item.status === 'completed' ? '✓' : item.status === 'in_progress' ? '▸' : '·';
83
88
  line(`${mark} ${item.text || item.step || item.content || ''}`);
84
89
  }
90
+ if (facts.plan.length > planItems.length)
91
+ line(`${facts.plan.length - planItems.length} additional plan steps`);
85
92
  }
86
93
  const count = Number.isFinite(height) ? Math.max(1, Math.floor(height)) : 1;
87
94
  const visible = rows.slice(0, count);
@@ -95,10 +95,16 @@ export function sessionSidebarRows(facts: SidebarFacts, height: number): string[
95
95
  const completed = facts.plan.filter(item => item.status === 'completed').length;
96
96
  line();
97
97
  styled(bold(`Plan ${completed}/${facts.plan.length}`));
98
- for (const item of facts.plan) {
98
+ const planItems = facts.plan.length <= 6 ? facts.plan : [
99
+ ...facts.plan.filter(item => item.status === 'in_progress').slice(0, 2),
100
+ ...facts.plan.filter(item => item.status !== 'in_progress' && item.status !== 'completed').slice(0, 3),
101
+ ...facts.plan.filter(item => item.status === 'completed').slice(-2)
102
+ ].slice(0, 6);
103
+ for (const item of planItems) {
99
104
  const mark = item.status === 'completed' ? '✓' : item.status === 'in_progress' ? '▸' : '·';
100
105
  line(`${mark} ${item.text || item.step || item.content || ''}`);
101
106
  }
107
+ if (facts.plan.length > planItems.length) line(`${facts.plan.length - planItems.length} additional plan steps`);
102
108
  }
103
109
 
104
110
  const count = Number.isFinite(height) ? Math.max(1, Math.floor(height)) : 1;
package/src/tui/stage.js CHANGED
@@ -232,7 +232,7 @@ export class Stage {
232
232
 
233
233
  const next = this.normalize(rows);
234
234
  const target = caret && Number.isFinite(caret.row)
235
- ? { row: Math.max(0, Math.min(Math.floor(caret.row), this.height - 1)), col: Math.max(0, Math.floor(caret.col) || 0), hideCursor: Boolean(caret.hideCursor) }
235
+ ? { row: Math.max(0, Math.min(Math.floor(caret.row), this.height - 1)), col: Math.max(0, Math.min(this.width() - 2, Math.floor(caret.col) || 0)), hideCursor: Boolean(caret.hideCursor) }
236
236
  : { row: this.height - 1, col: 0, hideCursor: Boolean(caret?.hideCursor) };
237
237
 
238
238
  const changed = [];
@@ -57,6 +57,8 @@ const MIN_VIEWPORT_ROWS = 2;
57
57
  const RAIL_MIN_WIDTH = 60;
58
58
  const RAIL_WIDTH = 2;
59
59
  const RAIL_BUDGET = RAIL_WIDTH + 1;
60
+ // The interactive turn rail takes three columns at the left of each row.
61
+ const TURN_RAIL_BUDGET = 3;
60
62
 
61
63
  // Which marker wins when several frames fall in the same rail row. A proportional
62
64
  // rail on a long session compresses dozens of frames per row, and what you want
@@ -373,7 +375,9 @@ export class StageSurface {
373
375
  if (!this.transcript.isEmpty()) this.opened = true;
374
376
  const before = this.lastHeight;
375
377
  const mainWidth = sessionMainWidth(this.width);
376
- const contentWidth = this.railEnabled(mainWidth) ? Math.max(20, mainWidth - RAIL_BUDGET) : mainWidth;
378
+ const contentWidth = this.railEnabled(mainWidth)
379
+ ? Math.max(20, mainWidth - RAIL_BUDGET - (hasSessionTurns(this.transcript) ? TURN_RAIL_BUDGET : 0))
380
+ : mainWidth;
377
381
  const after = this.transcript.height(contentWidth);
378
382
  this.lastHeight = after;
379
383
  // Growth is what drives auto-scroll. Handing the delta over is also what
@@ -426,7 +430,9 @@ export class StageSurface {
426
430
  const sidebar = sidebarVisible(width);
427
431
  const mainWidth = sessionMainWidth(width);
428
432
  const rail = this.railEnabled(mainWidth);
429
- const contentWidth = rail ? Math.max(20, mainWidth - RAIL_BUDGET) : mainWidth;
433
+ const contentWidth = rail
434
+ ? Math.max(20, mainWidth - RAIL_BUDGET - (hasSessionTurns(this.transcript) ? TURN_RAIL_BUDGET : 0))
435
+ : mainWidth;
430
436
 
431
437
  let block = promptRows;
432
438
  let caretRow = caret && Number.isFinite(caret.row) ? caret.row : Math.max(0, block.length - 1);
@@ -536,7 +542,9 @@ export class StageSurface {
536
542
  const painted = sidebar ? joinSessionSidebar(mainRows, panelRows, mainWidth) : mainRows;
537
543
  return this.stage.paint(painted, {
538
544
  row: rows.length + caretRow,
539
- col: caretCol,
545
+ // The composer may never put its caret into the sidebar or the reserved
546
+ // right margin, even if layout measurements differ after a resize.
547
+ col: Math.max(0, Math.min(mainWidth - 2, Number.isFinite(caretCol) ? Math.floor(caretCol) : 0)),
540
548
  hideCursor: caret?.hideCursor
541
549
  });
542
550
  }
@@ -624,7 +632,9 @@ export class StageSurface {
624
632
  // Re-derive from the new geometry: growing the viewport lowers maxScrollTop,
625
633
  // and leaving scrollTop above it would read as "the user scrolled away".
626
634
  const mainWidth = sessionMainWidth(this.width);
627
- const contentWidth = this.railEnabled(mainWidth) ? Math.max(20, mainWidth - RAIL_BUDGET) : mainWidth;
635
+ const contentWidth = this.railEnabled(mainWidth)
636
+ ? Math.max(20, mainWidth - RAIL_BUDGET - (hasSessionTurns(this.transcript) ? TURN_RAIL_BUDGET : 0))
637
+ : mainWidth;
628
638
  this.viewport.resize({ height: Math.max(MIN_VIEWPORT_ROWS, this.stage.height - 2), width: contentWidth });
629
639
  this.lastHeight = this.transcript.height(contentWidth);
630
640
  return this.stage.reserved;
@@ -656,6 +666,9 @@ export class StageSurface {
656
666
 
657
667
  const kinds = new Array(height).fill(null);
658
668
  for (const marker of this.transcript.markers(contentWidth)) {
669
+ // Suppress repetitive step/result/reasoning noise on the overview rail.
670
+ // Checkpoints, user turns, approvals, and errors remain discoverable.
671
+ if ((RAIL_PRIORITY[marker.kind] || 0) < 50) continue;
659
672
  const slot = slotOf(marker.row);
660
673
  const held = kinds[slot];
661
674
  if (!held || (RAIL_PRIORITY[marker.kind] || 0) > (RAIL_PRIORITY[held] || 0)) {
@@ -722,7 +735,10 @@ export class StageSurface {
722
735
  row = ` ${leftCell} ${row}`;
723
736
  }
724
737
  }
725
- rows[i] = `${padEnd(truncate(row, contentWidth, ''), contentWidth)} ${rightCell}`;
738
+ // Turn markers consume their own three-column lane. Preserve ALL
739
+ // previously rendered command text instead of clipping its last cells.
740
+ const rowWidth = contentWidth + (hasTurns ? TURN_RAIL_BUDGET : 0);
741
+ rows[i] = `${padEnd(truncate(row, rowWidth, ''), rowWidth)} ${rightCell}`;
726
742
  }
727
743
  return rows;
728
744
  }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Presentation-only compaction of completed, silent tool steps.
3
+ *
4
+ * Never drop errors, unknown diagnostics, structured results, or output. The
5
+ * AgentLoop's execution contract and underlying result object are unchanged.
6
+ * This TypeScript file is the single source of truth; `toolActivityPolicy.js`
7
+ * is the existing runtime compiler's emitted output.
8
+ */
9
+ export const TOOL_ACTIVITY_COMPACT_AFTER = 8;
10
+ const METADATA_ONLY = new Set([
11
+ 'success', 'exitCode', 'exit_code', 'durationMs', 'elapsedMs',
12
+ 'duration', 'statusCode', 'status_code'
13
+ ]);
14
+ /** Returns true only for a known silent success that can share its step row. */
15
+ export function compactSuccessfulToolResult(stepCount, result, tail, toolName) {
16
+ if (!Number.isFinite(stepCount) || stepCount < TOOL_ACTIVITY_COMPACT_AFTER)
17
+ return false;
18
+ if (result === null || typeof result !== 'object' || Array.isArray(result))
19
+ return false;
20
+ const record = result;
21
+ if (record.success !== true)
22
+ return false;
23
+ if (!tail || tail.kind !== 'step' || !tail.meta)
24
+ return false;
25
+ if (tail.meta.step !== stepCount || String(tail.meta.tool ?? '') !== String(toolName ?? ''))
26
+ return false;
27
+ for (const [key, value] of Object.entries(record)) {
28
+ if (METADATA_ONLY.has(key))
29
+ continue;
30
+ if (value == null || value === '' || (Array.isArray(value) && value.length === 0))
31
+ continue;
32
+ return false;
33
+ }
34
+ return true;
35
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Presentation-only compaction of completed, silent tool steps.
3
+ *
4
+ * Never drop errors, unknown diagnostics, structured results, or output. The
5
+ * AgentLoop's execution contract and underlying result object are unchanged.
6
+ * This TypeScript file is the single source of truth; `toolActivityPolicy.js`
7
+ * is the existing runtime compiler's emitted output.
8
+ */
9
+
10
+ export const TOOL_ACTIVITY_COMPACT_AFTER = 8;
11
+
12
+ export interface ToolActivityFrame {
13
+ readonly kind?: string;
14
+ readonly meta?: Readonly<Record<string, unknown>> | null;
15
+ }
16
+
17
+ const METADATA_ONLY = new Set([
18
+ 'success', 'exitCode', 'exit_code', 'durationMs', 'elapsedMs',
19
+ 'duration', 'statusCode', 'status_code'
20
+ ]);
21
+
22
+ /** Returns true only for a known silent success that can share its step row. */
23
+ export function compactSuccessfulToolResult(
24
+ stepCount: number,
25
+ result: unknown,
26
+ tail: ToolActivityFrame | null | undefined,
27
+ toolName: unknown
28
+ ): boolean {
29
+ if (!Number.isFinite(stepCount) || stepCount < TOOL_ACTIVITY_COMPACT_AFTER) return false;
30
+ if (result === null || typeof result !== 'object' || Array.isArray(result)) return false;
31
+ const record = result as Readonly<Record<string, unknown>>;
32
+ if (record.success !== true) return false;
33
+ if (!tail || tail.kind !== 'step' || !tail.meta) return false;
34
+ if (tail.meta.step !== stepCount || String(tail.meta.tool ?? '') !== String(toolName ?? '')) return false;
35
+
36
+ for (const [key, value] of Object.entries(record)) {
37
+ if (METADATA_ONLY.has(key)) continue;
38
+ if (value == null || value === '' || (Array.isArray(value) && value.length === 0)) continue;
39
+ return false;
40
+ }
41
+ return true;
42
+ }
@@ -168,6 +168,12 @@ export function buildTurnRailCells(turns, height, activeTurnIndex, hoveredTurnIn
168
168
  return { cells, layout: { dotRows, rowToTurn } };
169
169
  }
170
170
  const count = turns.length;
171
+ // Dense imported histories may contain hundreds of turns. Show a measured
172
+ // set of quiet milestones, while always retaining active/hovered endpoints.
173
+ // All turn objects are preserved for keyboard navigation and preview.
174
+ const quietStep = count > Math.max(16, Math.floor(height / 2))
175
+ ? Math.max(2, Math.ceil(count / Math.max(12, Math.floor(height / 3))))
176
+ : 1;
171
177
  // If count fits comfortably, stack consecutive dots centered or upper-aligned
172
178
  const startRow = count <= height
173
179
  ? Math.max(0, Math.floor((height - count) / 3))
@@ -186,9 +192,11 @@ export function buildTurnRailCells(turns, height, activeTurnIndex, hoveredTurnIn
186
192
  }
187
193
  rowIdx = Math.max(0, Math.min(height - 1, rowIdx));
188
194
  dotRows.set(turnNum, rowIdx);
189
- rowToTurn.set(rowIdx, turnNum);
190
195
  const isHovered = hoveredTurnIndex === turnNum;
191
196
  const isActive = activeTurnIndex === turnNum;
197
+ const showQuiet = quietStep === 1 || i === 0 || i === count - 1 || i % quietStep === 0;
198
+ if (isHovered || isActive || showQuiet)
199
+ rowToTurn.set(rowIdx, turnNum);
192
200
  if (isHovered) {
193
201
  // Hovered dot: bright silver highlighted circle
194
202
  cells[rowIdx] = '\x1b[1m\x1b[38;2;230;235;245m●\x1b[0m';
@@ -197,8 +205,8 @@ export function buildTurnRailCells(turns, height, activeTurnIndex, hoveredTurnIn
197
205
  // Active / current turn: bright white circle
198
206
  cells[rowIdx] = '\x1b[1m\x1b[38;2;250;250;250m●\x1b[0m';
199
207
  }
200
- else if (!cells[rowIdx]?.includes('●')) {
201
- // Muted inactive turns: subtle gray dot
208
+ else if (showQuiet && !cells[rowIdx]?.includes('●')) {
209
+ // Muted inactive turns: sparse gray dot in long sessions
202
210
  cells[rowIdx] = '\x1b[38;2;115;115;120m•\x1b[0m';
203
211
  }
204
212
  }
@@ -214,6 +214,12 @@ export function buildTurnRailCells(
214
214
  }
215
215
 
216
216
  const count = turns.length;
217
+ // Dense imported histories may contain hundreds of turns. Show a measured
218
+ // set of quiet milestones, while always retaining active/hovered endpoints.
219
+ // All turn objects are preserved for keyboard navigation and preview.
220
+ const quietStep = count > Math.max(16, Math.floor(height / 2))
221
+ ? Math.max(2, Math.ceil(count / Math.max(12, Math.floor(height / 3))))
222
+ : 1;
217
223
  // If count fits comfortably, stack consecutive dots centered or upper-aligned
218
224
  const startRow = count <= height
219
225
  ? Math.max(0, Math.floor((height - count) / 3))
@@ -233,10 +239,11 @@ export function buildTurnRailCells(
233
239
  rowIdx = Math.max(0, Math.min(height - 1, rowIdx));
234
240
 
235
241
  dotRows.set(turnNum, rowIdx);
236
- rowToTurn.set(rowIdx, turnNum);
237
242
 
238
243
  const isHovered = hoveredTurnIndex === turnNum;
239
244
  const isActive = activeTurnIndex === turnNum;
245
+ const showQuiet = quietStep === 1 || i === 0 || i === count - 1 || i % quietStep === 0;
246
+ if (isHovered || isActive || showQuiet) rowToTurn.set(rowIdx, turnNum);
240
247
 
241
248
  if (isHovered) {
242
249
  // Hovered dot: bright silver highlighted circle
@@ -244,8 +251,8 @@ export function buildTurnRailCells(
244
251
  } else if (isActive && !cells[rowIdx]?.includes('230;235;245m')) {
245
252
  // Active / current turn: bright white circle
246
253
  cells[rowIdx] = '\x1b[1m\x1b[38;2;250;250;250m●\x1b[0m';
247
- } else if (!cells[rowIdx]?.includes('●')) {
248
- // Muted inactive turns: subtle gray dot
254
+ } else if (showQuiet && !cells[rowIdx]?.includes('●')) {
255
+ // Muted inactive turns: sparse gray dot in long sessions
249
256
  cells[rowIdx] = '\x1b[38;2;115;115;120m•\x1b[0m';
250
257
  }
251
258
  }
@@ -82,6 +82,7 @@ export class ScrollAcceleration {
82
82
  // How close to the bottom counts as "back at the bottom" for the purposes of
83
83
  // resuming follow.
84
84
  const REENGAGE_TOLERANCE = 1;
85
+ import { captureReadingAnchor, restoreReadingAnchor } from './viewportAnchor.js';
85
86
  export class Viewport {
86
87
  transcript;
87
88
  viewHeight;
@@ -115,10 +116,25 @@ export class Viewport {
115
116
  * Geometry changed — a resize, or the input box growing under the viewport.
116
117
  */
117
118
  resize({ height, width } = {}) {
118
- if (height !== undefined && Number.isFinite(height) && height > 0)
119
- this.viewHeight = Math.floor(height);
120
- if (width !== undefined && Number.isFinite(width) && width > 0)
121
- this.viewWidth = Math.floor(width);
119
+ const nextHeight = height !== undefined && Number.isFinite(height) && height > 0
120
+ ? Math.floor(height) : this.viewHeight;
121
+ const nextWidth = width !== undefined && Number.isFinite(width) && width > 0
122
+ ? Math.floor(width) : this.viewWidth;
123
+ const reflow = nextWidth !== this.viewWidth;
124
+ const anchor = reflow && this.manual && this.transcript?.markers
125
+ ? captureReadingAnchor(this.transcript.markers(this.viewWidth), this.scrollTop, this.transcript.height(this.viewWidth)) : null;
126
+ this.viewHeight = nextHeight;
127
+ this.viewWidth = nextWidth;
128
+ if (anchor && this.transcript?.markers) {
129
+ this.scrollTop = restoreReadingAnchor(anchor, this.transcript.markers(nextWidth), this.transcript.height(nextWidth), nextHeight);
130
+ const max = this.maxScrollTop();
131
+ // A deliberate scroll must not suddenly become follow-mode just because
132
+ // a paragraph gained or lost wrapped rows during resize.
133
+ this.manual = max > 0 && this.scrollTop < max;
134
+ if (!this.manual)
135
+ this.unseen = 0;
136
+ return;
137
+ }
122
138
  this.refresh();
123
139
  }
124
140
  contentHeight() {
@@ -96,7 +96,10 @@ export class ScrollAcceleration {
96
96
  // resuming follow.
97
97
  const REENGAGE_TOLERANCE = 1;
98
98
 
99
+ import { captureReadingAnchor, restoreReadingAnchor } from './viewportAnchor.js';
100
+
99
101
  export interface TranscriptMarker {
102
+ id?: number;
100
103
  row: number;
101
104
  kind: string;
102
105
  }
@@ -172,8 +175,27 @@ export class Viewport {
172
175
  * Geometry changed — a resize, or the input box growing under the viewport.
173
176
  */
174
177
  resize({ height, width }: { height?: number; width?: number } = {}): void {
175
- if (height !== undefined && Number.isFinite(height) && height > 0) this.viewHeight = Math.floor(height);
176
- if (width !== undefined && Number.isFinite(width) && width > 0) this.viewWidth = Math.floor(width);
178
+ const nextHeight = height !== undefined && Number.isFinite(height) && height > 0
179
+ ? Math.floor(height) : this.viewHeight;
180
+ const nextWidth = width !== undefined && Number.isFinite(width) && width > 0
181
+ ? Math.floor(width) : this.viewWidth;
182
+ const reflow = nextWidth !== this.viewWidth;
183
+ const anchor = reflow && this.manual && this.transcript?.markers
184
+ ? captureReadingAnchor(this.transcript.markers(this.viewWidth), this.scrollTop,
185
+ this.transcript.height(this.viewWidth)) : null;
186
+
187
+ this.viewHeight = nextHeight;
188
+ this.viewWidth = nextWidth;
189
+ if (anchor && this.transcript?.markers) {
190
+ this.scrollTop = restoreReadingAnchor(anchor, this.transcript.markers(nextWidth),
191
+ this.transcript.height(nextWidth), nextHeight);
192
+ const max = this.maxScrollTop();
193
+ // A deliberate scroll must not suddenly become follow-mode just because
194
+ // a paragraph gained or lost wrapped rows during resize.
195
+ this.manual = max > 0 && this.scrollTop < max;
196
+ if (!this.manual) this.unseen = 0;
197
+ return;
198
+ }
177
199
  this.refresh();
178
200
  }
179
201
 
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Frame-anchored viewport reflow for Causyne's Stage/Transcript architecture.
3
+ *
4
+ * Numeric scroll rows are layout coordinates. They change when a terminal is
5
+ * resized, whereas a transcript frame's ID remains stable. Preserve the frame
6
+ * identity and the approximate relative reading position within that frame.
7
+ *
8
+ * TypeScript is the authoritative source. Runtime JS is produced by the
9
+ * repository's existing `tsc -p tsconfig.runtime.json` build.
10
+ */
11
+ function finiteRow(value) {
12
+ return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
13
+ }
14
+ function safeMarkers(markers) {
15
+ if (!Array.isArray(markers))
16
+ return [];
17
+ return markers.flatMap((marker, originalIndex) => {
18
+ if (!marker || !Number.isFinite(marker.row) || marker.row < 0)
19
+ return [];
20
+ return [{ id: marker.id, row: finiteRow(marker.row), originalIndex }];
21
+ });
22
+ }
23
+ /** Capture the first currently visible frame and relative position within it. */
24
+ export function captureReadingAnchor(markers, top, totalHeight) {
25
+ const entries = safeMarkers(markers);
26
+ if (entries.length === 0)
27
+ return null;
28
+ const row = finiteRow(top);
29
+ let selected = 0;
30
+ for (let i = 0; i < entries.length; i++) {
31
+ if ((entries[i]?.row ?? Number.POSITIVE_INFINITY) > row)
32
+ break;
33
+ selected = i;
34
+ }
35
+ const entry = entries[selected];
36
+ if (!entry)
37
+ return null;
38
+ const start = entry.row;
39
+ const next = entries[selected + 1]?.row ?? finiteRow(totalHeight);
40
+ const frameLength = Math.max(1, next - start);
41
+ return Object.freeze({
42
+ id: entry.id ?? null,
43
+ index: entry.originalIndex,
44
+ offset: Math.max(0, row - start),
45
+ fraction: Math.max(0, Math.min(1, (row - start) / frameLength)),
46
+ originalTop: row
47
+ });
48
+ }
49
+ /** Restore the matching frame and a proportional content offset after reflow. */
50
+ export function restoreReadingAnchor(anchor, markers, totalHeight, viewportHeight) {
51
+ const total = finiteRow(totalHeight);
52
+ const visible = Math.max(1, finiteRow(viewportHeight));
53
+ const max = Math.max(0, total - visible);
54
+ if (!anchor || max === 0)
55
+ return 0;
56
+ const entries = safeMarkers(markers);
57
+ if (entries.length === 0)
58
+ return Math.min(max, finiteRow(anchor.originalTop));
59
+ let selected = anchor.id == null
60
+ ? -1
61
+ : entries.findIndex(marker => marker.id === anchor.id);
62
+ if (selected < 0 && anchor.id == null && entries[anchor.index]?.originalIndex === anchor.index) {
63
+ selected = anchor.index;
64
+ }
65
+ if (selected < 0) {
66
+ // When the anchored frame was evicted, recover in the surviving transcript.
67
+ selected = 0;
68
+ }
69
+ const entry = entries[selected];
70
+ if (!entry)
71
+ return Math.min(max, finiteRow(anchor.originalTop));
72
+ const start = entry.row;
73
+ const end = entries[selected + 1]?.row ?? total;
74
+ const length = Math.max(1, end - start);
75
+ const fraction = Number.isFinite(anchor.fraction)
76
+ ? Math.max(0, Math.min(1, anchor.fraction))
77
+ : 0;
78
+ const offset = Math.min(length - 1, Math.round(fraction * length));
79
+ return Math.max(0, Math.min(max, start + offset));
80
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Frame-anchored viewport reflow for Causyne's Stage/Transcript architecture.
3
+ *
4
+ * Numeric scroll rows are layout coordinates. They change when a terminal is
5
+ * resized, whereas a transcript frame's ID remains stable. Preserve the frame
6
+ * identity and the approximate relative reading position within that frame.
7
+ *
8
+ * TypeScript is the authoritative source. Runtime JS is produced by the
9
+ * repository's existing `tsc -p tsconfig.runtime.json` build.
10
+ */
11
+
12
+ export interface ReadingMarker {
13
+ readonly id?: number;
14
+ readonly row: number;
15
+ readonly kind?: string;
16
+ }
17
+
18
+ export interface ReadingAnchor {
19
+ readonly id: number | null;
20
+ readonly index: number;
21
+ readonly offset: number;
22
+ readonly fraction: number;
23
+ readonly originalTop: number;
24
+ }
25
+
26
+ interface SafeMarker {
27
+ readonly id: number | undefined;
28
+ readonly row: number;
29
+ readonly originalIndex: number;
30
+ }
31
+
32
+ function finiteRow(value: number): number {
33
+ return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
34
+ }
35
+
36
+ function safeMarkers(markers: readonly ReadingMarker[] | null | undefined): SafeMarker[] {
37
+ if (!Array.isArray(markers)) return [];
38
+ return markers.flatMap((marker, originalIndex): SafeMarker[] => {
39
+ if (!marker || !Number.isFinite(marker.row) || marker.row < 0) return [];
40
+ return [{ id: marker.id, row: finiteRow(marker.row), originalIndex }];
41
+ });
42
+ }
43
+
44
+ /** Capture the first currently visible frame and relative position within it. */
45
+ export function captureReadingAnchor(
46
+ markers: readonly ReadingMarker[] | null | undefined,
47
+ top: number,
48
+ totalHeight: number
49
+ ): ReadingAnchor | null {
50
+ const entries = safeMarkers(markers);
51
+ if (entries.length === 0) return null;
52
+ const row = finiteRow(top);
53
+ let selected = 0;
54
+ for (let i = 0; i < entries.length; i++) {
55
+ if ((entries[i]?.row ?? Number.POSITIVE_INFINITY) > row) break;
56
+ selected = i;
57
+ }
58
+ const entry = entries[selected];
59
+ if (!entry) return null;
60
+ const start = entry.row;
61
+ const next = entries[selected + 1]?.row ?? finiteRow(totalHeight);
62
+ const frameLength = Math.max(1, next - start);
63
+ return Object.freeze({
64
+ id: entry.id ?? null,
65
+ index: entry.originalIndex,
66
+ offset: Math.max(0, row - start),
67
+ fraction: Math.max(0, Math.min(1, (row - start) / frameLength)),
68
+ originalTop: row
69
+ });
70
+ }
71
+
72
+ /** Restore the matching frame and a proportional content offset after reflow. */
73
+ export function restoreReadingAnchor(
74
+ anchor: ReadingAnchor | null,
75
+ markers: readonly ReadingMarker[] | null | undefined,
76
+ totalHeight: number,
77
+ viewportHeight: number
78
+ ): number {
79
+ const total = finiteRow(totalHeight);
80
+ const visible = Math.max(1, finiteRow(viewportHeight));
81
+ const max = Math.max(0, total - visible);
82
+ if (!anchor || max === 0) return 0;
83
+ const entries = safeMarkers(markers);
84
+ if (entries.length === 0) return Math.min(max, finiteRow(anchor.originalTop));
85
+
86
+ let selected = anchor.id == null
87
+ ? -1
88
+ : entries.findIndex(marker => marker.id === anchor.id);
89
+ if (selected < 0 && anchor.id == null && entries[anchor.index]?.originalIndex === anchor.index) {
90
+ selected = anchor.index;
91
+ }
92
+ if (selected < 0) {
93
+ // When the anchored frame was evicted, recover in the surviving transcript.
94
+ selected = 0;
95
+ }
96
+ const entry = entries[selected];
97
+ if (!entry) return Math.min(max, finiteRow(anchor.originalTop));
98
+ const start = entry.row;
99
+ const end = entries[selected + 1]?.row ?? total;
100
+ const length = Math.max(1, end - start);
101
+ const fraction = Number.isFinite(anchor.fraction)
102
+ ? Math.max(0, Math.min(1, anchor.fraction))
103
+ : 0;
104
+ const offset = Math.min(length - 1, Math.round(fraction * length));
105
+ return Math.max(0, Math.min(max, start + offset));
106
+ }