Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/cli/src/gemini.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ import { DualOutputContext } from './dualOutput/DualOutputContext.js';
import { RemoteInputWatcher } from './remoteInput/RemoteInputWatcher.js';
import { RemoteInputContext } from './remoteInput/RemoteInputContext.js';
import { installTerminalRedrawOptimizer } from './ui/utils/terminalRedrawOptimizer.js';
import { installSynchronizedOutput } from './ui/utils/synchronizedOutput.js';

const debugLogger = createDebugLogger('STARTUP');

Expand Down Expand Up @@ -174,6 +175,10 @@ export async function startInteractiveUI(
process.stdout.isTTY && !config.getScreenReader()
? installTerminalRedrawOptimizer(process.stdout)
: () => {};
const restoreSynchronizedOutput =
process.stdout.isTTY && !config.getScreenReader()
? installSynchronizedOutput(process.stdout)
: () => {};

// Create dual output bridge if --json-fd or --json-file is specified.
// Errors are caught so a bad fd/path degrades gracefully instead of
Expand Down Expand Up @@ -297,6 +302,7 @@ export async function startInteractiveUI(
// operational, preventing garbled terminal output after the app exits.
disableKittyProtocol();
instance.unmount();
restoreSynchronizedOutput();
restoreTerminalRedrawOptimizer();
});
}
Expand Down
78 changes: 78 additions & 0 deletions packages/cli/src/ui/AppContainer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
} from 'vitest';
import { render, cleanup } from 'ink-testing-library';
import { AppContainer, dedupeNewestFirst } from './AppContainer.js';
import ansiEscapes from 'ansi-escapes';
import {
type Config,
makeFakeConfig,
Expand Down Expand Up @@ -426,6 +427,83 @@ describe('AppContainer State Management', () => {
}).not.toThrow();
});

it('refreshStatic clears the terminal before remounting history', () => {
render(
<AppContainer
config={mockConfig}
settings={mockSettings}
version="1.0.0"
initializationResult={mockInitResult}
/>,
);

capturedUIActions.refreshStatic();

expect(mockStdout.write).toHaveBeenCalledWith(ansiEscapes.clearTerminal);
});

it('handleClearScreen avoids a second clearTerminal write', () => {
const clearSpy = vi.spyOn(console, 'clear').mockImplementation(() => {});

render(
<AppContainer
config={mockConfig}
settings={mockSettings}
version="1.0.0"
initializationResult={mockInitResult}
/>,
);

capturedUIActions.handleClearScreen();

expect(clearSpy).toHaveBeenCalledTimes(1);
expect(mockStdout.write).not.toHaveBeenCalledWith(
ansiEscapes.clearTerminal,
);

clearSpy.mockRestore();
});

it('passes a remount-only refresh callback to slash commands', () => {
let slashRefreshStatic: (() => void) | undefined;
mockedUseSlashCommandProcessor.mockImplementation(
(
_config,
_settings,
_addItem,
_clearItems,
_loadHistory,
refreshStatic,
) => {
slashRefreshStatic = refreshStatic;
return {
handleSlashCommand: vi.fn(),
slashCommands: [],
pendingHistoryItems: [],
commandContext: {},
shellConfirmationRequest: null,
confirmationRequest: null,
};
},
);

render(
<AppContainer
config={mockConfig}
settings={mockSettings}
version="1.0.0"
initializationResult={mockInitResult}
/>,
);

slashRefreshStatic?.();

expect(slashRefreshStatic).toBeDefined();
expect(mockStdout.write).not.toHaveBeenCalledWith(
ansiEscapes.clearTerminal,
);
});

it('provides ConfigContext with config object', () => {
expect(() => {
render(
Expand Down
14 changes: 9 additions & 5 deletions packages/cli/src/ui/AppContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -478,10 +478,14 @@ export const AppContainer = (props: AppContainerProps) => {
fetchUserMessages();
}, [historyManager.history, logger]);

const remountStaticHistory = useCallback(() => {
setHistoryRemountKey((prev) => prev + 1);
}, []);

const refreshStatic = useCallback(() => {
stdout.write(ansiEscapes.clearTerminal);
setHistoryRemountKey((prev) => prev + 1);
}, [setHistoryRemountKey, stdout]);
remountStaticHistory();
}, [remountStaticHistory, stdout]);

const {
isThemeDialogOpen,
Expand Down Expand Up @@ -704,7 +708,7 @@ export const AppContainer = (props: AppContainerProps) => {
historyManager.addItem,
historyManager.clearItems,
historyManager.loadHistory,
refreshStatic,
remountStaticHistory,
toggleVimEnabled,
isProcessing,
setIsProcessing,
Expand Down Expand Up @@ -1242,8 +1246,8 @@ export const AppContainer = (props: AppContainerProps) => {
const handleClearScreen = useCallback(() => {
historyManager.clearItems();
clearScreen();
refreshStatic();
}, [historyManager, refreshStatic]);
remountStaticHistory();
}, [historyManager, remountStaticHistory]);

const { handleInput: vimHandleInput } = useVim(buffer, handleFinalSubmit);

Expand Down
70 changes: 70 additions & 0 deletions packages/cli/src/ui/components/messages/ToolMessage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,76 @@ describe('<ToolMessage />', () => {
expect(output).toContain('line 30');
});

it('pre-slices large non-shell string output before MaxSizedBox layout', () => {
const longString = Array.from(
{ length: 5000 },
(_, i) => `line ${i + 1}`,
).join('\n');
const { lastFrame } = renderWithContext(
<ToolMessage
{...baseProps}
name="some-other-tool"
resultDisplay={longString}
status={ToolCallStatus.Success}
availableTerminalHeight={12}
/>,
StreamingState.Idle,
);
const output = lastFrame()!;

expect(output).toContain('... first 4995 lines hidden ...');
expect(output).not.toContain('line 4995');
expect(output).toContain('line 4996');
expect(output).toContain('line 4997');
expect(output).toContain('line 4998');
expect(output).toContain('line 4999');
expect(output).toContain('line 5000');
});

it('pre-slices single-line output by visual width before MaxSizedBox layout', () => {
const longSingleLine = Array.from({ length: 1000 }, (_, i) =>
String(i % 10),
).join('');
const { lastFrame } = renderWithContext(
<ToolMessage
{...baseProps}
name="some-other-tool"
contentWidth={20}
resultDisplay={longSingleLine}
status={ToolCallStatus.Success}
availableTerminalHeight={12}
/>,
StreamingState.Idle,
);
const output = lastFrame()!;

expect(output).toMatch(/\.\.\. first \d+ lin/);
expect(output).not.toContain(longSingleLine);
expect(output).toContain(longSingleLine.slice(-10));
});

it('does not pre-slice string output that exactly fits available height', () => {
const exactFitString = Array.from(
{ length: 6 },
(_, i) => `line ${i + 1}`,
).join('\n');
const { lastFrame } = renderWithContext(
<ToolMessage
{...baseProps}
name="some-other-tool"
resultDisplay={exactFitString}
status={ToolCallStatus.Success}
availableTerminalHeight={12}
/>,
StreamingState.Idle,
);
const output = lastFrame()!;

expect(output).not.toContain('lines hidden');
expect(output).toContain('line 1');
expect(output).toContain('line 6');
});

it.each([
['negative', -1],
['fractional', 1.5],
Expand Down
76 changes: 73 additions & 3 deletions packages/cli/src/ui/components/messages/ToolMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { DiffRenderer } from './DiffRenderer.js';
import { MarkdownDisplay } from '../../utils/MarkdownDisplay.js';
import { AnsiOutputText, ShellStatsBar } from '../AnsiOutput.js';
import type { ShellStatsBarProps } from '../AnsiOutput.js';
import { MaxSizedBox } from '../shared/MaxSizedBox.js';
import { MaxSizedBox, MINIMUM_MAX_HEIGHT } from '../shared/MaxSizedBox.js';
import { TodoDisplay } from '../TodoDisplay.js';
import type {
TodoResultDisplay,
Expand All @@ -31,6 +31,7 @@ import { theme } from '../../semantic-colors.js';
import { useSettings } from '../../contexts/SettingsContext.js';
import type { LoadedSettings } from '../../../config/settings.js';
import { useCompactMode } from '../../contexts/CompactModeContext.js';
import { getCachedStringWidth, toCodePoints } from '../../utils/textUtils.js';

import {
ToolStatusIndicator,
Expand All @@ -48,6 +49,65 @@ const DEFAULT_SHELL_OUTPUT_MAX_LINES = 5;
const MAXIMUM_RESULT_DISPLAY_CHARACTERS = 1000000;
export type TextEmphasis = 'high' | 'medium' | 'low';

function sliceTextForMaxHeight(
text: string,
maxHeight: number | undefined,
maxWidth: number,
): { text: string; hiddenLinesCount: number } {
if (maxHeight === undefined) {
return { text, hiddenLinesCount: 0 };
}

const targetMaxHeight = Math.max(Math.round(maxHeight), MINIMUM_MAX_HEIGHT);
const visibleContentHeight = targetMaxHeight - 1;
const visualWidth = Math.max(1, Math.floor(maxWidth));
const visibleLines: string[] = [];
let visualLineCount = 0;
let currentLine = '';
let currentLineWidth = 0;

const appendVisibleLine = (line: string) => {
visualLineCount += 1;
visibleLines.push(line);
if (visibleLines.length > visibleContentHeight) {
visibleLines.shift();
}
};

const flushCurrentLine = () => {
appendVisibleLine(currentLine);
currentLine = '';
currentLineWidth = 0;
};

for (const char of toCodePoints(text)) {
if (char === '\n') {
flushCurrentLine();
continue;
}

const charWidth = Math.max(getCachedStringWidth(char), 1);
if (currentLineWidth > 0 && currentLineWidth + charWidth > visualWidth) {
flushCurrentLine();
}

currentLine += char;
currentLineWidth += charWidth;
}

flushCurrentLine();

if (visualLineCount <= targetMaxHeight) {
return { text, hiddenLinesCount: 0 };
}

const hiddenLinesCount = visualLineCount - visibleContentHeight;
return {
text: visibleLines.join('\n'),
hiddenLinesCount,
};
}

type DisplayRendererResult =
| { type: 'none' }
| { type: 'todo'; data: TodoResultDisplay }
Expand Down Expand Up @@ -234,11 +294,21 @@ const StringResultRenderer: React.FC<{
);
}

const sliced = sliceTextForMaxHeight(
displayData,
availableHeight,
childWidth,
);
Comment on lines +297 to +301

Copilot AI Apr 24, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

String pre-slicing walks the entire output (codepoints + width measurement). Called directly during render, this can become expensive if parent re-renders while displayData is large. Memoizing the slice (e.g., via useMemo keyed on displayData, availableHeight, and childWidth) would avoid repeated full scans when inputs are unchanged.

Copilot uses AI. Check for mistakes.

return (
<MaxSizedBox maxHeight={availableHeight} maxWidth={childWidth}>
<MaxSizedBox
maxHeight={availableHeight}
maxWidth={childWidth}
additionalHiddenLinesCount={sliced.hiddenLinesCount}
>
<Box>
<Text wrap="wrap" color={theme.text.primary}>
{displayData}
{sliced.text}
</Text>
</Box>
</MaxSizedBox>
Expand Down
Loading
Loading