@causyne/agent 1.20.53 → 1.20.55

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.53",
3
+ "version": "1.20.55",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
@@ -18,8 +18,78 @@ const MUTATING_TOOLS = new Set([
18
18
  'fs_write', 'fs_edit', 'MultiEdit', 'fs_delete', 'fs_move', 'sysRun', 'sysRunBg',
19
19
  'gitOp', 'manage_local_dependencies', 'plugin_manage', 'tool_forge', 'plugins_factory', 'create_skill',
20
20
  'write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content',
21
- 'write', 'edit', 'multiedit', 'bash', 'terminal', 'execute'
21
+ 'write', 'edit', 'multiedit', 'bash', 'terminal', 'execute', 'run_command'
22
22
  ]);
23
+ function splitCommandSegments(command) {
24
+ const segments = [];
25
+ let current = '';
26
+ let inSingle = false;
27
+ let inDouble = false;
28
+ let escape = false;
29
+ for (let i = 0; i < command.length; i++) {
30
+ const ch = command[i];
31
+ if (escape) {
32
+ current += ch;
33
+ escape = false;
34
+ continue;
35
+ }
36
+ if (ch === '\\') {
37
+ escape = true;
38
+ current += ch;
39
+ continue;
40
+ }
41
+ if (ch === "'" && !inDouble) {
42
+ inSingle = !inSingle;
43
+ current += ch;
44
+ continue;
45
+ }
46
+ if (ch === '"' && !inSingle) {
47
+ inDouble = !inDouble;
48
+ current += ch;
49
+ continue;
50
+ }
51
+ if (!inSingle && !inDouble) {
52
+ if (ch === ';') {
53
+ if (current.trim())
54
+ segments.push(current.trim());
55
+ current = '';
56
+ continue;
57
+ }
58
+ if (ch === '&' && command[i + 1] === '&') {
59
+ if (current.trim())
60
+ segments.push(current.trim());
61
+ current = '';
62
+ i++;
63
+ continue;
64
+ }
65
+ if (ch === '|' && command[i + 1] === '|') {
66
+ if (current.trim())
67
+ segments.push(current.trim());
68
+ current = '';
69
+ i++;
70
+ continue;
71
+ }
72
+ }
73
+ current += ch;
74
+ }
75
+ if (current.trim())
76
+ segments.push(current.trim());
77
+ return segments;
78
+ }
79
+ const READ_ONLY_CMD_REGEX = /^\s*(?:(?:pwd|ls|find|rg|grep|cat|sed|awk|head|tail|wc|diff|file|stat|which|whereis|type|du|df|pdfinfo|pdftotext|identify|mediainfo|ffprobe|otool|readelf|nm|ps|lsof|top|uptime|whoami|id|uname|env|printenv|echo|printf|pytest)\b|git\s+(?:status|diff|log|show|branch|tag|remote|rev-parse|describe)\b|npm\s+(?:view|audit|test|ls|list|explain|run\s+(?:test|check|lint|typecheck|verify))\b|pnpm\s+(?:test|view|audit|ls|list|run\s+(?:test|check|lint|typecheck|verify))\b|yarn\s+(?:test|audit|list|run\s+(?:test|check|lint|typecheck|verify))\b|bun\s+(?:test|pm)\b|npx\s+(?:jest|vitest|mocha|ava|playwright\s+test|cypress\s+run|tsc\s+--noEmit)\b|tsc\s+--noEmit\b|node\s+(?:--check|--test|-e\b|--eval\b|-p\b|--print\b|.*?(?:test|spec|verify|check))|(?:python3?|py)\s+(?:-m\s+(?:unittest|pytest|doctest|py_compile)|-c\b|.*?(?:test|spec|verify))|cargo\s+(?:test|check)\b|go\s+test\b|curl\s+(?:-I|-sI|-s\b|--head)\b)/i;
80
+ export function isReadOnlyShellCommand(command) {
81
+ const trimmed = command.trim();
82
+ if (!trimmed)
83
+ return true;
84
+ const segments = splitCommandSegments(trimmed);
85
+ return segments.length > 0 && segments.every(seg => {
86
+ const s = seg.trim();
87
+ if (!s)
88
+ return true;
89
+ const stripped = s.replace(/^(?:[a-zA-Z_][a-zA-Z0-9_]*=[^\s]+\s+)+/, '');
90
+ return READ_ONLY_CMD_REGEX.test(stripped);
91
+ });
92
+ }
23
93
  function containsAny(text, terms) {
24
94
  return terms.some(term => text.includes(term));
25
95
  }
@@ -68,9 +138,9 @@ export function isMutatingToolCall(toolName, args = {}) {
68
138
  if (toolName === 'native_engine')
69
139
  return !['status', 'catalog', 'describe', 'inspect', 'probe'].includes(String(args.action ?? ''));
70
140
  if (MUTATING_TOOLS.has(toolName)) {
71
- if (['sysRun', 'sysRunBg', 'bash', 'terminal', 'execute', 'sh', 'zsh'].includes(toolName)) {
141
+ if (['sysRun', 'sysRunBg', 'bash', 'terminal', 'execute', 'sh', 'zsh', 'run_command'].includes(toolName)) {
72
142
  const command = String(args.command ?? args.cmd ?? '');
73
- return !/^\s*(?:pwd|ls|find|rg|grep|cat|sed|head|tail|git\s+(?:status|diff|log|show)|npm\s+(?:view|audit|test)|node\s+--check)\b/i.test(command);
143
+ return !isReadOnlyShellCommand(command);
74
144
  }
75
145
  if (toolName === 'gitOp') {
76
146
  const action = String(args.action ?? args.command ?? args.operation ?? '');
@@ -52,9 +52,77 @@ const MUTATING_TOOLS = new Set([
52
52
  'fs_write', 'fs_edit', 'MultiEdit', 'fs_delete', 'fs_move', 'sysRun', 'sysRunBg',
53
53
  'gitOp', 'manage_local_dependencies', 'plugin_manage', 'tool_forge', 'plugins_factory', 'create_skill',
54
54
  'write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content',
55
- 'write', 'edit', 'multiedit', 'bash', 'terminal', 'execute'
55
+ 'write', 'edit', 'multiedit', 'bash', 'terminal', 'execute', 'run_command'
56
56
  ]);
57
57
 
58
+ function splitCommandSegments(command: string): string[] {
59
+ const segments: string[] = [];
60
+ let current = '';
61
+ let inSingle = false;
62
+ let inDouble = false;
63
+ let escape = false;
64
+
65
+ for (let i = 0; i < command.length; i++) {
66
+ const ch = command[i]!;
67
+ if (escape) {
68
+ current += ch;
69
+ escape = false;
70
+ continue;
71
+ }
72
+ if (ch === '\\') {
73
+ escape = true;
74
+ current += ch;
75
+ continue;
76
+ }
77
+ if (ch === "'" && !inDouble) {
78
+ inSingle = !inSingle;
79
+ current += ch;
80
+ continue;
81
+ }
82
+ if (ch === '"' && !inSingle) {
83
+ inDouble = !inDouble;
84
+ current += ch;
85
+ continue;
86
+ }
87
+ if (!inSingle && !inDouble) {
88
+ if (ch === ';') {
89
+ if (current.trim()) segments.push(current.trim());
90
+ current = '';
91
+ continue;
92
+ }
93
+ if (ch === '&' && command[i + 1] === '&') {
94
+ if (current.trim()) segments.push(current.trim());
95
+ current = '';
96
+ i++;
97
+ continue;
98
+ }
99
+ if (ch === '|' && command[i + 1] === '|') {
100
+ if (current.trim()) segments.push(current.trim());
101
+ current = '';
102
+ i++;
103
+ continue;
104
+ }
105
+ }
106
+ current += ch;
107
+ }
108
+ if (current.trim()) segments.push(current.trim());
109
+ return segments;
110
+ }
111
+
112
+ const READ_ONLY_CMD_REGEX = /^\s*(?:(?:pwd|ls|find|rg|grep|cat|sed|awk|head|tail|wc|diff|file|stat|which|whereis|type|du|df|pdfinfo|pdftotext|identify|mediainfo|ffprobe|otool|readelf|nm|ps|lsof|top|uptime|whoami|id|uname|env|printenv|echo|printf|pytest)\b|git\s+(?:status|diff|log|show|branch|tag|remote|rev-parse|describe)\b|npm\s+(?:view|audit|test|ls|list|explain|run\s+(?:test|check|lint|typecheck|verify))\b|pnpm\s+(?:test|view|audit|ls|list|run\s+(?:test|check|lint|typecheck|verify))\b|yarn\s+(?:test|audit|list|run\s+(?:test|check|lint|typecheck|verify))\b|bun\s+(?:test|pm)\b|npx\s+(?:jest|vitest|mocha|ava|playwright\s+test|cypress\s+run|tsc\s+--noEmit)\b|tsc\s+--noEmit\b|node\s+(?:--check|--test|-e\b|--eval\b|-p\b|--print\b|.*?(?:test|spec|verify|check))|(?:python3?|py)\s+(?:-m\s+(?:unittest|pytest|doctest|py_compile)|-c\b|.*?(?:test|spec|verify))|cargo\s+(?:test|check)\b|go\s+test\b|curl\s+(?:-I|-sI|-s\b|--head)\b)/i;
113
+
114
+ export function isReadOnlyShellCommand(command: string): boolean {
115
+ const trimmed = command.trim();
116
+ if (!trimmed) return true;
117
+ const segments = splitCommandSegments(trimmed);
118
+ return segments.length > 0 && segments.every(seg => {
119
+ const s = seg.trim();
120
+ if (!s) return true;
121
+ const stripped = s.replace(/^(?:[a-zA-Z_][a-zA-Z0-9_]*=[^\s]+\s+)+/, '');
122
+ return READ_ONLY_CMD_REGEX.test(stripped);
123
+ });
124
+ }
125
+
58
126
  function containsAny(text: string, terms: readonly string[]): boolean {
59
127
  return terms.some(term => text.includes(term));
60
128
  }
@@ -107,9 +175,9 @@ export function isMutatingToolCall(toolName: string, args: Record<string, unknow
107
175
  }
108
176
  if (toolName === 'native_engine') return !['status', 'catalog', 'describe', 'inspect', 'probe'].includes(String(args.action ?? ''));
109
177
  if (MUTATING_TOOLS.has(toolName)) {
110
- if (['sysRun', 'sysRunBg', 'bash', 'terminal', 'execute', 'sh', 'zsh'].includes(toolName)) {
178
+ if (['sysRun', 'sysRunBg', 'bash', 'terminal', 'execute', 'sh', 'zsh', 'run_command'].includes(toolName)) {
111
179
  const command = String(args.command ?? args.cmd ?? '');
112
- return !/^\s*(?:pwd|ls|find|rg|grep|cat|sed|head|tail|git\s+(?:status|diff|log|show)|npm\s+(?:view|audit|test)|node\s+--check)\b/i.test(command);
180
+ return !isReadOnlyShellCommand(command);
113
181
  }
114
182
  if (toolName === 'gitOp') {
115
183
  const action = String(args.action ?? args.command ?? args.operation ?? '');
@@ -28,6 +28,7 @@ import { activityRows } from './activityLayout.js';
28
28
  import { cleanToolOutputPreview, normalizeHistoricalToolResult, normalizeHistoricalExternalAction } from './toolOutputNormalizer.js';
29
29
  import { formatMarkdownMath } from './markdownMath.js';
30
30
  import { renderThinkingFrame } from './thinkingBox.js';
31
+ import { measureMessages, resolveCharPool } from '../contextManager.js';
31
32
 
32
33
  // Bound the preview AFTER wrapping, not by source newlines: one 400 KB line of
33
34
  // minified output would otherwise become thousands of rows and lock the
@@ -566,6 +567,11 @@ export class ChatRenderer {
566
567
  if (info.messagesCount === undefined || info.messagesCount === null) {
567
568
  info.messagesCount = messages.filter(m => m && m.role !== 'system').length;
568
569
  }
570
+ const measuredChars = measureMessages(messages);
571
+ if (measuredChars > 0) {
572
+ this.status.contextChars = measuredChars;
573
+ info.contextChars = measuredChars;
574
+ }
569
575
 
570
576
  if (info.title || info.id) {
571
577
  this.renderSessionDivider(info);
@@ -704,6 +710,21 @@ export class ChatRenderer {
704
710
  }
705
711
  }
706
712
 
713
+ const finalMeasured = measureMessages(messages);
714
+ if (finalMeasured > 0) {
715
+ this.status.contextChars = finalMeasured;
716
+ }
717
+ if (!this.status.contextLimit) {
718
+ this.status.contextLimit = resolveCharPool(this.status.tier);
719
+ }
720
+ if (sessionInfo) {
721
+ this.status.setSession({
722
+ ...sessionInfo,
723
+ contextChars: this.status.contextChars || finalMeasured,
724
+ contextLimit: sessionInfo.contextLimit || this.status.contextLimit
725
+ });
726
+ }
727
+
707
728
  if (this.transcript?.surface?.viewport) {
708
729
  this.transcript.surface.viewport.manual = false;
709
730
  this.transcript.surface.viewport.unseen = 0;
@@ -2,6 +2,7 @@ import { ChatRenderer } from './chatRenderer.js';
2
2
  import { CODE_PANEL_LINES, codePreviewLineCount, defaultPreviewStart, renderCodeProgress } from './codeProgress.js';
3
3
  import { calculateThinkingLineCount, DEFAULT_MAX_EXPANDED_LINES } from './thinkingBox.js';
4
4
  import { markerAt } from './messageInteraction.js';
5
+ import { AdaptiveWheelDampener } from './scrollInteraction.js';
5
6
  function lastStart(event) {
6
7
  return Math.max(0, codePreviewLineCount(event) - CODE_PANEL_LINES);
7
8
  }
@@ -32,7 +33,13 @@ export class CodeStreamRenderer extends ChatRenderer {
32
33
  const limit = lastStart(state.event);
33
34
  if (limit === 0)
34
35
  return false;
35
- const next = Math.max(0, Math.min(limit, state.start + (wheel.direction === 'up' ? -3 : 3)));
36
+ if (!state.dampener) {
37
+ state.dampener = new AdaptiveWheelDampener();
38
+ }
39
+ const delta = state.dampener.stepRows(wheel.direction, 3);
40
+ if (delta === 0)
41
+ return true;
42
+ const next = Math.max(0, Math.min(limit, state.start + (wheel.direction === 'up' ? -delta : delta)));
36
43
  if (next === state.start)
37
44
  return true;
38
45
  state.start = next;
@@ -65,8 +72,15 @@ export class CodeStreamRenderer extends ChatRenderer {
65
72
  const limit = Math.max(0, totalLines - DEFAULT_MAX_EXPANDED_LINES);
66
73
  if (limit === 0)
67
74
  return false;
75
+ if (!frame.meta._dampener) {
76
+ frame.meta._dampener = new AdaptiveWheelDampener();
77
+ }
78
+ const dampener = frame.meta._dampener;
79
+ const delta = dampener.stepRows(wheel.direction, 3);
80
+ if (delta === 0)
81
+ return true;
68
82
  const currentStart = Number(frame.meta.scrollStart) || 0;
69
- const next = Math.max(0, Math.min(limit, currentStart + (wheel.direction === 'up' ? -3 : 3)));
83
+ const next = Math.max(0, Math.min(limit, currentStart + (wheel.direction === 'up' ? -delta : delta)));
70
84
  if (next === currentStart)
71
85
  return true;
72
86
  frame.meta.scrollStart = next;
@@ -2,9 +2,16 @@ import { ChatRenderer } from './chatRenderer.js';
2
2
  import { CODE_PANEL_LINES, codePreviewLineCount, defaultPreviewStart, renderCodeProgress, type CodeProgressEvent } from './codeProgress.js';
3
3
  import { calculateThinkingLineCount, DEFAULT_MAX_EXPANDED_LINES } from './thinkingBox.js';
4
4
  import { markerAt } from './messageInteraction.js';
5
+ import { AdaptiveWheelDampener } from './scrollInteraction.js';
5
6
 
6
7
  type RendererEvent = { type: string; [key: string]: unknown };
7
- type CodePanelState = { event: CodeProgressEvent; modelNote: string; start: number; followTail: boolean };
8
+ type CodePanelState = {
9
+ event: CodeProgressEvent;
10
+ modelNote: string;
11
+ start: number;
12
+ followTail: boolean;
13
+ dampener?: AdaptiveWheelDampener;
14
+ };
8
15
  type CodeFrame = { id: number; meta?: Record<string, unknown> | null; rows?: string[] | null; renderedWidth?: number; produce?: (width: number) => string[] };
9
16
  type CodeTranscript = {
10
17
  frames: CodeFrame[];
@@ -50,7 +57,13 @@ export class CodeStreamRenderer extends ChatRenderer {
50
57
  const limit = lastStart(state.event);
51
58
  if (limit === 0) return false;
52
59
 
53
- const next = Math.max(0, Math.min(limit, state.start + (wheel.direction === 'up' ? -3 : 3)));
60
+ if (!state.dampener) {
61
+ state.dampener = new AdaptiveWheelDampener();
62
+ }
63
+ const delta = state.dampener.stepRows(wheel.direction as 'up' | 'down', 3);
64
+ if (delta === 0) return true;
65
+
66
+ const next = Math.max(0, Math.min(limit, state.start + (wheel.direction === 'up' ? -delta : delta)));
54
67
  if (next === state.start) return true;
55
68
 
56
69
  state.start = next;
@@ -82,8 +95,15 @@ export class CodeStreamRenderer extends ChatRenderer {
82
95
  const limit = Math.max(0, totalLines - DEFAULT_MAX_EXPANDED_LINES);
83
96
  if (limit === 0) return false;
84
97
 
98
+ if (!frame.meta._dampener) {
99
+ frame.meta._dampener = new AdaptiveWheelDampener();
100
+ }
101
+ const dampener = frame.meta._dampener as AdaptiveWheelDampener;
102
+ const delta = dampener.stepRows(wheel.direction as 'up' | 'down', 3);
103
+ if (delta === 0) return true;
104
+
85
105
  const currentStart = Number(frame.meta.scrollStart) || 0;
86
- const next = Math.max(0, Math.min(limit, currentStart + (wheel.direction === 'up' ? -3 : 3)));
106
+ const next = Math.max(0, Math.min(limit, currentStart + (wheel.direction === 'up' ? -delta : delta)));
87
107
  if (next === currentStart) return true;
88
108
 
89
109
  frame.meta.scrollStart = next;
package/src/tui/prompt.js CHANGED
@@ -920,11 +920,11 @@ export class ChatPrompt {
920
920
  if (key.name === 'wheel') {
921
921
  if (!viewport || !key.wheel) return true;
922
922
  if (this.renderer?.scrollCodePanel?.(key, this.surface)) {
923
- this.draw();
923
+ if (typeof this.scheduleDraw === 'function') this.scheduleDraw(); else this.draw();
924
924
  return true;
925
925
  }
926
926
  if (this.renderer?.scrollThinkingPanel?.(key, this.surface)) {
927
- this.draw();
927
+ if (typeof this.scheduleDraw === 'function') this.scheduleDraw(); else this.draw();
928
928
  return true;
929
929
  }
930
930
 
@@ -7,13 +7,95 @@
7
7
  // preventing terminal scrollback desync and UI freezes.
8
8
  // 4. Scrollbar (rail) mouse interactions clamp cleanly even if clicked above or
9
9
  // below the chat box bounds.
10
+ /**
11
+ * Adaptive Wheel Dampener & Momentum Controller.
12
+ *
13
+ * Distinguishes single mechanical mouse wheel notches (e.g. 1 notch every 100ms+)
14
+ * from high-frequency macOS trackpad / Magic Mouse continuous event streams (10-100Hz).
15
+ *
16
+ * For single notches, full discrete step is preserved.
17
+ * For continuous trackpad streams, velocity is smoothly damped via sub-line accumulation
18
+ * so a natural finger swipe advances smoothly without exploding into runaway flight.
19
+ * Direction reversals provide instant braking to prevent momentum drift.
20
+ */
21
+ export class AdaptiveWheelDampener {
22
+ minDamping;
23
+ thresholdMs;
24
+ minTickInterval;
25
+ burstWindowMs;
26
+ maxBurstNotches;
27
+ lastTick = 0;
28
+ lastDirection = null;
29
+ rowAccumulator = 0;
30
+ recentBursts = [];
31
+ constructor(options = {}) {
32
+ this.minDamping = options.minDamping ?? 0.28;
33
+ this.thresholdMs = options.thresholdMs ?? 85;
34
+ this.minTickInterval = options.minTickInterval ?? 6;
35
+ this.burstWindowMs = options.burstWindowMs ?? 120;
36
+ this.maxBurstNotches = options.maxBurstNotches ?? 5.0;
37
+ }
38
+ /**
39
+ * Compute adaptive fractional notch multiplier for viewports that possess
40
+ * their own sub-row accumulator (e.g. Viewport).
41
+ */
42
+ computeNotches(direction, now = Date.now()) {
43
+ if (this.lastDirection && this.lastDirection !== direction) {
44
+ this.recentBursts = [];
45
+ this.lastTick = 0;
46
+ this.rowAccumulator = 0;
47
+ }
48
+ this.lastDirection = direction;
49
+ const gap = this.lastTick ? Math.max(0, now - this.lastTick) : Infinity;
50
+ this.lastTick = now;
51
+ if (gap === Infinity || gap > 150) {
52
+ this.recentBursts = [];
53
+ return 1.0;
54
+ }
55
+ if (gap < this.minTickInterval) {
56
+ return 1.0;
57
+ }
58
+ let damping = Math.max(this.minDamping, Math.min(1.0, gap / this.thresholdMs));
59
+ const windowStart = now - this.burstWindowMs;
60
+ this.recentBursts = this.recentBursts.filter(b => b.time >= windowStart);
61
+ const windowNotches = this.recentBursts.reduce((sum, b) => sum + b.notches, 0);
62
+ if (windowNotches >= this.maxBurstNotches) {
63
+ damping = Math.min(damping, 0.15);
64
+ }
65
+ this.recentBursts.push({ time: now, notches: damping });
66
+ return damping;
67
+ }
68
+ /**
69
+ * Compute whole integer row steps for widgets without internal sub-row accumulators
70
+ * (e.g. Code panel and Thinking box previews).
71
+ */
72
+ stepRows(direction, baseSpeed = 3, now = Date.now()) {
73
+ const notch = this.computeNotches(direction, now);
74
+ this.rowAccumulator += baseSpeed * notch;
75
+ const whole = Math.trunc(this.rowAccumulator);
76
+ if (whole !== 0) {
77
+ this.rowAccumulator -= whole;
78
+ return whole;
79
+ }
80
+ return 0;
81
+ }
82
+ reset() {
83
+ this.lastTick = 0;
84
+ this.lastDirection = null;
85
+ this.rowAccumulator = 0;
86
+ this.recentBursts = [];
87
+ }
88
+ }
89
+ export const defaultViewportDampener = new AdaptiveWheelDampener();
10
90
  /**
11
91
  * Handle mouse wheel scrolling with full viewport containment.
12
92
  * Replaces the buggy overscroll release with clean boundary saturation.
13
93
  */
14
- export function handleViewportWheel(key, viewport, surface, host) {
94
+ export function handleViewportWheel(key, viewport, surface, host, now = Date.now()) {
15
95
  if (!viewport || !key.wheel)
16
96
  return true;
97
+ if (key.wheel.direction !== 'up' && key.wheel.direction !== 'down')
98
+ return true;
17
99
  // Auto-heal: If the surface was ever detached, immediately re-capture mouse
18
100
  // so the session stays responsive and never freezes.
19
101
  if (surface && typeof surface.captureMouse === 'function' && surface.detached) {
@@ -26,10 +108,16 @@ export function handleViewportWheel(key, viewport, surface, host) {
26
108
  if (surface) {
27
109
  surface.activeTurnIndex = null;
28
110
  }
29
- // Pure isolated scrolling: clamp strictly inside [0, maxScrollTop]
30
- viewport.wheel(key.wheel.direction === 'down' ? 'down' : 'up');
31
- // Immediately draw updated viewport
32
- host.draw();
111
+ const dir = key.wheel.direction === 'down' ? 'down' : 'up';
112
+ const notches = defaultViewportDampener.computeNotches(dir, now);
113
+ viewport.wheel(dir, notches, now);
114
+ // Coalesce redraws to prevent terminal buffer flooding and latency pileup
115
+ if (typeof host.scheduleDraw === 'function') {
116
+ host.scheduleDraw();
117
+ }
118
+ else {
119
+ host.draw();
120
+ }
33
121
  return true;
34
122
  }
35
123
  /**
@@ -79,6 +79,107 @@ export interface PromptScrollHost {
79
79
  } | null;
80
80
  }
81
81
 
82
+ export interface WheelDampenerOptions {
83
+ minDamping?: number;
84
+ thresholdMs?: number;
85
+ minTickInterval?: number;
86
+ burstWindowMs?: number;
87
+ maxBurstNotches?: number;
88
+ }
89
+
90
+ /**
91
+ * Adaptive Wheel Dampener & Momentum Controller.
92
+ *
93
+ * Distinguishes single mechanical mouse wheel notches (e.g. 1 notch every 100ms+)
94
+ * from high-frequency macOS trackpad / Magic Mouse continuous event streams (10-100Hz).
95
+ *
96
+ * For single notches, full discrete step is preserved.
97
+ * For continuous trackpad streams, velocity is smoothly damped via sub-line accumulation
98
+ * so a natural finger swipe advances smoothly without exploding into runaway flight.
99
+ * Direction reversals provide instant braking to prevent momentum drift.
100
+ */
101
+ export class AdaptiveWheelDampener {
102
+ readonly minDamping: number;
103
+ readonly thresholdMs: number;
104
+ readonly minTickInterval: number;
105
+ readonly burstWindowMs: number;
106
+ readonly maxBurstNotches: number;
107
+ private lastTick = 0;
108
+ private lastDirection: 'up' | 'down' | null = null;
109
+ private rowAccumulator = 0;
110
+ private recentBursts: Array<{ time: number; notches: number }> = [];
111
+
112
+ constructor(options: WheelDampenerOptions = {}) {
113
+ this.minDamping = options.minDamping ?? 0.28;
114
+ this.thresholdMs = options.thresholdMs ?? 85;
115
+ this.minTickInterval = options.minTickInterval ?? 6;
116
+ this.burstWindowMs = options.burstWindowMs ?? 120;
117
+ this.maxBurstNotches = options.maxBurstNotches ?? 5.0;
118
+ }
119
+
120
+ /**
121
+ * Compute adaptive fractional notch multiplier for viewports that possess
122
+ * their own sub-row accumulator (e.g. Viewport).
123
+ */
124
+ computeNotches(direction: 'up' | 'down', now: number = Date.now()): number {
125
+ if (this.lastDirection && this.lastDirection !== direction) {
126
+ this.recentBursts = [];
127
+ this.lastTick = 0;
128
+ this.rowAccumulator = 0;
129
+ }
130
+ this.lastDirection = direction;
131
+
132
+ const gap = this.lastTick ? Math.max(0, now - this.lastTick) : Infinity;
133
+ this.lastTick = now;
134
+
135
+ if (gap === Infinity || gap > 150) {
136
+ this.recentBursts = [];
137
+ return 1.0;
138
+ }
139
+
140
+ if (gap < this.minTickInterval) {
141
+ return 1.0;
142
+ }
143
+
144
+ let damping = Math.max(this.minDamping, Math.min(1.0, gap / this.thresholdMs));
145
+
146
+ const windowStart = now - this.burstWindowMs;
147
+ this.recentBursts = this.recentBursts.filter(b => b.time >= windowStart);
148
+ const windowNotches = this.recentBursts.reduce((sum, b) => sum + b.notches, 0);
149
+
150
+ if (windowNotches >= this.maxBurstNotches) {
151
+ damping = Math.min(damping, 0.15);
152
+ }
153
+
154
+ this.recentBursts.push({ time: now, notches: damping });
155
+ return damping;
156
+ }
157
+
158
+ /**
159
+ * Compute whole integer row steps for widgets without internal sub-row accumulators
160
+ * (e.g. Code panel and Thinking box previews).
161
+ */
162
+ stepRows(direction: 'up' | 'down', baseSpeed: number = 3, now: number = Date.now()): number {
163
+ const notch = this.computeNotches(direction, now);
164
+ this.rowAccumulator += baseSpeed * notch;
165
+ const whole = Math.trunc(this.rowAccumulator);
166
+ if (whole !== 0) {
167
+ this.rowAccumulator -= whole;
168
+ return whole;
169
+ }
170
+ return 0;
171
+ }
172
+
173
+ reset(): void {
174
+ this.lastTick = 0;
175
+ this.lastDirection = null;
176
+ this.rowAccumulator = 0;
177
+ this.recentBursts = [];
178
+ }
179
+ }
180
+
181
+ export const defaultViewportDampener = new AdaptiveWheelDampener();
182
+
82
183
  /**
83
184
  * Handle mouse wheel scrolling with full viewport containment.
84
185
  * Replaces the buggy overscroll release with clean boundary saturation.
@@ -87,9 +188,11 @@ export function handleViewportWheel(
87
188
  key: KeyEvent,
88
189
  viewport: ViewportContract | null | undefined,
89
190
  surface: SurfaceContract | null | undefined,
90
- host: PromptScrollHost
191
+ host: PromptScrollHost,
192
+ now: number = Date.now()
91
193
  ): boolean {
92
194
  if (!viewport || !key.wheel) return true;
195
+ if (key.wheel.direction !== 'up' && key.wheel.direction !== 'down') return true;
93
196
 
94
197
  // Auto-heal: If the surface was ever detached, immediately re-capture mouse
95
198
  // so the session stays responsive and never freezes.
@@ -105,11 +208,16 @@ export function handleViewportWheel(
105
208
  (surface as any).activeTurnIndex = null;
106
209
  }
107
210
 
108
- // Pure isolated scrolling: clamp strictly inside [0, maxScrollTop]
109
- viewport.wheel(key.wheel.direction === 'down' ? 'down' : 'up');
211
+ const dir: 'up' | 'down' = key.wheel.direction === 'down' ? 'down' : 'up';
212
+ const notches = defaultViewportDampener.computeNotches(dir, now);
213
+ viewport.wheel(dir, notches, now);
110
214
 
111
- // Immediately draw updated viewport
112
- host.draw();
215
+ // Coalesce redraws to prevent terminal buffer flooding and latency pileup
216
+ if (typeof host.scheduleDraw === 'function') {
217
+ host.scheduleDraw();
218
+ } else {
219
+ host.draw();
220
+ }
113
221
  return true;
114
222
  }
115
223
 
@@ -41,11 +41,9 @@ export function sessionSidebarRows(facts, height) {
41
41
  styled(bold('Context'));
42
42
  const limit = Number.isFinite(facts.contextLimit) ? Number(facts.contextLimit) : 0;
43
43
  const used = Number.isFinite(facts.contextChars) ? Number(facts.contextChars) : 0;
44
- if (limit > 0) {
44
+ if (limit > 0 && used > 0) {
45
45
  const rawPercent = (used / limit) * 100;
46
- const percent = used > 0
47
- ? Math.max(1, Math.min(100, Math.round(rawPercent)))
48
- : 0;
46
+ const percent = Math.max(1, Math.min(100, Math.round(rawPercent)));
49
47
  styled(dim(`${percent}% of available window`));
50
48
  }
51
49
  else {
@@ -56,11 +56,9 @@ export function sessionSidebarRows(facts: SidebarFacts, height: number): string[
56
56
  styled(bold('Context'));
57
57
  const limit = Number.isFinite(facts.contextLimit) ? Number(facts.contextLimit) : 0;
58
58
  const used = Number.isFinite(facts.contextChars) ? Number(facts.contextChars) : 0;
59
- if (limit > 0) {
59
+ if (limit > 0 && used > 0) {
60
60
  const rawPercent = (used / limit) * 100;
61
- const percent = used > 0
62
- ? Math.max(1, Math.min(100, Math.round(rawPercent)))
63
- : 0;
61
+ const percent = Math.max(1, Math.min(100, Math.round(rawPercent)));
64
62
  styled(dim(`${percent}% of available window`));
65
63
  } else {
66
64
  styled(dim('No context measurement yet'));