feat(shell): enable interactive commands with virtual terminal (#6694)

This commit is contained in:
Gal Zahavi
2025-09-11 13:27:27 -07:00
committed by GitHub
parent 8969a232ec
commit 181898cb5d
43 changed files with 2345 additions and 324 deletions

View File

@@ -56,6 +56,7 @@ export enum Command {
REVERSE_SEARCH = 'reverseSearch',
SUBMIT_REVERSE_SEARCH = 'submitReverseSearch',
ACCEPT_SUGGESTION_REVERSE_SEARCH = 'acceptSuggestionReverseSearch',
TOGGLE_SHELL_INPUT_FOCUS = 'toggleShellInputFocus',
}
/**
@@ -162,4 +163,5 @@ export const defaultKeyBindings: KeyBindingConfig = {
// Note: original logic ONLY checked ctrl=false, ignored meta/shift/paste
[Command.SUBMIT_REVERSE_SEARCH]: [{ key: 'return', ctrl: false }],
[Command.ACCEPT_SUGGESTION_REVERSE_SEARCH]: [{ key: 'tab' }],
[Command.TOGGLE_SHELL_INPUT_FOCUS]: [{ key: 'f', ctrl: true }],
};

View File

@@ -106,6 +106,8 @@ const MIGRATION_MAP: Record<string, string> = {
sandbox: 'tools.sandbox',
selectedAuthType: 'security.auth.selectedType',
shouldUseNodePtyShell: 'tools.usePty',
shellPager: 'tools.shell.pager',
shellShowColor: 'tools.shell.showColor',
skipNextSpeakerCheck: 'model.skipNextSpeakerCheck',
summarizeToolOutput: 'model.summarizeToolOutput',
telemetry: 'telemetry',

View File

@@ -649,6 +649,36 @@ const SETTINGS_SCHEMA = {
'Use node-pty for shell command execution. Fallback to child_process still applies.',
showInDialog: true,
},
shell: {
type: 'object',
label: 'Shell',
category: 'Tools',
requiresRestart: false,
default: {},
description: 'Settings for shell execution.',
showInDialog: false,
properties: {
pager: {
type: 'string',
label: 'Pager',
category: 'Tools',
requiresRestart: false,
default: 'cat' as string | undefined,
description:
'The pager command to use for shell output. Defaults to `cat`.',
showInDialog: false,
},
showColor: {
type: 'boolean',
label: 'Show Color',
category: 'Tools',
requiresRestart: false,
default: false,
description: 'Show color in shell output.',
showInDialog: true,
},
},
},
autoAccept: {
type: 'boolean',
label: 'Auto Accept',

View File

@@ -71,6 +71,7 @@ describe('ShellProcessor', () => {
getTargetDir: vi.fn().mockReturnValue('/test/dir'),
getApprovalMode: vi.fn().mockReturnValue(ApprovalMode.DEFAULT),
getShouldUseNodePtyShell: vi.fn().mockReturnValue(false),
getShellExecutionConfig: vi.fn().mockReturnValue({}),
};
context = createMockCommandContext({
@@ -147,6 +148,7 @@ describe('ShellProcessor', () => {
expect.any(Function),
expect.any(Object),
false,
expect.any(Object),
);
expect(result).toEqual([{ text: 'The current status is: On branch main' }]);
});
@@ -218,6 +220,7 @@ describe('ShellProcessor', () => {
expect.any(Function),
expect.any(Object),
false,
expect.any(Object),
);
expect(result).toEqual([{ text: 'Do something dangerous: deleted' }]);
});
@@ -410,6 +413,7 @@ describe('ShellProcessor', () => {
expect.any(Function),
expect.any(Object),
false,
expect.any(Object),
);
});
@@ -574,6 +578,7 @@ describe('ShellProcessor', () => {
expect.any(Function),
expect.any(Object),
false,
expect.any(Object),
);
expect(result).toEqual([{ text: 'Command: match found' }]);
@@ -598,6 +603,7 @@ describe('ShellProcessor', () => {
expect.any(Function),
expect.any(Object),
false,
expect.any(Object),
);
expect(result).toEqual([
@@ -668,6 +674,7 @@ describe('ShellProcessor', () => {
expect.any(Function),
expect.any(Object),
false,
expect.any(Object),
);
});
@@ -697,6 +704,7 @@ describe('ShellProcessor', () => {
expect.any(Function),
expect.any(Object),
false,
expect.any(Object),
);
});
});

View File

@@ -20,6 +20,7 @@ import {
SHORTHAND_ARGS_PLACEHOLDER,
} from './types.js';
import { extractInjections, type Injection } from './injectionParser.js';
import { themeManager } from '../../ui/themes/theme-manager.js';
export class ConfirmationRequiredError extends Error {
constructor(
@@ -159,12 +160,19 @@ export class ShellProcessor implements IPromptProcessor {
// Execute the resolved command (which already has ESCAPED input).
if (injection.resolvedCommand) {
const activeTheme = themeManager.getActiveTheme();
const shellExecutionConfig = {
...config.getShellExecutionConfig(),
defaultFg: activeTheme.colors.Foreground,
defaultBg: activeTheme.colors.Background,
};
const { result } = await ShellExecutionService.execute(
injection.resolvedCommand,
config.getTargetDir(),
() => {},
new AbortController().signal,
config.getShouldUseNodePtyShell(),
shellExecutionConfig,
);
const executionResult = await result;

View File

@@ -34,6 +34,7 @@ import {
getAllGeminiMdFilenames,
AuthType,
clearCachedCredentialFile,
ShellExecutionService,
} from '@google/gemini-cli-core';
import { validateAuthMethod } from '../config/auth.js';
import { loadHierarchicalGeminiMemory } from '../config/config.js';
@@ -97,6 +98,18 @@ interface AppContainerProps {
initializationResult: InitializationResult;
}
/**
* The fraction of the terminal width to allocate to the shell.
* This provides horizontal padding.
*/
const SHELL_WIDTH_FRACTION = 0.89;
/**
* The number of lines to subtract from the available terminal height
* for the shell. This provides vertical padding and space for other UI elements.
*/
const SHELL_HEIGHT_PADDING = 10;
export const AppContainer = (props: AppContainerProps) => {
const { settings, config, initializationResult } = props;
const historyManager = useHistory();
@@ -110,6 +123,8 @@ export const AppContainer = (props: AppContainerProps) => {
initializationResult.themeError,
);
const [isProcessing, setIsProcessing] = useState<boolean>(false);
const [shellFocused, setShellFocused] = useState(false);
const [geminiMdFileCount, setGeminiMdFileCount] = useState<number>(
initializationResult.geminiMdFileCount,
);
@@ -506,6 +521,7 @@ Logging in with Google... Please restart Gemini CLI to continue.
pendingHistoryItems: pendingGeminiHistoryItems,
thought,
cancelOngoingRequest,
activePtyId,
loopDetectionConfirmationRequest,
} = useGeminiStream(
config.getGeminiClient(),
@@ -523,6 +539,10 @@ Logging in with Google... Please restart Gemini CLI to continue.
setModelSwitchedFromQuotaError,
refreshStatic,
() => cancelHandlerRef.current(),
setShellFocused,
terminalWidth,
terminalHeight,
shellFocused,
);
const { messageQueue, addMessage, clearQueue, getQueuedMessagesText } =
@@ -603,6 +623,13 @@ Logging in with Google... Please restart Gemini CLI to continue.
return terminalHeight - staticExtraHeight;
}, [terminalHeight]);
config.setShellExecutionConfig({
terminalWidth: Math.floor(terminalWidth * SHELL_WIDTH_FRACTION),
terminalHeight: Math.floor(availableTerminalHeight - SHELL_HEIGHT_PADDING),
pager: settings.merged.tools?.shell?.pager,
showColor: settings.merged.tools?.shell?.showColor,
});
const isFocused = useFocus();
useBracketedPaste();
@@ -620,6 +647,22 @@ Logging in with Google... Please restart Gemini CLI to continue.
const initialPromptSubmitted = useRef(false);
const geminiClient = config.getGeminiClient();
useEffect(() => {
if (activePtyId) {
ShellExecutionService.resizePty(
activePtyId,
Math.floor(terminalWidth * SHELL_WIDTH_FRACTION),
Math.floor(availableTerminalHeight - SHELL_HEIGHT_PADDING),
);
}
}, [
terminalHeight,
terminalWidth,
availableTerminalHeight,
activePtyId,
geminiClient,
]);
useEffect(() => {
if (
initialPrompt &&
@@ -840,6 +883,10 @@ Logging in with Google... Please restart Gemini CLI to continue.
!enteringConstrainHeightMode
) {
setConstrainHeight(false);
} else if (keyMatchers[Command.TOGGLE_SHELL_INPUT_FOCUS](key)) {
if (activePtyId || shellFocused) {
setShellFocused((prev) => !prev);
}
}
},
[
@@ -866,6 +913,8 @@ Logging in with Google... Please restart Gemini CLI to continue.
isSettingsDialogOpen,
isFolderTrustDialogOpen,
showPrivacyNotice,
activePtyId,
shellFocused,
settings.merged.general?.debugKeystrokeLogging,
],
);
@@ -991,6 +1040,8 @@ Logging in with Google... Please restart Gemini CLI to continue.
updateInfo,
showIdeRestartPrompt,
isRestarting,
activePtyId,
shellFocused,
}),
[
historyManager.history,
@@ -1064,6 +1115,8 @@ Logging in with Google... Please restart Gemini CLI to continue.
showIdeRestartPrompt,
isRestarting,
currentModel,
activePtyId,
shellFocused,
],
);

View File

@@ -0,0 +1,106 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { render } from 'ink-testing-library';
import { AnsiOutputText } from './AnsiOutput.js';
import type { AnsiOutput, AnsiToken } from '@google/gemini-cli-core';
// Helper to create a valid AnsiToken with default values
const createAnsiToken = (overrides: Partial<AnsiToken>): AnsiToken => ({
text: '',
bold: false,
italic: false,
underline: false,
dim: false,
inverse: false,
fg: '#ffffff',
bg: '#000000',
...overrides,
});
describe('<AnsiOutputText />', () => {
it('renders a simple AnsiOutput object correctly', () => {
const data: AnsiOutput = [
[
createAnsiToken({ text: 'Hello, ' }),
createAnsiToken({ text: 'world!' }),
],
];
const { lastFrame } = render(<AnsiOutputText data={data} />);
expect(lastFrame()).toBe('Hello, world!');
});
it('correctly applies all the styles', () => {
const data: AnsiOutput = [
[
createAnsiToken({ text: 'Bold', bold: true }),
createAnsiToken({ text: 'Italic', italic: true }),
createAnsiToken({ text: 'Underline', underline: true }),
createAnsiToken({ text: 'Dim', dim: true }),
createAnsiToken({ text: 'Inverse', inverse: true }),
],
];
// Note: ink-testing-library doesn't render styles, so we can only check the text.
// We are testing that it renders without crashing.
const { lastFrame } = render(<AnsiOutputText data={data} />);
expect(lastFrame()).toBe('BoldItalicUnderlineDimInverse');
});
it('correctly applies foreground and background colors', () => {
const data: AnsiOutput = [
[
createAnsiToken({ text: 'Red FG', fg: '#ff0000' }),
createAnsiToken({ text: 'Blue BG', bg: '#0000ff' }),
],
];
// Note: ink-testing-library doesn't render colors, so we can only check the text.
// We are testing that it renders without crashing.
const { lastFrame } = render(<AnsiOutputText data={data} />);
expect(lastFrame()).toBe('Red FGBlue BG');
});
it('handles empty lines and empty tokens', () => {
const data: AnsiOutput = [
[createAnsiToken({ text: 'First line' })],
[],
[createAnsiToken({ text: 'Third line' })],
[createAnsiToken({ text: '' })],
];
const { lastFrame } = render(<AnsiOutputText data={data} />);
const output = lastFrame();
expect(output).toBeDefined();
const lines = output!.split('\n');
expect(lines[0]).toBe('First line');
expect(lines[1]).toBe('Third line');
});
it('respects the availableTerminalHeight prop and slices the lines correctly', () => {
const data: AnsiOutput = [
[createAnsiToken({ text: 'Line 1' })],
[createAnsiToken({ text: 'Line 2' })],
[createAnsiToken({ text: 'Line 3' })],
[createAnsiToken({ text: 'Line 4' })],
];
const { lastFrame } = render(
<AnsiOutputText data={data} availableTerminalHeight={2} />,
);
const output = lastFrame();
expect(output).not.toContain('Line 1');
expect(output).not.toContain('Line 2');
expect(output).toContain('Line 3');
expect(output).toContain('Line 4');
});
it('renders a large AnsiOutput object without crashing', () => {
const largeData: AnsiOutput = [];
for (let i = 0; i < 1000; i++) {
largeData.push([createAnsiToken({ text: `Line ${i}` })]);
}
const { lastFrame } = render(<AnsiOutputText data={largeData} />);
// We are just checking that it renders something without crashing.
expect(lastFrame()).toBeDefined();
});
});

View File

@@ -0,0 +1,46 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type React from 'react';
import { Text } from 'ink';
import type { AnsiLine, AnsiOutput, AnsiToken } from '@google/gemini-cli-core';
const DEFAULT_HEIGHT = 24;
interface AnsiOutputProps {
data: AnsiOutput;
availableTerminalHeight?: number;
}
export const AnsiOutputText: React.FC<AnsiOutputProps> = ({
data,
availableTerminalHeight,
}) => {
const lastLines = data.slice(
-(availableTerminalHeight && availableTerminalHeight > 0
? availableTerminalHeight
: DEFAULT_HEIGHT),
);
return lastLines.map((line: AnsiLine, lineIndex: number) => (
<Text key={lineIndex}>
{line.length > 0
? line.map((token: AnsiToken, tokenIndex: number) => (
<Text
key={tokenIndex}
color={token.inverse ? token.bg : token.fg}
backgroundColor={token.inverse ? token.fg : token.bg}
dimColor={token.dim}
bold={token.bold}
italic={token.italic}
underline={token.underline}
>
{token.text}
</Text>
))
: null}
</Text>
));
};

View File

@@ -58,20 +58,22 @@ export const Composer = () => {
return (
<Box flexDirection="column">
<LoadingIndicator
thought={
uiState.streamingState === StreamingState.WaitingForConfirmation ||
config.getAccessibility()?.disableLoadingPhrases
? undefined
: uiState.thought
}
currentLoadingPhrase={
config.getAccessibility()?.disableLoadingPhrases
? undefined
: uiState.currentLoadingPhrase
}
elapsedTime={uiState.elapsedTime}
/>
{!uiState.shellFocused && (
<LoadingIndicator
thought={
uiState.streamingState === StreamingState.WaitingForConfirmation ||
config.getAccessibility()?.disableLoadingPhrases
? undefined
: uiState.thought
}
currentLoadingPhrase={
config.getAccessibility()?.disableLoadingPhrases
? undefined
: uiState.currentLoadingPhrase
}
elapsedTime={uiState.elapsedTime}
/>
)}
{!uiState.isConfigInitialized && <ConfigInitDisplay />}
@@ -178,6 +180,7 @@ export const Composer = () => {
onEscapePromptChange={uiActions.onEscapePromptChange}
focus={uiState.isFocused}
vimHandleInput={uiActions.vimHandleInput}
isShellFocused={uiState.shellFocused}
placeholder={
vimEnabled
? " Press 'i' for INSERT mode and 'Esc' for NORMAL mode."

View File

@@ -30,6 +30,8 @@ interface HistoryItemDisplayProps {
isPending: boolean;
isFocused?: boolean;
commands?: readonly SlashCommand[];
activeShellPtyId?: number | null;
shellFocused?: boolean;
}
export const HistoryItemDisplay: React.FC<HistoryItemDisplayProps> = ({
@@ -39,6 +41,8 @@ export const HistoryItemDisplay: React.FC<HistoryItemDisplayProps> = ({
isPending,
commands,
isFocused = true,
activeShellPtyId,
shellFocused,
}) => (
<Box flexDirection="column" key={item.id}>
{/* Render standard message types */}
@@ -85,6 +89,8 @@ export const HistoryItemDisplay: React.FC<HistoryItemDisplayProps> = ({
availableTerminalHeight={availableTerminalHeight}
terminalWidth={terminalWidth}
isFocused={isFocused}
activeShellPtyId={activeShellPtyId}
shellFocused={shellFocused}
/>
)}
{item.type === 'compression' && (

View File

@@ -50,6 +50,7 @@ export interface InputPromptProps {
approvalMode: ApprovalMode;
onEscapePromptChange?: (showPrompt: boolean) => void;
vimHandleInput?: (key: Key) => boolean;
isShellFocused?: boolean;
}
export const InputPrompt: React.FC<InputPromptProps> = ({
@@ -69,6 +70,7 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
approvalMode,
onEscapePromptChange,
vimHandleInput,
isShellFocused,
}) => {
const [justNavigatedHistory, setJustNavigatedHistory] = useState(false);
const [escPressCount, setEscPressCount] = useState(0);
@@ -591,7 +593,7 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
);
useKeypress(handleInput, {
isActive: true,
isActive: !isShellFocused,
});
const linesToRender = buffer.viewportVisualLines;

View File

@@ -54,6 +54,8 @@ export const MainContent = () => {
item={{ ...item, id: 0 }}
isPending={true}
isFocused={!uiState.isEditorDialogOpen}
activeShellPtyId={uiState.activePtyId}
shellFocused={uiState.shellFocused}
/>
))}
<ShowMoreLines constrainHeight={uiState.constrainHeight} />

View File

@@ -0,0 +1,57 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { useCallback } from 'react';
import type React from 'react';
import { useKeypress } from '../hooks/useKeypress.js';
import { ShellExecutionService } from '@google/gemini-cli-core';
import { keyToAnsi, type Key } from '../hooks/keyToAnsi.js';
export interface ShellInputPromptProps {
activeShellPtyId: number | null;
focus?: boolean;
}
export const ShellInputPrompt: React.FC<ShellInputPromptProps> = ({
activeShellPtyId,
focus = true,
}) => {
const handleShellInputSubmit = useCallback(
(input: string) => {
if (activeShellPtyId) {
ShellExecutionService.writeToPty(activeShellPtyId, input);
}
},
[activeShellPtyId],
);
const handleInput = useCallback(
(key: Key) => {
if (!focus || !activeShellPtyId) {
return;
}
if (key.ctrl && key.shift && key.name === 'up') {
ShellExecutionService.scrollPty(activeShellPtyId, -1);
return;
}
if (key.ctrl && key.shift && key.name === 'down') {
ShellExecutionService.scrollPty(activeShellPtyId, 1);
return;
}
const ansiSequence = keyToAnsi(key);
if (ansiSequence) {
handleShellInputSubmit(ansiSequence);
}
},
[focus, handleShellInputSubmit, activeShellPtyId],
);
useKeypress(handleInput, { isActive: focus });
return null;
};

View File

@@ -21,6 +21,9 @@ interface ToolGroupMessageProps {
availableTerminalHeight?: number;
terminalWidth: number;
isFocused?: boolean;
activeShellPtyId?: number | null;
shellFocused?: boolean;
onShellInputSubmit?: (input: string) => void;
}
// Main component renders the border and maps the tools using ToolMessage
@@ -29,14 +32,26 @@ export const ToolGroupMessage: React.FC<ToolGroupMessageProps> = ({
availableTerminalHeight,
terminalWidth,
isFocused = true,
activeShellPtyId,
shellFocused,
}) => {
const config = useConfig();
const isShellFocused =
shellFocused &&
toolCalls.some(
(t) =>
t.ptyId === activeShellPtyId && t.status === ToolCallStatus.Executing,
);
const hasPending = !toolCalls.every(
(t) => t.status === ToolCallStatus.Success,
);
const config = useConfig();
const isShellCommand = toolCalls.some((t) => t.name === SHELL_COMMAND_NAME);
const borderColor =
hasPending || isShellCommand ? theme.status.warning : theme.border.default;
hasPending || isShellCommand || isShellFocused
? theme.status.warning
: theme.border.default;
const staticHeight = /* border */ 2 + /* marginBottom */ 1;
// This is a bit of a magic number, but it accounts for the border and
@@ -89,12 +104,7 @@ export const ToolGroupMessage: React.FC<ToolGroupMessageProps> = ({
<Box key={tool.callId} flexDirection="column" minHeight={1}>
<Box flexDirection="row" alignItems="center">
<ToolMessage
callId={tool.callId}
name={tool.name}
description={tool.description}
resultDisplay={tool.resultDisplay}
status={tool.status}
confirmationDetails={tool.confirmationDetails}
{...tool}
availableTerminalHeight={availableTerminalHeightPerToolMessage}
terminalWidth={innerWidth}
emphasis={
@@ -104,7 +114,9 @@ export const ToolGroupMessage: React.FC<ToolGroupMessageProps> = ({
? 'low'
: 'medium'
}
renderOutputAsMarkdown={tool.renderOutputAsMarkdown}
activeShellPtyId={activeShellPtyId}
shellFocused={shellFocused}
config={config}
/>
</Box>
{tool.status === ToolCallStatus.Confirming &&

View File

@@ -11,6 +11,31 @@ import { ToolMessage } from './ToolMessage.js';
import { StreamingState, ToolCallStatus } from '../../types.js';
import { Text } from 'ink';
import { StreamingContext } from '../../contexts/StreamingContext.js';
import type { AnsiOutput } from '@google/gemini-cli-core';
vi.mock('../TerminalOutput.js', () => ({
TerminalOutput: function MockTerminalOutput({
cursor,
}: {
cursor: { x: number; y: number } | null;
}) {
return (
<Text>
MockCursor:({cursor?.x},{cursor?.y})
</Text>
);
},
}));
vi.mock('../AnsiOutput.js', () => ({
AnsiOutputText: function MockAnsiOutputText({ data }: { data: AnsiOutput }) {
// Simple serialization for snapshot stability
const serialized = data
.map((line) => line.map((token) => token.text || '').join(''))
.join('\n');
return <Text>MockAnsiOutput:{serialized}</Text>;
},
}));
// Mock child components or utilities if they are complex or have side effects
vi.mock('../GeminiRespondingSpinner.js', () => ({
@@ -181,4 +206,26 @@ describe('<ToolMessage />', () => {
// We can at least ensure it doesn't have the high emphasis indicator.
expect(lowEmphasisFrame()).not.toContain('←');
});
it('renders AnsiOutputText for AnsiOutput results', () => {
const ansiResult: AnsiOutput = [
[
{
text: 'hello',
fg: '#ffffff',
bg: '#000000',
bold: false,
italic: false,
underline: false,
dim: false,
inverse: false,
},
],
];
const { lastFrame } = renderWithContext(
<ToolMessage {...baseProps} resultDisplay={ansiResult} />,
StreamingState.Idle,
);
expect(lastFrame()).toContain('MockAnsiOutput:hello');
});
});

View File

@@ -10,10 +10,13 @@ import type { IndividualToolCallDisplay } from '../../types.js';
import { ToolCallStatus } from '../../types.js';
import { DiffRenderer } from './DiffRenderer.js';
import { MarkdownDisplay } from '../../utils/MarkdownDisplay.js';
import { AnsiOutputText } from '../AnsiOutput.js';
import { GeminiRespondingSpinner } from '../GeminiRespondingSpinner.js';
import { MaxSizedBox } from '../shared/MaxSizedBox.js';
import { TOOL_STATUS } from '../../constants.js';
import { ShellInputPrompt } from '../ShellInputPrompt.js';
import { SHELL_COMMAND_NAME, TOOL_STATUS } from '../../constants.js';
import { theme } from '../../semantic-colors.js';
import type { AnsiOutput, Config } from '@google/gemini-cli-core';
const STATIC_HEIGHT = 1;
const RESERVED_LINE_COUNT = 5; // for tool name, status, padding etc.
@@ -30,6 +33,9 @@ export interface ToolMessageProps extends IndividualToolCallDisplay {
terminalWidth: number;
emphasis?: TextEmphasis;
renderOutputAsMarkdown?: boolean;
activeShellPtyId?: number | null;
shellFocused?: boolean;
config?: Config;
}
export const ToolMessage: React.FC<ToolMessageProps> = ({
@@ -41,7 +47,17 @@ export const ToolMessage: React.FC<ToolMessageProps> = ({
terminalWidth,
emphasis = 'medium',
renderOutputAsMarkdown = true,
activeShellPtyId,
shellFocused,
ptyId,
config,
}) => {
const isThisShellFocused =
(name === SHELL_COMMAND_NAME || name === 'Shell') &&
status === ToolCallStatus.Executing &&
ptyId === activeShellPtyId &&
shellFocused;
const availableHeight = availableTerminalHeight
? Math.max(
availableTerminalHeight - STATIC_HEIGHT - RESERVED_LINE_COUNT,
@@ -74,12 +90,17 @@ export const ToolMessage: React.FC<ToolMessageProps> = ({
description={description}
emphasis={emphasis}
/>
{isThisShellFocused && (
<Box marginLeft={1}>
<Text color={theme.text.accent}>[Focused]</Text>
</Box>
)}
{emphasis === 'high' && <TrailingIndicator />}
</Box>
{resultDisplay && (
<Box paddingLeft={STATUS_INDICATOR_WIDTH} width="100%" marginTop={1}>
<Box flexDirection="column">
{typeof resultDisplay === 'string' && renderOutputAsMarkdown && (
{typeof resultDisplay === 'string' && renderOutputAsMarkdown ? (
<Box flexDirection="column">
<MarkdownDisplay
text={resultDisplay}
@@ -88,25 +109,37 @@ export const ToolMessage: React.FC<ToolMessageProps> = ({
terminalWidth={childWidth}
/>
</Box>
)}
{typeof resultDisplay === 'string' && !renderOutputAsMarkdown && (
) : typeof resultDisplay === 'string' && !renderOutputAsMarkdown ? (
<MaxSizedBox maxHeight={availableHeight} maxWidth={childWidth}>
<Box>
<Text wrap="wrap">{resultDisplay}</Text>
</Box>
</MaxSizedBox>
)}
{typeof resultDisplay !== 'string' && (
) : typeof resultDisplay === 'object' &&
!Array.isArray(resultDisplay) ? (
<DiffRenderer
diffContent={resultDisplay.fileDiff}
filename={resultDisplay.fileName}
availableTerminalHeight={availableHeight}
terminalWidth={childWidth}
/>
) : (
<AnsiOutputText
data={resultDisplay as AnsiOutput}
availableTerminalHeight={availableHeight}
/>
)}
</Box>
</Box>
)}
{isThisShellFocused && config && (
<Box paddingLeft={STATUS_INDICATOR_WIDTH} marginTop={1}>
<ShellInputPrompt
activeShellPtyId={activeShellPtyId ?? null}
focus={shellFocused}
/>
</Box>
)}
</Box>
);
};

View File

@@ -108,6 +108,8 @@ export interface UIState {
updateInfo: UpdateObject | null;
showIdeRestartPrompt: boolean;
isRestarting: boolean;
activePtyId: number | undefined;
shellFocused: boolean;
}
export const UIStateContext = createContext<UIState | null>(null);

View File

@@ -0,0 +1,77 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type { Key } from '../contexts/KeypressContext.js';
export type { Key };
/**
* Translates a Key object into its corresponding ANSI escape sequence.
* This is useful for sending control characters to a pseudo-terminal.
*
* @param key The Key object to translate.
* @returns The ANSI escape sequence as a string, or null if no mapping exists.
*/
export function keyToAnsi(key: Key): string | null {
if (key.ctrl) {
// Ctrl + letter
if (key.name >= 'a' && key.name <= 'z') {
return String.fromCharCode(
key.name.charCodeAt(0) - 'a'.charCodeAt(0) + 1,
);
}
// Other Ctrl combinations might need specific handling
switch (key.name) {
case 'c':
return '\x03'; // ETX (End of Text), commonly used for interrupt
// Add other special ctrl cases if needed
default:
break;
}
}
// Arrow keys and other special keys
switch (key.name) {
case 'up':
return '\x1b[A';
case 'down':
return '\x1b[B';
case 'right':
return '\x1b[C';
case 'left':
return '\x1b[D';
case 'escape':
return '\x1b';
case 'tab':
return '\t';
case 'backspace':
return '\x7f';
case 'delete':
return '\x1b[3~';
case 'home':
return '\x1b[H';
case 'end':
return '\x1b[F';
case 'pageup':
return '\x1b[5~';
case 'pagedown':
return '\x1b[6~';
default:
break;
}
// Enter/Return
if (key.name === 'return') {
return '\r';
}
// If it's a simple character, return it.
if (!key.ctrl && !key.meta && key.sequence) {
return key.sequence;
}
return null;
}

View File

@@ -53,6 +53,8 @@ describe('useShellCommandProcessor', () => {
let mockShellOutputCallback: (event: ShellOutputEvent) => void;
let resolveExecutionPromise: (result: ShellExecutionResult) => void;
let setShellInputFocusedMock: Mock;
beforeEach(() => {
vi.clearAllMocks();
@@ -60,9 +62,14 @@ describe('useShellCommandProcessor', () => {
setPendingHistoryItemMock = vi.fn();
onExecMock = vi.fn();
onDebugMessageMock = vi.fn();
setShellInputFocusedMock = vi.fn();
mockConfig = {
getTargetDir: () => '/test/dir',
getShouldUseNodePtyShell: () => false,
getShellExecutionConfig: () => ({
terminalHeight: 20,
terminalWidth: 80,
}),
} as Config;
mockGeminiClient = { addHistory: vi.fn() } as unknown as GeminiClient;
@@ -76,12 +83,12 @@ describe('useShellCommandProcessor', () => {
mockShellExecutionService.mockImplementation((_cmd, _cwd, callback) => {
mockShellOutputCallback = callback;
return {
return Promise.resolve({
pid: 12345,
result: new Promise((resolve) => {
resolveExecutionPromise = resolve;
}),
};
});
});
});
@@ -94,6 +101,7 @@ describe('useShellCommandProcessor', () => {
onDebugMessageMock,
mockConfig,
mockGeminiClient,
setShellInputFocusedMock,
),
);
@@ -139,6 +147,7 @@ describe('useShellCommandProcessor', () => {
expect.any(Function),
expect.any(Object),
false,
expect.any(Object),
);
expect(onExecMock).toHaveBeenCalledWith(expect.any(Promise));
});
@@ -172,6 +181,7 @@ describe('useShellCommandProcessor', () => {
}),
);
expect(mockGeminiClient.addHistory).toHaveBeenCalled();
expect(setShellInputFocusedMock).toHaveBeenCalledWith(false);
});
it('should handle command failure and display error status', async () => {
@@ -198,6 +208,7 @@ describe('useShellCommandProcessor', () => {
'Command exited with code 127',
);
expect(finalHistoryItem.tools[0].resultDisplay).toContain('not found');
expect(setShellInputFocusedMock).toHaveBeenCalledWith(false);
});
describe('UI Streaming and Throttling', () => {
@@ -208,7 +219,7 @@ describe('useShellCommandProcessor', () => {
vi.useRealTimers();
});
it('should throttle pending UI updates for text streams', async () => {
it('should throttle pending UI updates for text streams (non-interactive)', async () => {
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand(
@@ -217,6 +228,26 @@ describe('useShellCommandProcessor', () => {
);
});
// Verify it's using the non-pty shell
const wrappedCommand = `{ stream; }; __code=$?; pwd > "${path.join(
os.tmpdir(),
'shell_pwd_abcdef.tmp',
)}"; exit $__code`;
expect(mockShellExecutionService).toHaveBeenCalledWith(
wrappedCommand,
'/test/dir',
expect.any(Function),
expect.any(Object),
false, // usePty
expect.any(Object),
);
// Wait for the async PID update to happen.
await vi.waitFor(() => {
// It's called once for initial, and once for the PID update.
expect(setPendingHistoryItemMock).toHaveBeenCalledTimes(2);
});
// Simulate rapid output
act(() => {
mockShellOutputCallback({
@@ -224,28 +255,49 @@ describe('useShellCommandProcessor', () => {
chunk: 'hello',
});
});
// The count should still be 2, as throttling is in effect.
expect(setPendingHistoryItemMock).toHaveBeenCalledTimes(2);
// Should not have updated the UI yet
expect(setPendingHistoryItemMock).toHaveBeenCalledTimes(1); // Only the initial call
// Advance time and send another event to trigger the throttled update
await act(async () => {
await vi.advanceTimersByTimeAsync(OUTPUT_UPDATE_INTERVAL_MS + 1);
});
// Simulate more rapid output
act(() => {
mockShellOutputCallback({
type: 'data',
chunk: ' world',
});
});
// Should now have been called with the cumulative output
expect(setPendingHistoryItemMock).toHaveBeenCalledTimes(2);
expect(setPendingHistoryItemMock).toHaveBeenLastCalledWith(
expect.objectContaining({
tools: [expect.objectContaining({ resultDisplay: 'hello world' })],
}),
);
// Advance time, but the update won't happen until the next event
await act(async () => {
await vi.advanceTimersByTimeAsync(OUTPUT_UPDATE_INTERVAL_MS + 1);
});
// Trigger one more event to cause the throttled update to fire.
act(() => {
mockShellOutputCallback({
type: 'data',
chunk: '',
});
});
// Now the cumulative update should have occurred.
// Call 1: Initial, Call 2: PID update, Call 3: Throttled stream update
expect(setPendingHistoryItemMock).toHaveBeenCalledTimes(3);
const streamUpdateFn = setPendingHistoryItemMock.mock.calls[2][0];
if (!streamUpdateFn || typeof streamUpdateFn !== 'function') {
throw new Error(
'setPendingHistoryItem was not called with a stream updater function',
);
}
// Get the state after the PID update to feed into the stream updater
const pidUpdateFn = setPendingHistoryItemMock.mock.calls[1][0];
const initialState = setPendingHistoryItemMock.mock.calls[0][0];
const stateAfterPid = pidUpdateFn(initialState);
const stateAfterStream = streamUpdateFn(stateAfterPid);
expect(stateAfterStream.tools[0].resultDisplay).toBe('hello world');
});
it('should show binary progress messages correctly', async () => {
@@ -269,7 +321,15 @@ describe('useShellCommandProcessor', () => {
mockShellOutputCallback({ type: 'binary_progress', bytesReceived: 0 });
});
expect(setPendingHistoryItemMock).toHaveBeenLastCalledWith(
// The state update is functional, so we test it by executing it.
const updaterFn1 = setPendingHistoryItemMock.mock.lastCall?.[0];
if (!updaterFn1) {
throw new Error('setPendingHistoryItem was not called');
}
const initialState = setPendingHistoryItemMock.mock.calls[0][0];
const stateAfterBinaryDetected = updaterFn1(initialState);
expect(stateAfterBinaryDetected).toEqual(
expect.objectContaining({
tools: [
expect.objectContaining({
@@ -290,7 +350,12 @@ describe('useShellCommandProcessor', () => {
});
});
expect(setPendingHistoryItemMock).toHaveBeenLastCalledWith(
const updaterFn2 = setPendingHistoryItemMock.mock.lastCall?.[0];
if (!updaterFn2) {
throw new Error('setPendingHistoryItem was not called');
}
const stateAfterProgress = updaterFn2(stateAfterBinaryDetected);
expect(stateAfterProgress).toEqual(
expect.objectContaining({
tools: [
expect.objectContaining({
@@ -316,6 +381,7 @@ describe('useShellCommandProcessor', () => {
expect.any(Function),
expect.any(Object),
false,
expect.any(Object),
);
});
@@ -341,6 +407,7 @@ describe('useShellCommandProcessor', () => {
expect(finalHistoryItem.tools[0].resultDisplay).toContain(
'Command was cancelled.',
);
expect(setShellInputFocusedMock).toHaveBeenCalledWith(false);
});
it('should handle binary output result correctly', async () => {
@@ -394,6 +461,7 @@ describe('useShellCommandProcessor', () => {
type: 'error',
text: 'An unexpected error occurred: Unexpected failure',
});
expect(setShellInputFocusedMock).toHaveBeenCalledWith(false);
});
it('should handle synchronous errors during execution and clean up resources', async () => {
@@ -425,6 +493,7 @@ describe('useShellCommandProcessor', () => {
const tmpFile = path.join(os.tmpdir(), 'shell_pwd_abcdef.tmp');
// Verify that the temporary file was cleaned up
expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalledWith(tmpFile);
expect(setShellInputFocusedMock).toHaveBeenCalledWith(false);
});
describe('Directory Change Warning', () => {
@@ -473,4 +542,177 @@ describe('useShellCommandProcessor', () => {
expect(finalHistoryItem.tools[0].resultDisplay).not.toContain('WARNING');
});
});
describe('ActiveShellPtyId management', () => {
beforeEach(() => {
// The real service returns a promise that resolves with the pid and result promise
mockShellExecutionService.mockImplementation((_cmd, _cwd, callback) => {
mockShellOutputCallback = callback;
return Promise.resolve({
pid: 12345,
result: new Promise((resolve) => {
resolveExecutionPromise = resolve;
}),
});
});
});
it('should have activeShellPtyId as null initially', () => {
const { result } = renderProcessorHook();
expect(result.current.activeShellPtyId).toBeNull();
});
it('should set activeShellPtyId when a command with a PID starts', async () => {
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand('ls', new AbortController().signal);
});
await vi.waitFor(() => {
expect(result.current.activeShellPtyId).toBe(12345);
});
});
it('should update the pending history item with the ptyId', async () => {
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand('ls', new AbortController().signal);
});
await vi.waitFor(() => {
// Wait for the second call which is the functional update
expect(setPendingHistoryItemMock).toHaveBeenCalledTimes(2);
});
// The state update is functional, so we test it by executing it.
const updaterFn = setPendingHistoryItemMock.mock.lastCall?.[0];
expect(typeof updaterFn).toBe('function');
// The initial state is the first call to setPendingHistoryItem
const initialState = setPendingHistoryItemMock.mock.calls[0][0];
const stateAfterPid = updaterFn(initialState);
expect(stateAfterPid.tools[0].ptyId).toBe(12345);
});
it('should reset activeShellPtyId to null after successful execution', async () => {
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand('ls', new AbortController().signal);
});
const execPromise = onExecMock.mock.calls[0][0];
await vi.waitFor(() => {
expect(result.current.activeShellPtyId).toBe(12345);
});
act(() => {
resolveExecutionPromise(createMockServiceResult());
});
await act(async () => await execPromise);
expect(result.current.activeShellPtyId).toBeNull();
});
it('should reset activeShellPtyId to null after failed execution', async () => {
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand(
'bad-cmd',
new AbortController().signal,
);
});
const execPromise = onExecMock.mock.calls[0][0];
await vi.waitFor(() => {
expect(result.current.activeShellPtyId).toBe(12345);
});
act(() => {
resolveExecutionPromise(createMockServiceResult({ exitCode: 1 }));
});
await act(async () => await execPromise);
expect(result.current.activeShellPtyId).toBeNull();
});
it('should reset activeShellPtyId to null if execution promise rejects', async () => {
let rejectResultPromise: (reason?: unknown) => void;
mockShellExecutionService.mockImplementation(() =>
Promise.resolve({
pid: 1234_5,
result: new Promise((_, reject) => {
rejectResultPromise = reject;
}),
}),
);
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand('cmd', new AbortController().signal);
});
const execPromise = onExecMock.mock.calls[0][0];
await vi.waitFor(() => {
expect(result.current.activeShellPtyId).toBe(12345);
});
act(() => {
rejectResultPromise(new Error('Failure'));
});
await act(async () => await execPromise);
expect(result.current.activeShellPtyId).toBeNull();
});
it('should not set activeShellPtyId on synchronous execution error and should remain null', async () => {
mockShellExecutionService.mockImplementation(() => {
throw new Error('Sync Error');
});
const { result } = renderProcessorHook();
expect(result.current.activeShellPtyId).toBeNull(); // Pre-condition
act(() => {
result.current.handleShellCommand('cmd', new AbortController().signal);
});
const execPromise = onExecMock.mock.calls[0][0];
// The hook's state should not have changed to a PID
expect(result.current.activeShellPtyId).toBeNull();
await act(async () => await execPromise); // Let the promise resolve
// And it should still be null after everything is done
expect(result.current.activeShellPtyId).toBeNull();
});
it('should not set activeShellPtyId if service does not return a PID', async () => {
mockShellExecutionService.mockImplementation((_cmd, _cwd, callback) => {
mockShellOutputCallback = callback;
return Promise.resolve({
pid: undefined, // No PID
result: new Promise((resolve) => {
resolveExecutionPromise = resolve;
}),
});
});
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand('ls', new AbortController().signal);
});
// Let microtasks run
await act(async () => {});
expect(result.current.activeShellPtyId).toBeNull();
});
});
});

View File

@@ -9,8 +9,9 @@ import type {
IndividualToolCallDisplay,
} from '../types.js';
import { ToolCallStatus } from '../types.js';
import { useCallback } from 'react';
import { useCallback, useState } from 'react';
import type {
AnsiOutput,
Config,
GeminiClient,
ShellExecutionResult,
@@ -24,6 +25,7 @@ import crypto from 'node:crypto';
import path from 'node:path';
import os from 'node:os';
import fs from 'node:fs';
import { themeManager } from '../../ui/themes/theme-manager.js';
export const OUTPUT_UPDATE_INTERVAL_MS = 1000;
const MAX_OUTPUT_LENGTH = 10000;
@@ -69,7 +71,11 @@ export const useShellCommandProcessor = (
onDebugMessage: (message: string) => void,
config: Config,
geminiClient: GeminiClient,
setShellInputFocused: (value: boolean) => void,
terminalWidth?: number,
terminalHeight?: number,
) => {
const [activeShellPtyId, setActiveShellPtyId] = useState<number | null>(null);
const handleShellCommand = useCallback(
(rawQuery: PartListUnion, abortSignal: AbortSignal): boolean => {
if (typeof rawQuery !== 'string' || rawQuery.trim() === '') {
@@ -104,7 +110,7 @@ export const useShellCommandProcessor = (
resolve: (value: void | PromiseLike<void>) => void,
) => {
let lastUpdateTime = Date.now();
let cumulativeStdout = '';
let cumulativeStdout: string | AnsiOutput = '';
let isBinaryStream = false;
let binaryBytesReceived = 0;
@@ -134,18 +140,38 @@ export const useShellCommandProcessor = (
onDebugMessage(`Executing in ${targetDir}: ${commandToExecute}`);
try {
const activeTheme = themeManager.getActiveTheme();
const shellExecutionConfig = {
...config.getShellExecutionConfig(),
defaultFg: activeTheme.colors.Foreground,
defaultBg: activeTheme.colors.Background,
};
const { pid, result } = await ShellExecutionService.execute(
commandToExecute,
targetDir,
(event) => {
let shouldUpdate = false;
switch (event.type) {
case 'data':
// Do not process text data if we've already switched to binary mode.
if (isBinaryStream) break;
cumulativeStdout += event.chunk;
// PTY provides the full screen state, so we just replace.
// Child process provides chunks, so we append.
if (
typeof event.chunk === 'string' &&
typeof cumulativeStdout === 'string'
) {
cumulativeStdout += event.chunk;
} else {
cumulativeStdout = event.chunk;
shouldUpdate = true;
}
break;
case 'binary_detected':
isBinaryStream = true;
// Force an immediate UI update to show the binary detection message.
shouldUpdate = true;
break;
case 'binary_progress':
isBinaryStream = true;
@@ -157,7 +183,7 @@ export const useShellCommandProcessor = (
}
// Compute the display string based on the *current* state.
let currentDisplayOutput: string;
let currentDisplayOutput: string | AnsiOutput;
if (isBinaryStream) {
if (binaryBytesReceived > 0) {
currentDisplayOutput = `[Receiving binary output... ${formatMemoryUsage(
@@ -171,25 +197,49 @@ export const useShellCommandProcessor = (
currentDisplayOutput = cumulativeStdout;
}
// Throttle pending UI updates to avoid excessive re-renders.
if (Date.now() - lastUpdateTime > OUTPUT_UPDATE_INTERVAL_MS) {
setPendingHistoryItem({
type: 'tool_group',
tools: [
{
...initialToolDisplay,
resultDisplay: currentDisplayOutput,
},
],
// Throttle pending UI updates, but allow forced updates.
if (
shouldUpdate ||
Date.now() - lastUpdateTime > OUTPUT_UPDATE_INTERVAL_MS
) {
setPendingHistoryItem((prevItem) => {
if (prevItem?.type === 'tool_group') {
return {
...prevItem,
tools: prevItem.tools.map((tool) =>
tool.callId === callId
? { ...tool, resultDisplay: currentDisplayOutput }
: tool,
),
};
}
return prevItem;
});
lastUpdateTime = Date.now();
}
},
abortSignal,
config.getShouldUseNodePtyShell(),
shellExecutionConfig,
);
console.log(terminalHeight, terminalWidth);
executionPid = pid;
if (pid) {
setActiveShellPtyId(pid);
setPendingHistoryItem((prevItem) => {
if (prevItem?.type === 'tool_group') {
return {
...prevItem,
tools: prevItem.tools.map((tool) =>
tool.callId === callId ? { ...tool, ptyId: pid } : tool,
),
};
}
return prevItem;
});
}
result
.then((result: ShellExecutionResult) => {
@@ -269,6 +319,8 @@ export const useShellCommandProcessor = (
if (pwdFilePath && fs.existsSync(pwdFilePath)) {
fs.unlinkSync(pwdFilePath);
}
setActiveShellPtyId(null);
setShellInputFocused(false);
resolve();
});
} catch (err) {
@@ -287,7 +339,8 @@ export const useShellCommandProcessor = (
if (pwdFilePath && fs.existsSync(pwdFilePath)) {
fs.unlinkSync(pwdFilePath);
}
setActiveShellPtyId(null);
setShellInputFocused(false);
resolve(); // Resolve the promise to unblock `onExec`
}
};
@@ -306,8 +359,11 @@ export const useShellCommandProcessor = (
setPendingHistoryItem,
onExec,
geminiClient,
setShellInputFocused,
terminalHeight,
terminalWidth,
],
);
return { handleShellCommand };
return { handleShellCommand, activeShellPtyId };
};

View File

@@ -297,6 +297,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
() => {},
() => {},
80,
24,
);
},
{
@@ -459,6 +462,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
() => {},
() => {},
80,
24,
),
);
@@ -539,6 +545,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
() => {},
() => {},
80,
24,
),
);
@@ -648,6 +657,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
() => {},
() => {},
80,
24,
),
);
@@ -758,6 +770,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
() => {},
() => {},
80,
24,
),
);
@@ -888,6 +903,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
cancelSubmitSpy,
() => {},
80,
24,
),
);
@@ -901,6 +919,47 @@ describe('useGeminiStream', () => {
expect(cancelSubmitSpy).toHaveBeenCalled();
});
it('should call setShellInputFocused(false) when escape is pressed', async () => {
const setShellInputFocusedSpy = vi.fn();
const mockStream = (async function* () {
yield { type: 'content', value: 'Part 1' };
await new Promise(() => {}); // Keep stream open
})();
mockSendMessageStream.mockReturnValue(mockStream);
const { result } = renderHook(() =>
useGeminiStream(
mockConfig.getGeminiClient(),
[],
mockAddItem,
mockConfig,
mockLoadedSettings,
mockOnDebugMessage,
mockHandleSlashCommand,
false,
() => 'vscode' as EditorType,
() => {},
() => Promise.resolve(),
false,
() => {},
() => {},
vi.fn(),
setShellInputFocusedSpy, // Pass the spy here
80,
24,
),
);
// Start a query
await act(async () => {
result.current.submitQuery('test query');
});
simulateEscapeKeyPress();
expect(setShellInputFocusedSpy).toHaveBeenCalledWith(false);
});
it('should not do anything if escape is pressed when not responding', () => {
const { result } = renderTestHook();
@@ -1200,6 +1259,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
() => {},
() => {},
80,
24,
),
);
@@ -1254,6 +1316,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
() => {},
() => {},
80,
24,
),
);
@@ -1308,6 +1373,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
() => {},
() => {},
80,
24,
),
);
@@ -1360,6 +1428,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
() => {},
() => {},
80,
24,
),
);
@@ -1413,6 +1484,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
() => {},
() => {},
80,
24,
),
);
@@ -1495,6 +1569,7 @@ describe('useGeminiStream', () => {
[],
mockAddItem,
mockConfig,
mockLoadedSettings,
mockOnDebugMessage,
mockHandleSlashCommand,
false,
@@ -1505,6 +1580,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
() => {},
vi.fn(),
80,
24,
),
);
@@ -1556,6 +1634,9 @@ describe('useGeminiStream', () => {
vi.fn(), // setModelSwitched
vi.fn(), // onEditorClose
vi.fn(), // onCancelSubmit
vi.fn(), // setShellInputFocused
80, // terminalWidth
24, // terminalHeight
),
);
@@ -1624,6 +1705,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
() => {},
() => {},
80,
24,
),
);
@@ -1706,6 +1790,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
() => {},
() => {},
80,
24,
),
);
@@ -1761,6 +1848,9 @@ describe('useGeminiStream', () => {
() => {},
() => {},
() => {},
() => {},
80,
24,
),
);

View File

@@ -102,6 +102,10 @@ export const useGeminiStream = (
setModelSwitchedFromQuotaError: React.Dispatch<React.SetStateAction<boolean>>,
onEditorClose: () => void,
onCancelSubmit: () => void,
setShellInputFocused: (value: boolean) => void,
terminalWidth: number,
terminalHeight: number,
isShellFocused?: boolean,
) => {
const [initError, setInitError] = useState<string | null>(null);
const abortControllerRef = useRef<AbortController | null>(null);
@@ -141,7 +145,6 @@ export const useGeminiStream = (
}
},
config,
setPendingHistoryItem,
getPreferredEditor,
onEditorClose,
);
@@ -152,6 +155,17 @@ export const useGeminiStream = (
[toolCalls],
);
const activeToolPtyId = useMemo(() => {
const executingShellTool = toolCalls?.find(
(tc) =>
tc.status === 'executing' && tc.request.name === 'run_shell_command',
);
if (executingShellTool) {
return (executingShellTool as { pid?: number }).pid;
}
return undefined;
}, [toolCalls]);
const loopDetectedRef = useRef(false);
const [
loopDetectionConfirmationRequest,
@@ -165,15 +179,26 @@ export const useGeminiStream = (
await done;
setIsResponding(false);
}, []);
const { handleShellCommand } = useShellCommandProcessor(
const { handleShellCommand, activeShellPtyId } = useShellCommandProcessor(
addItem,
setPendingHistoryItem,
onExec,
onDebugMessage,
config,
geminiClient,
setShellInputFocused,
terminalWidth,
terminalHeight,
);
const activePtyId = activeShellPtyId || activeToolPtyId;
useEffect(() => {
if (!activePtyId) {
setShellInputFocused(false);
}
}, [activePtyId, setShellInputFocused]);
const streamingState = useMemo(() => {
if (toolCalls.some((tc) => tc.status === 'awaiting_approval')) {
return StreamingState.WaitingForConfirmation;
@@ -240,17 +265,19 @@ export const useGeminiStream = (
setPendingHistoryItem(null);
onCancelSubmit();
setIsResponding(false);
setShellInputFocused(false);
}, [
streamingState,
addItem,
setPendingHistoryItem,
onCancelSubmit,
pendingHistoryItemRef,
setShellInputFocused,
]);
useKeypress(
(key) => {
if (key.name === 'escape') {
if (key.name === 'escape' && !isShellFocused) {
cancelOngoingRequest();
}
},
@@ -1074,6 +1101,7 @@ export const useGeminiStream = (
pendingHistoryItems,
thought,
cancelOngoingRequest,
activePtyId,
loopDetectionConfirmationRequest,
};
};

View File

@@ -25,7 +25,6 @@ import { useCallback, useState, useMemo } from 'react';
import type {
HistoryItemToolGroup,
IndividualToolCallDisplay,
HistoryItemWithoutId,
} from '../types.js';
import { ToolCallStatus } from '../types.js';
@@ -46,6 +45,7 @@ export type TrackedWaitingToolCall = WaitingToolCall & {
};
export type TrackedExecutingToolCall = ExecutingToolCall & {
responseSubmittedToGemini?: boolean;
pid?: number;
};
export type TrackedCompletedToolCall = CompletedToolCall & {
responseSubmittedToGemini?: boolean;
@@ -65,9 +65,6 @@ export type TrackedToolCall =
export function useReactToolScheduler(
onComplete: (tools: CompletedToolCall[]) => Promise<void>,
config: Config,
setPendingHistoryItem: React.Dispatch<
React.SetStateAction<HistoryItemWithoutId | null>
>,
getPreferredEditor: () => EditorType | undefined,
onEditorClose: () => void,
): [TrackedToolCall[], ScheduleFn, MarkToolsAsSubmittedFn] {
@@ -77,21 +74,6 @@ export function useReactToolScheduler(
const outputUpdateHandler: OutputUpdateHandler = useCallback(
(toolCallId, outputChunk) => {
setPendingHistoryItem((prevItem) => {
if (prevItem?.type === 'tool_group') {
return {
...prevItem,
tools: prevItem.tools.map((toolDisplay) =>
toolDisplay.callId === toolCallId &&
toolDisplay.status === ToolCallStatus.Executing
? { ...toolDisplay, resultDisplay: outputChunk }
: toolDisplay,
),
};
}
return prevItem;
});
setToolCallsForDisplay((prevCalls) =>
prevCalls.map((tc) => {
if (tc.request.callId === toolCallId && tc.status === 'executing') {
@@ -102,7 +84,7 @@ export function useReactToolScheduler(
}),
);
},
[setPendingHistoryItem],
[],
);
const allToolCallsCompleteHandler: AllToolCallsCompleteHandler = useCallback(
@@ -119,12 +101,29 @@ export function useReactToolScheduler(
const existingTrackedCall = prevTrackedCalls.find(
(ptc) => ptc.request.callId === coreTc.request.callId,
);
const newTrackedCall: TrackedToolCall = {
// Start with the new core state, then layer on the existing UI state
// to ensure UI-only properties like pid are preserved.
const responseSubmittedToGemini =
existingTrackedCall?.responseSubmittedToGemini ?? false;
if (coreTc.status === 'executing') {
return {
...coreTc,
responseSubmittedToGemini,
liveOutput: (existingTrackedCall as TrackedExecutingToolCall)
?.liveOutput,
pid: (coreTc as ExecutingToolCall).pid,
};
}
// For other statuses, explicitly set liveOutput and pid to undefined
// to ensure they are not carried over from a previous executing state.
return {
...coreTc,
responseSubmittedToGemini:
existingTrackedCall?.responseSubmittedToGemini ?? false,
} as TrackedToolCall;
return newTrackedCall;
responseSubmittedToGemini,
liveOutput: undefined,
pid: undefined,
};
}),
);
},
@@ -278,6 +277,7 @@ export function mapToDisplay(
resultDisplay:
(trackedCall as TrackedExecutingToolCall).liveOutput ?? undefined,
confirmationDetails: undefined,
ptyId: (trackedCall as TrackedExecutingToolCall).pid,
};
case 'validating': // Fallthrough
case 'scheduled':

View File

@@ -68,6 +68,7 @@ const mockConfig = {
}),
getUseSmartEdit: () => false,
getGeminiClient: () => null, // No client needed for these tests
getShellExecutionConfig: () => ({ terminalWidth: 80, terminalHeight: 24 }),
} as unknown as Config;
const mockTool = new MockTool({
@@ -124,7 +125,6 @@ describe('useReactToolScheduler in YOLO Mode', () => {
onComplete,
mockConfig as unknown as Config,
setPendingHistoryItem,
() => undefined,
() => {},
),
);
@@ -163,7 +163,7 @@ describe('useReactToolScheduler in YOLO Mode', () => {
expect(mockToolRequiresConfirmation.execute).toHaveBeenCalledWith(
request.args,
expect.any(AbortSignal),
undefined /*updateOutputFn*/,
undefined,
);
// Check that onComplete was called with success
@@ -272,7 +272,6 @@ describe('useReactToolScheduler', () => {
onComplete,
mockConfig as unknown as Config,
setPendingHistoryItem,
() => undefined,
() => {},
),
);
@@ -314,7 +313,7 @@ describe('useReactToolScheduler', () => {
expect(mockTool.execute).toHaveBeenCalledWith(
request.args,
expect.any(AbortSignal),
undefined /*updateOutputFn*/,
undefined,
);
expect(onComplete).toHaveBeenCalledWith([
expect.objectContaining({

View File

@@ -63,6 +63,8 @@ describe('keyMatchers', () => {
key.name === 'return' && !key.ctrl,
[Command.ACCEPT_SUGGESTION_REVERSE_SEARCH]: (key: Key) =>
key.name === 'tab',
[Command.TOGGLE_SHELL_INPUT_FOCUS]: (key: Key) =>
key.ctrl && key.name === 'f',
};
// Test data for each command with positive and negative test cases
@@ -253,6 +255,11 @@ describe('keyMatchers', () => {
positive: [createKey('tab'), createKey('tab', { ctrl: true })],
negative: [createKey('return'), createKey('space')],
},
{
command: Command.TOGGLE_SHELL_INPUT_FOCUS,
positive: [createKey('f', { ctrl: true })],
negative: [createKey('f')],
},
];
describe('Data-driven key binding matches original logic', () => {

View File

@@ -66,6 +66,7 @@ export interface IndividualToolCallDisplay {
status: ToolCallStatus;
confirmationDetails: ToolCallConfirmationDetails | undefined;
renderOutputAsMarkdown?: boolean;
ptyId?: number;
outputFile?: string;
}

View File

@@ -133,6 +133,37 @@ describe('SettingsUtils', () => {
},
},
},
tools: {
type: 'object',
label: 'Tools',
category: 'Tools',
requiresRestart: false,
default: {},
description: 'Tool settings.',
showInDialog: false,
properties: {
shell: {
type: 'object',
label: 'Shell',
category: 'Tools',
requiresRestart: false,
default: {},
description: 'Shell tool settings.',
showInDialog: false,
properties: {
pager: {
type: 'string',
label: 'Pager',
category: 'Tools',
requiresRestart: false,
default: 'less',
description: 'The pager to use for long output.',
showInDialog: true,
},
},
},
},
},
} as const satisfies SettingsSchema;
vi.mocked(getSettingsSchema).mockReturnValue(
@@ -405,8 +436,13 @@ describe('SettingsUtils', () => {
expect(keys).not.toContain('general.preferredEditor'); // Now marked false
expect(keys).not.toContain('security.auth.selectedType'); // Advanced setting
// Most string settings are now hidden, so let's just check they exclude advanced ones
expect(keys.every((key) => !key.startsWith('tool'))).toBe(true); // No tool-related settings
// Check that user-facing tool settings are included
expect(keys).toContain('tools.shell.pager');
// Check that advanced/hidden tool settings are excluded
expect(keys).not.toContain('tools.discoveryCommand');
expect(keys).not.toContain('tools.callCommand');
expect(keys.every((key) => !key.startsWith('advanced.'))).toBe(true);
});
});

View File

@@ -853,12 +853,15 @@ function toToolCallContent(toolResult: ToolResult): acp.ToolCallContent | null {
content: { type: 'text', text: toolResult.returnDisplay },
};
} else {
return {
type: 'diff',
path: toolResult.returnDisplay.fileName,
oldText: toolResult.returnDisplay.originalContent,
newText: toolResult.returnDisplay.newContent,
};
if ('fileName' in toolResult.returnDisplay) {
return {
type: 'diff',
path: toolResult.returnDisplay.fileName,
oldText: toolResult.returnDisplay.originalContent,
newText: toolResult.returnDisplay.newContent,
};
}
return null;
}
} else {
return null;