@causyne/agent 1.20.112 → 1.20.116

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 (151) hide show
  1. package/docs/ARCHITECTURE.md +29 -0
  2. package/package.json +1 -1
  3. package/src/agentLoop.js +72 -37
  4. package/src/agentLoop.ts +70 -38
  5. package/src/browser/browserRuntime.js +13 -8
  6. package/src/browser/browserRuntime.ts +16 -8
  7. package/src/browser/causyneBrowser.js +7 -2
  8. package/src/browser/causyneBrowser.ts +8 -2
  9. package/src/browser/searchProviders.js +18 -7
  10. package/src/browser/searchProviders.ts +17 -5
  11. package/src/browser/snapshotWindow.js +1 -1
  12. package/src/browser/snapshotWindow.ts +1 -1
  13. package/src/browser/urlPolicy.js +21 -10
  14. package/src/browser/urlPolicy.ts +19 -10
  15. package/src/browser/workspacePreview.js +13 -1
  16. package/src/browser/workspacePreview.ts +11 -1
  17. package/src/computerUse/visionGrounding.js +31 -27
  18. package/src/computerUse/visionGrounding.ts +27 -27
  19. package/src/continuum/ui/continuumPicker.js +14 -6
  20. package/src/continuum/ui/continuumPicker.ts +13 -6
  21. package/src/continuum/ui/continuumPickerView.js +24 -15
  22. package/src/continuum/ui/continuumPickerView.ts +24 -16
  23. package/src/observer/advisory.js +32 -22
  24. package/src/observer/advisory.ts +30 -18
  25. package/src/observer/coldObserver.js +21 -33
  26. package/src/observer/coldObserver.ts +20 -33
  27. package/src/observer/evidence.js +20 -13
  28. package/src/observer/evidence.ts +21 -13
  29. package/src/observer.js +47 -12
  30. package/src/observer.ts +50 -18
  31. package/src/pluginsFactory/discovery.js +28 -16
  32. package/src/pluginsFactory/discovery.ts +29 -16
  33. package/src/pluginsFactory/pluginsFactory.js +213 -38
  34. package/src/pluginsFactory/pluginsFactory.ts +218 -39
  35. package/src/pluginsFactory/strategy.js +26 -16
  36. package/src/pluginsFactory/strategy.ts +34 -19
  37. package/src/pluginsFactory/templates.js +183 -62
  38. package/src/pluginsFactory/templates.ts +174 -54
  39. package/src/timeMachine.js +43 -22
  40. package/src/timeMachine.ts +44 -22
  41. package/src/tool-scripts/desktop_act.applescript +1 -0
  42. package/src/tools/computerUse.js +23 -10
  43. package/src/tools/computerUse.ts +19 -8
  44. package/src/tools/desktopAct.js +12 -1
  45. package/src/tools/pluginsFactory.js +108 -5
  46. package/src/tools/pluginsFactory.ts +115 -5
  47. package/src/tui/CausyneRotor.js +24 -10
  48. package/src/tui/CausyneRotor.ts +25 -10
  49. package/src/tui/activityLayout.js +9 -5
  50. package/src/tui/activityLayout.ts +9 -5
  51. package/src/tui/ask.js +34 -14
  52. package/src/tui/banner.js +55 -18
  53. package/src/tui/banner.ts +52 -17
  54. package/src/tui/block.js +47 -20
  55. package/src/tui/block.ts +54 -27
  56. package/src/tui/chatRenderer.js +135 -83
  57. package/src/tui/chatboxClipboard.js +12 -5
  58. package/src/tui/chatboxClipboard.ts +10 -4
  59. package/src/tui/clipboardImage.js +52 -42
  60. package/src/tui/clipboardImage.ts +50 -39
  61. package/src/tui/clipboardSync.js +12 -1
  62. package/src/tui/clipboardSync.ts +9 -1
  63. package/src/tui/codeProgress.js +57 -26
  64. package/src/tui/codeProgress.ts +57 -25
  65. package/src/tui/codeStreamRenderer.js +59 -14
  66. package/src/tui/codeStreamRenderer.ts +58 -14
  67. package/src/tui/commandPresentation.js +9 -2
  68. package/src/tui/commandPresentation.ts +9 -2
  69. package/src/tui/completion.js +45 -23
  70. package/src/tui/composerControls.js +21 -10
  71. package/src/tui/composerControls.ts +18 -10
  72. package/src/tui/composerGeometry.js +6 -4
  73. package/src/tui/composerGeometry.ts +6 -4
  74. package/src/tui/consoleGuard.js +29 -7
  75. package/src/tui/consoleGuard.ts +28 -7
  76. package/src/tui/dialogs.js +134 -71
  77. package/src/tui/diff.js +8 -4
  78. package/src/tui/history.js +6 -5
  79. package/src/tui/home.js +25 -13
  80. package/src/tui/homeView.js +37 -18
  81. package/src/tui/homeView.ts +38 -18
  82. package/src/tui/inlineSlash.js +6 -5
  83. package/src/tui/inlineSlash.ts +6 -5
  84. package/src/tui/keys.js +33 -17
  85. package/src/tui/layout.js +27 -9
  86. package/src/tui/layout.ts +26 -9
  87. package/src/tui/lineEditor.js +49 -23
  88. package/src/tui/markdownMath.js +64 -14
  89. package/src/tui/markdownMath.ts +69 -13
  90. package/src/tui/messageActionPlacement.js +28 -13
  91. package/src/tui/messageActionPlacement.ts +28 -13
  92. package/src/tui/messageInteraction.js +111 -46
  93. package/src/tui/messageInteraction.ts +115 -47
  94. package/src/tui/modelPicker.js +44 -15
  95. package/src/tui/modelPicker.ts +48 -15
  96. package/src/tui/observerPicker.js +56 -13
  97. package/src/tui/observerPicker.ts +73 -30
  98. package/src/tui/overlay.js +79 -35
  99. package/src/tui/overlay.ts +81 -34
  100. package/src/tui/prompt.js +162 -94
  101. package/src/tui/runningLight.js +1 -1
  102. package/src/tui/runningLight.ts +1 -1
  103. package/src/tui/scrollInteraction.js +64 -36
  104. package/src/tui/scrollInteraction.ts +70 -37
  105. package/src/tui/selectList.js +60 -32
  106. package/src/tui/sessionLayout.js +11 -3
  107. package/src/tui/sessionLayout.ts +10 -3
  108. package/src/tui/sessionPicker.js +74 -46
  109. package/src/tui/sessionPicker.ts +73 -48
  110. package/src/tui/sessionPickerView.js +32 -19
  111. package/src/tui/sessionPickerView.ts +31 -18
  112. package/src/tui/sessionSidebar.js +87 -57
  113. package/src/tui/sessionSidebar.ts +90 -54
  114. package/src/tui/setup.js +28 -3
  115. package/src/tui/setup.ts +27 -3
  116. package/src/tui/skillAuthoring.js +11 -5
  117. package/src/tui/skillAuthoring.ts +11 -5
  118. package/src/tui/smartLinkClick.js +75 -23
  119. package/src/tui/smartLinkClick.ts +86 -26
  120. package/src/tui/stage.js +47 -16
  121. package/src/tui/stage.ts +53 -18
  122. package/src/tui/stageSurface.js +120 -49
  123. package/src/tui/statusLine.js +85 -53
  124. package/src/tui/statusLine.ts +82 -46
  125. package/src/tui/terminalInputFramer.js +5 -2
  126. package/src/tui/text.js +117 -46
  127. package/src/tui/text.ts +113 -43
  128. package/src/tui/textLayout.js +6 -4
  129. package/src/tui/textLayout.ts +11 -5
  130. package/src/tui/theme.js +17 -8
  131. package/src/tui/thinkingBox.js +95 -95
  132. package/src/tui/thinkingBox.ts +105 -80
  133. package/src/tui/toolActivityPolicy.js +8 -1
  134. package/src/tui/toolActivityPolicy.ts +7 -1
  135. package/src/tui/toolDisplay.js +15 -6
  136. package/src/tui/toolDisplay.ts +16 -6
  137. package/src/tui/toolOutputNormalizer.js +16 -3
  138. package/src/tui/toolOutputNormalizer.ts +13 -3
  139. package/src/tui/transcript.js +15 -9
  140. package/src/tui/turnRail.js +156 -67
  141. package/src/tui/turnRail.ts +155 -58
  142. package/src/tui/usageCard.js +80 -45
  143. package/src/tui/usageCard.ts +81 -46
  144. package/src/tui/viewport.js +48 -23
  145. package/src/tui/viewport.ts +48 -27
  146. package/src/tui/viewportAnchor.js +2 -2
  147. package/src/tui/viewportAnchor.ts +2 -2
  148. package/src/tui/workspaceFileIndex.js +8 -6
  149. package/src/tui/workspaceFileIndex.ts +8 -6
  150. package/src/tui/workspaceSwitch.js +13 -10
  151. package/src/tui/workspaceSwitch.ts +11 -7
package/src/tui/stage.ts CHANGED
@@ -71,12 +71,17 @@ const ERASE_BELOW = '\x1b[J';
71
71
  *
72
72
  * CAUSYNE_STAGE: off | auto | <rows> | <pct>%
73
73
  */
74
- export function stageHeight(out: StageOutput = process.stdout, env: StageEnvironment = process.env): number {
75
- const setting = String(env.CAUSYNE_STAGE ?? 'auto').trim().toLowerCase();
74
+ export function stageHeight(
75
+ out: StageOutput = process.stdout,
76
+ env: StageEnvironment | null | undefined = process.env
77
+ ): number {
78
+ const safeEnv: StageEnvironment = env && typeof env === 'object' ? env : {};
79
+ const setting = String(safeEnv.CAUSYNE_STAGE ?? 'auto').trim().toLowerCase();
76
80
  if (setting === 'off' || setting === '0' || setting === 'false') return 0;
77
81
 
78
- const rows = Number(out && out.rows);
79
- if (!Number.isFinite(rows) || rows <= 0) return 0;
82
+ const rawRows = Number(out && out.rows);
83
+ if (!Number.isFinite(rawRows) || rawRows <= 0) return 0;
84
+ const rows = Math.floor(rawRows);
80
85
 
81
86
  // The seam: never take the last row of the user's screen. It costs one row
82
87
  // and it is the difference between "a region" and "the screen".
@@ -98,11 +103,15 @@ export function stageHeight(out: StageOutput = process.stdout, env: StageEnviron
98
103
  * Everything here is a reason the region could not be repainted safely, so the
99
104
  * answer is the scrollback renderer rather than a stage that misbehaves.
100
105
  */
101
- export function stageEnabled(out: StageOutput = process.stdout, env: StageEnvironment = process.env): boolean {
106
+ export function stageEnabled(
107
+ out: StageOutput = process.stdout,
108
+ env: StageEnvironment | null | undefined = process.env
109
+ ): boolean {
110
+ const safeEnv: StageEnvironment = env && typeof env === 'object' ? env : {};
102
111
  if (!out || !out.isTTY) return false;
103
- if (String(env.TERM || '') === 'dumb') return false;
104
- if (env.CAUSYNE_SIMPLE_INPUT === '1') return false;
105
- return stageHeight(out, env) > 0;
112
+ if (String(safeEnv.TERM || '') === 'dumb') return false;
113
+ if (safeEnv.CAUSYNE_SIMPLE_INPUT === '1') return false;
114
+ return stageHeight(out, safeEnv) > 0;
106
115
  }
107
116
 
108
117
  export class Stage {
@@ -115,7 +124,11 @@ export class Stage {
115
124
  prev: Array<string | null>;
116
125
  caret: StageCaret;
117
126
  stats: { paints: number; rowsWritten: number; bytes: number; claimed: number };
118
- constructor({ out = process.stdout, env = process.env, height = 0 }: StageOptions = {}) {
127
+ constructor(options: StageOptions | null = {}) {
128
+ const opts: StageOptions = options && typeof options === 'object' ? options : {};
129
+ const out = opts.out ?? process.stdout;
130
+ const env = opts.env && typeof opts.env === 'object' ? opts.env : process.env;
131
+ const height = opts.height ?? 0;
119
132
  this.out = out;
120
133
  this.env = env;
121
134
 
@@ -124,7 +137,7 @@ export class Stage {
124
137
  // it has something to put in and grows from there. Sizing it to the screen
125
138
  // is free on an alternate screen — which is what opencode is — and on a
126
139
  // reserved band it is 73 rows of void and a banner scrolled out of sight.
127
- this.maxHeight = height > 0 ? Math.floor(height) : stageHeight(out, env);
140
+ this.maxHeight = Number.isFinite(height) && height > 0 ? Math.floor(height) : stageHeight(out, env);
128
141
  // Rows actually claimed. Zero until reserve().
129
142
  this.height = 0;
130
143
 
@@ -175,7 +188,8 @@ export class Stage {
175
188
  */
176
189
  reserve(rows: number = this.maxHeight): boolean {
177
190
  if (this.reserved || this.maxHeight < 1) return false;
178
- const claim = Math.max(1, Math.min(Math.floor(rows), this.maxHeight));
191
+ const requested = Number.isFinite(rows) ? Math.floor(rows) : this.maxHeight;
192
+ const claim = Math.max(1, Math.min(requested, this.maxHeight));
179
193
  this.write('\n'.repeat(claim));
180
194
  this.stats.claimed += claim;
181
195
  this.reserved = true;
@@ -200,7 +214,7 @@ export class Stage {
200
214
  * (b) permits to move it.
201
215
  */
202
216
  grow(delta: number): number {
203
- if (!this.reserved || delta <= 0) return 0;
217
+ if (!this.reserved || !Number.isFinite(delta) || delta <= 0) return 0;
204
218
  const room = this.maxHeight - this.height;
205
219
  const claim = Math.min(Math.floor(delta), room);
206
220
  if (claim <= 0) return 0;
@@ -228,6 +242,7 @@ export class Stage {
228
242
  const out = new Array(this.height);
229
243
  for (let i = 0; i < this.height; i++) {
230
244
  let row = rows && rows[i] != null ? String(rows[i]) : '';
245
+ if (row.includes('\r')) row = row.replace(/\r/g, '');
231
246
  if (row.includes('\n')) row = row.split('\n')[0] ?? '';
232
247
  out[i] = visibleWidth(row) <= limit ? row : truncate(row, limit, '');
233
248
  }
@@ -235,7 +250,8 @@ export class Stage {
235
250
  }
236
251
 
237
252
  moveTo(row: number): void {
238
- const target = Math.max(0, Math.min(row, this.height - 1));
253
+ if (!Number.isFinite(row) || this.height <= 0) return;
254
+ const target = Math.max(0, Math.min(Math.floor(row), this.height - 1));
239
255
  const delta = target - this.cursor;
240
256
  // CUU/CUD only. Never a newline: on the band's last row a newline scrolls
241
257
  // the terminal, which would move the whole block out from under the diff.
@@ -259,6 +275,17 @@ export class Stage {
259
275
  return true;
260
276
  }
261
277
 
278
+ private unclosedOsc8Term(row: string): string {
279
+ if (!row.includes('\x1b]8;')) return '';
280
+ const osc8Re = /\x1b\]8;[^;]*;([^\x07\x1b]*)(\x07|\x1b\\)/g;
281
+ let active = '';
282
+ let match: RegExpExecArray | null;
283
+ while ((match = osc8Re.exec(row)) !== null) {
284
+ active = (match[1] ?? '').length > 0 ? (match[2] ?? '\x1b\\') : '';
285
+ }
286
+ return active;
287
+ }
288
+
262
289
  /**
263
290
  * Repaint the band. Rows that did not change cost nothing.
264
291
  *
@@ -266,11 +293,12 @@ export class Stage {
266
293
  * idle frame is free.
267
294
  */
268
295
  paint(rows: readonly unknown[], caret: StageCaret | null = null): number {
269
- if (!this.reserved) return 0;
296
+ if (!this.reserved || this.height <= 0) return 0;
270
297
 
271
298
  const next = this.normalize(rows);
299
+ const rawCol = caret && Number.isFinite(caret.col) ? Math.floor(caret.col) : 0;
272
300
  const target = caret && Number.isFinite(caret.row)
273
- ? { row: Math.max(0, Math.min(Math.floor(caret.row), this.height - 1)), col: Math.max(0, Math.min(Math.max(0, this.width() - 2), Math.floor(caret.col) || 0)), hideCursor: Boolean(caret.hideCursor) }
301
+ ? { row: Math.max(0, Math.min(Math.floor(caret.row), this.height - 1)), col: Math.max(0, Math.min(Math.max(0, this.width() - 2), rawCol)), hideCursor: Boolean(caret.hideCursor) }
274
302
  : { row: this.height - 1, col: 0, hideCursor: Boolean(caret?.hideCursor) };
275
303
 
276
304
  const changed = [];
@@ -286,7 +314,11 @@ export class Stage {
286
314
  this.write(SYNC_ON + HIDE_CURSOR + NOWRAP_ON);
287
315
  for (const i of changed) {
288
316
  this.moveTo(i);
289
- this.write('\r' + (next[i] ?? '') + ERASE_LINE);
317
+ const content = next[i] ?? '';
318
+ const osc8Term = this.unclosedOsc8Term(content);
319
+ const osc8Reset = osc8Term ? `\x1b]8;;${osc8Term}` : '';
320
+ const reset = content.includes('\x1b') && !content.endsWith('\x1b[0m') ? '\x1b[0m' : '';
321
+ this.write('\r' + content + osc8Reset + reset + ERASE_LINE);
290
322
  }
291
323
  this.moveTo(target.row);
292
324
  this.write('\r');
@@ -314,7 +346,9 @@ export class Stage {
314
346
  this.moveTo(0);
315
347
  this.write('\r' + ERASE_BELOW + SHOW_CURSOR + '\x1b[0 q' + SYNC_OFF);
316
348
  this.reserved = false;
349
+ this.height = 0;
317
350
  this.cursor = 0;
351
+ this.caret = { row: 0, col: 0 };
318
352
  this.prev = [];
319
353
  }
320
354
 
@@ -348,13 +382,14 @@ export class Stage {
348
382
  * (ChatPrompt already settles resize at 60ms).
349
383
  */
350
384
  resize(height = 0, claim = 0) {
351
- const next = height > 0 ? Math.floor(height) : stageHeight(this.out, this.env);
385
+ const next = Number.isFinite(height) && height > 0 ? Math.floor(height) : stageHeight(this.out, this.env);
352
386
  const wasReserved = this.reserved;
353
387
  if (wasReserved) this.collapse();
354
388
  this.maxHeight = next;
355
389
  this.height = 0;
356
390
  if (next < 1) return false;
357
- if (wasReserved) return this.reserve(claim > 0 ? claim : next);
391
+ const nextClaim = Number.isFinite(claim) && claim > 0 ? Math.floor(claim) : next;
392
+ if (wasReserved) return this.reserve(nextClaim);
358
393
  return false;
359
394
  }
360
395
 
@@ -32,10 +32,10 @@ import { mouseHoverTracking } from './mouseHover.js';
32
32
  import { truncate, padEnd, visibleWidth, stripAnsi } from './text.js';
33
33
  import { composerWidth } from './layout.js';
34
34
  import { placeHome, placeDialog } from './homeView.js';
35
- import { sidebarVisible, sessionMainWidth, sessionComposerWidth, sessionSidebarRows, joinSessionSidebar } from './sessionSidebar.js';
35
+ import { sidebarVisible, sessionSidebarWidth, sessionMainWidth, sessionComposerWidth, sessionSidebarRows, joinSessionSidebar } from './sessionSidebar.js';
36
36
  import { sessionStageHeight, alignTranscriptRows } from './sessionLayout.js';
37
37
  import { hasSessionTurns, collectSessionTurns, buildTurnRailCells, renderTurnPreviewCard, overlayTurnPreviewCard, resolveActiveTurnIndex } from './turnRail.js';
38
- import { registerStageConsoleGuard, setStageConsoleGuardActive } from './consoleGuard.js';
38
+ import { registerStageConsoleGuard, setStageConsoleGuardActive, runWithStageWrite } from './consoleGuard.js';
39
39
 
40
40
  // Rows of evicted transcript held for the exit log. Eviction only happens after
41
41
  // MAX_FRAMES, so this is a bound on a pathological session, not a working limit.
@@ -163,16 +163,17 @@ function railGlyph(kind) {
163
163
  * settled.
164
164
  */
165
165
  export function scrollSettings(env = process.env, config = null) {
166
+ const safeEnv = env && typeof env === 'object' ? env : {};
166
167
  const tui = (config && typeof config === 'object' && config.tui) || {};
167
168
 
168
- let speed = Number(env.CAUSYNE_SCROLL_SPEED);
169
+ let speed = Number(safeEnv.CAUSYNE_SCROLL_SPEED);
169
170
  if (!Number.isFinite(speed) || speed <= 0) speed = Number(tui.scrollSpeed);
170
171
  if (!Number.isFinite(speed) || speed <= 0) speed = DEFAULT_SCROLL_SPEED;
171
172
  // A wheel that moves half the screen per notch is not a preference, it is a
172
173
  // misconfiguration; clamp rather than obey it.
173
174
  speed = Math.min(speed, 20);
174
175
 
175
- const raw = env.CAUSYNE_SCROLL_ACCEL;
176
+ const raw = safeEnv.CAUSYNE_SCROLL_ACCEL;
176
177
  const accelerate = raw !== undefined && raw !== ''
177
178
  ? raw === '1' || raw === 'true'
178
179
  : Boolean(tui.scrollAcceleration);
@@ -238,6 +239,7 @@ export class StageSurface {
238
239
  this.unregisterConsoleGuard = null;
239
240
  this.wasModal = false;
240
241
  this.lastBlockLength = 0;
242
+ this.lastUserTurnCount = 0;
241
243
  }
242
244
 
243
245
  get width() {
@@ -274,7 +276,19 @@ export class StageSurface {
274
276
  }
275
277
 
276
278
  setSessionInfo(info) {
277
- this.sessionInfo = { ...this.sessionInfo, ...info };
279
+ const changedSession = info?.id && this.sessionInfo?.id && info.id !== this.sessionInfo.id;
280
+ if (changedSession) {
281
+ // Sidebar plans and turn hover coordinates belong to the previous chat.
282
+ this.sidebarPlan = [];
283
+ this.hoveredTurnIndex = null;
284
+ this.hoveredTurnAnchorY = null;
285
+ this.activeTurnIndex = null;
286
+ this.hoveredMessageFrameId = null;
287
+ this.turnRailLayout = null;
288
+ }
289
+ this.sessionInfo = changedSession
290
+ ? { ...this.sessionInfo, activeSkill: null, contextChars: 0, ...info }
291
+ : { ...this.sessionInfo, ...info };
278
292
  this.stage.invalidate();
279
293
  }
280
294
 
@@ -303,10 +317,17 @@ export class StageSurface {
303
317
  return true;
304
318
  }
305
319
 
320
+ writeModeControl(sequence) {
321
+ if (!sequence) return;
322
+ runWithStageWrite(() => {
323
+ this.out.write(sequence);
324
+ });
325
+ }
326
+
306
327
  enableMouse() {
307
- if (!this.mouseWanted || this.mouseOn || !this.stage.reserved) return false;
308
- this.out.write(mouseTracking(true));
309
- this.out.write(mouseHoverTracking(true, this.env));
328
+ if (this.homeInfo || !this.mouseWanted || this.mouseOn || !this.stage.reserved) return false;
329
+ this.writeModeControl(mouseTracking(true));
330
+ this.writeModeControl(mouseHoverTracking(true, this.env));
310
331
  this.mouseCaptured = true;
311
332
  this.mouseOn = true;
312
333
  return true;
@@ -315,8 +336,8 @@ export class StageSurface {
315
336
  disableMouse(force = false) {
316
337
  if (!force && !this.mouseOn && !this.mouseCaptured) return false;
317
338
  // Restore terminal motion modes, including stale tracking from an interrupted turn.
318
- this.out.write(mouseHoverTracking(false, { ...this.env, CAUSYNE_MOUSE_HOVER: '1' }));
319
- this.out.write(mouseTracking(false));
339
+ this.writeModeControl(mouseHoverTracking(false, { ...this.env, CAUSYNE_MOUSE_HOVER: '1' }));
340
+ this.writeModeControl(mouseTracking(false));
320
341
  this.mouseCaptured = false;
321
342
  this.mouseOn = false;
322
343
  this.detached = false;
@@ -413,6 +434,16 @@ export class StageSurface {
413
434
 
414
435
  handleChange() {
415
436
  if (!this.transcript.isEmpty()) this.opened = true;
437
+ let userTurns = 0;
438
+ for (const frame of this.transcript.frames) {
439
+ if (frame && frame.kind === 'user') userTurns++;
440
+ }
441
+ if (userTurns > this.lastUserTurnCount) {
442
+ this.activeTurnIndex = null;
443
+ this.hoveredTurnIndex = null;
444
+ this.hoveredTurnAnchorY = null;
445
+ }
446
+ this.lastUserTurnCount = userTurns;
416
447
  const before = this.lastHeight;
417
448
  const mainWidth = sessionMainWidth(this.width, false, this.env);
418
449
  const contentWidth = this.railEnabled(mainWidth)
@@ -450,6 +481,11 @@ export class StageSurface {
450
481
  this.lastPromptCaret = caret;
451
482
  }
452
483
 
484
+ // Do not grow, resize, or invalidate the band while the terminal owns
485
+ // scrollback; otherwise stage.grow emits newlines that shift the user's
486
+ // scroll position before the detached repaint guard below.
487
+ if (this.detached) return false;
488
+
453
489
  const isModal = Boolean(caret?.modal);
454
490
  if (isModal !== this.wasModal) {
455
491
  this.wasModal = isModal;
@@ -457,6 +493,9 @@ export class StageSurface {
457
493
  }
458
494
 
459
495
  if (this.homeInfo || (caret?.modal && !caret?.inline)) {
496
+ this.turnRailLayout = null;
497
+ this.hoveredTurnIndex = null;
498
+ this.hoveredTurnAnchorY = null;
460
499
  if (this.stage.height < this.stage.maxHeight) {
461
500
  this.stage.grow(this.stage.maxHeight - this.stage.height);
462
501
  }
@@ -474,7 +513,7 @@ export class StageSurface {
474
513
  ? Math.max(20, mainWidth - RAIL_BUDGET - (hasSessionTurns(this.transcript) ? TURN_RAIL_BUDGET : 0))
475
514
  : mainWidth;
476
515
 
477
- let block = promptRows;
516
+ let block = Array.isArray(promptRows) && promptRows.length > 0 ? promptRows : [''];
478
517
  let caretRow = caret && Number.isFinite(caret.row) ? caret.row : Math.max(0, block.length - 1);
479
518
  let caretCol = caret ? caret.col : 0;
480
519
 
@@ -506,6 +545,7 @@ export class StageSurface {
506
545
  block = block.slice(cut);
507
546
  caretRow = Math.max(0, caretRow - cut);
508
547
  }
548
+ caretRow = Math.max(0, Math.min(block.length - 1, Math.floor(caretRow)));
509
549
 
510
550
  if (this.lastBlockLength > 0 && this.lastBlockLength !== block.length) {
511
551
  this.stage.invalidate();
@@ -529,7 +569,13 @@ export class StageSurface {
529
569
  }
530
570
  this.decorate(rows, contentWidth);
531
571
  markHoveredMessage(rows, this, contentWidth);
532
- if (rail) this.attachRail(rows, contentWidth);
572
+ if (rail) {
573
+ this.attachRail(rows, contentWidth);
574
+ } else {
575
+ this.turnRailLayout = null;
576
+ this.hoveredTurnIndex = null;
577
+ this.hoveredTurnAnchorY = null;
578
+ }
533
579
  if (this.hoveredTurnIndex && this.turnRailLayout?.turns?.length) {
534
580
  const hoveredTurn = this.turnRailLayout.turns.find(t => t.turnIndex === this.hoveredTurnIndex);
535
581
  if (hoveredTurn) {
@@ -537,14 +583,19 @@ export class StageSurface {
537
583
  const anchorY = this.hoveredTurnAnchorY ?? Math.floor(rows.length / 2);
538
584
  rows = overlayTurnPreviewCard(rows, card, anchorY, this.turnRailLayout?.railX ?? 1, mainWidth);
539
585
  if (this.turnRailLayout) {
540
- const cardWidth = 52;
586
+ const cardWidth = visibleWidth(card[0] || '') || 52;
541
587
  const railX = this.turnRailLayout.railX ?? 1;
588
+ const safeAnchorY = Number.isFinite(anchorY) ? Math.floor(anchorY) : Math.floor(rows.length / 2);
542
589
  let cardX = railX - cardWidth - 1;
543
- if (cardX < 0 || (railX <= 4 && railX + 2 + cardWidth <= mainWidth)) {
590
+ if (railX <= 4 && railX + 2 < mainWidth) {
591
+ cardX = railX + 2;
592
+ } else if (cardX < 0) {
544
593
  cardX = Math.max(0, Math.min(mainWidth - cardWidth - 1, railX + 2));
545
594
  }
546
- const startY = Math.max(0, Math.min(rows.length - card.length, anchorY - Math.floor(card.length / 2)));
547
- this.turnRailLayout.cardRect = { x: cardX, y: startY, width: cardWidth, height: card.length, turnIndex: hoveredTurn.turnIndex };
595
+ const effectiveCardWidth = Math.max(1, Math.min(cardWidth, Math.max(1, mainWidth - cardX)));
596
+ const startY = Math.max(0, Math.min(rows.length - card.length, safeAnchorY - Math.floor(card.length / 2)));
597
+ const visibleCardHeight = Math.min(card.length, Math.max(0, rows.length - startY));
598
+ this.turnRailLayout.cardRect = { x: cardX, y: startY, width: effectiveCardWidth, height: visibleCardHeight, turnIndex: hoveredTurn.turnIndex };
548
599
  }
549
600
  }
550
601
  } else if (this.turnRailLayout) {
@@ -552,8 +603,9 @@ export class StageSurface {
552
603
  }
553
604
  if (this.messageActionOverlay) {
554
605
  const overlay = this.messageActionOverlay;
555
- const placed = placeMessageActionPanel(rows, overlay.panel, contentWidth,
556
- (this.out.rows || height) - height, overlay.layer.anchorY,
606
+ const overlayWidth = rail ? Math.max(contentWidth, mainWidth - RAIL_BUDGET) : contentWidth;
607
+ const placed = placeMessageActionPanel(rows, overlay.panel, overlayWidth,
608
+ Math.max(0, (this.out.rows || height) - height), overlay.layer.anchorY,
557
609
  overlay.layer.items.length, {
558
610
  messageBounds: overlay.layer.messageBounds,
559
611
  dimBackdrop: true
@@ -561,35 +613,25 @@ export class StageSurface {
561
613
  rows = placed.rows;
562
614
  overlay.layer.actionLayout = placed.layout;
563
615
  }
616
+ } else {
617
+ this.turnRailLayout = null;
618
+ this.hoveredTurnIndex = null;
619
+ this.hoveredTurnAnchorY = null;
564
620
  }
565
621
 
566
- // DO NOT PAINT WHILE THE TERMINAL OWNS THE SCROLL.
567
- //
568
- // The Stage repaints by DIFF against the rows it believes are on screen. It
569
- // has no way to know the user scrolled the terminal's own scrollback, and
570
- // when they do, the band's absolute rows move while the diff keeps writing
571
- // to the old coordinates — which is how a session ends up with a stray rail
572
- // column down the middle and fragments of old frames at the edges.
573
- //
574
- // We cannot detect a terminal scroll directly. What we CAN detect is the
575
- // moment we handed the wheel over (viewport at its top, mouse reporting
576
- // released), and from then until the user types again the terminal is the
577
- // thing scrolling. Painting nothing is correct: the band is not where we
578
- // left it, so every write would land somewhere wrong.
579
- if (this.detached) return false;
580
-
581
622
  const mainRows = rows.concat(block);
623
+ const panelWidth = sidebar ? sessionSidebarWidth(width, false, this.env) : 0;
582
624
  const panelRows = sidebar ? sessionSidebarRows({
583
625
  ...this.sessionInfo,
584
626
  cwd: this.sidebarStatus?.cwd || this.sessionInfo?.cwd,
585
627
  provider: this.sidebarStatus?.provider || this.sessionInfo?.provider,
586
628
  model: this.sidebarStatus?.model || this.sessionInfo?.model,
587
- contextChars: this.sidebarStatus?.contextChars,
588
- contextLimit: this.sidebarStatus?.contextLimit,
629
+ contextChars: this.sidebarStatus?.contextChars ?? this.sessionInfo?.contextChars,
630
+ contextLimit: this.sidebarStatus?.contextLimit ?? this.sessionInfo?.contextLimit,
589
631
  plan: this.sidebarPlan,
590
632
  activeSkill: this.sessionInfo?.activeSkill
591
- }, mainRows.length) : [];
592
- const painted = sidebar ? joinSessionSidebar(mainRows, panelRows, mainWidth) : mainRows;
633
+ }, mainRows.length, panelWidth) : [];
634
+ const painted = sidebar ? joinSessionSidebar(mainRows, panelRows, mainWidth, panelWidth) : mainRows;
593
635
  return this.stage.paint(painted, {
594
636
  row: rows.length + caretRow,
595
637
  // The composer may never put its caret into the sidebar or the reserved
@@ -655,6 +697,11 @@ export class StageSurface {
655
697
  this.evicted = [];
656
698
  this.transcript.clear();
657
699
  this.lastHeight = 0;
700
+ this.lastUserTurnCount = 0;
701
+ this.activeTurnIndex = null;
702
+ this.hoveredTurnIndex = null;
703
+ this.hoveredTurnAnchorY = null;
704
+ this.turnRailLayout = null;
658
705
  this.stage.invalidate();
659
706
  if (this.viewport) {
660
707
  this.viewport.manual = false;
@@ -682,6 +729,10 @@ export class StageSurface {
682
729
  // The existing rows are already reserved: repaint them in place with
683
730
  // their new width, clearing trailing cells through Stage.paint().
684
731
  const columns = this.stage.width();
732
+ if (columns !== this.lastColumns || next !== this.stage.maxHeight) {
733
+ this.hoveredTurnIndex = null;
734
+ this.hoveredTurnAnchorY = null;
735
+ }
685
736
  if (!this.stage.reserved || next !== this.stage.maxHeight) {
686
737
  this.stage.resize(next, 1);
687
738
  } else if (columns !== this.lastColumns && !this.detached) {
@@ -723,15 +774,32 @@ export class StageSurface {
723
774
  * Returns `height` single-column strings.
724
775
  */
725
776
  buildRail(height, contentWidth) {
726
- const total = Math.max(1, this.transcript.height(contentWidth));
727
- const slotOf = (row) => Math.max(0, Math.min(height - 1, Math.floor((row / total) * height)));
777
+ const flat = typeof this.transcript.flatten === 'function' ? this.transcript.flatten(contentWidth) : null;
778
+ const flatRows = Array.isArray(flat?.rows) ? flat.rows : [];
779
+ const markers = Array.isArray(flat?.markers) ? flat.markers : this.transcript.markers(contentWidth);
780
+ const rawTotal = Math.max(0, flat ? flatRows.length : this.transcript.height(contentWidth));
781
+ const total = Math.max(1, rawTotal);
782
+ const padding = rawTotal <= height ? Math.max(0, height - rawTotal) : 0;
783
+ const slotOf = (row) => (rawTotal <= height
784
+ ? Math.max(0, Math.min(height - 1, padding + row))
785
+ : Math.max(0, Math.min(height - 1, Math.floor((row / total) * height))));
728
786
 
729
787
  const kinds = new Array(height).fill(null);
730
- for (const marker of this.transcript.markers(contentWidth)) {
788
+ for (let mIdx = 0; mIdx < markers.length; mIdx++) {
789
+ const marker = markers[mIdx];
731
790
  // Suppress repetitive step/result/reasoning noise on the overview rail.
732
791
  // Checkpoints, user turns, approvals, and errors remain discoverable.
733
792
  if ((RAIL_PRIORITY[marker.kind] || 0) < 50) continue;
734
- const slot = slotOf(marker.row);
793
+ let markerRow = marker.row;
794
+ if (marker.kind === 'user' && flatRows.length > 0) {
795
+ const nextRow = mIdx + 1 < markers.length ? markers[mIdx + 1].row : flatRows.length;
796
+ if (markerRow + 1 < nextRow && markerRow + 1 < flatRows.length) {
797
+ const firstLine = stripAnsi(String(flatRows[markerRow] ?? '')).trim();
798
+ const secondLine = stripAnsi(String(flatRows[markerRow + 1] ?? '')).trim();
799
+ if (firstLine === '' && secondLine !== '') markerRow += 1;
800
+ }
801
+ }
802
+ const slot = slotOf(markerRow);
735
803
  const held = kinds[slot];
736
804
  if (!held || (RAIL_PRIORITY[marker.kind] || 0) > (RAIL_PRIORITY[held] || 0)) {
737
805
  kinds[slot] = marker.kind;
@@ -769,14 +837,15 @@ export class StageSurface {
769
837
  const turns = collectSessionTurns(this.transcript, contentWidth);
770
838
  const hasTurns = turns.length > 0;
771
839
  const isAtBottom = typeof this.viewport?.atBottom === 'function' ? this.viewport.atBottom() : false;
772
- const activeTurn = this.activeTurnIndex || resolveActiveTurnIndex(turns, this.viewport.state().scrollTop, rows.length, isAtBottom);
840
+ const scrollTop = this.viewport.state().scrollTop;
841
+ const activeTurn = this.activeTurnIndex || resolveActiveTurnIndex(turns, scrollTop, rows.length, isAtBottom);
773
842
  const railResult = hasTurns
774
- ? buildTurnRailCells(turns, rows.length, activeTurn, this.hoveredTurnIndex)
843
+ ? buildTurnRailCells(turns, rows.length, activeTurn, this.hoveredTurnIndex, scrollTop)
775
844
  : null;
776
845
 
777
846
  this.turnRailLayout = {
778
847
  railX: hasTurns ? 1 : contentWidth + 1,
779
- stageTop: (this.out.rows || this.stage.height) - this.stage.height,
848
+ stageTop: Math.max(0, (this.out.rows || this.stage.height) - this.stage.height),
780
849
  viewportHeight: rows.length,
781
850
  dotRows: railResult?.layout?.dotRows || new Map(),
782
851
  rowToTurn: railResult?.layout?.rowToTurn || new Map(),
@@ -802,7 +871,9 @@ export class StageSurface {
802
871
  // Turn markers consume their own three-column lane. Preserve ALL
803
872
  // previously rendered command text instead of clipping its last cells.
804
873
  const rowWidth = contentWidth + (hasTurns ? TURN_RAIL_BUDGET : 0);
805
- rows[i] = `${padEnd(truncate(row, rowWidth, ''), rowWidth)} ${rightCell}`;
874
+ const paddedRow = padEnd(truncate(row, rowWidth, ''), rowWidth);
875
+ const railReset = paddedRow.includes('\x1b[') ? '\x1b[0m' : '';
876
+ rows[i] = `${paddedRow}${railReset} ${rightCell}`;
806
877
  }
807
878
  return rows;
808
879
  }
@@ -819,8 +890,8 @@ export class StageSurface {
819
890
  */
820
891
  releaseMouse() {
821
892
  if (!this.mouseCaptured) return false;
822
- this.out.write(mouseHoverTracking(false, this.env));
823
- this.out.write(mouseTracking(false));
893
+ this.writeModeControl(mouseHoverTracking(false, this.env));
894
+ this.writeModeControl(mouseTracking(false));
824
895
  this.mouseCaptured = false;
825
896
  this.detached = true;
826
897
  return true;
@@ -830,8 +901,8 @@ export class StageSurface {
830
901
  captureMouse() {
831
902
  // Home and suspended stages must not arm modes their teardown cannot observe.
832
903
  if (!this.mouseWanted || !this.mouseOn || !this.stage.reserved || this.mouseCaptured) return false;
833
- this.out.write(mouseTracking(true));
834
- this.out.write(mouseHoverTracking(true, this.env));
904
+ this.writeModeControl(mouseTracking(true));
905
+ this.writeModeControl(mouseHoverTracking(true, this.env));
835
906
  this.mouseCaptured = true;
836
907
  this.detached = false;
837
908
  // After native scrollback, the former physical cursor location is unknown.