Skip to content
14 changes: 12 additions & 2 deletions packages/cli/src/ui/AppContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2685,12 +2685,22 @@ export const AppContainer = (props: AppContainerProps) => {
// agentViewState is declared earlier (before handleFinalSubmit) so it
// is available for input routing. Referenced here for layout computation.
const tabBarHeight = agentViewState.agents.size > 0 ? 1 : 0;
// `staticExtraHeight` (3) is pure <Static>-region overhead — meaningless in
// VP mode, which owns the viewport through the React tree and clips natively,
// so dropping it lets the composer sink to (near) the bottom instead of
// stranding ~5 blank rows beneath it. `MAIN_CONTENT_HEIGHT_RESERVATION` (2)
// stays in VP as a small slack: `controlsHeight` is measured one frame late
// (useLayoutEffect), so when the composer grows (multi-line input) the prior,
// smaller height would briefly oversize the list and overflow the terminal —
// the exact jitter this change set out to remove. Non-VP keeps both.
const mainContentHeightReservation = useTerminalBuffer
? MAIN_CONTENT_HEIGHT_RESERVATION
: staticExtraHeight + MAIN_CONTENT_HEIGHT_RESERVATION;
const availableTerminalHeight = Math.max(
0,
terminalHeight -
controlsHeight -
staticExtraHeight -
MAIN_CONTENT_HEIGHT_RESERVATION -
mainContentHeightReservation -
tabBarHeight,
);

Expand Down
16 changes: 14 additions & 2 deletions packages/cli/src/ui/components/ThinkingViewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { t } from '../../i18n/index.js';
import { AlternateScreen } from './AlternateScreen.js';
import type { ThinkingViewerData } from '../contexts/ThinkingViewerContext.js';
import { THINKING_ICON } from './messages/ConversationMessages.js';
import { wrapToVisualLines } from '../utils/textUtils.js';
import { formatDuration } from '../utils/displayUtils.js';

interface ThinkingViewerProps {
Expand All @@ -33,14 +34,25 @@ export const ThinkingViewer: FC<ThinkingViewerProps> = ({
onClose,
useAlternateScreen = true,
}) => {
const { rows } = useTerminalSize();
const { rows, columns } = useTerminalSize();
const [scrollOffset, setScrollOffset] = useState(0);

const headerHeight = 2;
const footerHeight = 2;
const contentHeight = Math.max(rows - headerHeight - footerHeight, 1);

const lines = useMemo(() => data.text.split('\n'), [data.text]);
// The thought text is frequently a single long paragraph with no explicit
// newlines. Splitting on '\n' alone yields one logical line that, rendered
// with `wrap="truncate-end"`, collapsed to a single ellipsised row above an
// empty box (and `maxScroll` stayed 0, so it could not scroll). Pre-wrap to
// visual rows at the inner content width — border (1 each side) + paddingX
// (1 each side) = 4 columns — so scrolling and rendering operate on the same
// rows the user actually sees.
const contentWidth = Math.max(1, columns - 4);
const lines = useMemo(
() => wrapToVisualLines(data.text, contentWidth),
[data.text, contentWidth],
);
const maxScroll = Math.max(0, lines.length - contentHeight);

useEffect(() => {
Expand Down
34 changes: 1 addition & 33 deletions packages/cli/src/ui/components/messages/ConversationMessages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
SCREEN_READER_USER_PREFIX,
} from '../../textConstants.js';
import { t } from '../../../i18n/index.js';
import { getCachedStringWidth } from '../../utils/textUtils.js';
import { wrapToVisualLines } from '../../utils/textUtils.js';
import { formatDuration } from '../../utils/displayUtils.js';

export const THINKING_ICON = '∴ ';
Expand Down Expand Up @@ -264,38 +264,6 @@ export const AssistantMessageContent: React.FC<

const MAX_STREAMING_THINKING_VISUAL_LINES = 4;

function wrapToVisualLines(text: string, width: number): string[] {
if (width <= 0) {
return [''];
}
const visualLines: string[] = [];
for (const logicalLine of text.split('\n')) {
if (logicalLine === '') {
visualLines.push('');
continue;
}
let currentLine = '';
let currentWidth = 0;
for (const char of logicalLine) {
const charWidth = getCachedStringWidth(char);
if (currentWidth + charWidth > width && currentWidth > 0) {
visualLines.push(currentLine);
currentLine = '';
currentWidth = 0;
}
currentLine += char;
currentWidth += charWidth;
}
if (currentLine) {
visualLines.push(currentLine);
}
}
if (visualLines.length === 0) {
visualLines.push('');
}
return visualLines;
}

function tailVisualLines(
text: string,
width: number,
Expand Down
113 changes: 95 additions & 18 deletions packages/cli/src/ui/components/shared/ScrollableList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@
* SPDX-License-Identifier: Apache-2.0
*/

import { useRef, forwardRef, useImperativeHandle, useCallback } from 'react';
import {
useRef,
forwardRef,
useImperativeHandle,
useCallback,
useEffect,
} from 'react';
import type React from 'react';
import {
VirtualizedList,
Expand Down Expand Up @@ -104,31 +110,102 @@ function ScrollableList<T>(
// native scrollback. In VP mode the list owns the visible region, so route
// wheel ticks and scrollbar drags to the virtualized viewport.
const WHEEL_LINES_PER_TICK = 3;
const handleMouseEvent = useCallback((event: MouseEvent) => {
if (!virtualizedListRef.current) return;
if (event.name === 'left-release') {
isDraggingScrollbar.current = false;

// Terminal mouse reporting emits one event per row the pointer crosses, so a
// brisk wheel spin or scrollbar drag fires a rapid burst. Applying each event
// synchronously forced one Ink reflow + terminal flush per event — the source
// of the "一顿一顿" stutter. Coalesce a burst into a single viewport update per
// frame: accumulate the intent in refs and flush on a short timer. A drag is
// absolute (snap to the newest row); a wheel burst is relative (sum the
// ticks); a drag in the same window wins. Tests drive real timers and only
// await microtasks, so apply synchronously under NODE_ENV==='test' (the same
// escape hatch VirtualizedList uses for its readiness gate).
const SCROLL_FRAME_MS = 16;
const pendingWheelDelta = useRef(0);
const pendingDragRow = useRef<number | null>(null);
const flushTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

const applyPendingScroll = useCallback(() => {
flushTimer.current = null;
const list = virtualizedListRef.current;
const dragRow = pendingDragRow.current;
const wheelDelta = pendingWheelDelta.current;
pendingDragRow.current = null;
pendingWheelDelta.current = 0;
if (!list) return;
if (dragRow !== null) {
list.scrollToScrollbarRow(dragRow);
return;
}
if (event.name === 'left-press') {
isDraggingScrollbar.current =
virtualizedListRef.current.hitTestScrollbar(event);
if (isDraggingScrollbar.current) {
virtualizedListRef.current.scrollToScrollbarRow(event.row);
}
return;
if (wheelDelta !== 0) {
list.scrollBy(wheelDelta);
}
if (event.name === 'move' && isDraggingScrollbar.current) {
virtualizedListRef.current.scrollToScrollbarRow(event.row);
}, []);

const scheduleScrollFlush = useCallback(() => {
if (process.env['NODE_ENV'] === 'test') {
applyPendingScroll();
return;
}
if (event.name === 'scroll-up') {
virtualizedListRef.current.scrollBy(-WHEEL_LINES_PER_TICK);
} else if (event.name === 'scroll-down') {
virtualizedListRef.current.scrollBy(WHEEL_LINES_PER_TICK);
if (flushTimer.current !== null) return;
flushTimer.current = setTimeout(applyPendingScroll, SCROLL_FRAME_MS);
}, [applyPendingScroll]);

// Discard any queued wheel/drag intent and cancel an in-flight flush. Used
// when a scrollbar press takes over: without it, a wheel burst scheduled
// moments earlier would still fire its timer and `scrollBy` the view away
// from the row the user just clicked.
const cancelPendingScroll = useCallback(() => {
pendingWheelDelta.current = 0;
pendingDragRow.current = null;
if (flushTimer.current !== null) {
clearTimeout(flushTimer.current);
flushTimer.current = null;
}
}, []);

useEffect(
() => () => {
if (flushTimer.current !== null) clearTimeout(flushTimer.current);
},
[],
);

const handleMouseEvent = useCallback(
(event: MouseEvent) => {
if (!virtualizedListRef.current) return;
if (event.name === 'left-release') {
isDraggingScrollbar.current = false;
return;
}
if (event.name === 'left-press') {
isDraggingScrollbar.current =
virtualizedListRef.current.hitTestScrollbar(event);
if (isDraggingScrollbar.current) {
// A press should feel instant — apply now and drop any queued
// wheel/drag intent (and its timer) so a flush scheduled moments
// earlier can't yank the view off the clicked row.
cancelPendingScroll();
virtualizedListRef.current.scrollToScrollbarRow(event.row);
}
return;
}
if (event.name === 'move' && isDraggingScrollbar.current) {
pendingDragRow.current = event.row;
scheduleScrollFlush();
return;
}
if (event.name === 'scroll-up') {
pendingWheelDelta.current -= WHEEL_LINES_PER_TICK;
scheduleScrollFlush();
} else if (event.name === 'scroll-down') {
pendingWheelDelta.current += WHEEL_LINES_PER_TICK;
scheduleScrollFlush();
}
},
[scheduleScrollFlush, cancelPendingScroll],
);

useMouseEvents(handleMouseEvent, { isActive: hasFocus });

// ScrollableList is a thin keyboard / mouse wrapper around VirtualizedList.
Expand Down
23 changes: 15 additions & 8 deletions packages/cli/src/ui/components/shared/VirtualizedList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -854,15 +854,22 @@ function VirtualizedList<T>(
scrollbarThumbActive,
]);

// The host passes `containerHeight` as the *maximum* viewport height (the
// room available between the header and the composer). Pinning the root box
// to that height unconditionally left a tall empty gap below short content
// and pushed the composer far down the screen — the legacy <Static> path
// instead grows with its content. Collapse to `totalHeight` whenever the
// content fits so the composer sits right beneath the conversation; only
// when the content overflows do we clamp to `containerHeight` and let the
// viewport scroll. `scrollableContainerHeight` (the scroll math) still uses
// the full `containerHeight`, so scrolling is unaffected.
const rootHeight =
props.containerHeight !== undefined
? Math.min(props.containerHeight, totalHeight)
: '100%';

return (
<Box
ref={rootRef}
width="100%"
height={
props.containerHeight !== undefined ? props.containerHeight : '100%'
}
flexDirection="row"
>
<Box ref={rootRef} width="100%" height={rootHeight} flexDirection="row">
<Box
ref={containerRef}
overflowY="hidden"
Expand Down
39 changes: 39 additions & 0 deletions packages/cli/src/ui/utils/textUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,45 @@ export function sliceTextByVisualHeight(
};
}

/**
* Wrap text into the visual rows it occupies at `width` columns, accounting
* for both explicit newlines and code-point-width-aware soft wrapping. Unlike
* `sliceTextByVisualHeight` (which keeps only a head/tail window), this returns
* every visual row, so callers that scroll an arbitrary offset (e.g. the
* ThinkingViewer) can slice the rows the user actually sees.
*/
export function wrapToVisualLines(text: string, width: number): string[] {
if (width <= 0) {
return [''];
}
const visualLines: string[] = [];
for (const logicalLine of text.split('\n')) {
if (logicalLine === '') {
visualLines.push('');
continue;
}
let currentLine = '';
let currentWidth = 0;
for (const char of logicalLine) {
const charWidth = getCachedStringWidth(char);
if (currentWidth + charWidth > width && currentWidth > 0) {
visualLines.push(currentLine);
currentLine = '';
currentWidth = 0;
}
currentLine += char;
currentWidth += charWidth;
}
if (currentLine) {
visualLines.push(currentLine);
}
}
if (visualLines.length === 0) {
visualLines.push('');
}
return visualLines;
}

/**
* Clear the string width cache
*/
Expand Down
Loading