@causyne/agent 1.20.83 → 1.20.85

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.83",
3
+ "version": "1.20.85",
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
 
@@ -1,6 +1,7 @@
1
1
  // Chatbox Clipboard Manager: surgical operations for copy, paste, and CRLF normalization.
2
2
  // Supports native terminal mouse selection, readline kill/yank, Alt+C/Alt+W/Alt+V, and /copy /paste commands.
3
3
  import { readClipboardSync, writeClipboardSync, emitOsc52Copy } from './clipboardSync.js';
4
+ import { stripAnsi } from './text.js';
4
5
  import { readClipboardImageSync, formatByteSize, loadLocalImageAttachment, extractPastedFilePath, isLocalImageFile } from './clipboardImage.js';
5
6
  export { loadLocalImageAttachment, extractPastedFilePath, isLocalImageFile };
6
7
  /**
@@ -10,10 +11,12 @@ export { loadLocalImageAttachment, extractPastedFilePath, isLocalImageFile };
10
11
  export function normalizeClipboardText(raw) {
11
12
  if (typeof raw !== 'string')
12
13
  return '';
13
- return raw
14
+ // Strip CSI/OSC *before* removing C0; deleting ESC first leaves `[31m`
15
+ // and mouse-control tails as user-visible text. Preserve LF and TAB.
16
+ return stripAnsi(raw)
14
17
  .replace(/\r\n/g, '\n')
15
18
  .replace(/\r/g, '\n')
16
- .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
19
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, '');
17
20
  }
18
21
  /**
19
22
  * Copy text to system clipboard and terminal emulator (via OSC 52).
@@ -48,7 +51,18 @@ export function copyChatboxInput(prompt) {
48
51
  * as well as drag-and-dropped local image file paths and empty bracketed pastes.
49
52
  */
50
53
  export function pasteIntoChatbox(prompt, fallbackText) {
54
+ const MAX_CHATBOX_BYTES = 2 * 1024 * 1024;
51
55
  const clean = normalizeClipboardText(fallbackText);
56
+ const fits = (text) => {
57
+ const existing = prompt.editor.getText();
58
+ if (Buffer.byteLength(existing, 'utf8') + Buffer.byteLength(text, 'utf8') <= MAX_CHATBOX_BYTES)
59
+ return true;
60
+ prompt.notice = 'Paste exceeds 2 MiB; input unchanged. Attach the file instead.';
61
+ prompt.scheduleDraw();
62
+ return false;
63
+ };
64
+ if (clean && !fits(clean))
65
+ return { success: false, notice: prompt.notice, text: '' };
52
66
  // 1. If fallbackText was provided (e.g. drag & drop or file paste), check if it's a local image file
53
67
  if (clean) {
54
68
  const filePath = extractPastedFilePath(clean);
@@ -96,13 +110,15 @@ export function pasteIntoChatbox(prompt, fallbackText) {
96
110
  if (typeof prompt.refreshCompletion === 'function') {
97
111
  prompt.refreshCompletion();
98
112
  }
99
- prompt.notice = 'pasted from clipboard';
113
+ prompt.notice = `pasted ${clean.split('\n').length} ${clean.includes('\n') ? 'lines' : 'line'} · ${Buffer.byteLength(clean, 'utf8').toLocaleString()} bytes`;
100
114
  prompt.scheduleDraw();
101
115
  return { success: true, notice: prompt.notice, text: clean, isImage: false };
102
116
  }
103
117
  // 4. No fallbackText provided and no clipboard image: read text from clipboard
104
118
  const clipText = normalizeClipboardText(readClipboardSync());
105
119
  if (clipText) {
120
+ if (!fits(clipText))
121
+ return { success: false, notice: prompt.notice, text: '' };
106
122
  const filePath = extractPastedFilePath(clipText);
107
123
  const localImg = loadLocalImageAttachment(filePath);
108
124
  if (localImg) {
@@ -124,7 +140,7 @@ export function pasteIntoChatbox(prompt, fallbackText) {
124
140
  if (typeof prompt.refreshCompletion === 'function') {
125
141
  prompt.refreshCompletion();
126
142
  }
127
- prompt.notice = 'pasted from clipboard';
143
+ prompt.notice = `pasted ${clipText.split('\n').length} ${clipText.includes('\n') ? 'lines' : 'line'} · ${Buffer.byteLength(clipText, 'utf8').toLocaleString()} bytes`;
128
144
  prompt.scheduleDraw();
129
145
  return { success: true, notice: prompt.notice, text: clipText, isImage: false };
130
146
  }
@@ -2,6 +2,7 @@
2
2
  // Supports native terminal mouse selection, readline kill/yank, Alt+C/Alt+W/Alt+V, and /copy /paste commands.
3
3
 
4
4
  import { readClipboardSync, writeClipboardSync, emitOsc52Copy } from './clipboardSync.js';
5
+ import { stripAnsi } from './text.js';
5
6
  import {
6
7
  readClipboardImageSync,
7
8
  formatByteSize,
@@ -59,10 +60,12 @@ export interface ChatboxCommandContext {
59
60
  */
60
61
  export function normalizeClipboardText(raw: unknown): string {
61
62
  if (typeof raw !== 'string') return '';
62
- return raw
63
+ // Strip CSI/OSC *before* removing C0; deleting ESC first leaves `[31m`
64
+ // and mouse-control tails as user-visible text. Preserve LF and TAB.
65
+ return stripAnsi(raw)
63
66
  .replace(/\r\n/g, '\n')
64
67
  .replace(/\r/g, '\n')
65
- .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
68
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, '');
66
69
  }
67
70
 
68
71
  /**
@@ -102,7 +105,16 @@ export function pasteIntoChatbox(
102
105
  prompt: ChatboxPrompt,
103
106
  fallbackText?: string
104
107
  ): { success: boolean; notice: string; text: string; isImage?: boolean } {
108
+ const MAX_CHATBOX_BYTES = 2 * 1024 * 1024;
105
109
  const clean = normalizeClipboardText(fallbackText);
110
+ const fits = (text: string): boolean => {
111
+ const existing = prompt.editor.getText();
112
+ if (Buffer.byteLength(existing, 'utf8') + Buffer.byteLength(text, 'utf8') <= MAX_CHATBOX_BYTES) return true;
113
+ prompt.notice = 'Paste exceeds 2 MiB; input unchanged. Attach the file instead.';
114
+ prompt.scheduleDraw();
115
+ return false;
116
+ };
117
+ if (clean && !fits(clean)) return { success: false, notice: prompt.notice, text: '' };
106
118
 
107
119
  // 1. If fallbackText was provided (e.g. drag & drop or file paste), check if it's a local image file
108
120
  if (clean) {
@@ -153,7 +165,7 @@ export function pasteIntoChatbox(
153
165
  if (typeof prompt.refreshCompletion === 'function') {
154
166
  prompt.refreshCompletion();
155
167
  }
156
- prompt.notice = 'pasted from clipboard';
168
+ prompt.notice = `pasted ${clean.split('\n').length} ${clean.includes('\n') ? 'lines' : 'line'} · ${Buffer.byteLength(clean, 'utf8').toLocaleString()} bytes`;
157
169
  prompt.scheduleDraw();
158
170
  return { success: true, notice: prompt.notice, text: clean, isImage: false };
159
171
  }
@@ -161,6 +173,7 @@ export function pasteIntoChatbox(
161
173
  // 4. No fallbackText provided and no clipboard image: read text from clipboard
162
174
  const clipText = normalizeClipboardText(readClipboardSync());
163
175
  if (clipText) {
176
+ if (!fits(clipText)) return { success: false, notice: prompt.notice, text: '' };
164
177
  const filePath = extractPastedFilePath(clipText);
165
178
  const localImg = loadLocalImageAttachment(filePath);
166
179
  if (localImg) {
@@ -183,7 +196,7 @@ export function pasteIntoChatbox(
183
196
  if (typeof prompt.refreshCompletion === 'function') {
184
197
  prompt.refreshCompletion();
185
198
  }
186
- prompt.notice = 'pasted from clipboard';
199
+ prompt.notice = `pasted ${clipText.split('\n').length} ${clipText.includes('\n') ? 'lines' : 'line'} · ${Buffer.byteLength(clipText, 'utf8').toLocaleString()} bytes`;
187
200
  prompt.scheduleDraw();
188
201
  return { success: true, notice: prompt.notice, text: clipText, isImage: false };
189
202
  }
package/src/tui/keys.js CHANGED
@@ -82,6 +82,9 @@ export class KeyDecoder {
82
82
  this.pending = Buffer.alloc(0);
83
83
  this.inPaste = false;
84
84
  this.pasteBuffer = '';
85
+ this.pasteChunks = [];
86
+ this.pasteByteLength = 0;
87
+ this.pasteOverflow = false;
85
88
  }
86
89
 
87
90
  /** Feed a chunk; get back every complete key event it contained. */
@@ -103,6 +106,17 @@ export class KeyDecoder {
103
106
  return events;
104
107
  }
105
108
 
109
+ /** Clear an abandoned control sequence rather than swallowing later typing. */
110
+ drainIncomplete() {
111
+ if (this.inPaste || this.pending.length === 0) return [];
112
+ const tail = this.pending.toString('utf8');
113
+ this.pending = Buffer.alloc(0);
114
+ if (tail === '[<') return [makeKey('char', { text: '[', sequence: '[' }),
115
+ makeKey('char', { text: '<', sequence: '<' })];
116
+ if (tail === '[') return [makeKey('char', { text: '[', sequence: '[' })];
117
+ return [makeKey('unknown', { sequence: '' })];
118
+ }
119
+
106
120
  /** Decode one event at `offset`. Returns bytes consumed, or 0 if incomplete. */
107
121
  step(buffer, offset, events) {
108
122
  // Inside a paste, everything is literal text until the closing marker. The
@@ -113,22 +127,19 @@ export class KeyDecoder {
113
127
 
114
128
  if (byte === 0x1b) return this.stepEscape(buffer, offset, events);
115
129
 
116
- // Orphaned SGR mouse sequence: [ < b ; x ; y M|m
117
- // Occurs when \x1b is consumed on a chunk boundary or dropped over PTY.
118
- // Intercepting here prevents raw sequence strings like `[<64;119;43M` from
119
- // leaking into the prompt input box as literal character keystrokes.
120
- if (byte === 0x5b && buffer.length - offset >= 3 && buffer[offset + 1] === 0x3c) {
130
+ // Orphaned SGR report: `ESC` may be lost before `[<b;x;yM`.
131
+ // Only buffer strings that are valid partial reports. Ordinary code such
132
+ // as `[<div>` must remain typable and must not hang the editor.
133
+ if (byte === 0x5b && buffer[offset + 1] === 0x3c) {
121
134
  const text = buffer.toString('utf8', offset);
122
- if (!/[Mm]/.test(text)) return 0; // Incomplete sequence; wait for subsequent bytes in this.pending
123
- const match = /^\[<(\d+);(\d+);(\d+)([Mm])/.exec(text);
135
+ const match = /^\[<(\d{1,6});(\d{1,6});(\d{1,6})([Mm])/.exec(text);
124
136
  if (match) {
125
- const code = parseInt(match[1], 10);
126
- const col = parseInt(match[2], 10);
127
- const row = parseInt(match[3], 10);
128
- const pressed = match[4] === 'M';
129
- this.emitMouse([code, col, row], pressed, match[0], events);
137
+ this.emitMouse([Number(match[1]), Number(match[2]), Number(match[3])],
138
+ match[4] === 'M', match[0], events);
130
139
  return match[0].length;
131
140
  }
141
+ // Don't wait forever on malformed or nonmouse `[` + `<` input.
142
+ if (text.length <= 64 && /^\[<(?:\d{0,6}(?:;\d{0,6}){0,2})$/.test(text)) return 0;
132
143
  }
133
144
 
134
145
  if (byte === 0x0d || byte === 0x0a) {
@@ -162,28 +173,45 @@ export class KeyDecoder {
162
173
  }
163
174
 
164
175
  stepPaste(buffer, offset, events) {
165
- const text = buffer.toString('utf8', offset);
166
- const end = text.indexOf(PASTE_END);
167
-
168
- if (end === -1) {
169
- // No terminator yet. Keep whole UTF-8 characters, hold back a split tail.
170
- let safe = buffer.length;
171
- while (safe > offset && utf8Length(buffer, safe - 1) === 0) safe--;
172
- // A partial terminator at the tail must not be swallowed as content.
173
- const chunk = buffer.toString('utf8', offset, safe);
174
- const keep = partialSuffixLength(chunk, PASTE_END);
175
- const usable = chunk.slice(0, chunk.length - keep);
176
- if (!usable) return 0;
177
- this.pasteBuffer += usable;
178
- return Buffer.byteLength(usable, 'utf8');
176
+ // Bracketed paste can split in the middle of a UTF-8 code point OR CSI
177
+ // terminator. Accumulate *bytes*, then decode once. Decoding each chunk
178
+ // independently corrupts emoji and CJK, and can change user code silently.
179
+ const marker = Buffer.from(PASTE_END, 'ascii');
180
+ const end = buffer.indexOf(marker, offset);
181
+ const maxBytes = 2 * 1024 * 1024;
182
+ const append = (chunk) => {
183
+ this.pasteByteLength += chunk.length;
184
+ if (this.pasteByteLength > maxBytes) { this.pasteOverflow = true; return; }
185
+ if (!this.pasteOverflow && chunk.length) this.pasteChunks.push(Buffer.from(chunk));
186
+ };
187
+
188
+ if (end >= 0) {
189
+ append(buffer.subarray(offset, end));
190
+ const pasted = this.pasteOverflow ? '' : Buffer.concat(this.pasteChunks).toString('utf8');
191
+ const oversized = this.pasteOverflow;
192
+ this.inPaste = false;
193
+ this.pasteBuffer = '';
194
+ this.pasteChunks = [];
195
+ this.pasteByteLength = 0;
196
+ this.pasteOverflow = false;
197
+ if (oversized) events.push(makeKey('paste-too-large', { sequence: '' }));
198
+ else events.push(makeKey('paste', { text: pasted, sequence: pasted }));
199
+ return end - offset + marker.length;
179
200
  }
180
201
 
181
- this.pasteBuffer += text.slice(0, end);
182
- this.inPaste = false;
183
- const pasted = this.pasteBuffer;
184
- this.pasteBuffer = '';
185
- events.push(makeKey('paste', { text: pasted, sequence: pasted }));
186
- return Buffer.byteLength(text.slice(0, end), 'utf8') + PASTE_END.length;
202
+ // Keep only a suffix that might start the paste terminator. All other
203
+ // bytes can be committed immediately without corrupting Unicode.
204
+ let retain = 0;
205
+ for (let count = Math.min(marker.length - 1, buffer.length - offset); count > 0; count--) {
206
+ if (buffer.subarray(buffer.length - count).equals(marker.subarray(0, count))) {
207
+ retain = count;
208
+ break;
209
+ }
210
+ }
211
+ const safeEnd = buffer.length - retain;
212
+ if (safeEnd === offset) return 0;
213
+ append(buffer.subarray(offset, safeEnd));
214
+ return safeEnd - offset;
187
215
  }
188
216
 
189
217
  stepEscape(buffer, offset, events) {
@@ -262,13 +290,23 @@ export class KeyDecoder {
262
290
  if (text.startsWith(PASTE_START)) {
263
291
  this.inPaste = true;
264
292
  this.pasteBuffer = '';
293
+ this.pasteChunks = [];
294
+ this.pasteByteLength = 0;
295
+ this.pasteOverflow = false;
265
296
  return PASTE_START.length;
266
297
  }
267
298
 
268
299
  // A CSI sequence is ESC [ , parameters, then one final byte in @..~.
269
300
  let index = 2;
270
301
  while (index < text.length && !/[@-~]/.test(text[index])) index++;
271
- if (index >= text.length) return 0; // still arriving
302
+ if (index >= text.length) {
303
+ // A malformed CSI stream must not buffer an unbounded quantity of user input.
304
+ if (buffer.length - offset > 128) {
305
+ events.push(makeKey('unknown', { sequence: '' }));
306
+ return buffer.length - offset;
307
+ }
308
+ return 0; // still arriving
309
+ }
272
310
 
273
311
  const final = text[index];
274
312
  const params = text.slice(2, index);
package/src/tui/prompt.js CHANGED
@@ -18,6 +18,7 @@
18
18
  // Pure Node. No dependency, no shell.
19
19
 
20
20
  import { KeyDecoder, bracketedPaste } from './keys.js';
21
+ import { TerminalInputFramer, INPUT_PREFIX_TIMEOUT_MS, shouldTreatAsAtomicPaste } from './terminalInputFramer.js';
21
22
  import { LineEditor } from './lineEditor.js';
22
23
  import { PromptHistory } from './history.js';
23
24
  import { FileIndex, suggest, applyCompletion, detectTrigger, renderPicker, MAX_VISIBLE } from './completion.js';
@@ -120,6 +121,9 @@ export class ChatPrompt {
120
121
  this.history = options.history || new PromptHistory();
121
122
  this.index = new FileIndex(this.root);
122
123
  this.decoder = new KeyDecoder();
124
+ this.inputFramer = new TerminalInputFramer();
125
+ this.inputFrameTimer = null;
126
+ this.decoderRecoveryTimer = null;
123
127
 
124
128
  this.busy = false;
125
129
  this.active = false;
@@ -181,6 +185,7 @@ export class ChatPrompt {
181
185
  start() {
182
186
  if (this.active) return;
183
187
  this.active = true;
188
+ this.inputFramer.clear();
184
189
  this.input.setRawMode(true);
185
190
  this.input.resume();
186
191
  this.input.on('data', this.handleData);
@@ -195,6 +200,10 @@ export class ChatPrompt {
195
200
  if (!this.active) return;
196
201
  this.active = false;
197
202
  this.stopTick();
203
+ if (this.inputFrameTimer) { clearTimeout(this.inputFrameTimer); this.inputFrameTimer = null; }
204
+ if (this.decoderRecoveryTimer) { clearTimeout(this.decoderRecoveryTimer); this.decoderRecoveryTimer = null; }
205
+ this.inputFramer.clear();
206
+ this.decoder.pending = Buffer.alloc(0);
198
207
  if (this.resizeTimer) { clearTimeout(this.resizeTimer); this.resizeTimer = null; }
199
208
  this.erase();
200
209
  // The exit contract (UX-01 rev 2 clause d): the band collapses and the whole
@@ -254,30 +263,52 @@ export class ChatPrompt {
254
263
  };
255
264
 
256
265
  handleData = (chunk) => {
266
+ // KeyDecoder expects complete escape prefixes. A PTY may split ESC from
267
+ // `[<button;x;yM`; framing these bytes first prevents mouse coordinates
268
+ // from becoming chat content. Do not decode bulk paste before this step.
269
+ const frames = this.inputFramer.push(chunk);
270
+ for (const frame of frames) this.handleFramedData(frame);
271
+ if (this.inputFrameTimer) { clearTimeout(this.inputFrameTimer); this.inputFrameTimer = null; }
272
+ if (this.inputFramer.hasPending) {
273
+ this.inputFrameTimer = setTimeout(() => {
274
+ this.inputFrameTimer = null;
275
+ for (const frame of this.inputFramer.flush()) this.handleFramedData(frame);
276
+ }, INPUT_PREFIX_TIMEOUT_MS);
277
+ this.inputFrameTimer.unref?.();
278
+ }
279
+ };
280
+
281
+ handleFramedData = (chunk) => {
257
282
  let motionOnly = true;
258
283
  const str = typeof chunk === 'string' ? chunk : Buffer.isBuffer(chunk) ? chunk.toString('utf8') : '';
259
- // Unbracketed multi-line or bulk paste safeguard: when a multi-line or bulk block arrives
260
- // without bracketed paste (e.g. VS Code terminal, native clipboard paste, terminal ANSI logs,
261
- // or piped stream), handle it atomically as a paste event rather than executing multiple
262
- // spurious Enter submissions or freezing in per-character completion loops.
263
- const isBracketedPasteStart = str.startsWith('\x1b[200~');
264
- const isMouse = str.startsWith('\x1b[<') || str.startsWith('\x1b[M');
265
- const hasNewlines = str.includes('\n') || str.includes('\r');
266
- if (!this.layer && !this.decoder.inPaste && !isBracketedPasteStart && !isMouse && (
267
- (str.length > 2 && hasNewlines) ||
268
- (str.length >= 64 && !str.startsWith('\x1b'))
269
- )) {
270
- const clean = stripAnsi(str).replace(/\r\n/g, '\n').replace(/\r/g, '\n');
284
+ // Unbracketed bulk input remains atomic ONLY when no control sequence
285
+ // is still in flight. This fixes mixed mouse/typing chunks that previously
286
+ // bypassed KeyDecoder and leaked CSI tails into the composer.
287
+ if (!this.layer && shouldTreatAsAtomicPaste(chunk, this.decoder)) {
271
288
  try {
272
- this.handleKey({ name: 'paste', text: clean, sequence: clean });
273
- } catch (e) {
274
- process.stderr.write(`\n[tui] paste failed: ${e.message}\n`);
289
+ this.handleKey({ name: 'paste', text: str, sequence: '' });
290
+ } catch (error) {
291
+ this.notice = `paste failed: ${error instanceof Error ? error.message : String(error)}`;
292
+ this.scheduleDraw();
275
293
  }
276
294
  this.draw();
277
295
  return;
278
296
  }
279
297
 
280
298
  const keys = this.decoder.decode(chunk);
299
+ // A truncated CSI/X10 mouse report must not swallow the next user keystroke.
300
+ // Paste is exempt: its terminator may arrive across many chunks.
301
+ if (this.decoderRecoveryTimer) clearTimeout(this.decoderRecoveryTimer);
302
+ this.decoderRecoveryTimer = null;
303
+ if (!this.decoder.inPaste && this.decoder.pending.length > 0) {
304
+ this.decoderRecoveryTimer = setTimeout(() => {
305
+ this.decoderRecoveryTimer = null;
306
+ const recovered = this.decoder.drainIncomplete();
307
+ for (const event of recovered) this.handleKey(event);
308
+ if (recovered.length) this.scheduleDraw();
309
+ }, 180);
310
+ this.decoderRecoveryTimer.unref?.();
311
+ }
281
312
  let charBatch = '';
282
313
 
283
314
  for (let i = 0; i < keys.length; i++) {
@@ -302,7 +333,8 @@ export class ChatPrompt {
302
333
  } catch (e) {
303
334
  // A key handler must never take the session down. Say so once and
304
335
  // carry on, rather than dying silently the way the old catch(e){} did.
305
- process.stderr.write(`\n[tui] key "${key.name}" failed: ${e.message}\n`);
336
+ this.notice = `input error: ${e instanceof Error ? e.message : String(e)}`;
337
+ this.scheduleDraw();
306
338
  }
307
339
  }
308
340
 
@@ -410,8 +442,13 @@ export class ChatPrompt {
410
442
  const line = parts.join(dim(` ${GLYPHS.dot} `));
411
443
  const trailing = [status.provider, status.tier].filter(Boolean).join(' ');
412
444
  const base = trailing ? `${line} ${dim(trailing)}` : line;
445
+ const details = [];
446
+ if (this.queue.length) details.push(`${this.queue.length} queued`);
447
+ if (this.editor.lines.length > 1) details.push(`${this.editor.lines.length} lines`);
448
+ const extra = details.length ? dim(` ${GLYPHS.dot} ${details.join(' · ')}`) : '';
449
+ const withMeta = visibleWidth(base) + visibleWidth(extra) <= width ? base + extra : base;
413
450
  const hints = dim(' Ctrl+G mode · Alt+M model · Ctrl+T variant');
414
- const full = visibleWidth(base) + visibleWidth(hints) <= width ? base + hints : base;
451
+ const full = visibleWidth(withMeta) + visibleWidth(hints) <= width ? withMeta + hints : withMeta;
415
452
  return visibleWidth(full) > width ? truncate(full, width, GLYPHS.ellipsis) : full;
416
453
  }
417
454
 
@@ -757,6 +794,12 @@ export class ChatPrompt {
757
794
  submit() {
758
795
  const text = this.editor.getText();
759
796
  if (!text.trim()) return;
797
+ if (this.busy && this.queue.length >= 32
798
+ && text.trim() !== '/stop' && text.trim() !== '/interrupt') {
799
+ this.notice = '32 queued messages: wait for a turn to complete before adding another';
800
+ this.scheduleDraw();
801
+ return;
802
+ }
760
803
 
761
804
  this.erase();
762
805
  this.history.add(text);
@@ -908,6 +951,12 @@ export class ChatPrompt {
908
951
  else if (action !== 'passthrough') return;
909
952
  }
910
953
 
954
+ if (key.name === 'paste-too-large') {
955
+ this.notice = 'Paste exceeds 2 MiB; input unchanged. Attach a file or reduce the selection.';
956
+ this.scheduleDraw();
957
+ return;
958
+ }
959
+
911
960
  if (key.name === 'paste') {
912
961
  if (this.surface && typeof this.surface.captureMouse === 'function') {
913
962
  this.surface.captureMouse();
@@ -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,98 @@
1
+ // Causyne TUI — terminal input framing and atomic unbracketed paste classification.
2
+ // Keep this module free of side effects so terminal sequences can be tested
3
+ // without a PTY. It does not decode keys, move the cursor, or execute commands.
4
+
5
+ export const INPUT_PREFIX_TIMEOUT_MS = 40;
6
+
7
+ /**
8
+ * Hold a trailing ESC or '[' long enough for a following stdin chunk to complete
9
+ * a CSI/mouse report. Without this, the original KeyDecoder treats standalone
10
+ * ESC as a key immediately; its following '[<...M' chunk can be pasted as text.
11
+ *
12
+ * Ordinary characters are released immediately, with at most one trailing
13
+ * byte delayed. The delay is deliberately bounded by ChatPrompt's timer.
14
+ */
15
+ export class TerminalInputFramer {
16
+ constructor() {
17
+ this.pending = Buffer.alloc(0);
18
+ }
19
+
20
+ get hasPending() {
21
+ return this.pending.length !== 0;
22
+ }
23
+
24
+ push(input) {
25
+ const incoming = Buffer.isBuffer(input) ? input : Buffer.from(String(input), 'utf8');
26
+ if (incoming.length === 0) return [];
27
+ const bytes = this.pending.length ? Buffer.concat([this.pending, incoming]) : incoming;
28
+ this.pending = Buffer.alloc(0);
29
+ const end = bytes[bytes.length - 1];
30
+ // '[' may be a literal character or the first byte of an orphaned SGR
31
+ // mouse report. Only one byte is held, so the editor is never blocked by
32
+ // a multi-kilobyte prefix buffer outside KeyDecoder.
33
+ if (end === 0x1b || end === 0x5b) {
34
+ const heldLength = end === 0x5b && bytes.length >= 2 && bytes[bytes.length - 2] === 0x1b ? 2 : 1;
35
+ this.pending = Buffer.from(bytes.subarray(-heldLength));
36
+ return bytes.length > heldLength ? [bytes.subarray(0, -heldLength)] : [];
37
+ }
38
+ return [bytes];
39
+ }
40
+
41
+ flush() {
42
+ const value = this.pending;
43
+ this.pending = Buffer.alloc(0);
44
+ // An incomplete ESC[ is not a printable character and should never be
45
+ // handed to KeyDecoder's CSI state forever after the timeout expires.
46
+ if (value.length === 2 && value[0] === 0x1b && value[1] === 0x5b) return [];
47
+ return value.length ? [value] : [];
48
+ }
49
+
50
+ clear() {
51
+ this.pending = Buffer.alloc(0);
52
+ }
53
+ }
54
+
55
+ const MOUSE_CSI = /\x1b\[<\d{1,6};\d{1,6};\d{1,6}[Mm]/;
56
+ const ORPHAN_MOUSE = /\[<\d{1,6};\d{1,6};\d{1,6}[Mm]/;
57
+ const MOUSE_TAIL = /(?:^|[Mm])<\d{1,6};\d{1,6};\d{1,6}[Mm]/;
58
+ const BRACKETED = /\x1b\[(?:200|201)~/;
59
+ // Only SGR color/control formatting is permitted in an ANSI log pasted as
60
+ // one atomic block; actual cursor and mouse sequences must go to KeyDecoder.
61
+ const SGR = /\x1b\[[0-9;]*m/g;
62
+
63
+ /**
64
+ * Avoid bypassing an incomplete key or mouse sequence with the 'large chunk =
65
+ * paste' heuristic. Allow bulk pasted ANSI-colored logs, which an existing
66
+ * regression test expects to arrive as a single multiline editor insertion.
67
+ */
68
+ export function shouldTreatAsAtomicPaste(raw, decoder) {
69
+ let text;
70
+ if (typeof raw === 'string') text = raw;
71
+ else {
72
+ // Classifying an incomplete UTF-8 byte stream as a bulk paste would
73
+ // replace a split emoji with U+FFFD. Let KeyDecoder buffer its tail.
74
+ try { text = new TextDecoder('utf-8', { fatal: true }).decode(raw); }
75
+ catch { return false; }
76
+ }
77
+ if (!text) return false;
78
+ if (decoder?.inPaste || (decoder?.pending?.length ?? 0) > 0) return false;
79
+ if (BRACKETED.test(text) || MOUSE_CSI.test(text) || ORPHAN_MOUSE.test(text) || MOUSE_TAIL.test(text)) return false;
80
+ const hasNewline = text.includes('\n') || text.includes('\r');
81
+ const big = text.length >= 64;
82
+ if (!big && !(hasNewline && text.length > 2)) return false;
83
+ if (text.includes('\x1b') || text.includes('\u009b')) {
84
+ // Colorized terminal output can be pasted without submitting each line.
85
+ // All control sequences must be complete SGR, with no other escapes.
86
+ const withoutColor = text.replace(SGR, '');
87
+ return hasNewline && !/[\x1b\u009b]/.test(withoutColor);
88
+ }
89
+ return hasNewline || big;
90
+ }
91
+
92
+ /** Display a short, non-sensitive paste notification (not the pasted content). */
93
+ export function pasteSummary(text) {
94
+ const lines = 1 + (text.match(/\n/g)?.length ?? 0);
95
+ const size = Buffer.byteLength(text, 'utf8');
96
+ const sizeLabel = size >= 1024 ? `${Math.round(size / 1024)} KiB` : `${size} B`;
97
+ return `pasted ${lines} ${lines === 1 ? 'line' : 'lines'} · ${sizeLabel}`;
98
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Keep the full execution trail, but collapse the second, visually redundant
3
+ * success row once a long tool-heavy run is underway. A failure, a non-empty
4
+ * output, a diagnostic, or any missing result stays expanded.
5
+ *
6
+ * Only the presentation changes. Original tool results still pass through
7
+ * captureLastOutput() and the AgentLoop is not affected.
8
+ */
9
+ export const TOOL_ACTIVITY_COMPACT_AFTER = 8;
10
+
11
+ export function compactSuccessfulToolResult(stepCount, result, tail, toolName) {
12
+ if (!Number.isFinite(stepCount) || stepCount < TOOL_ACTIVITY_COMPACT_AFTER) return false;
13
+ if (!result || result.success !== true) return false;
14
+ if (!tail || tail.kind !== 'step' || !tail.meta) return false;
15
+ if (tail.meta.step !== stepCount || String(tail.meta.tool ?? '') !== String(toolName ?? '')) return false;
16
+ // Only truly silent successes qualify. Unknown provider-specific result
17
+ // fields must remain visible, rather than being hidden by an allowlist of
18
+ // familiar output property names.
19
+ const metadataOnly = new Set([
20
+ 'success', 'exitCode', 'exit_code', 'durationMs', 'elapsedMs', 'duration',
21
+ 'statusCode', 'status_code'
22
+ ]);
23
+ for (const [key, value] of Object.entries(result)) {
24
+ if (metadataOnly.has(key)) continue;
25
+ if (value == null || value === '' || (Array.isArray(value) && value.length === 0)) continue;
26
+ return false;
27
+ }
28
+ return true;
29
+ }
@@ -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,19 @@
1
+ export interface ReadingMarker { id?: number; row: number; kind?: string }
2
+ export interface ReadingAnchor {
3
+ readonly id: number | null;
4
+ readonly index: number;
5
+ readonly offset: number;
6
+ readonly fraction: number;
7
+ readonly originalTop: number;
8
+ }
9
+ export declare function captureReadingAnchor(
10
+ markers: ReadingMarker[] | null | undefined,
11
+ top: number,
12
+ totalHeight: number
13
+ ): ReadingAnchor | null;
14
+ export declare function restoreReadingAnchor(
15
+ anchor: ReadingAnchor | null,
16
+ markers: ReadingMarker[] | null | undefined,
17
+ totalHeight: number,
18
+ viewportHeight: number
19
+ ): number;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Preserve the reader's location while terminal geometry changes.
3
+ *
4
+ * Row indices are screen-layout positions, not document positions. Re-wrapping a
5
+ * transcript changes frame heights, so keeping the same numeric scrollTop can
6
+ * jump to unrelated content. Frame identity + relative offset is stable across
7
+ * width changes, without storing or duplicating any message content.
8
+ *
9
+ * This module is deliberately independent of Stage, Transcript, and Node I/O.
10
+ */
11
+
12
+ function finiteRow(value) {
13
+ return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
14
+ }
15
+
16
+ function safeMarkers(markers) {
17
+ if (!Array.isArray(markers)) return [];
18
+ return markers
19
+ .filter(marker => marker && Number.isFinite(marker.row) && marker.row >= 0)
20
+ .map((marker, index) => ({
21
+ id: marker.id,
22
+ row: finiteRow(marker.row),
23
+ originalIndex: index
24
+ }));
25
+ }
26
+
27
+ /** Capture an anchor at the first visible row, measured within its frame. */
28
+ export function captureReadingAnchor(markers, top, totalHeight) {
29
+ const entries = safeMarkers(markers);
30
+ if (!entries.length) return null;
31
+ const row = finiteRow(top);
32
+ let selected = 0;
33
+ for (let i = 0; i < entries.length; i++) {
34
+ if (entries[i].row > row) break;
35
+ selected = i;
36
+ }
37
+ const start = entries[selected].row;
38
+ const next = entries[selected + 1]?.row ?? finiteRow(totalHeight);
39
+ const frameLength = Math.max(1, next - start);
40
+ return Object.freeze({
41
+ id: entries[selected].id ?? null,
42
+ index: entries[selected].originalIndex,
43
+ offset: Math.max(0, row - start),
44
+ fraction: Math.max(0, Math.min(1, (row - start) / frameLength)),
45
+ originalTop: row
46
+ });
47
+ }
48
+
49
+ /** Restore to the corresponding frame and approximately the same content line. */
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) return 0;
55
+ const entries = safeMarkers(markers);
56
+ if (!entries.length) return Math.min(max, finiteRow(anchor.originalTop));
57
+
58
+ let selected = anchor.id == null
59
+ ? -1
60
+ : entries.findIndex(marker => marker.id === anchor.id);
61
+ if (selected < 0 && anchor.id == null && entries[anchor.index]?.originalIndex === anchor.index) {
62
+ selected = anchor.index;
63
+ }
64
+ if (selected < 0) {
65
+ // Frames may have been evicted while the user was reading. Use the first
66
+ // surviving frame rather than silently jumping to an unrelated old row.
67
+ selected = 0;
68
+ }
69
+ const start = entries[selected].row;
70
+ const end = entries[selected + 1]?.row ?? total;
71
+ const length = Math.max(1, end - start);
72
+ const fraction = Number.isFinite(anchor.fraction) ? Math.max(0, Math.min(1, anchor.fraction)) : 0;
73
+ // Relative position is more useful than raw offset after a long paragraph
74
+ // wraps from 15 lines to 30, while staying inside the same frame.
75
+ const offset = Math.min(length - 1, Math.round(fraction * length));
76
+ return Math.max(0, Math.min(max, start + offset));
77
+ }