From b7ff51e49c295828c047c38e434d1f48eea0e321 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 2 Sep 2025 21:07:37 -0700 Subject: [PATCH] chore: cleanup shell mode --- extensions/cli/spec/bash-mode.md | 75 ---------- extensions/cli/spec/shell-mode.md | 138 ++++++++++++++++++ extensions/cli/src/slashCommands.ts | 2 +- .../cli/src/tools/runTerminalCommand.ts | 9 +- extensions/cli/src/ui/UserInput.tsx | 12 +- ...Mode.test.ts => useChat.shellMode.test.ts} | 2 +- ...eChat.bashMode.ts => useChat.shellMode.ts} | 29 ++-- extensions/cli/src/ui/hooks/useChat.ts | 4 +- 8 files changed, 164 insertions(+), 107 deletions(-) delete mode 100644 extensions/cli/spec/bash-mode.md create mode 100644 extensions/cli/spec/shell-mode.md rename extensions/cli/src/ui/hooks/{useChat.bashMode.test.ts => useChat.shellMode.test.ts} (98%) rename extensions/cli/src/ui/hooks/{useChat.bashMode.ts => useChat.shellMode.ts} (66%) diff --git a/extensions/cli/spec/bash-mode.md b/extensions/cli/spec/bash-mode.md deleted file mode 100644 index 18957e0b7..000000000 --- a/extensions/cli/spec/bash-mode.md +++ /dev/null @@ -1,75 +0,0 @@ -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/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 1c34c58fa..509ce8f61 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -28,7 +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.cyan("!")} Shell mode - run shell commands`, "", chalk.white("Controls:"), ` ${chalk.cyan("Ctrl+C")} Clear input`, diff --git a/extensions/cli/src/tools/runTerminalCommand.ts b/extensions/cli/src/tools/runTerminalCommand.ts index 242ecdeea..9aefceb9b 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: Just run the user's shell as a login shell + // Unix/macOS: Use login shell to source .bashrc/.zshrc etc. const userShell = process.env.SHELL || "/bin/bash"; return { shell: userShell, args: ["-l", "-c", command] }; } @@ -60,12 +60,7 @@ 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, { - cwd: process.cwd(), - env: process.env, - stdio: ["ignore", "pipe", "pipe"], // prevent child from reading TTY input - detached: false, - }); + const child = spawn(shell, args); 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 1f85011d7..1c916e9d0 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -190,13 +190,13 @@ const UserInput: React.FC = ({ return nextMode; }; - // Update bash mode state based on input + // 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 bash mode + // Disable other helpers while in shell mode setShowSlashCommands(false); setShowFileSearch(false); } @@ -275,7 +275,7 @@ const UserInput: React.FC = ({ return; } - // Disable file search if we're in bash mode or slash command mode + // Disable file search if we're in shell mode or slash command mode const trimmed = text.trimStart(); if (trimmed.startsWith("!") || trimmed.startsWith("/")) { setShowFileSearch(false); @@ -551,7 +551,7 @@ const UserInput: React.FC = ({ const handleEscapeKey = (key: any): boolean => { if (!key.escape) return false; - // If only "!" is present, clear bash mode + // If only "!" is present, clear shell mode if (inputMode && showBashMode && inputText.trim() === "!") { textBuffer.clear(); setInputText(""); @@ -688,9 +688,9 @@ const UserInput: React.FC = ({ const renderInputText = () => { const placeholderText = isRemoteMode - ? "Ask anything, / for slash commands, ! for bash mode" + ? "Ask anything, / for slash commands, ! for shell mode" : placeholder || - "Ask anything, @ for context, / for slash commands, ! for bash mode"; + "Ask anything, @ for context, / for slash commands, ! for shell mode"; if (inputText.length === 0) { return ( <> diff --git a/extensions/cli/src/ui/hooks/useChat.bashMode.test.ts b/extensions/cli/src/ui/hooks/useChat.shellMode.test.ts similarity index 98% rename from extensions/cli/src/ui/hooks/useChat.bashMode.test.ts rename to extensions/cli/src/ui/hooks/useChat.shellMode.test.ts index 43726bf09..5afed14bf 100644 --- a/extensions/cli/src/ui/hooks/useChat.bashMode.test.ts +++ b/extensions/cli/src/ui/hooks/useChat.shellMode.test.ts @@ -1,5 +1,5 @@ import { act } from "@testing-library/react"; -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { createMinimalTestContext } from "../../test-helpers/ui-test-context.js"; import { runTerminalCommandTool } from "../../tools/runTerminalCommand.js"; diff --git a/extensions/cli/src/ui/hooks/useChat.bashMode.ts b/extensions/cli/src/ui/hooks/useChat.shellMode.ts similarity index 66% rename from extensions/cli/src/ui/hooks/useChat.bashMode.ts rename to extensions/cli/src/ui/hooks/useChat.shellMode.ts index 534f0b3b7..18cac2d43 100644 --- a/extensions/cli/src/ui/hooks/useChat.bashMode.ts +++ b/extensions/cli/src/ui/hooks/useChat.shellMode.ts @@ -1,9 +1,11 @@ +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 bash mode commands (starting with !) + // Handle shell mode commands (starting with !) if (!message.trimStart().startsWith("!")) { return message; } @@ -16,7 +18,7 @@ export const handleBashModeProcessing = async ( } // Show tool call immediately, then run asynchronously and populate result - const toolCallId = `bash-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + const toolCallId = `shell-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; const toolCall = { id: toolCallId, type: "function" as const, @@ -27,25 +29,22 @@ export const handleBashModeProcessing = async ( }; // Add assistant message with tool call immediately - services.chatHistory.addAssistantMessage("", [toolCall as any]); + 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 - (async () => { - try { - const { runTerminalCommandTool } = await import( - "../../tools/runTerminalCommand.js" - ); - const result = await runTerminalCommandTool.run({ - command: bashCommand, - }); + void runTerminalCommandTool + .run({ + command: bashCommand, + }) + .then((result) => { services.chatHistory.addToolResult(toolCallId, result, "done"); - } catch (error: any) { - const errorMessage = `Bash command failed: ${error?.message || String(error)}`; + }) + .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 cc86d61fe..c2f1e0130 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -15,7 +15,6 @@ import { telemetryService } from "../../telemetry/telemetryService.js"; import { formatError } from "../../util/formatError.js"; import { logger } from "../../util/logger.js"; -import { handleBashModeProcessing } from "./useChat.bashMode.js"; import { handleAutoCompaction, handleCompactCommand, @@ -31,6 +30,7 @@ import { handleRemoteMessage, setupRemotePolling, } from "./useChat.remote.helpers.js"; +import { handleBashModeProcessing } from "./useChat.shellMode.js"; import { createStreamCallbacks, executeStreaming, @@ -424,7 +424,7 @@ export function useChat({ if (handled) return; - // Handle bash mode commands (before slash commands) + // 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