Elffuss BraidHub

kikocis/continue public

feat: bash mode
Changesetadd1a24afaff59ad1dc4bd94f397e1b953a10403284865503dd019bec9c85edc
AuthorDallin Romney <dallinromney@gmail.com> · 2025-09-02 19:17 -07:00
CommitterDallin Romney <dallinromney@gmail.com> · 2025-09-02 19:17 -07:00
Parents63295a49bc15

Browse the files at this changeset

8 files changed

modified extensions/cli/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

added extensions/cli/spec/bash-mode.md +64 −0
@@ -0,0 +1,64 @@
1+Bash Mode (CLI TUI)
2+
3+Overview
4+- Bash mode lets users run shell commands directly from the chat input by starting their input with an exclamation mark (!).
5+- It is intended for quick terminal command execution without leaving the TUI.
6+
7+Activation
8+- Bash mode is activated when the current input (trimmed) starts with !
9+ - Example: "!git status" or " !ls -la" both activate Bash mode.
10+- Visual indicator:
11+ - Input border color changes to yellow.
12+ - The input prompt indicator changes to a yellow "$".
13+ - The input placeholder includes "! for bash mode".
14+
15+Deactivation / Exiting Bash Mode
16+- Pressing Enter to submit the input exits bash mode immediately after submission, regardless of the command result.
17+- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits bash mode.
18+- Editing the input so it no longer starts with ! also exits bash mode and restores normal input behavior.
19+
20+Interaction with other input helpers
21+- When in bash mode (input starts with !):
22+ - "@" file search suggestions are disabled.
23+ - "/" slash command UI is disabled.
24+- When in slash command mode (input starts with /):
25+ - "@" file search suggestions are disabled.
26+
27+Submission behavior
28+- On submit (Enter) with a bash-mode input:
29+ - The leading ! is removed and the remainder is treated as the shell command to run.
30+ - 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.
31+ - The bash command is executed asynchronously; when it completes, the tool call status is updated to done (or error) and the output is populated.
32+
33+Execution semantics
34+- The command is executed from the current working directory of the CLI process.
35+- The command runs in the user’s shell as a login shell:
36+ - Unix/macOS: SHELL (or /bin/bash) invoked with -l -c "<command>".
37+ - Windows: powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "<command>".
38+- The child process stdin is detached (not connected to the TTY). This prevents the TUI from being suspended by job control. Consequences:
39+ - Interactive commands that require stdin will not work.
40+- Environment variables are inherited from the parent process. Aliases/functions availability depends on the user’s shell configuration and is not guaranteed.
41+
42+Output handling
43+- Stdout is streamed into memory; Stderr is captured and appended as a trailing "Stderr: ..." section on success.
44+- If the process exits non-zero and Stderr contains content, the tool call is marked as error and the error text is shown.
45+- Output is truncated to the first 5000 lines if exceeded.
46+- Timeout behavior: If no output is received for 30 seconds (configurable in tests), the process is terminated and the result includes a note like:
47+ "[Command timed out after 30 seconds of no output]".
48+
49+Keyboard behaviors (summary)
50+- Enter: submit input. If in bash mode, exits bash mode after submission and shows the pending Bash tool call immediately.
51+- Shift+Enter: new line.
52+- Backslash (\) at end-of-line: inserts a new line (line continuation) as usual.
53+- Esc: if only ! (trimmed) is present, clears input and exits bash mode; otherwise cancels streaming or closes suggestions depending on context.
54+
55+Scope / Modes
56+- Bash mode applies to interactive (TUI/standard) CLI usage. It is not part of headless (-p/--print) processing.
57+
58+Error handling
59+- Command execution errors are captured and surfaced in the tool call as status error with human-readable error text (including Stderr when available).
60+
61+Examples
62+- "!git status" → shows a Bash tool call immediately, then populates with the git status output.
63+- "!echo hello" → shows a Bash tool call immediately, then output "hello".
64+- "!some-unknown-cmd" → shows a Bash tool call immediately, then sets status to error with an error message.
modified extensions/cli/src/slashCommands.ts +3 −0
@@ -28,6 +28,7 @@
2828 ` ${chalk.cyan("Enter")} Submit message`,
2929 ` ${chalk.cyan("Shift+Enter")} New line`,
3030 ` ${chalk.cyan("\\")} Line continuation (at end of line)`,
31+ ` ${chalk.cyan("!")} Bash mode - run shell commands`,
3132 "",
3233 chalk.white("Controls:"),
3334 ` ${chalk.cyan("Ctrl+C")} Clear input`,
@@ -39,9 +40,11 @@
3940 chalk.white("Special Characters:"),
4041 ` ${chalk.cyan("@")} Search and attach files for context`,
4142 ` ${chalk.cyan("/")} Access slash commands`,
43+ ` ${chalk.cyan("!")} Execute bash commands directly`,
4244 "",
4345 chalk.white("Available Commands:"),
4446 ` Type ${chalk.cyan("/")} to see available slash commands`,
47+ ` Type ${chalk.cyan("!")} followed by a command to execute bash directly`,
4548 ].join("\n");
4649 posthogService.capture("useSlashCommand", { name: "help" });
4750 return { output: helpMessage };
modified extensions/cli/src/tools/runTerminalCommand.ts +7 −2
@@ -17,7 +17,7 @@
1717 args: ["-NoLogo", "-ExecutionPolicy", "Bypass", "-Command", command],
1818 };
1919 } else {
20- // Unix/macOS: Use login shell to source .bashrc/.zshrc etc.
20+ // Unix/macOS: Just run the user's shell as a login shell
2121 const userShell = process.env.SHELL || "/bin/bash";
2222 return { shell: userShell, args: ["-l", "-c", command] };
2323 }
@@ -60,7 +60,12 @@
6060 return new Promise((resolve, reject) => {
6161 // Use same shell logic as core implementation
6262 const { shell, args } = getShellCommand(command);
63- const child = spawn(shell, args);
63+ const child = spawn(shell, args, {
64+ cwd: process.cwd(),
65+ env: process.env,
66+ stdio: ["ignore", "pipe", "pipe"], // prevent child from reading TTY input
67+ detached: false,
68+ });
6469 let stdout = "";
6570 let stderr = "";
6671 let timeoutId: NodeJS.Timeout;
modified extensions/cli/src/ui/UserInput.tsx +43 −5
@@ -69,6 +69,7 @@
6969 const [showSlashCommands, setShowSlashCommands] = useState(false);
7070 const [slashCommandFilter, setSlashCommandFilter] = useState("");
7171 const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
72+ const [showBashMode, setShowBashMode] = useState(false);
7273 const [showFileSearch, setShowFileSearch] = useState(false);
7374 const [fileSearchFilter, setFileSearchFilter] = useState("");
7475 const [selectedFileIndex, setSelectedFileIndex] = useState(0);
@@ -118,6 +119,18 @@
118119 return nextMode;
119120 };
120121
122+ // Update bash mode state based on input
123+ const updateBashModeState = (text: string) => {
124+ const trimmed = text.trimStart();
125+ const isBash = trimmed.startsWith("!");
126+ setShowBashMode(isBash);
127+ if (isBash) {
128+ // Disable other helpers while in bash mode
129+ setShowSlashCommands(false);
130+ setShowFileSearch(false);
131+ }
132+ };
133+
121134 // Update slash command UI state based on input
122135 const updateSlashCommandState = (text: string, cursor: number) => {
123136 // Only show slash commands if slash is the very first character
@@ -126,6 +139,9 @@
126139 return;
127140 }
128141
142+ // When using slash commands, disable file search
143+ setShowFileSearch(false);
144+
129145 const trimmedText = text.trimStart();
130146 const beforeCursor = trimmedText.slice(
131147 0,
@@ -188,6 +204,13 @@
188204 return;
189205 }
190206
207+ // Disable file search if we're in bash mode or slash command mode
208+ const trimmed = text.trimStart();
209+ if (trimmed.startsWith("!") || trimmed.startsWith("/")) {
210+ setShowFileSearch(false);
211+ return;
212+ }
213+
191214 // Check if we're in a file search context
192215 const beforeCursor = text.slice(0, cursor);
193216 const lastAtIndex = beforeCursor.lastIndexOf("@");
@@ -226,6 +249,7 @@
226249 setFileSearchFilter(afterAt);
227250 setSelectedFileIndex(0);
228251 setShowSlashCommands(false);
252+ setShowBashMode(false);
229253 }
230254 }
231255 };
@@ -270,6 +294,7 @@
270294 setInputText(newText);
271295 setCursorPosition(newCursorPos);
272296 setShowSlashCommands(false);
297+ setShowBashMode(false);
273298 }
274299 };
275300
@@ -429,6 +454,7 @@
429454 setInputText("");
430455 setCursorPosition(0);
431456 setShowSlashCommands(false);
457+ setShowBashMode(false);
432458 }
433459 return true;
434460 }
@@ -454,6 +480,15 @@
454480 const handleEscapeKey = (key: any): boolean => {
455481 if (!key.escape) return false;
456482
483+ // If only "!" is present, clear bash mode
484+ if (inputMode && showBashMode && inputText.trim() === "!") {
485+ textBuffer.clear();
486+ setInputText("");
487+ setCursorPosition(0);
488+ setShowBashMode(false);
489+ return true;
490+ }
491+
457492 // Handle escape key to interrupt streaming
458493 if (isWaitingForResponse && onInterrupt) {
459494 onInterrupt();
@@ -482,6 +517,7 @@
482517 setCursorPosition(0);
483518 setShowSlashCommands(false);
484519 setShowFileSearch(false);
520+ setShowBashMode(false);
485521 inputHistory.resetNavigation();
486522 };
487523
@@ -493,6 +529,7 @@
493529 setCursorPosition(newCursor);
494530 updateSlashCommandState(newText, newCursor);
495531 updateFileSearchState(newText, newCursor);
532+ updateBashModeState(newText);
496533 inputHistory.resetNavigation();
497534 };
498535
@@ -573,14 +610,15 @@
573610 setCursorPosition,
574611 updateSlashCommandState,
575612 updateFileSearchState,
613+ updateBashModeState,
576614 inputHistory,
577615 });
578616 });
579617
580618 const renderInputText = () => {
581619 const placeholderText = isRemoteMode
582- ? "Ask anything, / for slash commands"
583- : placeholder || "Ask anything, @ for context, / for slash commands";
620+ ? "Ask anything, / for slash commands, ! for bash mode"
621+ : placeholder || "Ask anything, @ for context, / for slash commands, ! for bash mode";
584622 if (inputText.length === 0) {
585623 return (
586624 <>
@@ -677,10 +715,10 @@
677715 borderStyle="round"
678716 borderTop={true}
679717 paddingX={1}
680- borderColor={isRemoteMode ? "cyan" : "gray"}
718+ borderColor={showBashMode ? "yellow" : isRemoteMode ? "cyan" : "gray"}
681719 >
682- <Text color={isRemoteMode ? "cyan" : "blue"} bold>
683- {isRemoteMode ? "◉" : "●"}{" "}
720+ <Text color={showBashMode ? "yellow" : isRemoteMode ? "cyan" : "blue"} bold>
721+ {showBashMode ? "$" : isRemoteMode ? "◉" : "●"}
684722 </Text>
685723 {renderInputText()}
686724 </Box>
added extensions/cli/src/ui/hooks/useChat.bashMode.test.ts +108 −0
@@ -0,0 +1,108 @@
1+import { describe, it, expect, vi, beforeEach } from "vitest";
2+import { act } from "@testing-library/react";
3+
4+import { createMinimalTestContext } from "../../test-helpers/ui-test-context.js";
5+
6+// Mock the runTerminalCommandTool
7+vi.mock("../../tools/runTerminalCommand.js", () => ({
8+ runTerminalCommandTool: {
9+ run: vi.fn(),
10+ },
11+}));
12+
13+import { useChat } from "./useChat.js";
14+import { runTerminalCommandTool } from "../../tools/runTerminalCommand.js";
15+
16+describe("useChat - Bash Mode", () => {
17+ beforeEach(() => {
18+ vi.clearAllMocks();
19+ });
20+
21+ it("should detect bash mode when message starts with !", async () => {
22+ const mockRun = vi.mocked(runTerminalCommandTool.run);
23+ 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 ..");
24+
25+ const ctx = createMinimalTestContext();
26+ const chat = useChat({
27+ assistant: { name: "test" } as any,
28+ model: { name: "test-model" } as any,
29+ llmApi: {} as any,
30+ } as any);
31+
32+ await act(async () => {
33+ await chat.handleUserMessage("!ls -la");
34+ });
35+
36+ expect(mockRun).toHaveBeenCalledWith({ command: "ls -la" });
37+
38+ // Since history is managed by service, we just verify no exception and tool called
39+ ctx.cleanup();
40+ });
41+
42+ it("should handle bash command errors", async () => {
43+ const mockRun = vi.mocked(runTerminalCommandTool.run);
44+ mockRun.mockRejectedValue(new Error("Command not found"));
45+
46+ const chat = useChat({
47+ assistant: { name: "test" } as any,
48+ model: { name: "test-model" } as any,
49+ llmApi: {} as any,
50+ } as any);
51+
52+ await act(async () => {
53+ await chat.handleUserMessage("!invalidcommand");
54+ });
55+
56+ expect(mockRun).toHaveBeenCalledWith({ command: "invalidcommand" });
57+ });
58+
59+ it("should not trigger bash mode for regular messages", async () => {
60+ const mockRun = vi.mocked(runTerminalCommandTool.run);
61+
62+ const chat = useChat({
63+ assistant: { name: "test" } as any,
64+ model: { name: "test-model" } as any,
65+ llmApi: {} as any,
66+ } as any);
67+
68+ await act(async () => {
69+ await chat.handleUserMessage("Hello! How are you?");
70+ });
71+
72+ expect(mockRun).not.toHaveBeenCalled();
73+ });
74+
75+ it("should handle empty bash command", async () => {
76+ const mockRun = vi.mocked(runTerminalCommandTool.run);
77+
78+ const chat = useChat({
79+ assistant: { name: "test" } as any,
80+ model: { name: "test-model" } as any,
81+ llmApi: {} as any,
82+ } as any);
83+
84+ await act(async () => {
85+ await chat.handleUserMessage("!");
86+ });
87+
88+ // Should not call the tool for empty command
89+ expect(mockRun).not.toHaveBeenCalled();
90+ });
91+
92+ it("should handle bash command with leading whitespace", async () => {
93+ const mockRun = vi.mocked(runTerminalCommandTool.run);
94+ mockRun.mockResolvedValue("echo test output");
95+
96+ const chat = useChat({
97+ assistant: { name: "test" } as any,
98+ model: { name: "test-model" } as any,
99+ llmApi: {} as any,
100+ } as any);
101+
102+ await act(async () => {
103+ await chat.handleUserMessage(" !echo hello");
104+ });
105+
106+ expect(mockRun).toHaveBeenCalledWith({ command: "echo hello" });
107+ });
108+});
No newline at the end of the file
modified extensions/cli/src/ui/hooks/useChat.ts +53 −0
@@ -339,6 +339,52 @@
339339 return false;
340340 };
341341
342+ const handleBashModeProcessing = async (
343+ message: string,
344+ ): Promise<string | null> => {
345+ // Handle bash mode commands (starting with !)
346+ if (!message.trimStart().startsWith("!")) {
347+ return message;
348+ }
349+
350+ // Extract the command after the !
351+ const bashCommand = message.trimStart().slice(1).trim();
352+
353+ if (!bashCommand) {
354+ return message; // No command provided, treat as regular message
355+ }
356+
357+ // Show tool call immediately, then run asynchronously and populate result
358+ const toolCallId = `bash-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
359+ const toolCall = {
360+ id: toolCallId,
361+ type: "function" as const,
362+ function: {
363+ name: "Bash",
364+ arguments: JSON.stringify({ command: bashCommand }),
365+ },
366+ };
367+
368+ // Add assistant message with tool call immediately
369+ services.chatHistory.addAssistantMessage("", [toolCall as any]);
370+ // Mark as calling for immediate UI feedback
371+ services.chatHistory.updateToolStatus(toolCallId, "calling");
372+
373+ // Execute the bash command asynchronously - don't block UI
374+ (async () => {
375+ try {
376+ const { runTerminalCommandTool } = await import("../../tools/runTerminalCommand.js");
377+ const result = await runTerminalCommandTool.run({ command: bashCommand });
378+ services.chatHistory.addToolResult(toolCallId, result, "done");
379+ } catch (error: any) {
380+ const errorMessage = `Bash command failed: ${error?.message || String(error)}`;
381+ services.chatHistory.addToolResult(toolCallId, errorMessage, "error");
382+ }
383+ })();
384+
385+ return null; // Processed, no further message handling needed
386+ };
387+
342388 const handleSlashCommandProcessing = async (
343389 message: string,
344390 ): Promise<string | null> => {
@@ -423,6 +469,13 @@
423469
424470 if (handled) return;
425471
472+ // Handle bash mode commands (before slash commands)
473+ const bashProcessedMessage = await handleBashModeProcessing(message);
474+ if (bashProcessedMessage === null) {
475+ return; // Bash command was handled and no further processing needed
476+ }
477+ message = bashProcessedMessage;
478+
426479 // Handle slash commands
427480 const processedMessage = await handleSlashCommandProcessing(message);
428481 if (processedMessage === null) {
modified extensions/cli/src/ui/hooks/useUserInput.ts +3 −0
@@ -189,6 +189,7 @@
189189 setCursorPosition: (pos: number) => void;
190190 updateSlashCommandState: (text: string, cursor: number) => void;
191191 updateFileSearchState: (text: string, cursor: number) => void;
192+ updateBashModeState: (text: string) => void;
192193 inputHistory: any;
193194 }
194195
@@ -200,6 +201,7 @@
200201 setCursorPosition,
201202 updateSlashCommandState,
202203 updateFileSearchState,
204+ updateBashModeState,
203205 inputHistory,
204206 } = options;
205207
@@ -211,6 +213,7 @@
211213 setCursorPosition(newCursor);
212214 updateSlashCommandState(newText, newCursor);
213215 updateFileSearchState(newText, newCursor);
216+ updateBashModeState(newText);
214217 inputHistory.resetNavigation();
215218 }
216219 }