diff --git a/.github/workflows/cli-pr-checks.yml b/.github/workflows/cli-pr-checks.yml index 43a78d06e..94987f57b 100644 --- a/.github/workflows/cli-pr-checks.yml +++ b/.github/workflows/cli-pr-checks.yml @@ -59,6 +59,7 @@ jobs: matrix: os: [ubuntu-latest, windows-latest, macos-latest] node-version: [18, 20, 22, 24] + fail-fast: false runs-on: ${{ matrix.os }} steps: diff --git a/.github/workflows/compliance.yaml b/.github/workflows/compliance.yaml index 76c21d6b1..0e4a04e02 100644 --- a/.github/workflows/compliance.yaml +++ b/.github/workflows/compliance.yaml @@ -41,7 +41,7 @@ jobs: - name: Add PR title guidance comment if: always() && steps.pr-title-check.outputs.valid == 'false' - uses: actions/github-script@v7 + uses: actions/github-script@v8 with: script: | const { data: comments } = await github.rest.issues.listComments({ diff --git a/.github/workflows/label-merged-prs.yml b/.github/workflows/label-merged-prs.yml index d6f83eba8..b434d07fd 100644 --- a/.github/workflows/label-merged-prs.yml +++ b/.github/workflows/label-merged-prs.yml @@ -44,7 +44,7 @@ jobs: - name: Determine and apply tier label if: steps.check-author.outputs.should_label == 'true' - uses: actions/github-script@v7 + uses: actions/github-script@v8 with: script: | const pr = context.payload.pull_request; diff --git a/.github/workflows/respond-to-cubic.yaml b/.github/workflows/respond-to-cubic.yaml index 4be94e462..71717d114 100644 --- a/.github/workflows/respond-to-cubic.yaml +++ b/.github/workflows/respond-to-cubic.yaml @@ -29,7 +29,7 @@ jobs: - name: Add eyes reaction to comment if: steps.check-mention.outputs.contains_mention == 'true' - uses: actions/github-script@v7 + uses: actions/github-script@v8 with: script: | await github.rest.reactions.createForIssueComment({ @@ -49,7 +49,7 @@ jobs: - name: Get PR information if: steps.check-mention.outputs.contains_mention == 'true' id: pr-info - uses: actions/github-script@v7 + uses: actions/github-script@v8 with: script: | const { data: pr } = await github.rest.pulls.get({ @@ -107,7 +107,7 @@ jobs: - name: Comment with session URL if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url - uses: actions/github-script@v7 + uses: actions/github-script@v8 with: script: | const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request: @@ -144,7 +144,7 @@ jobs: - name: Add eyes reaction to comment if: steps.check-mention.outputs.contains_mention == 'true' - uses: actions/github-script@v7 + uses: actions/github-script@v8 with: script: | await github.rest.reactions.createForPullRequestReviewComment({ @@ -172,21 +172,59 @@ jobs: if: steps.check-mention.outputs.contains_mention == 'true' run: npm i -g @continuedev/cli + - name: Get review context + if: steps.check-mention.outputs.contains_mention == 'true' + id: review-context + uses: actions/github-script@v7 + with: + script: | + let reviewContext = ''; + + // Check if this comment is a reply to another review comment + if (context.payload.comment.in_reply_to_id) { + try { + const { data: originalComment } = await github.rest.pulls.getReviewComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: context.payload.comment.in_reply_to_id + }); + + reviewContext = `**Original review comment by @${originalComment.user.login}:** + ${originalComment.body} + + **Reply by @${{ github.event.comment.user.login }}:** + ${{ github.event.comment.body }}`; + } catch (error) { + console.log('Could not fetch original comment, using current comment only'); + reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:** + ${{ github.event.comment.body }}`; + } + } else { + reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:** + ${{ github.event.comment.body }}`; + } + + core.setOutput('context', reviewContext); + - name: Start remote session if: steps.check-mention.outputs.contains_mention == 'true' id: remote-session env: CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} run: | + # Debug: Echo the branch we're starting the session on + echo "Starting remote session on branch: ${{ github.event.pull_request.head.ref }}" + # Create a temporary file for the prompt to handle special characters and newlines properly cat > /tmp/prompt.txt << 'PROMPT_EOF' - Please help with the following code review comment from @${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}: + Please help with the following code review discussion from PR #${{ github.event.pull_request.number }}: **File:** ${{ github.event.comment.path }} **Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }} - **Comment:** ${{ github.event.comment.body }} - Please analyze the specific file and line mentioned, understand the review feedback, implement the necessary changes, and commit them to this branch. + ${{ steps.review-context.outputs.context }} + + Please analyze the specific file and line mentioned, understand the review feedback and any discussion context, implement the necessary changes, and commit them to this branch. PROMPT_EOF # Debug output @@ -211,7 +249,7 @@ jobs: - name: Comment with session URL if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url - uses: actions/github-script@v7 + uses: actions/github-script@v8 with: script: | const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request: diff --git a/.github/workflows/similar-issues.yml b/.github/workflows/similar-issues.yml index 9873a0585..4abf1cdd3 100644 --- a/.github/workflows/similar-issues.yml +++ b/.github/workflows/similar-issues.yml @@ -190,7 +190,7 @@ jobs: echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT - name: Comment with analysis - uses: actions/github-script@v7 + uses: actions/github-script@v8 with: script: | let comment = ''; @@ -307,7 +307,7 @@ jobs: - name: Add labels if: github.event_name == 'issues' - uses: actions/github-script@v7 + uses: actions/github-script@v8 with: script: | const labels = []; diff --git a/core/llm/index.ts b/core/llm/index.ts index 6602be1f1..f8fefd381 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -370,8 +370,17 @@ export abstract class BaseLLM implements ILLM { }, }); - if (error !== undefined) { - if (error === "cancel" || error.name === "AbortError") { + if (typeof error === "undefined") { + interaction?.logItem({ + kind: "success", + promptTokens, + generatedTokens, + thinkingTokens, + usage, + }); + return "success"; + } else { + if (error === "cancel" || error?.name?.includes("AbortError")) { interaction?.logItem({ kind: "cancel", promptTokens, @@ -393,15 +402,6 @@ export abstract class BaseLLM implements ILLM { }); return "error"; } - } else { - interaction?.logItem({ - kind: "success", - promptTokens, - generatedTokens, - thinkingTokens, - usage, - }); - return "success"; } } @@ -615,6 +615,7 @@ export abstract class BaseLLM implements ILLM { kind: "chunk", chunk: formattedContent, }); + completion += formattedContent; yield content; } @@ -630,6 +631,7 @@ export abstract class BaseLLM implements ILLM { kind: "chunk", chunk, }); + completion += chunk; yield chunk; } diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts index 1b12af8fb..b04c9196f 100644 --- a/core/tools/definitions/editFile.ts +++ b/core/tools/definitions/editFile.ts @@ -8,7 +8,7 @@ export interface EditToolArgs { } export const NO_PARALLEL_TOOL_CALLING_INTSRUCTION = - "Note this tool CANNOT be called in parallel with other tools."; + "This tool CANNOT be called in parallel with other tools."; const CHANGES_DESCRIPTION = "Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'"; diff --git a/core/tools/definitions/multiEdit.ts b/core/tools/definitions/multiEdit.ts index 09a26be5b..913961737 100644 --- a/core/tools/definitions/multiEdit.ts +++ b/core/tools/definitions/multiEdit.ts @@ -1,6 +1,7 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; import { NO_PARALLEL_TOOL_CALLING_INTSRUCTION } from "./editFile"; +import { singleFindAndReplaceTool } from "./singleFindAndReplace"; export interface EditOperation { old_string: string; @@ -24,60 +25,41 @@ export const multiEditTool: Tool = { isInstant: false, function: { name: BuiltInToolNames.MultiEdit, - description: `This is a tool for making multiple edits to a single file in one operation. It -is built on top of the single find and replace tool and allows you to perform multiple -find-and-replace operations efficiently. Prefer this tool over the single find and replace tool -when you need to make multiple edits to the same file. + description: `This is a tool for making multiple edits to a single file in one operation. It is built on top of the ${singleFindAndReplaceTool.function.name} and allows you to perform multiple find-and-replace operations efficiently. +Prefer this tool over the ${singleFindAndReplaceTool.function.name} tool when you need to make multiple edits to the same file. -Before using this tool: - -1. Use the read_file tool to understand the file's contents and context -2. Verify the directory path is correct - -To make multiple file edits, provide the following: - -1. filepath: The path to the file to modify (relative to the root of the workspace) +To make multiple edits to a file, provide the following: +1. filepath: The path to the file to modify, RELATIVE to the project/workspace root (verify the directory path is correct) 2. edits: An array of edit operations to perform, where each edit contains: - - old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation) + - old_string: The text to replace (must match the old file contents exactly, including all whitespace/indentation) - new_string: The edited text to replace the old_string - replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false. IMPORTANT: - All edits are applied in sequence, in the order they are provided -- Each edit operates on the result of the previous edit -- All edits must be valid for the operation to succeed - if any edit fails, -none will be applied -- This tool is ideal when you need to make several changes to different parts -of the same file +- Each edit operates on the result of the previous edit, so plan your edits carefully to avoid conflicts between sequential operations +- Edits are atomic - all edits must be valid for the operation to succeed - if any edit fails, none will be applied +- This tool is ideal when you need to make several changes to different parts of the same file CRITICAL REQUIREMENTS: - -1. All edits follow the same requirements as the single find and replace tool -2. The edits are atomic - either all succeed or none are applied -3. Plan your edits carefully to avoid conflicts between sequential operations -4. ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION} - -WARNING: - -- The tool will fail if edits.old_string doesn't match the file contents -exactly (including whitespace) -- The tool will fail if edits.old_string and edits.new_string are the same -- Since edits are applied in sequence, ensure that earlier edits don't affect -the text that later edits are trying to find - -When making edits: - +1. ALWAYS use the ${BuiltInToolNames.ReadFile} tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it. +2. ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION} +3. When making edits: - Ensure all edits result in idiomatic, correct code - Do not leave the code in a broken state -- Only use emojis if the user explicitly requests it. Avoid adding emojis to -files unless asked. -- Use replace_all for replacing and renaming strings across the file. This -parameter is useful if you want to rename a variable for instance. +- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked +- Use replace_all for replacing and renaming all matches for a string across the file. This parameter is useful if you want to rename a variable, for instance If you want to create a new file, use: -- A new file path +- A new file path, including new directory if needed - First edit: empty old_string and the new file's contents as new_string -- Subsequent edits are not allowed - there is no need since you are creating`, +- Subsequent edits are not allowed - there is no need since you are creating +- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required + +WARNINGS: +- If earlier edits affect the text that later edits are trying to find, files can become mangled +- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace) +- The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different`, parameters: { type: "object", required: ["filepath", "edits"], @@ -97,16 +79,18 @@ If you want to create a new file, use: properties: { old_string: { type: "string", - description: "The text to replace", + description: + "The text to replace (exact match including whitespace/indentation)", }, new_string: { type: "string", - description: "The text to replace it with", + description: + "The text to replace it with. MUST be different than old_string.", }, replace_all: { type: "boolean", description: - "Replace all occurrences of old_string (default false)", + "Replace all occurrences of old_string (default false) in the file", }, }, }, diff --git a/core/tools/definitions/singleFindAndReplace.ts b/core/tools/definitions/singleFindAndReplace.ts index a8a9fc15b..d0b172ad7 100644 --- a/core/tools/definitions/singleFindAndReplace.ts +++ b/core/tools/definitions/singleFindAndReplace.ts @@ -20,33 +20,18 @@ export const singleFindAndReplaceTool: Tool = { isInstant: false, function: { name: BuiltInToolNames.SingleFindAndReplace, - description: `Performs exact string replacements in files. - -Usage: - -- You must use your \`read_file\` tool at least once in the conversation before -editing. This tool will error if you attempt an edit without reading the file. - -- When editing text from read_file tool output, ensure you preserve the exact -indentation (tabs/spaces) as it appears AFTER the line number prefix. The line -number prefix format is: spaces + line number + tab. Everything after that tab -is the actual file content to match. Never include any part of the line number -prefix in the old_string or new_string. - -- ALWAYS prefer editing existing files in the codebase. NEVER write new files -unless explicitly required. - -- Only use emojis if the user explicitly requests it. Avoid adding emojis to -files unless asked. + description: `Performs exact string replacements in a file. +IMPORTANT: +- ALWAYS use the \`${BuiltInToolNames.ReadFile}\` tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it. - ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION} +- When editing text from \`${BuiltInToolNames.ReadFile}\` tool output, ensure you preserve exact whitespace/indentation. +- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked. +- Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable, for instance. -- The edit will FAIL if \`old_string\` is not unique in the file. Either provide -a larger string with more surrounding context to make it unique or use -\`replace_all\` to change every instance of \`old_string\`. - -- Use \`replace_all\` for replacing and renaming strings across the file. This -parameter is useful if you want to rename a variable for instance.`, +WARNINGS: +- When not using \`replace_all\`, the edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`. +- The edit will likely fail if you have not recently used the \`${BuiltInToolNames.ReadFile}\` tool to view up-to-date file contents.`, parameters: { type: "object", required: ["filepath", "old_string", "new_string"], @@ -58,12 +43,13 @@ parameter is useful if you want to rename a variable for instance.`, }, old_string: { type: "string", - description: "The text to replace", + description: + "The text to replace - must be exact including whitespace/indentation", }, new_string: { type: "string", description: - "The text to replace it with (must be different from old_string)", + "The text to replace it with (MUST be different from old_string)", }, replace_all: { type: "boolean", diff --git a/docs/features/autocomplete/how-to-customize.mdx b/docs/features/autocomplete/how-to-customize.mdx index 854be157e..4fab64383 100644 --- a/docs/features/autocomplete/how-to-customize.mdx +++ b/docs/features/autocomplete/how-to-customize.mdx @@ -3,6 +3,6 @@ title: “Customize Autocomplete Settings in Continue” description: “Learn how to customize autocomplete behavior in Continue, including user settings, configuration options, and adjustments to improve AI code suggestions in your IDE.” --- -Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](/customize/settings) to manage these settings. +Continue offers a handful of settings to customize autocomplete behavior. Visit the User Settings Page (Gear Icon) to manage these settings. For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](/customize/deep-dives/autocomplete). diff --git a/docs/reference/deprecated-docs.mdx b/docs/reference/deprecated-docs.mdx index c972db7fa..a62e88b49 100644 --- a/docs/reference/deprecated-docs.mdx +++ b/docs/reference/deprecated-docs.mdx @@ -408,4 +408,4 @@ The following configuration example includes: -This setup could also involve enabling Chromium as a backup for local documentation through the [User Settings Page](../customize/settings). \ No newline at end of file +This setup could also involve enabling Chromium as a backup for local documentation through the User Settings Page (Gear Icon). \ No newline at end of file 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/tools/edit.test.ts b/extensions/cli/src/tools/edit.test.ts index d3b0764b9..03c58c4ed 100644 --- a/extensions/cli/src/tools/edit.test.ts +++ b/extensions/cli/src/tools/edit.test.ts @@ -1,8 +1,9 @@ import * as fs from "fs"; -import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { editTool, markFileAsRead, readFilesSet } from "./edit.js"; +import { editTool } from "./edit.js"; +import { markFileAsRead, readFilesSet } from "./readFile.js"; // Mock the dependencies vi.mock("../telemetry/telemetryService.js"); @@ -21,6 +22,7 @@ vi.mock("fs", async () => { readFileSync: vi.fn(), writeFileSync: vi.fn(), unlinkSync: vi.fn(), + realpathSync: vi.fn(), }; }); @@ -34,6 +36,7 @@ describe("editTool", () => { vi.mocked(fs.existsSync).mockReturnValue(true); vi.mocked(fs.readFileSync).mockReturnValue(originalContent); vi.mocked(fs.writeFileSync).mockImplementation(() => {}); + vi.mocked(fs.realpathSync).mockImplementation((path) => path.toString()); }); afterEach(() => { @@ -126,7 +129,7 @@ describe("editTool", () => { const result = await editTool.preprocess!(args); expect(result.args).toEqual({ - file_path: testFilePath, + resolvedPath: testFilePath, newContent: "Hi there\nThis is a test file\nGoodbye world", oldContent: originalContent, }); @@ -163,7 +166,7 @@ describe("editTool", () => { it("should successfully write file and return success message", async () => { const newContent = "Hi there\nThis is a test file\nGoodbye world"; const args = { - file_path: testFilePath, + resolvedPath: testFilePath, newContent, oldContent: originalContent, }; @@ -186,7 +189,7 @@ describe("editTool", () => { }); const args = { - file_path: testFilePath, + resolvedPath: testFilePath, newContent: "new content", oldContent: originalContent, }; diff --git a/extensions/cli/src/tools/edit.ts b/extensions/cli/src/tools/edit.ts index a7b31ca10..545d14269 100644 --- a/extensions/cli/src/tools/edit.ts +++ b/extensions/cli/src/tools/edit.ts @@ -8,6 +8,7 @@ import { getLanguageFromFilePath, } from "../telemetry/utils.js"; +import { readFilesSet, readFileTool } from "./readFile.js"; import { Tool } from "./types.js"; import { generateDiff } from "./writeFile.js"; @@ -18,40 +19,23 @@ export interface EditArgs { replace_all?: boolean; } -// Track files that have been read in the current session -export const readFilesSet = new Set(); - export const editTool: Tool = { name: "Edit", displayName: "Edit", readonly: false, isBuiltIn: true, - description: `Performs exact string replacements in files. + description: `Performs exact string replacements in a file. +USAGE: +- ALWAYS use the \`${readFileTool.name}\` tool just before making edits, to understand the file's up-to-date contents and context. +- When editing text from ${readFileTool.name} tool output, ensure you preserve exact whitespace/indentation. +- Always prefer editing existing files in the codebase. NEVER write new files unless explicitly required. +- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked. +- Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable, for instance. -Usage: - -- You must use your \`Read\` tool at least once in the conversation before -editing. This tool will error if you attempt an edit without reading the file. - -- When editing text from Read tool output, ensure you preserve the exact -indentation (tabs/spaces) as it appears AFTER the line number prefix. The line -number prefix format is: spaces + line number + tab. Everything after that tab -is the actual file content to match. Never include any part of the line number -prefix in the old_string or new_string. - -- ALWAYS prefer editing existing files in the codebase. NEVER write new files -unless explicitly required. - -- Only use emojis if the user explicitly requests it. Avoid adding emojis to -files unless asked. - -- The edit will FAIL if \`old_string\` is not unique in the file. Either provide -a larger string with more surrounding context to make it unique or use -\`replace_all\` to change every instance of \`old_string\`. - -- Use \`replace_all\` for replacing and renaming strings across the file. This -parameter is useful if you want to rename a variable for instance.`, +WARNINGS: +- When not using \`replace_all\`, the edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`. +- The edit will FAIL if you have not recently used the \`${readFileTool.name}\` tool to view up-to-date file contents.`, parameters: { file_path: { type: "string", @@ -60,13 +44,14 @@ parameter is useful if you want to rename a variable for instance.`, }, old_string: { type: "string", - description: "The text to replace", + description: + "The text to replace - must be exact including whitespace/indentation", required: true, }, new_string: { type: "string", description: - "The text to replace it with (must be different from old_string)", + "The text to replace it with (MUST be different from old_string)", required: true, }, replace_all: { @@ -82,18 +67,12 @@ parameter is useful if you want to rename a variable for instance.`, new_string, replace_all = false, } = args as EditArgs; - throwIfFileIsSecurityConcern(file_path); - // Check if file has been read - if (!readFilesSet.has(file_path)) { - throw new Error( - `You must use the Read tool to read ${file_path} before editing it.`, - ); - } // Validate arguments if (!file_path) { throw new Error("file_path is required"); } + if (!old_string) { throw new Error("old_string is required"); } @@ -104,13 +83,24 @@ parameter is useful if you want to rename a variable for instance.`, throw new Error("old_string and new_string must be different"); } + const resolvedPath = fs.realpathSync(file_path); + + // Check if file has been read + if (!readFilesSet.has(resolvedPath)) { + throw new Error( + `You must use the ${readFileTool.name} tool to read ${file_path} before editing it.`, + ); + } + + throwIfFileIsSecurityConcern(resolvedPath); + // Check if file exists - if (!fs.existsSync(file_path)) { + if (!fs.existsSync(resolvedPath)) { throw new Error(`File ${file_path} does not exist`); } // Read current file content - const oldContent = fs.readFileSync(file_path, "utf-8"); + const oldContent = fs.readFileSync(resolvedPath, "utf-8"); // Check if old_string exists in the file if (!oldContent.includes(old_string)) { @@ -134,11 +124,11 @@ parameter is useful if you want to rename a variable for instance.`, } // Generate diff for preview - const diff = generateDiff(oldContent, newContent, file_path); + const diff = generateDiff(oldContent, newContent, resolvedPath); return { args: { - file_path, + resolvedPath, newContent, oldContent, }, @@ -155,19 +145,19 @@ parameter is useful if you want to rename a variable for instance.`, }; }, run: async (args: { - file_path: string; + resolvedPath: string; newContent: string; oldContent: string; }) => { try { - fs.writeFileSync(args.file_path, args.newContent, "utf-8"); + fs.writeFileSync(args.resolvedPath, args.newContent, "utf-8"); // Get lines for telemetry const { added, removed } = calculateLinesOfCodeDiff( args.oldContent, args.newContent, ); - const language = getLanguageFromFilePath(args.file_path); + const language = getLanguageFromFilePath(args.resolvedPath); if (added > 0) { telemetryService.recordLinesOfCodeModified("added", added, language); @@ -184,21 +174,16 @@ parameter is useful if you want to rename a variable for instance.`, const diff = generateDiff( args.oldContent, args.newContent, - args.file_path, + args.resolvedPath, ); - return `Successfully edited ${args.file_path}\nDiff:\n${diff}`; + return `Successfully edited ${args.resolvedPath}\nDiff:\n${diff}`; } catch (error) { throw new Error( - `Error: failed to edit ${args.file_path}: ${ + `Error: failed to edit ${args.resolvedPath}: ${ error instanceof Error ? error.message : String(error) }`, ); } }, }; - -// Function to mark a file as read (to be called from the read tool) -export function markFileAsRead(filePath: string) { - readFilesSet.add(filePath); -} diff --git a/extensions/cli/src/tools/multiEdit.test.ts b/extensions/cli/src/tools/multiEdit.test.ts index 408084652..597cab767 100644 --- a/extensions/cli/src/tools/multiEdit.test.ts +++ b/extensions/cli/src/tools/multiEdit.test.ts @@ -1,9 +1,10 @@ import * as fs from "fs"; import * as path from "path"; -import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { multiEditTool, markFileAsRead } from "./multiEdit.js"; +import { multiEditTool } from "./multiEdit.js"; +import { markFileAsRead } from "./readFile.js"; // Mock the dependencies vi.mock("../telemetry/telemetryService.js"); @@ -22,6 +23,7 @@ vi.mock("fs", async () => { readFileSync: vi.fn(), writeFileSync: vi.fn(), unlinkSync: vi.fn(), + realpathSync: vi.fn(), }; }); @@ -35,6 +37,7 @@ describe("multiEditTool", () => { vi.mocked(fs.existsSync).mockReturnValue(true); vi.mocked(fs.readFileSync).mockReturnValue(originalContent); vi.mocked(fs.writeFileSync).mockImplementation(() => {}); + vi.mocked(fs.realpathSync).mockImplementation((path) => path.toString()); }); afterEach(() => { diff --git a/extensions/cli/src/tools/multiEdit.ts b/extensions/cli/src/tools/multiEdit.ts index b0ec1cb26..2164c6742 100644 --- a/extensions/cli/src/tools/multiEdit.ts +++ b/extensions/cli/src/tools/multiEdit.ts @@ -9,12 +9,11 @@ import { getLanguageFromFilePath, } from "../telemetry/utils.js"; -import { markFileAsRead, readFilesSet } from "./edit.js"; +import { editTool } from "./edit.js"; +import { readFilesSet, readFileTool } from "./readFile.js"; import { Tool } from "./types.js"; import { generateDiff } from "./writeFile.js"; -export { markFileAsRead }; - export interface EditOperation { old_string: string; new_string: string; @@ -26,15 +25,10 @@ export interface MultiEditArgs { edits: EditOperation[]; } -// Function to check if file has been read (shared with edit tool) -function hasFileBeenRead(filePath: string): boolean { - return readFilesSet.has(filePath); -} - // Helper functions for multiEdit validation function validateMultiEditArgs(args: any): { original_path: string; - file_path: string; + resolved_path: string; edits: EditOperation[]; } { const { file_path, edits } = args as MultiEditArgs; @@ -53,7 +47,9 @@ function validateMultiEditArgs(args: any): { ? file_path : path.resolve(process.cwd(), file_path); - return { original_path: file_path, file_path: absolutePath, edits }; + const resolvedPath = fs.realpathSync(absolutePath); + + return { original_path: file_path, resolved_path: resolvedPath, edits }; } function validateEdits(edits: EditOperation[]): void { @@ -74,26 +70,25 @@ function validateEdits(edits: EditOperation[]): void { } function validateFileAccess( - original_path: string, - file_path: string, + resolvedPath: string, isCreatingNewFile: boolean, ): void { if (isCreatingNewFile) { // For new file creation, check if parent directory exists - const parentDir = path.dirname(file_path); + const parentDir = path.dirname(resolvedPath); if (parentDir && !fs.existsSync(parentDir)) { throw new Error(`Parent directory does not exist: ${parentDir}`); } } else { // For existing files, check if file has been read // Check with the original path first, then with absolute path - if (!hasFileBeenRead(original_path) && !hasFileBeenRead(file_path)) { + if (!readFilesSet.has(resolvedPath)) { throw new Error( - `You must use the Read tool to read ${original_path} before editing it.`, + `You must use the ${readFileTool.name} tool to read ${resolvedPath} before editing it.`, ); } - if (!fs.existsSync(file_path)) { - throw new Error(`File ${file_path} does not exist`); + if (!fs.existsSync(resolvedPath)) { + throw new Error(`File ${resolvedPath} does not exist`); } } } @@ -138,87 +133,42 @@ export const multiEditTool: Tool = { displayName: "MultiEdit", readonly: false, isBuiltIn: true, - description: `This is a tool for making multiple edits to a single file in one operation. It -is built on top of the Edit tool and allows you to perform multiple -find-and-replace operations efficiently. Prefer this tool over the Edit tool -when you need to make multiple edits to the same file. - - -Before using this tool: - - -1. Use the Read tool to understand the file's contents and context - -2. Verify the directory path is correct - - -To make multiple file edits, provide the following: - -1. file_path: The absolute path to the file to modify (must be absolute, not -relative) + description: `This is a tool for making multiple edits to a single file in one operation. It is built on top of the ${editTool.name} tool and allows you to perform multiple find-and-replace operations efficiently. +Prefer this tool over the ${editTool.name} tool when you need to make multiple edits to the same file. +To make multiple edits to a file, provide the following: +1. file_path: The absolute path to the file to modify (must be absolute, not relative) 2. edits: An array of edit operations to perform, where each edit contains: - - old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation) + - old_string: The text to replace (must match the file contents exactly, including all whitespace/indentation) - new_string: The edited text to replace the old_string - replace_all: Replace all occurences of old_string. This parameter is optional and defaults to false. IMPORTANT: - - All edits are applied in sequence, in the order they are provided - -- Each edit operates on the result of the previous edit - -- All edits must be valid for the operation to succeed - if any edit fails, -none will be applied - -- This tool is ideal when you need to make several changes to different parts -of the same file - -- For Jupyter notebooks (.ipynb files), use the NotebookEdit instead - +- Each edit operates on the result of the previous edit, so plan your edits carefully to avoid conflicts between sequential operations +- Edits are atomic - all edits must be valid for the operation to succeed - if any edit fails, none will be applied +- This tool is ideal when you need to make several changes to different parts of the same file CRITICAL REQUIREMENTS: - -1. All edits follow the same requirements as the single Edit tool - -2. The edits are atomic - either all succeed or none are applied - -3. Plan your edits carefully to avoid conflicts between sequential operations - - -WARNING: - -- The tool will fail if edits.old_string doesn't match the file contents -exactly (including whitespace) - -- The tool will fail if edits.old_string and edits.new_string are the same - -- Since edits are applied in sequence, ensure that earlier edits don't affect -the text that later edits are trying to find - - -When making edits: - +1. ALWAYS use the ${readFileTool.name} tool just before making edits, to understand the file's up-to-date contents and context +2. When making edits: - Ensure all edits result in idiomatic, correct code - - Do not leave the code in a broken state - - Always use absolute file paths (starting with /) - -- Only use emojis if the user explicitly requests it. Avoid adding emojis to -files unless asked. - -- Use replace_all for replacing and renaming strings across the file. This -parameter is useful if you want to rename a variable for instance. - +- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked. +- Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance. If you want to create a new file, use: - -- A new file path, including dir name if needed - +- A new file path, including new directory if needed - First edit: empty old_string and the new file's contents as new_string +- Subsequent edits: normal edit operations on the created content +- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required -- Subsequent edits: normal edit operations on the created content`, +WARNINGS: +- If earlier edits affect the text that later edits are trying to find, files can become mangled +- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace) +- The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different +- The tool will fail if you have not used the ${readFileTool.name} tool to read the file in this session`, parameters: { file_path: { type: "string", @@ -237,9 +187,9 @@ If you want to create a new file, use: }, preprocess: async (args) => { // Validate and extract arguments - const { original_path, file_path, edits } = validateMultiEditArgs(args); + const { resolved_path, edits } = validateMultiEditArgs(args); - throwIfFileIsSecurityConcern(file_path); + throwIfFileIsSecurityConcern(resolved_path); // Validate each edit operation validateEdits(edits); @@ -248,12 +198,12 @@ If you want to create a new file, use: const isCreatingNewFile = edits[0].old_string === ""; // Validate file access - validateFileAccess(original_path, file_path, isCreatingNewFile); + validateFileAccess(resolved_path, isCreatingNewFile); // Read current file content (or start with empty for new files) let currentContent = ""; if (!isCreatingNewFile) { - currentContent = fs.readFileSync(file_path, "utf-8"); + currentContent = fs.readFileSync(resolved_path, "utf-8"); } const originalContent = currentContent; @@ -266,11 +216,11 @@ If you want to create a new file, use: } // Generate diff for preview - const diff = generateDiff(originalContent, newContent, file_path); + const diff = generateDiff(originalContent, newContent, resolved_path); return { args: { - file_path, + file_path: resolved_path, newContent, originalContent, isCreatingNewFile, @@ -279,7 +229,7 @@ If you want to create a new file, use: preview: [ { type: "text", - content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${isCreatingNewFile ? "create" : "modify"} ${file_path}:`, + content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${isCreatingNewFile ? "create" : "modify"} ${resolved_path}:`, }, { type: "diff", diff --git a/extensions/cli/src/tools/readFile.ts b/extensions/cli/src/tools/readFile.ts index bca811696..62eab6fc7 100644 --- a/extensions/cli/src/tools/readFile.ts +++ b/extensions/cli/src/tools/readFile.ts @@ -2,10 +2,15 @@ import * as fs from "fs"; import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js"; -import { markFileAsRead } from "./edit.js"; import { formatToolArgument } from "./formatters.js"; import { Tool } from "./types.js"; +// Track files that have been read in the current session +export const readFilesSet = new Set(); +export function markFileAsRead(filePath: string) { + readFilesSet.add(filePath); +} + export const readFileTool: Tool = { name: "Read", displayName: "Read", @@ -41,9 +46,10 @@ export const readFileTool: Tool = { if (!fs.existsSync(filepath)) { return `Error: File does not exist: ${filepath}`; } - const content = fs.readFileSync(filepath, "utf-8"); + const realPath = fs.realpathSync(filepath); + const content = fs.readFileSync(realPath, "utf-8"); // Mark this file as read for the edit tool - markFileAsRead(filepath); + markFileAsRead(realPath); const lines = content.split("\n"); if (lines.length > 5000) { diff --git a/extensions/cli/src/tools/runTerminalCommand.ts b/extensions/cli/src/tools/runTerminalCommand.ts index 58d3939e5..726c86501 100644 --- a/extensions/cli/src/tools/runTerminalCommand.ts +++ b/extensions/cli/src/tools/runTerminalCommand.ts @@ -33,7 +33,7 @@ export const runTerminalCommandTool: Tool = { displayName: "Bash", description: `Executes a terminal command and returns the output -The command will be executed from the current working directory: ${process.cwd()} +Commands are automatically executed from the current working directory (${process.cwd()}), so there's no need to change directories with 'cd' commands. `, parameters: { command: { 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/components/StaticChatContent.tsx b/extensions/cli/src/ui/components/StaticChatContent.tsx index 0261b14d8..4c1c9f133 100644 --- a/extensions/cli/src/ui/components/StaticChatContent.tsx +++ b/extensions/cli/src/ui/components/StaticChatContent.tsx @@ -74,14 +74,12 @@ export const StaticChatContent: React.FC = ({ }, [chatHistory]); // Split chat history into stable and pending items - // Only put items in pending if they contain tool calls with "calling" status - // Everything else goes into static content + // The last two items may have pending tool calls const { staticItems, pendingItems } = React.useMemo(() => { - const items: React.ReactElement[] = []; - // Add intro message as first item if it should be shown + const staticItems: React.ReactElement[] = []; if (showIntroMessage) { - items.push( + staticItems.push( = ({ ); } - // Helper function to check if an item has pending tool calls - const hasPendingToolCalls = (item: ChatHistoryItem): boolean => { - return !!( - item.toolCallStates && - item.toolCallStates.some( - (toolState) => - toolState.status === "calling" || - toolState.status === "generating" || - toolState.status === "generated", - ) - ); - }; - - // Find the first message with pending tool calls from the end - let pendingStartIndex = filteredChatHistory.length; - for (let i = filteredChatHistory.length - 1; i >= 0; i--) { - if (hasPendingToolCalls(filteredChatHistory[i])) { - pendingStartIndex = i; - // If there's a message after this one, include it too as it might be related - if (i + 1 < filteredChatHistory.length) { - // Keep the pending start index as is, so we include the next message - } - break; - } - } - - const stableHistory = filteredChatHistory.slice(0, pendingStartIndex); - const pendingHistory = filteredChatHistory.slice(pendingStartIndex); + const PENDING_ITEMS_COUNT = 2; + const stableCount = Math.max( + 0, + filteredChatHistory.length - PENDING_ITEMS_COUNT, + ); + const stableHistory = filteredChatHistory.slice(0, stableCount); + const pendingHistory = filteredChatHistory.slice(stableCount); // Add stable messages to static items stableHistory.forEach((item, index) => { - items.push(renderMessage(item, index)); + staticItems.push(renderMessage(item, index)); }); // Pending items will be rendered dynamically outside Static - const pendingElements = pendingHistory.map((item, index) => - renderMessage(item, pendingStartIndex + index), + const pendingItems = pendingHistory.map((item, index) => + renderMessage(item, stableCount + index), ); return { - staticItems: items, - pendingItems: pendingElements, + staticItems, + pendingItems, }; }, [ showIntroMessage, 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(); } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 9affb4c2d..ba1f4a571 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -199,7 +199,9 @@ class IntelliJIDE( } override suspend fun openFile(path: String) = - fileUtils.openFile(path) + withContext(Dispatchers.EDT) { + fileUtils.openFile(path) + } override suspend fun openUrl(url: String) { withContext(Dispatchers.IO) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt index 04e4d3d2e..9e269226b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt @@ -43,10 +43,14 @@ class ContinueProcessHandler( } scope.launch(Dispatchers.IO) { for (message in pendingWrites) { - log.debug("Write: $message") - writer.write(message) - writer.write("\r\n") - writer.flush() + try { + log.debug("Write: $message") + writer.write(message) + writer.write("\r\n") + writer.flush() + } catch (e: IOException) { + log.warn(e) + } } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt index 69ea9b911..9d806ee66 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt @@ -21,6 +21,7 @@ class ContinueErrorSubmitter : ErrorReportSubmitter() { consumer: Consumer ): Boolean { try { + // todo: IdeaReportingEvent is deprecated; migrate to IdeaLoggingEvent + figure out how to read attachments val event = events.filterIsInstance() .firstOrNull() ?: return false service().report( diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKey.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKey.kt index 2402ff6c4..66a096f5e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKey.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKey.kt @@ -5,22 +5,27 @@ import com.github.continuedev.continueintellijextension.utils.castNestedOrNull import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType -import com.intellij.openapi.actionSystem.ActionManager -import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service +import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper class AddLicenseKey : AnAction() { override fun actionPerformed(e: AnActionEvent) { - val dialog = AddLicenseKeyDialog(e.project) + performAddLicenseKey(e.project) + } + + private fun performAddLicenseKey(project: Project?) { + if (project == null) + return + val dialog = AddLicenseKeyDialog(project) dialog.show() if (dialog.exitCode != DialogWrapper.OK_EXIT_CODE) return - val messenger = e.project?.service()?.coreMessenger + val messenger = project.service().coreMessenger ?: return messenger.request("mdm/setLicenseKey", mapOf("licenseKey" to dialog.licenseKey), null) { response -> val isValid = response.castNestedOrNull("content") ?: false @@ -28,7 +33,7 @@ class AddLicenseKey : AnAction() { createSuccessAction() else createErrorAction() - notification.notify(e.project) + notification.notify(project) } } @@ -37,7 +42,7 @@ class AddLicenseKey : AnAction() { "License key is valid. A restart is required for it to take effect.", NotificationType.INFORMATION ).addAction( - NotificationAction.create("Restart IDE") { event, notification -> + NotificationAction.create("Restart IDE") { _, _ -> ApplicationManager.getApplication().restart() } ) @@ -49,17 +54,7 @@ class AddLicenseKey : AnAction() { ).addAction( NotificationAction.create("Try again") { event, notification -> notification.expire() - val action = this@AddLicenseKey - action.actionPerformed( - AnActionEvent( - null, - event.dataContext, - ActionPlaces.UNKNOWN, - action.templatePresentation.clone(), - ActionManager.getInstance(), - 0 - ) - ) + performAddLicenseKey(event.project) } ) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKeyDialog.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKeyDialog.kt index 4ba6f2e21..af8763a21 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKeyDialog.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKeyDialog.kt @@ -3,9 +3,9 @@ package com.github.continuedev.continueintellijextension.license import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo +import com.intellij.ui.dsl.builder.AlignX import com.intellij.ui.dsl.builder.bindText import com.intellij.ui.dsl.builder.panel -import com.intellij.ui.dsl.gridLayout.HorizontalAlign import javax.swing.JComponent class AddLicenseKeyDialog(project: Project?) : DialogWrapper(project) { @@ -22,7 +22,7 @@ class AddLicenseKeyDialog(project: Project?) : DialogWrapper(project) { panel { row { textField().bindText(::licenseKey) - .horizontalAlign(HorizontalAlign.FILL) + .align(AlignX.FILL) .focused() .validationOnApply { if (it.text.isBlank()) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index ee1649b03..6e9c5b01a 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.3.3", + "version": "1.3.4", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/gui/src/components/gui/Switch.tsx b/gui/src/components/gui/Switch.tsx index 0af15f8eb..23d232124 100644 --- a/gui/src/components/gui/Switch.tsx +++ b/gui/src/components/gui/Switch.tsx @@ -1,5 +1,7 @@ +import { InformationCircleIcon } from "@heroicons/react/24/outline"; import React, { ReactNode } from "react"; import { vscButtonBackground } from ".."; +import { ToolTip } from "./Tooltip"; type ToggleSwitchProps = { isToggled: boolean; @@ -8,6 +10,7 @@ type ToggleSwitchProps = { size?: number; showIfToggled?: ReactNode; disabled?: boolean; + tooltip?: string; }; const ToggleSwitch: React.FC = ({ @@ -17,12 +20,20 @@ const ToggleSwitch: React.FC = ({ size = 16, showIfToggled, disabled = false, + tooltip, }) => { return (
- {text} + + {text}{" "} + {tooltip && ( + + + + )} +
{isToggled && !!showIfToggled && showIfToggled}
{/* */}