@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
@@ -1,10 +1,12 @@
1
- import { truncate, visibleWidth, wrapBlock, stripAnsi, padEnd } from './text.js';
1
+ import { truncate, visibleWidth, wrapBlock, stripAnsi, padEnd, safeDisplay } from './text.js';
2
2
  // @ts-expect-error untyped local TUI theme
3
3
  import { paint, bold, dim, GLYPHS } from './theme.js';
4
4
  export function formatTurnTimestamp(ts) {
5
5
  if (!ts || !Number.isFinite(ts))
6
6
  return '';
7
7
  const date = new Date(ts);
8
+ if (!Number.isFinite(date.getTime()))
9
+ return '';
8
10
  const now = new Date();
9
11
  const sameDay = date.getFullYear() === now.getFullYear() &&
10
12
  date.getMonth() === now.getMonth() &&
@@ -34,6 +36,7 @@ export function collectSessionTurns(transcript, contentWidth = 80) {
34
36
  }
35
37
  const flat = typeof transcript.flatten === 'function' ? transcript.flatten(contentWidth) : null;
36
38
  const markers = flat?.markers || [];
39
+ const transcriptHeight = Array.isArray(flat?.rows) ? flat.rows.length : undefined;
37
40
  const frames = transcript.frames;
38
41
  const userFrames = [];
39
42
  for (let i = 0; i < frames.length; i++) {
@@ -68,8 +71,20 @@ export function collectSessionTurns(transcript, contentWidth = 80) {
68
71
  break;
69
72
  }
70
73
  }
71
- const marker = markers.find((m) => m.id === frame.id);
74
+ const markerIdx = markers.findIndex((m) => m.id === frame.id);
75
+ const marker = markerIdx >= 0 ? markers[markerIdx] : undefined;
72
76
  const startRow = marker ? marker.row : 0;
77
+ const nextMarkerRow = markerIdx >= 0 && markerIdx + 1 < markers.length
78
+ ? markers[markerIdx + 1].row
79
+ : (Array.isArray(flat?.rows) ? flat.rows.length : 0);
80
+ let promptRow = startRow;
81
+ if (Array.isArray(flat?.rows) && startRow + 1 < nextMarkerRow && startRow + 1 < flat.rows.length) {
82
+ const firstLine = stripAnsi(String(flat.rows[startRow] ?? '')).trim();
83
+ const secondLine = stripAnsi(String(flat.rows[startRow + 1] ?? '')).trim();
84
+ if (firstLine === '' && secondLine !== '') {
85
+ promptRow = startRow + 1;
86
+ }
87
+ }
73
88
  turns.push({
74
89
  turnIndex,
75
90
  totalTurns,
@@ -78,7 +93,9 @@ export function collectSessionTurns(transcript, contentWidth = 80) {
78
93
  timestamp: frame.ts || Date.now(),
79
94
  formattedDate: formatTurnTimestamp(frame.ts || Date.now()),
80
95
  frameId: frame.id,
81
- startRow
96
+ startRow,
97
+ promptRow,
98
+ ...(transcriptHeight !== undefined ? { transcriptHeight } : {})
82
99
  });
83
100
  }
84
101
  return turns;
@@ -92,11 +109,13 @@ export function resolveActiveTurnIndex(turns, scrollTop, viewportHeight = 20, is
92
109
  if (isAtBottom) {
93
110
  return turns[turns.length - 1].turnIndex;
94
111
  }
95
- if (scrollTop <= 0) {
112
+ const safeScrollTop = Number.isFinite(scrollTop) ? scrollTop : 0;
113
+ const safeViewportHeight = Number.isFinite(viewportHeight) ? Math.max(0, viewportHeight) : 20;
114
+ if (safeScrollTop <= 0) {
96
115
  return turns[0].turnIndex;
97
116
  }
98
117
  let active = turns[turns.length - 1].turnIndex;
99
- const targetRow = Math.max(0, scrollTop + Math.floor(viewportHeight / 3));
118
+ const targetRow = Math.max(0, safeScrollTop + Math.floor(safeViewportHeight / 3));
100
119
  for (let i = turns.length - 1; i >= 0; i--) {
101
120
  const t = turns[i];
102
121
  if (t.startRow <= targetRow) {
@@ -110,6 +129,9 @@ export function resolveActiveTurnIndex(turns, scrollTop, viewportHeight = 20, is
110
129
  * ANSI-safe column slicing: skips the first startCol visible columns while preserving active styles.
111
130
  */
112
131
  export function sliceFromColumn(source, startCol) {
132
+ if (startCol === Number.POSITIVE_INFINITY)
133
+ return '';
134
+ const targetCol = Number.isFinite(startCol) ? Math.max(0, Math.floor(startCol)) : 0;
113
135
  let col = 0;
114
136
  let index = 0;
115
137
  let activeStyles = '';
@@ -120,7 +142,7 @@ export function sliceFromColumn(source, startCol) {
120
142
  || rest.match(/^\x1b\[[0-?]*[ -/]*[@-~]/)
121
143
  || rest.match(/^\x1b[@-Z\\-_]/);
122
144
  if (match) {
123
- if (col < startCol) {
145
+ if (col < targetCol) {
124
146
  if (match[0] === '\x1b[0m' || match[0] === '\x1b[m') {
125
147
  activeStyles = '';
126
148
  }
@@ -132,7 +154,7 @@ export function sliceFromColumn(source, startCol) {
132
154
  continue;
133
155
  }
134
156
  }
135
- if (col >= startCol) {
157
+ if (col >= targetCol) {
136
158
  const tail = source.slice(index);
137
159
  // Ensure any OSC 8 hyperlink opened inside `tail` is closed at the end of the slice
138
160
  let openOsc8Term = '';
@@ -160,54 +182,90 @@ export function sliceFromColumn(source, startCol) {
160
182
  * - Consecutive vertical pillar when turns fit within viewport height.
161
183
  * - Proportional scaling when turn count exceeds available height.
162
184
  */
163
- export function buildTurnRailCells(turns, height, activeTurnIndex, hoveredTurnIndex) {
164
- const cells = new Array(Math.max(0, height)).fill(' ');
185
+ export function buildTurnRailCells(turns, height, activeTurnIndex, hoveredTurnIndex, scrollTop) {
186
+ const safeHeight = Number.isFinite(height) ? Math.max(0, Math.floor(height)) : 0;
187
+ const cells = new Array(safeHeight).fill(' ');
165
188
  const dotRows = new Map();
166
189
  const rowToTurn = new Map();
167
- if (turns.length === 0 || height <= 0) {
190
+ if (turns.length === 0 || safeHeight <= 0) {
168
191
  return { cells, layout: { dotRows, rowToTurn } };
169
192
  }
170
193
  const count = turns.length;
194
+ const rawTranscriptHeight = turns[0]?.transcriptHeight;
195
+ const hasTranscriptHeight = typeof rawTranscriptHeight === 'number' &&
196
+ Number.isFinite(rawTranscriptHeight) &&
197
+ rawTranscriptHeight > 0;
198
+ const topOffset = hasTranscriptHeight && rawTranscriptHeight < safeHeight
199
+ ? safeHeight - Math.floor(rawTranscriptHeight)
200
+ : 0;
201
+ const activeHeight = Math.max(1, safeHeight - topOffset);
171
202
  // Dense imported histories may contain hundreds of turns. Show a measured
172
203
  // set of quiet milestones, while always retaining active/hovered endpoints.
173
204
  // 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))))
205
+ const quietStep = count > Math.max(16, Math.floor(activeHeight / 2))
206
+ ? Math.max(2, Math.ceil(count / Math.max(12, Math.floor(activeHeight / 3))))
176
207
  : 1;
177
208
  // If count fits comfortably, stack consecutive dots centered or upper-aligned
178
- const startRow = count <= height
179
- ? Math.max(0, Math.floor((height - count) / 3))
180
- : 0;
209
+ const startRow = count <= activeHeight
210
+ ? topOffset + Math.max(0, Math.floor((activeHeight - count) / 3))
211
+ : topOffset;
181
212
  for (let i = 0; i < count; i++) {
182
213
  const turn = turns[i];
183
214
  if (!turn)
184
215
  continue;
185
216
  const turnNum = turn.turnIndex;
186
217
  let rowIdx;
187
- if (count <= height) {
218
+ if (count === 1 && hasTranscriptHeight) {
219
+ const rawAnchor = Number.isFinite(turn.promptRow) ? turn.promptRow : turn.startRow;
220
+ const anchorRow = Number.isFinite(rawAnchor) ? Math.max(0, Math.floor(rawAnchor)) : 0;
221
+ if (topOffset > 0) {
222
+ rowIdx = topOffset + anchorRow;
223
+ }
224
+ else if (typeof scrollTop === 'number' && Number.isFinite(scrollTop)) {
225
+ const safeScrollTop = Math.max(0, Math.floor(scrollTop));
226
+ if (anchorRow >= safeScrollTop && anchorRow < safeScrollTop + safeHeight) {
227
+ rowIdx = anchorRow - safeScrollTop;
228
+ }
229
+ else if (anchorRow < safeScrollTop) {
230
+ rowIdx = 0;
231
+ }
232
+ else {
233
+ rowIdx = safeHeight - 1;
234
+ }
235
+ }
236
+ else {
237
+ rowIdx = Math.round((anchorRow / Math.max(1, Math.floor(rawTranscriptHeight) - 1)) * (safeHeight - 1));
238
+ }
239
+ }
240
+ else if (count <= activeHeight) {
188
241
  rowIdx = startRow + i;
189
242
  }
190
243
  else {
191
- rowIdx = Math.round((i / (count - 1)) * (height - 1));
244
+ rowIdx = topOffset + Math.round((i / (count - 1)) * (activeHeight - 1));
192
245
  }
193
- rowIdx = Math.max(0, Math.min(height - 1, rowIdx));
246
+ rowIdx = Math.max(topOffset, Math.min(safeHeight - 1, rowIdx));
194
247
  dotRows.set(turnNum, rowIdx);
195
248
  const isHovered = hoveredTurnIndex === turnNum;
196
249
  const isActive = activeTurnIndex === turnNum;
197
250
  const showQuiet = quietStep === 1 || i === 0 || i === count - 1 || i % quietStep === 0;
198
- if (isHovered || isActive || showQuiet)
199
- rowToTurn.set(rowIdx, turnNum);
251
+ const rowHasHovered = cells[rowIdx]?.includes('230;235;245m');
252
+ const rowHasDot = cells[rowIdx]?.includes('●');
200
253
  if (isHovered) {
201
254
  // Hovered dot: bright silver highlighted circle
202
255
  cells[rowIdx] = '\x1b[1m\x1b[38;2;230;235;245m●\x1b[0m';
256
+ rowToTurn.set(rowIdx, turnNum);
203
257
  }
204
- else if (isActive && !cells[rowIdx]?.includes('230;235;245m')) {
258
+ else if (isActive && !rowHasHovered) {
205
259
  // Active / current turn: bright white circle
206
260
  cells[rowIdx] = '\x1b[1m\x1b[38;2;250;250;250m●\x1b[0m';
261
+ rowToTurn.set(rowIdx, turnNum);
207
262
  }
208
- else if (showQuiet && !cells[rowIdx]?.includes('●')) {
263
+ else if (showQuiet && !rowHasDot) {
209
264
  // Muted inactive turns: sparse gray dot in long sessions
210
265
  cells[rowIdx] = '\x1b[38;2;115;115;120m•\x1b[0m';
266
+ if (!rowToTurn.has(rowIdx)) {
267
+ rowToTurn.set(rowIdx, turnNum);
268
+ }
211
269
  }
212
270
  }
213
271
  return { cells, layout: { dotRows, rowToTurn } };
@@ -220,7 +278,7 @@ export function buildTurnRailCells(turns, height, activeTurnIndex, hoveredTurnIn
220
278
  export function formatPreviewCardMarkdown(raw) {
221
279
  if (!raw)
222
280
  return '';
223
- let text = String(raw);
281
+ let text = safeDisplay(String(raw));
224
282
  // Strip code block fences
225
283
  text = text.replace(/```[a-zA-Z0-9_-]*\n?/g, ' ');
226
284
  // Strip headings: ### Heading -> Heading
@@ -266,31 +324,37 @@ export function formatPreviewCardMarkdown(raw) {
266
324
  * - Footer: Left 'X of Y', Right timestamp
267
325
  */
268
326
  export function renderTurnPreviewCard(turn, maxCardWidth = 50) {
269
- const cardWidth = Math.max(38, Math.min(60, maxCardWidth));
327
+ const safeTurn = turn && typeof turn === 'object' ? turn : {};
328
+ const safeWidth = Number.isFinite(maxCardWidth) ? Math.floor(maxCardWidth) : 50;
329
+ const cardWidth = Math.max(38, Math.min(60, safeWidth));
270
330
  const innerWidth = cardWidth - 4; // 2 border chars + 2 padding chars
271
331
  const cardBg = '\x1b[48;2;28;28;32m';
272
332
  const borderStyle = `${cardBg}\x1b[38;2;75;75;82m`;
273
333
  const reset = '\x1b[0m';
274
334
  // Format header: User Prompt (bold primary) rendered cleanly without raw markdown, strictly flush-left with hang: 0
275
- const rawPrompt = formatPreviewCardMarkdown(turn.userPrompt || 'User request');
335
+ const rawPrompt = formatPreviewCardMarkdown(safeTurn.userPrompt || 'User request');
276
336
  const promptLines = wrapBlock(rawPrompt, innerWidth, { hang: 0 }).slice(0, 2);
277
337
  if (promptLines.length === 2 && promptLines[1]) {
278
338
  promptLines[1] = truncate(promptLines[1], innerWidth - 3, '...');
279
339
  }
280
340
  // Format body: Assistant Summary (muted secondary) rendered cleanly without raw markdown, strictly flush-left with hang: 0
281
341
  let bodyLines = [];
282
- if (turn.assistantSummary) {
283
- const formattedSummary = formatPreviewCardMarkdown(turn.assistantSummary);
342
+ if (safeTurn.assistantSummary) {
343
+ const formattedSummary = formatPreviewCardMarkdown(safeTurn.assistantSummary);
284
344
  bodyLines = wrapBlock(formattedSummary, innerWidth, { hang: 0 }).slice(0, 3);
285
345
  if (bodyLines.length === 3 && bodyLines[2]) {
286
346
  bodyLines[2] = truncate(bodyLines[2], innerWidth - 3, '...');
287
347
  }
288
348
  }
289
349
  // Format footer: 'X of Y' on left, timestamp on right
290
- const counterText = `${turn.turnIndex} of ${turn.totalTurns}`;
291
- const dateText = turn.formattedDate;
292
- const footerSpace = Math.max(2, innerWidth - counterText.length - dateText.length);
293
- const footerLine = `${counterText}${' '.repeat(footerSpace)}${dateText}`;
350
+ const turnNum = Number.isFinite(safeTurn.turnIndex) ? safeTurn.turnIndex : 1;
351
+ const totalTurns = Number.isFinite(safeTurn.totalTurns) ? safeTurn.totalTurns : 1;
352
+ const counterText = truncate(safeDisplay(`${turnNum} of ${totalTurns}`), innerWidth, '');
353
+ const rawDateText = safeDisplay(safeTurn.formattedDate || '');
354
+ const maxDateWidth = Math.max(0, innerWidth - visibleWidth(counterText) - 2);
355
+ const dateText = maxDateWidth > 0 ? truncate(rawDateText, maxDateWidth, '…') : '';
356
+ const footerSpace = Math.max(0, innerWidth - visibleWidth(counterText) - visibleWidth(dateText));
357
+ const footerLine = truncate(`${counterText}${' '.repeat(footerSpace)}${dateText}`, innerWidth, '');
294
358
  // Assemble rows
295
359
  const rows = [];
296
360
  const topBorder = `${borderStyle}╭${'─'.repeat(cardWidth - 2)}╮${reset}`;
@@ -321,32 +385,51 @@ export function renderTurnPreviewCard(turn, maxCardWidth = 50) {
321
385
  * Overlay the floating preview card onto viewport rows at a specific anchorY.
322
386
  */
323
387
  export function overlayTurnPreviewCard(viewportRows, cardRows, anchorY, railX, screenWidth) {
324
- if (cardRows.length === 0 || viewportRows.length === 0)
388
+ if (!Array.isArray(viewportRows))
389
+ return [];
390
+ if (!Array.isArray(cardRows) ||
391
+ cardRows.length === 0 ||
392
+ viewportRows.length === 0 ||
393
+ !Number.isFinite(anchorY) ||
394
+ !Number.isFinite(railX) ||
395
+ !Number.isFinite(screenWidth) ||
396
+ screenWidth <= 0) {
325
397
  return viewportRows;
398
+ }
399
+ const safeAnchorY = Math.floor(anchorY);
400
+ const safeRailX = Math.max(0, Math.floor(railX));
401
+ const safeScreenWidth = Math.floor(screenWidth);
326
402
  const cardWidth = visibleWidth(cardRows[0] || '');
327
403
  // Clamp card placement horizontally: flush-left with transcript baseline at column 3
328
404
  const cardSpacing = 2; // railX + 2 gives x = 3, perfectly flush left with transcript content
329
- let x = railX - cardWidth - 1;
330
- if (x < 0 || (railX <= 4 && railX + cardSpacing + cardWidth <= screenWidth)) {
331
- x = Math.max(0, Math.min(screenWidth - cardWidth - 1, railX + cardSpacing));
405
+ let x = safeRailX - cardWidth - 1;
406
+ if (safeRailX <= 4 && safeRailX + cardSpacing < safeScreenWidth) {
407
+ x = safeRailX + cardSpacing;
408
+ }
409
+ else if (x < 0) {
410
+ x = Math.max(0, Math.min(safeScreenWidth - cardWidth - 1, safeRailX + cardSpacing));
332
411
  }
412
+ const effectiveCardWidth = Math.max(1, Math.min(cardWidth, Math.max(1, safeScreenWidth - x)));
333
413
  // Center vertically around anchorY
334
- const startY = Math.max(0, Math.min(viewportRows.length - cardRows.length, anchorY - Math.floor(cardRows.length / 2)));
414
+ const startY = Math.max(0, Math.min(viewportRows.length - cardRows.length, safeAnchorY - Math.floor(cardRows.length / 2)));
335
415
  const out = viewportRows.slice();
336
416
  for (let i = 0; i < cardRows.length; i++) {
337
417
  const targetY = startY + i;
338
418
  if (targetY >= out.length)
339
419
  break;
340
420
  const baseRow = out[targetY] || '';
341
- const cardRow = cardRows[i] || '';
421
+ const rawCardRow = cardRows[i] || '';
422
+ const cardRow = visibleWidth(rawCardRow) > effectiveCardWidth
423
+ ? `${padEnd(truncate(rawCardRow, effectiveCardWidth, ''), effectiveCardWidth)}${rawCardRow.includes('\x1b[') ? '\x1b[0m' : ''}`
424
+ : rawCardRow;
342
425
  // Composite cardRow onto baseRow at column x.
343
426
  // To the left of the card, NEVER allow severed underlying characters (like '▸' or text) to leak!
344
427
  // Maintain a perfectly clean, flush, symmetrical margin:
345
428
  // Only preserve the rail dot (if present at railX) and whitespace padding up to column x.
346
429
  let beforePart = '';
347
- if (x <= 6 && railX <= 4) {
430
+ if (x <= 6 && safeRailX <= 4 && x > safeRailX) {
348
431
  const plainBase = stripAnsi(baseRow);
349
- const dotChar = plainBase[railX] || ' ';
432
+ const dotChar = plainBase[safeRailX] || ' ';
350
433
  const isDot = dotChar === '●' || dotChar === '•' || dotChar === '·';
351
434
  let dotCell = ' ';
352
435
  if (isDot) {
@@ -362,8 +445,8 @@ export function overlayTurnPreviewCard(viewportRows, cardRows, anchorY, railX, s
362
445
  dotCell = dotChar;
363
446
  }
364
447
  }
365
- const leadingSpace = ' '.repeat(Math.max(0, railX));
366
- const trailingSpace = ' '.repeat(Math.max(0, x - railX - 1));
448
+ const leadingSpace = ' '.repeat(Math.max(0, safeRailX));
449
+ const trailingSpace = ' '.repeat(Math.max(0, x - safeRailX - 1));
367
450
  beforePart = `${leadingSpace}${dotCell}${trailingSpace}`;
368
451
  }
369
452
  else {
@@ -373,14 +456,18 @@ export function overlayTurnPreviewCard(viewportRows, cardRows, anchorY, railX, s
373
456
  if (x <= 6) {
374
457
  // For left-placed turn cards, preserve the right overview rail without severed text leaks
375
458
  const rowLen = visibleWidth(baseRow);
376
- const rightCell = rowLen > 0 ? sliceFromColumn(baseRow, rowLen - 1) : ' ';
377
- const rightCellWidth = visibleWidth(rightCell);
378
- const targetWidth = Math.max(screenWidth, rowLen);
379
- const gap = Math.max(0, targetWidth - x - cardWidth - rightCellWidth);
380
- restOfRow = `${' '.repeat(gap)}${rightCell}`;
459
+ if (rowLen > x + effectiveCardWidth) {
460
+ const rightCell = sliceFromColumn(baseRow, rowLen - 1);
461
+ const rightCellWidth = visibleWidth(rightCell);
462
+ const gap = Math.max(0, rowLen - x - effectiveCardWidth - rightCellWidth);
463
+ restOfRow = `${' '.repeat(gap)}${rightCell}`;
464
+ }
465
+ else {
466
+ restOfRow = '';
467
+ }
381
468
  }
382
469
  else {
383
- restOfRow = sliceFromColumn(baseRow, x + cardWidth);
470
+ restOfRow = sliceFromColumn(baseRow, x + effectiveCardWidth);
384
471
  }
385
472
  out[targetY] = `${beforePart}${cardRow}${restOfRow}`;
386
473
  }
@@ -390,16 +477,26 @@ export function isMouseMotion(sequence) {
390
477
  const code = Number(/^\x1b\[<(\d+);/.exec(sequence || '')?.[1]);
391
478
  return Number.isFinite(code) && (code & 32) !== 0;
392
479
  }
480
+ function redrawHost(host) {
481
+ if (typeof host?.scheduleDraw === 'function')
482
+ host.scheduleDraw();
483
+ else if (typeof host?.draw === 'function')
484
+ host.draw();
485
+ }
393
486
  /**
394
487
  * Handle mouse interaction (hover and click) for the Turn Rail.
395
488
  */
396
489
  export function handleTurnRailMouse(event, surface, host) {
397
- if (!surface?.turnRailLayout || !event.mouse)
490
+ if (!surface?.turnRailLayout ||
491
+ !event?.mouse ||
492
+ !Number.isFinite(event.mouse.x) ||
493
+ !Number.isFinite(event.mouse.y)) {
398
494
  return false;
495
+ }
399
496
  const layout = surface.turnRailLayout;
400
- const mouseX = event.mouse.x;
401
- const mouseY = event.mouse.y;
402
- const stageTop = layout.stageTop ?? 0;
497
+ const mouseX = Math.floor(event.mouse.x);
498
+ const mouseY = Math.floor(event.mouse.y);
499
+ const stageTop = Number.isFinite(layout.stageTop) ? Math.floor(layout.stageTop) : 0;
403
500
  const relY = mouseY - stageTop;
404
501
  // Rail hit box: if railX <= 4, check columns 0..5 (left margin); otherwise check [railX - 2, railX + 3]
405
502
  const isRail = layout.railX <= 4
@@ -439,15 +536,15 @@ export function handleTurnRailMouse(event, surface, host) {
439
536
  if (!surface._turnCardLeaveTimer) {
440
537
  surface._turnCardLeaveTimer = setTimeout(() => {
441
538
  surface._turnCardLeaveTimer = null;
539
+ if (surface.stage?.reserved === false)
540
+ return;
442
541
  if (surface.hoveredTurnIndex !== null && surface.hoveredTurnIndex !== undefined) {
443
542
  surface.hoveredTurnIndex = null;
444
543
  surface.hoveredTurnAnchorY = null;
445
- if (typeof host?.scheduleDraw === 'function')
446
- host.scheduleDraw();
447
- else if (typeof host?.draw === 'function')
448
- host.draw();
544
+ redrawHost(host);
449
545
  }
450
546
  }, 120);
547
+ surface._turnCardLeaveTimer.unref?.();
451
548
  }
452
549
  }
453
550
  return false;
@@ -490,20 +587,14 @@ export function handleTurnRailMouse(event, surface, host) {
490
587
  if (surface.hoveredTurnIndex !== null && surface.hoveredTurnIndex !== undefined) {
491
588
  surface.hoveredTurnIndex = null;
492
589
  surface.hoveredTurnAnchorY = null;
493
- if (typeof host?.scheduleDraw === 'function')
494
- host.scheduleDraw();
495
- else if (typeof host?.draw === 'function')
496
- host.draw();
590
+ redrawHost(host);
497
591
  }
498
592
  return true;
499
593
  }
500
594
  if (surface.hoveredTurnIndex !== turnNum) {
501
595
  surface.hoveredTurnIndex = turnNum;
502
596
  surface.hoveredTurnAnchorY = anchorY;
503
- if (typeof host?.scheduleDraw === 'function')
504
- host.scheduleDraw();
505
- else if (typeof host?.draw === 'function')
506
- host.draw();
597
+ redrawHost(host);
507
598
  }
508
599
  return true;
509
600
  }
@@ -528,6 +619,7 @@ export function handleTurnRailMouse(event, surface, host) {
528
619
  surface._turnRailSuppressTimer = setTimeout(() => {
529
620
  surface.turnRailHoverSuppressed = false;
530
621
  }, 400);
622
+ surface._turnRailSuppressTimer.unref?.();
531
623
  if (typeof host?.draw === 'function')
532
624
  host.draw();
533
625
  else if (typeof host?.scheduleDraw === 'function')
@@ -538,10 +630,7 @@ export function handleTurnRailMouse(event, surface, host) {
538
630
  else if (surface.hoveredTurnIndex !== null && surface.hoveredTurnIndex !== undefined) {
539
631
  surface.hoveredTurnIndex = null;
540
632
  surface.hoveredTurnAnchorY = null;
541
- if (typeof host?.scheduleDraw === 'function')
542
- host.scheduleDraw();
543
- else if (typeof host?.draw === 'function')
544
- host.draw();
633
+ redrawHost(host);
545
634
  }
546
635
  return false;
547
636
  }