From c7ffe89be36056c85069d60bfdecc1833a540434 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 2 Sep 2025 19:17:49 -0700 Subject: [PATCH] feat: bash mode --- extensions/cli/package-lock.json | 6 - extensions/cli/spec/bash-mode.md | 64 +++++++++++ extensions/cli/src/slashCommands.ts | 3 + .../cli/src/tools/runTerminalCommand.ts | 9 +- extensions/cli/src/ui/UserInput.tsx | 48 +++++++- .../cli/src/ui/hooks/useChat.bashMode.test.ts | 108 ++++++++++++++++++ extensions/cli/src/ui/hooks/useChat.ts | 53 +++++++++ extensions/cli/src/ui/hooks/useUserInput.ts | 3 + 8 files changed, 281 insertions(+), 13 deletions(-) create mode 100644 extensions/cli/spec/bash-mode.md create mode 100644 extensions/cli/src/ui/hooks/useChat.bashMode.test.ts diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json index d52b3f219..6510bc717 100644 --- a/extensions/cli/package-lock.json +++ b/extensions/cli/package-lock.json @@ -9,12 +9,6 @@ "version": "0.0.0-dev", "license": "Apache-2.0", "dependencies": { - "@img/sharp-darwin-arm64": "^0.33.5", - "@img/sharp-darwin-x64": "^0.33.5", - "@img/sharp-linux-arm": "^0.33.5", - "@img/sharp-linux-arm64": "^0.33.5", - "@img/sharp-linux-x64": "^0.33.5", - "@img/sharp-win32-x64": "^0.33.5", "@sentry/profiling-node": "^9.43.0" }, "bin": { diff --git a/extensions/cli/spec/bash-mode.md b/extensions/cli/spec/bash-mode.md new file mode 100644 index 000000000..cbf99c9fe --- /dev/null +++ b/extensions/cli/spec/bash-mode.md @@ -0,0 +1,64 @@ +Bash Mode (CLI TUI) + +Overview +- Bash 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 +- Bash mode is activated when the current input (trimmed) starts with ! + - Example: "!git status" or " !ls -la" both activate Bash mode. +- Visual indicator: + - Input border color changes to yellow. + - The input prompt indicator changes to a yellow "$". + - The input placeholder includes "! for bash mode". + +Deactivation / Exiting Bash Mode +- Pressing Enter to submit the input exits bash mode immediately after submission, regardless of the command result. +- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits bash mode. +- Editing the input so it no longer starts with ! also exits bash mode and restores normal input behavior. + +Interaction with other input helpers +- When in bash 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 bash-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 Bash tool call, with status set to calling, so users can see that the command is in progress. + - The bash 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 from the current working directory of the CLI process. +- The command runs in the user’s shell as a login shell: + - Unix/macOS: SHELL (or /bin/bash) invoked with -l -c "". + - Windows: powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "". +- The child process stdin is detached (not connected to the TTY). This prevents the TUI from being suspended by job control. Consequences: + - Interactive commands that require stdin will not work. +- Environment variables are inherited from the parent process. Aliases/functions availability depends on the user’s shell configuration and is not guaranteed. + +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 bash mode, exits bash mode after submission and shows the pending Bash 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 bash mode; otherwise cancels streaming or closes suggestions depending on context. + +Scope / Modes +- Bash 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 Bash tool call immediately, then populates with the git status output. +- "!echo hello" → shows a Bash tool call immediately, then output "hello". +- "!some-unknown-cmd" → shows a Bash 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..1c34c58fa 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("!")} Bash 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/tools/runTerminalCommand.ts b/extensions/cli/src/tools/runTerminalCommand.ts index 9aefceb9b..242ecdeea 100644 --- a/extensions/cli/src/tools/runTerminalCommand.ts +++ b/extensions/cli/src/tools/runTerminalCommand.ts @@ -17,7 +17,7 @@ function getShellCommand(command: string): { shell: string; args: string[] } { args: ["-NoLogo", "-ExecutionPolicy", "Bypass", "-Command", command], }; } else { - // Unix/macOS: Use login shell to source .bashrc/.zshrc etc. + // Unix/macOS: Just run the user's shell as a login shell const userShell = process.env.SHELL || "/bin/bash"; return { shell: userShell, args: ["-l", "-c", command] }; } @@ -60,7 +60,12 @@ The command will be executed from the current working directory: ${process.cwd() return new Promise((resolve, reject) => { // Use same shell logic as core implementation const { shell, args } = getShellCommand(command); - const child = spawn(shell, args); + const child = spawn(shell, args, { + cwd: process.cwd(), + env: process.env, + stdio: ["ignore", "pipe", "pipe"], // prevent child from reading TTY input + detached: false, + }); let stdout = ""; let stderr = ""; let timeoutId: NodeJS.Timeout; diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index be24ccb52..e022e3cc3 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -69,6 +69,7 @@ const UserInput: React.FC = ({ const [showSlashCommands, setShowSlashCommands] = useState(false); 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); @@ -118,6 +119,18 @@ const UserInput: React.FC = ({ return nextMode; }; + // Update bash 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 bash 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 @@ -126,6 +139,9 @@ const UserInput: React.FC = ({ return; } + // When using slash commands, disable file search + setShowFileSearch(false); + const trimmedText = text.trimStart(); const beforeCursor = trimmedText.slice( 0, @@ -188,6 +204,13 @@ const UserInput: React.FC = ({ return; } + // Disable file search if we're in bash 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("@"); @@ -226,6 +249,7 @@ const UserInput: React.FC = ({ setFileSearchFilter(afterAt); setSelectedFileIndex(0); setShowSlashCommands(false); + setShowBashMode(false); } } }; @@ -270,6 +294,7 @@ const UserInput: React.FC = ({ setInputText(newText); setCursorPosition(newCursorPos); setShowSlashCommands(false); + setShowBashMode(false); } }; @@ -429,6 +454,7 @@ const UserInput: React.FC = ({ setInputText(""); setCursorPosition(0); setShowSlashCommands(false); + setShowBashMode(false); } return true; } @@ -454,6 +480,15 @@ const UserInput: React.FC = ({ const handleEscapeKey = (key: any): boolean => { if (!key.escape) return false; + // If only "!" is present, clear bash 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(); @@ -482,6 +517,7 @@ const UserInput: React.FC = ({ setCursorPosition(0); setShowSlashCommands(false); setShowFileSearch(false); + setShowBashMode(false); inputHistory.resetNavigation(); }; @@ -493,6 +529,7 @@ const UserInput: React.FC = ({ setCursorPosition(newCursor); updateSlashCommandState(newText, newCursor); updateFileSearchState(newText, newCursor); + updateBashModeState(newText); inputHistory.resetNavigation(); }; @@ -573,14 +610,15 @@ 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 bash mode" + : placeholder || "Ask anything, @ for context, / for slash commands, ! for bash mode"; if (inputText.length === 0) { return ( <> @@ -677,10 +715,10 @@ const UserInput: React.FC = ({ borderStyle="round" borderTop={true} paddingX={1} - borderColor={isRemoteMode ? "cyan" : "gray"} + borderColor={showBashMode ? "yellow" : isRemoteMode ? "cyan" : "gray"} > - - {isRemoteMode ? "◉" : "●"}{" "} + + {showBashMode ? "$" : isRemoteMode ? "◉" : "●"} {renderInputText()} diff --git a/extensions/cli/src/ui/hooks/useChat.bashMode.test.ts b/extensions/cli/src/ui/hooks/useChat.bashMode.test.ts new file mode 100644 index 000000000..89105cd4e --- /dev/null +++ b/extensions/cli/src/ui/hooks/useChat.bashMode.test.ts @@ -0,0 +1,108 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { act } from "@testing-library/react"; + +import { createMinimalTestContext } from "../../test-helpers/ui-test-context.js"; + +// Mock the runTerminalCommandTool +vi.mock("../../tools/runTerminalCommand.js", () => ({ + runTerminalCommandTool: { + run: vi.fn(), + }, +})); + +import { useChat } from "./useChat.js"; +import { runTerminalCommandTool } from "../../tools/runTerminalCommand.js"; + +describe("useChat - Bash Mode", () => { + 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 ctx = createMinimalTestContext(); + const chat = useChat({ + assistant: { name: "test" } as any, + model: { name: "test-model" } as any, + llmApi: {} as any, + } as any); + + await act(async () => { + await chat.handleUserMessage("!ls -la"); + }); + + expect(mockRun).toHaveBeenCalledWith({ command: "ls -la" }); + + // Since history is managed by service, we just verify no exception and tool called + ctx.cleanup(); + }); + + it("should handle bash command errors", async () => { + const mockRun = vi.mocked(runTerminalCommandTool.run); + mockRun.mockRejectedValue(new Error("Command not found")); + + const chat = useChat({ + assistant: { name: "test" } as any, + model: { name: "test-model" } as any, + llmApi: {} as any, + } as any); + + await act(async () => { + await chat.handleUserMessage("!invalidcommand"); + }); + + expect(mockRun).toHaveBeenCalledWith({ command: "invalidcommand" }); + }); + + it("should not trigger bash mode for regular messages", async () => { + const mockRun = vi.mocked(runTerminalCommandTool.run); + + const chat = useChat({ + assistant: { name: "test" } as any, + model: { name: "test-model" } as any, + llmApi: {} as any, + } as any); + + await act(async () => { + await chat.handleUserMessage("Hello! How are you?"); + }); + + expect(mockRun).not.toHaveBeenCalled(); + }); + + it("should handle empty bash command", async () => { + const mockRun = vi.mocked(runTerminalCommandTool.run); + + const chat = useChat({ + assistant: { name: "test" } as any, + model: { name: "test-model" } as any, + llmApi: {} as any, + } as any); + + await act(async () => { + await chat.handleUserMessage("!"); + }); + + // Should not call the tool for empty command + expect(mockRun).not.toHaveBeenCalled(); + }); + + it("should handle bash command with leading whitespace", async () => { + const mockRun = vi.mocked(runTerminalCommandTool.run); + mockRun.mockResolvedValue("echo test output"); + + const chat = useChat({ + assistant: { name: "test" } as any, + model: { name: "test-model" } as any, + llmApi: {} as any, + } as any); + + await act(async () => { + await chat.handleUserMessage(" !echo hello"); + }); + + expect(mockRun).toHaveBeenCalledWith({ command: "echo hello" }); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index c62854ed4..4c6876629 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -339,6 +339,52 @@ export function useChat({ return false; }; + const handleBashModeProcessing = async ( + message: string, + ): Promise => { + // Handle bash 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 = `bash-${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 as any]); + // Mark as calling for immediate UI feedback + services.chatHistory.updateToolStatus(toolCallId, "calling"); + + // Execute the bash command asynchronously - don't block UI + (async () => { + try { + const { runTerminalCommandTool } = await import("../../tools/runTerminalCommand.js"); + const result = await runTerminalCommandTool.run({ command: bashCommand }); + services.chatHistory.addToolResult(toolCallId, result, "done"); + } catch (error: any) { + const errorMessage = `Bash command failed: ${error?.message || String(error)}`; + services.chatHistory.addToolResult(toolCallId, errorMessage, "error"); + } + })(); + + return null; // Processed, no further message handling needed + }; + const handleSlashCommandProcessing = async ( message: string, ): Promise => { @@ -423,6 +469,13 @@ export function useChat({ if (handled) return; + // Handle bash 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 aa99c421e..983a17d09 100644 --- a/extensions/cli/src/ui/hooks/useUserInput.ts +++ b/extensions/cli/src/ui/hooks/useUserInput.ts @@ -189,6 +189,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; } @@ -200,6 +201,7 @@ export function updateTextBufferState(options: TextBufferStateOptions) { setCursorPosition, updateSlashCommandState, updateFileSearchState, + updateBashModeState, inputHistory, } = options; @@ -211,6 +213,7 @@ export function updateTextBufferState(options: TextBufferStateOptions) { setCursorPosition(newCursor); updateSlashCommandState(newText, newCursor); updateFileSearchState(newText, newCursor); + updateBashModeState(newText); inputHistory.resetNavigation(); } }