diff --git a/extensions/cli/spec/shell-mode.md b/extensions/cli/spec/shell-mode.md new file mode 100644 index 000000000..a3bdd6cf4 --- /dev/null +++ b/extensions/cli/spec/shell-mode.md @@ -0,0 +1,138 @@ +shell Mode (CLI TUI) + +Overview + +- shell mode lets users run shell commands directly from the chat input by starting their input with an exclamation mark (!). +- It is intended for quick terminal command execution without leaving the TUI. + +Activation + +- shell mode is activated when the current input (trimmed) starts with ! + - Example: "!git status" or " !ls -la" both activate shell mode. +- Visual indicator: + - Input border color changes to yellow. + - The input prompt indicator changes to a yellow "$". + - The input placeholder includes "! for shell mode". + +Deactivation / Exiting shell Mode + +- Pressing Enter to submit the input exits shell mode immediately after submission, regardless of the command result. +- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits shell mode. +- Editing the input so it no longer starts with ! also exits shell mode and restores normal input behavior. + +Interaction with other input helpers + +- When in shell mode (input starts with !): + - "@" file search suggestions are disabled. + - "/" slash command UI is disabled. +- When in slash command mode (input starts with /): + - "@" file search suggestions are disabled. + +Submission behavior + +- On submit (Enter) with a shell-mode input: + - The leading ! is removed and the remainder is treated as the shell command to run. + - The TUI immediately appends an assistant message representing a shell tool call, with status set to calling, so users can see that the command is in progress. + - The shell command is executed asynchronously; when it completes, the tool call status is updated to done (or error) and the output is populated. + +Execution semantics + +- The command is executed in the same way as terminal tool commands, minus permissions + +Output handling + +- Stdout is streamed into memory; Stderr is captured and appended as a trailing "Stderr: ..." section on success. +- If the process exits non-zero and Stderr contains content, the tool call is marked as error and the error text is shown. +- Output is truncated to the first 5000 lines if exceeded. +- Timeout behavior: If no output is received for 30 seconds (configurable in tests), the process is terminated and the result includes a note like: + "[Command timed out after 30 seconds of no output]". + +Keyboard behaviors (summary) + +- Enter: submit input. If in shell mode, exits shell mode after submission and shows the pending shell tool call immediately. +- Shift+Enter: new line. +- Backslash (\) at end-of-line: inserts a new line (line continuation) as usual. +- Esc: if only ! (trimmed) is present, clears input and exits shell mode; otherwise cancels streaming or closes suggestions depending on context. + +Scope / Modes + +- shell mode applies to interactive (TUI/standard) CLI usage. It is not part of headless (-p/--print) processing. + +Error handling + +- Command execution errors are captured and surfaced in the tool call as status error with human-readable error text (including Stderr when available). + +Examples + +- "!git status" → shows a shell tool call immediately, then populates with the git status output. +- "!echo hello" → shows a shell tool call immediately, then output "hello". +- "!some-unknown-cmd" → shows a shell tool call immediately, then sets status to error with an error message. + Shell Mode (CLI TUI) + +Overview + +- Shell mode lets users run shell commands directly from the chat input by starting their input with an exclamation mark (!). +- It is intended for quick terminal command execution without leaving the TUI. + +Activation + +- Shell mode is activated when the current input (trimmed) starts with ! + - Example: "!git status" or " !ls -la" both activate Shell mode. +- Visual indicator: + - Input border color changes to yellow. + - The input prompt indicator changes to a yellow "$". + - The input placeholder includes "! for shell mode". + +Deactivation / Exiting Shell Mode + +- Pressing Enter to submit the input exits shell mode immediately after submission, regardless of the command result. +- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits shell mode. +- Editing the input so it no longer starts with ! also exits shell mode and restores normal input behavior. + +Interaction with other input helpers + +- When in shell mode (input starts with !): + - "@" file search suggestions are disabled. + - "/" slash command UI is disabled. +- When in slash command mode (input starts with /): + - "@" file search suggestions are disabled. + +Submission behavior + +- On submit (Enter) with a shell-mode input: + - The leading ! is removed and the remainder is treated as the shell command to run. + - The TUI immediately appends an assistant message representing a Shell tool call, with status set to calling, so users can see that the command is in progress. + - The shell command is executed asynchronously; when it completes, the tool call status is updated to done (or error) and the output is populated. + +Execution semantics + +- The command is executed in the same way as terminal tool commands, minus permissions, and inserted into the chat history the same. + +Output handling + +- Stdout is streamed into memory; Stderr is captured and appended as a trailing "Stderr: ..." section on success. +- If the process exits non-zero and Stderr contains content, the tool call is marked as error and the error text is shown. +- Output is truncated to the first 5000 lines if exceeded. +- Timeout behavior: If no output is received for 30 seconds (configurable in tests), the process is terminated and the result includes a note like: + "[Command timed out after 30 seconds of no output]". + +Keyboard behaviors (summary) + +- Enter: submit input. If in shell mode, exits shell mode after submission and shows the pending Shell tool call immediately. +- Shift+Enter: new line. +- Backslash (\) at end-of-line: inserts a new line (line continuation) as usual. +- Esc: if only ! (trimmed) is present, clears input and exits shell mode; otherwise cancels streaming or closes suggestions depending on context. + +Scope / Modes + +- Shell mode applies to interactive (TUI/standard) CLI usage. It is not part of headless (-p/--print) processing. + +Error handling + +- Command execution errors are captured and surfaced in the tool call as status error with human-readable error text (including Stderr when available). + +Examples + +- "!git status" → shows a Shell tool call immediately, then populates with the git status output. +- "!echo hello" → shows a Shell tool call immediately, then output "hello". +- "!some-unknown-cmd" → shows a Shell tool call immediately, then sets status to error with an error message. diff --git a/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts index b5dc3d9aa..509ce8f61 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -28,6 +28,7 @@ async function handleHelp(_args: string[], _assistant: AssistantConfig) { ` ${chalk.cyan("Enter")} Submit message`, ` ${chalk.cyan("Shift+Enter")} New line`, ` ${chalk.cyan("\\")} Line continuation (at end of line)`, + ` ${chalk.cyan("!")} Shell mode - run shell commands`, "", chalk.white("Controls:"), ` ${chalk.cyan("Ctrl+C")} Clear input`, @@ -39,9 +40,11 @@ async function handleHelp(_args: string[], _assistant: AssistantConfig) { chalk.white("Special Characters:"), ` ${chalk.cyan("@")} Search and attach files for context`, ` ${chalk.cyan("/")} Access slash commands`, + ` ${chalk.cyan("!")} Execute bash commands directly`, "", chalk.white("Available Commands:"), ` Type ${chalk.cyan("/")} to see available slash commands`, + ` Type ${chalk.cyan("!")} followed by a command to execute bash directly`, ].join("\n"); posthogService.capture("useSlashCommand", { name: "help" }); return { output: helpMessage }; diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index ea48988d9..e0a60dac6 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -20,6 +20,77 @@ import { import { SlashCommandUI } from "./SlashCommandUI.js"; import { TextBuffer } from "./TextBuffer.js"; +// Small presentational helpers to reduce cyclomatic complexity in UserInput +const InterruptedBanner: React.FC<{ wasInterrupted: boolean }> = ({ + wasInterrupted, +}) => { + if (!wasInterrupted) return null; + return ( + + ⚠ Interrupted by user - Press enter to resume + + ); +}; + +const SlashCommandsMaybe: React.FC<{ + show: boolean; + inputMode: boolean; + hideNormalUI: boolean; + isRemoteMode: boolean; + assistant?: AssistantConfig; + filter: string; + selectedIndex: number; +}> = ({ + show, + inputMode, + hideNormalUI, + isRemoteMode, + assistant, + filter, + selectedIndex, +}) => { + if (!show || !inputMode || hideNormalUI || !(isRemoteMode || assistant)) + return null; + return ( + + ); +}; + +const FileSearchMaybe: React.FC<{ + show: boolean; + inputMode: boolean; + hideNormalUI: boolean; + isRemoteMode: boolean; + filter: string; + selectedIndex: number; + onSelect: (path: string) => void | Promise; + onFilesUpdated: (files: Array<{ path: string; displayName: string }>) => void; +}> = ({ + show, + inputMode, + hideNormalUI, + isRemoteMode, + filter, + selectedIndex, + onSelect, + onFilesUpdated, +}) => { + if (!show || !inputMode || hideNormalUI || isRemoteMode) return null; + return ( + + ); +}; + interface UserInputProps { onSubmit: (message: string, imageMap?: Map) => void; isWaitingForResponse: boolean; @@ -78,10 +149,13 @@ const UserInput: React.FC = ({ setCursorPosition(0); setShowSlashCommands(false); setShowFileSearch(false); + setShowBashMode(false); inputHistory.resetNavigation(); }, [textBuffer]); + const [slashCommandFilter, setSlashCommandFilter] = useState(""); const [selectedCommandIndex, setSelectedCommandIndex] = useState(0); + const [showBashMode, setShowBashMode] = useState(false); const [showFileSearch, setShowFileSearch] = useState(false); const [fileSearchFilter, setFileSearchFilter] = useState(""); const [selectedFileIndex, setSelectedFileIndex] = useState(0); @@ -131,6 +205,18 @@ const UserInput: React.FC = ({ return nextMode; }; + // Update shell mode state based on input + const updateBashModeState = (text: string) => { + const trimmed = text.trimStart(); + const isBash = trimmed.startsWith("!"); + setShowBashMode(isBash); + if (isBash) { + // Disable other helpers while in shell mode + setShowSlashCommands(false); + setShowFileSearch(false); + } + }; + // Update slash command UI state based on input const updateSlashCommandState = (text: string, cursor: number) => { // Only show slash commands if slash is the very first character @@ -139,6 +225,9 @@ const UserInput: React.FC = ({ return; } + // When using slash commands, disable file search + setShowFileSearch(false); + const trimmedText = text.trimStart(); const beforeCursor = trimmedText.slice( 0, @@ -196,6 +285,13 @@ const UserInput: React.FC = ({ return; } + // Disable file search if we're in shell mode or slash command mode + const trimmed = text.trimStart(); + if (trimmed.startsWith("!") || trimmed.startsWith("/")) { + setShowFileSearch(false); + return; + } + // Check if we're in a file search context const beforeCursor = text.slice(0, cursor); const lastAtIndex = beforeCursor.lastIndexOf("@"); @@ -234,6 +330,7 @@ const UserInput: React.FC = ({ setFileSearchFilter(afterAt); setSelectedFileIndex(0); setShowSlashCommands(false); + setShowBashMode(false); } } }; @@ -278,6 +375,7 @@ const UserInput: React.FC = ({ setInputText(newText); setCursorPosition(newCursorPos); setShowSlashCommands(false); + setShowBashMode(false); } }; @@ -437,6 +535,7 @@ const UserInput: React.FC = ({ setInputText(""); setCursorPosition(0); setShowSlashCommands(false); + setShowBashMode(false); } return true; } @@ -462,6 +561,15 @@ const UserInput: React.FC = ({ const handleEscapeKey = (key: any): boolean => { if (!key.escape) return false; + // If only "!" is present, clear shell mode + if (inputMode && showBashMode && inputText.trim() === "!") { + textBuffer.clear(); + setInputText(""); + setCursorPosition(0); + setShowBashMode(false); + return true; + } + // Handle escape key to interrupt streaming if (isWaitingForResponse && onInterrupt) { onInterrupt(); @@ -491,6 +599,7 @@ const UserInput: React.FC = ({ setCursorPosition(newCursor); updateSlashCommandState(newText, newCursor); updateFileSearchState(newText, newCursor); + updateBashModeState(newText); inputHistory.resetNavigation(); }; @@ -587,14 +696,16 @@ const UserInput: React.FC = ({ setCursorPosition, updateSlashCommandState, updateFileSearchState, + updateBashModeState, inputHistory, }); }); const renderInputText = () => { const placeholderText = isRemoteMode - ? "Ask anything, / for slash commands" - : placeholder || "Ask anything, @ for context, / for slash commands"; + ? "Ask anything, / for slash commands, ! for shell mode" + : placeholder || + "Ask anything, @ for context, / for slash commands, ! for shell mode"; if (inputText.length === 0) { return ( <> @@ -677,50 +788,44 @@ const UserInput: React.FC = ({ return ( - {/* Interruption message - shown just above the input box */} - {wasInterrupted && ( - - - ⚠ Interrupted by user - Press enter to resume - - - )} + {/* Input box */} - - {isRemoteMode ? "◉" : "●"}{" "} + + {showBashMode ? "$" : isRemoteMode ? "◉" : "●"} {renderInputText()} - {/* Slash command UI - show in remote mode OR when assistant is available */} - {showSlashCommands && - inputMode && - !hideNormalUI && - (isRemoteMode || assistant) && ( - - )} + - {/* File search UI - only show in local mode */} - {showFileSearch && inputMode && !hideNormalUI && !isRemoteMode && ( - - )} + ); }; diff --git a/extensions/cli/src/ui/hooks/useChat.shellMode.test.ts b/extensions/cli/src/ui/hooks/useChat.shellMode.test.ts new file mode 100644 index 000000000..3308fdde5 --- /dev/null +++ b/extensions/cli/src/ui/hooks/useChat.shellMode.test.ts @@ -0,0 +1,148 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { runTerminalCommandTool } from "src/tools/runTerminalCommand.js"; + +import { services } from "../../services/index.js"; + +import { handleBashModeProcessing } from "./useChat.shellMode.js"; + +// Mock the runTerminalCommandTool with the correct path for the import in shellMode.ts +vi.mock("src/tools/runTerminalCommand.js", () => ({ + runTerminalCommandTool: { + run: vi.fn(), + }, +})); + +// Mock the services +vi.mock("../../services/index.js", () => ({ + services: { + chatHistory: { + addAssistantMessage: vi.fn(), + updateToolStatus: vi.fn(), + addToolResult: vi.fn(), + }, + }, +})); + +describe("handleBashModeProcessing", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("should detect bash mode when message starts with !", async () => { + const mockRun = vi.mocked(runTerminalCommandTool.run); + mockRun.mockResolvedValue( + "total 5\ndrwxr-xr-x 2 user user 4096 Jan 1 12:00 .\ndrwxr-xr-x 3 user user 4096 Jan 1 12:00 ..", + ); + + const result = await handleBashModeProcessing("!ls -la"); + + expect(result).toBe(null); // Processed, no further handling needed + expect(services.chatHistory.addAssistantMessage).toHaveBeenCalled(); + expect(services.chatHistory.updateToolStatus).toHaveBeenCalledWith( + expect.any(String), + "calling", + ); + + // Use vi.waitFor to wait for async operations in the void expression + await vi.waitFor( + () => { + expect(mockRun).toHaveBeenCalledWith({ command: "ls -la" }); + }, + { timeout: 1000 }, + ); + + await vi.waitFor( + () => { + expect(services.chatHistory.addToolResult).toHaveBeenCalledWith( + expect.any(String), + "total 5\ndrwxr-xr-x 2 user user 4096 Jan 1 12:00 .\ndrwxr-xr-x 3 user user 4096 Jan 1 12:00 ..", + "done", + ); + }, + { timeout: 1000 }, + ); + }); + + it("should handle bash command errors", async () => { + const mockRun = vi.mocked(runTerminalCommandTool.run); + mockRun.mockRejectedValue(new Error("Command not found")); + + const result = await handleBashModeProcessing("!invalidcommand"); + + expect(result).toBe(null); // Processed, no further handling needed + expect(services.chatHistory.addAssistantMessage).toHaveBeenCalled(); + expect(services.chatHistory.updateToolStatus).toHaveBeenCalledWith( + expect.any(String), + "calling", + ); + + // Use vi.waitFor to wait for async operations in the void expression + await vi.waitFor( + () => { + expect(mockRun).toHaveBeenCalledWith({ command: "invalidcommand" }); + }, + { timeout: 1000 }, + ); + + await vi.waitFor( + () => { + expect(services.chatHistory.addToolResult).toHaveBeenCalledWith( + expect.any(String), + "Bash command failed: Command not found", + "errored", + ); + }, + { timeout: 1000 }, + ); + }); + + it("should not trigger bash mode for regular messages", async () => { + const mockRun = vi.mocked(runTerminalCommandTool.run); + + const result = await handleBashModeProcessing("Hello! How are you?"); + + expect(result).toBe("Hello! How are you?"); // Pass through unchanged + expect(mockRun).not.toHaveBeenCalled(); + expect(services.chatHistory.addAssistantMessage).not.toHaveBeenCalled(); + }); + + it("should handle empty bash command", async () => { + const mockRun = vi.mocked(runTerminalCommandTool.run); + + const result = await handleBashModeProcessing("!"); + + expect(result).toBe("!"); // Pass through unchanged for empty command + expect(mockRun).not.toHaveBeenCalled(); + expect(services.chatHistory.addAssistantMessage).not.toHaveBeenCalled(); + }); + + it("should handle bash command with leading whitespace", async () => { + const mockRun = vi.mocked(runTerminalCommandTool.run); + mockRun.mockResolvedValue("echo test output"); + + const result = await handleBashModeProcessing(" !echo hello"); + + expect(result).toBe(null); // Processed, no further handling needed + expect(services.chatHistory.addAssistantMessage).toHaveBeenCalled(); + + // Use vi.waitFor to wait for async operations in the void expression + await vi.waitFor( + () => { + expect(mockRun).toHaveBeenCalledWith({ command: "echo hello" }); + }, + { timeout: 1000 }, + ); + + await vi.waitFor( + () => { + expect(services.chatHistory.addToolResult).toHaveBeenCalledWith( + expect.any(String), + "echo test output", + "done", + ); + }, + { timeout: 1000 }, + ); + }); +}); diff --git a/extensions/cli/src/ui/hooks/useChat.shellMode.ts b/extensions/cli/src/ui/hooks/useChat.shellMode.ts new file mode 100644 index 000000000..9c441310f --- /dev/null +++ b/extensions/cli/src/ui/hooks/useChat.shellMode.ts @@ -0,0 +1,51 @@ +import { runTerminalCommandTool } from "src/tools/runTerminalCommand.js"; +import { getErrorString } from "src/util/error.js"; + +import { services } from "../../services/index.js"; + +export const handleBashModeProcessing = async ( + message: string, +): Promise => { + // Handle shell mode commands (starting with !) + if (!message.trimStart().startsWith("!")) { + return message; + } + + // Extract the command after the ! + const bashCommand = message.trimStart().slice(1).trim(); + + if (!bashCommand) { + return message; // No command provided, treat as regular message + } + + // Show tool call immediately, then run asynchronously and populate result + const toolCallId = `shell-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + const toolCall = { + id: toolCallId, + type: "function" as const, + function: { + name: "Bash", + arguments: JSON.stringify({ command: bashCommand }), + }, + }; + + // Add assistant message with tool call immediately + services.chatHistory.addAssistantMessage("", [toolCall]); + // Mark as calling for immediate UI feedback + services.chatHistory.updateToolStatus(toolCallId, "calling"); + + // Execute the bash command asynchronously - don't block UI + void runTerminalCommandTool + .run({ + command: bashCommand, + }) + .then((result) => { + services.chatHistory.addToolResult(toolCallId, result, "done"); + }) + .catch((error) => { + const errorMessage = `Bash command failed: ${getErrorString(error)}`; + services.chatHistory.addToolResult(toolCallId, errorMessage, "errored"); + }); + + return null; // Processed, no further message handling needed +}; diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index c62854ed4..c2f1e0130 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -30,6 +30,7 @@ import { handleRemoteMessage, setupRemotePolling, } from "./useChat.remote.helpers.js"; +import { handleBashModeProcessing } from "./useChat.shellMode.js"; import { createStreamCallbacks, executeStreaming, @@ -423,6 +424,13 @@ export function useChat({ if (handled) return; + // Handle shell mode commands (before slash commands) + const bashProcessedMessage = await handleBashModeProcessing(message); + if (bashProcessedMessage === null) { + return; // Bash command was handled and no further processing needed + } + message = bashProcessedMessage; + // Handle slash commands const processedMessage = await handleSlashCommandProcessing(message); if (processedMessage === null) { diff --git a/extensions/cli/src/ui/hooks/useUserInput.ts b/extensions/cli/src/ui/hooks/useUserInput.ts index b1a09ae43..b8a48cd04 100644 --- a/extensions/cli/src/ui/hooks/useUserInput.ts +++ b/extensions/cli/src/ui/hooks/useUserInput.ts @@ -104,6 +104,7 @@ interface TextBufferStateOptions { setCursorPosition: (pos: number) => void; updateSlashCommandState: (text: string, cursor: number) => void; updateFileSearchState: (text: string, cursor: number) => void; + updateBashModeState: (text: string) => void; inputHistory: any; } @@ -115,6 +116,7 @@ export function updateTextBufferState(options: TextBufferStateOptions) { setCursorPosition, updateSlashCommandState, updateFileSearchState, + updateBashModeState, inputHistory, } = options; @@ -126,6 +128,7 @@ export function updateTextBufferState(options: TextBufferStateOptions) { setCursorPosition(newCursor); updateSlashCommandState(newText, newCursor); updateFileSearchState(newText, newCursor); + updateBashModeState(newText); inputHistory.resetNavigation(); } }